diff --git "a/6380.jsonl" "b/6380.jsonl" new file mode 100644--- /dev/null +++ "b/6380.jsonl" @@ -0,0 +1,183 @@ +{"seq_id":"21688142773","text":"from datetime import date\n\nimport configparser\nimport json\nimport os\nimport requests\n\nclass ClientQuotes:\n headers = None\n\n def __init__(self):\n config = configparser.ConfigParser()\n config.read('config.ini')\n assert 'RAPIDAPI_SKYSCANNER_KEY' in config['DEFAULT'], 'Could not find key \\'RAPIDAPI_SKYSCANNER_KEY\\' in config.ini. Exit.'\n assert 'RAPIDAPI_SKYSCANNER_HOST' in config['DEFAULT'], 'Could not find key \\'RAPIDAPI_SKYSCANNER_HOST\\' in config.ini. Exit.'\n rapidapi_skyscanner_key = config['DEFAULT']['RAPIDAPI_SKYSCANNER_KEY']\n rapidapi_skyscanner_host = config['DEFAULT']['RAPIDAPI_SKYSCANNER_HOST']\n\n self.headers = {\n 'x-rapidapi-key': rapidapi_skyscanner_key,\n 'x-rapidapi-host': rapidapi_skyscanner_host\n }\n\n def get_city_id(self, place_name: str):\n result = None\n\n # Query the Skyscanner API\n url = 'https://skyscanner-skyscanner-flight-search-v1.p.rapidapi.com/apiservices/autosuggest/v1.0/US/USD/en-US/'\n params = {'query': place_name}\n response = requests.request('GET', url, headers=self.headers, params=params)\n assert response.status_code == 200, 'Response code = {} != 200. Exit.'.format(response.status_code)\n \n # Parse JSON response\n parsed = json.loads(response.text)\n result = json.dumps(parsed, indent=3, sort_keys=True)\n #print(result) # Debugging\n places = parsed['Places']\n found = False\n for i in range(len(places)):\n place = places[i]\n if place['PlaceName'] == place_name:\n result = place['CityId']\n found = True\n break\n \n return found, result\n \n def get_quote(self, origin: str, destination: str, outbound_date: date):\n result = None\n\n # Query the Skyscanner API\n url = 'https://skyscanner-skyscanner-flight-search-v1.p.rapidapi.com/apiservices/browsequotes/v1.0/US/USD/en-US/{}/{}/{}'.format(origin, destination, outbound_date)\n params = {'inboundpartialdate': ''}\n response = requests.request('GET', url, headers=self.headers, params=params)\n assert response.status_code in [200, 429], 'Response code = {} not in [200, 429]. Exit.'.format(response.status_code)\n\n if response.status_code == 200:\n # Parse JSON response\n parsed = json.loads(response.text)\n #print(json.dumps(parsed, indent=3, sort_keys=True)) # Debugging\n quotes = parsed['Quotes']\n if len(quotes) > 0:\n result = min([quote['MinPrice'] for quote in quotes])\n\n return response.status_code, result","repo_name":"fabianrigterink/optimizing-multi-city-flights","sub_path":"src/client_quotes.py","file_name":"client_quotes.py","file_ext":"py","file_size_in_byte":2692,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"60"} +{"seq_id":"1692484984","text":"# -*- coding: utf-8 -*-\n#\n# BitcoinLib - Python Cryptocurrency Library\n# Unit Tests Custom classes\n# © 2018 February - 1200 Web Development \n#\n\n\nfrom datetime import datetime\n\n\nclass CustomAssertions:\n\n def assertDictEqualExt(self, result_dict, expected_dict, none_allowed=None):\n \"\"\"\n Compare dictionaries, skip items not found in expected dictionary.\n\n Lists and recursion's in dictionaries are allowed.\n\n :param result_dict: First dictionary with results\n :type result_dict: dict\n :param expected_dict: Second dictionary with expected values\n :type expected_dict: dict\n :param none_allowed: List of fields for which None value in result_dict is allowed\n :type none_allowed: list\n\n :return bool: Dictionaries are identical?\n \"\"\"\n if none_allowed is None:\n none_allowed = []\n if not isinstance(expected_dict, dict):\n if expected_dict == result_dict:\n return True\n else:\n raise AssertionError(\"Different value for %s != %s\" % (result_dict, expected_dict))\n expected_keys = expected_dict.keys()\n for k in result_dict:\n if k not in expected_keys:\n continue\n if isinstance(result_dict[k], dict):\n self.assertDictEqualExt(result_dict[k], expected_dict[k], none_allowed)\n elif isinstance(result_dict[k], list):\n for i in range(len(result_dict[k])):\n if not isinstance(expected_dict[k], list):\n raise AssertionError(\"No list expected for %s attribute, expected '%s' but received: '%s'\" %\n (k, expected_dict[k], result_dict[k]))\n self.assertDictEqualExt(result_dict[k][i], expected_dict[k][i], none_allowed)\n elif result_dict[k] != expected_dict[k]:\n if isinstance(result_dict[k], datetime):\n if result_dict[k].date() == expected_dict[k].date():\n continue\n if result_dict[k] is not None or k not in none_allowed:\n raise AssertionError(\"Different value for '%s': %s != %s\" % (k, result_dict[k], expected_dict[k]))\n","repo_name":"1200wd/bitcoinlib","sub_path":"tests/test_custom.py","file_name":"test_custom.py","file_ext":"py","file_size_in_byte":2292,"program_lang":"python","lang":"en","doc_type":"code","stars":512,"dataset":"github-code","pt":"60"} +{"seq_id":"71660108030","text":"import os\nimport os.path\nimport datetime\nimport time\nimport numpy as np\nimport torch\nimport torch.nn as nn\nfrom scipy import*\nfrom copy import*\nimport sys\nimport pandas as pd\nimport shutil\nfrom tqdm import tqdm\nimport torchvision\nimport glob\nimport dimod\nimport matplotlib.pyplot as plt\nimport pickle\n\n#================= DATA GENERATION ===================================================\nclass ReshapeTransform:\n def __init__(self, new_size):\n self.new_size = new_size\n\n def __call__(self, img):\n return torch.reshape(img, self.new_size)\n\n\nclass ReshapeTransformTarget:\n def __init__(self, args, number_classes):\n self.number_classes = number_classes\n self.args = args\n\n def __call__(self, target):\n target=torch.tensor(target).unsqueeze(0).unsqueeze(1)\n target_onehot = -1*torch.ones((1, self.number_classes))\n return target_onehot.scatter_(1, target.long(), 1).repeat_interleave(self.args.expand_output).squeeze(0)\n \nclass DefineDataset():\n def __init__(self, images, labels=None, transforms=None, target_transforms=None):\n self.x = images\n self.y = labels\n self.transforms = transforms\n self.target_transforms = target_transforms\n\n def __getitem__(self, i):\n data = self.x[i, :]\n target = self.y[i]\n\n if self.transforms:\n data = self.transforms(data)\n\n if self.target_transforms:\n target = self.target_transforms(target)\n\n if self.y is not None:\n return (data, target)\n else:\n return data\n\n def __len__(self):\n return (len(self.x))\n \n\ndef generate_patterns(args):\n '''\n Generate 2 patterns which are orthogonal diagonals in a 3x3 square\n --> already implemented for 3 patterns, bu \n '''\n \n data_test = -1*torch.ones((2,1,3,3)) # 1: numbers of different patterns, 2: number of input channels: 1 here, 3,4: size of the input (3x3 here)\n for (idx1, idx2) in ((0,0),(1,1),(2,2)): data_test[0,:,idx1, idx2] = 1 #first pattern : diagonal right\n for (idx1, idx2) in ((0,2),(1,1),(2,0)): data_test[1,:,idx1, idx2] = 1 #second pattern : diagonal left\n\n target_test = torch.tensor([0,1])\n \n test_data = DefineDataset(data_test, labels=target_test, target_transforms=ReshapeTransformTarget(args, 2))\n test_loader = torch.utils.data.DataLoader(test_data, batch_size=args.batchSize, shuffle=True)\n \n train_data = DefineDataset(data_train, labels=target_train, target_transforms=ReshapeTransformTarget(args, 2))\n train_loader = torch.utils.data.DataLoader(train_data, batch_size=args.batchSize, shuffle=True)\n \n return train_loader, test_loader\n \n \n#================= CONV ARCHITECTURES ===================================================\ndef createBQM(net, args, data, beta = 0, target = None, mode = None):\n\n #index of the patches of the images being convolved: (it is 2x2 patches as we use 2x2 kernels \n image_idx = [[0,0],[0,1],[1,0],[1,1], [0,1],[0,2],[1,1],[1,2], [1,0],[1,1],[2,0],[2,1], [1,1],[1,2],[2,1],[2,2]]\n\n ## Biases\n bias_lim = args.bias_lim\n # inputs on the QPU - biases are large here in order to have the input qbits being clamped\n h = {idx: -2 if data[0][elm[0],elm[1]] > 0 else 2 for (idx, elm) in enumerate(image_idx)}\n \n comp = len(image_idx)\n \n #bias for neurons after convolution: no bias!\n h.update({item: 0 for item in net.index_before_pool})\n \n #no bias for neurons after pooling\n h.update({item: 0 for item in net.index_after_pool})\n \n #bias for output neurons - with or without nudge\n if target is not None:\n bias_nudge = -beta*target\n h.update({net.index_fc[k]: (bias_nudge[k] + net.fc[0].bias[k]).clip(-bias_lim,bias_lim).item() for k in range(len(net.fc[0].bias))})\n else:\n h.update({net.index_fc[k]: net.fc[0].bias[k].clip(-bias_lim,bias_lim).item() for k in range(len(net.fc[0].bias))})\n\n\n ## Couplings\n coupled_qbits = [[[[0,16],[4,20],[8,24],[12,28]],[[1,16],[5,20],[9,24],[13,28]],[[2,16],[6,20],[10,24],[14,28]],[[3,16],[7,20],[11,24],[15,28]]], \n [[[0,17],[4,21],[8,25],[12,29]],[[1,17],[5,21],[9,25],[13,29]],[[2,17],[6,21],[10,25],[14,29]],[[3,17],[7,21],[11,25],[15,29]]], \n [[[0,18],[4,22],[8,26],[12,30]],[[1,18],[5,22],[9,26],[13,30]],[[2,18],[6,22],[10,26],[14,30]],[[3,18],[7,22],[11,26],[15,30]]], \n [[[0,19],[4,23],[8,27],[12,31]],[[1,19],[5,23],[9,27],[13,31]],[[2,19],[6,23],[10,27],[14,31]],[[3,19],[7,23],[11,27],[15,31]]]]\n \n J = {}\n #convolution weights\n for k in range(args.convList[0]):\n comp=0\n for i in range(2):\n for j in range(2):\n J.update({(elm[0],elm[1]): net.conv[0].weight[k][0][i][j].item() for (idx,elm) in enumerate(coupled_qbits[k][comp])})\n comp+=1\n \n #pooling weights = 1/4\n coupled_qbits_pooling = [[[16,32],[20,32],[24,32],[28,32]],\n [[17,33],[21,33],[25,33],[29,33]],\n [[18,34],[22,34],[26,34],[30,34]],\n [[19,35],[23,35],[27,35],[31,35]]]\n \n for k in range(args.convList[0]):\n avg_pool_coef = -args.pool_coef\n J.update({(elm[0],elm[1]): avg_pool_coef for (idx,elm) in enumerate(coupled_qbits_pooling[k])})\n \n #fc weights\n for k in range(args.layersList[1]):\n for i in range(args.layersList[0]):\n J.update({(net.index_after_pool[k],net.index_fc[i]): net.fc[0].weight[i][k].item()})\n\n model = dimod.BinaryQuadraticModel.from_ising(h, J, 0)\n\n return model\n \n \ndef train(net, args, train_loader, sampler):\n '''\n function to train the network for 1 epoch\n '''\n exact_pred, exact_loss = 0, 0\n qpu_pred, qpu_loss = 0, 0\n\n with torch.no_grad():\n for idx, (DATA, TARGET) in enumerate(tqdm(train_loader)):\n store_seq = None\n store_s = None\n \n for k in range(DATA.size()[0]):\n data, target = DATA[k].numpy(), TARGET[k].numpy()\n\n ## Free phase\n model = createBQM(net, args, data)\n # QPU sampling\n qpu_seq = sampler.sample(model, num_reads = args.n_iter_free, chain_strength = args.chain_strength, auto_scale = args.auto_scale)\n\n ## Nudge phase: same system except bias for the output layer\n model = createBQM(net, args, data, beta = args.beta, target = target)\n reverse_schedule = [[0.0, 1.0], [10, args.frac_anneal_nudge], [20, 1]]\n reverse_anneal_params = dict(anneal_schedule=reverse_schedule,\n initial_state=qpu_seq.first.sample,\n reinitialize_state=True)\n\n if np.array_equal(qpu_seq.record[\"sample\"][0].reshape(1,-1)[:,-args.layersList[1]:][0], target): \n qpu_s = qpu_seq\n else:\n qpu_s = sampler.sample(model, num_reads = args.n_iter_nudge, chain_strength = args.chain_strength, auto_scale = args.auto_scale, **reverse_anneal_params)\n\n if store_seq is None:\n store_seq = qpu_seq.record[\"sample\"][0].reshape(1, qpu_seq.record[\"sample\"][0].shape[0])\n store_s = qpu_s.record[\"sample\"][0].reshape(1, qpu_s.record[\"sample\"][0].shape[0])\n else:\n store_seq = np.concatenate((store_seq, qpu_seq.record[\"sample\"][0].reshape(1, qpu_seq.record[\"sample\"][0].shape[0])),0)\n store_s = np.concatenate((store_s, qpu_s.record[\"sample\"][0].reshape(1, qpu_s.record[\"sample\"][0].shape[0])),0)\n\n del qpu_seq, qpu_s\n del data, target\n\n seq = net.sample_to_s(args, DATA, store_seq) \n s = net.sample_to_s(args, DATA, store_s)\n\n ## Compute loss and error for QPU sampling\n loss, pred = net.computeLossAcc(seq, TARGET, args, stage = 'training')\n\n qpu_pred += pred\n qpu_loss += loss\n\n net.updateParams(DATA, s, seq, args)\n net.sign_beta = 1\n\n del seq, s\n del DATA, TARGET\n\n return qpu_loss, qpu_pred\n\n\ndef initDataframe(path, dataframe_to_init = 'results.csv'):\n '''\n Initialize a dataframe with Pandas so that parameters are saved\n '''\n if os.name != 'posix':\n prefix = '\\\\'\n else:\n prefix = '/'\n \n print(path)\n print(dataframe_to_init)\n if os.path.isfile(path + dataframe_to_init):\n dataframe = pd.read_csv(path + dataframe_to_init, sep = ',', index_col = 0)\n else:\n columns_header = ['QPU_Train_Accuracy','Train_Loss']\n dataframe = pd.DataFrame({},columns = columns_header)\n dataframe.to_csv(path + prefix + 'results.csv')\n return dataframe\n\n\ndef updateDataframe(BASE_PATH, dataframe, train_error, train_loss):\n '''\n Add data to the pandas dataframe\n '''\n if os.name != 'posix':\n prefix = '\\\\'\n else:\n prefix = '/'\n \n data = [train_error, train_loss]\n\n\n new_data = pd.DataFrame([data],index=[1],columns=dataframe.columns)\n\n dataframe = pd.concat([dataframe, new_data], axis=0)\n dataframe.to_csv(BASE_PATH + prefix + 'results.csv')\n\n return dataframe\n\n#=======================================================================================================\n#=========================================== COMMONS ===================================================\n#=======================================================================================================\n\ndef createPath(args):\n '''\n Create path to save data\n '''\n if os.name != 'posix':\n prefix = '\\\\'\n BASE_PATH = prefix + prefix + \"?\" + prefix + os.getcwd()\n else:\n prefix = '/'\n BASE_PATH = '' + os.getcwd()\n\n BASE_PATH += prefix + 'DATA' + str(args.dataset)\n\n BASE_PATH += prefix + datetime.datetime.now().strftime(\"%Y-%m-%d\")\n\n if not os.path.exists(BASE_PATH):\n os.makedirs(BASE_PATH)\n\n filePath = shutil.copy('plotFunction.py', BASE_PATH)\n\n files = os.listdir(BASE_PATH)\n\n if 'plotFunction.py' in files:\n files.pop(files.index('plotFunction.py'))\n\n if not files:\n BASE_PATH = BASE_PATH + prefix + 'S-1'\n else:\n tab = []\n for names in files:\n if names.split('.')[-1] != 'DS_Store':\n tab.append(int(names.split('-')[1]))\n BASE_PATH += prefix + 'S-' + str(max(tab)+1)\n \n\n return BASE_PATH\n\n\ndef saveHyperparameters(BASE_PATH, args):\n '''\n Save all hyperparameters in the path provided\n '''\n if os.name != 'posix':\n prefix = '\\\\'\n else:\n prefix = '/'\n\n f = open(BASE_PATH + prefix + 'Hyperparameters.txt', 'w')\n \n f.write('Convolutional architecture trained with EP on an Ising machine \\n')\n f.write(' Parameters of the simulation \\n ')\n f.write('\\n')\n \n\n for key in args.__dict__:\n f.write(key)\n f.write(': ')\n f.write(str(args.__dict__[key]))\n f.write('\\n')\n\n f.close()\n\n\ndef save_model_numpy(path, net):\n '''\n Save the parameters of the model as a dictionnary in a pickel file\n '''\n if os.name != 'posix':\n prefix = '\\\\'\n else:\n prefix = '/'\n\n with open(path + prefix + 'model_parameters.pickle', 'wb') as f:\n pickle.dump(net, f)\n\n return 0\n\n\ndef load_model_numpy(path):\n '''\n Save the parameters of the model as a dictionnary in a pickel file\n '''\n if os.name != 'posix':\n prefix = '\\\\'\n else:\n prefix = '/'\n\n with open(path + prefix + 'model_parameters.pickle', 'rb') as f:\n net = pickle.load(f)\n\n return net","repo_name":"jlaydevant/Ising-Machine-EqProp","sub_path":"Conv/QA-SA/Tools.py","file_name":"Tools.py","file_ext":"py","file_size_in_byte":11795,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"60"} +{"seq_id":"18851814681","text":"import numpy as np\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\n\nsizeBCT = np.array([32, 66, 92, 175, 348])\nsizeWRZ = np.array([33, 64, 93, 164, 338])\n\ncritBCT = np.array([1304.6875, 1367.1875, 1398.4375, 1414.0625, 1429.6875])\nerrBCT = np.array([7.8125, 7.8125, 7.8125, 7.8125, 7.8125])\n\ncritWRZ = np.array([1367.1875, 1382.8125, 1429.6875, 1445.3125, 1460.9375])\nerrWRZ = np.array([7.8125, 7.8125, 7.8125, 7.8125, 7.8125])\n\ncm = 1/2.54 #centimeters in inches\nplt.figure(figsize=(6.2*cm, 4.75*cm))\nmatplotlib.rcParams.update({'font.size': 9.98655939})\nplt.title('Critical temperatures', fontsize=9.98655939)\nplt.xlabel('$N_c$', labelpad=1)\nplt.ylabel(r'$T_{crit}$ [K]', labelpad=1)\n\nline = plt.errorbar(sizeBCT, critBCT, yerr=errBCT, label='BCT', lw=1, capsize=5.0)\n#plt.fill_between(sizeBCT, critBCT+errBCT, critBCT-errBCT, alpha=0.25, color=line[0]._color)\n\nline = plt.errorbar(sizeWRZ, critWRZ, yerr=errWRZ, label='WRZ', lw=1, capsize=5.0)\n#plt.fill_between(sizeWRZ, critWRZ+errWRZ, critWRZ-errWRZ, alpha=0.25, color=line[0]._color)\n\nplt.legend(loc='center left', bbox_to_anchor=(1, 0.5), handlelength=1)\nplt.tight_layout()\nplt.savefig('critTemps2.pdf', pad_inches = 0.0)","repo_name":"carle13/ClusterGrowth","sub_path":"plotCrit2.py","file_name":"plotCrit2.py","file_ext":"py","file_size_in_byte":1203,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"60"} +{"seq_id":"28150633588","text":"\n\ndebugging: bool = False;\nrequired_output: int = 19690720\n\ndef main():\n with open(\"data/02-Intcode.txt\") as file:\n raw_data = file.read(None).split(\",\")\n\n #Convert to ints\n for i in range(0, len(raw_data)):\n raw_data[i] = int(raw_data[i])\n\n for noun in range(0, 99):\n for verb in range(0, 99):\n intcode = raw_data[:]\n intcode[1] = noun\n intcode[2] = verb\n if(debugging):\n print(\"%s, Verb = %s\" % (noun, verb))\n \n intcode = run_code(intcode)\n\n if (intcode[0] == required_output):\n print(\"Code to produce %s is %s\" % (required_output, 100 * noun + verb))\n\n #print(\"Value at index 0: %s\" % (ints[0]))\n\ndef run_code(int_list):\n for i in range(0, len(int_list), 4):\n code: int = int(int_list[i])\n #Debugging\n if(debugging):\n print(\"Index: %s, Code: %s\" % (i, code))\n\n if code == 1:\n total = int_list[int_list[i+1]] + int_list[int_list[i+2]]\n int_list[int_list[i+3]] = total\n elif code == 2:\n total = int_list[int_list[i+1]] * int_list[int_list[i+2]]\n int_list[int_list[i+3]] = total\n elif code == 99:\n return int_list\n else:\n print(\"Unknown code found\")\n return None\n\n\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"byarker/AdventOfCode-2019","sub_path":"02-Intcode.py","file_name":"02-Intcode.py","file_ext":"py","file_size_in_byte":1392,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"60"} +{"seq_id":"43407157048","text":"class Solution:\n def countAndSay(self, n: int) -> str:\n if n == 1:\n return \"1\"\n if n == 2:\n return \"11\"\n if n == 3:\n return \"21\"\n res = \"21\"\n for i in range(3, n):\n res = self.get_string(res)\n return res\n\n def get_string(self, string: str):\n res = \"\"\n index = 0\n while index < len(string):\n cur_idnex = index\n cur_char = string[cur_idnex]\n while index < len(string) and string[index] == cur_char:\n index += 1\n res = res + str(index - cur_idnex) + cur_char\n return res\n\nsolution = Solution()\nprint(solution.countAndSay(5))","repo_name":"wcg14231022/leetcode","sub_path":"python/leetcode_038.py","file_name":"leetcode_038.py","file_ext":"py","file_size_in_byte":700,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"60"} +{"seq_id":"36039674754","text":"# TASK 1\n#\n# start = int(input('Введите начало диапазона: '))\n# end = int(input('Введите конец диапазона: '))\n#\n# gen_expr = (i ** 2 for i in range(start, end + 1))\n#\n# print(*gen_expr)\n\n\n# TASK 2\n#\ndef simple_gen(start, end):\n for i_nums in range(start, end):\n simple = True\n for j in range(2, i_nums // 2):\n if i_nums % j == 0:\n simple = False\n if simple:\n yield i_nums\n\n\nfor i in simple_gen(1, 25):\n print(i)\n\n\n# TASK 3\n#\n# class Even_nums:\n# def __init__(self, start, end):\n# self.start = start\n# self.end = end\n# self.ev = start - 1\n#\n# def __iter__(self):\n# print('__iter__')\n# return self\n#\n# def __next__(self):\n# print('__next__')\n# if self.ev == self.end:\n# raise StopIteration\n# self.ev += 1\n# if self.ev % 2 == 0:\n# return self.ev\n# else:\n# return\n#\n#\n# for i in Even_nums(10, 20):\n# print(i)\n","repo_name":"NikMerenyuk/study_1","sub_path":"homework_16/merenyuk_hw_16.py","file_name":"merenyuk_hw_16.py","file_ext":"py","file_size_in_byte":1044,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"60"} +{"seq_id":"36345632506","text":"from django.conf.urls import url\nfrom django.conf import settings\nfrom . import views\n#para llamar a nuestra página para insertar tenemos que invocar la dirección /pelicula/nueva\n\n# se puede crear un hipervinculo para llamarla, en este ejemplo hay que invocar manualmente la dirección.\n\nurlpatterns = [\n url(r'^$', views.tienda_lista),\n url(r'^tienda/$', views.tienda_nueva2, name='tienda_nueva2'),\n url(r'^tienda/nueva/$', views.tienda_nueva, name='tienda_nueva'),\n url(r'^tienda/(?P[0-9]+)/$', views.tienda_detalle, name='tienda_detalle'),\n url(r'^tienda/(?P[0-9]+)/editar/$', views.tienda_editar, name='tienda_editar'),\n url(r'^tienda/(?P\\d+)/eliminar/$', views.tienda_eliminar, name='tienda_eliminar'),\n url(r'^productos/$', views.producto_lista, name='producto_lista'),\n url(r'^inventario$', views.inventario_nuevo, name='inventario_nuevo'),\n url(r'^producto/nuevo/$', views.producto_nuevo, name='producto_nuevo'),\n url(r'^producto/(?P[0-9]+)/$', views.producto_detalle, name='producto_detalle'),\n url(r'^producto/(?P[0-9]+)/editar/$', views.producto_editar, name='producto_editar'),\n url(r'^producto/(?P\\d+)/eliminar/$', views.producto_eliminar, name='producto_eliminar'),\n ]\n","repo_name":"AllanCoyoyPC/allan","sub_path":"tiendas/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1248,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"60"} +{"seq_id":"38785400637","text":"import tkinter as tk\r\nfrom tkinter import messagebox\r\nfrom PIL import ImageTk\r\n\r\ncnt = 1\r\n\r\ndef pushed():\r\n global cnt\r\n if cnt % 3 == 0:\r\n textarea.insert(tk.END, 'ぶりゅりゅりゅゆ…')\r\n cnt += 1\r\n elif cnt % 10 == 0:\r\n canvas.place(x=110, y=30)\r\n messagebox.showinfo('【悲報】', '達也の肛門は破壊されました')\r\n cnt += 1\r\n else:\r\n textarea.insert(tk.END, 'ぶりッ…')\r\n cnt += 1\r\n\r\n\r\nroot = tk.Tk()\r\nroot.title('tkinter sample')\r\nroot.geometry(\"640x480\")\r\n\r\ntextarea = tk.Text(root, width=200)\r\ntextarea.pack()\r\n\r\nimg = ImageTk.PhotoImage(file='unti.jpg')\r\n\r\ncanvas = tk.Canvas(root, width=400, height=400)\r\ncanvas.create_image(200, 200, image=img)\r\n\r\nlabel2 = tk.Label(root, text=\"スイッチを押すと達也が脱糞します\")\r\nlabel2.place(x=270, y=350)\r\n\r\nbutton = tk.Button(root, text='達也が漏らスイッチ', command=pushed)\r\nbutton.place(x=290, y=380)\r\n\r\nroot.mainloop()","repo_name":"ppHaoqq/tkinter_sample","sub_path":"sample.py","file_name":"sample.py","file_ext":"py","file_size_in_byte":978,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"60"} +{"seq_id":"20168002253","text":"# altered function from prac_02 - more_scores.py\ndef write_text_file(path, text):\n with open(path, 'w') as file:\n file.write(text)\n file.write('\\n')\n file.close()\n\n\ndef get_text_file_content(path):\n try:\n with open(path, 'r') as file:\n lines_read = file.readlines()\n return lines_read\n except FileNotFoundError:\n print(\"Invalid Filename\")\n\n\nFILE_NAME_EXCERSISE_1 = \"names.txt\"\nFILE_NAME_EXCERSISE_2 = \"numbers.txt\"\n\ndef main():\n # Write to File\n name_of_user = str(input(\"Enter your name: \"))\n write_text_file(FILE_NAME_EXCERSISE_1, name_of_user)\n\n # Read \"name.txt\" File\n lines_read = get_text_file_content(FILE_NAME_EXCERSISE_1)\n print(f\"Your name is {lines_read[0]}\") # the name is stored in the first line, hence [0]\n\n\n # Read \"number.txt\" File\n lines_read = get_text_file_content(FILE_NAME_EXCERSISE_2) #should override the existing lines_read var\n line_1 = int(lines_read[0])\n line_2 = int(lines_read[1])\n result = line_1 + line_2\n print(str(result))\n\n #Add them all up\n result = 0\n for line in lines_read:\n result += int(line)\n\n print(result)\n\nmain()","repo_name":"GuidoPerren/cp1404practicals","sub_path":"prac_03/files.py","file_name":"files.py","file_ext":"py","file_size_in_byte":1179,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"60"} +{"seq_id":"75020312192","text":"import sys\nfrom collections import deque\ninput = sys.stdin.readline\ndef find(start = 0, l = 0):\n global ans\n global total\n if l == 3:\n visit = [[0] * M for _ in range(N)]\n dr = [0, 0, -1, 1]\n dc = [-1, 1, 0, 0]\n Q = deque()\n for virus in double:\n Q.append(virus)\n temp = 3\n while Q:\n c, r = Q.popleft()\n for i in range(4):\n C = c + dc[i]\n R = r + dr[i]\n if 0 <= C < N and 0 <= R < M:\n if arr[C][R] == 0 and visit[C][R] == 0:\n temp += 1\n visit[C][R] = 1\n Q.append([C, R])\n\n ans = max((N * M) - (total + temp), ans)\n return\n\n for i in range(start, len(zero)):\n c, r = zero[i]\n arr[c][r] = 1\n find(i + 1, l + 1)\n arr[c][r] = 0\n\n\nN, M = map(int, input().split()) # 세로, 가로\narr = [list(map(int, input().split())) for _ in range(N)]\nzero = deque()\ndouble = deque()\ntotal = 0\nfor i in range(N):\n for j in range(M):\n if arr[i][j] == 0:\n zero.append([i, j])\n elif arr[i][j] == 2:\n total += 1\n double.append([i, j])\n else:\n total += 1\n\nans = 0\nfind()\nprint(ans)","repo_name":"hwanny7/algorithm","sub_path":"백준/14502_연구소.py","file_name":"14502_연구소.py","file_ext":"py","file_size_in_byte":1295,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"60"} +{"seq_id":"34187407913","text":"import pygame\r\nimport random\r\n\r\n\r\npygame.init()\r\n\r\ndisplay_width = 800\r\ndisplay_height = 600\r\n\r\ndisplay = pygame.display.set_mode((display_width, display_height))\r\npygame.display.set_caption('Код для копирки') # громкость звука 1 - 100%\r\n\r\njump_sound = pygame.mixer.Sound('Sounds/Rrr.wav')\r\nfall_sound = pygame.mixer.Sound('Sounds/Bdish.wav')\r\nlose_sound = pygame.mixer.Sound('Sounds/loss.wav')\r\nheart_plus_sound = pygame.mixer.Sound('Sounds/hp+.wav')\r\nbutton_sound = pygame.mixer.Sound('Sounds/button.wav')\r\nbullet_sound = pygame.mixer.Sound('Sounds/shot.wav')\r\n\r\n\r\nicon = pygame.image.load('Backgrounds/icon.png')\r\npygame.display.set_icon(icon)\r\n\r\ncactus_img = [pygame.image.load('Objects/Cactus0.png'), pygame.image.load('Objects/Cactus1.png'), pygame.image.load(\r\n 'Objects/Cactus2.png')]\r\ncactus_option = [69, 449, 37, 410, 40, 420]\r\n\r\n\r\nstone_img = [pygame.image.load('Objects/Stone0.png'), pygame.image.load('Objects/Stone1.png')]\r\ncloud_img = [pygame.image.load('Objects/Cloud0.png'), pygame.image.load('Objects/Cloud1.png')]\r\n\r\ndino_img = [pygame.image.load('Dino/Dino0.png'), pygame.image.load('Dino/Dino1.png'),\r\n pygame.image.load('Dino/Dino2.png'), pygame.image.load('Dino/Dino3.png'), pygame.image.load(\r\n 'Dino/Dino4.png')]\r\n\r\nbird_img = [pygame.image.load('Bird/Bird0.png'), pygame.image.load('Bird/Bird1.png'),\r\n pygame.image.load('Bird/Bird2.png'), pygame.image.load('Bird/Bird3.png'), pygame.image.load(\r\n 'Bird/Bird4.png'), pygame.image.load('Bird/Bird5.png')]\r\n\r\nhealth_image = pygame.image.load('Effects/heart.png')\r\nhealth_image = pygame.transform.scale(health_image, (30, 30))\r\n\r\nbullet_img = pygame.image.load('Effects/shot.png')\r\nbullet_img = pygame.transform.scale(bullet_img, (30, 9))\r\n\r\nimg_counter = 0\r\nhealth = 2\r\n\r\n\r\nclass Object:\r\n def __init__(self, x, y, width, speed, image):\r\n self.x = x\r\n self.y = y\r\n self.width = width\r\n self.speed = speed\r\n self.image = image\r\n\r\n def move(self):\r\n if self.x >= -self.width:\r\n display.blit(self.image, (self.x, self.y))\r\n self.x -= self.speed\r\n return True\r\n else:\r\n self.x = display_width + 50 + random.randrange(-80, 60)\r\n return False\r\n\r\n def return_self(self, radius, y, width, image):\r\n self.y = y\r\n self.width = width\r\n self.image = image\r\n self.x = radius\r\n display.blit(self.image, (self.x, self.y))\r\n\r\n\r\nclass Button:\r\n def __init__(self, width, height):\r\n self.width = width\r\n self.height = height\r\n self.inactive_color = (13, 162, 58)\r\n self.active_color = (23, 204, 58)\r\n self.draw_effects = False\r\n self.clear_effects = False\r\n self.rect_h = 10\r\n self.rect_w = width\r\n\r\n def draw(self, x, y, message, action=None, font_size=30):\r\n mouse = pygame.mouse.get_pos()\r\n click = pygame.mouse.get_pressed()\r\n # ctrl + .(на русской раскладке) коментят весь выделеный текст\r\n\r\n if x < mouse[0] < x + self.width and y < mouse[1] < y + self.height:\r\n if click[0] == 1:\r\n pygame.mixer.Sound.play(button_sound)\r\n pygame.time.delay(300)\r\n if action is not None:\r\n if action == quit:\r\n pygame.quit()\r\n quit()\r\n else:\r\n action()\r\n\r\n self.draw_beautiful_rect(mouse[0], mouse[1], x, y)\r\n print_text(message=message, x=x + 10, y=y + 10, font_size=font_size)\r\n\r\n def draw_beautiful_rect(self, ms_x, ms_y, x, y):\r\n if x <= ms_x <= x + self.width and y <= ms_y <= y + self.height:\r\n self.draw_effects = True\r\n\r\n if self.draw_effects:\r\n if ms_x < x or ms_x > x + self.width or ms_y < y or ms_y > y + self.height:\r\n self.clear_effects = True\r\n self.draw_effects = False\r\n\r\n if self.rect_h < self.height:\r\n self.rect_h += (self.height - 10) / 40\r\n\r\n if self.clear_effects and not self.draw_effects:\r\n if self.rect_h > 10:\r\n self.rect_h -= (self.height - 10) / 40\r\n else:\r\n self.clear_effects = False\r\n\r\n draw_y = y + self.height - self.rect_h\r\n pygame.draw.rect(display, self.active_color, (x, draw_y, self.rect_w, self.rect_h))\r\n\r\n\r\nclass Bullet:\r\n def __init__(self, x, y):\r\n self.x = x\r\n self.y = y\r\n self.speed_x = 8\r\n self.speed_y = 0\r\n self.dest_x = 0\r\n self.dest_y = 0\r\n\r\n def move(self):\r\n self.x += self.speed_x\r\n if self.x <= display_width:\r\n display.blit(bullet_img, (self.x, self.y))\r\n return True\r\n else:\r\n return False\r\n\r\n def find_path(self, dest_x, dest_y):\r\n self.dest_x = dest_x\r\n self.dest_y = dest_y\r\n\r\n delta_x = dest_x - self.x\r\n count_up = delta_x // self.speed_x\r\n\r\n if self.y >= dest_y:\r\n delta_y = self.y - dest_y\r\n self.speed_y = delta_y / count_up\r\n else:\r\n delta_y = dest_y - self.y\r\n self.speed_y = -(delta_y / count_up)\r\n\r\n def move_to(self, reverse=False):\r\n if reverse:\r\n self.x -= self.speed_x\r\n self.y += self.speed_y\r\n else:\r\n self.x += self.speed_x\r\n self.y -= self.speed_y\r\n\r\n if self.x <= display_width and not reverse:\r\n display.blit(bullet_img, (self.x, self.y))\r\n return True\r\n elif self.x >= 0 and reverse:\r\n display.blit(bullet_img, (self.x, self.y))\r\n return True\r\n else:\r\n return False\r\n\r\n\r\nclass Bird:\r\n def __init__(self, away_y):\r\n self.x = self.x = random.randrange(550, 730)\r\n self.y = away_y\r\n self.width = 105\r\n self.height = 55\r\n self.away_y = away_y\r\n self.speed = 3\r\n self.dest_y = self.speed * random.randrange(20, 70)\r\n self.img_cnt = 0\r\n self.cd_hide = 0\r\n self.come = True\r\n self.go_away = False\r\n self.cd_shoot = 0\r\n self.all_bullets = []\r\n\r\n def draw(self):\r\n if self.img_cnt == 30:\r\n self.img_cnt = 0\r\n\r\n display.blit(bird_img[self.img_cnt // 5], (self.x, self.y))\r\n self.img_cnt += 1\r\n\r\n if self.come and self.cd_hide == 0:\r\n return 1\r\n\r\n elif self.go_away:\r\n return 2\r\n\r\n elif self.cd_hide > 0:\r\n self.cd_hide -= 1\r\n\r\n return 0\r\n\r\n def show(self):\r\n if self.y < self.dest_y:\r\n self.y += self.speed\r\n else:\r\n self.come = False\r\n # self.go_away = True\r\n self.dest_y = self.away_y\r\n\r\n def hide(self):\r\n if self.y > self.dest_y:\r\n self.y -= self.speed\r\n else:\r\n self.come = True\r\n self.go_away = False\r\n self.x = random.randrange(550, 730)\r\n self.dest_y = self.speed * random.randrange(20, 70)\r\n self.cd_hide = 80\r\n\r\n def check_dmg(self, bullet):\r\n if self.x <= bullet.x <= self.x + self.width:\r\n if self.y <= bullet.y <= self.y + self.height:\r\n self.go_away = True\r\n\r\n def shoot(self):\r\n if not self.cd_shoot:\r\n pygame.mixer.Sound.play(bullet_sound)\r\n\r\n new_bullet = Bullet(self.x, self.y)\r\n new_bullet.find_path(usr_x + usr_width // 2, usr_y + usr_height // 2)\r\n\r\n self.all_bullets.append(new_bullet)\r\n self.cd_shoot = 200\r\n else:\r\n self.cd_shoot -= 1\r\n\r\n for bullet in self.all_bullets:\r\n if not bullet.move_to(reverse=True):\r\n self.all_bullets.remove(bullet)\r\n\r\n\r\nusr_width = 60\r\nusr_height = 100\r\nusr_x = display_width // 3\r\nusr_y = display_height - usr_height - 100\r\n\r\ncactus_width = 20\r\ncactus_height = 70\r\ncactus_x = display_width - 50\r\ncactus_y = display_height - cactus_height - 100\r\n\r\nclock = pygame.time.Clock()\r\n\r\nmake_jump = False\r\njump_counter = 30\r\n\r\nscores = 0\r\nmax_scores = 0\r\nmax_above = 0\r\n\r\ncooldown = 0\r\n\r\n\r\ndef show_menu():\r\n menu_bckgr = pygame.image.load('Backgrounds/Menu.jpg')\r\n\r\n pygame.mixer.music.load('Sounds/Big_Slinker.mp3')\r\n pygame.mixer.music.set_volume(0.5)\r\n pygame.mixer.music.play(-1)\r\n\r\n show = True\r\n start_btn = Button(288, 70)\r\n quit_btn = Button(120, 70)\r\n\r\n while show:\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n pygame.quit()\r\n quit()\r\n\r\n display.blit(menu_bckgr, (0, 0))\r\n start_btn.draw(270, 200, 'Start game.', start_game, 50)\r\n quit_btn.draw(358, 300, 'Quit', quit, 50)\r\n\r\n pygame.display.update()\r\n clock.tick(60)\r\n\r\n\r\ndef start_game():\r\n global scores, make_jump, jump_counter, usr_y, health, cooldown\r\n\r\n pygame.mixer.music.load('Sounds/background.mp3')\r\n pygame.mixer.music.set_volume(0.5)\r\n pygame.mixer.music.play(-1)\r\n\r\n while game_cycle():\r\n scores = 0\r\n make_jump = False\r\n jump_counter = 30\r\n usr_y = display_height - usr_height - 100\r\n health = 2\r\n cooldown = 0\r\n\r\n\r\ndef game_cycle():\r\n global make_jump, cooldown\r\n # Если хотим чтобы музыка играла всю игру -1, если 1 раз, то 1\r\n\r\n game = True\r\n cactus_arr = []\r\n create_cactus_arr(cactus_arr)\r\n land = pygame.image.load('Backgrounds/Land1.jpg')\r\n\r\n stone, cloud = open_random_objects()\r\n heart = Object(display_width, 280, 30, 4, health_image)\r\n\r\n all_btn_bullets = []\r\n all_ms_bullets = []\r\n\r\n bird1 = Bird(-80)\r\n bird2 = Bird(-70)\r\n\r\n all_birds = [bird1, bird2]\r\n\r\n while game:\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n pygame.quit()\r\n quit()\r\n\r\n keys = pygame.key.get_pressed()\r\n mouse = pygame.mouse.get_pos()\r\n click = pygame.mouse.get_pressed()\r\n\r\n if keys[pygame.K_SPACE]:\r\n make_jump = True\r\n\r\n count_scores(cactus_arr)\r\n\r\n display.blit(land, (0, 0))\r\n print_text('Scores: ' + str(scores), 600, 10)\r\n\r\n draw_array(cactus_arr)\r\n move_obects(stone, cloud)\r\n\r\n draw_dino()\r\n\r\n if keys[pygame.K_ESCAPE]:\r\n pause()\r\n\r\n if not cooldown:\r\n if keys[pygame.K_x]:\r\n pygame.mixer.Sound.play(bullet_sound)\r\n all_btn_bullets.append(Bullet(usr_x + usr_width, usr_y + 28))\r\n cooldown = 50\r\n elif click[0]:\r\n pygame.mixer.Sound.play(bullet_sound)\r\n add_bullet = Bullet(usr_x + usr_width, usr_y + 28)\r\n add_bullet.find_path(mouse[0], mouse[1])\r\n all_ms_bullets.append(add_bullet)\r\n cooldown = 50\r\n\r\n else:\r\n print_text('Cooldown time:' + str(cooldown // 10), 482, 40)\r\n cooldown -= 1\r\n\r\n for bullet in all_btn_bullets:\r\n if not bullet.move():\r\n all_btn_bullets.remove(bullet)\r\n\r\n for bullet in all_ms_bullets:\r\n if not bullet.move_to():\r\n all_ms_bullets.remove(bullet)\r\n\r\n heart.move()\r\n hearts_plus(heart)\r\n\r\n if make_jump:\r\n jump()\r\n\r\n if check_collision(cactus_arr):\r\n # pygame.mixer.music.stop()\r\n # pygame.mixer.Sound.play(fall_sound)\r\n # if not check_health():\r\n game = False\r\n\r\n show_health()\r\n\r\n # bird1.draw()\r\n # bird2.draw()\r\n\r\n draw_birds(all_birds)\r\n check_birds_dmg(all_ms_bullets, all_birds)\r\n\r\n pygame.display.update()\r\n clock.tick(80)\r\n\r\n return game_over()\r\n\r\n\r\ndef jump():\r\n global usr_y, jump_counter, make_jump\r\n if jump_counter >= -30:\r\n if jump_counter == 30:\r\n pygame.mixer.Sound.play(jump_sound)\r\n if jump_counter == -30:\r\n pygame.mixer.Sound.play(fall_sound)\r\n\r\n usr_y -= jump_counter / 2.5\r\n jump_counter -= 1\r\n else:\r\n jump_counter = 30\r\n make_jump = False\r\n\r\n\r\ndef create_cactus_arr(array):\r\n choice = random.randrange(0, 3)\r\n img = cactus_img[choice]\r\n width = cactus_option[choice * 2]\r\n height = cactus_option[choice * 2 + 1]\r\n array.append(Object(display_width + 20, height, width, 4, img))\r\n\r\n choice = random.randrange(0, 3)\r\n img = cactus_img[choice]\r\n width = cactus_option[choice * 2]\r\n height = cactus_option[choice * 2 + 1]\r\n array.append(Object(display_width + 300, height, width, 4, img))\r\n\r\n choice = random.randrange(0, 3)\r\n img = cactus_img[choice]\r\n width = cactus_option[choice * 2]\r\n height = cactus_option[choice * 2 + 1]\r\n array.append(Object(display_width + 600, height, width, 4, img))\r\n\r\n\r\ndef find_radius(array):\r\n maximum = max(array[0].x, array[1].x, array[2].x)\r\n\r\n if maximum < display_width:\r\n radius = display_width\r\n if radius - maximum < 50:\r\n radius += 280\r\n else:\r\n radius = maximum\r\n\r\n choise = random.randrange(0, 5)\r\n if choise == 0:\r\n radius += random.randrange(10, 15)\r\n else:\r\n radius += random.randrange(250, 400)\r\n\r\n return radius\r\n\r\n\r\ndef draw_array(array):\r\n for cactus in array:\r\n check = cactus.move()\r\n if not check:\r\n object_return(array, cactus)\r\n radius = find_radius(array)\r\n\r\n choice = random.randrange(0, 3)\r\n img = cactus_img[choice]\r\n width = cactus_option[choice * 2]\r\n height = cactus_option[choice * 2 + 1]\r\n\r\n cactus.return_self(radius, height, width, img)\r\n\r\n\r\ndef object_return(objects, obj):\r\n radius = find_radius(objects)\r\n\r\n choice = random.randrange(0, 3)\r\n img = cactus_img[choice]\r\n width = cactus_option[choice * 2]\r\n height = cactus_option[choice * 2 + 1]\r\n\r\n obj.return_self(radius, height, width, img)\r\n\r\n\r\ndef open_random_objects():\r\n choice = random.randrange(0, 2)\r\n img_of_stone = stone_img[choice]\r\n\r\n choice = random.randrange(0, 2)\r\n img_of_cloud = cloud_img[choice]\r\n\r\n stone = Object(display_width, display_height - 80, 10, 4, img_of_stone)\r\n cloud = Object(display_width, 80, 70, 2, img_of_cloud)\r\n\r\n return stone, cloud\r\n\r\n\r\ndef move_obects(stone, cloud):\r\n check = stone.move()\r\n if not check:\r\n choice = random.randrange(0, 2)\r\n img_of_stone = stone_img[choice]\r\n stone.return_self(display_width, 500 + random.randrange(10, 80), stone.width, img_of_stone)\r\n\r\n check = cloud.move()\r\n if not check:\r\n choice = random.randrange(0, 2)\r\n img_of_cloud = cloud_img[choice]\r\n cloud.return_self(display_width, random.randrange(10, 200), cloud.width, img_of_cloud)\r\n\r\n\r\ndef draw_dino():\r\n global img_counter\r\n if img_counter == 25:\r\n img_counter = 0\r\n\r\n display.blit(dino_img[img_counter // 5], (usr_x, usr_y))\r\n img_counter += 1\r\n\r\n\r\ndef print_text(message, x, y, font_color=(0, 0, 0), font_type='PingPong.ttf', font_size = 30):\r\n font_type = pygame.font.Font(font_type, font_size)\r\n text = font_type.render(message, True, font_color)\r\n display.blit(text, (x, y))\r\n\r\n\r\ndef pause():\r\n paused = True\r\n\r\n pygame.mixer.music.pause()\r\n\r\n while paused:\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n pygame.quit()\r\n quit()\r\n\r\n print_text('Paused. Press enter to continue.', 160, 300)\r\n\r\n keys = pygame.key.get_pressed()\r\n if keys[pygame.K_RETURN]:\r\n paused = False\r\n\r\n pygame.display.update()\r\n clock.tick(15)\r\n\r\n pygame.mixer.music.unpause()\r\n\r\n\r\ndef check_collision(barriers): # проверка на то, персонаж ли игрок с кактусом, или нет\r\n for barrier in barriers: # проходимся по всем препятствиям, через которые должен перепрыгнуть игрок\r\n if barrier.y == 449: # маленький кактус\r\n if not make_jump: # если не делаем прыжок\r\n if barrier.x <= usr_x + usr_width - 22 <= barrier.x + barrier.width: # если выполняется это условие\r\n if check_health():\r\n object_return(barriers, barrier)\r\n else:\r\n return True\r\n\r\n elif jump_counter >= 0: # если прыжок начинает возрастать. 1 часть параболы\r\n if usr_y + usr_height - 5 >= barrier.y: # проверяем координаты по у\r\n if barrier.x <= usr_x + usr_width - 22 <= barrier.x + barrier.width: # проверка правой координаты\r\n if check_health():\r\n object_return(barriers, barrier)\r\n else:\r\n return True\r\n else: # если же вторая часть прыжка\r\n if usr_y + usr_height - 10 >= barrier.y: # проверяем координаты по у\r\n if barrier.x <= usr_x <= barrier.x + barrier.width: # проверка правой координаты\r\n if check_health():\r\n object_return(barriers, barrier)\r\n else:\r\n return True\r\n else: # если не маленький кактус\r\n if not make_jump: # если не делаем прыжок\r\n if barrier.x <= usr_x + usr_width + 5 <= barrier.x + barrier.width: # если выполняется это условие\r\n if check_health():\r\n object_return(barriers, barrier)\r\n return False\r\n else:\r\n return True\r\n elif jump_counter == 10: # начало прыжка\r\n if usr_y + usr_height - 2 >= barrier.y: # если есть столкновение по координате y\r\n if barrier.x <= usr_x + 13 <= barrier.x + barrier.width: # Если столкнулись\r\n if check_health():\r\n object_return(barriers, barrier)\r\n return False\r\n else:\r\n return True\r\n elif jump_counter <= 1: # до того момента, как динозавр начнет падать вниз\r\n if usr_y + usr_height - 2 >= barrier.y: # столкновение по у\r\n if barrier.x <= usr_x + usr_width + 13 <= barrier.x + barrier.width: # по х координате\r\n if check_health():\r\n object_return(barriers, barrier)\r\n return False\r\n else:\r\n return True\r\n elif jump_counter >= 1: # игрок совершает 2 часть прыжка\r\n if usr_y + usr_height - 2 >= barrier.y: # столкновение по у\r\n if barrier.x <= usr_x + usr_width - 22 <= barrier.x + barrier.width: # по х координате\r\n if check_health():\r\n object_return(barriers, barrier)\r\n return False\r\n else:\r\n return True\r\n else:\r\n if usr_y + usr_height - 3 >= barrier.y: # проверяем координаты по у\r\n if barrier.x <= usr_x + usr_width + 5 <= barrier.x + barrier.width: # проверка правой координаты\r\n if check_health():\r\n object_return(barriers, barrier)\r\n return False\r\n else:\r\n return True\r\n return False # если же ничего не произошло, то возвращаем false, т.е ничего не было\r\n\r\n\r\ndef count_scores(cactus_arr):\r\n global scores\r\n for cactus in cactus_arr:\r\n if cactus.x - 2 <= usr_x <= cactus.x + 1:\r\n scores += 1\r\n\r\n\r\n\r\ndef game_over():\r\n stopped = True\r\n while stopped:\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n pygame.quit()\r\n quit()\r\n\r\n print_text('Game over. Press enter to play again, Esc to exit.', 40, 300)\r\n\r\n keys = pygame.key.get_pressed()\r\n if keys[pygame.K_RETURN]:\r\n return True\r\n\r\n if keys[pygame.K_ESCAPE]:\r\n return False\r\n\r\n pygame.display.update()\r\n clock.tick(15)\r\n\r\n\r\ndef show_health():\r\n global health\r\n show = 0\r\n x = 20\r\n while show != health:\r\n display.blit(health_image, (x, 20))\r\n x += 40\r\n show += 1\r\n\r\n\r\ndef check_health():\r\n global health\r\n health -= 1\r\n if health == 0:\r\n pygame.mixer.Sound.play(lose_sound)\r\n return False\r\n else:\r\n pygame.mixer.Sound.play(fall_sound)\r\n return True\r\n\r\n\r\ndef hearts_plus(heart):\r\n global health, usr_x, usr_y, usr_width, usr_height\r\n\r\n if heart.x <= -heart.width:\r\n radius = display_width + random.randrange(1000, 3000)\r\n heart.return_self(radius, heart.y, heart.width, heart.image)\r\n\r\n if usr_x <= heart.x <= usr_x + usr_width:\r\n if usr_y <= heart.y <= usr_y + usr_height:\r\n pygame.mixer.Sound.play(heart_plus_sound)\r\n if health < 5:\r\n health += 1\r\n\r\n radius = display_width + random.randrange(1000, 3000)\r\n heart.return_self(radius, heart.y, heart.width, heart.image)\r\n\r\n\r\ndef draw_birds(birds):\r\n for bird in birds:\r\n action = bird.draw()\r\n if action == 1:\r\n bird.show()\r\n elif action == 2:\r\n bird.hide()\r\n else:\r\n bird.shoot()\r\n\r\n\r\ndef check_birds_dmg(bullets, birds):\r\n for bird in birds:\r\n for bullet in bullets:\r\n bird.check_dmg(bullet)\r\n\r\n\r\nshow_menu()\r\n\r\npygame.quit()\r\nquit()\r\n","repo_name":"3TonY3/PythonProject","sub_path":"not dinozavr.py","file_name":"not dinozavr.py","file_ext":"py","file_size_in_byte":22556,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"60"} +{"seq_id":"14375294222","text":"\"\"\"\nempty message\n\nRevision ID: de010dc14402\nRevises: 55365e50ff52\nCreate Date: 2020-07-02 14:17:23.420116\n\n\"\"\"\nfrom alembic import op\nfrom marshmallow import fields, validate\nimport sqlalchemy as sa\nimport sqlalchemy_utils\nfrom sqlalchemy_utils.types.json import JSONType\nfrom sqlalchemy_utils.types.uuid import UUIDType\n\nfrom viime.models import BaseModel, BaseSchema, CSVFile, db, \\\n METADATA_TYPES, TABLE_COLUMN_TYPES, TABLE_ROW_TYPES, \\\n ValidatedMetaboliteTable\n\n\n# revision identifiers, used by Alembic.\nrevision = 'de010dc14402'\ndown_revision = '55365e50ff52'\nbranch_labels = None\ndepends_on = None\n\n\nclass TableColumn(BaseModel):\n csv_file_id = db.Column(UUIDType(binary=False), db.ForeignKey('csv_file.id'), primary_key=True)\n column_index = db.Column(db.Integer, primary_key=True)\n column_type = db.Column(db.String, nullable=False)\n subtype = db.Column(db.String, nullable=True)\n meta = db.Column(JSONType, nullable=True)\n\n csv_file = db.relationship(\n CSVFile, backref=db.backref('columns', lazy=True, order_by='TableColumn.column_index'))\n\n\nclass TableColumnSchema(BaseSchema):\n __model__ = TableColumn # type: ignore\n\n column_index = fields.Int(required=True, validate=validate.Range(min=0))\n column_type = fields.Str(required=True, validate=validate.OneOf(TABLE_COLUMN_TYPES))\n subtype = fields.Str(required=False, validate=validate.OneOf(METADATA_TYPES))\n meta = fields.Dict(missing=dict)\n\n\nclass TableRow(BaseModel):\n csv_file_id = db.Column(\n UUIDType(binary=False), db.ForeignKey('csv_file.id'), primary_key=True)\n row_index = db.Column(db.Integer, primary_key=True)\n row_type = db.Column(db.String, nullable=False)\n subtype = db.Column(db.String, nullable=True)\n meta = db.Column(JSONType, nullable=True)\n\n csv_file = db.relationship(\n CSVFile, backref=db.backref('rows', lazy=True, order_by='TableRow.row_index'))\n\n\nclass TableRowSchema(BaseSchema):\n __model__ = TableRow # type: ignore\n\n row_name = fields.Str(dump_only=True)\n row_index = fields.Int(required=True, validate=validate.Range(min=0))\n row_type = fields.Str(required=True, validate=validate.OneOf(TABLE_ROW_TYPES))\n subtype = fields.Str(required=False, validate=validate.OneOf(METADATA_TYPES))\n meta = fields.Dict(missing=dict)\n\n\ndef upgrade(): # noqa\n column_schema = TableColumnSchema()\n row_schema = TableRowSchema()\n op.add_column(\n 'csv_file',\n sa.Column('column_json', sqlalchemy_utils.types.json.JSONType(), nullable=True)\n )\n op.add_column(\n 'csv_file',\n sa.Column('row_json', sqlalchemy_utils.types.json.JSONType(), nullable=True)\n )\n\n # move row/column information into csv_file table here:\n for csv_file in CSVFile.query:\n try:\n column_json = column_schema.dump(csv_file.columns, many=True)\n row_json = row_schema.dump(csv_file.rows, many=True)\n\n key_column_index = 0\n data_column_index = 0\n for index, column in enumerate(column_json):\n dci = None\n if column['column_type'] == TABLE_COLUMN_TYPES.DATA:\n dci = data_column_index\n data_column_index += 1\n elif column['column_type'] == TABLE_COLUMN_TYPES.INDEX:\n key_column_index = index\n column['data_column_index'] = dci\n\n header_row_index = 0\n data_row_index = 0\n keys = csv_file.table.iloc[:, key_column_index]\n for index, row in enumerate(row_json):\n dri = None\n if row['row_type'] == TABLE_ROW_TYPES.DATA:\n dri = data_row_index\n data_row_index += 1\n elif row['row_type'] == TABLE_ROW_TYPES.INDEX:\n header_row_index = index\n\n row['data_row_index'] = dri\n row['row_name'] = str(keys.iloc[index])\n\n headers = csv_file.table.iloc[header_row_index, :]\n for index, column in enumerate(column_json):\n column['column_header'] = str(headers.iloc[index])\n\n csv_file.column_json = column_json\n csv_file.row_json = row_json\n except Exception:\n # some tables have irreconcileable errors, so just delete them\n print(f'Deleting {csv_file.id}')\n for row in csv_file.rows:\n db.session.delete(row)\n for column in csv_file.columns:\n db.session.delete(column)\n validated = ValidatedMetaboliteTable.query.filter_by(csv_file_id=csv_file.id).first()\n if validated:\n db.session.delete(validated)\n db.session.commit()\n db.session.delete(csv_file)\n\n db.session.commit()\n\n with op.batch_alter_table('csv_file', schema=None) as batch_op:\n batch_op.alter_column('column_json', nullable=False)\n batch_op.alter_column('row_json', nullable=False)\n op.drop_table('table_row')\n op.drop_table('table_column')\n\n\ndef downgrade():\n op.drop_column('csv_file', 'row_json')\n op.drop_column('csv_file', 'column_json')\n op.create_table(\n 'table_column',\n sa.Column('csv_file_id', sa.CHAR(length=32), nullable=False),\n sa.Column('column_index', sa.INTEGER(), nullable=False),\n sa.Column('column_type', sa.VARCHAR(), nullable=False),\n sa.Column('meta', sa.TEXT(), nullable=True),\n sa.Column('subtype', sa.VARCHAR(), nullable=True),\n sa.ForeignKeyConstraint(\n ['csv_file_id'], ['csv_file.id'],\n name='fk_table_column_csv_file_id_csv_file'\n ),\n sa.PrimaryKeyConstraint('csv_file_id', 'column_index', name='pk_table_column')\n )\n op.create_table(\n 'table_row',\n sa.Column('csv_file_id', sa.CHAR(length=32), nullable=False),\n sa.Column('row_index', sa.INTEGER(), nullable=False),\n sa.Column('row_type', sa.VARCHAR(), nullable=False),\n sa.Column('meta', sa.TEXT(), nullable=True),\n sa.Column('subtype', sa.VARCHAR(), nullable=True),\n sa.ForeignKeyConstraint(\n ['csv_file_id'], ['csv_file.id'], name='fk_table_row_csv_file_id_csv_file'),\n sa.PrimaryKeyConstraint('csv_file_id', 'row_index', name='pk_table_row')\n )\n","repo_name":"girder/viime","sub_path":"migrations/versions/de010dc14402_.py","file_name":"de010dc14402_.py","file_ext":"py","file_size_in_byte":6317,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"60"} +{"seq_id":"8247140661","text":"#Euler 10 - Find the sum of all the primes below two million.\r\n\r\nint_list = []\r\nnum = 0\r\n\r\ndef prime_check (z):\r\n if z >= 0 and z <=3:\r\n return True\r\n else:\r\n if z%2 == 0:\r\n return False\r\n for y in range (3,int(z**0.5)+1,2):\r\n #print (str(z)+\"%\"+str(y)+\" - \"+str(z%y))\r\n if z%y==0:\r\n return False\r\n return True\r\n\r\nfor x in range (3,2000000,2):\r\n if x==3:\r\n num += 1+2+3\r\n #int_list.append(1,2,3)\r\n elif prime_check(x)==True:\r\n num += x\r\n #int_list.append(x)\r\n\r\n#print(int_list)\r\nprint (num)","repo_name":"phillips0616/euler100","sub_path":"tt/Euler010.py","file_name":"Euler010.py","file_ext":"py","file_size_in_byte":606,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"60"} +{"seq_id":"32165031037","text":"import requests\nimport lxml.html as lh\nimport pandas as pd\n\nroot = 'https://www.wahlrecht.de/umfragen/'\ninsts = [\n 'allensbach',\n 'emnid',\n 'politbarometer',\n 'gms',\n 'dimap',\n 'insa',\n 'yougov'\n]\n\ndef getUrl(inst):\n return root + inst + '.htm'\n\ndef getData(inst):\n # Create a handle, page, to handle the contents of the website\n page = requests.get(getUrl(inst))\n\n # Store the contents of the website under doc\n doc = lh.fromstring(page.content)\n\n # Create empty list\n headers=[]\n data=[]\n headers.append('date')\n\n # Parse headers header\n theader = doc.xpath('/html/body/table/thead/tr')\n\n # Parse body\n tbody = doc.xpath('/html/body/table/tbody')\n\n # store headers in an empty list\n for t in theader[0]:\n name=t.text_content()\n if len(name) > 1 and name != 'Datum':\n headers.append(name)\n\n # loop through rows\n for r in tbody[0]:\n row = []\n\n # loop through cells\n for t in r:\n name=t.text_content()\n\n # exclude \\ cells but include NaN\n if len(name) > 1 or name in ['?', '–']:\n # print('this is the name: ' + name)\n row.append(name)\n\n zipbObj = zip(headers, row)\n datadict = dict(zipbObj)\n data.append(datadict)\n\n # create data frame from dictionaries\n polls = pd.DataFrame(data)\n polls['Institut'] = inst\n\n # drop bundestagswahl rows\n polls = polls.dropna(axis=0, how='any', thresh=None, subset=None, inplace=False)\n return polls\n\n# save polling data to csv\nfor i in insts:\n results = getData(i)\n results.to_csv(\n r'./data/' + i + '.csv',\n index=None, header=True, sep=\";\")","repo_name":"henrythier/wahlen","sub_path":"polls.py","file_name":"polls.py","file_ext":"py","file_size_in_byte":1573,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"60"} +{"seq_id":"42546989102","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 ('content', '0006_authorizationtoken'),\n ]\n\n operations = [\n migrations.RenameField(\n model_name='locationcontent',\n old_name='google_doc',\n new_name='html_url',\n ),\n ]\n","repo_name":"reyrodrigues/refugeeinfo.eu","sub_path":"content/migrations/0007_auto_20151026_1504.py","file_name":"0007_auto_20151026_1504.py","file_ext":"py","file_size_in_byte":402,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"60"} +{"seq_id":"32317763856","text":"from fastapi import Depends, HTTPException, Query\nfrom sqlalchemy.orm import Session\nfrom databases.config import get_db\nfrom .. import models,schemas\nimport functools\n\n\"\"\" 1. GET \"\"\"\n\n\n\n\n\n#\ndef get_groups(\n skip: int = 0,\n limit: int = 100,\n db: Session = Depends(get_db),\n):\n return db.query(models.Groups).offset(skip).limit(limit).all()\n\n\n\"\"\" 2. POST \"\"\"\n\n\ndef post_group(group: schemas.Group, db: Session = Depends(get_db)):\n db_item = models.Groups(**group.dict())\n db.add(db_item)\n db.commit()\n db.refresh(db_item)\n return db_item\n\n\n\n\n\"\"\" 3. GET by id \"\"\"\ndef get_group_by_id(group_id:int,db: Session = Depends(get_db)):\n group = db.query(models.Groups).filter(models.Groups.id==group_id).first()\n if group:\n return group\n raise HTTPException(status_code=404, detail=\"Department not found\")\n\n\n\n\n\"\"\" 4. UPDATE \"\"\"\n\ndef update_group(group_id: int, group: schemas.Group, db: Session = Depends(get_db)):\n db_group = db.query(models.Groups).filter(models.Groups.id == group_id).first()\n if db_group:\n for var, value in vars(group).items():\n setattr(db_group, var, value) if value else None\n db.add(db_group)\n db.commit()\n db.refresh(db_group)\n return db_group\n else:\n raise HTTPException(status_code=400, detail=\"Department with id %s not found\" % group_id)\n\n\n\n\"\"\" 5. DELETE \"\"\"\ndef delete_group(group_id,db: Session = Depends(get_db)):\n try:\n aux = db.query(models.Groups).filter_by(id=group_id).delete()\n if aux == 0:\n raise HTTPException(status_code=400, detail=\"Department with id %s not found\" % group_id)\n else:\n db.commit()\n return {'Msg':\"Department with id %s deleted\" % group_id}\n except HTTPException as e:\n raise\n except Exception as e:\n #print(e); esto no va para el usuario sino para mi login\n raise HTTPException(status_code=500, detail=\"Server Error\")\n return\n\n\n\n\n\n\n\"\"\"\n# mapeo de nombres y claves; tmb. podría definir consultas del tipo FK\ndef mapeo():\n return {\n \"tipo\": models.Sede.tipo,\n \"direccion\": models.Sede.direccion,\n \"nombre\": models.Sede.nombre,\n }\n\n\ndef filter_department(data):\n queries = [models.Sede.id > 0]\n campos = mapeo()\n for clave, valor in data.items():\n if valor:\n if isinstance(valor, str):\n queries.append(campos[clave] == valor)\n elif isinstance(valor, list):\n queries_aux = []\n for v in valor:\n queries_aux.append(campos[clave] == v)\n query_aux = functools.reduce(lambda a, b: a | b, queries_aux)\n queries.append(query_aux)\n query = functools.reduce(lambda a, b: (a & b), queries)\n return query\n\n\n\nuso:\n\nquery = filter_department(\n {\n 'tipo': tipo,\n 'direccion': direccion,\n 'nombre': nombre\n })\n return list(db.query(models.Sede).filter(query).offset(skip).limit(limit))\n\n\"\"\"","repo_name":"MNGARCIA085/Fast-API---Fisrt-projects","sub_path":"FASTAPI-RBAC/app/auth/groups/db_operations.py","file_name":"db_operations.py","file_ext":"py","file_size_in_byte":3039,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"60"} +{"seq_id":"70389126272","text":"def url():\r\n urldaily = \"http://datapoint.metoffice.gov.uk/public/data/val/wxfcs/all/json/all?res=daily&key=137a0d7f-fe44-4086-bcec-a5135a5e40a0\"\r\n return urldaily\n\ndef sitemapping():\n return {\n 'id':'siteID',\n 'name':'siteName',\n 'unitaryAuthArea':'region'\n }\r\n\r\ndef dailydatacolumnsmapping():\r\n return {\r\n 'i': 'siteid',\r\n 'lat': 'latitude',\r\n 'Dm': 'day_max_temperature',\r\n 'Period.value': 'weather_date',\r\n 'FDm': 'feels_like_day_max_temperature',\r\n 'Gn': 'wind_gust_noon',\r\n 'U': 'max_uv_index',\r\n 'name': 'region',\r\n 'Hn': 'screen_relative_humidity_noon',\r\n 'PPd': 'precipitation_probability_day',\r\n 'lon': 'longitude',\r\n 'D': 'wind_direction',\r\n 'Gm': 'wind_gust_midnight',\r\n 'Hm': 'screen_relative_humidity_midnight',\r\n 'PPn': 'precipitation_probability_night',\r\n 'S': 'wind_speed',\r\n 'V': 'visibility',\r\n 'Nm': 'night_min_temperature',\r\n 'FNm': 'feels_like_night_min_temperature',\r\n 'W': 'weather_type',\r\n 'max_uv_index': '0',\r\n '$': 'daynight_indicator',\r\n }\r\n\r\ndef dailydatacolconvert():\r\n return ['day_max_temperature',\r\n 'feels_like_day_max_temperature',\r\n 'feels_like_night_min_temperature',\r\n 'wind_gust_midnight',\r\n 'wind_gust_noon',\r\n 'screen_relative_humidity_midnight',\r\n 'screen_relative_humidity_noon',\r\n 'night_min_temperature',\r\n 'precipitation_probability_day',\r\n 'wind_speed',\r\n 'max_uv_index',\r\n 'weather_type',\r\n 'longitude',\r\n 'latitude',\r\n 'siteid',\r\n 'precipitation_probability_night']\r\n\r\ndef addnewcolumns():\r\n return ['dl_filename',\r\n 'dl_line_no',\r\n 'dl_file_date',\r\n 'dl_insert_dttm',\r\n 'dl_talend_job_id',\r\n 'dl_talend_job_run_id']\r\n\r\ndef locationkeys():\n return [\"name\", \"lat\", \"lon\", \"i\", [\"Period\", \"value\"]]","repo_name":"shashank-puranik/Weather","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":2052,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"60"} +{"seq_id":"10921296564","text":"import os\nimport sys\nimport sysconfig\nfrom setuptools import find_packages\nfrom setuptools import setup\nfrom setuptools.extension import Extension\n\n\ndef config_cython():\n sys_cflags = sysconfig.get_config_var('CFLAGS')\n try:\n from Cython.Build import cythonize\n ret = []\n path = 'tpm/_cython'\n for fn in os.listdir(path):\n if fn.endswith('.pyx'):\n ret.append(Extension(\n 'tpm.%s' % fn[:-4],\n ['%s/%s' % (path, fn)],\n include_dirs=['../include'],\n # libraries=['tpm_runtime'],\n libraries=[],\n extra_compile_args=['-DUSE_CUDNN', '-std=c++11'],\n extra_link_args=[],\n language='c++',\n ))\n return cythonize(ret, compiler_directives={'language_level': 3})\n except ImportError:\n print(\"Cython is not installed\")\n return []\n\n\nsetup(\n name='tpm',\n version='0.1',\n description='Optimizing Deep Learning Computations with Tensor Mutations',\n zip_safe=False,\n install_requires=[],\n packages=find_packages(),\n url='https://github.com/whjthu/ml-opt',\n ext_modules=config_cython(),\n)\n","repo_name":"thu-pacman/PET","sub_path":"python/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1244,"program_lang":"python","lang":"en","doc_type":"code","stars":109,"dataset":"github-code","pt":"60"} +{"seq_id":"25309861849","text":"import tkinter as tk\nfrom tkinter import ttk as ttk\nfrom DataFrameManager import *\nfrom TableDisplay import *\nfrom pandastable import Table\nfrom PlotDisplay import *\nfrom matplotlib.backends.backend_tkagg import FigureCanvasTkAgg \n\nclass GUI:\n\n selected_game = 0\n selected_team = 0\n selected_player = 0\n event_array = []\n\n \n def __init__(self, root, data_frame_manager: DataFrameManager):\n print('GUI Initialized')\n\n # General dataframe\n self.dfm = data_frame_manager\n\n # Window Canvas\n self.canvas = tk.Canvas(root, width=1250, height=600)\n self.canvas.pack()\n\n # Creating left and right frames\n self.frm_left = tk.Frame(root, bg='gray92')\n self.frm_left.place(relheight=1, relwidth=0.25) # Left Frame\n\n self.frm_right = tk.Frame(root, bg='white')\n self.frm_right.place(relx=0.25, relheight=1, relwidth=0.75) # Right Frame\n\n ##### Left frame widgets #####\n \n # Display selection\n self.lbl_display = tk.Label(self.frm_left, text='Display:', bg='gray')\n self.lbl_display.pack(fill='x')\n self.combo_display = ttk.Combobox(self.frm_left, values=['Table - Individual Events', 'Table - Aggregate Events', 'Point Map'])\n self.combo_display.pack(fill='x')\n self.combo_display.current(0)\n\n self.combo_list_games = []\n self.combo_list_teams = []\n self.combo_list_players = []\n\n # Creating combobox list of games, Replacing Olympic text because it's ugly\n self.game_array = data_frame_manager.game_df.values.tolist()\n self.combo_list_games.append(\"All\")\n for i in self.game_array:\n home = i[1].replace(\"Olympic (Women) - \",\"\")\n away = i[2].replace(\"Olympic (Women) - \",\"\")\n txt = i[0]+ \": \" + away + \" @ \" + home\n self.combo_list_games.append(txt)\n \n self.team_array = []\n self.player_array = []\n\n # Filter Players based on combobox results\n def filter_players():\n self.combo_list_players = []\n self.combo_list_players.append(\"All\")\n if self.selected_team != 0:\n self.player_array = data_frame_manager.player_df.sort_values('Player').where((data_frame_manager.player_df['TeamID'] == self.selected_team)).dropna().astype({\"TeamID\":'int', \"PlayerID\":'int'}).values.tolist()\n for i in self.player_array:\n self.combo_list_players.append(i[0])\n else: \n self.player_array = data_frame_manager.player_df.sort_values('Player').values.tolist()\n for i in self.player_array:\n self.combo_list_players.append(i[0])\n self.combo_player.configure(values=self.combo_list_players)\n\n # Filter teams based on combobox results\n def filter_teams():\n self.combo_list_teams = []\n self.combo_list_teams.append(\"All\")\n if self.selected_game != 0:\n home_str = data_frame_manager.game_df['Home Team'].where(data_frame_manager.game_df['GameID'] == self.selected_game).dropna().iloc[0]\n away_str = data_frame_manager.game_df['Away Team'].where(data_frame_manager.game_df['GameID'] == self.selected_game).dropna().iloc[0]\n self.team_array = data_frame_manager.team_df.where((data_frame_manager.team_df['Team'] == home_str) | (data_frame_manager.team_df['Team'] == away_str)).dropna().astype({\"TeamID\":'int'}).values.tolist()\n for i in self.team_array:\n self.combo_list_teams.append(i[0])\n else: \n self.team_array = data_frame_manager.team_df.values.tolist()\n for i in self.team_array:\n self.combo_list_teams.append(i[0])\n self.combo_team.configure(values=self.combo_list_teams)\n filter_players()\n\n # Game selection\n def pick_game(e):\n game = self.combo_game.get()\n idx = -1\n for i in self.combo_list_games:\n if i == game:\n break\n idx += 1\n if idx == -1:\n self.selected_game = 0\n else:\n self.selected_game = self.game_array[idx][3]\n self.selected_team = 0\n self.selected_player = 0\n filter_teams()\n \n self.lbl_game = tk.Label(self.frm_left, text='Game:', bg='gray')\n self.lbl_game.pack(fill='x')\n self.combo_game = ttk.Combobox(self.frm_left, values=self.combo_list_games)\n self.combo_game.pack(fill='x')\n self.combo_game.bind(\"<>\", pick_game)\n self.combo_game.current = 0\n\n # Team selection\n def pick_team(e):\n team = self.combo_team.get()\n idx = -1\n for i in self.combo_list_teams:\n if i == team:\n break\n idx += 1\n if idx == -1:\n self.selected_team = 0\n else:\n self.selected_team = self.team_array[idx][1]\n \n self.selected_player = 0\n filter_players()\n \n self.lbl_team = tk.Label(self.frm_left, text='Team:', bg='gray')\n self.lbl_team.pack(fill='x')\n self.combo_team = ttk.Combobox(self.frm_left, values=self.combo_list_teams)\n self.combo_team.pack(fill='x')\n self.combo_team.bind(\"<>\", pick_team)\n self.combo_team.current = 0\n\n # Player selection\n def pick_player(e):\n player = self.combo_player.get()\n idx = -1\n for i in self.combo_list_players:\n if i == player:\n break\n idx += 1\n if idx == -1:\n self.selected_player = 0\n else:\n self.selected_player = self.player_array[idx][1]\n \n self.lbl_player = tk.Label(self.frm_left, text='Player:', bg='gray')\n self.lbl_player.pack(fill='x')\n self.combo_player = ttk.Combobox(self.frm_left, values=self.combo_list_players)\n self.combo_player.pack(fill='x')\n self.combo_player.bind(\"<>\", pick_player)\n self.combo_player.current = 0\n \n # Event Selection\n self.lbl_events = tk.Label(self.frm_left, text='Events:', bg='gray')\n self.lbl_events.pack(fill='x')\n self.combo_list_events = ['Shot Attempts', 'Goals', 'Plays', 'Takeaways', 'Recoveries', 'Zone Entries', 'Faceoffs', 'Penalties']\n for index, event in enumerate(self.combo_list_events):\n self.event_array.append(tk.IntVar(value=0, name=event))\n tk.Checkbutton(self.frm_left, variable=self.event_array[index], bg='gray92', text=event).pack()\n \n # Show data button\n self.btn_show_data = tk.Button(self.frm_left, text='Show Data', bg='gray92', command=self.show_data)\n self.btn_show_data.pack(fill='x')\n\n # Chooses which data is to be displayed\n def show_data(self):\n \n ##### Right frame widgets #####\n\n # Destroying old sub frame and adding a new one in frm_right\n for widget in self.frm_right.winfo_children():\n widget.destroy()\n self.frm_right.pack_forget()\n self.frm_sub = tk.Frame(self.frm_right, bg='white')\n self.frm_sub.place(relx=0, relheight=1, relwidth=1)\n\n if self.combo_display.get() == 'Table - Individual Events':\n self.individual_table()\n if self.combo_display.get() == 'Table - Aggregate Events':\n self.aggregate_table()\n if self.combo_display.get() == 'Point Map':\n self.point_map()\n \n # Individual events\n def individual_table(self):\n table_display = TableDisplay(self.dfm.whole_df)\n df = table_display.individual_table(self.selected_game, self.selected_team, self.selected_player, self.event_array)\n pt = Table(self.frm_sub, dataframe=df)\n pt.show()\n\n # Aggregated events\n def aggregate_table(self):\n table_display = TableDisplay(self.dfm.whole_df)\n df = table_display.aggregate_table(self.selected_game, self.selected_team, self.selected_player, self.event_array, self.dfm.game_df, self.dfm.team_df, self.dfm.player_df)\n pt = Table(self.frm_sub, dataframe=df)\n pt.show()\n \n # Map of individual events\n def point_map(self):\n try:\n plot_display = PlotDisplay(self.dfm.whole_df)\n df_plot = plot_display.plot_data(self.selected_game, self.selected_team, self.selected_player, self.event_array)\n fig, axs = plot_display.pointplot(df_plot)\n\n fig_canvas = FigureCanvasTkAgg(fig, master=self.frm_sub)\n fig_canvas.draw()\n fig_canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.Y, expand=1)\n except:\n print('Error on displaying chart')\n ","repo_name":"hunterkimmett/FlamesSubmission","sub_path":"GUI.py","file_name":"GUI.py","file_ext":"py","file_size_in_byte":8977,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"60"} +{"seq_id":"11661076224","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport pickle\nimport numpy as np\nimport pytest\nfrom graphdot.minipandas.series import Series\n\n\n@pytest.mark.parametrize('array', [\n [1, 2, 3],\n [1.0, 2, 3],\n [1, 2.0, True],\n [None, None],\n ['hello', 'world'],\n ['hello', 2, 3, -1],\n np.arange(10),\n range(10),\n])\ndef test_series_creation(array):\n s = Series(array)\n assert(isinstance(s, np.ndarray))\n assert(isinstance(s, Series))\n assert(len(s) == len(array))\n assert(isinstance(repr(s), str))\n\n\n@pytest.mark.parametrize('case', [\n (np.array(10), np.int, np.int),\n (np.empty(10, dtype=np.bool_), np.bool_, np.bool_),\n (np.linspace(0, 1, 10), np.float, np.float),\n (np.array([1, 2, 3], dtype=np.object), np.object, np.int),\n (np.array(['hello', 'world']), np.dtype('U5'), np.dtype('U5')),\n (np.array(['hello', 'world!']), np.dtype('U6'), np.dtype('U6')),\n (np.array([(1, 2), (3, 4, 5)], dtype=np.object), np.object, tuple),\n ([(1, 2), (3, 4)], np.object, tuple),\n ([(1, 2), (3, 4, 5)], np.object, tuple),\n ([1, 2, 3], np.int16, np.int16),\n ([1.0, 2, 3], np.float32, np.float32),\n (['abc', 'd', 'ef'], np.dtype('U3'), np.dtype('U3')),\n # ([1, 'd', False], np.object, None),\n])\ndef test_series_dtype(case):\n array, t_dtype, t_concrete = case\n s = Series(array)\n assert(s.concrete_type == t_concrete)\n assert(s.dtype == t_dtype)\n\n\n@pytest.mark.parametrize('array', [\n np.linspace(0, 1, 100),\n np.arange(1000),\n np.zeros(100, dtype=np.bool_),\n np.array(['hello', 'world!']),\n np.array(['hello', True, 1.0, -2]),\n])\ndef test_series_pickle(array):\n s = Series(array)\n pck = pickle.dumps(s)\n mirror = pickle.loads(pck)\n assert(len(s) == len(mirror))\n assert(s.concrete_type == mirror.concrete_type)\n for _1, _2 in zip(s, mirror):\n assert(_1 == _2)\n","repo_name":"yhtang/GraphDot","sub_path":"test/minipandas/test_series.py","file_name":"test_series.py","file_ext":"py","file_size_in_byte":1867,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"60"} +{"seq_id":"9128917282","text":"import docx\nimport pdfplumber\n\n\ndef text_from_docx(path: str) -> str:\n doc = docx.Document(path)\n paragraphs = [para.text for para in doc.paragraphs]\n text = '\\n'.join(paragraphs)\n\n return text\n\n\ndef text_from_pdf(path: str) -> str:\n text = ''\n with pdfplumber.open(path) as pdf:\n for page in pdf.pages:\n text += page.extract_text(\n layout=False,\n use_text_flow=True\n )\n return text\n\n\nif __name__ == '__main__':\n # print(text_from_docx('../documents/АЗН/2015_ворд/ARHKRS_OPIS_2893.docx'))\n print(text_from_pdf('../documents/single_test/AKT_KRS_2831_АЗН2.PDF'))\n","repo_name":"cyXXqeq/ActParser","sub_path":"utils/get_text.py","file_name":"get_text.py","file_ext":"py","file_size_in_byte":657,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"60"} +{"seq_id":"19283960570","text":"print(\"01. Importing core libraries\")\n\nimport os\nimport sys\nimport json\nimport atexit\nimport argparse\nimport traceback\nimport subprocess\n\nfrom core.config import *\n\nprint(f\"02. Importing {NAME} libraries\")\nfrom PyQt5.QtGui import QFontDatabase, QFont, QIcon\nfrom PyQt5.QtWidgets import QApplication, QMessageBox\nfrom gui.utils import styles\nfrom core.user.environment import Composition\nfrom core.exception_handler import report_unhandled_exception\n\nsys.path.append(\"./Engine\")\n# Back up the reference to the exceptionhook\nsys._excepthook = sys.excepthook\n\n# Set the exception hook to our wrapping function\nsys.excepthook = report_unhandled_exception\nprint(\"03. Installed exception hook\")\n\n\ndef launch_window():\n print(f\"Revision {VERSION} {EDITION} edition [{TEAM} | {AUTHOR}]\")\n QFontDatabase().addApplicationFont(r\"font.ttf\")\n\n \"\"\"splash = MovieSplashScreen(QMovie(\"gui/resources/splash.gif\"\n if os.path.isfile(\"gui/resources/splash.gif\")\n else \"splash.gif\"))\n splash.setWindowFlags(Qt.WindowStaysOnTopHint | Qt.FramelessWindowHint)\n splash.setEnabled(False)\n\n splash.setFont(QFont(\"나눔바른펜\", 17))\n splash.setWindowTitle(\" \".join([NAME, VERSION]))\n # splash.showMessage(f\"{AUTHOR}'s {NAME} {VERSION}\", alignment=Qt.AlignTop | Qt.AlignCenter, color=Qt.white)\n\n splash.setWindowIcon(QIcon(r\"gui\\resources\\icon.ico\"))\n\n splash.show()\n\n for i in range(31):\n t = time.time()\n while time.time() < t + 0.1:\n app.processEvents()\n\n # Simulate something that takes time\"\"\"\n\n styles.apply(app)\n app.setFont(QFont(\"나눔바른펜\", 11))\n try:\n from gui.window import MainForm\n\n root = MainForm()\n # splash.finish(root)\n root.show()\n app.exec_()\n except Exception as e:\n atexit.register(report_unhandled_exception, traceback.format_exc())\n print(e)\n\n\ndef main():\n # TODO: unstable exit with unknown error with 0xC0000409:\n # see https://stackoverflow.com/questions/12827305/pyqt-application-close-with-error\n\n app.setWindowIcon(\n QIcon(\n r\"gui\\resources\\icon.ico\"\n if os.path.isfile(r\"gui\\resources\\icon.ico\")\n else r\"icon.ico\"\n )\n )\n\n # if not os.path.isfile(os.environ['PYTHON']):\n # sys.exit(\"PYTHON NOT FOUND.\")\n print(\"04. Detecting Python [\", end=str())\n if RELEASE:\n if os.path.isfile(PREF_FILE):\n os.environ[\"PYTHON\"] = json.loads(open(PREF_FILE).read())[\"python\"]\n else:\n try:\n os.environ[\"PYTHON\"] = \"\".join(\n list(subprocess.check_output(\"where python\").decode(\"utf8\"))[0:-2]\n )\n except:\n pass\n Composition.launch()\n\n try:\n os.environ[\"PYTHON\"]\n except KeyError:\n QMessageBox.information(\n None, f\"{NAME} 실행 거부됨\", f\"{NAME} 실행에 필요한 필수 구성이 완료되지 않았습니다.\"\n )\n sys.exit(-1)\n\n os.mkdir(TMP_PATH)\n with open(PREF_FILE, \"w\") as p:\n p.write(json.dumps({\"python\": os.environ[\"PYTHON\"]}, indent=4))\n else:\n os.environ[\"PYTHON\"] = \"python\"\n print(os.environ[\"PYTHON\"] + \"]\")\n\n print(\"05. Checking dependency [\", end=str())\n\n try:\n subprocess.check_output('python -c \"import pygame\"', shell=True) == b\"\"\n print(\"Done]\")\n except subprocess.CalledProcessError:\n print(\"ERROR]\")\n print(\" 05-1. Installing pygame\")\n subprocess.Popen(\n [os.environ[\"PYTHON\"], \"-m\", \"pip\", \"install\", \"pygame\"]\n ).wait()\n except:\n try:\n print(\"FAILED]\")\n print(\" 05-1. Installing pygame\")\n subprocess.Popen(\n [os.environ[\"PYTHON\"], \"-m\", \"pip\", \"install\", \"pygame\"]\n ).wait()\n except:\n input(\"UNKNOWN ERROR]\\n\\nPress Enter to terminate.\")\n\n print(\"06. Using plugins [\", end=str())\n from core import config\n\n if os.path.isdir(PLUGIN_DIR):\n config.USE_PLUGINS = True\n\n # Disable plugins\n config.USE_PLUGINS = False\n print(f\"{config.USE_PLUGINS}]\")\n\n del config\n\n print(f\"07. Running {NAME} on {sys.platform}\")\n launch_window()\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\n \"-w\", \"--use-white-theme\", help=\"프로그램 색상을 흰색으로 변경합니다.\", action=\"store_true\"\n )\n args = parser.parse_args()\n if args.use_white_theme:\n CONF[\"THEME\"] = \"WHITE\"\n app = QApplication(sys.argv)\n app.setApplicationName(NAME)\n app.setApplicationVersion(VERSION)\n\n main()\n print(\"07. Terminating all process\")\n","repo_name":"tdh8316/Guico","sub_path":"bootstrap.py","file_name":"bootstrap.py","file_ext":"py","file_size_in_byte":4842,"program_lang":"python","lang":"en","doc_type":"code","stars":21,"dataset":"github-code","pt":"60"} +{"seq_id":"32783270953","text":"from django.db.models.signals import post_save, pre_save\nfrom django.dispatch import receiver\n\nfrom iva_backend.app.models import ShoppingListRule, MeasurableItem, ShoppingListItem, ShoppingList\nfrom iva_backend.app.polymorphic_receiver import polymorphic_receiver\nfrom iva_backend.shopping_list_manager import ShoppingListManager\n\n\n@polymorphic_receiver(post_save, sender=MeasurableItem)\ndef check_if_item_needs_to_be_added_to_shopping_list(sender, instance, **kwargs):\n try:\n rule = instance.shopping_list_rule\n except ShoppingListRule.DoesNotExist:\n pass\n else:\n if rule.item_should_be_added_to_shopping_list:\n ShoppingListManager.add_item_on_shopping_list(instance, rule.amount_to_purchase)\n\n\n@receiver(post_save, sender=ShoppingList)\ndef record_purchased_item(sender, instance, created, **kwargs):\n if created or instance.closed_at is None:\n return\n\n for shopping_item in instance.items.all():\n if shopping_item.purchased:\n item = shopping_item.item\n item.amount += shopping_item.amount\n item.save()\n","repo_name":"project-iva/iva_backend","sub_path":"iva_backend/app/signals/shopping_list.py","file_name":"shopping_list.py","file_ext":"py","file_size_in_byte":1099,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"60"} +{"seq_id":"33940070580","text":"#imports\nfrom math import *\nfrom nsepy import get_history\nfrom datetime import date, timedelta, datetime\nfrom dateutil.relativedelta import relativedelta\nimport numpy as np\n\n#Collect stock data\ndef uptrend(LowPrice, HighPrice):\n Wave1StartPoint = LowPrice\n Wave1EndPoint = HighPrice\n Wave2StartPoint = Wave1EndPoint\n Wave2EndPoint = Wave2StartPoint - ((HighPrice - LowPrice) * 0.618)\n Wave3StartPoint = Wave2EndPoint \n Wave3EndPoint = Wave3StartPoint + ((HighPrice - LowPrice) * 1.618)\n Wave4StartPoint = Wave3EndPoint\n Wave4EndPoint = Wave4StartPoint - ((Wave3EndPoint - Wave3StartPoint) * 0.382)\n Wave5StartPoint = Wave4EndPoint\n Wave5EndPoint = Wave5StartPoint + (HighPrice - LowPrice) \n WaveAStartPoint = Wave5EndPoint\n WaveAEndPoint = WaveAStartPoint - ((Wave5EndPoint - Wave5StartPoint) * 0.382)\n WaveBStartPoint = WaveAEndPoint\n WaveBEndPoint = WaveBStartPoint + (((Wave5EndPoint - Wave5StartPoint) * 0.382) * 0.618)\n WaveCStartPoint = WaveBEndPoint\n WaveCEndPoint = WaveCStartPoint - ((Wave5EndPoint - Wave5StartPoint) * 0.382)\n points=[Wave1StartPoint, Wave1EndPoint, Wave2EndPoint,\n Wave3EndPoint, Wave4EndPoint, Wave5EndPoint, WaveAEndPoint, WaveBEndPoint, WaveCEndPoint]\n return points\n\ndef downtrend(LowPrice, HighPrice):\n Wave1StartPoint = HighPrice\n Wave1EndPoint = LowPrice\n Wave2StartPoint = Wave1EndPoint\n Wave2EndPoint = Wave1EndPoint + ((Wave1StartPoint - Wave1EndPoint) * 0.618)\n Wave3StartPoint = Wave2EndPoint\n Wave3EndPoint = Wave2EndPoint - ((Wave1StartPoint - Wave1EndPoint) * 1.618)\n Wave4StartPoint = Wave3EndPoint\n Wave4EndPoint = Wave3EndPoint + (((Wave1StartPoint - Wave1EndPoint) * 1.618) * 0.382)\n Wave5StartPoint = Wave4EndPoint\n Wave5EndPoint = Wave4EndPoint - (Wave1StartPoint - Wave1EndPoint)\n WaveAStartPoint = Wave5EndPoint\n WaveAEndPoint = Wave5EndPoint + ((Wave1StartPoint - Wave1EndPoint) * 0.382)\n WaveBStartPoint = WaveAEndPoint\n WaveBEndPoint = WaveAEndPoint - (((Wave1StartPoint - Wave1EndPoint) * 0.382) * 0.618)\n WaveCStartPoint = WaveBEndPoint\n WaveCEndPoint = WaveBEndPoint + ((Wave1StartPoint - Wave1EndPoint) * 0.382)\n points=[Wave1StartPoint, Wave1EndPoint, Wave2EndPoint,\n Wave3EndPoint, Wave4EndPoint, Wave5EndPoint, WaveAEndPoint, WaveBEndPoint, WaveCEndPoint]\n return points\n\ndef elliott(stock, LowPrice, HighPrice, ClosePrice, low_date, high_date):\n low_date = datetime.strptime(low_date, '%Y-%m-%d').date()\n high_date = datetime.strptime(high_date, '%Y-%m-%d').date()\n elliottwave = dict()\n\n if ClosePrice < HighPrice:\n print('downtrend')\n elliottwave['trend'] = 'Downtrend'\n points=downtrend(LowPrice, HighPrice)\n else:\n print('uptrend')\n elliottwave['trend'] = 'Uptrend'\n points=uptrend(LowPrice, HighPrice)\n points = [round(i) for i in points]\n elliottwave['elliottPrices'] = points\n\n #degree conversion\n for k in range(0,len(points)-1):\n price_diff=abs(points[k]-points[k+1])\n degree=((sqrt(price_diff)*180)-225)%360\n #calculating number having same degree\n l=[]\n for i in range(1,3):\n #l.append(round((2*i+2*degree/360-1.25)**2))\n l.append(round((2*i+2*degree/360+1.25)**2))\n elliottwave['Wave '+str(k+1)] = []\n #Predicting future date (low/high)\n preddate=[]\n for j in l:\n preddate.append(high_date+ relativedelta(days=+j))\n preddate.append(low_date+ relativedelta(days=+j))\n for a in preddate:\n elliottwave['Wave '+str(k+1)] = elliottwave['Wave '+str(k+1)] + [str(a)]\n return elliottwave\n","repo_name":"ansari-asad/Stock-Prediction","sub_path":"calc/wave.py","file_name":"wave.py","file_ext":"py","file_size_in_byte":3676,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"60"} +{"seq_id":"25089214690","text":"import pandas as pd\nimport csv\nfrom timeit import timeit\nimport PySimpleGUI as sg\nimport re\n\nstates = ['AL', 'AK', 'AZ', 'AR', 'CA', 'CO', 'CT', 'DC', 'DE', 'FL', 'GA',\n 'HI', 'ID', 'IL', 'IN', 'IA', 'KS', 'KY', 'LA', 'ME', 'MD',\n 'MA', 'MI', 'MN', 'MS', 'MO', 'MT', 'NE', 'NV', 'NH', 'NJ',\n 'NM', 'NY', 'NC', 'ND', 'OH', 'OK', 'OR', 'PA', 'RI', 'SC',\n 'SD', 'TN', 'TX', 'UT', 'VT', 'VA', 'WA', 'WV', 'WI', 'WY']\n\nstates = {\"AL\":\"Alabama\",\"AK\":\"Alaska\",\"AZ\":\"Arizona\",\"AR\":\"Arkansas\",\"CA\":\"California\",\"CO\":\"Colorado\",\"CT\":\"Connecticut\",\"DE\":\"Delaware\",\"FL\":\"Florida\",\"GA\":\"Georgia\",\"HI\":\"Hawaii\",\"ID\":\"Idaho\",\"IL\":\"Illinois\",\"IN\":\"Indiana\",\"IA\":\"Iowa\",\"KS\":\"Kansas\",\"KY\":\"Kentucky\",\"LA\":\"Louisiana\",\"ME\":\"Maine\",\"MD\":\"Maryland\",\"MA\":\"Massachusetts\",\"MI\":\"Michigan\",\"MN\":\"Minnesota\",\"MS\":\"Mississippi\",\"MO\":\"Missouri\",\"MT\":\"Montana\",\"NE\":\"Nebraska\",\"NV\":\"Nevada\",\"NH\":\"New Hampshire\",\"NJ\":\"New Jersey\",\"NM\":\"New Mexico\",\"NY\":\"New York\",\"NC\":\"North Carolina\",\"ND\":\"North Dakota\",\"OH\":\"Ohio\",\"OK\":\"Oklahoma\",\"OR\":\"Oregon\",\"PA\":\"Pennsylvania\",\"RI\":\"Rhode Island\",\"SC\":\"South Carolina\",\"SD\":\"South Dakota\",\"TN\":\"Tennessee\",\"TX\":\"Texas\",\"UT\":\"Utah\",\"VT\":\"Vermont\",\"VA\":\"Virginia\",\"WA\":\"Washington\",\"WV\":\"West Virginia\",\"WI\":\"Wisconsin\",\"WY\":\"Wyoming\"}\n\ndef wru(selected):\n state = re.search('^[^0-9]+(\\,\\s){1}(?P[A-Z]{2}|[A-Za-z]+){1}\\s(\\d{5})', addresses).groupdict()['state']\n responses = []\n if selected == state:\n responses.append(names[addresses.index(state)])\n \n\nf = open('customers10.csv', 'rt')\ncsv_reader = csv.DictReader(f, escapechar='\\\\')\n#q = input(\"what name?\")\nq = 'bibb'\n\nnames = []\naddresses = []\nzips = []\nstreets = []\nwebsites = []\n\nfor row in csv_reader:\n #print(row['name'])\n names.append(row['name'])\n addresses.append(row['address'])\n zips.append(row['zip'])\n streets.append(row['street'])\n websites.append(row['website'])\n #print(row['name'])\n #if q.title() in row['name']:\n #print(row)\n \n #f.close\n\n\"\"\"\nthis is what needs to do:\n1) dropdown list of all states\n2) when a state is selected, then regex match occurs checking the address column where search = selected state\n3) \n\n\"\"\"\n\n\nfor e in names:\n print(e)\n\n\n\nsg.theme(\"DarkBlue\")\n\nitems = ['USA', 'Mexico', 'Japan', 'Korea', 'UK', 'China', 'France']\nasia_index = (2 ,3, 5)\n\n\n\n\n\nlayout = [\n [sg.Listbox(states, size=(10, 5), key='-LISTBOX1-', enable_events=True)],\n [sg.Listbox(names, size=(50, 20), key='-LISTBOX-', enable_events=True)]\n]\n\n# Create a binding on the listbox onclick\n#facility_list.bind(\"<>\", fillout)\n\nwindow = sg.Window('Title', layout, finalize=True)\nlistbox = window['-LISTBOX-'].Widget\nlistbox2 = window['-LISTBOX1-'].Widget\nfor index in asia_index:\n listbox.itemconfigure(index, bg='green', fg='white') # set options for item in listbox\nwhile True:\n event, values = window.read()\n if event == sg.WINDOW_CLOSED:\n break\n if event == '-LISTBOX-':\n print(values['-LISTBOX-'])\n #print(event, values)\n #sg.popup_get_text('This is {}'.format(values['-LISTBOX-'][0]))\n if event == '-LISTBOX1-':\n print(values['-LISTBOX1-'])\n \n \n\n \n\nwindow.close()\n\n#t = timeit.Timer('char in text', setup='text = \"sample string\"; char = \"g\"')\n#t = timeit.Timer('char in text', setup='text = \"sample string\"; char = \"g\"')\n#t.timeit()\n\n\n\"\"\"\nstt = 'Maryland'\n\nif stt in states:\n print(states[stt])\n\nkeys = [k for k, v in states.items() if v == 'Maryland']\nprint(keys)\n\nkeyer = states.get('MD')\nprint(keyer)\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","repo_name":"Nomadically/IB","sub_path":"preproto8.py","file_name":"preproto8.py","file_ext":"py","file_size_in_byte":3594,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"60"} +{"seq_id":"34409787454","text":"from __future__ import annotations\nfrom typing import TYPE_CHECKING, Optional, Any, Union\n\nfrom neocord.models.base import DiscordModel\nfrom neocord.models.attachment import Attachment\nfrom neocord.dataclasses.embeds import Embed\nfrom neocord.dataclasses.flags.message import MessageFlags\n\nfrom neocord.internal import helpers\n\n\nif TYPE_CHECKING:\n from neocord.api.state import State\n from neocord.models.user import User\n from neocord.models.guild import Guild\n from neocord.abc import Messageable\n from neocord.typings.message import Message as MessagePayload\n from neocord.typings.member import Member as MemberPayload\n\n from neocord.models.channels.text import TextChannel\n from neocord.models.channels.direct import DMChannel\n\n MessageableChannel = Union[TextChannel, DMChannel]\n\nclass MessageInteraction(DiscordModel):\n \"\"\"\n Represents the interaction's information attached to an interaction response's message.\n\n Attributes\n ----------\n id: :class:`int`\n The ID of interaction.\n name: :class:`str`\n The name of application command, If applicable.\n user: :class:`User`\n The user that invoked this interaction.\n application_id: :class:`int`\n The application's ID this interaction belongs to.\n \"\"\"\n __slots__ = ('id', 'name', 'user', 'type', 'application_id')\n\n if TYPE_CHECKING:\n name: str\n user: User\n application_id: int\n type: int\n\n def __init__(self, data: Any, application_id: int) -> None:\n self.id = helpers.get_snowflake(data, 'id') # type: ignore\n self.name = data.get('name')\n\n if data.get('user'):\n user = data['user']\n self.user = self.state.get_user(int(user['id'])) or self.state.add_user(user)\n\n self.type = int(data.get('type', 1))\n self.application_id = application_id\n\n\nclass _MessageReferenceMixin:\n def _get_reference_message(self) -> DiscordModel:\n raise NotImplementedError\n\n def to_message_reference_dict(self):\n message = self._get_reference_message()\n\n ret = {\n 'message_id': self.id,\n 'channel_id': self.channel_id,\n }\n\n if self.guild_id is not None:\n ret['guild_id'] = self.guild_id\n\n return ret\n\nclass MessageReference(_MessageReferenceMixin):\n \"\"\"Represents the reference \"aka\" the reply of a message.\n\n This class can be constructed by users.\n\n Parameters\n ----------\n id: :class:`int`\n The ID of message being referenced or replied.\n channel_id: :class:`int`\n The ID of channel that the message belongs to.\n guild_id: Optional[:class:`int`]\n The ID of guild that this message belongs to or None if it's a DM.\n fail_if_not_exists: :class:`bool`\n Whether to raise :exc:`HTTPError` if the message being referenced does not\n exist. Defaults to False.\n \"\"\"\n __slots__ = ('message_id', 'channel_id', 'guild_id', 'fail_if_not_exist')\n\n def __init__(self, *,\n id: int,\n channel_id: int,\n guild_id: Optional[int] = None,\n fail_if_not_exists: bool = False,\n ):\n self.id = id\n self.channel_id = channel_id\n self.guild_id = guild_id\n self.fail_if_not_exists = fail_if_not_exists\n\n def _get_reference_message(self):\n return self\n\n\nclass Message(DiscordModel, _MessageReferenceMixin):\n \"\"\"Represents a discord message entity.\n\n Attributes\n ----------\n id: :class:`int`\n The snowflake ID of this message.\n channel_id: :class:`int`\n The ID of channel in which the message was sent.\n guild_id: :class:`int`\n The ID of guild in which message was sent.\n content: :class:`str`\n The content of message, this may be None if message has no content.\n created_at: :class:`datetime.datetime`\n The datetime representation of the time when message was sent.\n tts: :class:`bool`\n Whether message is a \"text-to-speech\" message.\n mention_everyone: :class:`bool`\n Whether this message involves the @everyone or @here mention.\n pinned: :class:`bool`\n Whether the message is pinned in the parent channel.\n type: :class:`MessageType`\n The type of message.\n webhook_id: :class:`int`\n If a webhook has sent this message, then this is the ID of that webhook.\n author: Union[:class:`GuildMember`, :class:`User`]\n The user that sent this message, this could be None. If the message was sent\n in a DM, Then it is :class:`User`, otherwise, it's a :class:`GuildMember`\n interaction: :class:`MessageInteraction`\n The interaction information if this message is an interaction response.\n embeds: List[:class:`Embed`]\n The list of embeds on this message.\n application_id: :class:`int`\n If message is an interaction, The application ID of the interaction.\n role_mentions: List[:class:`Role`]\n The list of roles that are mentioned in message.\n raw_role_mentions: List[:class:`int`]\n The list of role IDs that are mentioned in message.\n mentions: [:class:`User`, :class:`GuildMember`]\n The mentions that are done in the message.\n flags: :class:`MessageFlags`\n The flags attached to this message.\n attachments: List[:class:`Attachment`]\n The list of attachments attached to this message.\n \"\"\"\n __slots__ = (\n 'id', 'channel_id', 'guild_id', 'content', 'created_at', '_edited_timestamp',\n 'tts', 'mention_everyone', 'pinned', 'type', 'webhook_id', 'author', '_state',\n 'mentions', 'role_mentions', 'raw_role_mentions', 'embeds', 'interaction', 'application_id',\n 'flags', 'attachments'\n )\n\n def __init__(self, data: MessagePayload, state: State) -> None:\n self._state = state\n self.channel_id = helpers.get_snowflake(data, 'channel_id')\n self.webhook_id = helpers.get_snowflake(data, 'webhook_id')\n self.id = int(data['id'])\n self.guild_id = helpers.get_snowflake(data, 'guild_id')\n self.created_at = helpers.iso_to_datetime(data.get('timestamp'))\n self.tts = data.get('tts', False)\n self.type = data.get('type')\n self.author = None # type: ignore\n self.application_id = helpers.get_snowflake(data, 'application_id')\n author = data.get('author')\n\n if self.webhook_id is None:\n if self.guild:\n # since the member is most likely to be partial here, we try to\n # obtain member from our cache (which is complete) and in case we fail, we will\n # resolve it to user.\n self.author = self.guild.get_member(int(author['id']))\n\n if self.author is None:\n self.author = self._state.get_user(int(author['id'])) or self._state.add_user(author)\n\n self.interaction = None\n inter = data.get('interaction')\n if inter:\n self.interaction = MessageInteraction(data['interaction'], application_id=self.application_id) # type: ignore\n\n self._update(data)\n\n def _get_reference_message(self):\n return self\n\n def _update(self, data: MessagePayload):\n # this only has the fields that are subject to change after\n # initial create.\n self.content = data.get('content')\n\n self._edited_timestamp = data.get('edited_timestamp')\n self.pinned = data.get('pinned', False)\n self.mention_everyone = data.get('mention_everyone', False)\n\n self.mentions = []\n mentions = data.get('mentions', [])\n\n for mention in mentions:\n if 'member' in mention:\n try:\n member_data: MemberPayload = {**mention['member'], 'user': mention} # type: ignore\n member = self.guild.get_member(int(mention['id'])) or self.guild._add_member(member_data)\n except:\n member = None\n else:\n self.mentions.append(member)\n else:\n user = self._state.get_user(int(mention['id'])) or self._state.add_user(mention)\n self.mentions.append(user)\n\n self.role_mentions = []\n self.raw_role_mentions = []\n\n for role in data.get('mention_roles', []):\n # guild should not be None here\n role = self.guild.get_role(int(role)) # type: ignore\n if role:\n self.role_mentions.append(role)\n\n self.raw_role_mentions.append(int(role)) # type: ignore\n\n self.attachments = [Attachment(a, state=self._state) for a in data.get('attachments', [])]\n self.embeds = [Embed.from_dict(e) for e in data.get('embeds', [])]\n self.flags = MessageFlags(data.get('flags', 0))\n\n @property\n def guild(self) -> Optional[Guild]:\n \"\"\"\n :class:`Guild`: Returns the guild in which message was sent. Could be None\n if message was sent in a DM channel.\n \"\"\"\n return self._state.get_guild(self.guild_id) # type: ignore\n\n @property\n def channel(self) -> Optional[MessageableChannel]:\n \"\"\"\n :class:`GuildChannel`: Returns the channel in which message was sent.\n \"\"\"\n if self.guild:\n return self.guild.get_channel(self.channel_id) # type: ignore\n else:\n return self._state.get_dm_channel(self.channel_id)\n\n def is_interaction_response(self):\n \"\"\"\n Returns a boolean showing whether this message is an interaction i.e application\n command or message component's response.\n \"\"\"\n return (self.application_id is not None)\n\n async def delete(self):\n \"\"\"\n Deletes the message.\n\n Raises\n ------\n Forbidden\n You are not allowed to delete this message.\n HTTPError\n The message sending failed somehow.\n \"\"\"\n # channel here would *always* be a subclass of abc.Messageable\n\n await self.channel.delete_message(self) # type: ignore\n\n async def edit(self, *args, **kwargs):\n \"\"\"\n Edits the message.\n\n Raises\n ------\n Forbidden\n You cannot edit this message.\n HTTPError\n Editing of message failed.\n \"\"\"\n await self.channel.edit_message(self, *args, **kwargs)\n\n\n async def reply(self, *args, **kwargs):\n \"\"\"\n Replies to the message. This is a shorthand for :meth:`TextChannel.send` and\n so does take same parameters.\n\n Raises\n ------\n Forbidden\n You are not allowed to send this message.\n HTTPError\n The message sending failed somehow.\n\n Returns\n -------\n :class:`Message`\n The created message.\n \"\"\"\n kwargs.pop('reference', None)\n return (await self.channel.send(*args, **kwargs, reference=self))\n\n # TODO: Add API methods when guild channels are implemented.","repo_name":"oliiiiiiiiiiiii/neocord","sub_path":"neocord/models/message.py","file_name":"message.py","file_ext":"py","file_size_in_byte":10955,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"60"} +{"seq_id":"6611687989","text":"# -*- coding: utf-8 -*-\nfrom dataclasses import dataclass\nfrom fractions import Fraction\nfrom functools import lru_cache\nfrom typing import Tuple, List\nfrom bitarray import bitarray\nimport bitarray\nfrom bitarray.util import ba2int\nimport numpy as np\n\n\n__all__ = [\n \"read_mp7_signature\",\n]\n\n\nSIGELEM_SIZE = 380\n\n\n@dataclass\nclass Frame:\n \"\"\"Represents an MP7 Frame Signature.\"\"\"\n\n vector: np.ndarray # 380 dimensional vector, range: 0..2\n elapsed: Fraction # time elapsed since start of video\n confidence: int # signature confidence, range: 0..255\n\n\n@lru_cache\ndef calc_byte_to_bit3():\n # type: () -> np.ndarray\n \"\"\"\n Build lookup table.\n\n :return: table to convert a 8bit value into five three-bit-values\n :rtype: np.ndarray\n \"\"\"\n table_3_bit = np.zeros((256, 5), dtype=np.uint8)\n for i in range(256):\n div3 = 3 * 3 * 3 * 3\n for iii in range(0, 5):\n table_3_bit[i, iii] = (i // div3) % 3\n div3 //= 3\n return table_3_bit\n\n\ndef pop_bits(data_bits, pos, bits=32):\n # type: (bitarray, int, int) -> Tuple[int, int]\n \"\"\"\n Take out 0/1 values and pack them again to an unsigned integer.\n\n :param bitarray data_bits: 0/1 data\n :param int pos: position in 0/1 data\n :param int bits: number of bits (default 32)\n :return: value, new position\n :rtype: Tuple[int, int]\n \"\"\"\n chunk = data_bits[pos : pos + bits]\n value = ba2int(chunk, signed=False)\n pos += bits\n return value, pos\n\n\ndef read_mp7_signature(byte_data):\n # type: (bytes) -> List[Frame]\n \"\"\"\n Decode binary MP7 video signature.\n\n :param bytes byte_data: Raw MP7 video signature (as extracted by ffmpeg)\n :return: List of Frame Signatures\n :rtype: List[Frame]\n \"\"\"\n table_3_bit = calc_byte_to_bit3()\n data_bits = bitarray.bitarray()\n data_bits.frombytes(byte_data)\n pos = 0\n pos += 129\n num_of_frames, pos = pop_bits(data_bits, pos)\n media_time_unit, pos = pop_bits(data_bits, pos, 16)\n pos += 1 + 32 + 32\n num_of_segments, pos = pop_bits(data_bits, pos)\n pos += num_of_segments * (4 * 32 + 1 + 5 * 243)\n pos += 1\n frame_sigs_v = []\n frame_sigs_c = []\n frame_sigs_e = []\n frame_sigs_tu = []\n for i in range(num_of_frames):\n pos += 1\n raw_media_time, pos = pop_bits(data_bits, pos)\n frame_confidence, pos = pop_bits(data_bits, pos, 8)\n pos += 5 * 8\n vec = np.zeros((SIGELEM_SIZE,), dtype=np.uint8)\n p = 0\n for ii in range(SIGELEM_SIZE // 5):\n dat, pos = pop_bits(data_bits, pos, 8)\n vec[p : p + 5] = table_3_bit[dat]\n p += 5\n frame_sigs_v.append(vec)\n frame_sigs_e.append(raw_media_time)\n frame_sigs_c.append(frame_confidence)\n frame_sigs_tu.append(media_time_unit)\n\n fsigs = []\n r = (frame_sigs_v, frame_sigs_e, frame_sigs_c, frame_sigs_tu)\n for v, e, c, tu in zip(*r):\n fsigs.append(Frame(vector=v, elapsed=Fraction(e, tu), confidence=c))\n return fsigs\n","repo_name":"iscc/iscc-sdk","sub_path":"iscc_sdk/mp7.py","file_name":"mp7.py","file_ext":"py","file_size_in_byte":3021,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"60"} +{"seq_id":"17114935648","text":"\"\"\"\nThis module provides:\n\n1. The `BrowserAutomator` class, simplifying web automation via the Chrome Developer Protocol (CDP).\n\n2. Integration with the BAS_SAFE internal API for secure management of functions and properties within\n the BAS_SAFE environment, ensuring reliable execution of critical operations such as simulating mouse movements.\n\"\"\"\n\nimport json\nfrom typing import Any, Dict, List, Tuple, Union\n\nimport filelock\nimport httpx\nfrom playwright.async_api import Browser, BrowserContext, CDPSession, Locator, Page\nfrom playwright.async_api import Playwright as AsyncPlaywright\nfrom playwright.async_api import async_playwright\n\nfrom pybas_automation.browser_automator.cdp_client import CDPClient\nfrom pybas_automation.browser_automator.models import WebsocketUrl, WsUrlModel\nfrom pybas_automation.browser_profile import BrowserProfile\nfrom pybas_automation.utils import get_logger\n\nlogger = get_logger()\n\n\nclass BrowserWsConnectError(Exception):\n \"\"\"Exception raised when unable to connect to the browser's remote debugging port.\"\"\"\n\n\ndef _url_to_ws_endpoint(endpoint_url: str) -> str:\n \"\"\"\n Convert an HTTP endpoint URL to a WebSocket endpoint URL.\n\n :param endpoint_url: HTTP endpoint URL.\n :return: WebSocket endpoint URL.\n\n :raises BrowserWsConnectError: If unable to connect to the HTTP endpoint URL.\n \"\"\"\n if endpoint_url.startswith(\"ws\"):\n return endpoint_url\n\n logger.debug(\"Preparing WebSocket: retrieving WebSocket URL from %s\", endpoint_url)\n\n http_url = endpoint_url if endpoint_url.endswith(\"/\") else f\"{endpoint_url}/\"\n http_url += \"json/version/\"\n try:\n response = httpx.get(http_url)\n except httpx.ConnectError as exc:\n raise BrowserWsConnectError(\n f\"Cannot connect to {http_url}. This may not be a DevTools server. Consider connecting via ws://.\"\n ) from exc\n\n if response.status_code != 200:\n raise ValueError(\n f\"Unexpected status {response.status_code} when connecting to {http_url}. \"\n \"This might not be a DevTools server. Consider connecting via ws://.\"\n )\n\n json_data = json.loads(response.text)\n logger.debug(\"WebSocket preparation response: %s\", json_data)\n\n return str(json_data[\"webSocketDebuggerUrl\"])\n\n\nasync def _elem_coordinates(elem: Locator) -> Tuple[int, int]:\n \"\"\"\n Get the coordinates of the given element.\n :param elem: The element to get the coordinates for.\n\n :raises ValueError: If unable to fetch bounding box for the given element.\n\n :return: The coordinates of the given element.\n \"\"\"\n\n bounding_box = await elem.bounding_box()\n if not bounding_box:\n raise ValueError(f\"Unable to fetch bounding box for element: {elem}\")\n\n # Calculate the coordinates for the click (center of the element)\n x = int(bounding_box[\"x\"] + bounding_box[\"width\"] / 2)\n y = int(bounding_box[\"y\"] + bounding_box[\"height\"] / 2)\n return x, y\n\n\nclass BrowserAutomator:\n \"\"\"\n A Python class for simplifying web automation by connecting to and interacting with web browsers\n through the Chrome Developer Protocol (CDP).\n\n This class provides a user-friendly and streamlined interface built on top of the core CDP commands,\n making it easier to automate browser actions and extract information from web pages.\n\n Additionally, it seamlessly integrates with the BAS_SAFE internal API, enhancing security and reliability\n within the BAS_SAFE environment. This integration extends to various actions, such as retrieving page source,\n simulating mouse movements, and more (Note: Not all functions are currently supported).\n \"\"\"\n\n ws_endpoint: WsUrlModel\n remote_debugging_port: int\n\n browser_profile: BrowserProfile\n browser_version: Union[str, None]\n pw: AsyncPlaywright\n browser: Browser\n context: BrowserContext\n page: Page\n cdp_client: CDPClient\n cdp_session: CDPSession\n\n unique_process_id: Union[str, None]\n _javascript_code: str\n\n _lock: filelock.FileLock\n\n def __init__(\n self, browser_profile: BrowserProfile, remote_debugging_port: int, unique_process_id: Union[str, None] = None\n ):\n \"\"\"\n Initialize the BrowserAutomator instance.\n\n :param browser_profile: The browser profile to use.\n :param remote_debugging_port: The remote debugging port to connect to.\n :param unique_process_id: A unique identifier for the `Worker.exe` process. Retrieved from the command line.\n \"\"\"\n\n self.browser_profile = browser_profile\n self.remote_debugging_port = int(remote_debugging_port)\n if unique_process_id:\n self.unique_process_id = unique_process_id\n self._javascript_code = f\"location.reload['_bas_hide_{unique_process_id}']\"\n else:\n self.unique_process_id = None\n\n def get_ws_endpoint(self) -> str:\n \"\"\"\n Return the WebSocket endpoint URL.\n\n :return: WebSocket endpoint URL.\n \"\"\"\n return self.ws_endpoint.ws_url.unicode_string()\n\n def connect(self) -> None:\n \"\"\"\n Connect to the browser via the WebSocket protocol.\n \"\"\"\n ws_endpoint_url = _url_to_ws_endpoint(f\"http://localhost:{self.remote_debugging_port}\")\n self.ws_endpoint = WsUrlModel(ws_url=WebsocketUrl(ws_endpoint_url))\n self.cdp_client = CDPClient(self.ws_endpoint)\n\n async def __aexit__(self, *args: Any) -> None:\n \"\"\"Asynchronous exit method to stop the Playwright instance.\"\"\"\n if self.pw:\n await self.pw.stop()\n\n async def _get_browser_version(self) -> None:\n \"\"\"\n Fetch and set the browser version from the WebSocket endpoint.\n\n :raises ValueError: If unable to retrieve the browser version from the WebSocket endpoint.\n \"\"\"\n\n data = await self.cdp_client.send_command(\"Browser.getVersion\")\n\n product_version = data.get(\"product\", None)\n if not product_version:\n raise ValueError(\"Unable to fetch browser version\")\n\n self.browser_version = product_version\n\n async def _fetch_attached_sessions(self) -> List[Dict]:\n \"\"\"\n Retrieve a list of attached session information from the WebSocket endpoint.\n\n :return: List of attached session information.\n :raises ValueError: If unable to retrieve the attached sessions from the WebSocket endpoint.\n \"\"\"\n\n data = await self.cdp_client.send_command(\"Target.getTargets\")\n\n if not data.get(\"targetInfos\", None):\n raise ValueError(\"Unable to fetch attached sessions\")\n\n return [target_info for target_info in data[\"targetInfos\"] if target_info[\"attached\"]]\n\n async def _prepare_cdp(self) -> None:\n # Enables network tracking, network events will now be delivered to the client.\n await self.cdp_session.send(\"Network.setCacheDisabled\", params={\"cacheDisabled\": False})\n # https://chromedevtools.github.io/devtools-protocol/tot/DOMStorage/#method-enable\n await self.cdp_session.send(\"DOMStorage.enable\")\n\n async def __aenter__(self) -> \"BrowserAutomator\":\n \"\"\"\n Asynchronous enter method to initialize the connection and retrieve session details.\n\n :return: BrowserAutomator instance.\n :raises BrowserWsConnectError: If unable to connect to the browser's remote debugging port.\n \"\"\"\n\n self.connect()\n\n await self._get_browser_version()\n logger.info(\"Retrieved browser version: %s\", self.browser_version)\n\n self.pw = await async_playwright().start()\n self.browser = await self.pw.chromium.connect_over_cdp(self.ws_endpoint.ws_url.unicode_string())\n self.context = self.browser.contexts[0]\n self.page = self.context.pages[0]\n\n # Fetch the attached sessions\n sessions = await self._fetch_attached_sessions()\n logger.debug(\"Attached sessions retrieved: %s\", sessions)\n\n self.cdp_session: CDPSession = await self.context.new_cdp_session(self.page)\n await self._prepare_cdp()\n\n if self.unique_process_id:\n _bas_hide_debug_result = await self._bas_hide_debug(page=self.page)\n logger.debug(\"BAS_HIDE_DEBUG result: %s\", _bas_hide_debug_result)\n\n logger.debug(\"Successfully connected to browser: %s\", self.browser)\n\n return self\n\n async def _bas_hide_call(self, page: Page, javascript_func_code: str) -> Any:\n \"\"\"\n Call a JavaScript function in the BAS _SAFE internal API.\n\n :param page: The current page.\n :param javascript_func_code: The JavaScript function code to execute.\n\n :raises ValueError: If the self.unique_process_id is not set.\n\n :return: The result of the JavaScript function call.\n \"\"\"\n\n if not self.unique_process_id:\n raise ValueError(\"You should set self.unique_process_id to use BAS_SAFE API\")\n\n return await page.evaluate(javascript_func_code)\n\n async def _bas_hide_debug(self, page: Union[Page, None] = None) -> Any:\n javascript_func_code = f\"Object.keys({self._javascript_code})\"\n if page is None:\n page = self.page\n\n return await self._bas_hide_call(page=page, javascript_func_code=javascript_func_code)\n\n async def bas_get_page_content(self, page: Union[Page, None] = None) -> Any:\n \"\"\"\n Get the current page content.\n\n :param page: The current page.\n\n :raises ValueError: If the self.unique_process_id is not set.\n\n :return: The current page content.\n \"\"\"\n\n if page is None:\n page = self.page\n\n javascript_func_code = f\"{self._javascript_code}['BrowserAutomationStudio_GetPageContent']()\"\n return await self._bas_hide_call(page=page, javascript_func_code=javascript_func_code)\n\n async def bas_scroll_mouse_to_coordinates(self, x: int, y: int, page: Union[Page, None] = None) -> Any:\n \"\"\"\n Click on the given coordinates.\n\n :param x: The x coordinate.\n :param y: The y coordinate.\n :param page: The current page.\n\n :raises ValueError: If the self.unique_process_id is not set.\n \"\"\"\n\n if page is None:\n page = self.page\n\n javascript_func_code = f\"{self._javascript_code}['BrowserAutomationStudio_ScrollToCoordinates']({x},{y},true)\"\n return await self._bas_hide_call(page=page, javascript_func_code=javascript_func_code)\n\n async def bas_move_mouse_to_elem(self, elem: Locator, page: Union[Page, None] = None) -> Any:\n \"\"\"\n Move the mouse to the given element.\n\n :param elem: The element to move the mouse to.\n :param page: The current page.\n\n :raises ValueError: If the self.unique_process_id is not set.\n\n :return: The result of the JavaScript function call.\n \"\"\"\n\n if page is None:\n page = self.page\n\n x, y = await _elem_coordinates(elem=elem)\n\n result = await self.bas_scroll_mouse_to_coordinates(x=x, y=y, page=page)\n logger.debug(\"Scrolled to coordinates: %s\", result)\n return result\n","repo_name":"sergerdn/py-bas-automation","sub_path":"pybas_automation/browser_automator/browser_automator.py","file_name":"browser_automator.py","file_ext":"py","file_size_in_byte":11093,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"60"} +{"seq_id":"14172686117","text":"import torch\n\nfrom playground import PositionwiseFeedForward, MultiHeadedAttention, EncoderLayer, Encoder\n\n\nclass SelfAttentiveEncoder(torch.nn.Module):\n def __init__(self, config, transducer):\n super().__init__()\n self.transducer = Encoder(\n EncoderLayer(int(config[\"d_model\"]),\n MultiHeadedAttention(int(config[\"heads\"]), int(config[\"d_model\"])),\n PositionwiseFeedForward(int(config[\"d_model\"]),\n int(config[\"d_model\"])+10),\n dropout=0.1),\n N=int(config[\"N\"]))\n self.outputdim = int(config['d_model']) * int(config['ATTENTION_hops'])\n self.nhops = int(config['ATTENTION_hops'])\n self.drop = torch.nn.Dropout(float(config['ATTENTION_dropout']))\n\n # The bias on these layers should be turned off according to paper!\n self.ws1 = torch.nn.Linear(int(config['d_model']),\n\n int(config['ATTENTION_nhidden']),\n bias=False)\n\n self.ws2 = torch.nn.Linear(int(config['ATTENTION_nhidden']),\n self.nhops,\n bias=False)\n self.tanh = torch.nn.Tanh()\n self.softmax = torch.nn.Softmax(dim=1)\n\n\n def get_output_dim(self):\n return self.outputdim\n\n def forward(self, inp, emb, pad_index):\n # outp has shape [len,bsz, nhid*2]\n outp = self.transducer(emb,(inp != pad_index).unsqueeze(-2)).contiguous()\n batch_size, inp_len, h_size2 = outp.size() # [bsz, len, nhid*2]\n # flatten dimension 1 and 2\n compressed_embeddings = outp.view(-1, h_size2) # [bsz*len, nhid*2]\n\n # Calculate attention\n hbar = self.tanh(self.ws1(self.drop(compressed_embeddings))) # [bsz*len, nattention]\n alphas = self.ws2(hbar).view(batch_size, inp_len, -1) # [bsz, len, hop]\n\n # Transpose input and reshape it\n transposed_inp = inp.view(batch_size, 1, inp_len) # [bsz, 1, len]\n concatenated_inp = [transposed_inp for _ in range(self.nhops)]\n concatenated_inp = torch.cat(concatenated_inp, 1) # [bsz, hop, len]\n\n # Hack\n # Set attention on padded sequence to zero\n alphas = torch.transpose(alphas, 1, 2).contiguous()\n padded_attention = -1e4 * (concatenated_inp == pad_index).float()\n alphas += padded_attention\n\n talhpas = alphas.view(-1, inp_len) # [bsz*hop,inp_len]\n # Softmax over 1st dimension (with len inp_len)\n alphas = self.softmax(talhpas)\n alphas = alphas.view(batch_size, self.nhops, inp_len) # [bsz, hop, len]\n return torch.bmm(alphas, outp), alphas\n","repo_name":"MFajcik/Transformer_playground","sub_path":"fully_attentive_classifier/encoders.py","file_name":"encoders.py","file_ext":"py","file_size_in_byte":2738,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"60"} +{"seq_id":"43076233089","text":"import os\nfrom datetime import datetime, timedelta, timezone\nimport tempfile\n\nfrom django.db import transaction\n\nimport boto3\nimport pytz\nfrom google.transit import gtfs_realtime_pb2\n\nfrom busshaming.models import Trip, TripDate, TripStop, RealtimeEntry, Route, Stop\nfrom busshaming.enums import ScheduleRelationship\n\nS3_BUCKET_NAME = os.environ.get('S3_BUCKET_NAME', 'busshaming-realtime-dumps')\n\n\nDEBUG = False\nglobal_stats = {}\n\n\nSCHEDULE_RELATIONSHIP = dict(gtfs_realtime_pb2.TripDescriptor.ScheduleRelationship.items())\n\nROUTE_ID_SET = set()\n\nupsert_log = {}\n\ndef to_schedule_relationship(proto):\n if proto == SCHEDULE_RELATIONSHIP['SCHEDULED']:\n return ScheduleRelationship.SCHEDULED.value\n elif proto == SCHEDULE_RELATIONSHIP['ADDED']:\n return ScheduleRelationship.ADDED.value\n elif proto == SCHEDULE_RELATIONSHIP['UNSCHEDULED']:\n return ScheduleRelationship.UNSCHEDULED.value\n elif proto == SCHEDULE_RELATIONSHIP['CANCELED']:\n return ScheduleRelationship.CANCELLED.value\n return ScheduleRelationship.SCHEDULED.value\n\n\ndef add_missing_tripdate(feed, realtime_trip, vehicle_id):\n gtfs_trip_id = realtime_trip.trip_id\n start_date = realtime_trip.start_date\n if DEBUG:\n print(f'Adding missing trip date for gtfs id {gtfs_trip_id} on date {start_date}')\n date = datetime.strptime(start_date, '%Y%m%d').date()\n\n if not realtime_trip.route_id:\n return None\n\n with transaction.atomic():\n try:\n trip = Trip.objects.filter(gtfs_trip_id=gtfs_trip_id, route__gtfs_route_id=realtime_trip.route_id).order_by('-version').first()\n except Trip.DoesNotExist as e:\n trip = None\n if trip is None:\n trip = add_missing_trip(feed, realtime_trip)\n if trip is None:\n return None\n if DEBUG:\n print(f'Found trip: {trip}')\n try:\n return TripDate.objects.get(trip=trip, date=date)\n except TripDate.DoesNotExist as e:\n pass\n schedule_relationship = to_schedule_relationship(realtime_trip.schedule_relationship) \n tripdate = TripDate(trip=trip, date=date, added_from_realtime=True, vehicle_id=vehicle_id, schedule_relationship=schedule_relationship)\n tripdate.save()\n if trip.scheduled:\n global_stats['missing_tripdates'] += 1\n else:\n global_stats['unscheduled_tripdates'] += 1\n if not trip.added_from_realtime:\n global_stats['missing_tripdates_but_trip_existed'] += 1\n print(f'Trip {trip} was in the timetable, just not for tripdate {tripdate}')\n return tripdate\n\n\ndef add_missing_trip(feed, realtime_trip):\n gtfs_trip_id = realtime_trip.trip_id\n if realtime_trip.route_id not in ROUTE_ID_SET:\n return None\n if realtime_trip.schedule_relationship == SCHEDULE_RELATIONSHIP['ADDED'] and '_' in gtfs_trip_id:\n original_trip_id = gtfs_trip_id.split('_')[0]\n trip = Trip.objects.filter(gtfs_trip_id=original_trip_id).order_by('-version').first()\n if trip is not None:\n global_stats['unscheduled_trips'] += 1\n new_trip = trip.clone_to_unscheduled(gtfs_trip_id)\n return new_trip\n try:\n route = Route.objects.get(feed=feed, gtfs_route_id=realtime_trip.route_id)\n except Route.DoesNotExist as e2:\n global_stats['missing_routes'] += 1\n print(f'Route did not exist: {realtime_trip.route_id}')\n return None\n print(f'Trip with gtfs id {gtfs_trip_id} (from route {route}) does not exist!!')\n newtrip = Trip(\n gtfs_trip_id=gtfs_trip_id,\n active=True,\n direction=0,\n route=route,\n added_from_realtime=True,\n wheelchair_accessible=False,\n bikes_allowed=False,\n scheduled=(realtime_trip.schedule_relationship == SCHEDULE_RELATIONSHIP['SCHEDULED'])\n )\n newtrip.save()\n global_stats['missing_trips'] += 1\n if DEBUG:\n print(f'Added new trip: {newtrip}')\n return newtrip\n\n\ndef format_stop_time(time, plus_24h):\n hour = time.hour\n if plus_24h:\n hour += 24\n return f'{hour:02d}:{time.minute:02d}:{time.second:02d}'\n\n\ndef get_stop(feed, stop_id, stops):\n with transaction.atomic():\n try:\n stop = Stop.objects.get(feed=feed, gtfs_stop_id=stop_id)\n except Stop.DoesNotExist:\n stop = Stop(feed=feed, gtfs_stop_id=stop_id, name='Unknown', position=None)\n stop.save()\n stops[stop.gtfs_stop_id] = stop\n global_stats['missing_stops'] += 1\n return stop\n\n\ndef process_trip_update(feed, trip_dates, stops, feed_tz, trip_update, threshold, start_date_str, start_date_str_after_midnight):\n global_stats['trip_updates_found'] += 1\n trip = trip_update.trip\n plus_24h = False\n if trip.start_time < '04:00:00':\n if trip.start_date == start_date_str_after_midnight:\n trip.start_date = start_date_str\n plus_24h = True\n else:\n return\n if trip.start_date != start_date_str:\n return\n # Some trips are missing ids altogether.\n # Construct an id from 'unscheduled' and the vehicle id\n if not trip.trip_id:\n if not trip_update.vehicle.id:\n return\n global_stats['missing_trip_id'] += 1\n trip.trip_id = 'unscheduled_' + trip_update.vehicle.id\n key = (trip.trip_id, start_date_str)\n if key not in trip_dates:\n trip_date = add_missing_tripdate(feed, trip, trip_update.vehicle.id)\n if trip_date is not None:\n if DEBUG:\n print(\"COULDN'T FIND IN SCHEDULE: {}\".format(key))\n print(trip)\n trip_dates[key] = trip_date\n else:\n trip_date = trip_dates[key]\n if trip_date is None:\n return\n if trip.schedule_relationship != SCHEDULE_RELATIONSHIP['SCHEDULED']:\n trip_date.schedule_relationship = to_schedule_relationship(trip.schedule_relationship)\n trip_date.vehicle_id = trip_update.vehicle.id\n trip_date.save()\n if DEBUG:\n print(f'Upserting realtime entries for tripdate {trip_date.id}')\n for stop_update in trip_update.stop_time_update:\n global_stats['stop_updates_found'] += 1\n if stop_update.arrival.time < threshold:\n if stop_update.stop_id in stops:\n stop = stops[stop_update.stop_id]\n else:\n stop = get_stop(feed, stop_update.stop_id, stops)\n arrival_time = datetime.fromtimestamp(stop_update.arrival.time, feed_tz)\n departure_time = datetime.fromtimestamp(stop_update.departure.time, feed_tz)\n schedule_relationship = to_schedule_relationship(stop_update.schedule_relationship)\n # Upsert RealtimeEntry\n # RealtimeEntry.objects.upsert(trip_date.id, stop.id, stop_update.stop_sequence, arrival_time, stop_update.arrival.delay, departure_time, stop_update.departure.delay)\n upsert_log[(trip_date.id, stop.id, stop_update.stop_sequence)] = (arrival_time, stop_update.arrival.delay, departure_time, stop_update.departure.delay, schedule_relationship)\n global_stats['stop_updates_stored'] += 1\n\n\ndef process_dump_contents(feed, contents, trip_dates, stops, fetchtime, feed_tz, start_date_str, start_date_str_after_midnight):\n global global_stats\n global_stats = {\n 'trip_updates_found': 0,\n 'stop_updates_found': 0,\n 'stop_updates_stored': 0,\n 'missing_trips': 0,\n 'unscheduled_trips': 0,\n 'unscheduled_tripdates': 0,\n 'missing_stops': 0,\n 'missing_trip_id': 0,\n 'missing_tripdates': 0,\n 'missing_tripdates_but_trip_existed': 0,\n 'missing_routes': 0,\n }\n feed_message = gtfs_realtime_pb2.FeedMessage()\n feed_message.ParseFromString(contents)\n threshold = int((fetchtime + timedelta(minutes=5)).timestamp())\n for entity in feed_message.entity:\n if entity.HasField('trip_update'):\n process_trip_update(feed, trip_dates, stops, feed_tz, entity.trip_update, threshold, start_date_str, start_date_str_after_midnight)\n for stat in global_stats:\n print(f'{stat}: {global_stats[stat]}')\n\n\ndef fetch_next_dumps(realtime_progress, num_dumps, temp_dir):\n print(f'Processing next {num_dumps} realtime dumps in {realtime_progress}')\n client = boto3.client('s3')\n file_prefix = f'{realtime_progress.feed.slug}/'\n\n last_processed_file = realtime_progress.last_processed_dump\n if last_processed_file is None:\n last_processed_file = file_prefix + realtime_progress.start_time().strftime('%Y-%m-%dT%H:%M:%S.%f')\n\n if last_processed_file is not None:\n response = client.list_objects_v2(Bucket=S3_BUCKET_NAME, Prefix=file_prefix, StartAfter=last_processed_file, MaxKeys=num_dumps)\n else:\n response = client.list_objects_v2(Bucket=S3_BUCKET_NAME, Prefix=file_prefix, MaxKeys=num_dumps)\n\n results = []\n\n if response['KeyCount'] != 0:\n for content in response['Contents']:\n key = content['Key']\n s3 = boto3.resource('s3')\n tmp_path = os.path.join(temp_dir, key.split('/')[1])\n if DEBUG:\n print(f'Fetching {key}...')\n s3.Object(S3_BUCKET_NAME, key).download_file(tmp_path)\n results.append((key, tmp_path))\n else:\n print(f'No new realtime dump data for {realtime_progress.feed}')\n return results\n\n\ndef refresh_route_list():\n global ROUTE_LIST\n ROUTE_ID_SET = set(Route.objects.values_list('gtfs_route_id', flat=True))\n\ndef clear_upsert_log():\n global upsert_log\n upsert_log = {}\n\ndef write_upsert_log():\n global upsert_log\n print(f'Upsert log contains {len(upsert_log)} entries.')\n list_batch = []\n for realtime_key, value in upsert_log.items():\n #RealtimeEntry.objects.upsert(trip_date.id, stop.id, stop_update.stop_sequence, arrival_time, stop_update.arrival.delay, departure_time, stop_update.departure.delay)\n # RealtimeEntry.objects.upsert(*realtime_key, *value)\n list_batch.append((*realtime_key, *value))\n start = 0\n while start < len(list_batch):\n batch = list_batch[start : start + 500]\n start += 500\n if len(batch) != 0:\n RealtimeEntry.objects.upsert_bulk(batch)\n\n\ndef process_next(realtime_progress, num_dumps):\n feed = realtime_progress.feed\n succeed = realtime_progress.take_processing_lock()\n clear_upsert_log()\n if not succeed:\n # It'll try again with another progress\n return\n try:\n with tempfile.TemporaryDirectory() as temp_dir:\n cached_dumps = fetch_next_dumps(realtime_progress, num_dumps, temp_dir)\n feed_tz = pytz.timezone(feed.timezone)\n start_date_str = realtime_progress.start_date.strftime('%Y%m%d')\n start_date_str_after_midnight = (realtime_progress.start_date + timedelta(days=1)).strftime('%Y%m%d')\n\n if len(cached_dumps) != 0:\n # Prefetch stops\n stops = {}\n for stop in Stop.objects.filter(feed=feed):\n stops[stop.gtfs_stop_id] = stop\n\n # Prefetch Routes\n refresh_route_list()\n\n # Prefetch Trip Dates\n first_key = cached_dumps[0][0]\n trip_dates = {}\n datestr = os.path.split(first_key)[1].rstrip('.pb')\n fetchtime = datetime.strptime(datestr, '%Y-%m-%dT%H:%M:%S.%f').replace(tzinfo=timezone.utc)\n # Assume no bus runs longer than 48h\n fetchtime = fetchtime.astimezone(feed_tz)\n for trip_date in TripDate.objects.filter(date=realtime_progress.start_date).prefetch_related('trip'):\n datestr = trip_date.date.strftime('%Y%m%d')\n trip_dates[(trip_date.trip.gtfs_trip_id, datestr)] = trip_date\n\n for key, tmp_file in cached_dumps:\n datestr = os.path.split(key)[1].rstrip('.pb')\n fetchtime = datetime.strptime(datestr, '%Y-%m-%dT%H:%M:%S.%f').replace(tzinfo=timezone.utc)\n # Assume no bus runs longer than 48h\n fetchtime = fetchtime.astimezone(feed_tz)\n with open(tmp_file, 'rb') as f:\n contents = f.read()\n print(f'Processing {key}')\n process_dump_contents(feed, contents, trip_dates, stops, fetchtime, feed_tz, start_date_str, start_date_str_after_midnight)\n if fetchtime > realtime_progress.end_time():\n break\n # Update where we're up to.\n write_upsert_log()\n if fetchtime > realtime_progress.end_time():\n realtime_progress.update_progress(key, True)\n else:\n realtime_progress.update_progress(key, False)\n finally:\n realtime_progress.release_processing_lock()\n","repo_name":"katharosada/bus-shaming","sub_path":"busshaming/data_processing/process_realtime_dumps.py","file_name":"process_realtime_dumps.py","file_ext":"py","file_size_in_byte":12852,"program_lang":"python","lang":"en","doc_type":"code","stars":39,"dataset":"github-code","pt":"60"} +{"seq_id":"20079705697","text":"from utils import *\n\ninp = inp_readlines()\n\ngr = defaultdict(list)\n\nfor line in inp:\n a, b = line.split(\"-\")\n gr[a].append(b)\n gr[b].append(a)\n\n\ndef paths(pt, part, visited=None):\n if pt == \"end\":\n return 1\n if visited is None:\n visited = [pt]\n c = 0\n for b in gr[pt]:\n if b not in visited or b.isupper() or (part == 2 and b not in [\"start\", \"end\"] and is_uniq(filter(lambda x: x.islower(), visited))):\n c += paths(b, part, visited+[b])\n return c\n\n\nprint(\"Part 1:\", paths(\"start\", 1))\nprint(\"Part 2:\", paths(\"start\", 2))\n","repo_name":"joefarebrother/adventofcode","sub_path":"2021/12/sol.py","file_name":"sol.py","file_ext":"py","file_size_in_byte":577,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"60"} +{"seq_id":"9345946553","text":"import tensorflow as tf\nfrom tensorflow import keras\nimport numpy as np\nfrom purestochastic.model.layers import *\nfrom purestochastic.model.base_uncertainty_models import *\nfrom keras import backend as K\nfrom purestochastic.common.regularizers import Orthonormality\nfrom keras.layers import Dense\n\nclass OrthonormalCertificatesModel(StochasticModel):\n \"\"\" Implementation of the Orthonormal Certificates model.\n\n The model was proposed in [4]_ . To estimate epistemic uncertainty, they propose Orthonormal Certificates (OCs), \n a collection of diverse non-constant functions that map all training samples to zero.\n\n The model can be constructed manually (not recommended) or it's possible to use the method ``toOrthonormalCertificates``\n to convert a simple :class:`keras.Model` object into a :class:`OrthonormalCertificatesModel` object. \n \n Methods\n -------\n fit(X, y, epochs_oc=0, learning_rate_oc=0.001):\n Fit the initial and OC model.\n fit_oc(X, y, learning_rate_oc=0.001):\n Fit the OC model.\n compute_metrics(x, y, predictions, sample_weight):\n Specify the mean and stochastic part of the predictions to compute the metrics.\n predict(data, S=5, verbose=0):\n Computes the predictions of the initial model and an epistemic score.\n find_loss():\n Returns the loss specified in ``compile``.\n\n\n References\n ------------\n .. [4] Tagasovska, Natasa and Lopez-Paz, David. « Single-model uncertainties for deep learning ». \n In : Advances in Neural Information Processing Systems 2019.Nips (2019), p. 1-12. issn : 10495258. \n arXiv : 1811.00908.\n \"\"\"\n\n def compute_metrics(self, x, y, predictions, sample_weight):\n \"\"\" Custom ``compute_metrics`` method.\n \n As stated in the parent method ``compute_metrics``, this method called the \n parent function with the appropriate ``y_pred`` and ``stochastic_predictions`` \n arguments. \n\n Warning\n -------\n For ``OrthonormalCertificatesModel``, the choice is to remove stochastic\n metrics because the certificates don't have a real sense. \n\n Arguments\n ---------\n x : tf.Tensor\n Input data.\n y : tf.Tensor\n Target data.\n predictions : tf.Tensor\n Predictions returned by the model (output of `model(x)`)\n sample_weight : optional\n Sample weights for weighting the loss function.\n\n Returns\n -------\n See parent method.\n \"\"\"\n\n return super(StochasticModel, self).compute_metrics(x, y, predictions[0], sample_weight)\n\n def fit(self, X, y, epochs_oc=0, learning_rate_oc=0.001, **kwargs):\n \"\"\"Train the model the initial model and the orthonormal certificates.\n\n The model is trained in two parts : \n\n * During ``epochs`` epochs, the model is trained normally. It's defined as \n the training of the initial model and the training uses the optimizer and \n learning rate specified in the ``compile`` function. The certificates are\n frozen.\n\n * During ``epochs_oc`` epochs, all the layer are frozen except the certificates.\n The training is parametrized by ``learning_rate_oc`` and the sum of the loss \n function specified in the ``compile`` function and the Orthonormality loss.\n\n Note\n -----\n By default, the parameter ``epochs_oc`` is set to 0, and the orthonormal certificates\n are not trained.\n\n See Also\n ---------\n purestochastic.common.regularizer.Orthonormality\n\n Parameters\n ----------\n X: np.ndarray\n The input data.\n y: np.ndarray\n The target data.\n epoch_oc : int (default : 0)\n Number of epochs for the training of certificates.\n learning_rate_oc : float (default : 0.001)\n Learning rate for the training of certificates.\n \n Returns\n -------\n History of the two trainings.\n \"\"\"\n\n # Freeze OC layer\n self.layers[-1].trainable = False\n\n # Train the basic model\n self.compile(loss=[self.find_loss(), None], optimizer=self.optimizer, metrics=self.compiled_metrics._metrics, stochastic_metrics=self.stochastic_metrics)\n training_history = super(OrthonormalCertificatesModel, self).fit(X, y, **kwargs)\n\n # Train the OrthogonalCertificates model\n kwargs[\"epochs\"] = epochs_oc\n training_history_oc = self.fit_oc(X, y, learning_rate_oc=learning_rate_oc, **kwargs)\n\n return training_history, training_history_oc\n\n def fit_oc(self, X, y, learning_rate_oc=0.001, **kwargs):\n \"\"\" Train the orthonormal certificates.\n\n All the layer are frozen except the orthonormal certificates. The model is trained \n with the optimizer specified in the ``compile`` function with the learning rate\n ``learning_rate_oc``. The loss is the sum of the two following parts : \n\n * The loss function with predicted value set to the output of the orthonormal\n certificates and target value set to 0.\n\n * The orthonormality regularizer added to the kernel so that the certificates \n are orthonormal. For more details, see :class:``purestochastic.common.regularizer.Orthonormality``.\n\n The details of the method is detailled in [4]_.\n\n Parameters\n ----------\n X: np.ndarray\n The input data.\n y: np.ndarray\n The target data.\n learning_rate_oc : float (default : 0.001)\n Learning rate for the training of certificates.\n \n Returns\n -------\n History of the training.\n \"\"\"\n\n #Freeze other layers and unfreeze OC layer\n for layer in self.layers[:-1]:\n layer.trainable = False\n self.layers[-1].trainable = True\n\n # Update the loss function to OC loss function and None for the first part\n K.set_value(self.optimizer.learning_rate, learning_rate_oc)\n self.compile(loss=[None, self.find_loss()], optimizer=self.optimizer, metrics=self.compiled_metrics._metrics, stochastic_metrics=self.stochastic_metrics)\n\n # Fit OC model\n y_oc = tf.zeros([X.shape[0], ] + self.output[1].shape[1:])\n training_history = super(OrthonormalCertificatesModel, self).fit(X, y_oc, **kwargs)\n\n #Unfreeze other layers and freeze OC layer\n for layer in self.layers[:-1]:\n layer.trainable = True\n self.layers[-1].trainable = False\n\n # Recompile the model to put the loss a the good place and save frozen layers\n self.compile(loss=[self.find_loss(), None], optimizer=self.optimizer, metrics=self.compiled_metrics._metrics, stochastic_metrics=self.stochastic_metrics)\n\n return training_history\n \n def predict(self, x, **kwargs):\n \"\"\" Compute predictions.\n\n This method just called the parent's method to compute the predictions of the initial model and\n the orthonormal certificates. The norm of the orthonormal certificates is computed in order to\n have a score for the epistemic uncertainty as defined in the article [4]_ .\n\n Arguments\n ----------\n x : tf.Tensor\n Input data.\n kwargs : optional\n Other Arguments of the `predict` parent's method.\n \n Returns\n -------\n np.ndarray\n Predictions made by the Deep Ensemble model.\n \"\"\"\n\n # Compute the predictions\n predictions, oc = super(OrthonormalCertificatesModel, self).predict(x, **kwargs)\n\n # Compute scores and normalize them\n scores = np.mean(np.power(oc, 2), axis=-1)\n # scores_epi = (scores - scores.min(axis=0)) / (scores.max(axis=0) - scores.min(axis=0))\n\n return tf.stack((predictions, scores), axis=-1).numpy()\n\n def find_loss(self):\n \"\"\" Returns the loss specified in the ``compile function``.\n\n Return\n ------\n str\n The name of the loss.\n \"\"\"\n\n if isinstance(self.loss, str):\n return self.loss\n else:\n return [i for i in list(self.loss) if i != None][0]\n\n\ndef toOrthonormalCertificates(net, K, nb_layers_head, multiple_miso=True, lambda_coeff=1):\n \"\"\"Convert a regular model into a Orthonormal Certificates model.\n\n This method intends to be high-level interface to construct\n a Orthonormal Certificates model from a regular model. \n\n Parameters\n ----------\n net : :class:`tf.keras.Sequential` or :class:`tf.keras.Model`\n a tensorflow model\n\n nb_models : int\n the number of models\n\n Return\n ------\n :class:`class OrthonormalCertificatesModel`\n a Orthonormal Certificates Model\n \"\"\"\n\n # Create Orthonormal Certificates for Epistemic Uncertainties\n input_oc = net.layers[-(nb_layers_head+1)].output\n if multiple_miso:\n nb_outputs = net.output.shape[1]\n output_oc = Dense2Dto3D(nb_outputs, K, name=\"output_oc\", kernel_regularizer=Orthonormality(miso=False, lambda_coeff=lambda_coeff))(input_oc)\n else:\n output_oc = Dense(K, name=\"output_oc\", kernel_regularizer=Orthonormality(lambda_coeff=lambda_coeff))(input_oc) \n\n # Change output name of model\n net.layers[-1]._name = \"output_initial_model\"\n \n # Create the new model\n return OrthonormalCertificatesModel(net.input, [net.output, output_oc])\n","repo_name":"Purecontrol/purestochastic","sub_path":"purestochastic/model/orthonormal_certificates.py","file_name":"orthonormal_certificates.py","file_ext":"py","file_size_in_byte":9496,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"60"} +{"seq_id":"40510416933","text":"#!/usr/bin/python3\n\nimport pycparser as pycp\nimport z3\nimport sys\n\nt_qe = z3.Tactic('qe')\nt = z3.Repeat(z3.Then(\"simplify\", \"propagate-ineqs\",\n \"propagate-values\", \"unit-subsume-simplify\",\n z3.OrElse(\"split-clause\", \"skip\")))\nt_qe_ = z3.Then(t_qe, t)\n\n\ndef gen_smt_expr(ast):\n if isinstance(ast, pycp.c_ast.Constant):\n return z3.IntVal(ast.value)\n elif isinstance(ast, pycp.c_ast.ID):\n return vars[ast.name]\n elif isinstance(ast, pycp.c_ast.UnaryOp):\n if ast.op == \"-\":\n return \"-\" + gen_smt_expr(ast.expr)\n if ast.op == \"!\":\n return z3.Not(gen_smt_expr(ast.expr))\n elif isinstance(ast, pycp.c_ast.BinaryOp):\n lexp = gen_smt_expr(ast.left)\n rexp = gen_smt_expr(ast.right)\n if ast.op == \"+\":\n return lexp + rexp\n if ast.op == \"-\":\n return lexp - rexp\n elif ast.op == \"*\":\n return lexp * rexp\n elif ast.op == \"%\":\n return lexp % rexp\n elif ast.op == \"<\":\n return lexp < rexp\n elif ast.op == \">\":\n return lexp > rexp\n elif ast.op == \"<=\":\n return lexp <= rexp\n elif ast.op == \">=\":\n return lexp >= rexp\n elif ast.op == \"==\":\n return lexp == rexp\n if ast.op == \"&&\":\n return z3.And(lexp, rexp)\n if ast.op == \"||\":\n return z3.Or(lexp, rexp)\n elif ast.op == \"!=\":\n return lexp != rexp\n\n\ndef walk_block(node, prev_g=None, cond=True):\n g = z3.Goal()\n g.add(cond)\n if prev_g is not None:\n for e in prev_g:\n if isinstance(e, z3.Goal):\n g.add(e.as_expr())\n else:\n g.add(e)\n\n if isinstance(node, pycp.c_ast.Compound):\n if node.block_items is not None:\n for e in node.block_items:\n g_next = walk_block(e, g)\n g = g_next\n elif isinstance(node, pycp.c_ast.Decl):\n if \"int\" in node.type.type.names:\n vars[node.name] = z3.Int(node.name)\n if \"float\" in node.type.type.names:\n vars[node.name] = z3.Real(node.name)\n elif isinstance(node, pycp.c_ast.FuncCall):\n if node.name.name == \"__ASSUME\":\n for e_exp in node.args.exprs:\n g.add(gen_smt_expr(e_exp))\n elif node.name.name == \"__ASSERT\":\n assertions = z3.Goal()\n for e_exp in node.args.exprs:\n assertions.add(gen_smt_expr(e_exp))\n print(\"solving..\")\n print(\"SP:\", g.as_expr())\n print(\"assert:\", assertions)\n\n seen = set()\n\n def bv_length(e):\n li = [-1]\n if e in seen:\n return -1\n if (z3.is_bv(e) and\n z3.is_const(e) and\n e.decl().kind() == z3.Z3_OP_UNINTERPRETED):\n li.append(e.size())\n seen.add(e)\n if z3.is_app(e):\n for ch in e.children():\n li.append(bv_length(ch))\n elif z3.is_quantifier(e):\n for ch in e.body().children():\n li.append(bv_length(ch))\n return max(li)\n\n t = z3.Tactic('nla2bv')\n s = z3.Then(t, 'default').solver()\n fml = z3.And(g.as_expr(), z3.Not(assertions.as_expr()))\n print(\"solving using bitvector underapproximation..\")\n s.add(fml)\n status = s.check()\n\n if status == z3.unknown:\n print(\"returned 'unknown'! trying again with bigger bit length..\")\n print(\"getting highest bit length used in formula..\")\n bv_l = bv_length(t(fml).as_expr())\n print(\"highest bit length used:\", bv_l)\n\n while True:\n bv_l += 1\n print(\"trying with bit length:\", bv_l)\n s = z3.Then(z3.With('nla2bv', nla2bv_bv_size=bv_l),\n 'default').solver()\n s.add(fml)\n status = s.check()\n\n if status != z3.unknown or bv_l >= 64:\n break\n\n if status == z3.sat:\n model = s.model()\n print(\"program is unsafe.\\nlisting an unsafe assignments..\")\n for e in vars:\n print(e, ':', model[vars[e]])\n elif status == z3.unsat:\n print(\"program is safe.\")\n elif status == z3.unknown:\n print(\"unknown\")\n\n s.reset()\n else:\n print(\"found a func call\")\n elif isinstance(node, pycp.c_ast.Assignment):\n rexp = gen_smt_expr(node.rvalue)\n if z3.is_int(vars[node.lvalue.name]):\n hand_ = z3.Int('__hand__')\n elif z3.is_real(vars[node.lvalue.name]):\n hand_ = z3.Real('__hand__')\n if node.op == \"=\":\n g.add(hand_ == rexp)\n elif node.op == \"+=\":\n g.add(hand_ == (vars[node.lvalue.name] + rexp))\n elif node.op == \"-=\":\n g.add(hand_ == (vars[node.lvalue.name] - rexp))\n elif node.op == \"*=\":\n g.add(hand_ == (vars[node.lvalue.name] * rexp))\n elif node.op == \"%=\":\n g.add(hand_ == (vars[node.lvalue.name] % rexp))\n g_ = z3.Goal()\n g_.add(z3.Exists(vars[node.lvalue.name], g.as_expr()))\n g_ = t_qe_(g_)\n g = z3.Goal()\n g.add(z3.substitute(g_.as_expr(), (hand_, vars[node.lvalue.name])))\n # g = g.simplify()\n elif isinstance(node, pycp.c_ast.If):\n cond_exp = gen_smt_expr(node.cond)\n if node.iftrue is not None:\n true_expr = walk_block(node.iftrue, g, cond_exp).as_expr()\n else:\n true_expr = z3.And(cond_exp, g.as_expr())\n if node.iffalse is not None:\n false_expr = walk_block(\n node.iffalse, g, z3.Not(cond_exp)).as_expr()\n else:\n false_expr = z3.And(z3.Not(cond_exp), g.as_expr())\n g = z3.Goal()\n g.add(z3.Or(true_expr, false_expr))\n g = t(g) # g.simplify()\n else:\n return prev_g\n # print(g.as_expr(), \"\\n\")\n return g\n\n\nif __name__ == \"__main__\":\n c_fname = sys.argv[1]\n\n ast = pycp.parse_file(c_fname, use_cpp=True,\n cpp_path='gcc',\n cpp_args=['-E', r'-Iutils/fake_libc_include'])\n\n # ast.show()\n\n vars = {}\n\n main_func = None\n\n for e in ast.ext:\n if isinstance(e, pycp.c_ast.FuncDef) and e.decl.name == \"main\":\n main_func = e\n break\n\n if main_func is None:\n raise(\"no main function\")\n\n s = z3.Solver()\n\n g = walk_block(main_func.body)\n","repo_name":"rnbguy/svss","sub_path":"mini_proj/smt_verify_sp.py","file_name":"smt_verify_sp.py","file_ext":"py","file_size_in_byte":6823,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"60"} +{"seq_id":"25164661024","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Jun 22 07:26:37 2017\n\n@author: Mostafa Hammoud\n\nThis script is opens a folder containing multiple diseases, and open every \nfolder and then saves the ECG along with a tag\n\nNOTE: This script has to be changed for every folder\nCurrently it is being used for reading ptbdb\n\"\"\"\n\nimport numpy as np\nfrom ecg import qrs_detector\nimport save_functions\nimport pandas as pd\nimport os\n\nbig_file_name = r'C:\\Users\\MHammoud\\Desktop\\Physionet Data\\ptbdb'\n\n# Initialize the arrays\nall_ecg_path = []\nall_header_path = []\nall_ecg = {}\nall_disease_type = []\nall_disease_number = []\nall_peaks = {}\ntemp_content = []\n\n# Set the sampling frequency\nfs = 1000\n\n# Get the names of the folders inside big_file_name\nfolder_names = save_functions.get_folders(big_file_name)\n# Get the path of these folders\nfolder_paths = save_functions.get_path(big_file_name, folder_names)\n\n# Loop through the folders\nfor z in folder_paths:\n \n if os.path.isdir(z):\n \n # Get the names of the files inside the folders \n ecg_names = save_functions.get_folders(z)\n # Get the path of the files inside the folders \n ecg_path = save_functions.get_path(z, ecg_names)\n \n header_path = []\n \n # Loop thorugh the files and select the header files\n for j in ecg_path:\n if len(j) > 4:\n if j[-4:] == '.hea':\n header_path.append(j)\n all_header_path.append(j)\n \n # This is a temp array used to do the loop \n temp = header_path.copy()\n \n # Check the disease we are working with\n for j in temp:\n with open(j) as f:\n content = f.readlines()\n #Remove whitespace characters like `\\n` at the end of each line\n content = [x.strip() for x in content] \n \n # content[22] contains the disease type\n if 'Healthy' in content[22]:\n disease_num = 0\n elif 'Myocardial infarction' in content[22]:\n disease_num = 1\n \n # In case we have a disease we dont want then use -100 as a number \n # so we wont access it\n else:\n disease_num = -100\n # Set number of diseases.\n # Here since we want to add this data to another set of data we set \n # num_of_disease = 2 to match the other data\n num_of_diseases = 2\n \n # If the disease number if more than -1, indicating that we dont \n # want the case of -100\n if disease_num > -1:\n # Save the ECG signal\n all_ecg_path.append(j[:-4] + '.csv')\n # Save the disease number\n all_disease_number.append(disease_num)\n else:\n # If the disease we have is not what we want, then remove the \n # path of the header file\n all_header_path.remove(j)\n\n# Loop through the ECG paths and extract the ECG signals that we need\nj = 0\nfor i in all_ecg_path:\n\n # Read the signal\n file = pd.read_csv(i, delimiter=',', header = None)\n # Convert to matrix for easier accessing\n file = file.as_matrix()\n # Take out Leads I II III\n all_ecg[j] = file[:,0]\n all_ecg[j+1] = file[:,1]\n all_ecg[j+2] = file[:,2]\n \n # Change the frequency of the data to match the AstroSkin frequency = 256\n all_ecg[j] = save_functions.change_freq(fs,256,all_ecg[j])\n all_ecg[j+1] = save_functions.change_freq(fs,256,all_ecg[j+1])\n all_ecg[j+2] = save_functions.change_freq(fs,256,all_ecg[j+2])\n \n # Increment j\n j+=3\n \n \n# Loop through the ECG signals and store them\nj = 0\nfor i in range(0,np.size(all_ecg_path)*3,3):\n # Indicate when to start and end\n start = 0\n end = len(all_ecg[i])\n # Initialize a set to store the three ECG leads\n three_ecg = {}\n \n # Get the disease_num we are working with\n disease_num = all_disease_number[j]\n \n # If the disease number is more than -1 indicating the disease we want, \n # then save it\n if disease_num > -1:\n \n # Use Lead I to find the QRS complex\n # We need the QRS complex to separate the signal into heart beats\n all_peaks[j] = qrs_detector(256,all_ecg[i],filter_length = (end-start))\n \n # Save the three leads to three_ecg\n three_ecg[0] = all_ecg[i]\n three_ecg[1] = all_ecg[i+1]\n three_ecg[2] = all_ecg[i+2]\n \n \n \n # Specify what the last peak we need to take, this is added since the last \n # few seconds are sometimes noisy, since it is recorded when the ECG is \n # getting disconnected \n end_peak = np.size(all_peaks[j]) - 4 \n \n # Save the ECG beats\n save_functions.save_ecg(all_peaks[j],three_ecg,256,num_of_diseases,all_disease_number[j],end_peak) \n \n # Reinitialize to be used in next loop\n three_ecg = {}\n all_peaks[j] = []\n all_ecg[j] = []\n all_ecg[j+1] = []\n all_ecg[j+2] = [] \n j += 1\n \n","repo_name":"JulienL3vesque/Hexoskin_RnD_OSM","sub_path":"Gathering data/physio_save_all.py","file_name":"physio_save_all.py","file_ext":"py","file_size_in_byte":5198,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"60"} +{"seq_id":"907007609","text":"import numpy as np\n\nfrom dtqw.coin.coin2d.coin2d import Coin2D\n\n__all__ = ['Fourier2D']\n\n\nclass Fourier2D(Coin2D):\n \"\"\"Class that represents the 2-dimensional Fourier coin.\"\"\"\n\n def __init__(self, spark_context):\n \"\"\"\n Build a 2-dimensional Fourier coin object.\n\n Parameters\n ----------\n spark_context : SparkContext\n The SparkContext object.\n\n \"\"\"\n super().__init__(spark_context)\n\n self._data = np.array(\n [[1, 1, 1, 1],\n [1, 1.0j, -1, -1.0j],\n [1, -1, 1, -1],\n [1, -1.0j, -1, 1.0j]], dtype=complex\n ) / 2.0\n","repo_name":"alfabr90/dtqw","sub_path":"dtqw/coin/coin2d/fourier2d.py","file_name":"fourier2d.py","file_ext":"py","file_size_in_byte":637,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"60"} +{"seq_id":"73260219391","text":"from logging import exception\nfrom unittest import result\nfrom mlrgetpy.enums.Area import Area\nfrom mlrgetpy.Filter import Filter\nfrom mlrgetpy.Repository import Repository\nimport pandas as pd\nimport unittest\nfrom pandas import testing as tm\nfrom mlrgetpy.enums.AttributeType import FilterAttributeType\n\nfrom mlrgetpy.enums.Characteristic import Characteristic\nfrom mlrgetpy.enums.Task import Task\n\n\nclass TestFilter(unittest.TestCase):\n\n def test_area_init(self):\n\n with self.assertRaises(ValueError, msg=\"Must be an Area Class\"):\n filter = Filter(area=\"Science\")\n\n with self.assertRaises(ValueError, msg=\"Must be a List\"):\n filter = Filter(area=Area.COMPUTER_SCIENCE)\n\n with self.assertRaises(ValueError, msg=\"Must be an List of Area Class\"):\n filter = Filter(area=[\"Science\"])\n\n with self.assertRaises(ValueError, msg=\"Must be an List of Area Class\"):\n filter = Filter(area=[Area.BUSINESS, \"Game\", Area.LAW])\n\n filter = Filter(area=[Area.BUSINESS])\n self.assertEqual(Filter, type(filter), msg=\"One element\")\n\n filter = Filter(area=[Area.BUSINESS, Area.ENGINEERING])\n self.assertEqual(Filter, type(filter), msg=\"Two element\")\n\n filter = Filter(area=[Area.BUSINESS, Area.ENGINEERING, Area.LAW])\n self.assertEqual(Filter, type(filter))\n\n def test_characteristic_init(self):\n\n with self.assertRaises(ValueError, msg=\"Must be an Characteristic Class\"):\n filter = Filter(characteristics=\"Tabular\")\n\n with self.assertRaises(ValueError, msg=\"Must be a List\"):\n filter = Filter(characteristics=Characteristic.TABULAR)\n\n with self.assertRaises(ValueError, msg=\"Must be an List of Characteristic Class\"):\n filter = Filter(characteristics=[\"Tabular\"])\n\n with self.assertRaises(ValueError, msg=\"Must be an List of Characteristic Class\"):\n filter = Filter(characteristics=[\n Characteristic.TABULAR, \"Image\", Characteristic.SEQUENTIAL])\n\n filter = Filter(characteristics=[Characteristic.TABULAR])\n self.assertEqual(Filter, type(filter), msg=\"One element\")\n\n filter = Filter(characteristics=[\n Characteristic.TABULAR, Characteristic.SEQUENTIAL])\n self.assertEqual(Filter, type(filter), msg=\"Two element\")\n\n filter = Filter(characteristics=[\n Characteristic.TABULAR, Characteristic.SEQUENTIAL, Characteristic.TIME_SERIES])\n self.assertEqual(Filter, type(filter))\n\n def test_area(self):\n df = pd.DataFrame({'ID': [25, 78, 86,\n 93, 102, 124,\n 128, 132, 135],\n 'Name': ['data1', 'data2', 'data3',\n 'data4', 'data5', 'data6',\n 'data7', 'data8', 'data9'],\n 'Area': ['Financial', 'Computer', 'Business',\n 'Computer Science', 'Life', 'Life Sciences',\n 'Other', None, 'Area1']})\n df = df.set_index('ID')\n\n # Business should search for Financial and Business\n filter = Filter(area=[Area.BUSINESS])\n result = filter.filter(df)\n self.assertEqual([25, 86], result.index.tolist())\n\n # test Computer science should search for Computer and Compute Science\n # in the online repository mistakenly just search for\n # \"Computer\" and not for \"Computer Science\"\n filter = Filter(area=[Area.COMPUTER_SCIENCE])\n result = filter.filter(df)\n self.assertEqual([78, 93], result.index.tolist())\n\n # test LIFE_SCIENCES should search for Life and Life Sciences\n filter = Filter(area=[Area.LIFE_SCIENCES])\n result = filter.filter(df)\n self.assertEqual([102, 124], result.index.tolist())\n\n # test other. false in none value\n filter = Filter(area=[Area.OTHER])\n result = filter.filter(df)\n self.assertEqual([128], result.index.tolist())\n\n def test_characteristic(self):\n\n df = pd.DataFrame({'ID': [25, 78, 86,\n 93, 102, 124,\n 128, 132, 135,\n 137, 139, 142,\n 145, 147],\n 'Name': ['data1', 'data2', 'data3',\n 'data4', 'data5', 'data6',\n 'data7', 'data8', 'data9',\n 'data10', 'data11', 'data12',\n 'data13', 'data14'],\n 'Types': ['Tabular', 'Multivariate', 'Univariate',\n 'Sequential', 'Time-Series', 'Sequential',\n 'Other', None, 'Tabular,Multivariate',\n 'Tabular,Univariate', 'Univariate, Multivariate', 'Univariate,Multivariate',\n 'Tabular,Multivariate', 'Multivariate,Tabular']})\n df = df.set_index('ID')\n\n # TABULAR: str = [\"Tabular\", \"Multivariate\", \"Univariate\"]\n # The characteristic in id 139 is not valid due to a space\n filter = Filter(characteristics=[Characteristic.TABULAR])\n result = filter.filter(df)\n self.assertEqual([25, 78, 86, 135, 137, 142, 145, 147],\n result.index.tolist())\n\n def test_task(self):\n # test data\n df = pd.DataFrame({'ID': [25, 78, 86, 93, 102],\n 'Name': ['data1', 'data2', 'data3', 'data4', 'data5'],\n 'Task': ['Classification', 'Classification', 'Regression', 'Clustering', 'Other']})\n df = df.set_index('ID')\n\n # test classification\n filter = Filter(task=Task.CLASSIFICATION)\n result = filter.filter(df)\n self.assertEqual([25, 78], result.index.tolist())\n\n # test Regression\n filter = Filter(task=Task.REGRESSION)\n result = filter.filter(df)\n self.assertEqual([86], result.index.tolist())\n\n # test clustering\n filter = Filter(task=Task.CLUSTERING)\n result = filter.filter(df)\n self.assertEqual([93], result.index.tolist())\n\n # test Other\n filter = Filter(task=Task.OTHER)\n result = filter.filter(df)\n self.assertEqual([102], result.index.tolist())\n\n def test_attribute_type(self):\n\n df = pd.DataFrame({'ID': [25, 78, 86,\n 93, 102, 124,\n 128, 132, 135,\n 137, 139, 142,\n 145, 147],\n 'Name': ['data1', 'data2', 'data3',\n 'data4', 'data5', 'data6',\n 'data7', 'data8', 'data9',\n 'data10', 'data11', 'data12',\n 'data13', 'data14'],\n 'AttributeTypes': ['Integer', 'Real', 'Integer,Real',\n 'Categorical', 'Time-Series', 'Sequential',\n 'Categorical', None, 'Integer,Real',\n 'Integer,Categorical', 'Real,Categorical', 'Real, Categorical',\n 'Tabular,Multivariate', 'Multivariate,Tabular']})\n df = df.set_index('ID')\n\n filter = Filter(attribute_type=FilterAttributeType.NUMERICAL)\n result = filter.filter(df)\n self.assertEqual([25, 78, 86, 135, 137, 139, 142],\n result.index.tolist())\n\n filter = Filter(attribute_type=FilterAttributeType.CATEGORICAL)\n result = filter.filter(df)\n self.assertEqual([93, 128, 137, 139, 142], result.index.tolist())\n\n # There should be at least one attribute type Numerical and one Categorical\n # every attribute type is separated by comma and may contain space (id 142)\n filter = Filter(attribute_type=FilterAttributeType.MIXED)\n result = filter.filter(df)\n self.assertEqual([137, 139, 142],\n result.index.tolist())\n","repo_name":"jos101/mlgetpy","sub_path":"mlrgetpy/tests/test_Filter.py","file_name":"test_Filter.py","file_ext":"py","file_size_in_byte":8310,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"60"} +{"seq_id":"4880296477","text":"import datetime\nimport os\nimport shutil as sh\n\nimport config\nimport logger\n\n\ndef new_db_copy():\n file_path = config.db_copies_path\n today = str(datetime.datetime.now())[:10]\n sh.copy2('1543.eljur.bot/1543.eljur.bot.db', file_path + '/database_' + today + '.db')\n\n\ndef delete_db():\n file_path = config.db_copies_path\n today = str(datetime.datetime.now())[:10]\n copies_of_db = os.listdir(file_path)\n for db in copies_of_db:\n if int(today[5:7]) - int(db[14:16]) == 2 or int(today[5:7]) - int(db[14:16]) == -10:\n os.remove(file_path + \"/\" + db)\n\n\nif __name__ == '__main__':\n try:\n new_db_copy()\n delete_db()\n except Exception as ex:\n logger.log(\"db_copier\", f\"error {ex}\")\n","repo_name":"felpsyatina/1543.eljur.bot","sub_path":"db_copier.py","file_name":"db_copier.py","file_ext":"py","file_size_in_byte":735,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"60"} +{"seq_id":"75109774910","text":"\nfrom Database.database import DatabaseManager\nfrom DeleteBookErrors import *\nfrom Models.AbstractModel import IModel\nfrom psycopg2.errors import *\nclass DeleteCopyModel(IModel):\n def __init__(self):\n self._observers = set()\n self._isDeleted = False\n self._message = ''\n\n def Register(self, listener):\n self._observers.add(listener)\n\n def Notify(self):\n for obs in self._observers:\n obs.Notify()\n\n def DeleteCopy(self, copyId):\n if (copyId and copyId.isnumeric()):\n try:\n db = DatabaseManager()\n db.DeleteCopy(copyId)\n self._message = \"Book successfully removed\"\n self._isDeleted = True\n except BaseDeleteBookError as e:\n self._message = e.message\n self._isDeleted = False\n except NumericValueOutOfRange:\n self._message = \"Too big id copy value\"\n self._isDeleted = False\n else: \n self._message = \"Book id should be numeric string\"\n self._isDeleted = False\n \n self.Notify()\n","repo_name":"GreatHorizon/library","sub_path":"Models/DeleteCopyModel.py","file_name":"DeleteCopyModel.py","file_ext":"py","file_size_in_byte":1134,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"60"} +{"seq_id":"32472893301","text":"import numpy as np\nimport sys\nimport keras\nfrom keras.models import Sequential\nfrom keras.layers.core import Dense, Dropout, Activation, Flatten\nfrom keras.layers.convolutional import Conv2D, MaxPooling2D, AveragePooling2D\nfrom keras.utils import np_utils, generic_utils, to_categorical\nfrom keras.layers import BatchNormalization\n\n##### Read in data #####\ndata_files = ['train_data_2.npy', 'train_data_3.npy', 'train_data_4.npy', 'train_data_5.npy', 'train_data_6.npy']\n\ny_train = []\ndata = np.load('train_data_1.npy') \nfor i in data_files:\n\tx = np.load(i)\n\tdata = np.append(data, x, axis=0)\n\ny = data[0:,1]\nfor i in range(y.shape[0]):\n\tif (y[i] == [1,0]):\n\t\ty_train.append(1)\n\telse:\n\t\ty_train.append(0)\n\nx_train = np.load(\"total_train.npy\")\nnp.save(\"labels\", y_train)\n##### Set model parameters #####\nbatch_size = 32 \nnb_classes = 2\nnb_epoch = 25\n\nimg_channels = 1\nimg_rows = 270\nimg_cols = 480\n\n##### Convert labels to one-hot matrix #####\ny_train = to_categorical(y_train, nb_classes)\n\n##### Create Model #####\nmodel = Sequential()\n\n#Block 1\nmodel.add(Conv2D(filters=32, kernel_size=(3,3), padding='same', input_shape=[270, 480, 1]))\nmodel.add(BatchNormalization())\nmodel.add(Activation('relu'))\nmodel.add(Conv2D(filters=32, kernel_size=(3,3), padding='valid'))\nmodel.add(BatchNormalization())\nmodel.add(Activation('relu'))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Dropout(0.45))\n\n#Block 2\nmodel.add(Conv2D(filters=64, kernel_size=(3,3), padding='same'))\nmodel.add(BatchNormalization())\nmodel.add(Activation('relu'))\nmodel.add(Conv2D(filters=64, kernel_size=(3,3), padding='valid'))\nmodel.add(BatchNormalization())\nmodel.add(Activation('relu'))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Dropout(0.45))\n\n#Block 3\nmodel.add(Conv2D(filters=128, kernel_size=(3,3), padding='same'))\nmodel.add(BatchNormalization())\nmodel.add(Activation('relu'))\nmodel.add(Conv2D(filters=128, kernel_size=(3,3), padding='valid'))\nmodel.add(BatchNormalization())\nmodel.add(Activation('relu'))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Dropout(0.45))\n\n#Dense layer\nmodel.add(Flatten())\nmodel.add(Dense(512))\nmodel.add(BatchNormalization())\nmodel.add(Activation('relu'))\nmodel.add(Dropout(0.5))\nmodel.add(Dense(256))\nmodel.add(BatchNormalization())\nmodel.add(Activation('relu'))\nmodel.add(Dropout(0.5))\nmodel.add(Dense(nb_classes))\nmodel.add(Activation('softmax'))\n\n#opt = keras.optimizers.rmsprop(lr=0.001, decay=1e-6)\n#opt = keras.optimizers.SGD(lr=0.01, decay=0.0005, momentum=0.9)\n#opt = keras.optimizers.Adam(lr=0.001, decay=1e-6)\nopt = keras.optimizers.Adam(lr=0.01, decay=0.0005)\n\nmodel.compile(loss='categorical_crossentropy', optimizer=opt, metrics=['accuracy'])\n\n\ndef train():\n\tmodel.fit(x_train, y_train, batch_size=batch_size, epochs=nb_epoch, shuffle=True)\n\ntrain()\nmodel.save(\"model\")\n","repo_name":"Stepheni12/Deep_Learning_Projects","sub_path":"Flappy_Bird_Bot/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":2809,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"60"} +{"seq_id":"14703939759","text":"def is_leap(year): # 宣告1个is_leap function\n if year % 4 != 0: # 设计判断公式\n return False # 回传判断结果\n elif year % 100 != 0:\n return True\n elif year % 400 != 0:\n return False\n elif year % 3200 != 0:\n return True\n else:\n return False\n\nwhile True: # 设立一个重复输入的循环\n keyin_year = input('请输入要查询的年份,或输入 q 退出程序:') # 设计用户输入位置\n if keyin_year == 'q': # 如果用户输入q就退出程序\n break\n\n result_year = is_leap(int(keyin_year)) # 将用户输入的字串转为整数\n # 在将转好的整数带入is_leap function做运算\n # 将运算结果存在result_year变数里\n\n if result_year == True: # 如果取得的结果是True,打印{}年份是闰年\n print(f'{keyin_year} 是闰年')\n else:\n print(f'{keyin_year} 不是闰年')\n","repo_name":"brianhsu2693/PythonProjectStudy","sub_path":"completed_project/Py_判斷是不是閏年程式.py","file_name":"Py_判斷是不是閏年程式.py","file_ext":"py","file_size_in_byte":995,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"60"} +{"seq_id":"25208766270","text":"\"\"\"\nhttps://leetcode.com/problems/merge-sorted-array/description/\n\n9/21/2023\n\n--- PROMPT ---\nYou are given two integer arrays nums1 and nums2, sorted in non-decreasing order, and two integers m and n, representing the number of elements in nums1 and nums2 respectively.\n\nMerge nums1 and nums2 into a single array sorted in non-decreasing order.\n\nThe final sorted array should not be returned by the function, but instead be stored inside the array nums1. To accommodate this, nums1 has a length of m + n, where the first m elements denote the elements that should be merged, and the last n elements are set to 0 and should be ignored. nums2 has a length of n.\n\n\n\n\n--- LESSONS ---\nstruggled really with following all the pointers thru each iteration\n\nrecognizing edge cases, WITHOUT a pre-built test\n\ninterestingly, when put into gpt, I get the same solution. What is shown below is Neetcode\n\n--- QUESTIONS ---\n\n--- PSEUDOCODE ---\n 2 arrays - nums1 and nums2 - increasing order. m notes the number of elements in nums1. n notes number of elements in num2\n merge these two arrays into 1, which will be stored into nums1 (which has length m + n, where the first m elements are numbers, and the last n elements are 0)\n \n 3 pointers\n - one locating the replaced pointer\n - one locating last val of nums2\n - one locating last val of nums1\n\n start pointer at the end of nums 1\n place the largest value in that point\n compare the last value in nums1, and last number in nums2. place the larger value into placement\n\n\n\n\"\"\"\n# --- MY SOLUTION ---\nclass Solution(object):\n def merge(self, nums1, m, nums2, n):\n \"\"\"\n :type nums1: List[int]\n :type m: int\n :type nums2: List[int]\n :type n: int\n :rtype: None Do not return anything, modify nums1 in-place instead.\n \"\"\"\n\n # nums1 -> m\n # nums2 -> n\n\n end_of_nums1 = m + n - 1\n\n # merge in reverse order, replacing the values if\n while m > 0 and n > 0:\n if nums1[m-1] > nums2[n-1]:\n nums1[end_of_nums1] = nums1[m-1]\n m -=1\n else: \n nums1[end_of_nums1] = nums2[n-1]\n n-=1\n # always decrement last pointer\n end_of_nums1-=1\n\n\n # edge case: when remainder of nums2 is smaller than nums1\n # I wouldn't have even recognized this edge case...\n # fill nums1 with leftover nums2 elements, only if there are leftover elements in n\n while n > 0:\n nums1[end_of_nums1] = nums2[n-1]\n n -=1\n end_of_nums1 -=1\n\n\n# --- TEST ---\n\n\n# --- ALT SOLN by others ---\n","repo_name":"callmelazarus/leetcode-codewars-journey","sub_path":"TWO POINTERS/merge_sorted_array_e88.py","file_name":"merge_sorted_array_e88.py","file_ext":"py","file_size_in_byte":2699,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"60"} +{"seq_id":"7009348088","text":"COMPLETE = False\nyear, day = [2022, 21]\n\ndef recurFind(cur_monkey, monkeys, ops):\n if type(monkeys[cur_monkey]) is int:\n return monkeys[cur_monkey]\n \n m1, symb, m2 = monkeys[cur_monkey].split(\" \")\n\n return ops[symb](recurFind(m1, monkeys, ops), recurFind(m2, monkeys, ops))\n\ndef main(enabled_print=True, test=False):\n if test:\n with open(r\"2022\\day21\\test.txt\", 'r') as f:\n inp = [line.strip() for line in f.readlines()]\n else:\n with open(r\"2022\\day21\\input.txt\", 'r') as f:\n inp = [line.strip() for line in f.readlines()]\n \n monkeys = {}\n ops = {'*': lambda x, y: x*y, '/': lambda x, y: x // y, '-': lambda x, y: x - y, '+':lambda x, y: x + y}\n \n for line in inp:\n name, operation = line.split(\":\")\n operation = operation[1:]\n just_num = True\n for op in ops.keys():\n if op in operation:\n just_num = False\n break\n \n if just_num:\n monkeys[name] = int(operation)\n else:\n monkeys[name] = operation\n \n return recurFind(\"root\", monkeys, ops)\n\nif __name__ == \"__main__\":\n from aocd import submit\n\n import bs4\n import copier\n\n answer = main(not COMPLETE)\n \n if COMPLETE:\n r = submit(answer, year=year, day=day)\n soup = bs4.BeautifulSoup(r.text, \"html.parser\")\n message = soup.article.text\n if \"That's the right answer\" in message:\n copier.make_next(year, day)\n else:\n print(answer)\n","repo_name":"awsloth/adventOfCode","sub_path":"2022/day21/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":1532,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"60"} +{"seq_id":"28795510044","text":"CONFIG = {\n 'mode': 'wsgi',\n 'environment': {\n 'PYTHONPATH': '/usr/bin/python',\n },\n 'working_dir': '/home/box/web',\n 'user': 'www-data',\n 'group': 'www-data',\n 'args': (\n '--bind=0.0.0.0:8080',\n '--workers=4',\n '--timeout=30',\n 'hello:application',\n ),\n}\n","repo_name":"dynnoil/stepic_web","sub_path":"etc/hello.py","file_name":"hello.py","file_ext":"py","file_size_in_byte":315,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"60"} +{"seq_id":"27192875388","text":"import sqlite3\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport datetime\nimport time\nfrom scipy import signal\nimport seaborn as sns\nfrom scipy import interpolate\nfrom cycler import cycler\n\n\nyear = 2018\ndate0 = str(year - 1) + '-12-15'\n\n\ndef caltime(date1, date2):\n date1 = time.strptime(date1, \"%Y-%m-%d\")\n date2 = time.strptime(date2, \"%Y-%m-%d\")\n date1 = datetime.datetime(date1[0], date1[1], date1[2])\n date2 = datetime.datetime(date2[0], date2[1], date2[2])\n return (date2-date1).days\n\n\ndef get_mh_data(database_name):\n mh = {}\n db = sqlite3.connect(database_name).cursor()\n # print('Connect Successful!')\n db.execute(\"select * from sqlite_master\")\n # print([x[1] for x in db.fetchall()])\n head = db.execute(\"pragma table_info([DATE_DATA])\")\n for x in head.fetchall():\n mh[x[1]] = []\n\n table = db.execute(\"select * from DATE_DATA\")\n for row in table:\n i = 0\n for k in mh:\n mh[k].append(row[i])\n i += 1\n return mh\n\n\ndef static_sleep(mh):\n dates = mh['DATE']\n day_nums = []\n slp_sts = []\n slp_eds = []\n\n for i in range(len(dates)):\n day_num = caltime(date0, dates[i])\n if 0 < day_num < 366:\n summary = mh['SUMMARY'][i]\n slp_st_loc = summary.find('\"st\":')\n slp_ed_loc = summary.find(',\"ed\":')\n slp_dp_loc = summary.find(',\"dp\":')\n slp_st = datetime.datetime.fromtimestamp(int(summary[slp_st_loc+5:slp_ed_loc]))\n slp_ed = datetime.datetime.fromtimestamp(int(summary[slp_ed_loc+6:slp_dp_loc]))\n if slp_ed != slp_st:\n day_nums.append(day_num)\n slp_sts.append((slp_st.hour + slp_st.minute/60 + slp_st.second/3600+8) % 24-8)\n slp_eds.append(slp_ed.hour + slp_ed.minute/60 + slp_st.second/3600)\n\n sns.jointplot(slp_sts, slp_eds, kind='reg')\n plt.plot(range(-4, 8), np.arange(-4, 8)+9, 'g')\n plt.plot(range(-4, 8), np.arange(-4, 8) + 7, 'r')\n plt.plot(range(-4, 8), np.arange(-4, 8) + 5, 'k')\n plt.text(6, 15, '9 hours', color='g')\n plt.text(6, 13, '7 hours', color='r')\n plt.text(6, 11, '5 hours', color='k')\n plt.xlabel('sleep_start')\n plt.ylabel('sleep_end')\n plt.axis([-8, 10, 0, 18])\n plt.show()\n\n\ndef static_step(mh):\n dates = mh['DATE']\n day_nums = []\n stp_ttls = []\n for i in range(len(dates)):\n date = dates[i]\n day_num = caltime(date0, date)\n if -50 < day_num < 366+50:\n summary = mh['SUMMARY'][i]\n stp_ttl_loc = summary.find('\"ttl\":')\n stp_dis_loc = summary.find(',\"dis\":')\n # print(summary[stp_ttl_loc+6:stp_dis_loc])\n stp_ttl = int(summary[stp_ttl_loc+6:stp_dis_loc])\n day_nums.append(day_num)\n stp_ttls.append(stp_ttl)\n step = np.array(stp_ttls)\n day = np.array(day_nums)\n return day, step\n\n\ndef step_cwt(day_nums, stp_ttls):\n f = interpolate.interp1d(day_nums, stp_ttls, kind='linear')\n start_day = day_nums[0]\n end_day = day_nums[-1]\n xnew = np.linspace(start_day, end_day, end_day-start_day+1)\n step = f(xnew)\n mean = stp_ttls.mean()\n print(mean)\n mean = step.mean()\n widths = np.arange(1, 40)\n cwtmatr = signal.cwt(step - mean, signal.ricker, widths)\n # sns.distplot(ttl, kde=False, bins=20)\n # plt.axis([0, 35000, 0, 0.0001])\n plt.imshow(cwtmatr,\n extent=[1, 365, 40, 5],\n cmap='jet', aspect=1,\n vmax=cwtmatr.max(), vmin=cwtmatr.min())\n\n date = [str(year)+'/'+str(x)+'/1' for x in range(1, 13)]\n plt.xticks(np.array([17, 48, 76, 107, 137, 168, 198, 229, 260, 290, 321, 351]), date)\n # plt.title(\"My Steps\")\n # plt.xlabel(\"days from 2016/10/27\")\n # plt.ylabel(\"Scale\")\n # plt.colorbar()\n plt.show()\n # plt.savefig('figure\\\\step.png')\n\n\ndef static_7_day(days, steps):\n err = np.array([[0.]*7]*12)\n mean = np.array([[0.]*7]*12)\n # max = np.array([[0.] * 7] * 12)\n # min = np.array([[0.] * 7] * 12)\n alist = [[list()]*7]*12\n\n a1=list()\n for i in range(12):\n for j in range(7):\n for k in range(len(steps)):\n libai = (days[k] + 4) % 7\n date = datetime.datetime(2016, 12, 15) + datetime.timedelta(int(days[k]))\n # print(date)\n if int((date.month - 1)) == i and libai == j:\n a1.append(steps[k])\n # alist[date.month - 1][libai].append(step[i])\n mean[i][j] = np.array(a1).mean()\n err[i][j] = np.array(a1).std()\n # max[i][j] = np.array(a1).max()\n # min[i][j] = np.array(a1).min()\n a1.clear()\n\n cmap = plt.cm.get_cmap('Paired')\n c = cycler('color', cmap(np.linspace(0, 1, 12)))\n plt.rcParams[\"axes.prop_cycle\"] = c\n for i in range(12):\n ind = np.arange(7)\n # bottom = 50000*i\n # y = mean[i]+bottom\n # print(y)\n plt.bar(ind+0.3*(i % 3), mean[i], yerr=err[i], width=0.3, bottom=20000*int(i/3))\n plt.legend(range(1, 13), loc='center right')\n plt.xlim([-0.5, 8])\n plt.yticks(range(0, 90001, 10000), ['0', '10000', '0', '10000', '0', '10000', '0', '10000'])\n plt.xticks(np.arange(0, 8)+0.3, ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'])\n plt.show()\n\n\ndef static_52_weeks(days, steps):\n first_date = time.strptime(date0, \"%Y-%m-%d\")\n anyday = int(datetime.datetime(first_date[0], first_date[1], first_date[2]).strftime(\"%w\"))\n\n cld = [[0]*53 for x in range(7)]\n\n for i in range(len(days)):\n day = days[i]\n if 0 < day < 366:\n week_num = (day+anyday)//7\n day_of_week = (day+anyday) % 7\n cld[day_of_week][week_num] = steps[i]\n\n p = []\n for i in range(7):\n start = 0\n end = 53\n if cld[i][0] == 0:\n start = 1\n if cld[i][-1] == 0:\n end = 52\n y = np.array(cld[i][start:end])\n x = np.arange(start, end)\n N = 4\n # plt.scatter(range(start, end), y-i*20000)\n y_move = np.convolve(y, np.ones((N,)) / N)[(N - 1):]\n # plt.plot(range(start, end), y_move-i*20000)\n # plt.bar(x, y-y_move-i*20000)\n p.append(plt.bar(x, height=y-y_move, bottom=-i*20000+y*0))\n plt.plot(x, y*0-i*20000, c='k')\n plt.yticks(-np.arange(0, 7*20000, 20000), ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'])\n plt.xticks(np.arange(15, 365+15, 30)/7, range(1, 13))\n plt.xlim([-1, 53])\n plt.show()\n\n\nif __name__ == '__main__':\n year = 2018\n file_name = 'apps/com.xiaomi.hm.health/db/origin_db_d05598c008a33f0ce464da4c71b90820'\n mh2018 = get_mh_data(file_name)\n # static_sleep(mh)\n day, step = static_step(mh2018)\n static_52_weeks(day, step)\n","repo_name":"zzyztyy/MiHealth1","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":6760,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"60"} +{"seq_id":"22623539073","text":"from aiogram import types\nfrom aiogram.dispatcher.filters.builtin import CommandStart\nfrom aiogram.dispatcher import FSMContext\nfrom data.config import ADMINS\nfrom states import MessageForm, CategoryForm, SendAll\nfrom keyboards.inline import category_btn, cencel_btn, menuIN_btn, order_delete_btn\nfrom utils.db_api import create_message, create_category, get_message, delete_message, delete_category, get_users, get_xls,\\\nusers_count\nfrom loader import dp\nimport re\nimport asyncio\nfrom data.config import ADMINS\n\n@dp.message_handler(commands=['admin'], user_id=ADMINS)\nasync def hello_admin(msg: types.Message):\n await msg.answer(\"Hello admin\", reply_markup=category_btn())\n\n@dp.callback_query_handler(lambda call: call.data == 'download')\nasync def xsl_down_send(call: types.CallbackQuery):\n user_count = users_count()[0][0]\n get_xls()\n await call.message.answer_document(open('./users.xlsx', 'rb'), caption=f\"Users: {user_count}\")\n\n@dp.callback_query_handler(lambda call: call.data == 'send_message')\nasync def send_message(call: types.CallbackQuery):\n await call.message.answer(\"Send me message:\", reply_markup=cencel_btn)\n await SendAll.msg.set()\n\n@dp.callback_query_handler(lambda call: call.data == 'send_forward')\nasync def send_message_frwd(call: types.CallbackQuery):\n await call.message.answer(\"Send me message:\", reply_markup=cencel_btn)\n await SendAll.forward.set()\n\n@dp.callback_query_handler(lambda call: call.data == 'cencel', state='*')\nasync def cencel(call: types.CallbackQuery, state: FSMContext):\n await call.answer()\n await state.finish()\n await call.message.answer(\"Бийкар етилди\")\n\n@dp.callback_query_handler(lambda call: 'menu_id=' in call.data)\nasync def add_category_for_msg(call: types.CallbackQuery, state: FSMContext):\n await call.answer()\n menu_id = call.data.split('=')[1]\n await state.update_data(menu_id=menu_id)\n await CategoryForm.name.set()\n await call.message.answer(\"Меню атын киритиң:\", reply_markup=cencel_btn)\n\n@dp.message_handler(state=CategoryForm.name, content_types=['text'])\nasync def set_text_category(msg: types.Message, state: FSMContext):\n data = await state.get_data()\n create_category(data['menu_id'], msg.text)\n await msg.answer(\"Қосылды ✅\")\n await state.finish()\n await msg.answer(\"Hello admin\", reply_markup=category_btn()) \n\n@dp.callback_query_handler(lambda call: 'menu_IN=' in call.data)\nasync def add_category_for_msg(call: types.CallbackQuery, state: FSMContext):\n await call.answer()\n menu_id = call.data.split('=')[1]\n await call.message.answer(\"Менюдиң ишки бөлими!\", reply_markup=menuIN_btn(menu_id))\n\n@dp.callback_query_handler(lambda call: 'menuIN_id=' in call.data)\nasync def add_category_for_msg(call: types.CallbackQuery, state: FSMContext):\n await call.answer()\n category_id = call.data.split('=')[1]\n await state.update_data(cat_id=category_id)\n await MessageForm.photo.set()\n await call.message.answer(\"Сүўрет жибериң:\", reply_markup=cencel_btn)\n\n@dp.message_handler(state=MessageForm.photo, content_types=['photo'])\nasync def set_photo(msg: types.Message, state: FSMContext):\n await msg.answer(\"Пост ушын текст киритиң:\", reply_markup=cencel_btn)\n photo_id = msg.photo[0].file_id\n await state.update_data(photo=photo_id)\n await MessageForm.next()\n\n@dp.message_handler(state=MessageForm.text, content_types=['text'])\nasync def set_photo(msg: types.Message, state: FSMContext):\n data = await state.get_data()\n create_message(data['cat_id'], msg.text, data['photo'])\n await msg.answer(\"Қосылды ✅\")\n await state.finish()\n await msg.answer(\"Hello admin\", reply_markup=category_btn())\n\n@dp.message_handler(state=SendAll.msg)\nasync def send_messge_users(msg: types.Message, state: FSMContext):\n s, n = 0, 0\n await msg.answer(\"seding...\")\n await state.finish()\n \n for x in get_users(): \n try:\n await msg.copy_to(x[0], reply_markup=msg.reply_markup)\n await asyncio.sleep(.07)\n s +=1\n except: n +=1\n await msg.reply(f\"Жиберилди: {s}\\nЖиберилмеди: {n}\")\n\n@dp.message_handler(state=SendAll.forward)\nasync def send_messge_forward(msg: types.Message, state: FSMContext):\n s, n = 0, 0\n await msg.answer(\"seding...\")\n await state.finish()\n \n for x in get_users(): \n try:\n await msg.forward(x[0])\n await asyncio.sleep(.07)\n s +=1\n except: n +=1\n await msg.reply(f\"Жиберилди: {s}\\nЖиберилмеди: {n}\")\n\n\n@dp.callback_query_handler(lambda call: 'CategoryOpen=' in call.data)\nasync def set_cat_open(call: types.CallbackQuery):\n category_id = call.data.split('=')[1]\n data = get_message(cate_id=category_id)\n if len(data) > 0:\n for x in data:\n await call.message.answer_photo(x[3], x[2], reply_markup=order_delete_btn(x[0]))\n else: await call.answer(\"Мағлыўмат жоқ\", True)\n\n@dp.callback_query_handler(lambda call: 'msg_del' in call.data)\nasync def delete_product(call: types.CallbackQuery):\n await call.answer(\"deleted\")\n msg_id = call.data.split('=')[1]\n delete_message(msg_id)\n await call.message.delete()\n\n\n@dp.callback_query_handler(lambda call: 'deleteCategory=' in call.data)\nasync def delete_category_func(call: types.CallbackQuery):\n cat_id = call.data.split('=')[1]\n delete_category(cat_id)\n await call.answer(\"deleted\")\n await call.message.delete()\n","repo_name":"Azizbek-007/ProektArtBot","sub_path":"handlers/users/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":5558,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"60"} +{"seq_id":"17015265605","text":"from typing import TYPE_CHECKING, Dict\n\nimport gradio as gr\n\nfrom llmtuner.extras.constants import METHODS, SUPPORTED_MODELS\nfrom llmtuner.extras.template import templates\nfrom llmtuner.webui.common import list_checkpoint, get_model_path, get_template, save_config\nfrom llmtuner.webui.utils import can_quantize\n\nif TYPE_CHECKING:\n from gradio.components import Component\n\n\ndef create_top() -> Dict[str, \"Component\"]:\n available_models = list(SUPPORTED_MODELS.keys()) + [\"Custom\"]\n\n with gr.Row():\n lang = gr.Dropdown(choices=[\"en\", \"zh\"], scale=1)\n model_name = gr.Dropdown(choices=available_models, scale=3)\n model_path = gr.Textbox(scale=3)\n\n with gr.Row():\n finetuning_type = gr.Dropdown(choices=METHODS, value=\"lora\", scale=1)\n checkpoints = gr.Dropdown(multiselect=True, scale=5)\n refresh_btn = gr.Button(scale=1)\n\n with gr.Accordion(label=\"Advanced config\", open=False) as advanced_tab:\n with gr.Row():\n quantization_bit = gr.Dropdown(choices=[\"None\", \"8\", \"4\"], value=\"None\", scale=1)\n template = gr.Dropdown(choices=list(templates.keys()), value=\"default\", scale=1)\n system_prompt = gr.Textbox(scale=2)\n\n lang.change(save_config, [lang, model_name, model_path])\n\n model_name.change(\n list_checkpoint, [model_name, finetuning_type], [checkpoints]\n ).then(\n get_model_path, [model_name], [model_path]\n ).then(\n get_template, [model_name], [template]\n ) # do not save config since the below line will save\n\n model_path.change(save_config, [lang, model_name, model_path])\n\n finetuning_type.change(\n list_checkpoint, [model_name, finetuning_type], [checkpoints]\n ).then(\n can_quantize, [finetuning_type], [quantization_bit]\n )\n\n refresh_btn.click(\n list_checkpoint, [model_name, finetuning_type], [checkpoints], queue=False\n )\n\n return dict(\n lang=lang,\n model_name=model_name,\n model_path=model_path,\n finetuning_type=finetuning_type,\n checkpoints=checkpoints,\n refresh_btn=refresh_btn,\n advanced_tab=advanced_tab,\n quantization_bit=quantization_bit,\n template=template,\n system_prompt=system_prompt\n )\n","repo_name":"SupritYoung/Zhongjing","sub_path":"src/llmtuner/webui/components/top.py","file_name":"top.py","file_ext":"py","file_size_in_byte":2255,"program_lang":"python","lang":"en","doc_type":"code","stars":171,"dataset":"github-code","pt":"60"} +{"seq_id":"13360825447","text":"from flask import Flask\nfrom cricbuzz.config import config_by_name\nfrom cricbuzz.model.db import db\nfrom cricbuzz.api import api_v1\nfrom cricbuzz.utils.error_handlers import not_found_error, global_error_handler\nfrom sqlalchemy_utils import database_exists, create_database\nfrom sqlalchemy import create_engine\nimport cricbuzz.model.models\nimport logging\n# import logging.config\n\n# log = logging.getLogger(__name__)\n\ndef create_app(config_name='dev'):\n config = config_by_name[config_name]\n app = Flask(config.APP_NAME)\n\n # app.register_error_handler(404, not_found_error)\n # app.register_error_handler(Exception, global_error_handler)\n\n app.config.from_object(config)\n app.register_blueprint(api_v1)\n\n # logging.config.fileConfig(app.config.get('LOG_CONFIG_PATH'))\n\n db_connection_uri = f\"{config.DB_DIALECT}://{config.DB_USER}:{config.DB_PASSWORD}@{config.DB_HOST}:{config.DB_PORT}/{config.DB_NAME}\"\n app.config[\"SQLALCHEMY_DATABASE_URI\"] = db_connection_uri\n app.config[\"SQLALCHEMY_TRACK_MODIFICATIONS\"] = False\n app.config[\"SQLALCHEMY_ECHO\"] = False\n\n db.init_app(app)\n\n engine = create_engine(db_connection_uri)\n logging.info(\"Checking if database exists...\")\n if not database_exists(engine.url):\n logging.info(\"Creating database...\")\n create_database(engine.url)\n\n setup_db(app)\n return app\n\n\ndef setup_db(app):\n logging.info(\"creating database tables if not exists...\")\n with app.app_context():\n db.create_all()\n\ndef main():\n app = create_app('dev')\n host = '0.0.0.0'\n port = 5000\n app.run(host=host, port=port, DEBUG = True)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"RichaSharma2720/cricbuzz","sub_path":"cricbuzz/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1663,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"60"} +{"seq_id":"28908643468","text":"# This is Server\n\nimport socket\n\nHOST = ('localhost', 10000)\n\nserver = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nserver.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\nserver.bind(HOST)\nserver.listen()\n\nprint('I am listening your connections😈')\n\nwhile True:\n connection, addr = server.accept()\n print('Connected -', addr)\n response = b\"Hello my friend!\" # encode(fmt)\n connection.send(response)\n\n connection.close()\n","repo_name":"rilistx/telegram","sub_path":"socket/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":449,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"60"} +{"seq_id":"7208617820","text":"import seaborn as sns\nimport pandas as pd\nfrom matplotlib import pyplot as plt\nimport numpy as np\n\nSOURCE = \"BTC\"\ndf = pd.read_csv(\"DATASET.CSV\", parse_dates=True, index_col=\"Date\")\n# df[\"Date\"] = pd.to_datetime(df.Date)\n# df = df.set_index(\"Date\")\n\n\ndef plot_difficulty():\n fig, axes = plt.subplots(nrows=3, ncols=1, sharex=True)\n df[[\"Close\"]].plot(ax=axes[0])\n # df[[\"BlkCnt\"]].plot(ax=axes[1], linewidth=2, color='r', linestyle='dashed')\n df[[\"BlkCnt\"]].plot(ax=axes[1])\n df[[\"DiffMean\"]].plot(ax=axes[2])\n # 'AdrActCnt', 'BlkSizeByte'\n\nif SOURCE == \"BTC\":\n # plot_difficulty()\n pass\n\n# http://atedstone.github.io/pandas-plot-seasons-time-series/\n# https://pbpython.com/pandas-pivot-table-explained.html\n'''preprocess\ndf['doy'] = df.index.dayofyear\ndf['dow'] = df.index.dayofweek\ndf['year'] = df.index.year\ndf['week'] = df.index.week\n'''\n# piv = pd.pivot_table(df, index=['doy'], columns=['year'], values=['Close'])\n# piv = pd.pivot_table(df, index=['dow'], columns=['week'], values=['Close'], fill_value=0)\npiv = pd.pivot_table(df, index=['Dow'], columns=['Week'], values=['Close'], fill_value=0)\n\nperiod_average = piv.fillna(method='ffill')\n# period_average = piv.fillna(method='pad')\nperiod_average = period_average.apply(lambda x: np.mean(x), axis=1)\nperiod_average = period_average.reset_index()\n# period_average.plot(x='doy')\nperiod_average.plot(x='Dow')\n\npiv[\"period_average\"] = period_average[0]\n# yearly plot\n'''\n\n## generate the sequence with a step of 100 milliseconds\ndf_times = pd.date_range(t0, t1, freq = '100L', tz= \"UTC\")\n\n# piv[\"date_range\"] = pd.date_range(\"2019-01-01\", \"2019-12-31\")\npiv[\"date_range\"] = pd.date_range(\"2019-01-01\", \"2020-01-01\")\npiv.plot(logy=True, legend=True, x=\"date_range\")\n'''\n\n'''\n# weekly plot\n'''\nax = piv.plot(logy=True, legend=False)\n# ax.set_xticks(piv.index)\n# ax.set_xticklabels([\"Mon\", \"Tue\", \"Wed\", \"Thu\", \"Fri\", \"Sat\", \"Sun\"], rotation=0)\n\nplt.show()\n","repo_name":"devcon14/timeseries-lab","sub_path":"btc_difficulty_seasonal_pivot.py","file_name":"btc_difficulty_seasonal_pivot.py","file_ext":"py","file_size_in_byte":1932,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"60"} +{"seq_id":"28463760347","text":"APP_TITLE = \"Test app\"\n\nDRAW_SCALE = 100\nCOOR_TEXT = \"x: {}\\ny: {}\"\nGRID_PRECISIONS = tuple(i / 10 for i in range(1, 11, 1))\n\ndef get_color(r_ratio: float, g_ratio: float, b_ratio: float, rate: float=1):\n # apply rate\n def apply_rate(color_ratio: float) -> float:\n return (1 * (1 - rate)) + (color_ratio * rate)\n\n # convert [0; 1] to hexa\n r = min(round(apply_rate(r_ratio) * 256), 255)\n g = min(round(apply_rate(g_ratio) * 256), 255)\n b = min(round(apply_rate(b_ratio) * 256), 255)\n\n return '#{:02x}{:02x}{:02x}'.format(r, g, b)\n\nORIGIN_COLOR = \"darkgreen\"\nTARGET_COLOR = \"darkblue\"\nASTAR_COLOR = \"violet\"\nNOGRID_COLOR = \"green\"\nGRID_COLOR = \"lightgray\"\nOBSTACLE_COLOR_GETTER = lambda rate: get_color(.9, .5, .5, rate=rate)\nOBSTACLE_BORDER_COLOR = \"red\"\n\nNODE_RADIUS = 5\nNODE_WIDTH = 3\n\nLABEL_FRAME_KWARGS = {\"side\": \"top\", \"fill\": \"x\", \"expand\": \"yes\"}\nCOOR_INNER_FRAME_KWARGS = {\"side\": \"left\", \"fill\": \"x\", \"expand\": \"yes\", \"ipadx\": 5, \"ipady\": 5, \"padx\": 5, \"pady\": 5}\n\n\nget_color(0, 0, 1)\nget_color(.1, .2, .1)","repo_name":"EMarquer/nogrid-pathfinder","sub_path":"gui/const.py","file_name":"const.py","file_ext":"py","file_size_in_byte":1044,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"60"} +{"seq_id":"70607948672","text":"# -*- coding: utf-8 -*-\nfrom logging import getLogger\nfrom logging import getLogger, StreamHandler, NullHandler, DEBUG, ERROR\nimport numpy as np\nimport numpy as np\nimport pandas as pd\n\nfrom accelbrainbase.computableloss._torch.l2_norm_loss import L2NormLoss\nfrom accelbrainbase.extractabledata.unlabeled_csv_extractor import UnlabeledCSVExtractor\nfrom accelbrainbase.iteratabledata._torch.unlabeled_sequential_csv_iterator import UnlabeledSequentialCSVIterator\nfrom accelbrainbase.noiseabledata._torch.gauss_noise import GaussNoise\nfrom accelbrainbase.observabledata._torch.lstm_networks import LSTMNetworks\nfrom accelbrainbase.observabledata._torch.lstmnetworks.encoder_decoder import EncoderDecoder\n\nfrom pysummarization.abstractable_semantics import AbstractableSemantics\nfrom pysummarization.vectorizable_token import VectorizableToken\n\nimport torch\n\n\nclass EncDecAD(AbstractableSemantics):\n '''\n LSTM-based Encoder/Decoder scheme for Anomaly Detection (EncDec-AD).\n\n This library applies the Encoder-Decoder scheme for Anomaly Detection (EncDec-AD)\n to text summarizations by intuition. In this scheme, LSTM-based Encoder/Decoder \n or so-called the sequence-to-sequence(Seq2Seq) model learns to reconstruct normal time-series behavior,\n and thereafter uses reconstruction error to detect anomalies.\n \n Malhotra, P., et al. (2016) showed that EncDecAD paradigm is robust and \n can detect anomalies from predictable, unpredictable, periodic, aperiodic, \n and quasi-periodic time-series. Further, they showed that the paradigm is able to \n detect anomalies from short time-series (length as small as 30) as well as long \n time-series (length as large as 500).\n\n This library refers to the intuitive insight in relation to the use case of \n reconstruction error to detect anomalies above to apply the model to text summarization.\n As exemplified by Seq2Seq paradigm, document and sentence which contain tokens of text\n can be considered as time-series features. The anomalies data detected by EncDec-AD \n should have to express something about the text.\n\n From the above analogy, this library introduces two conflicting intuitions. On the one hand,\n the anomalies data may catch observer's eye from the viewpoints of rarity or amount of information\n as the indicator of natural language processing like TF-IDF shows. On the other hand,\n the anomalies data may be ignorable noise as mere outlier.\n \n In any case, this library deduces the function and potential of EncDec-AD in text summarization\n is to draw the distinction of normal and anomaly texts and is to filter the one from the other.\n\n References:\n - Malhotra, P., Ramakrishnan, A., Anand, G., Vig, L., Agarwal, P., & Shroff, G. (2016). LSTM-based encoder-decoder for multi-sensor anomaly detection. arXiv preprint arXiv:1607.00148.\n '''\n\n # Logs of accuracy.\n __logs_tuple_list = []\n\n __ctx = \"cpu\"\n\n def get_ctx(self):\n ''' getter for `mx.gpu()` or `mx.cpu()`. '''\n return self.__ctx\n\n def set_ctx(self, value):\n ''' setter for `mx.gpu()` or `mx.cpu()`. '''\n self.__ctx = value\n\n ctx = property(get_ctx, set_ctx)\n\n def __init__(\n self, \n computable_loss=None,\n normal_prior_flag=False,\n encoder_decoder_controller=None,\n hidden_neuron_count=20,\n output_neuron_count=20,\n dropout_rate=0.5,\n epochs=100,\n learning_rate=1e-05,\n seq_len=8,\n ctx=\"cpu\",\n initializer_f=None,\n optimizer_f=None,\n ):\n '''\n Init.\n\n Args:\n computable_loss: is-a `ComputableLoss`.\n normal_prior_flag: If `True`, this class will select abstract sentence\n from sentences with low reconstruction error.\n\n encoder_decoder_controller: is-a `EncoderDecoderController`.\n hidden_neuron_count: The number of units in hidden layers.\n output_neuron_count: The number of units in output layers.\n\n dropout_rate: Probability of dropout.\n epochs: The epochs in mini-batch training Encoder/Decoder and retrospective encoder.\n batch_size: Batch size.\n learning_rate: Learning rate.\n learning_attenuate_rate: Attenuate the `learning_rate` by a factor of this value every `attenuate_epoch`.\n attenuate_epoch: Attenuate the `learning_rate` by a factor of `learning_attenuate_rate` every `attenuate_epoch`.\n \n\n seq_len: The length of sequneces in Decoder with Attention model.\n\n '''\n if computable_loss is None:\n computable_loss = L2NormLoss()\n\n self.ctx = ctx\n self.__normal_prior_flag = normal_prior_flag\n if encoder_decoder_controller is None:\n encoder_decoder_controller = self.__build_encoder_decoder_controller(\n computable_loss=computable_loss,\n hidden_neuron_count=hidden_neuron_count,\n output_neuron_count=output_neuron_count,\n dropout_rate=dropout_rate,\n learning_rate=learning_rate,\n seq_len=seq_len,\n initializer_f=initializer_f,\n optimizer_f=optimizer_f,\n )\n else:\n if isinstance(encoder_decoder_controller, EncoderDecoderController) is False:\n raise TypeError()\n\n self.__encoder_decoder_controller = encoder_decoder_controller\n\n logger = getLogger(\"accelbrainbase\")\n self.__logger = logger\n self.__logs_tuple_list = []\n self.__computable_loss = computable_loss\n\n def __build_encoder_decoder_controller(\n self,\n computable_loss=None,\n hidden_neuron_count=20,\n output_neuron_count=20,\n dropout_rate=0.5,\n epochs=1000,\n learning_rate=1e-05,\n seq_len=8,\n initializer_f=None,\n optimizer_f=None,\n ):\n encoder = LSTMNetworks(\n initializer_f=initializer_f,\n optimizer_f=optimizer_f,\n # is-a `ComputableLoss` or `mxnet.gluon.loss`.\n computable_loss=computable_loss,\n # `int` of the length of series.\n seq_len=seq_len,\n # `int` of the number of units in hidden layer.\n hidden_n=hidden_neuron_count,\n # `float` of dropout rate.\n dropout_rate=dropout_rate,\n # `bool` that means this class has output layer or not.\n output_layer_flag=False,\n # `mx.cpu()` or `mx.gpu()`.\n ctx=self.ctx,\n )\n\n decoder = LSTMNetworks(\n initializer_f=initializer_f,\n optimizer_f=optimizer_f,\n # is-a `ComputableLoss` or `mxnet.gluon.loss`.\n computable_loss=computable_loss,\n # `int` of the length of series.\n seq_len=seq_len,\n # `int` of the number of units in hidden layer.\n hidden_n=hidden_neuron_count,\n # `int` of the number of units in output layer.\n output_n=output_neuron_count,\n # `float` of dropout rate.\n dropout_rate=dropout_rate,\n # `bool` that means this class has output layer or not.\n output_layer_flag=True,\n # `bool` for using bias or not in output layer(last hidden layer).\n output_no_bias_flag=True,\n # `mx.cpu()` or `mx.gpu()`.\n ctx=self.ctx,\n )\n\n encoder_decoder_controller = EncoderDecoder(\n # is-a `LSTMNetworks`.\n encoder=encoder,\n # is-a `LSTMNetworks`.\n decoder=decoder,\n # is-a `ComputableLoss` or `mxnet.gluon.loss`.\n computable_loss=computable_loss,\n # `float` of learning rate.\n learning_rate=learning_rate,\n # `mx.cpu()` or `mx.gpu()`.\n ctx=self.ctx,\n )\n self.__computable_loss = computable_loss\n return encoder_decoder_controller\n\n def learn(self, iteratable_data):\n '''\n Learn the observed data points\n for vector representation of the input time-series.\n\n Args:\n iteratable_data: is-a `IteratableData`.\n\n '''\n self.__encoder_decoder_controller.learn(iteratable_data)\n\n def inference(self, observed_arr):\n '''\n Infernece by the model.\n\n Args:\n observed_arr: `np.ndarray` of observed data points.\n\n Returns:\n `np.ndarray` of inferenced feature points.\n '''\n\n if isinstance(observed_arr, torch.Tensor) is False:\n observed_arr = torch.from_numpy(observed_arr)\n observed_arr = observed_arr.to(self.ctx)\n return self.__encoder_decoder_controller.inference(observed_arr)\n\n def summarize(self, iteratable_data, vectorizable_token, sentence_list, limit=5):\n '''\n Summarize input document.\n\n Args:\n iteratable_data: is-a `IteratableData`.\n vectorizable_token: is-a `VectorizableToken`.\n sentence_list: `list` of all sentences.\n limit: The number of selected abstract sentence.\n \n Returns:\n `np.ndarray` of scores.\n '''\n if isinstance(vectorizable_token, VectorizableToken) is False:\n raise TypeError()\n\n _score_arr = None\n _test_arr = None\n for _, _, test_arr, _ in iteratable_data.generate_inferenced_samples():\n reconstruced_arr = self.inference(test_arr)\n score_arr = self.__computable_loss(test_arr, reconstruced_arr)\n score_arr = score_arr.to('cpu').detach().numpy().copy()\n\n if _score_arr is None:\n _score_arr = score_arr\n else:\n _score_arr = np.r_[_score_arr, score_arr]\n if _test_arr is None:\n _test_arr = test_arr.to('cpu').detach().numpy().copy()\n else:\n _test_arr = np.r_[_test_arr, test_arr.to('cpu').detach().numpy().copy()]\n\n score_list = _score_arr.tolist()\n test_arr = _test_arr\n score_arr = _score_arr\n\n abstract_list = []\n for i in range(limit):\n if self.__normal_prior_flag is True:\n key = score_arr.argmin()\n else:\n key = score_arr.argmax()\n\n score = score_list.pop(key)\n score_arr = np.array(score_list)\n\n seq_arr = test_arr[key]\n token_arr = vectorizable_token.tokenize(seq_arr.tolist())\n s = \" \".join(token_arr.tolist())\n _s = \"\".join(token_arr.tolist())\n\n for sentence in sentence_list:\n if s in sentence or _s in sentence:\n abstract_list.append(sentence)\n abstract_list = list(set(abstract_list))\n else:\n hit_n = 0\n for token in token_arr.tolist():\n if token in sentence:\n hit_n += 1\n if hit_n == len(token_arr.tolist()):\n abstract_list.append(sentence)\n abstract_list = list(set(abstract_list))\n\n if len(abstract_list) >= limit:\n break\n\n return abstract_list\n\n def set_readonly(self, value):\n ''' setter '''\n raise TypeError()\n\n def get_encoder_decoder_controller(self):\n ''' getter '''\n return self.__encoder_decoder_controller\n\n encoder_decoder_controller = property(get_encoder_decoder_controller, set_readonly)\n","repo_name":"accel-brain/accel-brain-code","sub_path":"Automatic-Summarization/pysummarization/abstractablesemantics/_torch/enc_dec_ad.py","file_name":"enc_dec_ad.py","file_ext":"py","file_size_in_byte":11881,"program_lang":"python","lang":"en","doc_type":"code","stars":288,"dataset":"github-code","pt":"60"} +{"seq_id":"24378987343","text":"\"\"\"Weighting preprocessor module.\"\"\"\n\nimport logging\n\nimport iris\n\nfrom ._supplementary_vars import register_supplementaries\n\nlogger = logging.getLogger(__name__)\n\n\ndef _get_land_fraction(cube):\n \"\"\"Extract land fraction as :mod:`dask.array`.\"\"\"\n fx_cube = None\n land_fraction = None\n errors = []\n try:\n fx_cube = cube.ancillary_variable('land_area_fraction')\n except iris.exceptions.AncillaryVariableNotFoundError:\n try:\n fx_cube = cube.ancillary_variable('sea_area_fraction')\n except iris.exceptions.AncillaryVariableNotFoundError:\n errors.append('Ancillary variables land/sea area fraction not '\n 'found in cube. Check ancillary data availability.')\n return (land_fraction, errors)\n\n if fx_cube.var_name == 'sftlf':\n land_fraction = fx_cube.core_data() / 100.0\n if fx_cube.var_name == 'sftof':\n land_fraction = 1.0 - fx_cube.core_data() / 100.0\n\n return (land_fraction, errors)\n\n\n@register_supplementaries(\n variables=['sftlf', 'sftof'],\n required='require_at_least_one',\n)\ndef weighting_landsea_fraction(cube, area_type):\n \"\"\"Weight fields using land or sea fraction.\n\n This preprocessor function weights a field with its corresponding land or\n sea area fraction (value between 0 and 1). The application of this is\n important for most carbon cycle variables (and other land-surface outputs),\n which are e.g. reported in units of `kgC m-2`. This actually refers to 'per\n square meter of land/sea' and NOT 'per square meter of gridbox'. So in\n order to integrate these globally or regionally one has to both area-weight\n the quantity but also weight by the land/sea fraction.\n\n Parameters\n ----------\n cube : iris.cube.Cube\n Data cube to be weighted. It should have an\n :class:`iris.coords.AncillaryVariable` with standard name\n ``'land_area_fraction'`` or ``'sea_area_fraction'``. If both are\n present, only the ``'land_area_fraction'`` will be used.\n area_type : str\n Use land (``'land'``) or sea (``'sea'``) fraction for weighting.\n\n Returns\n -------\n iris.cube.Cube\n Land/sea fraction weighted cube.\n\n Raises\n ------\n TypeError\n ``area_type`` is not ``'land'`` or ``'sea'``.\n ValueError\n Land/sea fraction variables ``sftlf`` or ``sftof`` not found.\n \"\"\"\n if area_type not in ('land', 'sea'):\n raise TypeError(\n f\"Expected 'land' or 'sea' for area_type, got '{area_type}'\")\n (land_fraction, errors) = _get_land_fraction(cube)\n if land_fraction is None:\n raise ValueError(\n f\"Weighting of '{cube.var_name}' with '{area_type}' fraction \"\n f\"failed because of the following errors: {' '.join(errors)}\")\n core_data = cube.core_data()\n if area_type == 'land':\n cube.data = core_data * land_fraction\n elif area_type == 'sea':\n cube.data = core_data * (1.0 - land_fraction)\n return cube\n","repo_name":"ESMValGroup/ESMValCore","sub_path":"esmvalcore/preprocessor/_weighting.py","file_name":"_weighting.py","file_ext":"py","file_size_in_byte":3010,"program_lang":"python","lang":"en","doc_type":"code","stars":35,"dataset":"github-code","pt":"60"} +{"seq_id":"32941822171","text":"#!/usr/bin/python3\n\n\"\"\" Python Module that inserts a line of text to a file,\nafter each line containing a specific string\n\"\"\"\n\n\ndef append_after(filename=\"\", search_string=\"\", new_string=\"\"):\n \"\"\" Function that inserts a line of text to a file,\n after each line containing a specific string \"\"\"\n\n with open(filename, mode=\"r+\", encoding=\"utf-8\") as opf:\n tex = opf.readlines()\n\n num = 0\n with open(filename, mode=\"w\", encoding=\"utf-8\") as wrf:\n for lines in tex:\n num += 1\n if search_string in lines:\n tex.insert(num, new_string)\n for lines in tex:\n wrf.write(lines)\n","repo_name":"dot-eagle/alx-higher_level_programming","sub_path":"0x0B-python-input_output/100-append_after.py","file_name":"100-append_after.py","file_ext":"py","file_size_in_byte":651,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"60"} +{"seq_id":"42222844033","text":"# pylint: disable=anomalous-backslash-in-string\n# pylint: disable=line-too-long, invalid-name\n\"\"\"Hindi IPA pronunciation module. Implements template {{hi-IPA}}.\nModified from https://en.wiktionary.org/wiki/Module:hi-IPA Lua module partially.\n\"\"\"\n\nfrom __future__ import print_function\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport regex as re\nfrom .hi_translit import transliterate\n\n\ncorrespondences = {\n \"ṅ\": \"ŋ\", \"g\": \"ɡ\",\n \"c\": \"t͡ʃ\", \"j\": \"d͡ʒ\", \"ñ\": \"ɲ\",\n \"ṭ\": \"ʈ\", \"ḍ\": \"ɖ\", \"ṇ\": \"ɳ\",\n \"t\": \"t̪\", \"d\": \"d̪\",\n \"y\": \"j\", \"r\": \"ɾ\", \"v\": \"ʋ\", \"l\": \"l̪\",\n \"ś\": \"ʃ\", \"ṣ\": \"ʃ\", \"h\": \"ɦ\",\n \"ṛ\": \"ɽ\", \"ž\": \"ʒ\", \"ḻ\": \"ɭ\", \"ġ\": \"ɡ\",\n \"q\": \"k\", \"x\": \"kʰ\", \"ṉ\": \"n\", \"ṟ\": \"ɹ\",\n\n \"a\": \"ə\", \"ā\": \"ɑː\", \"i\": \"ɪ\",\n \"ī\": \"iː\", \"o\": \"oː\", \"e\": \"eː\", \"ŕ\": \"ɾɪ\",\n \"u\": \"ʊ\", \"ū\": \"uː\", \"ŏ\": \"ɔ\", \"ĕ\": \"æː\",\n\n \"ũ\": \"ʊ̃\", \"õ\": \"õː\", \"ã\": \"ə̃\", \"ā̃\": \"ɑ̃ː\",\n\n \"ॐ\": \"oːm\", \"ḥ\": \"ʰ\",\n # get rid of spaces\n \" \": \"\",\n}\n\nidentical = \"knlsfzθ\"\nfor char in identical:\n correspondences[char] = char\n\nvowels = \"aāiīuūoɔɛeæ\"\nweak_h = \"([gjdḍbṛnmaãāā̃eẽiĩīī̃uũūū̃oõː])h\"\naspirate = \"([kctṭp])\"\nsyllabify_pattern = \"([\" + vowels + \"])\" + \\\n \"([^\" + vowels + \"\\.]?)\" + \\\n \"([^\" + vowels + \"\\.]+)\" + \\\n \"([\" + vowels + \"])\"\n\n\ndef syllabify(text):\n def repl(match):\n a, b, c, d = \\\n match.group(1), match.group(2), match.group(3), match.group(4)\n if re.match(weak_h, b + c) or re.match(aspirate + \"h\", b + \" \" + c):\n b, c = \"\", b + c\n if c == \"\" and b != \"\":\n c, b = b, \"\"\n return a + b + \".\" + c + d\n\n for _ in range(2):\n text = re.sub(syllabify_pattern, repl, text)\n return text\n\ndef to_IPA(text):\n \"\"\"Generates Hindi IPA from spelling.\n\n Implements template `{{hi-IPA}}`_.\n\n .. _{{hi-IPA}}: https://en.wiktionary.org/wiki/Template:hi-IPA\n\n Parameters\n ----------\n text : string\n String of hi-IPA text parsed in `{{hi-IPA}}`_ from Wiktionary.\n\n Returns\n -------\n string\n Converted Hindi IPA.\n\n Notes\n -----\n - Modified from `Wiktioanry hi-IPA Lua module`_ partially.\n - Testcases are modified from `Wiktionary hi-IPA/testcases`_.\n\n .. _Wiktioanry hi-IPA Lua module: https://en.wiktionary.org/wiki/Module:hi-IPA\n .. _Wiktionary hi-IPA/testcases: https://en.wiktionary.org/wiki/Module:hi-IPA/testcases\n\n Examples\n --------\n >>> hi_text = \"मैं\" # hi: [[मैं]]\n >>> hi_IPA = hi_pron.to_IPA(hi_text)\n >>> hi_IPA\n \"mɛ̃ː\"\n \"\"\"\n translit = transliterate(text)\n if not translit:\n return \"\"\n\n translit = re.sub(\"͠\", \"̃\", translit)\n translit = re.sub(\"a(̃?)i\", r\"ɛ\\1ː\", translit)\n translit = re.sub(\"a(̃?)u\", r\"ɔ\\1ː\", translit)\n translit = re.sub(\"\\-\", \".\", translit)\n\n translit = syllabify(translit)\n translit = re.sub(\"jñ\", \"gy\", translit)\n translit = re.sub(\"ah\", \"ɛːʱ\", translit)\n translit = re.sub(aspirate + \"h\", r\"\\1ʰ\", translit)\n translit = re.sub(weak_h, r\"\\1ʱ\", translit)\n translit = re.sub(\"\\.ː\", \"ː.\", translit)\n\n result = []\n for ch in translit:\n if ch in correspondences.keys():\n result.append(correspondences[ch])\n else:\n result.append(ch)\n return \"\".join(result)\n","repo_name":"abuccts/wikt2pron","sub_path":"pywiktionary/IPA/hi_pron.py","file_name":"hi_pron.py","file_ext":"py","file_size_in_byte":3472,"program_lang":"python","lang":"en","doc_type":"code","stars":30,"dataset":"github-code","pt":"60"} +{"seq_id":"38855714618","text":"import math\nm,n=map(int,input().split())\nfor _ in range(m):\n num=int(input())\n if(num<0):\n print(\"no\")\n else:\n a=int((num)**0.5)\n #print(num-(a*a))\n #print(0.01*n*num)\n if((num-(a*a))<=(0.01*n*num)):\n print(\"yes\")\n else:\n print(\"no\")","repo_name":"ranveerrajput/Codechef","sub_path":"ROOTSQR.py","file_name":"ROOTSQR.py","file_ext":"py","file_size_in_byte":298,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"60"} +{"seq_id":"2522686237","text":"# Problem Id: 面试题 02.03\n# Problem Name: Delete Middle Node LCCI, 删除中间节点\n# Problem Url: https://leetcode-cn.com/problems/delete-middle-node-lcci/\n# Problem Level: Easy\n# Language: Python3\n \n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution:\n def deleteNode(self, node):\n \"\"\"\n :type node: ListNode\n :rtype: void Do not return anything, modify node in-place instead.\n \"\"\"\n t = node\n while t.next:\n t.val = t.next.val\n if not t.next.next:\n t.next = None\n break\n t = t.next\n \n ","repo_name":"siru-xiong/leetcode-solutions","sub_path":"solutions/面试题02.03-删除中间节点.py","file_name":"面试题02.03-删除中间节点.py","file_ext":"py","file_size_in_byte":721,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"60"} +{"seq_id":"41828891005","text":"from utils.config import load_config\nfrom utils.args import parse_args\nfrom tasks.index import task_index\n\nargs = parse_args()\ntask = args.task\n\nconfig_path = args.config\nconfig = load_config(config_path, task)\n\nprint(f\"Running a {task} VAE.\")\nif (\n task in task_index.keys()\n): # check if the provided task is included in the list of tasks\n task_obj = task_index[task] # collect the task object from the task index\n task = task_obj(\n config\n ) # initialize the task object from the provided environment config\n task.run() # run the task run() function\nelse:\n raise ValueError(f\"The task '{task}' is not in the task index.\")\n","repo_name":"data4help/crispy-train","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":654,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"60"} +{"seq_id":"44647701570","text":"class Solution:\n # @param A : list of integers\n # @param B : integer\n # @param C : integer\n # @param D : integer\n # @return an integer\n def solve(self, A, B, C, D):\n N = len(A)\n\n b_max = c_max = d_max = -5e9\n\n for i in range(1, N + 1):\n b_max = max(b_max, B * A[i - 1])\n c_max = max(c_max, b_max + C * A[i - 1])\n d_max = max(d_max, c_max + D * A[i - 1])\n\n return d_max\n","repo_name":"0xStryK3R/Scaler-DSA-Revision","sub_path":"python/Day-69/HW_4.py","file_name":"HW_4.py","file_ext":"py","file_size_in_byte":448,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"60"} +{"seq_id":"9590822570","text":"# -*- coding: utf-8\nfrom __future__ import unicode_literals, absolute_import\nimport os\n\nimport django\n\nROOT_DIR = os.getcwd()\nAPPS_DIR = os.path.join(ROOT_DIR, \"genome\")\n\nDEBUG = True\nUSE_TZ = True\n\n# SECURITY WARNING: keep the secret key used in production secret!\nSECRET_KEY = \"gpz*kbklvx1=18(8r^x=o39u1$d6cewfb@237yv7c!+$e7aruo\"\n\nDATABASES = {\n \"default\": {\n \"ENGINE\": \"django.db.backends.sqlite3\",\n \"NAME\": \"testing.db\",\n }\n}\n\nROOT_URLCONF = \"tests.urls\"\n\nINSTALLED_APPS = [\n \"django.contrib.auth\",\n \"django.contrib.contenttypes\",\n \"django.contrib.sessions\",\n \"django.contrib.sites\",\n \"django.contrib.staticfiles\",\n \"django.contrib.admin\",\n \"django.contrib.messages\",\n\n \"genome\",\n\n \"rest_framework\",\n \"django_filters\",\n]\n\nSITE_ID = 1\n\nDJANGO_MIDDLEWARE = [\n 'django.middleware.security.SecurityMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n]\n\nif django.VERSION >= (1, 10):\n MIDDLEWARE = DJANGO_MIDDLEWARE\nelse:\n MIDDLEWARE_CLASSES = DJANGO_MIDDLEWARE\n\n# TEMPLATE CONFIGURATION\n# ------------------------------------------------------------------------------\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#templates\nTEMPLATES = [\n {\n # See: https://docs.djangoproject.com/en/dev/ref/settings/#std:setting-TEMPLATES-BACKEND\n 'BACKEND': 'django.template.backends.django.DjangoTemplates',\n # See: https://docs.djangoproject.com/en/dev/ref/settings/#template-dirs\n 'DIRS': [\n os.path.join(ROOT_DIR, 'templates'),\n os.path.join(APPS_DIR, 'templates'),\n ],\n 'OPTIONS': {\n # See: https://docs.djangoproject.com/en/dev/ref/settings/#template-debug\n 'debug': DEBUG,\n # See: https://docs.djangoproject.com/en/dev/ref/settings/#template-loaders\n # https://docs.djangoproject.com/en/dev/ref/templates/api/#loader-types\n 'loaders': [\n 'django.template.loaders.filesystem.Loader',\n 'django.template.loaders.app_directories.Loader',\n ],\n # See: https://docs.djangoproject.com/en/dev/ref/settings/#template-context-processors\n 'context_processors': [\n 'django.template.context_processors.debug',\n 'django.template.context_processors.request',\n 'django.contrib.auth.context_processors.auth',\n 'django.template.context_processors.i18n',\n 'django.template.context_processors.media',\n 'django.template.context_processors.static',\n 'django.template.context_processors.tz',\n 'django.contrib.messages.context_processors.messages',\n # Your stuff: custom template context processors go here\n ],\n },\n },\n]\n\nSTATIC_URL = '/static/'\n\nREST_FRAMEWORK = {\n 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination',\n 'PAGE_SIZE': 100,\n}\n\nLOGGING = {\n 'version': 1,\n 'disable_existing_loggers': False,\n 'formatters': {\n 'simple': {\n 'format': '%(levelname)s %(message)s'\n },\n },\n 'handlers': {\n 'log_to_stdout': {\n 'level': 'DEBUG',\n 'class': 'logging.StreamHandler',\n 'formatter': 'simple',\n },\n },\n 'loggers': {\n 'genome.management.commands.genome_sync': {\n 'handlers': ['log_to_stdout'],\n 'level': 'DEBUG',\n 'propagate': True,\n }\n }\n}\n","repo_name":"chopdgd/django-genome","sub_path":"tests/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":3800,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"60"} +{"seq_id":"30722010040","text":"#! python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jan 30 21:57:00 2018\n@author: Saif Kurdi-Teylouni\n\"\"\"\nfrom storer.storer import storeUser, retrieveUser, retrieveUsersByTeam, storeLaw, deleteLaw, retrieveLaw, updateLaw, storeArchive, updateArchive, retrieveBill\nfrom collections import namedtuple\nfrom .team import User\nfrom .html_template import Template\nimport jsonpickle, re\n\nclass Update(object):\n\n \"\"\"username = ''\n identifier = ''\n lastUpdate= ''\n \"\"\"\n\n def __init__(self, username, identifier, lastUpdate):\n self.username=username\n self.identifier=identifier\n self.lastUpdate=lastUpdate\n\n def get_Content(self):\n return self.lastUpdate\n\nclass Information( object ):\n\n \"\"\"legislature=\"NONE\"\n bills=[]\"\"\"\n\n def __init__(self):\n self.users=[]\n\n def set_users(self, users):\n self.users=users\n\n def build_archives(self):\n for user in self.users:\n self.build_update_by_user(user)\n\n def takeLatestDateofBill(billupdate):\n if billupdate[0] and len(billupdate[0].events)!=0:\n if billupdate[0].events[-1][\"date\"]!=\"N/A\":\n key=billupdate[0].legislature+billupdate[0].events[-1][\"date\"]\n else:\n key=billupdate[0].legislature\n return key\n return \"AAA\"\n\n def build_update_by_user(self, user):\n updatetext=\"\"\n billupdates=[]\n for lawname in user.lawnames:\n strippedlawname=user.LawNamefromOfficaltoBill(lawname)\n cachedLaw=retrieveLaw(strippedlawname)\n if cachedLaw!=None:\n bills=cachedLaw.getDependantBills()\n for billid in bills:\n bill=retrieveBill(billid)\n billupdate=(bill, strippedlawname)\n billupdates.append(billupdate)\n billupdates.sort(key=Information.takeLatestDateofBill, reverse=True)\n for billupdate in billupdates:\n updatetext+=self.build_update(user, billupdate[0], billupdate[1])\n html=self.inject_update_in_template(updatetext)\n update=Update(user.username, user.username, html)\n storeArchive(update)\n\n def build_update(self, user, bill, cachedLaw):\n #build html src code\n if bill==None:\n return \"\"\n if bill.legislature==\"GazetteQuébec\":\n billno=bill.title.split(\"_\")[0]\n else:\n billno=bill.title.strip(bill.legislature)\n if len(bill.events)!=0:\n stage=bill.events[-1][\"stage\"]\n date=bill.events[-1][\"date\"]\n else:\n stage=\"N/A\"\n date=\"N/A\"\n hyperlink=\"N/A\"\n if hasattr(bill, 'hyperlink'):\n hyperlink=\"Content\"\n lawtitle=bill.legislature+\" - \" +cachedLaw.split(\"(\")[0]\n html=\" \\r\\n\"\\\n \t\t\" \"+billno+\"\\r\\n\"\\\n \t\t\" \"+lawtitle+\"\\r\\n\"\\\n \t\t\" \"+stage+\"\\r\\n\"\\\n \t\t\" \"+date+\"\\r\\n\"\\\n \t\t\" \"+bill.legislature+\"\\r\\n\"\\\n \t\t\" \"+hyperlink+\"\\r\\n\"\\\n \t\t\" \\r\\n\"\n return html\n\n def inject_update_in_template(self, updatetext):\n return Template.emailStart+Template.rowfont+updatetext+Template.emailEnd\n\n def addUser(self, user):\n self.users.append(user)\n\n def getUsers(self):\n return self.users\n","repo_name":"teylouniseif/Lexamind","sub_path":"Lexamind/Scraper/account_manager/displayer.py","file_name":"displayer.py","file_ext":"py","file_size_in_byte":5231,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"60"} +{"seq_id":"21832044241","text":"for _ in range(int(input())):\n n = int(input())\n arr = list(map(int,input().rstrip().split(\" \")))\n arr.sort()\n temp = 0\n sum = 0\n n = len(arr)-1\n for i in range(len(arr)//2):\n if temp != 0:\n sum += temp-arr[i]\n sum += arr[n] - arr[i]\n temp = arr[n]\n n -= 1\n sum += temp-arr[0]\n \n print(sum)\n","repo_name":"deepak01-Hacker/DAily-Practice","sub_path":"minimum sum of absolute pair.py","file_name":"minimum sum of absolute pair.py","file_ext":"py","file_size_in_byte":360,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"60"} +{"seq_id":"1729558564","text":"# -*- coding: utf-8 -*-\n\"\"\"\nGeneral purpose functions for the br_anatel_telefonia_movel project of the pipelines\n\"\"\"\n# pylint: disable=too-few-public-methods,invalid-name\n\nimport os\nfrom io import BytesIO\nfrom pathlib import Path\nfrom urllib.request import urlopen\nfrom zipfile import ZipFile\n\nimport numpy as np\nimport pandas as pd\n\n\ndef download_and_unzip(url, path):\n \"\"\"download and unzip a zip file\n\n Args:\n url (str): a url\n\n\n Returns:\n list: unziped files in a given folder\n \"\"\"\n\n os.system(f\"mkdir -p {path}\")\n\n http_response = urlopen(url)\n zipfile = ZipFile(BytesIO(http_response.read()))\n zipfile.extractall(path=path)\n\n return path\n\n\ndef to_partitions_microdados(\n data: pd.DataFrame, partition_columns: list[str], savepath: str\n):\n \"\"\"Save data in to hive patitions schema, given a dataframe and a list of partition columns.\n Args:\n data (pandas.core.frame.DataFrame): Dataframe to be partitioned.\n partition_columns (list): List of columns to be used as partitions.\n savepath (str, pathlib.PosixPath): folder path to save the partitions\n Exemple:\n data = {\n \"ano\": [2020, 2021, 2020, 2021, 2020, 2021, 2021,2025],\n \"mes\": [1, 2, 3, 4, 5, 6, 6,9],\n \"sigla_uf\": [\"SP\", \"SP\", \"RJ\", \"RJ\", \"PR\", \"PR\", \"PR\",\"PR\"],\n \"dado\": [\"a\", \"b\", \"c\", \"d\", \"e\", \"f\", \"g\",'h'],\n }\n to_partitions(\n data=pd.DataFrame(data),\n partition_columns=['ano','mes','sigla_uf'],\n savepath='partitions/'\n )\n \"\"\"\n\n if isinstance(data, (pd.core.frame.DataFrame)):\n savepath = Path(savepath)\n\n # create unique combinations between partition columns\n unique_combinations = (\n data[partition_columns]\n .drop_duplicates(subset=partition_columns)\n .to_dict(orient=\"records\")\n )\n\n for filter_combination in unique_combinations:\n patitions_values = [\n f\"{partition}={value}\"\n for partition, value in filter_combination.items()\n ]\n\n # get filtered data\n df_filter = data.loc[\n data[filter_combination.keys()]\n .isin(filter_combination.values())\n .all(axis=1),\n :,\n ]\n df_filter = df_filter.drop(columns=partition_columns)\n\n # create folder tree\n filter_save_path = Path(savepath / \"/\".join(patitions_values))\n filter_save_path.mkdir(parents=True, exist_ok=True)\n file_filter_save_path = Path(filter_save_path) / \"data.csv\"\n\n # append data to csv\n df_filter.to_csv(\n file_filter_save_path,\n index=False,\n mode=\"a\",\n header=not file_filter_save_path.exists(),\n )\n else:\n raise BaseException(\"Data need to be a pandas DataFrame\")\n","repo_name":"basedosdados/pipelines","sub_path":"pipelines/datasets/br_anatel_telefonia_movel/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2956,"program_lang":"python","lang":"en","doc_type":"code","stars":25,"dataset":"github-code","pt":"60"} +{"seq_id":"31649723784","text":"from ctl import CtlLine as CtlLine\r\n\r\n# The ROM class is where the microinstructions are figured out\r\n# for the instruction decoder. This implementation of SAP CPU\r\n# is using a lookup table, for each instruction, for each t-step\r\n# in those instructions, what is the bitwise representation of\r\n# the various control lines that have to be pulled high and low\r\n# to set the various Enable and Latch lines on the components.\r\n\r\nclass ROM(object):\r\n NOP = 0\r\n # mkctl generates control words that are bitwise representations\r\n # for the control lines, stored in CPU.oflags.\r\n def mkctl(self,flags=[]):\r\n word = self.NOP\r\n for f in flags:\r\n if f not in self.oflags:\r\n print(\"unknown control flag: [{}]\".format(f))\r\n continue\r\n if self.oflags[f].inv == 1:\r\n word &= ~self.oflags[f].mask\r\n else:\r\n word |= self.oflags[f].mask\r\n return word\r\n # At runtime we can create a new assembly instruction\r\n # for the ROM, providing the microinstructions associated\r\n # with the assembly instruction.\r\n def addinstr(self,instr,micro):\r\n if type(micro) is list:\r\n for condition,value in enumerate(micro):\r\n if not condition in self.addr:\r\n self.addr[condition] = dict()\r\n self.addr[condition][self.ASM[instr]] = value\r\n elif type(micro) is int:\r\n for condition in range(2**len(self.iflags)):\r\n if not condition in self.addr:\r\n self.addr[condition] = dict()\r\n self.addr[condition][self.ASM[instr]] = micro\r\n # At runtime, we can assemble a new program into machine code,\r\n # usually those will get stored back into RAM for later execution.\r\n def assemble(self,instr,data=0xF):\r\n if instr in self.ASM:\r\n return (self.ASM[instr] << 4) | data\r\n def __str__(self) -> str:\r\n ret = \"\"\r\n for cond in self.addr:\r\n for i,asm in enumerate(self.addr[cond]):\r\n ret = \"{}\\naddress=[0x{:02X}] condition=[0b{:02b}] asm=[0x{:02X}] microinstruction=[0x{:02X}]\".format(ret,i,cond,asm,self.addr[cond][asm])\r\n return ret\r\n","repo_name":"mlheur/pySAP","sub_path":"rom.py","file_name":"rom.py","file_ext":"py","file_size_in_byte":2234,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"60"} +{"seq_id":"21916023434","text":"# -*- coding: utf-8 -*-\n\nimport itertools\nimport collections\nimport numpy as np\n\n\ndef repeat_or_iter(obj):\n try:\n return iter(obj)\n except TypeError:\n return itertools.repeat(obj)\n\n\nclass Minimizer(object):\n\n def __init__(self, wrt, args=None):\n self.wrt = wrt\n if args is None:\n self.args = itertools.repeat(([], {}))\n else:\n self.args = args\n\n def minimize_until(self, criterions):\n \"\"\"Minimize until one of the supplied `criterions` is met.\n\n Each criterion is a callable that, given the info object yielded by\n an optimizer, returns a boolean indicating whether to stop. False means\n to continue, True means to stop.\"\"\"\n if not criterions:\n raise ValueError('need to supply at least one criterion')\n\n # if criterions is a single criterion, wrap it in iterable list\n if not isinstance(criterions, collections.Iterable):\n criterions = [criterions]\n\n info = {}\n for info in self:\n for criterion in criterions:\n if criterion(info):\n return info\n return info\n\n\ndef is_nonzerofinite(arr):\n \"\"\"Return True if the array is neither zero, NaN or infinite.\"\"\"\n return (arr != 0).any() and np.isfinite(arr).all()\n","repo_name":"SFPD/rlreloaded","sub_path":"3rdparty/climin/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":1317,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"60"} +{"seq_id":"17185843956","text":"\"\"\"\n@Date: Friday, April 2, 2021\n@Author: Chen Zhang\n@Brief: 基于邻接矩阵的图的实现\n\"\"\"\n\n\nclass MatrixGraph:\n \"\"\"Implement of matrix-based graph\"\"\"\n def __init__(self, num_of_nods, edges_list, directed=False, weighted=False):\n \"\"\"\n Create a new graph\n\n The graph is formed as:\n\n n0 n1 n2 n3 n4 Graph=\n n0 0 0 0 0 0 [[0, 0, 0, 0, 0],\n n1 0 0 0 0 0 [0, 0, 0, 0, 0],\n n2 0 0 0 0 0 >>>>> [0, 0, 0, 0, 0],\n n3 0 0 0 0 0 [0, 0, 0, 0, 0],\n n4 0 0 0 0 0 [0, 0, 0, 0, 0]]\n\n ni indicates the i_th node of the graph, the value stored in (ni, nj) indicates whether\n there is an edge sourced from node_i and pointed to node_j.\n\n :param num_of_nods: The amount of nodes\n :param edges_list: A list describes edges of graph, [(node_i, node_j), ...]\n :param directed: Bool, if True create directed graph, else create undirected graph.\n :param weighted: Bool, if True save edge weight, else not.\n \"\"\"\n assert isinstance(num_of_nods, int), 'Only accept integer!'\n assert len(edges_list) != 0, 'Graph can not be empty!'\n assert isinstance(directed, bool), 'Only accept bool!'\n assert isinstance(weighted, bool), 'Only accept bool!'\n\n self.node_num = num_of_nods # number of nodes\n self.edge_num = len(edges_list) # number of edges\n self.directed = directed # directed or not\n self.weighted = weighted # weighted or not\n self.mat = [[0] * self.node_num for _ in range(self.node_num)] # create empty mat\n self.node_name_dict = {} # save name of nodes\n\n # Record edges\n for i in range(self.edge_num):\n\n # Transfer node name to specific index\n if edges_list[i][0] not in self.node_name_dict:\n self.node_name_dict[edges_list[i][0]] = len(self.node_name_dict) # 以加入字典的顺序为索引\n if edges_list[i][1] not in self.node_name_dict:\n self.node_name_dict[edges_list[i][1]] = len(self.node_name_dict)\n\n # Record value of every position\n if self.weighted: # 记录权值\n self.mat[self.node_name_dict[edges_list[i][0]]][self.node_name_dict[edges_list[i][1]]] = edges_list[i][2] # 记录edge\n if not self.directed: # 若为无向图,则将对称位置也置1\n self.mat[self.node_name_dict[edges_list[i][1]]][self.node_name_dict[edges_list[i][0]]] = edges_list[i][2]\n else: # 仅标记\n self.mat[self.node_name_dict[edges_list[i][0]]][self.node_name_dict[edges_list[i][1]]] = 1\n if not self.directed: # 若为无向图,则将对称位置也置1\n self.mat[self.node_name_dict[edges_list[i][1]]][self.node_name_dict[edges_list[i][0]]] = 1\n\n def __len__(self):\n \"\"\"Return (node amount, edge amount)\"\"\"\n return self.node_num, self.edge_num\n\n def __str__(self):\n \"\"\"Print the graph as a matrix with title\"\"\"\n title = sorted(self.node_name_dict.items(), key=lambda x: x[1])\n string = ' ' * (len(str(title[1][0])) + 1) # Title line\n for i in range(len(title)):\n string += str(title[i][0]) + ' '\n for i in range(self.node_num):\n string += '\\n' + str(title[i][0]) + ' ' + ' '.join(map(str, self.mat[i]))\n return string + '\\n'\n\n def add_newEdges(self, newEdge):\n \"\"\"Add new edges to self\"\"\"\n # Check the format of input\n assert isinstance(newEdge, tuple), 'Only accept tuple'\n if self.weighted:\n assert len(newEdge) == 3, 'Only accept (node_i, node_j, weight)!'\n assert isinstance(newEdge[2], int) or isinstance(newEdge[2], float), 'Weight should be integer or float type!'\n else:\n assert len(newEdge) == 2, 'Only accept (node_i, node_j)!'\n\n if newEdge[0] not in self.node_name_dict or newEdge[1] not in self.node_name_dict:\n print('\\n')\n print(\"Operation failed! 'newEdge' contains unknown node, please check it out or create a new graph instead!\")\n print('\\n')\n else:\n if not self.weighted:\n self.mat[self.node_name_dict[newEdge[0]]][self.node_name_dict[newEdge[1]]] = 1\n if not self.directed:\n self.mat[self.node_name_dict[newEdge[1]]][self.node_name_dict[newEdge[0]]] = 1\n else:\n self.mat[self.node_name_dict[newEdge[0]]][self.node_name_dict[newEdge[1]]] = newEdge[2]\n if not self.directed:\n self.mat[self.node_name_dict[newEdge[1]]][self.node_name_dict[newEdge[0]]] = newEdge[2]\n\n def delete(self, edge):\n \"\"\"Delete the specific edge\"\"\"\n assert len(edge) in [2, 3], 'Illegal input format!'\n if edge[0] not in self.node_name_dict or edge[1] not in self.node_name_dict: # 若节点不存在则操作失败\n print('Operation failed! Can not delete edge of unavailable nodes!')\n else:\n self.mat[self.node_name_dict[edge[0]]][self.node_name_dict[edge[1]]] = 0\n if not self.directed: # 若为无向图,则对称位置置0\n self.mat[self.node_name_dict[edge[1]]][self.node_name_dict[edge[0]]] = 0\n\n\nif __name__ == '__main__':\n nodes = 4\n edges = [('A', 'C', 1), ('A', 'D', 2), ('B', 'A', 6), ('C', 'B', 3), ('C', 'D', 4), ('D', 'B', 5)]\n new_graph = MatrixGraph(nodes, edges, directed=True, weighted=True)\n print(new_graph)\n\n new_graph.add_newEdges(('A', 'B', 7))\n print(new_graph)\n\n new_graph.delete(('A', 'B'))\n print(new_graph)\n","repo_name":"noob-cod/DataSturcture-python","sub_path":"Graph/MatrixGraph.py","file_name":"MatrixGraph.py","file_ext":"py","file_size_in_byte":5800,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"60"} +{"seq_id":"14075163018","text":"\nfrom flask import render_template,redirect,url_for\nfrom app import app\nfrom .request import get_news,search_news\n\n\n\n# Views\n@app.route('/')\ndef index(): \n '''\n View root page function that returns the index page and its data\n '''\n #getting news\n \n sports_news =get_news('sports')\n politics_news = get_news('politics')\n business_news = get_news('business')\n title = 'Welcome to todays Bulletin'\n \n return render_template('index.html',title=title,sports =sports_news,politics =politics_news,business=business_news)\n\n\n@app.route('/news/')\ndef news(news_id):\n\n '''\n View source page function that returns the movie details page and its data\n '''\n \n \n\n return render_template('news.html',id=news_id)\n\n@app.route('/search/')\ndef search(news_name):\n '''\n View function to display the search results\n '''\n news_name_list = news_name.split(\" \")\n news_name_format = \"+\".join(news_name_list)\n searched_news = search_news(news_name_format)\n title = f'search results for {news_name}'\n return render_template('search.html',news = searched_news)\n\n\n\n\n ","repo_name":"oscar9181/news","sub_path":"app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1134,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"60"} +{"seq_id":"33927594356","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport os\nimport pprint\npp = pprint.PrettyPrinter(indent=4)\n\nimport joblib\nfrom skimage.io import imread\nfrom skimage.transform import resize\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import SGDClassifier\n\n\n\ndata = dict()\ndata['description'] = \"10 x 10 image either black or white\"\ndata['label'] = []\ndata['filename'] = []\ndata['data'] = [] \n\n\ndirectory = 'IMAGES'\n \n# iterate over files in\n# that directory\nfor filename in os.listdir(directory):\n f = os.path.join(directory, filename)\n \n\n im = imread(f)\n\n data['label'].append(filename)\n data['filename'].append(filename)\n data['data'].append(im)\n\nlabels = np.unique(data['label'])\nfig, axes = plt.subplots(1, len(labels))\nfig.set_size_inches(15,4)\nfig.tight_layout()\n\nfor ax, label in zip(axes, labels):\n idx = data['label'].index(label)\n \n ax.imshow(data['data'][idx])\n ax.axis('off')\n ax.set_title(label)\n\n\nX = np.array(data['data'])\ny = np.array(data['label'])\n\ny = np.flip(y)\n\nnew_x = []\n\nfor item in X:\n FLAT = [item for sublist in item for item in sublist]\n new_x.insert(-1, FLAT)\n\n \nsgd_clf = SGDClassifier(random_state=42, max_iter=1000, tol=1e-3)\nsgd_clf.fit(new_x, y)\n\n\n\ny_pred = sgd_clf.predict(new_x)\n\nprint(new_x)\nprint(y_pred)\n\n\n\n","repo_name":"adopolis23/SKLEARN","sub_path":"NeuralNetImageClassifier/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1328,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"60"} +{"seq_id":"8397487619","text":"from pyroub import *\nfrom pyrogram import filters\nfrom core.helpers.checkaddon import CheckSelfInstaller\n\n@app.on_command(cmd(\"install\") & filters.me)\nasync def install(_, message):\n if CheckSelfInstaller() is False:\n await eor(message, f\"Self Installer is off. Enable it by running `{PREFIX}var -s SELF_INSTALLER ENABLE` (if you're using Heroku) else edit your config.py file\")\n return\n if os.path.exists(\"sample_config.py\"):\n await eor(message, \"Availabe for SelfHost only as of now!\")\n return\n if not message.reply_to_message:\n await eor(message, \"Reply to a Plugin!\")\n return\n if not message.reply_to_message.document:\n await eor(message, \"Reply to a Plugin!\")\n return\n file = message.reply_to_message.document.file_name\n is_py = file.split(\".\")[1]\n if is_py.lower() != \"py\":\n await eor(message, \"Only Python Files Allowed!\")\n return\n if os.path.exists(os.path.join(\"pyroub/modules/\" + file)):\n await eor(message, \"Plugin Already Installed!\")\n return\n await message.reply_to_message.download(file_name=\"pyroub/modules/\")\n await eor(message, f\"Installed {file}\\nRestart once!\")\n return\n ","repo_name":"swatv3nub/PyroUB","sub_path":"pyroub/modules/_install.py","file_name":"_install.py","file_ext":"py","file_size_in_byte":1210,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"60"} +{"seq_id":"17659574406","text":"class Node:\n def __init__(self,data):\n self.data=data\n self.next=None\n\n\nclass LinkedList:\n def __init__(self):\n self.head=None\n\n def insertAtEnd(self,data):\n newNode= Node(data)\n if self.head is None:\n self.head=newNode\n return\n curNode=self.head\n while curNode.next:\n curNode=curNode.next\n curNode.next =newNode\n\n def printList(self):\n curNode =self.head\n while curNode:\n print(curNode.data,end='=>')\n curNode=curNode.next\n print('None')\n\n def checkIfPallindrome(self,method):\n if method==1:\n cur =self.head\n s=''\n while cur:\n s+=cur.data\n cur=cur.next\n return s[:]==s[::-1]\n elif method==2:\n cur=self.head\n lis=[]\n while cur:\n lis.append(cur.data)\n cur=cur.next\n cur=self.head\n while cur:\n if cur.data!=lis.pop():\n return False\n cur=cur.next\n return True\n else:\n p=self.head\n q=self.head\n prev=[]\n count=0\n while q:\n prev.append(q)\n count+=1\n q=q.next\n q=prev[count-1]\n\n i=1\n while i<= count//2+1:\n if prev[-i].data!=p.data:\n return False\n i+=1\n p=p.next\n return True\n\nllist = LinkedList()\nllist.insertAtEnd(\"A\")\nllist.insertAtEnd(\"B\")\nllist.insertAtEnd(\"C\")\nllist.insertAtEnd(\"B\")\nllist.insertAtEnd(\"A\")\n\nllist.printList()\n\nprint(llist.checkIfPallindrome(1))\nprint(llist.checkIfPallindrome(2))\nprint(llist.checkIfPallindrome(3))","repo_name":"surmayi/CodePython","sub_path":"PythonLearning/LinkedListSingly/IsPallindrome.py","file_name":"IsPallindrome.py","file_ext":"py","file_size_in_byte":1826,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"60"} +{"seq_id":"2804081851","text":"def calc_Q(l, fi, n, vm):\n '''\n ulaz: Duljina filtera\n Promjer zdenca\n Propusnost filtera\n Maks. ulazna brzina\n \n racun: Polumjer = promjer/2\n Opseg = 2* r *PI\n povrsina = duljina * opseg\n povrsina ulaza = povrsina * propusnost\n maks kapacitet = ulazna brzina * povrsina ulaza\n '''\n import math\n\n r = fi/2 #izracun radijusa iz promjera\n opseg = 2 * r * math.pi # izracun opsega\n povrsina = l * opseg #izracun povrsine cijevi\n pov_ulaza = povrsina * n #izracun povrsine ulaza vode u zdenac (propusnost filtera)\n max_kap = float(\"{0:.5f}\".format(pov_ulaza * vm)) #maksimalni kapacitet koji moze dati ta duljina filetra\n\n return max_kap\n\ndef unos_par():\n '''\n unos podataka\n '''\n while True:\n try:\n l = float(input('Unesi duljinu filtera [m]: ')) #unos podata s provjerom tocnosti ulaza da se ibjegnu neocekivani errori\n except:\n print('Dubilja filetra mora biti broj!!!!')\n continue\n else:\n break\n\n while True:\n try:\n fi = float(input('Unesi promjer ugradnje [m]: '))\n except:\n print('Promjer ugradnje mora biti broj!!!!')\n continue\n else:\n break\n \n while True:\n try:\n n = float(input('Unesi propusnost filtera (0.00 - 0.50): '))\n except:\n print('Propusnost filtera mora biti broj!!!!')\n continue\n else:\n break\n\n while True:\n try:\n vm = float(input('Unesi ulaznu brzinu vode u ugradnju (0.01 - 0.06 m/s): '))\n except:\n print('Ulazna brzina mora biti broj!!!!')\n continue\n else:\n break\n \n ans = calc_Q(l, fi, n ,vm) # izracun kapaciteta filtera iz unesenih podataka\n return ans\n \n\ndef main():\n\n ans = unos_par()\n opt_ans = float(\"{0:.5f}\".format(ans * 0.7)) # optimalni kapacitet zdenca koji je 70% maksimalnog\n print('Maksimalni kapacitet zdenca = ' + str(ans) + ' m^3/s' + ' ---> ' + str(ans*1000) + ' l/s')\n print('Optimani kapacitet zdenca = ' + str(opt_ans) + ' m^3/s'+ ' ---> ' + str(opt_ans*1000) + ' l/s' )\n input('Pritisni Enter za izlaz')\n\nmain()","repo_name":"lblazok/App","sub_path":"calc_Q.py","file_name":"calc_Q.py","file_ext":"py","file_size_in_byte":2281,"program_lang":"python","lang":"sh","doc_type":"code","stars":0,"dataset":"github-code","pt":"60"} +{"seq_id":"29036647027","text":"import torch\nfrom torch.autograd import Variable # module reponsible to gradient decent\nimport cv2\n# will do require transformations to fit the images in the NN\n# VOC classes will do enconding\nfrom data import BaseTransform, VOC_CLASSES as labelmap\nfrom ssd import build_ssd\nimport imageio\n\n\n# torch.cuda.is_available = lambda: False\ntorch.cuda.is_available()\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n\n\ndef detect(image, network, transform):\n\n height, width = image.shape[:2] # gets first 2 channels\n image_transform = transform(image)[0] # we get first element\n\n # convertion to Torch Tensor\n # the permute its to adjust the indixes of color to GRb instead of RGB\n x = torch.from_numpy(image_transform).permute(2, 0, 1)\n # adding fake dimension. Always add to first dimentions to the batch\n x = x.unsqueeze(0)\n\n # feed image to NN\n with torch.no_grad():\n y = network(x)\n\n detections = y.data # first attreibute is tensor and second is gradient\n # create a tensor object of dimensions [width, height, width, height]\n # this is because the position needs to be normalised between 0,1 and positions of the objects\n scale = torch.Tensor([width, height, width, height])\n \"\"\"\n detections = [batch, num of classes (objects),number of occurance of class,(score,x0,y0,x1,y1)]\n \"\"\"\n\n for i in range(detections.size(1)):\n j = 0 # occurtance tracking\n while detections[0, i, j, 0] >= 0.6:\n # We get the coordinates of the points at the upper left and the lower right of the detector rectangle.\n # we consider scale and convert to numpy array\n pt = (detections[0, i, j, 1:]*scale).numpy()\n\n cv2.rectangle(image, (int(pt[0]), int(pt[1])), (int(\n pt[2]), int(pt[3])), (0, 255, 0), 3)\n\n cv2.putText(\n image, labelmap[i-1], (int(pt[0]), int(pt[1])), cv2.FONT_HERSHEY_SIMPLEX, 2, (255, 255, 255), 2, cv2.LINE_AA)\n\n j += 1\n\n return image\n\n\ndef main():\n # we will use the test because we will use as pretrained moodel\n network = build_ssd(\"test\")\n network.load_state_dict(torch.load(\"ssd300_mAP_77.43_v2.pth\",\n map_location=lambda storage, loc: storage)) # load weights\n\n # scale on which the NN was trained\n transforms = BaseTransform(network.size, (104/256.0, 117/256.0, 123/256.0))\n\n video = imageio.get_reader(\"funny_dog.mp4\")\n fps = video.get_meta_data()[\"fps\"]\n writer = imageio.get_writer(\"output.mp4\",fps=fps)\n for i ,image in enumerate(video):\n image = detect(image,network.eval(),transforms)\n writer.append_data(image)\n print(i)\n\n writer.close()\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"esteban-andrade/Deep_Learning_varied","sub_path":"Computer Vision/Object Detection/object_detection.py","file_name":"object_detection.py","file_ext":"py","file_size_in_byte":2761,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"60"} +{"seq_id":"4574499804","text":"from django.shortcuts import get_object_or_404, render, redirect\nfrom django.urls import reverse_lazy\nfrom django.views import generic\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth.mixins import LoginRequiredMixin\nfrom django.core.exceptions import ObjectDoesNotExist\n\nfrom .models import (Dock, DockManifest,\n CargoHazard, DockSupervisor,\n Person, Ship, State)\nfrom .forms import DockManifestForm\nfrom services.models import Service, AnimatedIntro, WelcomeNote\n\n\n\n\n# Create your views here.\nclass HomePage(generic.TemplateView):\n template_name = 'index.html'\n model = Service\n\n def get_context_data(self, **kwargs):\n context = super(HomePage, self).get_context_data(**kwargs)\n context['intro_list'] = AnimatedIntro.objects.all()\n context['welcomenotes'] = WelcomeNote.objects.all()[:3]\n return context\n\n\ndef dock_overview(request):\n \"\"\"A view to display an overview of docks\"\"\"\n template = 'ship/dock_overview.html'\n context = {\n 'data': []\n }\n\n docks = Dock.objects.all()\n for dock in docks:\n hazards = CargoHazard.objects.filter(container__ship__dock=dock).distinct()\n context['data'].append({\n 'dock': dock,\n 'hazards': hazards\n })\n\n return render(request, template, context)\n\n\nclass DockDetail(LoginRequiredMixin, generic.DetailView):\n model = Dock\n template_name = 'ship/dock_details.html'\n\n\n@login_required\ndef user_profile(request):\n \"\"\"A view to display the details of a logged in user.\"\"\"\n template = 'ship/user_profile.html'\n person = get_object_or_404(Person, user=request.user)\n ships = Ship.objects.filter(captain__person=person)\n\n context = {\n 'person': person,\n 'ships': ships,\n }\n\n return render(request, template, context)\n\n\n\nclass CreateDockManifest(LoginRequiredMixin, generic.CreateView):\n model = DockManifest\n form_class = DockManifestForm\n template_name = 'ship/manifest_form.html'\n success_url = reverse_lazy('accounts:profile')\n\n def form_valid(self, form):\n all_manifest = DockManifest.objects.all()\n if (not all_manifest):\n form.instance.current_position = State.due_to_offload\n else:\n first = all_manifest.first()\n last = all_manifest.last()\n if last.is_due_offload():\n form.instance.current_position = State.not_offloaded\n elif first.is_offloaded():\n form.instance.current_position = State.due_to_offload\n elif last.is_not_offloaded():\n form.instance.current_position = State.not_offloaded\n return super(CreateDockManifest, self).form_valid(form)\n\n\nclass DockManifestList(generic.ListView):\n model = DockManifest\n template_name = 'ship/manifest_list.html'\n\n def get_context_data(self, *args, **kwargs):\n context = super(DockManifestList, self).get_context_data(*args, **kwargs)\n context['offloaded'] = DockManifest.objects.filter\\\n (current_position__iexact = 'oo')\n context['due_to_offload'] = DockManifest.objects.filter\\\n (current_position__iexact = 'dd')\n context['not_offloaded'] = DockManifest.objects.filter\\\n (current_position__iexact = 'yy')\n return context\n\n\nclass DockManifestDetail(generic.DetailView):\n model = DockManifest\n template_name = 'ship/manifest_detail.html'\n\n\nclass DockManifestUpdate(generic.UpdateView):\n model = DockManifest\n template_name = 'ship/manifest_form.html'\n\n\nclass DockManifestDelete(generic.DeleteView):\n model = DockManifest\n template_name = 'ship/manifest_delete.html'\n\n\nclass ShipList(generic.ListView):\n model = Ship\n template_name = 'ship/ship_list.html'\n\n\n@login_required\ndef offload(requst, pk):\n \"\"\"offload each dock manifest using queue \"\"\"\n\n # get the item to offload\n dock_manifest = get_object_or_404(DockManifest, pk=pk)\n\n #if (dock_manifest.current_position == 'dd' or check_next):\n if (dock_manifest.is_due_offload()):\n dock_manifest.current_position = State.offloaded\n\n try:\n dock_manifest_next = dock_manifest.\\\n get_next_by_timestamp()\n except ObjectDoesNotExist:\n print(\"No Previous Item\")\n else:\n dock_manifest_next.current_position = State.due_to_offload\n dock_manifest_next.save()\n\n dock_manifest.save()\n\n return redirect(reverse_lazy('accounts:profile'))\n\n\ndef print_manifest(request, pk):\n pass\n","repo_name":"Tosin-JD/online_port","sub_path":"ship/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4684,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"60"} +{"seq_id":"31436363674","text":"import pyopencl as cl\nimport pyopencl.characterize.performance as perf\n\n\ndef main():\n ctx = cl.create_some_context()\n\n prof_overhead, latency = perf.get_profiling_overhead(ctx)\n print(\"command latency: %g s\" % latency)\n print(\"profiling overhead: {:g} s -> {:.1f} %\".format(\n prof_overhead, 100*prof_overhead/latency))\n queue = cl.CommandQueue(\n ctx, properties=cl.command_queue_properties.PROFILING_ENABLE)\n\n print(\"empty kernel: %g s\" % perf.get_empty_kernel_time(queue))\n print(\"float32 add: %g GOps/s\" % (perf.get_add_rate(queue)/1e9))\n\n for tx_type in [\n perf.HostToDeviceTransfer,\n perf.DeviceToHostTransfer,\n perf.DeviceToDeviceTransfer]:\n print(\"----------------------------------------\")\n print(tx_type.__name__)\n print(\"----------------------------------------\")\n\n print(\"latency: %g s\" % perf.transfer_latency(queue, tx_type))\n for i in range(6, 31, 2):\n bs = 1 << i\n try:\n result = \"%g GB/s\" % (\n perf.transfer_bandwidth(queue, tx_type, bs)/1e9)\n except Exception as e:\n result = \"exception: %s\" % e.__class__.__name__\n print(\"bandwidth @ %d bytes: %s\" % (bs, result))\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"inducer/pyopencl","sub_path":"examples/dump-performance.py","file_name":"dump-performance.py","file_ext":"py","file_size_in_byte":1332,"program_lang":"python","lang":"en","doc_type":"code","stars":998,"dataset":"github-code","pt":"60"} +{"seq_id":"71202200831","text":"from Q2 import alpha, beta, gamma, delta\nimport numpy as np\nimport matplotlib.pyplot as plt\ndef display_contour(f, x, y, levels):\n X, Y = np.meshgrid(x, y)\n Z = f(X, Y)\n fig, ax = plt.subplots()\n contour_set = plt.contour(\n X, Y, Z, colors=\"grey\", linestyles=\"dashed\", \n levels=levels \n )\n ax.clabel(contour_set)\n plt.grid(True)\n plt.xlabel(\"$x_1$\") \n plt.ylabel(\"$x_2$\")\n plt.gca().set_aspect(\"equal\")\ndef H(x,y):\n return(delta*x - gamma * np.log(x) + beta*y - alpha*np.log(y))\n\ndisplay_contour(H, np.linspace(0.1,2,20), np.linspace(0.1,2,20), 20)\nplt.show()","repo_name":"jedupau/Projet-numerique2","sub_path":"Q5.py","file_name":"Q5.py","file_ext":"py","file_size_in_byte":606,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"60"} +{"seq_id":"37924713689","text":"\"\"\"\n--- Day 1: Calorie Counting ---\n--- Part Two ---\nBy the time you calculate the answer to the Elves' question, they've already realized that the Elf carrying the most Calories of food might eventually run out of snacks.\n\nTo avoid this unacceptable situation, the Elves would instead like to know the total Calories carried by the top three Elves carrying the most Calories. That way, even if one of those Elves runs out of snacks, they still have two backups.\n\nIn the example above, the top three Elves are the fourth Elf (with 24000 Calories), then the third Elf (with 11000 Calories), then the fifth Elf (with 10000 Calories). The sum of the Calories carried by these three elves is 45000.\n\nFind the top three Elves carrying the most Calories. How many Calories are those Elves carrying in total?\n\"\"\"\nelf:int=0\nsum_cal:int=0\nthree_elves:list[int]=[0,0,0]\nthree_max_cal :list[int]=[0,1,2]\nwith open (\"calories.txt\", \"r\") as calories_list:\n for calories in calories_list:\n if calories == \"\\n\":\n min_cal=min(three_max_cal)\n if sum_cal>min_cal:\n for index, max_cal in enumerate(three_max_cal):\n if min_cal==max_cal:\n three_max_cal[index]=sum_cal\n three_elves[index]=elf\n elf+=1\n sum_cal=0\n else:\n sum_cal+=int(calories)\ntot=0\nfor max_cal in three_max_cal:\n tot+=max_cal\n\nprint(f\"The elfs with the most calories are n: {three_elves} with a total of {tot} calories.\")","repo_name":"MaKeG0/MYadventofcode2022-","sub_path":"Day1/part2.py","file_name":"part2.py","file_ext":"py","file_size_in_byte":1521,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"60"} +{"seq_id":"4538763224","text":"# ======================================================\n# Python Script for getting report file from FTP to [source_folder] \n#\n# Created By : Hertanto Purwanto\n# Email : antho.firuze@gmail.com\n# Created at : 2019-10-30\n# File name : 01-get_report.py\n# Version : 1.0\n# ======================================================\n\nimport os, datetime, time, sys, re\nimport threading\nimport multiprocessing \nimport ftplib\nimport queue\nfrom dotenv import load_dotenv\nfrom os.path import join, dirname\nfrom itertools import islice\nfrom functools import partial\n\nmy_queue = queue.Queue()\ncountProcess = 1\n\ndef storeInQueue(f):\n def wrapper(*args):\n my_queue.put(f(*args))\n return wrapper\n\ndef loadEnv():\n # Load environment data from .env file\n dotenv_path = join(dirname(__file__), '.env')\n load_dotenv(dotenv_path)\n\ndef grabFile(ftp, filename, to_dir):\n with open(f'{to_dir}/{filename}', 'wb') as localfile:\n ftp.retrbinary('RETR ' + filename, localfile.write, 1024)\n\n# @storeInQueue\ndef grabFile_x(fld, filename, to_dir):\n with ftplib.FTP(os.getenv('FTP_SERVER')) as ftp:\n try:\n ftp.login(user=os.getenv('FTP_USER'), passwd=os.getenv('FTP_PASS')) \n ftp.cwd(f'/{fld}/')\n with open(f'{to_dir}/{filename}', 'wb') as localfile:\n ftp.retrbinary('RETR ' + filename, localfile.write, 1024)\n \n # return True\n\n except ftplib.all_errors as e:\n print('FTP error:', e)\n # return False\n\ndef grabFile_x2(fld, to_dir, filename):\n if filename.lower().endswith(\".txt\"):\n if not os.path.isfile(f'{to_dir}/{filename}'):\n with ftplib.FTP(os.getenv('FTP_SERVER')) as ftp:\n try:\n ftp.login(user=os.getenv('FTP_USER'), passwd=os.getenv('FTP_PASS')) \n ftp.cwd(f'/{fld}/')\n with open(f'{to_dir}/{filename}', 'wb') as localfile:\n ftp.retrbinary('RETR ' + filename, localfile.write, 1024)\n \n # return True\n\n except ftplib.all_errors as e:\n print('FTP error:', e)\n # return False\n\ndef main():\n global countProcess\n\n while True:\n loadEnv()\n copiedFiles = 0\n skippedFiles = 0\n # The with command will automatically close the connection to the server for Python 3 code\n with ftplib.FTP(os.getenv('FTP_SERVER')) as ftp:\n try:\n ftp.login(user=os.getenv('FTP_USER'), passwd=os.getenv('FTP_PASS')) \n\n ftp_folder = os.getenv('FTP_FOLDER').split(',')\n for fld in ftp_folder:\n ftp.cwd(f'/{fld}/')\n files = ftp.nlst()\n source_folder = f\"{os.getenv('CONVERT_FOLDER_SOURCE')}/{fld}\"\n # Check the folder is exists\n if not os.path.exists(source_folder):\n os.makedirs(source_folder)\n\n with multiprocessing.Pool(processes=100) as pool:\n func = partial(grabFile_x2, fld, source_folder)\n pool.map(func, files)\n pool.close()\n pool.join()\n\n # for idx, f in enumerate(files):\n # if f.lower().endswith(\".txt\"):\n # # Check the file is exists\n # if not os.path.isfile(f'{source_folder}/{f}'):\n # # grabFile(ftp, f, source_folder)\n # # t = threading.Thread(target=grabFile_x, args=(fld, f, source_folder,))\n # # t.start()\n # # t.join()\n\n # # p = multiprocessing.Process(target=grabFile_x, args=(fld, f, source_folder,))\n # # p.start()\n # # p.join()\n\n # copiedFiles += 1\n # if idx % 100 == 0:\n # print(f' Copying process (*.txt) => [{idx}] files copied.', end='\\r')\n # else:\n # skippedFiles += 1\n # # print(f'{idx}:skip:{f}')\n\n # # if idx > 100:\n # # break\n\n # # print(f'{fld} = {len(files)}')\n\n except ftplib.all_errors as e:\n print('FTP error:', e)\n \n header = f\"========== Process #{countProcess} ==========\"\n logger = f\"\\n{header}\"\n cp = f'{copiedFiles:0,.0f}'\n sk = f'{skippedFiles:0,.0f}'\n logger += f\"\\n{' Copied of file/s':<20}{cp:>11}\"\n logger += f\"\\n{' Skipped of file/s':<20}{sk:>11}\"\n logger += f\"\\n{'='*len(header)}\"\n print(logger)\n countProcess += 1\n time.sleep(10)\n\nif __name__ == '__main__':\n main()","repo_name":"antho-firuze/mst_dbs_20191008","sub_path":"01-get_report.py","file_name":"01-get_report.py","file_ext":"py","file_size_in_byte":4363,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"60"} +{"seq_id":"2471196876","text":"from sanic.exceptions import abort\nfrom sanic.response import json as res_json\nfrom sanic_openapi import doc\nfrom sanic_jwt_extended import jwt_required\nfrom sanic_jwt_extended.tokens import Token\nfrom server.api.mentor import mentor_api\nfrom bson import ObjectId\nimport time\n\n\n@mentor_api.post('/request/')\n@jwt_required\n@doc.summary('멘토링 신청')\nasync def MentoringRequest(request, token: Token, question_id):\n user = token.jwt_identity\n\n # 이미 신청한 멘토링은 아닌지 확인\n if await request.app.db.requests.find_one({\n 'user_id': user['id'],\n 'question_id': question_id,\n }):\n abort(400)\n\n req = {\n 'user_id': user['id'],\n 'question_id': question_id,\n 'timestamp': int(time.time()),\n 'approved': False\n }\n res = await request.app.db.requests.insert_one(req)\n if not res.acknowledged:\n abort(500)\n return res_json({'id': str(res.inserted_id)})\n\n\n@mentor_api.post('/approve/')\n@jwt_required\n@doc.summary('멘토링 승인')\nasync def MentoringApprove(request, token: Token, question_id):\n user = token.jwt_identity\n\n # question 쿼리, 작성자 확인\n question = await request.app.db.questions.find_one({\n '_id': ObjectId(question_id),\n 'user_id': user['id'],\n })\n if not question:\n abort(404)\n\n # 다른 멘토링이 이미 승인된 것은 아닌지 확인\n if await request.app.db.requests.find_one({\n 'question_id': question_id,\n 'approved': True\n }):\n abort(400)\n\n # post로 받은 request_id를 가진 request의 approved를 True로 업데이트\n request_id = request.json['request_id']\n res = await request.app.db.requests.update_one({'_id': ObjectId(request_id)}, {\n '$set': {\n 'approved': True\n }\n })\n if not res.acknowledged:\n abort(500)\n\n # question의 status 변경\n res = await request.app.db.questions.update_one({'_id': ObjectId(question_id)}, {\n '$set': {\n 'status': 'M'\n }\n })\n if not res.acknowledged:\n abort(500)\n\n return res_json({})\n\n\n@mentor_api.get('/')\n@jwt_required\n@doc.summary('멘토링 목록')\nasync def MentoringList(request, token: Token):\n user = token.jwt_identity\n\n questions = {\n 'user': {},\n 'mentor': [], # user가 멘토인 questions\n 'mentee': [] # user가 멘티인 questions\n }\n\n questions['user'] = await request.app.db.users.find_one({\n '_id': ObjectId(user['id']),\n }, {'_id': False})\n\n # 자신의 user_id를 가진 모든 question 쿼리 +\n cursor = request.app.db.questions.find({\n 'user_id': user['id']\n })\n questions['mentee'] = await cursor.to_list(length=50)\n\n # 자신의 user_id를 가진 approve된 request 쿼리 -> question 쿼리\n cursor = request.app.db.requests.find({\n 'user_id': user['id'],\n 'approved': True,\n })\n requests = await cursor.to_list(length=50)\n questions['mentor'] = [await request.app.db.questions.find_one({\n '_id': ObjectId(req['question_id']),\n }) for req in requests]\n \n for question in questions['mentor']:\n question['id'] = str(question['_id'])\n del question['_id']\n cursor = request.app.db.requests.find({\n 'question_id': question['id']\n }, {'_id': False})\n reqs = await cursor.to_list(length=50)\n question['requests'] = len(reqs)\n for question in questions['mentee']:\n question['id'] = str(question['_id'])\n del question['_id']\n cursor = request.app.db.requests.find({\n 'question_id': question['id']\n }, {'_id': False})\n reqs = await cursor.to_list(length=50)\n question['requests'] = len(reqs)\n return res_json({'mentorings': questions})\n","repo_name":"inudevs/ithaca-server","sub_path":"server/api/mentor/resources.py","file_name":"resources.py","file_ext":"py","file_size_in_byte":3835,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"60"} +{"seq_id":"3237497341","text":"import matplotlib.pyplot as plt\nimport torch\nfrom torch import nn\nfrom torch import optim\nimport torch.nn.functional as F\nfrom torchvision import datasets, transforms, models\nimport time\n\nfrom PIL import Image\n\nimport numpy as np\nimport pandas as pd \n\nimport nn_utility \n\nimport importlib\nworkspase_utils = importlib.import_module(\"workspace-utils\")\n\nimport argparse\n\ndef main():\n ''' Runs required flow to train a network, if everything works ok it should create a checkpoint. file\n '''\n args = get_args()\n print('... Init train.py script ...')\n\n ## Defining needed variables for training\n # Directory Params\n data_dir = args.data_dir #'flowers'\n save_dir = args.save_dir #'checkpoint.pth'\n print(save_dir)\n # Training parameters\n dropout = args.dropout #0.5\n learning_rate = args.lr #0.001\n epochs = args.epochs #5\n print_each = args.print_each #40\n \n # Build image loaders\n trainloader, testloader, validationloader = set_imageLoaders(data_dir)\n \n # Build classifier and model\n cat_to_name_file = args.cat_names #'cat_to_name.json'\n cat_to_name = nn_utility.get_cat_to_name(cat_to_name_file)\n model = set_model(learning_rate, cat_to_name, dropout)\n\n # Start training model\n trained_model, optimizer = start_training(model, trainloader, validationloader, learning_rate, epochs, print_each)\n \n # Test model\n test_approval = test_trained_model(trained_model, testloader)\n \n # Save model\n save_model(test_approval, trained_model, optimizer, learning_rate, epochs, print_each, cat_to_name, save_dir)\n \n\ndef set_imageLoaders(data_dir):\n print('... setting image loaders ...')\n \n # Images paths\n train_dir = data_dir + '/train'\n valid_dir = data_dir + '/valid'\n test_dir = data_dir + '/test'\n \n # Transforms and Loaders Required values\n means = [0.485, 0.456, 0.406]\n std_deviations = [0.229, 0.224, 0.225]\n rand_rotation, crop_to_size, img_size = 30, 224, 255\n train_batch_size = 32\n validation_batch_size = 32\n \n # Transforms and Loaders \n train_transform, test_transform = nn_utility.build_transforms(means, std_deviations,\n rand_rotation, crop_to_size, img_size)\n trainloader, testloader, validationloader = nn_utility.build_loaders(train_dir, test_dir, valid_dir,\n train_transform, test_transform,\n train_batch_size, validation_batch_size)\n return trainloader, testloader, validationloader\n \ndef set_model(learning_rate, cat_to_name, dropout):\n print('... setting model ...')\n model = models.densenet169(pretrained = True)\n \n input_features = model.classifier.in_features\n output_features = len(cat_to_name)\n\n my_classifier = nn_utility.build_myclassifier(input_features, output_features, dropout)\n model = nn_utility.update_model_classifier(model, my_classifier)\n return model\n\ndef start_training(model, trainloader, validationloader, lr, epochs, print_each):\n print('... starting training ...')\n #with workspase_utils.active_session(): #Commented due not running on my personal device\n start_time = time.time()\n trained_model, best_model_state_dict, optimizer = nn_utility.train_model(model, trainloader, validationloader, lr, epochs, print_each)\n end_time = time.time()\n print('... Training time: {} hours ...'.format((end_time - start_time)/3600))\n\n return trained_model, optimizer\n\ndef test_trained_model(trained_model, testloader):\n print('... starting testing ...') \n test_approval = nn_utility.test_model(trained_model, testloader)\n print('... Did the model approve the test?: {} ...'.format('yes' if test_approval else 'no'))\n return test_approval\n\ndef save_model(test_approval, trained_model, optimizer, learning_rate, epochs, print_each, cat_to_name, checkpoint_name):\n print('... start saving ...') \n if test_approval:\n nn_utility.save_checkpoint(trained_model, optimizer, learning_rate, epochs, print_each, cat_to_name, checkpoint_name)\n print('... Checkpoint saved due test approval...')\n print('... Checkpoint name = {}'.format(checkpoint_name))\n\ndef get_args():\n \n in_args = argparse.ArgumentParser(description=\"Neural network to identify a flower type image.\")\n\n in_args.add_argument('--data_dir', type=str, default='flowers',\n help='Points to main data storage directory. Must contain /train, /test and /valid folders along with its inner label folders in order to work as expected.')\n\n in_args.add_argument('--save_dir', type=str, default='checkpoint.pth', \n help='Point to save file path as str.')\n\n in_args.add_argument('--cat_names', type=str, default='cat_to_name.json',\n help='Mapping from categories to real names.') \n \n in_args.add_argument('--dropout', type=float, default=0.5,\n help='Define dropout value.') \n \n in_args.add_argument('--lr', type=float, default=0.001,\n help='Define learning rate value.') \n \n in_args.add_argument('--epochs', type=int, default=10,\n help='Define epochs number for training.') \n \n in_args.add_argument('--print_each', type=int, default=40,\n help='Defefine number of steps to print model accuracy.') \n\n # Parse args\n args = in_args.parse_args()\n \n return args\n\n\n\nif __name__ == '__main__': main()\n\n\n","repo_name":"juanmonsalveh/python-ml-udacity","sub_path":"deliverable_project/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":5638,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"60"} +{"seq_id":"35244435349","text":"import pygame\nimport chess\nfrom .utils import get_pieces_png, get_move\nfrom evaluation.evaluation import Evaluator\n\n\nclass Game():\n def __init__(self, w, h):\n self.w, self.h = w, h\n self.screen = pygame.display.set_mode([self.w, self.h])\n self.square_w = w // 8\n self.pieces_img, self.pieces_sprites = get_pieces_png()\n self.board = chess.Board()\n self.board_array = self.update_board()\n self.dali = Evaluator()\n \n self.is_dragging = False\n self.current_piece = None\n\n def draw(self):\n self.draw_background()\n self.draw_pieces()\n pygame.display.update()\n\n def mouse_pressed(self, mouse_pos, mouse_pressed):\n if mouse_pressed[0]:\n i, j = mouse_pos[0] // self.square_w, mouse_pos[1] // self.square_w\n if self.board_array[i][j] != '.':\n self.current_piece = (i,j)\n self.mouse_pos = mouse_pos\n\n def mouse_released(self, mouse_pos, mouse_pressed):\n if not mouse_pressed[0]:\n if self.current_piece:\n i, j = mouse_pos[0] // self.square_w, mouse_pos[1] // self.square_w\n move = get_move(self.current_piece, (i,j))\n\n if move in self.board.legal_moves:\n self.board.push(move)\n self.board_array = self.update_board()\n self.draw()\n\n self.dali_play()\n\n self.current_piece = None\n\n def dali_play(self):\n current_hash = self.dali.zobrist_hash(self.board)\n best_move = self.dali.find_best_move(self.board, False)\n\n calculated_hash = self.dali.zobrist_hash_from_previous(current_hash, best_move, self.board) \n self.board.push(best_move)\n\n new_hash = self.dali.zobrist_hash(self.board)\n print(new_hash, calculated_hash)\n\n self.board_array = self.update_board()\n self.draw()\n\n def mouse_moved(self, mouse_pos):\n if self.current_piece:\n self.mouse_pos = mouse_pos\n\n def update_board(self):\n board_array = [ [0] * 8 for _ in range(8)]\n board_str = str(self.board).replace(\" \", \"\").replace(\"\\n\", \"\")\n for i in range(len(board_str)):\n x = i % 8\n y = i // 8 \n board_array[x][y] = board_str[i]\n return board_array\n\n\n def draw_pieces(self):\n for i in range(len(self.board_array)):\n for j in range(len(self.board_array[i])):\n x = i * self.square_w \n y = j * self.square_w \n c = self.board_array[i][j]\n if c in self.pieces_img:\n img_size = self.pieces_img[c].size\n x = x + self.square_w / 2 - img_size[0] / 2\n y = y + self.square_w / 2 - img_size[0] / 2\n if self.current_piece:\n current_i, current_j = self.current_piece[0], self.current_piece[1]\n if current_i == i and current_j == j:\n x = self.mouse_pos[0] - img_size[0] / 2\n y = self.mouse_pos[1] - img_size[0] / 2\n self.screen.blit(self.pieces_sprites, pygame.Rect(x, y,self.square_w, self.square_w), area=self.pieces_img[c])\n\n def draw_background(self):\n for i in range(0,8):\n for j in range(0,8):\n color = (251, 217, 181) if (i + j) % 2 == 0 else (181, 136, 99)\n pygame.draw.rect(self.screen, color, pygame.Rect(i * self.square_w, j * self.square_w, self.square_w, self.square_w))\n\n","repo_name":"AyoubBouisri/Dali","sub_path":"game/game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":3589,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"60"} +{"seq_id":"6528187697","text":"#Libraries\nfrom flask_api import status\nfrom datetime import datetime\nfrom flask import Flask, render_template,jsonify,request,abort\nfrom flask_sqlalchemy import SQLAlchemy\nimport requests\n\n\nip='http://34.207.157.150/' #IP of Orchestrator/DBaaS\nipu=\"http://52.55.28.15/\" #IP of Users\n\ncount=0 #for counter\n\n\n#validate password-SHA1\ndef is_sha1(x):\n if len(x) != 40:\n return 0\n try:\n y = int(x, 16)\n except ValueError:\n return 0\n return 1\n\n\napp = Flask(__name__)\n\n\napp.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db'\ndb = SQLAlchemy(app)\n# Ensure FOREIGN KEY for sqlite3\nif 'sqlite' in app.config['SQLALCHEMY_DATABASE_URI']:\n def _fk_pragma_on_connect(dbapi_con, con_record): # noqa\n dbapi_con.execute('pragma foreign_keys=ON')\n\n with app.app_context():\n from sqlalchemy import event\n event.listen(db.engine, 'connect', _fk_pragma_on_connect)\n\n\n\n\n#defining DataBase structure\nclass Ride(db.Model):\n\trideid = db.Column(db.Integer,primary_key=True)\n\tsource = db.Column(db.Text(),nullable=False)\n\tdestination = db.Column(db.Text(),nullable=False)\n\ttimestamp = db.Column(db.DateTime(),nullable=False)\n\tcreated_by= db.Column(db.Text(),nullable=False)\n\n\n\n#db foreign Key contrain to be added\n\tdef __repr__(self):\n\t\treturn '' % self.rideid\n\tdef __init__(self,s,d,t,c):\n\t\tself.source= s\n\t\tself.destination= d\n\t\tdatetime_object = datetime.strptime(t, '%d-%m-%Y:%S-%M-%H')\n\t\tself.timestamp = datetime_object\n\t\tself.created_by= c\n\n\n\nclass Ridetake(db.Model):\n\t#A table definition for a user joining a ride\n\trideid = db.Column(db.Integer,db.ForeignKey('ride.rideid'),nullable=False, primary_key=True)\n\tuser=db.Column(db.Text(),nullable=False, primary_key=True)\n\tdef __repr__(self):\n\t\treturn '' % self.rideid\n\tdef __init__(self,r,u):\n\t\tself.rideid= r\n\t\tself.user= u\n\t\t\n\n\n\n\n@app.route(\"/api/v1/rides\",methods=[\"POST\",\"PUT\"])\ndef create_ride():\n\t#try:\n\t\tglobal count\n\t\tcount+=1\n\t\tif(request.method!=\"POST\"):\n\t\t\tabort(405)\n\t\tur=request.url_root\n\n\n\n\t\ttry:\n\n\t\t\t#Creating data in specific format for write database request\n\t\t\tdata={'table':'Ride','insert':[request.get_json()['source'],request.get_json()['destination'],request.get_json()['timestamp'],request.get_json()['created_by']]}\n\t\t\n\t\texcept:\n\t\t\t\n\t\t\t#if any data is missing return 400\n\t\t\treturn (\"Invalid Request\",status.HTTP_400_BAD_REQUEST)\n\t\t\n\n\n\n\t\t#Requesting User to get all the users\n\t\tq=requests.get(ipu+'api/v1/users',json=data )\n\t\tif(q.status_code!=204):#204=no user\n\t\t\t\n\t\t\tz=(q.json())\n\n\n\t\t\t#To check if user creating ride exists\n\t\t\tif(request.get_json()['created_by'] in z):\n\n\t\t\t\t\t#requesting write to DBaaS\n\t\t\t\t\tr=requests.post(ip+'api/v1/db/write',json=data )\n\t\t\t\n\n\t\t\t\t\treturn (jsonify(),status.HTTP_201_CREATED)\t\n\t\treturn (\"USER NOT FOUND\",status.HTTP_400_BAD_REQUEST)\n\t\t\n\n\n\n@app.route(\"/api/v1/rides/count\",methods=[\"GET\"])\ndef count_rides():\n\t\tglobal count\n\t\tcount+=1\n\n\n\t\tur=request.url_root\n\n\t\ttry:\n\n\t\t\t#creating data in specific format\n\t\t\tdata={\"table\": \"Ride\",\"columns\": [\"created_by\",\"rideid\",\"timestamp\"]}\n\n\t\texcept:\n\n\t\t\t#if missing value\n\t\t\treturn ('Missing Parameter',status.HTTP_400_BAD_REQUEST)\n\t\t\n\t\t#requesting Read to DBaaS\n\t\tr=requests.post(ip+'api/v1/db/read',json=data )\n\n\t\td=r.json()\n\n\t\treturn (jsonify(len(d)))\t#returning Count\n\t\t\n\n\n\n@app.route(\"/api/v1/rides\",methods=[\"GET\"])\ndef get_rides():\n\n\t\tglobal count\n\t\tcount+=1\n\n\t\tur=request.url_root\n\n\n\t\ttry:\n\n\t\t\t#data in specific format for read request for upcoming rides\n\t\t\tdata={\"table\": \"Ride\",\"columns\": [\"created_by\",\"rideid\",\"timestamp\"],\"where\": \"Ride.timestamp>='\"+str(datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\"))+\"',Ride.source==\"+request.args.get('source')+\",Ride.destination==\"+request.args.get('destination')}\n\n\t\texcept:\n\n\t\t\treturn ('Missing Parameter',status.HTTP_400_BAD_REQUEST)\n\n\n\n\t\t#Source and destination should be in valid range\t\n\t\tif int(request.args.get('source')) in range(1,199) and int(request.args.get('destination')) in range(1,199):\n\t\t\t\n\t\t\t#read request to Orchestrator\n\t\t\tr=requests.post(ip+'api/v1/db/read',json=data )\n\t\t\td=r.json()\n\n\t\t\t#check if atleast one ride is available\n\t\t\tif(len(d)==0):\n\t\t\t\treturn (\"\",status.HTTP_204_NO_CONTENT)\n\n\t\t\t#\n\t\t\tfor i in d:\n\n\n\t\t\t\t#changing read data into specified format\n\t\t\t\ti['username']=i.pop(\"created_by\")\n\t\t\t\ti['timestamp'] = datetime.strptime(i['timestamp'], '%Y-%m-%d %H:%M:%S').strftime('%d-%m-%Y:%S-%M-%H')\n\n\n\t\t\treturn (jsonify(d))\n\n\n\t\telse:\n\n\n\t\t\t#if source or destination is out of range\n\t\t\treturn ('Source/destination invalid',status.HTTP_400_BAD_REQUEST)\n\t\t\n\n\n\t\n\n@app.route(\"/api/v1/rides/\",methods=[\"POST\"])\ndef join_rides(rideId):\n\n\n\t\tglobal count\n\t\tcount+=1\n\n\t\tur=request.url_root\n\n\n\t\ttry:\n\n\t\t\t#to insert data changing into specific format\n\t\t\tdata={'table':'Ridetake','insert':[rideId,request.get_json()['username']]}\n\n\t\texcept:\n\n\n\t\t\treturn ('Missing Parameter',status.HTTP_400_BAD_REQUEST)\n\n\t\t#getting users\n\t\tq=requests.get(ipu+'api/v1/users')\t\n\n\n\t\tif(q.status_code!=204):#204=no users\n\n\t\t\tz=(q.json())\n\n\t\t\tif(request.get_json()['username'] in z):#user creating ride exists\n\n\t\t\t\tr=requests.post(ip+'api/v1/db/write',json=data )\n\n\t\t\t\treturn (jsonify())\n\n\t\treturn (\"USER NOT FOUND\",status.HTTP_400_BAD_REQUEST)\n\t\t\n\n\t\t\n\n@app.route(\"/api/v1/rides/\")\ndef ride_detail(rideId):\n\t\tglobal count\n\t\tcount+=1\n\n\t#try:\n\t\tur=request.url_root\n\t\ttry:\n\n\t\t\t#data into specific format for read request\n\t\t\tdata={\"table\": \"Ride\",\"columns\": [\"created_by\",\"rideid\",\"timestamp\",\"source\",\"destination\"],\"where\": \"Ride.rideid==\"+rideId}\n\t\t\n\t\texcept:\n\n\t\t\treturn ('Missing Parameter',status.HTTP_400_BAD_REQUEST)\n\n\t\t#Sending read request to DBaaS to fetch ride details\n\t\tr=requests.post(ip+'api/v1/db/read',json=data )\n\n\t\td=r.json()[0]\n\n\t\t#Sending read request to fetch users associated with the ride\n\t\tdata={\"table\": \"Ridetake\",\"columns\": [\"user\"],\"where\": \"Ride.rideid==\"+rideId}\n\t\t\n\t\t#Sending read request to DBaaS to fetch users associated with the ride\n\t\tr=requests.post(ip+'api/v1/db/read',json=data )\n\n\t\tuser=(r.json())\n\n\t\t#users taking the ride\n\t\td[\"users\"]=[x[\"user\"] for x in user ]\n\n\t\tif r.status_code==500:\n\n\t\t\treturn (\"Ride Not Found\",status.HTTP_400_BAD_REQUEST)\n\t\t\n\t\treturn (jsonify(d))\n\n'''\n\n\n@app.route(\"/api/v1/rides/\",methods=[\"DELETE\"])\ndef del_ride(rideId):\n\n\tglobal count\n\t\n\tcount+=1\n\n\t\n\tb=Ride.query.filter(Ride.rideid==rideId).first()\n\tif(b==None):\n\t\treturn('Ride Not found',status.HTTP_400_BAD_REQUEST)\n\t\n\n\tdb.session.delete(b)\n\n\tdb.session.commit()\n\n\treturn(jsonify())\n\n'''\n\n\n\t\n@app.route(\"/api/v1/db/clear\",methods=[\"POST\"])\ndef clr_db():\n\n\t#sending clear request to DBaaS\n\tr=requests.post(ip+'api/v1/db/clear')\n\n\treturn(jsonify())\n\n\n\n@app.route(\"/api/v1/_count\",methods=[\"GET\"])\ndef get_count():\n\n\t\t#counting number of requests\n\t\tglobal count\n\n\t\treturn (jsonify([count]))\t\n\t\t\n\n@app.route(\"/api/v1/_count\",methods=[\"DELETE\"])\ndef zer_count():\n\n\t\t#to reset counter\n\t\tglobal count\n\n\t\tcount=0\n\n\t\treturn (jsonify())\n\t\n\n\n\n\nif __name__ == '__main__':\n\t\n\tapp.run(host='0.0.0.0',port=80)\n","repo_name":"aniket1304/RideShare","sub_path":"Final Project/Ride/ride.py","file_name":"ride.py","file_ext":"py","file_size_in_byte":6992,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"60"} +{"seq_id":"20460628364","text":"def BubbleSort(arr):\n n = len(arr)\n\n for i in range(0,n):\n swap = False\n for j in range(0, n-i-1):\n if(arr[j] > arr[j+1]):\n arr[j],arr[j+1] = arr[j+1], arr[j]\n swap = True\n if(swap == False):\n return arr\n return arr\n\nif __name__ == \"__main__\":\n sample_arr = [23,20,15,10,7,1]\n sorted_arr = BubbleSort(sample_arr)\n print(sorted_arr)\n\n\n# we can further optimize the bubble sort by checking whether the array is sorted or not by number of swaps happens.","repo_name":"Divisekara/algorithms-in-python-java-cpp","sub_path":"Bubble sorting algorithm/BubbleSort.py","file_name":"BubbleSort.py","file_ext":"py","file_size_in_byte":541,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"60"} +{"seq_id":"72291074110","text":"import csv\nimport numpy as np\nimport sys\nfrom LogisticModel import LRmodel\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\ncn1 = 44\ncn = 51\nif len(sys.argv) == 3:\n\t# for cn1 in range(2,56):\n\t# \tfor cn in range(cn1+1,57):\n\t### Parsing data ###\n\tdata = np.genfromtxt(sys.argv[1], delimiter=',')\n\tdata = np.delete(data, 0, 1)\t\t\t# Delete first column\n\tdata = np.nan_to_num(data)\t\t\t\t# Replace nan with 0\n\n\t# Overfitting\n\t# train_in = train_in[:276, :]\n\t# train_out = train_out[:276, 0][np.newaxis].T\n\n\t# multiple order\n\tdata = np.concatenate((data[:, :-1], (data[:, cn1]**3*data[:, cn]**3)[np.newaxis].T, data[:, -1][np.newaxis].T), axis=1)\n\n\t# # Feature scaling\n\t# mean = np.sum(train_in, axis=0)/train_in.shape[0]\n\t# sd = (np.sum((train_in-mean)**2, axis=0)/train_in.shape[0])**0.5\n\t# train_in = (train_in-mean)/sd\n\n\t### N-fold cross validation ###\n\ttrain_in_1 = np.concatenate((data[0::3, :-1], data[1::3, :-1]))\n\ttrain_in_2 = np.concatenate((data[1::3, :-1], data[2::3, :-1]))\n\ttrain_in_3 = np.concatenate((data[0::3, :-1], data[2::3, :-1]))\n\ttrain_out_1 = np.concatenate((data[0::3, -1], data[1::3, -1]))[np.newaxis].T\n\ttrain_out_2 = np.concatenate((data[1::3, -1], data[2::3, -1]))[np.newaxis].T\n\ttrain_out_3 = np.concatenate((data[0::3, -1], data[2::3, -1]))[np.newaxis].T\n\tnf_test_in_1 = data[2::3, :-1]\n\tnf_test_in_2 = data[0::3, :-1]\n\tnf_test_in_3 = data[1::3, :-1]\n\tnf_test_out_1 = data[2::3, -1][np.newaxis].T\n\tnf_test_out_2 = data[0::3, -1][np.newaxis].T\n\tnf_test_out_3 = data[1::3, -1][np.newaxis].T\n\ttrain_in = data[:, :-1]\n\ttrain_out = data[:, -1][np.newaxis].T\n\n\t### Model parameter ###\n\t# eta = 0.00000000009\t\t# Learning rate for pure LR\n\teta = 0.2\t\t# Learning rate\n\tfNum = 58\n\tw1 = np.ones((fNum, 1))\t# weightings\n\tw2 = np.ones((fNum, 1))\n\tw3 = np.ones((fNum, 1))\n\tw = np.ones((fNum, 1))\n\tbias = 0\n\titeration = 10000\t\t# Iteration times\n\tlam = 0\n\tuseAdagrad = True\n\n\t# multiple order\n\t# w1 = np.concatenate((w1, w1), axis=0)\n\t# w2 = np.concatenate((w2, w2), axis=0)\n\t# w3 = np.concatenate((w3, w3), axis=0)\n\t# w = np.concatenate((w, w), axis=0)\n\n\n\t### Build model ###\n\tmodel1_f1 = LRmodel(eta, w1, bias, iteration, lam, useAdagrad,\n\t\ttrain_in_1, train_out_1, nf_test_in_1, nf_test_out_1)\n\tmodel1_f2 = LRmodel(eta, w2, bias, iteration, lam, useAdagrad,\n\t\ttrain_in_2, train_out_2, nf_test_in_2, nf_test_out_2)\n\tmodel1_f3 = LRmodel(eta, w3, bias, iteration, lam, useAdagrad,\n\t\ttrain_in_3, train_out_3, nf_test_in_3, nf_test_out_3)\n\n\tmodel1_f1.run()\n\tmodel1_f1.print_nf_result()\n\tmodel1_f2.run()\n\tmodel1_f2.print_nf_result()\n\tmodel1_f3.run()\n\tmodel1_f3.print_nf_result()\n\n\tavgTrainAccu = (model1_f1.getTrainLoss()+model1_f2.getTrainLoss()\n\t\t+model1_f3.getTrainLoss())/3\n\tavgAccu = (model1_f1.nf_test_result()+model1_f2.nf_test_result()+\n\t\tmodel1_f3.nf_test_result())/3\n\t# if avgAccu < 0.9256:\n\t# \tcontinue\n\tprint (\"test: \"+str(avgAccu)+' train: '+str(avgTrainAccu)+\n\t\t\" Learning rate: \"+str(eta)+' lam: '+str(lam))\n\n\t# Run with all training data\n\tmodel1_all = LRmodel(eta, w, bias, iteration, lam, useAdagrad,\n\t\ttrain_in, train_out, 0, 0)\n\tmodel1_all.run()\n\tprint \n\n\t# Parameter log\n\twith open('parameter.log', 'a') as plog:\n\t\tplog.write('# '+str(cn1)+'*'+str(cn)+'\\n')\n\t\tplog.write('test: '+str(avgAccu)+' train: '+str(avgTrainAccu)+\n\t\t\t' iter: '+str(iteration)+' eta: '+str(eta)+' lam: '+\n\t\t\tstr(lam)+'\\n')\n\t# Save model\n\tnp.save('model', [model1_all.getW(), model1_all.getBias()])\n\nif len(sys.argv) == 4:\n\t### Parsing testing data ###\n\ttestdata = np.genfromtxt(sys.argv[2], delimiter=',')\n\ttestdata = np.delete(testdata, 0, 1)\t# Delete first column\n\ttestdata = np.nan_to_num(testdata)\t\t\t# Replace nan with 0\n\n\t# # Feature scaling\n\t# test_in = (test_in-mean)/sd\n\n\t# multiple order\n\ttestdata = np.concatenate((testdata, (testdata[:, cn1]*testdata[:, cn])[np.newaxis].T), axis=1)\n\n\t### Testing result ###\n\t[test_w, test_b] = np.load('model.npy')\n\tmodel_test = LRmodel(w=test_w, bias=test_b)\n\ttest_out = model_test.testing_output(testdata)\n\n\t# Output file\n\tfilename = sys.argv[3]\n\twith open(filename, 'w+') as outfile:\n\t\toutfile.write('id,label\\n')\n\t\tfor i in range(len(test_out)):\n\t\t\toutfile.write(str(i+1)+','+str(test_out[i, 0])+'\\n')\n\n\t\n\n\n\n\n","repo_name":"TingKaiChen/ML2016","sub_path":"hw2/logistic_regression.py","file_name":"logistic_regression.py","file_ext":"py","file_size_in_byte":4156,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"60"} +{"seq_id":"41475925349","text":"from pathlib import Path\nimport re\n\nclass FileHandling():\n \n \n def __init__(self, path_to_file: str):\n \n self.absolute_filename = Path(path_to_file)\n \n if self.absolute_filename.exists():\n self.file = open(self.absolute_filename)\n else:\n raise ValueError(\"Invalid path to file\")\n \n self.raw_input = self.fill_raw_input()\n \n if self.verify_pattern():\n print(\"File handler created successfully.\")\n else:\n raise ValueError(\"Input does not match pattern. File handler was not created.\")\n \n \n def print(self):\n print(self.absolute_filename)\n \n \n def fill_raw_input(self) -> dict:\n dict_input = dict()\n lines = self.file.readlines()\n \n dict_input[\"Components\"] = lines[0][:-1]\n dict_input[\"Rules\"] = [line for line in lines[1:]]\n \n return dict_input\n \n \n def verify_pattern(self) -> bool:\n comp_pattern = re.compile(r\"\\(\\{([a-z],\\s*)*[a-z]\\},\\s*\\{(q(\\d+|f),\\s*)*q(\\d+|f)\\},\\s*D,\\s*q\\d+,\\s*\\{(q(\\d+|f),\\s*)*q(\\d+|f)\\},\\s*\\{([A-Z],\\s*)*[A-Z]\\}\\)\")\n rule_pattern = re.compile(r\"q(\\d+|f),\\s*[a-z?-],\\s*[A-Z?-],\\s*q(\\d+|f),\\s*[A-Z-]\")\n \n if not re.match(comp_pattern, self.raw_input[\"Components\"]):\n return False\n \n for rule in self.raw_input[\"Rules\"]:\n if not re.match(rule_pattern, rule):\n return False\n \n return True\n \n \n def get_raw_input(self) -> dict:\n return self.raw_input","repo_name":"hellsdeur/Pushdown-Automaton","sub_path":"src/file_handling.py","file_name":"file_handling.py","file_ext":"py","file_size_in_byte":1588,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"60"} +{"seq_id":"1455235055","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\n# from HR_fitter import contour_1d\n\nfrom sys import argv\n# if 'big' in argv:\nmass_key = 'M'\n# else:\n# mass_key = 'star_mass'\n\n\nvalid_vary = [mass_key, 'Z', 'Y', 'alpha', 'diff', 'over'][:-2] # diff and over dont work yet\n\nif len(argv) > 1:\n varying = argv[1]\n no_plot = 'no_plot' in argv\n run_all = False\n if varying == 'all':\n varying = valid_vary[0]\n no_plot = True\n run_all = True\n elif varying not in valid_vary:\n print(\"Invalid vary paramter given.\")\n print(\"Must be one of:\", valid_vary)\n exit()\nelse:\n print(\"Give a paramter to vary from:\")\n print(valid_vary)\n exit()\n\n\nimport split_grid as sg\n\ndef get_colour(v):\n \"\"\" Get an RGB colour from a smooth continuous spectrum\n given a value `v` between 0 and 1.\n \"\"\"\n v %= 1\n RGB = np.array([ # this will cover the whole RGB spectrum\n [1, 1, 0, 0, 0, 1],\n [0, 1, 1, 1, 0, 0],\n [0, 0, 0, 1, 1, 1],\n ])\n RGB = RGB[:, [0, 1, 4, 5]] # Select a colour range that looks good\n nVals = len(RGB[0])\n\n v = (v * nVals) % nVals # value within [0, nVals)\n left = int(v) % nVals\n right = int(v + 1) % nVals\n dec = v % 1 # value within [0, 1)\n\n left_rgb = RGB[:, left]\n right_rgb = RGB[:, right]\n\n shift = right_rgb - left_rgb\n return left_rgb + dec * shift\n\n\n\n\nfont = {'weight' : 'normal',\n# 'family' : 'normal',\n'size' : 18}\nplt.rc('font', **font)\nplt.rc('figure', figsize=(12, 8))\nplt.rc('axes', grid=True)\n\n# Get unique tracks\nsg.init('mass_conv_core', 'center_degeneracy')\nunq = sg.get_unique_tracks()\n\nsolar_X = 0.7346\nsolar_Y = 0.2725; range_Y = 0.0005\nsolar_Z = 0.01858 ; range_Z = 0.0005\n# 1 - 0.7346 - 0.2485 = 0.0169\n\nsolar_mass = 1.0; range_mass = 0.001\ncenter_alpha = 1.836; range_alpha = 0.05\ncenter_diff = 1; range_diff = 0.01\ncenter_over = 0.001; range_over = 0.01\n\nep_shifts = {\n v:0 for v in valid_vary\n}\n\nep_nu_shifts = {\n v:0 for v in valid_vary\n}\n\nvary_vals = {v:list() for v in valid_vary}\ntrackss = None\n\n # m = density + 2 < 0\n # return np.flatnonzero(m)[0]\n\nquiver_kwargs = {\n 'angles':'xy',\n 'scale_units':'xy',\n 'scale':1\n}\n\nep_labels = None\ndef run():\n global ep_shifts\n global trackss\n global vary_vals\n global ep_labels\n\n max_mass = solar_mass + range_mass\n min_mass = solar_mass - range_mass\n\n max_alpha = center_alpha + range_alpha\n min_alpha = center_alpha - range_alpha\n\n max_diff = center_diff + range_diff\n min_diff = center_diff - range_diff\n\n max_over = center_over + range_over\n min_over = center_over - range_over\n\n max_Y = solar_Y + range_Y\n min_Y = solar_Y - range_Y\n\n max_feh = solar_Z + range_Z\n min_feh = solar_Z - range_Z\n\n m_ax = unq[mass_key]\n feh_ax = unq['Z']\n Y_ax = unq['Y']\n alpha_ax = unq['alpha']\n diff_ax = unq['diffusion']\n over_ax = unq['overshoot']\n\n m_solar_mask = (m_ax > min_mass) & (m_ax < max_mass)\n feh_solar_mask = (feh_ax < max_feh) & (feh_ax > min_feh)\n Y_solar_mask = (Y_ax < max_Y) & (Y_ax > min_Y)\n alpha_center_mask = (alpha_ax > min_alpha) & (alpha_ax < max_alpha)\n diff_center_mask = (diff_ax > min_diff) & (diff_ax < max_diff)\n over_center_mask = (over_ax > min_over) & (over_ax < max_over)\n\n fixed_masks = {\n mass_key: m_solar_mask,\n 'Z': feh_solar_mask,\n 'Y': Y_solar_mask,\n 'alpha': alpha_center_mask,\n 'diff': diff_center_mask,\n 'over': over_center_mask\n }\n\n all_fixed_mask = np.ones(len(m_solar_mask), dtype=bool)\n for m in fixed_masks:\n if m == varying: continue\n\n all_fixed_mask &= fixed_masks[m]\n\n any_found = np.any(all_fixed_mask)\n\n if not any_found:\n print(\"No tracks found. :(\")\n mask_lens = {k:len(x[x==True]) for k, x in fixed_masks.items()}\n print(\"mask `True` counts:\")\n for m, c in mask_lens.items():\n print(f\"{m:<6}: {c}\")\n else:\n track_ids = unq['id'][all_fixed_mask]\n # sort them:\n sort_mask = np.argsort(unq[varying][all_fixed_mask])\n track_ids = track_ids[sort_mask]\n track_count = len(track_ids)\n print(f\"{track_count} tracks found.\")\n\n if not any_found or 'guide' in argv:\n print(\"Plotting a helpful diagram\")\n m_shift = (m_ax - solar_mass) / range_mass\n feh_shift = (feh_ax - solar_Z) / range_Z\n Y_shift = (Y_ax - solar_Y) / range_Y\n alpha_shift = (alpha_ax - center_alpha) / range_alpha\n diff_shift = (diff_ax - center_diff) / range_diff\n over_shift = (over_ax - center_over) / range_over\n plt.plot(m_shift, '.', label=mass_key)\n plt.plot(feh_shift, '.', label='Z')\n plt.plot(Y_shift, '.', label='Y')\n plt.plot(alpha_shift, '.', label='alpha')\n plt.plot(diff_shift, '.', label='diff')\n plt.plot(over_shift, '.', label='over')\n all_points = np.array([feh_shift, Y_shift, alpha_shift, diff_shift, over_shift, m_shift])\n mins = np.min(all_points, axis=0)\n maxs = np.max(all_points, axis=0)\n for m, mn, mx in zip(np.arange(len(m_shift)), mins, maxs):\n plt.plot([m, m], [mn, mx], linewidth=1, color='gray')\n plt.axhline(1)\n plt.axhline(-1)\n if any_found:\n found_idxs = np.flatnonzero(all_fixed_mask)\n plt.plot(found_idxs, 0*found_idxs, 'rx', label=\"picked tracks\")\n plt.ylabel(\"ranges from center value\")\n plt.xlabel(\"Unique track\")\n plt.legend()\n # plt.show()\n\n if not any_found:\n plt.show()\n exit()\n\n plt.figure(f\"{varying}_var\")\n\n # return np.argmin(abs_d)\n\n # def degen_ep(track):\n # return np.argmax(track.center_degeneracy)\n\n trackset = sg.TrackSet(\n *[ sg.get_track_from_id(id, 'log_R', 'star_age', 'center_h1') for id in track_ids ]\n )\n\n trackss = trackset\n\n trackset.add_ep_func(zams_ep)\n trackset.add_ep_func(h_depletion)\n trackset.add_ep_func(density_eps)\n ep_labels = ['ZAMS', 'H depletion', '1% Solar Avg Density']\n\n\n\n # The rough left/right shift of tracks:\n shift = int(np.sign(trackset[1].T_ax[0] - trackset[0].T_ax[0]))\n\n for i, track in enumerate(trackset):\n last_track = i + 1 == len(trackset)\n\n R = 10**track.log_R\n T = track.T_ax\n\n numax_ax = track.M / ((R**2) * np.sqrt(T/5777.)) * 3100\n nupk = max(numax_ax)\n\n if not last_track:\n eps_this = trackset.get_ep_points(i) # shape (, 2)\n eps_next = trackset.get_ep_points(i + 1)\n eps_shift = eps_next - eps_this\n ep_shifts[varying] += eps_shift\n\n for e in range(trackset.num_eps):\n nu_shift = np.zeros(trackset.num_eps)\n nu_shift[e] = (\n trackset.interp_ep(i, e, nupk - numax_ax) -\n trackset.interp_ep(i + 1, e, nupk - numax_ax)\n )\n ep_nu_shifts[varying] += nu_shift\n print(ep_nu_shifts)\n if not no_plot:\n plt.quiver(\n eps_this[e, 0], eps_this[e, 1],\n eps_shift[e, 0], eps_shift[e, 1],\n **quiver_kwargs, color=f\"C{e}\", width=0.003,\n label=(ep_labels[e] if i == 0 else None)\n )\n\n vary_val = track.__getattribute__(varying)\n vary_vals[varying].append(vary_val)\n\n s = f\"{varying}: {vary_val:.4f}\"\n\n print(s)\n\n if last_track or i == 0:\n midpoint = int(len(track) * .75)\n data_point = (track.T_ax[midpoint], track.L_ax[midpoint])\n ha_i, ha_f = ['left', 'right'][::shift]\n if i == 0:\n text_point = (data_point[0]-shift*0.005, data_point[1])\n plt.annotate(\n s, data_point, xytext=text_point,\n size='small', ha=ha_i)\n else:\n text_point = (data_point[0]+shift*0.005, data_point[1])\n plt.annotate(\n s, data_point, xytext=text_point,\n size='small', ha=ha_f)\n\n if not no_plot:\n age_ax = ((track.star_age) / 15e9)\n # age_ax /= age_ax[-1]\n step = 4\n for k in range(trackset.eps[i][0], len(track.T_ax), step):\n T = track.T_ax[k:k+step+1]\n L = numax_ax[k:k+step+1]\n age = age_ax[k]\n plt.loglog(T, L, '-', color=get_colour(age))\n\n # h= plt.plot(track.star_age, track.mass_conv_core)\n\n ep_shifts[varying] /= (len(trackset) - 1)\n\n if not no_plot:\n plt.title(f\"Evolutionary tracks with varying {varying}, colour coded by Age / 10 Gyr\")\n plt.gca().invert_xaxis()\n plt.gca().invert_yaxis()\n plt.legend(title=\"Evolutionary stages\")\n plt.xlabel(r\"$T_{eff} [K]$\")\n plt.ylabel(r\"$L$ [solar]\")\n plt.show()\n\nif __name__ == '__main__':\n if run_all:\n for v in valid_vary:\n varying = v\n run()\n\n plt.close('all')\n\n fig = plt.figure('all_vary')\n axes = fig.subplots(ncols=3, nrows=2)\n\n arrow_mags = {\n 'M' : [0.01, 0.01, 0.01],\n 'Y' : [0.01, 0.01, 0.01],\n 'Z' : [0.0025, 0.0025, 0.001],\n 'alpha': [0.2, 0.2, 0.05]\n }\n\n for var, vals in vary_vals.items():\n vals = np.array(vals)\n vals = vals[1:] - vals[:-1]\n mean = np.mean(vals)\n ep_shifts[var] /= mean\n ep_nu_shifts[var] /= mean\n\n vary_vals[var] = mean\n\n for i, ax in enumerate(axes[0]):\n title = ep_labels[i]\n ax.set_title(title)\n ax.set_xlabel(r\"$T_{eff} [K]$\")\n ax.set_ylabel(r\"$L$ [solar]\")\n ax.invert_xaxis()\n\n for k, var in enumerate(valid_vary):\n arr_mag = arrow_mags[var][i]\n (u, v) = ep_shifts[var][i] * arr_mag\n ax.quiver(\n u, v, **quiver_kwargs, width=0.007, label=f\"{var} [+{arr_mag*100}%]\",\n color=f'C{k}')\n\n ax.legend()\n ax.set_xlim(150, -150)\n ax.set_ylim(-0.2, 0.2)\n\n for i, ax in enumerate(axes[1]):\n title = ep_labels[i]\n ax.set_title(title)\n ax.set_xlabel(r\"$T_{eff} [K]$\")\n ax.set_ylabel(r\"$\\nu_{max}$\")\n ax.invert_xaxis()\n\n for k, var in enumerate(valid_vary):\n arr_mag = arrow_mags[var][i]\n u = ep_shifts[var][i][0] * arr_mag\n v = ep_nu_shifts[var][i] * arr_mag\n ax.quiver(\n u, v, **quiver_kwargs, width=0.007, label=f\"{var} [+{arr_mag*100}%]\",\n color=f'C{k}')\n\n\n ax.legend()\n ax.set_xlim(150, -150)\n ax.set_ylim(1500, -1500)\n\n\n plt.show()\n else:\n run()\n","repo_name":"LCarnovale/ResearchAstro","sub_path":"plot_2.py","file_name":"plot_2.py","file_ext":"py","file_size_in_byte":10999,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"60"} +{"seq_id":"32108223528","text":"#!/usr/bin/env python\nimport os\nfrom rich.console import Console\nimport re\nimport dotenv\nfrom utils.console import handle_input\n\nconsole = Console()\n\nsuccess = True\n\n\ndef check_env() -> bool:\n if not os.path.exists(\".env.template\"):\n console.print(\"[red]Couldn't find .env.template. Unable to check variables.\")\n return False\n with open(\".env.template\", \"r\") as template:\n # req_envs = [env.split(\"=\")[0] for env in template.readlines() if \"=\" in env]\n matching = {}\n explanations = {}\n req_envs = []\n var_optional = False\n for line in template.readlines():\n if \"=\" in line and var_optional is not True:\n req_envs.append(line.split(\"=\")[0])\n elif \"#OPTIONAL\" in line:\n var_optional = True\n elif line.startswith(\"#MATCH_REGEX \"):\n matching[req_envs[-1]] = line.removeprefix(\"#MATCH_REGEX \")[:-1]\n var_optional = False\n elif line.startswith(\"#EXPLANATION \"):\n explanations[req_envs[-1]] = line.removeprefix(\"#EXPLANATION \")[:-1]\n var_optional = False\n else:\n var_optional = False\n missing = []\n incorrect = []\n dotenv.load_dotenv()\n for env in req_envs:\n value = os.getenv(env)\n if value is None:\n missing.append(env)\n continue\n if env in matching.keys():\n env, re.match(matching[env], value) is None and incorrect.append(env)\n if len(missing):\n for i in range(len(missing)):\n try:\n missing[i] = missing[i] + \": \" + explanations[missing[i]]\n except KeyError:\n pass\n console.print(\n f\"[red]{'These variables are'*(len(missing) > 1) or 'This variable is'} non-optional and missing: \\n\\n\"\n + \"\\n\\n\".join(missing)\n )\n success = False\n if len(incorrect):\n console.print(\n f\"[red]{'These variables are'*(len(incorrect) > 1) or 'This variable is'} set incorrectly: \"\n + \"\\n\".join(incorrect)\n )\n success = False\n # if success is True:\n # return True\n # console.print(\"[green]Do you want to enter the missing variables by hand(y/n)\")\n # if not input().casefold().startswith(\"y\"):\n # console.print(\"[red]Aborting: Unresolved missing variables\")\n # return success\n # with open(\".env\", \"a\") as env_file:\n # for env in missing:\n # pass\n return success\n\n\nif __name__ == \"__main__\":\n check_env()\n","repo_name":"aldo1234aldo/ooo","sub_path":"utils/checker.py","file_name":"checker.py","file_ext":"py","file_size_in_byte":2551,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"60"} +{"seq_id":"6277929017","text":"import random\n\n#Moneycounter\nmoneycount = 0\n\n#Gamestart\ndef start():\n print(\" You have\", moneycount,\"DKK. Press e for exit, d for desk, q for queue, t for trashcan, m for empty table, o for old man, c for cleaning staff, f for family.\")\n user_input = input(\":\")\n#Go to exit\n if user_input == \"e\" or user_input == \"E\":\n Exit()\n#Go to desk\n elif user_input == \"d\" or user_input == \"D\":\n desk()\n#Go to queue\n elif user_input == \"q\" or user_input == \"Q\":\n queue()\n#Go to trashcan\n elif user_input == \"t\" or user_input == \"T\":\n trashcan()\n#Go to empty table\n elif user_input == \"m\" or user_input == \"M\":\n empty_table()\n#Go to old man\n elif user_input == \"o\" or user_input == \"O\":\n old_man()\n#Go to cleaning staff\n elif user_input == \"c\" or user_input == \"C\":\n cleaning()\n#Go to family\n elif user_input == \"f\" or user_input == \"F\":\n family()\n #Wrong key\n else:\n print(\"Try again\")\n\n#exit\ndef Exit():\n global moneycount\n global running\n print(\"You are at the exit. Give up? y=yes, n=no\")\n user_input = input(\":\")\n if user_input == \"y\" or user_input == \"Y\":\n print(\"You gave up. You had \", moneycount, \"DKK\")\n running = False\n elif user_input == \"n\" or user_input == \"N\":\n pass\n\n#desk\ndef desk():\n global moneycount\n print(\"You are at the desk. You have \", moneycount, \"DKK.\")\n if moneycount >= 65:\n print(\"You have enough money for a burger, do you wanna buy? y=yes, n=no.\")\n user_input = input(\":\")\n if user_input == \"y\" or user_input == \"Y\":\n print(\"You have now bought a burger.\")\n moneycount = moneycount-65\n elif user_input == \"n\" or user_input == \"N\":\n print(\"You have not bought a burger.\")\n elif moneycount < 65:\n print(\"You cannot afford a burger.\")\n\n#Kø\ndef queue():\n global moneycount\n print(\"You are at the queue. Do you start begging for money (b) or du you start stealing (s)? \")\n user_input = input(\":\")\n if user_input == \"b\" or user_input == \"B\":\n print(\"You beg for money.\")\n x = random.choice([1,1,0,2,3,0,0,0,0.5,0.5])\n moneycount = moneycount+x\n print(\"You got \", x, \"DKK from begging\")\n elif user_input == \"s\" or user_input == \"S\":\n print(\"You steal money.\")\n x = random.choice([1,2,0,2,3,0,0,0,5,2])\n moneycount = moneycount+x\n print(\"You got \", x, \"DKK from stealing\")\n\n#trashcan\ndef trashcan():\n global running\n print(\"You are at the trashcan. Are you looking for a burger (b)? Or are you looking for bottle deposit (d)?\")\n user_input = input(\":\")\n if user_input == \"d\" or user_input == \"D\":\n print(\"You are looking for bottle deposit, unfortunately there are no bottle deposit at McDonalds.\")\n elif user_input == \"b\" or user_input == \"B\":\n print(\"You are looking for a burger.\")\n x = random.choice([\"a mouse\", \"a burger\", \"nothing\", \"nothing\", \"nothing\", \"nothing\", \"nothing\", \"nothing\",\"a mouse\",\"nothing\"])\n if x == \"a burger\":\n print(\"YOU FOUND A BURGER AND WON THE GAME!\")\n running = False\n else:\n print(\"You found \",x)\n\n \n#empty table\ndef empty_table():\n global moneycount\n print(\"You are at the empty table. Du you wanna cry(c) or look for money(l)?\")\n user_input = input(\":\")\n if user_input == \"c\" or user_input == \"C\":\n print(\"You cry.\")\n elif user_input == \"l\" or user_input == \"L\":\n print(\"You look for money under the table.\")\n x = random.choice([0,2,2,1,1,0.5,0.5,0,1,0.5])\n moneycount = moneycount+x\n print(\"You found\",x,\"DKK under the table.\")\n\n#The old man\ndef old_man():\n print(\"You are at the old man. Du you want to offer him a good time in your bedroom (b). Du you want to listen to him talking about the good old days (l)\")\n user_input = input(\":\")\n if user_input == \"b\" or user_input == \"B\":\n print(\"You offer him a good time in your bedroom, he refuses ...\")\n elif user_input == \"l\" or user_input == \"L\":\n print(\"You listen to him talking about the good old days, while you are hoping that he offers you a burger.\")\n print(\"But he doesn't.\")\n\n#Cleaning staff\ndef cleaning():\n global moneycount\n print(\"You are at the cleaning staff and want to work. Do you want a legal (l) or illegal (i) job?\")\n user_input = input(\":\")\n if user_input == \"l\" or user_input == \"L\":\n print(\"You offer to work legal. The cleaning staff tells you to wait for the boss to arrive. You wait for hours and die from hunger.\")\n elif user_input == \"i\" or user_input == \"I\":\n x = random.choice([\"wash the floor\",\"empty the trashcan\",\"wash the windows\", \"cleanse the toilets\"])\n if x == \"wash the floor\":\n y = 3\n elif x == \"empty the trashcan\":\n y = 1\n elif x == \"wash the windows\":\n y = 4\n elif x == \"cleanse the toilets\":\n y = 6\n moneycount = moneycount+y\n print(\"You offer to work illegal. The cleaning staff tells you to \",x,\".\")\n print(\"You do, and the cleaning staff gives you\", y, \"DKK for the job\")\n\n#Family\ndef family():\n global moneycount\n print(\"You are at the family. Do you wanna take the children and blackmail the parents (b), or do you offer to take care of the children for the parents (c).\")\n user_input = input(\":\")\n if user_input == \"b\" or user_input == \"B\":\n print(\"You take the children and blackmail the family.\")\n print(\"How much do you want for the children?\")\n user_input = input(\":\")\n user_input = int(user_input)\n if user_input <= 50:\n moneycount = moneycount + user_input\n print(\"The family gives you the money!\")\n elif user_input > 50:\n print(\"The family do not want to pay that much for the children. They just leave you with the chying kids.\")\n elif user_input == \"c\" or user_input == \"C\":\n print(\"You offer to take care of the children.\")\n\n#run game\nrunning = True\nwhile running:\n start()\n","repo_name":"BruceBannerr/Mcd_spil","sub_path":"mcd.py","file_name":"mcd.py","file_ext":"py","file_size_in_byte":6114,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"60"} +{"seq_id":"30991903042","text":"from datetime import date\r\nmenor_idade = 0\r\nmaior_idade = 0\r\nfor pessoa in range(1, 8):\r\n ano = int(input(f'Em que ano a {pessoa}ª pessoa nasceu? '))\r\n if date.today().year - ano > 18:\r\n maior_idade += 1\r\n else:\r\n menor_idade += 1\r\nprint(\r\n f'Ao todo tivemos {maior_idade} pessoas maiores de idade\\nE também tivemos {menor_idade} menores de idade')\r\n","repo_name":"fabiano-filho/python-curso-em-video","sub_path":"ex054.py","file_name":"ex054.py","file_ext":"py","file_size_in_byte":378,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"60"} +{"seq_id":"44702012760","text":"'''\nGiven a binary tree, find its maximum depth.\n\nThe maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.\n\nNote: A leaf is a node with no children.\n\nExample:\n\nGiven binary tree [3,9,20,null,null,15,7],\n\n 3\n / \\\n 9 20\n / \\\n 15 7\n\n'''\n# recurve to find the max depth\n# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\nclass Solution(object):\n def maxDepth(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: int\n \"\"\"\n depth = 0\n if (root):\n lchilddeep = self.maxDepth(root.left)\n rchilddeep = self.maxDepth(root.right)\n if lchilddeep >= rchilddeep:\n depth = lchilddeep+1\n else:\n depth = rchilddeep+1\n return depth","repo_name":"MajestyLee/leetcode_TopInterview","sub_path":"104.py","file_name":"104.py","file_ext":"py","file_size_in_byte":927,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"60"} +{"seq_id":"11760469126","text":"# Python Program to make a scrollable frame \n# using Tkinter \n \nfrom tkinter import *\n \nclass ScrollBar: \n \n # constructor \n def __init__(self): \n \n # create root window \n root = Tk() \n \n # create a horizontal scrollbar by \n # setting orient to horizontal \n h = Scrollbar(root, orient = 'horizontal') \n \n # attach Scrollbar to root window at \n # the bootom \n h.pack(side = BOTTOM, fill = X) \n \n # create a vertical scrollbar-no need \n # to write orient as it is by \n # default vertical \n v = Scrollbar(root) \n \n # attach Scrollbar to root window on \n # the side \n v.pack(side = RIGHT, fill = Y) \n \n \n # create a Text widget with 15 chars \n # width and 15 lines height \n # here xscrollcomannd is used to attach Text \n # widget to the horizontal scrollbar \n # here yscrollcomannd is used to attach Text \n # widget to the vertical scrollbar \n t = Text(root, width = 15, height = 15, wrap = NONE, \n xscrollcommand = h.set, \n yscrollcommand = v.set) \n \n # insert some text into the text widget \n for i in range(20): \n t.insert(END,\"this is some text\\n\") \n \n # attach Text widget to root window at top \n t.pack(side=TOP, fill=X) \n \n # here command represents the method to \n # be executed xview is executed on \n # object 't' Here t may represent any \n # widget \n h.config(command=t.xview) \n \n # here command represents the method to \n # be executed yview is executed on \n # object 't' Here t may represent any \n # widget \n v.config(command=t.yview) \n \n # the root window handles the mouse \n # click event \n root.mainloop() \n \n# create an object to Scrollbar class \ns = ScrollBar() \n\n#==============================\n\nimport sys\nimport random\nimport matplotlib\nimport matplotlib.pyplot as plt\n\nfrom PyQt5.QtWidgets import (\n QWidget,\n QApplication,\n QMainWindow,\n QVBoxLayout,\n QScrollArea,\n )\n\nfrom matplotlib.backends.backend_qt5agg import (\n FigureCanvasQTAgg as FigCanvas,\n NavigationToolbar2QT as NabToolbar,\n )\n\n# Make sure that we are using QT5\nmatplotlib.use('Qt5Agg')\n\n# create a figure and some subplots\nFIG, AXES = plt.subplots(ncols=4, nrows=5, figsize=(16,16))\n\nfor AX in AXES.flatten():\n random_array = [random.randint(1, 30) for i in range(10)]\n AX.plot(random_array)\n\ndef main():\n app = QApplication(sys.argv)\n window = MyApp(FIG)\n sys.exit(app.exec_())\n\nclass MyApp(QWidget):\n def __init__(self, fig):\n super().__init__()\n self.title = 'VERTICAL, HORIZONTAL SCROLLABLE WINDOW : HERE!'\n self.posXY = (700, 40)\n self.windowSize = (1200, 800)\n self.fig = fig\n self.initUI()\n\n def initUI(self):\n QMainWindow().setCentralWidget(QWidget())\n\n self.setLayout(QVBoxLayout())\n self.layout().setContentsMargins(0, 0, 0, 0)\n self.layout().setSpacing(0)\n\n canvas = FigCanvas(self.fig)\n canvas.draw()\n\n scroll = QScrollArea(self)\n scroll.setWidget(canvas)\n\n nav = NabToolbar(canvas, self)\n self.layout().addWidget(nav)\n self.layout().addWidget(scroll)\n\n self.show_basic()\n\n def show_basic(self):\n self.setWindowTitle(self.title)\n self.setGeometry(*self.posXY, *self.windowSize)\n self.show()\n\n\nif __name__ == '__main__':\n main()\n\n\n#=================\n\n\nimport math\nimport sys\n\nfrom tkinter import Tk, Button, Frame, Canvas, Scrollbar\nimport tkinter.constants as Tkconstants\n\nfrom matplotlib import pyplot as plt\nfrom matplotlib.backends.backend_tkagg import FigureCanvasTkAgg\nimport pprint\n\nframe = None\ncanvas = None\n\ndef printBboxes(label=\"\"):\n global canvas, mplCanvas, interior, interior_id, cwid\n print(\" \"+label,\n \"canvas.bbox:\", canvas.bbox(Tkconstants.ALL),\n \"mplCanvas.bbox:\", mplCanvas.bbox(Tkconstants.ALL))\n\ndef addScrollingFigure(figure, frame):\n global canvas, mplCanvas, interior, interior_id, cwid\n # set up a canvas with scrollbars\n canvas = Canvas(frame)\n canvas.grid(row=1, column=1, sticky=Tkconstants.NSEW)\n\n xScrollbar = Scrollbar(frame, orient=Tkconstants.HORIZONTAL)\n yScrollbar = Scrollbar(frame)\n\n xScrollbar.grid(row=2, column=1, sticky=Tkconstants.EW)\n yScrollbar.grid(row=1, column=2, sticky=Tkconstants.NS)\n\n canvas.config(xscrollcommand=xScrollbar.set)\n xScrollbar.config(command=canvas.xview)\n canvas.config(yscrollcommand=yScrollbar.set)\n yScrollbar.config(command=canvas.yview)\n\n # plug in the figure\n figAgg = FigureCanvasTkAgg(figure, canvas)\n mplCanvas = figAgg.get_tk_widget()\n #mplCanvas.grid(sticky=Tkconstants.NSEW)\n\n # and connect figure with scrolling region\n cwid = canvas.create_window(0, 0, window=mplCanvas, anchor=Tkconstants.NW)\n printBboxes(\"Init\")\n canvas.config(scrollregion=canvas.bbox(Tkconstants.ALL),width=200,height=200)\n\n# def changeSize(figure, factor):\n# global canvas, mplCanvas, interior, interior_id, frame, cwid\n# oldSize = figure.get_size_inches()\n# print(\"old size is\", oldSize)\n# figure.set_size_inches([factor * s for s in oldSize])\n# wi,hi = [i*figure.dpi for i in figure.get_size_inches()]\n# print(\"new size is\", figure.get_size_inches())\n# print(\"new size pixels: \", wi,hi)\n# mplCanvas.config(width=wi, height=hi) ; printBboxes(\"A\")\n# #mplCanvas.grid(sticky=Tkconstants.NSEW)\n# canvas.itemconfigure(cwid, width=wi, height=hi) ; printBboxes(\"B\")\n# canvas.config(scrollregion=canvas.bbox(Tkconstants.ALL),width=200,height=200)\n# figure.canvas.draw() ; printBboxes(\"C\")\n# print()\n\nif __name__ == \"__main__\":\n root = Tk()\n# root.rowconfigure(1, weight=1)\n# root.columnconfigure(1, weight=1)\n\n frame = Frame(root)\n frame.grid(column=1, row=1, sticky=Tkconstants.NSEW)\n frame.rowconfigure(1, weight=1)\n frame.columnconfigure(1, weight=1)\n\n figure = plt.figure(dpi=150, figsize=(4, 4))\n plt.plot(range(10), [math.sin(x) for x in range(10)])\n\n addScrollingFigure(figure, frame)\n\n# buttonFrame = Frame(root)\n# buttonFrame.grid(row=1, column=2, sticky=Tkconstants.NS)\n# biggerButton = Button(buttonFrame, text=\"larger\",\n# command=lambda : changeSize(figure, 1.5))\n# biggerButton.grid(column=1, row=1)\n# smallerButton = Button(buttonFrame, text=\"smaller\",\n# command=lambda : changeSize(figure, .5))\n# smallerButton.grid(column=1, row=2)\n\n root.mainloop()\n\n#=============\n\n\nfrom tkinter import * \n\nfrom numpy import arange, sin, pi\nfrom matplotlib.backends.backend_tkagg import FigureCanvasTkAgg\n\nfrom matplotlib.figure import Figure\n\nclass App(Tk):\n def __init__(self):\n Tk.__init__(self)\n # self.configure(width=400, height=400)\n\n\n # f = Figure(figsize=(6, 5), dpi=100)\n # a = f.add_subplot(111)\n # t = arange(0.0, 3.0, 0.01)\n # s = sin(2*pi*t)\n # a.plot(t, s)\n\n canvas = FigureCanvasTkAgg(f, self)\n canvas.show()\n canvas.get_tk_widget().grid(row=0, column=0)\n\n vbar=Scrollbar(self, orient = VERTICAL)\n vbar.grid(row=0, column=1) \n hbar=Scrollbar(self, orient=HORIZONTAL)\n hbar.grid(row=1, column=0)\n\n\n canvas.get_tk_widget().config(xscrollcommand=hbar.set, yscrollcommand = vbar.set)\n\n hbar.config(command=canvas.get_tk_widget().xview)\n vbar.config(command=canvas.get_tk_widget().yview)\n\n\n\nif __name__ == \"__main__\":\n app = App()\n app.geometry(\"400x400+51+51\")\n app.title(\"Test\")\n app.mainloop()\n\n\n #======================\n\n\n\nimport tkinter as tk # python 3\n# import Tkinter as tk # python 2\n\nclass Example(tk.Frame):\n def __init__(self, root):\n\n tk.Frame.__init__(self, root)\n self.canvas = tk.Canvas(root, borderwidth=0, background=\"#ffffff\")\n self.frame = tk.Frame(self.canvas, background=\"#ffffff\")\n self.vsb = tk.Scrollbar(root, orient=\"vertical\", command=self.canvas.yview)\n self.canvas.configure(yscrollcommand=self.vsb.set)\n\n self.vsb.pack(side=\"right\", fill=\"y\")\n self.canvas.pack(side=\"left\", fill=\"both\", expand=True)\n self.canvas.create_window((4,4), window=self.frame, anchor=\"nw\", \n tags=\"self.frame\")\n\n self.frame.bind(\"\", self.onFrameConfigure)\n\n self.populate()\n\n def populate(self):\n '''Put in some fake data'''\n for row in range(100):\n tk.Label(self.frame, text=\"%s\" % row, width=3, borderwidth=\"1\", \n relief=\"solid\").grid(row=row, column=0)\n t=\"this is the second column for row %s\" %row\n tk.Label(self.frame, text=t).grid(row=row, column=1)\n\n def onFrameConfigure(self, event):\n '''Reset the scroll region to encompass the inner frame'''\n self.canvas.configure(scrollregion=self.canvas.bbox(\"all\"))\n\nif __name__ == \"__main__\":\n root=tk.Tk()\n Example(root).pack(side=\"top\", fill=\"both\", expand=True)\n root.mainloop()\n\n\n#===============\nimport tkinter as tk\nimport numpy as np\nfrom matplotlib.backends.backend_tkagg import FigureCanvasTkAgg\nfrom matplotlib.figure import Figure\n \nclass tkintertool:\n def __init__(self,master):\n self.clicks= 0 \n self.master = master\n \n master.geometry(\"2000x1000\")\n \n self.myframe = tk.Frame(master,relief=tk.GROOVE,width=500,height=300,bd=1,background=\"blue\")\n self.myframe.grid(row=0,column=0)\n \n self.canvas=tk.Canvas(self.myframe,background=\"green\")\n self.frame=tk.Frame(self.canvas,background=\"red\")\n \n button = tk.Button(master,text='click',command=lambda: self.data())\n \n myscrollbar=tk.Scrollbar(self.myframe,orient=\"vertical\",command=self.canvas.yview)\n myscrollbarx=tk.Scrollbar(self.myframe,orient=\"horizontal\",command=self.canvas.xview)\n self.canvas.configure(yscrollcommand=myscrollbar.set,xscrollcommand=myscrollbarx.set)\n \n myscrollbar.pack(side=\"right\",fill=\"y\")\n myscrollbarx.pack(side=\"bottom\",fill=\"x\")\n button.grid(row=2,column=0)\n self.canvas.pack(side=\"left\")\n self.canvas.create_window((0,0),window=self.frame,anchor='nw')\n self.frame.bind(\"\",self.myfunction())\n size = (self.frame.winfo_reqwidth(), self.frame.winfo_reqheight())\n print(size)\n def data(self):\n self.clicks+=1\n self.frame.bind(\"\",self.myfunction())\n shape = np.random.randint(0,(3),[5,5])\n lon = np.arange(5)\n lat = np.arange(5)\n fig = Figure(figsize=(4,4))\n ax = fig.add_subplot(111)\n c = ax.pcolor(lon,lat,shape)\n fig.colorbar(c,ax=ax,fraction=0.046,pad=0.04)\n canvas = FigureCanvasTkAgg(fig,self.frame)\n canvas.get_tk_widget().grid(row=0,column=(self.clicks))\n # self.canvas.config(scrollregion='0 0 %s %s' % size)\n \n def myfunction(self):\n self.canvas.configure(scrollregion=(0,0,288*(self.clicks),288),width=500,height=300)\n \nroot = tk.Tk()\nmy_gui = tkintertool(root)\nroot.mainloop()","repo_name":"alexnesov/Tkinter-toolbox-Python-GUI","sub_path":"Scrollbar.py","file_name":"Scrollbar.py","file_ext":"py","file_size_in_byte":11409,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"60"} +{"seq_id":"36147247858","text":"# ---------------------------------- imports --------------------------------- #\nimport os\nimport requests\nfrom bs4 import BeautifulSoup\nimport pandas as pd\nimport logging\n\n# local imports\nfrom df import *\nfrom browser_manager import Browser\nfrom scraper import Scraper, ids\nfrom mp import MP, MP_Site\nfrom throttle import Throttle\nfrom paths import current_folder, data_folder, logs_folder\n\n# ------------------------------------- < ------------------------------------ #\n\n\n# create log file\nlogging.basicConfig(\n filename=f\"{logs_folder}/sejm.log\",\n level=logging.INFO,\n format=\"%(asctime)s:%(levelname)s:%(message)s\"\n)\n\n\n# scrape mp data function\ndef scrape_mp_data(mp_index, browser, throttle):\n\n # create MP_Site object, to get mp_info_site url\n url = MP_Site(mp_index).mp_info_site\n\n # use throttle module to wait before making a request\n throttle.wait()\n\n # check if server responds\n throttle.try_get_response(url, browser.driver)\n\n # get html from browser\n html = browser.driver.page_source\n\n # pass html to Scraper\n scraper = Scraper(html)\n\n # get political info data\n elected_date, party_list, constituency, no_of_votes, oath_date, club_name, parliamentary_experience = scraper.get_political_info()\n\n # get personal info data\n name, surname, birth_date, birth_place, education, school, profession = scraper.get_personal_info()\n\n # get email address\n email = scraper.get_email_address()\n\n # create MP object\n mp = MP(\n mp_index,\n name,\n surname,\n url,\n constituency,\n elected_date,\n party_list,\n no_of_votes,\n oath_date,\n parliamentary_experience,\n club_name,\n birth_date,\n education,\n school,\n profession,\n email\n )\n\n # return MP object\n return mp\n\n\ndef main():\n\n # create browser object\n browser = Browser()\n\n # create throttle object\n throttle = Throttle(2)\n\n # iterate over all MPs\n for i in ids:\n\n # load mps_df\n mps_df = load_df()\n\n # log\n logging.info(f\"Scraping MP index: {i}\")\n\n # check if MP index is already in the id column of the dataframe\n if check_if_id_exists(i, mps_df) == True:\n continue\n\n # scrape mp data\n mp = scrape_mp_data(i, browser, throttle)\n\n # append mp data to mps_df\n new_df = insert_mp_to_df(mp, mps_df)\n\n # save updated dataframe to csv\n save_df_to_csv(new_df)\n\n # quit browser\n browser.driver.quit()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"seszele64/sejm-data-scraper","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2585,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"60"} +{"seq_id":"5500642671","text":"import pandas as pd\n\ndef m_add(safra_ini, qt):\n return (pd.to_datetime(safra_ini, format=\"%Y%m\") + pd.DateOffset(months=qt)).strftime(\"%Y%m\")\n\nclass Query(object):\n def __init__(self):\n self.main_table = None\n self._all_tables = []\n self._join_list = []\n self._variables = []\n self._filters = []\n\n def _in_var_list(self, var_name):\n for var in self._variables:\n if var_name == var.name:\n return True\n return False\n\n def _in_table_list(self, table_name):\n for tb in self._all_tables:\n if table_name == tb.table_name:\n return True\n return False\n\n def _get_table_ref(self, table_name):\n for tb in self._all_tables:\n if table_name == tb.table_name:\n return tb\n raise ValueError(\"Table not in table list.\")\n\n def _get_filters(self):\n if len(self._filters)>0:\n filter_start = 'WHERE \\n'\n filters = '\\nAND\\n'.join(['\\t{} {} {}'.format(filter.var_name,filter.operator,filter.value) for filter in self._filters])\n return filter_start + filters\n else:\n return ''\n\n def _gen_join_condition(self, tb):\n if len(tb.table_key) > 1:\n return ' AND\\n'.join([\"{main_alias}.{main_key}={alias}.{key}\".format(alias=tb.table_alias,\n key=key,\n main_alias=self.main_table.table_alias,\n main_key=main_key)\n for key, main_key in zip(tb.table_key,\n self.main_table.table_key)])\n else:\n return \"{main_alias}.{main_key}={alias}.{key}\".format(alias=tb.table_alias,\n key=tb.table_key[0],\n main_alias=self.main_table.table_alias,\n main_key=self.main_table.table_key[0])\n\n\n def _get_table_joins(self):\n return '\\n'.join(['''LEFT JOIN\\n\\t{db}.{tb} {alias}\\nON {condition}'''.format(db=tb.database,\n tb=tb.table_name,\n alias=tb.table_alias,\n condition=self._gen_join_condition(tb))\n if tb.database != ''\n else\n '''LEFT JOIN\\n\\t{tb} {alias}\\nON {condition}'''.format(tb=tb.table_name,\n alias=tb.table_alias,\n condition=self._gen_join_condition(tb))\n for tb in self._join_list])\n\n def _get_main_table(self):\n main_tb_part = '\\t{}.{} {}'.format(self.main_table.database,self.main_table.table_name, self.main_table.table_alias)\n if self.main_table.database == '':\n main_tb_part = '\\t{} {}'.format(self.main_table.table_name, self.main_table.table_alias)\n return main_tb_part\n\n def _get_all_variables(self):\n all_vars = ',\\n'.join(['\\t{} as {}'.format(var.name, var.alias)\n if var.fl_case_when else\n '\\t{}.{}'.format(var.table.table_alias,var.name)\n if not var.flag_alias else\n '\\t{}.{} as {}'.format(var.table.table_alias,\n var.name,\n var.alias)\n for var in self._variables])\n return all_vars\n\n def __str__(self):\n\n query = \"SELECT\\n{}\\nFROM\\n{}\\n{}\\n{}\".format(self._get_all_variables(),\n self._get_main_table(),\n self._get_table_joins(),\n self._get_filters())\n\n return query\n\n @staticmethod\n def create():\n return QueryBuilder(Query())\n\nclass QueryBuilder(object):\n \"\"\"docstring for QueryBuilder.\"\"\"\n\n def __init__(self, query=Query()):\n self.query = query\n\n @property\n def variable(self):\n return QueryVariableBuilder(self.query)\n\n @property\n def left_join(self):\n return QueryLeftJoinBuilder(self.query)\n\n @property\n def main_table(self):\n return QueryMainTableBuilder(self.query)\n\n @property\n def case_when(self):\n return QueryCaseWhenBuilder(self.query)\n\n # Next properties I will implement for the QueryBuilder\n # @property\n # def group_by(self):\n # return QueryGroupByBuilder(self.query)\n #\n @property\n def where(self):\n return QueryWhereBuilder(self.query)\n #\n @property\n def agg_primitive(self):\n return QueryAggPrimitiveBuilder(self.query)\n\n def build(self):\n return self.query\n\n\nclass Condition:\n def __init__(self, var_name, operator, value, l_operator=' AND '):\n self.var_name = var_name\n self.operator = operator\n self.value = value\n self.l_operator = l_operator\n\nclass QueryWhereBuilder(QueryBuilder):\n def __init__(self, query):\n super().__init__(query)\n\n def add(self, var_name, operator, value):\n self.query._filters.append(\n Condition(\n var_name,\n operator,\n value\n )\n )\n return self\n\nclass QueryCaseWhenBuilder(QueryBuilder):\n def __init__(self, query):\n super().__init__(query)\n\n def add(self, table_name, var_name, var_alias, transformation):\n if not self.query._in_var_list(var_name):\n tb = self.query._get_table_ref(table_name=table_name)\n var_name = self._create_case_when(tb, var_name, transformation)\n tb.add_var(var_name, var_alias=var_alias, fl_case_when=True)\n self.query._variables.append(tb.variables[-1])\n return self\n\n def _create_case_when(self, tb, var_name, transformation):\n case = \"CASE\\n\"\n whens = []\n else_ = ''\n if transformation[-1][0]==\"else\":\n for line in transformation[:-1]:\n when = \"\\tWHEN\"\n for condition in line[:-1]:\n when += \" {tb_alias}.{var_name}\" + condition\n when += \" THEN \" + str(line[-1])\n whens += [when]\n whens = \"\\n\\t\".join(whens)\n else_ = \"\\n\\tELSE {} END\".format(transformation[-1][1])\n else:\n for line in transformation:\n when = \"\\tWHEN\"\n for condition in line[:-1]:\n when += \" {tb_alias}.{var_name}\" + condition\n when += \" THEN \" + str(line[-1])\n whens += [when]\n whens = \"\\n\\t\".join(whens)\n case_when = case + whens + else_\n return case_when.format(tb_alias=tb.table_alias, var_name=var_name)\n\nclass QueryAggPrimitiveBuilder(QueryBuilder):\n def __init__(self, query):\n super().__init__(query)\n\n def add(self, table_name_list, var_name_list, var_alias, primitive, x_range=None):\n tb_list = [self.query._get_table_ref(table_name=table_name)\n for table_name in table_name_list]\n var_name = \"\"\n if primitive == \"mean\":\n var_name = self._mean(tb_list, var_name_list)\n elif primitive == \"sum\":\n var_name = self._sum(tb_list, var_name_list)\n elif primitive == \"max\":\n var_name = self._max(tb_list, var_name_list)\n elif primitive == \"min\":\n var_name = self._min(tb_list, var_name_list)\n elif primitive == \"range\":\n var_name = self._range(tb_list, var_name_list)\n # elif primitive == \"meandiff\":\n # var_name = self._meandiff(tb_list, var_name_list)\n elif primitive == \"slope\":\n var_name = self._slope(tb_list, var_name_list, x_range)\n elif primitive == \"intercept\":\n var_name = self._intercept(tb_list, var_name_list, x_range)\n elif primitive == \"variance\":\n var_name = self._variance(tb_list, var_name_list)\n else:\n raise RuntimeError(\"Primitive %s not defined.\" %primitive)\n if not self.query._in_var_list(var_name):\n tb_list[0].add_var(var_name, var_alias=var_alias, fl_case_when=True)\n self.query._variables.append(tb_list[0].variables[-1])\n return self\n\n def _mean(self, tb_list, var_name_list):\n return \"({})/{}\".format(self._sum(tb_list, var_name_list),\n len(var_name_list))\n\n def _sum(self, tb_list, var_name_list):\n return \" + \".join([\"{}.{}\".format(tb.table_alias, var_name) \n for tb, var_name in zip(tb_list,var_name_list)])\n\n def _diff(self, tb_list, var_name_list):\n return \" + \".join([\"({}.{} - \".format(tb_list[i].table_alias, var_name_list[i]) +\n \"{}.{})\".format(tb_list[i+1].table_alias, var_name_list[i+1])\n for i in range(len(var_name_list)-1)])\n\n def _vars_as_args(self, tb_list, var_name_list):\n return \", \".join([\"{}.{}\".format(tb.table_alias, var_name) \n for tb, var_name in zip(tb_list,var_name_list)])\n\n def _max(self, tb_list, var_name_list):\n return \"greatest({})\".format(self._vars_as_args(tb_list, var_name_list))\n \n def _min(self, tb_list, var_name_list):\n return \"least({})\".format(self._vars_as_args(tb_list, var_name_list))\n\n def _range(self, tb_list, var_name_list):\n return \"\"\"greatest({variables}) -\\nleast({variables})\"\"\"\\\n .format(variables=self._vars_as_args(tb_list, var_name_list))\n \n def _meandiff(self, tb_list, var_name_list):\n return \"({})/{}\".format(self._diff(tb_list, var_name_list),\n len(var_name_list)-1)\n\n def _variance(self, tb_list, var_name_list):\n return (\"(({})/{}\".format(\" + \".join([\"{a}.{v}*{a}.{v}\".format(a=tb.table_alias,v=var_name) \n for tb, var_name in zip(tb_list,var_name_list)]),\n len(var_name_list)) + \n \" - ({m})*({m}))\".format(m=self._mean(tb_list, var_name_list)))\n\n def _x_sum_of_squares(self, x_range):\n m = sum(x_range)/len(x_range)\n return str(sum([x*x for x in x_range]) - len(x_range)*m*m)\n\n def _x_y_multiply(self, tb_list, var_name_list, x_range):\n multiply = \" + \".join([\"{}*{}.{}\".format(x,tb.table_alias, var_name) \n for x, tb, var_name in zip(x_range,tb_list,var_name_list)])\n return \"({})\".format(multiply)\n\n def _slope(self, tb_list, var_name_list, x_range):\n x_range_rev = x_range.copy()\n x_range_rev.reverse()\n y_mean = self._mean(tb_list, var_name_list)\n x_mean = str(sum(x_range_rev)/len(x_range_rev))\n x_square_mean = str(sum([x*x for x in x_range_rev]))\n x_y_multiply = self._x_y_multiply(tb_list, var_name_list, x_range_rev)\n denominator = self._x_sum_of_squares(x_range_rev)\n return \"(({y_m})*{x_square_m}-{x_m}*({x_y}))/{den}\"\\\n .format(y_m=y_mean,\n x_square_m=x_square_mean,\n x_m=x_mean,\n x_y=x_y_multiply,\n den=denominator)\n\n def _intercept(self, tb_list, var_name_list, x_range):\n x_range_rev = x_range.copy()\n x_range_rev.reverse()\n y_mean = self._mean(tb_list, var_name_list)\n x_mean = str(sum(x_range_rev)/len(x_range_rev))\n x_y_multiply = self._x_y_multiply(tb_list, var_name_list, x_range_rev)\n denominator = self._x_sum_of_squares(x_range_rev)\n return \"({x_y}-{x_m}*{x_m})/{den}\"\\\n .format(y_m=y_mean,\n x_m=x_mean,\n x_y=x_y_multiply,\n den=denominator)\n\n\n\nclass QueryVariableBuilder(QueryBuilder):\n def __init__(self, query):\n super().__init__(query)\n\n def add(self, table_name, var_name, var_alias='', flag_alias=True):\n if not self.query._in_var_list(var_name):\n tb = self.query._get_table_ref(table_name=table_name)\n tb.add_var(var_name, var_alias, flag_alias)\n self.query._variables.append(tb.variables[-1])\n return self\n\nclass QueryLeftJoinBuilder(QueryBuilder):\n def __init__(self, query):\n super().__init__(query)\n\n def add(self, database, table_name, table_alias, table_safra, table_key='nr_cpf_cnpj'):\n if not self.query._in_table_list(table_name=table_name):\n self.query._join_list.append(Table(database,\n table_name,\n table_alias,\n table_safra,\n table_key)\n )\n self.query._all_tables.append(self.query._join_list[-1])\n return self\n\n\nclass QueryMainTableBuilder(QueryBuilder):\n def __init__(self, query):\n super().__init__(query)\n\n def add(self, database, table_name, table_alias, table_safra, table_key='nr_cpf_cnpj'):\n self.query.main_table = Table(database,\n table_name,\n table_alias,\n table_safra,\n table_key)\n self.query._all_tables.append(self.query.main_table)\n return self\n\nclass Variable:\n\n def __init__(self, table, name, alias='', fl_case_when=False, flag_alias=True):\n self.name = name\n self.table = table\n self.alias = alias\n self.flag_alias = flag_alias\n # self.type = var_type\n self.fl_case_when = fl_case_when\n\n# Need to think of some smart way to apply this class so I can with more complex\n# relationships between tables\nclass Relationship:\n\n def __init__(self, left_table, right_table, left_table_keys, right_table_keys):\n self.left_table = left_table\n self.left_table_keys = left_table_keys\n self.table_right = table_right\n self.right_table_keys = right_table_keys\n\nclass Table:\n\n def __init__(self, database, table_name, table_alias, table_safra, table_key='nr_cpf_cnpj'):\n self.database = database\n self.table_name = table_name\n self.table_alias = table_alias\n self.table_safra = table_safra\n self.table_key = table_key\n self.variables = []\n\n @staticmethod\n def _var_name_checker(var_name):\n if len(var_name.strip())>0:\n return True\n return False\n\n def add_var(self, var_name, var_alias='', flag_alias=True, fl_case_when=False):\n if (not self._in_var_list(var_name)) and (self._var_name_checker(var_name)):\n self.variables.append(Variable(table=self,\n name=var_name.strip(),\n alias=var_alias.strip(),\n flag_alias=flag_alias,\n fl_case_when=fl_case_when\n ))\n return self\n\n def _in_var_list(self, var_name):\n for var in self.variables:\n if var_name.strip().lower() == var.name.lower():\n return True\n return False\n\n\nclass BaseReaderStrategy:\n\n def __init__(self, safras, query_dict):\n self.query = None\n self.safras = safras\n self.query_dict = query_dict\n\n def _get_safra(self):\n if type(self.safras)==list:\n safra = self.safras[0]\n elif type(self.safras)==str:\n safra = self.safras\n return safra\n\n def _get_var_name(self, var, var_name, safra, mX):\n if \"TRANSFORMATIONS\" not in var.keys():\n return var[\"ALIAS\"].format((mX+var[\"DEFASAGEM\"]))#var_name.format(m_add(safra,-(mX+var[\"DEFASAGEM\"])))\n elif str(mX+var[\"DEFASAGEM\"]) in var[\"TRANSFORMATIONS\"].keys():\n return var[\"ALIAS\"].format((mX+var[\"DEFASAGEM\"]))\n else:\n return var[\"ALIAS\"].format((mX+var[\"DEFASAGEM\"]))#var_name.format(m_add(safra,-(mX+var[\"DEFASAGEM\"])))\n\n def _add_var_to_query(self, query, tb_name, var, var_name, safra, mX, flag_alias=True):\n if \"TRANSFORMATIONS\" not in var.keys():\n query.variable.add(tb_name.format(m_add(safra, -mX)),\n var_name.format(m_add(safra,-(mX+var[\"DEFASAGEM\"]))),\n var[\"ALIAS\"].format((mX+var[\"DEFASAGEM\"])),\n flag_alias\n )\n elif str(mX+var[\"DEFASAGEM\"]) in var[\"TRANSFORMATIONS\"].keys():\n query.case_when.add(tb_name.format(m_add(safra, -mX)),\n var_name.format(m_add(safra,-(mX+var[\"DEFASAGEM\"]))),\n var[\"ALIAS\"].format(\"t_\"+str(mX+var[\"DEFASAGEM\"])),\n var[\"TRANSFORMATIONS\"][str(mX+var[\"DEFASAGEM\"])]\n )\n else:\n query.variable.add(tb_name.format(m_add(safra, -mX)),\n var_name.format(m_add(safra,-(mX+var[\"DEFASAGEM\"]))),\n var[\"ALIAS\"].format((mX+var[\"DEFASAGEM\"])),\n flag_alias\n )\n\n def _add_filter_to_query(self, query, var, var_name, safra, mX):\n if \"FILTER\" not in var.keys():\n pass\n elif str(mX+var[\"DEFASAGEM\"]) in var[\"FILTER\"].keys():\n query.where.add(var_name.format(m_add(safra,-(mX+var[\"DEFASAGEM\"]))),\n var[\"FILTER\"][str(mX+var[\"DEFASAGEM\"])][0],\n var[\"FILTER\"][str(mX+var[\"DEFASAGEM\"])][1]\n )\n else:\n pass\n\n\n def get_main_table(self, safra):\n\n main_tb_name = ''\n main_tb = None\n main_count_validator = 0\n for tb_name, tb in self.query_dict.items():\n if \"MAIN\" in tb.keys():\n main_count_validator += 1\n main_tb_name = tb_name.format(m_add(safra, -tb[\"MAIN\"]))\n main_tb = tb\n if main_count_validator == 1:\n return main_tb_name, main_tb\n elif main_count_validator > 1:\n raise ValueError(\"More than one main table in table dict.\")\n else:\n raise ValueError(\"No main table in table dict.\")\n\n def build(self, safras, query_dict): pass\n\nclass UnionAllSafrasStrategy(BaseReaderStrategy):\n def build(self):\n\n self.query = \"SELECT * FROM \\n (\"\n\n subqueries = []\n for safra in self.safras:\n subqueries.append(str(SimpleQueryStrategy([safra], self.query_dict).build()))\n\n self.query += (')\\n UNION ALL \\n(').join(subqueries) + ')'\n\n return self.query\n\nclass StackedTableQueryStrategy(BaseReaderStrategy):\n\n def _add_var_to_stacked_query(self, stacked_query, subquery, vr):\n name = '({})'.format(str(subquery.build()))\n if vr.alias != '':\n stacked_query.variable.\\\n add(name,\n vr.alias)\n else:\n stacked_query.variable.\\\n add(name,\n vr.name)\n\n def build(self):\n\n safra = self.safras[0]\n\n tb_name, tb = self.get_main_table(safra)\n\n main_tb_alias = tb[\"ALIAS\"].format(m_add(safra,tb['MAIN']))\n\n subquery_dict = {}\n\n subquery_dict[tb[\"ALIAS\"].format(m_add(safra,tb['MAIN']))] = \\\n Query.create().main_table.add(tb[\"DATABASE\"],\n tb_name.format(m_add(safra,tb['MAIN'])),\n tb[\"ALIAS\"].format(m_add(safra,tb['MAIN'])),\n m_add(safra,tb['MAIN']),\n tb[\"TABLE_KEY\"]).where.add(\n tb[\"ALIAS\"].format(m_add(safra,tb['MAIN']))+'.data_ref',\n '=',\n m_add(safra,tb['MAIN'])\n )\n\n for tb_name, tb in self.query_dict.items():\n for var_name, var in tb[\"VARS\"].items():\n for mX in var[\"SAFRAS\"]:\n if tb[\"ALIAS\"].format(m_add(safra, -mX)) in subquery_dict.keys():\n self._add_var_to_query(subquery_dict[tb[\"ALIAS\"].format(m_add(safra, -mX))], tb_name, var, var_name, safra, mX)\n else:\n subquery_dict[tb[\"ALIAS\"].format(m_add(safra, -mX))] = \\\n Query.create().main_table.add(tb[\"DATABASE\"],\n tb_name.format(m_add(safra, -mX)),\n tb[\"ALIAS\"].format(m_add(safra, -mX)),\n m_add(safra,-mX)).where.add(\n '{}.{}'.format(tb[\"ALIAS\"].format(m_add(safra, -mX)),tb[\"SAFRADA\"]),\n '=',\n m_add(safra, -mX)\n ).\\\n variable.\\\n add(tb_name.format(m_add(safra, -mX)), 'nr_cpf_cnpj')\n self._add_var_to_query(subquery_dict[tb[\"ALIAS\"].format(m_add(safra, -mX))], tb_name, var, var_name, safra, mX)\n\n stacked_query = Query.create().main_table.add('',\n '({})'.format(str(subquery_dict[main_tb_alias].build())),\n main_tb_alias,\n 0)\n for vr in subquery_dict[main_tb_alias].query._variables:\n self._add_var_to_stacked_query(stacked_query,subquery_dict[main_tb_alias],vr)\n\n for tb_alias, subquery in subquery_dict.items():\n if tb_alias != main_tb_alias:\n stacked_query.left_join.add('',\n '({})'.format(str(subquery.build())),\n tb_alias,\n 0)\n for vr in subquery.query._variables:\n self._add_var_to_stacked_query(stacked_query,subquery,vr)\n\n self.query = str(stacked_query.build())\n\n return self.query\n\nclass SimpleQueryStrategy(BaseReaderStrategy):\n\n def _subquery(self, safra, tb_name, tb, mX):\n subquery = SingleTableQueryStrategy(safra, {tb_name:tb})\n return '({})'.format(str(subquery.build(mX)))\n\n def build(self):\n\n safra = self._get_safra()\n\n tb_name, tb = self.get_main_table(safra)\n\n new_tb_name = tb_name.format(m_add(safra,tb['MAIN']))\n db_name = tb[\"DATABASE\"]\n if \"SAFRADA\" in tb.keys():\n db_name = ''\n new_tb_name = '({})'.format(str(SingleTableQueryStrategy(safra, {tb_name:tb}).\\\n build(tb['MAIN'])))\n\n query = Query.create().main_table.add(db_name,\n new_tb_name,\n tb[\"ALIAS\"].format(m_add(safra,tb['MAIN'])),\n m_add(safra,tb['MAIN']),\n table_key=tb[\"TABLE_KEY\"])\n\n for tb_name, tb in self.query_dict.items():\n for var_name, var in tb[\"VARS\"].items():\n for mX in var[\"SAFRAS\"]:\n if \"SAFRADA\" in tb.keys():\n \n query.left_join.add('',\n self._subquery(safra, tb_name, tb, mX),\n tb[\"ALIAS\"].format(m_add(safra, -mX)),\n m_add(safra,-mX),\n table_key=tb[\"TABLE_KEY\"])\n\n query.variable.add(self._subquery(safra, tb_name, tb, mX),\n self._get_var_name(var, var_name, safra, mX),\n flag_alias=False\n )\n\n else:\n\n query.left_join.add(tb[\"DATABASE\"],\n tb_name.format(m_add(safra, -mX)),\n tb[\"ALIAS\"].format(m_add(safra, -mX)),\n m_add(safra,-mX),\n table_key=tb[\"TABLE_KEY\"])\n\n self._add_var_to_query(query, tb_name, var, var_name, safra, mX)\n\n self._add_filter_to_query(query, var, var_name, safra, mX)\n\n if \"AGG_PRIMITIVES\" in var.keys():\n #Primitives for variables of the same table for now...\n #will extend later\n for agg_var in var[\"AGG_PRIMITIVES\"]:\n primitive, start, stop, step, length = agg_var.split('_')\n table_name_list = []\n var_name_list = []\n x_range = list(range(int(start), int(stop), int(step)))\n for mX in x_range:\n if \"SAFRADA\" in tb.keys():\n query.left_join.add(\"\",\n self._subquery(safra, tb_name, tb, mX),\n tb[\"ALIAS\"].format(m_add(safra, -mX)),\n m_add(safra,-mX),\n table_key=tb[\"TABLE_KEY\"])\n table_name_list.append(self._subquery(safra, tb_name, tb, mX))\n var_name_list.append(self._get_var_name(var,\n var_name,\n safra,\n mX))\n else:\n query.left_join.add(tb[\"DATABASE\"],\n tb_name.format(m_add(safra, -mX)),\n tb[\"ALIAS\"].format(m_add(safra, -mX)),\n m_add(safra,-mX),\n table_key=tb[\"TABLE_KEY\"])\n table_name_list.append(tb_name.format(m_add(safra, -mX)))\n var_name_list.append(var_name.format(m_add(safra,\n -(mX+var[\"DEFASAGEM\"]))))\n\n\n query.agg_primitive.add(table_name_list,\n var_name_list,\n var[\"ALIAS\"].format(agg_var),\n primitive,\n x_range=x_range)\n\n\n self.query = str(query.build())\n\n return self.query\n\nclass SingleTableQueryStrategy(BaseReaderStrategy):\n\n def build(self, mX):\n\n safra = self._get_safra()\n\n tb_name = list(self.query_dict.keys())[0]\n tb = self.query_dict[tb_name]\n\n query = Query.create().main_table.add(tb[\"DATABASE\"],\n tb_name.format(m_add(safra,-mX)),\n tb[\"ALIAS\"].format(m_add(safra,-mX)),\n m_add(safra,-mX),\n table_key=tb[\"TABLE_KEY\"])\n\n if \"SAFRADA\" in tb.keys():\n query.where.add('{}.{}'.format(tb[\"ALIAS\"].format(m_add(safra, -mX)),tb[\"SAFRADA\"]),\n '=',\n m_add(safra, -mX))\n\n for key in tb['TABLE_KEY']:\n query.variable.add(tb_name.format(m_add(safra, -mX)),\n key,\n flag_alias=False)\n\n\n for var_name, var in tb[\"VARS\"].items():\n if mX in var[\"SAFRAS\"]:\n self._add_var_to_query(query, tb_name, var, var_name, safra, mX)\n\n self._add_filter_to_query(query, var, var_name, safra, mX)\n\n if \"AGG_PRIMITIVES\" in var.keys():\n for agg_var in var[\"AGG_PRIMITIVES\"]:\n primitive, start, stop, step, length = agg_var.split('_')\n if mX in list(range(int(start), int(stop), int(step))):\n self._add_var_to_query(query, tb_name, var, var_name, safra, mX) \n\n self.query = str(query.build())\n\n return self.query\n\n\nclass ConfigQueryReader:\n\n def __init__(self, safras, query_dict):\n self.query = None\n self.safras = safras\n self.query_dict = query_dict\n self.query_strategy = None\n\n def build(self, stacked=False):\n self._set_strategy(stacked)\n self.query = self.query_strategy.build()\n return self\n\n def _set_strategy(self,stacked):\n if stacked:\n self.query_strategy = StackedTableQueryStrategy(self.safras, self.query_dict)\n elif len(self.safras)>1 and type(self.safras)==list:\n self.query_strategy = UnionAllSafrasStrategy(self.safras, self.query_dict)\n elif (len(self.safras)==1 and type(self.safras)==list) or type(self.safras)==str:\n self.query_strategy = SimpleQueryStrategy(self.safras, self.query_dict)\n\n def __str__(self):\n return str(self.query)\n","repo_name":"CaioMar/dsutils","sub_path":"querybuilder.py","file_name":"querybuilder.py","file_ext":"py","file_size_in_byte":31004,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"60"} +{"seq_id":"24792373095","text":"from numba import njit\nimport numpy as np\nfrom .slug_emissions import *\n\n\ndef update_ftau(old_F, old_tau, data, post_g, update_F=True):\n \"\"\"updates the parameters f and tau\n F, tau [n_sfs x 1] : parameter arrays to be updated\n bwd_gac [2 x 3] array of Pr(O = i | G = j, c=0) which is the same\n as for c=1 with het removed\n fwd_g : forward probs of genotype [n_snps x 3]\n fwd_c : forward probs of contamination [n_obs x 1]\n\n calc bwd_g: Pr(O | G) = Pr(O | G, C=0) Pr(C=0) +\n Pr(O | C=1, A=0) Pr(C=1, A=0)\n Pr(O | C=1, A=1) Pr(C=1, A=1)\n\n as events are disjoint\n\n\n \"\"\"\n\n tau, F = np.empty(data.n_sfs), np.empty(data.n_sfs)\n tau[:], F[:] = old_tau, old_F\n\n for k in range(data.n_sfs):\n g0, g1, g2 = np.mean(post_g[data.SNP2SFS == k], 0)\n\n tau[k] = (g1 / 2.0 + g2) / (g0 + g1 + g2)\n\n if update_F:\n if data.haploid_snps is None:\n f0, f1, f2 = 0, 0, 0\n else:\n ix1 = data.SNP2SFS == k\n ix1[data.haploid_snps] = False\n if np.all(~ix1):\n f0, f1, f2 = 0, 0, 0\n else:\n f0, f1, f2 = np.mean(post_g[ix1], 0)\n\n F[k] = 2 * f0 / (2 * f0 + f1 + 1e-300) - f1 / (2 * f2 + f1 + 1e-300)\n np.clip(F, 0, 1, out=F) # round to [0, 1]\n\n return F, tau\n\n\ndef update_ftau_debug(data, pars, post_g):\n \"\"\"updates the parameters f and tau\n F, tau [n_sfs x 1] : parameter arrays to be updated\n bwd_gac [2 x 3] array of Pr(O = i | G = j, c=0) which is the same\n as for c=1 with het removed\n fwd_g : forward probs of genotype [n_snps x 3]\n fwd_c : forward probs of contamination [n_obs x 1]\n\n calc bwd_g: Pr(O | G) = Pr(O | G, C=0) Pr(C=0) +\n Pr(O | C=1, A=0) Pr(C=1, A=0)\n Pr(O | C=1, A=1) Pr(C=1, A=1)\n\n as events are disjoint\n\n\n \"\"\"\n np.set_printoptions(suppress=True, precision=4)\n ll = -np.inf\n\n for k in range(data.n_sfs):\n g0, g1, g2 = np.mean(post_g[data.SNP2SFS == k], 0)\n if data.haploid_snps is None:\n h0, h1, h2 = 0, 0, 0\n else:\n ix1 = data.SNP2SFS == k\n ix1[data.haploid_snps] = False\n if np.all(~ix1):\n f0, f1, f2 = 0, 0, 0\n else:\n f0, f1, f2 = np.mean(post_g[ix1], 0)\n\n # f0, f1, f2 = g0 - h0, g1 - h1, g2 - h2\n pars.F[k], prev_F = (\n 2 * f0 / (2 * f0 + f1 + 1e-300) - f1 / (2 * f2 + f1 + 1e-300),\n pars.F[k],\n )\n\n np.clip(pars.F, 0, 1, out=pars.F) # round to [0, 1]\n\n pars.tau[k], prev_tau = (g1 / 2.0 + g2) / (g0 + g1 + g2), pars.tau[k]\n ll, prev_ll = calc_full_ll(data, pars), ll\n print(\n f\"{k} : ll = {ll}: Delta: {ll-prev_ll:.4f} | tau : {prev_tau:.4f} -> {pars.tau[k]:.4f}\"\n )\n if ll - prev_ll < 0:\n breakpoint()\n\n\n# @njit\ndef update_c(post_c, REF, ALT, OBS2RG, n_rgs):\n \"\"\"update c\n parameters:\n c - vector of contamination rates to updates\n post_c : Pr( C_i = k| O_i = j)\n REF, ALT: number of reference and alt alleles\n OBS2RG: indices for readgroup\n n_rgs: number of rgs\n \"\"\"\n\n c = np.empty(n_rgs)\n\n reads = np.vstack((REF, ALT)).T\n\n v = post_c * np.expand_dims(reads, 2)\n\n breakpoint()\n\n for r in range(n_rgs):\n # x = np.sum(post_c[OBS2RG == r], (0, 1))\n # x = np.sum(np.sum(post_c[OBS2RG == r], 0), 0)\n x = np.sum(np.sum(v[OBS2RG == r], 0), 0)\n c[r] = x[1] / (x[0] + x[1])\n # print(r, c[r], np.sum(OBS2RG==r))\n\n return c\n\n\ndef update_eb(post_x, ALT, REF, two_errors=True):\n post_x[:, 0] *= np.expand_dims(REF, 1)\n post_x[:, 1] *= np.expand_dims(ALT, 1)\n tmp = np.sum(post_x, 0)\n\n if two_errors:\n # ΣPr(X=1 | O = 0) / ΣPr(X=0|O=0) + ΣPr(X=1|O=0)\n e = tmp[1, 0] / np.sum(tmp[:, 0])\n b = tmp[0, 1] / np.sum(tmp[:, 1])\n else:\n e = (tmp[1, 0] + tmp[0, 1]) / np.sum(tmp)\n b = e\n\n if np.isnan(e):\n e = 0\n if np.isnan(b):\n b = 0\n return e, b\n\n\ndef squarem(pars0, data, controller):\n EPS = 1e-6\n MIN_STEP_0, MAX_STEP_0 = 1.0, 1.0\n MSTEP = 4.0\n \"\"\"squarem port from R\"\"\"\n\n controller.copy_pars = True # required for squarem\n controller.n_iter = 50\n min_step, max_step = MIN_STEP_0, MAX_STEP_0\n pars = pars0\n controller.do_update_ftau = False\n controller.do_update_cont = True\n controller.do_update_eb = True\n pars.e, pars.b = 0, 0\n for i in range(controller.n_iter):\n pars1 = update_pars(pars, data, controller)\n Δp1 = pars1 - pars\n if pars1.ll < pars.ll:\n breakpoint()\n if norm(Δp1) < EPS: # or pars1.ll < pars1.prev_ll:\n pars = pars1\n break\n\n pars2 = update_pars(pars1, data, controller)\n Δp2 = pars2 - pars1\n if norm(Δp2) < EPS: # or pars2.ll < pars2.prev_ll:\n pars = pars2\n break\n\n Δp3 = Δp2 - Δp1\n\n step_size = norm(Δp1) / norm(Δp3)\n print(f\"basic step: {step_size} = {norm(Δp1)} / {norm(Δp3)}\")\n step_size = np.clip(step_size, min_step, max_step)\n\n pars_sq = deepcopy(pars2)\n pars_sq.pars[:] = pars.pars + 2 * step_size * Δp1 + step_size * step_size * Δp3\n\n # \"stabilization step if all parameters are in bounds\n if np.all(0 <= pars_sq.pars) and np.all(pars_sq.pars <= 1):\n pars_sq = update_pars(pars_sq, data, controller)\n print(f\"stab step {pars2.ll} -> {pars_sq.ll}\")\n else:\n pars_sq.pars[pars_sq.pars < 0] = EPS\n pars_sq.pars[pars_sq.pars > 1] = 1 - EPS\n pars_sq = update_pars(pars_sq, data, controller)\n print(\n f\"out of bounds {pars2.ll} -> {pars_sq.ll} | {np.sum(pars_sq.pars < 0)}\"\n )\n # pars_sq = pars2\n\n print(\n f\"LLs p0 {pars.ll:.4f} | p1 {pars1.ll-pars.ll:.4f} | p2 {pars2.ll-pars1.ll:.4f} | psq {pars_sq.ll-pars2.ll:.4f}\"\n )\n\n # ll did not improve\n if pars_sq.ll <= pars2.ll:\n print(f\"bad improvement'{min_step} - {max_step} | {step_size}\")\n pars = pars2\n if step_size >= max_step:\n max_step = np.maximum(MAX_STEP_0, max_step / MSTEP)\n step_size = 1.0\n else:\n pars = pars_sq\n print(f\"good step!!!'{min_step} - {max_step} | {step_size}\")\n\n if step_size == max_step:\n max_step *= MSTEP\n\n s = f\"iter {i}: step: {step_size:.3f} | ll: {pars.ll:4f}\"\n s += f\"Δll : {pars.delta_ll:.6f} | e={pars.e[0]:.4f} | b={pars.b[0]:.4f}\"\n s += f\" | Δc : {pars.delta_cont:.4f} | Δtau : {pars.delta_tau:.4f} | ΔF : {pars.delta_F:.4f}\"\n print(s)\n\n posterior_gt = full_posterior_genotypes(data, pars)\n return pars, posterior_gt\n\n\ndef norm(self):\n return np.sqrt(np.sum(np.power(self, 2)))\n\n\ndef em(pars, data, controller):\n for i in range(controller.n_iter):\n update_pars(pars, data, controller)\n s = f\"iter {i}: ll: {pars.ll:4f} | Δll : {pars.delta_ll:4f} | e={pars.e[0]:.4f} | b={pars.b[0]:.4f}\"\n s += f\" | Δc : {pars.delta_cont:.4f} | Δtau : {pars.delta_tau:.4f} | ΔF : {pars.delta_F:.4f}\"\n print(s)\n if pars.ll - pars.prev_ll < controller.ll_tol:\n break\n\n posterior_gt = full_posterior_genotypes(data, pars)\n return posterior_gt\n\n\ndef update_pars(pars, data, controller):\n \"\"\"update all parameters; 1 EM step\"\"\"\n O = controller\n IX = data\n\n pars = deepcopy(pars) if controller.copy_pars else pars\n\n fwd_g = slug_p_gt_diploid(pars.tau, pars.F)[IX.SNP2SFS] # size [L x 3]\n if IX.haploid_snps is not None:\n fwd_g[IX.haploid_snps] = slug_p_gt_haploid(pars.tau)[\n IX.SNP2SFS[IX.haploid_snps]\n ] # size [L x 3]\n\n fwd_a = data.psi # size [L x 1]\n\n fwd_c = np.empty_like(pars.cont) # copy just to make sure no update effects\n fwd_c[:] = pars.cont # size [O x 1]\n\n bwd_x = slug_bwd_p_o_given_x(pars.e, pars.b) # size [2 x 2]\n\n fwd_x_cont = slug_fwd_p_x_cont(fwd_a) # size [L x 1]\n fwd_x_nocont = slug_fwd_p_x_nocont(fwd_g) # size [L x 1]\n fwd_x = slug_fwd_p_x(fwd_x_cont, fwd_x_nocont, fwd_c, IX)\n\n if O.do_update_ftau:\n\n bwd_g1 = slug_bwd_p_one_o_given_g(\n bwd_x, fwd_a, fwd_c, IX.OBS2SNP, IX.OBS2RG, IX.n_obs\n ) # size [O x 3]\n\n bwd_g = slug_bwd_p_all_o_given_g(\n bwd_g1, data.REF, data.ALT, data.OBS2SNP, data.n_snps\n )\n post_g = slug_post_g(bwd_g, fwd_g)\n pars.prev_F[:], pars.prev_tau[:] = pars.F, pars.tau\n pars.F, pars.tau = update_ftau(pars.F, pars.tau, data, post_g)\n\n if O.do_update_eb:\n post_x = slug_post_x(fwd_x, bwd_x) # [O x 2 x 2]\n pars.prev_e, pars.prev_b = pars.e, pars.b\n pars.e, pars.b = update_eb(post_x, data.ALT, data.REF)\n\n if O.do_update_cont:\n post_c = slug_post_c(\n bwd_x, fwd_x_nocont, fwd_x_cont, fwd_c, IX.OBS2SNP, IX.OBS2RG, IX.n_obs\n ) # [O x 2 x 2]\n pars.prev_cont[:] = pars.cont\n pars.cont = update_c(post_c, data.REF, data.ALT, data.OBS2RG, data.n_rgs)\n\n if O.do_ll:\n pars.ll, pars.prev_ll = calc_full_ll(data, pars), pars.ll\n if pars.ll < pars.prev_ll:\n pass\n # breakpoint()\n\n return pars\n","repo_name":"BenjaminPeter/admixfrog","sub_path":"admixfrog/slug/old/slug_em.py","file_name":"slug_em.py","file_ext":"py","file_size_in_byte":9385,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"60"} +{"seq_id":"74469987070","text":"from django.shortcuts import render, redirect\nfrom django.urls import reverse\nfrom carts.models import Cart\nfrom .models import Order, OrderAddress, OrderInvoiceAddress\nfrom .forms import OrderAddressForm, OrderInvoiceAddressForm\n\nfrom .extras import generate_order_id, send_mail_confirmation\n\n\ndef checkout(request):\n\n\ttry:\n\t\tthe_id = request.session['cart_id']\n\t\tcart = Cart.objects.get(id=the_id)\n\texcept Cart.DoesNotExist:\n\t\tthe_id = None\n\t\treturn redirect(reverse('shop:carts:cart_view'))\n\n\t# returns a tuple of (OrderObject, True/False)\n\tnew_order, created = Order.objects.get_or_create(cart=cart)\n\tif created:\n\t\tnew_order.order_id = generate_order_id()\n\t\trequest.session['order_id'] = new_order.id\n\t\tnew_order.save()\n\n\tif new_order.status == 'Finished':\n\t\tdel request.session['cart_id']\n\t\treturn redirect(reverse('shop:carts:cart_view'))\n\n\taddress_form = OrderAddressForm()\n\taddress_invoice_form = OrderInvoiceAddressForm()\n\tcontext = {\n\t\t'order': new_order,\n\t\t'address_form': address_form,\n\t\t'address_invoice_form': address_invoice_form,\n\t}\n\ttemplate = 'shop/pages/checkout.html'\n\n\treturn render(request, template, context)\n\n\ndef checkout_sent(request):\n\n\ttry:\n\t\torder_id = request.session['order_id']\n\t\torder_to_send = Order.objects.get(id=order_id)\n\texcept Order.DoesNotExist:\n\t\treturn redirect(reverse('shop:carts:cart_view'))\n\n\tif request.method == 'POST':\n\t\torder_address = OrderAddress.objects.create(order=order_to_send)\n\t\taddress_form = OrderAddressForm(request.POST)\n\t\tif address_form.is_valid():\n\t\t\torder_address = OrderAddressForm(request.POST, instance=order_address)\n\t\t\torder_address.save()\n\n\t\torder_invoice_address = OrderInvoiceAddress.objects.create(order=order_to_send)\n\t\tinvoice_address_form = OrderInvoiceAddressForm(request.POST)\n\t\tif invoice_address_form.is_valid():\n\t\t\torder_invoice_address = OrderInvoiceAddressForm(request.POST, instance=order_invoice_address)\n\t\t\torder_invoice_address.save()\n\telse:\n\t\tprint('not post request')\n\n\tdelivery_address = OrderAddress.objects.get(order_id=order_id)\n\tinvoice_details = OrderInvoiceAddress.objects.get(order_id=order_id)\n\tordered_products = order_to_send.cart.cartitem_set.all()\n\tcontext = {\n\t\t'delivery_address': delivery_address,\n\t\t'invoice_details': invoice_details,\n\t\t'ordered_products': ordered_products,\n\t\t'order': order_to_send,\n\t}\n\ttemplate = 'shop/pages/checkout_sent.html'\n\n\t# # send order details\n\t# send_mail_confirmation(template, context)\n\n\torder_to_send.status = 'Finished'\n\tif order_to_send.status == 'Finished':\n\t\tdel request.session['cart_id']\n\t\tdel request.session['items_total']\n\n\treturn render(request, template, context)\n\n\n\n\n\n","repo_name":"lasongrzegorz/ecommerce_vegeshop","sub_path":"orders/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2622,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"60"} +{"seq_id":"18391811238","text":"import laspy\nimport numpy as np\nimport ogr, osr\n\nhdr = laspy.header.Header()\n\nx_list = []\ny_list = []\nz_list = []\n\n# Define coordinate transformation\ninSpatialRef = osr.SpatialReference()\ninSpatialRef.ImportFromEPSG(4326)\noutSpatialRef = osr.SpatialReference()\noutSpatialRef.ImportFromEPSG(32619)\ncoordTransform = osr.CoordinateTransformation(inSpatialRef, outSpatialRef)\n\nxyz_file = open('bag_uit_clip.xyz','r')\nfor row in xyz_file:\n\n # Create a geometry from coordinates (input = lat,lon)\n #point = ogr.Geometry(ogr.wkbPoint)\n #point.AddPoint(float(row.split()[1]), float(row.split()[0]))\n\n # Transform point\n #point.Transform(coordTransform)\n\n # Add to list\n #x_list.append(point.GetX())\n #y_list.append(point.GetY())\n x_list.append(float(row.split()[0]))\n y_list.append(float(row.split()[1]))\n z_list.append(float(row.split()[2]))\n\noutfile = laspy.file.File(\"SWIslay_swath_2m.las\", mode=\"w\", header=hdr)\nallx = np.array(x_list) # Four Points\nally = np.array(y_list)\nallz = np.array(z_list)\n\nxmin = np.floor(np.min(allx))\nymin = np.floor(np.min(ally))\nzmin = np.floor(np.min(allz))\nxmax = np.floor(np.max(allx))\nymax = np.floor(np.max(ally))\nzmax = np.floor(np.max(allz))\n\n#outfile.header.dataformat_id = 1\n#outfile.header.minor_version = 1\noutfile.header.offset = [xmin,ymin,zmin]\noutfile.header.scale = [1,1,0.1]\n#outfile.header.min = [xmin, ymin, zmin]\n#outfile.header.max = [xmax, ymax, zmax]\n\noutfile.x = allx\noutfile.y = ally\noutfile.z = allz\n\noutfile.close()","repo_name":"MarkTerlien/Hydro","sub_path":"xyz2las.py","file_name":"xyz2las.py","file_ext":"py","file_size_in_byte":1501,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"60"} +{"seq_id":"12123175117","text":"import time\nimport asyncio\n\n\nasync def pc():\n start = time.perf_counter()\n await asyncio.sleep(4)\n print('perf_counter: ', end='\\t')\n print(time.perf_counter() - start)\n\n\nasync def pt():\n start = time.process_time()\n await asyncio.sleep(4)\n print('process_time: ', end='\\t')\n print(time.process_time() - start)\n\n\nasync def tt():\n start = time.time()\n await asyncio.sleep(4)\n print('time: ', end='\\t\\t')\n print(time.time() - start)\n\n\nasync def main():\n tasks = [asyncio.create_task(f()) for f in (tt, pc, pt)]\n await asyncio.gather(*tasks)\n\n\nasyncio.run(main())\n","repo_name":"javadr/yt-channel-stuff","sub_path":"Programming Tips/[Python] perf_counter.py","file_name":"[Python] perf_counter.py","file_ext":"py","file_size_in_byte":603,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"60"} +{"seq_id":"71342853631","text":"def answer(x, y):\n height_start = x + y - 1\n width_step = x - 1\n start_num = 0\n for i in range(1, height_start): # final but last level\n start_num += i\n\n start_num += 1 # goto final level\n\n return str(start_num + width_step)\n\n\ndef main():\n print(answer(3, 2))\n\n print(answer(5, 10))\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"anarkia7115/google-foobar","sub_path":"bunny_prisoner_locating.py","file_name":"bunny_prisoner_locating.py","file_ext":"py","file_size_in_byte":356,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"60"} +{"seq_id":"14677066499","text":"import random\nimport string\nimport time\nfrom unittest import TestCase\nfrom bluetoothconnection.bluetooth_connection_dummy import Bluetooth\nfrom bed.sensor.dummy_gpio import Gpio\n\nimport os\nimport configparser\ndir_path = os.path.dirname(os.path.realpath(__file__))\nfile1 = os.path.join(dir_path, '../../src/configuration/config.ini')\nfile2 = os.path.join(dir_path, '../../src/configuration/config_for_tests.ini')\nconfig = configparser.ConfigParser()\nconfig.read(file1)\nconfig_blue = config['BLUETOOTHCONNECTION']\nconfig_tests = configparser.ConfigParser()\nconfig_tests.read(file2)\nconfig_tests_blue = config_tests['BLUETOOTHCONNECTION']\n\n\nclass TestBluetoothConnection(TestCase):\n @classmethod\n def setUpClass(cls):\n cls.test_file = config_tests_blue['TEST_FILES']\n cls.bluetooth_connection = Bluetooth()\n cls.bluetooth_connection.run(send_dummy_data=config_tests_blue.getboolean('SEND_DUMMY'))\n cls.dummy_gpio = Gpio(inflatable_regions=int(config_tests_blue['INFLATABLE_REGIONS']))\n\n def test_bluetooth_decode(self):\n message = b'!Hello World*'\n self.bluetooth_connection.receive_data(message)\n\n def test_gpio_callback(self):\n self.bluetooth_connection.register_gpio_callback(self.dummy_gpio.set_relay)\n data = b'!11'\n self.bluetooth_connection.receive_data(data)\n\n def test_send_dummy_data(self):\n self.bluetooth_connection.send_dummy_data()\n\n def test_bluetooth_queue_1(self):\n try:\n message = \"Hello World\"\n self.bluetooth_connection.enqueue_bluetooth_data(message, config_blue['MESSAGE_START'])\n except Exception as e:\n self.fail(e)\n\n\n def test_bluetooth_queue_2(self):\n try:\n for i in range(1, 100):\n message = \"Hello World{}\".format(i)\n self.bluetooth_connection.enqueue_bluetooth_data(message, config_blue['MESSAGE_START'])\n except Exception as e:\n self.fail(e)\n\n def test_bluetooth_queue_3(self):\n try:\n for i in range(1, 100):\n message = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(1500)) + str(i)\n self.bluetooth_connection.enqueue_bluetooth_data(message, config_blue['MESSAGE_START'])\n except Exception as e:\n self.fail(e)\n time.sleep(5)\n return\n\n","repo_name":"jacksonmed-dev/raspberry_pi_bed","sub_path":"tests/test_bluetoothconnection/test_bluetooth_connection.py","file_name":"test_bluetooth_connection.py","file_ext":"py","file_size_in_byte":2378,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"60"} +{"seq_id":"43809220429","text":"#\n# SOLR indexing for all datasets.\n# This will recreate the full index and swap the SOLR alias on successful completion.\n# It will also remove old collections.\n#\n\nfrom airflow import DAG\nfrom airflow.utils.dates import days_ago\nfrom datetime import timedelta\nfrom datetime import datetime\n\nfrom ala.ala_helper import step_bash_cmd, s3_cp, get_default_args\nfrom ala import cluster_setup, ala_config\n\ns3_bucket = ala_config.S3_BUCKET\nsolrCollection = ala_config.SOLR_COLLECTION\nsolrConfigset = ala_config.SOLR_CONFIGSET\nsolrUrl = ala_config.SOLR_URL\nzkUrl = ala_config.ZK_URL\n\nDAG_ID = 'SOLR_indexing'\n\nsolrCollectionName = f\"{solrCollection}_\" + datetime.now().strftime(\"%d_%m_%H_%M_%S\")\n\nincludeSampling = \"{{ dag_run.conf['includeSampling'] }}\".strip()\nincludeJackKnife = \"{{ dag_run.conf['includeJackKnife'] }}\".strip()\nincludeClustering = \"{{ dag_run.conf['includeClustering'] }}\".strip()\nincludeOutlier = \"{{ dag_run.conf['includeOutlier'] }}\".strip()\n\n# If including sampling, we need to use partitions to avoid hotspots\nnumOfPartitions = 1\nif includeSampling:\n numOfPartitions = 8\n\ncurlUrl = f\"{solrUrl}/admin/collections\" \\\n \"?action=CREATE\" \\\n f\"&name={solrCollectionName}\" \\\n \"&numShards=4\" \\\n \"&replicationFactor=1\" \\\n f\"&collection.configName={solrConfigset}\"\n\ncreateAlias = f\"{solrUrl}/admin/collections\" \\\n \"?action=CREATEALIAS\" \\\n f\"&collections={solrCollectionName}\" \\\n f\"&name={solrCollection}\"\n\nprint(\"Creating collection with URL: \" + curlUrl)\n\nSPARK_STEPS = [\n step_bash_cmd(\"a. Create SOLR Collection\", \" sudo -u hadoop curl -X GET \\\"\" + curlUrl + \"\\\"\"),\n s3_cp(\"b. Copy Sampling and IndexRecord from S3\", f\"s3://{ala_config.S3_BUCKET_AVRO}/pipelines-all-datasets\", f\"hdfs:///pipelines-all-datasets\"),\n s3_cp(\"c. Copy Clustering from S3\", f\"s3://{ala_config.S3_BUCKET_AVRO}/pipelines-clustering/\", \"hdfs:///pipelines-clustering/\", action_on_failure=\"CONTINUE\"),\n s3_cp(\"d. Copy Jack knife from S3\", f\"s3://{ala_config.S3_BUCKET_AVRO}/pipelines-jackknife/\", \"hdfs:///pipelines-jackknife/\", action_on_failure=\"CONTINUE\"),\n s3_cp(\"e. Copy Outlier from S3\", f\"s3://{ala_config.S3_BUCKET_AVRO}/pipelines-outlier/\", \"hdfs:///pipelines-outlier/\", action_on_failure=\"CONTINUE\"),\n s3_cp(\"e. Copy Annotations from S3\", f\"s3://{ala_config.S3_BUCKET_AVRO}/pipelines-annotations/\", \"hdfs:///pipelines-annotations/\", action_on_failure=\"CONTINUE\"),\n step_bash_cmd(\"f. SOLR indexing\", f\" la-pipelines solr all --cluster --extra-args=\\\"solrCollection={solrCollectionName},includeSampling={includeSampling},includeJackKnife={includeJackKnife},includeClustering={includeClustering},includeOutlier={includeOutlier}\\\"\"),\n step_bash_cmd(\"g. Create new SOLR alias\", \" sudo -u hadoop curl -X GET \\\"\" + createAlias + \"\\\"\"),\n step_bash_cmd(\"h. Delete old SOLR indexes\", f\" sudo -u hadoop python3 /tmp/solr_cleanup.py {solrUrl} {solrCollection} {solrCollectionName}\")\n]\n\nwith DAG(\n dag_id=DAG_ID,\n description=\"SOLR indexing for all datasets. This will recreate the full index and swap the SOLR alias on successful completion\",\n default_args=get_default_args(),\n dagrun_timeout=timedelta(hours=4),\n start_date=days_ago(1),\n schedule_interval=None,\n tags=['emr','all-datasets'],\n params={\n \"includeSampling\": \"true\",\n \"includeJackKnife\": \"true\",\n \"includeClustering\": \"true\",\n \"includeOutlier\": \"true\"\n }\n) as dag:\n cluster_setup.run_large_emr(dag, SPARK_STEPS, \"bootstrap-index-actions.sh\")\n","repo_name":"AtlasOfLivingAustralia/pipelines-airflow","sub_path":"dags/solr_dag.py","file_name":"solr_dag.py","file_ext":"py","file_size_in_byte":3545,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"60"} +{"seq_id":"22999307862","text":"# -- coding: UTF-8 --\n\n\"\"\" Main file for subclasses \"\"\"\n\nimport logging\nimport logging.config\nimport json\n\nfrom classes.subclass import SuperClass, SubClass\n\n__author__ = 'saranya@gyandata.com'\n\nLOGGER = logging.getLogger('root')\nLOGGER_CONFIG_PATH = 'config/logging.json'\n\n\ndef setup_logging(default_path=LOGGER_CONFIG_PATH):\n \"\"\"\n Function Description: To setup logging using the json file\n :param default_path: Path of the configuration file\n :type default_path: str\n \"\"\"\n with open(default_path, 'rt') as file:\n config = json.load(file)\n logging.config.dictConfig(config)\n\n\ndef main():\n \"\"\" Main Function \"\"\"\n setup_logging()\n # Creating instance of subclass using superclass instance\n a_1 = SuperClass()\n b_1 = a_1.__class__.__subclasses__()[0]()\n LOGGER.info(\"Type of b1 is: %s\", type(b_1))\n\n b_2 = SubClass()\n # b_2.__class__ = SuperClass\n # b_2.meth_a()\n a_2 = b_2.__class__.__base__()\n LOGGER.info(\"Type of a2 is: %s\", type(a_2))\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"saranyasivam98/Classes_Objects","sub_path":"main_subclasses.py","file_name":"main_subclasses.py","file_ext":"py","file_size_in_byte":1040,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"60"} +{"seq_id":"20461150385","text":"# -*- coding: utf-8 -*-\r\nimport numpy as np\r\nimport torch\r\nimport torch.nn as nn\r\nimport torch.nn.functional as F\r\nfrom torch_geometric.nn import GatedGraphConv, GCNConv, GATConv\r\n\r\n\r\ndef trans_to_cuda(variable):\r\n if torch.cuda.is_available():\r\n return variable.cuda()\r\n else:\r\n return variable\r\n\r\n\r\ndef trans_to_cpu(variable):\r\n if torch.cuda.is_available():\r\n return variable.cpu()\r\n else:\r\n return variable\r\n\r\n\r\ndef handle_adj_weight(adj_dict, weight_dict, num_node, sample_num):\r\n adj_entity = np.zeros([num_node, sample_num], dtype=np.int64)\r\n weight_entity = np.zeros([num_node, sample_num], dtype=np.float32)\r\n for i in range(0, num_node):\r\n neighbor = adj_dict[i]\r\n neighbor_weight = weight_dict[i]\r\n n_neighbor = len(neighbor)\r\n if n_neighbor == 0:\r\n adj_entity[i] = np.full(sample_num, i)\r\n weight_dict[i] = np.ones(sample_num, dtype=np.float)\r\n continue\r\n elif n_neighbor < sample_num:\r\n sampled_indices = np.random.choice(list(range(n_neighbor)), size=sample_num - n_neighbor, replace=True)\r\n adj_entity[i] = np.concatenate((adj_dict[i], np.array([neighbor[i] for i in sampled_indices])))\r\n weight_entity[i] = np.concatenate((weight_dict[i], np.array([neighbor_weight[i] for i in sampled_indices])))\r\n else:\r\n adj_entity[i] = neighbor\r\n weight_entity[i] = neighbor_weight\r\n\r\n return torch.from_numpy(adj_entity).long(), F.normalize(torch.from_numpy(weight_entity))\r\n\r\n\r\ndef translate_to_seq(session_embed, alias_session):\r\n seq_hidden = trans_to_cuda(torch.zeros(alias_session.shape[0], alias_session.shape[1], session_embed[0].shape[-1]))\r\n for i in range(alias_session.shape[0]):\r\n seq_hidden[i] = session_embed[i][alias_session[i]]\r\n\r\n return seq_hidden\r\n\r\n\r\nclass SessionGraphCL(nn.Module):\r\n def __init__(self, opt, hidden_size):\r\n super(SessionGraphCL, self).__init__()\r\n self.opt = opt\r\n self.hidden_size = hidden_size\r\n if self.opt.GNN == \"GGNN\":\r\n self.ggnn = GatedGraphConv(self.hidden_size, num_layers=1)\r\n elif self.opt.GNN == \"GCN\":\r\n self.gcn = GCNConv(self.hidden_size, self.hidden_size)\r\n elif self.opt.GNN == \"GAT\":\r\n self.gat_1 = GATConv(self.hidden_size, self.hidden_size, heads=4)\r\n self.gat_2 = GATConv(self.hidden_size * 4, self.hidden_size)\r\n else:\r\n raise \"No GNN is specified\"\r\n self.w1 = nn.Linear(self.hidden_size, self.hidden_size, bias=False)\r\n self.w2 = nn.Linear(self.hidden_size, self.hidden_size)\r\n self.leaky_relu = nn.LeakyReLU(negative_slope=self.opt.alpha)\r\n\r\n def InfoNCE(self, view1, view2):\r\n temperature = self.opt.tua\r\n view1, view2 = F.normalize(view1, dim=1), F.normalize(view2, dim=1)\r\n pos_score = (view1 * view2).sum(dim=-1)\r\n pos_score = torch.exp(pos_score / temperature)\r\n ttl_score = torch.matmul(view1, view2.transpose(0, 1))\r\n ttl_score = torch.exp(ttl_score / temperature).sum(dim=1)\r\n cl_loss = -torch.log(pos_score / ttl_score)\r\n return torch.mean(cl_loss)\r\n\r\n def forward(self, x_embed, data):\r\n edge_index, batch = data.edge_index, data.batch\r\n mask = data.mask.unsqueeze(-1)\r\n random_noise = torch.rand_like(x_embed)\r\n x_embed_cl = x_embed + torch.sign(torch.randn_like(x_embed)) * F.normalize(random_noise, dim=-1) * self.opt.eps\r\n if self.opt.GNN == \"GGNN\":\r\n node_embed = self.ggnn(x_embed, edge_index) + x_embed\r\n node_embed_cl = self.ggnn(x_embed_cl, edge_index) + x_embed_cl\r\n elif self.opt.GNN == \"GCN\":\r\n node_embed = self.leaky_relu(self.gcn(x_embed, edge_index)) + x_embed\r\n node_embed_cl = self.leaky_relu(self.gcn(x_embed_cl, edge_index)) + x_embed_cl\r\n elif self.opt.GNN == \"GAT\":\r\n node_embed = self.leaky_relu(self.gat_1(x_embed, edge_index))\r\n node_embed_cl = self.leaky_relu(self.gat_1(x_embed_cl, edge_index))\r\n node_embed = self.gat_2(node_embed, edge_index) + x_embed\r\n node_embed_cl = self.gat_2(node_embed_cl, edge_index) + x_embed_cl\r\n else:\r\n raise \"No GNN is specified\"\r\n gcl_loss = self.InfoNCE(node_embed, node_embed_cl)\r\n\r\n section = torch.bincount(data.batch)\r\n session_embed = torch.split(node_embed, list(section.cpu().numpy()))\r\n seq_embed = translate_to_seq(session_embed, data.alias_session) * mask.float()\r\n session_mean_embed = F.relu(self.w2(torch.mean(seq_embed, dim=1))).unsqueeze(dim=1).repeat(1, mask.shape[1], 1)\r\n session_mean_embed = F.dropout(session_mean_embed, p=self.opt.dropout_gnn, training=self.training)\r\n session_pre = seq_embed + session_mean_embed\r\n\r\n return session_pre, gcl_loss\r\n\r\n\r\nclass NeighborPooling(nn.Module):\r\n def __init__(self, opt, hidden_size, embedding):\r\n super(NeighborPooling, self).__init__()\r\n self.opt = opt\r\n self.hidden_size = hidden_size\r\n self.embedding = embedding\r\n self.w_1 = nn.Linear(self.hidden_size * 2 + 1, self.hidden_size)\r\n self.w_2 = nn.Linear(self.hidden_size, 1, bias=False)\r\n self.w_3 = nn.Linear(self.hidden_size * 2, self.hidden_size, bias=False)\r\n self.leaky_relu = nn.LeakyReLU(negative_slope=opt.alpha)\r\n\r\n def forward(self, x_embed, data, adj, weight):\r\n mask = data.mask.unsqueeze(-1).float()\r\n seq_lens = mask.shape[1]\r\n all_neighbor_adj = adj[data.session]\r\n all_neighbor_weight = weight[data.session]\r\n\r\n section = torch.bincount(data.batch)\r\n session_embed = torch.split(x_embed, list(section.cpu().numpy()))\r\n session_embed = translate_to_seq(session_embed, data.alias_session) * mask.float()\r\n session_mean_embed = session_embed.sum(dim=1) / mask.sum(dim=1)\r\n\r\n sample_num = all_neighbor_adj.shape[-1]\r\n all_neighbor_embedding = self.embedding(all_neighbor_adj)\r\n alpha = self.w_1(torch.cat([session_mean_embed.unsqueeze(dim=1).unsqueeze(1).repeat(1, seq_lens, sample_num, 1)\r\n , all_neighbor_embedding, all_neighbor_weight.unsqueeze(-1)], dim=-1))\r\n alpha = self.w_2(self.leaky_relu(alpha)).squeeze(-1)\r\n alpha = F.softmax(alpha, dim=-1).unsqueeze(-1)\r\n neighbor_vector = torch.sum(alpha * all_neighbor_embedding, dim=2)\r\n last_item_pre = session_embed[:, 0, :] + neighbor_vector[:, 0, :]\r\n\r\n neighbor_vector = F.dropout(neighbor_vector, p=self.opt.dropout_nei, training=self.training)\r\n global_pre = session_embed + neighbor_vector\r\n\r\n return global_pre, last_item_pre\r\n","repo_name":"QiWang98/NRGNN","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":6775,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"60"} +{"seq_id":"42857353232","text":"from django.conf.urls import url, include\nfrom rest_framework.urlpatterns import format_suffix_patterns\nfrom snippets import views\n\nurlpatterns = [\n url(r'^snippets/$', views.SnippetList.as_view()),\n url(r'^snippets/(?P[0-9]+)/$', views.SnippetDetail.as_view()),\n url(r'^users/$', views.UserList.as_view()),\n url(r'^users/(?P[0-9]+)/$', views.UserDetail.as_view()),\n]\n\n# Allows us URLs like host.com/snippets/1.json (if we want it),\n# as well as the more traditional host.com/snippets/1/\nurlpatterns = format_suffix_patterns(urlpatterns)\n\n# Sets up a login page for the browseable API, otherwise we're\n# restricted to readonly because we can't log in.\nurlpatterns += [\n url(r'^api-auth/', include('rest_framework.urls',\n namespace='rest_framework')),\n]\n","repo_name":"peterussell/django-rest-api-tutorial","sub_path":"tutorial/snippets/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":794,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"60"} +{"seq_id":"1627112694","text":"import requests\r\nfrom bs4 import BeautifulSoup\r\nfrom fake_useragent import UserAgent\r\n\r\n\r\nCITY = 'Москва'\r\nITEMS = 50\r\nURL = f'https://zakupki.gov.ru/epz/eruz/search/results.html?&address={CITY}&recordsPerPage={ITEMS}'\r\n\r\n\r\ndef extract_max_page():\r\n zakupki_request = requests.get(URL, headers={'User-Agent': UserAgent().chrome})\r\n zakupki_soup = BeautifulSoup(zakupki_request.text, 'html.parser')\r\n pages = []\r\n paginator = zakupki_soup.find_all(\"a\", class_='page__link')\r\n for page in paginator:\r\n pages.append(int(page.find(\"span\", class_='link-text').text))\r\n return pages[-1]\r\n\r\ndef extract_data(html):\r\n try:\r\n urls = []\r\n e_mail = []\r\n telefon = []\r\n address = []\r\n fio = []\r\n e_dol = []\r\n d_inn = []\r\n title = html.find('div', class_='registry-entry__body-href').find('a').text\r\n title = title.strip()\r\n link = html.find('a')['href']\r\n urls.append('http://zakupki.gov.ru' + link)\r\n number = html.find('div', class_='registry-entry__header').find('a').text\r\n number = number.strip()\r\n number = number.partition(' ')[2]\r\n inn = html.find('div', class_='registry-entry__body-value').text\r\n inn = inn.strip()\r\n kpp = html.find_all('div', class_='registry-entry__body-value')[1].text\r\n kpp = kpp.strip()\r\n ogrn = html.find_all('div', class_='registry-entry__body-value')[2].text\r\n ogrn = ogrn.strip()\r\n for url in urls:\r\n result = requests.get(url, headers={'User-Agent': UserAgent().chrome})\r\n soup = BeautifulSoup(result.text, 'html.parser')\r\n email = soup.find_all('div', class_='row')[8].find_all('section', class_='section')[1].find('span', class_='section__info').text\r\n e_mail.append(email)\r\n tel = soup.find_all('div', class_='row')[8].find_all('section', class_='section')[2].find('span', class_='section__info').text\r\n telefon.append(tel)\r\n add = soup.find_all('div', class_='row')[8].find_all('section', class_='section')[0].find('span', class_='section__info').text\r\n address.append(add)\r\n name = soup.find_all('div', class_='row')[7].find('td', class_='tableBlock__col').text\r\n fio.append(name)\r\n dol = soup.find_all('div', class_='row')[7].find_all('td', class_='tableBlock__col')[1].text\r\n e_dol.append(dol)\r\n dinn = soup.find_all('div', class_='row')[7].find_all('td', class_='tableBlock__col')[2].text\r\n d_inn.append(dinn)\r\n except IOError:\r\n print('Error')\r\n continue\r\n return {\r\n 'title': title, 'number': number, 'inn': inn, 'kpp': kpp, \r\n 'link': 'zakupki.gov.ru' + link, 'telefon': ''.join(telefon), \r\n 'email': ''.join(e_mail), 'address': ''.join(address), 'FIO': ''.join(fio),\r\n 'Dolzhnost': ''.join(e_dol), 'Dir inn': ''.join(d_inn)\r\n }\r\n\r\ndef extract_org(last_page):\r\n orgs = []\r\n for page in range(1, last_page + 1):\r\n print(f'Парсинг страницы {page}')\r\n result = requests.get(f'{URL}&pageNumber={page}', headers={'User-Agent': UserAgent().chrome})\r\n soup = BeautifulSoup(result.text, 'html.parser')\r\n results = soup.find_all('div', class_='col-8 pr-0 mr-21px')\r\n for result in results:\r\n org = extract_data(result)\r\n orgs.append(org)\r\n return orgs\r\n","repo_name":"evgenyyakimov/parser_zakupki.gov.ru","sub_path":"zakupki.py","file_name":"zakupki.py","file_ext":"py","file_size_in_byte":3471,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"60"} +{"seq_id":"13938707388","text":"import json\nimport pytz\nfrom datetime import datetime\nfrom datetime import timedelta\nfrom geopy import distance\nimport pulp\n\nconfigs_file = open('configs.json', 'r')\nconfigs = json.loads(configs_file.read())\n\nTIME_FIX_FAILURES = configs['failure_time_to_fix']\nPLACE_FIX_FAILURES = configs['failure_treatment']\n\nPRICE_PER_L = configs['price_per_l']\nSCALE_TIME = 60\nMIN_SPEED = None\n\n\ndef _pre_processing(data, airports):\n global MIN_SPEED\n\n routes = data['rotas']\n routes.insert(0, 'first')\n routes.append('last')\n airplanes = data['aeronaves']\n\n speeds = [airplane['veloc_max'] for airplane in airplanes]\n MIN_SPEED = min(speeds)\n\n airports_by_iata = {}\n for airport in airports:\n airports_by_iata[airport['iata']] = airport\n\n for airplane in airplanes:\n airplane['disponibilidade'] = datetime.strptime(airplane['disponibilidade'], '%Y-%m-%dT%H:%M:%S.%f')\n\n for route in routes:\n if route is not 'first' and route is not 'last':\n route['horario_decolagem'] = datetime.strptime(route['horario_decolagem'], '%Y-%m-%dT%H:%M:%S.%f')\n route['horario_pouso'] = datetime.strptime(route['horario_pouso'], '%Y-%m-%dT%H:%M:%S.%f')\n\n route['origem'] = airports_by_iata[route['origem']]\n route['destino'] = airports_by_iata[route['destino']]\n\n origin_coordinate = (route['origem']['lat'], route['origem']['lon'])\n destine_coordinate = (route['destino']['lat'], route['destino']['lon'])\n route['distancia'] = distance.vincenty(origin_coordinate, destine_coordinate).km\n\n schedule_restrictions = []\n airplane_restrictions = []\n cost = [[[9999999999 for x in range(len(airplanes))] for y in range(len(routes))] for z in range(len(routes))]\n for i in range(len(routes)):\n for j in range(len(routes)):\n if i == j or j == 0 or i == len(routes)-1:\n schedule_restrictions.append((i, j))\n elif i != 0 and j != len(routes)-1:\n if routes[i]['destino'] == routes[j]['origem']:\n if _incompatible_times(routes[i], routes[j]):\n schedule_restrictions.append((i, j))\n elif _incompatible_routes(routes[i], routes[j]):\n schedule_restrictions.append((i, j))\n\n for k in range(len(airplanes)):\n if i != j and i != len(routes)-1 and j != 0:\n km_by_l = airplanes[k]['autonomia']/airplanes[k]['consumo']\n\n between_cost = 0\n if i == 0 and j != len(routes)-1:\n actual = airports_by_iata[airplanes[k]['localizacao']]\n origin_coordinate = (actual['lat'], actual['lon'])\n destine_coordinate = (routes[j]['origem']['lat'], routes[j]['origem']['lon'])\n km_distance = distance.vincenty(origin_coordinate, destine_coordinate).km\n between_cost = (km_distance / km_by_l) * PRICE_PER_L\n elif i != 0 and j != len(routes)-1 and routes[i]['destino'] != routes[j]['origem']:\n between_cost = _calculate_between_cost(km_by_l, routes[i], routes[j])\n\n first_route_cost = 0\n if j != len(routes) - 1:\n first_route_cost = (routes[j]['distancia'] / km_by_l) * PRICE_PER_L\n\n cost[i][j][k] = between_cost + first_route_cost# + second_route_cost\n\n if j != 0 and j != len(routes)-1:\n actual = airports_by_iata[airplanes[k]['localizacao']]\n origin_coordinate = (actual['lat'], actual['lon'])\n destine_coordinate = (routes[j]['origem']['lat'], routes[j]['origem']['lon'])\n km_distance = distance.vincenty(origin_coordinate, destine_coordinate).km\n hours_to_travel = km_distance / airplanes[k]['veloc_max']\n if (routes[j]['horario_decolagem'] < (airplanes[k]['disponibilidade'] + timedelta(hours=hours_to_travel))\n or airplanes[k]['max_pas'] < routes[j]['num_passageiros'])\\\n and not airplane_restrictions.__contains__((k, j)):\n airplane_restrictions.append((k, j))\n\n schedule_restrictions = list(filter(lambda sr: sr[0] != len(routes)-1 and sr[1] != 0, schedule_restrictions))\n\n return schedule_restrictions, airplane_restrictions, cost\n\n\ndef _incompatible_times(first_route, second_route):\n first_arrive_time = first_route['horario_pouso']\n second_departure_time = second_route['horario_decolagem']\n return first_arrive_time > (second_departure_time - timedelta(minutes=SCALE_TIME))\n\n\ndef _incompatible_routes(first_route, second_route):\n first_coordinate = (first_route['destino']['lat'], first_route['destino']['lon'])\n second_coordinate = (second_route['origem']['lat'], second_route['origem']['lon'])\n distance_km = distance.vincenty(first_coordinate, second_coordinate).km\n mins_to_travel = (distance_km / MIN_SPEED) * 60\n\n first_arrive_time = first_route['horario_pouso']\n second_departure_time = second_route['horario_decolagem']\n return first_arrive_time > (second_departure_time - timedelta(minutes=SCALE_TIME + mins_to_travel))\n\n\ndef _calculate_between_cost(km_by_l, first_route, second_route):\n first_coordinate = (first_route['destino']['lat'], first_route['destino']['lon'])\n second_coordinate = (second_route['origem']['lat'], second_route['origem']['lon'])\n distance_km = distance.vincenty(first_coordinate, second_coordinate).km\n return (distance_km / km_by_l) * PRICE_PER_L\n\n\ndef _prepare_data(data, c):\n routes = data['rotas']\n airplanes = data['aeronaves']\n\n arcs = []\n arc_data = {}\n\n for i in range(len(routes)):\n for j in range(len(routes)):\n for k in range(len(airplanes)):\n arc = (i, j, airplanes[k]['tail'])\n arc_data[arc] = [c[i][j][k], 0, 1]\n arcs.append(arc)\n\n return arcs, arc_data\n\n\ndef optimize(data, airports):\n sr, ar, c = _pre_processing(data, airports)\n arcs, arc_data = _prepare_data(data, c)\n\n routes = data['rotas']\n airplanes = data['aeronaves']\n allocation = []\n\n costs, mins, maxs = pulp.splitDict(arc_data)\n\n # cria os limites das variaveis\n x = pulp.LpVariable.dicts(\"Route\", arcs, 0, 1, pulp.LpInteger)\n for arc in arcs:\n x[arc].bounds(mins[arc], maxs[arc])\n\n # variavel com estrutura do problema\n prob = pulp.LpProblem(\"Min Routes\", pulp.LpMinimize)\n\n # funcao objetivo\n prob += pulp.lpSum([x[arc] * costs[arc] for arc in arcs]), \"\"\n\n # restricao 1: voos que nao podem ser feitos seguidamente\n for i, j in sr:\n prob += pulp.lpSum([x[(i, j, k['tail'])] for k in airplanes]) == 0, \"\"\n\n # restricao 2: todos os voos devem ser feitos\n for j in range(1, len(routes)-1):\n prob += pulp.lpSum([x[(i, j, k['tail'])] for i in range(len(routes)) for k in airplanes]) == 1, \"\"\n\n # restricao 3: todas as naves que chegam em um no, saem desse no\n for i in range(1, len(routes) - 1):\n for k in airplanes:\n prob += pulp.lpSum([x[(i, j, k['tail'])] for j in range(len(routes))]) == \\\n pulp.lpSum([x[(j, i, k['tail'])] for j in range(len(routes))]), \"\"\n\n # restricao 4: todas as naves devem sair do no inicial\n for k in airplanes:\n prob += pulp.lpSum([x[(0, j, k['tail'])] for j in range(len(routes))]) == 1, \"\"\n\n # restricao 5: todas as naves devem chegar no no final\n for k in airplanes:\n prob += pulp.lpSum([x[(i, (len(routes)-1), k['tail'])] for i in range(len(routes))]) == 1, \"\"\n\n # restricao 6: naves que nao podem fazer certos voos\n for k, j in ar:\n prob += pulp.lpSum([x[(i, j, airplanes[k]['tail'])] for i in range(len(routes))]) == 0, \"\"\n\n # restricao 7: nenhuma nave deve chegar no no inicial\n for k in airplanes:\n prob += pulp.lpSum([x[(i, 0, k['tail'])] for i in range(len(routes))]) == 0, \"\"\n\n # restricao 8: nenhuma nave deve sair do no final\n for k in airplanes:\n prob += pulp.lpSum([x[((len(routes)-1), j, k['tail'])] for j in range(len(routes))]) == 0, \"\"\n\n # resolvendo\n prob.writeLP(\"min_routes.lp\")\n prob.solve()\n print(\"Status:\", pulp.LpStatus[prob.status])\n for v in prob.variables():\n if v.varValue == 1:\n print(v.name, \"=\", v.varValue)\n name = v.name.replace(')', '')\n chars = name.split('(')[1].split(',_')\n route = int(chars[1])\n tail = chars[-1].replace('\\'', '')\n flight = routes[route]\n if flight != 'last':\n allocation.append({\n 'airplane': tail,\n 'origin': {\n 'name': flight['origem']['iata'],\n 'lat': flight['origem']['lat'],\n 'lon': flight['origem']['lon']\n },\n 'destine': {\n 'name': flight['destino']['iata'],\n 'lat': flight['destino']['lat'],\n 'lon': flight['destino']['lon']\n },\n 'departure_time': flight['horario_decolagem']\n })\n\n print(\"Cost = \", pulp.value(prob.objective))\n\n cost = pulp.value(prob.objective)\n return cost, allocation\n\n\ndef treat_failures(airplanes, airports):\n airports_by_iata = {}\n for airport in airports:\n airports_by_iata[airport['iata']] = airport\n\n routes = []\n cost = 0\n to_remove = []\n for airplane in airplanes:\n km_by_l = airplane['autonomia']/airplane['consumo']\n\n if len(airplane['falhas']['3']) > 0:\n last_3 = datetime.strptime(airplane['falhas']['3'][-1], '%Y-%m-%dT%H:%M:%S.%f')\n last_3 = last_3.astimezone(pytz.timezone('America/Sao_Paulo'))\n if (last_3 + timedelta(hours=TIME_FIX_FAILURES[2])) <= datetime.now(pytz.timezone('America/Sao_Paulo')):\n final_fix = None\n final_distance = 999999999\n actual = airports_by_iata[airplane['localizacao']]\n for place in PLACE_FIX_FAILURES[2]:\n place_to_fix = airports_by_iata[place]\n origin_coordinate = (actual['lat'], actual['lon'])\n destine_coordinate = (place_to_fix['lat'], place_to_fix['lon'])\n km_distance = distance.vincenty(origin_coordinate, destine_coordinate).km\n if km_distance < final_distance:\n final_distance = km_distance\n final_fix = place_to_fix\n cost += (final_distance / km_by_l) * PRICE_PER_L\n routes.append({\n 'airplane': airplane['tail'],\n 'origin': {\n 'name': actual['iata'],\n 'lat': actual['lat'],\n 'lon': actual['lon']\n },\n 'destine': {\n 'name': final_fix['iata'],\n 'lat': final_fix['lat'],\n 'lon': final_fix['lon']\n },\n 'departure_time': last_3\n })\n to_remove.append(airplane)\n\n elif len(airplane['falhas']['2']) > 0:\n last_2 = datetime.strptime(airplane['falhas']['2'][-1], '%Y-%m-%dT%H:%M:%S.%f')\n last_2 = last_2.astimezone(pytz.timezone('America/Sao_Paulo'))\n if (last_2 + timedelta(hours=TIME_FIX_FAILURES[1])) <= datetime.now(pytz.timezone('America/Sao_Paulo')):\n final_fix = None\n final_distance = 999999999\n actual = airports_by_iata[airplane['localizacao']]\n for place in PLACE_FIX_FAILURES[1]:\n place_to_fix = airports_by_iata[place]\n origin_coordinate = (actual['lat'], actual['lon'])\n destine_coordinate = (place_to_fix['lat'], place_to_fix['lon'])\n km_distance = distance.vincenty(origin_coordinate, destine_coordinate).km\n if km_distance < final_distance:\n final_distance = km_distance\n final_fix = place_to_fix\n cost += (final_distance / km_by_l) * PRICE_PER_L\n routes.append({\n 'airplane': airplane['tail'],\n 'origin': {\n 'name': actual['iata'],\n 'lat': actual['lat'],\n 'lon': actual['lon']\n },\n 'destine': {\n 'name': final_fix['iata'],\n 'lat': final_fix['lat'],\n 'lon': final_fix['lon']\n },\n 'departure_time': last_2\n })\n to_remove.append(airplane)\n\n elif len(airplane['falhas']['1']) > 0:\n last_1 = datetime.strptime(airplane['falhas']['1'][-1], '%Y-%m-%dT%H:%M:%S.%f')\n last_1 = last_1.astimezone(pytz.timezone('America/Sao_Paulo'))\n if (last_1 + timedelta(hours=TIME_FIX_FAILURES[0])) <= datetime.now(pytz.timezone('America/Sao_Paulo')):\n final_fix = None\n final_distance = 999999999\n actual = airports_by_iata[airplane['localizacao']]\n for place in PLACE_FIX_FAILURES[0]:\n place_to_fix = airports_by_iata[place]\n origin_coordinate = (actual['lat'], actual['lon'])\n destine_coordinate = (place_to_fix['lat'], place_to_fix['lon'])\n km_distance = distance.vincenty(origin_coordinate, destine_coordinate).km\n if km_distance < final_distance:\n final_distance = km_distance\n final_fix = place_to_fix\n cost += (final_distance / km_by_l) * PRICE_PER_L\n routes.append({\n 'airplane': airplane['tail'],\n 'origin': {\n 'name': actual['iata'],\n 'lat': actual['lat'],\n 'lon': actual['lon']\n },\n 'destine': {\n 'name': final_fix['iata'],\n 'lat': final_fix['lat'],\n 'lon': final_fix['lon']\n },\n 'departure_time': last_1\n })\n to_remove.append(airplane)\n\n for airplane in to_remove:\n airplanes.remove(airplane)\n\n return cost, routes\n","repo_name":"castro150/ap-simulator","sub_path":"optimizer/optimize.py","file_name":"optimize.py","file_ext":"py","file_size_in_byte":14750,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"60"} +{"seq_id":"18080766536","text":"import os\nimport subprocess\nimport glob\nfrom os import path\nimport shutil\nimport sys\nimport csv\nimport re\nimport copy\nimport tempfile\nimport argparse\nimport subprocess\n\ninstructions = \"\"\"\n To use throw52:\n\n for every function which might be on the stack when an exception\n is thrown (aka might throw an exception, call a function which\n throws an exception, call a function which calls a function which etc.)\n annotate it by creating a line right above it that begins with \n the PREPEND constant below (e.g. //throw_)\n\n Go through the source code looking for instances where these\n exception-throwing functions are called. throw52 works when the\n function calls are:\n 1. called on a line with no other statements\n 2. has the return value unused\n OR \n has the return value immediately assigned to a variable\n OR\n is called after a 'return' keyword (with no modification)\n so that the returned value is immediately returned.\n 3. best practice is to enclose any code you want ignored\n in throw52 in a preprocessor block that is NOT an else block.\n (use IF, IFDEF, IFNDEF, or ELSEIF instead)\n Because you may now or later want multiple else blocks\n in your code that pertain to different conditions' negative.\n\n You should go over your code manually to for #2 and remove\n all violators. Throw52 will detect some, but others will \n lead to type errors and syntax errors.\n \n Main violators to look for\n A.calling an exception-throwing function as an argument\n to pass to a function call. \n f.g(h());\n instead assign it to a temporary variable\n int tmp = h(); \n f.g(tmp);\n\n If the variable returned is large (E.g. a vector) and\n copying is expensive, you can use preprocessor blocks\n to keep the direct as-argument call for when you're \n not processing with throw52.\n\n If you miss some of these, throw52 will detect some instances\n but not all. In fact if an exception-throwing function\n is used as an argument on a line other than the outer function\n call, it will break the code and cause a compile error.\n\n f.g(\"abc\",\n h()); \n \n B.modifying the result before assignment.\n int num = h() + 5;\n return g() / 2;\n instead assign it in its own line and then modify the result\n int num = h();\n num += 5;\n int tmp = g();\n return tmp + 5;\n \n This is usually something that throw52 will not detect as an error\n and will come up as a type error on compile time. \n\n C. using ternary assignment.\n name = (last)? getFirst() : getLast();\n instead use an if else block\n if (last) {\n name = getFirst();\n else {\n name = getLast();\n }\n \n This will sometimes be detected by throw52, and some other \n times cause type errors, but most of the time cause syntax\n errors. Ensure you have replaced all ternary assignment\n by searching for question marks.\n \n\n\n\"\"\"\n\n\nclass _Logger:\n FATAL = 0\n ERROR = 1\n WARN = 2\n DEFAULT = 2\n NOTE = 3\n OUTLINE = 4\n VALUES = 5\n DEBUG = 6\n def __init__(self, verbosity):\n self.verbosity = verbosity\n \n def log(self, level, msg):\n if self.verbosity >= level:\n prefix = \"\"\n suffix = \"\"\n if level == _Logger.FATAL:\n prefix = \"FATAL ERROR: \"\n suffix = \". Exiting.\"\n elif level == _Logger.ERROR:\n prefix = \"ERROR: \"\n elif level == _Logger.WARN:\n prefix = \"WARNING: \"\n suffix = \"\" \n sys.stderr.write(prefix + msg + suffix + \"\\n\")\n if level == _Logger.FATAL:\n sys.exit()\n \n_logger = _Logger(1)\n\n\n\n\n #instructions will include an extra column for a minify bit, \n # which will only be valid with anything above NO_REQUEST\n # actually wait, no i need to think about this more.\n # maybe minify should be ternify with NO_REQUEST, NO_MINIFY, MINIFY?\n #\tI don't think the users want to keep track of two separate overlapping\n # trees of inheritance in their head. perhaps the original method is best.\n \ndef getDefaultParams():\n return {\n # capitalized parameters are parameters that for most users\n # won't be that useful to know about (vs. say, knowing how to\n # use debug mode for rapid testing that you've set up\n # includes and tilthSrc() calls right)\n \n #when changing these, be sure to edit corresponding value\n #in argparse cmd-line code (at bottom)\n \"verbosity\": _Logger.DEFAULT,\n \"igblock_open\": \"#IFDEF THROWABLE\",\n \"igblock_close\": \"#ENDIF\",\n \"throws_indicator\":\"#?throw_\",\n \"error_class\":\"ErrWrap\",\n \"extra_tests\":False,\n \"use_templates\":False,\n \"gen_ec\":False\n #templates: ErrWrap\n #no templates: ErrWrapint\n }\n\ndef _createTask(l_in, l_out, paramdeltas={}):\n params = getDefaultParams()\n for k in paramdeltas: \n params[k] = paramdeltas[k]\n return Throw52Task([{'in':l_in, 'out':l_out}], params)\n\nclass Throw52Task:\n def __init__(self, srcdestpairs, params):\n # on creation, stores a snapshot of parameters\n \n #behavior which should be able to be applied to some blocks and \n # files but not others should be integrated into instructions\n # rather than through piecewise changing of configuration.\n \n self._params = copy.deepcopy(params)\n \n global _logger\n _logger.verbosity = self._params['verbosity']\n self.f_map = {}\n \n # this program doesn't aspire to deal with C++ files > 100k lines,\n # so storing the text in memory is fine\n # text is stored as an array of the lines of the program.\n for i in range(0,len(srcdestpairs)):\n f_in = open(srcdestpairs[i]['in'], 'r') \n srcdestpairs[i]['data'] = f_in.read().split(\"\\n\")\n f_in.close()\n self.processCalls(srcdestpairs[i]['data'], True)\n\n for i in range(0,len(srcdestpairs)):\n self.processCalls(srcdestpairs[i]['data'], False)\n outputstr = \"\\n\".join(srcdestpairs[i]['data'])\n f_out = open(srcdestpairs[i]['out'], 'w')\n f_out.write(outputstr)\n f_out.flush()\n f_out.close()\n\n def stripToCode(self, line):\n return (line.split(\"//\")[0]).rstrip()\n\n def checkUnusableLine(self, line, num, whyUnusable):\n #making this optional and disabled by default saves us a serious amount of time,\n #otherwise for a 5k size file we're calling ~50 regex searches on every second or third line.\n if not self._params['extra_tests']:\n return\n for f in self.f_map:\n if line.find(f) and re.search(f + \"\\s*\\(\", line):\n _logger.log(_Logger.ERROR,\n str(num) + \": exception throwing func '\" + f + \"' is present in line \" + \\\n \" but \" + whyUnusable + \" output not tested! must be fixed.\")\n def processCalls(self, text, scan_pass):\n #ASSUMES:\n # 1. left var and assignment occurs on the \n # SAME line as the function call\n # (though the function call arguments may be \n # spread over several lines\n # 2. all assignment operators assign simple \n # function call results, NOT ternary operators.\n _logger.log(_Logger.OUTLINE, \"----processCalls()----\")\n varnum = 1 \n void_funcs = [ x for x in self.f_map if self.f_map[x] == 'void' ]\n assign_funcs = [ x for x in self.f_map if self.f_map[x] != 'void' ]\n ident = \"[a-zA-Z_](?:[a-zA-Z_0-9]*(\\.|->)[a-zA-Z_][a-zA-Z_0-9]*|[a-zA-Z_0-9]*)?\"\n typestr = \"[a-zA-Z_](?:[a-zA-Z_0-9\\*]*|[a-zA-Z_0-9]*<[a-zA-Z_0-9\\*\\s]+>\\*?)?\"\n #'a', 'ab', and 'a.b' are all valid. 'a.' is not,\n #ident = \"[a-zA-Z_]\" #'a', 'ab', and 'a.b' are all valid. 'a.' is not,\n re_header = re.compile(\"\\s*//\\s?\" + self._params['throws_indicator'])\n re_header_beginblock = re.compile(\"\\s*//\\s?\" + self._params['throws_indicator'] + \"begin\")\n re_header_endblock = re.compile(\"\\s*//\\s?\" + self._params['throws_indicator'] + \"end\")\n re_signature = re.compile(\"^\\s?(?P\"+typestr+\")\\s[a-zA-Z_][a-zA-Z0-9_:]*\\(.*?\")\n re_func_name = re.compile(\"(([a-zA-Z]*(\\.|->))*)(?P\" + ident + \")\\s*\\(\")\n void_call = re.compile(\"^\\s*(\" +ident +\")\\s*\\([^;]*;?\")\n assign_call = re.compile(\"^\\s*(?P(?:\" + ident + \"[\\*\\s]+\" + ident + \"|\" + ident + \"))\\s*=\\s*(\" +ident +\")\\s*\\([^;]*;?\")\n ERROR_CLASS=self._params['error_class']\n\n ident_sig = \"[a-zA-Z_][a-zA-Z_0-9]*\"\n re_sig = re.compile(\"^\\s?(?:[A-Za-z_0-9]+::)*\" + \\\n \"(?P\" + typestr + \"[\\s\\*\\&]*?)\\s*\" \\\n \"(?:\" + ident_sig + \"\\s+)?\" + \\\n \"(?P(?:\" + ident_sig + \\\n \"::)?)(?P\"+ ident_sig + \\\n \")\\((?P.*)\")\n # a superset of re_sig\n # that instead of accepting only up to one space before\n # return type, accepts up to five (5 not 4 because not in the \n # business of enforcing whitespace via causing confusing failures \n # from minor whitespace errors.\n re_sig_throwblock = re.compile(\"^\\s{0,5}(?:[A-Za-z_0-9]+::)*(?P\" + typestr + \"[\\s\\*\\&]*?)\\s*\" \\\n \"(?:\" + ident_sig + \"\\s+)?\" + \\\n \"(?P(?:\" + ident_sig + \\\n \"::)?)(?P\"+ ident_sig + \\\n \")\\((?P.*)\")\n\n AFTER_SEMICOLON = \"it occurs after a semicolon (against throw52 convention)\"\n ASSIGN_OF_VOID = \" is of void return but may be assigned to a var in this line. skipping.\"\n DBG_ASSIGNED = \" function result assigned to a var in source \"\n DBG_NOT_ASSIGNED = \" function result NOT assigned to a var in source \"\n STATEMENT_NUM = \" is called in this line but is not the only statement in the line (throw52 convention expects it to be). skipping.\"\n\n begun_call = False\n line = \"\"\n finish_call = \"\"\n\n igblock_open = self._params['igblock_open']\n igblock_close = self._params['igblock_close']\n in_ignored_block = False\n\n in_throw_block = False\n\n outer_is_void = False\n outer_ret_type = \"\"\n outer_throws = False\n funcname = \"\"\n\n outer_func_name = \"\"\n #good for generating list of error classes needed.\n gen_ec = self._params['gen_ec']\n error_class_set = set()\n returned_class_set = set()\n\n use_templates = self._params['use_templates']\n no_wrap = False\n\n for i in range(0, len(text)):\n line = self.stripToCode(text[i])\n if in_ignored_block:\n if (line.upper()).find(igblock_close) != -1:\n in_ignored_block = False\n continue\n if (line.upper()).find(igblock_open) != -1:\n in_ignored_block = True\n continue \n m = re.match((re_sig_throwblock if in_throw_block else re_sig),\n text[i])\n if m:\n newret = m.group(\"ret\")\n #this assignshouldn't ever be used anyway... \n #no need to know ret. type if no throwing func calls w/in.\n outer_ret_type = newret \n outer_is_void = (newret == 'void') \n outer_throws = in_throw_block\n if not outer_throws:\n outer_throws = re.match(re_header, text[i-1])\n outer_func_name = m.group('name')\n if outer_throws: \n #if m.group('class'):\n # raise \"don't know what to do with throwing class member\"\n self.f_map[m.group('name')] = {'name':\"\", \n 'wrap':True, \n 'void':False}\n if outer_is_void:\n self.f_map[m.group('name')]['void'] = True\n newret = 'int'\n\n if newret[-1] != \"*\" and newret[0].upper() == newret[0]:\n self.f_map[m.group('name')]['wrap'] = False\n returned_class_set.add(newret)\n outer_ret_type = newret\n elif use_templates:\n outer_ret_type = \"\".join([self._params['error_class'],\n '<', newret, '>' ])\n else:\n if gen_ec:\n error_class_set.add(newret)\n newret = newret.replace(\"<\",\"\")\n newret = newret.replace(\">\",\"\")\n newret = newret.replace(\" \",\"\")\n newret = newret.replace(\"*\", \"Ptr\")\n\n outer_ret_type = \"\".join([self._params['error_class'],\n newret])\n self.f_map[m.group('name')]['name'] = outer_ret_type\n if (not scan_pass):\n text[i] = re.sub(re_sig_throwblock, \n outer_ret_type + \\\n \" \\g\\g(\\g\", \n text[i])\n continue\n \n if not in_throw_block:\n if re.match(re_header_beginblock, text[i]):\n in_throw_block = True\n continue\n elif re.match(re_header_endblock, text[i]):\n in_throw_block = False\n continue\n if scan_pass or (not outer_throws and \\\n not self._params['extra_tests']):\n continue\n\n if begun_call:\n pos = line.find(\";\")\n if pos >= 0:\n #_logger.log(_Logger.VALUES, str(i) + \" found statement end \")\n text[i] = \"\".join([text[i][:pos+1], \" \", \n finish_call, \n text[i][pos+1:] ])\n line = line[pos+1:]\n if outer_is_void: #if we're here outer throws by definition.\n if line[pos+1:].find(\"return\") != -1:\n text[i] = text[i].replace(\" return \", \n \" return noErr\")\n text[i] = text[i].replace(\" return;\", \n \" return noErr;\")\n self.checkUnusableLine(line[pos+1:], i, \n AFTER_SEMICOLON)\n begun_call = False\n self.checkUnusableLine(line, i, \n \"\".join([\" call to funcname \",\n funcname,\n \" hasn't closed \"]))\n continue\n\n if outer_throws and outer_is_void:\n if text[i].find(\"return\") != -1: \n text[i] = text[i].replace(\" return \", \" return noErr\")\n text[i] = text[i].replace(\" return;\", \" return noErr;\")\n elif outer_is_void:\n print(\" no such thing \")\n if begun_call or line.find(\"(\") == -1:\n continue\n\n newvar = \"th52\" + str(varnum)\n varnum += 1 \n m = re.search(re_func_name, line)\n if not m:\n continue\n funcname = m.group(\"funcname\")\n if not (funcname in self.f_map):\n _logger.log(_Logger.DEBUG, \n \"\".join([str(i+1),\n \" func found, but not in f_map: '\",\n funcname, \"'\"]) ) \n if not (funcname == \"DEBUGRET\"):\n self.checkUnusableLine(line, i, \n \" is not the first function call.\")\n continue\n _logger.log(_Logger.VALUES, \n \"\".join([str(i+1),\n \" throwable func found: '\",\n funcname,\n \"'\"])) \n callret_type = self.f_map[funcname]['name']\n use_wrap = self.f_map[funcname]['wrap']\n is_void = self.f_map[funcname]['void']\n if line.find(\"=\") != -1 and is_void:\n _logger.log(_Logger.WARN, \n \"\".join([str(i+1), \n \": error-throwing function \",\n funcname,\n ASSIGN_OF_VOID]) )\n retvar = \"th52\" + str(varnum)\n #we don't need to wrap the signature's ret type\n #because we already wrapped that in the \n #signature processing pass.\n varnum += 1\n finish_call = \"\".join([\" if (\", newvar, \".err) { \", \n outer_ret_type, \" \", retvar, \"; \", \n retvar, \".err = true; \",\n #\"DEBUGOUT(\\\"\",\n #outer_func_name,\n #\"\\\", false); \",\n \" return \", \n retvar, \"; } \"])\n m = re.match(void_call, line)\n \n if m:\n _logger.log(_Logger.DEBUG, \n \"\".join([str(i+1),\n DBG_NOT_ASSIGNED]))\n pos = line.find(m.group(0))\n text[i] = \"\".join([text[i][:pos],\n callret_type, \" \",\n newvar, \" = \",\n text[i][pos:] ])\n elif not line.find(\"=\"):\n _logger.log(_Logger.ERROR,\n \"\".join([str(i),\n \": error-throwing function \",\n funcname,\n STATEMENT_NUM]))\n continue\n else:\n _logger.log(_Logger.DEBUG,\n \"\".join([str(i),\n DBG_ASSIGNED]))\n m = re.match(assign_call, line)\n if not m:\n _logger.log(_Logger.ERROR,\n \"\".join([str(i),\n \" error-throwing function \",\n funcname,\n STATEMENT_NUM]))\n continue\n normalvar = m.group('normalvar')\n if use_wrap:\n text[i] = text[i].replace(normalvar, \n callret_type + \\\n \" \" + newvar, 1)\n finish_call = \"\".join([finish_call, \n normalvar, \" = \", \n newvar, \".val; \"])\n else: \n ensure_no_type = normalvar.split(\" \")[-1]\n finish_call = \"\".join([\" if (\", \n ensure_no_type, \n \".err) { \", \n outer_ret_type, \" \", retvar, \"; \", \n retvar, \".err = true; \",\n #\"DEBUGOUT(\\\"\",\n #outer_func_name,\n #\"\\\", false); \",\n \" return \", \n retvar, \"; } \"])\n if line[-1] == ';':\n _logger.log(_Logger.VALUES, str(i) + \\\n \" found statement end (sameline) \")\n text[i] = \"\".join([self.stripToCode(text[i]),\n \" \", finish_call, \n text[i][len(self.stripToCode(text[i])):] ])\n finish_call = \"DEFAULT_FINISH_CALL\"\n else:\n begun_call = True\n if scan_pass or not gen_ec:\n return\n print(\"// ensure there are bool .err members, initialized with false\\n\" +\\\n \"// in the following classes:\")\n for rc in returned_class_set:\n print(\"// \"+rc)\n print(\"\")\n \n for typename in error_class_set:\n typecleaned = typename.replace(\"<\", \"\")\n typecleaned = typecleaned.replace(\">\", \"\")\n typecleaned = typecleaned.replace(\" \", \"\")\n typecleaned = typecleaned.replace(\"*\", \"Ptr\")\n print(\"\".join([\"class \",\n ERROR_CLASS, typecleaned,\n \" {\\npublic:\\n \",\n \"bool err;\\n \",\n typename, \" val;\\n \",\n ERROR_CLASS, typecleaned, \n \"() {\\n \",\n \"err = false;\\n }\\n \",\n ERROR_CLASS, typecleaned,\n \"(\", typename, \" in) {\\n \",\n \"val = in;\\n \",\n \"err = false;\\n }\\n\"\n \"};\\n\"]))\n \n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description=\"Throw52 web workflow\")\n \n # defaults are manually copied here to contribute to convention of reviewing\n #\targparse args for possible needed changes when changing defaults.\n #\tin most cases, it wouldn't be alright to just change the output\n #\tof just getDefaultParams.\n parser.add_argument('infile', nargs='?', type=argparse.FileType('r'),\n default=\"/home/n/coding/esp3/src/linprima.cpp\")\n #default=sys.stdin)\n parser.add_argument('outfile', nargs='?', type=argparse.FileType('w'),\n default=\"/home/n/coding/esp3/tmp/linprima.cpp\")\n #default=sys.stdout)\n parser.add_argument(\"-v \", type=int, choices=range(0,6), dest=\"verbosity\",\n default=0,\n help=\"verbosity. 0 is only display errors, 1 is default (warnings), 5 is max\")\n parser.add_argument(\"-e\",\"--extra_tests\", dest=\"extra_tests\",\n action=\"store_true\",default=False,\n help=\"check more thoroughly for potential sources of processing errors. You should use this \" + \\\n \"option at least once if you make any heavy additions or refactors\")\n parser.add_argument(\"-t\",\"--use_templates\", dest=\"use_templates\",\n action=\"store_true\",default=False,\n help=\"use templates with the error class (e.g. ErrWrap instead of ErrWrapint) advantages: don't need to include variant of each class in source. disadvantage: slower performance.\")\n\n parser.add_argument(\"-g\",\"--generate_errorclasses\", dest=\"gen_ec\",\n action=\"store_true\",default=False,\n help=\"If you're not using templates, you will want to include code in your source with a wrapping errorclass for each return type of an exception-throwing function. This option will output that code to stdout. implies no templates\")\n\n parser.add_argument(\"--ignored-block-opener\", dest=\"igblock_open\",\n action=\"store\", default=\"#IFDEF THROWABLE\",\n\thelp=\" line that if detected, throw52 will skip all lines of code \" + \\\n \"until it reaches the ignored-block-closer\")\n parser.add_argument(\"--ignored-block-closer\", dest=\"igblock_close\",\n action=\"store\", default=\"#ENDIF\",\n\thelp=\" line that closes a block of code to be ignored by throw52\")\n\n prev=\"\"\"parser.add_argument(\"-c\",\"--compress-instructions\", dest=\"comp_instr\",\n\taction=\"store_true\",default=False,\n\thelp=\"generate in the current directory an instructions .csv with \" + \\\n\t\t\" only the input instructions which are not NO_REQUEST \" + \\\n\t\t\" and that refer to an existing file.\")\nparser.add_argument(\"-d\",\"--debug-mode\", dest=\"debug_mode\",\n\taction=\"store_true\", default=False,\n\thelp=\"skip any requested minifying of files for faster testing\")\nparser.add_argument(\"-g\",\"--generate-instructions\", dest=\"exp_instr\",\n\taction=\"store_true\",default=False,\n\thelp=\"generate in the current directory an instructions .csv with \" + \\\n\t\t\" the input instructions + all other source files.\")\nparser.add_argument(\"-j\",\"--joomla-mode\", dest=\"joomla_mode\",\n\taction=\"store_true\",default=False,\n\thelp=\"rewrite all urls relative to the lowest shared directory,\" + \\\n\t\"instead of relative to the current index file.\")\nparser.add_argument(\"--maincache-dir\", dest=\"maincache_dir\",\n\taction=\"store\", default=\".\",\n\thelp=\" relative path within the prod. directory to store the main \" + \\\n\t\t\"(site-wide) cache. Default is '.'\")\nparser.add_argument(\"-p\",\"--production-folder\", dest=\"production_folder\",\n\taction=\"store\", default=\"_c\",\n\thelp=\" name of production folder (where all output is stored). \" + \\\n\t\t\" default is _c\")\nparser.add_argument(\"--path-closure\", dest=\"path_closure\",\n\taction=\"store\", default=\"minify/compiler.jar\",\n\thelp=\" path to closure compiler .jar file. Assumed \" + \\\n\t\t\"'minify/compiler.jar'. If both yui and closure are used,\" + \\\n\t\t\" closure is preferred for js. You need at least one to minify js.\")\nparser.add_argument(\"--path-yui\", dest=\"path_yui\",\n\taction=\"store\", default=\"minify/yuicompressor*.jar\",\n\thelp=\" path to yuicompressor.jar file (req'd for css minification).\" + \\\n\t\t\" Assumed 'minify/yuicompressor*.jar'.\")\nparser.add_argument(\"-s\",\"--source-dirs\", dest=\"source_dirs\",\n\taction=\"store\", nargs=\"+\",\tdefault=[\"src/content/*\",\"src/lib/*\"],\n\thelp=\" a folder or folders to use as source libraries (instead of \" + \\\n\t\" the defaults of any folder matching ./src/lib/* or\" + \\\n\t\" ./src/content/*) You can provide as many arguments as you want.\")\nparser.add_argument(\"-t \", \"--transparent-mode\", dest=\"update_only\",\n\taction=\"store_true\",default=False,\n\thelp=\" See file changes instantaneously without re-calling tilth \" + \\\n\t\t\" or changing include paths. Creates a production folder \" + \\\n\t\t\" skeleton with files that are soft links to their source \" + \\\n\t\t\" folder counterpart. Available only on filesystems that \" + \\\n\t\t\" (by default) allow users to create symbolic links (OS X and \" + \\\n\t\t\" linux filesystems). Overrides Debug Mode if both are used.\")\nparser.add_argument(\"path_instr\", action=\"store\", \n\tdefault=\"tilth_instructions\")\"\"\"\n args = parser.parse_args()\n \n paramdeltas = {\n \"verbosity\":args.verbosity+1,\n \"igblock_open\":args.igblock_open,\n \"igblock_close\":args.igblock_close,\n \"extra_tests\":args.extra_tests,\n \"use_templates\":args.use_templates and not args.gen_ec,\n \"gen_ec\":args.gen_ec}\n\n #\t\t\t\"debug_mode\":args.debug_mode,\n #\t\t\t\"joomla_mode\":args.joomla_mode,\n #\t\t\t\"maincache_dir\":args.maincache_dir,\n #\t\t\t\"transparent_mode\":args.transparent_mode,\n #\t\t\t\"path_closure_compiler\":args.path_closure,\n #\t\t\t\"path_yui_compressor\":args.path_yui,\n #\t\t\t\"path_instructions\":args.path_instr}\n _createTask(args.infile, args.outfile, paramdeltas)\n","repo_name":"nathanross/linprima","sub_path":"throw52.py","file_name":"throw52.py","file_ext":"py","file_size_in_byte":28103,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"60"} +{"seq_id":"7323055793","text":"#!/usr/bin/python3\n\"\"\"\ntakes in a URL and an email, sends a POST request\nto the passed URL with the email as a parameter\n\"\"\"\nimport urllib.request\nimport sys\n\nif __name__ == \"__main__\":\n url = sys.argv[1]\n email = sys.argv[2].encode(\"utf-8\")\n request_object = urllib.request.Request(url, data=email, method=\"POST\")\n with urllib.request.urlopen(request_object) as response:\n print(response.read().decode(\"utf-8\"))\n","repo_name":"Orino1/alx-higher_level_programming","sub_path":"0x11-python-network_1/2-post_email.py","file_name":"2-post_email.py","file_ext":"py","file_size_in_byte":432,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"60"} +{"seq_id":"43332302322","text":"\"\"\"\ninvoice.views\n\nis_staff:\n* see all of invoice\n* can arch\n\"\"\"\n\n# 1. system\nimport decimal\nimport json\nimport logging\n# 3. django\nfrom django.contrib.auth.decorators import login_required\nfrom django.urls import reverse\nfrom django.db import transaction\nfrom django.http import HttpResponse\nfrom django.shortcuts import get_object_or_404, redirect, render\nfrom django.utils.decorators import method_decorator\nfrom django.views.generic import ListView\n# 2. my\nfrom core.models import FileSeq, FileSeqItem\nfrom invarch.models import Scan\nfrom . import models, forms, utils\nfrom .views_extras import \\\n ROLE_ACCOUNTER, ROLE_ASSIGNEE, ROLE_CHIEF, ROLE_LAWYER, ROLE_BOSS, \\\n STATE_DONE, STATE_DRAFT, STATE_ONPAY, STATE_ONWAY, STATE_REJECTED, \\\n USER_BOSS\nfrom .views_extras import fill_route, handle_shipper, mailto, rotate_img, set_filter_state, update_fileseq\n\nlogger = logging.getLogger(__name__)\n\nPAGE_SIZE = 25\nFSNAME = 'fstate' # 0..3\n\n\n@method_decorator(login_required, name='dispatch')\nclass InvoiceList(ListView):\n \"\"\"\n ACL:\n - All:\n -- Исполнитель: только свои (где он - Исполнитель)\n x- Руководитель: только где он - текущий Подписант или в Истории\n -- *: все\n - Inboud:\n -- Испольнитель: только свои И без подписанта (== Черновик, Завернут, Исполнен)\n -- Директор, Бухгалтер = где роль тек. Подписанта == роль юзверя\n -- *: == тек. Подписант\n\n \"\"\"\n template_name = 'invoice/list.html'\n paginate_by = PAGE_SIZE\n # custom:\n approver = None\n mode = None\n\n # fsfilter = None\n # place = None\n # shipper = None\n # payer = None\n\n def get_queryset(self):\n # 1. vars\n self.paginate_by = self.request.session.get('lpp', PAGE_SIZE)\n user = self.request.user\n self.approver = models.Approver.objects.get(user=user)\n role_id = self.approver.role.pk\n self.mode = int(self.request.session.get('mode', 1))\n # self.fsfilter = self.request.session.get(FSNAME, 31) # int 0..15: dropped|done|onway|draft\n # 2. query\n q = models.Invoice.objects.all().order_by('-pk')\n if self.mode == 1: # Everything\n if (role_id == ROLE_ASSIGNEE) and (not user.is_superuser) and (not user.is_staff): # Исполнитель\n q = q.filter(assign=self.approver)\n # 3. filter using Filter\n # - state\n fsfilter = self.request.session.get(FSNAME, None) # int 0..15: dropped|done|onway|draft\n if fsfilter is None:\n fsfilter = 31 # all together\n self.request.session[FSNAME] = fsfilter\n else:\n fsfilter = int(fsfilter)\n q = set_filter_state(q, fsfilter)\n form_initial = {\n 'dead': bool(fsfilter & 1),\n 'done': bool(fsfilter & 2),\n 'onpay': bool(fsfilter & 4),\n 'onway': bool(fsfilter & 8),\n 'draft': bool(fsfilter & 16),\n }\n # - place\n place = int(self.request.session.get('place', 0))\n if place:\n q = q.filter(place__pk=place)\n form_initial['place'] = place\n # - subject\n subject = int(self.request.session.get('subject', 0))\n if subject:\n q = q.filter(subject__pk=subject)\n form_initial['subject'] = subject\n # - depart\n depart = int(self.request.session.get('depart', 0))\n if depart:\n q = q.filter(depart__pk=depart)\n form_initial['depart'] = depart\n # - shipper\n shipper = int(self.request.session.get('shipper', 0))\n if shipper:\n q = q.filter(shipper__pk=shipper)\n form_initial['shipper'] = shipper\n # - payer\n payer = int(self.request.session.get('payer', 0))\n if payer:\n q = q.filter(payer__pk=payer)\n form_initial['payer'] = payer\n # 5. go\n self.fsform = forms.FilterBillListForm(initial=form_initial)\n else: # Inbound\n self.fsform = None\n if role_id == ROLE_ASSIGNEE: # Испо��нитель\n q = q.filter(assign=self.approver, rpoint=None)\n elif role_id in {ROLE_LAWYER, ROLE_BOSS, ROLE_ACCOUNTER}: # Юрист, Бухгалтер\n q = q.filter(rpoint__role=self.approver.role)\n else:\n q = q.filter(rpoint__approve=self.approver)\n return q\n\n def get_context_data(self, **kwargs):\n context = super(InvocieList, self).get_context_data(**kwargs)\n context['lpp'] = self.paginate_by\n context['role'] = self.approver.role\n context['canadd'] = self.approver.canadd\n context['mode'] = self.mode\n context['fsform'] = self.fsform\n return context\n\n\ndef invoice_get_subjects(request):\n \"\"\"\n AJAX callback on place change\n \"\"\"\n place = request.GET.get('place')\n ret = [dict(id='', value='---'), ]\n if place:\n for subj in models.Subject.objects.filter(place=place).order_by('name'):\n ret.append(dict(id=subj.pk, value=subj.name))\n return HttpResponse(json.dumps(ret), content_type='application/json')\n\n\n@login_required\ndef invoice_filter_state(request):\n \"\"\"\n Set filter on state of bill list\n POST only\n * set filter in cookie\n * redirect\n ACL: *\n \"\"\"\n fsform = forms.FilterBillListForm(request.POST)\n if fsform.is_valid():\n fsfilter = \\\n int(fsform.cleaned_data['dead']) * 1 | \\\n int(fsform.cleaned_data['done']) * 2 | \\\n int(fsform.cleaned_data['onpay']) * 4 | \\\n int(fsform.cleaned_data['onway']) * 8 | \\\n int(fsform.cleaned_data['draft']) * 16\n request.session[FSNAME] = fsfilter\n request.session['place'] = fsform.cleaned_data['place'].pk if fsform.cleaned_data['place'] else 0\n request.session['subject'] = fsform.cleaned_data['subject'].pk if fsform.cleaned_data['subject'] else 0\n request.session['depart'] = fsform.cleaned_data['depart'].pk if fsform.cleaned_data['depart'] else 0\n request.session['shipper'] = fsform.cleaned_data['shipper'].pk if fsform.cleaned_data['shipper'] else 0\n request.session['payer'] = fsform.cleaned_data['payer'].pk if fsform.cleaned_data['payer'] else 0\n return redirect('invoice_list')\n\n\n@login_required\ndef invoice_set_lpp(request, lpp):\n \"\"\"\n Set lines-per-page of bill list.\n ACL: *\n \"\"\"\n request.session['lpp'] = lpp\n return redirect('invoice_list')\n\n\n@login_required\ndef invoice_set_mode(request, mode):\n \"\"\"\n Set bill list mode (all/inbound)\n ACL: *\n \"\"\"\n request.session['mode'] = mode\n return redirect('invoice_list')\n\n\n@login_required\n@transaction.atomic\ndef invoice_add(request):\n \"\"\"\n Add new (draft) bill\n ACL: Исполнитель\n \"\"\"\n user = request.user\n approver = models.Approver.objects.get(user=user)\n if approver.role.pk != ROLE_ASSIGNEE:\n return redirect('invoice_list')\n if request.method == 'POST':\n # path = request.POST['path']\n form = forms.BillAddForm(request.POST, request.FILES)\n if form.is_valid():\n # FIXME: add transaction\n # 1. create fileseq\n fileseq = FileSeq.objects.create()\n # 2. convert image and add to fileseq\n update_fileseq(request.FILES['file'], fileseq, form.cleaned_data['rawpdf'])\n # 3. bill at all\n shipper = handle_shipper(form)\n bill = models.Invoice.objects.create(\n fileseq=fileseq,\n place=form.cleaned_data['place'],\n subject=form.cleaned_data['subject'],\n depart=form.cleaned_data['depart'],\n payer=form.cleaned_data['payer'],\n shipper=shipper,\n billno=form.cleaned_data['doc_no'],\n billdate=form.cleaned_data['doc_date'],\n billsum=form.cleaned_data['doc_sum'],\n payedsum=form.cleaned_data['sum_payed'],\n topaysum=form.cleaned_data['sum_2pay'],\n assign=approver,\n rpoint=None,\n state=models.State.objects.get(pk=STATE_DRAFT),\n )\n # 4. add route\n # boss = form.cleaned_data['boss']\n fill_route(bill)\n return redirect('invoice_view', bill.pk)\n else:\n form = forms.BillAddForm()\n return render(request, 'invoice/form.html', {\n 'form': form,\n 'places': models.Place.objects.all(),\n })\n\n\n@login_required\n@transaction.atomic\ndef invoice_edit(request, pk):\n \"\"\"\n Update (edit) new Draft bill\n ACL: root | (Испольнитель & Draft & !Locked)\n TODO: transaction\n \"\"\"\n doc = get_object_or_404(models.Invoice, pk=int(pk)) # FIXME: select_for_update(nowait=False)\n # bill = models.Bill.objects.get(pk=int(pk))\n user = request.user\n approver = models.Approver.objects.get(pk=user.pk)\n if not (request.user.is_superuser or (\n (doc.assign == approver) and\n (doc.get_state_id() == STATE_DRAFT) and\n (not doc.locked))):\n return redirect('invoice_view', bill.pk)\n if request.method == 'POST':\n form = forms.BillEditForm(request.POST, request.FILES)\n if form.is_valid():\n # FIXME: add transaction\n shipper = handle_shipper(form)\n # 1. update bill\n doc.place = form.cleaned_data['place']\n doc.subject = form.cleaned_data['subject']\n doc.depart = form.cleaned_data['depart']\n doc.payer = form.cleaned_data['payer']\n doc.shipper = shipper\n doc.billno = form.cleaned_data['billno']\n doc.billdate = form.cleaned_data['billdate']\n doc.billsum = form.cleaned_data['billsum']\n doc.payedsum = form.cleaned_data['payedsum']\n doc.topaysum = form.cleaned_data['topaysum']\n doc.save() # FIXME: update()\n # 2. update mgr (if required)\n # mgr = bill.get_mgr()\n # if (mgr.approve != form.cleaned_data['mgr']):\n # mgr.approve = form.cleaned_data['mgr']\n # mgr.save()\n # 2. update boss (if required)\n # boss = bill.get_boss()\n # if (boss.approve != form.cleaned_data['boss']):\n # boss.approve = form.cleaned_data['boss']\n # if (boss.approve.pk != USER_BOSS):\n # boss.approve = models.Approver.objects.get(pk=USER_BOSS)\n # boss.save()\n # 3. update image\n file = request.FILES.get('file', None)\n if file:\n fileseq = doc.fileseq\n fileseq.clean_children()\n update_fileseq(file, fileseq, form.cleaned_data['rawpdf']) # unicode error\n return redirect('invoice_view', doc.pk)\n else: # GET\n form = forms.BillEditForm(initial={\n 'id': doc.fileseq.pk,\n 'place': doc.place,\n 'subject': doc.subject,\n 'depart': doc.depart,\n 'payer': doc.payer,\n 'suppinn': doc.shipper.inn,\n 'suppname': doc.shipper.name,\n 'suppfull': doc.shipper.fullname,\n 'billno': doc.billno,\n 'billdate': doc.billdate,\n 'billsum': doc.billsum,\n 'payedsum': doc.payedsum,\n 'topaysum': doc.topaysum,\n # 'mgr': bill.get_mgr().approve, # костыль для initial\n # 'boss': bill.get_boss().approve, # костыль для initial\n # 'approver': 6,\n })\n return render(request, 'invoice/form.html', {\n 'form': form,\n 'object': doc,\n 'places': models.Place.objects.all(),\n })\n\n\n@login_required\n@transaction.atomic\ndef invoice_reedit(request, pk):\n \"\"\"\n Update (edit) locked Draft bill\n ACL: root | (Испольнитель & Draft & Locked)\n \"\"\"\n doc = get_object_or_404(models.Invoice, pk=int(pk))\n # bill = models.Bill.objects.get(pk=int(pk))\n user = request.user\n approver = models.Approver.objects.get(pk=user.pk)\n if not (request.user.is_superuser or (\n (doc.assign == approver) and\n (doc.get_state_id() == STATE_DRAFT) and\n doc.locked)):\n return redirect('invoice_view', doc.pk)\n max_topaysum = doc.billsum - doc.payedsum\n if request.method == 'POST':\n form = forms.BillReEditForm(request.POST, max_topaysum=doc.billsum - doc.payedsum)\n if form.is_valid():\n # 1. update bill\n doc.topaysum = form.cleaned_data['topaysum']\n if doc.route_set.count() != 3:\n fill_route(doc)\n doc.save()\n # 2. update mgr (if required)\n # mgr = bill.get_mgr()\n # if (mgr.approve != form.cleaned_data['mgr']):\n # mgr.approve = form.cleaned_data['mgr']\n # mgr.save()\n # 2. and boss (if required)\n # boss = bill.get_boss()\n # if (boss.approve != form.cleaned_data['boss']):\n # boss.approve = form.cleaned_data['boss']\n # if (boss.approve.pk != USER_BOSS):\n # boss.approve = models.Approver.objects.get(pk=USER_BOSS)\n # boss.save()\n return redirect('invoice_view', doc.pk)\n else: # GET\n # hack (fill mgr and boss for wrong invoice)\n # if (bill.route_set.count() == 0): # empty route_set\n # mgr = models.Approver.objects.get(pk=DEFAULT_CHIEF)\n # boss = models.Approver.objects.get(pk=DEFAULT_BOSS)\n # print \"Old scheme:\", bill.route_set.count()\n if doc.route_set.count() != 3:\n doc.route_set.all().delete()\n fill_route(doc)\n # /hack\n form = forms.BillReEditForm(initial={\n 'topaysum': doc.topaysum if doc.topaysum else max_topaysum,\n # 'mgr': bill.get_mgr().approve,\n # 'boss': bill.get_boss().approve,\n })\n return render(request, 'invoice/form_reedit.html', {\n 'form': form,\n 'object': doc,\n })\n\n\n@login_required\n@transaction.atomic\ndef invoice_view(request, pk, upload_form=None):\n \"\"\"\n TODO: use __can_resume()\n View | Accept/Reject bill\n ACL: (assignee & Draft & Route ok) | (approver & OnWay)\n - POST (Draft)\n -- Исполнитель & Draft\n -- Руководитель & Подписант онже [& Onway]\n -- Директор & Подписант.Роль егоже [& Onway]\n -- Бухгалтер & Подписант.Роль [& (Onway/Onpay)]\n -- Гендир & Подписант онже [& Onway]\n - POST (upload):\n -- user == Исполнитель & Draft\n - POST\n -- user == Исполнитель & Draft\n -- user.role == Директор | Бухгалтер == Подписант.Роль\n -- user == Подписант\n - GET\n -- root\n -- Исполнитель: user == Исполнитель\n -- Руководитель: user == Подписант или в Истории\n -- *: все\n \"\"\"\n\n def __can_upload(bill, approver):\n \"\"\"\n ACL to uppload img.\n user == bill.approver && bill.state == Draft\n \"\"\"\n return (approver == bill.assign) and (bill.get_state_id() == STATE_DRAFT)\n\n def __upload(request, bill):\n \"\"\"\n Upload file to Bill\n @param request\n @parma bill:models.Bill\n @return upload_form\n \"\"\"\n upload_form = forms.BillAddFileForm(request.POST, request.FILES)\n if upload_form.is_valid():\n file = request.FILES.get('file', None)\n if file:\n fileseq = bill.fileseq\n update_fileseq(file, fileseq, upload_form.cleaned_data['rawpdf']) # unicode error\n return upload_form\n\n def __can_resume(request, doc, approver):\n \"\"\"\n ACL to resume.\n - Draft and user == bill assign\n - OnWay and ((user == bill.rpoint.user) or (user.role == bill.rpoint.role))\n - OnPay and user.role == Accounter\n \"\"\"\n invoice_state_id = doc.get_state_id()\n return (\n request.POST['resume'] in {'accept', 'reject'} and (\n ((invoice_state_id == STATE_DRAFT) and (approver == doc.assign)) or (\n (invoice_state_id == STATE_ONWAY) and (\n ((doc.rpoint.approve is not None) and (approver == doc.rpoint.approve)) or\n ((doc.rpoint.approve is None) and (approver.role == doc.rpoint.role))\n )\n ) or (\n (invoice_state_id == STATE_ONPAY) and (approver.role == doc.rpoint.role)\n )\n )\n )\n\n def __resume(request, doc):\n \"\"\"\n @return resume_form, err[, redirect[ url]\n \"\"\"\n approver = models.Approver.objects.get(user=request.user)\n invoice_state_id = doc.get_state_id()\n ok = False\n err = None\n resume_form = forms.ResumeForm(request.POST)\n if resume_form.is_valid():\n resume = (request.POST['resume'] == 'accept')\n # 0. check prerequisites\n if (not resume) and (not resume_form.cleaned_data['note']): # resume not empty on reject\n err = 'Отказ необходимо комментировать'\n else:\n # 1. new comment\n models.Event.objects.create(\n doc=doc,\n approve=approver,\n resume=resume,\n comment=resume_form.cleaned_data['note']\n )\n # 2. update bill\n if resume: # Ok\n route_list = doc.route_set.all().order_by('order')\n if invoice_state_id == STATE_DRAFT: # 1. 1st (draft)\n doc.rpoint = route_list[0]\n doc.set_state_id(STATE_ONWAY)\n elif invoice_state_id == STATE_ONWAY: # 2. onway\n rpoint = doc.rpoint\n if rpoint.order == len(route_list): # 2. last (accounter)\n doc.set_state_id(STATE_ONPAY)\n else: # 3. intermediate\n doc.rpoint = doc.route_set.get(order=rpoint.order + 1)\n elif invoice_state_id == STATE_ONPAY: # OnPay\n doc.rpoint = None\n doc.payedsum += doc.topaysum\n doc.topaysum = decimal.Decimal('0.00')\n doc.set_state_id(STATE_DONE)\n doc.locked = (doc.payedsum < doc.billsum)\n else: # Reject\n doc.set_state_id(STATE_REJECTED)\n doc.rpoint = None\n doc.save()\n if (doc.get_state_id() == STATE_DONE) and (doc.locked is False): # That's all\n doc.route_set.all().delete()\n mailto(request, doc)\n ok = True\n return ok, resume_form, err\n\n def __can_accept():\n pass\n\n def __accept():\n pass\n\n def __can_reject():\n pass\n\n def __reject():\n pass\n\n doc = get_object_or_404(models.Invoice, pk=int(pk))\n user = request.user\n logger.info('invoice_view: user: %s, bill: %s' % (user.username, pk))\n approver = models.Approver.objects.get(user=user)\n invoice_state_id = doc.get_state_id()\n upload_form = None\n resume_form = None\n err = ''\n if request.method == 'POST':\n if request.POST['action'] == 'upload':\n if __can_upload(doc, approver):\n upload_form = __upload(request, doc)\n else: # resume\n if __can_resume(request, doc, approver):\n ok, resume_form, err = __resume(request, doc)\n if ok:\n return redirect('invoice_list')\n else: # GET\n if user.is_superuser or ((doc.assign == approver) and (invoice_state_id == STATE_DRAFT)):\n upload_form = forms.BillAddFileForm()\n if resume_form is None:\n resume_form = forms.ResumeForm()\n buttons = {\n # assignee & Draft*\n 'edit': (user.is_superuser or ((doc.assign == approver) and (invoice_state_id == STATE_DRAFT))),\n # assignee & (Draft|Rejected)\n 'del': (user.is_superuser or (\n (doc.assign == approver) and (invoice_state_id in {STATE_DRAFT, STATE_REJECTED}) and (\n doc.locked is False))\n ),\n # assignee & (Rejected*|Done?)\n 'restart': (user.is_superuser or ((doc.assign == approver) and (\n (invoice_state_id == STATE_REJECTED) or ((invoice_state_id == STATE_DONE) and (doc.locked is True))))),\n # assignee & Done\n 'arch': (user.is_superuser or (\n ((doc.assign == approver) or user.is_staff) and (invoice_state_id == STATE_DONE) and (\n doc.locked is False))),\n }\n # Accepting (Вперед, Согласовано, В оплате, Исполнено)\n buttons['accept'] = 0\n if invoice_state_id == STATE_DRAFT:\n if doc.assign == approver:\n buttons['accept'] = 1 # Вперед\n elif invoice_state_id == STATE_ONWAY:\n if approver.role.pk != ROLE_ACCOUNTER:\n if (((doc.rpoint.approve is None) and (doc.rpoint.role == approver.role)) or\n ((doc.rpoint.approve is not None) and (doc.rpoint.approve == approver))):\n buttons['accept'] = 2 # Согласовано\n else: # Accounter\n if doc.rpoint.role == approver.role:\n buttons['accept'] = 3 # В оплате\n elif invoice_state_id == STATE_ONPAY:\n if approver.role.pk == ROLE_ACCOUNTER:\n buttons['accept'] = 4 # Оплачен\n # Rejecting\n buttons['reject'] = 0\n if approver.role.pk != ROLE_ACCOUNTER:\n if (invoice_state_id == STATE_ONWAY) and (\n ((doc.rpoint.approve is None) and (doc.rpoint.role == approver.role)) or\n ((doc.rpoint.approve is not None) and (doc.rpoint.approve == approver))):\n buttons['reject'] = 1\n else:\n if (invoice_state_id in {STATE_ONWAY, STATE_ONPAY}) and (doc.rpoint.role == approver.role):\n buttons['reject'] = 1\n return render(request, 'invoice/detail.html', {\n 'object': doc,\n 'form': resume_form if (buttons['accept'] or buttons['reject']) else None,\n 'upload_form': upload_form,\n 'err': err,\n 'button': buttons,\n })\n\n\n@login_required\n@transaction.atomic\ndef invoice_delete(request, pk):\n \"\"\"\n Delete bill\n ACL: root | (Assignee & (Draft|Rejected) & (not Locked))\n \"\"\"\n doc = get_object_or_404(models.Invoice, pk=int(pk))\n # bill = models.Bill.objects.get(pk=int(pk))\n if request.user.is_superuser or (\n (doc.assign.user.pk == request.user.pk) and\n (doc.get_state_id() in {STATE_DRAFT, STATE_REJECTED} and\n (doc.locked is False))):\n # fileseq = bill.fileseq\n doc.delete()\n # fileseq.purge()\n return redirect('invoice_list')\n return redirect('invoice_view', doc.pk)\n\n\n@login_required\n@transaction.atomic\ndef invoice_restart(request, pk):\n \"\"\"\n Restart bill (partialy Done or Rejected)\n ACL: root | (Assignee & (Rejected | (Done & Locked)))\n \"\"\"\n doc = get_object_or_404(models.Invoice, pk=int(pk))\n # bill = models.Bill.objects.get(pk=int(pk))\n if request.user.is_superuser or (\n (doc.assign.user.pk == request.user.pk) and\n ((doc.get_state_id() == STATE_REJECTED) or (\n (doc.get_state_id() == STATE_DONE) and (doc.locked is True)))):\n doc.set_state_id(STATE_DRAFT)\n # hack about ols style\n if doc.route_set.count() != 3:\n doc.route_set.all().delete()\n fill_route(doc)\n # /hack\n doc.save()\n return redirect('invoice_view', doc.pk)\n\n\n@login_required\ndef invoice_mail(request, pk):\n \"\"\"\n Test of email\n @param pk: bill pk\n ACL: root only\n \"\"\"\n doc = models.Invoice.objects.get(pk=int(pk))\n if request.user.is_superuser:\n utils.send_mail(\n ['ti.eugene@gmail.com'],\n 'Новый счет на подпись: %s' % pk,\n 'Вам на подпись поступил новый счет: %s' % request.build_absolute_uri(\n reverse('invoice_view', kwargs={'pk': doc.pk})),\n )\n return redirect('invoice_view', doc.pk)\n\n\n@login_required\n@transaction.atomic\ndef invoice_toscan(request, pk):\n \"\"\"\n Move bill to scans.\n ACL: root | ((Исполнитель | is_staff) && Done && !Locked)\n \"\"\"\n doc = get_object_or_404(models.Invoice, pk=int(pk))\n # bill = models.Bill.objects.get(pk=int(pk))\n if request.user.is_superuser or (\n ((doc.assign.user.pk == request.user.pk) or request.user.is_staff) and\n ((doc.get_state_id() == STATE_DONE) and (not doc.locked))):\n scan = Scan.objects.create(\n fileseq=doc.fileseq,\n place=doc.place.name,\n subject=doc.subject.name if doc.subject else None,\n depart=doc.depart.name if doc.depart else None,\n payer=doc.payer.name if doc.payer else None,\n shipper=doc.shipper,\n supplier=doc.shipper.name,\n no=doc.billno,\n date=doc.billdate,\n sum=doc.billsum,\n )\n # for event in (bill.events.all()):\n for event in (doc.event_set.all()):\n scan.event_set.create(\n approve='%s %s (%s)' % (\n event.approve.user.last_name,\n event.approve.user.first_name if event.approve.user.first_name else '',\n event.approve.jobtit),\n resume=event.resume,\n ctime=event.ctime,\n comment=event.comment\n )\n doc.delete()\n return redirect('invoice_list')\n else:\n return redirect('invoice_view', doc.pk)\n\n\n@login_required\ndef invoice_img_del(request, pk):\n \"\"\"\n Delete bill img (one from).\n ACL: root | (Исполнитель && Draft)\n \"\"\"\n fsi = get_object_or_404(FileSeqItem, pk=int(pk))\n fs = fsi.fileseq\n doc = fs.bill\n if request.user.is_superuser or (\n (doc.assign.user.pk == request.user.pk) and\n (doc.get_state_id() == STATE_DRAFT)):\n fs.del_file(int(pk))\n return redirect('invoice_view', fs.pk)\n\n\n@login_required\n# transaction.atomic\ndef invoice_img_up(request, pk):\n \"\"\"\n Move img upper.\n ACL: root | (Исполнитель && Draft)\n \"\"\"\n fsi = FileSeqItem.objects.get(pk=int(pk))\n fs = fsi.fileseq\n doc = fs.bill\n if request.user.is_superuser or (\n (doc.assign.user.pk == request.user.pk) and\n (doc.get_state_id() == STATE_DRAFT)):\n if not fsi.is_first():\n fsi.swap(fsi.order - 1)\n return redirect('invoice_view', fsi.fileseq.pk)\n\n\n@login_required\n# transaction.atomic\ndef invoice_img_dn(request, pk):\n \"\"\"\n Move img lower.\n ACL: root | (Исполнитель && Draft)\n \"\"\"\n fsi = FileSeqItem.objects.get(pk=int(pk))\n doc = fsi.fileseq.bill\n if request.user.is_superuser or (\n (doc.assign.user.pk == request.user.pk) and\n (doc.get_state_id() == STATE_DRAFT)):\n if not fsi.is_last():\n fsi.swap(fsi.order + 1)\n return redirect('invoice_view', fsi.fileseq.pk)\n\n\ndef __invoice_img_r(request, pk, folder):\n \"\"\"\n Rotate image\n \"\"\"\n fsi = FileSeqItem.objects.get(pk=int(pk))\n doc = fsi.fileseq.bill\n if request.user.is_superuser or (\n (doc.assign.user.pk == request.user.pk) and\n (doc.get_state_id() == STATE_DRAFT)):\n rotate_img(fsi.file, dir)\n return redirect('invoice_view', fsi.fileseq.pk)\n\n\n@login_required\ndef invoice_img_rl(request, pk):\n \"\"\"\n Rotate img left\n \"\"\"\n return __invoice_img_r(request, pk, False)\n\n\n@login_required\ndef invoice_img_rr(request, pk):\n \"\"\"\n Rotate img right\n \"\"\"\n return __invoice_img_r(request, pk, True)\n","repo_name":"tieugene/tipython","sub_path":"dasist-0.2.0/dasist/invoice/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":28860,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"60"} +{"seq_id":"18665978889","text":"\"\"\"\nUsing two different tables, which ever is chosen, to create a data set of previously identified known lenses. \nThe two tables are Jacobs or DES2017.\nThe Jacobs known lenses are from: https://arxiv.org/abs/1811.03786 . \nThe DES2017 known lenses are from: https://iopscience.iop.org/article/10.3847/1538-4365/aa8667 .\n\nThe data from the chosen table is then put into a readible format, either .fits or .xlsx files. \nThis data is read, and the g, r and i DES images are downloaded corresponding to the given ra, and dec\ncoordinates in the respective files. These original DES images are clipped using WCS, to create \na 100*100 pixel image. These images are then normalised and a RGB composite is made. These images are the KnownLenses.\n\"\"\"\nimport glob\n# importing modules needed\nimport matplotlib\nmatplotlib.use('Agg')\nimport os\nimport sys\nimport desTiler\nimport astropy.table as atpy\nimport xlrd\nfrom astLib import *\nfrom astropy.io import fits\nfrom negativeDESUtils import loadDES, normaliseRGB\n\n\ndef clipWCS(tile_name, num, ra, dec, path_processed, des_tile='', base_dir='DES/DES_Original'):\n \"\"\"\n Clips the g, r, i original .fits images for each source from DES to have 100*100 pixel size\n or 0.0073125*0.007315 degrees. The wcs coordinates are used, to maintain the necessary\n information that may be needed in future. These WCSclipped images are saved at \n ('%s.WCSclipped.fits' % (paths[band+'BandPath']). The wcs images, are normalised and\n saved at ('%s.norm.fits' % (paths[band + 'BandPath']).\n\n Args:\n tilename(string): The tilename of the DES image from DES DR1. This is the often referred to as the \n source name of the image. \n num(integer): This is the number of the source that is to be processed. \n ra(float): This is the Right Ascension of the source retrieved from the DES_Access table.\n dec(float): This is the Declination of the source retrieved from the DEC_Access table.\n path_processed(string): This is the path of directory in which the wcsclipped images are to be saved.\n des_tile(string): This is the DESJ2000 name given for these sources in the DES2017 paper.\n base_dir(string): This is the root directory of the DES Original images, for each source \n which are clipped in this clipWCS function.\n Saves:\n wcs_clipped (numpy array): A numpy array of the WCSclipped, with its wcs coordinates.\n The g, r, and i wcs_clipped images are saved under '\n KnownLense/table/num_source/', with the revelant astronomical\n parameters in the header of these images.\n \"\"\"\n\n # Getting the RA and Dec of each source\n size_wcs = [0.0073125, 0.0073125] # 100*100 pixels in degrees\n\n paths = {'gBandPath': glob.glob('%s/%s/%s*_g.fits.fz' % (base_dir, tile_name, tile_name))[0],\n 'rBandPath': glob.glob('%s/%s/%s*_r.fits.fz' % (base_dir, tile_name, tile_name))[0],\n 'iBandPath': glob.glob('%s/%s/%s*_i.fits.fz' % (base_dir, tile_name, tile_name))[0]}\n\n if not os.path.exists('%s' % path_processed):\n os.mkdir('%s' % path_processed)\n\n new_path = '%s/%s_%s' % (path_processed, num, tile_name)\n if not os.path.exists('%s' % new_path):\n os.mkdir('%s' % new_path)\n\n for band in ['g', 'r', 'i']:\n with fits.open(paths[band + 'BandPath']) as bandDES:\n header = bandDES[1].header\n header.set('RA', ra)\n header.set('DEC', dec)\n # header.set('DES', des_tile)\n wcs = astWCS.WCS(header, mode=\"pyfits\")\n wcs_clipped = astImages.clipImageSectionWCS(bandDES[1].data, wcs, ra, dec, size_wcs)\n astImages.saveFITS('%s/%s_WCSClipped.fits' % (new_path, band), wcs_clipped['data'], wcs)\n print('Created %s_WCSclipped at %s/%s_WCSClipped.fits' % (band, new_path, band))\n\n\n# ____________________________________________________________________________________________________________________\n# MAIN\nstart_number = int(sys.argv[1])\nprint(start_number)\nlocation_of_file = \"UnseenData/Unseen_KnownLenses.xlsx\"\nworkbook = xlrd.open_workbook(location_of_file) # opening a workbook\nsheet = workbook.sheet_by_index(0)\nnum_of_rows = sheet.nrows\nra = 0.0\ndec = 0.0\n\nfor num in range(start_number, sheet.nrows):\n print(\"Num: \" + str(num))\n des_tile = sheet.cell_value(num, 0).encode('utf-8')\n print(\"DESTILE: \" + (des_tile) + \" TYPE: \" + str(type(des_tile)))\n ra = str(sheet.cell_value(num, 1)).encode('utf-8')\n col_c = sheet.cell_value(num, 2) # index of whether or not dec is +ve or -ve\n\n dec_degree = str(sheet.cell_value(num, 4)).encode('utf-8')\n\n ra = float(ra)\n if col_c == 1:\n dec = 0 - float(dec_degree)\n elif col_c == 0:\n dec = float(dec_degree)\n\n print(\"ra: \" + str(ra) + \" TYPE: \" + str(type(ra)))\n print(\"dec: \" + str(dec) + \" TYPE: \" + str(type(dec)))\n\n tiler = desTiler.DESTiler(\"UnseenData/DES_DR1_TILE_INFO.csv\")\n\n # How to get tile name\n ra_deg, dec_deg = ra, dec\n tile_name = tiler.getTileName(ra_deg, dec_deg)\n if tile_name is None:\n print('TileName is NONE')\n continue\n\n print('TileName: ' + tile_name)\n # How to fetch all images for tile which contains given coords\n tiler.fetchTileImages(ra_deg, dec_deg, tile_name)\n print('done')\n path_processed = 'UnseenData/KnownLenses'\n # get g_mag, r_mag, i_mag\n #loadDES(tile_name)\n print('loaded image from DES')\n clipWCS(tile_name, num, ra_deg, dec_deg, path_processed, des_tile)\n normaliseRGB(num, tile_name, base_dir=path_processed)\n","repo_name":"Annarien/GravitationalLenses","sub_path":"Training/knownLenses.py","file_name":"knownLenses.py","file_ext":"py","file_size_in_byte":5772,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"60"} +{"seq_id":"8516662529","text":"from flask import Flask, request, jsonify\nfrom google.ads.googleads.client import GoogleAdsClient\nfrom google.ads.googleads.errors import GoogleAdsException\n\napp = Flask(__name__)\n\n@app.route('/getaccountdetails')\ndef get_account_details():\n login_customer_id = request.args.get('login_customer_id')\n if not login_customer_id:\n return 'Error: Please provide a login_customer_id.'\n\n try:\n # Create the Google Ads client using the configuration file.\n googleads_client = GoogleAdsClient.load_from_storage()\n\n # Call the main method to get the account hierarchy.\n accounts_hierarchy = main(googleads_client, login_customer_id)\n\n # Return the accounts hierarchy as a JSON response.\n return jsonify(accounts_hierarchy)\n\n except GoogleAdsException as ex:\n return 'Error: An error occurred while getting the account hierarchy - {}'.format(ex.message)\n\ndef main(client, login_customer_id=None):\n \"\"\"Gets the account hierarchy of the given MCC and login customer ID.\n\n Args:\n client: The Google Ads client.\n login_customer_id: Optional manager account ID. If none provided, this\n method will instead list the accounts accessible from the\n authenticated Google Ads account.\n \"\"\"\n\n # Gets instances of the GoogleAdsService and CustomerService clients.\n googleads_service = client.get_service(\"GoogleAdsService\")\n customer_service = client.get_service(\"CustomerService\")\n\n # A collection of customer IDs to handle.\n seed_customer_ids = []\n\n # Creates a query that retrieves all child accounts of the manager\n # specified in search calls below.\n query = \"\"\"\n SELECT\n customer_client.client_customer,\n customer_client.level,\n customer_client.manager,\n customer_client.descriptive_name,\n customer_client.currency_code,\n customer_client.time_zone,\n customer_client.id\n FROM customer_client\n WHERE customer_client.level <= 1\"\"\"\n\n # If a Manager ID was provided in the customerId parameter, it will be\n # the only ID in the list. Otherwise, we will issue a request for all\n # customers accessible by this authenticated Google account.\n if login_customer_id is not None:\n seed_customer_ids = [login_customer_id]\n else:\n accounts_hierarchy = []\n customer_resource_names = (\n customer_service.list_accessible_customers().resource_names\n )\n\n for customer_resource_name in customer_resource_names:\n customer_id = googleads_service.parse_customer_path(\n customer_resource_name\n )[\"customer_id\"]\n seed_customer_ids.append(customer_id)\n\n accounts_hierarchy = []\n for seed_customer_id in seed_customer_ids:\n # Performs a breadth-first search to build a Dictionary that maps\n # managers to their child accounts (customerIdsToChildAccounts).\n unprocessed_customer_ids = [seed_customer_id]\n customer_ids_to_child_accounts = dict()\n root_customer_client = None\n\n while unprocessed_customer_ids:\n customer_id = int(unprocessed_customer_ids.pop(0))\n response = googleads_service.search(\n customer_id=str(customer_id), query=query\n )\n\n # Iterates over all rows in all pages to get all customer\n # clients under the specified customer's hierarchy.\n for googleads_row in response:\n customer_client = googleads_row.customer_client\n\n # The customer client that with level \n # 0 is the manager account.\n if customer_client.level == 0:\n root_customer_client = customer_client\n continue\n\n # Adds the customer ID to the map with a reference to the\n # customer client.\n if customer_client.manager in customer_ids_to_child_accounts:\n customer_ids_to_child_accounts[customer_client.manager].append(\n customer_client\n )\n else:\n customer_ids_to_child_accounts[customer_client.manager] = [\n customer_client\n ]\n\n # Adds the customer ID to the list of unprocessed customers.\n if customer_client.client_customer in customer_ids_to_child_accounts:\n unprocessed_customer_ids.append(customer_client.id)\n\n # Converts the customer ID map into a hierarchy.\n hierarchy = convert_customer_id_map_to_hierarchy(\n customer_ids_to_child_accounts, root_customer_client\n )\n\n accounts_hierarchy.append(hierarchy)\n\n return accounts_hierarchy\n\n\ndef convert_customer_id_map_to_hierarchy(\n customer_ids_to_child_accounts, root_customer_client\n):\n \"\"\"Converts a map of customer IDs to their child accounts into a dictionary\n representing a hierarchy of accounts.\n\n Args:\n customer_ids_to_child_accounts: A dictionary mapping customer IDs to their\n child accounts.\n root_customer_client: The root customer client for the hierarchy.\n\n Returns:\n A dictionary representing the hierarchy of accounts.\n \"\"\"\n hierarchy = {\n \"id\": root_customer_client.id,\n \"name\": root_customer_client.descriptive_name,\n \"currency_code\": root_customer_client.currency_code,\n \"time_zone\": root_customer_client.time_zone,\n }\n\n if root_customer_client.id in customer_ids_to_child_accounts:\n hierarchy[\"child_accounts\"] = [\n convert_customer_id_map_to_hierarchy(\n customer_ids_to_child_accounts, child\n )\n for child in customer_ids_to_child_accounts[root_customer_client.id]\n ]\n\n return hierarchy\n\n\nif __name__ == \"__main__\":\n app.run()","repo_name":"Sathishkumar-Ramachandran/GoogleAds","sub_path":"Account/GetAccountHierarchy.py","file_name":"GetAccountHierarchy.py","file_ext":"py","file_size_in_byte":5814,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"60"} +{"seq_id":"40131422904","text":"import os\nimport shutil\nfrom PIL import Image\nimport numpy as np\nfrom numpy.random import randint\nimport scipy.io\nimport imageio\n\n\n# takes an image file path and returns the 3D numpy array representing it\ndef get_image_array(path):\n image = Image.open(path)\n ans = np.asarray(image)\n image.close()\n return ans\n\ndef replace_mask_colour (study_image, ZL_colour):\n ZL_file = scipy.io.loadmat('ZL_colors.mat') # load the ZL_colors file\n\n # access the RGB fields:\n ZL_red = ZL_file['ZL_colors'][0][0][0][0][int(ZL_colour - 1)]\n ZL_green = ZL_file['ZL_colors'][0][0][1][0][int(ZL_colour - 1)]\n ZL_blue = ZL_file['ZL_colors'][0][0][2][0][int(ZL_colour - 1)]\n\n # specify the mask colors to be replaced\n colour_file_data = get_image_array('vcs_stim\\\\shapecolourv4_colour.jpg')\n \n # the +-1 is to capture visual artifacts in the image while assigning new values\n # maybe this can be moved somewhere cleanly so that it doesn't have to process every time, \n # but this is pretty fast to begin with, and time accuracy hasn't been an issue\n mask_colours = np.empty([3, 3])\n mask_colours[0][0] = colour_file_data[0][0][0]\n mask_colours[0][1] = mask_colours[0][0] - 1\n mask_colours[0][2] = mask_colours[0][0] + 1\n\n mask_colours[1][0] = colour_file_data[0][0][1]\n mask_colours[1][1] = mask_colours[1][0] - 1\n mask_colours[1][2] = mask_colours[1][0] + 1\n\n mask_colours[2][0] = colour_file_data[0][0][2]\n mask_colours[2][1] = mask_colours[2][0] - 1\n mask_colours[2][2] = mask_colours[2][0] + 1\n\n # now access the color data of the study image file:\n red_channel = np.array(study_image[:, :, 0])\n green_channel = np.array(study_image[:, :, 1])\n blue_channel = np.array(study_image[:, :, 2])\n\n # replace the mask-valued colors with the specified ZL color\n red_channel[red_channel == mask_colours[0][0]] = ZL_red\n red_channel[red_channel == mask_colours[0][1]] = ZL_red\n red_channel[red_channel == mask_colours[0][2]] = ZL_red\n red_channel[red_channel == mask_colours[0][0] + 2] = ZL_red\n red_channel[red_channel == mask_colours[0][0] - 2] = ZL_red\n green_channel[green_channel == mask_colours[1][0]] = ZL_green\n green_channel[green_channel == mask_colours[1][1]] = ZL_green\n green_channel[green_channel == mask_colours[1][2]] = ZL_green\n green_channel[green_channel == mask_colours[0][0] + 2] = ZL_green\n green_channel[green_channel == mask_colours[0][0] - 2] = ZL_green\n blue_channel[blue_channel == mask_colours[2][0]] = ZL_blue\n blue_channel[blue_channel == mask_colours[2][0]] = ZL_blue\n blue_channel[blue_channel == mask_colours[2][0]] = ZL_blue\n blue_channel[blue_channel == mask_colours[0][0] + 2] = ZL_blue\n blue_channel[blue_channel == mask_colours[0][0] - 2] = ZL_blue\n \n return np.dstack((red_channel, green_channel, blue_channel)) # re-combine the three channels\n\n# generates a list of dictionaries for use with TrialHandler, one dictionary of trial params per trial\n# keys: 'condition' (either 1, 2, or 3), 'shape_1' (VCS 1 - 360), 'shape_2' (VCS 1 - 360), 'shape_3' (VCS 1 - 360),\n# 'colour_1' (ZL 1 - 180), 'colour_2' (ZL 1 - 180), 'colour_3' (ZL 1 - 180), 'study_shape', 'study_colour',\n# 'shape_jitter' (note: same for every trial), 'colour_jitter' (unique per trial)\ndef trial_matrix(trial_num=60):\n trial_lists = []\n for i in range(trial_num):\n rand_shape = randint(1, 361)\n rand_colour = randint(1, 181)\n\n shape_list = [rand_shape + i * 36 for i in range(1, 11)]\n for shape in shape_list:\n if shape > 360:\n shape_list[shape_list.index(shape)] = shape - 360\n \n colour_list = [rand_colour + i * 18 for i in range(1, 11)]\n for colour in colour_list:\n if colour > 180:\n colour_list[colour_list.index(colour)] = colour - 180\n \n trial_list = [(shape_list[i], colour_list[i]) for i in range(10)]\n trial_lists.append(trial_list)\n\n if os.path.exists('generated_stim'):\n shutil.rmtree('generated_stim')\n os.makedirs('generated_stim')\n\n for i, trial in enumerate(trial_lists):\n for j in range(10):\n shape_path = f'vcs_stim\\\\shapecolourv4_{trial[j][0]}.jpg'\n filepath = f'generated_stim\\\\t{i+1}_{j+1}.jpg'\n imageio.imsave(filepath, replace_mask_colour(get_image_array(shape_path), trial[j][1]))\n\ntrial_matrix()","repo_name":"james-y-yuan/executable-pipeline","sub_path":"stimulus_generator/generate_stims.py","file_name":"generate_stims.py","file_ext":"py","file_size_in_byte":4434,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"60"} +{"seq_id":"29005526415","text":"import random\nimport numpy\nimport time\nimport math\nfrom pyspark import SparkFiles\n\nfrom operator import add\n\n\n'''\nTo run:\n In pyspark: copy and paste this code\n'''\n\nSTRIKE_PRICE = 105 # K\nASSET_PRICE = 100 # S\nT = 1 # 1 year\nSTEPS = 100 # N \nRATE = 0.05 # R == 12%\nSIGMA = 4.5\nTHETA = 0\n# m steps, n num simulations\n\n####################################\n# Computing the constants*\n####################################\n\ndt = T/float(STEPS)\nnudt = (RATE - THETA - (pow(SIGMA, 2)/2)) * dt\nsigsdt = SIGMA * pow(dt, 0.5)\nlnS = math.log(ASSET_PRICE)\ndiscount_factor = math.exp(-RATE * T)\n\n\npath = os.path.join(\"./\", \"ints.txt\")\nsc.addFile(path)\n\n\ndef call_payoff(asset_price, STRIKE_PRICE):\n return max(0.0, asset_price - STRIKE_PRICE)\n\ndef grow(seed):\n numpy.random.seed(int(seed))\n portfolio_value = ASSET_PRICE\n lnSt = lnS\n for x in range(STEPS):\n lnSt += nudt + sigsdt * numpy.random.normal()\n asset_price_ST = math.exp(lnSt)\n portfolio_value += call_payoff(asset_price_ST, STRIKE_PRICE)\n \n return portfolio_value\n\n###########################################\n# This method helps simulate getting the \n# values in the intermediate steps as it\n# could not be accessed in grow() because\n# they were being run on worker nodes. You\n# said it was okay to do this.\n###########################################\ndef mockIntermediateValues(seed, n):\n numpy.random.seed(int(seed))\n portfolio_value = ASSET_PRICE\n lnSt = lnS\n f = open(\"ints_{num}.txt\".format(num=n), \"a+\")\n for x in range(STEPS):\n lnSt += nudt + sigsdt * numpy.random.normal()\n val = portfolio_value+lnSt\n f.write(\"%0.2f\\n\" % val)\n \n asset_price_ST = math.exp(lnSt)\n portfolio_value += call_payoff(asset_price_ST, STRIKE_PRICE)\n \n f.close()\n\nseeds = sc.parallelize([time.time() + i for i in xrange(100000)])\nresults = seeds.map(grow)\n\nsum = results.reduce(add)\nprice = sum/100000.\n\n# print option value\n\"${:,.2f}\".format(price)\n\n\n# Run 5 simulations for spreadsheet report\nfor x in xrange(1,6):\n mockIntermediateValues(time.time(), x)\n","repo_name":"talk2bryan/cloud-computing-class","sub_path":"a4/src/cloud/assignments/a4/MonteCarloStockGrowthEstimate.py","file_name":"MonteCarloStockGrowthEstimate.py","file_ext":"py","file_size_in_byte":2087,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"60"} +{"seq_id":"74517460031","text":"LAB_SOURCE_FILE = __file__\n\n\ndef add_chars(w1, w2):\n s=''\n j=0\n for ch in w2:\n if j==len(w1):\n s+=ch\n elif ch != w1[j]:\n s+=ch\n else:\n j=1\n return s\n\n","repo_name":"AshenskyABCDE/Python-CS61A-","sub_path":"lab/lab04/lab04/lab04.py","file_name":"lab04.py","file_ext":"py","file_size_in_byte":216,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"60"} +{"seq_id":"29149446726","text":"#!/usr/bin/env python3\nfrom apollo import __version__\nimport setuptools\nimport argparse\nimport os.path\nimport snakemake\nimport sys\nfrom tempfile import gettempdir\nimport tempfile\nimport pprint\nimport json\nimport csv\nimport os\nfrom datetime import datetime\nfrom Bio import SeqIO\nimport csv\n\nimport pkg_resources\nfrom . import _program\n\nimport apollofunks as qcfunk\nimport custom_logger as custom_logger\nimport log_handler_handle as lh\n\nthisdir = os.path.abspath(os.path.dirname(__file__))\ncwd = os.getcwd()\n\ndef main(sysargs = sys.argv[1:]):\n\n parser = argparse.ArgumentParser(prog = _program, \n description=qcfunk.preamble(__version__), \n usage='''apollo -i [options]\n apollo -c ''')\n\n io_group = parser.add_argument_group('input output options')\n io_group.add_argument('-c',\"--configfile\",help=\"Config file with apollo run settings\",dest=\"configfile\")\n io_group.add_argument('-i','--read-path',help=\"Path to the directory containing fastq files\",dest=\"read_path\")\n io_group.add_argument('-o','--output-prefix', action=\"store\",help=\"Output prefix. Default: apollo__\")\n io_group.add_argument('--outdir', action=\"store\",help=\"Output directory. Default: current working directory\")\n io_group.add_argument('--tempdir',action=\"store\",help=\"Specify where you want the temp stuff to go. Default: $TMPDIR\")\n \n\n barcode_group = parser.add_argument_group('barcode options')\n barcode_group.add_argument('-b','--barcodes-csv',help=\"CSV file describing which barcodes were used on which sample\",dest=\"barcodes_csv\")\n barcode_group.add_argument('-k','--barcode-kit',help=\"Indicates which barcode kit was used. Default: native. Options: native, rapid, pcr, all\",dest=\"barcode_kit\")\n\n demux_group = parser.add_argument_group('demultiplexing options')\n demux_group.add_argument('--demultiplex',action=\"store_true\",help=\"Indicates that your reads have not been demultiplexed and will run guppy demultiplex on your provided read directory\",dest=\"demultiplex\")\n demux_group.add_argument('--path-to-guppy',action=\"store\",help=\"Path to guppy_barcoder executable\",dest=\"path_to_guppy\")\n\n run_group = parser.add_argument_group('run options')\n run_group.add_argument('-s',\"--species\", action=\"store\",help=\"Indicate which species is being sequenced. Options: mus, apodemus, desmodus\", dest=\"species\")\n run_group.add_argument(\"-r\",\"--report\",action=\"store_true\",help=\"Generate markdown report of estimated age\")\n \n misc_group = parser.add_argument_group('misc options')\n misc_group.add_argument('-t', '--threads', action='store',type=int,help=\"Number of threads\")\n misc_group.add_argument(\"--no-temp\",action=\"store_true\",help=\"Output all intermediate files, for dev purposes.\")\n misc_group.add_argument(\"--verbose\",action=\"store_true\",help=\"Print lots of stuff to screen\")\n misc_group.add_argument(\"-v\",\"--version\", action='version', version=f\"apollo {__version__}\")\n\n \"\"\"\n Exit with help menu if no args supplied\n \"\"\"\n\n args = parser.parse_args(sysargs)\n \n \"\"\"\n Initialising dicts\n \"\"\"\n\n config = qcfunk.get_defaults()\n\n configfile = qcfunk.look_for_config(args.configfile,cwd,config)\n\n # if a yaml file is detected, add everything in it to the config dict\n if configfile:\n qcfunk.parse_yaml_file(configfile, config)\n else:\n if len(sysargs)<1: \n parser.print_help()\n sys.exit(0)\n \n \"\"\"\n Get outdir, tempdir and the data\n \"\"\"\n # get data for a particular species, and get species\n qcfunk.get_package_data(thisdir, args.species, config)\n \n # default output dir\n qcfunk.get_outdir(args.outdir,args.output_prefix,cwd,config)\n\n # specifying temp directory, outdir if no_temp (tempdir becomes working dir)\n tempdir = qcfunk.get_temp_dir(args.tempdir, args.no_temp,cwd,config)\n\n \n\n config[\"cpg_header\"] = qcfunk.make_cpg_header(config[\"cpg_sites\"])\n\n # add min and max read lengths to the config\n qcfunk.get_read_length_filter(config)\n\n # looks for basecalled directory\n qcfunk.look_for_basecalled_reads(args.read_path,cwd,config)\n \n # looks for the csv file saying which barcodes in sample\n qcfunk.look_for_barcodes_csv(args.barcodes_csv,cwd,config)\n\n \"\"\"\n Configure whether guppy barcoder needs to be run\n \"\"\"\n\n qcfunk.look_for_guppy_barcoder(args.demultiplex,args.path_to_guppy,cwd,config)\n\n\n # don't run in quiet mode if verbose specified\n if args.verbose:\n quiet_mode = False\n config[\"log_string\"] = \"\"\n else:\n quiet_mode = True\n lh_path = os.path.realpath(lh.__file__)\n config[\"log_string\"] = f\"--quiet --log-handler-script {lh_path} \"\n\n qcfunk.add_arg_to_config(\"threads\",args.threads,config)\n \n try:\n config[\"threads\"]= int(config[\"threads\"])\n except:\n sys.stderr.write(qcfunk.cyan('Error: Please specifiy an integer for variable `threads`.\\n'))\n sys.exit(-1)\n threads = config[\"threads\"]\n\n print(f\"Number of threads: {threads}\\n\")\n\n # find the master Snakefile\n snakefile = qcfunk.get_snakefile(thisdir)\n\n if args.verbose:\n print(\"\\n**** CONFIG ****\")\n for k in sorted(config):\n print(qcfunk.green(k), config[k])\n\n status = snakemake.snakemake(snakefile, printshellcmds=True, forceall=True, force_incomplete=True,\n workdir=tempdir,config=config, cores=threads,lock=False\n )\n else:\n logger = custom_logger.Logger()\n status = snakemake.snakemake(snakefile, printshellcmds=False, forceall=True,force_incomplete=True,workdir=tempdir,\n config=config, cores=threads,lock=False,quiet=True,log_handler=logger.log_handler\n )\n\n if status: # translate \"success\" into shell exit code of 0\n return 0\n\n return 1\n\nif __name__ == '__main__':\n main()","repo_name":"WildAnimalClocks/apollo","sub_path":"apollo/command.py","file_name":"command.py","file_ext":"py","file_size_in_byte":5986,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"60"} +{"seq_id":"18171363121","text":"import os\nimport discord\n\nimport asyncio\nimport youtube_dl\n\nfrom discord.ext import commands\n\nimport aiomysql # async db\n\nfrom dotenv import load_dotenv\n\ndescription = '''Shaun & Sean's Mechanized Commander'''\n\nintents = discord.Intents.default()\nintents.members = True\n\nload_dotenv()\n\ndb_host = os.getenv('DB_HOST')\ndb_user = os.getenv('DB_USER')\ndb_password = os.getenv('DB_PASSWORD')\ndb_database = os.getenv('DB_DATABASE')\ndb_admin_whitelist = [str(i) for i in os.environ.get(\n \"DB_ADMIN_WHITELIST\").split(\",\")]\n\nwipe_password = \"boom\"\n\nbot = commands.Bot(command_prefix='!',\n description=description, intents=intents)\n\n\n@bot.event\nasync def on_ready():\n print('------')\n print('Logged in as')\n print(bot.user.name)\n print(bot.user.id)\n print('------')\n\n\n@bot.command()\nasync def printout(ctx):\n \"\"\"Check that it works\"\"\"\n # ctx (context) object\n # details available at https://discordpy.readthedocs.io/en/rewrite/ext/commands/api.html#context\n # https://discordpy.readthedocs.io/en/stable/api.html#guild\n # https://discordpy.readthedocs.io/en/stable/api.html#message\n print(\"It works!\")\n await ctx.send(\"It works!\")\n # await ctx.send(ctx.message.guild)\n await ctx.send(ctx.message.guild.id)\n\n\n@bot.command()\nasync def create(ctx, name: str, discord_id=\"0\", ):\n conn = await aiomysql.connect(\n\n host=db_host,\n user=db_user,\n password=db_password,\n db=db_database,\n )\n cursor = await conn.cursor()\n\n sql_select_query = \"\"\"SELECT * FROM teamkills WHERE name = %s AND guild_id = %s\"\"\"\n await cursor.execute(sql_select_query, (name, ctx.message.guild.id))\n record = await cursor.fetchone()\n msg = \"\"\n\n if record is None:\n mysql_insert_query = \"\"\"INSERT INTO teamkills (`name`, `discord_id`, `deaths`, `guild_id`)\n VALUES (%s, %s, %s, %s) \"\"\"\n await cursor.execute(mysql_insert_query, (name, discord_id, 0, ctx.message.guild.id))\n msg = name + \" added! Welcome to the Thunderdome.\"\n else:\n msg = \"This guy already exists\"\n\n await ctx.send(msg)\n\n await conn.commit()\n await cursor.close()\n\n\n@bot.command()\nasync def inject(ctx, injection_string: str):\n # Johnny Tables\n\n conn = await aiomysql.connect(\n\n host=db_host,\n user=db_user,\n password=db_password,\n db=db_database,\n )\n cursor = await conn.cursor()\n\n if not (str(ctx.message.author.id) in db_admin_whitelist):\n print(\"Invalid user - Injection command cancelled.\")\n return\n\n print(\"We're about to inject:\\n\" + injection_string)\n\n await cursor.execute(injection_string)\n records = await cursor.fetchall()\n msg = \"\"\n\n if records is not None:\n # If statement returns results, print them out\n for row in records:\n for item in row:\n msg += str(item) + \" \"\n msg += \"\\n\"\n\n if (msg == \"\"):\n msg = \"Done!\"\n\n await ctx.send(msg)\n await conn.commit()\n await cursor.close()\n\n\n@bot.command()\nasync def remove(ctx, name: str):\n conn = await aiomysql.connect(\n host=db_host,\n user=db_user,\n password=db_password,\n db=db_database,\n )\n cursor = await conn.cursor()\n\n sql_select_query = \"\"\"DELETE FROM teamkills WHERE name = %s AND guild_id = %s\"\"\"\n await cursor.execute(sql_select_query, (name, ctx.message.guild.id))\n\n await ctx.send(\"OK - done\")\n\n await conn.commit()\n await cursor.close()\n\n\n@bot.command()\nasync def add(ctx, name: str):\n \"\"\"Adds TK`s\"\"\"\n # await ctx.message.delete()\n conn = await aiomysql.connect(\n host=db_host,\n user=db_user,\n password=db_password,\n db=db_database,\n )\n cursor = await conn.cursor()\n\n sql_select_query = \"\"\"SELECT * FROM teamkills WHERE name = %s AND guild_id = %s\"\"\"\n await cursor.execute(sql_select_query, (name, ctx.message.guild.id))\n record = await cursor.fetchone()\n\n msg = \"\"\n\n if record is not None:\n sql_update_query = \"\"\"UPDATE teamkills SET deaths = %s WHERE name = %s AND guild_id = %s\"\"\"\n new_kill = record[3] + 1\n await cursor.execute(sql_update_query, (new_kill, name, ctx.message.guild.id))\n\n msg = \"TK ADDED: \\n\" + name + \" is now on \" + str(new_kill) + \" Kills\"\n else:\n mysql_insert_query = \"\"\"INSERT INTO teamkills (`name`, `deaths`, `guild_id`)\n VALUES (%s, %s, %s) \"\"\"\n await cursor.execute(mysql_insert_query, (name, 0, ctx.message.guild.id))\n msg = name + \" does not exist, added instead! Welcome to the Thunderdome.\"\n\n await ctx.send(msg)\n\n await conn.commit()\n await cursor.close()\n\n\n@bot.command()\nasync def set(ctx, name: str, num: int):\n \"\"\"Sets the score\"\"\"\n # await ctx.message.delete()\n conn = await aiomysql.connect(\n host=db_host,\n user=db_user,\n password=db_password,\n db=db_database,\n )\n cursor = await conn.cursor()\n\n sql_select_query = \"\"\"SELECT * FROM teamkills WHERE name = %s AND guild_id = %s\"\"\"\n await cursor.execute(sql_select_query, (name, ctx.message.guild.id))\n record = await cursor.fetchone()\n\n msg = \"\"\n\n if record is not None:\n sql_select_query = \"\"\"UPDATE teamkills SET deaths = %s WHERE name = %s AND guild_id = %s\"\"\"\n await cursor.execute(sql_select_query, (num, name, ctx.message.guild.id))\n msg = \"SCORE SET: \\n\" + name + \" is now on \" + str(num) + \" Kills\"\n else:\n msg = \"Person doesn't exist, didn't do anything.\"\n pass\n\n await ctx.send(msg)\n\n await conn.commit()\n await cursor.close()\n\n\n@bot.command()\nasync def get(ctx, name: str):\n \"\"\"f\"\"\"\n # await ctx.message.delete()\n conn = await aiomysql.connect(\n host=db_host,\n user=db_user,\n password=db_password,\n db=db_database,\n )\n cursor = await conn.cursor()\n\n sql_select_query = \"\"\"SELECT * FROM teamkills WHERE name = %s AND guild_id = %s\"\"\"\n await cursor.execute(sql_select_query, (name, ctx.message.guild.id))\n record = await cursor.fetchone()\n\n msg = \"\"\n\n if record is not None:\n msg = record[1] + \" is on \" + str(record[3]) + \" kills.\"\n else:\n\n msg = \"You numpty, \" + name + \\\n \" doesn't even exist. Use '!add \" + name + \"' to add them.\"\n\n await ctx.send(msg)\n\n await conn.commit()\n await cursor.close()\n\n\n@bot.command()\nasync def check(ctx):\n \"\"\"Counts TK`s\"\"\"\n # await ctx.message.delete()\n conn = await aiomysql.connect(\n host=db_host,\n user=db_user,\n password=db_password,\n db=db_database,\n )\n cursor = await conn.cursor()\n\n sql_select_query = \"\"\"SELECT * FROM teamkills where guild_id = %s ORDER BY deaths DESC\"\"\"\n await cursor.execute(sql_select_query, (ctx.message.guild.id,))\n records = await cursor.fetchall()\n print(\"Fetching teamkillers list\")\n msg = \"TeamKillers: \\n\"\n for row in records:\n msg += row[1] + \": \" + str(row[3]) + \"\\n\"\n\n await ctx.send(msg)\n\n await conn.commit()\n await cursor.close()\n\n\n@bot.command()\nasync def wipe(ctx, password: str):\n \"\"\"Wipe TK`s\"\"\"\n await ctx.message.delete()\n conn = await aiomysql.connect(\n host=db_host,\n user=db_user,\n password=db_password,\n db=db_database,\n )\n cursor = await conn.cursor()\n sql_update_query = \"\"\"UPDATE teamkills SET deaths = 0 WHERE guild_id = %s\"\"\"\n\n msg = \"\"\n\n if password == wipe_password:\n\n await cursor.execute(sql_update_query, (ctx.message.guild.id,))\n\n msg = \"WIPEEEEEEED\"\n else:\n msg = \"Password incorrect - You'll need it to perform a wipe.\"\n pass\n\n await ctx.send(msg)\n\n await conn.commit()\n await cursor.close()\n\n\n@bot.command()\nasync def rename(ctx, name: str, new_name: str):\n \"\"\"Renames somebody\"\"\"\n # await ctx.message.delete()\n conn = await aiomysql.connect(\n host=db_host,\n user=db_user,\n password=db_password,\n db=db_database,\n )\n cursor = await conn.cursor()\n\n sql_select_query = \"\"\"SELECT * FROM teamkills WHERE name = %s AND guild_id = %s\"\"\"\n await cursor.execute(sql_select_query, (name, ctx.message.guild.id))\n record = await cursor.fetchone()\n\n if record is not None:\n sql_update_query = \"\"\"UPDATE teamkills SET name = %s WHERE name = %s AND guild_id = %s\"\"\"\n await cursor.execute(sql_update_query, (new_name, name, ctx.message.guild.id))\n await ctx.send(\"RENAMED: \\n\" + name + \" is now called \" + new_name + \".\")\n else:\n\n await ctx.send(\"You numpty, \" + name + \" doesn't even exist. Use '!add \" + name + \"' to add them.\")\n\n await conn.commit()\n await cursor.close()\n\n\n@bot.command()\nasync def nigel(ctx):\n \"\"\"Absolutely thrashes someone\"\"\"\n # await ctx.message.delete()\n await ctx.send(\"What an absolute Nigel\")\n\n\n@bot.command()\nasync def winner(ctx):\n conn = await aiomysql.connect(\n host=db_host,\n user=db_user,\n password=db_password,\n db=db_database,\n )\n cursor = await conn.cursor()\n\n sql_select_query = \"\"\"SELECT * FROM teamkills WHERE guild_id = %s ORDER BY deaths desc LIMIT 1\"\"\"\n await cursor.execute(sql_select_query, (ctx.message.guild.id,))\n record = await cursor.fetchone()\n if record is not None:\n msg = \"As it looks, \" + \\\n record[1] + \" is in the lead with a smashing \" + \\\n str(record[3]) + \" teamkills.\"\n else:\n msg = \"Nobody is here\"\n\n await ctx.send(msg)\n await cursor.close()\n\n\n@bot.command()\nasync def what(ctx):\n \"\"\"Help message\"\"\"\n await ctx.send(\"\"\"\n Help:\n\n !create [name] [discord_id]: Creates a new player.\n !add [name]: Adds a teamkill to their tally.\n !check: Check the scoreboard.\n !rename [name] [new_name]: Mistyped their name? Fix your ways here.\n !set [name] [score]: Sets the score.\n !remove [name]: Removes that player.\n !winner: Try it and see.\n\n Name and shame. NAME AND SHAME.\"\"\")\n\n\n# Suppress noise about console usage from errors\nyoutube_dl.utils.bug_reports_message = lambda: ''\n\nytdl_format_options = {\n 'format': 'bestaudio/best',\n 'outtmpl': '%(extractor)s-%(id)s-%(title)s.%(ext)s',\n 'restrictfilenames': True,\n 'noplaylist': True,\n 'nocheckcertificate': True,\n 'ignoreerrors': False,\n 'logtostderr': False,\n 'quiet': True,\n 'no_warnings': True,\n 'default_search': 'auto',\n\n # bind to ipv4 since ipv6 addresses cause issues sometimes\n 'source_address': '0.0.0.0'\n\n}\n\nffmpeg_options = {\n 'options': '-vn'\n}\n\nytdl = youtube_dl.YoutubeDL(ytdl_format_options)\n\n\nclass YTDLSource(discord.PCMVolumeTransformer):\n def __init__(self, source, *, data, volume=0.5):\n super().__init__(source, volume)\n\n self.data = data\n\n self.title = data.get('title')\n self.url = data.get('url')\n\n @classmethod\n async def from_url(cls, url, *, loop=None, stream=False):\n loop = loop or asyncio.get_event_loop()\n data = await loop.run_in_executor(None, lambda: ytdl.extract_info(url, download=not stream))\n\n if 'entries' in data:\n # take first item from a playlist\n data = data['entries'][0]\n\n filename = data['url'] if stream else ytdl.prepare_filename(data)\n return cls(discord.FFmpegPCMAudio(filename, **ffmpeg_options), data=data)\n\n\nclass Music(commands.Cog):\n def __init__(self, bot):\n self.bot = bot\n\n @commands.command()\n async def join(self, ctx, *, channel: discord.VoiceChannel):\n \"\"\"Joins a voice channel\"\"\"\n\n if ctx.voice_client is not None:\n return await ctx.voice_client.move_to(channel)\n\n await channel.connect()\n\n # @commands.command()\n # async def play(self, ctx, *, query):\n # \"\"\"Plays a file from the local filesystem\"\"\"\n #\n # source = discord.PCMVolumeTransformer(discord.FFmpegPCMAudio(query))\n # ctx.voice_client.play(source, after=lambda e: print('Player error: %s' % e) if e else None)\n #\n # await ctx.send('Now playing: {}'.format(query))\n\n @commands.command()\n async def yt(self, ctx, *, url):\n \"\"\"Plays from a url (almost anything youtube_dl supports)\"\"\"\n\n async with ctx.typing():\n player = await YTDLSource.from_url(url, loop=self.bot.loop)\n ctx.voice_client.play(player, after=lambda e: print(\n 'Player error: %s' % e) if e else None)\n\n await ctx.send('Now playing: {}'.format(player.title))\n\n @commands.command()\n async def play(self, ctx, *, url):\n \"\"\"Streams from a url (same as yt, but doesn't predownload)\"\"\"\n\n async with ctx.typing():\n player = await YTDLSource.from_url(url, loop=self.bot.loop, stream=True)\n ctx.voice_client.play(player, after=lambda e: print(\n 'Player error: %s' % e) if e else None)\n\n await ctx.send('Now playing: {}'.format(player.title))\n\n @commands.command()\n async def stimpy(self, ctx, *, url=\"\"):\n \"\"\"Streams from a url (same as yt, but doesn't predownload)\"\"\"\n url = \"https://youtu.be/IZui2PYfTSk\"\n async with ctx.typing():\n player = await YTDLSource.from_url(url, loop=self.bot.loop, stream=True)\n ctx.voice_client.play(player, after=lambda e: print(\n 'Player error: %s' % e) if e else None)\n\n await ctx.send('Now playing: {}'.format(player.title))\n\n @commands.command()\n async def volume(self, ctx, volume: int):\n \"\"\"Changes the player's volume\"\"\"\n\n if ctx.voice_client is None:\n return await ctx.send(\"Not connected to a voice channel.\")\n\n ctx.voice_client.source.volume = volume / 100\n await ctx.send(\"Changed volume to {}%\".format(volume))\n\n @commands.command()\n async def stop(self, ctx):\n \"\"\"Stops and disconnects the bot from voice\"\"\"\n\n await ctx.voice_client.disconnect()\n\n @play.before_invoke\n @stimpy.before_invoke\n @yt.before_invoke\n async def ensure_voice(self, ctx):\n if ctx.voice_client is None:\n if ctx.author.voice:\n await ctx.author.voice.channel.connect()\n else:\n await ctx.send(\"You are not connected to a voice channel.\")\n\n raise commands.CommandError(\n \"Author not connected to a voice channel.\")\n\n elif ctx.voice_client.is_playing():\n ctx.voice_client.stop()\n\n\nbot.add_cog(Music(bot))\n\nbot.run(os.getenv('BOT_TOKEN'))\n","repo_name":"prawn185/TarkovTK","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":14554,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"60"} +{"seq_id":"28615514006","text":"#!/usr/bin/python\nimport os\nimport subprocess\nimport argparse\nimport sys\n\nparser = argparse.ArgumentParser()\nparser.add_argument('port_number', type=int)\nargs = parser.parse_args()\n\nc = ['lsof','-n',f'-i4TCP:{args.port_number}']\ntry:\n p = subprocess.run(c, check=True, stdout=subprocess.PIPE).stdout\nexcept subprocess.CalledProcessError:\n print(f'No program listening on {args.port_number}')\n sys.exit(1)\npid = int(bytes.decode(p).split()[10])\nos.kill(pid,9)\n","repo_name":"mattiascockburn/learn","sub_path":"python/p.py","file_name":"p.py","file_ext":"py","file_size_in_byte":468,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"60"} +{"seq_id":"12633368659","text":"\"\"\"SonarQube violations collector.\"\"\"\n\nfrom shared_data_model import DATA_MODEL\n\nfrom collector_utilities.type import URL\nfrom model import Entities, Entity, SourceMeasurement, SourceResponses\n\nfrom .base import SonarQubeCollector\n\n\nclass SonarQubeViolations(SonarQubeCollector):\n \"\"\"SonarQube violations metric. Also base class for metrics that measure specific rules.\"\"\"\n\n rules_configuration = \"\" # Subclass responsibility\n types_parameter = \"types\"\n\n async def _landing_url(self, responses: SourceResponses) -> URL:\n \"\"\"Extend to add the issues path and parameters.\"\"\"\n url = await super()._landing_url(responses)\n component = self._parameter(\"component\")\n branch = self._parameter(\"branch\")\n landing_url = f\"{url}/project/issues?id={component}&branch={branch}&resolved=false\"\n return URL(\n landing_url\n + self._query_parameter(\"severities\")\n + self._query_parameter(self.types_parameter)\n + self.__rules_url_parameter(),\n )\n\n async def _api_url(self) -> URL:\n \"\"\"Extend to add the issue search path and parameters.\"\"\"\n url = await super()._api_url()\n component = self._parameter(\"component\")\n branch = self._parameter(\"branch\")\n # If there's more than 500 issues only the first 500 are returned. This is no problem since we limit\n # the number of \"entities\" sent to the server anyway (that limit is 100 currently).\n api = f\"{url}/api/issues/search?componentKeys={component}&branch={branch}&resolved=false&ps=500\"\n return URL(\n api\n + self._query_parameter(\"severities\")\n + self._query_parameter(self.types_parameter)\n + self.__rules_url_parameter(),\n )\n\n def _query_parameter(self, parameter_key: str) -> str:\n \"\"\"Return the multiple choice parameter as query parameter that can be passed to SonarQube.\"\"\"\n values = \",\".join(value.upper() for value in sorted(self._parameter(parameter_key)))\n return \"\" if values == self.__default_value(parameter_key) else f\"&{parameter_key}={values}\"\n\n def __rules_url_parameter(self) -> str:\n \"\"\"Return the rules url parameter, if any.\"\"\"\n rules = (\n DATA_MODEL.sources[self.source_type].configuration[self.rules_configuration].value\n if self.rules_configuration\n else []\n )\n return f\"&rules={','.join(rules)}\" if rules else \"\"\n\n async def _parse_source_responses(self, responses: SourceResponses) -> SourceMeasurement:\n \"\"\"Override to parse the issues.\"\"\"\n value = 0\n entities = Entities()\n for response in responses:\n json = await response.json()\n value += int(json.get(\"total\", 0))\n entities.extend([await self._entity(issue) for issue in json.get(\"issues\", [])])\n return SourceMeasurement(value=str(value), entities=entities)\n\n async def __issue_landing_url(self, issue_key: str) -> URL:\n \"\"\"Generate a landing url for the issue.\"\"\"\n url = await super()._landing_url(SourceResponses())\n component = self._parameter(\"component\")\n branch = self._parameter(\"branch\")\n return URL(f\"{url}/project/issues?id={component}&branch={branch}&issues={issue_key}&open={issue_key}\")\n\n async def _entity(self, issue) -> Entity:\n \"\"\"Create an entity from an issue.\"\"\"\n return Entity(\n key=issue[\"key\"],\n url=await self.__issue_landing_url(issue[\"key\"]),\n message=issue[\"message\"],\n severity=issue.get(\"severity\", \"no severity\").lower(),\n type=issue[\"type\"].lower(),\n component=issue[\"component\"],\n creation_date=issue[\"creationDate\"],\n update_date=issue[\"updateDate\"],\n )\n\n def __default_value(self, parameter_key: str) -> str:\n \"\"\"Return the default value for the parameter.\"\"\"\n defaults = DATA_MODEL.sources[self.source_type].parameters[parameter_key].values or []\n return \",\".join(value.upper() for value in sorted(defaults))\n\n\nclass SonarQubeViolationsWithPercentageScale(SonarQubeViolations):\n \"\"\"SonarQube violations collectors that support the percentage scale.\"\"\"\n\n total_metric = \"\" # Subclass responsibility\n\n async def _get_source_responses(self, *urls: URL) -> SourceResponses:\n \"\"\"Extend to, next to the violations, get the total number of violations as basis for the percentage scale.\"\"\"\n component = self._parameter(\"component\")\n branch = self._parameter(\"branch\")\n base_api_url = await SonarQubeCollector._api_url(self) # noqa: SLF001\n total_metric_api_url = URL(\n f\"{base_api_url}/api/measures/component?component={component}&branch={branch}\"\n f\"&metricKeys={self.total_metric}\",\n )\n return await super()._get_source_responses(*([*urls, total_metric_api_url]))\n\n async def _parse_source_responses(self, responses: SourceResponses) -> SourceMeasurement:\n \"\"\"Extend to parse the total number of violations.\"\"\"\n measurement = await super()._parse_source_responses(responses)\n measures: list[dict[str, str]] = []\n for response in responses:\n measures.extend((await response.json()).get(\"component\", {}).get(\"measures\", []))\n # Note that the SonarQube api sometimes omits values (when they are 0) from the component measurement endpoint\n # This has not (yet) been observed for the 'functions' metric and current code would iterate over an empty list\n measurement.total = str(sum(int(measure[\"value\"]) for measure in measures))\n return measurement\n","repo_name":"ICTU/quality-time","sub_path":"components/collector/src/source_collectors/sonarqube/violations.py","file_name":"violations.py","file_ext":"py","file_size_in_byte":5688,"program_lang":"python","lang":"en","doc_type":"code","stars":42,"dataset":"github-code","pt":"60"} +{"seq_id":"6663957372","text":"import pandas as pd\r\nimport numpy as np\r\nimport random\r\nimport os\r\nos.chdir(r\"C:\\Users\\tyler\\shippingRIE\")\r\n\r\norder_ids_needed = 10\r\n\r\n#first we need to build out some dummy orders\r\norder_ids = np.arange(0,order_ids_needed,1)\r\nline_numbers = np.arange(1,100,1)\r\npartids = ['a','b','c','d','e','f','g']\r\n\r\n#Random Date Generator\r\nend_date = pd.Timestamp.today() # Current date\r\ndate_offsets = np.random.randint(0,360,order_ids_needed).tolist()\r\ndue_dates = []\r\nfor date in date_offsets:\r\n due_dates.append(end_date - pd.DateOffset(days=date) )\r\n\r\ndf = pd.DataFrame({'order_id':order_ids,\r\n 'due_date':due_dates,\r\n 'lines' : np.random.randint(1,10,order_ids_needed)})\r\n\r\n\r\nline_objects = []\r\n\r\n\r\nfor index, row in df.iterrows():\r\n so_id = row['order_id']\r\n due_date = row['due_date']\r\n line_count = row['lines']\r\n for line in range(1, line_count + 1):\r\n so_line_detail = {\r\n 'order_id': f'SO-0000{so_id}',\r\n 'due_date': due_date,\r\n 'line_no': line,\r\n 'part_id': np.random.choice(partids),\r\n 'qty': np.random.randint(1, 15, 1)[0], # Get the actual integer value\r\n 'identifier': f'SO-0000{so_id}/{line}'\r\n }\r\n line_objects.append(so_line_detail)\r\n\r\n\r\ntest = pd.DataFrame(line_objects)\r\ntest.to_csv('excelSources/open_orders.csv')\r\n\r\n#Build the fake inventory data\r\ninventory = {}\r\nfor part in partids:\r\n count = random.randint(1,10)\r\n for item in range(0,count):\r\n serial = f'abcde{part}{count}{item}'\r\n inventory[serial] = (part, count, item, 1, serial)\r\n\r\npd.DataFrame(inventory\r\n , index =['part_id','total_count','item','qty','serial']).T.to_csv('excelSources/inventory_listing.csv'\r\n ,index=False)\r\n\r\n\r\n \r\n\r\n\r\n\r\n","repo_name":"tylerwhitlock50/ShippingRIE","sub_path":"dummy_data_generator.py","file_name":"dummy_data_generator.py","file_ext":"py","file_size_in_byte":1807,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"60"} +{"seq_id":"28600953035","text":"from dotenv import load_dotenv\nfrom utils.settings import Settings\nfrom audio.train_lstm_model import train_audio_lstm, train_audio_lstm_cv\nfrom audio.train_traditional_model import train_audio_traditional_model, train_audio_traditional_model_cv\n\nif __name__ == '__main__':\n # set the environment variables\n load_dotenv()\n\n # set the parameter for audio data\n settings = Settings()\n settings.set_audio()\n\n # type of process file\n data_type = \"audio_mfcc_100ms_50ms\" # \"audio_mfcc_20ms_10ms\"\n\n # train one sample\n test_size = 0.3\n train_audio_traditional_model(data_type=data_type, test_size=test_size)\n train_audio_lstm(data_type=data_type, settings=settings, test_size=test_size, number_model_to_trained=1)\n\n # using cross validation\n cv_n = 5\n train_audio_traditional_model_cv(data_type=data_type, cv_n=cv_n, presaved_index=False, save_index=True)\n train_audio_lstm_cv(data_type=data_type, settings=settings, cv_n=cv_n, number_model_to_trained=20,\n presaved_index=True,\n save_index=False)\n","repo_name":"jinchen1036/PME4-Emotion-Recognition","sub_path":"audio/audio_main.py","file_name":"audio_main.py","file_ext":"py","file_size_in_byte":1083,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"60"} +{"seq_id":"27766326893","text":"import cffi\nimport numpy as np\n\nffi = cffi.FFI()\nffi.cdef(\"\"\"\ntypedef struct { float kappa_X, kappa_Y, sigma_X, sigma_Y, invepsilon; } params_t;\n\"\"\")\nfor d in ['ou', 'doublewell']:\n ffi.cdef(\"\"\"\n void sde_eigen_{}(params_t *params,\n unsigned long omega_X, unsigned long omega_Y,\n\t float h, unsigned long N, float t0,\n\t unsigned long dimX, unsigned long dimY,\n\t float *x0_p, float *y0_p,\n\t float *X_p, float *Y_p);\n \"\"\".format(d))\n\nC = ffi.dlopen('sde_eigen.dylib')\n\ndef sde(params, omega_X, omega_Y, h, t0, x0, y0, X, Y):\n x0 = np.ascontiguousarray(x0, dtype=np.float32)\n y0 = np.ascontiguousarray(y0, dtype=np.float32)\n X = np.ascontiguousarray(X, dtype=np.float32)\n Y = np.ascontiguousarray(Y, dtype=np.float32)\n params_p = ffi.new(\"params_t *\")\n for a in dir(params_p):\n setattr(params_p, a, params[a])\n x0_ptr = ffi.cast(\"float *\", ffi.from_buffer(x0))\n y0_ptr = ffi.cast(\"float *\", ffi.from_buffer(y0))\n X_ptr = ffi.cast(\"float *\", ffi.from_buffer(X))\n Y_ptr = ffi.cast(\"float *\", ffi.from_buffer(Y))\n dimX = x0.shape[0]\n dimY = y0.shape[0]\n N = X.shape[0]\n fn = getattr(C, 'sde_eigen_{}'.format(params['dynamics']))\n fn(params_p, omega_X, omega_Y, h, N, t0, dimX, dimY,\n x0_ptr, y0_ptr, X_ptr, Y_ptr)\n","repo_name":"bobpepin/SDE-Coupling","sub_path":"src/sde_eigen.py","file_name":"sde_eigen.py","file_ext":"py","file_size_in_byte":1321,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"60"} +{"seq_id":"40024468507","text":"import collections\nfrom typing import List\n\n\nclass DetectSquares:\n\n def __init__(self):\n # 统计点的个数\n self.counter = collections.Counter()\n # 记录 x 对应的 y\n self.xs = collections.defaultdict(set)\n\n def add(self, point: List[int]) -> None:\n # 点的个数加 1\n self.counter[tuple(point)] += 1\n # 记录 x 和 y 关系\n self.xs[point[0]].add(point[1])\n\n def count(self, point: List[int]) -> int:\n res = 0\n x, y = point\n for a in self.xs[x]:\n if y == a:\n continue\n side = abs(a - y)\n res += self.counter[(x, a)] * self.counter[(x + side, y)] * self.counter[(x + side, a)]\n res += self.counter[(x, a)] * self.counter[(x - side, y)] * self.counter[(x - side, a)]\n return res\n\n# Your DetectSquares object will be instantiated and called as such:\n# obj = DetectSquares()\n# obj.add(point)\n# param_2 = obj.count(point)\n","repo_name":"yqkcn/leetcode","sub_path":"detect-squares.py","file_name":"detect-squares.py","file_ext":"py","file_size_in_byte":979,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"60"} +{"seq_id":"15605858931","text":"from __future__ import division\nimport numpy as np\nimport difeq\nimport h5py as h5\nimport pylab as plt\nimport main\n\n#simulation parameters----------------------------------------------------------------------------\nL = 100 #mesh size per dimension in Mpc/h\nn = 100 #number of particles per dimension\nN = 100 #number of steps for evolution of a\naf = 1 #final a (today)\nMpcphtokm = 4.081e19 #unit converters\n\n##initial condition parameters--------------------------------------------------------------------\na0 = 0.02 #scale factor for an initial redshift of 49\nD0 = 0.0256745 #linear growth function at redshift 49\n\ndata = open(\"linearpower_Box1000.dat\", \"r\")\n\narr = []\nfor line in data:\n values = line.split()\n row = [float(x) for x in values]\n arr.append(row)\ndata.close()\n\nP = np.array(arr)\nP = np.concatenate(([[0,0]],P))\nP[:,1] = P[:,1]*D0**2\n\nSx,Sy,Sz = main.init(P,n,L)\n\nx = np.zeros((n,n,n,3))\nZ = np.zeros((n,n,n,3))\nfor k in range(n):\n for j in range(n):\n for i in range(n):\n x[i,j,k] = np.array([i*L/n,j*L/n,k*L/n])\n Z[i,j,k] = np.array([i*L/n,j*L/n,k*L/n])\n\nx[:,:,:,0] = x[:,:,:,0] + D0*Sx\nx[:,:,:,1] = x[:,:,:,1] + D0*Sy\nx[:,:,:,2] = x[:,:,:,2] + D0*Sz\n\nZ[:,:,:,0] = Z[:,:,:,0] + Sx\nZ[:,:,:,1] = Z[:,:,:,1] + Sy\nZ[:,:,:,2] = Z[:,:,:,2] + Sz\n\n\nv = np.zeros((n,n,n,3))\nv[:,:,:,0] = D0*Sx*Mpcphtokm/a0\nv[:,:,:,1] = D0*Sy*Mpcphtokm/a0\nv[:,:,:,2] = D0*Sz*Mpcphtokm/a0\n\nX = []\nV = []\nZel = []\n\nfor k in range(n):\n for j in range(n):\n for i in range(n):\n X.append(x[i,j,k])\n V.append(v[i,j,k])\n Zel.append(Z[i,j,k])\n\nX = np.array(X)%L\n\nV = np.array(V)\n\nZel = np.array(Zel)%L\n\nr0 = np.concatenate((X,V),axis=1)\n\ndef func(r,a):\n return main.f(r,a,L)\n\nA,R = difeq.rk4(func,r0,a0,af,N)\n\nIC = h5.File(\"initcon.dat\", \"w\")\nresults = h5.File(\"results.dat\", \"w\")\nZeldovich = h5.File(\"Zeldovich.dat\", \"w\")\n\niset = IC.create_dataset(\"array\", R[0][:,0:3].shape, dtype=np.float)\niset[...] = R[0][:,0:3]\ndset = results.create_dataset(\"array\", R[-1][:,0:3].shape, dtype=np.float)\ndset[...] = R[-1][:,0:3]%L\npset = Zeldovich.create_dataset(\"array\", Zel.shape, dtype=np.float)\npset[...] = Zel\n\nIC.close()\nresults.close()\nZeldovich.close()\n","repo_name":"nyu-compphys-2016/project-mghimire","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":2416,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"60"} +{"seq_id":"26197763527","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[381]:\n\nimport numpy\nclass Polynomial:\n def __init__(self,coefficients):\n self.coefficients = coefficients\n @staticmethod\n def from_string(str):\n str = str.replace(\" \",\"\")\n str = str.replace(\"+\", \" \")\n str = str.replace(\"-\",\" -\")\n raw = str.split(\" \")\n raw = [x for x in raw if x != '']\n i=0\n while i=0:\n raw[i] += \"^1\"\n else:\n raw[i] +=\"*x^0\"\n i = i+1\n orders = []\n i=0\n while i0:\n if coeffs[j] == 0:\n coeffs = numpy.delete(coeffs,j)\n j = len(coeffs)-1\n else:\n break\n return Polynomial(coeffs)\n def __sub__(self,other):\n coeffs = numpy.zeros(max(len(self.coefficients),len(other.coefficients))+1,dtype=int)\n i = 0\n while i0:\n if coeffs[j] == 0:\n coeffs = numpy.delete(coeffs,j)\n j = len(coeffs)-1\n else:\n break\n return Polynomial(coeffs)\n def __mul__(self,other):\n coeffs = numpy.zeros(len(self.coefficients)+len(other.coefficients)+1,dtype=int)\n i=0\n j=0\n while i0:\n if coeffs[j] == 0:\n coeffs = numpy.delete(coeffs,j)\n j = len(coeffs)-1\n else:\n break \n return Polynomial(coeffs)\n def __truediv__(self,other):\n return RationalPolynomial(self,other)\n\nimport sympy\n\nclass RationalPolynomial:\n def __init__(self,numerator, denominator):\n self.numerator = numerator\n self.denominator = denominator\n self._reduce(self)\n @staticmethod\n def _reduce(self):\n n = sympy.sympify(repr(self.numerator))\n d = sympy.sympify(repr(self.denominator))\n gcd = sympy.gcd(n,d)\n gcds = repr(gcd).replace(\"**\",\"^\")\n gcd_c = numpy.flip(Polynomial.from_string(gcds).coefficients)\n n_c = numpy.flip(self.numerator.coefficients)\n d_c = numpy.flip(self.denominator.coefficients)\n [n_f,r1] = numpy.polydiv(n_c,gcd_c)\n [d_f,r2] = numpy.polydiv(d_c,gcd_c)\n self.numerator = Polynomial(numpy.flip(n_f))\n self.denominator = Polynomial(numpy.flip(d_f))\n def from_string(str):\n n = str.split(\"/\")[0]\n d = str.split(\"/\")[1]\n return RationalPolynomial(Polynomial.from_string(n[1:-1]),Polynomial.from_string(d[1:-1]))\n def __repr__(self):\n return \"(\"+repr(self.numerator)+\")\" + \"/\" + \"(\"+repr(self.denominator)+\")\"\n def __add__(self,other):\n return RationalPolynomial(self.numerator*other.denominator+other.numerator*self.denominator,self.denominator*other.denominator)\n def __sub__(self,other):\n return RationalPolynomial(self.numerator*other.denominator-other.numerator*self.denominator,self.denominator*other.denominator)\n def __mul__(self,other):\n return RationalPolynomial(self.numerator*other.numerator,self.denominator*other.denominator)\n def __truediv__(self,other):\n return RationalPolynomial(self.numerator*other.denominator,self.denominator*other.numerator)\n def __eq__(self,other):\n return (self.numerator * other.denominator) == (self.denominator * other.numerator)\n\n\n# In[ ]:\n\n\n\n\n","repo_name":"HalcyonAQ/ESAM446_AlecQ","sub_path":"polynomial.py","file_name":"polynomial.py","file_ext":"py","file_size_in_byte":7080,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"60"} +{"seq_id":"619573034","text":"import sys\n\nsys.path.append(\"src\")\n\nimport bot_namer\nimport goofspiel\n\n\nconfig = goofspiel.GameConfig(\n deck=[c for c in range(1, 8)],\n namer=bot_namer.AliceBenjamin(),\n logger=goofspiel.GoofLogger(log_types=[\"RESULTS\", \"GUTS\"]),\n)\nevo_config = goofspiel.EvoConfig(\n multiplicity=0,\n width=4,\n new_bots=2,\n survival_rate=2,\n generations=3,\n mutation_degree=0.2,\n)\ngoofspiel.play_until_dead(n_bots=1, config=config, evo_config=evo_config)\n","repo_name":"gaffney2010/goofspiel-python","sub_path":"scripts/play_2p.py","file_name":"play_2p.py","file_ext":"py","file_size_in_byte":465,"program_lang":"python","lang":"de","doc_type":"code","stars":0,"dataset":"github-code","pt":"60"} +{"seq_id":"38169963680","text":"# https://adventofcode.com/2020/day/15\n\ndef compute(content, iter_count):\n predata = [ int(num) for num in content[:-1].split(',') ]\n last = predata[-1]\n data = { int(num): index for index, num in enumerate(predata) }\n\n for turn in range(len(data), iter_count):\n if last in data:\n old_last = data[last]\n data[last] = turn - 1\n last = turn - old_last - 1\n else:\n data[last] = turn - 1\n last = 0\n\n return last\n\ndef part_1(content):\n return compute(content[:], 2020)\n\ndef part_2(content):\n return compute(content[:], 30000000)\n\nwith open('input.txt', 'r') as file:\n content = file.read()\n\n # Part one\n print(part_1(content))\n\n # Part two\n print(part_2(content))\n","repo_name":"MetGang/Advent-of-Code","sub_path":"2020/15/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":764,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"60"} +{"seq_id":"16073937770","text":"\"\"\"add column entry_id\n\nRevision ID: 48f561c0ce6\nRevises:\nCreate Date: 2015-02-18 21:17:19.346998\n\n\"\"\"\n\n# revision identifiers, used by Alembic.\nrevision = '48f561c0ce6'\ndown_revision = None\nbranch_labels = None\ndepends_on = None\n\nimport conf\nfrom alembic import op\nimport sqlalchemy as sa\n\n\ndef upgrade():\n op.add_column('article', sa.Column('entry_id', sa.String(), nullable=True))\n\n\ndef downgrade():\n if 'sqlite' not in conf.SQLALCHEMY_DATABASE_URI:\n op.drop_column('article', 'entry_id')\n","repo_name":"mdheller/newspipe","sub_path":"migrations/versions/48f561c0ce6_add_column_entry_id.py","file_name":"48f561c0ce6_add_column_entry_id.py","file_ext":"py","file_size_in_byte":505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"60"} +{"seq_id":"5085723546","text":"import sys\n\nif __name__ == \"__main__\":\n N, d, k, c = map(int, sys.stdin.readline().split())\n sushi = [int(input()) for _ in range(N)]\n # 원형으로 연결된 경우이므로 앞부분의 k-1개 만큼의 초밥을 뒤에 추가해준다.\n sushi += sushi[:k-1]\n\n answer = 0\n for i in range(N):\n my_sushi = set(sushi[i:i+k])\n my_sushi.add(c)\n answer = max(answer, len(my_sushi))\n\n print(answer)\n\n\n","repo_name":"deok2kim/algorithm","sub_path":"백준/기타/2531. 회전 초밥.py","file_name":"2531. 회전 초밥.py","file_ext":"py","file_size_in_byte":439,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"60"} +{"seq_id":"38235408619","text":"import smbus\nimport time\n\n# Define I2C bus number and device address\nbus_number = 1\ndevice_address = 0x68\n\n# Define register addresses for BN055\nreg_acc = 0x3B\nreg_gyro = 0x43\nreg_mag = 0x03\n\n# Initialize I2C bus\nbus = smbus.SMBus(bus_number)\n\n# Enable accelerometer and gyroscope\nbus.write_byte_data(device_address, 0x6B, 0b00000000)\n\nwhile True:\n\n # Read gyroscope data\n gyro_x = bus.read_word_data(device_address, reg_gyro)\n gyro_y = bus.read_word_data(device_address, reg_gyro + 2)\n gyro_z = bus.read_word_data(device_address, reg_gyro + 4)\n\n\n gyro_x = -(gyro_x & 0xFFFF ^ 0xFFFF) if gyro_x & 0x8000 else gyro_x\n gyro_y = -(gyro_y & 0xFFFF ^ 0xFFFF) if gyro_y & 0x8000 else gyro_y\n gyro_z = -(gyro_z & 0xFFFF ^ 0xFFFF) if gyro_z & 0x8000 else gyro_z\n\n # Print data\n print(\"Gyroscope (deg/s): x = %.2f, y = %.2f, z = %.2f\" % (gyro_x / 131.0, gyro_y / 131.0, gyro_z / 131.0))\n","repo_name":"TJREVERB/balloon-pfs","sub_path":"imu.py","file_name":"imu.py","file_ext":"py","file_size_in_byte":905,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"60"} +{"seq_id":"35778357397","text":"\"\"\"\n***************************************************\nFilename: Life hack #2, problem1.py\nDescription: if statements for radar problem1\nAuthor: Lee.M\nDate: 23/02/2021\n***************************************************\n\"\"\"\n# get variables\nspeed = int(input(\"Enter a speed as an integer\"))\n\n# compute fines\nfine_1 = 100\nfine_2 = 270\nfine_3 = 570\n\n# setting the fines\nif speed > 0 or speed < 21:\n print (\"You are speeding and your fine is $\" + str(fine_1))\nelse:\n print (\"Congratulations, you are within the speed limit!\")\n\nif speed > 20 or speed < 31:\n print (\"You are speeding and your fine is $\" + str(fine_2))\nelse: \n print (\"Congratulations, you are within the speed limit!\")\n\nif speed > 31:\n print (\"You are speeding and your fine is $\" + str(fine_3))\nelse:\n print (\"Congratulations, you are within the speed limit!\")\n\n\n\n","repo_name":"SACHSTech/ics2o1-livehack-2-Leem5800","sub_path":"problem1.py","file_name":"problem1.py","file_ext":"py","file_size_in_byte":833,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"60"} +{"seq_id":"39377754773","text":"from directory.models import *\nfrom django.core import serializers\nfrom manual_matching.models import *\nimport logging, json\nfrom .get_manual_data import color_line\n\nlogger = logging.getLogger(__name__)\n\n\nclass Filter:\n\n def __init__(self, filter_matching):\n self.filter_matching = filter_matching\n\n def set_filter_matching(self, filter_matching):\n self.filter_matching = filter_matching\n\n def get_filter_matching(self):\n return self.filter_matching\n\n def business_logic(self, **fields):\n fm = self.get_filter_matching()\n result = fm.start(**fields)\n try:\n data = serializers.serialize('json', result)\n except AttributeError:\n data = result\n return data\n\n\nclass ManualFilter:\n\n def get_filter_fields(self, fields):\n filter_field = { # Данные поля будут присутствовать всегда\n 'sku_dict__pk': fields['sku_id'], # id SKU\n 'number_competitor': fields['number_competitor'], # id SKU справочника\n }\n\n # Какие поля пришли с форм фильтрации\n if fields['barcode']:\n filter_field['sku_dict__nnt'] = fields['barcode'] # Штриход\n if fields['manufacturer']:\n print(fields['manufacturer'])\n filter_field['eas_dict__manufacturer__icontains'] = fields['manufacturer'] # Производитель\n if fields['tn_fv']:\n filter_field['eas_dict__tn_fv__icontains'] = fields['tn_fv'] # Наименование номенклатуры\n return filter_field\n\n def get_manufacturer(self, **filter_field):\n \"\"\"выгрузка для выпадающего списка фильтра Производитель\"\"\"\n manufacturer = ManualMatchingData.objects.filter(**filter_field).values('eas_dict__manufacturer') \\\n .distinct('eas_dict__manufacturer')\n manufacturer = json.dumps(list(manufacturer))\n return manufacturer\n\n def get_barcode(self, **filter_field):\n \"\"\"выгрузка для выпадающего списка фильтра Штрихкод\"\"\"\n barcode = ManualMatchingData.objects.filter(**filter_field).values('sku_dict__nnt').distinct('sku_dict__nnt')\n barcode = json.dumps(list(barcode))\n return barcode\n\n def get_eas(self, **filter_field):\n \"\"\"выгрузка вариантов мэтчинга\"\"\"\n eas = ManualMatchingData.objects.filter(**filter_field).values('eas_dict', 'name_eas')\n eas = color_line(eas, 'name_eas')\n eas = json.dumps(list(eas))\n return eas\n\n def start(self, **fields):\n logger.debug(fields)\n filter_field = self.get_filter_fields(fields) # Подгон полей для поиска по модели\n eas = self.get_eas(**filter_field) # выгрузка вариантов мэтчинга\n\n if fields['manufacturer']:\n manufacturer = self.get_manufacturer(**filter_field) # Выгрузка для выпадающего списка в фильтре\n # производитель\n else:\n manufacturer = None\n if fields['barcode']:\n barcode = self.get_barcode(**filter_field) # Выгрузка для выпадающего списка в фильтре штрихкод\n else:\n barcode = None\n result = {'eas': eas, \"manufacturer\": manufacturer, 'barcode': barcode}\n\n return result\n\n\nclass SKUFilter:\n\n def start(self, **fields):\n sku = ManualMatchingData.objects.filter(**fields).distinct('sku_dict__pk').values(\n 'sku_dict',\n 'name_sku',\n 'sku_dict__number_competitor__pk',\n 'sku_dict__number_competitor__name',\n )\n sku = color_line(sku, 'name_sku')\n sku = json.dumps(list(sku))\n result = {'sku': sku}\n return result\n\n\nif __name__ == '__main__':\n filter_match = Filter(FilterManufacturer())\n res = filter_match.business_logic(\n sku_id=666,\n number_competitor=2,\n eas_dict__manufacturer='burugaga',\n eas_dict__tn_fv='zelenka'\n )\n print(res)\n","repo_name":"mnmyasis/fedor_app","sub_path":"fedor/manual_matching/services/filters.py","file_name":"filters.py","file_ext":"py","file_size_in_byte":4237,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"60"} +{"seq_id":"1248831282","text":"#!/usr/bin/env python3\n\nfrom pathlib import Path\nfrom sys import path, argv, exit\nfrom glob import glob\nfrom os import _exit\nfrom os.path import isfile\nfrom traceback import format_exc\nfrom json import loads\nfrom subprocess import run\n\npath.extend((f\"{Path.cwd()}/utils\", f\"{Path.cwd()}/tests\"))\n\nfrom DockerTest import DockerTest\nfrom AutoconfTest import AutoconfTest\nfrom SwarmTest import SwarmTest\nfrom KubernetesTest import KubernetesTest\nfrom LinuxTest import LinuxTest\nfrom logger import log\n\nif len(argv) <= 1:\n log(\"TESTS\", \"❌\", \"Missing type argument\")\n exit(1)\n\ntest_type = argv[1]\nif test_type not in (\"linux\", \"docker\", \"autoconf\", \"swarm\", \"kubernetes\", \"ansible\"):\n log(\"TESTS\", \"❌\", \"Wrong type argument \" + test_type)\n exit(1)\n\nrun(\"docker system prune\", shell=True)\n\nlog(\"TESTS\", \"ℹ️\", \"Starting tests for \" + test_type + \" ...\")\nret = False\nend_fun = None\nif test_type == \"docker\":\n ret = DockerTest.init()\n end_fun = DockerTest.end\nelif test_type == \"autoconf\":\n ret = AutoconfTest.init()\n end_fun = AutoconfTest.end\nelif test_type == \"swarm\":\n ret = SwarmTest.init()\n end_fun = SwarmTest.end\nelif test_type == \"kubernetes\":\n ret = KubernetesTest.init()\n end_fun = KubernetesTest.end\nelif test_type == \"linux\":\n distro = argv[2]\n ret = LinuxTest.init(distro)\n end_fun = LinuxTest.end\nif not ret:\n log(\"TESTS\", \"❌\", \"Test.init() failed\")\n exit(1)\n\nfor example in glob(\"./examples/*\"):\n if isfile(f\"{example}/tests.json\"):\n try:\n with open(f\"{example}/tests.json\") as f:\n tests = loads(f.read())\n if test_type not in tests[\"kinds\"]:\n log(\n \"TESTS\",\n \"ℹ️\",\n \"Skipping tests for \" + tests[\"name\"] + \" (not in kinds)\",\n )\n continue\n test_obj = None\n no_copy_container = False\n delay = 0\n if \"no_copy_container\" in tests:\n no_copy_container = tests[\"no_copy_container\"]\n if \"delay\" in tests:\n delay = tests[\"delay\"]\n if test_type == \"docker\":\n test_obj = DockerTest(\n tests[\"name\"],\n tests[\"timeout\"],\n tests[\"tests\"],\n no_copy_container=no_copy_container,\n delay=delay,\n )\n elif test_type == \"autoconf\":\n test_obj = AutoconfTest(\n tests[\"name\"],\n tests[\"timeout\"],\n tests[\"tests\"],\n no_copy_container=no_copy_container,\n delay=delay,\n )\n elif test_type == \"swarm\":\n test_obj = SwarmTest(tests[\"name\"], tests[\"timeout\"], tests[\"tests\"], delay=delay)\n elif test_type == \"kubernetes\":\n test_obj = KubernetesTest(tests[\"name\"], tests[\"timeout\"], tests[\"tests\"], delay=delay)\n elif test_type == \"linux\":\n test_obj = LinuxTest(tests[\"name\"], tests[\"timeout\"], tests[\"tests\"], distro)\n if not test_obj.run_tests():\n log(\"TESTS\", \"❌\", \"Tests failed for \" + tests[\"name\"])\n if test_type == \"linux\":\n ret = end_fun(distro)\n else:\n ret = end_fun()\n _exit(1)\n except:\n log(\n \"TESTS\",\n \"❌\",\n \"Exception while executing test for example \" + example + \" : \" + format_exc(),\n )\n if test_type == \"linux\":\n ret = end_fun(distro)\n else:\n ret = end_fun()\n exit(1)\n\nif test_type == \"linux\":\n ret = end_fun(distro)\nelse:\n ret = end_fun()\nif not ret:\n log(\"TESTS\", \"❌\", \"Test.end() failed\")\n exit(1)\n\nlog(\"TESTS\", \"ℹ️\", \"All tests finished for \" + test_type + \" !\")\n\nrun(\"docker system prune\", shell=True)\n","repo_name":"bunkerity/bunkerweb","sub_path":"tests/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4014,"program_lang":"python","lang":"en","doc_type":"code","stars":3185,"dataset":"github-code","pt":"60"} +{"seq_id":"31139003079","text":"def maxMin(k, arr):\n arr = sorted(arr)\n arr_len = len(arr)\n minn = 10**9+7\n\n for i in range(k-1, arr_len):\n if arr[i]-arr[i-k+1] < minn:\n minn = arr[i]-arr[i-k+1]\n\n return minn\n\nwith open('input.txt') as f:\n content = f.readlines()\n n = int(content[0])\n k = int(content[1])\n arr = []\n for i in range(2, n+2):\n arr.append(int(content[i]))\n\n\n print(maxMin(k, arr))","repo_name":"erjantj/hackerrank","sub_path":"min-max.py","file_name":"min-max.py","file_ext":"py","file_size_in_byte":420,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"60"} +{"seq_id":"30571157616","text":"import numpy as np\nimport torch\n\n\nclass DeepFool(object):\n def __init__(self, nb_candidate=10, overshoot=0.02, max_iter=50, clip_min=0.0, clip_max=1.0):\n self.nb_candidate = nb_candidate\n self.overshoot = overshoot\n self.max_iter = max_iter\n self.clip_min = clip_min\n self.clip_max = clip_max\n\n def attack(self, model, x):\n device = x.device\n\n with torch.no_grad():\n logits = model(x)\n self.nb_classes = logits.size(-1)\n assert self.nb_candidate <= self.nb_classes, 'nb_candidate should not be greater than nb_classes'\n\n # preds = logits.topk(self.nb_candidate)[0]\n # grads = torch.stack(jacobian(preds, x, self.nb_candidate), dim=1)\n # grads will be the shape [batch_size, nb_candidate, image_size]\n\n adv_x = x.clone().requires_grad_()\n\n iteration = 0\n logits = model(adv_x)\n current = logits.argmax(dim=1)\n if current.size() == ():\n current = torch.tensor([current])\n w = torch.squeeze(torch.zeros(x.size()[1:])).to(device)\n r_tot = torch.zeros(x.size()).to(device)\n original = current\n\n while ((current == original).any and iteration < self.max_iter):\n predictions_val = logits.topk(self.nb_candidate)[0]\n gradients = torch.stack(jacobian(predictions_val, adv_x, self.nb_candidate), dim=1)\n with torch.no_grad():\n for idx in range(x.size(0)):\n pert = float('inf')\n if current[idx] != original[idx]:\n continue\n for k in range(1, self.nb_candidate):\n w_k = gradients[idx, k, ...] - gradients[idx, 0, ...]\n f_k = predictions_val[idx, k] - predictions_val[idx, 0]\n pert_k = (f_k.abs() + 0.00001) / w_k.view(-1).norm()\n if pert_k < pert:\n pert = pert_k\n w = w_k\n\n r_i = pert * w / w.view(-1).norm()\n r_tot[idx, ...] = r_tot[idx, ...] + r_i\n\n adv_x = torch.clamp(r_tot + x, self.clip_min, self.clip_max).requires_grad_()\n logits = model(adv_x)\n current = logits.argmax(dim=1)\n if current.size() == ():\n current = torch.tensor([current])\n iteration = iteration + 1\n\n adv_x = torch.clamp((1 + self.overshoot) * r_tot + x, self.clip_min, self.clip_max)\n return adv_x\n\n\ndef jacobian(predictions, x, nb_classes):\n list_derivatives = []\n\n for class_ind in range(nb_classes):\n outputs = predictions[:, class_ind]\n derivatives, = torch.autograd.grad(outputs, x, grad_outputs=torch.ones_like(outputs), retain_graph=True)\n list_derivatives.append(derivatives)\n\n return list_derivatives\n","repo_name":"tobylyf/adv-attack","sub_path":"mydeepfool.py","file_name":"mydeepfool.py","file_ext":"py","file_size_in_byte":2874,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"60"} +{"seq_id":"1775993435","text":"#Frases de los tres chiflados\nquotes = {\n \"Moe\":\"Un tipo listo, eh?\",\n \"Larry\":\"Ow!\",\n \"Curly\":\"Nuyk nyuk!\",\n}\n\nchiflado1 = \"Larry\"\nchiflado2 = \"Curly\"\nprint(chiflado1,\"dice:\", quotes[chiflado1])\nprint(chiflado2,\"dice:\", quotes[chiflado2])","repo_name":"jaquiroz/IntroducingPython","sub_path":"Cap1/Ejemplos/Example-3.py","file_name":"Example-3.py","file_ext":"py","file_size_in_byte":248,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"60"} +{"seq_id":"29552876789","text":"class Solution(object):\n def findRadius(self, houses, heaters):\n \"\"\"\n :type houses: List[int]\n :type heaters: List[int]\n :rtype: int\n \"\"\"\n res = 0\n \n houses.sort()\n heaters.sort()\n i = 0\n \n for house in houses:\n while i < len(heaters) - 1 and abs(heaters[i + 1] - house) <= abs(heaters[i] - house):\n i += 1\n res = max(res, abs(heaters[i] - house))\n \n return res","repo_name":"P-ppc/leetcode","sub_path":"algorithms/Heaters/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":499,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"60"} +{"seq_id":"30703387097","text":"from django import forms\nfrom django.utils.formats import localize\nfrom django.utils.translation import gettext_lazy as _\nfrom django.forms.widgets import TextInput\n\nfrom polaris.models import Transaction, Asset\n\n\nclass CardNumberInput(TextInput):\n template_name = \"widgets/card_number.html\"\n\n\nclass CardExpirationInput(TextInput):\n template_name = \"widgets/card_expiration.html\"\n\n\nclass CardCvvInput(TextInput):\n template_name = \"widgets/card_cvv.html\"\n\n\nclass CreditCardField(forms.CharField):\n def __init__(self, placeholder=None, *args, **kwargs):\n super().__init__(\n # override default widget\n widget=CardNumberInput(attrs={\"placeholder\": placeholder}),\n *args,\n **kwargs,\n )\n\n default_error_messages = {\n \"invalid\": _(\"The credit card number is invalid\"),\n }\n\n @staticmethod\n def luhn_checksum(card_number):\n def digits_of(n):\n return [int(d) for d in str(n)]\n\n digits = digits_of(card_number)\n odd_digits = digits[-1::-2]\n even_digits = digits[-2::-2]\n checksum = 0\n checksum += sum(odd_digits)\n for ed in even_digits:\n checksum += sum(digits_of(ed * 2))\n return checksum % 10\n\n def is_luhn_valid(self, card_number):\n return self.luhn_checksum(card_number) == 0\n\n def clean(self, value):\n # ensure no spaces or dashes\n value = value.replace(\" \", \"\").replace(\"-\", \"\")\n if not (value.isdigit() and self.is_luhn_valid(value)):\n raise forms.ValidationError(self.error_messages[\"invalid\"])\n return value\n\n\nclass CreditCardForm(forms.Form):\n \"\"\"\n A generic form for collecting credit or debit card information.\n\n Ensures `card_number` is valid, but does not validate the `expiration` or\n `cvv`. Subclass this form for additional validation.\n \"\"\"\n\n name = forms.CharField(label=_(\"Name\"))\n card_number = CreditCardField(label=_(\"Card Number\"))\n expiration = forms.Field(widget=CardExpirationInput, label=_(\"Expiration\"))\n cvv = forms.Field(widget=CardCvvInput, label=_(\"CVV\"))\n\n\nclass TransactionForm(forms.Form):\n \"\"\"\n A base class for collecting transaction information. Developers must define\n subclasses to collect additional information and apply additional validation.\n\n This form assumes the amount collected is in units of a Stellar\n :class:`~polaris.models.Asset`. If the amount of an\n :class:`~polaris.models.OffChainAsset` must be collected, create a different\n form.\n\n Note that Polaris' base UI treats the amount field on this form and its\n subclasses differently than other forms. Specifically, Polaris automatically\n adds the asset's symbol to the input field, adds a placeholder value of 0,\n makes the fee table visible (by default), and uses the amount entered to update\n the fee table on each change.\n\n If you do not want the fee table to be displayed when this form class is\n rendered, set ``\"show_fee_table\"`` to ``False`` in the dict returned from\n :meth:`~polaris.integrations.DepositIntegration.content_for_template`.\n\n Fee calculation within the UI is done using the asset's fixed and percentage\n fee values saved to the database. If those values are not present, Polaris makes\n calls to the anchor's `/fee` endpoint and displays the response value to the\n user. If your `/fee` endpoint requires a `type` parameter, add a\n ``TransactionForm.type`` attribute to the form. Polaris will detect the\n attribute's presence on the form and include it in `/fee` requests.\n\n The :attr:`amount` field is validated with the :meth:`clean_amount` function,\n which ensures the amount is within the bounds for the asset type.\n \"\"\"\n\n def __init__(self, transaction: Transaction, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n self.transaction = transaction\n self.asset = transaction.asset\n self.decimal_places = self.asset.significant_decimals\n if transaction.kind == Transaction.KIND.deposit:\n self.min_amount = round(self.asset.deposit_min_amount, self.decimal_places)\n self.max_amount = round(self.asset.deposit_max_amount, self.decimal_places)\n self.min_default = (\n getattr(Asset, \"_meta\").get_field(\"deposit_min_amount\").default\n )\n self.max_default = (\n getattr(Asset, \"_meta\").get_field(\"deposit_max_amount\").default\n )\n else:\n self.min_amount = round(\n self.asset.withdrawal_min_amount, self.decimal_places\n )\n self.max_amount = round(\n self.asset.withdrawal_max_amount, self.decimal_places\n )\n self.min_default = (\n getattr(Asset, \"_meta\").get_field(\"withdrawal_min_amount\").default\n )\n self.max_default = (\n getattr(Asset, \"_meta\").get_field(\"withdrawal_max_amount\").default\n )\n\n # Re-initialize the 'amount' field now that we have all the parameters necessary\n self.fields[\"amount\"].__init__(\n widget=forms.TextInput(\n attrs={\n \"class\": \"polaris-transaction-form-amount\",\n \"inputmode\": \"decimal\",\n \"symbol\": self.asset.symbol,\n }\n ),\n min_value=self.min_amount,\n max_value=self.max_amount,\n decimal_places=self.decimal_places,\n label=_(\"Amount\"),\n localize=True,\n )\n\n limit_str = \"\"\n if self.min_amount > self.min_default and self.max_amount < self.max_default:\n limit_str = f\"({localize(self.min_amount)} - {localize(self.max_amount)})\"\n elif self.min_amount > self.min_default:\n limit_str = _(\"(minimum: %s)\") % localize(self.min_amount)\n elif self.max_amount < self.max_default:\n limit_str = _(\"(maximum: %s)\") % localize(self.max_amount)\n\n if limit_str:\n self.fields[\"amount\"].label += \" \" + limit_str\n\n amount = forms.DecimalField()\n\n def clean_amount(self):\n \"\"\"Validate the provided amount of an asset.\"\"\"\n amount = round(self.cleaned_data[\"amount\"], self.decimal_places)\n if amount < self.min_amount:\n raise forms.ValidationError(\n _(\"The minimum amount is: %s\")\n % localize(round(self.min_amount, self.decimal_places))\n )\n elif amount > self.max_amount:\n raise forms.ValidationError(\n _(\"The maximum amount is: %s\")\n % localize(round(self.max_amount, self.decimal_places))\n )\n return amount\n","repo_name":"stellar/django-polaris","sub_path":"polaris/integrations/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":6744,"program_lang":"python","lang":"en","doc_type":"code","stars":92,"dataset":"github-code","pt":"60"} +{"seq_id":"70284778750","text":"from . import db\nfrom sqlalchemy.sql import func\n\n\nclass Lesson(db.Model):\n __tablename__ = \"lesson\" #will change to \"lesson\"\n\n id = db.Column(db.Integer, primary_key=True)\n title = db.Column(db.String)\n rating = db.Column(db.String)\n description = db.Column(db.String)\n #professor= db.Column(db.String, db.ForeignKey(\"user.id\"), nullable=False)\n #professor = db.relationship(\"User\", backref=\"lesson\", lazy=True)\n discipline = db.Column(db.String)\n\n \n \n release_date = db.Column(db.DateTime)\n created_at = db.Column(db.DateTime, nullable=False, default=func.now())\n updated_at = db.Column(\n db.DateTime, nullable=False, default=func.now(), onupdate=func.now()\n )\n\n def __repr__(self):\n #return \"\" % self.id\n return \"\" % self.id\n","repo_name":"mauro-fernandes/chamada-rottenpotatoes","sub_path":"app/models/lesson.py","file_name":"lesson.py","file_ext":"py","file_size_in_byte":820,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"60"} +{"seq_id":"39450244962","text":"# Defining an engine in Wasmer is one of the fundamental steps.\n#\n# As a reminder, an engine applies roughly 2 steps:\n#\n# 1. It compiles the Wasm module bytes to executable code, through\n# the intervention of a compiler,\n# 2. It stores the executable code somewhere.\n#\n# This example focuses on the first step: the compiler. It\n# illustrates how the abstraction over the compiler is so powerful\n# that it is possible to cross-compile a Wasm module.\n#\n# You can run the example directly by executing in Wasmer root:\n#\n# ```shell\n# $ python examples/engine_cross_compilation.py\n# ```\n#\n# Ready?\n\nfrom wasmer import engine, target, wat2wasm, Store, Module\nfrom wasmer_compiler_cranelift import Compiler\n\n# Let's declare the Wasm module with the text representation.\nwasm_bytes = wat2wasm(\n \"\"\"\n (module\n (type $sum_t (func (param i32 i32) (result i32)))\n (func $sum_f (type $sum_t) (param $x i32) (param $y i32) (result i32)\n local.get $x\n local.get $y\n i32.add)\n (export \"sum\" (func $sum_f)))\n \"\"\"\n)\n\n# Here we go.\n#\n# Let's define the target “triple”. Historically, such things had\n# three fields, though additional fields have been added over time.\ntriple = target.Triple('x86_64-linux-musl')\n\n# Here we go again.\n#\n# Let's define a CPU feature.\ncpu_features = target.CpuFeatures()\ncpu_features.add('sse2')\n\n# Here we go finally.\n#\n# Let's build the target.\ntarget = target.Target(triple, cpu_features)\n\n# Define the engine that will drive everything.\n#\n# In this case, the engine is `wasmer.engine.Dylib` which means that\n# a native object is going to be generated.\n#\n# That's where we specify the target for the compiler.\n# Use the Dylib engine.\nengine = engine.Dylib(Compiler, target)\n\n# Create a store, that holds the engine.\nstore = Store(engine)\n\n# Let's compile the Wasm module.\nmodule = Module(store, wasm_bytes)\n\nassert isinstance(module, Module)\n\n# Congrats, the Wasm module is cross-compiled!\n#\n# What to do with that? It is possible to use an engine (probably a\n# headless engine) to execute the cross-compiled Wasm module an the\n# targeted platform.\n","repo_name":"wasmerio/wasmer-python","sub_path":"examples/engine_cross_compilation.py","file_name":"engine_cross_compilation.py","file_ext":"py","file_size_in_byte":2121,"program_lang":"python","lang":"en","doc_type":"code","stars":1888,"dataset":"github-code","pt":"60"} +{"seq_id":"601590458","text":"import subprocess\nimport sys\nfrom multiprocessing import Process\nimport os\n\ndef run_process():\n subprocess.run([\n \"dotnet\",\n \"build\",\n sys.argv[1] + \"/Heart.NET.Sdk/Heart.NET.Sdk.csproj\",\n ])\n \nif __name__ == '__main__':\n print(os.environ)\n p = Process(target=run_process)#, args=(sys.argv[1],))\n p.start()\n p.join()","repo_name":"TheApplePieGod/Heart","sub_path":"HeartScripting/scripts/build-dotnet.py","file_name":"build-dotnet.py","file_ext":"py","file_size_in_byte":358,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"60"} +{"seq_id":"74936394110","text":"def box_path(points, width, twist = 0):\n\n from numpy import dot, concatenate, array\n\n # Find normal to bisecting plane through each point.\n n = len(points)\n p = array(points)\n from chimerax.geometry import normalize_vector as nv\n tangents = array([nv(array(nv(p[min(i+1,n-1)]-p[i]))\n + array(nv(p[i]-p[max(i-1,0)]))) for i in range(n)])\n\n # Trace edge of square cross-section from start to finish.\n edges = []\n y, z = p[2]-p[0], tangents[0]\n from chimerax.geometry import rotation, orthonormal_frame\n if twist != 0:\n y = rotation(z, twist) * y\n f = orthonormal_frame(z, y)\n xa, ya = f.axes()[:2]\n corners = ((1,1), (-1,1), (-1,-1), (1,-1))\n for x, y in corners:\n ep = [points[0] + (x*0.5*width)*xa + (y*0.5*width)*ya]\n for i in range(n-1):\n e0, p0, p1, t = ep[i], p[i], p[i+1], tangents[i+1]\n ep.append(e0 + (dot(p1-e0, t)/dot(p1-p0, t))*(p1-p0))\n edges.append(ep)\n\n # Calculate triangles for each face of a surface model.\n # Make sharp edges.\n va = concatenate(edges + edges + edges + edges)\n ta = []\n nc = len(corners)\n for s in range(n-1):\n for c in range(nc):\n c1 = (c+1)%nc + nc\n t = s + (s % 2)*2*nc*n\n ta.append((c*n+t,c1*n+1+t,c*n+1+t))\n ta.append((c*n+t,c1*n+t,c1*n+1+t))\n\n # Add end caps.\n ta.extend([(nc*n+0,nc*n+(2+c)*n,nc*n+(1+c)*n) for c in range(nc-2)])\n ta.extend([(n-1,(1+c)*n+n-1,(2+c)*n+n-1) for c in range(nc-2)])\n ta = array(ta)\n\n return va, ta\n\n#\n# Cut distances along box edges.\n#\ndef cut_distances(va, nc = 4):\n\n from chimerax.geometry import norm\n cuts = []\n cut = [0]*nc\n n = len(va)//(4*nc)\n for s in range(n-1):\n for c in range(nc):\n e = va[c*n:] if s%2 == 0 else va[((c + nc//2) % nc)*n:]\n cut[c] += norm(e[s+1] - e[s])\n cuts.append(tuple(cut))\n return cuts\n \n\n","repo_name":"RBVI/ChimeraX","sub_path":"src/bundles/shape/src/boxpath.py","file_name":"boxpath.py","file_ext":"py","file_size_in_byte":1954,"program_lang":"python","lang":"en","doc_type":"code","stars":103,"dataset":"github-code","pt":"60"} +{"seq_id":"15494659790","text":"import random\nimport numpy as np\nimport math\nimport sys\n# for 2d int feature comparison\n\n\ndef randomly_chosen_means(k, datalist):\n min_first_feature = min(np.array(datalist)[:, 0])\n min_second_feature = min(np.array(datalist)[:, 1])\n max_first_feature = max(np.array(datalist)[:, 0])\n max_second_feature = max(np.array(datalist)[:, 1])\n cluster_centers = []\n for i in range(k):\n cluster_centers.append([random.uniform(min_first_feature + 1, max_first_feature - 1),\n random.uniform(min_second_feature + 1, max_second_feature - 1)])\n return cluster_centers\n\n\n# updating center wrt new point and old mean : (old_mean*(number_of_points-1)+new_point)/ (number_of_points)\ndef update_cluster_center(sz, center, data):\n center[0] = round(((center[0] * (sz - 1) + data[0]) / float(sz)), 3)\n center[1] = round(((center[1] * (sz - 1) + data[1]) / float(sz)), 3)\n return center\n\n\n# the closest cluster center index to the point returns\ndef euclidean_distance(k, means, data):\n dist = sys.maxsize\n index = -1\n for i in range(k):\n d = (means[i][0] - data[0])**2 + (means[i][1] - data[1])**2\n d = math.sqrt(d)\n if d < dist:\n dist = d\n index = i\n return index\n\n\n# with given data_dict or csv file it returns :cluster centers, data_groups(belongs to), and base data dictionary\ndef find_clusters(k, data_dict):\n cluster_centers = randomly_chosen_means(k, list(data_dict.values()))\n cluster_centers_sizes = [0]*k\n groups = [[] for i in range(k)]\n for t in range(100000):\n for key, data in data_dict.items():\n index = euclidean_distance(k, cluster_centers, data)\n if key in groups[index]:\n pass\n else:\n groups[index].append(key)\n cluster_centers_sizes[index] += 1\n cluster_centers[index] = update_cluster_center(cluster_centers_sizes[index],\n cluster_centers[index], data)\n\n return cluster_centers, groups\n\n\n","repo_name":"besteburhan/deployment-manager","sub_path":"deployment_app/statistics/k_means_clustering.py","file_name":"k_means_clustering.py","file_ext":"py","file_size_in_byte":2088,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"60"} +{"seq_id":"28081508659","text":"\"\"\"\nEuler problem 18\n\nBy starting at the top of the triangle below and moving to adjacent numbers on the row below, the maximum total from top\nto bottom is 23.\n\n3\n7 4\n2 4 6\n8 5 9 3\n\nThat is, 3 + 7 + 4 + 9 = 23.\n\nFind the maximum total from top to bottom of the triangle below:\n\"\"\"\nimport time\n\nwith open('p67.txt','r') as f:\n triangle = f.read()\n\ntriangle_array = [[int(n) for n in line.split()] \n\t\t for line in triangle.split('\\n')[:-1]]\n\n##Recursive:\n#def max_path(tr):\n#\n# if len(tr) == 1: \n# return tr[0][0]\n#\n# else:\n# return sum([ tr[0][0], \n# max( max_path( [ line[1:] for line in tr[1:] ] ),\n# max_path( [ line[:-1] for line in tr[1:] ] ) \n# )\n# ])\n\n#Iterative\ndef max_path(tr):\n for row in range(len(tr)-2,-1,-1):\n for col in range(0,len(tr[row]),1):\n tr[row][col] += max(tr[row+1][col], tr[row+1][col+1] )\n return 0\n\nstart = time.time()\nmax_path(triangle_array)\nmax_sum=triangle_array[0][0]\nstop = time.time() - start\n\nprint(\"Answer = {0}\".format(max_sum))\nprint(\"Elapsed time: {0:.6f}\".format(stop))\n","repo_name":"jboomer/Project_Euler","sub_path":"python/p67.py","file_name":"p67.py","file_ext":"py","file_size_in_byte":1147,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"60"} +{"seq_id":"3916256804","text":"import psycopg2\n\nfrom app.config import Config\nfrom app.logger import Logger\nfrom .user_orders_sql_operations import getInsert\n\n\nclass Loader:\n def __init__(self, worker_name):\n self.logger = Logger(worker_name)\n\n def load(self, user_orders):\n connection = None\n sql_command = getInsert()\n\n try:\n connection = psycopg2.connect(\n user=Config.POSTGRES_USER,\n password=Config.POSTGRES_PASSWORD,\n host=Config.POSTGRES_HOST,\n port=Config.POSTGRES_PORT,\n database=Config.POSTGRES_DATABASE\n )\n cursor = connection.cursor()\n cursor.executemany(sql_command, user_orders)\n cursor.close()\n connection.commit()\n except (Exception, psycopg2.DatabaseError) as error:\n self.logger.error('PostgreSQL error')\n raise error\n finally:\n if connection is not None:\n connection.close()\n","repo_name":"cobantudor/ETL-service","sub_path":"app/loader/loader.py","file_name":"loader.py","file_ext":"py","file_size_in_byte":1000,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"60"} +{"seq_id":"27213553323","text":"# -*- coding: utf-8 -*-\n\"\"\"\n@Time: 2020/6/9 11:05\n@Author: Sue Zhu\n\"\"\"\n__all__ = ['calc_market_factor', 'calc_timing_factor', 'get_index_ff3', 'get_index_bond5']\n\nfrom itertools import product\n\nimport pandas as pd\n\nfrom .comment import get_price, get_risk_free_rates, get_dates\nfrom .. import const\n\n\ndef _get_index_price(code):\n price = get_price(const.AssetEnum.INDEX, code=code)\n return price.set_index('trade_dt').loc[lambda ser: ~ser.index.duplicated(), 'close_']\n\n\ndef _resample_ret(price, freq):\n mapper = get_dates(freq).to_series().resample('D').bfill()\n return price.rename(index=mapper).loc[lambda ser: ~ser.index.duplicated()].pct_change(1)\n\n\ndef calc_market_factor(code_or_price, calc_freq=const.FreqEnum.W):\n \"\"\"\n calculate market factor without risk-free rate\n\n comment factor code for markets:\n - A Share: h00985.CSI 中证全指; h00300.CSI; h00905.CSI\n - Bond: CBA00301.CS; h11001.CSI\n - CMoney: h11025.CSI; 885009.WI\n\n :param code_or_price: str or series or dict\n :param calc_freq:\n :return:\n \"\"\"\n if isinstance(code_or_price, str):\n code_or_price = _get_index_price(code_or_price)\n elif isinstance(code_or_price, dict):\n code_or_price = pd.Series(code_or_price)\n\n return _resample_ret(code_or_price, calc_freq).sub(get_risk_free_rates('save', calc_freq)).dropna()\n\n\ndef _unit_gii_factor(df):\n \"\"\"\n GII Timing Factor\n\n $ P_{mt} = \\big[ \\prod_{k \\in month(t)}^t \\max(1+r_{mk}, 1+r_{fk}) \\big] - (1+r_{mt}) $\n $ r_t = \\alpha + \\beta r_{mt} + \\gamma P_{mt} + \\varepsilon_t $\n \"\"\"\n market_ret, rf = df['market'], df['rf']\n prod_alpha = market_ret.where(market_ret > rf, rf).add(1).prod()\n prod_mkt = market_ret.add(1).prod()\n return prod_alpha - prod_mkt\n\n\ndef calc_timing_factor(code_or_price, method='gii', calc_freq=const.FreqEnum.W):\n if isinstance(code_or_price, str):\n code_or_price = _get_index_price(code_or_price)\n\n if method == 'gii':\n _FREQ_ORDER = list('DWMQY')\n base_freq = const.FreqEnum[_FREQ_ORDER[_FREQ_ORDER.index(calc_freq.name) - 1]]\n org_ret = pd.DataFrame({\n 'market': _resample_ret(code_or_price, base_freq),\n 'rf': get_risk_free_rates('save', base_freq),\n 'label': get_dates(calc_freq).to_series()\n })\n org_ret.loc[:, 'label'] = org_ret['label'].ffill().bfill()\n timing = org_ret.dropna().groupby('label').apply(_unit_gii_factor)\n return timing\n\n elif method in ('hm', 'tm'):\n rf = get_risk_free_rates('save', calc_freq)\n market = _resample_ret(code_or_price, calc_freq)\n net_ret = market.sub(rf).dropna()\n if method == 'hm':\n return net_ret.where(net_ret > 0, 0)\n else:\n return net_ret ** 2\n\n else:\n raise KeyError(f\"Unknown `method` {method}.\")\n\n\ndef get_index_ff3(calc_freq=const.FreqEnum.W, timing=None):\n market_price = _get_index_price('h00985.CSI')\n\n box9_price = pd.DataFrame({f'{c}{v}': _get_index_price(f'ff3_{c}{v}') for c, v in product('smb', 'gnv')})\n box9_ret = _resample_ret(box9_price, calc_freq).iloc[1:]\n\n filter_mean = lambda x: box9_ret.filter(regex=x, axis=1).mean(axis=1)\n factors = pd.DataFrame({\n 'market': calc_market_factor(code_or_price=market_price, calc_freq=calc_freq),\n 'smb': filter_mean('s.') - filter_mean('b.'),\n 'hml': filter_mean('.v') - filter_mean('.g'),\n }).dropna()\n if timing:\n factors['timing'] = calc_timing_factor(market_price, calc_freq=calc_freq, method=timing)\n return factors\n\n\ndef get_index_bond5(calc_freq=const.FreqEnum.W):\n bond_market = _get_index_price('CBA00301.CS')\n credit_3a = _get_index_price('CBA04201.CS')\n high_yield = _get_index_price('CBA03801.CS')\n\n factors = pd.DataFrame({\n 'market': calc_market_factor(code_or_price=bond_market, calc_freq=calc_freq),\n 'credit': _resample_ret(credit_3a, calc_freq) - _resample_ret(bond_market, calc_freq),\n 'default_': _resample_ret(high_yield, calc_freq) - _resample_ret(credit_3a, calc_freq),\n 'cmoney': calc_market_factor(code_or_price='h11025.CSI', calc_freq=calc_freq),\n 'convert': calc_market_factor(code_or_price='h00906.CSI', calc_freq=calc_freq),\n }).dropna()\n return factors\n","repo_name":"dxcv/paramecium","sub_path":"paramecium/database/index_.py","file_name":"index_.py","file_ext":"py","file_size_in_byte":4300,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"60"} +{"seq_id":"6543165545","text":"import datetime\n\nfrom sqlalchemy import (\n Column, Unicode, Integer, DateTime, Boolean, ForeignKey, Table)\nfrom sqlalchemy.orm import relationship\nfrom sqlalchemy.dialects.postgresql import JSONB\nfrom sqlalchemy.ext.mutable import MutableDict\n\nfrom goodtablesio.models.base import Base, BaseModelMixin, make_uuid\n\n\nclass Source(Base, BaseModelMixin):\n\n __tablename__ = 'sources'\n\n id = Column(Unicode, primary_key=True, default=make_uuid)\n name = Column(Unicode)\n active = Column(Boolean, nullable=False, default=False)\n updated = Column(DateTime(timezone=True), nullable=False,\n default=datetime.datetime.utcnow)\n job_number = Column(Integer, default=1)\n conf = Column(MutableDict.as_mutable(JSONB))\n integration_name = Column(Unicode, ForeignKey('integrations.name'))\n integration = relationship(\n 'Integration',\n primaryjoin='Source.integration_name == Integration.name')\n\n users = relationship('User', backref='sources', secondary=Table(\n 'source_users', Base.metadata,\n Column('source_id', Unicode,\n ForeignKey('sources.id', ondelete='CASCADE'),\n primary_key=True),\n Column('user_id', Unicode,\n ForeignKey('users.id', ondelete='CASCADE'),\n primary_key=True),\n Column('role', Unicode, nullable=False, default='default')))\n\n jobs = relationship(\n 'Job', backref='source', primaryjoin='Job.source_id == Source.id',\n order_by='Job.created')\n\n __mapper_args__ = {\n 'polymorphic_on': integration_name,\n 'polymorphic_identity': 'source'\n }\n\n def to_api(self, with_last_job=False, with_job_history=False):\n source = {\n 'id': self.id,\n 'name': self.name,\n 'integration_name': self.integration_name,\n 'active': self.active,\n }\n\n # Add last job\n if with_last_job:\n source['last_job'] = (self.last_job.to_api()\n if self.last_job else None)\n\n # Add job history\n if with_job_history:\n source['job_history'] = self.job_history\n\n return source\n\n @property\n def last_job(self):\n return self.jobs[-1] if self.jobs else None\n\n @property\n def job_history(self):\n history = []\n for job in self.jobs:\n history.append({\n 'id': job.id,\n 'status': job.status,\n 'created': job.created,\n 'finished': job.finished,\n 'integration_name': job.integration_name,\n 'number': job.number,\n 'conf': job.conf,\n })\n return history\n\n @staticmethod\n def get_by_integration_and_name(integration_name, name):\n return (Source.query().\n filter_by(integration_name=integration_name, name=name).\n one_or_none())\n","repo_name":"AntoineAugusti/goodtables.io","sub_path":"goodtablesio/models/source.py","file_name":"source.py","file_ext":"py","file_size_in_byte":2951,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"60"} +{"seq_id":"74206706752","text":"\n\"\"\" import wmi\n\nw = wmi.WMI()\nfor p in w.Win32_Product():\n\tprint (r\"\\newcommand*{\\Title}\", \"{\" + p.Version +\"}\")\n\tprint (r\"\\newcommand*{\\Title}\", \"{\" + p.Vendor +\"}\")\n\tprint (r\"\\newcommand*{\\Title}\", \"{\" + p.Caption +\"}\")\n\tprint (r\"\\newcommand*{\\Title}\", \"{%s}\" % p.Caption)\n\tprint(\"\\n\")\n \"\"\"\n\"\"\" \t\t\ttry:\n\t\t\t\tsoftware['version'] = winreg.QueryValueEx(sub_key, \"DisplayVersion\")[0]\n\t\t\texcept EnvironmentError:\n\t\t\t\tsoftware['version'] = 'undefined'\n\t\t\ttry:\n\t\t\t\tsoftware['publisher'] = winreg.QueryValueEx(sub_key, \"Publisher\")[0]\n\t\t\texcept EnvironmentError: \n\t\t\t\tsoftware['publisher'] = 'undefined'\"\"\"\n\n#\tprint('Name: %s, Version: %s, Publisher: %s' % (software['name'], software['version'], software['publisher']))\n\nimport winreg\nimport datetime\n\n\ndef sofware_instaled(hive, flag):\n\tRegister = winreg.ConnectRegistry(None, hive)\n\tKey = winreg.OpenKey(Register, r\"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\", 0, winreg.KEY_READ | flag)\n\n\tcount_subkey = winreg.QueryInfoKey(Key)[0]\n\tdt = datetime.datetime.fromtimestamp(count_subkey)\n\tprint(dt)\n\t\n\tsoftware_list = []\n\n\tfor i in range(count_subkey):\n\t\tsoftware = {}\n\t\ttry:\n\t\t\tsub_key_name = winreg.EnumKey(Key, i)\n\t\t\tsub_key = winreg.OpenKey(Key, sub_key_name)\n\t\t\tsoftware['name'] = winreg.QueryValueEx(sub_key, \"DisplayName\")[0]\n\t\t\ttry:\n\t\t\t\tsoftware['date'] = winreg.QueryValueEx(sub_key, \"InstallDate\")[0]\n\t\t\texcept EnvironmentError:\n\t\t\t\tsoftware['date'] = 'undefined'\n\t\t\tsoftware_list.append(software)\n\t\texcept EnvironmentError:\n\t\t\tcontinue\n\tprint(sub_key)\n\treturn software_list\n\nsoftware_list = sofware_instaled(winreg.HKEY_LOCAL_MACHINE, winreg.KEY_WOW64_32KEY) + sofware_instaled(winreg.HKEY_LOCAL_MACHINE, winreg.KEY_WOW64_64KEY) + sofware_instaled(winreg.HKEY_CURRENT_USER, 0)\n\nfor software in software_list:\n\tdate = str(software['date'])\n\tif date.isnumeric() == True:\n\t\tagedate = date[0:4]\n\t\tmonthdate = date[4:6]\n\t\tdaydate = date[6:8]\n\t\tformatdate = agedate + \"-\" + monthdate + \"-\" + daydate\n\t\tprint('Name: %s' % (software['name']), formatdate)\n\t\t#print(formatdate)\n\telse:\n\t\tif date.isalpha == True:\n\t\t\tprint(date)\nprint('Number of installed apps: %s' % len(software_list))\n\n","repo_name":"Yeraygb/recovery","sub_path":"prueba.py","file_name":"prueba.py","file_ext":"py","file_size_in_byte":2141,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"60"} +{"seq_id":"38621956399","text":"#!/usr/bin/env python3\r\n\"\"\"\r\nMerge pdfs and append page number\r\nYuri Shimane, 2020/09/30\r\n\r\nCommand line usage:\r\n\r\npython merge_pdfs.py\r\npython merge_pdfs.py \r\n\r\nreference: https://qiita.com/wrblue_mica34/items/16fe8cf3f8d12ebbbe58\r\n\"\"\"\r\n\r\n# generic modules\r\nimport sys\r\nimport os\r\nimport time\r\n\r\n# for merging pdf\r\nimport glob\r\nimport PyPDF2\r\n\r\n# for numerating pages\r\nfrom reportlab.pdfgen.canvas import Canvas\r\nfrom pdfrw import PdfReader\r\nfrom pdfrw.toreportlab import makerl\r\nfrom pdfrw.buildxobj import pagexobj\r\n\r\n\r\ndef merge(source_dir):\r\n \"\"\"Function merges PDFs\r\n\r\n Args:\r\n source_dir (str): directory to grab all pdf files\r\n \"\"\"\r\n print(f'Taking pdfs from {source_dir}...')\r\n\r\n # import all pdfs in the source directory\r\n source_path = source_dir + '/*.pdf'\r\n pdffiles = glob.glob(source_path)\r\n print(f'Merging {len(pdffiles)} pdf files... ')\r\n\r\n # create merger object\r\n merger = PyPDF2.PdfFileMerger()\r\n # merge all objects\r\n for f in pdffiles:\r\n merger.append(f)\r\n\r\n # create directory where output pdf is taken\r\n savepath = source_dir + '/merged_pdf/'\r\n if not os.path.exists(savepath):\r\n os.makedirs(savepath)\r\n\r\n\r\n # save version without page number\r\n timestamp = time.strftime('%m%d_%H%M')\r\n flename_nopagenum = 'merge_' + timestamp + '_no_page_numbers.pdf'\r\n save_path_nopagenum = savepath + flename_nopagenum\r\n merger.write(save_path_nopagenum) # output merged files\r\n merger.close()\r\n\r\n # ----------------------------------------------------------------- #\r\n # append page numbers to generated pdf\r\n # if len(sys.argv) != 2 or \".pdf\" not in sys.argv[1].lower():\r\n # print(f\"Usage: python {sys.argv[0]} \")\r\n # sys.exit()\r\n input_file = save_path_nopagenum\r\n output_file = savepath + 'merge_' + timestamp + \".pdf\"\r\n\r\n reader = PdfReader(input_file)\r\n pages = [pagexobj(p) for p in reader.pages]\r\n\r\n canvas = Canvas(output_file)\r\n\r\n for page_num, page in enumerate(pages, start=1):\r\n canvas.doForm(makerl(canvas, page))\r\n\r\n footer_text = f\"{page_num}/{len(pages)}\"\r\n canvas.saveState()\r\n canvas.setStrokeColorRGB(0, 0, 0)\r\n canvas.setFont('Times-Roman', 14)\r\n canvas.drawString(290, 10, footer_text)\r\n canvas.restoreState()\r\n canvas.showPage()\r\n\r\n # ----------------------------------------------------------------- #\r\n # save output\r\n canvas.save()\r\n print(f'Done, saved at {output_file}!')\r\n\r\n\r\nif __name__==\"__main__\":\r\n # find source pdf directory\r\n if len(sys.argv)==1:\r\n #source_dir = './source_pdfs'\r\n source_dir = input('Source path (grabbing all pdfs here): ')\r\n else:\r\n source_dir = sys.argv[1]\r\n\r\n","repo_name":"Yuricst/pdfbenri","sub_path":"pdfbenri/merge.py","file_name":"merge.py","file_ext":"py","file_size_in_byte":2802,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"60"} +{"seq_id":"30811724151","text":"#https://www.acmicpc.net/problem/10711\n\n'''\n주변의 . 개수가 해당 숫자보다 크거나 같으면 없어짐\n\n'''\ndef in_range(a,b):\n if 0<= a < scale_x and 0<= b < scale_y:\n return True\n else:\n False\n\ndr = [1,1,1,0,0,-1,-1,-1]\ndc = [1,0,-1,1,-1,1,0,-1]\n\nscale_x, scale_y = map(int, input().split())\nli = list()\nfor s_x in range(scale_x):\n li.append(list(input()))\n\nans = 0\nend = True\nwhile end:\n ans +=1\n end = False\n S = list()\n for x in range(1,scale_x-1):\n for y in range(1,scale_y-1):\n count = 0\n if li[x][y] == '.' or li[x][y] == '9':\n continue\n else:\n for i in range(8):\n if in_range(x+dr[i],y+dc[i]) and li[x+dr[i]][y+dc[i]]=='.':\n count +=1\n if int(li[x][y]) <= count:\n S.append((x,y))\n break\n for k in S:\n a, b = k\n li[a][b] ='.'\n end = True\n print(li)\nprint(ans-1)\n\n#########################################################\n\n","repo_name":"shs9509/Algorithm","sub_path":"모래성.py","file_name":"모래성.py","file_ext":"py","file_size_in_byte":1086,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"60"} +{"seq_id":"9913375159","text":"import pandas as pd\nfrom plotly import graph_objs, subplots\n\nfrom mining import LEXIQUE, df, url_name_to_lexical_field\n\npd.options.mode.chained_assignment = None\n\n\ndef get_lexicon_from_pathname(pathname):\n \"\"\"Link the webpage pathname to the corresponding lexicon.\"\"\"\n\n if pathname == \"/\":\n return {\n lexicon_name: {word for field in lexicon.values() for word in field}\n for lexicon_name, lexicon in LEXIQUE.items()\n }\n else:\n return LEXIQUE[url_name_to_lexical_field[pathname]]\n\n\ndef build_datatable(pathname, field, words, and_or):\n \"\"\"Update datatable depending on the activated filters.\"\"\"\n\n data_frame = df\n\n if pathname:\n data_frame = data_frame[data_frame[\"intent\"] == pathname]\n\n if field:\n data_frame = data_frame[(data_frame[\"intent\"] == field) | (data_frame[\"subintent\"] == field)]\n\n if words:\n word_filter = data_frame[\"QT_\" + words[0]] > 0\n if len(words) >= 2:\n for word in words[1:]:\n if and_or == \"AND\":\n word_filter = word_filter & (data_frame[\"QT_\" + word] > 0)\n elif and_or == \"OR\":\n word_filter = word_filter | (data_frame[\"QT_\" + word] > 0)\n data_frame = data_frame[word_filter]\n\n return data_frame.to_dict(\"rows\")\n\n\ndef build_graphs(data_frame, lexicon):\n \"\"\"Update graphs depending on the activated filters.\"\"\"\n\n intents = [\n field for field in lexicon.keys() if field in set(data_frame[\"intent\"]) or field in set(data_frame[\"subintent\"])\n ]\n\n fig = subplots.make_subplots(rows=len(intents), cols=1, shared_xaxes=False, subplot_titles=(tuple(intents)))\n\n for ind, field in enumerate(intents):\n\n data = data_frame[(data_frame[\"intent\"] == field) | (data_frame[\"subintent\"] == field)]\n\n sessions_bar = graph_objs.Histogram(\n x=data[\"number of words\"].values,\n text=\"number of words\",\n xbins=dict(start=1, end=max(data[\"number of words\"]) + 1, size=1),\n )\n\n fig.append_trace(sessions_bar, ind + 1, 1)\n\n for i in fig[\"layout\"][\"annotations\"]:\n i[\"font\"] = dict(size=12)\n\n fig[\"layout\"].update(height=min(200 + 200 * len(intents), 2500), showlegend=False)\n updated_fig = fig\n return updated_fig\n","repo_name":"MichaelKarpe/dash-text-mining-dashboard","sub_path":"components/functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":2298,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"60"} +{"seq_id":"9426393789","text":"# python 2.7\nfrom __future__ import absolute_import, unicode_literals, with_statement\nfrom io import open\n\n# builtins\nfrom unittest import TestCase, main\nfrom os import path, getcwd, chdir, remove\n\n# custom\nimport tox_cleanup\n\n__author__ = 'chad nelson'\n__project__ = 'blowdrycss'\n\n\ndef create_file(file_path=''):\n \"\"\" Build create a file at the defined file_path, and write the word 'test' inside it.\n\n :type file_path: str\n :param file_path: Path to the file to be created.\n\n \"\"\"\n with open(file_path, 'w', encoding='utf-8') as _file:\n _file.write('test')\n\n\nclass TestToxCleanup(TestCase):\n def test_tox_cleanup_file_exists(self):\n original_dir = getcwd()\n print('The tox_cleanup started in', original_dir)\n\n cwd = original_dir\n module_path = path.join(cwd, 'blowdrycss') # Prevent removal of source settings file.\n\n if cwd.endswith('unit_tests') and not path.isdir(module_path):\n up2 = path.join('..', '..')\n chdir(up2)\n cwd = getcwd()\n\n settings_path = path.join(cwd, 'blowdrycss_settings.py')\n\n if not path.isfile(settings_path):\n create_file(file_path=settings_path)\n\n self.assertTrue(path.isfile(settings_path), msg=settings_path)\n tox_cleanup.main()\n self.assertFalse(path.isfile(settings_path), msg=settings_path)\n\n chdir(original_dir) # Reset directory\n\n def test_tox_cleanup_file_does_not_exist(self):\n original_dir = getcwd()\n print('The tox_cleanup started in', original_dir)\n\n cwd = original_dir\n\n if cwd.endswith('unit_tests'):\n up2 = path.join('..', '..')\n chdir(up2)\n cwd = getcwd()\n\n settings_path = path.join(cwd, 'blowdrycss_settings.py')\n\n if path.isfile(settings_path):\n remove(settings_path) # Delete blowdrycss_settings.py if it exists.\n\n self.assertFalse(path.isfile(settings_path), msg=settings_path)\n tox_cleanup.main()\n self.assertFalse(path.isfile(settings_path), msg=settings_path)\n\n chdir(original_dir) # Reset directory\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"nueverest/blowdrycss","sub_path":"blowdrycss/unit_tests/test_tox_cleanup.py","file_name":"test_tox_cleanup.py","file_ext":"py","file_size_in_byte":2302,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"60"} +{"seq_id":"73926975551","text":"\nimport os.path\n\nimport requests\nfrom selenium.webdriver.common.by import By\n\nfrom selenium import webdriver\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom bs4 import BeautifulSoup\nfrom selenium.webdriver.firefox.options import Options\n\n\ndef download():\n print(\"informe a URL de Download\")\n url = input()\n print(\"informe o nome do arquivo\")\n nome = input()\n options = Options()\n options.add_argument(\"--headless\")\n driver = webdriver.Firefox(options=options)\n print(\"Aguardando retorno da página...\")\n driver.get(url)\n WebDriverWait(driver, timeout=10).until(\n lambda x: x.find_element(By.TAG_NAME, \"video\"))\n print(\"Vídeo Encontrado!\")\n page_source = driver.page_source\n xml_soup = BeautifulSoup(page_source, 'html.parser')\n video = xml_soup.find('video')\n link = video.get('src')\n print(link)\n fim = requests.get(link).content\n home_directory = os.path.expanduser('~')\n f = open(f'{home_directory}/{nome}.mp4', 'wb')\n print(\"Salvando arquivo...\")\n f.write(fim)\n print(f'Arquivo {nome} salvo com sucesso no local {home_directory}')\n","repo_name":"paduaalves/download-video-instagram","sub_path":"file_one.py","file_name":"file_one.py","file_ext":"py","file_size_in_byte":1122,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"60"} +{"seq_id":"28234015512","text":"import sys\r\ninput = sys.stdin.readline\r\n\r\nS = input().rstrip()\r\nK = input().rstrip()\r\n\r\nnewS = ''.join([i for i in S if not i.isdigit()])\r\n\r\nHM = [373587883, 179424673]\r\nHK = [8779, 8179]\r\nHK4 = [1, 1]\r\nans1 = [0, 0]\r\nans2 = [0, 0]\r\nr = ['0', '0']\r\n\r\nn = len(K)\r\nfor j in range(2):\r\n for i in range(n):\r\n ans1[j] *= HK[j]\r\n ans2[j] *= HK[j]\r\n ans1[j] += ord(newS[i])\r\n ans2[j] += ord(K[i])\r\n ans1[j] %= HM[j]\r\n ans2[j] %= HM[j]\r\n\r\n HK4[j] *= HK[j]\r\n HK4[j] %= HM[j]\r\n\r\n # print(ans1, ans2)\r\n if ans1[j] == ans2[j]:\r\n r[j] = '1'\r\n \r\n for i in range(n, len(newS)):\r\n ans1[j] *= HK[j]\r\n ans1[j] -= (ord(newS[i-n])*HK4[j])%HM[j]\r\n ans1[j] += ord(newS[i])\r\n ans1[j] += HM[j]\r\n ans1[j] %= HM[j]\r\n # print(ans1, ans2)\r\n if ans1[j] == ans2[j]:\r\n r[j] = '1'\r\n \r\nif r[0] == r[1] and r[0] == '1':\r\n print('1')\r\nelse:\r\n print('0')","repo_name":"realrealbback/Algoritmn","sub_path":"BOJ/16172_나는 친구가 적다(Large).py","file_name":"16172_나는 친구가 적다(Large).py","file_ext":"py","file_size_in_byte":977,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"60"} +{"seq_id":"13309341371","text":"import os\nimport pickle\nimport platform\nimport time\n\nimport requests\n# https://chromedriver.chromium.org/downloads\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.support.wait import WebDriverWait\n\nimport config\n\n\nclass HuyaDriver:\n def __init__(self, room_id):\n options = webdriver.ChromeOptions()\n prefs = {\n \"profile.default_content_setting_values.plugins\": 1,\n \"profile.content_settings.plugin_whitelist.adobe-flash-player\": 1,\n \"profile.content_settings.exceptions.plugins.*,*.per_resource.adobe-flash-player\": 1,\n \"PluginsAllowedForUrls\": \"https://www.huya.com\"\n }\n options.add_experimental_option(\"prefs\", prefs)\n # options.add_argument('--ignore-certificate-errors')\n if platform.system() == 'Windows':\n executable_path = './win/chromedriver.exe'\n elif platform.system() == 'Darwin':\n executable_path = './mac/chromedriver'\n elif platform.system() == 'Linux':\n executable_path = './linux/chromedriver'\n else:\n executable_path = ''\n self.driver = webdriver.Chrome(executable_path=executable_path, chrome_options=options)\n\n # 隐式等待是全局性的,只要用了driver.findxx没有第一时间找到元素,就会等待5s,当然一般都被用wait覆盖掉了\n self.driver.implicitly_wait(5)\n # 显示等待是定向性的,最大等待时间10s,每次检测元素有没有生成的时间间隔300ms,过了最大等待时间抛出异常\n self.wait = WebDriverWait(self.driver, timeout=10, poll_frequency=300)\n\n self.url = f'https://www.huya.com/{room_id}'\n\n if os.path.exists(config.get('cookie_path')):\n print(\"当前目录下存在虎牙登录的cookie文件,将为您自动登录\")\n self.login_with_cookie()\n else:\n print(\"当前目录下不存在虎牙登录的cookie文件\")\n self.login_with_qr()\n\n # self.close_video()\n\n def close_video(self):\n print('关闭video')\n try:\n WebDriverWait(self.driver, 10).until(\n EC.visibility_of_element_located((By.XPATH, '//*[@id=\"pub_msg_input\"]')))\n except:\n print(\"对不起,暂停按钮\")\n return\n\n def login_with_qr(self):\n self.driver.get(self.url)\n\n self.driver.maximize_window()\n print(self.driver.title)\n # 这个是最垃圾的等待,都定死啦\n time.sleep(1)\n\n # login_button = self.wait.until(\n # EC.element_to_be_clickable(\n # (By.XPATH, '//*[@id=\"nav-login\"]')))\n # driver.find_element_by_link_text(\"登录\").click()\n # 点击登录按钮\n # login_button.click()\n\n # 这个时候我们用二维码登录,设置最多等待3分钟,如果登录那个区域是可见的,就登录成功\n WebDriverWait(self.driver, 180).until(\n EC.visibility_of_element_located((By.XPATH, '//*[@id=\"J_duyaHeaderRight\"]/div/div[2]/a/img')))\n\n print(\"登录成功\")\n # 保存cookie到cookies.pkl文件\n session = requests.Session()\n # 获取cookie\n cookies = self.driver.get_cookies()\n # 把cookie写入文件\n if not os.path.exists(\"cookie\"):\n os.mkdir(\"cookie\")\n pickle.dump(cookies, open(config.get('cookie_path'), \"wb\"))\n\n def login_with_cookie(self):\n\n # driver.get(\"https://www.douyu.com\")\n self.driver.get(self.url)\n self.driver.maximize_window()\n # 把cookie文件加载出来\n with open(config.get('cookie_path'), \"rb\") as cookiefile:\n cookies = pickle.load(cookiefile)\n for cookie in cookies:\n print(cookie)\n self.driver.add_cookie(cookie)\n time.sleep(3)\n self.driver.refresh()\n # 如果登录成功那个区域不可见的,说明cookie没有登录成功,重新用二维码登录\n try:\n WebDriverWait(self.driver, 10).until(\n EC.visibility_of_element_located((By.XPATH, '//*[@id=\"login-username\"]')))\n except:\n print(\"对不起,使用cookie登录失败,请重新扫描二维码登录\")\n self.login_with_qr()\n\n print(\"登录成功\")\n print(self.driver.title)\n\n def send_barrage(self, message):\n # print('开始输入弹幕')\n try:\n WebDriverWait(self.driver, 10).until(\n EC.visibility_of_element_located((By.XPATH, '//*[@id=\"pub_msg_input\"]')))\n except:\n print(\"对不起,没有找到输入框\")\n return\n\n # 清空输入框信息\n self.wait.until(\n EC.element_to_be_clickable((By.XPATH, '//*[@id=\"pub_msg_input\"]'))).clear()\n\n time.sleep(3)\n self.wait.until(\n EC.element_to_be_clickable((By.XPATH, '//*[@id=\"pub_msg_input\"]'))).send_keys(message)\n self.wait.until(\n EC.element_to_be_clickable((By.XPATH, '//*[@id=\"msg_send_bt\"]'))).click()\n print(f'发送成功 message = {message}')\n\n def close(self):\n self.driver.close()\n\n\nif __name__ == \"__main__\":\n driver = HuyaDriver('10132155')\n driver.send_barrage('hahah')\n","repo_name":"br3ant/huya_barrage","sub_path":"huya_login.py","file_name":"huya_login.py","file_ext":"py","file_size_in_byte":5370,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"60"} +{"seq_id":"37713788183","text":"from importlib.metadata import version\n\nimport pytest\n\nfrom dependabot_alerts.cli import cli\n\n\ndef test_it(GitHub, github, subprocess, capsys, format_text):\n cli([\"test-organization\"])\n\n GitHub.assert_called_once_with(subprocess.run)\n github.alerts.assert_called_once_with(\"test-organization\")\n format_text.assert_called_once_with(github.alerts.return_value, \"test-organization\")\n captured = capsys.readouterr()\n assert captured.out == f\"{format_text.return_value}\\n\"\n assert not captured.err\n\n\ndef test_format_slack(capsys, github, format_slack):\n cli([\"--format\", \"slack\", \"test-organization\"])\n\n format_slack.assert_called_once_with(\n github.alerts.return_value, \"test-organization\"\n )\n captured = capsys.readouterr()\n assert captured.out == f\"{format_slack.return_value}\\n\"\n\n\ndef test_it_prints_nothing_if_there_are_no_alerts(capsys, format_text):\n format_text.return_value = None\n\n cli([\"test-organization\"])\n\n captured = capsys.readouterr()\n assert not captured.out\n assert not captured.err\n\n\ndef test_it_crashes_if_no_organization_argument_is_given(capsys):\n with pytest.raises(SystemExit) as exc_info:\n cli([])\n\n assert exc_info.value.code == 2\n captured = capsys.readouterr()\n assert not captured.out\n assert \"error: the following arguments are required: organization\" in captured.err\n\n\ndef test_it_crashes_if_an_invalid_format_is_given(capsys):\n with pytest.raises(SystemExit) as exc_info:\n cli([\"--format\", \"foo\", \"organization\"])\n\n assert exc_info.value.code == 2\n captured = capsys.readouterr()\n assert not captured.out\n assert \"error: argument --format: invalid choice: 'foo'\" in captured.err\n\n\ndef test_help():\n with pytest.raises(SystemExit) as exc_info:\n cli([\"--help\"])\n\n assert not exc_info.value.code\n\n\ndef test_version(capsys):\n with pytest.raises(SystemExit) as exc_info:\n cli([\"--version\"])\n\n assert capsys.readouterr().out.strip() == version(\"dependabot-alerts\")\n assert not exc_info.value.code\n\n\n@pytest.fixture(autouse=True)\ndef GitHub(mocker):\n return mocker.patch(\"dependabot_alerts.cli.GitHub\")\n\n\n@pytest.fixture\ndef github(GitHub):\n return GitHub.return_value\n\n\n@pytest.fixture(autouse=True)\ndef format_slack(mocker):\n return mocker.patch(\"dependabot_alerts.cli.format_slack\")\n\n\n@pytest.fixture(autouse=True)\ndef format_text(mocker):\n return mocker.patch(\"dependabot_alerts.cli.format_text\")\n\n\n@pytest.fixture(autouse=True)\ndef subprocess(mocker):\n return mocker.patch(\"dependabot_alerts.cli.subprocess\")\n","repo_name":"hypothesis/dependabot-alerts","sub_path":"tests/unit/dependabot_alerts/cli_test.py","file_name":"cli_test.py","file_ext":"py","file_size_in_byte":2581,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"60"} +{"seq_id":"36596727865","text":"A , B = map(int , input().split())\n\ndef aorb(A , B):\n if A == B:\n return \"Draw\"\n elif A == 1 or A > B and B != 1:\n return \"Alice\"\n else:\n return \"Bob\"\n\nif __name__ == '__main__':\n ans = aorb(A , B)\n print(ans)","repo_name":"takapdayon/atcoder","sub_path":"abc/AtCoderBeginnerContest054/A.py","file_name":"A.py","file_ext":"py","file_size_in_byte":245,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"60"} +{"seq_id":"6140601824","text":"import collections\n\nfrom test_framework import generic_test\nfrom test_framework.test_failure import TestFailure\n\n\nclass LruCache:\n def __init__(self, capacity: int) -> None:\n\n self._isbn_price_table: collections.OrderedDict[\n int, int] = collections.OrderedDict()\n self._capacity = capacity\n\n def lookup(self, isbn: int) -> int:\n\n if isbn not in self._isbn_price_table:\n return -1\n price = self._isbn_price_table.pop(isbn)\n self._isbn_price_table[isbn] = price\n return price\n\n def insert(self, isbn: int, price: int) -> None:\n\n # We add the value for key only if key is not present - we don't update\n # existing values.\n if isbn in self._isbn_price_table:\n price = self._isbn_price_table.pop(isbn)\n elif len(self._isbn_price_table) == self._capacity:\n self._isbn_price_table.popitem(last=False)\n self._isbn_price_table[isbn] = price\n\n def erase(self, isbn: int) -> bool:\n\n return self._isbn_price_table.pop(isbn, None) is not None\n\n\ndef lru_cache_tester(commands):\n if len(commands) < 1 or commands[0][0] != 'LruCache':\n raise RuntimeError('Expected LruCache as first command')\n\n cache = LruCache(commands[0][1])\n\n for cmd in commands[1:]:\n if cmd[0] == 'lookup':\n result = cache.lookup(cmd[1])\n if result != cmd[2]:\n raise TestFailure('Lookup: expected ' + str(cmd[2]) +\n ', got ' + str(result))\n elif cmd[0] == 'insert':\n cache.insert(cmd[1], cmd[2])\n elif cmd[0] == 'erase':\n result = 1 if cache.erase(cmd[1]) else 0\n if result != cmd[2]:\n raise TestFailure('Erase: expected ' + str(cmd[2]) + ', got ' +\n str(result))\n else:\n raise RuntimeError('Unexpected command ' + cmd[0])\n\n\nif __name__ == '__main__':\n exit(\n generic_test.generic_test_main('lru_cache.py', 'lru_cache.tsv',\n lru_cache_tester))\n","repo_name":"adnanaziz/EPIJudge","sub_path":"epi_judge_python_solutions/lru_cache.py","file_name":"lru_cache.py","file_ext":"py","file_size_in_byte":2095,"program_lang":"python","lang":"en","doc_type":"code","stars":2693,"dataset":"github-code","pt":"60"} +{"seq_id":"30222614316","text":"import os\nimport sys\nimport time\nimport yaml\nimport itertools\nimport logging\n\nfrom subprocess import call, check_output, DEVNULL\nfrom retrying import retry\n\ndef main(input_path, threads):\n base_path = os.path.abspath(input_path)\n if not os.path.isdir(base_path):\n raise IOError(\"%s does not exist or is not a directory\"%base_path)\n\n audios = get_audios()\n start = datetime.now()\n if threads == 1:\n for audio in audios:\n download_files(base_path, audio)\n else:\n with Pool(threads) as pool:\n with tqdm(total=len(audios)) as pbar:\n for i, _ in tqdm(enumerate(pool.imap(download_files_star,\n zip(itertools.repeat(base_path), audios)))):\n pbar.update()\n\n end = datetime.now()\n print(\"It took: %s\"%(end-start))\n\ndef get_audios():\n audios = []\n person = yaml.load(open(yaml_in))\n for session, talks in person.items():\n for talk_id, talk in talks.items():\n audios.append([talk_id, talk['text'], talk['audio']])\n return audios\n\ndef download_files_star(base_path_audio):\n return download_files(*base_path_audio)\n\ndef download_files(base_path, audio):\n '''creates the paths and initiates the download of files\n '''\n text_path, text, link = audio\n paths = create_local_paths(base_path, audio)\n audio_path = os.path.dirname(paths['audio_path'])\n if not os.path.isdir(audio_path):\n try:\n os.makedirs(audio_path)\n except FileExistsError:\n logging.warning(\"conflicting mkdir on %s. Safely skipping.\"%audio_path)\n check_download_convert(link,paths['audio_path'])\n\ndef create_local_paths(base_path, audio):\n '''takes an object with id, text and url; outputs a paths dictionary\n '''\n text_path, text, link = audio\n paths = {}\n base_name = os.path.basename(link)\n paths['audio_path'] = os.path.join(base_path,\n base_name[0],\n base_name[1],\n base_name)\n paths['txt_path'] = text_path.replace('text', 'clean_text')\n return paths\n\ndef check_download_convert(uri, filepath):\n '''downloads a mp3, converts it to mp3 and then deletes the original.\n '''\n if not filepath.endswith('.mp3'):\n raise ValueError('Expected a mp3 audio file but found %s'%filepath)\n if not os.path.isfile(filepath):\n # download\n check_download(uri, filepath)\n else:\n msg = 'skipping %s for %s'%(filepath, uri)\n logging.info(msg)\n\ndef check_download(uri, filepath):\n if not os.path.exists(filepath):\n curl_download(uri, filepath)\n else:\n logging.info(\"%s exists, skipping.\"%filepath)\n\n@retry(stop_max_attempt_number=3, wait_fixed=1000)\ndef curl_download(uri, filepath):\n msg = 'checking %s'%uri\n logging.info(msg)\n # check the http headers\n status, uri = get_status_code(uri)\n if status == 302:\n # redirect uri should have been extracted to the uri variable\n status, uri = get_status_code(uri)\n if status != 200:\n error = 'the resource in the url %s cannot be reached'\\\n 'with status %i.'%(uri,status)\n logging.error(error)\n if status == 401:\n return None\n else:\n raise ConnectionError(error)\n\n # create file\n with open(filepath,'w') as fout:\n cmd = ['curl','-g',uri]\n logging.info(\"downloading %s\"%uri)\n call(cmd, stdout=fout, stderr=DEVNULL) #seems dangerous but 404s are\n #caught by the get_status_code\ndef get_status_code(url):\n cmd = ['curl','-I',url]\n header = check_output(cmd, stderr=DEVNULL)\n header_list = header.split(b'\\n')\n code = int(header_list[0].split()[1])\n uri = url\n if code == 302:\n for h in header_list:\n if h.startswith(b'Location: '):\n uri = h.strip().decode('ascii')[10:]\n if 'http' not in uri:\n code = 401\n return code, uri\n\ndef simple_convert(source, target):\n '''makes a subprocess call to ffmpeg -i \n '''\n if not os.path.exists(source):\n msg = \"%s does not exists (for conversion)\"%source\n logging.error(msg)\n raise IOError(msg)\n cmd = \"ffmpeg -i %s %s -hide_banner -loglevel panic\"%(source, target)\n logging.info(cmd)\n call(cmd.split(), stdout=DEVNULL)\n\nif __name__ == \"__main__\":\n input_path = sys.argv[1]\n if len(sys.argv) > 2:\n threads = int(sys.argv[2])\n if threads > 4:\n raise ValueError(\"cannot have threads larger than 4\")\n else:\n threads = 1\n\n log_file = 'parlament_download.log'\n current_path = os.getcwd()\n logging.basicConfig(filename=os.path.join(current_path,log_file),\n format=\"%(asctime)s-%(levelname)s: %(message)s\",\n level=logging.INFO,\n filemode='a')\n\n main(input_path, threads)\n","repo_name":"gullabi/parlament-scrape","sub_path":"utils/download.py","file_name":"download.py","file_ext":"py","file_size_in_byte":5058,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"60"} +{"seq_id":"2233419871","text":"import pandas as pd\n\nfrom expenses_server.common.models import C, SpecialTypeId, TransactionCategory\nfrom expenses_server.readers.cal_reader import CalReader\nfrom expenses_server.readers.leumi_reader import LeumiReader\nfrom expenses_server.readers.max_foreign_curr_reader import MaxForeignCurrencyReader\nfrom expenses_server.readers.max_reader import MaxReader\nfrom expenses_server.common.settings import AppSettings\nfrom readers.abstract_read_data import OverrideColumn\nfrom readers.pepper_reader import PepperReader\nfrom services import categorize_service\nfrom services.categorize_service import Rule, RuleType\n\n\ndef read_all_data():\n cal = CalReader(AppSettings.settings.cal_file_path,\n custom_override=[OverrideColumn(column_name=C.TYPE_ID, value=SpecialTypeId.CREDIT_CARD_CAL)]\n ).start()\n max_cards = MaxReader(AppSettings.settings.max_file_path).start()\n max_foreign_cards = MaxForeignCurrencyReader(AppSettings.settings.max_file_path).start()\n leumi = LeumiReader(AppSettings.settings.leumi_file_path,\n custom_override=[OverrideColumn(column_name=C.TYPE_ID, value=SpecialTypeId.BANK_LEUMI)]\n ).start()\n pepper = PepperReader(AppSettings.settings.pepper_file_path,\n custom_override=[OverrideColumn(column_name=C.TYPE_ID, value=SpecialTypeId.BANK_PEPPER)]\n ).start()\n\n return pd.concat([cal, max_cards, max_foreign_cards, leumi, pepper])\n\n\ndef generate_transaction_id(row):\n date_str = row[C.T_DATE].date().isoformat()\n money_str = str(abs(row[C.MONEY])).replace(\".\", \"-\")\n business_str = '-'.join([str(ord(c)) for c in row[C.BUSINESS].replace(\" \", \"-\")[:3]])\n return f't_{date_str}_{money_str}_{business_str}'\n\n\ndef init_db():\n if not AppSettings.globals.rules_db.is_db_exist():\n placeholder = Rule(r_type=RuleType.transaction_id, value=\"empty\", category=TransactionCategory.UNKNOWN_EXPENSE)\n rules_data = pd.DataFrame(data=[placeholder.dict()])\n AppSettings.globals.rules_db.store_all_data(rules_data)\n AppSettings.globals.rules_db.load_data()\n\n if not AppSettings.globals.transaction_db.is_db_exist():\n data = read_all_data()\n data[C.T_ID] = data.apply(generate_transaction_id, axis=1)\n categorize_service.apply_rules(data)\n AppSettings.globals.transaction_db.store_all_data(data)\n AppSettings.globals.transaction_db.load_data([C.T_DATE])\n\n\n","repo_name":"benhorngh/expenses","sub_path":"expenses_server/common/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2475,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"60"} +{"seq_id":"31508657492","text":"r\"\"\"\nTemplate for permutations of interval exchange transformations\n\nThis file define high level operations on permutations (alphabet,\nthe different rauzy moves, ...) shared by reduced and labeled\npermutations.\n\nAUTHORS:\n\n- Vincent Delecroix (2008-12-20): initial version\n\n- Vincent Delecroix (2010-02-11): datatype simplification\n\nTODO:\n\n- disallow access to stratum, stratum component for permutations with flip\n\n- construct dynamic Rauzy graphs and paths\n\n- construct coherent _repr_\n\n\"\"\"\n#*****************************************************************************\n# Copyright (C) 2008 Vincent Delecroix <20100.delecroix@gmail.com>\n#\n# Distributed under the terms of the GNU General Public License (GPL)\n# as published by the Free Software Foundation; either version 2 of\n# the License, or (at your option) any later version.\n# https://www.gnu.org/licenses/\n#*****************************************************************************\n\nfrom __future__ import print_function, absolute_import\nfrom six.moves import range, map, filter, zip\nfrom six import iterkeys, iteritems\n\nfrom functools import total_ordering\n\nfrom sage.structure.sage_object import SageObject\n\nfrom copy import copy\n\nfrom sage.rings.integer import Integer\nfrom sage.rings.integer_ring import ZZ\nfrom sage.matrix.constructor import identity_matrix, matrix\nfrom sage.misc.nested_class import NestedClassMetaclass\n\nfrom surface_dynamics.misc.permutation import perms_canonical_labels\n\ndef to_fat_graphs(twin):\n lt = len(twin[0])\n lb = len(twin[1])\n assert twin[1][-1] == (0,0)\n\n if any(i == 1 for i,j in twin[0][1:]):\n # non-separating\n n = lt + lb - 2\n\n labels = [[None]*lt, [None]*lb]\n labels[0][0] = labels[1][-1] = -1\n k = 0\n ep = [None] * n\n for i in range(2):\n for j in range(len(labels[i])):\n if labels[i][j] is None:\n ii,jj = twin[i][j]\n labels[i][j] = k\n labels[ii][jj] = k+1\n ep[k] = k+1\n ep[k+1] = k\n k += 2\n assert k == n\n labels[0].pop(0)\n labels[1].pop(-1)\n\n fp = [None] * n\n for i in range(lt-1):\n j = (i-1) % (lt-1)\n fp[labels[0][i]] = labels[0][j]\n for i in range(lb-1):\n j = (i+1) % (lb-1)\n fp[labels[1][i]] = labels[1][j]\n\n return [(ep, fp)]\n else:\n # separating\n labelstop = [None] * lt\n labelstop[0] = -1\n eptop = [None] * (lt-1)\n k = 0\n for j in range(len(labelstop)):\n if labelstop[j] is None:\n jj = twin[0][j][1]\n labelstop[j] = k\n labelstop[jj] = k+1\n eptop[k] = k+1\n eptop[k+1] = k\n k += 2\n labelstop.pop(0)\n fptop = [None] * (lt-1)\n for i in range(lt-1):\n j = (i-1) % (lt-1)\n fptop[labelstop[i]] = labelstop[j]\n\n labelsbot = [None] * lb\n labelsbot[-1] = -1\n epbot = [None] * (lb-1)\n k = 0\n for j in range(len(labelsbot)):\n if labelsbot[j] is None:\n jj = twin[1][j][1]\n labelsbot[j] = k\n labelsbot[jj] = k+1\n epbot[k] = k+1\n epbot[k+1] = k\n k += 2\n labelsbot.pop(-1)\n fpbot = [None] * (lb-1)\n for i in range(lb-1):\n j = (i+1) % (lb-1)\n fpbot[labelsbot[i]] = labelsbot[j]\n\n return [(eptop, fptop), (epbot, fpbot)]\n\ndef cylindric_canonical(p):\n r\"\"\"\n TESTS::\n\n sage: from surface_dynamics import QuadraticStratum\n sage: from surface_dynamics.interval_exchanges.template import cylindric_canonical\n\n sage: C = QuadraticStratum(1,genus=0).unique_component()\n sage: R = C.permutation_representative().rauzy_diagram()\n sage: K = [p for p in R if p.is_cylindric()]\n sage: Kcan = set(cylindric_canonical(p) for p in K)\n sage: Kcan\n {((1, 0), (1, 2, 3, 4, 5, 0))}\n sage: C = QuadraticStratum(1,1,genus=0).unique_component()\n sage: R = C.permutation_representative().rauzy_diagram()\n sage: K = [p for p in R if p.is_cylindric()]\n sage: Kcan = set(cylindric_canonical(p) for p in K)\n sage: Kcan\n {((1, 0), (1, 2, 3, 4, 6, 0, 7, 8, 9, 5)),\n ((1, 2, 3, 4, 5, 0), (1, 2, 3, 4, 5, 0))}\n \"\"\"\n twin = p._twin\n if twin[1][-1] != (0,0):\n lt = len(twin[0])\n lb = len(twin[1])\n p._move(0, lt-1, 0, 0)\n p._move(1, 0, 1, lb)\n fg = [perms_canonical_labels([ep,fp])[0][1] for ep,fp in to_fat_graphs(twin)]\n fg.sort()\n return tuple(map(tuple, fg))\n\ndef interval_conversion(interval=None):\n r\"\"\"\n Converts the argument in 0 or 1.\n\n INPUT:\n\n - ``winner`` - 'top' (or 't' or 0) or bottom (or 'b' or 1)\n\n OUTPUT:\n\n integer -- 0 or 1\n\n TESTS::\n\n sage: from surface_dynamics import *\n\n sage: from surface_dynamics.interval_exchanges.template import interval_conversion\n sage: interval_conversion('top')\n 0\n sage: interval_conversion('t')\n 0\n sage: interval_conversion(0)\n 0\n sage: interval_conversion('bottom')\n 1\n sage: interval_conversion('b')\n 1\n sage: interval_conversion(1)\n 1\n\n .. Non admissible strings raise a ValueError::\n\n sage: interval_conversion('')\n Traceback (most recent call last):\n ...\n ValueError: the interval can not be the empty string\n sage: interval_conversion('right')\n Traceback (most recent call last):\n ...\n ValueError: 'right' can not be converted to interval\n sage: interval_conversion('top_right')\n Traceback (most recent call last):\n ...\n ValueError: 'top_right' can not be converted to interval\n \"\"\"\n if isinstance(interval, (int,Integer)):\n if interval != 0 and interval != 1:\n raise ValueError(\"interval must be 0 or 1\")\n else:\n return interval\n\n elif isinstance(interval,str):\n if not interval: raise ValueError(\"the interval can not be the empty string\")\n elif 'top'.startswith(interval): return 0\n elif 'bottom'.startswith(interval): return 1\n else: raise ValueError(\"'%s' can not be converted to interval\" %(interval))\n\n else:\n raise TypeError(\"'%s' is not an admissible type\" %(str(interval)))\n\ndef side_conversion(side=None):\n r\"\"\"\n Converts the argument in 0 or -1.\n\n INPUT:\n\n - ``side`` - either 'left' (or 'l' or 0) or 'right' (or 'r' or -1)\n\n OUTPUT:\n\n integer -- 0 or -1\n\n TESTS::\n\n sage: from surface_dynamics.interval_exchanges.template import side_conversion\n sage: side_conversion('left')\n 0\n sage: side_conversion('l')\n 0\n sage: side_conversion(0)\n 0\n sage: side_conversion('right')\n -1\n sage: side_conversion('r')\n -1\n sage: side_conversion(1)\n -1\n sage: side_conversion(-1)\n -1\n\n .. Non admissible strings raise a ValueError::\n\n sage: side_conversion('')\n Traceback (most recent call last):\n ...\n ValueError: no empty string for side\n sage: side_conversion('top')\n Traceback (most recent call last):\n ...\n ValueError: 'top' can not be converted to a side\n \"\"\"\n if side is None:\n return -1\n\n elif isinstance(side,str):\n if not side: raise ValueError(\"no empty string for side\")\n if 'left'.startswith(side): return 0\n elif 'right'.startswith(side): return -1\n raise ValueError(\"'%s' can not be converted to a side\" %(side))\n\n elif isinstance(side, (int,Integer)):\n if side == 0: return 0\n elif side == 1 or side == -1: return -1\n else: raise ValueError(\"side must be 0 or 1\")\n\n else:\n raise TypeError(\"'%s' is not an admissible type\" %(str(side)))\n\n#\n# NICE PRINTING OF FLIPS\n#\n\ndef labelize_flip(couple):\n r\"\"\"\n Returns a string from a 2-uple couple of the form (name, flip).\n\n TESTS::\n\n sage: from surface_dynamics.interval_exchanges.template import labelize_flip\n sage: labelize_flip((0,1))\n ' 0'\n sage: labelize_flip((0,-1))\n '-0'\n \"\"\"\n if couple[1] == -1: return '-' + str(couple[0])\n return ' ' + str(couple[0])\n\n#\n# CLASSES FOR PERMUTATIONS\n#\n\n@total_ordering\nclass Permutation(SageObject):\n r\"\"\"\n Template for all permutations.\n\n .. warning::\n\n Internal class! Do not use directly!\n\n This class implement generic algorithm (stratum, connected component, ...)\n and unfies all its children.\n\n It has four attributes\n\n - ``_alphabet`` -- the alphabet on which the permutation is defined. Be\n careful, it might have a different cardinality as the size of the\n permutation!\n\n - ``_twin`` -- the permutation\n\n - ``_labels`` -- None or the list of labels\n\n - ``_flips`` -- None or the list of flips (each flip is either ``1`` or\n ``-1``)\n\n The datatype for ``_twin`` differs for IET and LI (TODO: unify).\n \"\"\"\n _alphabet = None\n _twin = None\n _labels = None\n _flips = None\n\n def __init__(self, intervals=None, alphabet=None, reduced=False, flips=None):\n r\"\"\"\n INPUT:\n\n - ``intervals`` - the intervals as a list of two lists\n\n - ``alphabet`` - something that should be converted to an alphabet\n\n - ``reduced`` - (boolean) whether the permutation is reduced or labeled\n\n - ``flips`` - (optional) a list of letters of the alphabet to be flipped (in which\n case the permutation corresponds to non-orientable surface)\n\n TESTS::\n\n sage: from surface_dynamics.interval_exchanges.labelled import LabelledPermutationIET\n\n sage: p1 = LabelledPermutationIET([[1,2,3],[3,2,1]])\n sage: p1 == loads(dumps(p1))\n True\n sage: p2 = LabelledPermutationIET([['a', 'b', 'c'], ['c', 'b', 'a']])\n sage: p2 == loads(dumps(p2))\n True\n sage: p3 = LabelledPermutationIET([['1','2','3'],['3','2','1']])\n sage: p3 == loads(dumps(p3))\n True\n sage: from surface_dynamics.interval_exchanges.labelled import LabelledPermutationLI\n sage: p1 = LabelledPermutationLI([[1,2,2],[3,3,1]])\n sage: p1 == loads(dumps(p1))\n True\n sage: p2 = LabelledPermutationLI([['a','b','b'],['c','c','a']])\n sage: p2 == loads(dumps(p2))\n True\n sage: p3 = LabelledPermutationLI([['1','2','2'],['3','3','1']])\n sage: p3 == loads(dumps(p3))\n True\n\n sage: from surface_dynamics.interval_exchanges.reduced import ReducedPermutationIET\n sage: p = ReducedPermutationIET()\n sage: loads(dumps(p)) == p\n True\n sage: p = ReducedPermutationIET([['a','b'],['b','a']])\n sage: loads(dumps(p)) == p\n True\n sage: from surface_dynamics.interval_exchanges.reduced import ReducedPermutationLI\n sage: p = ReducedPermutationLI()\n sage: loads(dumps(p)) == p\n True\n sage: p = ReducedPermutationLI([['a','a'],['b','b']])\n sage: loads(dumps(p)) == p\n True\n\n sage: from surface_dynamics.interval_exchanges.labelled import FlippedLabelledPermutationIET\n sage: p = FlippedLabelledPermutationIET([['a','b'],['a','b']],flips='a')\n sage: p == loads(dumps(p))\n True\n sage: p = FlippedLabelledPermutationIET([['a','b'],['b','a']],flips='ab')\n sage: p == loads(dumps(p))\n True\n\n sage: from surface_dynamics.interval_exchanges.labelled import FlippedLabelledPermutationLI\n sage: p = FlippedLabelledPermutationLI([['a','a','b'],['b','c','c']],flips='a')\n sage: p == loads(dumps(p))\n True\n sage: p = FlippedLabelledPermutationLI([['a','a'],['b','b','c','c']],flips='ac')\n sage: p == loads(dumps(p))\n True\n\n sage: from surface_dynamics import iet\n sage: p = iet.Permutation('a b','b a',reduced=True,flips='a')\n sage: p == loads(dumps(p))\n True\n sage: p = iet.Permutation('a b','b a',reduced=True,flips='b')\n sage: p == loads(dumps(p))\n True\n sage: p = iet.Permutation('a b','b a',reduced=True,flips='ab')\n sage: p == loads(dumps(p))\n True\n sage: p = iet.GeneralizedPermutation('a a','b b',reduced=True,flips='a')\n sage: p == loads(dumps(p))\n True\n sage: p = iet.GeneralizedPermutation('a a','b b',reduced=True,flips='b')\n sage: p == loads(dumps(p))\n True\n sage: p = iet.GeneralizedPermutation('a a','b b',reduced=True,flips='ab')\n sage: p == loads(dumps(p))\n True\n \"\"\"\n # this constructor assumes that several methods are present\n # _init_twin(intervals)\n # _set_alphabet(alphabet)\n # _init_alphabet(intervals)\n # _init_flips(intervals, flips)\n\n # setting twins\n if intervals is None:\n self._twin = [[], []]\n else:\n self._init_twin(intervals)\n\n # setting alphabet\n if alphabet is not None:\n self._set_alphabet(alphabet)\n elif intervals is not None:\n self._init_alphabet(intervals)\n\n # optionally setting labels\n if intervals is not None and not reduced:\n self._labels = [\n list(map(self._alphabet.rank, intervals[0])),\n list(map(self._alphabet.rank, intervals[1]))]\n\n # optionally setting flips\n if flips is not None:\n self._init_flips(intervals, flips)\n\n def _init_flips(self,intervals,flips):\n r\"\"\"\n Initialize the flip list\n\n TESTS::\n\n sage: from surface_dynamics import *\n\n sage: iet.Permutation('a b','b a',flips='a').flips() #indirect doctest\n ['a']\n sage: iet.Permutation('a b','b a',flips='b').flips() #indirect doctest\n ['b']\n sage: iet.Permutation('a b','b a',flips='ab').flips() #indirect doctest\n ['a', 'b']\n\n ::\n\n sage: iet.GeneralizedPermutation('a a','b b',flips='a').flips()\n ['a']\n sage: iet.GeneralizedPermutation('a a','b b',flips='b').flips()\n ['b']\n sage: iet.GeneralizedPermutation('a a','b b',flips='ab').flips()\n ['a', 'b']\n \"\"\"\n self._flips = [[1]*self.length_top(), [1]*self.length_bottom()]\n for interval in (0,1):\n for i,letter in enumerate(intervals[interval]):\n if letter in flips:\n self._flips[interval][i] = -1\n\n def __eq__(self,other):\n r\"\"\"\n Tests equality\n\n TESTS::\n\n sage: from surface_dynamics import *\n\n sage: p1 = iet.Permutation('a b','a b',reduced=True,alphabet='ab')\n sage: p2 = iet.Permutation('a b','a b',reduced=True,alphabet='ba')\n sage: q1 = iet.Permutation('a b','b a',reduced=True,alphabet='ab')\n sage: q2 = iet.Permutation('a b','b a',reduced=True,alphabet='ba')\n sage: p1 == p2 and p2 == p1 and q1 == q2 and q2 == q1\n True\n sage: p1 == q1 or p2 == q1 or q1 == p1 or q1 == p2\n False\n\n sage: p1 = iet.Permutation('a b', 'b a', alphabet='ab')\n sage: p2 = iet.Permutation('a b', 'b a', alphabet='ba')\n sage: q1 = iet.Permutation('b a', 'a b', alphabet='ab')\n sage: q2 = iet.Permutation('b a', 'a b', alphabet='ba')\n sage: p1 == p2 or p2 == p1\n False\n sage: p1 == q1 or q1 == p1\n False\n sage: p1 == q2 or q2 == p1\n False\n sage: p2 == q1 or q1 == p2\n False\n sage: p2 == q2 or q2 == p2\n False\n sage: q1 == q2 or q2 == q1\n False\n\n ::\n\n sage: p1 = iet.GeneralizedPermutation('a a','b b',alphabet='ab')\n sage: p2 = iet.GeneralizedPermutation('a a','b b',alphabet='ba')\n sage: q1 = iet.GeneralizedPermutation('b b','a a',alphabet='ab')\n sage: q2 = iet.GeneralizedPermutation('b b','a a',alphabet='ba')\n sage: p1 == p2 or p2 == p1\n False\n sage: p1 == q1 or q1 == p1\n False\n sage: p1 == q2 or q2 == p1\n False\n sage: p2 == q1 or q1 == p2\n False\n sage: p2 == q2 or q2 == p2\n False\n sage: q1 == q2 or q2 == q1\n False\n\n ::\n\n sage: p = iet.GeneralizedPermutation('a b b', 'c c a', reduced = True)\n sage: q = iet.GeneralizedPermutation('b a a', 'c c b', reduced = True)\n sage: r = iet.GeneralizedPermutation('t s s', 'w w t', reduced = True)\n sage: p == q\n True\n sage: p == r\n True\n\n ::\n\n sage: p = iet.Permutation('a b','a b',reduced=True,flips='a')\n sage: q = copy(p)\n sage: q.alphabet([0,1])\n sage: p == q\n True\n sage: l0 = ['a b','a b']\n sage: l1 = ['a b','b a']\n sage: l2 = ['b a', 'a b']\n sage: p0 = iet.Permutation(l0, reduced=True, flips='ab')\n sage: p1 = iet.Permutation(l1, reduced=True, flips='a')\n sage: p2 = iet.Permutation(l2, reduced=True, flips='b')\n sage: p3 = iet.Permutation(l1, reduced=True, flips='ab')\n sage: p4 = iet.Permutation(l2 ,reduced=True,flips='ab')\n sage: p0 == p1 or p0 == p2 or p0 == p3 or p0 == p4\n False\n sage: p1 == p2 and p3 == p4\n True\n sage: p1 == p3 or p1 == p4 or p2 == p3 or p2 == p4\n False\n\n ::\n\n sage: a0 = [0,0,1]\n sage: a1 = [1,2,2]\n sage: p = iet.GeneralizedPermutation(a0,a1,reduced=True,flips=[0])\n sage: q = copy(p)\n sage: q.alphabet(\"abc\")\n sage: p == q\n True\n sage: b0 = [1,0,0]\n sage: b1 = [2,2,1]\n sage: r = iet.GeneralizedPermutation(b0,b1,reduced=True,flips=[0])\n sage: p == r or q == r\n False\n\n ::\n\n sage: p1 = iet.Permutation('a b c', 'c b a', flips='a')\n sage: p2 = iet.Permutation('a b c', 'c b a', flips='b')\n sage: p3 = iet.Permutation('d e f', 'f e d', flips='d')\n sage: p1 == p1 and p2 == p2 and p3 == p3\n True\n sage: p1 == p2\n False\n sage: p1 == p3\n False\n sage: p1.reduced() == p3.reduced()\n True\n\n sage: p1 = iet.Permutation('a b', 'a b', reduced=True, alphabet='ab')\n sage: p2 = iet.Permutation('a b', 'a b', reduced=True, alphabet='ba')\n sage: q1 = iet.Permutation('a b', 'b a', reduced=True, alphabet='ab')\n sage: q2 = iet.Permutation('a b', 'b a', reduced=True, alphabet='ba')\n sage: p1 != p2 or p2 != p1 or q1 != q2 or q2 != q1\n False\n sage: p1 != q1 and p2 != q1 and q1 != p1 and q1 != p2\n True\n\n sage: p1 = iet.Permutation('a b', 'b a', alphabet='ab')\n sage: p2 = iet.Permutation('a b', 'b a', alphabet='ba')\n sage: q1 = iet.Permutation('b a', 'a b', alphabet='ab')\n sage: q2 = iet.Permutation('b a', 'a b', alphabet='ba')\n sage: p1 != p2 and p2 != p1\n True\n sage: p1 != q1 and q1 != p1\n True\n sage: p1 != q2 and q2 != p1\n True\n sage: p2 != q1 and q1 != p2\n True\n sage: p2 != q2 and q2 != p2\n True\n sage: q1 != q2 and q2 != q1\n True\n\n ::\n\n sage: p1 = iet.GeneralizedPermutation('a a','b b',alphabet='ab')\n sage: p2 = iet.GeneralizedPermutation('a a','b b',alphabet='ba')\n sage: q1 = iet.GeneralizedPermutation('b b','a a',alphabet='ab')\n sage: q2 = iet.GeneralizedPermutation('b b','a a',alphabet='ba')\n sage: p1 != p2 or p2 != p1\n True\n sage: p1 != q1 or q1 != p1\n True\n sage: p1 != q2 or q2 != p1\n True\n sage: p2 != q1 or q1 != p2\n True\n sage: p2 != q2 or q2 != p2\n True\n sage: q1 != q2 or q2 != q1\n True\n\n ::\n\n sage: p = iet.GeneralizedPermutation('a b b', 'c c a', reduced = True)\n sage: q = iet.GeneralizedPermutation('b b a', 'c c a', reduced = True)\n sage: r = iet.GeneralizedPermutation('i j j', 'k k i', reduced = True)\n sage: p != q\n True\n sage: p != r\n False\n\n ::\n\n sage: p = iet.Permutation('a b','a b',reduced=True,flips='a')\n sage: q = copy(p)\n sage: q.alphabet([0,1])\n sage: p != q\n False\n sage: l0 = ['a b','a b']\n sage: l1 = ['a b','b a']\n sage: l2 = ['b a', 'a b']\n sage: p0 = iet.Permutation(l0, reduced=True, flips='ab')\n sage: p1 = iet.Permutation(l1, reduced=True, flips='a')\n sage: p2 = iet.Permutation(l2, reduced=True, flips='b')\n sage: p3 = iet.Permutation(l1, reduced=True, flips='ab')\n sage: p4 = iet.Permutation(l2 ,reduced=True,flips='ab')\n sage: p0 != p1 and p0 != p2 and p0 != p3 and p0 != p4\n True\n sage: p1 != p2 or p3 != p4\n False\n sage: p1 != p3 and p1 != p4 and p2 != p3 and p2 != p4\n True\n\n ::\n\n sage: a0 = [0,0,1]\n sage: a1 = [1,2,2]\n sage: p = iet.GeneralizedPermutation(a0,a1,reduced=True,flips=[0])\n sage: q = copy(p)\n sage: q.alphabet(\"abc\")\n sage: p != q\n False\n sage: b0 = [1,0,0]\n sage: b1 = [2,2,1]\n sage: r = iet.GeneralizedPermutation(b0,b1,reduced=True,flips=[0])\n sage: p != r and q != r\n True\n\n ::\n\n sage: p1 = iet.Permutation('a b c','c b a',flips='a')\n sage: p2 = iet.Permutation('a b c','c b a',flips='b')\n sage: p3 = iet.Permutation('d e f','f e d',flips='d')\n sage: p1 != p1 or p2 != p2 or p3 != p3\n False\n sage: p1 != p2\n True\n sage: p1 != p3\n True\n sage: p1.reduced() != p3.reduced()\n False\n \"\"\"\n return type(self) == type(other) and \\\n self._twin == other._twin and \\\n self._labels == other._labels and \\\n self._flips == other._flips and \\\n (self._labels is None or self._alphabet == other._alphabet)\n\n def __lt__(self, other):\n r\"\"\"\n Defines a natural lexicographic order.\n\n TESTS::\n\n sage: from surface_dynamics import *\n\n sage: p = iet.GeneralizedPermutation('a b','a b',reduced=True)\n sage: q = copy(p)\n sage: q.alphabet([0,1])\n sage: p == q\n True\n sage: p0 = iet.GeneralizedPermutation('a b', 'a b', reduced=True)\n sage: p1 = iet.GeneralizedPermutation('a b', 'b a', reduced=True)\n sage: p0 < p1 and p1 > p0\n True\n sage: q0 = iet.GeneralizedPermutation('a b c','a b c',reduced=True)\n sage: q1 = iet.GeneralizedPermutation('a b c','a c b',reduced=True)\n sage: q2 = iet.GeneralizedPermutation('a b c','b a c',reduced=True)\n sage: q3 = iet.GeneralizedPermutation('a b c','c a b',reduced=True)\n sage: q4 = iet.GeneralizedPermutation('a b c','b c a',reduced=True)\n sage: q5 = iet.GeneralizedPermutation('a b c','c b a',reduced=True)\n sage: p0 < q0 and q0 > p0 and p1 < q0 and q0 > p1\n True\n sage: q0 < q1 and q1 > q0\n True\n sage: q1 < q2 and q2 > q1\n True\n sage: q2 < q3 and q3 > q2\n True\n sage: q3 < q4 and q4 > q3\n True\n sage: q4 < q5 and q5 > q4\n True\n\n sage: p0 = iet.Permutation('1 2', '1 2')\n sage: p1 = iet.Permutation('1 2', '2 1')\n sage: p0 != p0\n False\n sage: (p0 == p0) and (p0 < p1)\n True\n sage: (p1 > p0) and (p1 == p1)\n True\n\n sage: p0 = iet.GeneralizedPermutation('0 0','1 1 2 2')\n sage: p1 = iet.GeneralizedPermutation('0 0','1 2 1 2')\n sage: p2 = iet.GeneralizedPermutation('0 0','1 2 2 1')\n sage: p3 = iet.GeneralizedPermutation('0 0 1 1','2 2')\n sage: p4 = iet.GeneralizedPermutation('0 0 1','1 2 2')\n sage: p5 = iet.GeneralizedPermutation('0 1 0 1','2 2')\n sage: p6 = iet.GeneralizedPermutation('0 1 1 0','2 2')\n sage: p0 == p0 and p0 < p1 and p0 < p2 and p0 < p3 and p0 < p4\n True\n sage: p0 < p5 and p0 < p6 and p1 < p2 and p1 < p3 and p1 < p4\n True\n sage: p1 < p5 and p1 < p6 and p2 < p3 and p2 < p4 and p2 < p5\n True\n sage: p2 < p6 and p3 < p4 and p3 < p5 and p3 < p6 and p4 < p5\n True\n sage: p4 < p6 and p5 < p6 and p0 == p0 and p1 == p1 and p2 == p2\n True\n sage: p3 == p3 and p4 == p4 and p5 == p5 and p6 == p6\n True\n\n sage: p = iet.Permutation('a b','a b',reduced=True,flips='a')\n sage: q = copy(p)\n sage: q.alphabet([0,1])\n sage: p == q\n True\n sage: l0 = ['a b','a b']\n sage: l1 = ['a b','b a']\n sage: p1 = iet.Permutation(l1,reduced=True, flips='b')\n sage: p2 = iet.Permutation(l1,reduced=True, flips='a')\n sage: p3 = iet.Permutation(l1,reduced=True, flips='ab')\n sage: p2 > p3 and p3 < p2\n True\n sage: p1 > p2 and p2 < p1\n True\n sage: p1 > p3 and p3 < p1\n True\n sage: q1 = iet.Permutation(l0, reduced=True, flips='a')\n sage: q2 = iet.Permutation(l0, reduced=True, flips='b')\n sage: q3 = iet.Permutation(l0, reduced=True, flips='ab')\n sage: q2 > q1 and q2 > q3 and q1 < q2 and q3 < q2\n True\n sage: q1 > q3\n True\n sage: q3 < q1\n True\n sage: r = iet.Permutation('a b c','a b c', reduced=True, flips='a')\n sage: r > p1 and r > p2 and r > p3\n True\n sage: p1 < r and p2 < r and p3 < r\n True\n \"\"\"\n if type(self) != type(other):\n raise TypeError(\"Permutations must be of the same type\")\n\n if len(self) < len(other):\n return True\n elif len(self) > len(other):\n return False\n\n if self._twin < other._twin:\n return True\n elif self._twin > other._twin:\n return False\n\n if self._labels is not None:\n if self._labels < other._labels:\n return True\n elif self._labels > other._labels:\n return False\n\n if self._flips is not None:\n if self._flips < other._flips:\n return True\n elif self._flips > other._flips:\n return False\n\n # equality\n return False\n\n def _check(self):\n r\"\"\"\n TESTS::\n\n sage: from surface_dynamics import *\n sage: p = iet.Permutation('a b c d', 'd a c b', flips=['a','b'])\n sage: p._check()\n \"\"\"\n if set(self.letters()) != set().union(*self.list()):\n raise RuntimeError(\"letters are bad\")\n\n for i in range(2):\n for p in range(self.length(i)):\n j,q = self.twin(i,p)\n if self.twin(j,q) != (i,p):\n raise RuntimeError(\"self.twin is not an involution: i={} p={} j={} q={}\".format(i,p,j,q))\n if self[i][p] != self[j][q]:\n raise RuntimeError(\"uncoherent getitem i={} p={} j={} q={}\".format(i,p,j,q))\n if self._labels is not None:\n if self._labels[i][p] != self._labels[j][q]:\n raise RuntimeError(\"self._labels wrong i={} p={} j={} q={}\".format(i,p,j,q))\n if self._flips is not None:\n if self._flips[i][p] != self._flips[j][q]:\n raise RuntimeError(\"self._flips wrong i={} p={} j={} q={}\".format(i,p,j,q))\n\n def letters(self):\n r\"\"\"\n Returns the list of letters of the alphabet used for representation.\n\n The letters used are not necessarily the whole alphabet (for example if\n the alphabet is infinite).\n\n OUTPUT: a list of labels\n\n EXAMPLES::\n\n sage: from surface_dynamics import *\n\n sage: p = iet.Permutation([1,2],[2,1])\n sage: p.alphabet(Alphabet(name=\"NN\"))\n sage: p\n 0 1\n 1 0\n sage: p.letters()\n [0, 1]\n\n sage: p = iet.GeneralizedPermutation('a a b','b c c')\n sage: p.letters()\n ['a', 'b', 'c']\n sage: p.alphabet(range(10))\n sage: p.letters()\n [0, 1, 2]\n sage: p._remove_interval(0, 2)\n sage: p.letters()\n [0, 2]\n\n sage: p = iet.GeneralizedPermutation('a a b', 'b c c', reduced=True)\n sage: p.letters()\n ['a', 'b', 'c']\n\n For permutations with flips, the letters appear as pairs made of an element\n of the alphabet and the flip::\n\n sage: p = iet.Permutation('A B C D', 'D C A B', flips='AC')\n sage: p.letters()\n ['A', 'B', 'C', 'D']\n\n sage: p = iet.GeneralizedPermutation('A A B', 'B C C', flips='B')\n sage: p.letters()\n ['A', 'B', 'C']\n \"\"\"\n unrank = self._alphabet.unrank\n if self._labels is not None:\n labels = set(self._labels[0]).union(self._labels[1])\n return [unrank(l) for l in sorted(labels)]\n else:\n return [unrank(i) for i in range(len(self))]\n\n def _repr_(self):\n r\"\"\"\n Representation method of self.\n\n Apply the function str to _repr_type(_repr_options) if _repr_type is\n callable and _repr_type else.\n\n TESTS::\n\n sage: from surface_dynamics import *\n\n sage: p = iet.Permutation('a b c','c b a')\n sage: p._repr_type = 'str'\n sage: p._repr_options = ('\\n',)\n sage: p #indirect doctest\n a b c\n c b a\n sage: p._repr_options = (' / ',)\n sage: p #indirect doctest\n a b c / c b a\n\n ::\n\n sage: p._repr_type = '_twin'\n sage: p #indirect doctest\n [[2, 1, 0], [2, 1, 0]]\n \"\"\"\n if self._repr_type is None:\n return ''\n\n elif self._repr_type == 'reduced':\n return ''.join(map(str,self[1]))\n\n else:\n f = getattr(self, self._repr_type)\n if callable(f):\n return str(f(*self._repr_options))\n else:\n return str(f)\n\n def __hash__(self):\n r\"\"\"\n TESTS::\n\n sage: from surface_dynamics import *\n\n sage: p = iet.Permutation('a b c', 'c b a')\n sage: q = iet.Permutation('a b c', 'c b a', flips=['a'])\n sage: r = iet.Permutation('a b c', 'c b a', reduced=True)\n sage: s = iet.Permutation('a b c', 'c b a', flips=['a'], reduced=True)\n sage: len(set([hash(p), hash(q), hash(r), hash(s)]))\n 4\n\n sage: P = [iet.Permutation(t, b, flips=f, reduced=False) \\\n ....: for t in ['a b', 'b a'] \\\n ....: for b in ['a b', 'b a'] \\\n ....: for f in [None, 'a', 'b', 'ab']]\n sage: P.extend(iet.Permutation('a b', b, flips=f, reduced=True) \\\n ....: for b in ['a b', 'b a'] \\\n ....: for f in [None, 'a', 'b', 'ab'])\n sage: len(set(hash(x) for x in P))\n 24\n \"\"\"\n h = hash(tuple(self._twin[0] + self._twin[1]))\n if self._labels is not None:\n h *= 7461864723258187525\n h ^= hash(tuple(self._labels[0] + self._labels[1]))\n h += hash(tuple(self.letters()))\n if self._flips is not None:\n h *= 5566797465546889505\n h ^= hash(tuple(self._flips[0] + self._flips[1]))\n return h\n\n def str(self, sep= \"\\n\", align=None):\n r\"\"\"\n A string representation of the generalized permutation.\n\n INPUT:\n\n - ``sep`` - (default: '\\n') a separator for the two intervals\n\n OUTPUT:\n\n string -- the string that represents the permutation\n\n\n EXAMPLES::\n\n sage: from surface_dynamics import *\n\n For permutations of iet::\n\n sage: p = iet.Permutation('a b c','c b a')\n sage: p.str()\n 'a b c\\nc b a'\n sage: p.str(sep=' | ')\n 'a b c | c b a'\n\n The permutation can be rebuilt from the standard string::\n\n sage: p == iet.Permutation(p.str())\n True\n\n For permutations of li::\n\n sage: p = iet.GeneralizedPermutation('a b b','c c a')\n sage: p.str()\n 'a b b\\nc c a'\n sage: p.str(sep=' | ')\n 'a b b | c c a'\n\n sage: iet.GeneralizedPermutation([0,0], [1,2,3,2,1,3])\n 0 0\n 1 2 3 2 1 3\n sage: iet.GeneralizedPermutation([0,1,2,1,0,2], [3,3])\n 0 1 2 1 0 2\n 3 3\n\n Again, the generalized permutation can be rebuilt from the standard string::\n\n sage: p == iet.GeneralizedPermutation(p.str())\n True\n\n With flips::\n\n sage: p = iet.GeneralizedPermutation('a a','b b',flips='a')\n sage: print(p.str())\n -a -a\n b b\n sage: print(p.str('/'))\n -a -a/ b b\n\n Alignment with alphabet of different sizes::\n\n sage: p = iet.Permutation('aa b ccc d', 'd b ccc aa')\n sage: print(p.str())\n aa b ccc d\n d b ccc aa\n sage: print(p.str(align='left'))\n aa b ccc d\n d b ccc aa\n sage: print(p.str(align='right'))\n aa b ccc d\n d b ccc aa\n\n sage: p = iet.GeneralizedPermutation('aa fff b ccc b fff d', 'eee d eee ccc aa')\n sage: print(p.str())\n aa fff b ccc b fff d\n eee d eee ccc aa\n sage: print(p.str(align='left'))\n aa fff b ccc b fff d\n eee d eee ccc aa\n sage: print(p.str(align='right'))\n aa fff b ccc b fff d\n eee d eee ccc aa\n \"\"\"\n s = []\n if self._flips is None:\n l0, l1 = self.list()\n formatter = str\n else:\n l0, l1 = self.list(flips=True)\n formatter = labelize_flip\n\n n = min(len(l0), len(l1))\n for i in range(n):\n l0[i] = s0 = formatter(l0[i])\n l1[i] = s1 = formatter(l1[i])\n if align is None:\n continue\n elif len(s0) < len(s1):\n if align == 'right':\n l0[i] = ' ' * (len(s1) - len(s0)) + l0[i]\n elif align == 'left':\n l0[i] = l0[i] + ' ' * (len(s1) - len(s0))\n elif len(s0) > len(s1):\n if align == 'right':\n l1[i] = ' ' * (len(s0) - len(s1)) + l1[i]\n elif align == 'left':\n l1[i] = l1[i] + ' ' * (len(s0) - len(s1))\n for i in range(n, len(l0)):\n l0[i] = formatter(l0[i])\n for i in range(n, len(l1)):\n l1[i] = formatter(l1[i])\n\n return sep.join([' '.join(l0), ' '.join(l1)])\n\n def flips(self):\n r\"\"\"\n Returns the list of flips.\n\n If the permutation is not a flipped permutations then ``None`` is returned.\n\n EXAMPLES::\n\n sage: from surface_dynamics import *\n\n sage: iet.Permutation('a b c', 'c b a').flips()\n []\n sage: iet.Permutation('a b c', 'c b a', flips='ac').flips()\n ['a', 'c']\n sage: iet.GeneralizedPermutation('a a', 'b b', flips='a').flips()\n ['a']\n sage: iet.GeneralizedPermutation('a a','b b', flips='b', reduced=True).flips()\n ['b']\n \"\"\"\n if self._flips is None:\n return []\n\n res = []\n l = self.list(flips=False)\n letters = []\n for i,f in enumerate(self._flips[0]):\n if f == -1 and l[0][i] not in letters:\n res.append(l[0][i])\n letters.append(l[0][i])\n for i,f in enumerate(self._flips[1]):\n if f == -1 and l[1][i] not in letters:\n res.append(l[1][i])\n letters.append(l[1][i])\n return letters\n\n def __copy__(self) :\n r\"\"\"\n Returns a copy of self.\n\n EXAMPLES::\n\n sage: from surface_dynamics import *\n\n sage: p = iet.Permutation('a b c', 'c b a', reduced=True)\n sage: q = copy(p)\n sage: p == q\n True\n sage: p is q\n False\n sage: p = iet.GeneralizedPermutation('a b b','c c a', reduced=True)\n sage: q = copy(p)\n sage: p == q\n True\n sage: p is q\n False\n\n TESTS::\n\n sage: p1 = iet.Permutation('a b c', 'c b a', reduced=True)\n sage: p2 = iet.Permutation('a b c', 'c b a', reduced=False)\n sage: p3 = iet.Permutation('a b c', 'c b a', flips='a', reduced=True)\n sage: p4 = iet.Permutation('a b c', 'c b a', flips='a', reduced=False)\n\n sage: p5 = iet.GeneralizedPermutation('a a b', 'b c c', reduced=True)\n sage: p6 = iet.GeneralizedPermutation('a a b', 'b c c', reduced=False)\n sage: p7 = iet.GeneralizedPermutation('a a b', 'b c c', flips='a', reduced=True)\n sage: p8 = iet.GeneralizedPermutation('a a b', 'b c c', flips='a', reduced=False)\n\n sage: for p in (p1,p2,p3,p4,p5,p6,p7,p8):\n ....: q = p.__copy__()\n ....: assert type(p) is type(q)\n ....: assert p == q\n \"\"\"\n q = self.__class__.__new__(self.__class__)\n\n q._twin = [self._twin[0][:], self._twin[1][:]]\n q._alphabet = self._alphabet\n q._repr_type = self._repr_type\n q._repr_options = self._repr_options\n\n if self._labels is not None:\n q._labels = [self._labels[0][:], self._labels[1][:]]\n\n if self._flips is not None:\n q._flips = [self._flips[0][:], self._flips[1][:]]\n\n return q\n\n _repr_type = 'str'\n _repr_options = (\"\\n\",)\n\n def __len__(self):\n r\"\"\"\n TESTS::\n\n sage: from surface_dynamics import *\n\n sage: p = iet.Permutation('a b','b a',reduced=True)\n sage: len(p)\n 2\n sage: p = iet.Permutation('a b','b a',reduced=False)\n sage: len(p)\n 2\n sage: p = iet.GeneralizedPermutation('a a b','b c c',reduced=True)\n sage: len(p)\n 3\n sage: p = iet.GeneralizedPermutation('a a b','b c c',reduced=False)\n sage: len(p)\n 3\n sage: p = iet.GeneralizedPermutation('a a','b b c c',reduced=True)\n sage: len(p)\n 3\n sage: p = iet.GeneralizedPermutation('a a','b b c c',reduced=False)\n sage: len(p)\n 3\n \"\"\"\n return (len(self._twin[0]) + len(self._twin[1])) // 2\n\n def length_top(self):\n r\"\"\"\n Returns the number of intervals in the top segment.\n\n OUTPUT:\n\n integer -- the length of the top segment\n\n EXAMPLES::\n\n sage: from surface_dynamics import *\n\n sage: p = iet.Permutation('a b c','c b a', reduced=True)\n sage: p.length_top()\n 3\n sage: p = iet.Permutation('a b c','c b a', reduced=False)\n sage: p.length_top()\n 3\n sage: p = iet.GeneralizedPermutation('a a b','c d c b d',reduced=True)\n sage: p.length_top()\n 3\n sage: p = iet.GeneralizedPermutation('a a b','c d c d b',reduced=False)\n sage: p.length_top()\n 3\n sage: p = iet.GeneralizedPermutation('a b c b d c d', 'e a e',reduced=True)\n sage: p.length_top()\n 7\n sage: p = iet.GeneralizedPermutation('a b c d b c d', 'e a e', reduced=False)\n sage: p.length_top()\n 7\n \"\"\"\n return len(self._twin[0])\n\n def length_bottom(self):\n r\"\"\"\n Returns the number of intervals in the bottom segment.\n\n OUTPUT:\n\n integer -- the length of the bottom segment\n\n EXAMPLES::\n\n sage: from surface_dynamics import *\n\n sage: p = iet.Permutation('a b c','c b a',reduced=True)\n sage: p.length_bottom()\n 3\n sage: p = iet.Permutation('a b c','c b a',reduced=False)\n sage: p.length_bottom()\n 3\n sage: p = iet.GeneralizedPermutation('a a b','c d c b d',reduced=True)\n sage: p.length_bottom()\n 5\n sage: p = iet.GeneralizedPermutation('a a b','c d c b d',reduced=False)\n sage: p.length_bottom()\n 5\n \"\"\"\n return len(self._twin[1])\n\n def length(self, interval=None):\n r\"\"\"\n Returns the 2-uple of lengths.\n\n p.length() is identical to (p.length_top(), p.length_bottom())\n If an interval is specified, it returns the length of the specified\n interval.\n\n INPUT:\n\n - ``interval`` - None, 'top' (or 't' or 0) or 'bottom' (or 'b' or 1)\n\n OUTPUT:\n\n integer or 2-uple of integers -- the corresponding lengths\n\n EXAMPLES::\n\n sage: from surface_dynamics import *\n\n sage: p = iet.Permutation('a b c','c b a',reduced=False)\n sage: p.length()\n (3, 3)\n sage: p = iet.Permutation('a b c','c b a',reduced=True)\n sage: p.length()\n (3, 3)\n\n sage: p = iet.GeneralizedPermutation('a a b','c d c b d',reduced=False)\n sage: p.length()\n (3, 5)\n sage: p = iet.GeneralizedPermutation('a a b','c d c b d',reduced=True)\n sage: p.length()\n (3, 5)\n \"\"\"\n if interval is None :\n return len(self._twin[0]),len(self._twin[1])\n else :\n interval = interval_conversion(interval)\n return len(self._twin[interval])\n\n def _set_alphabet(self, alphabet):\n r\"\"\"\n Sets the alphabet of self.\n\n TESTS:\n\n sage: from surface_dynamics import *\n\n sage: p = iet.GeneralizedPermutation('a a','b b')\n sage: p.alphabet([0,1]) #indirect doctest\n sage: p.alphabet() == Alphabet([0,1])\n True\n sage: p\n 0 0\n 1 1\n sage: p.alphabet(\"cd\") #indirect doctest\n sage: p.alphabet() == Alphabet(['c','d'])\n True\n sage: p\n c c\n d d\n\n Tests with reduced permutations::\n\n sage: p = iet.Permutation('a b','b a',reduced=True)\n sage: p.alphabet([0,1]) #indirect doctest\n sage: p.alphabet() == Alphabet([0,1])\n True\n sage: p\n 0 1\n 1 0\n sage: p.alphabet(\"cd\") #indirect doctest\n sage: p.alphabet() == Alphabet(['c','d'])\n True\n sage: p\n c d\n d c\n\n ::\n\n sage: p = iet.GeneralizedPermutation('a a','b b',reduced=True)\n sage: p.alphabet([0,1]) #indirect doctest\n sage: p.alphabet() == Alphabet([0,1])\n True\n sage: p\n 0 0\n 1 1\n sage: p.alphabet(\"cd\") #indirect doctest\n sage: p.alphabet() == Alphabet(['c','d'])\n True\n sage: p\n c c\n d d\n \"\"\"\n from sage.combinat.words.alphabet import build_alphabet\n alphabet = build_alphabet(alphabet)\n if alphabet.cardinality() < len(self):\n raise ValueError(\"not enough letters in alphabet\")\n self._alphabet = alphabet\n\n def alphabet(self, data=None):\n r\"\"\"\n Manages the alphabet of self.\n\n If there is no argument, the method returns the alphabet used. If the\n argument could be converted to an alphabet, this alphabet will be used.\n\n INPUT:\n\n - ``data`` - None or something that could be converted to an alphabet\n\n\n OUTPUT:\n\n - either None or the current alphabet\n\n\n EXAMPLES::\n\n sage: from surface_dynamics import *\n\n sage: p = iet.Permutation('a b','a b')\n sage: p.alphabet([0,1])\n sage: p.alphabet() == Alphabet([0,1])\n True\n sage: p\n 0 1\n 0 1\n sage: p.alphabet(\"cd\")\n sage: p.alphabet() == Alphabet(['c','d'])\n True\n sage: p\n c d\n c d\n \"\"\"\n if data is None:\n return self._alphabet\n else:\n self._set_alphabet(data)\n\n def left_right_inverse(self, inplace=False):\n r\"\"\"\n Return the left-right inverse.\n\n The left-right inverse of a permutation, is the permutation obtained by\n reversing the order of the underlying ordering.\n\n You can also use the shorter .lr_inverse()\n\n There are two other symmetries of permutation which are accessible via\n the methods\n :meth:`Permutation.top_bottom_inverse` and\n :meth:`Permutation.symmetric`.\n\n OUTPUT: a permutation\n\n EXAMPLES::\n\n sage: from surface_dynamics import *\n\n For labelled permutations::\n\n sage: p = iet.Permutation('a b c','c a b')\n sage: p.left_right_inverse()\n c b a\n b a c\n sage: p = iet.Permutation('a b c d','c d a b')\n sage: p.left_right_inverse()\n d c b a\n b a d c\n\n for reduced permutations::\n\n sage: p = iet.Permutation('a b c','c a b',reduced=True)\n sage: p.left_right_inverse()\n a b c\n b c a\n sage: p = iet.Permutation('a b c d','c d a b',reduced=True)\n sage: p.left_right_inverse()\n a b c d\n c d a b\n\n for labelled quadratic permutations::\n\n sage: p = iet.GeneralizedPermutation('a a','b b c c')\n sage: p.left_right_inverse()\n a a\n c c b b\n\n for reduced quadratic permutations::\n\n sage: p = iet.GeneralizedPermutation('a a','b b c c',reduced=True)\n sage: p.left_right_inverse() == p\n True\n \"\"\"\n res = self if inplace else copy(self)\n res._reversed_twin()\n\n if res._flips is not None:\n res._flips[0].reverse()\n res._flips[1].reverse()\n\n if res._labels is not None:\n res._labels[0].reverse()\n res._labels[1].reverse()\n\n return res\n\n lr_inverse = left_right_inverse\n vertical_inverse = left_right_inverse\n\n def top_bottom_inverse(self, inplace=False):\n r\"\"\"\n Return the top-bottom inverse.\n\n You can use also use the shorter .tb_inverse().\n\n There are two other symmetries of permutation which are accessible via\n the methods\n :meth:`Permutation.left_right_inverse` and\n :meth:`Permutation.symmetric`.\n\n OUTPUT: a permutation\n\n EXAMPLES::\n\n sage: from surface_dynamics import *\n\n sage: p = iet.Permutation('a b','b a')\n sage: p.top_bottom_inverse()\n b a\n a b\n sage: p = iet.Permutation('a b','b a',reduced=True)\n sage: p.top_bottom_inverse() == p\n True\n\n ::\n\n sage: p = iet.Permutation('a b c d','c d a b')\n sage: p.top_bottom_inverse()\n c d a b\n a b c d\n\n TESTS::\n\n sage: from surface_dynamics import *\n\n sage: p = iet.Permutation('a b','a b')\n sage: p == p.top_bottom_inverse()\n True\n sage: p is p.top_bottom_inverse()\n False\n sage: p = iet.GeneralizedPermutation('a a','b b',reduced=True)\n sage: p == p.top_bottom_inverse()\n True\n sage: p is p.top_bottom_inverse()\n False\n \"\"\"\n res = self if inplace else copy(self)\n res._inversed_twin()\n\n if res._flips is not None:\n res._flips = [res._flips[1], res._flips[0]]\n\n if res._labels is not None:\n res._labels = [res._labels[1], res._labels[0]]\n\n return res\n\n tb_inverse = top_bottom_inverse\n horizontal_inverse = top_bottom_inverse\n\n def symmetric(self):\n r\"\"\"\n Returns the symmetric permutation.\n\n The symmetric permutation is the composition of the top-bottom\n inversion and the left-right inversion (which are geometrically\n orientation reversing).\n\n There are two other symmetries of permutation which are accessible via\n the methods\n :meth:`Permutation.left_right_inverse` and\n :meth:`Permutation.top_bottom_inverse`.\n\n OUTPUT: a permutation\n\n EXAMPLES::\n\n sage: from surface_dynamics import *\n\n sage: p = iet.Permutation('a b c','c b a',reduced=True)\n sage: p.symmetric() == p\n True\n sage: p = iet.Permutation('a b c d','c a d b',reduced=True)\n sage: q = p.symmetric()\n sage: q\n a b c d\n b d a c\n sage: q1 = p.tb_inverse().lr_inverse()\n sage: q2 = p.lr_inverse().tb_inverse()\n sage: q == q1 and q == q2\n True\n\n It works for any type of permutations::\n\n sage: p = iet.GeneralizedPermutation('a b b','c c a',flips='ab')\n sage: p\n -a -b -b\n c c -a\n sage: p.symmetric()\n -a c c\n -b -b -a\n\n TESTS::\n\n sage: from surface_dynamics import *\n\n sage: p = iet.GeneralizedPermutation('a a b','b c c',reduced=True)\n sage: q = p.symmetric()\n sage: q1 = p.tb_inverse().lr_inverse()\n sage: q2 = p.lr_inverse().tb_inverse()\n sage: q == q1 and q == q2\n True\n \"\"\"\n res = copy(self)\n res._inversed_twin()\n res._reversed_twin()\n\n if res._flips is not None:\n res._flips[0].reverse()\n res._flips[1].reverse()\n res._flips.reverse()\n\n if res._labels is not None:\n res._labels[0].reverse()\n res._labels[1].reverse()\n res._labels.reverse()\n\n return res\n\n def _canonical_signs(self):\n r\"\"\"\n Return label positions and orientation in some compatible way.\n\n OUTPUT:\n\n - a dictionary whose keys are the labels of this permutation and the\n value associated to a label `a` is a pair `((ip,jp), (im,jm))` made\n of the two positions of `a`.\n\n - a list of two lists that give the signs of each subinterval\n\n EXAMPLES::\n\n sage: from surface_dynamics import *\n\n sage: p = iet.GeneralizedPermutation('d a e a b b','e c c d')\n sage: twins, orientation = p._canonical_signs()\n sage: twins\n {'a': [(0, 1), (0, 3)],\n 'b': [(0, 4), (0, 5)],\n 'c': [(1, 2), (1, 1)],\n 'd': [(0, 0), (1, 3)],\n 'e': [(0, 2), (1, 0)]}\n sage: orientation\n [[1, 1, 1, -1, 1, -1], [-1, -1, 1, -1]]\n\n sage: for a, ((ip,jp),(im,jm)) in twins.items():\n ....: assert p[ip][jp] == p[im][jm] == a\n ....: assert orientation[ip][jp] == +1\n ....: assert orientation[im][jm] == -1\n\n sage: p = iet.Permutation('a b c', 'c b a', flips='ac')\n sage: twins, orientation = p._canonical_signs()\n sage: twins\n {'a': [(0, 0), (1, 2)],\n 'b': [(0, 1), (1, 1)],\n 'c': [(0, 2), (1, 0)]}\n sage: orientation\n [[1, 1, 1], [1, -1, 1]]\n\n sage: p = iet.GeneralizedPermutation('a a', 'b b c c', flips='b')\n sage: twins, orientation = p._canonical_signs()\n sage: twins\n {'a': [(0, 0), (0, 1)],\n 'b': [(1, 1), (1, 0)],\n 'c': [(1, 3), (1, 2)]}\n sage: orientation\n [[1, -1], [1, 1, -1, 1]]\n \"\"\"\n flips = self._flips\n letters = set(self.letters())\n\n label_to_twins = {}\n sign_top = []\n sign_bot = []\n for i,a in enumerate(self[0]):\n if a in letters: # first time seen\n sign_top.append(1)\n label_to_twins[a] = [(0,i)]\n letters.remove(a)\n else: # already seen\n if flips is not None and flips[0][i] == -1:\n sign_top.append(1)\n else:\n sign_top.append(-1)\n label_to_twins[a].append((0,i))\n\n n = len(self[1])\n for i,a in enumerate(reversed(self[1])):\n i = n - 1 - i\n if a in letters: # first time seen\n sign_bot.append(1)\n letters.remove(a)\n label_to_twins[a] = [(1,i)]\n else: # already seen\n if flips is not None and flips[1][i] == -1:\n sign_bot.append(1)\n else:\n sign_bot.append(-1)\n label_to_twins[a].append((1,i))\n sign_bot.reverse()\n\n return (label_to_twins, [sign_top, sign_bot])\n\n def interval_diagram(self, glue_ends=True, sign=False):\n r\"\"\"\n Return the interval diagram of self.\n\n The result is in random order.\n\n INPUT:\n\n - ``glue_ends`` - bool (default: True)\n\n - ``sign`` - bool (default: False)\n\n EXAMPLES::\n\n sage: from surface_dynamics import *\n\n sage: p = iet.Permutation('a b c','c b a')\n sage: p.interval_diagram()\n [['b', ('c', 'a')], ['b', ('c', 'a')]]\n\n sage: p = iet.Permutation('a b c','c a b')\n sage: p.interval_diagram()\n [['a', 'b'], [('c', 'b'), ('c', 'a')]]\n\n sage: p = iet.GeneralizedPermutation('a a','b b c c')\n sage: p.interval_diagram()\n [['a'], [('b', 'a', 'c')], ['b'], ['c']]\n\n sage: p = iet.GeneralizedPermutation('a a b b','c c')\n sage: p.interval_diagram()\n [['a'], [('b', 'c', 'a')], ['b'], ['c']]\n sage: p.interval_diagram(sign=True)\n [[('a', -1)], [(('b', 1), ('c', 1), ('a', 1))], [('b', -1)], [('c', -1)]]\n\n sage: p = iet.GeneralizedPermutation((0,1,0,2),(3,2,4,1,4,3))\n sage: p.interval_diagram()\n [[0, 1, 4, 1], [2, 3, 4, (2, 3, 0)]]\n sage: p.interval_diagram(sign=True)\n [[(0, -1), (1, 1), (4, -1), (1, -1)],\n [(2, 1), (3, -1), (4, 1), ((2, -1), (3, 1), (0, 1))]]\n\n sage: p = iet.GeneralizedPermutation('a b c d b', 'e d f e a f c', flips='bdf')\n sage: p.interval_diagram()\n [['a', 'b', 'd', 'e', 'f', 'c', ('b', 'c'), 'd', 'f'], [('e', 'a')]]\n\n TESTS::\n\n sage: from surface_dynamics import *\n\n sage: p = iet.GeneralizedPermutation('0 1 2 3 2','4 3 4 1 0')\n sage: p.interval_diagram(sign=True)\n [[('1', 1), (('4', 1), ('0', 1)), ('1', -1), (('2', 1), ('0', -1))],\n [('2', -1), ('3', 1), ('4', -1), ('3', -1)]]\n\n sage: p = iet.Permutation('a b c', 'c b a', flips='a')\n sage: p.interval_diagram(glue_ends=False, sign=True)\n [[('a', -1), ('b', -1), ('c', 1), ('a', 1), ('c', -1), ('b', 1)]]\n sage: p.interval_diagram(glue_ends=True, sign=False)\n [['a', 'b', ('c', 'a', 'c'), 'b']]\n\n sage: iet.Permutation('a b c', 'c b a', flips='b').interval_diagram(glue_ends=False, sign=True)\n [[('a', -1), ('b', 1), ('a', 1), ('c', 1), ('b', -1), ('c', -1)]]\n sage: iet.Permutation('a b c', 'c b a', flips='c').interval_diagram(glue_ends=False, sign=True)\n [[('a', -1), ('b', 1), ('c', 1), ('b', -1), ('a', 1), ('c', -1)]]\n\n sage: iet.Permutation('a b c', 'c b a', flips='bc').interval_diagram(glue_ends=False, sign=True)\n [[('a', -1), ('b', 1), ('a', 1), ('c', -1)], [('b', -1), ('c', 1)]]\n\n sage: iet.Permutation('a b c', 'c b a', flips='ac').interval_diagram(glue_ends=False, sign=True)\n [[('a', -1), ('b', -1), ('c', 1), ('b', 1)], [('a', 1), ('c', -1)]]\n\n sage: iet.Permutation('a b c', 'c b a', flips='ab').interval_diagram(glue_ends=False, sign=True)\n [[('a', -1), ('b', 1)], [('a', 1), ('c', -1), ('b', -1), ('c', 1)]]\n\n sage: iet.Permutation('a b c', 'c b a', flips='abc').interval_diagram(glue_ends=False, sign=True)\n [[('a', -1), ('b', 1)], [('a', 1), ('c', -1)], [('b', -1), ('c', 1)]]\n \"\"\"\n # NOTE: each interval comes with an orientation (obtained from the\n # method ._canonical_signs(). We label each side of each interval\n # by either +1 or -1 as follows\n #\n # o---------------->--------------o\n # +1 (for source) -1 (for target)\n #\n flips = self._flips\n twin = self.twin_list()\n labels = self.list()\n letters = set((label,j) for label in self.letters() for j in (+1,-1))\n label_to_twins, orientation = self._canonical_signs()\n m0 = len(labels[0])\n m1 = len(labels[1])\n\n singularities = []\n\n just_glued = False # True iff the last elt in singularity is paired\n glued_at_begin = False # True iff the 1st elt in singularity is paired\n flip = 1\n while letters:\n # pick a remaining letter\n try:\n # try picking the minimum\n t = min(letters)\n letters.remove(t)\n label, j = t\n except TypeError:\n # pick a random one\n print('failure')\n label,j = letters.pop()\n (i0,p0),(i1,p1) = label_to_twins[label] # its two positions in the interval\n\n # try to see if one of (i0, p0) fits for anti-clockwise order\n # otherwise start with clockwise direction\n if j == -1:\n if orientation[i0][p0] == -1:\n i,p = i0,p0\n flip = 1\n elif orientation[i1][p1] == -1:\n i,p = i1,p1\n flip = 1\n else:\n i,p = i0,p0\n flip = -1\n else:\n if orientation[i0][p0] == +1:\n i,p = i0,p0\n flip = 1\n elif orientation[i1][p1] == +1:\n i,p = i1,p1\n flip = 1\n else:\n i,p = i0,p0\n flip = -1\n\n\n if sign:\n singularity = [(label,j)]\n else:\n singularity = [label]\n while True:\n i,p = twin[i][p]\n if flips is not None and flips[i][p] == -1:\n flip *= -1\n if i == 0: # twin on top\n p += flip # next interval\n if flip == 1 and p == m0: # at the right end?\n i = 1\n p = m1-1\n elif flip == -1 and p == -1: # at the left end?\n i = 1\n p = 0\n else: # twin on bot\n p -= flip # next interval\n if flip == 1 and p == -1: # at the left end?\n i = 0\n p = 0\n elif flip == -1 and p == m1: # at the right end?\n i = 0\n p = m0 - 1\n\n label = labels[i][p]\n j = flip * orientation[i][p]\n\n\n if (label,j) not in letters:\n if (glue_ends and\n ((i == 1 and p == m1-1 and flip == +1) or (i == 0 and p == 0 and flip == +1) or\n (i == 0 and p == m1-1 and flip == -1) or (i == 1 and p == 0 and flip == -1))):\n sg2 = singularity.pop(0)\n sg1 = singularity.pop(-1)\n if glued_at_begin:\n singularity.append((sg1,) + sg2)\n elif just_glued:\n singularity.append(sg1 + (sg2,))\n else:\n singularity.append((sg1, sg2))\n break\n letters.remove((label,j))\n if (glue_ends and (\n (i == 1 and p == m1-1 and flip == +1) or (i == 0 and p == 0 and flip == 1) or\n (i == 0 and p == m1-1 and flip == -1) or (i == 1 and p == 0 and flip == -1))):\n sg1 = singularity.pop(-1)\n if sign:\n sg2 = (label,j)\n else:\n sg2 = label\n if len(singularity) == 0:\n glued_at_begin = True\n if just_glued:\n singularity.append(sg1 + (sg2,))\n else:\n singularity.append((sg1,sg2))\n just_glued = True\n else:\n if sign:\n singularity.append((label,j))\n else:\n singularity.append(label)\n just_glued = False\n\n singularities.append(singularity)\n just_glued = False\n glued_at_begin = False\n\n return singularities\n\n def _remove_interval(self, i, pos):\n r\"\"\"\n Remove the letter in the interval ``i`` and position ``pos`` (and its\n twin).\n\n TESTS::\n\n sage: from surface_dynamics import *\n\n sage: p = iet.Permutation('a b c d', 'd a b c')\n sage: p._remove_interval(0, 1); p\n a c d\n d a c\n sage: p._check()\n sage: p.twin_list()\n [[(1, 1), (1, 2), (1, 0)], [(0, 2), (0, 0), (0, 1)]]\n sage: p._remove_interval(0, 2); p\n a c\n a c\n sage: p._check()\n sage: p.twin_list()\n [[(1, 0), (1, 1)], [(0, 0), (0, 1)]]\n sage: p._remove_interval(0, 0); p\n c\n c\n sage: p.twin_list()\n [[(1, 0)], [(0, 0)]]\n\n sage: p = iet.Permutation('a b c d', 'd c b a', reduced=True)\n sage: p._remove_interval(0, 1); p\n a b c\n c b a\n sage: p._check()\n sage: p._remove_interval(1, 0); p\n a b\n b a\n sage: p._check()\n\n sage: p = iet.Permutation('a b c d', 'd a c b', flips=['a','b'])\n sage: p._remove_interval(0, 0); p\n -b c d\n d c -b\n sage: p._check()\n sage: p._remove_interval(1, 0); p\n -b c\n c -b\n sage: p._check()\n\n sage: p = iet.Permutation('a b c e d', 'e b d a c')\n sage: p._remove_interval(0, 3); p\n a b c d\n b d a c\n sage: p._check()\n sage: p._remove_interval(1, 3); p\n a b d\n b d a\n sage: p._check()\n sage: p._remove_interval(1, 0); p\n a d\n d a\n sage: p._check()\n\n sage: p = iet.GeneralizedPermutation('a a b c b e d e', 'f c d f g g')\n sage: p._remove_interval(0, 0)\n sage: p._check()\n sage: p._remove_interval(0, 4)\n sage: p._check()\n sage: p._remove_interval(1, 4)\n sage: p._check()\n sage: p\n b c b e e\n f c f\n \"\"\"\n assert i == 0 or i == 1\n assert 0 <= pos < self.length(i)\n\n ii, ppos = self.twin(i, pos)\n if i == ii and pos < ppos:\n pos, ppos = ppos, pos\n\n for j,t in enumerate(self.twin_list()):\n for q,(jj,qq) in enumerate(t):\n dec = (jj == i and qq > pos) + (jj == ii and qq > ppos)\n if dec:\n self._set_twin(j, q, jj, qq - dec)\n\n del self._twin[i][pos]\n del self._twin[ii][ppos]\n\n if self._flips is not None:\n del self._flips[i][pos]\n del self._flips[ii][ppos]\n\n if self._labels is not None:\n del self._labels[i][pos]\n del self._labels[ii][ppos]\n\n def _identify_intervals(self, side):\n r\"\"\"\n Identify the two intervals on the right (if ``side=-1``) or on the left\n (if ``side=0``).\n\n This is needed for the generalized Rauzy induction when the length on\n top and bottom are equal.\n\n The label of the top interval disappears.\n\n EXAMPLES::\n\n sage: from surface_dynamics import *\n\n sage: p = iet.Permutation('a b c', 'c a b')\n sage: p._identify_intervals(-1); p\n a b\n b a\n sage: p._check()\n\n sage: p = iet.Permutation('a b c', 'c b a')\n sage: p._identify_intervals(0); p\n b c\n b c\n sage: p._check()\n\n sage: p = iet.Permutation('a b c', 'c b a')\n sage: p._identify_intervals(0); p\n b c\n b c\n sage: p._check()\n\n sage: p = iet.Permutation('a b c d', 'c a d b')\n sage: p._identify_intervals(-1); p\n a b c\n c a b\n sage: p._check()\n\n sage: p = iet.Permutation('a b c d', 'd a c b')\n sage: p._identify_intervals(-1); p\n a b c\n b a c\n sage: p._check()\n\n sage: p = iet.GeneralizedPermutation('a d e e a b', 'b c c d')\n sage: p._identify_intervals(0); p\n d e e b b\n c c d\n sage: p._check()\n sage: p._identify_intervals(-1); p\n d e e d\n c c\n sage: p._check()\n\n sage: p = iet.GeneralizedPermutation('a b b', 'a c c')\n sage: p._identify_intervals(0); p\n b b\n c c\n sage: p._check()\n \"\"\"\n if self._flips:\n raise ValueError(\"not implemented if there is a flip\")\n\n if side == 0:\n pos0 = pos1 = 0\n elif side == -1:\n pos0 = self.length_top()-1\n pos1 = self.length_bottom()-1\n twin = self.twin(0, pos0)\n if self.twin(0, pos0) != (1, pos1):\n self._move(1, pos1, twin[0], twin[1])\n self._remove_interval(0, pos0)\n\n def cover(self, perms, as_tuple=False):\n r\"\"\"\n Return a covering of this permutation.\n\n INPUT:\n\n - ``perms`` - a list of permutations that describe the gluings\n\n - ``as_tuple`` - whether permutations need to be considered as `1`-based\n (default) or `0`-based.\n\n EXAMPLES::\n\n sage: from surface_dynamics import iet\n sage: p = iet.Permutation('a b', 'b a')\n sage: p.cover(['(1,2)', '(1,3)'])\n Covering of degree 3 of the permutation:\n a b\n b a\n\n sage: p.cover([[1,0,2], [2,1,0]], as_tuple=True)\n Covering of degree 3 of the permutation:\n a b\n b a\n\n sage: p = iet.GeneralizedPermutation('a a b b','c c')\n sage: q = p.cover(['(0,1)', [], [2,1,0]], as_tuple=True)\n sage: q\n Covering of degree 3 of the permutation:\n a a b b\n c c\n sage: q.covering_data('a')\n (1,2)\n sage: q.covering_data('b')\n ()\n sage: q.covering_data('c')\n (1,3)\n \"\"\"\n if len(perms) != len(self):\n raise ValueError(\"wrong number of permutations\")\n\n from surface_dynamics.misc.permutation import perm_init, equalize_perms\n if as_tuple:\n perms = [perm_init(p) for p in perms]\n else:\n try:\n # Trac #28652: Rework the constructor of PermutationGroupElement\n from sage.groups.perm_gps.constructor import PermutationGroupElement\n except ImportError:\n from sage.groups.perm_gps.permgroup_element import PermutationGroupElement\n perms = [PermutationGroupElement(p,check=True) for p in perms]\n perms = [[i-1 for i in p.domain()] for p in perms]\n\n d = equalize_perms(perms)\n from .cover import PermutationCover\n return PermutationCover(self, d, perms)\n\n def regular_cover(self, G, elts):\n r\"\"\"\n Return a regular (or normal) cover of this permutation.\n\n EXAMPLES::\n\n sage: from surface_dynamics import iet\n\n sage: p = iet.Permutation('a b c d', 'd c b a')\n sage: G = SymmetricGroup(4)\n sage: ga = G('(1,2)')\n sage: gb = G('(1,3,4)')\n sage: gc = G('(1,3)')\n sage: gd = G('()')\n sage: pp = p.regular_cover(G, [ga, gb, gc, gd])\n sage: pp\n Regular cover of degree 24 with group Symmetric group of order 4! as a permutation group of the permutation:\n a b c d\n d c b a\n sage: pp.genus()\n 33\n\n Additive groups are converted to multiplicative groups::\n\n sage: p = iet.GeneralizedPermutation('a a b', 'b c c')\n sage: G = Zmod(5)\n sage: p.regular_cover(G, [0, 1, 2])\n Regular cover of degree 5 with group Multiplicative Abelian group isomorphic to C5 of the permutation:\n a a b\n b c c\n \"\"\"\n from .cover import RegularCover\n return RegularCover(self, G, elts)\n\nclass PermutationIET(Permutation):\n def _init_twin(self, a):\n r\"\"\"\n Initializes the twin list.\n\n EXAMPLES::\n\n sage: from surface_dynamics import *\n\n sage: iet.Permutation('a b','b a',reduced=True) #indirect doctest\n a b\n b a\n sage: iet.Permutation('a b c','c a b',reduced=True) #indirect doctest\n a b c\n c a b\n \"\"\"\n if a is None:\n self._twin = [[],[]]\n\n else:\n self._twin = [[0]*len(a[0]), [0]*len(a[1])]\n for i in range(len(a[0])) :\n j = a[1].index(a[0][i])\n self._twin[0][i] = j\n self._twin[1][j] = i\n\n def twin(self, i, pos):\n r\"\"\"\n Return the twin of the interval in the interval ``i`` at position\n ``pos``.\n\n EXAMPLES::\n\n sage: from surface_dynamics import *\n sage: p = iet.Permutation('a b c e d', 'e b d a c')\n sage: p.twin(0,0)\n (1, 3)\n sage: p.twin(0,1)\n (1, 1)\n\n sage: twin_top = [p.twin(0,i) for i in range(p.length_top())]\n sage: twin_bot = [p.twin(1,i) for i in range(p.length_bottom())]\n sage: p.twin_list() == [twin_top, twin_bot]\n True\n \"\"\"\n return (1-i, self._twin[i][pos])\n\n def _set_twin(self, i, p, j, q):\n r\"\"\"\n \"\"\"\n assert i == 0 or i == 1\n assert j == 0 or j == 1\n assert i == 1 - j\n assert 0 <= p < self.length(i)\n assert 0 <= q < self.length(j)\n self._twin[i][p] = q\n\n def twin_list(self):\n r\"\"\"\n Returns the twin list of self.\n\n The twin list is the involution without fixed point associated to that\n permutation seen as two lines of symbols. As the domain is two lines,\n the position are 2-tuples `(i,j)` where `i` specifies the line and `j`\n the position in the line.\n\n EXAMPLES::\n\n sage: from surface_dynamics import *\n\n sage: p = iet.Permutation('a b c','c b a')\n sage: p.twin_list()[0]\n [(1, 2), (1, 1), (1, 0)]\n sage: p.twin_list()[1]\n [(0, 2), (0, 1), (0, 0)]\n\n We may check that it is actually an involution without fixed point::\n\n sage: t = p.twin_list()\n sage: all(t[i][j] != (i,j) for i in range(2) for j in range(len(t[i])))\n True\n sage: all(t[t[i][j][0]][t[i][j][1]] == (i,j) for i in range(2) for j in range(len(t[i])))\n True\n \"\"\"\n twin0 = [(1,i) for i in self._twin[0]]\n twin1 = [(0,i) for i in self._twin[1]]\n return [twin0,twin1]\n\n def _init_alphabet(self,a) :\n r\"\"\"\n Initializes the alphabet from intervals.\n\n INPUT:\n\n - ``a`` - the two intervals as lists\n\n TESTS::\n\n sage: from surface_dynamics import *\n\n sage: p = iet.Permutation('a b c d','d c a b') #indirect doctest\n sage: p.alphabet() == Alphabet(['a', 'b', 'c', 'd'])\n True\n sage: p = iet.Permutation([0,1,2],[1,0,2],reduced=True) #indirect doctest\n sage: p.alphabet() == Alphabet([0,1,2])\n True\n \"\"\"\n from sage.combinat.words.alphabet import build_alphabet\n self._alphabet = build_alphabet(a[0])\n\n def _inversed_twin(self):\n r\"\"\"\n Inverses the twin of the permutation.\n\n EXAMPLES::\n\n sage: from surface_dynamics import *\n\n sage: p = iet.Permutation('a b c','c a b',reduced=True)\n sage: p.left_right_inverse() # indirect doc test\n a b c\n b c a\n\n ::\n\n sage: p = iet.Permutation('a b c d','d a b c',reduced=True)\n sage: p.left_right_inverse() # indirect doctest\n a b c d\n b c d a\n \"\"\"\n self._twin = [self._twin[1], self._twin[0]]\n\n def _reversed_twin(self):\n r\"\"\"\n Reverses the twin of the permutation.\n\n EXAMPLES::\n\n sage: from surface_dynamics import *\n\n sage: p = iet.Permutation('a b c','c a b',reduced=True)\n sage: p.top_bottom_inverse() # indirect doctest\n a b c\n b c a\n sage: p = iet.Permutation('a b c d','d a b c',reduced=True)\n sage: p.top_bottom_inverse() # indircet doctest\n a b c d\n b c d a\n \"\"\"\n tmp = [self._twin[0][:], self._twin[1][:]]\n\n n = self.length_top()\n for i in (0,1):\n for j in range(n):\n tmp[i][n- 1 - j] = n - 1 - self._twin[i][j]\n\n self._twin = tmp\n\n def _move(self, interval, position, interval_to, position_to):\n r\"\"\"\n Moves the element at (interval,position) to (interval, position_to)\n\n INPUT:\n\n - ``interval`` - 0 or 1\n\n - ``position`` - a position in interval\n\n - ``interval_to`` - 0 or 1\n\n - ``position_to`` - a position in interval\n\n TESTS::\n\n sage: from surface_dynamics import *\n\n sage: p = iet.Permutation('a b c d','d c b a')\n sage: p._move(0,0,0,2)\n sage: p\n b a c d\n d c b a\n sage: p._move(0,1,0,3)\n sage: p\n b c a d\n d c b a\n sage: p._move(0,2,0,4)\n sage: p\n b c d a\n d c b a\n sage: p._move(1,3,1,1)\n sage: p\n b c d a\n d a c b\n \"\"\"\n assert interval == interval_to\n\n if position < position_to:\n if self._flips is not None:\n self._flips[interval].insert(\n position_to-1,\n self._flips[interval].pop(position))\n\n if self._labels is not None:\n self._labels[interval].insert(\n position_to-1,\n self._labels[interval].pop(position))\n\n elti = 1-interval\n eltp = self._twin[interval][position]\n k = self._twin[interval][position+1:position_to]\n\n # decrement the twin between position and position to\n for j,pos in enumerate(k):\n self._twin[elti][pos] = position+j\n\n # modify twin of the moved element\n self._twin[elti][eltp] = position_to-1\n\n # move\n self._twin[interval].insert(\n position_to-1,\n self._twin[interval].pop(position))\n\n elif position_to < position:\n if self._flips is not None:\n self._flips[interval].insert(\n position_to,\n self._flips[interval].pop(position))\n\n if self._labels is not None:\n self._labels[interval].insert(\n position_to,\n self._labels[interval].pop(position))\n\n elti = 1-interval\n eltp = self._twin[interval][position]\n k = self._twin[interval][position_to:position]\n\n # increment the twin between position and position to\n for j,pos in enumerate(k):\n self._twin[1-interval][pos] = position_to+j+1\n\n # modify twin of the moved element\n self._twin[elti][eltp] = position_to\n\n # move\n self._twin[interval].insert(\n position_to,\n self._twin[interval].pop(position))\n\n def has_rauzy_move(self, winner, side='right'):\n r\"\"\"\n Test if a Rauzy move can be performed on this permutation.\n\n EXAMPLES::\n\n sage: from surface_dynamics import *\n\n for labelled permutations::\n\n sage: p = iet.Permutation('a b c','a c b',reduced=False)\n sage: p.has_rauzy_move(0,'right')\n True\n sage: p.has_rauzy_move(0,'left')\n False\n sage: p.has_rauzy_move(1,'right')\n True\n sage: p.has_rauzy_move(1,'left')\n False\n\n for reduced permutations::\n\n sage: p = iet.Permutation('a b c','a c b',reduced=True)\n sage: p.has_rauzy_move(0,'right')\n True\n sage: p.has_rauzy_move(0,'left')\n False\n sage: p.has_rauzy_move(1,'right')\n True\n sage: p.has_rauzy_move(1,'left')\n False\n \"\"\"\n side = side_conversion(side)\n winner = interval_conversion(winner)\n\n return self._twin[winner][side] % len(self) != side % len(self)\n\n def is_irreducible(self, return_decomposition=False) :\n r\"\"\"\n Test irreducibility.\n\n A permutation p = (p0,p1) is reducible if:\n set(p0[:i]) = set(p1[:i]) for an i < len(p0)\n\n OUTPUT:\n\n - a boolean\n\n EXAMPLES::\n\n sage: from surface_dynamics import *\n\n sage: p = iet.Permutation('a b c', 'c b a')\n sage: p.is_irreducible()\n True\n\n sage: p = iet.Permutation('a b c', 'b a c')\n sage: p.is_irreducible()\n False\n\n sage: p = iet.Permutation('a b c', 'c b a', flips=['a'])\n sage: p.is_irreducible()\n True\n\n \"\"\"\n s0, s1 = 0, 0\n for i in range(len(self)-1) :\n s0 += i\n s1 += self._twin[0][i]\n if s0 == s1 :\n if return_decomposition :\n return False, (self[0][:i+1], self[0][i+1:], self[1][:i+1], self[1][i+1:])\n return False\n if return_decomposition:\n return True, (self[0],[],self[1],[])\n return True\n\n\nclass PermutationLI(Permutation):\n def _init_twin(self, a):\n r\"\"\"\n Initializes the _twin attribute\n\n TESTS::\n\n sage: from surface_dynamics import *\n\n sage: p = iet.GeneralizedPermutation('a a','b b',reduced=True) #indirect doctest\n sage: p._twin\n [[(0, 1), (0, 0)], [(1, 1), (1, 0)]]\n \"\"\"\n if a is None:\n self._twin = [[],[]]\n\n else:\n twin = [\n [(0,j) for j in range(len(a[0]))],\n [(1,j) for j in range(len(a[1]))]]\n\n for i in (0, 1):\n for j in range(len(twin[i])) :\n if twin[i][j] == (i,j) :\n if a[i][j] in a[i][j+1:] :\n # two up or two down\n j2 = (a[i][j+1:]).index(a[i][j]) + j + 1\n twin[i][j] = (i,j2)\n twin[i][j2] = (i,j)\n else:\n # one up, one down (here i=0)\n j2 = a[1].index(a[i][j])\n twin[0][j] = (1,j2)\n twin[1][j2] = (0,j)\n\n self._twin = twin\n\n def _init_alphabet(self, intervals) :\n r\"\"\"\n Initialization procedure of the alphabet of self from intervals list\n\n TESTS::\n\n sage: from surface_dynamics import *\n\n sage: p = iet.GeneralizedPermutation('a a','b b') #indirect doctest\n sage: p.alphabet()\n {'a', 'b'}\n\n sage: p = iet.GeneralizedPermutation('b b','a a') #indirect doctest\n sage: p.alphabet()\n {'b', 'a'}\n \"\"\"\n tmp_alphabet = []\n for letter in intervals[0] + intervals[1] :\n if letter not in tmp_alphabet :\n tmp_alphabet.append(letter)\n\n from sage.combinat.words.alphabet import build_alphabet\n self._alphabet = build_alphabet(tmp_alphabet)\n\n def _inversed_twin(self):\n r\"\"\"\n Inverses the twin of the permutation.\n\n EXAMPLES::\n\n sage: from surface_dynamics import *\n\n sage: p = iet.GeneralizedPermutation('a a','b b',reduced=True)\n sage: p.left_right_inverse() #indirect doctest\n a a\n b b\n sage: p = iet.GeneralizedPermutation('a a b','b c c',reduced=True)\n sage: p.left_right_inverse() #indirect doctest\n a b b\n c c a\n sage: p = iet.GeneralizedPermutation('a a','b b c c',reduced=True)\n sage: p.left_right_inverse() #indirect doctest\n a a b b\n c c\n \"\"\"\n self._twin = [self._twin[1], self._twin[0]]\n\n for interval in (0,1):\n for j in range(self.length(interval)):\n self._twin[interval][j] = (\n 1-self._twin[interval][j][0],\n self._twin[interval][j][1])\n\n def _reversed_twin(self):\n r\"\"\"\n Reverses the twin of the permutation.\n\n EXAMPLES::\n\n sage: from surface_dynamics import *\n\n sage: p = iet.GeneralizedPermutation('a b b','c c a',reduced=True)\n sage: p.top_bottom_inverse() #indirect doctest\n a a b\n b c c\n sage: p = iet.GeneralizedPermutation('a a','b b c c',reduced=True)\n sage: p.top_bottom_inverse() #indirect doctest\n a a\n b b c c\n \"\"\"\n tmp = [self._twin[0][:], self._twin[1][:]]\n\n n = self.length()\n\n for i in (0,1):\n for j in range(n[i]):\n interval, position = self._twin[i][j]\n tmp[i][n[i] - 1 - j] = (\n interval,\n n[interval] - 1 - position)\n\n self._twin = tmp\n\n def _move(self, interval, position, interval_to, position_to):\n r\"\"\"\n _move the element at (interval,position) to (interval_to, position_to)\n\n INPUT:\n\n - ``interval`` - 0 or 1\n\n - ``position`` - a position in the corresponding interval\n\n - ``interval_to`` - 0 or 1\n\n - ``position_to`` - a position in the corresponding interval\n\n TESTS::\n\n sage: from surface_dynamics import *\n\n sage: p = iet.GeneralizedPermutation('a b c c','d b d a',flips='a')\n sage: p._move(0,0,0,2)\n sage: p\n b -a c c\n d b d -a\n sage: p._move(0,1,0,0)\n sage: p\n -a b c c\n d b d -a\n sage: p._move(1,1,1,4)\n sage: p\n -a b c c\n d d -a b\n sage: p._move(1,3,1,1)\n sage: p\n -a b c c\n d b d -a\n \"\"\"\n if interval != interval_to:\n if self._flips is not None:\n self._flips[interval_to].insert(\n position_to,\n self._flips[interval].pop(position))\n\n if self._labels is not None:\n self._labels[interval_to].insert(\n position_to,\n self._labels[interval].pop(position))\n\n elti,eltp = self._twin[interval][position] # the element to move\n k1 = self._twin[interval_to][position_to:] # interval to shift\n k2 = self._twin[interval][position+1:] # interval to unshift\n\n # increment the twin after the position_to\n for j,(tw,pos) in enumerate(k1):\n self._twin[tw][pos] = (interval_to, position_to+j+1)\n\n # decrement the twin after the position\n for j,(tw,pos) in enumerate(k2):\n self._twin[tw][pos] = (interval, position+j)\n\n # modify twin of the moved interval\n self._twin[elti][eltp] = (interval_to, position_to)\n\n # move\n self._twin[interval_to].insert(\n position_to,\n self._twin[interval].pop(position))\n\n else: # interval == interval_to (just one operation !)\n if position < position_to:\n if self._flips is not None:\n self._flips[interval].insert(\n position_to-1,\n self._flips[interval].pop(position))\n\n if self._labels is not None:\n self._labels[interval].insert(\n position_to-1,\n self._labels[interval].pop(position))\n\n elti, eltp = self._twin[interval][position]\n k = self._twin[interval][position+1:position_to]\n\n # decrement the twin between position and position to\n for j,(tw,pos) in enumerate(k):\n self._twin[tw][pos] = (interval,position+j)\n\n # modify twin of the moved element\n self._twin[elti][eltp] = (interval_to, position_to-1)\n\n # move\n self._twin[interval].insert(\n position_to-1,\n self._twin[interval].pop(position))\n\n elif position_to < position:\n if self._flips is not None:\n self._flips[interval].insert(\n position_to,\n self._flips[interval].pop(position))\n\n if self._labels is not None:\n self._labels[interval].insert(\n position_to,\n self._labels[interval].pop(position))\n\n elti, eltp = self._twin[interval][position]\n k = self._twin[interval][position_to:position]\n\n # increment the twin between position and position to\n for j,(tw,pos) in enumerate(k):\n self._twin[tw][pos] = (interval,position_to+j+1)\n\n # modify twin of the moved element\n self._twin[elti][eltp] = (interval_to,position_to)\n\n # move\n self._twin[interval].insert(\n position_to,\n self._twin[interval].pop(position))\n\n\n def _set_twin(self, i, p, j, q):\n assert i == 0 or i == 1\n assert j == 0 or j == 1\n assert 0 <= p < self.length(i)\n assert 0 <= q < self.length(j)\n self._twin[i][p] = (j,q)\n\n def twin(self, i, pos):\n r\"\"\"\n Return the twin of the letter in interval ``i`` at position ``pos``\n\n EXAMPLES::\n\n sage: from surface_dynamics import *\n sage: p = iet.GeneralizedPermutation('a a b c', 'c e b e')\n sage: p.twin(0,0)\n (0, 1)\n sage: p.twin(0,1)\n (0, 0)\n\n sage: twin_top = [p.twin(0,i) for i in range(p.length_top())]\n sage: twin_bot = [p.twin(1,i) for i in range(p.length_bottom())]\n sage: p.twin_list() == [twin_top, twin_bot]\n True\n \"\"\"\n return self._twin[i][pos]\n\n def twin_list(self):\n r\"\"\"\n Returns the twin list of self.\n\n The twin list is the involution without fixed point which defines it. As the\n domain is naturally split into two lines we use a 2-tuple (i,j) to\n specify the element at position j in line i.\n\n EXAMPLES::\n\n sage: from surface_dynamics import *\n\n sage: p = iet.GeneralizedPermutation('a a b','b c c')\n sage: p.twin_list()[0]\n [(0, 1), (0, 0), (1, 0)]\n sage: p.twin_list()[1]\n [(0, 2), (1, 2), (1, 1)]\n\n And we may check that it is actually an involution without fixed point::\n\n sage: t = p.twin_list()\n sage: all(t[i][j] != (i,j) for i in range(2) for j in range(len(t[i])))\n True\n sage: all(t[t[i][j][0]][t[i][j][1]] == (i,j) for i in range(2) for j in range(len(t[i])))\n True\n\n A slightly more complicated example::\n\n sage: q = iet.GeneralizedPermutation('a b c a','d e f e g c b g d f')\n sage: q.twin_list()[0]\n [(0, 3), (1, 6), (1, 5), (0, 0)]\n sage: q.twin_list()[1]\n [(1, 8), (1, 3), (1, 9), (1, 1), (1, 7), (0, 2), (0, 1), (1, 4), (1, 0), (1, 2)]\n\n ::\n\n sage: t = q.twin_list()\n sage: all(t[t[i][j][0]][t[i][j][1]] == (i,j) for i in range(2) for j in range(len(t[i])))\n True\n \"\"\"\n return [self._twin[0][:],self._twin[1][:]]\n\n def is_irreducible(self, return_decomposition=False):\n r\"\"\"\n Test of reducibility\n\n A quadratic (or generalized) permutation is *reducible* if there exists\n a decomposition\n\n .. math::\n\n A1 u B1 | ... | B1 u A2\n\n A1 u B2 | ... | B2 u A2\n\n where no corners is empty, or exactly one corner is empty\n and it is on the left, or two and they are both on the\n right or on the left. The definition is due to [BoiLan09]_ where they prove\n that the property of being irreducible is stable under Rauzy induction.\n\n INPUT:\n\n - ``return_decomposition`` - boolean (default: False) - if True, and\n the permutation is reducible, returns also the blocks A1 u B1, B1 u\n A2, A1 u B2 and B2 u A2 of a decomposition as above.\n\n OUTPUT:\n\n If return_decomposition is True, returns a 2-uple\n (test,decomposition) where test is the preceding test and\n decomposition is a 4-uple (A11,A12,A21,A22) where:\n\n A11 = A1 u B1\n A12 = B1 u A2\n A21 = A1 u B2\n A22 = B2 u A2\n\n EXAMPLES::\n\n sage: from surface_dynamics import *\n\n sage: GP = iet.GeneralizedPermutation\n\n sage: GP('a a','b b').is_irreducible()\n False\n sage: GP('a a b','b c c').is_irreducible()\n True\n sage: GP('1 2 3 4 5 1','5 6 6 4 3 2').is_irreducible()\n True\n\n TESTS::\n\n sage: from surface_dynamics import *\n\n Test reducible permutations with no empty corner::\n\n sage: GP('1 4 1 3','4 2 3 2').is_irreducible(True)\n (False, (['1', '4'], ['1', '3'], ['4', '2'], ['3', '2']))\n\n Test reducible permutations with one left corner empty::\n\n sage: GP('1 2 2 3 1','4 4 3').is_irreducible(True)\n (False, (['1'], ['3', '1'], [], ['3']))\n sage: GP('4 4 3','1 2 2 3 1').is_irreducible(True)\n (False, ([], ['3'], ['1'], ['3', '1']))\n\n Test reducible permutations with two left corner empty::\n\n sage: GP('1 1 2 3','4 2 4 3').is_irreducible(True)\n (False, ([], ['3'], [], ['3']))\n\n Test reducible permutations with two right corner empty::\n\n sage: GP('1 2 2 3 3','1 4 4').is_irreducible(True)\n (False, (['1'], [], ['1'], []))\n sage: GP('1 2 2','1 3 3').is_irreducible(True)\n (False, (['1'], [], ['1'], []))\n sage: GP('1 2 3 3','2 1 4 4 5 5').is_irreducible(True)\n (False, (['1', '2'], [], ['2', '1'], []))\n\n A ``NotImplementedError`` is raised when there are flips::\n\n sage: p = iet.GeneralizedPermutation('a b c e b','d c d a e', flips='abcd', reduced=True)\n sage: p.is_irreducible()\n Traceback (most recent call last):\n ...\n NotImplementedError: irreducibility test not implemented for generalized permutations with flips\n sage: p = iet.GeneralizedPermutation('a b c e b','d c d a e', flips='abcd', reduced=False)\n sage: p.is_irreducible()\n Traceback (most recent call last):\n ...\n NotImplementedError: irreducibility test not implemented for generalized permutations with flips\n \"\"\"\n if self._flips is not None:\n raise NotImplementedError('irreducibility test not implemented for generalized permutations with flips')\n\n l0 = self.length_top()\n l1 = self.length_bottom()\n s0,s1 = self.list()\n\n # testing two corners empty on the right (i12 = i22 = 0)\n A11, A21, A12, A22 = [],[],[],[]\n\n for i11 in range(1, l0):\n if s0[i11-1] in A11:\n break\n A11 = s0[:i11]\n\n for i21 in range(1, l1):\n if s1[i21-1] in A21:\n break\n A21 = s1[:i21]\n\n if sorted(A11) == sorted(A21):\n if return_decomposition:\n return False,(A11,A12,A21,A22)\n return False\n A21 = []\n\n # testing no corner empty but one or two on the left\n t11 = t21 = False\n A11, A12, A21, A22 = [], [], [], []\n for i11 in range(0, l0):\n if i11 > 0 and s0[i11-1] in A11:\n break\n A11 = s0[:i11]\n\n for i21 in range(0, l1) :\n if i21 > 0 and s1[i21-1] in A21:\n break\n A21 = s1[:i21]\n\n for i12 in range(l0 - 1, i11 - 1, -1) :\n if s0[i12] in A12 or s0[i12] in A21:\n break\n A12 = s0[i12:]\n\n for i22 in range(l1 - 1, i21 - 1, -1) :\n if s1[i22] in A22 or s1[i22] in A11:\n break\n A22 = s1[i22:]\n\n if sorted(A11 + A22) == sorted(A12 + A21) :\n if return_decomposition :\n return False, (A11,A12,A21,A22)\n return False\n A22 = []\n A12 = []\n A21 = []\n\n\n if return_decomposition:\n return True, ()\n return True\n\n\n def to_cylindric(self):\n r\"\"\"\n Return a cylindric permutation in the same extended Rauzy class\n\n A generalized permutation is *cylindric* if the first letter in the top\n interval is the same as the last letter in the bottom interval or if the\n laster letter of the top interval is the same as the fist letter of the\n bottom interval.\n\n EXAMPLES::\n\n sage: from surface_dynamics import iet\n\n sage: p = iet.GeneralizedPermutation('a b d a c','c e b e d')\n sage: p.is_irreducible()\n True\n sage: p.to_cylindric().is_cylindric()\n True\n\n sage: p = iet.GeneralizedPermutation([0,1,2,1,2,3,4,5,6], [6,0,5,4,7,3,7], reduced=True)\n sage: p.to_cylindric()\n 0 1 2 1 2 3 4 5 6\n 6 0 5 4 7 3 7\n\n TESTS::\n\n sage: from surface_dynamics import *\n\n sage: p = iet.GeneralizedPermutation([[0,1,1],[2,2,0]], reduced=True)\n sage: p.to_cylindric()\n 0 1 1\n 2 2 0\n\n ALGORITHM:\n\n The algorithm is naive. It computes the extended Rauzy class until it\n finds a cylindric permutation.\n \"\"\"\n if self.is_cylindric():\n return self\n\n wait = [self]\n rauzy_class = set([self])\n while wait:\n q = wait.pop()\n if q.has_rauzy_move('t'): # top rauzy move\n qq = q.rauzy_move('t')\n if qq not in rauzy_class:\n if qq._twin[1][-1] == (0,0) or qq._twin[0][-1] == (1,0):\n return qq\n wait.append(qq)\n rauzy_class.add(qq)\n if q.has_rauzy_move('b'): # bot rauzy move\n qq = q.rauzy_move('b')\n if qq not in rauzy_class:\n if qq._twin[1][-1] == (0,0) or qq._twin[0][-1] == (1,0):\n return qq\n wait.append(qq)\n rauzy_class.add(qq)\n qq = q.symmetric() # symmetric\n if qq not in rauzy_class:\n if qq._twin[1][-1] == (0,0) or qq._twin[0][-1] == (1,0):\n return qq\n wait.append(qq)\n rauzy_class.add(qq)\n\n raise RuntimeError(\"no cylindric permutation in the extended Rauzy class\")\n\n def is_cylindric(self):\n r\"\"\"\n Test if the permutation is cylindric\n\n EXAMPLES::\n\n sage: from surface_dynamics import *\n\n sage: q = iet.GeneralizedPermutation('a b b','c c a')\n sage: q.is_cylindric()\n True\n sage: q = iet.GeneralizedPermutation('a a b b','c c')\n sage: q.is_cylindric()\n False\n \"\"\"\n return self._twin[0][-1] == (1,0) or self._twin[1][-1] == (0,0)\n\n def profile(self):\n r\"\"\"\n Returns the ``profile`` of self.\n\n The *profile* of a generalized permutation is the list `(d_1, \\ldots,\n d_k)` where `(d_1 \\pi, \\ldots, d_k \\pi)` is the list of angles of any\n suspension of that generalized permutation.\n\n See also :meth:`marked_profile`.\n\n EXAMPLES::\n\n sage: from surface_dynamics import *\n\n sage: p1 = iet.GeneralizedPermutation('a a b','b c c')\n sage: p1.profile()\n [1, 1, 1, 1]\n sage: all(p.profile() == [1, 1, 1, 1] for p in p1.rauzy_diagram())\n True\n\n sage: p2 = iet.GeneralizedPermutation('0 1 2 1 3','4 3 4 2 0')\n sage: p2.profile()\n [4, 4]\n sage: all(p.profile() == [4,4] for p in p2.rauzy_diagram())\n True\n\n sage: p3 = iet.GeneralizedPermutation('0 1 2 3 3','2 1 4 4 0')\n sage: p3.profile()\n [3, 3, 1, 1]\n sage: all(p.profile() == [3, 3, 1, 1] for p in p3.rauzy_diagram())\n True\n \"\"\"\n from sage.combinat.partition import Partition\n s = self.interval_diagram(sign=False,glue_ends=True)\n return Partition(sorted((len(x) for x in s),reverse=True))\n\n def genus(self):\n r\"\"\"\n Returns the genus of any suspension of self.\n\n The genus `g` can be deduced from the profile (see :meth:`profile`)\n `p=(p_1,\\ldots,p_k)` of self by the formula:\n `4g-4 = \\sum_{i=1}^k (p_i - 2)`.\n\n EXAMPLES::\n\n sage: from surface_dynamics import *\n\n sage: iet.GeneralizedPermutation('a a b','b c c').genus()\n 0\n sage: iet.GeneralizedPermutation((0,1,2,1,3),(4,3,4,2,0)).genus()\n 2\n \"\"\"\n p = self.profile()\n return Integer((sum(p)-2*len(p)) // 4 + 1)\n\n def marking(self):\n r\"\"\"\n Return the marking induced by the two sides of the interval\n\n EXAMPLES::\n\n sage: from surface_dynamics import *\n\n sage: p = iet.GeneralizedPermutation('0 1 2 3 4 3 5 6 7','1 6 8 4 2 7 5 8 0')\n sage: p.marking()\n 8|7\n\n sage: p = iet.GeneralizedPermutation('0 1 2 3 4 3 5 6 7','1 6 8 4 2 7 8 0 5')\n sage: p.marking()\n 8o8\n \"\"\"\n return self.marked_profile().marking()\n\n def marked_profile(self):\n r\"\"\"\n Returns the marked profile of self.\n\n The *marked profile* of a generalized permutation is an integer\n partition and some additional data associated to the angles of conical\n singularities in the suspension. The partition, called the\n *profile*, is the list of angles divided by `2\\pi` (see\n :meth:`profile`). The additional is called the *marking* and may be of\n two different types.\n\n If the left endpoint and the right endpoint of the interval associated\n to the permutation coincides, then the marking is of *type 1* and the\n additional data consists of a couple `(m,a)` such that `m` is the\n angle of the conical singularity and `a` is the angle between the\n outgoing separatrix associated to the left endpoint and the incoming\n separatrix associated to the right endpoint. A marking of type one is\n denoted `m | a`.\n\n If the left endpoint and the right endpoint are two different conical\n singularities in the suspension, then the marking is of *type 2* and the\n data consists in a couple `(m_l,m_r)` where `m_l` (resp. `m_r`) is\n the conical angle of the singularity at the left endpoint (resp. right\n endpoint). A marking of type two is denoted `m_l \\circ m_r`\n\n EXAMPLES::\n\n sage: from surface_dynamics import *\n\n All possible markings for the profile [1, 1, 1, 1]::\n\n sage: p = iet.GeneralizedPermutation('a a b','b c c')\n sage: p.marked_profile()\n 1o1 [1, 1, 1, 1]\n sage: p = iet.GeneralizedPermutation('a a','b b c c')\n sage: p.marked_profile()\n 1|0 [1, 1, 1, 1]\n\n All possible markings for the profile [4, 4]::\n\n sage: p = iet.GeneralizedPermutation('0 1 2 1 3','3 4 0 4 2')\n sage: p.marked_profile()\n 4o4 [4, 4]\n\n sage: p = iet.GeneralizedPermutation('0 1 2 1 3','4 3 2 0 4')\n sage: p.marked_profile()\n 4|0 [4, 4]\n\n sage: p = iet.GeneralizedPermutation('0 1 0 2 3 2','4 3 4 1')\n sage: p.marked_profile()\n 4|1 [4, 4]\n\n sage: p = iet.GeneralizedPermutation('0 1 2 3 2','4 3 4 1 0')\n sage: p.marked_profile()\n 4|2 [4, 4]\n\n sage: p = iet.GeneralizedPermutation('0 1 0 1','2 3 2 4 3 4')\n sage: p.marked_profile()\n 4|3 [4, 4]\n \"\"\"\n if self._flips:\n raise ValueError('not available on permutations with flips')\n\n from .marked_partition import MarkedPartition\n\n if len(self) == 1:\n return MarkedPartition([],2,(0,0))\n\n g = self.interval_diagram(glue_ends=True,sign=True)\n signs = self._canonical_signs()[1]\n p = sorted(map(lambda x: len(x), g),reverse=True)\n\n left1 = ((self[1][0], -signs[1][0]), (self[0][0], signs[0][0]))\n left2 = (left1[1], left1[0])\n right1 = ((self[0][-1], -signs[0][-1]), (self[1][-1], signs[1][-1]))\n right2 = (right1[1], right1[0])\n if len(set(left1+right1)) == 3:\n if left1[0] == right1[0]:\n lr1 = (left1[1], left1[0],right1[1])\n lr2 = (right1[1], left1[0], left1[1])\n elif left1[0] == right1[1]:\n lr1 = (left1[1], left1[0], right1[0])\n lr2 = (right1[0], left1[0], left1[1])\n elif left1[1] == right1[0]:\n lr1 = (left1[0], left1[1], right1[1])\n lr2 = (right1[1], left1[1], left1[0])\n elif left1[1] == right1[1]:\n lr1 = (left1[0], left1[1], right1[0])\n lr2 = (right1[0], left1[1], left1[0])\n for c in g:\n if lr1 in c or lr2 in c:\n break\n return MarkedPartition(p, 1, (len(c), 0))\n else:\n c_left = c_right = None\n for c in g:\n if left1 in c or left2 in c: c_left = c\n if right1 in c or right2 in c: c_right = c\n\n if c_left == c_right:\n mm = len(c_left)\n if right1 in c_right:\n r = c_right.index(right1)\n else:\n r = c_right.index(right2)\n if left1 in c_left:\n l = c_left.index(left1)\n else:\n l = c_left.index(left2)\n a = ((r-l)%mm)\n return MarkedPartition(p, 1, (mm, a))\n\n else:\n m_l = len(c_left)\n m_r = len(c_right)\n return MarkedPartition(p, 2, (m_l,m_r))\n\n def erase_marked_points(self):\n r\"\"\"\n Return a permutation without marked points.\n\n This method is not implemented for generalized permutations.\n\n EXAMPLES::\n\n sage: from surface_dynamics import *\n\n sage: p = iet.GeneralizedPermutation('a a b','b c c')\n sage: p.stratum()\n Q_0(-1^4)\n sage: p.erase_marked_points()\n a a b\n b c c\n sage: p = iet.GeneralizedPermutation('a d d a b','b c c')\n sage: p.stratum()\n Q_0(0, -1^4)\n sage: p.erase_marked_points()\n Traceback (most recent call last):\n ...\n NotImplementedError: not yet implemented! Do it!\n \"\"\"\n if self.stratum().nb_fake_zeros():\n raise NotImplementedError(\"not yet implemented! Do it!\")\n else:\n return self\n\n def is_hyperelliptic(self, verbose=False):\n r\"\"\"\n Test if this permutation is in an hyperelliptic connected component.\n\n EXAMPLES::\n\n sage: from surface_dynamics import *\n\n An example of hyperelliptic permutation::\n\n sage: p = iet.GeneralizedPermutation([0,1,2,0,6,5,3,1,2,3],[4,5,6,4])\n sage: p.is_hyperelliptic()\n True\n\n Check for the correspondence::\n\n sage: q = QuadraticStratum(6,6)\n sage: c_hyp, c_reg, c_irr = q.components()\n\n sage: p_hyp = c_hyp.permutation_representative()\n sage: p_hyp\n 0 1 2 3 4 1 5 6 7\n 7 6 5 8 4 3 2 8 0\n sage: p_hyp.is_hyperelliptic()\n True\n\n sage: p_reg = c_reg.permutation_representative()\n sage: p_reg\n 0 1 2 3 4 5 2 6 7 5\n 1 4 6 8 7 8 3 0\n sage: p_reg.is_hyperelliptic()\n False\n\n sage: p_irr = c_irr.permutation_representative()\n sage: p_irr\n 0 1 2 3 4 3 5 6 7\n 1 6 8 4 2 7 5 8 0\n sage: p_irr.is_hyperelliptic()\n False\n\n sage: q = QuadraticStratum(3,3,2)\n sage: c_hyp, c_non_hyp = q.components()\n sage: p_hyp = c_hyp.permutation_representative()\n sage: p_hyp.is_hyperelliptic()\n True\n sage: p_non_hyp = c_non_hyp.permutation_representative()\n sage: p_non_hyp.is_hyperelliptic()\n False\n sage: q = QuadraticStratum(5,5,2)\n sage: c_hyp, c_non_hyp = q.components()\n sage: p_hyp = c_hyp.permutation_representative()\n sage: p_hyp.is_hyperelliptic()\n True\n sage: p_non_hyp = c_non_hyp.permutation_representative()\n sage: p_non_hyp.is_hyperelliptic()\n False\n sage: q = QuadraticStratum(3,3,1,1)\n sage: c_hyp, c_non_hyp = q.components()\n sage: p_hyp = c_hyp.permutation_representative()\n sage: p_hyp.is_hyperelliptic()\n True\n sage: p_non_hyp = c_non_hyp.permutation_representative()\n sage: p_non_hyp.is_hyperelliptic()\n False\n \"\"\"\n p = self.erase_marked_points()\n s = p.stratum()\n zeros = s.zeros()\n\n if not s.has_hyperelliptic_component():\n return False\n\n q = p.to_cylindric()\n\n if q[0][0] == q[1][-1]:\n l0 = []\n q0 = q[0][1:]\n q1 = q[1][:-1]\n for i,j in q._twin[0][1:]:\n if i == 0: l0.append((0,j-1))\n else: l0.append((1,j))\n l1 = []\n for i,j in q._twin[1][:-1]:\n if i == 0: l1.append((0,j-1))\n else: l1.append((1,j))\n else:\n l0 = []\n q0 = q[0][:-1]\n q1 = q[1][1:]\n for i,j in q._twin[0][:-1]:\n if i == 1: l0.append((1,j-1))\n else: l0.append((0,j))\n l1 = []\n for i,j in q._twin[1][1:]:\n if i ==1: l1.append((1,j-1))\n else: l1.append((0,j))\n\n if verbose:\n print(\"found Jenkins-Strebel\")\n print(q)\n print(l0)\n print(l1)\n\n if any(x[0] == 1 for x in l0):\n if verbose: print(\"potential form 1\")\n i0 = []\n i1 = []\n for i in range(len(l0)):\n if l0[i][0] == 0:\n i0.append(i)\n for i in range(len(l1)):\n if l1[i][0] == 1:\n i1.append(i)\n if len(i0) != 2 or len(i1) != 2:\n if verbose: print(\"no repetition twice in intervals\")\n return False\n\n q0_0 = q0[i0[0]+1:i0[1]]\n q0_1 = q0[i0[1]+1:] + q0[:i0[0]]\n q0_0.reverse()\n q0_1.reverse()\n\n q1_0 = q1[i1[0]+1:i1[1]]\n q1_1 = q1[i1[1]+1:] + q1[:i1[0]]\n\n if verbose:\n print(q0_0, q0_1)\n print(q1_0, q1_1)\n\n return (q0_0 == q1_0 and q0_1 == q1_1) or (q0_0 == q1_1 and q0_1 == q1_0)\n\n else:\n if verbose: print(\"potential form 2\")\n if any(i==1 for i,_ in l0) or any(i==0 for i,_ in l1):\n return False\n j = len(l0) // 2\n for i in range(j):\n if l0[i][1] != j+i:\n return False\n\n j = len(l1) // 2\n for i in range(j):\n if l1[i][1] != j+i:\n return False\n\n return True\n\n def stratum_component(self):\n r\"\"\"\n Return the connected component of stratum in which self belongs to.\n\n EXAMPLES::\n\n sage: from surface_dynamics import *\n\n sage: p = iet.GeneralizedPermutation('a b b','c c a')\n sage: p.stratum_component()\n Q_0(-1^4)^c\n\n Test the exceptional strata in genus 3::\n\n sage: Q = QuadraticStratum(9,-1)\n sage: p = Q.regular_component().permutation_representative()\n sage: p.stratum_component()\n Q_3(9, -1)^reg\n sage: p = Q.irregular_component().permutation_representative()\n sage: p.stratum_component()\n Q_3(9, -1)^irr\n\n sage: Q = QuadraticStratum(6,3,-1)\n sage: p = Q.regular_component().permutation_representative()\n sage: p.stratum_component()\n Q_3(6, 3, -1)^reg\n sage: p = Q.irregular_component().permutation_representative()\n sage: p.stratum_component()\n Q_3(6, 3, -1)^irr\n\n sage: Q = QuadraticStratum(3,3,3,-1)\n sage: p = Q.regular_component().permutation_representative()\n sage: p.stratum_component()\n Q_3(3^3, -1)^reg\n sage: p = Q.irregular_component().permutation_representative()\n sage: p.stratum_component()\n Q_3(3^3, -1)^irr\n\n Test the exceptional strata in genus 4::\n\n sage: Q = QuadraticStratum(12)\n sage: p = Q.regular_component().permutation_representative()\n sage: p.stratum_component()\n Q_4(12)^reg\n sage: p = Q.irregular_component().permutation_representative()\n sage: p.stratum_component()\n Q_4(12)^irr\n\n sage: Q = QuadraticStratum(9,3)\n sage: p = Q.regular_component().permutation_representative()\n sage: p.stratum_component()\n Q_4(9, 3)^reg\n sage: p = Q.irregular_component().permutation_representative()\n sage: p.stratum_component()\n Q_4(9, 3)^irr\n\n sage: Q = QuadraticStratum(6,6)\n sage: p = Q.hyperelliptic_component().permutation_representative()\n sage: p.stratum_component()\n Q_4(6^2)^hyp\n sage: p = Q.regular_component().permutation_representative()\n sage: p.stratum_component()\n Q_4(6^2)^reg\n sage: p = Q.irregular_component().permutation_representative()\n sage: p.stratum_component()\n Q_4(6^2)^irr\n\n sage: Q = QuadraticStratum(6,3,3)\n sage: p = Q.regular_component().permutation_representative()\n sage: p.stratum_component()\n Q_4(6, 3^2)^reg\n sage: p = Q.irregular_component().permutation_representative()\n sage: p.stratum_component()\n Q_4(6, 3^2)^irr\n\n sage: Q = QuadraticStratum(3,3,3,3)\n sage: p = Q.hyperelliptic_component().permutation_representative()\n sage: p.stratum_component()\n Q_4(3^4)^hyp\n sage: p = Q.regular_component().permutation_representative()\n sage: p.stratum_component()\n Q_4(3^4)^reg\n sage: p = Q.irregular_component().permutation_representative()\n sage: p.stratum_component()\n Q_4(3^4)^irr\n \"\"\"\n stratum = self.stratum()\n cc = stratum.components()\n\n if len(cc) == 1: # connected\n return cc[0]\n\n elif stratum.has_hyperelliptic_component(): # hyp / nonhyp\n if self.is_hyperelliptic():\n return stratum.hyperelliptic_component()\n elif len(cc) == 2:\n return stratum.non_hyperelliptic_component()\n\n # reg / irr\n from surface_dynamics.databases.flat_surfaces import IrregularComponentTwins\n D = IrregularComponentTwins()\n if len(D.list_strata()) != 8:\n raise NotImplementedError(\"database of irregular twins not available\")\n\n p = self.erase_marked_points().to_cylindric()\n if cylindric_canonical(p) in D.get(stratum):\n return stratum.irregular_component()\n return stratum.regular_component()\n\n def has_rauzy_move(self, winner, side='right'):\n r\"\"\"\n Test of Rauzy movability (with an eventual specified choice of winner)\n\n A quadratic (or generalized) permutation is rauzy_movable type\n depending on the possible length of the last interval. It's\n dependent of the length equation.\n\n INPUT:\n\n - ``winner`` - the integer 'top' or 'bottom'\n\n EXAMPLES::\n\n sage: from surface_dynamics import *\n\n sage: p = iet.GeneralizedPermutation('a a','b b')\n sage: p.has_rauzy_move('top','right')\n False\n sage: p.has_rauzy_move('top','left')\n False\n sage: p.has_rauzy_move('bottom','right')\n False\n sage: p.has_rauzy_move('bottom','left')\n False\n\n ::\n\n sage: p = iet.GeneralizedPermutation('a a b','b c c')\n sage: p.has_rauzy_move('top','right')\n True\n sage: p.has_rauzy_move('bottom','right')\n True\n sage: p.has_rauzy_move('top','left')\n True\n sage: p.has_rauzy_move('bottom','left')\n True\n\n ::\n\n sage: p = iet.GeneralizedPermutation('a a','b b c c')\n sage: p.has_rauzy_move('top','right')\n True\n sage: p.has_rauzy_move('bottom','right')\n False\n sage: p.has_rauzy_move('top','left')\n True\n sage: p.has_rauzy_move('bottom','left')\n False\n\n ::\n\n sage: p = iet.GeneralizedPermutation('a a b b','c c')\n sage: p.has_rauzy_move('top','right')\n False\n sage: p.has_rauzy_move('bottom','right')\n True\n sage: p.has_rauzy_move('top','left')\n False\n sage: p.has_rauzy_move('bottom','left')\n True\n \"\"\"\n winner = interval_conversion(winner)\n side = side_conversion(side)\n\n loser = 1 - winner\n\n if side == -1:\n # the same letter at the right-end (False)\n if self._twin[0][-1] == (1, self.length_bottom()-1):\n return False\n\n # winner or loser letter is repeated on the other interval (True)\n if self._twin[0][-1][0] == 1: return True\n if self._twin[1][-1][0] == 0: return True\n\n # the loser letter is the only letter repeated in\n # the loser interval (False)\n if [i for i,_ in self._twin[loser]].count(loser) == 2:\n return False\n\n return True\n\n elif side == 0:\n # the same letter at the left-end (False)\n if (self._twin[0][0] == (1,0)):\n return False\n\n # winner or loser repeated on the other interval (True)\n if self._twin[0][0][0] == 1: return True\n if self._twin[1][0][0] == 0: return True\n\n # the loser letter is the only letter repeated in\n # the loser interval (False)\n if [i for i,_ in self._twin[loser]].count(loser) == 2:\n return False\n\n return True\n\n def orientation_cover(self):\n r\"\"\"\n Return the orientation cover of this permutation.\n\n EXAMPLES::\n\n sage: from surface_dynamics import *\n\n sage: p = iet.GeneralizedPermutation('a a b', 'b c c')\n sage: c = p.orientation_cover()\n sage: c\n Covering of degree 2 of the permutation:\n a a b\n b c c\n sage: c.stratum()\n H_1(0^4)\n\n sage: C = QuadraticStratum(3,2,2,1).unique_component()\n sage: p = C.permutation_representative()\n sage: c = p.orientation_cover()\n sage: c.stratum()\n H_6(4, 2, 1^4)\n \"\"\"\n rank = self.alphabet().rank\n p0 = set(map(rank, self[0]))\n p1 = set(map(rank, self[1]))\n inv_letters = p0.symmetric_difference(p1)\n permut_cover = [[1,0] if i in inv_letters else [0,1] for i in range(len(self))]\n return self.cover(permut_cover, as_tuple=True)\n\nclass OrientablePermutationIET(PermutationIET):\n \"\"\"\n Template for permutation of Interval Exchange Transformation.\n\n .. warning::\n\n Internal class! Do not use directly!\n\n AUTHOR:\n\n - Vincent Delecroix (2008-12-20): initial version\n\n \"\"\"\n def is_identity(self):\n r\"\"\"\n Returns True if self is the identity.\n\n EXAMPLES::\n\n sage: from surface_dynamics import *\n\n sage: iet.Permutation(\"a b\",\"a b\",reduced=False).is_identity()\n True\n sage: iet.Permutation(\"a b\",\"a b\",reduced=True).is_identity()\n True\n sage: iet.Permutation(\"a b\",\"b a\",reduced=False).is_identity()\n False\n sage: iet.Permutation(\"a b\",\"b a\",reduced=True).is_identity()\n False\n \"\"\"\n return all(self._twin[0][i] == i for i in range(len(self)))\n\n #TODO: change the name\n def decompose(self):\n r\"\"\"\n Returns the decomposition as a concatenation of irreducible permutations.\n\n OUTPUT:\n\n a list of permutations\n\n EXAMPLES::\n\n sage: from surface_dynamics import *\n\n sage: p = iet.Permutation('a b c','c b a').decompose()[0]\n sage: p\n a b c\n c b a\n\n ::\n\n sage: p1,p2,p3 = iet.Permutation('a b c d e','b a c e d').decompose()\n sage: p1\n a b\n b a\n sage: p2\n c\n c\n sage: p3\n d e\n e d\n \"\"\"\n l = []\n test, t = self.is_irreducible(return_decomposition=True)\n l.append(self.__class__((t[0],t[2])))\n\n while not test:\n q = self.__class__((t[1],t[3]))\n test, t = q.is_irreducible(return_decomposition=True)\n l.append(self.__class__((t[0],t[2])))\n\n return l\n\n def intersection_matrix(self, ring=None):\n r\"\"\"\n Returns the intersection matrix.\n\n This `d*d` antisymmetric matrix is given by the rule :\n\n .. math::\n\n m_{ij} = \\begin{cases}\n 1 & \\text{$i < j$ and $\\pi(i) > \\pi(j)$} \\\\\n -1 & \\text{$i > j$ and $\\pi(i) < \\pi(j)$} \\\\\n 0 & \\text{else}\n \\end{cases}\n\n OUTPUT:\n\n - a matrix\n\n EXAMPLES::\n\n sage: from surface_dynamics import *\n\n sage: p = iet.Permutation('a b c d','d c b a')\n sage: p.intersection_matrix()\n [ 0 1 1 1]\n [-1 0 1 1]\n [-1 -1 0 1]\n [-1 -1 -1 0]\n\n ::\n\n sage: p = iet.Permutation('1 2 3 4 5','5 3 2 4 1')\n sage: p.intersection_matrix()\n [ 0 1 1 1 1]\n [-1 0 1 0 1]\n [-1 -1 0 0 1]\n [-1 0 0 0 1]\n [-1 -1 -1 -1 0]\n\n ::\n\n sage: p = iet.Permutation('a b c d', 'd c b a')\n sage: R = p.rauzy_diagram()\n sage: g = R.path(p, *'tbt')\n sage: m = g.matrix()\n sage: q = g.end()\n sage: q.intersection_matrix() == m.transpose() * p.intersection_matrix() * m\n True\n \"\"\"\n if ring is None:\n ring = ZZ\n n = self.length_top()\n m = matrix(ring,n)\n # NOTE: because of the extended Rauzy inductions, the labels are just a subset of\n # {0, 1, ...} not necessarily the first n integers.\n use_labels = self._labels is not None and \\\n min(self._labels[0]) == 0 and \\\n max(self._labels[0]) == n - 1\n for i in range(n):\n ii = self._labels[0][i] if use_labels else i\n for j in range(i,n):\n jj = self._labels[0][j] if use_labels else j\n if self._twin[0][i] > self._twin[0][j]:\n m[ii,jj] = 1\n m[jj,ii] = -1\n return m\n\n def attached_out_degree(self):\n r\"\"\"\n Returns the degree of the singularity at the left of the interval.\n\n OUTPUT:\n\n - a positive integer\n\n\n EXAMPLES::\n\n sage: from surface_dynamics import *\n\n sage: p1 = iet.Permutation('a b c d e f g','d c g f e b a')\n sage: p2 = iet.Permutation('a b c d e f g','e d c g f b a')\n sage: p1.attached_out_degree()\n 3\n sage: p2.attached_out_degree()\n 1\n \"\"\"\n left_corner = (self[1][0], +1)\n for s in self.interval_diagram(glue_ends=False,sign=True):\n if left_corner in s:\n return len(s)//2 - 1\n\n def attached_in_degree(self):\n r\"\"\"\n Returns the degree of the singularity at the right of the interval.\n\n OUTPUT:\n\n - a positive integer\n\n\n EXAMPLES::\n\n sage: from surface_dynamics import *\n\n sage: p1 = iet.Permutation('a b c d e f g','d c g f e b a')\n sage: p2 = iet.Permutation('a b c d e f g','e d c g f b a')\n sage: p1.attached_in_degree()\n 1\n sage: p2.attached_in_degree()\n 3\n \"\"\"\n right_corner = (self[1][-1], -1)\n for s in self.interval_diagram(glue_ends=False,sign=True):\n if right_corner in s:\n return len(s)//2 - 1\n\n def profile(self):\n r\"\"\"\n Returns the profile of the permutation\n\n EXAMPLES::\n\n sage: from surface_dynamics import *\n\n sage: iet.Permutation('a b c d','d c b a').profile()\n [3]\n sage: iet.Permutation('a b c d e','e d c b a').profile()\n [2, 2]\n \"\"\"\n from sage.combinat.partition import Partition\n s = self.interval_diagram(glue_ends=True,sign=False)\n return Partition(sorted((len(x)/2 for x in s),reverse=True))\n\n def marking(self):\n r\"\"\"\n Return the marking induced by the two sides of the interval\n\n EXAMPLES::\n\n sage: from surface_dynamics import *\n\n sage: p = iet.Permutation('a b c d e f','f a e b d c')\n sage: p.marking()\n 5|0\n sage: p = iet.Permutation('0 1 2 3 4 5 6','3 2 4 6 5 1 0')\n sage: p.marking()\n 3o3\n \"\"\"\n return self.marked_profile().marking()\n\n def marked_profile(self):\n r\"\"\"\n Returns the marked profile of the permutation\n\n The marked profile of a permutation corresponds to the integer partition\n associated to the angles of conical singularities in the suspension\n together with a data associated to the endpoint called marking.\n\n If the left endpoint and the right endpoint of the interval associated\n to the permutation, then the marking is of type one and consists in a\n couple ``(m,a)`` such that ``m`` is the angle of the conical singularity\n and ``a`` is the angle between the outgoing separatrix associated to the\n left endpoint and the incoming separatrix associated to the right\n endpoint. A marking of type one is denoted ``(m|a)``.\n\n If the left endpoint and the right endpoint are two different conical\n singularities in the suspension the marking is of type two and\n consists in a couple ``(m_l,m_r)`` where ``m_l`` (resp. ``m_r``) is the\n conical angle of the singularity at the left endpoint (resp. right\n endpoint). A marking of type two is denoted ``m_l o m_r``\n\n EXAMPLES::\n\n sage: from surface_dynamics import *\n\n The irreducible permutation on 1 interval has marked profile of type 2\n with data `(0,0)`::\n\n sage: p = iet.Permutation('a','a')\n sage: p.marked_profile()\n 0o0 []\n\n Permutations in H(3,1) with all possible profiles::\n\n sage: p = iet.Permutation('a b c d e f g','b g a c f e d')\n sage: p.interval_diagram()\n [['a', ('b', 'a'), ('g', 'd'), 'e', 'f', 'g', 'b', 'c'], ['c', 'd', 'e', 'f']]\n sage: p.marked_profile()\n 4|0 [4, 2]\n\n sage: p = iet.Permutation('a b c d e f g','c a g d f b e')\n sage: p.interval_diagram()\n [['a', 'b', 'f', 'g'], ['c', 'd', ('g', 'e'), 'f', 'd', 'e', 'b', ('c', 'a')]]\n sage: p.marked_profile()\n 4|1 [4, 2]\n\n sage: p = iet.Permutation('a b c d e f g','e b d g c a f')\n sage: p.interval_diagram()\n [['a', 'b', 'e', 'f'], ['c', 'd', 'b', 'c', ('g', 'f'), 'g', 'd', ('e', 'a')]]\n sage: p.marked_profile()\n 4|2 [4, 2]\n\n sage: p = iet.Permutation('a b c d e f g', 'e c g b a f d')\n sage: p.interval_diagram()\n [['a', 'b', ('g', 'd'), ('e', 'a'), 'b', 'c', 'e', 'f'], ['c', 'd', 'f', 'g']]\n sage: p.marked_profile()\n 4|3 [4, 2]\n\n sage: p = iet.Permutation('a b c d e f g', 'f d c a g e b')\n sage: p.interval_diagram()\n [['a', 'b', 'e', ('f', 'a'), 'c', 'd', 'f', 'g'], ['c', 'd', 'e', ('g', 'b')]]\n sage: p.marked_profile()\n 4o2 [4, 2]\n \"\"\"\n from .marked_partition import MarkedPartition\n\n if len(self) == 1:\n return MarkedPartition([],2,(0,0))\n\n g = self.interval_diagram(glue_ends=True,sign=True)\n p = sorted(map(lambda x: len(x)//2, g),reverse=True)\n left = ((self[1][0], +1), (self[0][0], +1))\n right = ((self[0][-1], -1), (self[1][-1], -1))\n for c in g:\n if left in c: c_left = c\n if right in c: c_right = c\n\n if c_left == c_right:\n mm = len(c_left)\n a = ((c_right.index(right)-c_left.index(left)-1) %mm) // 2\n return MarkedPartition(p, 1, (mm//2, a))\n\n else:\n m_l = len(c_left) // 2\n m_r = len(c_right) // 2\n return MarkedPartition(p, 2, (m_l,m_r))\n\n def stratum(self):\n r\"\"\"\n Returns the strata in which any suspension of this permutation lives.\n\n OUTPUT:\n\n - a stratum of Abelian differentials\n\n EXAMPLES::\n\n sage: from surface_dynamics import *\n\n sage: p = iet.Permutation('a b c', 'c b a')\n sage: p.stratum()\n H_1(0^2)\n\n sage: p = iet.Permutation('a b c d', 'd a b c')\n sage: p.stratum()\n H_1(0^3)\n\n sage: p = iet.Permutation(list(range(9)), [8,5,2,7,4,1,6,3,0])\n sage: p.stratum()\n H_3(1^4)\n\n sage: a = 'a b c d e f g h i j'\n sage: b3 = 'd c g f e j i h b a'\n sage: b2 = 'd c e g f j i h b a'\n sage: b1 = 'e d c g f h j i b a'\n sage: p3 = iet.Permutation(a, b3)\n sage: p3.stratum()\n H_4(3, 2, 1)\n sage: p2 = iet.Permutation(a, b2)\n sage: p2.stratum()\n H_4(3, 2, 1)\n sage: p1 = iet.Permutation(a, b1)\n sage: p1.stratum()\n H_4(3, 2, 1)\n\n AUTHORS:\n\n - Vincent Delecroix (2008-12-20)\n \"\"\"\n from surface_dynamics.flat_surfaces.abelian_strata import AbelianStratum\n\n if not self.is_irreducible():\n return list(map(lambda x: x.stratum(), self.decompose()))\n\n if len(self) == 1:\n return AbelianStratum([])\n\n singularities = [x - 1 for x in self.profile()]\n\n return AbelianStratum(singularities)\n\n def genus(self) :\n r\"\"\"\n Returns the genus corresponding to any suspension of self.\n\n The genus can be deduced from the profile (see :meth:`profile`)\n `p = (p_1,\\ldots,p_k)` of self by the formula:\n `2g-2 = \\sum_{i=1}^k (p_i-1)`.\n\n EXAMPLES::\n\n sage: from surface_dynamics import *\n\n sage: p = iet.Permutation('a b c', 'c b a')\n sage: p.genus()\n 1\n\n sage: p = iet.Permutation('a b c d','d c b a')\n sage: p.genus()\n 2\n \"\"\"\n p = self.profile()\n return Integer((sum(p)-len(p))//2+1)\n\n def arf_invariant(self):\n r\"\"\"\n Returns the Arf invariant of the permutation.\n\n To a permutation `\\pi` is associated a quadratic form on the field with\n 2 elements. The *Arf invariant* is the total invariant of linear\n equivalence class of quadratic form of given rank.\n\n Let `V` be a vector space on the field with two elements `\\FF_2`. `V`\n there are two equivalence classes of non degenerate quadratic forms. A\n complete invariant for quadratic forms is the *Arf invariant*.\n\n For non zero degenerate quadratic forms there are three equivalence\n classes. If `B` denotes the bilinear form associated to `q` then the\n three classes are as follows\n\n - the restriction of `q` to `ker(B)` is non zero\n\n - the restriction of `q` to `ker(B)` is zero and the spin parity of `q`\n on the quotient `V/ker(B)` is 0\n\n - the restriction of `q` to `ker(B)` is zero and the spin parity of `q`\n on the quotient `V/ker(B)` is 1\n\n The function returns respectively `None`, `0` or `1` depending on the\n three alternatives above.\n\n EXAMPLES::\n\n sage: from surface_dynamics import *\n\n Permutations from the odd and even component of H(2,2,2)::\n\n sage: a = list(range(10))\n sage: b1 = [3,2,4,6,5,7,9,8,1,0]\n sage: b0 = [6,5,4,3,2,7,9,8,1,0]\n sage: p1 = iet.Permutation(a,b1)\n sage: p1.arf_invariant()\n 1\n sage: p0 = iet.Permutation(a,b0)\n sage: p0.arf_invariant()\n 0\n\n Permutations from the odd and even component of H(4,4)::\n\n sage: a = list(range(11))\n sage: b1 = [3,2,5,4,6,8,7,10,9,1,0]\n sage: b0 = [5,4,3,2,6,8,7,10,9,1,0]\n sage: p1 = iet.Permutation(a,b1)\n sage: p1.arf_invariant()\n 1\n sage: p0 = iet.Permutation(a,b0)\n sage: p0.arf_invariant()\n 0\n \"\"\"\n if any((z+1)%2 for z in self.profile()):\n return None\n\n from sage.rings.finite_rings.finite_field_constructor import GF\n GF2 = GF(2)\n\n M = self.intersection_matrix(GF2)\n F, C = M.symplectic_form()\n\n g = F.rank() // 2\n n = F.ncols()\n\n s = GF2(0)\n for i in range(g):\n a = C.row(i)\n\n a_indices = [k for k in range(n) if a[k]]\n t_a = GF2(len(a_indices))\n for j1 in range(len(a_indices)):\n for j2 in range(j1+1,len(a_indices)):\n t_a += M[a_indices[j1], a_indices[j2]]\n\n b = C.row(g+i)\n b_indices = [k for k in range(n) if b[k]]\n t_b = GF2(len(b_indices))\n for j1 in range(len(b_indices)):\n for j2 in range(j1+1,len(b_indices)):\n t_b += M[b_indices[j1],b_indices[j2]]\n\n s += t_a * t_b\n\n return s\n\n def stratum_component(self):\n r\"\"\"\n Returns a connected components of a stratum.\n\n EXAMPLES::\n\n sage: from surface_dynamics import *\n\n Permutations from the stratum H(6)::\n\n sage: a = list(range(8))\n sage: b_hyp = [7,6,5,4,3,2,1,0]\n sage: b_odd = [3,2,5,4,7,6,1,0]\n sage: b_even = [5,4,3,2,7,6,1,0]\n sage: p_hyp = iet.Permutation(a, b_hyp)\n sage: p_odd = iet.Permutation(a, b_odd)\n sage: p_even = iet.Permutation(a, b_even)\n sage: p_hyp.stratum_component()\n H_4(6)^hyp\n sage: p_odd.stratum_component()\n H_4(6)^odd\n sage: p_even.stratum_component()\n H_4(6)^even\n\n Permutations from the stratum H(4,4)::\n\n sage: a = list(range(11))\n sage: b_hyp = [10,9,8,7,6,5,4,3,2,1,0]\n sage: b_odd = [3,2,5,4,6,8,7,10,9,1,0]\n sage: b_even = [5,4,3,2,6,8,7,10,9,1,0]\n sage: p_hyp = iet.Permutation(a,b_hyp)\n sage: p_odd = iet.Permutation(a,b_odd)\n sage: p_even = iet.Permutation(a,b_even)\n sage: p_hyp.stratum() == AbelianStratum(4,4)\n True\n sage: p_hyp.stratum_component()\n H_5(4^2)^hyp\n sage: p_odd.stratum() == AbelianStratum(4,4)\n True\n sage: p_odd.stratum_component()\n H_5(4^2)^odd\n sage: p_even.stratum() == AbelianStratum(4,4)\n True\n sage: p_even.stratum_component()\n H_5(4^2)^even\n\n As for stratum you can specify that you want to attach the singularity\n on the left of the interval using the option marked_separatrix::\n\n sage: a = list(range(1,10))\n sage: b_odd = [4,3,6,5,7,9,8,2,1]\n sage: b_even = [6,5,4,3,7,9,8,2,1]\n sage: p_odd = iet.Permutation(a,b_odd)\n sage: p_even = iet.Permutation(a,b_even)\n sage: p_odd.stratum_component()\n H_4(4, 2)^odd\n sage: p_even.stratum_component()\n H_4(4, 2)^even\n \"\"\"\n from surface_dynamics.flat_surfaces.abelian_strata import (ASC, HypASC, NonHypASC, OddASC, EvenASC)\n\n if not self.is_irreducible():\n return list(map(lambda x: x.stratum_component(), self.decompose()))\n\n stratum = self.stratum()\n cc = stratum._cc\n\n if len(cc) == 1:\n return stratum.components()[0]\n\n if HypASC in cc:\n if self.is_hyperelliptic():\n return HypASC(stratum)\n else:\n cc = cc[1:]\n\n if len(cc) == 1:\n return cc[0](stratum)\n\n else:\n spin = self.arf_invariant()\n if spin == 0:\n return EvenASC(stratum)\n else:\n return OddASC(stratum)\n\n def order_of_rauzy_action(self, winner, side=None):\n r\"\"\"\n Returns the order of the action of a Rauzy move.\n\n INPUT:\n\n - ``winner`` - string ``'top'`` or ``'bottom'``\n\n - ``side`` - string ``'left'`` or ``'right'``\n\n OUTPUT:\n\n An integer corresponding to the order of the Rauzy action.\n\n EXAMPLES::\n\n sage: from surface_dynamics import *\n\n sage: p = iet.Permutation('a b c d','d a c b')\n sage: p.order_of_rauzy_action('top', 'right')\n 3\n sage: p.order_of_rauzy_action('bottom', 'right')\n 2\n sage: p.order_of_rauzy_action('top', 'left')\n 1\n sage: p.order_of_rauzy_action('bottom', 'left')\n 3\n \"\"\"\n winner = interval_conversion(winner)\n side = side_conversion(side)\n\n if side == -1:\n return self.length(winner) - self._twin[winner][-1] - 1\n elif side == 0:\n return self._twin[winner][0]\n\n def rauzy_move(self, winner, side='right', inplace=False):\n r\"\"\"\n Returns the permutation after a Rauzy move.\n\n INPUT:\n\n - ``winner`` - 'top' or 'bottom' interval\n\n - ``side`` - 'right' or 'left' (default: 'right') corresponding\n to the side on which the Rauzy move must be performed.\n\n - ``inplace`` - (default ``False``) whether the Rauzy move is\n performed inplace (to be used with care since permutations\n are hashable, set to ``True`` if you are sure to know what\n you are doing)\n\n OUTPUT:\n\n - a permutation\n\n EXAMPLES::\n\n sage: from surface_dynamics import *\n\n sage: p = iet.Permutation('a b','b a')\n sage: p.rauzy_move(winner='top', side='right') == p\n True\n sage: p.rauzy_move(winner='bottom', side='right') == p\n True\n sage: p.rauzy_move(winner='top', side='left') == p\n True\n sage: p.rauzy_move(winner='bottom', side='left') == p\n True\n\n The options winner can be shortened to 't', 'b' and 'r', 'l'. As you\n can see in the following example::\n\n sage: p = iet.Permutation('a b c','c b a')\n sage: p.rauzy_move(winner='t', side='r')\n a b c\n c a b\n sage: p.rauzy_move(winner='b', side='r')\n a c b\n c b a\n sage: p.rauzy_move(winner='t', side='l')\n a b c\n b c a\n sage: p.rauzy_move(winner='b', side='l')\n b a c\n c b a\n\n This works as well for reduced permutations::\n\n sage: p = iet.Permutation('a b c d','d b c a',reduced=True)\n sage: p.rauzy_move('t')\n a b c d\n d a b c\n\n If Rauzy induction is not well defined, an error is raised::\n\n sage: p = iet.Permutation('a b', 'a b')\n sage: p.rauzy_move('t')\n Traceback (most recent call last):\n ...\n ValueError: Rauzy induction is not well defined\n\n\n Test the inplace option::\n\n sage: p = iet.Permutation('a b c d', 'd c b a')\n sage: q = p.rauzy_move('t', inplace=True)\n sage: assert q is p\n sage: p\n a b c d\n d a c b\n sage: q = p.rauzy_move('b', inplace=True)\n sage: assert q is p\n \"\"\"\n winner = interval_conversion(winner)\n side = side_conversion(side)\n loser = 1 - winner\n\n if self._twin[0][side] == side or self._twin[0][side] == len(self)+side:\n raise ValueError(\"Rauzy induction is not well defined\")\n\n if inplace:\n res = self\n else:\n res = self.__copy__()\n\n wtp = res._twin[winner][side]\n\n if side == -1:\n res._move(loser, len(self._twin[loser])-1, loser, wtp+1)\n\n if side == 0:\n res._move(loser, 0, loser, wtp)\n\n return res\n\n def backward_rauzy_move(self, winner, side='right', inplace=False):\n r\"\"\"\n Returns the permutation before a Rauzy move.\n\n INPUT:\n\n - ``winner`` - 'top' or 'bottom' interval\n\n - ``side`` - 'right' or 'left' (default: 'right') corresponding\n to the side on which the Rauzy move must be performed.\n\n - ``inplace`` - (default ``False``) whether the Rauzy move is\n performed inplace (to be used with care since permutations\n are hashable, set to ``True`` if you are sure to know what\n you are doing)\n\n OUTPUT:\n\n - a permutation\n\n TESTS::\n\n sage: from surface_dynamics import *\n\n Testing the inversion on labelled permutations::\n\n sage: p = iet.Permutation('a b c d','d c b a')\n sage: for pos,side in [('t','r'),('b','r'),('t','l'),('b','l')]:\n ....: q = p.rauzy_move(pos,side)\n ....: print(q.backward_rauzy_move(pos,side) == p)\n ....: q = p.backward_rauzy_move(pos,side)\n ....: print(q.rauzy_move(pos,side) == p)\n True\n True\n True\n True\n True\n True\n True\n True\n\n Testing the inversion on reduced permutations::\n\n sage: p = iet.Permutation('a b c d','d c b a',reduced=True)\n sage: for pos,side in [('t','r'),('b','r'),('t','l'),('b','l')]:\n ....: q = p.rauzy_move(pos,side)\n ....: print(q.backward_rauzy_move(pos,side) == p)\n ....: q = p.backward_rauzy_move(pos,side)\n ....: print(q.rauzy_move(pos,side) == p)\n True\n True\n True\n True\n True\n True\n True\n True\n\n Test the inplace option::\n\n sage: p = iet.Permutation('a b c d', 'd c b a')\n sage: q = p.backward_rauzy_move('t', inplace=True)\n sage: assert q is p\n sage: p\n a b c d\n d b a c\n sage: q = p.backward_rauzy_move('t', inplace=True)\n sage: q = p.backward_rauzy_move('b', inplace=True)\n sage: assert q is p\n sage: q = p.rauzy_move('b', inplace=True)\n sage: q = p.rauzy_move('t', inplace=True)\n sage: q = p.rauzy_move('t', inplace=True)\n sage: p\n a b c d\n d c b a\n \"\"\"\n winner = interval_conversion(winner)\n side = side_conversion(side)\n\n loser = 1 - winner\n winner_twin = self._twin[winner][side]\n d = len(self)\n\n if inplace:\n res = self\n else:\n res = copy(self)\n\n if side == -1:\n if self._labels is not None:\n res._labels[loser].append(res._labels[loser].pop(winner_twin+1))\n\n # move the element\n res._twin[loser].append(res._twin[loser].pop(winner_twin+1))\n\n # correction for the moved element\n res._twin[winner][res._twin[loser][-1]] = d\n\n # shift twins that are after the moved element\n for j in range(winner_twin + 1, d):\n res._twin[winner][res._twin[loser][j]] -= 1\n\n elif side == 0:\n if res._labels is not None:\n res._labels[loser].insert(\n 0,\n res._labels[loser].pop(winner_twin-1))\n\n # move the element\n res._twin[loser].insert(\n 0,\n res._twin[loser].pop(winner_twin-1))\n\n # correction for the moved element\n res._twin[winner][res._twin[loser][0]] = 0\n\n # unshift elements before the moved element\n for j in range(1, winner_twin):\n res._twin[winner][res._twin[loser][j]] += 1\n\n return res\n\n def erase_marked_points(self):\n r\"\"\"\n Returns a permutation equivalent to self but without marked points.\n\n EXAMPLES::\n\n sage: from surface_dynamics import *\n\n sage: p = iet.Permutation('a b','b a')\n sage: p.erase_marked_points()\n a b\n b a\n sage: p = iet.Permutation('a b1 b2 c d', 'd c b1 b2 a')\n sage: p.erase_marked_points()\n a b1 c d\n d c b1 a\n sage: p = iet.Permutation('a0 a1 b0 b1 c0 c1 d0 d1','d0 d1 c0 c1 b0 b1 a0 a1')\n sage: p.erase_marked_points()\n a0 b0 c0 d0\n d0 c0 b0 a0\n sage: p = iet.Permutation('a b y0 y1 x0 x1 c d','c x0 x1 a d y0 y1 b')\n sage: p.erase_marked_points()\n a b c d\n c a d b\n sage: p = iet.Permutation('a x y z b','b x y z a')\n sage: p.erase_marked_points()\n a b\n b a\n sage: p = iet.Permutation(\"0 1 2 3 4 5 6\",\"6 0 3 2 4 1 5\")\n sage: p.stratum()\n H_3(4, 0)\n sage: p.erase_marked_points().stratum()\n H_3(4)\n \"\"\"\n if len(self) == 1:\n return self\n\n if not self.is_irreducible():\n raise ValueError(\"the permutation must be irreducible\")\n\n tops = [True]*len(self) # true if we keep and false if not\n bots = [True]*len(self)\n\n # remove the zeros which are not at the endpoints\n i = 0\n while i < len(self):\n i += 1\n while i < len(self) and self._twin[0][i] == self._twin[0][i-1]+1:\n tops[i] = False\n bots[self._twin[0][i]] = False\n i += 1\n\n # remove the fake zero on the left\n i0 = self._twin[1][0]-1\n i1 = self._twin[0][0]-1\n while i0>0 and i1>0 and self._twin[0][i0] == i1:\n tops[i0] = False\n bots[i1] = False\n i0 -= 1\n i1 -= 1\n\n # remove the fake zero on the right\n i0 = self._twin[1][-1]+1\n i1 = self._twin[0][-1]+1\n n = len(self)\n while i02:\n if top[-1] == bot[0] and bot[-1] != top[0]:\n if bot[1] == top[0] and bot[-1] == top[-2]:\n del bot[-1]\n del bot[1]\n del top[-2]\n bot.append(top[0])\n\n elif top[-1] != bot[0] and bot[-1] == top[0]:\n if top[1] == bot[0] and top[-1] == bot[-2]:\n del top[-1]\n del top[1]\n del bot[-2]\n top.append(bot[0])\n\n else:\n i0 = top.index(bot[-1])\n i1 = bot.index(top[-1])\n if bot[i1+1] == top[0] and top[i0+1] == bot[0]:\n del top[i0+1]\n del bot[i1]\n del bot[0]\n bot.insert(0, top[-1])\n\n return self.__class__((top,bot))\n\n def is_hyperelliptic(self):\n r\"\"\"\n Returns True if the permutation is in the class of the symmetric\n permutations (with eventual marked points).\n\n This is equivalent to say that the suspension lives in an hyperelliptic\n stratum of Abelian differentials H_hyp(2g-2) or H_hyp(g-1, g-1) with\n some marked points.\n\n EXAMPLES::\n\n sage: from surface_dynamics import *\n\n sage: iet.Permutation('a b c d','d c b a').is_hyperelliptic()\n True\n sage: iet.Permutation('0 1 2 3 4 5','5 2 1 4 3 0').is_hyperelliptic()\n False\n \"\"\"\n test = self.erase_marked_points()\n\n n = test.length_top()\n cylindric = test.to_standard()\n return cylindric._twin[0] == list(range(n-1,-1,-1))\n\n def to_cylindric(self):\n r\"\"\"\n Returns a cylindric permutation in the same Rauzy class.\n\n A permutation is *cylindric* if the first letter in the top interval is\n also the last letter of the bottom interval or if the last letter of the\n top interval is the first letter of the bottom interval.\n\n TESTS::\n\n sage: from surface_dynamics import *\n\n sage: p = iet.Permutation('a b c','c b a')\n sage: p.to_cylindric() == p\n True\n sage: p = iet.Permutation('a b c d','b d a c')\n sage: q = p.to_cylindric()\n sage: q[0][0] == q[1][-1] or q[1][0] == q[1][0]\n True\n \"\"\"\n tmp = copy(self)\n n = self.length(0)\n\n a0 = tmp._twin[0][-1]\n a1 = tmp._twin[1][-1]\n p_min = min(a0,a1)\n\n while p_min > 0:\n if p_min == a0:\n k_min = min(tmp._twin[1][a0+1:])\n k = n - tmp._twin[1].index(k_min) - 1\n\n for j in range(k):\n tmp = tmp.rauzy_move(0)\n\n else:\n k_min = min(tmp._twin[0][a1+1:])\n k = n - tmp._twin[0].index(k_min) - 1\n\n for j in range(k):\n tmp = tmp.rauzy_move(1)\n\n a0 = tmp._twin[0][-1]\n a1 = tmp._twin[1][-1]\n p_min = min(a0,a1)\n\n return tmp\n\n def is_cylindric(self):\n r\"\"\"\n Returns True if the permutation is cylindric\n\n A permutation `\\pi` is cylindric if `\\pi(1) = n` or `\\pi(n) = 1`. The\n name cylindric comes from geometry. A cylindric permutation has a\n suspension which is a flat surface with a completely periodic horizontal\n direction which is made of only one cylinder.\n\n\n EXAMPLES::\n\n sage: from surface_dynamics import *\n\n sage: iet.Permutation('1 2 3','3 2 1').is_cylindric()\n True\n sage: iet.Permutation('1 2 3','3 1 2').is_cylindric()\n True\n sage: iet.Permutation('1 2 3 4','3 1 2 4').is_cylindric()\n False\n \"\"\"\n return self._twin[0][-1] == 0 or self._twin[1][-1] == 0\n\n def to_standard(self):\n r\"\"\"\n Returns a standard permutation in the same Rauzy class.\n\n TESTS::\n\n sage: from surface_dynamics import *\n\n sage: p = iet.Permutation('a b c','c b a')\n sage: p.to_standard() == p\n True\n sage: p = iet.Permutation('a b c d','b d a c')\n sage: q = p.to_standard()\n sage: q[0][0] == q[1][-1]\n True\n sage: q[1][0] == q[1][0]\n True\n \"\"\"\n tmp = self.to_cylindric()\n n = len(self)\n\n a0 = tmp._twin[0][-1]\n a1 = tmp._twin[1][-1]\n p_min = min(a0,a1)\n\n if a0 == 0:\n for j in range(n - tmp._twin[1].index(0) - 1):\n tmp = tmp.rauzy_move(0)\n\n else:\n for j in range(n - tmp._twin[0].index(0) - 1):\n tmp = tmp.rauzy_move(1)\n\n return tmp\n\n def is_standard(self):\n r\"\"\"\n Test if the permutation is standard\n\n A permutation `\\pi` is standard if '\\pi(n) = 1` and `\\pi(1) = n`.\n\n EXAMPLES::\n\n sage: from surface_dynamics import *\n\n sage: p = iet.Permutation('a b c d','d c b a')\n sage: p.is_standard()\n True\n sage: p = p.rauzy_move('top')\n sage: p.is_standard()\n False\n \"\"\"\n return self._twin[0][-1] == 0 and self._twin[1][-1] == 0\n\n def to_permutation(self):\n r\"\"\"\n Returns the permutation as an element of the symmetric group.\n\n EXAMPLES::\n\n sage: from surface_dynamics import *\n\n sage: p = iet.Permutation('a b c','c b a')\n sage: p.to_permutation()\n [3, 2, 1]\n\n ::\n\n sage: p = Permutation([2,4,1,3])\n sage: q = iet.Permutation(p)\n sage: q.to_permutation() == p\n True\n \"\"\"\n from sage.combinat.permutation import Permutation\n return Permutation(list(map(lambda x: x+1,self._twin[1])))\n\n def suspension_cone(self, winner=None):\n r\"\"\"\n Return the cone of suspension data.\n\n A suspension data `\\tau` for a permutation `(\\pi_{top}, \\pi_{bot})`\n on the alphabet `\\mathcal{A}` is a real vector in `RR^\\mathcal{A}`\n so that\n\n .. MATH::\n\n \\forall 1 \\leq k < d,\\,\n \\sum_{\\beta: \\pi_{top}(\\beta) \\leq k} \\tau_\\beta > 0\n \\quad \\text{and} \\quad\n \\sum_{\\beta: \\pi_{bot}(\\beta) \\leq k} \\tau_\\beta < 0.\n\n A suspension data determines half of a zippered rectangle construction.\n The other half is the length data that is a positive vector in\n `\\RR^\\mathcal{A}`.\n\n INPUT:\n\n - ``winner`` - (optional) either ``None``, ``\"top\"`` or ``\"bottom\"``. If\n not ``None`` , then return only half of the suspension cone corresponding\n to data that either comes from a top or bottom Rauzy induction.\n\n .. SEEALSO::\n\n :meth:`heights_cone`\n\n EXAMPLES::\n\n sage: from surface_dynamics import *\n sage: p = iet.Permutation('a b c d e f', 'e c b f d a')\n sage: H = p.suspension_cone()\n sage: H.dimension()\n 6\n sage: rays = [r.vector() for r in H.rays()]\n sage: r = sum(randint(1,5)*ray for ray in rays)\n sage: r[0]>0 and r[0]+r[1] > 0 and r[0]+r[1]+r[2] > 0\n True\n sage: r[0]+r[1]+r[2]+r[3]>0\n True\n sage: r[0]+r[1]+r[2]+r[3]+r[4]>0\n True\n sage: r[4]<0 and r[4]+r[2]<0 and r[4]+r[2]+r[1] < 0\n True\n sage: r[4]+r[2]+r[1]+r[5]<0\n True\n sage: r[4]+r[2]+r[1]+r[5]+r[3]<0\n True\n\n The construction also works with reduced permutations (ie not carrying\n labels)::\n\n sage: p = iet.Permutation('a b c d', 'd c b a', reduced=True)\n sage: H = p.suspension_cone()\n sage: r = sum(r.vector() for r in H.rays())\n sage: r[0] > 0 and r[0]+r[1] > 0 and r[0]+r[1]+r[2] > 0\n True\n sage: r[3] < 0 and r[3]+r[2] < 0 and r[3]+r[2]+r[1] < 0\n True\n \"\"\"\n n = len(self)\n ieqs = []\n\n if self._labels is not None:\n labels = self._labels\n else:\n labels = [list(range(n)), self._twin[1]]\n\n for i in range(1,len(self)):\n ieq = [0]*(n+1)\n for j in range(i):\n ieq[labels[0][j]+1] = 1\n ieqs.append(ieq)\n\n ieq = [0]*(n+1)\n for j in range(i):\n ieq[labels[1][j]+1] = -1\n ieqs.append(ieq)\n\n if winner is not None:\n winner = interval_conversion(winner)\n if winner == 0:\n # sum of heights is <= 0\n ieqs.append([0] + [-1] * len(self))\n elif winner == 1:\n # sum of heights is >= 0\n ieqs.append([0] + [1] * len(self))\n\n from sage.geometry.polyhedron.constructor import Polyhedron\n return Polyhedron(ieqs=ieqs)\n\n def heights_cone(self, side=None):\n r\"\"\"\n Return the cone of heights data.\n\n .. SEEALSO::\n\n :meth:`suspension_cone`\n\n EXAMPLES::\n\n sage: from surface_dynamics import *\n sage: p = iet.Permutation('a b c d', 'd c b a')\n sage: C = p.heights_cone()\n sage: C\n A 4-dimensional polyhedron in QQ^4 defined as the convex hull of 1 vertex and 5 rays\n sage: C.rays_list()\n [[0, 0, 1, 1], [0, 1, 1, 0], [0, 1, 1, 1], [1, 1, 0, 0], [1, 1, 1, 0]]\n\n sage: p.heights_cone('top').rays_list()\n [[0, 0, 1, 1], [0, 1, 1, 0], [1, 1, 0, 0], [1, 1, 1, 0]]\n sage: p.heights_cone('bot').rays_list()\n [[0, 0, 1, 1], [0, 1, 1, 0], [0, 1, 1, 1], [1, 1, 0, 0]]\n \"\"\"\n I = self.intersection_matrix()\n C = self.suspension_cone(side)\n\n from sage.geometry.polyhedron.constructor import Polyhedron\n return Polyhedron(rays=[-I*c.vector() for c in C.rays()])\n\n def invariant_density_rauzy(self, winner=None, var='x'):\n r\"\"\"\n Return the invariant density for the Rauzy induction.\n\n Goes via the zippered rectangle construction of [Vee1982]_.\n\n EXAMPLES::\n\n sage: from surface_dynamics import iet\n sage: f = iet.Permutation('a b c d', 'd c b a').invariant_density_rauzy()\n sage: f\n (1)/((x2 + x3)*(x1 + x2)*(x1 + x2 + x3)*(x0 + x1)) + (1)/((x2 + x3)*(x1 + x2)*(x0 + x1)*(x0 + x1 + x2))\n\n sage: f_top = iet.Permutation('a b c d', 'd c b a').invariant_density_rauzy('top')\n sage: f_top\n (1)/((x2 + x3)*(x1 + x2)*(x0 + x1)*(x0 + x1 + x2))\n sage: f_bot = iet.Permutation('a b c d', 'd c b a').invariant_density_rauzy('bot')\n sage: f_bot\n (1)/((x2 + x3)*(x1 + x2)*(x1 + x2 + x3)*(x0 + x1))\n\n sage: f == f_bot + f_top\n True\n \"\"\"\n from surface_dynamics.misc.additive_multivariate_generating_series import AdditiveMultivariateGeneratingSeriesRing\n from surface_dynamics.misc.linalg import cone_triangulate\n\n d = len(self)\n S = self.suspension_cone(winner=winner)\n Omega = self.intersection_matrix()\n M = AdditiveMultivariateGeneratingSeriesRing(var, d)\n\n ans = M.zero()\n hyperplane = sum(Omega.columns())\n fac = 1 / ZZ(d).factorial()\n for t in cone_triangulate(S, hyperplane):\n heights = [r * Omega for r in t]\n for h in heights: h.set_immutable()\n d = {}\n for h in heights:\n if h not in d: d[h] = ZZ.one()\n else: d[h] += ZZ.one()\n ans += M.term(ZZ.one(), d)\n\n return ans\n\n def to_origami(self):\n r\"\"\"\n Return the origami associated to a cylindric permutation.\n\n EXAMPLES::\n\n sage: from surface_dynamics import iet\n sage: p = iet.Permutation('a b', 'b a')\n sage: p.to_origami()\n (1)\n (1)\n\n sage: p = iet.Permutation('a b c e d f g', 'f e b g d c a')\n sage: p.to_origami()\n (1,2,3,4,5,6)\n (1,3,2,6,4,5)\n sage: assert p.stratum_component() == p.to_origami().stratum_component()\n \"\"\"\n n = len(self._twin[0])\n if self._twin[1][-1] != 0:\n raise ValueError(\"to_origami is only valid for cylindric permutation\")\n\n from surface_dynamics.misc.permutation import perm_invert\n from surface_dynamics.flat_surfaces.origamis.origami import Origami\n r = list(range(1, n-1))\n r.append(0)\n u = perm_invert([self._twin[1][i]-1 for i in range(n-1)])\n return Origami(r, u, as_tuple=True)\n\n def _masur_polygon_helper(self, lengths, heights):\n n = len(self)\n\n from sage.structure.sequence import Sequence\n\n s = Sequence(list(lengths) + list(heights))\n lengths = s[:len(lengths)]\n heights = s[len(lengths):]\n base_ring = s.universe()\n\n if self._labels is None:\n lengths = [lengths[:n]] + [lengths[j] for j in self._twins[1]]\n heights = [heights[:n]] + [heights[j] for j in self._twins[1]]\n else:\n lengths = [[lengths[j] for j in self._labels[i]] for i in [0, 1]]\n heights = [[heights[j] for j in self._labels[i]] for i in [0, 1]]\n\n try:\n zero = base_ring.zero()\n except AttributeError:\n zero = base_ring(0)\n\n # build the polygon in counter-clockwise order\n Ltop = [(zero,zero)]\n for i,dx,dy in zip(range(n), lengths[0], heights[0]):\n x, y = Ltop[-1]\n if dx <= 0 or (y <= 0 and i != 0):\n raise ValueError('invalid suspension data dx={} y={} at i={} on top'.format(dx, y, i))\n Ltop.append((x+dx, y+dy))\n Lbot = [(zero,zero)]\n for i,dx,dy in zip(range(n), lengths[1], heights[1]):\n x, y = Lbot[-1]\n if dx <= 0 or (y >= 0 and i != 0):\n raise ValueError('invalid suspension data dx={} y={} at i={} on bot'.format(dx, y, i))\n Lbot.append((x+dx, y+dy))\n\n assert Ltop[0] == Lbot[0] and Ltop[-1] == Lbot[-1], (Ltop, Lbot)\n Ltop.pop(0)\n Lbot.pop(0)\n endpoint = Ltop.pop(-1)\n Lbot.pop(-1)\n\n from flatsurf.geometry.polygon import Polygon\n\n ptop = Ltop[0]\n pbot = Lbot[0]\n triangles = [Polygon(vertices=[(zero,zero), pbot, ptop])]\n tops = [(0,2)]\n bots = [(0,0)]\n mids = [(0,1)]\n itop = 1\n ibot = 1\n k = 1\n while itop < len(Ltop) or ibot < len(Lbot):\n xtop = Ltop[itop][0] if itop < len(Ltop) else None\n xbot = Lbot[ibot][0] if ibot < len(Lbot) else None\n if xbot is None or (xtop is not None and xtop <= xbot):\n # add a triangle with a new vertex on top\n pptop = Ltop[itop]\n itop += 1\n triangles.append(Polygon(vertices=[ptop,pbot,pptop]))\n tops.append((k,2))\n mids.append((k,0))\n mids.append((k,1))\n ptop = pptop\n else:\n ppbot = Lbot[ibot]\n ibot += 1\n triangles.append(Polygon(vertices=[ptop,pbot,ppbot]))\n bots.append((k,1))\n mids.append((k,0))\n mids.append((k,2))\n pbot = ppbot\n k += 1\n\n triangles.append(Polygon(vertices=[ptop, pbot, endpoint]))\n tops.append((k, 2))\n bots.append((k, 1))\n mids.append((k, 0))\n\n assert len(tops) == len(bots) == n, (n, tops, bots)\n assert len(triangles) == 2*n-2, (n, len(triangles))\n\n return base_ring, triangles, tops, bots, mids\n\n def masur_polygon(self, lengths, heights):\n r\"\"\"\n Return the Masur polygon for the given ``lengths`` and ``heights``\n\n EXAMPLES::\n\n sage: from surface_dynamics import iet\n\n sage: p = iet.Permutation('a b c', 'c b a')\n sage: S = p.masur_polygon([1,4,2], [2,0,-1]) # optional: sage_flatsurf\n sage: S # optional: sage_flatsurf\n Translation Surface in H_1(0^2) built from 2 isosceles triangles and 2 triangles\n sage: S.stratum() # optional: sage_flatsurf\n H_1(0^2)\n\n Generic construction using suspension cone::\n\n sage: p = iet.Permutation('a b c d e f g h i', 'b g f c a d i e h')\n sage: x = polygen(QQ)\n sage: poly = x^3 - x - 1\n sage: emb = AA.polynomial_root(poly, RIF(1.3,1.4))\n sage: K = NumberField(poly, 'a', embedding=emb)\n sage: a = K.gen()\n sage: R = [r.vector() for r in p.suspension_cone().rays()]\n sage: C = [1, a, a+1, 2-a, 2, 1, a, a, 1, a-1, 1]\n sage: H = sum(c*r for c,r in zip(C,R))\n sage: H\n (a + 2, -2, 2, -2*a + 2, 3*a, -a - 4, 0, -a + 1, -2*a - 1)\n sage: L = [1+a**2, 2*a**2-1, 1, 1, 1+a, a**2, a-1, a-1, 2]\n sage: S = p.masur_polygon(L, H) # optional: sage_flatsurf\n sage: S # optional: sage_flatsurf\n Translation Surface in H_3(1^4) built from 15 triangles and a right triangle\n\n TESTS::\n\n sage: p = iet.Permutation('a b c', 'c b a')\n sage: for L in [[1,4,2],[2,4,1],[5,1,1],[1,5,1],[1,1,5]]: # optional: sage_flatsurf\n ....: S = p.masur_polygon(L, [2,0,-1])\n ....: assert S.stratum() == p.stratum()\n \"\"\"\n base_ring, triangles, tops, bots, mids = self._masur_polygon_helper(lengths, heights)\n\n from flatsurf import MutableOrientedSimilaritySurface\n S = MutableOrientedSimilaritySurface(base_ring)\n for t in triangles:\n S.add_polygon(t)\n for i in range(len(self)):\n p1, e1 = tops[i]\n p2, e2 = bots[self._twin[0][i]]\n S.glue((p1, e1), (p2, e2))\n for i in range(0,len(mids),2):\n p1, e1 = mids[i]\n p2, e2 = mids[i+1]\n S.glue((p1, e1), (p2, e2))\n S.set_immutable()\n return S\n\n\nclass OrientablePermutationLI(PermutationLI):\n r\"\"\"\n Template for quadratic permutation.\n\n .. warning::\n\n Internal class! Do not use directly!\n\n AUTHOR:\n\n - Vincent Delecroix (2008-12-20): initial version\n\n \"\"\"\n def rauzy_move(self, winner, side='right', inplace=False):\n r\"\"\"\n Returns the permutation after a Rauzy move.\n\n TESTS::\n\n sage: from surface_dynamics import *\n\n sage: p = iet.GeneralizedPermutation('a a b','b c c',reduced=True)\n sage: p.rauzy_move(0)\n a a b\n b c c\n sage: p.rauzy_move(1)\n a a\n b b c c\n\n ::\n\n sage: p = iet.GeneralizedPermutation('a a b','b c c',reduced=True)\n sage: p.rauzy_move(0)\n a a b\n b c c\n sage: p.rauzy_move(1)\n a a\n b b c c\n\n ::\n\n sage: p = iet.GeneralizedPermutation('a a b','b c c',reduced=True)\n sage: pp = p.rauzy_move(0, inplace=True)\n sage: p\n a a b\n b c c\n sage: pp is p\n True\n \"\"\"\n winner = interval_conversion(winner)\n side = side_conversion(side)\n loser = 1 - winner\n\n if inplace:\n res = self\n else:\n res = self.__copy__()\n\n wti, wtp = res._twin[winner][side]\n\n if side == -1:\n d = len(res._twin[loser])\n if wti == loser:\n res._move(loser, d-1, loser, wtp+1)\n else:\n res._move(loser, d-1, winner, wtp)\n\n if side == 0:\n if wti == loser:\n res._move(loser, 0, loser, wtp)\n else:\n res._move(loser, 0, winner, wtp+1)\n\n return res\n\n def backward_rauzy_move(self, winner, side='top'):\n r\"\"\"\n Return the permutation before the Rauzy move.\n\n TESTS::\n\n sage: from surface_dynamics import *\n\n Tests the inversion on labelled generalized permutations::\n\n sage: p = iet.GeneralizedPermutation('a a b b','c c d d')\n sage: for pos,side in [('t','r'),('b','r'),('t','l'),('b','l')]:\n ....: q = p.rauzy_move(pos,side)\n ....: print(q.backward_rauzy_move(pos,side) == p)\n ....: q = p.backward_rauzy_move(pos,side)\n ....: print(q.rauzy_move(pos,side) == p)\n True\n True\n True\n True\n True\n True\n True\n True\n\n Tests the inversion on reduced generalized permutations::\n\n sage: p = iet.GeneralizedPermutation('a a b b','c c d d',reduced=True)\n sage: for pos,side in [('t','r'),('b','r'),('t','l'),('b','l')]:\n ....: q = p.rauzy_move(pos,side)\n ....: print(q.backward_rauzy_move(pos,side) == p)\n ....: q = p.backward_rauzy_move(pos,side)\n ....: print(q.rauzy_move(pos,side) == p)\n True\n True\n True\n True\n True\n True\n True\n True\n \"\"\"\n winner = interval_conversion(winner)\n side = side_conversion(side)\n loser = 1 - winner\n\n res = copy(self)\n\n wti, wtp = res._twin[winner][side]\n\n\n if side == -1:\n d = len(self._twin[loser])\n if wti == loser:\n res._move(loser, wtp+1, loser, d)\n else:\n res._move(winner, wtp-1, loser, d)\n\n if side == 0:\n if wti == loser:\n res._move(loser, wtp-1, loser, 0)\n else:\n res._move(winner, wtp+1, loser, 0)\n\n return res\n\n def stratum(self):\n r\"\"\"\n Returns the stratum associated to self\n\n EXAMPLES::\n\n sage: from surface_dynamics import *\n\n sage: p = iet.GeneralizedPermutation('a b b','c c a')\n sage: p.stratum()\n Q_0(-1^4)\n \"\"\"\n if self.is_irreducible():\n from surface_dynamics.flat_surfaces.quadratic_strata import QuadraticStratum\n return QuadraticStratum([x-2 for x in self.profile()])\n raise ValueError(\"stratum is well defined only for irreducible permutations\")\n\n\nFlippedPermutation = Permutation\n\n\nclass FlippedPermutationIET(PermutationIET):\n r\"\"\"\n Template for flipped Abelian permutations.\n\n .. warning::\n\n Internal class! Do not use directly!\n \"\"\"\n def rauzy_move(self, winner, side='right', inplace=False):\n r\"\"\"\n Returns the permutation after a Rauzy move.\n\n TESTS::\n\n sage: from surface_dynamics import iet\n\n sage: p = iet.Permutation('a b c', 'c a b', flips=['b'], reduced=True)\n sage: p.rauzy_move('t','r')\n a -b c\n c -b a\n sage: p.rauzy_move('b','r')\n a -b -c\n -b a -c\n sage: p.rauzy_move('t','l')\n a -b c\n c a -b\n sage: p.rauzy_move('b','l')\n -a b c\n c b -a\n\n sage: p = iet.GeneralizedPermutation('a b c d','d a b c',flips='abcd')\n sage: p\n -a -b -c -d\n -d -a -b -c\n sage: p.rauzy_move('top','right')\n -a -b c -d\n c -d -a -b\n sage: p.rauzy_move('bottom','right')\n -a -b d -c\n d -a -b -c\n sage: p.rauzy_move('top','left')\n -a -b -c d\n -a d -b -c\n sage: p.rauzy_move('bottom','left')\n -b -c -d a\n -d a -b -c\n\n sage: p = iet.GeneralizedPermutation('a b c d','d a b c',flips='abcd')\n sage: pp = p.rauzy_move('top', 'right', inplace=True)\n sage: pp is p\n True\n sage: p\n -a -b c -d\n c -d -a -b\n \"\"\"\n winner = interval_conversion(winner)\n side = side_conversion(side)\n loser = 1 - winner\n\n if inplace:\n res = self\n else:\n res = self.__copy__()\n\n wtp = res._twin[winner][side]\n flip = self._flips[winner][side]\n if flip == -1:\n res._flips[loser][side] *= -1\n res._flips[winner][res._twin[loser][side]] *= -1\n flip = 1\n else:\n flip = 0\n\n if side == -1:\n d = len(res._twin[loser])\n res._move(loser, d-1, loser, wtp+1-flip)\n\n if side == 0:\n res._move(loser, 0, loser, wtp+flip)\n\n return res\n\n def backward_rauzy_move(self, winner, side=-1):\n r\"\"\"\n Returns the permutation before a Rauzy move.\n\n TESTS::\n\n sage: from surface_dynamics import *\n\n sage: p = iet.GeneralizedPermutation('a b c d e','d a b e c', flips='abcd')\n sage: for pos,side in [('t','r'),('b','r'),('t','l'),('b','l')]:\n ....: q = p.rauzy_move(pos,side)\n ....: print(q.backward_rauzy_move(pos,side) == p)\n ....: q = p.backward_rauzy_move(pos,side)\n ....: print(q.rauzy_move(pos,side) == p)\n True\n True\n True\n True\n True\n True\n True\n True\n\n Testing the inversion on reduced permutations::\n\n sage: p = iet.Permutation('f a b c d e','d f c b e a', flips='abcd', reduced=True)\n sage: for pos,side in [('t','r'),('b','r'),('t','l'),('b','l')]:\n ....: q = p.rauzy_move(pos,side)\n ....: print(q.backward_rauzy_move(pos,side) == p)\n ....: q = p.backward_rauzy_move(pos,side)\n ....: print(q.rauzy_move(pos,side) == p)\n True\n True\n True\n True\n True\n True\n True\n True\n \"\"\"\n winner = interval_conversion(winner)\n side = side_conversion(side)\n loser = 1 - winner\n\n res = copy(self)\n\n wtp = res._twin[winner][side]\n flip = self._flips[winner][side]\n\n if side == -1:\n d = len(self._twin[loser])\n\n if flip == -1:\n res._flips[loser][wtp-1] *= -1\n res._flips[winner][res._twin[loser][wtp-1]] *= -1\n res._move(loser, wtp-1, loser, d)\n else:\n res._move(loser, wtp+1, loser, d)\n\n if side == 0:\n if flip == -1:\n res._flips[loser][wtp+1] *= -1\n res._flips[winner][res._twin[loser][wtp+1]] *= -1\n res._move(loser, wtp+1, loser, 0)\n else:\n res._move(loser, wtp-1, loser, 0)\n\n return res\n\n\nclass FlippedPermutationLI(PermutationLI):\n r\"\"\"\n Template for flipped quadratic permutations.\n\n .. warning::\n\n Internal class! Do not use directly!\n\n AUTHORS:\n\n - Vincent Delecroix (2008-12-20): initial version\n\n \"\"\"\n def rauzy_move(self, winner, side='right', inplace=False):\n r\"\"\"\n Rauzy move\n\n TESTS::\n\n sage: from surface_dynamics import iet\n\n sage: p = iet.GeneralizedPermutation('a b c b','d c d a',flips='abcd')\n sage: p\n -a -b -c -b\n -d -c -d -a\n sage: p.rauzy_move('top','right')\n a -b a -c -b\n -d -c -d\n sage: p.rauzy_move('bottom','right')\n b -a b -c\n -d -c -d -a\n sage: p.rauzy_move('top','left')\n -a -b -c -b\n -c d -a d\n sage: p.rauzy_move('bottom','left')\n -b -c -b\n -d -c a -d a\n\n sage: p = iet.GeneralizedPermutation('a b c b','d c d a',flips='abcd')\n sage: pp = p.rauzy_move('top', 'right', inplace=True)\n sage: p\n a -b a -c -b\n -d -c -d\n sage: pp is p\n True\n \"\"\"\n winner = interval_conversion(winner)\n side = side_conversion(side)\n loser = 1 - winner\n\n if inplace:\n res = self\n else:\n res = self.__copy__()\n\n wti, wtp = res._twin[winner][side]\n flip = res._flips[winner][side]\n if flip == -1:\n res._flips[loser][side] *= -1\n lti,ltp = res._twin[loser][side]\n res._flips[lti][ltp] *= -1\n flip = 1\n else:\n flip = 0\n\n if side == -1:\n d = len(res._twin[loser])\n if wti == loser:\n res._move(loser, d-1, loser, wtp+1-flip)\n else:\n res._move(loser, d-1, winner, wtp+flip)\n\n if side == 0:\n if wti == loser:\n res._move(loser, 0, loser, wtp+flip)\n else:\n res._move(loser, 0, winner, wtp+1-flip)\n\n return res\n\n def backward_rauzy_move(self, winner, side=-1):\n r\"\"\"\n Rauzy move\n\n TESTS::\n\n sage: from surface_dynamics import *\n\n sage: p = iet.GeneralizedPermutation('a b c e b','d c d a e',flips='abcd')\n sage: for pos,side in [('t','r'),('b','r'),('t','l'),('b','l')]:\n ....: q = p.rauzy_move(pos,side)\n ....: print(q.backward_rauzy_move(pos,side) == p)\n ....: q = p.backward_rauzy_move(pos,side)\n ....: print(q.rauzy_move(pos,side) == p)\n True\n True\n True\n True\n True\n True\n True\n True\n\n Testing the inversion on reduced permutations::\n\n sage: p = iet.GeneralizedPermutation('a b c e b','d c d a e',flips='abcd',reduced=True)\n sage: for pos,side in [('t','r'),('b','r'),('t','l'),('b','l')]:\n ....: q = p.rauzy_move(pos,side)\n ....: print(q.backward_rauzy_move(pos,side) == p)\n ....: q = p.backward_rauzy_move(pos,side)\n ....: print(q.rauzy_move(pos,side) == p)\n True\n True\n True\n True\n True\n True\n True\n True\n \"\"\"\n winner = interval_conversion(winner)\n side = side_conversion(side)\n loser = 1 - winner\n\n res = copy(self)\n\n wti, wtp = res._twin[winner][side]\n flip = self._flips[winner][side]\n\n if side == -1:\n d = len(self._twin[loser])\n if wti == loser:\n if flip == -1:\n res._flips[loser][wtp-1] *= -1\n lti,ltp = res._twin[loser][wtp-1]\n res._flips[lti][ltp] *= -1\n res._move(loser, wtp-1, loser, d)\n else:\n res._move(loser, wtp+1, loser, d)\n\n else:\n if flip == -1:\n res._flips[winner][wtp+1] *= -1\n lti,ltp = res._twin[winner][wtp+1]\n res._flips[lti][ltp] *= -1\n res._move(winner, wtp+1, loser, d)\n else:\n res._move(winner, wtp-1, loser, d)\n\n\n if side == 0:\n if wti == loser:\n if flip == -1:\n res._flips[loser][wtp+1] *= -1\n lti,ltp = res._twin[loser][wtp+1]\n res._flips[lti][ltp] *= -1\n res._move(loser, wtp+1, loser, 0)\n else:\n res._move(loser, wtp-1, loser, 0)\n else:\n if flip == -1:\n res._flips[winner][wtp-1] *= -1\n lti,ltp = res._twin[winner][wtp-1]\n res._flips[lti][ltp] *= -1\n res._move(winner, wtp-1, loser, 0)\n else:\n res._move(winner, wtp+1, loser, 0)\n\n return res\n\nclass RauzyDiagram(SageObject):\n r\"\"\"\n Template for Rauzy diagrams.\n\n .. warning:\n\n Internal class! Do not use directly!\n\n AUTHORS:\n\n - Vincent Delecroix (2008-12-20): initial version\n\n \"\"\"\n # TODO: pickle problem of Path (it does not understand what is its parent)\n __metaclass__ = NestedClassMetaclass\n\n class Path(SageObject):\n r\"\"\"\n Path in Rauzy diagram.\n\n A path in a Rauzy diagram corresponds to a subsimplex of the simplex of\n lengths. This correspondence is obtained via the Rauzy induction. To a\n idoc IET we can associate a unique path in a Rauzy diagram. This\n establishes a correspondence between infinite full path in Rauzy diagram\n and equivalence topologic class of IET.\n \"\"\"\n def __init__(self, parent, *data):\n r\"\"\"\n Constructor of the path.\n\n TESTS::\n\n sage: from surface_dynamics import *\n\n sage: p = iet.Permutation('a b c', 'c b a')\n sage: r = p.rauzy_diagram()\n sage: g = r.path(p, 0, 1, 0); g\n Path of length 3 in a Rauzy diagram\n\n Check for trac ticket 8388::\n\n sage: loads(dumps(g)) == g\n True\n \"\"\"\n self._parent = parent\n\n if len(data) == 0:\n raise ValueError(\"No empty data\")\n\n start = data[0]\n if start not in self._parent:\n raise ValueError(\"Starting point not in this Rauzy diagram\")\n\n self._start = self._parent._permutation_to_vertex(start)\n\n cur_vertex = self._start\n self._edge_types = []\n\n n = len(self._parent._edge_types)\n for i in data[1:]:\n if not isinstance(i, (int,Integer)): # try parent method\n i = self._parent.edge_types_index(i)\n\n if i < 0 or i > n:\n raise ValueError(\"indices must be integer between 0 and %d\"%(n))\n neighbours = self._parent._succ[cur_vertex]\n if neighbours[i] is None:\n raise ValueError(\"Invalid path\")\n\n cur_vertex = neighbours[i]\n self._edge_types.append(i)\n\n self._end = cur_vertex\n\n def _repr_(self):\n r\"\"\"\n Returns a representation of the path.\n\n TESTS::\n\n sage: from surface_dynamics import *\n\n sage: p = iet.Permutation('a b','b a')\n sage: r = p.rauzy_diagram()\n sage: r.path(p) #indirect doctest\n Path of length 0 in a Rauzy diagram\n sage: r.path(p,'top') #indirect doctest\n Path of length 1 in a Rauzy diagram\n sage: r.path(p,'bottom') #indirect doctest\n Path of length 1 in a Rauzy diagram\n \"\"\"\n return \"Path of length %d in a Rauzy diagram\" %(len(self))\n\n def start(self):\n r\"\"\"\n Returns the first vertex of the path.\n\n EXAMPLES::\n\n sage: from surface_dynamics import *\n\n sage: p = iet.Permutation('a b c','c b a')\n sage: r = p.rauzy_diagram()\n sage: g = r.path(p, 't', 'b')\n sage: g.start() == p\n True\n \"\"\"\n return self._parent._vertex_to_permutation(self._start)\n\n def end(self):\n r\"\"\"\n Returns the last vertex of the path.\n\n EXAMPLES::\n\n sage: from surface_dynamics import *\n\n sage: p = iet.Permutation('a b c','c b a')\n sage: r = p.rauzy_diagram()\n sage: g1 = r.path(p, 't', 'b', 't')\n sage: g1.end() == p\n True\n sage: g2 = r.path(p, 'b', 't', 'b')\n sage: g2.end() == p\n True\n \"\"\"\n return self._parent._vertex_to_permutation(self._end)\n\n def edge_types(self):\n r\"\"\"\n Returns the edge types of the path.\n\n EXAMPLES::\n\n sage: from surface_dynamics import *\n\n sage: p = iet.Permutation('a b c','c b a')\n sage: r = p.rauzy_diagram()\n sage: g = r.path(p, 0, 1)\n sage: g.edge_types()\n [0, 1]\n \"\"\"\n return copy(self._edge_types)\n\n def __eq__(self, other):\n r\"\"\"\n Tests equality\n\n TESTS::\n\n sage: from surface_dynamics import *\n\n sage: p1 = iet.Permutation('a b','b a')\n sage: r1 = p1.rauzy_diagram()\n sage: p2 = p1.reduced()\n sage: r2 = p2.rauzy_diagram()\n sage: r1.path(p1,0,1) == r2.path(p2,0,1)\n False\n sage: r1.path(p1,0) == r1.path(p1,0)\n True\n sage: r1.path(p1,1) == r1.path(p1,0)\n False\n \"\"\"\n return (\n type(self) == type(other) and\n self._parent == other._parent and\n self._start == other._start and\n self._edge_types == other._edge_types)\n\n def __ne__(self,other):\n r\"\"\"\n Tests inequality\n\n TESTS::\n\n sage: from surface_dynamics import *\n\n sage: p1 = iet.Permutation('a b','b a')\n sage: r1 = p1.rauzy_diagram()\n sage: p2 = p1.reduced()\n sage: r2 = p2.rauzy_diagram()\n sage: r1.path(p1,0,1) != r2.path(p2,0,1)\n True\n sage: r1.path(p1,0) != r1.path(p1,0)\n False\n sage: r1.path(p1,1) != r1.path(p1,0)\n True\n \"\"\"\n return not self == other\n\n def __copy__(self):\n r\"\"\"\n Returns a copy of the path.\n\n TESTS::\n\n sage: from surface_dynamics import *\n\n sage: p = iet.Permutation('a b c','c b a')\n sage: r = p.rauzy_diagram()\n sage: g1 = r.path(p,0,1,0,0)\n sage: g2 = copy(g1)\n sage: g1 is g2\n False\n \"\"\"\n res = self.__class__(self._parent, self.start())\n res._edge_types = copy(self._edge_types)\n res._end = copy(self._end)\n return res\n\n def pop(self):\n r\"\"\"\n Pops the queue of the path\n\n OUTPUT:\n\n a path corresponding to the last edge\n\n EXAMPLES::\n\n sage: from surface_dynamics import *\n\n sage: p = iet.Permutation('a b','b a')\n sage: r = p.rauzy_diagram()\n sage: g = r.path(p,0,1,0)\n sage: g0,g1,g2,g3 = g[0], g[1], g[2], g[3]\n sage: g.pop() == r.path(g2,0)\n True\n sage: g == r.path(g0,0,1)\n True\n sage: g.pop() == r.path(g1,1)\n True\n sage: g == r.path(g0,0)\n True\n sage: g.pop() == r.path(g0,0)\n True\n sage: g == r.path(g0)\n True\n sage: g.pop() == r.path(g0)\n True\n \"\"\"\n if len(self) == 0:\n return self._parent.path(self.start())\n\n else:\n e = self._edge_types.pop()\n self._end = self._parent._pred[self._end][e]\n return self._parent.path(self.end(),e)\n\n def append(self, edge_type):\n r\"\"\"\n Append an edge to the path.\n\n EXAMPLES::\n\n sage: from surface_dynamics import *\n\n sage: p = iet.Permutation('a b c','c b a')\n sage: r = p.rauzy_diagram()\n sage: g = r.path(p)\n sage: g.append('top')\n sage: g\n Path of length 1 in a Rauzy diagram\n sage: g.append('bottom')\n sage: g\n Path of length 2 in a Rauzy diagram\n \"\"\"\n if not isinstance(edge_type, (int,Integer)):\n edge_type = self._parent.edge_types_index(edge_type)\n\n elif edge_type < 0 or edge_type >= len(self._parent._edge_types):\n raise ValueError(\"invalid edge type\")\n\n if self._parent._succ[self._end][edge_type] is None:\n raise ValueError(\"%d is not a valid edge\" %(edge_type))\n\n self._edge_types.append(edge_type)\n self._end = self._parent._succ[self._end][edge_type]\n\n def _fast_append(self, edge_type):\n r\"\"\"\n Append an edge to the path without verification.\n\n EXAMPLES::\n\n sage: from surface_dynamics import *\n\n sage: p = iet.GeneralizedPermutation('a a','b b c c')\n sage: r = p.rauzy_diagram()\n\n .. try to add 1 with append::\n\n sage: g = r.path(p)\n sage: r[p][1] is None\n True\n sage: g.append(1)\n Traceback (most recent call last):\n ...\n ValueError: 1 is not a valid edge\n\n .. the same with fast append::\n\n sage: g = r.path(p)\n sage: r[p][1] is None\n True\n sage: g._fast_append(1)\n \"\"\"\n self._edge_types.append(edge_type)\n self._end = self._parent._succ[self._end][edge_type]\n\n def extend(self, path):\n r\"\"\"\n Extends self with another path.\n\n EXAMPLES::\n\n sage: from surface_dynamics import *\n\n sage: p = iet.Permutation('a b c d','d c b a')\n sage: r = p.rauzy_diagram()\n sage: g1 = r.path(p,'t','t')\n sage: g2 = r.path(p.rauzy_move('t').rauzy_move('t'),'b','b')\n sage: g = r.path(p,'t','t','b','b')\n sage: g == g1 + g2\n True\n sage: g = copy(g1)\n sage: g.extend(g2)\n sage: g == g1 + g2\n True\n \"\"\"\n if self._parent != path._parent:\n raise ValueError(\"not on the same Rauzy diagram\")\n\n if self._end != path._start:\n raise ValueError(\"the end of the first path must the start of the second\")\n\n self._edge_types.extend(path._edge_types)\n self._end = path._end\n\n def _fast_extend(self, path):\n r\"\"\"\n Extension with no verification.\n\n EXAMPLES::\n\n sage: from surface_dynamics import *\n\n sage: p = iet.Permutation('a b c','c b a')\n sage: r = p.rauzy_diagram()\n sage: p0, p1 = r[p]\n sage: g = r.path(p)\n sage: g._fast_extend(r.path(p0))\n sage: g\n Path of length 0 in a Rauzy diagram\n sage: g._fast_extend(r.path(p1))\n sage: g\n Path of length 0 in a Rauzy diagram\n \"\"\"\n self._edge_types.extend(path._edge_types)\n self._end = path._end\n\n def __len__(self):\n r\"\"\"\n Returns the length of the path.\n\n TESTS::\n\n sage: from surface_dynamics import *\n\n sage: p = iet.Permutation('a b c','c b a')\n sage: r = p.rauzy_diagram()\n sage: len(r.path(p))\n 0\n sage: len(r.path(p,0))\n 1\n sage: len(r.path(p,1))\n 1\n \"\"\"\n return len(self._edge_types)\n\n def __getitem__(self, i):\n r\"\"\"\n TESTS::\n\n sage: from surface_dynamics import *\n\n sage: p = iet.Permutation('a b c','c b a')\n sage: r = p.rauzy_diagram()\n sage: g = r.path(p,'t','b')\n sage: g[0] == p\n True\n sage: g[1] == p.rauzy_move('t')\n True\n sage: g[2] == p.rauzy_move('t').rauzy_move('b')\n True\n sage: g[-1] == g[2]\n True\n sage: g[-2] == g[1]\n True\n sage: g[-3] == g[0]\n True\n \"\"\"\n if i > len(self) or i < -len(self)-1:\n raise IndexError(\"path index out of range\")\n\n if i == 0: return self.start()\n if i < 0: i = i + len(self) + 1\n\n v = self._start\n for k in range(i):\n v = self._parent._succ[v][self._edge_types[k]]\n return self._parent._vertex_to_permutation(v)\n\n def __add__(self, other):\n r\"\"\"\n Concatenation of paths.\n\n EXAMPLES::\n\n sage: from surface_dynamics import *\n\n sage: p = iet.Permutation('a b','b a')\n sage: r = p.rauzy_diagram()\n sage: r.path(p) + r.path(p,'b') == r.path(p,'b')\n True\n sage: r.path(p,'b') + r.path(p) == r.path(p,'b')\n True\n sage: r.path(p,'t') + r.path(p,'b') == r.path(p,'t','b')\n True\n \"\"\"\n if self._end != other._start:\n raise ValueError(\"the end of the first path is not the start of the second\")\n\n res = copy(self)\n res._fast_extend(other)\n return res\n\n def __mul__(self, n):\n r\"\"\"\n Multiple of a loop.\n\n EXAMPLES::\n\n sage: from surface_dynamics import *\n\n sage: p = iet.Permutation('a b','b a')\n sage: r = p.rauzy_diagram()\n sage: l = r.path(p,'b')\n sage: l * 2 == r.path(p,'b','b')\n True\n sage: l * 3 == r.path(p,'b','b','b')\n True\n \"\"\"\n if not self.is_loop():\n raise ValueError(\"Must be a loop to have multiple\")\n\n if not isinstance(n, (Integer,int)):\n raise TypeError(\"The multiplier must be an integer\")\n\n if n < 0:\n raise ValueError(\"The multiplier must be non negative\")\n\n res = copy(self)\n for i in range(n-1):\n res += self\n return res\n\n def is_loop(self):\n r\"\"\"\n Tests whether the path is a loop (start point = end point).\n\n EXAMPLES::\n\n sage: from surface_dynamics import *\n\n sage: p = iet.Permutation('a b','b a')\n sage: r = p.rauzy_diagram()\n sage: r.path(p).is_loop()\n True\n sage: r.path(p,0,1,0,0).is_loop()\n True\n \"\"\"\n return self._start == self._end\n\n def winners(self):\n r\"\"\"\n Returns the winner list associated to the edge of the path.\n\n EXAMPLES::\n\n sage: from surface_dynamics import *\n\n sage: p = iet.Permutation('a b','b a')\n sage: r = p.rauzy_diagram()\n sage: r.path(p).winners()\n []\n sage: r.path(p,0).winners()\n ['b']\n sage: r.path(p,1).winners()\n ['a']\n \"\"\"\n return self.composition(\n self._parent.edge_to_winner,\n list.__add__)\n\n def losers(self):\n r\"\"\"\n Returns a list of the loosers on the path.\n\n EXAMPLES::\n\n sage: from surface_dynamics import *\n\n sage: p = iet.Permutation('a b c','c b a')\n sage: r = p.rauzy_diagram()\n sage: g0 = r.path(p,'t','b','t')\n sage: g0.losers()\n ['a', 'c', 'b']\n sage: g1 = r.path(p,'b','t','b')\n sage: g1.losers()\n ['c', 'a', 'b']\n \"\"\"\n return self.composition(\n self._parent.edge_to_loser,\n list.__add__)\n\n def __iter__(self):\n r\"\"\"\n Iterator over the permutations of the path.\n\n EXAMPLES::\n\n sage: from surface_dynamics import *\n\n sage: p = iet.Permutation('a b c','c b a')\n sage: r = p.rauzy_diagram()\n sage: g = r.path(p)\n sage: for q in g:\n ....: print(p)\n a b c\n c b a\n sage: g = r.path(p, 't', 't')\n sage: for q in g:\n ....: print(\"%s\\n*****\" % q)\n a b c\n c b a\n *****\n a b c\n c a b\n *****\n a b c\n c b a\n *****\n sage: g = r.path(p,'b','t')\n sage: for q in g:\n ....: print(\"%s\\n*****\" % q)\n a b c\n c b a\n *****\n a c b\n c b a\n *****\n a c b\n c b a\n *****\n \"\"\"\n i = self._start\n\n for edge_type in self._edge_types:\n yield self._parent._vertex_to_permutation(i)\n i = self._parent._succ[i][edge_type]\n\n yield self.end()\n\n def composition(self, function, composition = None):\n r\"\"\"\n Compose an edges function on a path\n\n INPUT:\n\n - ``path`` - either a Path or a tuple describing a path\n\n - ``function`` - function must be of the form\n\n - ``composition`` - the composition function\n\n AUTHOR:\n\n - Vincent Delecroix (2009-09-29)\n\n EXAMPLES::\n\n sage: from surface_dynamics import *\n\n sage: p = iet.Permutation('a b','b a')\n sage: r = p.rauzy_diagram()\n sage: def f(i,t):\n ....: if t is None: return []\n ....: return [t]\n sage: g = r.path(p)\n sage: g.composition(f,list.__add__)\n []\n sage: g = r.path(p,0,1)\n sage: g.composition(f, list.__add__)\n [0, 1]\n \"\"\"\n result = function(None,None)\n cur_vertex = self._start\n p = self._parent._element\n\n if composition is None: composition = result.__class__.__mul__\n\n for i in self._edge_types:\n self._parent._set_element(cur_vertex)\n result = composition(result, function(p,i))\n cur_vertex = self._parent._succ[cur_vertex][i]\n\n return result\n\n def right_composition(self, function, composition = None) :\n r\"\"\"\n Compose an edges function on a path\n\n INPUT:\n\n - ``function`` - function must be of the form (indice,type) ->\n element. Moreover function(None,None) must be an identity element\n for initialization.\n\n - ``composition`` - the composition function for the function. * if None (default: None)\n\n TESTS::\n\n sage: from surface_dynamics import *\n\n sage: p = iet.Permutation('a b','b a')\n sage: r = p.rauzy_diagram()\n sage: def f(i,t):\n ....: if t is None: return []\n ....: return [t]\n sage: g = r.path(p)\n sage: g.right_composition(f,list.__add__)\n []\n sage: g = r.path(p,0,1)\n sage: g.right_composition(f, list.__add__)\n [1, 0]\n \"\"\"\n result = function(None,None)\n p = self._parent._element\n cur_vertex = self._start\n\n if composition is None: composition = result.__class__.__mul__\n\n for i in self._edge_types:\n self._parent._set_element(cur_vertex)\n result = composition(function(p,i),result)\n cur_vertex = self._parent._succ[cur_vertex][i]\n\n return result\n\n def __init__(self, p,\n right_induction=True,\n left_induction=False,\n left_right_inversion=False,\n top_bottom_inversion=False,\n symmetric=False):\n r\"\"\"\n self._succ contains successors\n self._pred contains predecessors\n\n self._element_class is the class of elements of self\n self._element is an instance of this class (hence contains the alphabet,\n the representation mode, ...). It is used to store data about property\n of permutations and also as a fast iterator.\n\n INPUT:\n\n - ``right_induction`` - boolean or 'top' or 'bottom': consider the\n right induction\n\n - ``left_induction`` - boolean or 'top' or 'bottom': consider the\n left induction\n\n - ``left_right_inversion`` - consider the left right inversion\n\n - ``top_bottom_inversion`` - consider the top bottom inversion\n\n - ``symmetric`` - consider the symmetric\n\n TESTS::\n\n sage: from surface_dynamics import *\n\n sage: r1 = iet.RauzyDiagram('a b','b a')\n sage: r2 = loads(dumps(r1))\n \"\"\"\n self._edge_types = []\n self._index = {}\n\n if right_induction is True:\n self._index['rt_rauzy'] = len(self._edge_types)\n self._edge_types.append(('rauzy_move',(0,-1)))\n self._index['rb_rauzy'] = len(self._edge_types)\n self._edge_types.append(('rauzy_move',(1,-1)))\n\n elif isinstance(right_induction,str):\n if right_induction == '':\n raise ValueError(\"right_induction can not be empty string\")\n\n elif 'top'.startswith(right_induction):\n self._index['rt_rauzy'] = len(self._edge_types)\n self._edge_types.append(('rauzy_move',(0,-1)))\n\n elif 'bottom'.startswith(right_induction):\n self._index['rb_rauzy'] = len(self._edge_types)\n self._edge_types.append(('rauzy_move',(1,-1)))\n\n else:\n raise ValueError(\"%s is not valid for right_induction\" %(right_induction))\n\n if left_induction is True:\n self._index['lt_rauzy'] = len(self._edge_types)\n self._edge_types.append(('rauzy_move',(0,0)))\n self._index['lb_rauzy'] = len(self._edge_types)\n self._edge_types.append(('rauzy_move',(1,0)))\n\n elif isinstance(left_induction,str):\n if left_induction == '':\n raise ValueError(\"left_induction can not be empty string\")\n\n elif 'top'.startswith(left_induction):\n self._index['lt_rauzy'] = len(self._edge_types)\n self._edge_types.append(('rauzy_move',(0,0)))\n\n elif 'bottom'.startswith(left_induction):\n self._index['lb_rauzy'] = len(self._edge_types)\n self._edge_types.append(('rauzy_move',(1,0)))\n\n else:\n raise ValueError(\"%s is not valid for left_induction\" %(right_induction))\n\n if left_right_inversion is True:\n self._index['lr_inverse'] = len(self._edge_types)\n self._edge_types.append(('left_right_inverse',()))\n\n if top_bottom_inversion is True:\n self._index['tb_inverse'] = len(self._edge_types)\n self._edge_types.append(('top_bottom_inverse',()))\n\n if symmetric is True:\n self._index['symmetric'] = len(self._edge_types)\n self._edge_types.append(('symmetric',()))\n\n self._n = len(p)\n self._element_class = p.__class__\n self._element = copy(p)\n self._alphabet = self._element._alphabet\n\n self._pred = {}\n self._succ = {}\n\n self.complete(p)\n\n def __eq__(self, other):\n r\"\"\"\n Tests equality.\n\n TESTS::\n\n sage: from surface_dynamics import *\n\n sage: iet.RauzyDiagram('a b','b a') == iet.RauzyDiagram('a b c','c b a')\n False\n sage: r = iet.RauzyDiagram('a b c','c b a')\n sage: r1 = iet.RauzyDiagram('a c b','c b a', alphabet='abc')\n sage: r2 = iet.RauzyDiagram('a b c','c a b', alphabet='abc')\n sage: r == r1\n True\n sage: r == r2\n True\n sage: r1 == r2\n True\n\n ::\n\n sage: r = iet.RauzyDiagram('a b c d','d c b a')\n sage: for p in r:\n ....: p.rauzy_diagram() == r\n True\n True\n True\n True\n True\n True\n True\n \"\"\"\n return type(self) == type(other) and \\\n self._edge_types == other._edge_types and \\\n next(iterkeys(self._succ)) in other._succ\n\n def __ne__(self, other):\n r\"\"\"\n Tests difference.\n\n TESTS::\n\n sage: from surface_dynamics import *\n\n sage: iet.RauzyDiagram('a b','b a') != iet.RauzyDiagram('a b c','c b a')\n True\n sage: r = iet.RauzyDiagram('a b c','c b a')\n sage: r1 = iet.RauzyDiagram('a c b','c b a', alphabet='abc')\n sage: r2 = iet.RauzyDiagram('a b c','c a b', alphabet='abc')\n sage: r != r1\n False\n sage: r != r2\n False\n sage: r1 != r2\n False\n \"\"\"\n return not self == other\n\n def vertices(self):\n r\"\"\"\n Returns a list of the vertices.\n\n EXAMPLES::\n\n sage: from surface_dynamics import *\n\n sage: r = iet.RauzyDiagram('a b','b a')\n sage: for p in r.vertices(): print(p)\n a b\n b a\n \"\"\"\n return list(map(\n lambda x: self._vertex_to_permutation(x),\n self._succ.keys()))\n\n def vertex_iterator(self):\n r\"\"\"\n Returns an iterator over the vertices\n\n EXAMPLES::\n\n sage: from surface_dynamics import *\n\n sage: r = iet.RauzyDiagram('a b','b a')\n sage: for p in r.vertex_iterator(): print(p)\n a b\n b a\n\n ::\n\n sage: r = iet.RauzyDiagram('a b c d','d c b a')\n sage: r_1n = filter(lambda x: x.is_standard(), r)\n sage: for p in r_1n: print(p)\n a b c d\n d c b a\n \"\"\"\n return map(\n lambda x: self._vertex_to_permutation(x),\n self._succ.keys())\n\n def edges(self,labels=True):\n r\"\"\"\n Returns a list of the edges.\n\n EXAMPLES::\n\n sage: from surface_dynamics import *\n\n sage: r = iet.RauzyDiagram('a b','b a')\n sage: len(r.edges())\n 2\n \"\"\"\n return list(self.edge_iterator())\n\n def edge_iterator(self):\n r\"\"\"\n Returns an iterator over the edges of the graph.\n\n EXAMPLES::\n\n sage: from surface_dynamics import *\n\n sage: p = iet.Permutation('a b','b a')\n sage: r = p.rauzy_diagram()\n sage: for e in r.edge_iterator():\n ....: print('%s --> %s' %(e[0].str(sep='/'), e[1].str(sep='/')))\n a b/b a --> a b/b a\n a b/b a --> a b/b a\n \"\"\"\n for x in self._succ.keys():\n for i,y in enumerate(self._succ[x]):\n if y is not None:\n yield(\n (self._vertex_to_permutation(x),\n self._vertex_to_permutation(y),\n i))\n\n def edge_types_index(self, data):\n r\"\"\"\n Try to convert the data as an edge type.\n\n INPUT:\n\n - ``data`` - a string\n\n OUTPUT:\n\n integer\n\n EXAMPLES:\n\n sage: from surface_dynamics import *\n\n For a standard Rauzy diagram (only right induction) the 0 index\n corresponds to the 'top' induction and the index 1 corresponds to the\n 'bottom' one::\n\n sage: p = iet.Permutation('a b c','c b a')\n sage: r = p.rauzy_diagram()\n sage: r.edge_types_index('top')\n 0\n sage: r[p][0] == p.rauzy_move('top')\n True\n sage: r.edge_types_index('bottom')\n 1\n sage: r[p][1] == p.rauzy_move('bottom')\n True\n\n The special operations (inversion and symmetry) always appears after the\n different Rauzy inductions::\n\n sage: p = iet.Permutation('a b c','c b a')\n sage: r = p.rauzy_diagram(symmetric=True)\n sage: r.edge_types_index('symmetric')\n 2\n sage: r[p][2] == p.symmetric()\n True\n\n This function always try to resolve conflictuous name. If it's\n impossible a ValueError is raised::\n\n sage: p = iet.Permutation('a b c','c b a')\n sage: r = p.rauzy_diagram(left_induction=True)\n sage: r.edge_types_index('top')\n Traceback (most recent call last):\n ...\n ValueError: left and right inductions must be differentiated\n sage: r.edge_types_index('top_right')\n 0\n sage: r[p][0] == p.rauzy_move(0)\n True\n sage: r.edge_types_index('bottom_left')\n 3\n sage: r[p][3] == p.rauzy_move('bottom', 'left')\n True\n\n ::\n\n sage: p = iet.Permutation('a b c','c b a')\n sage: r = p.rauzy_diagram(left_right_inversion=True,top_bottom_inversion=True)\n sage: r.edge_types_index('inversion')\n Traceback (most recent call last):\n ...\n ValueError: left-right and top-bottom inversions must be differentiated\n sage: r.edge_types_index('lr_inverse')\n 2\n sage: p.lr_inverse() == r[p][2]\n True\n sage: r.edge_types_index('tb_inverse')\n 3\n sage: p.tb_inverse() == r[p][3]\n True\n\n Short names are accepted::\n\n sage: p = iet.Permutation('a b c','c b a')\n sage: r = p.rauzy_diagram(right_induction='top',top_bottom_inversion=True)\n sage: r.edge_types_index('top_rauzy_move')\n 0\n sage: r.edge_types_index('t')\n 0\n sage: r.edge_types_index('tb')\n 1\n sage: r.edge_types_index('inversion')\n 1\n sage: r.edge_types_index('inverse')\n 1\n sage: r.edge_types_index('i')\n 1\n \"\"\"\n if not isinstance(data,str):\n raise ValueError(\"the edge type must be a string\")\n\n if ('top_rauzy_move'.startswith(data) or\n 't_rauzy_move'.startswith(data)):\n if 'lt_rauzy' in self._index:\n if 'rt_rauzy' in self._index:\n raise ValueError(\"left and right inductions must be differentiated\")\n return self._index['lt_rauzy']\n\n if 'rt_rauzy' in self._index:\n return self._index['rt_rauzy']\n\n raise ValueError(\"no top induction in this Rauzy diagram\")\n\n if ('bottom_rauzy_move'.startswith(data) or\n 'b_rauzy_move'.startswith(data)):\n if 'lb_rauzy' in self._index:\n if 'rb_rauzy' in self._index:\n raise ValueError(\"left and right inductions must be differentiated\")\n return self._index['lb_rauzy']\n\n if 'rb_rauzy' in self._index:\n return self._index['rb_rauzy']\n\n raise ValueError(\"no bottom Rauzy induction in this diagram\")\n\n if ('left_rauzy_move'.startswith(data) or\n 'l_rauzy_move'.startswith(data)):\n if 'lt_rauzy' in self._index:\n if 'lb_rauzy' in self._index:\n raise ValueError(\"top and bottom inductions must be differentiated\")\n return self._index['lt_rauzy']\n\n if 'lb_rauzy' in self._index:\n return self._index('lb_rauzy')\n\n raise ValueError(\"no left Rauzy induction in this diagram\")\n\n if ('lt_rauzy_move'.startswith(data) or\n 'tl_rauzy_move'.startswith(data) or\n 'left_top_rauzy_move'.startswith(data) or\n 'top_left_rauzy_move'.startswith(data)):\n if 'lt_rauzy' not in self._index:\n raise ValueError(\"no top-left Rauzy induction in this diagram\")\n else:\n return self._index['lt_rauzy']\n\n if ('lb_rauzy_move'.startswith(data) or\n 'bl_rauzy_move'.startswith(data) or\n 'left_bottom_rauzy_move'.startswith(data) or\n 'bottom_left_rauzy_move'.startswith(data)):\n if 'lb_rauzy' not in self._index:\n raise ValueError(\"no bottom-left Rauzy induction in this diagram\")\n else:\n return self._index['lb_rauzy']\n\n if 'right'.startswith(data):\n raise ValueError(\"ambiguity with your edge name: %s\" %(data))\n\n if ('rt_rauzy_move'.startswith(data) or\n 'tr_rauzy_move'.startswith(data) or\n 'right_top_rauzy_move'.startswith(data) or\n 'top_right_rauzy_move'.startswith(data)):\n if 'rt_rauzy' not in self._index:\n raise ValueError(\"no top-right Rauzy induction in this diagram\")\n else:\n return self._index['rt_rauzy']\n\n if ('rb_rauzy_move'.startswith(data) or\n 'br_rauzy_move'.startswith(data) or\n 'right_bottom_rauzy_move'.startswith(data) or\n 'bottom_right_rauzy_move'.startswith(data)):\n if 'rb_rauzy' not in self._index:\n raise ValueError(\"no bottom-right Rauzy induction in this diagram\")\n else:\n return self._index['rb_rauzy']\n\n if 'symmetric'.startswith(data):\n if 'symmetric' not in self._index:\n raise ValueError(\"no symmetric in this diagram\")\n else:\n return self._index['symmetric']\n\n if 'inversion'.startswith(data) or data == 'inverse':\n if 'lr_inverse' in self._index:\n if 'tb_inverse' in self._index:\n raise ValueError(\"left-right and top-bottom inversions must be differentiated\")\n return self._index['lr_inverse']\n\n if 'tb_inverse' in self._index:\n return self._index['tb_inverse']\n\n raise ValueError(\"no inversion in this diagram\")\n\n if ('lr_inversion'.startswith(data) or\n data == 'lr_inverse' or\n 'left_right_inversion'.startswith(data) or\n data == 'left_right_inverse'):\n if 'lr_inverse' not in self._index:\n raise ValueError(\"no left-right inversion in this diagram\")\n else:\n return self._index['lr_inverse']\n\n if ('tb_inversion'.startswith(data) or\n data == 'tb_inverse' or\n 'top_bottom_inversion'.startswith(data)\n or data == 'top_bottom_inverse'):\n if 'tb_inverse' not in self._index:\n raise ValueError(\"no top-bottom inversion in this diagram\")\n else:\n return self._index['tb_inverse']\n\n raise ValueError(\"this edge type does not exist: %s\" %(data))\n\n def edge_types(self):\n r\"\"\"\n Print information about edges.\n\n EXAMPLES::\n\n sage: from surface_dynamics import *\n\n sage: r = iet.RauzyDiagram('a b', 'b a')\n sage: r.edge_types()\n 0: rauzy_move(0, -1)\n 1: rauzy_move(1, -1)\n\n ::\n\n sage: r = iet.RauzyDiagram('a b', 'b a', left_induction=True)\n sage: r.edge_types()\n 0: rauzy_move(0, -1)\n 1: rauzy_move(1, -1)\n 2: rauzy_move(0, 0)\n 3: rauzy_move(1, 0)\n\n ::\n\n sage: r = iet.RauzyDiagram('a b',' b a',symmetric=True)\n sage: r.edge_types()\n 0: rauzy_move(0, -1)\n 1: rauzy_move(1, -1)\n 2: symmetric()\n \"\"\"\n for i,(edge_type,t) in enumerate(self._edge_types):\n print(str(i) + \": \" + edge_type + str(t))\n\n def alphabet(self, data=None):\n r\"\"\"\n TESTS::\n\n sage: from surface_dynamics import *\n\n sage: r = iet.RauzyDiagram('a b','b a')\n sage: r.alphabet() == Alphabet(['a','b'])\n True\n sage: r = iet.RauzyDiagram([0,1],[1,0])\n sage: r.alphabet() == Alphabet([0,1])\n True\n \"\"\"\n if data is None:\n return self._element._alphabet\n else:\n self._element._set_alphabet(data)\n\n def letters(self):\n r\"\"\"\n Returns the letters used by the RauzyDiagram.\n\n EXAMPLES::\n\n sage: from surface_dynamics import *\n\n sage: r = iet.RauzyDiagram('a b','b a')\n sage: r.alphabet()\n {'a', 'b'}\n sage: r.letters()\n ['a', 'b']\n sage: r.alphabet('ABCDEF')\n sage: r.alphabet()\n {'A', 'B', 'C', 'D', 'E', 'F'}\n sage: r.letters()\n ['A', 'B']\n \"\"\"\n return self._element.letters()\n\n def _vertex_to_permutation(self,data=None):\n r\"\"\"\n Converts the (vertex) data to a permutation.\n\n TESTS:\n\n sage: from surface_dynamics import *\n\n sage: r = iet.RauzyDiagram('a b','b a') #indirect doctest\n \"\"\"\n if data is not None:\n self._set_element(data)\n return copy(self._element)\n\n def edge_to_matrix(self, p=None, edge_type=None):\n r\"\"\"\n Return the corresponding matrix\n\n INPUT:\n\n - ``p`` - a permutation\n\n - ``edge_type`` - 0 or 1 corresponding to the type of the edge\n\n OUTPUT:\n\n A matrix\n\n EXAMPLES::\n\n sage: from surface_dynamics import *\n\n sage: p = iet.Permutation('a b c','c b a')\n sage: d = p.rauzy_diagram()\n sage: print(d.edge_to_matrix(p,1))\n [1 0 1]\n [0 1 0]\n [0 0 1]\n \"\"\"\n if p is None and edge_type is None:\n return identity_matrix(self._n)\n\n function_name = self._edge_types[edge_type][0] + '_matrix'\n\n if not hasattr(self._element_class,function_name):\n return identity_matrix(self._n)\n\n arguments = self._edge_types[edge_type][1]\n\n return getattr(p,function_name)(*arguments)\n\n def edge_to_winner(self, p=None, edge_type=None):\n r\"\"\"\n Return the corresponding winner\n\n TESTS::\n\n sage: from surface_dynamics import *\n\n sage: r = iet.RauzyDiagram('a b','b a')\n sage: r.edge_to_winner(None,None)\n []\n \"\"\"\n if p is None and edge_type is None:\n return []\n\n function_name = self._edge_types[edge_type][0] + '_winner'\n\n if not hasattr(self._element_class, function_name):\n return [None]\n\n arguments = self._edge_types[edge_type][1]\n\n return [getattr(p,function_name)(*arguments)]\n\n def edge_to_loser(self, p=None, edge_type=None):\n r\"\"\"\n Return the corresponding loser\n\n TESTS::\n\n sage: from surface_dynamics import *\n\n sage: r = iet.RauzyDiagram('a b','b a')\n sage: r.edge_to_loser(None,None)\n []\n \"\"\"\n if p is None and edge_type is None:\n return []\n\n function_name = self._edge_types[edge_type][0] + '_loser'\n\n if not hasattr(self._element_class, function_name):\n return [None]\n\n arguments = self._edge_types[edge_type][1]\n\n return [getattr(p,function_name)(*arguments)]\n\n def _all_npath_extension(self, g, length=0):\n r\"\"\"\n Returns an iterator over all extension of fixed length of p.\n\n INPUT:\n\n - ``p`` - a path\n\n - ``length`` - a non-negative integer\n\n TESTS::\n\n sage: from surface_dynamics import *\n\n sage: p = iet.Permutation('a b','b a')\n sage: r = p.rauzy_diagram()\n sage: g0 = r.path(p)\n sage: for g in r._all_npath_extension(g0,0):\n ....: print(g)\n Path of length 0 in a Rauzy diagram\n sage: for g in r._all_npath_extension(g0,1):\n ....: print(g)\n Path of length 1 in a Rauzy diagram\n Path of length 1 in a Rauzy diagram\n sage: for g in r._all_npath_extension(g0,2):\n ....: print(g)\n Path of length 2 in a Rauzy diagram\n Path of length 2 in a Rauzy diagram\n Path of length 2 in a Rauzy diagram\n Path of length 2 in a Rauzy diagram\n\n ::\n\n sage: p = iet.GeneralizedPermutation('a a','b b c c',reduced=True)\n sage: r = p.rauzy_diagram()\n sage: g0 = r.path(p)\n sage: len(list(r._all_npath_extension(g0,0)))\n 1\n sage: len(list(r._all_npath_extension(g0,1)))\n 1\n sage: len(list(r._all_npath_extension(g0,2)))\n 2\n sage: len(list(r._all_npath_extension(g0,3)))\n 3\n sage: len(list(r._all_npath_extension(g0,4)))\n 5\n \"\"\"\n if length == 0:\n yield g\n\n else:\n for i in range(len(self._edge_types)):\n if self._succ[g._end][i] is not None:\n g._fast_append(i)\n for h in self._all_npath_extension(g,length-1): yield h\n g.pop()\n\n def _all_path_extension(self, g, length=0):\n r\"\"\"\n Returns an iterator over all path extension of p.\n\n TESTS::\n\n sage: from surface_dynamics import *\n\n sage: p = iet.Permutation('a b','b a')\n sage: r = p.rauzy_diagram()\n sage: g0 = r.path(p)\n sage: for g in r._all_path_extension(g0,0):\n ....: print(g)\n Path of length 0 in a Rauzy diagram\n sage: for g in r._all_path_extension(g0, 1):\n ....: print(g)\n Path of length 0 in a Rauzy diagram\n Path of length 1 in a Rauzy diagram\n Path of length 1 in a Rauzy diagram\n\n ::\n\n sage: p = iet.GeneralizedPermutation('a a','b b c c')\n sage: r = p.rauzy_diagram()\n sage: g0 = r.path(p)\n sage: len(list(r._all_path_extension(g0,0)))\n 1\n sage: len(list(r._all_path_extension(g0,1)))\n 2\n sage: len(list(r._all_path_extension(g0,2)))\n 4\n sage: len(list(r._all_path_extension(g0,3)))\n 7\n \"\"\"\n yield g\n\n if length > 0:\n for i in range(len(self._edge_types)):\n if self._succ[g._end][i] is not None:\n g._fast_append(i)\n for h in self._all_path_extension(g,length-1): yield h\n g.pop()\n\n def __iter__(self):\n r\"\"\"\n Iterator over the permutations of the Rauzy diagram.\n\n EXAMPLES::\n\n sage: from surface_dynamics import *\n\n sage: r = iet.RauzyDiagram('a b','b a')\n sage: for p in r: print(p)\n a b\n b a\n sage: r = iet.RauzyDiagram('a b c','c b a')\n sage: for p in r: print(p.stratum())\n H_1(0^2)\n H_1(0^2)\n H_1(0^2)\n \"\"\"\n for data in iterkeys(self._succ):\n yield self._vertex_to_permutation(data)\n\n def __contains__(self, element):\n r\"\"\"\n Containance test.\n\n TESTS::\n\n sage: from surface_dynamics import *\n\n sage: p = iet.Permutation('a b c d','d c b a',reduced=True)\n sage: q = iet.Permutation('a b c d','d b c a',reduced=True)\n sage: r = p.rauzy_diagram()\n sage: s = q.rauzy_diagram()\n sage: p in r\n True\n sage: p in s\n False\n sage: q in r\n False\n sage: q in s\n True\n \"\"\"\n for p in iterkeys(self._succ):\n if self._vertex_to_permutation(p) == element:\n return True\n\n return False\n\n def _repr_(self):\n r\"\"\"\n Returns a representation of self\n\n TESTS::\n\n sage: from surface_dynamics import *\n\n sage: iet.RauzyDiagram('a b','b a') #indirect doctest\n Rauzy diagram with 1 permutation\n sage: iet.RauzyDiagram('a b c','c b a') #indirect doctest\n Rauzy diagram with 3 permutations\n \"\"\"\n if len(self._succ) == 0:\n return \"Empty Rauzy diagram\"\n elif len(self._succ) == 1:\n return \"Rauzy diagram with 1 permutation\"\n else:\n return \"Rauzy diagram with %d permutations\" %(len(self._succ))\n\n def __getitem__(self,p):\n r\"\"\"\n Returns the neighbors of p.\n\n Just use the function vertex_to_permutation that must be defined\n in each child.\n\n INPUT:\n\n - ``p`` - a permutation in the Rauzy diagram\n\n TESTS::\n\n sage: from surface_dynamics import *\n\n\n sage: p = iet.Permutation('a b c','c b a')\n sage: p0 = iet.Permutation('a b c','c a b',alphabet=\"abc\")\n sage: p1 = iet.Permutation('a c b','c b a',alphabet=\"abc\")\n sage: r = p.rauzy_diagram()\n sage: r[p] == [p0, p1]\n True\n sage: r[p1] == [p1, p]\n True\n sage: r[p0] == [p, p0]\n True\n \"\"\"\n if not isinstance(p, self._element_class):\n raise ValueError(\"Your element does not have the good type\")\n\n perm = self._permutation_to_vertex(p)\n return list(map(lambda x: self._vertex_to_permutation(x),\n self._succ[perm]))\n\n def __len__(self):\n r\"\"\"\n Deprecated use cardinality.\n\n EXAMPLES::\n\n sage: from surface_dynamics import *\n\n sage: r = iet.RauzyDiagram('a b','b a')\n sage: r.cardinality()\n 1\n \"\"\"\n return self.cardinality()\n\n def cardinality(self):\n r\"\"\"\n Returns the number of permutations in this Rauzy diagram.\n\n OUTPUT:\n\n - `integer` - the number of vertices in the diagram\n\n EXAMPLES::\n\n sage: from surface_dynamics import *\n\n sage: r = iet.RauzyDiagram('a b','b a')\n sage: r.cardinality()\n 1\n sage: r = iet.RauzyDiagram('a b c','c b a')\n sage: r.cardinality()\n 3\n sage: r = iet.RauzyDiagram('a b c d','d c b a')\n sage: r.cardinality()\n 7\n \"\"\"\n return len(self._succ)\n\n def complete(self, p):\n r\"\"\"\n Completion of the Rauzy diagram.\n\n Add to the Rauzy diagram all permutations that are obtained by\n successive operations defined by edge_types(). The permutation must be\n of the same type and the same length as the one used for the creation.\n\n INPUT:\n\n - ``p`` - a permutation of Interval exchange transformation\n\n Rauzy diagram is the reunion of all permutations that could be\n obtained with successive rauzy moves. This function just use the\n functions __getitem__ and has_rauzy_move and rauzy_move which must\n be defined for child and their corresponding permutation types.\n\n TESTS::\n\n sage: from surface_dynamics import *\n\n sage: r = iet.RauzyDiagram('a b c','c b a') #indirect doctest\n sage: r = iet.RauzyDiagram('a b c','c b a',left_induction=True) #indirect doctest\n sage: r = iet.RauzyDiagram('a b c','c b a',symmetric=True) #indirect doctest\n sage: r = iet.RauzyDiagram('a b c','c b a',lr_inversion=True) #indirect doctest\n sage: r = iet.RauzyDiagram('a b c','c b a',tb_inversion=True) #indirect doctest\n \"\"\"\n if p.__class__ is not self._element_class:\n raise TypeError(\"wrong permutation type\")\n\n if len(p) != self._n:\n raise ValueError(\"wrong length\")\n\n pred = self._pred\n succ = self._succ\n p = self._permutation_to_vertex(p)\n perm = self._element\n l = []\n\n if p not in succ:\n succ[p] = [None] * len(self._edge_types)\n pred[p] = [None] * len(self._edge_types)\n l.append(p)\n\n while l:\n p = l.pop()\n self._set_element(p)\n\n for t,edge in enumerate(self._edge_types):\n if (not hasattr(perm, 'has_'+edge[0]) or\n getattr(perm, 'has_'+edge[0])(*(edge[1]))):\n q = getattr(perm,edge[0])(*(edge[1]))\n q = self._permutation_to_vertex(q)\n if q not in succ:\n succ[q] = [None] * len(self._edge_types)\n pred[q] = [None] * len(self._edge_types)\n l.append(q)\n succ[p][t] = q\n pred[q][t] = p\n\n def path(self, *data):\n r\"\"\"\n Returns a path over this Rauzy diagram.\n\n INPUT:\n\n - ``initial_vertex`` - the initial vertex (starting point of the path)\n\n - ``data`` - a sequence of edges\n\n EXAMPLES::\n\n sage: from surface_dynamics import *\n\n sage: p = iet.Permutation('a b c','c b a')\n sage: r = p.rauzy_diagram()\n sage: g = r.path(p, 'top', 'bottom')\n \"\"\"\n if len(data) == 0:\n raise TypeError(\"Must be non empty\")\n elif len(data) == 1 and isinstance(data[0], self.Path):\n return copy(data[0])\n return self.Path(self,*data)\n\n def graph(self):\n r\"\"\"\n Returns the Rauzy diagram as a Graph object\n\n The graph returned is more precisely a DiGraph (directed graph) with\n loops and multiedges allowed.\n\n EXAMPLES::\n\n sage: from surface_dynamics import *\n\n sage: r = iet.RauzyDiagram('a b c','c b a')\n sage: r\n Rauzy diagram with 3 permutations\n sage: r.graph()\n Looped digraph on 3 vertices\n \"\"\"\n from sage.graphs.digraph import DiGraph\n\n if len(self._element) != 2:\n G = DiGraph(loops=True,multiedges=False)\n else:\n G = DiGraph(loops=True,multiedges=True)\n\n for p,neighbours in iteritems(self._succ):\n p = self._vertex_to_permutation(p)\n for i,n in enumerate(neighbours):\n if n is not None:\n q = self._vertex_to_permutation(n)\n G.add_edge(p,q,i)\n\n return G\n\nclass FlippedRauzyDiagram(RauzyDiagram):\n r\"\"\"\n Template for flipped Rauzy diagrams.\n\n .. warning:\n\n Internal class! Do not use directly!\n\n AUTHORS:\n\n - Vincent Delecroix (2009-09-29): initial version\n\n \"\"\"\n def complete(self, p, reducible=False):\n r\"\"\"\n Completion of the Rauzy diagram\n\n Add all successors of p for defined operations in edge_types. Could be\n used for generating non (strongly) connected Rauzy diagrams. Sometimes,\n for flipped permutations, the maximal connected graph in all\n permutations is not strongly connected. Finding such components needs to\n call most than once the .complete() method.\n\n INPUT:\n\n - ``p`` - a permutation\n\n - ``reducible`` - put or not reducible permutations\n\n EXAMPLES::\n\n sage: from surface_dynamics import *\n\n sage: p = iet.Permutation('a b c','c b a',flips='a')\n sage: d = p.rauzy_diagram()\n sage: d\n Rauzy diagram with 3 permutations\n sage: p = iet.Permutation('a b c','c b a',flips='b')\n sage: d.complete(p)\n sage: d\n Rauzy diagram with 8 permutations\n sage: p = iet.Permutation('a b c','c b a',flips='a')\n sage: d.complete(p)\n sage: d\n Rauzy diagram with 8 permutations\n \"\"\"\n if p.__class__ is not self._element_class:\n raise ValueError(\"your permutation is not of good type\")\n\n if len(p) != self._n:\n raise ValueError(\"your permutation has not the good length\")\n\n pred = self._pred\n succ = self._succ\n p = self._permutation_to_vertex(p)\n l = []\n\n if p not in succ:\n succ[p] = [None] * len(self._edge_types)\n pred[p] = [None] * len(self._edge_types)\n l.append(p)\n\n while l:\n p = l.pop()\n\n for t,edge_type in enumerate(self._edge_types):\n perm = self._vertex_to_permutation(p)\n\n if (not hasattr(perm,'has_' + edge_type[0]) or\n getattr(perm, 'has_' + edge_type[0])(*(edge_type[1]))):\n q = perm.rauzy_move(t)\n q = self._permutation_to_vertex(q)\n if reducible is True or perm.is_irreducible():\n if q not in succ:\n succ[q] = [None] * len(self._edge_types)\n pred[q] = [None] * len(self._edge_types)\n l.append(q)\n\n succ[p][t] = q\n pred[q][t] = p\n","repo_name":"flatsurf/surface-dynamics","sub_path":"surface_dynamics/interval_exchanges/template.py","file_name":"template.py","file_ext":"py","file_size_in_byte":234429,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"60"} +{"seq_id":"9003108746","text":"from typing import List\n\n\n# 1 7 5 3 9\ndef containerWithMostWater(height: List[int]):\n p1, p2 = 0, len(height) - 1\n res = float(\"-inf\")\n while p1 < p2:\n current_capacity = min(height[p1], height[p2]) * (p2 - p1)\n res = max(res, current_capacity)\n if height[p1] < height[p2]:\n p1 = p1 + 1\n else:\n p2 = p2 + 1\n return res\n","repo_name":"Raghavs26/master-the-coding-interview","sub_path":"1. Arrays/2. Container With Most Water/container-with-most-water-optimal.py","file_name":"container-with-most-water-optimal.py","file_ext":"py","file_size_in_byte":381,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"60"} +{"seq_id":"29706056220","text":"class Staff:\n def __init__(self, nama):\n self.nama = nama\n self.jam_kerja = 0\n self.progress = 0\n \n def kerja(self, jam):\n self.jam_kerja += jam\n\n def hitung_gaji(self):\n pass \n\n\nclass StaffAcara(Staff):\n def __init__(self,nama):\n super().__init__(nama)\n \n def kerja(self, jam):\n self.jam_kerja += jam\n self.progress += self.jam_kerja * 4\n if self.progress < 100:\n return '{} bekerja selama {} jam'.format(self.nama.capitalize(), self.progress)\n else:\n return '{} sudah mencapai {}% progress'.format(self.nama.capitalize(), self.progress)\n\n def hitung_gaji(self):\n return self.progress * 2000\n\nclass StaffPartnership(Staff):\n def __init__(self,nama):\n super().__init__(nama)\n\n def kerja(self, jam):\n self.jam_kerja += jam\n self.progress += self.jam_kerja * 1\n if self.progress < 100:\n return '{} bekerja selama {} jam'.format(self.nama.capitalize(), self.progress)\n else:\n return '{} sudah mencapai {}% progress'.format(self.nama.capitalize(), self.progress)\n\n def hitung_gaji(self):\n return self.jam_kerja * self.progress * 4000\n\nclass StaffPublikasi(Staff):\n def __init__(self,nama):\n super().__init__(nama)\n\n def kerja(self, jam):\n self.jam_kerja += jam\n self.progress += self.jam_kerja * 20\n if self.progress < 100:\n return '{} bekerja selama {} jam'.format(self.nama.capitalize(), self.progress)\n else:\n return '{} sudah mencapai {}% progress'.format(self.nama.capitalize(), self.progress)\n\n def hitung_gaji(self):\n return self.jam_kerja * 1500\n\nclass Manager:\n def __init__(self):\n self.staffs = {}\n\n def recruit_staff(self, staf):\n self.staffs[staf.nama] = staf\n\n def get_staff(self,nama):\n return self.staffs[nama]\n\n def is_staff_recruited(self, nama):\n return nama in self.staffs\n\nmanager = Manager()\n\nwhile True:\n masukan = input().lower().split(';')\n\n if masukan[0] == 'exit':\n break\n\n perintah = masukan[0]\n\n if perintah == 'rekrut' and len(masukan) == 3:\n if manager.is_staff_recruited(masukan[1]):\n print('{} sudah direkrut sebelumnya'.format(staf.nama.capitalize()))\n else:\n if(masukan[2] == 'acara'):\n staf = StaffAcara(masukan[1])\n elif(masukan[2] == 'partnership'):\n staf = StaffPartnership(masukan[1])\n elif(masukan[2] == 'publikasi'):\n staf = StaffPublikasi(masukan[1])\n manager.recruit_staff(staf)\n print('{} direkrut'.format(staf.nama.capitalize()))\n\n if perintah == 'kerja' and len(masukan) == 3:\n print(manager.get_staff(masukan[1]).kerja(int(masukan[2])))\n\n if perintah == 'log' and len(masukan) == 2:\n print('>> ', manager.get_staff(masukan[1]).nama,\\\n '\\nTelah bekerja selama:', manager.get_staff(masukan[1]).jam_kerja,\\\n 'jam\\nProgress:', manager.get_staff(masukan[1]).progress,\\\n 'persen\\nGaji sementara:', manager.get_staff(masukan[1]).hitung_gaji(),\\\n 'bencoin')\n","repo_name":"bungamaku/foundation-programming-1","sub_path":"Lab/Lab DDP (8)/Lab08_D_NN_Bunga Amalia Kurniawati_1706022104.py","file_name":"Lab08_D_NN_Bunga Amalia Kurniawati_1706022104.py","file_ext":"py","file_size_in_byte":3222,"program_lang":"python","lang":"id","doc_type":"code","stars":0,"dataset":"github-code","pt":"60"} +{"seq_id":"22459911681","text":"_base_ = '../imagenet/common/classification_base.py'\n\n# oss_io_config = dict(ak_id='', # your oss ak id\n# ak_secret='', # your oss ak secret\n# hosts='', # your oss hosts\n# buckets=[]) # your oss bucket name\n\n# Ensure the CLASSES definition is in one line, for adapt to its replacement by user_config_params.\n# yapf:disable\nCLASSES = ['label1', 'label2', 'label3'] # replace with your true lables of itag manifest file\nnum_classes = 3\n# model settings\nmodel = dict(\n type='Classification',\n backbone=dict(type='MobileNetV2'),\n head=dict(\n type='ClsHead',\n with_avg_pool=True,\n in_channels=1280,\n loss_config=dict(\n type='CrossEntropyLossWithLabelSmooth',\n label_smooth=0,\n ),\n num_classes=num_classes))\n\ntrain_itag_file = '/your/itag/train/file.manifest' # or oss://your_bucket/data/train.manifest\ntest_itag_file = '/your/itag/test/file.manifest' # oss://your_bucket/data/test.manifest\n\nimage_size2 = 224\nimage_size1 = int((256 / 224) * image_size2)\ndata_source_type = 'ClsSourceItag'\ndataset_type = 'ClsDataset'\nimg_norm_cfg = dict(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])\ntrain_pipeline = [\n dict(type='RandomResizedCrop', size=image_size2),\n dict(type='RandomHorizontalFlip'),\n dict(type='ToTensor'),\n dict(type='Normalize', **img_norm_cfg),\n dict(type='Collect', keys=['img', 'gt_labels'])\n]\ntest_pipeline = [\n dict(type='Resize', size=image_size1),\n dict(type='CenterCrop', size=image_size2),\n dict(type='ToTensor'),\n dict(type='Normalize', **img_norm_cfg),\n dict(type='Collect', keys=['img', 'gt_labels'])\n]\n\ndata = dict(\n imgs_per_gpu=32, # total 256\n workers_per_gpu=4,\n train=dict(\n type=dataset_type,\n data_source=dict(\n type=data_source_type,\n list_file=train_itag_file,\n class_list=CLASSES,\n ),\n pipeline=train_pipeline),\n val=dict(\n type=dataset_type,\n data_source=dict(\n type=data_source_type,\n list_file=test_itag_file,\n class_list=CLASSES),\n pipeline=test_pipeline))\n\neval_config = dict(initial=False, interval=1, gpu_collect=True)\neval_pipelines = [\n dict(\n mode='test',\n data=data['val'],\n dist_eval=True,\n evaluators=[dict(type='ClsEvaluator', topk=(1, ))],\n )\n]\n\n# optimizer\noptimizer = dict(type='SGD', lr=0.1, momentum=0.9, weight_decay=0.0001)\n\n# learning policy\nlr_config = dict(policy='step', step=[30, 60, 90])\ncheckpoint_config = dict(interval=5)\n\n# runtime settings\ntotal_epochs = 100\ncheckpoint_sync_export = True\nexport = dict(export_neck=True)\n","repo_name":"alibaba/EasyCV","sub_path":"configs/classification/itag/mobilenetv2.py","file_name":"mobilenetv2.py","file_ext":"py","file_size_in_byte":2719,"program_lang":"python","lang":"en","doc_type":"code","stars":1565,"dataset":"github-code","pt":"60"} +{"seq_id":"6543324255","text":"from goodtablesio.utils.signature import (\n create_signature, validate_signature)\n\n\n# Tests\n\ndef test_create_signature():\n key = 'key'\n text = 'text'\n signature = 'sha1=369e2959eb49450338b212748f77d8ded74847bb'\n assert create_signature(key, text) == signature\n\n\ndef test_validate_signature():\n key = 'key'\n text = 'text'\n signature = 'sha1=369e2959eb49450338b212748f77d8ded74847bb'\n assert validate_signature(key, text, signature)\n\n\ndef test_validate_signature_invalid():\n key = 'key'\n text = 'text'\n signature = 'sha1=369e2959eb49450338b212748f77d8ded74-----'\n assert not validate_signature(key, text, signature)\n","repo_name":"AntoineAugusti/goodtables.io","sub_path":"goodtablesio/tests/utils/test_signature.py","file_name":"test_signature.py","file_ext":"py","file_size_in_byte":653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"60"} +{"seq_id":"8403669147","text":"import json\n\nfrom django.core.urlresolvers import reverse\nfrom django.test import TestCase\nfrom django.test.client import Client\n\nfrom vavilov.db_management.tests import load_test_data\n\n\nclass ApiTest(TestCase):\n def setUp(self):\n load_test_data()\n\n def test_accession_number(self):\n client = Client()\n response = client.get(reverse('api_accession_numbers'))\n accession_numbers = json.loads(response.content.decode())\n assert len(accession_numbers) == 14\n\n def test_taxons(self):\n client = Client()\n response = client.get(reverse('api_taxons'))\n taxons = json.loads(response.content.decode())\n assert len(taxons) == 14\n\n url = reverse('api_taxons') + \"?term=br\"\n response = client.get(url)\n taxons = json.loads(response.content.decode())\n taxons = [t['label'] for t in taxons]\n assert taxons == ['Brassica', 'Brassica oleracea',\n 'Brassica oleracea acephala']\n","repo_name":"pziarsolo/vavilov2","sub_path":"vavilov/test/test_apis.py","file_name":"test_apis.py","file_ext":"py","file_size_in_byte":992,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"60"} +{"seq_id":"43630235966","text":"# /usr/bin/env python\n# -*- coding:utf-8 -*-\n\nfrom app自动化.config.登录 import *\nfrom app自动化.data.数据 import *\n\nclass ceshi(unittest.TestCase):\n def test_1(self):\n aa=shuju()\n bb=denglu()\n shu1=aa.shu1()\n dr=bb.bbb(int(shu1[0][0]),int(shu1[0][1]))\n wd = dr.find_elements_by_class_name('android.widget.TextView')\n for i in wd:\n j = i.text\n self.assertIsNotNone(j)\n\n\n\n","repo_name":"menglf1203/python","sub_path":"app自动化/test/喔图测试.py","file_name":"喔图测试.py","file_ext":"py","file_size_in_byte":448,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"60"} +{"seq_id":"23488597273","text":"\"\"\"\nArrange for all ContextService connections to be torn down unconditionally,\nrequired for reliable LRU tests.\n\"\"\"\n\nimport ansible_mitogen.connection\nimport ansible_mitogen.services\nimport mitogen.service\n\nfrom ansible.plugins.strategy import StrategyBase\nfrom ansible.plugins.action import ActionBase\n\n\nclass ActionModule(ActionBase):\n def run(self, tmp=None, task_vars=None):\n if not isinstance(self._connection,\n ansible_mitogen.connection.Connection):\n return {\n 'skipped': True,\n }\n\n self._connection._connect()\n return {\n 'changed': True,\n 'result': self._connection.parent.call_service(\n service_name='ansible_mitogen.services.ContextService',\n method_name='shutdown_all',\n )\n }\n","repo_name":"candlerb/mitogen","sub_path":"tests/ansible/lib/action/mitogen_shutdown_all.py","file_name":"mitogen_shutdown_all.py","file_ext":"py","file_size_in_byte":844,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"60"} +{"seq_id":"11019231466","text":"import json\n\nfrom fastapi import FastAPI, HTTPException\nfrom pydantic import BaseModel\nfrom typing import Optional\nfrom fastapi.middleware.cors import CORSMiddleware\n\n\norigins = [\n \"http://localhost.tiangolo.com\",\n \"https://localhost.tiangolo.com\",\n \"http://localhost\",\n \"http://localhost:8080\",\n \"http://localhost:8000\",\n \"http://localhost:3000\",\n]\n\napp = FastAPI()\n\napp.add_middleware(\n CORSMiddleware,\n allow_origins=[\"*\"],\n allow_credentials=True,\n allow_methods=[\"*\"],\n allow_headers=[\"*\"],\n)\n\nclass Dish(BaseModel):\n id: Optional[int] = None\n name: str\n image: str\n desc: str\n steps: str\n cat: str\n\n\nwith open(\"dishes.json\", \"r\") as f:\n dishes = json.load(f)\n\n\n@app.post(\"/adddish\", status_code=201)\nasync def add_dish(dish: Dish):\n d_id = max([d[\"id\"] for d in dishes[\"dishes\"]]) + 1\n new_dieh = {\n \"id\": d_id,\n \"name\": dish.name,\n \"image\": dish.image,\n \"desc\": dish.desc,\n \"steps\": dish.steps,\n \"cat\": dish.cat\n }\n dishes[\"dishes\"].append(new_dieh)\n with open(\"dishes.json\", \"w\") as f:\n json.dump(dishes, f)\n\n\n@app.get(\"/dishes\")\nasync def root():\n return dishes['dishes']\n\n\n@app.get(\"/dishes/{d_cat}\")\ndef get_cat(d_cat: str):\n dishes_by_cat = [d for d in dishes[\"dishes\"] if d['cat'] == d_cat]\n return dishes_by_cat if len(dishes_by_cat) > 0 else {}\n\n\n@app.put(\"/change_dish\", status_code=204)\ndef change_d(dish: Dish):\n new_dieh = {\n \"id\": dish.id,\n \"name\": dish.name,\n \"image\": dish.image,\n \"desc\": dish.desc,\n \"steps\": dish.steps,\n \"cat\": dish.cat\n }\n dish_list = [d for d in dishes['dishes'] if d[\"id\"] == dish.id]\n if len(dish_list) > 0:\n dishes.remove(dish_list[0])\n dishes.append(new_dieh)\n with open(\"dishes.json\", \"w\") as f:\n json.dump(dishes, f)\n return dishes\n else:\n return HTTPException(status_code=404, detail=f\"dish with the id {dish.id} dosn't exist\")\n\n\n@app.delete(\"/delete_dish/{d_id}\", status_code=204)\ndef delete_d(d_id: int):\n dish_list = [d for d in dishes if int(d[\"id\"]) == int(d_id)]\n if len(dish_list) > 0:\n dishes.remove(dish_list[0])\n with open(\"dishes.json\", \"w\") as f:\n json.dump(dishes, f)\n return dishes\n else:\n return HTTPException(status_code=404, detail=f\"dish with the id {d_id} dosn't exist\")\n\n","repo_name":"akar27/api_react_python","sub_path":"RESTapi/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2419,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"60"} +{"seq_id":"1821933165","text":"import telebot\nfrom TOKEN import TOKEN\nfrom extensions import APIException, CurrencyConverter\n\n\nbot = telebot.TeleBot(TOKEN)\n\n\n@bot.message_handler(commands=['start', 'help'])\ndef hello(message: telebot.types.Message):\n text = f'Hello, {message.chat.username}. I can show you the currency exchange rate. '\\\n '\\n'\\\n 'To begin, please use this format: \"Currency\" \"Convert to\" \"Amount\". Example: USD EUR 1500'\\\n '\\n'\\\n 'Available commands: Values - shows available currencies.'\n bot.reply_to(message, text)\n\n\n@bot.message_handler(commands=['values'])\ndef values(message: telebot.types.Message):\n bot.reply_to(message, 'Available currencies: Euro, Great Britain Pound(GBP), USD')\n\n\n@bot.message_handler(content_types=['text', ])\ndef exchange(message: telebot.types.Message):\n try:\n values = message.text.split(' ')\n\n if len(values) != 3:\n raise APIException('Invalid number of parameters, please check example in /values')\n\n base, quote, amount = values\n response = CurrencyConverter.get_price(quote, base, amount)\n\n if not amount.isdigit():\n raise APIException('Amount should be a valid number.')\n\n except APIException as errormessage:\n bot.reply_to(message, f'Input error.\\n{errormessage}')\n except Exception as errormessage:\n bot.reply_to(message, f'Could not process a command, server error.\\n{errormessage}')\n else:\n text = f'{amount} {base} is {response} {quote}'\n bot.send_message(message.chat.id, text)\n\n\nbot.polling()\n","repo_name":"nnwq/TelegramBot","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1573,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"60"} +{"seq_id":"41307754618","text":"from astropy.io import ascii\nimport matplotlib.pyplot as plt\n\n\ndef dRAvsdDec(filename: str, columns) -> None:\n ''' Plot the deltaRA vs delta Dec given a file containing the position offset in\n milliarcseconds, of a star as a function of time'''\n data =ascii.read(filename, names=columns)\n fig,ax=plt.subplots()\n ax.scatter(data['RA'],data['Dec'])\n #plt.axis([-430,400,-550,280])\n plt.xlabel('$\\Delta$RA (mas)')\n plt.ylabel('$\\Delta$Dec (mas)')\n plt.show()\n \n return None\n\nif __name__==\"__main__\":\n filename = 'phy270_ass1_parallax.txt'\n columns = ['Days', 'RA', 'Dec']\n dRAvsdDec(filename, columns)\n ","repo_name":"Devejya/AstroPhysics","sub_path":"A1/q2_1.py","file_name":"q2_1.py","file_ext":"py","file_size_in_byte":645,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"60"} +{"seq_id":"755479910","text":"# coding: utf-8\n\nimport cherrypy\nimport datetime\n\nfrom .database import Database_cl\nfrom .view import View_cl\n\n\n# GET /articles/all/ alle Artikel\n# GET /articles/month/:month die Artikel, die im angegebenen Monat erstellt oder geändert wurden\n# GET /articles/tag/:tag die Artikel, die die angegebene Marke enthalten\n\n#----------------------------------------------------------\nclass Articles_cl(object):\n#----------------------------------------------------------\n\n exposed = True\n\n #-------------------------------------------------------\n def __init__(self):\n #-------------------------------------------------------\n self.db_o = Database_cl()\n self.view_o = View_cl()\n\n #-------------------------------------------------------\n def GET(self, mode, parameter=None):\n #-------------------------------------------------------\n retVal_s = ''\n\n if mode == 'all':\n retVal_s = self.getList_p()\n \n if mode == 'month':\n retVal_s = self.getArticlesByMonth_p(parameter)\n \n if mode == 'tag':\n retVal_s = self.getArticlesByTag_p(parameter)\n\n return retVal_s\n \n #-------------------------------------------------------\n def getList_p(self):\n #-------------------------------------------------------\n data_a = self.db_o.read_px()\n # default-Werte entfernen\n \n ndata_a = data_a[0:]\n \n return self.view_o.createList_px(ndata_a)\n \n #-------------------------------------------------------\n def getArticlesByMonth_p(self, month):\n #-------------------------------------------------------\n # Format muss sein: 01.2018, also das Jahr muss einbezogen werden\n year = month[3:7]\n month = month[0:2]\n \n data_a = self.db_o.read_px()\n \n data_unsort = []\n \n #--------------------------------\n i = 0\n\n for value in data_a:\n if (int(value['chdat'][3:5]) == int(month) and int(value['chdat'][6:10]) == int(year)): # python slicing substring 4th element up to 5th element = month\n data_unsort.append(value)\n\n data_sort = []\n \n data_unsort.sort(key=lambda x: x['chdat'])\n data_sort = data_unsort[::-1]\n\n return self.view_o.createList_px(data_sort)\n \n #-------------------------------------------------------\n def getArticlesByTag_p(self, tag):\n #-------------------------------------------------------\n data_a = self.db_o.read_px()\n \n data_unsort = []\n \n for value in data_a:\n for valuetag in value['tag']:\n if valuetag == tag:\n data_unsort.append(value)\n \n data_sort = []\n \n data_unsort.sort(key=lambda x: x['chdat'])\n data_sort = data_unsort[::-1]\n\n\n return self.view_o.createList_px(data_sort)\n# EOF","repo_name":"vsypraktikum/web","sub_path":"WEB/WEB Praktika/mhb/app/articles.py","file_name":"articles.py","file_ext":"py","file_size_in_byte":2849,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"60"} +{"seq_id":"43143459034","text":"from flask import Flask, render_template, request, url_for, redirect\n\napp = Flask(__name__)\n\nlista = []\n\n\n@app.route('/', methods=['GET', 'POST'])\ndef index():\n total = 0\n if request.method == 'GET':\n for item in lista:\n if item['isreceita'] == 1:\n total += int(item['preco'])\n else:\n total -= int(item['preco'])\n return render_template(\"tela_produtos.html\", itens=lista, total=total)\n\n\n@app.route(\"/produto/novo\")\ndef get_produto_novo():\n id = int(request.args.get(\"id\"))\n item = {}\n if id > 0:\n item = lista[id-1]\n return render_template(\"produto_novo.html\", item=item)\n\n\n@app.route(\"/produto/novo\", methods=[\"POST\"])\ndef produto_novo():\n form_data = request.form\n index = int(request.args.get(\"id\"))\n isreceita = int(request.args.get(\"receita\"))\n if index > 0:\n atualizado = {\n \"id\": index,\n \"nome\": form_data[\"nome\"],\n \"preco\": form_data[\"preco\"],\n \"isreceita\": isreceita\n }\n lista[index-1] = atualizado\n else:\n novo = {\n \"id\": len(lista) + 1,\n \"nome\": form_data[\"nome\"],\n \"preco\": form_data[\"preco\"],\n \"isreceita\": isreceita\n }\n lista.append(novo)\n print(lista)\n\n return redirect(url_for(\"index\"))\n\n\n@app.route(\"/produto/excluir\")\ndef produto_excluir():\n id = int(request.args.get(\"id\"))\n lista.remove(lista[id-1])\n return redirect(url_for(\"index\"))\n\n\nif __name__ == \"__main__\":\n app.run(\"localhost\", 55000, True)\n","repo_name":"FernandoMorenoFernandes/prova-web","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1573,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"60"} +{"seq_id":"40088173086","text":"from unittest import TestCase\n\nfrom PIL import Image, ImageDraw\n\nfrom python.src.processors.image_rotator import ImageRotator\n\n\ndef create_initial_image():\n img = Image.new(\"RGB\", (100, 200), color=\"white\")\n draw = ImageDraw.Draw(img)\n # Draw a triangle pointing upwards\n draw.polygon([(40, 50), (60, 50), (50, 30)], fill=\"black\")\n return img\n\n\nclass TestImageRotator(TestCase):\n def setUp(self):\n config = {\n \"left\": {\"angle\": 90},\n \"right\": {\"angle\": -90},\n }\n self.image_rotator = ImageRotator(config)\n\n def test_process_left(self):\n img = create_initial_image()\n\n # Expected: triangle pointing to the left\n expected_img = img.rotate(90, resample=Image.Resampling.BICUBIC, expand=True)\n\n result = self.image_rotator.process(img, True)\n\n # Compare properties of the resulting image and the expected image\n self.assertTrue(result == expected_img)\n\n def test_process_right(self):\n img = create_initial_image()\n\n # Expected: triangle pointing to the right\n expected_img = img.rotate(-90, resample=Image.Resampling.BICUBIC, expand=True)\n\n result = self.image_rotator.process(img, False)\n\n # Compare properties of the resulting image and the expected image\n self.assertTrue(result == expected_img)\n","repo_name":"iankonradjohnson/BatchImageProcessor","sub_path":"python/test/processors/test_image_rotator.py","file_name":"test_image_rotator.py","file_ext":"py","file_size_in_byte":1346,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"60"} +{"seq_id":"26841496735","text":"from antlr4 import CommonTokenStream, InputStream\nfrom sql_analyze.grammars.ClickHouse import (ClickHouseLexer, ClickHouseParser,\n statement_builder)\nfrom typing import Optional\n\n\ndef parse_clickhouse_sql_tree(sql_statement: str):\n \"\"\"Creates a parse tree from the provided (multi) SQL statement.\"\"\"\n input_stream = InputStream(sql_statement)\n lexer = ClickHouseLexer.ClickHouseLexer(input_stream)\n stream = CommonTokenStream(lexer)\n parser = ClickHouseParser.ClickHouseParser(stream)\n return (parser.multiQueryStmt(), parser)\n\n\ndef parse_clickhouse_sql_statement(sql_statement: str):\n \"\"\"Parses a list of statements from the provided (multi) SQL statement.\"\"\"\n tree, parser = parse_clickhouse_sql_tree(sql_statement)\n visitor = statement_builder.MultiQueryStmtVisitor()\n visitor.visit(tree)\n return (tree, parser, visitor.statements)\n\n\ndef parse_clickhouse_sql_create(sql_statement: str,\n java_package_name: Optional[str] = None):\n \"\"\"Parses a create statement from sql_statement text, and returns it.\"\"\"\n input_stream = InputStream(sql_statement)\n lexer = ClickHouseLexer.ClickHouseLexer(input_stream)\n stream = CommonTokenStream(lexer)\n parser = ClickHouseParser.ClickHouseParser(stream)\n tree = parser.createStmt()\n visitor = statement_builder.QueryStmtVisitor(java_package_name)\n visitor.visitCreateStmt(tree)\n if visitor.statements:\n return visitor.statements[0]\n return None\n\n\ndef parse_clickhouse_expression(sql_expression: str):\n \"\"\"Creates a parse tree from a SQL expression.\"\"\"\n input_stream = InputStream(sql_expression)\n lexer = ClickHouseLexer.ClickHouseLexer(input_stream)\n stream = CommonTokenStream(lexer)\n parser = ClickHouseParser.ClickHouseParser(stream)\n return (parser.expression(), parser)\n","repo_name":"NunaInc/sql_tools","sub_path":"sql_analyze/grammars/ClickHouse/parse_sql_lib.py","file_name":"parse_sql_lib.py","file_ext":"py","file_size_in_byte":1876,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"60"} +{"seq_id":"1315091530","text":"import unittest\n\nfrom sipay import Ecommerce\n\nfrom sipay.amount import Amount\n\nfrom sipay.ecommerce.responses.unlock import Unlock\n\n\nclass UnlockTests(unittest.TestCase):\n\n def setUp(self):\n\n self.payload = {\n 'amount': 100,\n 'currency': 'EUR'\n }\n self.amount = Amount(self.payload['amount'], self.payload['currency'])\n\n def test_init_unlock(self):\n\n ecommerce = Ecommerce('etc/config.ini')\n\n amount = Amount(100, 'EUR')\n\n self.unlock = ecommerce.unlock('something', amount)\n\n self.assertIsInstance(self.unlock, Unlock)\n\n def test_init2test_init_unlock(self):\n\n self.assertIn('amount', self.payload)\n self.assertIn('currency', self.payload)\n self.assertEqual(self.payload['amount'], self.amount.amount)\n self.assertEqual(self.payload['currency'], self.amount.currency)\n","repo_name":"Sipay/python-sdk","sub_path":"tests/test_unlock.py","file_name":"test_unlock.py","file_ext":"py","file_size_in_byte":877,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"60"} +{"seq_id":"12130403146","text":"import speech_recognition\nimport librosa\nimport soundfile as sf\nimport base64\nfrom flask_cors import CORS\nfrom flask import Flask, request\napp = Flask(__name__)\nCORS(app)\n\n\n# Transformer la donnée de la base64 au format mp3 et la stocker dans un fichier output.mp3\ndef decode_base64_to_mp3(base64_string):\n wav_bytes = base64.b64decode(base64_string)\n \n # write the bytes to a file\n with open(\"output.mp3\", \"wb\") as f:\n f.write(wav_bytes)\n\n\n@app.route('/audio', methods=['POST'])\ndef handle_request():\n # Récupérer les données du corps de la requête\n data = request.get_json()\n print(data)\n text = ''\n base64_string = data['audioData']\n decode_base64_to_mp3(base64_string)\n # Lire le fichier mp3\n data, sr = librosa.load('output.mp3')\n # Transformer l'audio mp3 au format wav\n sf.write(\"example.wav\", data, sr)\n\n recognizer = speech_recognition.Recognizer()\n\n with speech_recognition.AudioFile(\"example.wav\") as wavaudio:\n audio = recognizer.record(wavaudio, duration=5)\n \n # reconnaître la parole à l'aide de Google Speech Recognition\n try:\n text = recognizer.recognize_google(audio, language='fr-FR')\n text = text.lower()\n except speech_recognition.UnknownValueError:\n text = \"Je n'ai pas compris votre audio, pouvez-vous le répéter ?\"\n except speech_recognition.RequestError as e:\n text = \"Impossible de demander les résultats du service de reconnaissance vocale Google; {0}\".format(e)\n return {\n 'statusCode': 200,\n 'body': text # envoyer le text transcrit\n }\n\n\n\n\nif __name__ == '__main__':\n app.run(debug=True)","repo_name":"Mustapha-Manssoum/QUIZZ-Game","sub_path":"ML/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1691,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"60"} +{"seq_id":"35822836385","text":"\nfrom fastapi import APIRouter, Body, Security\nfrom fastapi.encoders import jsonable_encoder\nfrom fastapi.security import HTTPAuthorizationCredentials, HTTPBearer\nfrom typing import List\nfrom db.userDb import (\n add_user,\n delete_user,\n retrieve_user,\n retrieve_users,\n update_user,\n login\n)\nfrom models.User import UserIn, UserOut\nfrom auth import Auth\n\nsecurity = HTTPBearer()\nauth_handler = Auth()\nrouter = APIRouter()\n\n@router.post(\n \"/signup\",\n response_description=\"User data added into the database\"\n)\nasync def add_user_data(user: UserIn = Body(...)):\n '''\n ### Signup a new User\n ---\n #### _NOTE:_ If username or email already exist a **409** will be returned\n ---\n '''\n user = jsonable_encoder(user)\n return await add_user(user)\n\n@router.post(\n \"/login\",\n response_description=\"User data added into the database\"\n)\nasync def login_user(user: UserIn = Body(...)):\n '''\n ### Login existing user\n Upon successful login an `access_token` and `refresh_token` will be returned to the calling entity.\n ```json\n {\n \"access_token\": \"jwt\",\n \"refresh_token\": \"jwt\"\n }\n ```\n '''\n user = jsonable_encoder(user)\n return await login(user)\n\n@router.get(\n \"/\",\n response_description=\"Users retrieved\"\n)\nasync def get_users_data() -> List[UserOut]:\n '''Get Users'''\n return await retrieve_users()\n\n\n@router.get(\n \"/{username}\",\n response_description=\"User data retrieved\"\n)\nasync def get_user_data(username: str):\n '''Get User'''\n return await retrieve_user(username)\n\n@router.post('/secret')\ndef secret_data(credentials: HTTPAuthorizationCredentials = Security(security)):\n '''Test Route'''\n token = credentials.credentials\n if(auth_handler.decode_token(token)):\n return 'Top Secret data only authorized users can access this info'\n\n@router.post('/refresh_token')\nasync def refresh_token(credentials: HTTPAuthorizationCredentials = Security(security)):\n '''Obtain a refresh token for the user'''\n token = credentials.credentials\n get_user_data(id)\n return auth_handler.refresh_token(token)\n\n@router.put(\"/{username}\")\nasync def update_user_data(\n username: str,\n req: UserIn = Body(...),\n credentials: HTTPAuthorizationCredentials = Security(security)\n):\n '''Update User'''\n if auth_handler.is_user_permitted(credentials.credentials, req):\n return await update_user(\n username,\n req\n )\n \n\n@router.delete(\n \"/{username}\",\n response_description=\"User data deleted from the database\"\n)\nasync def delete_user_data(username: str):\n '''Delete User'''\n return await delete_user(username)\n","repo_name":"NetPenguins/edgy-auth-jwt","sub_path":"routes/user.py","file_name":"user.py","file_ext":"py","file_size_in_byte":2690,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"60"} +{"seq_id":"5793059119","text":"''' Plotting of head0, head1 and diff.'''\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport datetime as dt\nimport load_nom_II as ld\nimport plot_nom_II as pt\n\n\ndef plot(year,month,day,lastofmonth=False):\n # Loading data\n if lastofmonth:\n if month!=12:\n time, data = ld.load_nom(period=(dt.datetime(year,month,day),dt.datetime(year,month+1,1)), products=('M','A'))\n else:\n time, data = ld.load_nom(period=(dt.datetime(year,month,day),dt.datetime(year+1,1,1)), products=('M','A'))\n else:\n time, data = ld.load_nom(period=(dt.datetime(year,month,day),dt.datetime(year,month,day+1)), products=('M','A'))\n print('Data loaded successfully.')\n \n # Combining data (Main and Auxiliary Product)\n ld.combine_data(time, data)\n print('Data combined successfully.')\n \n # Plotting data (Aufruf zum Speichern in Plotfunktion)\n pt.plot_ts(data, time, period=[dt.datetime(2021,12,4,13,30),dt.datetime(2021,12,4,16,30)], head=0, save=True, norm='tmax')\n # pt.plot_ts(data, time, head=0, save='plots_norm/logmax/', norm='logmax')\n # pt.plot_ts(data, time, head=1, save='plots_norm/')\n # pt.plot_ts_diff(data,time, save='plots_norm/', single=False)\n plt.close('all')\n print('Data plotted successfully.')\n\nplot(2021,12,4)\n \n \n# Oktober 2021 \n# for i in range(22,32):\n# mon = 10\n# y = 2021\n# if i != 31:\n# plot(y,mon,i)\n# else:\n# plot(y,mon,i,lastofmonth=True)\n \n# November 2021\n# for i in range(1,31):\n# mon = 11\n# y = 2021\n# if i != 30:\n# plot(y,mon,i)\n# else:\n# plot(y,mon,i,lastofmonth=True)\n\n# Dezember 2021\n# for i in range(1,32):\n# mon = 12\n# y = 2021\n# if i != 31:\n# plot(y,mon,i)\n# else:\n# plot(y,mon,i,lastofmonth=True)\n\n# Januar 2022\n# 10/01/22 und 11/01/22 wollen anscheinend nicht...\n# for i in range(12,32):\n# mon = 1\n# y = 2022\n# if i != 31:\n# plot(y,mon,i)\n# else:\n# plot(y,mon,i,lastofmonth=True)\n\n# # Februar 2022\n# for i in range(1,29):\n# mon = 2\n# y = 2022\n# if i != 28:\n# plot(y,mon,i)\n# else:\n# plot(y,mon,i,lastofmonth=True)\n \n# # März 2022\n# for i in range(1,9):\n# mon = 3\n# y =2022\n# if i != 31:\n# plot(y,mon,i)\n# else:\n# plot(y,mon,i,lastofmonth=True)\n","repo_name":"hannes-ebe/SolO_STEP","sub_path":"plot_data.py","file_name":"plot_data.py","file_ext":"py","file_size_in_byte":2367,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"60"} +{"seq_id":"19598219907","text":"\"\"\"\n# Definition for a QuadTree node.\nclass Node:\n def __init__(self, val, isLeaf, topLeft, topRight, bottomLeft, bottomRight):\n self.val = val\n self.isLeaf = isLeaf\n self.topLeft = topLeft\n self.topRight = topRight\n self.bottomLeft = bottomLeft\n self.bottomRight = bottomRight\n\"\"\"\n\nclass Solution:\n def construct(self, grid: List[List[int]]) -> 'Node':\n self.grid = grid\n return self.recurse(0, 0, len(grid))\n \n def recurse(self, rowstart, colstart, width):\n onecount = 0\n zerocount = 0\n for row in range(rowstart, rowstart+width):\n for col in range(colstart, colstart+width):\n if self.grid[row][col] == 0: zerocount += 1\n else: onecount += 1\n \n if zerocount and onecount:\n half = width//2\n topleft = self.recurse(rowstart, colstart, half)\n topright = self.recurse(rowstart, colstart+half, half)\n bottomleft = self.recurse(rowstart+half, colstart, half)\n bottomright = self.recurse(rowstart+half, colstart+half, half)\n return Node(1, False, topleft, topright, bottomleft, bottomright)\n \n val = 1 if onecount else 0\n return Node(val, True, None, None, None, None)\n \n \n \n","repo_name":"jiheechoi6/a-leetcode-a-day","sub_path":"427_quadtree.py","file_name":"427_quadtree.py","file_ext":"py","file_size_in_byte":1411,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"60"} +{"seq_id":"22445431484","text":"#!/usr/bin/env python3\n\"\"\" VIO benchmarking library. \"\"\"\n\nimport argparse\nfrom collections import OrderedDict\nfrom datetime import datetime\nimport time\nimport subprocess\nimport os\nimport pathlib\nimport json\nfrom collections import deque\nimport concurrent.futures\nfrom functools import partial\nimport multiprocessing\n\nfrom .utils import GpsToLocalConverter\nfrom .compute_metrics import computeMetrics, Metric\nfrom .plot import makeAllPlots, getFigurePath\n\nimport numpy as np\n\nDATE_FORMAT = \"%Y-%m-%d_%H-%M-%S\"\n\nDEFAULT_OUTPUT_DIR = \"output\"\nDEFAULT_METRICS = \",\".join([\n Metric.PIECEWISE.value,\n Metric.FULL_3D.value,\n])\n\n# Can be enabled to get postprocessed and real-time tracks plot in the same figures.\n# Usually it gets too cluttered to make sense of.\nCOMPARE_POSTPROCESSED = False\n\n# Will be printed to VIO logs.\nCPU_TIME_MESSAGE = \"CPU time (user sys percent)\"\n\nDEFAULT_SAMPLE_INTERVAL_FOR_VELOCITY = 0.02\n\ndef getArgParser():\n allMetrics = [m.value for m in list(Metric)]\n\n parser = argparse.ArgumentParser(__doc__)\n parser.add_argument(\"-output\", help=\"Output parent directory\", default=DEFAULT_OUTPUT_DIR)\n parser.add_argument(\"-rootDataDir\", help=\"Paths in benchmark sets are given relative to this directory\", default=\"data/benchmark\")\n parser.add_argument(\"-set\", help=\"Path to JSON description of benchmark set to run\")\n parser.add_argument(\"-dataDir\", help=\"Run all datasets in this directory. Ignores `-rootDataDir`\")\n parser.add_argument(\"-setDir\", help=\"An additional directory to search for benchmark set\", default=\"../sets\")\n parser.add_argument(\"-recordingDir\", help=\"Path to a single benchmark recording to run. Ignores `-rootDataDir`\")\n parser.add_argument(\"-params\", help=\"Parameters as a string, eg '-params \\\"-useStereo=false -v=1\\\"'\")\n parser.add_argument(\"-threads\", help=\"How many CPU threads to use for running benchmarks\", default=6)\n parser.add_argument(\"-runId\", help=\"Output folder name. If unset will use timestamp\")\n parser.add_argument(\"-skipBenchmark\", help=\"Skips running benchmark and only aggregates existing ones. For development use.\", action=\"store_true\")\n parser.add_argument(\"-offsetTracks\", help=\"When enabled, tracks are stacked instead of overlaid\", action=\"store_true\")\n parser.add_argument('-metricSet', type=str, default=DEFAULT_METRICS,\n help=\"One or more metric kinds, joined by comma, selected from: {}\".format(\", \".join(allMetrics)))\n parser.add_argument(\"-fixOrigin\", action=\"store_true\", help=\"Force track starting positions to match for metrics and plots\")\n parser.add_argument(\"-methodName\", default=\"VIO\", help=\"Name of the VIO method being benchmarked\")\n parser.add_argument(\"-gitDir\", help=\"Subfolder that should be used for saving git stats\")\n parser.add_argument(\"-gitBranchName\", help=\"Written to info.json\")\n parser.add_argument(\"-baseline\", help=\"Path to metrics.json to use in computing relative metrics\")\n parser.add_argument(\"-excludePlots\", type=str, help=\"Tracks to skip plotting, split by comma\", default=\"ondevice\")\n parser.add_argument(\"-debug\", help=\"Print more informative error messages\", action=\"store_true\")\n parser.add_argument(\"-sampleIntervalForVelocity\", help=\"Downsamples ground truth position/orientation frequency before calculating velocity and angular velocity, provide minimum number of seconds between samples i.e. 0.1 = max 10Hz GT\", type=float, default=DEFAULT_SAMPLE_INTERVAL_FOR_VELOCITY)\n return parser\n\n\nclass Benchmark:\n dir = None\n params = None\n name = None\n paramSet = None\n\n def __init__(self, dir, name=None, params=None, paramSet=None):\n self.dir = dir\n self.name = name\n self.params = params\n self.paramSet = paramSet\n\ndef computeVideoTimeSpan(dataJsonlPath):\n if not os.path.exists(dataJsonlPath): return None\n span = None\n with open(dataJsonlPath) as dataJsonlFile:\n for line in dataJsonlFile:\n o = json.loads(line)\n if not \"frames\" in o or not \"time\" in o: continue\n if not span: span = [o[\"time\"], o[\"time\"]]\n span[1] = o[\"time\"]\n if span[1] < span[0]: return None\n return span\n\ndef writeSharedInfoFile(args, dirs, startTime, endTime, aggregateMetrics):\n def runAndCapture(cmd):\n return subprocess.run(cmd, stdout=subprocess.PIPE, shell=True).stdout.decode('utf-8').strip()\n\n info = {\n \"outputDirectory\": dirs.results,\n \"startTime\": startTime,\n \"endTime\": endTime,\n \"metrics\": aggregateMetrics,\n \"parameters\": args.params,\n }\n\n info[\"methodName\"] = args.methodName\n info[\"parameters\"] = args.params\n mainBinary = dirs.results + \"/main\"\n if os.path.isfile(mainBinary) and runAndCapture(\"command -v shasum\"):\n info[\"fingerprint\"] = runAndCapture(\"shasum -a 256 \" + mainBinary)\n info[\"system\"] = runAndCapture(\"uname -a\")\n if args.set: info[\"set\"] = args.set\n if args.dataDir: info[\"dataDir\"] = args.dataDir\n\n if args.gitDir:\n originalDir = os.getcwd()\n os.chdir(args.gitDir)\n inGitRepository = runAndCapture(\"git rev-parse --is-inside-work-tree\")\n if inGitRepository == \"true\":\n if args.gitBranchName:\n # The `rev-parse` often returns \"HEAD\" in Github's runner.\n branchName = args.gitBranchName\n else:\n branchName = runAndCapture(\"git rev-parse --abbrev-ref HEAD\")\n info[\"git\"] = {\n \"repository\": runAndCapture(\"basename `git rev-parse --show-toplevel`\"),\n \"branch\": branchName,\n \"sha\": runAndCapture(\"git rev-parse --short HEAD\"),\n }\n subprocess.run(\"git show > \\\"{}/git_show.txt\\\"\".format(dirs.results), shell=True)\n subprocess.run(\"git diff > \\\"{}/git_diff.txt\\\"\".format(dirs.results), shell=True)\n subprocess.run(\"git diff --staged > \\\"{}/git_diff_staged.txt\\\"\".format(dirs.results), shell=True)\n os.chdir(originalDir)\n\n infoJsonPath = dirs.results + \"/info.json\"\n with open(infoJsonPath, \"w\") as f:\n f.write(json.dumps(info, indent=4, separators=(',', ': ')))\n\n return infoJsonPath\n\n# Maps from JSONL format keys to names shown in the output data and plots.\nTRACK_KINDS = {\n \"groundTruth\": \"groundTruth\",\n \"ARKit\": \"ARKit\",\n \"arcore\": \"ARCore\",\n \"arengine\": \"AREngine\",\n \"output\": \"OnDevice\",\n \"realsense\": \"RealSense\",\n \"gps\": \"GPS\",\n \"rtkgps\": \"RTKGPS\",\n \"externalPose\": \"externalPose\",\n}\n\nDEVICE_TRANSFORM = {}\nWORLD_TRANSFORM = {\n \"arcore\": np.array([\n [1, 0, 0, 0],\n [0, 0, -1, 0],\n [0, 1, 0, 0],\n [0, 0, 0, 1],\n ]),\n \"arengine\": np.array([\n [1, 0, 0, 0],\n [0, 0, -1, 0],\n [0, 1, 0, 0],\n [0, 0, 0, 1],\n ]),\n # TODO Missing realsense.\n}\n\ndef convertComparisonData(casePaths, metricSets):\n gpsConverter = GpsToLocalConverter()\n rtkgpsConverter = GpsToLocalConverter()\n frameCount = 0\n datasets = {}\n\n needsOrientation = (Metric.VELOCITY.value in metricSets\n or Metric.ANGULAR_VELOCITY.value in metricSets\n or Metric.ORIENTATION.value in metricSets\n or Metric.ORIENTATION_FULL.value in metricSets\n or Metric.ORIENTATION_ALIGNED.value in metricSets)\n if needsOrientation:\n # Import conditionally since scipy is otherwise not needed for benchmarking.\n from scipy.spatial.transform import Rotation\n\n def handleRow(rowJson):\n kind = None\n for k in TRACK_KINDS:\n if rowJson.get(k) is not None:\n kind = k\n break\n if not kind: return\n\n if not kind in datasets:\n datasets[kind] = []\n\n hasOrientation = False\n dToW = np.identity(4) # Device-to-world matrix.\n if kind == \"gps\":\n p = gpsConverter.convert(**rowJson[\"gps\"])\n elif kind == \"rtkgps\":\n p = rtkgpsConverter.convert(**dataRow[\"rtkgps\"])\n else:\n p = rowJson[kind][\"position\"]\n if needsOrientation and \"orientation\" in rowJson[kind]:\n hasOrientation = True\n q = [rowJson[kind][\"orientation\"][c] for c in \"xyzw\"]\n dToW[0:3, 0:3] = Rotation.from_quat(q).as_matrix()\n dToW[0:3, 3] = [p[c] for c in \"xyz\"]\n\n if kind in DEVICE_TRANSFORM:\n dToW = dToW.dot(DEVICE_TRANSFORM[kind])\n if kind in WORLD_TRANSFORM:\n dToW = WORLD_TRANSFORM[kind].dot(dToW)\n\n json = {\n \"time\": rowJson[\"time\"],\n \"position\": { \"x\": dToW[0, 3], \"y\": dToW[1, 3], \"z\": dToW[2, 3] },\n }\n if hasOrientation:\n q = Rotation.from_matrix(dToW[0:3, 0:3]).as_quat()\n json[\"orientation\"] = { \"x\": q[0], \"y\": q[1], \"z\": q[2], \"w\": q[3] }\n datasets[kind].append(json)\n\n if os.path.exists(casePaths[\"input\"]):\n with open(casePaths[\"input\"]) as f:\n for line in f.readlines():\n dataRow = json.loads(line)\n if dataRow.get(\"frames\") is not None:\n frameCount += 1\n continue\n handleRow(dataRow)\n if os.path.exists(casePaths[\"inputGroundTruth\"]):\n with open(casePaths[\"inputGroundTruth\"]) as f:\n for line in f.readlines():\n handleRow(json.loads(line))\n\n postprocessed = []\n if COMPARE_POSTPROCESSED and os.path.exists(casePaths[\"outputMap\"]):\n with open(casePaths[\"outputMap\"]) as f:\n for line in f.readlines():\n row = json.loads(line)\n postprocessed.append({\n \"time\": row[\"time\"],\n \"position\": row[\"position\"],\n })\n\n realtime = []\n if COMPARE_POSTPROCESSED and os.path.exists(casePaths[\"outputRealtime\"]):\n with open(casePaths[\"outputRealtime\"]) as f:\n for line in f.readlines():\n row = json.loads(line)\n realtime.append({\n \"time\": row[\"time\"],\n \"position\": row[\"position\"],\n })\n\n with open(casePaths[\"gtJson\"], \"w\") as gtJsonFile:\n def addDataSet(array, name, d):\n if d: array.append({ 'name': name, 'data': d })\n\n # First found data type will be used as ground truth.\n kindsOrdered = [\n \"groundTruth\",\n \"externalPose\",\n \"ARKit\",\n \"arcore\",\n \"arengine\",\n \"output\",\n \"realsense\",\n \"gps\",\n \"rtkgps\",\n ]\n datasetsOrdered = []\n for kind in kindsOrdered:\n if not kind in datasets: continue\n addDataSet(datasetsOrdered, TRACK_KINDS[kind], datasets[kind])\n\n if COMPARE_POSTPROCESSED:\n addDataSet(datasetsOrdered, \"postprocessed\", postprocessed)\n addDataSet(datasetsOrdered, \"realtime\", realtime)\n\n json.dump({'datasets': datasetsOrdered}, gtJsonFile)\n\n return frameCount\n\ndef benchmarkSingleDataset(benchmark, dirs, vioTrackingFn, args, baselineMetrics=None):\n caseDir = benchmark.dir\n caseName = benchmark.name\n\n casePaths = {\n \"input\": caseDir + \"/data.jsonl\",\n \"inputGroundTruth\": caseDir + \"/groundtruth.jsonl\",\n \"output\": \"{}/{}.jsonl\".format(dirs.out, caseName),\n \"outputMap\": \"{}/{}_map.jsonl\".format(dirs.out, caseName),\n \"outputRealtime\": \"{}/{}_realtime.jsonl\".format(dirs.out, caseName),\n \"gtJson\": \"{}/{}.json\".format(dirs.groundTruth, caseName),\n \"logs\": \"{}/{}.txt\".format(dirs.logs, caseName),\n }\n\n # Compute CPU time and wall time.\n timeCmd = \"\"\n if pathlib.Path(\"/usr/bin/time\").exists():\n # GNU `time` format is easier to set than for bash/zsh `time`.\n timeCmd = \"/usr/bin/time -f '{}: %U %S %P'\".format(CPU_TIME_MESSAGE)\n startTime = time.time()\n\n vioSuccess = vioTrackingFn(args, benchmark, dirs.results, casePaths[\"output\"], timeCmd)\n\n duration = time.time() - startTime\n cpuTime = None\n if timeCmd:\n with open(casePaths[\"logs\"], \"r\") as f:\n for line in f:\n if not line.startswith(CPU_TIME_MESSAGE): continue\n tokens = line.split()\n cpuTime = float(tokens[-2]) + float(tokens[-3]) # sys + user\n\n if not pathlib.Path(casePaths[\"output\"]).exists():\n print(\"No output for case\", caseName)\n return\n\n metricSets = args.metricSet.split(\",\")\n frameCount = convertComparisonData(casePaths, metricSets)\n\n infoPath = \"{}/{}.json\".format(dirs.info, caseName)\n with open(infoPath, \"w\") as infoFile:\n infoJson = {\n \"caseName\": caseName,\n \"dir\": benchmark.dir,\n \"paramSet\": benchmark.paramSet,\n \"methodName\": args.methodName,\n \"duration\": duration,\n \"frameCount\": frameCount,\n \"metricSets\": metricSets,\n \"fixOrigin\": args.fixOrigin,\n \"videoTimeSpan\": computeVideoTimeSpan(casePaths[\"input\"]),\n }\n if cpuTime: infoJson[\"cpuTime\"] = cpuTime\n infoFile.write(json.dumps(infoJson, indent=4, separators=(',', ': ')))\n\n baseline = None\n if baselineMetrics and caseName in baselineMetrics:\n baseline = baselineMetrics[caseName]\n\n try:\n metric = computeMetrics(dirs.results, caseName, baseline, args.sampleIntervalForVelocity)\n except Exception as e:\n if args.debug:\n import traceback\n print(traceback.format_exc())\n print(\"computeMetrics() failed for {}: {}\".format(caseName, e))\n return False\n\n metricStr = \"N/A\" # Either no ground-truth or no VIO output.\n if metric: metricStr = \"{:.3f}\".format(metric)\n print(\"{:40} {:>6.0f}s metric: {:>8}\".format(caseName, duration, metricStr))\n return vioSuccess\n\ndef setupBenchmarkFromSetDescription(args, setName):\n # Look for the set file in a predefined directory or by path.\n searchDirs = [args.setDir + \"/\", os.getcwd(), \"\"]\n success = False\n triedFiles = []\n for searchDir in searchDirs:\n try:\n path = searchDir + setName\n if not \".json\" in path:\n path += \".json\"\n triedFiles.append(path)\n setFile = open(path)\n success = True\n break\n except FileNotFoundError:\n pass\n if not success:\n raise Exception(\"Benchmark set \\\"{}\\\" not found in {}\".format(setName, searchDirs))\n\n setDefinition = json.loads(setFile.read())\n benchmarks = []\n parameterSets = [{}]\n if setDefinition.get(\"parameterSets\") != None:\n parameterSets = setDefinition[\"parameterSets\"]\n print(\"For {} parameters sets: {}\".format(len(setDefinition[\"parameterSets\"]),\n \", \".join(\"[\" + s[\"params\"] + \"]\" for s in setDefinition[\"parameterSets\"])))\n for benchmark in setDefinition[\"benchmarks\"]:\n for parameterSet in parameterSets:\n dir = args.rootDataDir + \"/\" + benchmark[\"folder\"]\n params = []\n if parameterSet.get(\"params\"): params.append(parameterSet[\"params\"])\n if benchmark.get(\"params\"): params.append(benchmark[\"params\"])\n if benchmark.get(\"name\"):\n name = benchmark.get(\"name\").replace(' ', '-')\n else:\n name = benchmark[\"folder\"]\n for symbol in \" _/\": name = name.replace(symbol, '-')\n if parameterSet.get(\"name\"): name = \"{}-{}\".format(name, parameterSet.get(\"name\").replace(' ', '-'))\n benchmarks.append(Benchmark(\n dir=dir,\n params=(None if len(params) == 0 else \" \".join(params)),\n name=name,\n paramSet=(parameterSet[\"name\"] if \"name\" in parameterSet else args.methodName),\n ))\n x = lambda s : \"{} ({})\".format(s[\"folder\"], s[\"params\"]) if s.get(\"params\") else s[\"folder\"]\n print(\"Running {} benchmark datasets:\\n {}\".format(len(setDefinition[\"benchmarks\"]),\n \"\\n \".join(x(s) for s in setDefinition[\"benchmarks\"])))\n\n if len(benchmarks) != len(set(b.name for b in benchmarks)):\n raise Exception(\"All benchmarks don't have unique names! Make sure all parameterSets and duplicate data sets have 'name' field\")\n return benchmarks\n\n\ndef setupBenchmarkFromFolder(args, dataDir):\n cases = next(os.walk(args.dataDir))[1]\n cases.sort()\n print(\"Running benchmarks:\\n \" + \"\\n \".join([os.path.basename(c) for c in cases]))\n benchmarks = []\n for case in cases:\n benchmarks.append(Benchmark(\n dir=os.path.join(args.dataDir, case),\n params=None,\n name=case,\n paramSet=args.methodName,\n ))\n return benchmarks\n\ndef setupBenchmarkFromRecordingDir(args, recordingDir):\n print(\"Running benchmarks:\\n \" + recordingDir)\n case = recordingDir.rsplit('/', 1)[1]\n benchmarks = []\n benchmarks.append(Benchmark(\n dir=recordingDir,\n params=None,\n name=case,\n paramSet=args.methodName,\n ))\n return benchmarks\n\nclass Dirs:\n results = None\n groundTruth = None\n out = None\n figures = None\n logs = None\n info = None\n\ndef collectMetrics(values, key):\n # Filter out non-existing values and Nones.\n return [v[key] for v in values if (key in v and not v[key] is None)]\n\ndef aggregateMetrics(metrics):\n def geometricMean(a):\n assert(a)\n return np.array(a).prod() ** (1.0 / len(a))\n if not metrics: return None\n\n metricSets = set()\n for metric in metrics:\n metricSets.update(metric.keys())\n\n result = {}\n for metricSetStr in metricSets:\n values = collectMetrics(metrics, metricSetStr)\n if not values:\n result[metricSetStr] = None\n continue\n\n if metricSetStr == \"relative\":\n result[\"relative\"] = {}\n for relativeMetric in values[0]:\n result[\"relative\"][relativeMetric] = geometricMean(collectMetrics(values, relativeMetric))\n elif isinstance(values[0], float):\n # Single numbers like for coverage and angular velocity metrics.\n result[metricSetStr] = np.mean(values)\n else:\n # Nested entries. Average within each category.\n result[metricSetStr] = {}\n for x in values[0]:\n result[metricSetStr][x] = np.mean(collectMetrics(values, x))\n return result\n\ndef benchmark(args, vioTrackingFn, setupFn=None, teardownFn=None):\n \"\"\"Run benchmark for a VIO algorithm using callbacks\n\n @param args arguments to use\n @param vioTrackingFn function that runs VIO on a single dataset. Should return True iff VIO did not produce errors\n @param setupFn function that is run before any of the individual sets\n @param teardownFn function that is run after all the individual sets\n @return True iff none of the VIO runs produced errors\n \"\"\"\n\n startTime = datetime.now().strftime(DATE_FORMAT)\n runId = args.runId if args.runId else startTime\n\n if args.skipBenchmark and not args.runId:\n raise Exception(\"-skipBenchmark requires -runId.\")\n\n def withMkdir(dir):\n pathlib.Path(dir).mkdir(parents=True, exist_ok=True)\n return dir\n\n results = withMkdir(os.path.abspath(args.output + \"/\" + runId))\n print(results)\n\n baselineMetrics = {}\n if args.baseline:\n with open(args.baseline) as baselineFile:\n baselineMetrics = json.loads(baselineFile.read())\n\n # TODO Is this class useless?\n dirs = Dirs()\n dirs.results = results\n dirs.groundTruth = withMkdir(results + \"/ground-truth\")\n dirs.out = withMkdir(results + \"/vio-output\")\n dirs.figures = withMkdir(results + \"/figures\")\n dirs.logs = withMkdir(results + \"/vio-logs\")\n dirs.info = withMkdir(results + \"/info\")\n dirs.metrics = withMkdir(results + \"/metrics\")\n\n if setupFn:\n setupFn(args, dirs.results)\n\n success = True\n if not args.skipBenchmark:\n if args.set:\n benchmarks = setupBenchmarkFromSetDescription(args, args.set)\n elif args.dataDir:\n benchmarks = setupBenchmarkFromFolder(args, args.dataDir)\n elif args.recordingDir:\n benchmarks = setupBenchmarkFromRecordingDir(args, args.recordingDir)\n else:\n print(\"You must select benchmark data using either `-set`, `-dataDir` or `-recordingDir`.\")\n return\n\n if len(benchmarks) == 0:\n print(\"No matching benchmarks found! Exiting\")\n return\n\n threadFunction = partial(benchmarkSingleDataset,\n dirs=dirs, vioTrackingFn=vioTrackingFn, args=args, baselineMetrics=baselineMetrics)\n\n print(\"---\")\n if args.threads == 1:\n for benchmark in benchmarks:\n if not threadFunction(benchmark):\n success = False\n else:\n workerCount = int(args.threads) if args.threads else multiprocessing.cpu_count()\n with concurrent.futures.ProcessPoolExecutor(max_workers=workerCount) as executor:\n for ret in executor.map(threadFunction, benchmarks):\n if not ret: success = False\n\n if teardownFn:\n teardownFn(args, dirs.results)\n\n endTime = datetime.now().strftime(DATE_FORMAT)\n\n metrics = {}\n for x in os.walk(results + \"/metrics\"):\n for caseMetricsJsonPath in x[2]:\n benchmarkMetrics = json.loads(open(os.path.join(results, \"metrics\", caseMetricsJsonPath)).read())\n caseName = caseMetricsJsonPath.rpartition(\".\")[0]\n assert(not caseName in metrics)\n metrics[caseName] = benchmarkMetrics\n ametrics = aggregateMetrics(list(metrics.values()))\n\n # Delete the relative numbers so it's easier to copy-paste entries from this file\n # to the baseline metrics file.\n for x in metrics:\n if \"relative\" in metrics[x]: del metrics[x][\"relative\"]\n metricsJsonPath = results + \"/metrics.json\"\n with open(metricsJsonPath, \"w\") as f:\n f.write(json.dumps(metrics, indent=4, separators=(',', ': ')))\n\n # Needed by plotting below.\n infoJsonPath = writeSharedInfoFile(args, dirs, startTime, endTime, ametrics)\n\n print(\"---\\nBenchmarks finished. Computing figures…\")\n startTime = time.time()\n makeAllPlots(results, args.excludePlots, args.debug, args.sampleIntervalForVelocity)\n # Print the elapsed time since the plotting has been quite slow in the past.\n print(\"… took {:.0f}s.\".format(time.time() - startTime))\n\n # Copy the aggregate figure of each metric to a shared folder for easier comparison.\n metricSets = args.metricSet.split(\",\")\n for metricSet in metricSets:\n src = getFigurePath(\"{}/figures\".format(results), metricSet)\n if not os.path.exists(src): continue\n dstDir = os.path.abspath(\"{}/figures/{}\".format(args.output, metricSet))\n pathlib.Path(dstDir).mkdir(parents=True, exist_ok=True)\n dst = \"{}/{}.png\".format(dstDir, runId)\n subprocess.run([\"cp\", src, dst])\n\n return success\n","repo_name":"SpectacularAI/benchmark","sub_path":"tools/benchmark.py","file_name":"benchmark.py","file_ext":"py","file_size_in_byte":23065,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"60"} +{"seq_id":"11893572929","text":"import sys\nsys.path.append(\"..\")\nimport torch\nimport config\nimport random\nfrom tqdm import tqdm\nfrom typing import List,Tuple,Dict,Union\nfrom pytorch_pretrained_bert import BertTokenizer\nfrom loguru import logger\ndef load_sub_vocab():\n\tsub_vocab = {}\n\twith open(config.ProjectConfiguration.bert_vocab, 'r', encoding=\"utf-8\") as fr:\n\t\tfor line in fr:\n\t\t\t_line = line.strip('\\n')\n\t\t\tif \"##\" in _line and sub_vocab.get(_line) is None:\n\t\t\t\tsub_vocab[_line] = 1\n\treturn sub_vocab\ndef load_bert_tokenizer() -> BertTokenizer:\n\ttokenizer = BertTokenizer.from_pretrained(config.ProjectConfiguration.bert_model_dir)\n\treturn tokenizer\n\ndef parseIOBlabel(labels : List[str]) -> List[Dict]:\n\n\toutput = []\n\tlabels = list(map(lambda x :x.replace(\"_\",\"-\"),labels))\n\tfor i in range(len(labels)):\n\n\t\tif labels[i].startswith(\"B-\"):\n\t\t\tspan_start = i\n\t\t\tlabel = labels[i][2:]\n\t\t\tspan_end = i\n\t\t\tfor j in range(span_start + 1, len(labels)):\n\t\t\t\tif labels[j] == \"I-\" + label:\n\t\t\t\t\tspan_end = j\n\t\t\t\tif labels[j] == labels[i]:\n\t\t\t\t\tbreak\n\t\t\toutput.append({label: [span_start, span_end]})\n\n\treturn output\nclass InputExample(object):\n\tdef __init__(self, guid, text_a, text_b=None, label=None):\n\t\t\"\"\"创建一个输入实例\n\t\tArgs:\n\t\t\tguid: 每个example拥有唯一的id\n\t\t\ttext_a: 第一个句子的原始文本,一般对于文本分类来说,只需要text_a\n\t\t\ttext_b: 第二个句子的原始文本,在句子对的任务中才有,分类问题中为None\n\t\t\tlabel: example对应的标签,对于训练集和验证集应非None,测试集为None\n\t\t\"\"\"\n\t\tself.guid = guid\n\t\tself.text_a = text_a\n\t\tself.text_b = text_b\n\t\tself.label = label\n\nclass InputFeature(object):\n\tdef __init__(self, input_ids, input_mask, segment_ids, label_id, output_mask):\n\t\tself.input_ids = input_ids\n\t\tself.input_mask = input_mask\n\t\tself.segment_ids = segment_ids\n\t\tself.label_id = label_id\n\t\tself.output_mask = output_mask\n\nclass DataProcessor(object):\n\n\t\"\"\"数据预处理的基类,自定义的MyPro继承该类\"\"\"\n\tdef get_train_examples(self):\n\t\t\"\"\"读取训练集 Gets a collection of `InputExample`s for the train set.\"\"\"\n\t\traise NotImplementedError()\n\n\tdef get_dev_examples(self):\n\t\t\"\"\"读取验证集 Gets a collection of `InputExample`s for the dev set.\"\"\"\n\t\traise NotImplementedError()\n\n\tdef get_labels(self):\n\t\t\"\"\"读取标签 Gets the list of labels for this data set.\"\"\"\n\t\traise NotImplementedError()\n\n\t@classmethod\n\tdef _read_json(cls, input_file):\n\t\twith open(input_file, \"r\", encoding='utf-8') as fr:\n\t\t\tlines = []\n\t\t\tfor line in fr:\n\t\t\t\t_line = line.strip('\\n')\n\t\t\t\tlines.append(_line)\n\t\t\treturn lines\n\tdef __iter__(self):\n\t\treturn self\n\ndef tensor2list(cudatensor : torch.tensor) -> List:\n\treturn list(cudatensor.cpu().numpy())\nclass text2TokenClassfierDataProcessor(DataProcessor):\n\n\tdef __init__(self,lines:Union[List[str],List[Tuple]]):\n\t\tself.lines = lines\n\t\tself.iter_now = 0\n\tdef _create_example(self,lines:Union[List[str],List[Tuple]],set_type) ->List[InputExample]:\n\t\texamples = []\n\t\tfor i, line in enumerate(lines):\n\t\t\tif line == \"\":\n\t\t\t\tcontinue\n\t\t\tguid = \"%s-%d\" % (set_type, i)\n\t\t\tassert type(line) in [str,tuple]\n\t\t\tif type(line) == str:\n\t\t\t\texample = InputExample(guid=guid, text_a=line)\n\t\t\telse:\n\t\t\t\texample = InputExample(guid=guid, text_a=line[0],text_b=line[1])\n\t\t\texamples.append(example)\n\t\treturn examples\n\n\tdef get_dev_examples(self) ->List[InputExample]:\n\t\texamples = self._create_example(self.lines, \"test\")\n\t\treturn examples\n\n\tdef get_labels(self):\n\t\treturn None\n\n\tdef __iter__(self):\n\t\treturn self\n\tdef __next__(self) -> Tuple[int,InputExample]:\n\t\tif self.iter_now < len(self.lines):\n\t\t\texample = self._create_example([self.lines[self.iter_now]],\"test\")[0]\n\t\t\tself.iter_now += 1\n\t\t\treturn self.iter_now - 1,example\n\t\telse:\n\t\t\traise StopIteration\ndef convert_tokens_to_features(\n\t\ttokens_a,labels,max_seq_length,tokenizer,label_list,sub_vocab,segment_id = 0)\\\n\t\t-> Tuple[List[str],List[int],List[int],List[int],List[int],List[int]]:\n\n\tif labels == None:\n\t\tlabels = \" \".join([\"-1\"] * len(tokens_a))\n\t# ----------------对text_a按max_seq1_length切分-----------------\n\n\tlabels = labels.split()\n\tassert len(tokens_a) == len(labels)\n\tif len(tokens_a) == 0 or len(labels) == 0:\n\t\treturn 0\n\tif len(tokens_a) > max_seq_length - 2:\n\t\ttokens_a = tokens_a[:(max_seq_length - 2)]\n\t\tlabels = labels[:(max_seq_length - 2)]\n\n\t# ----------------token to Inputids--------------\n\t## 句子首尾加入标示符\n\ttokens = [\"[CLS]\"] + tokens_a + [\"[SEP]\"]\n\tsegment_ids = [segment_id] * len(tokens)\n\t## 词转换成数字\n\tinput_ids = tokenizer.convert_tokens_to_ids(tokens)\n\tinput_mask = [1] * len(input_ids)\n\toutput_mask = [0 if sub_vocab.get(t) is not None else 1 for t in tokens_a]\n\toutput_mask = [0] + output_mask + [0]\n\n\t# ---------------训练时处理target----------------\n\t## Notes: label_id中不包括[CLS]和[SEP]\n\tif label_list != None:\n\t\tlabel_map = {label: i for i, label in enumerate(label_list)}\n\t\tlabel_id = [label_map[l] for l in labels]\n\t\tlabel_id = [-1] + label_id + [-1]\n\telse:\n\t\tlabel_id = [-1] * len(input_ids)\n\n\tlabel_padding = [-1] * (max_seq_length - len(label_id))\n\n\t# ----------------训练时加上padding-----------------\n\tpadding = [0] * (max_seq_length - len(input_ids))\n\tinput_ids += padding\n\tinput_mask += padding\n\tsegment_ids += [segment_id] * (max_seq_length - len(segment_ids))\n\toutput_mask += padding\n\tlabel_id += label_padding\n\n\tassert len(input_ids) == max_seq_length\n\tassert len(input_mask) == max_seq_length\n\tassert len(segment_ids) == max_seq_length\n\tassert len(output_mask) == max_seq_length\n\n\treturn tokens,label_id,input_ids,input_mask,segment_ids,output_mask\ndef convert_examples_to_features(\n\t\texamples : List[InputExample], label_list, max_seq_length, tokenizer,show_example,max_seq2_length = 10)\\\n\t\t-> List[InputFeature]:\n\n\t'''\n\t:param examples:\n\t:param label_list: 如果没有对应的序列标签,那么设置label_list = None\n\t:param max_seq_length:\n\t:param tokenizer:\n\t:return:\n\t'''\n\t# 标签转换为数字\n\tsub_vocab = load_sub_vocab()\n\tfeatures = []\n\tfor ex_index, example in enumerate(examples):\n\t\ttokens_a = tokenizer.tokenize(example.text_a)\n\t\tlabels = example.label\n\t\tvalue = convert_tokens_to_features(\n\t\t\ttokens_a = tokens_a,\n\t\t\tlabels = labels,\n\t\t\tmax_seq_length = max_seq_length,\n\t\t\ttokenizer = tokenizer,\n\t\t\tlabel_list = label_list,\n\t\t\tsub_vocab = sub_vocab,\n\t\t\tsegment_id =0\n\t\t)\n\t\tif value != 0:\n\t\t\ttokens, label_id, input_ids, input_mask, segment_ids, output_mask = value\n\t\telse:\n\t\t\tcontinue\n\n\t\tif example.text_b != None:\n\t\t\ttokens_b = tokenizer.tokenize(example.text_b)\n\t\t\tvalue = convert_tokens_to_features(\n\t\t\t\ttokens_a=tokens_b,\n\t\t\t\tlabels=None,\n\t\t\t\tmax_seq_length=max_seq2_length,\n\t\t\t\ttokenizer=tokenizer,\n\t\t\t\tlabel_list=None,\n\t\t\t\tsub_vocab=sub_vocab,\n\t\t\t\tsegment_id=1\n\t\t\t)\n\t\t\tif value != 0:\n\t\t\t\ttokens_2, label_id_2, input_ids_2, input_mask_2, segment_ids_2, output_mask_2 = value\n\t\t\telse:\n\t\t\t\tcontinue\n\t\t\ttokens += tokens_2[1:]\n\t\t\tlabel_id += label_id_2[1:]\n\t\t\tinput_ids += input_ids_2[1:]\n\t\t\tinput_mask += input_mask_2[1:]\n\t\t\tsegment_ids += segment_ids_2[1:]\n\t\t\toutput_mask += output_mask_2[1:]\n\t\t# ----------------处理后结果-------------------------\n\t\t# for example, in the case of max_seq_length=10:\n\t\t# raw_data: 春 秋 忽 代 谢le\n\t\t# token: [CLS] 春 秋 忽 代 谢 ##le [SEP]\n\t\t# input_ids: 101 2 12 13 16 14 15 102 0 0 0\n\t\t# input_mask: 1 1 1 1 1 1 1 1 0 0 0\n\t\t# label_id: T T O O O\n\t\t# output_mask: 0 1 1 1 1 1 0 0 0 0 0\n\t\t# --------------看结果是否合理------------------------\n\t\tif ex_index < 1 and show_example :\n\t\t\tlogger.info(\"-----------------Example-----------------\")\n\t\t\tlogger.info(\"guid: %s\" % (example.guid))\n\t\t\tlogger.info(\"tokens: %s\" % \" \".join([str(x) for x in tokens]) + \"len: %d\"%len(tokens))\n\t\t\tlogger.info(\"input_ids: %s\" % \" \".join([str(x) for x in input_ids]))\n\t\t\tlogger.info(\"input_mask: %s\" % \" \".join([str(x) for x in input_mask]))\n\t\t\tlogger.info(\"segment ids: %s \" % \" \".join([str(x) for x in segment_ids]))\n\t\t\tlogger.info(\"label_ids : %s \" % \" \".join([str(x) for x in label_id]))\n\t\t\tlogger.info(\"output_mask: %s \" % \" \".join([str(x) for x in output_mask]))\n\t\t# ----------------------------------------------------\n\n\t\tfeature = InputFeature(input_ids=input_ids,\n\t\t\t\t\t\t\t input_mask=input_mask,\n\t\t\t\t\t\t\t segment_ids=segment_ids,\n\t\t\t\t\t\t\t label_id=label_id,\n\t\t\t\t\t\t\t output_mask=output_mask)\n\t\tfeatures.append(feature)\n\n\treturn features\ndef train_val_split(X, y, valid_size=0.2, random_state=2018, shuffle=True)-> Tuple[List,List]:\n\t\"\"\"\n\t训练集验证集分割\n\t:param X: sentences\n\t:param y: labels\n\t:param random_state: 随机种子\n\t\"\"\"\n\tlogger.info('Train val split')\n\n\tdata = []\n\tfor data_x, data_y in tqdm(zip(X, y), desc='Merge'):\n\t\tdata.append((data_x, data_y))\n\tdel X, y\n\n\tN = len(data)\n\ttest_size = int(N * valid_size)\n\n\tif shuffle:\n\t\trandom.seed(random_state)\n\t\trandom.shuffle(data)\n\n\tvalid = data[:test_size]\n\ttrain = data[test_size:]\n\n\treturn train, valid\ndef sent2char(line):\n\t\"\"\"\n\t句子处理成单词\n\t:param line: 原始行\n\t:return: 单词, 标签\n\t\"\"\"\n\tres = line.strip('\\n').split()\n\treturn res","repo_name":"Hyacinth-YX/NLPCrawler-Analyze","sub_path":"utils/dataprocessUtils.py","file_name":"dataprocessUtils.py","file_ext":"py","file_size_in_byte":9105,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"60"} +{"seq_id":"28402893878","text":"kernels = [\n r\"\"\"\n#include \n#include \n#include \n#include \n__host int32_t v0;\n__host int32_t v1;\nint32_t main(){\n int32_t v2;\n v2 = v0 + v1;\n return 0l;\n}\n\"\"\",\n r\"\"\"\n#include \n#include \n#include \n#include \n__host uint64_t v0;\n__host uint64_t v1;\nint32_t main(){\n uint64_t v2;\n v2 = v0 + v1;\n return 0l;\n}\n\"\"\",\n r\"\"\"\n#include \n#include \n#include \n#include \n__host float v0;\n__host float v1;\nint32_t main(){\n float v2;\n v2 = v0 + v1;\n return 0l;\n}\n\"\"\",\n]\nfrom dpu import DpuSet\nimport numpy as np\nfrom dataclasses import dataclass\nfrom typing import NamedTuple, Union, Callable, Tuple\ni8 = i16 = i32 = i64 = u8 = u16 = u32 = u64 = int; f32 = f64 = float; char = string = str\n\ndef main():\n v0 = 2\n del v0\n v1 = 1\n del v1\n v2 = 0\n del v2\n v3 = 2\n del v3\n v4 = 5\n del v4\n v5 = 1\n del v5\n v6 = 2.5\n del v6\n v7 = 4.4\n del v7\n v8 = 2\n del v8\n return \n\nif __name__ == '__main__': print(main())\n","repo_name":"mrakgr/The-Spiral-Language","sub_path":"Spiral Compilation Tests/upmem_tests/test3/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1094,"program_lang":"python","lang":"en","doc_type":"code","stars":877,"dataset":"github-code","pt":"60"} +{"seq_id":"30364713563","text":"\"\"\"options table constraint\n\nRevision ID: b531c6dadfcf\nRevises: 8af57a53dc4e\nCreate Date: 2019-11-15 17:22:40.911136\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'b531c6dadfcf'\ndown_revision = '8af57a53dc4e'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_table('chat')\n op.drop_index('ix_option_chat_key', table_name='chat_option')\n op.drop_table('chat_option')\n op.drop_index('ix_chat_hash', table_name='photo')\n op.drop_index('ix_user_hash_date', table_name='photo')\n op.drop_table('photo')\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('photo',\n sa.Column('id', sa.INTEGER(), nullable=False),\n sa.Column('file_hash', sa.VARCHAR(length=240), nullable=False),\n sa.Column('chat_id', sa.INTEGER(), nullable=False),\n sa.Column('user_id', sa.INTEGER(), nullable=False),\n sa.Column('msg_date', sa.DATETIME(), nullable=False),\n sa.Column('msg_id', sa.INTEGER(), nullable=False),\n sa.Column('yd_path', sa.VARCHAR(length=240), nullable=False),\n sa.ForeignKeyConstraint(['chat_id'], ['chat.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_index('ix_user_hash_date', 'photo', ['user_id', 'file_hash', 'msg_date'], unique=False)\n op.create_index('ix_chat_hash', 'photo', ['chat_id', 'file_hash'], unique=False)\n op.create_table('chat_option',\n sa.Column('id', sa.INTEGER(), nullable=False),\n sa.Column('chat_id', sa.INTEGER(), nullable=True),\n sa.Column('key', sa.VARCHAR(length=50), nullable=False),\n sa.Column('value', sa.VARCHAR(length=240), nullable=True),\n sa.ForeignKeyConstraint(['chat_id'], ['chat.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_index('ix_option_chat_key', 'chat_option', ['chat_id', 'key'], unique=False)\n op.create_table('chat',\n sa.Column('id', sa.INTEGER(), nullable=False),\n sa.Column('name', sa.VARCHAR(length=240), nullable=False),\n sa.Column('local_folder', sa.VARCHAR(length=240), nullable=False),\n sa.Column('yd_folder', sa.VARCHAR(length=240), nullable=False),\n sa.PrimaryKeyConstraint('id')\n )\n # ### end Alembic commands ###\n","repo_name":"ShiawasenaHoshi/telegram_photo_saver_bot","sub_path":"migrations/versions/b531c6dadfcf_options_table_constraint.py","file_name":"b531c6dadfcf_options_table_constraint.py","file_ext":"py","file_size_in_byte":2308,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"60"} +{"seq_id":"10708547226","text":"import matplotlib\nmatplotlib.use(\"agg\")\nimport torch.backends.cudnn as cudnn\nimport os\nif \"CUDNN_DETERMINISTIC\" in os.environ and os.environ[\"CUDNN_DETERMINISTIC\"] not in (0, False, \"false\", \"FALSE\", \"False\"):\n cudnn.benchmark = False\n cudnn.deterministic = True\nelse:\n cudnn.benchmark = True\n cudnn.deterministic = False\nimport atexit\nimport numpy as np\nimport torch\nfrom trixi.util import ResultLogDict\nfrom trixi.experiment import PytorchExperiment\nfrom trixi.logger import TelegramMessageLogger\nfrom batchgenerators.transforms import Compose\n\nfrom probunet.util import check_attributes, set_seeds\n\n\n\nclass TumorGrowthExperiment(PytorchExperiment):\n\n def __init__(self, *args, use_telegram=False, **kwargs):\n\n super().__init__(*args, **kwargs)\n self.use_telegram = use_telegram\n\n def setup(self):\n\n self.cleanup()\n\n set_seeds(self.config.seed, \"cuda\" in self.config.device)\n\n if self.use_telegram:\n self.setup_telegram()\n self.setup_subjects()\n self.setup_data()\n self.setup_augmentation()\n self.setup_model()\n self.setup_loss_and_eval()\n\n self.config.epoch_str_template = \"{:0\" + str(len(str(self.config.n_epochs))) + \"d}\"\n self.clog.show_text(self.model.__repr__(), \"Model\")\n\n def cleanup(self):\n\n # close everything that could have open files\n self.augmenter_train = None\n self.augmenter_val = None\n self.augmenter_test = None\n self.generator_train = None\n self.generator_val = None\n self.generator_test = None\n self.data_train = None\n self.data_val = None\n self.data_test = None\n self.results.close()\n\n def setup_telegram(self):\n\n self.tlogger = TelegramMessageLogger(token=\"123:abc\", chat_id=\"123\")\n info_str = \"{} started\\n\".format(self.exp_name)\n info_str += \"-\" * 20 + \"\\n\"\n info_str += self.config.description\n info_str += \"-\" * 20 + \"\\n\"\n self.tlogger.show_text(info_str)\n\n def exit_message():\n info_str = \"{} ended\\n\".format(self.exp_name)\n info_str += \"-\" * 20 + \"\\n\"\n info_str += \"Status {}, {}/{} epochs\\n\".format(self._exp_state, self._epoch_idx + 1, self.n_epochs)\n info_str += \"-\" * 20 + \"\\n\"\n info_str += self.config.description\n info_str += \"-\" * 20 + \"\\n\"\n self.tlogger.show_text(info_str)\n\n atexit.register(exit_message)\n\n def setup_subjects(self):\n\n c = self.config\n\n if c.data_dir is not None:\n c.data_module.data_dir = c.data_dir\n\n if not check_attributes(c, [\"subjects_train\", \"subjects_val\", \"subjects_test\"]):\n split = c.data_module.split()\n c.subjects_val = split[c.split_val]\n c.subjects_test = split[c.split_test]\n c.subjects_train = []\n for i in range(len(split)):\n if i not in (c.split_val, c.split_test) or c.train_on_all:\n c.subjects_train = c.subjects_train + split[i]\n c.subjects_train = sorted(c.subjects_train)\n\n if c.debug:\n c.subjects_train = c.subjects_train[:10]\n c.subjects_val = c.subjects_val[:5]\n c.subjects_test = c.subjects_test[:5]\n\n def setup_data(self):\n\n c = self.config\n\n self.data_train = c.data_module.load(c.mmap_mode, subjects=c.subjects_train, npz=c.npz)\n self.data_val = c.data_module.load(c.mmap_mode, subjects=c.subjects_val, npz=c.npz)\n self.data_test = c.data_module.load(c.mmap_mode, subjects=c.subjects_test, npz=c.npz)\n\n self.generator_train = c.generator_train(\n self.data_train, c.batch_size, c.input_timesteps + 1,\n number_of_threads_in_multithreaded=c.augmenter_train_kwargs.num_processes)\n self.generator_val = c.generator_val(\n self.data_val, c.batch_size_val, c.input_timesteps + 1,\n number_of_threads_in_multithreaded=c.augmenter_val_kwargs.num_processes)\n self.generator_test = c.generator_val(\n self.data_test, c.batch_size_val, c.input_timesteps + 1,\n number_of_threads_in_multithreaded=c.augmenter_val_kwargs.num_processes)\n\n def setup_augmentation(self):\n\n c = self.config\n\n transforms_train = []\n for t in sorted(c.transforms_train.keys()):\n if c.transforms_train[t][\"active\"]:\n cls = c.transforms_train[t][\"type\"]\n kwargs = c.transforms_train[t][\"kwargs\"]\n transforms_train.append(cls(**kwargs))\n self.augmenter_train = c.augmenter_train(self.generator_train,\n Compose(transforms_train),\n **c.augmenter_train_kwargs)\n\n transforms_val = []\n for t in sorted(c.transforms_val.keys()):\n if c.transforms_val[t][\"active\"]:\n cls = c.transforms_val[t][\"type\"]\n kwargs = c.transforms_val[t][\"kwargs\"]\n transforms_val.append(cls(**kwargs))\n self.augmenter_val = c.augmenter_val(self.generator_val,\n Compose(transforms_val),\n **c.augmenter_val_kwargs)\n self.augmenter_test = c.augmenter_val(self.generator_test,\n Compose(transforms_val),\n **c.augmenter_val_kwargs)\n\n def setup_model(self):\n\n c = self.config\n\n # model\n self.model = c.model(**c.model_kwargs)\n if c.model_init_weights_args is not None:\n if isinstance(c.model_init_weights_args, dict):\n for key, val in c.model_init_weights_args.items():\n try:\n self.model._modules[key].init_weights(*val)\n except Exception as e:\n print(\"Tried to initialize {} with {}, but got the following error:\".format(key, val))\n print(repr(e))\n elif isinstance(c.model_init_weights_args, (list, tuple)):\n self.model.init_weights(*c.model_init_weights_args)\n else:\n raise TypeError(\"model_init_weights_args must be dict, list or tuple, but found {}.\".format(type(c.model_init_weights_args)))\n if c.model_init_bias_args is not None:\n if isinstance(c.model_init_bias_args, dict):\n for key, val in c.model_init_bias_args.items():\n try:\n self.model._modules[key].init_bias(*val)\n except Exception as e:\n print(\"Tried to initialize {} with {}, but got the following error:\".format(key, val))\n print(repr(e))\n elif isinstance(c.model_init_bias_args, (list, tuple)):\n self.model.init_bias(*c.model_init_bias_args)\n else:\n raise TypeError(\"model_init_bias_args must be dict, list or tuple, but found {}.\".format(type(c.model_init_bias_args)))\n\n # optimizer\n self.optimizer = c.optimizer(self.model.parameters(), **c.optimizer_kwargs)\n self.scheduler = c.scheduler(self.optimizer, **c.scheduler_kwargs)\n\n def setup_loss_and_eval(self):\n\n raise NotImplementedError\n\n def _setup_internal(self):\n\n super()._setup_internal()\n self.results.close()\n mode = \"w\" if os.stat(os.path.join(self.elog.result_dir, \"results-log.json\")).st_size <= 4 else \"a\"\n self.results = ResultLogDict(\"results-log.json\", base_dir=self.elog.result_dir, mode=mode, running_mean_length=self.config.show_every)\n self.elog.save_config(self.config, \"config\") # default PytorchExperiment only saves self._config_raw\n\n def prepare(self):\n\n for name, model in self.get_pytorch_modules().items():\n model.to(self.config.device)\n\n def validate_make_default_info(self):\n\n info = {}\n info[\"dims\"] = [\"Subject and Timestep\", \"Label\", \"Metric\"]\n info[\"coords\"] = {\"Subject and Timestep\": []}\n info[\"coords\"][\"Label\"] = [self.evaluator.label_names[l] for l in self.evaluator.label_values]\n info[\"coords\"][\"Metric\"] = self.evaluator.metrics\n\n return info\n\n def validate_score(self, summary, epoch):\n\n segmentation = torch.argmax(summary[\"prediction\"], 1, keepdim=False)[0, ...].cpu().numpy()\n reference = summary[\"seg\"][0, -1, ...]\n if torch.is_tensor(reference):\n reference = reference.cpu().numpy()\n\n self.evaluator.set_reference(reference)\n self.evaluator.set_test(segmentation)\n self.evaluator.evaluate()\n\n return self.evaluator.to_array()\n\n def validate_log(self, summary, epoch):\n\n epoch_str = self.config.epoch_str_template.format(epoch)\n\n if self.evaluator.nan_for_nonexisting:\n validation_scores_mean = np.nanmean(summary[\"validation_scores\"], 0)\n else:\n validation_scores_mean = np.mean(summary[\"validation_scores\"], 0)\n\n self.elog.save_numpy_data(summary[\"validation_scores\"], \"validation/{}.npy\".format(epoch_str))\n self.elog.save_dict(summary[\"validation_info\"], \"validation/{}.json\".format(epoch_str))\n self.elog.show_text(\"{}/{}: {}\".format(epoch, self.config.n_epochs, summary[\"validation_time\"]), name=\"Validation Time\")\n\n for l, label in enumerate(self.evaluator.label_values):\n label_name = self.evaluator.label_names[label].lower().replace(\" \", \"_\")\n for metric in self.config.validate_metrics:\n m = self.evaluator.metrics.index(metric)\n output_name = \"validation_{}_{}\".format(label_name, metric)\n self.add_result(float(validation_scores_mean[l][m]), output_name, epoch, \"Scores\")\n\n def _end_epoch_internal(self, epoch):\n\n self.save_results()\n if (epoch+1) % self.config.backup_every == 0:\n self.save_temp_checkpoint()\n","repo_name":"jenspetersen/probabilistic-unet","sub_path":"probunet/experiment/tumorgrowthexperiment.py","file_name":"tumorgrowthexperiment.py","file_ext":"py","file_size_in_byte":10038,"program_lang":"python","lang":"en","doc_type":"code","stars":39,"dataset":"github-code","pt":"60"} +{"seq_id":"13327934817","text":"import multiprocessing\nimport time\n\nNULL_CHAR = chr(0x00)\n\nclass KeyboardProcess:\n keyboard = {\n \"a\": 0x04,\n \"esc\": 0x29\n }\n service = None\n \n def press_key(self, id):\n self.write_report(NULL_CHAR*2+chr(id)+NULL_CHAR*5)\n # Release keys\n self.write_report(NULL_CHAR*8)\n \n def write_report(self, report):\n with open('/dev/hidg0', 'rb+') as fd:\n fd.write(report.encode())\n \n def pressEscForever(self, key, timespan):\n while(True):\n self.press_key(self.keyboard[key])\n time.sleep(timespan)\n \n def stop(self):\n if self.service is not None:\n self.service.terminate()\n def start(self, key=\"esc\", timespan=300):\n self.stop()\n self.service = multiprocessing.Process(name='fake-keyboard-service', target=self.pressEscForever, args=(key,timespan,))\n self.service.start()\n def status(self):\n if self.service is None:\n return \"STOP\"\n return \"RUN\" if self.service.is_alive() else \"STOP\"\n","repo_name":"simon020286/fake-keyboard","sub_path":"keyboard.py","file_name":"keyboard.py","file_ext":"py","file_size_in_byte":1024,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"60"}