query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
Convert a dataframe of correlation data into a matrix
def make_correlation_matrices(dataframe): # Group the data by residue then use a pivot table-like function # to create correlation matrices if u'residue' in dataframe.index.names: correlation_group = dataframe.reset_index().groupby(u'residue') else: correlation_group = dataframe.groupby(u'residue') correlation_matrix = correlation_group.apply(lambda x: x.pivot(index=u'model_free_name_1', columns=u'model_free_name_2', values=u'covariance')) correlation_matrix = DataFrame(correlation_matrix) # Pandas groupby doesn't preserve the print formatter correlation_matrix = correlation_matrix.__finalize__(dataframe, 'copy') # Append columns for each of the parameters in 'model_free_name_2' new_col_names = dataframe.model_free_name_2.unique() for col in new_col_names: correlation_matrix._print_format[col] = correlation_matrix._print_format['covariance'] return correlation_matrix
[ "def create_correlation_matrix(df, columns):\r\n correlations = df.corr()\r\n fig = plt.figure()\r\n ax = fig.add_subplot(111)\r\n cax = ax.matshow(correlations, vmin=-1, vmax=1)\r\n fig.colorbar(cax)\r\n ticks = np.arange(0,9,1)\r\n ax.set_xticks(ticks)\r\n ax.set_yticks(ticks)\r\n ax.set_xticklabels(columns, rotation = 90)\r\n ax.set_yticklabels(columns)\r\n plt.show()\r\n return", "def _compute_corr_matrix(spark_df, corr_method='pearson'):\n numeric_columns = spark_df.dtypes\n if (len(numeric_columns) == 0):\n raise AssertionError(\"The provided spark dataframe does not contain any numeric columns. \" \\\n \"Cannot compute feature correlation on categorical columns. The numeric datatypes are: {}\" \\\n \" and the number of numeric datatypes in the dataframe is: {} ({})\".format(\n constants.SPARK_CONFIG.SPARK_NUMERIC_TYPES, len(spark_df.dtypes), spark_df.dtypes))\n if (len(numeric_columns) == 1):\n raise AssertionError(\"The provided spark dataframe only contains one numeric column. \" \\\n \"Cannot compute feature correlation on just one column. The numeric datatypes are: {}\" \\\n \"and the number of numeric datatypes in the dataframe is: {} ({})\".format(\n constants.SPARK_CONFIG.SPARK_NUMERIC_TYPES, len(spark_df.dtypes), spark_df.dtypes))\n if (len(numeric_columns) > constants.FEATURE_STORE.MAX_CORRELATION_MATRIX_COLUMNS):\n raise AssertionError(\n \"The provided dataframe contains {} columns, feature correlation can only be computed for dataframes with < {} columns due to scalability reasons (number of correlatons grows quadratically with the number of columns)\".format(\n len(numeric_columns), constants.FEATURE_STORE.MAX_CORRELATION_MATRIX_COLUMNS))\n spark_df_rdd = spark_df.rdd.map(lambda row: row[0:])\n corr_mat = Statistics.corr(spark_df_rdd, method=corr_method)\n pd_df_corr_mat = pd.DataFrame(corr_mat, columns=spark_df.columns, index=spark_df.columns)\n return pd_df_corr_mat", "def dataframe_to_matrix(df):\n #1) add column of ones to dataframe\n df.insert(0, '1', 1)\n \n # Extracting all features (x1,x2,...,xD)\n X_train = df.iloc[:,:-1]\n \n # Convert DataFrame to array\n X_matrix_train = X_train.values\n \n # Extract 'y' column\n Y_train = df.iloc[:,-1:]\n \n # Convert DataFrame to array\n Y_matrix_train = Y_train.values\n \n return(X_matrix_train, Y_matrix_train)", "def _get_correlation_matrix(self, column_name):\n if column_name not in ['Score', 'Real Correlation', 'Synthetic Correlation']:\n raise ValueError(f\"Invalid column name for _get_correlation_matrix : '{column_name}'\")\n\n table = self._details.dropna(subset=[column_name])\n names = list(pd.concat([table['Column 1'], table['Column 2']]).unique())\n heatmap_df = pd.DataFrame(index=names, columns=names)\n\n for idx_1, column_name_1 in enumerate(names):\n for column_name_2 in names[idx_1:]:\n if column_name_1 == column_name_2:\n heatmap_df.loc[column_name_1, column_name_2] = 1\n continue\n\n # check wether the combination (Colunm 1, Column 2) or (Column 2, Column 1)\n # is in the table\n col_1_loc = (table['Column 1'] == column_name_1)\n col_2_loc = (table['Column 2'] == column_name_2)\n if table.loc[col_1_loc & col_2_loc].empty:\n col_1_loc = (table['Column 1'] == column_name_2)\n col_2_loc = (table['Column 2'] == column_name_1)\n\n if not table.loc[col_1_loc & col_2_loc].empty:\n score = table.loc[col_1_loc & col_2_loc][column_name].array[0]\n heatmap_df.loc[column_name_1, column_name_2] = score\n heatmap_df.loc[column_name_2, column_name_1] = score\n\n heatmap_df = heatmap_df.astype(float)\n\n return heatmap_df.round(3)", "def cat_correlation_heatmap(df):\n cat_columns = df.select_dtypes(exclude=[\"number\"]).columns\n subset = df[cat_columns]\n size = len(cat_columns)\n corr_vals = np.zeros((size, size))\n for ind1, col1 in enumerate(cat_columns):\n for ind2, col2 in enumerate(cat_columns):\n corr = cramers_v(df[col1], df[col2])\n corr_vals[ind1][ind2] = corr\n return corr_vals, cat_columns", "def get_correlation_matrix(symbols_list):\r\n df = pd.read_csv('https://raw.githubusercontent.com/haobruce/SysTrade/master/SysTrade_CorrelationMatrix.csv')\r\n df.set_index('Symbol', inplace=True)\r\n df = df.loc[symbols_list][symbols_list]\r\n return df", "def corrMatrix(df, data_title = \"\", excel_export = \"no\"):\n \n joining = pd.concat([df, coil_data], axis =1)\n corrMatrix = joining.corr()\n \n plt.matshow(corrMatrix)\n plt.show()\n \n if excel_export == \"yes\":\n corrMatrix.to_excel(str(data_title)+\".xlsx\")\n \n return corrMatrix", "def feature_matrix(self):\n return np.array([entry.data[\"correlations\"] for entry in self._entries])", "def _get_con_df(raw_mat, roi_names):\n # sanity check if matrix is symmetrical\n assert np.allclose(raw_mat, raw_mat.T), \"matrix not symmetrical\"\n\n np.fill_diagonal(raw_mat, 0)\n con_df = pd.DataFrame(raw_mat, index=roi_names, columns=roi_names)\n return con_df", "def corr_matrix(X, y):\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)\n labels = load_breast_cancer().feature_names\n df = pd.DataFrame(data=X_train)\n sns.set(font_scale=0.5)\n sns.heatmap(\n df.corr().abs(),\n annot=True,\n fmt=\"1.1f\",\n xticklabels=labels,\n yticklabels=labels,\n cmap=\"Blues\",\n )\n plt.tight_layout()\n plt.show()", "def correlation_between_columns(self, df):\n try:\n lg.info('correlation_between_columns')\n return df.corr()\n except Excepton as e:\n lg.exception(str(e))", "def show_correlation_matrix(self, columns):\n data = {}\n for column in columns:\n data[self.header[column]] = self.columns[column]\n\n df = pd.DataFrame(data)\n\n corr = df.corr()\n corr.style.background_gradient(cmap='coolwarm')\n\n sn.heatmap(corr, annot=True)\n plt.show()", "def get_full_matrix(correlations):\n n = correlations.shape[1]\n matrix = np.zeros((n,n), dtype=np.uint8)\n for i in range(n):\n for j in range(correlations.shape[0]):\n if correlations[j,i] == 1:\n col = i+j+1\n if col < n and col >= 0:\n matrix[i,col] = 1\n matrix[col,i] = 1\n return matrix", "def convert_to_numpy_array(df, columns=None):\n return df.as_matrix(columns)", "def dataframe_to_ndarray():\n df = pd.DataFrame(operations.get_mixed_matrix())\n print(type(df)) # <class 'pandas.core.frame.DataFrame'>\n print(df)\n ary = df.to_numpy()\n print(type(ary)) # <class 'numpy.ndarray'>\n print(ary)\n print(ary.shape) # (10, 10)", "def correlation_data_raw(self):\n df = self.features.data()\n raw_corr = df.corr(method=\"pearson\")\n return raw_corr", "def calculate_cov_matrix(var_1, var_2, corr_coef):\n\n # Calculate the covariance from the variances and correlation\n cov = corr_coef * np.sqrt(var_1 * var_2)\n\n cov_matrix = np.array([[var_1, cov], [cov, var_2]])\n\n return cov_matrix", "def get_distance_matrix(self, df):\n\n dist = sklearn.neighbors.DistanceMetric.get_metric('jaccard')\n distance_matrix = dist.pairwise(df.iloc[:,:].to_numpy())\n print(f'Distance matrix : {distance_matrix}')\n print(f'{len(distance_matrix)}, {len(distance_matrix[0])}')\n\n distance_df = pd.DataFrame(distance_matrix, index=df.index, columns=df.index)\n\n return distance_df", "def covariance_to_correlation( covarianceMatrix, data ):\n diag = numpy.sqrt( matrix.diagonal() )\n corr = matrix / diag / diag[:,numpy.newaxis]\n # now fix diagonal + remove any NaN (from div/0):\n corr[ [range(len(corr)),range(len(corr))] ] = 1.0 # must be exactly 1\n corr[ numpy.isnan(corr) ] = 0\n # scale by 1000 if desired\n return corr" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculate wave solution using 16th order finite difference
def solve_wave_FD16(U,Up,h,c,ncpml,b,psi,phi): ny , nx = U.shape for i in range(8,ny-8): for j in range(8,nx-8): Up[i,j] = 2.0*U[i,j] - Up[i,j] + c[i-8,j-8]* \ ((-735*U[i-8,j]+15360*U[i-7,j]-156800*U[i-6,j]+1053696*U[i-5,j]-5350800*U[i-4,j]+22830080*U[i-3,j]-94174080*U[i-2,j]+538137600*U[i-1,j]-924708642*U[i+0,j]+538137600*U[i+1,j]-94174080*U[i+2,j]+22830080*U[i+3,j]-5350800*U[i+4,j]+1053696*U[i+5,j]-156800*U[i+6,j]+15360*U[i+7,j]-735*U[i+8,j])+ \ (-735*U[i,j-8]+15360*U[i,j-7]-156800*U[i,j-6]+1053696*U[i,j-5]-5350800*U[i,j-4]+22830080*U[i,j-3]-94174080*U[i,j-2]+538137600*U[i,j-1]-924708642*U[i,j+0]+538137600*U[i,j+1]-94174080*U[i,j+2]+22830080*U[i,j+3]-5350800*U[i,j+4]+1053696*U[i,j+5]-156800*U[i,j+6]+15360*U[i,j+7]-735*U[i,j+8]))/ \ (302702400*1.0*h**2) #CPML boundary in X-domain for i in range(8+ncpml,ny-ncpml-8): for j in range(8,ncpml+1): phi[i,j]=b[j-8]*phi[i,j]+(b[j-8]-1.0)*(U[i,j+1]-U[i,j])/h phi[i,-j-1]=b[j-8]*phi[i,-j-1]+(b[j-8]-1.0)*(U[i,-j-1]-U[i,-j-2])/h for j in range(8,ncpml): psi[i,j]=b[j-8]*psi[i,j]+(b[j-8]-1.0)*\ ((U[i,j-1]-2*U[i,j]+U[i,j+1])/h/h \ +(phi[i,j+1]-phi[i,j])/h) psi[i,-j-1]=b[j-8]*psi[i,-j-1]+(b[j-8]-1.0)*\ ((U[i,-j-2]-2*U[i,-j-1]+U[i,-j])/h/h \ +(phi[i,-j-1]-phi[i,-j-2])/h) Up[i,j] += c[i-8,j-8]*((phi[i,j+1]-phi[i,j])/h+psi[i,j]) Up[i,-j-1] += c[i-8,-j-9]*((phi[i,-j-1]-phi[i,-j-2])/h+psi[i,-j-1]) #CPML boundary in Y-domain for i in range(8,ncpml+1): for j in range(8,nx-8): phi[i,j]=b[i-8]*phi[i,j]+(b[i-8]-1.0)*(U[i+1,j]-U[i,j])/h phi[-i-1,j]=b[i-8]*phi[-i-1,j]+(b[i-8]-1.0)*(U[-i-1,j]-U[-i-2,j])/h for i in range(8,ncpml): for j in range(8,nx-8): psi[i,j]=b[i-8]*psi[i,j]+(b[i-8]-1.0)*\ ((U[i-1,j]-2*U[i,j]+U[i+1,j])/h/h \ +(phi[i+1,j]-phi[i,j])/h) psi[-i-1,j]=b[i-8]*psi[-i-1,j]+(b[i-8]-1.0)*\ ((U[-i-2,j]-2*U[-i-1,j]+U[-i,j])/h/h \ +(phi[-i-1,j]-phi[-i-2,j])/h) Up[i,j] += c[i-8,j-8]*((phi[i+1,j]-phi[i,j])/h+psi[i,j]) Up[-i-1,j] += c[-i-9,j-8]*((phi[-i-1,j]-phi[-i-2,j])/h+psi[-i-1,j])
[ "def solve_wave_FD12(U,Up,h,c,ncpml,b,psi,phi):\n ny , nx = U.shape\n for i in range(6,ny-6):\n for j in range(6,nx-6):\n Up[i,j] = 2.0*U[i,j] - Up[i,j] + c[i-8,j-6]* \\\n ((-50*U[i-6,j]+864*U[i-5,j]-7425*U[i-4,j]+44000*U[i-3,j]-222750*U[i-2,j]+1425600*U[i-1,j]-2480478*U[i+0,j]+1425600*U[i+1,j]-222750*U[i+2,j]+44000*U[i+3,j]-7425*U[i+4,j]+864*U[i+5,j]-50*U[i+6,j])+ \\\n (-50*U[i,j-6]+864*U[i,j-5]-7425*U[i,j-4]+44000*U[i,j-3]-222750*U[i,j-2]+1425600*U[i,j-1]-2480478*U[i,j+0]+1425600*U[i,j+1]-222750*U[i,j+2]+44000*U[i,j+3]-7425*U[i,j+4]+864*U[i,j+5]-50*U[i,j+6]))/ \\\n (831600*1.0*h**2)\n \n #CPML boundary in X-domain\n for i in range(6+ncpml,ny-ncpml-6):\n for j in range(6,ncpml+1):\n phi[i,j]=b[j-1]*phi[i,j]+(b[j-1]-1.0)*(U[i,j+1]-U[i,j])/h\n phi[i,-j-1]=b[j-1]*phi[i,-j-1]+(b[j-1]-1.0)*(U[i,-j-1]-U[i,-j-2])/h\n for j in range(6,ncpml):\n psi[i,j]=b[j-1]*psi[i,j]+(b[j-1]-1.0)*\\\n ((U[i,j-1]-2*U[i,j]+U[i,j+1])/h/h \\\n +(phi[i,j+1]-phi[i,j])/h)\n psi[i,-j-1]=b[j-1]*psi[i,-j-1]+(b[j-1]-1.0)*\\\n ((U[i,-j-2]-2*U[i,-j-1]+U[i,-j])/h/h \\\n +(phi[i,-j-1]-phi[i,-j-2])/h)\n Up[i,j] += c[i-6,j-6]*((phi[i,j+1]-phi[i,j])/h+psi[i,j])\n Up[i,-j-1] += c[i-6,-j-7]*((phi[i,-j-1]-phi[i,-j-2])/h+psi[i,-j-1])\n \n #CPML boundary in Y-domain\n for i in range(6,ncpml+1):\n for j in range(6,nx-6):\n phi[i,j]=b[i-1]*phi[i,j]+(b[i-1]-1.0)*(U[i+1,j]-U[i,j])/h\n phi[-i-1,j]=b[i-1]*phi[-i-1,j]+(b[i-1]-1.0)*(U[-i-1,j]-U[-i-2,j])/h\n for i in range(6,ncpml):\n for j in range(6,nx-6):\n psi[i,j]=b[i-1]*psi[i,j]+(b[i-1]-1.0)*\\\n ((U[i-1,j]-2*U[i,j]+U[i+1,j])/h/h \\\n +(phi[i+1,j]-phi[i,j])/h)\n psi[-i-1,j]=b[i-1]*psi[-i-1,j]+(b[i-1]-1.0)*\\\n ((U[-i-2,j]-2*U[-i-1,j]+U[-i,j])/h/h \\\n +(phi[-i-1,j]-phi[-i-2,j])/h)\n Up[i,j] += c[i-6,j-6]*((phi[i+1,j]-phi[i,j])/h+psi[i,j])\n Up[-i-1,j] += c[-i-7,j-6]*((phi[-i-1,j]-phi[-i-2,j])/h+psi[-i-1,j])", "def solve_wave_FD4(U,Up,h,c,ncpml,b,psi,phi):\n ny , nx = U.shape\n for i in range(2,ny-2):\n for j in range(2,nx-2):\n Up[i,j] = 2.0*U[i,j] - Up[i,j] + c[i-2,j-2]* \\\n ((-1*U[i-2,j]+16*U[i-1,j]-30*U[i,j]+16*U[i+1,j]-1*U[i+2,j]) + \\\n (-1*U[i,j-2]+16*U[i,j-1]-30*U[i,j]+16*U[i,j+1]-1*U[i,j+2]))/ \\\n (12*1.0*h**2)\n #CPML boundary in X-domain\n for i in range(2+ncpml,ny-ncpml-2):\n for j in range(2,ncpml+1):\n phi[i,j]=b[j-1]*phi[i,j]+(b[j-1]-1.0)*(U[i,j+1]-U[i,j])/h\n phi[i,-j-1]=b[j-1]*phi[i,-j-1]+(b[j-1]-1.0)*(U[i,-j-1]-U[i,-j-2])/h\n for j in range(2,ncpml):\n psi[i,j]=b[j-1]*psi[i,j]+(b[j-1]-1.0)*\\\n ((U[i,j-1]-2*U[i,j]+U[i,j+1])/h/h \\\n +(phi[i,j+1]-phi[i,j])/h)\n psi[i,-j-1]=b[j-1]*psi[i,-j-1]+(b[j-1]-1.0)*\\\n ((U[i,-j-2]-2*U[i,-j-1]+U[i,-j])/h/h \\\n +(phi[i,-j-1]-phi[i,-j-2])/h)\n Up[i,j] += c[i-2,j-2]*((phi[i,j+1]-phi[i,j])/h+psi[i,j])\n Up[i,-j-1] += c[i-2,-j-3]*((phi[i,-j-1]-phi[i,-j-2])/h+psi[i,-j-1])\n \n #CPML boundary in Y-domain\n for i in range(2,ncpml+1):\n for j in range(2,nx-2):\n phi[i,j]=b[i-1]*phi[i,j]+(b[i-1]-1.0)*(U[i+1,j]-U[i,j])/h\n phi[-i-1,j]=b[i-1]*phi[-i-1,j]+(b[i-1]-1.0)*(U[-i-1,j]-U[-i-2,j])/h\n for i in range(2,ncpml):\n for j in range(2,nx-2):\n psi[i,j]=b[i-1]*psi[i,j]+(b[i-1]-1.0)*\\\n ((U[i-1,j]-2*U[i,j]+U[i+1,j])/h/h \\\n +(phi[i+1,j]-phi[i,j])/h)\n psi[-i-1,j]=b[i-1]*psi[-i-1,j]+(b[i-1]-1.0)*\\\n ((U[-i-2,j]-2*U[-i-1,j]+U[-i,j])/h/h \\\n +(phi[-i-1,j]-phi[-i-2,j])/h)\n Up[i,j] += c[i-2,j-2]*((phi[i+1,j]-phi[i,j])/h+psi[i,j])\n Up[-i-1,j] += c[-i-3,j-2]*((phi[-i-1,j]-phi[-i-2,j])/h+psi[-i-1,j])", "def wfDerivative(signalRaw,sp=10.):\n signalDeriv = np.zeros(len(signalRaw))\n for i in range(len(signalRaw)-1):\n signalDeriv[i] = (signalRaw[i+1] - signalRaw[i])/sp\n return signalDeriv", "def solve_wave_FD8(U,Up,h,c,ncpml,b,psi,phi):\n ny , nx = U.shape\n for i in range(4,ny-4):\n for j in range(4,nx-4):\n Up[i,j] = 2.0*U[i,j] - Up[i,j] + c[i-4,j-4]* \\\n ((-9*U[i,j-4]+128*U[i,j-3]-1008*U[i,j-2]+8064*U[i,j-1]-14350*U[i,j+0]+8064*U[i,j+1]-1008*U[i,j+2]+128*U[i,j+3]-9*U[i,j+4])+ \\\n (-9*U[i-4,j]+128*U[i-3,j]-1008*U[i-2,j]+8064*U[i-1,j]-14350*U[i+0,j]+8064*U[i+1,j]-1008*U[i+2,j]+128*U[i+3,j]-9*U[i+4,j]))/ \\\n (5040*1.0*h**2)\n \n #CPML boundary in X-domain\n for i in range(4+ncpml,ny-ncpml-4):\n for j in range(4,ncpml+1):\n phi[i,j]=b[j-1]*phi[i,j]+(b[j-1]-1.0)*(U[i,j+1]-U[i,j])/h\n phi[i,-j-1]=b[j-1]*phi[i,-j-1]+(b[j-1]-1.0)*(U[i,-j-1]-U[i,-j-2])/h\n for j in range(4,ncpml):\n psi[i,j]=b[j-1]*psi[i,j]+(b[j-1]-1.0)*\\\n ((U[i,j-1]-2*U[i,j]+U[i,j+1])/h/h \\\n +(phi[i,j+1]-phi[i,j])/h)\n psi[i,-j-1]=b[j-1]*psi[i,-j-1]+(b[j-1]-1.0)*\\\n ((U[i,-j-2]-2*U[i,-j-1]+U[i,-j])/h/h \\\n +(phi[i,-j-1]-phi[i,-j-2])/h)\n Up[i,j] += c[i-4,j-4]*((phi[i,j+1]-phi[i,j])/h+psi[i,j])\n Up[i,-j-1] += c[i-4,-j-5]*((phi[i,-j-1]-phi[i,-j-2])/h+psi[i,-j-1])\n \n #CPML boundary in Y-domain\n for i in range(4,ncpml+1):\n for j in range(4,nx-4):\n phi[i,j]=b[i-1]*phi[i,j]+(b[i-1]-1.0)*(U[i+1,j]-U[i,j])/h\n phi[-i-1,j]=b[i-1]*phi[-i-1,j]+(b[i-1]-1.0)*(U[-i-1,j]-U[-i-2,j])/h\n for i in range(4,ncpml):\n for j in range(4,nx-4):\n psi[i,j]=b[i-1]*psi[i,j]+(b[i-1]-1.0)*\\\n ((U[i-1,j]-2*U[i,j]+U[i+1,j])/h/h \\\n +(phi[i+1,j]-phi[i,j])/h)\n psi[-i-1,j]=b[i-1]*psi[-i-1,j]+(b[i-1]-1.0)*\\\n ((U[-i-2,j]-2*U[-i-1,j]+U[-i,j])/h/h \\\n +(phi[-i-1,j]-phi[-i-2,j])/h)\n Up[i,j] += c[i-4,j-4]*((phi[i+1,j]-phi[i,j])/h+psi[i,j])\n Up[-i-1,j] += c[-i-5,j-4]*((phi[-i-1,j]-phi[-i-2,j])/h+psi[-i-1,j])", "def wah_wah(x, fs):\n\n # buffer size\n wah_length = fs * 2\n\n # damping factor\n # lower the damping factor the smaller the pass band\n damp = 1.8\n\n # min and max centre cutoff frequency of variable bandpass filter\n minf = 500\n maxf = 3000\n\n # wah frequency, how many Hz per second are cycled through\n fw = 2000\n #########################################################################\n\n # change in centre frequency per sample (Hz)\n # delta = 0.2\n delta = fw / fs \n #0.1 => at 44100 samples per second should mean 4.41kHz Fc shift per sec\n\n # create triangle wave of centre frequency values\n fc = np.arange(minf, maxf, delta)\n while len(fc) < len(x):\n fc = np.append(fc, np.arange(maxf, minf, -delta))\n fc = np.append(fc, np.arange(minf, maxf, delta))\n \n # trim tri wave to size of input\n fc = fc[:len(x)]\n\n # difference equation coefficients\n F1 = 2 * np.sin((np.pi * fc[1]) / fs) # must be recalculated each time Fc changes\n Q1 = 2 * damp # this dictates size of the pass bands\n\n yh = np.zeros(x.shape[0]) # create emptly out vectors\n yb = np.zeros(x.shape[0])\n yl = np.zeros(x.shape[0])\n\n # first sample, to avoid referencing of negative signals\n yh[1] = x[1]\n yb[1] = F1 * yh[1]\n yl[1] = F1 * yb[1]\n\n # apply difference equation to the sample\n for n in range(2, len(x) - 1):\n yh[n] = x[n] - yl[n - 1] - Q1 * yb[n - 1]\n yb[n] = F1 * yh[n] + yb[n - 1]\n yl[n] = F1 * yb[n] + yl[n - 1]\n \n F1 = 2 * np.sin((np.pi * fc[n]) / fs)\n\n #normalise\n maxyb = max(abs(yb))\n y = yb / (maxyb + Epsilon)\n\n return shape_check(y)", "def solve_wave_FD2(U,Up,h,c,ncpml,b,psi,phi):\n ny , nx = U.shape\n for i in range(1,ny-1):\n for j in range(1,nx-1):\n Up[i,j] = 2.0*U[i,j] - Up[i,j] + c[i-1,j-1]* \\\n (U[i-1,j]-2*U[i,j]+U[i+1,j]+ \\\n (U[i,j-1]-2*U[i,j]+U[i,j+1]))/h/h\n #CPML boundary in X-domain\n for i in range(1+ncpml,ny-ncpml-1):\n for j in range(1,ncpml+1):\n phi[i,j]=b[j-1]*phi[i,j]+(b[j-1]-1.0)*(U[i,j+1]-U[i,j])/h\n phi[i,-j-1]=b[j-1]*phi[i,-j-1]+(b[j-1]-1.0)*(U[i,-j-1]-U[i,-j-2])/h\n for j in range(1,ncpml):\n psi[i,j]=b[j-1]*psi[i,j]+(b[j-1]-1.0)*\\\n ((U[i,j-1]-2*U[i,j]+U[i,j+1])/h/h \\\n +(phi[i,j+1]-phi[i,j])/h)\n psi[i,-j-1]=b[j-1]*psi[i,-j-1]+(b[j-1]-1.0)*\\\n ((U[i,-j-2]-2*U[i,-j-1]+U[i,-j])/h/h \\\n +(phi[i,-j-1]-phi[i,-j-2])/h)\n Up[i,j] += c[i-1,j-1]*((phi[i,j+1]-phi[i,j])/h+psi[i,j])\n Up[i,-j-1] += c[i-1,-j-2]*((phi[i,-j-1]-phi[i,-j-2])/h+psi[i,-j-1])\n \n #CPML boundary in Y-domain\n for i in range(1,ncpml+1):\n for j in range(1,nx-1):\n phi[i,j]=b[i-1]*phi[i,j]+(b[i-1]-1.0)*(U[i+1,j]-U[i,j])/h\n phi[-i-1,j]=b[i-1]*phi[-i-1,j]+(b[i-1]-1.0)*(U[-i-1,j]-U[-i-2,j])/h\n for i in range(1,ncpml):\n for j in range(1,nx-1):\n psi[i,j]=b[i-1]*psi[i,j]+(b[i-1]-1.0)*\\\n ((U[i-1,j]-2*U[i,j]+U[i+1,j])/h/h \\\n +(phi[i+1,j]-phi[i,j])/h)\n psi[-i-1,j]=b[i-1]*psi[-i-1,j]+(b[i-1]-1.0)*\\\n ((U[-i-2,j]-2*U[-i-1,j]+U[-i,j])/h/h \\\n +(phi[-i-1,j]-phi[-i-2,j])/h)\n Up[i,j] += c[i-1,j-1]*((phi[i+1,j]-phi[i,j])/h+psi[i,j])\n Up[-i-1,j] += c[-i-2,j-1]*((phi[-i-1,j]-phi[-i-2,j])/h+psi[-i-1,j])", "def solver(I, w, dt, T, V, f):\n dt = float(dt)\n Nt = int(round(T/dt)) # 100000\n u = np.zeros(Nt+1)\n t = np.linspace(0, Nt*dt, Nt+1)\n\n u[0] = I\n u[1] = u[0] + dt*V + 0.5*(f(t[0]) - w**2*u[0])*dt**2#compute first step by 1'st order difference\n for n in range(1, Nt):\n u[n+1] = (f(t[n])-w**2*u[n])*dt**2 + 2*u[n]-u[n-1]\n return u, t", "def find_s0(wavelet, dt):\n def f(s):\n return wavelet.fourier_period(s) - 2 * dt\n return scipy.optimize.fsolve(f, 1)[0]", "def rickerwave(f = 25, length = 0.512, dt = 0.004): \n time = np.arange(-length/2, (length-dt)/2, dt)\n amplitude = (1.0 - 2.0*(np.pi**2)*(f**2)*(time**2))* \\\n np.exp(-(np.pi**2)*(f**2)*(time**2))\n return (time, amplitude)", "def fourier(self):\n n = self.nsamples()\n yC = self.vpp / self.adcrange\n xC = 1.e-6\n yF = yC * (2.0/n) * np.abs(fft(self.bulk)[:n//2])\n xF = xC * fftfreq(n,(self.Dt)*1.e-9)[:n//2] \n return xF,yF", "def gen_powphase2d_old(si, phiF, rF, inner, outer, dx, dy, xW, yW, normfres=True, debug=True):\r\n # specified diffraction and refraction scales\r\n ld = rF / phiF \r\n lr = rF * phiF \r\n\r\n nx = int(xW/dx)\r\n ny = nx\r\n if debug: print 'targeted number of x,y samples = ', nx,ny\n \n #print \"nx\", nx\n #print \"ny\", ny\n \r\n xvec = (arange(0.,nx)-nx/2+1)*dx\r\n yvec = (arange(0.,ny)-ny/2+1)*dy\r\n\r\n dqx = 2.*pi / xW \r\n dqy = 2.*pi / yW\r\n qmaxx = (2.*pi) / (2.*dx)\r\n qmaxy = (2.*pi) / (2.*dy)\r\n\r\n nqx = 2*int(qmaxx/dqx)\r\n nqy = 2*int(qmaxy/dqy)\r\n if debug: print 'targeted number of q samples = ', nqx, nqy \r\n if nqx != nx: \r\n print \"Forcing nqx = nx = \", nx\r\n nqx = nx\r\n if nqy != ny: \r\n print \"Forcing nqy = ny = \", ny\r\n nqy = ny\r\n qxvec = (arange(0.,nqx)-nqx/2+1)*dqx\r\n qxvec = roll(qxvec,nqx/2+1)\r\n qyvec = (arange(0.,nqy)-nqy/2+1)*dqy\r\n qyvec = roll(qyvec,nqy/2+1)\r\n\r\n qin = 2.*pi / inner\r\n qout = 2.*pi / outer\r\n qshape = zeros((nqx, nqy))\r\n \r\n for i, qxi in enumerate(qxvec):\r\n for j, qyj in enumerate(qyvec):\r\n qsq = qxi**2 + qyj**2\r\n qshape[i,j] = (qout**2 + qsq)**(-si/4.) \r\n #qshape[i,j] = (qout**2 + qsq)**(-si/4.) * exp(-(qsq/(2.*qin**2))) \r\n npoints = size(qshape)\r\n\r\n if debug:\r\n print si, inner, outer, dx, npoints\r\n print dqx, dqy, qin, qout\r\n\r\n xformr=randn(nqx, nqy)*qshape\r\n xformi=randn(nqx, nqy)*qshape\r\n xform = xformr + 1j*xformi\r\n spectrum=real(xform*conj(xform))\r\n xseries = real(ifft2(xform))\r\n\r\n if normfres:\r\n frindx = int(rF/dx)\r\n x1dcut = xseries[0,:]\r\n var_fres_in = var(x1dcut[0:size(x1dcut)-frindx]-x1dcut[frindx:])\r\n xseries_norm = xseries * rF / sqrt(var_fres_in) \r\n xn1dcut = xseries_norm[0,:]\r\n var_fres_out = var(xn1dcut[0:size(xn1dcut)-frindx]-xn1dcut[frindx:])\r\n #var_fres_out = var(xseries_norm[0:size(xseries_norm)-frindx]-xseries_norm[frindx:])\r\n print \"index of fresnel scale = \", frindx\r\n print var_fres_in, var_fres_out\r\n\r\n return xvec, yvec, xseries, xseries_norm, qxvec, qyvec, qshape", "def get_time_audio_signal(fs, wave):\n return np.arange(wave.size)/float(fs)", "def Y2W(r, Y, mode, F): #im ana, and i want to make some mess in my boyfriend's code :)\n\n [h, vr] = Y\n Fphi, Fz = F(r)[2:]\n\n kappa = mode.disk.kappa(r)\n Omega = mode.disk.Omega(r)\n Omegav = mode.disk.Omegav(r)\n dkappa = mode.disk.dkappa(r)\n c = mode.disk.cs\n \n m, n = mode.m, mode.n\n omegat = mode.omegat(r)\n \n [h, vr] = Y\n vphi = -(-2*h*m*Omega + 1j*(-2*Fphi*Omega*r**2 + kappa**2*r*vr))/(2.*Omega*omegat*r**2) \n vz = 1j*(c*Fz - h*n*Omegav)/(c*omegat) \t \n \n # solution vector:\n W = np.array([h, vr, vphi, vz])\n \n # derivatives of h and vr are calculated by calling ode_rhs:\n [dh, dvr] = ode_rhs(r, Y, mode, F)\n\n # derivative of the force:\n dFphi, dFz = F.der(r)[2:]\n \n # derivatives of the two other velocities are: \n \n dvphi = (-(-2*dh*m*Omega - 2*h*m*(kappa**2/(2.*Omega*r) - (2*Omega)/r) + \n 1j*(dvr*kappa**2*r - 4*Fphi*Omega*r - 2*dFphi*Omega*r**2 - \n 2*Fphi*(kappa**2/(2.*Omega*r) - (2*Omega)/r)*r**2 + kappa**2*vr + 2*dkappa*kappa*r*vr))/\n (2.*Omega*omegat*r**2) + (-2*h*m*Omega + 1j*(-2*Fphi*Omega*r**2 + kappa**2*r*vr))/\n (Omega*omegat*r**3) - (m*(kappa**2/(2.*Omega*r) - (2*Omega)/r)*\n (-2*h*m*Omega + 1j*(-2*Fphi*Omega*r**2 + kappa**2*r*vr)))/(2.*Omega*omegat**2*r**2) + \n ((kappa**2/(2.*Omega*r) - (2*Omega)/r)*(-2*h*m*Omega + 1j*(-2*Fphi*Omega*r**2 + kappa**2*r*vr)))/\n (2.*Omega**2*omegat*r**2))\n\n dvz = (0.5j*(c*(Fz*m*(kappa**2 - 4*Omega**2) + 2*dFz*Omega*omegat*r) - \n n*Omegav*(h*m*(kappa**2 - 4*Omega**2) + 2*dh*Omega*omegat*r)))/(c*Omega*omegat**2*r)\n \n dW =np.array([dh, dvr, dvphi, dvz])\n \n return [W, dW]", "def wave_vector_value(E_eV=6000) :\n return 1. / (wavelength_nm_from_energy_ev(E_eV) * 10) # 1nm = 10A\n #return 2 * math.pi / (wavelength_nm_from_energy_ev(E_eV) * 10) # 1nm = 10A", "def syntheticSeismogram(\n d, rho, v, wavf, wavA=1.0, usingT=True, wavtyp=\"RICKER\", dt=0.0001, dmax=200\n):\n\n v, rho, d = (\n np.array(v, dtype=float),\n np.array(rho, dtype=float),\n np.array(d, dtype=float),\n )\n usingT = np.array(usingT, dtype=bool)\n\n _, t = getTimeDepth(d, v, dmax)\n rseries, R = getReflectivity(d, rho, v)\n\n # time for reflectivity series\n tref = t[1:-1]\n\n # create time vector\n t = np.arange(t.min(), t.max(), dt)\n\n # make wavelet\n twav = np.arange(-2.0 / np.min(wavf), 2.0 / np.min(wavf), dt)\n\n # Get source wavelet\n wav = {\"RICKER\": getRicker, \"ORMSBY\": getOrmsby, \"KLAUDER\": getKlauder}[wavtyp](\n wavf, twav\n )\n wav = wavA * wav\n\n rseriesconv = np.zeros(len(t))\n for i in range(len(tref)):\n index = np.abs(t - tref[i]).argmin()\n rseriesconv[index] = rseries[i]\n\n # Do the convolution\n seis = np.convolve(wav, rseriesconv)\n tseis = np.min(twav) + dt * np.arange(len(seis))\n index = np.logical_and(tseis >= 0, tseis <= np.max(t))\n tseis = tseis[index]\n seis = seis[index]\n\n return tseis, seis, twav, wav, tref, rseries", "def interpret_tempsig(self): \n temp_sig = []\n dewpoint_sig = []\n for i in range(len(self.df_tempsig)):\n #print (temp_dewpoint_sig[i])\n if self.df_tempsig.TempDew[i]=='/////':\n temp_sig.append(np.nan)\n dewpoint_sig.append(np.nan)\n else:\n temp_i = float(self.df_tempsig.TempDew[i][0:3])\n dewpoint_i = float(self.df_tempsig.TempDew[i][3:5])\n #if i==0:\n if temp_i%2==0:\n temp_sig.append(temp_i/10)\n if dewpoint_i <= 50.0:\n dewpoint_sig.append(round((temp_sig[i] - dewpoint_i/10),2))\n if dewpoint_i >50.0:\n dewpoint_d = dewpoint_i - 50.0\n dewpoint_sig.append(round((temp_sig[i] - dewpoint_d),2))\n if temp_i%2!=0:\n temp_sig.append(temp_i*-1/10)\n if dewpoint_i <= 50.0:\n dewpoint_sig.append(round((temp_sig[i] - dewpoint_i/10),2))\n if dewpoint_i >50.0:\n dewpoint_d = dewpoint_i - 50.0\n dewpoint_sig.append(round((temp_sig[i] - dewpoint_d),2))\n temp_sig_series = pd.Series(temp_sig)\n dewpoint_sig_series = pd.Series(dewpoint_sig)\n self.df_tempsig[\"Temp\"] = temp_sig_series.values\n self.df_tempsig[\"Dewpoint\"] = dewpoint_sig_series.values\n self.df_tempsig = self.df_tempsig.drop(['TempDew'], axis=1)", "def cdq4(f, x, h=1e-5):\n return (f(x-2*h) - 8*f(x-h) + 8*f(x+h) - f(x+2*h))/(12*h)", "def dB(self,valeurdB):\n assert(type(valeurdB)==float or type(valeurdB)==int),\"Flottant attendu\"\n \n#valeur trouvee experimentalement pour rapport de puissance en dB du format wave :\n const_dB = 0.113129\n if(self.nbOctet==1): #on passe en mode valeurs positives et negatives\n Ndata = [self.data[i]-128 for i in range(len(self.data))]\n else:\n Ndata = [self.data[i] for i in range(len(self.data))]\n \n if(valeurdB<0): #on diminue la puissance de valeurdB\n valeurdB*=-1\n for j in range(len(self.data)):\n self.data[j] = int(Ndata[j]/np.exp(const_dB*valeurdB))\n else: #on augmente la puissance de valeurdB\n for j in range(len(self.data)):\n self.data[j] = int(Ndata[j]*np.exp(const_dB*valeurdB))\n \n if(self.nbOctet==1): #on revient au format de donnees wave pour 1 octet\n self.data = [self.data[i]+128 for i in range(len(self.data))]\n if(max(self.data)>255 or min(self.data)<0):\n print(\"ATTENTION : saturation prevue au moment de l'ecriture\")\n else:\n if(max(self.data)>32767 or min(self.data)<-32676):\n print(\"ATTENTION : saturation prevue au moment de l'ecriture\")\n print(\"Nouvelle valeur max = {}, nouvelle valeur min = {}\"\\\n .format(max(self.data),min(self.data)))", "def pink_tsp():\n \n import primes\n import cmath\n import numpy as np\n from scipy.io import wavfile\n from utility import float2pcm\n \n # User settings\n dur = 5 # length of signal (seconds)\n fs = 48000 # number of samples per second (Hz)\n nbits = 16 # number of bits per sample (bit)\n reps = 4 # number of repeated measurements (times)\n \n N = 2 ** (nextpow2(dur * fs))\n m = primes.primes_below(N / 4)\n m = m[-1]\n \n a = 2 * m * np.pi / ((N / 2) * np.log(N / 2))\n j = cmath.sqrt(-1)\n pi = (cmath.log(-1)).imag\n \n H = np.array([1])\n H = np.hstack(\n [H, np.exp(j * a * np.arange(1, N / 2 + 1) * np.log(np.arange(1, N / 2 + 1))) / np.sqrt(np.arange(1, N / 2 + 1))])\n H = np.hstack([H, np.conj(H[int((N / 2 - 1)):0:-1])])\n h = (np.fft.ifft(H)).real\n mvBefore = np.abs(h)\n mv = min(mvBefore)\n mi = np.where(mvBefore == mvBefore.min())\n mi = int(mi[0])\n h = np.hstack([h[mi:len(h)], h[0:mi]])\n h = h[::-1]\n \n Hinv = np.array([1])\n Hinv = np.hstack([Hinv, np.exp(j * a * np.arange(1, N / 2 + 1) * np.log(np.arange(1, N / 2 + 1))) * np.sqrt(\n np.arange(1, N / 2 + 1))])\n Hinv = np.hstack([Hinv, np.conj(Hinv[int((N / 2 - 1)):0:-1])])\n hinv = (np.fft.ifft(Hinv)).real\n \n hh = np.hstack((np.tile(h, (reps, 1)).flatten(), np.zeros(len(h))))\n out = hh / max(np.abs(hh)) / np.sqrt(2)\n \n wavfile.write('pinktsp.wav', fs, float2pcm(out, 'int16'))\n \n plt.specgram(out, Fs=fs)\n plt.show()" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculate wave solution using 12th order finite difference
def solve_wave_FD12(U,Up,h,c,ncpml,b,psi,phi): ny , nx = U.shape for i in range(6,ny-6): for j in range(6,nx-6): Up[i,j] = 2.0*U[i,j] - Up[i,j] + c[i-8,j-6]* \ ((-50*U[i-6,j]+864*U[i-5,j]-7425*U[i-4,j]+44000*U[i-3,j]-222750*U[i-2,j]+1425600*U[i-1,j]-2480478*U[i+0,j]+1425600*U[i+1,j]-222750*U[i+2,j]+44000*U[i+3,j]-7425*U[i+4,j]+864*U[i+5,j]-50*U[i+6,j])+ \ (-50*U[i,j-6]+864*U[i,j-5]-7425*U[i,j-4]+44000*U[i,j-3]-222750*U[i,j-2]+1425600*U[i,j-1]-2480478*U[i,j+0]+1425600*U[i,j+1]-222750*U[i,j+2]+44000*U[i,j+3]-7425*U[i,j+4]+864*U[i,j+5]-50*U[i,j+6]))/ \ (831600*1.0*h**2) #CPML boundary in X-domain for i in range(6+ncpml,ny-ncpml-6): for j in range(6,ncpml+1): phi[i,j]=b[j-1]*phi[i,j]+(b[j-1]-1.0)*(U[i,j+1]-U[i,j])/h phi[i,-j-1]=b[j-1]*phi[i,-j-1]+(b[j-1]-1.0)*(U[i,-j-1]-U[i,-j-2])/h for j in range(6,ncpml): psi[i,j]=b[j-1]*psi[i,j]+(b[j-1]-1.0)*\ ((U[i,j-1]-2*U[i,j]+U[i,j+1])/h/h \ +(phi[i,j+1]-phi[i,j])/h) psi[i,-j-1]=b[j-1]*psi[i,-j-1]+(b[j-1]-1.0)*\ ((U[i,-j-2]-2*U[i,-j-1]+U[i,-j])/h/h \ +(phi[i,-j-1]-phi[i,-j-2])/h) Up[i,j] += c[i-6,j-6]*((phi[i,j+1]-phi[i,j])/h+psi[i,j]) Up[i,-j-1] += c[i-6,-j-7]*((phi[i,-j-1]-phi[i,-j-2])/h+psi[i,-j-1]) #CPML boundary in Y-domain for i in range(6,ncpml+1): for j in range(6,nx-6): phi[i,j]=b[i-1]*phi[i,j]+(b[i-1]-1.0)*(U[i+1,j]-U[i,j])/h phi[-i-1,j]=b[i-1]*phi[-i-1,j]+(b[i-1]-1.0)*(U[-i-1,j]-U[-i-2,j])/h for i in range(6,ncpml): for j in range(6,nx-6): psi[i,j]=b[i-1]*psi[i,j]+(b[i-1]-1.0)*\ ((U[i-1,j]-2*U[i,j]+U[i+1,j])/h/h \ +(phi[i+1,j]-phi[i,j])/h) psi[-i-1,j]=b[i-1]*psi[-i-1,j]+(b[i-1]-1.0)*\ ((U[-i-2,j]-2*U[-i-1,j]+U[-i,j])/h/h \ +(phi[-i-1,j]-phi[-i-2,j])/h) Up[i,j] += c[i-6,j-6]*((phi[i+1,j]-phi[i,j])/h+psi[i,j]) Up[-i-1,j] += c[-i-7,j-6]*((phi[-i-1,j]-phi[-i-2,j])/h+psi[-i-1,j])
[ "def solve_wave_FD16(U,Up,h,c,ncpml,b,psi,phi):\n ny , nx = U.shape\n for i in range(8,ny-8):\n for j in range(8,nx-8):\n Up[i,j] = 2.0*U[i,j] - Up[i,j] + c[i-8,j-8]* \\\n ((-735*U[i-8,j]+15360*U[i-7,j]-156800*U[i-6,j]+1053696*U[i-5,j]-5350800*U[i-4,j]+22830080*U[i-3,j]-94174080*U[i-2,j]+538137600*U[i-1,j]-924708642*U[i+0,j]+538137600*U[i+1,j]-94174080*U[i+2,j]+22830080*U[i+3,j]-5350800*U[i+4,j]+1053696*U[i+5,j]-156800*U[i+6,j]+15360*U[i+7,j]-735*U[i+8,j])+ \\\n (-735*U[i,j-8]+15360*U[i,j-7]-156800*U[i,j-6]+1053696*U[i,j-5]-5350800*U[i,j-4]+22830080*U[i,j-3]-94174080*U[i,j-2]+538137600*U[i,j-1]-924708642*U[i,j+0]+538137600*U[i,j+1]-94174080*U[i,j+2]+22830080*U[i,j+3]-5350800*U[i,j+4]+1053696*U[i,j+5]-156800*U[i,j+6]+15360*U[i,j+7]-735*U[i,j+8]))/ \\\n (302702400*1.0*h**2)\n \n #CPML boundary in X-domain\n for i in range(8+ncpml,ny-ncpml-8):\n for j in range(8,ncpml+1):\n phi[i,j]=b[j-8]*phi[i,j]+(b[j-8]-1.0)*(U[i,j+1]-U[i,j])/h\n phi[i,-j-1]=b[j-8]*phi[i,-j-1]+(b[j-8]-1.0)*(U[i,-j-1]-U[i,-j-2])/h\n for j in range(8,ncpml):\n psi[i,j]=b[j-8]*psi[i,j]+(b[j-8]-1.0)*\\\n ((U[i,j-1]-2*U[i,j]+U[i,j+1])/h/h \\\n +(phi[i,j+1]-phi[i,j])/h)\n psi[i,-j-1]=b[j-8]*psi[i,-j-1]+(b[j-8]-1.0)*\\\n ((U[i,-j-2]-2*U[i,-j-1]+U[i,-j])/h/h \\\n +(phi[i,-j-1]-phi[i,-j-2])/h)\n Up[i,j] += c[i-8,j-8]*((phi[i,j+1]-phi[i,j])/h+psi[i,j])\n Up[i,-j-1] += c[i-8,-j-9]*((phi[i,-j-1]-phi[i,-j-2])/h+psi[i,-j-1])\n \n #CPML boundary in Y-domain\n for i in range(8,ncpml+1):\n for j in range(8,nx-8):\n phi[i,j]=b[i-8]*phi[i,j]+(b[i-8]-1.0)*(U[i+1,j]-U[i,j])/h\n phi[-i-1,j]=b[i-8]*phi[-i-1,j]+(b[i-8]-1.0)*(U[-i-1,j]-U[-i-2,j])/h\n for i in range(8,ncpml):\n for j in range(8,nx-8):\n psi[i,j]=b[i-8]*psi[i,j]+(b[i-8]-1.0)*\\\n ((U[i-1,j]-2*U[i,j]+U[i+1,j])/h/h \\\n +(phi[i+1,j]-phi[i,j])/h)\n psi[-i-1,j]=b[i-8]*psi[-i-1,j]+(b[i-8]-1.0)*\\\n ((U[-i-2,j]-2*U[-i-1,j]+U[-i,j])/h/h \\\n +(phi[-i-1,j]-phi[-i-2,j])/h)\n \n Up[i,j] += c[i-8,j-8]*((phi[i+1,j]-phi[i,j])/h+psi[i,j])\n Up[-i-1,j] += c[-i-9,j-8]*((phi[-i-1,j]-phi[-i-2,j])/h+psi[-i-1,j])", "def solver(I, w, dt, T, V, f):\n dt = float(dt)\n Nt = int(round(T/dt)) # 100000\n u = np.zeros(Nt+1)\n t = np.linspace(0, Nt*dt, Nt+1)\n\n u[0] = I\n u[1] = u[0] + dt*V + 0.5*(f(t[0]) - w**2*u[0])*dt**2#compute first step by 1'st order difference\n for n in range(1, Nt):\n u[n+1] = (f(t[n])-w**2*u[n])*dt**2 + 2*u[n]-u[n-1]\n return u, t", "def find_s0(wavelet, dt):\n def f(s):\n return wavelet.fourier_period(s) - 2 * dt\n return scipy.optimize.fsolve(f, 1)[0]", "def wah_wah(x, fs):\n\n # buffer size\n wah_length = fs * 2\n\n # damping factor\n # lower the damping factor the smaller the pass band\n damp = 1.8\n\n # min and max centre cutoff frequency of variable bandpass filter\n minf = 500\n maxf = 3000\n\n # wah frequency, how many Hz per second are cycled through\n fw = 2000\n #########################################################################\n\n # change in centre frequency per sample (Hz)\n # delta = 0.2\n delta = fw / fs \n #0.1 => at 44100 samples per second should mean 4.41kHz Fc shift per sec\n\n # create triangle wave of centre frequency values\n fc = np.arange(minf, maxf, delta)\n while len(fc) < len(x):\n fc = np.append(fc, np.arange(maxf, minf, -delta))\n fc = np.append(fc, np.arange(minf, maxf, delta))\n \n # trim tri wave to size of input\n fc = fc[:len(x)]\n\n # difference equation coefficients\n F1 = 2 * np.sin((np.pi * fc[1]) / fs) # must be recalculated each time Fc changes\n Q1 = 2 * damp # this dictates size of the pass bands\n\n yh = np.zeros(x.shape[0]) # create emptly out vectors\n yb = np.zeros(x.shape[0])\n yl = np.zeros(x.shape[0])\n\n # first sample, to avoid referencing of negative signals\n yh[1] = x[1]\n yb[1] = F1 * yh[1]\n yl[1] = F1 * yb[1]\n\n # apply difference equation to the sample\n for n in range(2, len(x) - 1):\n yh[n] = x[n] - yl[n - 1] - Q1 * yb[n - 1]\n yb[n] = F1 * yh[n] + yb[n - 1]\n yl[n] = F1 * yb[n] + yl[n - 1]\n \n F1 = 2 * np.sin((np.pi * fc[n]) / fs)\n\n #normalise\n maxyb = max(abs(yb))\n y = yb / (maxyb + Epsilon)\n\n return shape_check(y)", "def wfDerivative(signalRaw,sp=10.):\n signalDeriv = np.zeros(len(signalRaw))\n for i in range(len(signalRaw)-1):\n signalDeriv[i] = (signalRaw[i+1] - signalRaw[i])/sp\n return signalDeriv", "def solve_wave_FD4(U,Up,h,c,ncpml,b,psi,phi):\n ny , nx = U.shape\n for i in range(2,ny-2):\n for j in range(2,nx-2):\n Up[i,j] = 2.0*U[i,j] - Up[i,j] + c[i-2,j-2]* \\\n ((-1*U[i-2,j]+16*U[i-1,j]-30*U[i,j]+16*U[i+1,j]-1*U[i+2,j]) + \\\n (-1*U[i,j-2]+16*U[i,j-1]-30*U[i,j]+16*U[i,j+1]-1*U[i,j+2]))/ \\\n (12*1.0*h**2)\n #CPML boundary in X-domain\n for i in range(2+ncpml,ny-ncpml-2):\n for j in range(2,ncpml+1):\n phi[i,j]=b[j-1]*phi[i,j]+(b[j-1]-1.0)*(U[i,j+1]-U[i,j])/h\n phi[i,-j-1]=b[j-1]*phi[i,-j-1]+(b[j-1]-1.0)*(U[i,-j-1]-U[i,-j-2])/h\n for j in range(2,ncpml):\n psi[i,j]=b[j-1]*psi[i,j]+(b[j-1]-1.0)*\\\n ((U[i,j-1]-2*U[i,j]+U[i,j+1])/h/h \\\n +(phi[i,j+1]-phi[i,j])/h)\n psi[i,-j-1]=b[j-1]*psi[i,-j-1]+(b[j-1]-1.0)*\\\n ((U[i,-j-2]-2*U[i,-j-1]+U[i,-j])/h/h \\\n +(phi[i,-j-1]-phi[i,-j-2])/h)\n Up[i,j] += c[i-2,j-2]*((phi[i,j+1]-phi[i,j])/h+psi[i,j])\n Up[i,-j-1] += c[i-2,-j-3]*((phi[i,-j-1]-phi[i,-j-2])/h+psi[i,-j-1])\n \n #CPML boundary in Y-domain\n for i in range(2,ncpml+1):\n for j in range(2,nx-2):\n phi[i,j]=b[i-1]*phi[i,j]+(b[i-1]-1.0)*(U[i+1,j]-U[i,j])/h\n phi[-i-1,j]=b[i-1]*phi[-i-1,j]+(b[i-1]-1.0)*(U[-i-1,j]-U[-i-2,j])/h\n for i in range(2,ncpml):\n for j in range(2,nx-2):\n psi[i,j]=b[i-1]*psi[i,j]+(b[i-1]-1.0)*\\\n ((U[i-1,j]-2*U[i,j]+U[i+1,j])/h/h \\\n +(phi[i+1,j]-phi[i,j])/h)\n psi[-i-1,j]=b[i-1]*psi[-i-1,j]+(b[i-1]-1.0)*\\\n ((U[-i-2,j]-2*U[-i-1,j]+U[-i,j])/h/h \\\n +(phi[-i-1,j]-phi[-i-2,j])/h)\n Up[i,j] += c[i-2,j-2]*((phi[i+1,j]-phi[i,j])/h+psi[i,j])\n Up[-i-1,j] += c[-i-3,j-2]*((phi[-i-1,j]-phi[-i-2,j])/h+psi[-i-1,j])", "def solve_wave_FD8(U,Up,h,c,ncpml,b,psi,phi):\n ny , nx = U.shape\n for i in range(4,ny-4):\n for j in range(4,nx-4):\n Up[i,j] = 2.0*U[i,j] - Up[i,j] + c[i-4,j-4]* \\\n ((-9*U[i,j-4]+128*U[i,j-3]-1008*U[i,j-2]+8064*U[i,j-1]-14350*U[i,j+0]+8064*U[i,j+1]-1008*U[i,j+2]+128*U[i,j+3]-9*U[i,j+4])+ \\\n (-9*U[i-4,j]+128*U[i-3,j]-1008*U[i-2,j]+8064*U[i-1,j]-14350*U[i+0,j]+8064*U[i+1,j]-1008*U[i+2,j]+128*U[i+3,j]-9*U[i+4,j]))/ \\\n (5040*1.0*h**2)\n \n #CPML boundary in X-domain\n for i in range(4+ncpml,ny-ncpml-4):\n for j in range(4,ncpml+1):\n phi[i,j]=b[j-1]*phi[i,j]+(b[j-1]-1.0)*(U[i,j+1]-U[i,j])/h\n phi[i,-j-1]=b[j-1]*phi[i,-j-1]+(b[j-1]-1.0)*(U[i,-j-1]-U[i,-j-2])/h\n for j in range(4,ncpml):\n psi[i,j]=b[j-1]*psi[i,j]+(b[j-1]-1.0)*\\\n ((U[i,j-1]-2*U[i,j]+U[i,j+1])/h/h \\\n +(phi[i,j+1]-phi[i,j])/h)\n psi[i,-j-1]=b[j-1]*psi[i,-j-1]+(b[j-1]-1.0)*\\\n ((U[i,-j-2]-2*U[i,-j-1]+U[i,-j])/h/h \\\n +(phi[i,-j-1]-phi[i,-j-2])/h)\n Up[i,j] += c[i-4,j-4]*((phi[i,j+1]-phi[i,j])/h+psi[i,j])\n Up[i,-j-1] += c[i-4,-j-5]*((phi[i,-j-1]-phi[i,-j-2])/h+psi[i,-j-1])\n \n #CPML boundary in Y-domain\n for i in range(4,ncpml+1):\n for j in range(4,nx-4):\n phi[i,j]=b[i-1]*phi[i,j]+(b[i-1]-1.0)*(U[i+1,j]-U[i,j])/h\n phi[-i-1,j]=b[i-1]*phi[-i-1,j]+(b[i-1]-1.0)*(U[-i-1,j]-U[-i-2,j])/h\n for i in range(4,ncpml):\n for j in range(4,nx-4):\n psi[i,j]=b[i-1]*psi[i,j]+(b[i-1]-1.0)*\\\n ((U[i-1,j]-2*U[i,j]+U[i+1,j])/h/h \\\n +(phi[i+1,j]-phi[i,j])/h)\n psi[-i-1,j]=b[i-1]*psi[-i-1,j]+(b[i-1]-1.0)*\\\n ((U[-i-2,j]-2*U[-i-1,j]+U[-i,j])/h/h \\\n +(phi[-i-1,j]-phi[-i-2,j])/h)\n Up[i,j] += c[i-4,j-4]*((phi[i+1,j]-phi[i,j])/h+psi[i,j])\n Up[-i-1,j] += c[-i-5,j-4]*((phi[-i-1,j]-phi[-i-2,j])/h+psi[-i-1,j])", "def bounds(step_test, delta_phi_star):\n\n # define integration for one step\n def step_integrate(phi0, u_val, step):\n \"\"\" function that integrates one step forward. returns final phase,\n total shift value \"\"\"\n def dphidt(phi, t):\n return ((2*np.pi)/pmodel.T\n - u_val*prc_spl(start_time+(phi)*pmodel.T/(2*np.pi)))\n\n int_times = np.linspace(0,step,101) # in hours\n phis = integrate.odeint(dphidt, [phi0], int_times, hmax=0.01)\n return int_times, phis, phis[-1][0]-phi0-2*np.pi/pmodel.T*step\n\n # find the max advance or delay in each cycle\n def dphitot_dt(phis, t):\n [phi_osc_pos, phi_osc_neg, phi_shift_pos, phi_shift_neg] = phis\n dphi_osc_pos_dt = (2*np.pi)/pmodel.T +\\\n umax*prc_pos_spl(phi_osc_pos*pmodel.T/(2*np.pi))\n dphi_osc_neg_dt = (2*np.pi)/pmodel.T +\\\n umax*prc_neg_spl(phi_osc_neg*pmodel.T/(2*np.pi))\n dphi_shft_pos_dt = umax*prc_pos_spl(phi_osc_pos*pmodel.T/(2*np.pi))\n dphi_shft_neg_dt = umax*prc_neg_spl(phi_osc_neg*pmodel.T/(2*np.pi))\n return dphi_osc_pos_dt, dphi_osc_neg_dt, dphi_shft_pos_dt, dphi_shft_neg_dt\n\n int_times = np.linspace(0,200, 10001)\n delta_phis_total = integrate.odeint(dphitot_dt, [0,0,0,0], int_times,\n hmax=0.001)\n phis_adv = delta_phis_total[:,0]\n phis_del = delta_phis_total[:,1]\n advs = delta_phis_total[:,2]\n dels = delta_phis_total[:,3]\n delta_phi_star_calc = delta_phis_total[np.min(\n np.where(delta_phis_total[:,2]-delta_phis_total[:,3]>2*np.pi)\n ), 2]\n\n # max 1 cycle advances are where the oscillator reaches 0 again\n max_1cyc_adv = advs[np.min(\n np.where(phis_adv>2*np.pi)[0]\n )]\n max_1cyc_del = dels[np.min(\n np.where(phis_del>2*np.pi)[0]\n )]\n\n\n\n def loss_zero_cross(umax, stepsize, cross=6, start_bound=[0,12]):\n \"\"\"\n calculates the max loss for a specific zero-crossing of the PRC\n \"\"\"\n # first, find where the pulse lines up the worst\n def min_shift(init):\n init = init[0]\n times, phases, shift = step_integrate(init*2*np.pi/pmodel.T,\n umax, stepsize)\n return np.abs(shift)\n # get alignment\n mins = optimize.minimize(min_shift, cross, bounds = [start_bound])\n even_start = mins.x[0]\n\n times, phases, shift = step_integrate(even_start*2*np.pi/pmodel.T,\n umax, stepsize)\n stim_PRC = prc_spl(start_time+phases*pmodel.T/(2*np.pi))\n ePRC = interpolate.UnivariateSpline(times, stim_PRC, k=3, s=0)\n loss = np.max(umax*np.abs(integrate.cumtrapz(ePRC(times), times)))\n zero_cross = times[np.argmax(umax*np.abs(integrate.cumtrapz(ePRC(times),\n times)))]\n return even_start, zero_cross, loss\n\n\n # find the loss for each crossing, where it starts, where it crosses\n zero_neg_start, zero_neg_cross, loss_neg = loss_zero_cross(0.06, step_test)\n zero_pos_start, zero_pos_cross, loss_pos = loss_zero_cross(0.06, step_test,\n cross=22, start_bound=[18,27])\n\n adv_per_cycle = max_1cyc_adv - loss_neg - loss_pos\n del_per_cycle = max_1cyc_del + loss_neg + loss_pos\n\n # for the advance, there is also the slowdown loss - the phase advance lost\n # by the oscillator not advancing\n slowdown_pos = np.abs(step_integrate(zero_pos_start*2*np.pi/pmodel.T,\n 0.06, zero_pos_cross)[-1])\n slowdown_neg = np.abs(step_integrate(zero_neg_start*2*np.pi/pmodel.T,\n 0.06, zero_neg_cross)[-1])\n # slowdown_loss is how much phase shift we miss at most due to this\n def max_shift_pos(init):\n init = init[0]\n times, phases, shift = step_integrate(init*2*np.pi/pmodel.T,\n umax, slowdown_pos*pmodel.T/(2*np.pi))\n return -shift\n def max_shift_neg(init):\n init = init[0]\n times, phases, shift = step_integrate(init*2*np.pi/pmodel.T,\n umax, slowdown_neg*pmodel.T/(2*np.pi))\n return shift\n\n pos_loss_maximization = optimize.minimize(max_shift_pos, [0], bounds=[[0,8]])\n neg_loss_maximization = optimize.minimize(max_shift_neg, [0], bounds=[[12,24]])\n slowdown_pos_loss = pos_loss_maximization.fun\n slowdown_neg_loss = neg_loss_maximization.fun\n\n\n # figure out the direction and number of cycle bounds\n delta_phi_fs = np.arange(-2*np.pi,2*np.pi,0.01)\n adv_del = [] #0 if advance, 1 if delay\n numcycles = []\n del_phis = []\n directions = []\n regions_missed = []\n cyc_to_reachs = []\n for delta_phi in delta_phi_fs:\n direction = int(delta_phi > delta_phi_star)\n if delta_phi>0:\n ncyc = 1 + delta_phi//max_1cyc_adv\n cyc_to_reach = 1 + delta_phi//adv_per_cycle\n adv_del.append(0)\n # upper limit of how much can be missed\n region_missed = (ncyc)*(\n np.abs(slowdown_pos_loss+slowdown_pos_loss)+loss_neg+loss_pos)\n del_phi = region_missed\n elif delta_phi<=0:\n ncyc = 1+ -delta_phi//-max_1cyc_del\n cyc_to_reach = 1+ -delta_phi//-del_per_cycle\n adv_del.append(1)\n # upper limit of how much can be missed\n region_missed = (ncyc)*(loss_neg+loss_pos)\n # will the minimum achieved be better or worse than the max lost\n del_phi = region_missed\n\n del_phis.append(del_phi)\n directions.append(direction)\n numcycles.append(ncyc)\n cyc_to_reachs.append(cyc_to_reach)\n regions_missed.append(region_missed)\n\n result_dict = {'delta_phi_fs' : delta_phi_fs,\n 'directions' : directions,\n 'numcycles' : numcycles,\n 'regions_missed' : regions_missed,\n 'cyc_to_reachs' : cyc_to_reachs,\n 'del_phis' : del_phis}\n\n return result_dict", "def converged_MFS(mesh,plotx,ploty,plotz,k,incDir,incAmp=1.0,mintau=1,maxtau=20,steps=38):\n \n testx=plotx[0]\n testy=ploty[0]\n testz=plotz[0]\n taus=np.linspace(mintau,maxtau,steps+1)\n vals = np.zeros((steps+1,),dtype=np.complex)\n for i in xrange(steps+1):\n\tvals[i] = MFS(mesh,testx,testy,testz,k,incDir,incAmp,taus[i])[0]\n #vals=[MFS(mesh,testx,testy,testz,k,incDir,incAmp,tau) for tau in taus]\n vals = np.array([np.abs(vals[i]-vals[i+1]) for i in xrange(steps)])\n vals[np.where(vals==0)[0]]=100\n tau = taus[ np.where(vals==np.min(vals))[0][0] +1 ]\n print vals\n print \"MFS solution settled at tau: %.2f\" % (tau)\n return MFS(mesh,plotx,ploty,plotz,k,incDir,incAmp,tau)", "def test_getNewTimes_with_half_phase_two_day_bin():\n times = np.random.uniform(0, 10, 75)\n newtimes = wm.getNewTimes(times, 2.)\n newtimes2 = wm.getNewTimes(times, 2., phase=0.5)\n assert np.round((np.min(newtimes2) - np.min(newtimes)), 7) == 1.000", "def solve_wave_FD2(U,Up,h,c,ncpml,b,psi,phi):\n ny , nx = U.shape\n for i in range(1,ny-1):\n for j in range(1,nx-1):\n Up[i,j] = 2.0*U[i,j] - Up[i,j] + c[i-1,j-1]* \\\n (U[i-1,j]-2*U[i,j]+U[i+1,j]+ \\\n (U[i,j-1]-2*U[i,j]+U[i,j+1]))/h/h\n #CPML boundary in X-domain\n for i in range(1+ncpml,ny-ncpml-1):\n for j in range(1,ncpml+1):\n phi[i,j]=b[j-1]*phi[i,j]+(b[j-1]-1.0)*(U[i,j+1]-U[i,j])/h\n phi[i,-j-1]=b[j-1]*phi[i,-j-1]+(b[j-1]-1.0)*(U[i,-j-1]-U[i,-j-2])/h\n for j in range(1,ncpml):\n psi[i,j]=b[j-1]*psi[i,j]+(b[j-1]-1.0)*\\\n ((U[i,j-1]-2*U[i,j]+U[i,j+1])/h/h \\\n +(phi[i,j+1]-phi[i,j])/h)\n psi[i,-j-1]=b[j-1]*psi[i,-j-1]+(b[j-1]-1.0)*\\\n ((U[i,-j-2]-2*U[i,-j-1]+U[i,-j])/h/h \\\n +(phi[i,-j-1]-phi[i,-j-2])/h)\n Up[i,j] += c[i-1,j-1]*((phi[i,j+1]-phi[i,j])/h+psi[i,j])\n Up[i,-j-1] += c[i-1,-j-2]*((phi[i,-j-1]-phi[i,-j-2])/h+psi[i,-j-1])\n \n #CPML boundary in Y-domain\n for i in range(1,ncpml+1):\n for j in range(1,nx-1):\n phi[i,j]=b[i-1]*phi[i,j]+(b[i-1]-1.0)*(U[i+1,j]-U[i,j])/h\n phi[-i-1,j]=b[i-1]*phi[-i-1,j]+(b[i-1]-1.0)*(U[-i-1,j]-U[-i-2,j])/h\n for i in range(1,ncpml):\n for j in range(1,nx-1):\n psi[i,j]=b[i-1]*psi[i,j]+(b[i-1]-1.0)*\\\n ((U[i-1,j]-2*U[i,j]+U[i+1,j])/h/h \\\n +(phi[i+1,j]-phi[i,j])/h)\n psi[-i-1,j]=b[i-1]*psi[-i-1,j]+(b[i-1]-1.0)*\\\n ((U[-i-2,j]-2*U[-i-1,j]+U[-i,j])/h/h \\\n +(phi[-i-1,j]-phi[-i-2,j])/h)\n Up[i,j] += c[i-1,j-1]*((phi[i+1,j]-phi[i,j])/h+psi[i,j])\n Up[-i-1,j] += c[-i-2,j-1]*((phi[-i-1,j]-phi[-i-2,j])/h+psi[-i-1,j])", "def test_wavefunc(file):\n filedir = \"__testfiles__/\" + file\n interpdata = sol.input_reader(filedir)[1]\n x_min, x_max = interpdata[:2]\n length = x_max - x_min\n methode, potar = sol.input_reader(filedir)[2:4]\n eigmin, eigmax = sol.input_reader(filedir)[4:6]\n x_vals = sol.potential_interpolate(interpdata, methode, potar)[:, 0]\n # getting the wavefunctions for the specific problem from data or equations\n wavefuncsmat = np.empty((len(x_vals), eigmax - eigmin + 1))\n if file == \"test_infpot.txt\":\n for nn in range(eigmin, eigmax + 1):\n wavefuncs = []\n if nn % 2 == 0:\n for val in enumerate(x_vals):\n wavefunc = np.sqrt(2 / length) * np.sin(nn * np.pi /\n length * val[1])\n wavefuncs.append(wavefunc)\n else:\n for val in enumerate(x_vals):\n wavefunc = np.sqrt(2 / length) * np.cos(nn * np.pi /\n length * val[1])\n wavefuncs.append(wavefunc)\n wavefuncsmat[:, nn - 1] = wavefuncs\n elif file == \"test_harmonic.txt\":\n wavefuncsmat = np.loadtxt\\\n (\"__unittestfiles__/test_harmonic_wf.dat\")[:, 1:]\n elif file == \"test_pot.txt\":\n wavefuncsmat = np.loadtxt\\\n (\"__unittestfiles__/test_pot_wf.dat\")[:, 1:]\n elif file == \"test_dualpot_lin.txt\":\n wavefuncsmat = np.loadtxt\\\n (\"__unittestfiles__/test_dualpot_lin_wf.dat\")[:, 1:]\n elif file == \"test_dualpot_cspline.txt\":\n wavefuncsmat = np.loadtxt\\\n (\"__unittestfiles__/test_dualpot_cspline_wf.dat\")[:, 1:]\n elif file == \"test_asympot.txt\":\n wavefuncsmat = np.loadtxt\\\n (\"__unittestfiles__/test_asympot_wf.dat\")[:, 1:]\n else:\n wavefuncsmat = np.ones((len(x_vals), eigmax - eigmin + 1))\n # checking if the norm of the wavefunctions is equal to testdata\n sol.run(filedir, \"__output__\")\n testwavefuncs = np.loadtxt(\"__output__/wavefuncs.dat\")[:, 1:]\n assert np.all(np.abs(np.abs(wavefuncsmat)**2 - np.abs(testwavefuncs)**2)\n < ERROR)", "def harmonicModelAnal(x, fs, window, fft_size, hop_size, min_fft_val, nSines, minf0, maxf0, f0et, harmDevSlope=0.01, minSineDur=.02):\n\n\tif (minSineDur <0): # raise exception if minSineDur is smaller than 0\n\t\traise ValueError(\"Minimum duration of sine tracks smaller than 0\")\n\t\t\n\t#hN = fft_size / 2 # size of positive spectrum\n\thM1 = int(math.floor((window.size + 1) / 2)) # half analysis window size by rounding\n\thM2 = int(math.floor(window.size / 2)) # half analysis window size by floor\n\tx = np.append(np.zeros(hM2), x) # add zeros at beginning to center first window at sample 0\n\tx = np.append(x, np.zeros(hM2)) # add zeros at the end to analyze last sample\n\tpin = hM1 # init sound pointer in middle of anal window \n\tpend = x.size - hM1 # last sample to start a frame\n\t#fftbuffer = np.zeros(fft_size) # initialize buffer for FFT\n\twindow = window / sum(window) # normalize analysis window\n\thfreqp = [] # initialize harmonic frequencies of previous frame\n\tf0t = 0 # initialize f0 track\n\tf0stable = 0 # initialize f0 stable\n\n\twhile pin<=pend:\n\t\t#print(\"pin:\", pin, \" pend:\", pend)\n\t\tx1 = x[pin-hM1:pin+hM2] # select frame\n\t\t#--------- harmonic Analysis frame\n\t\t# mX, pX = DFT.dftAnal(x1, w, N) # compute dft \n\t\t# ploc = UF.peakDetection(mX, t) # detect peak locations \n\t\t# iploc, ipmag, ipphase = UF.peakInterp(mX, pX, ploc) # refine peak values\n\t\t# ipfreq = fs * iploc/N # convert locations to Hz\n\t\t# f0t = UF.f0Twm(ipfreq, ipmag, f0et, minf0, maxf0, f0stable) # find f0\n\t\t# if ((f0stable==0)&(f0t>0)) \\\n\t\t# \t\tor ((f0stable>0)&(np.abs(f0stable-f0t)<f0stable/5.0)):\n\t\t# \tf0stable = f0t # consider a stable f0 if it is close to the previous one\n\t\t# else:\n\t\t# \tf0stable = 0\n\t\t# hfreq, hmag, hphase = harmonicDetection(ipfreq, ipmag, ipphase, f0t, nH, hfreqp, fs, harmDevSlope) # find harmonics\n\t\t#-----------\n\t\tuseTWM=0\n\t\tmX, f0stable, f0t, hfreq, hmag, hphase = harmonicModelAnalFrame (x1, window, fft_size, min_fft_val, fs, hfreqp, f0et, minf0, maxf0, nSines, f0stable, harmDevSlope, useTWM)\n\t\thfreqp = hfreq #hfreq(previous)\n\t\tif pin == hM1: # first frame\n\t\t\txhfreq = np.array([hfreq])\n\t\t\txhmag = np.array([hmag])\n\t\t\txhphase = np.array([hphase])\n\t\telse: # next frames\n\t\t\txhfreq = np.vstack((xhfreq,np.array([hfreq])))\n\t\t\txhmag = np.vstack((xhmag, np.array([hmag])))\n\t\t\txhphase = np.vstack((xhphase, np.array([hphase])))\n\t\tpin += hop_size # advance sound pointer\n\txhfreq = SM.cleaningSineTracks(xhfreq, round(fs * minSineDur / hop_size)) # delete tracks shorter than minSineDur\n\treturn xhfreq, xhmag, xhphase, f0stable", "def rickerwave(f = 25, length = 0.512, dt = 0.004): \n time = np.arange(-length/2, (length-dt)/2, dt)\n amplitude = (1.0 - 2.0*(np.pi**2)*(f**2)*(time**2))* \\\n np.exp(-(np.pi**2)*(f**2)*(time**2))\n return (time, amplitude)", "def wind_stress(uw, vw):\n \n nx = len(uw[:,0])\n ny = len(uw[0,:])\n nz = 2 \n Fx = numpy.zeros(((nz,nx,ny)))\n Fy = numpy.zeros(((nz,nx,ny)))\n k = 0.001\n Fx[1,:,:]= k*uw[:,:]*numpy.sqrt((uw[:,:]**2)+(vw[:,:]**2))\n Fy[1,:,:]= k*vw[:,:]*numpy.sqrt((uw[:,:]**2)+(vw[:,:]**2))\n return Fx, Fy", "def Y2W(r, Y, mode, F): #im ana, and i want to make some mess in my boyfriend's code :)\n\n [h, vr] = Y\n Fphi, Fz = F(r)[2:]\n\n kappa = mode.disk.kappa(r)\n Omega = mode.disk.Omega(r)\n Omegav = mode.disk.Omegav(r)\n dkappa = mode.disk.dkappa(r)\n c = mode.disk.cs\n \n m, n = mode.m, mode.n\n omegat = mode.omegat(r)\n \n [h, vr] = Y\n vphi = -(-2*h*m*Omega + 1j*(-2*Fphi*Omega*r**2 + kappa**2*r*vr))/(2.*Omega*omegat*r**2) \n vz = 1j*(c*Fz - h*n*Omegav)/(c*omegat) \t \n \n # solution vector:\n W = np.array([h, vr, vphi, vz])\n \n # derivatives of h and vr are calculated by calling ode_rhs:\n [dh, dvr] = ode_rhs(r, Y, mode, F)\n\n # derivative of the force:\n dFphi, dFz = F.der(r)[2:]\n \n # derivatives of the two other velocities are: \n \n dvphi = (-(-2*dh*m*Omega - 2*h*m*(kappa**2/(2.*Omega*r) - (2*Omega)/r) + \n 1j*(dvr*kappa**2*r - 4*Fphi*Omega*r - 2*dFphi*Omega*r**2 - \n 2*Fphi*(kappa**2/(2.*Omega*r) - (2*Omega)/r)*r**2 + kappa**2*vr + 2*dkappa*kappa*r*vr))/\n (2.*Omega*omegat*r**2) + (-2*h*m*Omega + 1j*(-2*Fphi*Omega*r**2 + kappa**2*r*vr))/\n (Omega*omegat*r**3) - (m*(kappa**2/(2.*Omega*r) - (2*Omega)/r)*\n (-2*h*m*Omega + 1j*(-2*Fphi*Omega*r**2 + kappa**2*r*vr)))/(2.*Omega*omegat**2*r**2) + \n ((kappa**2/(2.*Omega*r) - (2*Omega)/r)*(-2*h*m*Omega + 1j*(-2*Fphi*Omega*r**2 + kappa**2*r*vr)))/\n (2.*Omega**2*omegat*r**2))\n\n dvz = (0.5j*(c*(Fz*m*(kappa**2 - 4*Omega**2) + 2*dFz*Omega*omegat*r) - \n n*Omegav*(h*m*(kappa**2 - 4*Omega**2) + 2*dh*Omega*omegat*r)))/(c*Omega*omegat**2*r)\n \n dW =np.array([dh, dvr, dvphi, dvz])\n \n return [W, dW]", "def PF_effectiveDiff(x_in,w,kappa_phi,z=None,alpha=0,dy=None,kappa_y=0,dt=0.01):\n\n n = x_in.shape[0]\n kappa_eff = kappa_y + kappa_phi\n \n # particle diffusion\n x_in = x_in + np.pi # range between 0 and 2pi\n dx = np.random.normal(kappa_y/kappa_eff*dy,1/np.sqrt(kappa_eff) * np.sqrt(dt),n)\n x_out = x_in + dx\n x_out = (x_out % (2*np.pi) ) - np.pi # range between -pi and pi\n \n # compute weights\n if alpha != 0: # only compute weights and resample if there is an observation\n w = w * vonmises.pdf(x_out, alpha,loc=z)\n w = w/np.sum(w)\n #resampling\n N_eff = 1/np.sum(w**2)\n if N_eff/n < 0.5:\n x_out = np.random.choice(x_out,n,p=w)\n w = 1/n * np.ones(n)\n \n return x_out, w", "def fourier_series(x, *a):\n output = 0\n output += a[0]/2\n w = a[1]\n for n in range(2, len(a), 2):\n n_ = n/2\n val1 = a[n]\n val2 = a[n+1]\n output += val1*np.sin(n_*x*w)\n output += val2*np.cos(n_*x*w)\n return output", "def derive_variables(self, window, freq):\r\n \r\n length = len(self.price)\r\n window = window # time window for FFM regression model\r\n freq = freq # frequency of regression calibration\r\n \r\n sp = pd.Series(-1, index=self.price.index)\r\n # sp: Equals 1 when the slope of price trend is significantly positive\r\n sn = pd.Series(-1, index=self.price.index)\r\n # sn: Equals 1 when the slope of price trend is significantly negative \r\n c_f = pd.Series(0.0, index=self.price.index)\r\n # c_f: forecast close from linear model using previous 14 close\r\n fo = pd.Series(0.0, index=self.price.index)\r\n # fo: forecast oscillator\r\n ma3 = pd.Series(0.0, index=self.price.index)\r\n # 3-day mover average of the forecast oscillator\r\n lu = pd.Series(-1, index=self.price.index)\r\n # equals 1 when the oscillator crosses upward over its ma3\r\n ld = pd.Series(-1, index=self.price.index)\r\n # equals 1 when the oscillator crosses downward over its ma3\r\n \r\n up_moment = pd.Series(0.0, index=self.price.index)\r\n # up-day moment, equal |close_t - close_t-1| if close_t > close_t-1 o.w. 0\r\n down_moment = pd.Series(0.0, index=self.price.index)\r\n # down-day moment, equal |close_t - close_t-1| if close_t < close_t-1 o.w. 0\r\n ud = pd.Series(-1, index=self.price.index)\r\n # equals 1 when the closing price of the index is up at the present day\r\n aud = pd.Series(-1, index=self.price.index)\r\n # equals 1 when the closing prices are either up or down consecutively \r\n # for at least 3 days\r\n \r\n upd = pd.Series(0, index=self.price.index)\r\n # equals 1 when the closing price of next day exceeds present day\r\n dnd = pd.Series(0, index=self.price.index)\r\n # equals 1 when the closing price of next day is less than present day\r\n \r\n sd = pd.Series(0.0, index=self.price.index)\r\n # up-day moment over 14-days\r\n su = pd.Series(0.0, index=self.price.index)\r\n # down-day moment over 14-days\r\n rsi = pd.Series(0.0, index=self.price.index)\r\n # relative strength index\r\n rsi_h = pd.Series(0.0, index=self.price.index)\r\n # highest RSI over past 14 days (incl. current)\r\n rsi_l = pd.Series(0.0, index=self.price.index)\r\n # lowest RSI over past 14 days (incl. current)\r\n stoch_rsi = pd.Series(0.0, index=self.price.index)\r\n # stochastic RSI\r\n \r\n rsi1 = pd.Series(-1, index=self.price.index)\r\n # equals 1 when the stochastic RSI falls from 100\r\n rsi2 = pd.Series(-1, index=self.price.index)\r\n # equals 1 when the stochastic RSI rises from 0\r\n rsi3 = pd.Series(-1, index=self.price.index)\r\n # equals 1 when the stochastic RSI is greater than 90\r\n rsi4 = pd.Series(-1, index=self.price.index)\r\n # equals 1 when the stochastic RSI is less than 10\r\n \r\n x = sm.add_constant(range(1, window+1)) # prepare x for regression\r\n \r\n # below variables start at index window, since regression takes window data points to start\r\n for t in range(window, length):\r\n if t % freq == 0:\r\n y = self.price[(t - window):t].values\r\n # run regression and evaluate beta and p-value\r\n model = regression.linear_model.OLS(y, x).fit()\r\n if model.params[1] > 0 and model.pvalues[1] < 0.05:\r\n sp[t] = 1 \r\n elif model.params[1] < 0 and model.pvalues[1] < 0.05:\r\n sn[t] = 1 \r\n x1 = (1, window+1) # prepare X for one-step forecast\r\n c_f[t] = np.dot(x1, model.params) # forecast price using regression\r\n fo[t] = 100*(self.price[t] - c_f[t])/self.price[t]\r\n\r\n # below variables start at index window+2, since ma3 takes another 2 data points to start\r\n for t in range(window + 2, length):\r\n ma3[t] = (fo[t] + fo[t-1] + fo[t-2])/3\r\n if fo[t-1] < ma3[t-1] and fo[t] > ma3[t]: \r\n lu[t] = 1 # fo cross upward over ma3\r\n elif fo[t-1] > ma3[t-1] and fo[t] < ma3[t]:\r\n ld[t] = 1 # fo cross downward over ma3\r\n \r\n # below variables start at index 1\r\n for t in range(1, length):\r\n if self.price[t] > self.price[t-1]:\r\n up_moment[t] = abs(self.price[t] - self.price[t-1])\r\n ud[t] = 1\r\n elif self.price[t] < self.price[t-1]:\r\n down_moment[t] = abs(self.price[t] - self.price[t-1])\r\n\r\n # below variables start at index 3\r\n for t in range(3, length):\r\n if ((self.price[t] > self.price[t-1] > self.price[t-2] > self.price[t-3]) or\r\n (self.price[t] < self.price[t-1] < self.price[t-2] < self.price[t-3])):\r\n aud[t] = 1\r\n \r\n # below variables start at index 0 till index length - 1\r\n for t in range(0, length - 1):\r\n if self.price[t+1] > self.price[t]:\r\n upd[t] = 1 # equals 0 otherwise\r\n elif self.price[t+1] < self.price[t]:\r\n dnd[t] = 1 # equals 0 otherwise\r\n \r\n # below variables start at index window, since up_moment & down_moment takes\r\n # 1 data point to start, and RSI takes (window-1) to start\r\n # All three include time t value\r\n for t in range(window, length):\r\n su[t] = up_moment[t - window + 1:t + 1].sum()\r\n sd[t] = down_moment[t - window + 1:t + 1].sum()\r\n rsi[t] = 100 * su[t] / (su[t] + sd[t])\r\n '''corrected RSI formula from original paper'''\r\n \r\n # below variables start at index 2*window-1, since rsi_h and rsi_l take\r\n # another (window-1) data points to start\r\n # All three include time t value\r\n for t in range(2*window - 1, length):\r\n rsi_h[t] = max(rsi[t - window + 1:t + 1])\r\n rsi_l[t] = min(rsi[t - window + 1:t + 1])\r\n stoch_rsi[t] = (100 * (rsi[t] - rsi_l[t]) / (rsi_h[t] - rsi_l[t]))\r\n \r\n # below variables start at index 2*window-1, since stoch_rsi takes 2*window-1 data points to start\r\n for t in range(2*window - 1, length):\r\n if stoch_rsi[t-1] == 100.0 and stoch_rsi[t] < 100.0:\r\n rsi1[t] = 1\r\n elif stoch_rsi[t-1] == 0.0 and stoch_rsi[t] > 0.0:\r\n rsi2[t] = 1\r\n if stoch_rsi[t] > 90.0:\r\n rsi3[t] = 1\r\n elif stoch_rsi[t] < 10.0:\r\n rsi4[t] = 1\r\n \r\n # append calculated variables to price and define data frames\r\n self.intermediate_vars = pd.concat([self.price, c_f, fo, ma3, up_moment,\r\n down_moment, su, sd, rsi, rsi_h, rsi_l,\r\n stoch_rsi], axis=1).iloc[2*window - 1:, ]\r\n self.intermediate_vars.columns = [\"close\", \"forec_close\", \"forecast_oscillator\",\r\n \"ma3\", \"up_moment\", \"down_moment\", \"su\", \"sd\",\r\n \"rsi\", \"rsi_h\", \"rsi_l\", \"stoch_rsi\"]\r\n self.sample = pd.concat([self.price, sp, sn, lu, ld, ud, aud, upd, dnd, \r\n rsi1, rsi2, rsi3, rsi4], axis=1).iloc[2*window - 1:, ]\r\n self.sample.columns = [\"close\", \"sp\", \"sn\", \"lu\", \"ld\", \"ud\", \"aud\",\r\n \"upd\", \"dnd\", \"rsi1\", \"rsi2\", \"rsi3\", \"rsi4\"]\r\n \r\n return self.sample" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculate wave solution using 8th finite difference
def solve_wave_FD8(U,Up,h,c,ncpml,b,psi,phi): ny , nx = U.shape for i in range(4,ny-4): for j in range(4,nx-4): Up[i,j] = 2.0*U[i,j] - Up[i,j] + c[i-4,j-4]* \ ((-9*U[i,j-4]+128*U[i,j-3]-1008*U[i,j-2]+8064*U[i,j-1]-14350*U[i,j+0]+8064*U[i,j+1]-1008*U[i,j+2]+128*U[i,j+3]-9*U[i,j+4])+ \ (-9*U[i-4,j]+128*U[i-3,j]-1008*U[i-2,j]+8064*U[i-1,j]-14350*U[i+0,j]+8064*U[i+1,j]-1008*U[i+2,j]+128*U[i+3,j]-9*U[i+4,j]))/ \ (5040*1.0*h**2) #CPML boundary in X-domain for i in range(4+ncpml,ny-ncpml-4): for j in range(4,ncpml+1): phi[i,j]=b[j-1]*phi[i,j]+(b[j-1]-1.0)*(U[i,j+1]-U[i,j])/h phi[i,-j-1]=b[j-1]*phi[i,-j-1]+(b[j-1]-1.0)*(U[i,-j-1]-U[i,-j-2])/h for j in range(4,ncpml): psi[i,j]=b[j-1]*psi[i,j]+(b[j-1]-1.0)*\ ((U[i,j-1]-2*U[i,j]+U[i,j+1])/h/h \ +(phi[i,j+1]-phi[i,j])/h) psi[i,-j-1]=b[j-1]*psi[i,-j-1]+(b[j-1]-1.0)*\ ((U[i,-j-2]-2*U[i,-j-1]+U[i,-j])/h/h \ +(phi[i,-j-1]-phi[i,-j-2])/h) Up[i,j] += c[i-4,j-4]*((phi[i,j+1]-phi[i,j])/h+psi[i,j]) Up[i,-j-1] += c[i-4,-j-5]*((phi[i,-j-1]-phi[i,-j-2])/h+psi[i,-j-1]) #CPML boundary in Y-domain for i in range(4,ncpml+1): for j in range(4,nx-4): phi[i,j]=b[i-1]*phi[i,j]+(b[i-1]-1.0)*(U[i+1,j]-U[i,j])/h phi[-i-1,j]=b[i-1]*phi[-i-1,j]+(b[i-1]-1.0)*(U[-i-1,j]-U[-i-2,j])/h for i in range(4,ncpml): for j in range(4,nx-4): psi[i,j]=b[i-1]*psi[i,j]+(b[i-1]-1.0)*\ ((U[i-1,j]-2*U[i,j]+U[i+1,j])/h/h \ +(phi[i+1,j]-phi[i,j])/h) psi[-i-1,j]=b[i-1]*psi[-i-1,j]+(b[i-1]-1.0)*\ ((U[-i-2,j]-2*U[-i-1,j]+U[-i,j])/h/h \ +(phi[-i-1,j]-phi[-i-2,j])/h) Up[i,j] += c[i-4,j-4]*((phi[i+1,j]-phi[i,j])/h+psi[i,j]) Up[-i-1,j] += c[-i-5,j-4]*((phi[-i-1,j]-phi[-i-2,j])/h+psi[-i-1,j])
[ "def solve_wave_FD16(U,Up,h,c,ncpml,b,psi,phi):\n ny , nx = U.shape\n for i in range(8,ny-8):\n for j in range(8,nx-8):\n Up[i,j] = 2.0*U[i,j] - Up[i,j] + c[i-8,j-8]* \\\n ((-735*U[i-8,j]+15360*U[i-7,j]-156800*U[i-6,j]+1053696*U[i-5,j]-5350800*U[i-4,j]+22830080*U[i-3,j]-94174080*U[i-2,j]+538137600*U[i-1,j]-924708642*U[i+0,j]+538137600*U[i+1,j]-94174080*U[i+2,j]+22830080*U[i+3,j]-5350800*U[i+4,j]+1053696*U[i+5,j]-156800*U[i+6,j]+15360*U[i+7,j]-735*U[i+8,j])+ \\\n (-735*U[i,j-8]+15360*U[i,j-7]-156800*U[i,j-6]+1053696*U[i,j-5]-5350800*U[i,j-4]+22830080*U[i,j-3]-94174080*U[i,j-2]+538137600*U[i,j-1]-924708642*U[i,j+0]+538137600*U[i,j+1]-94174080*U[i,j+2]+22830080*U[i,j+3]-5350800*U[i,j+4]+1053696*U[i,j+5]-156800*U[i,j+6]+15360*U[i,j+7]-735*U[i,j+8]))/ \\\n (302702400*1.0*h**2)\n \n #CPML boundary in X-domain\n for i in range(8+ncpml,ny-ncpml-8):\n for j in range(8,ncpml+1):\n phi[i,j]=b[j-8]*phi[i,j]+(b[j-8]-1.0)*(U[i,j+1]-U[i,j])/h\n phi[i,-j-1]=b[j-8]*phi[i,-j-1]+(b[j-8]-1.0)*(U[i,-j-1]-U[i,-j-2])/h\n for j in range(8,ncpml):\n psi[i,j]=b[j-8]*psi[i,j]+(b[j-8]-1.0)*\\\n ((U[i,j-1]-2*U[i,j]+U[i,j+1])/h/h \\\n +(phi[i,j+1]-phi[i,j])/h)\n psi[i,-j-1]=b[j-8]*psi[i,-j-1]+(b[j-8]-1.0)*\\\n ((U[i,-j-2]-2*U[i,-j-1]+U[i,-j])/h/h \\\n +(phi[i,-j-1]-phi[i,-j-2])/h)\n Up[i,j] += c[i-8,j-8]*((phi[i,j+1]-phi[i,j])/h+psi[i,j])\n Up[i,-j-1] += c[i-8,-j-9]*((phi[i,-j-1]-phi[i,-j-2])/h+psi[i,-j-1])\n \n #CPML boundary in Y-domain\n for i in range(8,ncpml+1):\n for j in range(8,nx-8):\n phi[i,j]=b[i-8]*phi[i,j]+(b[i-8]-1.0)*(U[i+1,j]-U[i,j])/h\n phi[-i-1,j]=b[i-8]*phi[-i-1,j]+(b[i-8]-1.0)*(U[-i-1,j]-U[-i-2,j])/h\n for i in range(8,ncpml):\n for j in range(8,nx-8):\n psi[i,j]=b[i-8]*psi[i,j]+(b[i-8]-1.0)*\\\n ((U[i-1,j]-2*U[i,j]+U[i+1,j])/h/h \\\n +(phi[i+1,j]-phi[i,j])/h)\n psi[-i-1,j]=b[i-8]*psi[-i-1,j]+(b[i-8]-1.0)*\\\n ((U[-i-2,j]-2*U[-i-1,j]+U[-i,j])/h/h \\\n +(phi[-i-1,j]-phi[-i-2,j])/h)\n \n Up[i,j] += c[i-8,j-8]*((phi[i+1,j]-phi[i,j])/h+psi[i,j])\n Up[-i-1,j] += c[-i-9,j-8]*((phi[-i-1,j]-phi[-i-2,j])/h+psi[-i-1,j])", "def solve_wave_FD12(U,Up,h,c,ncpml,b,psi,phi):\n ny , nx = U.shape\n for i in range(6,ny-6):\n for j in range(6,nx-6):\n Up[i,j] = 2.0*U[i,j] - Up[i,j] + c[i-8,j-6]* \\\n ((-50*U[i-6,j]+864*U[i-5,j]-7425*U[i-4,j]+44000*U[i-3,j]-222750*U[i-2,j]+1425600*U[i-1,j]-2480478*U[i+0,j]+1425600*U[i+1,j]-222750*U[i+2,j]+44000*U[i+3,j]-7425*U[i+4,j]+864*U[i+5,j]-50*U[i+6,j])+ \\\n (-50*U[i,j-6]+864*U[i,j-5]-7425*U[i,j-4]+44000*U[i,j-3]-222750*U[i,j-2]+1425600*U[i,j-1]-2480478*U[i,j+0]+1425600*U[i,j+1]-222750*U[i,j+2]+44000*U[i,j+3]-7425*U[i,j+4]+864*U[i,j+5]-50*U[i,j+6]))/ \\\n (831600*1.0*h**2)\n \n #CPML boundary in X-domain\n for i in range(6+ncpml,ny-ncpml-6):\n for j in range(6,ncpml+1):\n phi[i,j]=b[j-1]*phi[i,j]+(b[j-1]-1.0)*(U[i,j+1]-U[i,j])/h\n phi[i,-j-1]=b[j-1]*phi[i,-j-1]+(b[j-1]-1.0)*(U[i,-j-1]-U[i,-j-2])/h\n for j in range(6,ncpml):\n psi[i,j]=b[j-1]*psi[i,j]+(b[j-1]-1.0)*\\\n ((U[i,j-1]-2*U[i,j]+U[i,j+1])/h/h \\\n +(phi[i,j+1]-phi[i,j])/h)\n psi[i,-j-1]=b[j-1]*psi[i,-j-1]+(b[j-1]-1.0)*\\\n ((U[i,-j-2]-2*U[i,-j-1]+U[i,-j])/h/h \\\n +(phi[i,-j-1]-phi[i,-j-2])/h)\n Up[i,j] += c[i-6,j-6]*((phi[i,j+1]-phi[i,j])/h+psi[i,j])\n Up[i,-j-1] += c[i-6,-j-7]*((phi[i,-j-1]-phi[i,-j-2])/h+psi[i,-j-1])\n \n #CPML boundary in Y-domain\n for i in range(6,ncpml+1):\n for j in range(6,nx-6):\n phi[i,j]=b[i-1]*phi[i,j]+(b[i-1]-1.0)*(U[i+1,j]-U[i,j])/h\n phi[-i-1,j]=b[i-1]*phi[-i-1,j]+(b[i-1]-1.0)*(U[-i-1,j]-U[-i-2,j])/h\n for i in range(6,ncpml):\n for j in range(6,nx-6):\n psi[i,j]=b[i-1]*psi[i,j]+(b[i-1]-1.0)*\\\n ((U[i-1,j]-2*U[i,j]+U[i+1,j])/h/h \\\n +(phi[i+1,j]-phi[i,j])/h)\n psi[-i-1,j]=b[i-1]*psi[-i-1,j]+(b[i-1]-1.0)*\\\n ((U[-i-2,j]-2*U[-i-1,j]+U[-i,j])/h/h \\\n +(phi[-i-1,j]-phi[-i-2,j])/h)\n Up[i,j] += c[i-6,j-6]*((phi[i+1,j]-phi[i,j])/h+psi[i,j])\n Up[-i-1,j] += c[-i-7,j-6]*((phi[-i-1,j]-phi[-i-2,j])/h+psi[-i-1,j])", "def solve_wave_FD4(U,Up,h,c,ncpml,b,psi,phi):\n ny , nx = U.shape\n for i in range(2,ny-2):\n for j in range(2,nx-2):\n Up[i,j] = 2.0*U[i,j] - Up[i,j] + c[i-2,j-2]* \\\n ((-1*U[i-2,j]+16*U[i-1,j]-30*U[i,j]+16*U[i+1,j]-1*U[i+2,j]) + \\\n (-1*U[i,j-2]+16*U[i,j-1]-30*U[i,j]+16*U[i,j+1]-1*U[i,j+2]))/ \\\n (12*1.0*h**2)\n #CPML boundary in X-domain\n for i in range(2+ncpml,ny-ncpml-2):\n for j in range(2,ncpml+1):\n phi[i,j]=b[j-1]*phi[i,j]+(b[j-1]-1.0)*(U[i,j+1]-U[i,j])/h\n phi[i,-j-1]=b[j-1]*phi[i,-j-1]+(b[j-1]-1.0)*(U[i,-j-1]-U[i,-j-2])/h\n for j in range(2,ncpml):\n psi[i,j]=b[j-1]*psi[i,j]+(b[j-1]-1.0)*\\\n ((U[i,j-1]-2*U[i,j]+U[i,j+1])/h/h \\\n +(phi[i,j+1]-phi[i,j])/h)\n psi[i,-j-1]=b[j-1]*psi[i,-j-1]+(b[j-1]-1.0)*\\\n ((U[i,-j-2]-2*U[i,-j-1]+U[i,-j])/h/h \\\n +(phi[i,-j-1]-phi[i,-j-2])/h)\n Up[i,j] += c[i-2,j-2]*((phi[i,j+1]-phi[i,j])/h+psi[i,j])\n Up[i,-j-1] += c[i-2,-j-3]*((phi[i,-j-1]-phi[i,-j-2])/h+psi[i,-j-1])\n \n #CPML boundary in Y-domain\n for i in range(2,ncpml+1):\n for j in range(2,nx-2):\n phi[i,j]=b[i-1]*phi[i,j]+(b[i-1]-1.0)*(U[i+1,j]-U[i,j])/h\n phi[-i-1,j]=b[i-1]*phi[-i-1,j]+(b[i-1]-1.0)*(U[-i-1,j]-U[-i-2,j])/h\n for i in range(2,ncpml):\n for j in range(2,nx-2):\n psi[i,j]=b[i-1]*psi[i,j]+(b[i-1]-1.0)*\\\n ((U[i-1,j]-2*U[i,j]+U[i+1,j])/h/h \\\n +(phi[i+1,j]-phi[i,j])/h)\n psi[-i-1,j]=b[i-1]*psi[-i-1,j]+(b[i-1]-1.0)*\\\n ((U[-i-2,j]-2*U[-i-1,j]+U[-i,j])/h/h \\\n +(phi[-i-1,j]-phi[-i-2,j])/h)\n Up[i,j] += c[i-2,j-2]*((phi[i+1,j]-phi[i,j])/h+psi[i,j])\n Up[-i-1,j] += c[-i-3,j-2]*((phi[-i-1,j]-phi[-i-2,j])/h+psi[-i-1,j])", "def wah_wah(x, fs):\n\n # buffer size\n wah_length = fs * 2\n\n # damping factor\n # lower the damping factor the smaller the pass band\n damp = 1.8\n\n # min and max centre cutoff frequency of variable bandpass filter\n minf = 500\n maxf = 3000\n\n # wah frequency, how many Hz per second are cycled through\n fw = 2000\n #########################################################################\n\n # change in centre frequency per sample (Hz)\n # delta = 0.2\n delta = fw / fs \n #0.1 => at 44100 samples per second should mean 4.41kHz Fc shift per sec\n\n # create triangle wave of centre frequency values\n fc = np.arange(minf, maxf, delta)\n while len(fc) < len(x):\n fc = np.append(fc, np.arange(maxf, minf, -delta))\n fc = np.append(fc, np.arange(minf, maxf, delta))\n \n # trim tri wave to size of input\n fc = fc[:len(x)]\n\n # difference equation coefficients\n F1 = 2 * np.sin((np.pi * fc[1]) / fs) # must be recalculated each time Fc changes\n Q1 = 2 * damp # this dictates size of the pass bands\n\n yh = np.zeros(x.shape[0]) # create emptly out vectors\n yb = np.zeros(x.shape[0])\n yl = np.zeros(x.shape[0])\n\n # first sample, to avoid referencing of negative signals\n yh[1] = x[1]\n yb[1] = F1 * yh[1]\n yl[1] = F1 * yb[1]\n\n # apply difference equation to the sample\n for n in range(2, len(x) - 1):\n yh[n] = x[n] - yl[n - 1] - Q1 * yb[n - 1]\n yb[n] = F1 * yh[n] + yb[n - 1]\n yl[n] = F1 * yb[n] + yl[n - 1]\n \n F1 = 2 * np.sin((np.pi * fc[n]) / fs)\n\n #normalise\n maxyb = max(abs(yb))\n y = yb / (maxyb + Epsilon)\n\n return shape_check(y)", "def wfDerivative(signalRaw,sp=10.):\n signalDeriv = np.zeros(len(signalRaw))\n for i in range(len(signalRaw)-1):\n signalDeriv[i] = (signalRaw[i+1] - signalRaw[i])/sp\n return signalDeriv", "def solve_wave_FD2(U,Up,h,c,ncpml,b,psi,phi):\n ny , nx = U.shape\n for i in range(1,ny-1):\n for j in range(1,nx-1):\n Up[i,j] = 2.0*U[i,j] - Up[i,j] + c[i-1,j-1]* \\\n (U[i-1,j]-2*U[i,j]+U[i+1,j]+ \\\n (U[i,j-1]-2*U[i,j]+U[i,j+1]))/h/h\n #CPML boundary in X-domain\n for i in range(1+ncpml,ny-ncpml-1):\n for j in range(1,ncpml+1):\n phi[i,j]=b[j-1]*phi[i,j]+(b[j-1]-1.0)*(U[i,j+1]-U[i,j])/h\n phi[i,-j-1]=b[j-1]*phi[i,-j-1]+(b[j-1]-1.0)*(U[i,-j-1]-U[i,-j-2])/h\n for j in range(1,ncpml):\n psi[i,j]=b[j-1]*psi[i,j]+(b[j-1]-1.0)*\\\n ((U[i,j-1]-2*U[i,j]+U[i,j+1])/h/h \\\n +(phi[i,j+1]-phi[i,j])/h)\n psi[i,-j-1]=b[j-1]*psi[i,-j-1]+(b[j-1]-1.0)*\\\n ((U[i,-j-2]-2*U[i,-j-1]+U[i,-j])/h/h \\\n +(phi[i,-j-1]-phi[i,-j-2])/h)\n Up[i,j] += c[i-1,j-1]*((phi[i,j+1]-phi[i,j])/h+psi[i,j])\n Up[i,-j-1] += c[i-1,-j-2]*((phi[i,-j-1]-phi[i,-j-2])/h+psi[i,-j-1])\n \n #CPML boundary in Y-domain\n for i in range(1,ncpml+1):\n for j in range(1,nx-1):\n phi[i,j]=b[i-1]*phi[i,j]+(b[i-1]-1.0)*(U[i+1,j]-U[i,j])/h\n phi[-i-1,j]=b[i-1]*phi[-i-1,j]+(b[i-1]-1.0)*(U[-i-1,j]-U[-i-2,j])/h\n for i in range(1,ncpml):\n for j in range(1,nx-1):\n psi[i,j]=b[i-1]*psi[i,j]+(b[i-1]-1.0)*\\\n ((U[i-1,j]-2*U[i,j]+U[i+1,j])/h/h \\\n +(phi[i+1,j]-phi[i,j])/h)\n psi[-i-1,j]=b[i-1]*psi[-i-1,j]+(b[i-1]-1.0)*\\\n ((U[-i-2,j]-2*U[-i-1,j]+U[-i,j])/h/h \\\n +(phi[-i-1,j]-phi[-i-2,j])/h)\n Up[i,j] += c[i-1,j-1]*((phi[i+1,j]-phi[i,j])/h+psi[i,j])\n Up[-i-1,j] += c[-i-2,j-1]*((phi[-i-1,j]-phi[-i-2,j])/h+psi[-i-1,j])", "def solver(I, w, dt, T, V, f):\n dt = float(dt)\n Nt = int(round(T/dt)) # 100000\n u = np.zeros(Nt+1)\n t = np.linspace(0, Nt*dt, Nt+1)\n\n u[0] = I\n u[1] = u[0] + dt*V + 0.5*(f(t[0]) - w**2*u[0])*dt**2#compute first step by 1'st order difference\n for n in range(1, Nt):\n u[n+1] = (f(t[n])-w**2*u[n])*dt**2 + 2*u[n]-u[n-1]\n return u, t", "def flw3i8s(ex, ey, ez, ep, D, ed):\n ir = ep[0]\n ngp = ir*ir*ir\n\n if ir == 2:\n g1 = 0.577350269189626\n w1 = 1\n gp = np.mat([\n [-1, -1, -1],\n [1, -1, -1],\n [1, 1, -1],\n [-1, 1, -1],\n [-1, -1, 1],\n [1, -1, 1],\n [1, 1, 1],\n [-1, 1, 1]\n ])*g1\n w = np.mat(np.ones((8, 3)))*w1\n elif ir == 3:\n g1 = 0.774596669241483\n g2 = 0.\n w1 = 0.555555555555555\n w2 = 0.888888888888888\n gp = np.mat(np.zeros((27, 3)))\n w = np.mat(np.zeros((27, 3)))\n I1 = np.array([-1, 0, 1, -1, 0, 1, -1, 0, 1])\n I2 = np.array([0, -1, 0, 0, 1, 0, 0, 1, 0])\n gp[:, 0] = np.mat([I1, I1, I1]).reshape(27, 1)*g1\n gp[:, 0] = np.mat([I2, I2, I2]).reshape(27, 1)*g2+gp[:, 0]\n I1 = abs(I1)\n I2 = abs(I2)\n w[:, 0] = np.mat([I1, I1, I1]).reshape(27, 1)*w1\n w[:, 0] = np.mat([I2, I2, I2]).reshape(27, 1)*w2+w[:, 0]\n I1 = np.array([-1, -1, -1, 0, 0, 0, 1, 1, 1])\n I2 = np.array([0, 0, 0, 1, 1, 1, 0, 0, 0])\n gp[:, 1] = np.mat([I1, I1, I1]).reshape(27, 1)*g1\n gp[:, 1] = np.mat([I2, I2, I2]).reshape(27, 1)*g2+gp[:, 1]\n I1 = abs(I1)\n I2 = abs(I2)\n w[:, 1] = np.mat([I1, I1, I1]).reshape(27, 1)*w1\n w[:, 1] = np.mat([I2, I2, I2]).reshape(27, 1)*w2+w[:, 1]\n I1 = np.array([-1, -1, -1, -1, -1, -1, -1, -1, -1])\n I2 = np.array([0, 0, 0, 0, 0, 0, 0, 0, 0])\n I3 = abs(I1)\n gp[:, 2] = np.mat([I1, I2, I3]).reshape(27, 1)*g1\n gp[:, 2] = np.mat([I2, I3, I2]).reshape(27, 1)*g2+gp[:, 2]\n w[:, 2] = np.mat([I3, I2, I3]).reshape(27, 1)*w1\n w[:, 2] = np.mat([I2, I3, I2]).reshape(27, 1)*w2+w[:, 2]\n else:\n info(\"Used number of integration points not implemented\")\n return\n\n wp = np.multiply(np.multiply(w[:, 0], w[:, 1]), w[:, 2])\n\n xsi = gp[:, 0]\n eta = gp[:, 1]\n zet = gp[:, 2]\n r2 = ngp*3\n\n N = np.multiply(np.multiply((1-xsi), (1-eta)), (1-zet))/8.\n N = np.append(N, np.multiply(np.multiply(\n (1+xsi), (1-eta)), (1-zet))/8., axis=1)\n N = np.append(N, np.multiply(np.multiply(\n (1+xsi), (1+eta)), (1-zet))/8., axis=1)\n N = np.append(N, np.multiply(np.multiply(\n (1-xsi), (1+eta)), (1-zet))/8., axis=1)\n N = np.append(N, np.multiply(np.multiply(\n (1-xsi), (1-eta)), (1+zet))/8., axis=1)\n N = np.append(N, np.multiply(np.multiply(\n (1+xsi), (1-eta)), (1+zet))/8., axis=1)\n N = np.append(N, np.multiply(np.multiply(\n (1+xsi), (1+eta)), (1+zet))/8., axis=1)\n N = np.append(N, np.multiply(np.multiply(\n (1-xsi), (1+eta)), (1+zet))/8., axis=1)\n\n dNr = np.mat(np.zeros((r2, 8)))\n dNr[0:r2:3, 0] = np.multiply(-(1-eta), (1-zet))\n dNr[0:r2:3, 1] = np.multiply((1-eta), (1-zet))\n dNr[0:r2:3, 2] = np.multiply((1+eta), (1-zet))\n dNr[0:r2:3, 3] = np.multiply(-(1+eta), (1-zet))\n dNr[0:r2:3, 4] = np.multiply(-(1-eta), (1+zet))\n dNr[0:r2:3, 5] = np.multiply((1-eta), (1+zet))\n dNr[0:r2:3, 6] = np.multiply((1+eta), (1+zet))\n dNr[0:r2:3, 7] = np.multiply(-(1+eta), (1+zet))\n dNr[1:r2+1:3, 0] = np.multiply(-(1-xsi), (1-zet))\n dNr[1:r2+1:3, 1] = np.multiply(-(1+xsi), (1-zet))\n dNr[1:r2+1:3, 2] = np.multiply((1+xsi), (1-zet))\n dNr[1:r2+1:3, 3] = np.multiply((1-xsi), (1-zet))\n dNr[1:r2+1:3, 4] = np.multiply(-(1-xsi), (1+zet))\n dNr[1:r2+1:3, 5] = np.multiply(-(1+xsi), (1+zet))\n dNr[1:r2+1:3, 6] = np.multiply((1+xsi), (1+zet))\n dNr[1:r2+1:3, 7] = np.multiply((1-xsi), (1+zet))\n dNr[2:r2+2:3, 0] = np.multiply(-(1-xsi), (1-eta))\n dNr[2:r2+2:3, 1] = np.multiply(-(1+xsi), (1-eta))\n dNr[2:r2+2:3, 2] = np.multiply(-(1+xsi), (1+eta))\n dNr[2:r2+2:3, 3] = np.multiply(-(1-xsi), (1+eta))\n dNr[2:r2+2:3, 4] = np.multiply((1-xsi), (1-eta))\n dNr[2:r2+2:3, 5] = np.multiply((1+xsi), (1-eta))\n dNr[2:r2+2:3, 6] = np.multiply((1+xsi), (1+eta))\n dNr[2:r2+2:3, 7] = np.multiply((1-xsi), (1+eta))\n dNr = dNr/8.\n\n eci = N*np.mat([ex, ey, ez]).T\n if ed.ndim == 1:\n ed = np.array([ed])\n red, ced = np.shape(ed)\n JT = dNr*np.mat([ex, ey, ez]).T\n\n es = np.mat(np.zeros((ngp*red, 3)))\n et = np.mat(np.zeros((ngp*red, 3)))\n for i in range(ngp):\n indx = np.array([3*(i+1)-2, 3*(i+1)-1, 3*(i+1)])\n detJ = np.linalg.det(JT[indx-1, :])\n if detJ < 10*np.finfo(float).eps:\n info(\"Jacobideterminanten lika med noll!\")\n JTinv = np.linalg.inv(JT[indx-1, :])\n B = JTinv*dNr[indx-1, :]\n p1 = -D*B*ed.T\n p2 = B*ed.T\n es[i:ngp*red:ngp, :] = p1.T\n et[i:ngp*red:ngp, :] = p2.T\n\n return es, et, eci", "def find_s0(wavelet, dt):\n def f(s):\n return wavelet.fourier_period(s) - 2 * dt\n return scipy.optimize.fsolve(f, 1)[0]", "def rickerwave(f = 25, length = 0.512, dt = 0.004): \n time = np.arange(-length/2, (length-dt)/2, dt)\n amplitude = (1.0 - 2.0*(np.pi**2)*(f**2)*(time**2))* \\\n np.exp(-(np.pi**2)*(f**2)*(time**2))\n return (time, amplitude)", "def get_time_audio_signal(fs, wave):\n return np.arange(wave.size)/float(fs)", "def waveElevIrreg(self,rampTime,dt,maxIt,df):\n t = np.arange(maxIt+1)*dt # array of time with dt time steps\n initialZeros = np.zeros((maxIt+1))\n self.waveAmpTime = [t,initialZeros]\n maxRampIT=int(np.round(rampTime/dt))\n iiter = np.size(self.waveDir)\n tmp = np.sqrt(np.matlib.repmat(self.A,iiter,1)*np.matlib.repmat(df,iiter,1)*np.transpose([self.waveSpread,]))\n c1 = np.matlib.repmat(self.w,iiter,1) # matlib.repmat method that repeats arrays which results in matrix form of arrays\n if rampTime == 0:\n for i in range(maxIt+1): # keeping for loop was faster than changing it to all matrix computation even when there were multiple wave direction\n t = (i)*dt\n tmp1 = tmp*np.real(np.exp(((-1)**0.5)*(c1*t + self.phase))) \n self.waveAmpTime[1][i] = np.sum(tmp1)\n else:\n for i in range(maxRampIT):\n t = (i)*dt\n tmp1 = tmp*np.real(np.exp(((-1)**0.5)*(c1*t + self.phase))) \n ad = (1+np.cos(np.pi+np.pi*(i)/maxRampIT))/2\n self.waveAmpTime[1][i] = np.sum(np.sum(tmp1, axis=1)*ad)\n for i in range(maxRampIT, maxIt+1):\n t = (i)*dt\n tmp1 = tmp*np.real(np.exp(((-1)**0.5)*(c1*t + self.phase))) \n self.waveAmpTime[1][i] = np.sum(tmp1)\n self.waveAmpTime1 = self.waveAmpTime # if wave guage location is not set, wave elevation is same as waveAmpTime\n self.waveAmpTime2 = self.waveAmpTime # if wave guage location is not set, wave elevation is same as waveAmpTime\n self.waveAmpTime3 = self.waveAmpTime # if wave guage location is not set, wave elevation is same as waveAmpTime \n if self.wavegauge1loc[0] != 0 or self.wavegauge1loc[1] != 0 or self.wavegauge2loc[0] != 0 or self.wavegauge2loc[1] != 0 or self.wavegauge3loc[0] != 0 or self.wavegauge3loc[1] != 0:\n c2 = np.matlib.repmat(self.k,iiter,1)\n c_cos = np.cos(np.transpose([self.waveDir,])*np.pi/180)\n c_sin = np.sin(np.transpose([self.waveDir,])*np.pi/180)\n t = np.arange(maxIt+1)*dt # array of time with dt time steps\n self.waveAmpTime1 = [t,np.zeros((maxIt+1))] # set to arrays of zero get an error if it is not set individually\n self.waveAmpTime2 = [t,np.zeros((maxIt+1))] # set to arrays of zero get an error if it is not set individually\n self.waveAmpTime3 = [t,np.zeros((maxIt+1))] # set to arrays of zero get an error if it is not set individually\n if rampTime == 0:\n for i in range(maxIt+1):\n t = (i)*dt\n tmp11 = tmp*np.real(np.exp(((-1)**0.5)*(c1*t - c2*(self.wavegauge1loc[0]*c_cos + self.wavegauge1loc[1]*c_sin) + self.phase)))\n tmp12 = tmp*np.real(np.exp(((-1)**0.5)*(c1*t - c2*(self.wavegauge2loc[0]*c_cos + self.wavegauge2loc[1]*c_sin) + self.phase)))\n tmp13 = tmp*np.real(np.exp(((-1)**0.5)*(c1*t - c2*(self.wavegauge3loc[0]*c_cos + self.wavegauge3loc[1]*c_sin) + self.phase)))\n self.waveAmpTime1[1][i] = np.sum(tmp11)\n self.waveAmpTime2[1][i] = np.sum(tmp12)\n self.waveAmpTime3[1][i] = np.sum(tmp13)\n else:\n for i in range(maxRampIT):\n t = (i)*dt\n tmp11 = tmp*np.real(np.exp(((-1)**0.5)*(c1*t - c2*(self.wavegauge1loc[0]*c_cos + self.wavegauge1loc[1]*c_sin) + self.phase)))\n tmp12 = tmp*np.real(np.exp(((-1)**0.5)*(c1*t - c2*(self.wavegauge2loc[0]*c_cos + self.wavegauge2loc[1]*c_sin) + self.phase)))\n tmp13 = tmp*np.real(np.exp(((-1)**0.5)*(c1*t - c2*(self.wavegauge3loc[0]*c_cos + self.wavegauge3loc[1]*c_sin) + self.phase)))\n ad = (1+np.cos(np.pi+np.pi*(i)/maxRampIT))/2\n self.waveAmpTime1[1][i] = np.sum(np.sum(tmp11, axis=1)*ad)\n self.waveAmpTime2[1][i] = np.sum(np.sum(tmp12, axis=1)*ad)\n self.waveAmpTime3[1][i] = np.sum(np.sum(tmp13, axis=1)*ad)\n for i in range(maxRampIT, maxIt+1):\n t = (i)*dt\n tmp11 = tmp*np.real(np.exp(((-1)**0.5)*(c1*t - c2*(self.wavegauge1loc[0]*c_cos + self.wavegauge1loc[1]*c_sin) + self.phase)))\n tmp12 = tmp*np.real(np.exp(((-1)**0.5)*(c1*t - c2*(self.wavegauge2loc[0]*c_cos + self.wavegauge2loc[1]*c_sin) + self.phase)))\n tmp13 = tmp*np.real(np.exp(((-1)**0.5)*(c1*t - c2*(self.wavegauge3loc[0]*c_cos + self.wavegauge3loc[1]*c_sin) + self.phase)))\n self.waveAmpTime1[1][i] = np.sum(tmp11)\n self.waveAmpTime2[1][i] = np.sum(tmp12)\n self.waveAmpTime3[1][i] = np.sum(tmp13)", "def soli8s(ex, ey, ez, ep, D, ed):\n\n ir = ep[0]\n ngp = ir*ir*ir\n\n ir = ep[0]\n ngp = ir*ir*ir\n\n if ir == 1:\n g1 = 0.0\n w1 = 2.0\n gp = np.array([g1, g1, g1]).reshape(1, 3)\n w = np.array([w1, w1, w1]).reshape(1, 3)\n elif ir == 2:\n g1 = 0.577350269189626\n w1 = 1\n gp = np.zeros((8, 3))\n w = np.zeros((8, 3))\n gp[:, 0] = np.array([-1, 1, 1, -1, -1, 1, 1, -1])*g1\n w[:, 0] = np.array([1, 1, 1, 1, 1, 1, 1, 1])*w1\n gp[:, 1] = np.array([-1, -1, 1, 1, -1, -1, 1, 1])*g1\n w[:, 1] = np.array([1, 1, 1, 1, 1, 1, 1, 1])*w1\n gp[:, 2] = np.array([-1, -1, -1, -1, 1, 1, 1, 1])*g1\n w[:, 2] = np.array([1, 1, 1, 1, 1, 1, 1, 1])*w1\n else:\n g1 = 0.774596669241483,\n g2 = 0.0\n w1 = 0.555555555555555\n w2 = 0.888888888888888\n\n gp = np.zeros((27, 3))\n w = np.zeros((27, 3))\n\n I1 = np.array([-1, 0, 1, -1, 0, 1, -1, 0, 1]).reshape(1, 9)\n I2 = np.array([0, -1, 0, 0, 1, 0, 0, 1, 0]).reshape(1, 9)\n\n gp[:, 0] = np.concatenate((I1, I1, I1), axis=1)*g1\n gp[:, 0] = np.concatenate((I2, I2, I2), axis=1)*g2 + gp[:, 0]\n\n I1 = np.abs(I1)\n I2 = np.abs(I2)\n\n w[:, 0] = np.concatenate((I1, I1, I1), axis=1)*w1\n w[:, 0] = np.concatenate((I2, I2, I2), axis=1)*w2 + w[:, 0]\n\n I1 = np.array([-1, -1, -1, 0, 0, 0, 1, 1, 1]).reshape(1, 9)\n I2 = np.array([0, 0, 0, 1, 1, 1, 0, 0, 0]).reshape(1, 9)\n\n gp[:, 1] = np.concatenate((I1, I1, I1), axis=1)*g1\n gp[:, 1] = np.concatenate((I2, I2, I2), axis=1)*g2 + gp[:, 1]\n\n I1 = np.abs(I1)\n I2 = np.abs(I2)\n\n w[:, 1] = np.concatenate((I1, I1, I1), axis=1)*w1\n w[:, 1] = np.concatenate((I2, I2, I2), axis=1)*w2 + w[:, 1]\n\n I1 = np.array([-1, -1, -1, -1, -1, -1, -1, -1, -1]).reshape(1, 9)\n I2 = np.array([0, 0, 0, 0, 0, 0, 0, 0, 0]).reshape(1, 9)\n I3 = np.abs(I1)\n\n gp[:, 2] = np.concatenate((I1, I2, I3), axis=1)*g1\n gp[:, 2] = np.concatenate((I2, I3, I2), axis=1)*g2 + gp[:, 2]\n\n w[:, 2] = np.concatenate((I3, I2, I3), axis=1)*w1\n w[:, 2] = np.concatenate((I2, I3, I2), axis=1)*w2 + w[:, 2]\n\n wp = w[:, 0]*w[:, 1]*w[:, 2]\n\n xsi = gp[:, 0]\n eta = gp[:, 1]\n zet = gp[:, 2]\n r2 = ngp*3\n\n N = np.zeros((ngp, 8))\n dNr = np.zeros((r2, 8))\n\n N[:, 0] = (1-xsi)*(1-eta)*(1-zet)/8\n N[:, 1] = (1+xsi)*(1-eta)*(1-zet)/8\n N[:, 2] = (1+xsi)*(1+eta)*(1-zet)/8\n N[:, 3] = (1-xsi)*(1+eta)*(1-zet)/8\n N[:, 4] = (1-xsi)*(1-eta)*(1+zet)/8\n N[:, 5] = (1+xsi)*(1-eta)*(1+zet)/8\n N[:, 6] = (1+xsi)*(1+eta)*(1+zet)/8\n N[:, 7] = (1-xsi)*(1+eta)*(1+zet)/8\n\n dNr[0:r2+1:3, 0] = -(1-eta)*(1-zet)\n dNr[0:r2+1:3, 1] = (1-eta)*(1-zet)\n dNr[0:r2+1:3, 2] = (1+eta)*(1-zet)\n dNr[0:r2+1:3, 3] = -(1+eta)*(1-zet)\n dNr[0:r2+1:3, 4] = -(1-eta)*(1+zet)\n dNr[0:r2+1:3, 5] = (1-eta)*(1+zet)\n dNr[0:r2+1:3, 6] = (1+eta)*(1+zet)\n dNr[0:r2+1:3, 7] = -(1+eta)*(1+zet)\n dNr[1:r2+2:3, 0] = -(1-xsi)*(1-zet)\n dNr[1:r2+2:3, 1] = -(1+xsi)*(1-zet)\n dNr[1:r2+2:3, 2] = (1+xsi)*(1-zet)\n dNr[1:r2+2:3, 3] = (1-xsi)*(1-zet)\n dNr[1:r2+2:3, 4] = -(1-xsi)*(1+zet)\n dNr[1:r2+2:3, 5] = -(1+xsi)*(1+zet)\n dNr[1:r2+2:3, 6] = (1+xsi)*(1+zet)\n dNr[1:r2+2:3, 7] = (1-xsi)*(1+zet)\n dNr[2:r2+3:3, 0] = -(1-xsi)*(1-eta)\n dNr[2:r2+3:3, 1] = -(1+xsi)*(1-eta)\n dNr[2:r2+3:3, 2] = -(1+xsi)*(1+eta)\n dNr[2:r2+3:3, 3] = -(1-xsi)*(1+eta)\n dNr[2:r2+3:3, 4] = (1-xsi)*(1-eta)\n dNr[2:r2+3:3, 5] = (1+xsi)*(1-eta)\n dNr[2:r2+3:3, 6] = (1+xsi)*(1+eta)\n dNr[2:r2+3:3, 7] = (1-xsi)*(1+eta)\n\n dNr = dNr/8.0\n\n ex = np.asarray(ex).reshape((8, 1))\n ey = np.asarray(ey).reshape((8, 1))\n ez = np.asarray(ez).reshape((8, 1))\n\n JT = dNr@np.concatenate((ex, ey, ez), axis=1)\n\n eps = np.finfo(float).eps\n \n eci = N@np.concatenate((ex, ey, ez), axis=1)\n et = np.zeros((ngp, 6))\n es = np.zeros((ngp, 6))\n\n ed = ed.reshape(1, 24)\n\n for i in range(ngp):\n indx = [i*3, i*3+1, i*3+2]\n detJ = np.linalg.det(JT[indx, :])\n if detJ < 10*eps:\n print('Jacobideterminant equal or less than zero!')\n JTinv = np.linalg.inv(JT[indx, :])\n dNx = JTinv@dNr[indx, :]\n\n B = np.zeros((6, 24))\n N2 = np.zeros((3, 24))\n\n B[0, 0:24:3] = dNx[0, :]\n B[1, 1:25:3] = dNx[1, :]\n B[2, 2:26:3] = dNx[2, :]\n B[3, 0:24:3] = dNx[1, :]\n B[3, 1:25:3] = dNx[0, :]\n B[4, 0:24:3] = dNx[2, :]\n B[4, 2:26:3] = dNx[0, :]\n B[5, 1:25:3] = dNx[2, :]\n B[5, 2:26:3] = dNx[1, :]\n\n N2[0, 0:24:3] = N[i, :]\n N2[1, 1:25:3] = N[i, :]\n N2[2, 2:26:3] = N[i, :]\n\n # [6x24] x [24,1]\n ee = B@np.transpose(ed)\n\n et[i, :] = ee.reshape(6,)\n es[i, :] = (D@ee).reshape(6,)\n\n return et, es, eci", "def test_wavefunc(file):\n filedir = \"__testfiles__/\" + file\n interpdata = sol.input_reader(filedir)[1]\n x_min, x_max = interpdata[:2]\n length = x_max - x_min\n methode, potar = sol.input_reader(filedir)[2:4]\n eigmin, eigmax = sol.input_reader(filedir)[4:6]\n x_vals = sol.potential_interpolate(interpdata, methode, potar)[:, 0]\n # getting the wavefunctions for the specific problem from data or equations\n wavefuncsmat = np.empty((len(x_vals), eigmax - eigmin + 1))\n if file == \"test_infpot.txt\":\n for nn in range(eigmin, eigmax + 1):\n wavefuncs = []\n if nn % 2 == 0:\n for val in enumerate(x_vals):\n wavefunc = np.sqrt(2 / length) * np.sin(nn * np.pi /\n length * val[1])\n wavefuncs.append(wavefunc)\n else:\n for val in enumerate(x_vals):\n wavefunc = np.sqrt(2 / length) * np.cos(nn * np.pi /\n length * val[1])\n wavefuncs.append(wavefunc)\n wavefuncsmat[:, nn - 1] = wavefuncs\n elif file == \"test_harmonic.txt\":\n wavefuncsmat = np.loadtxt\\\n (\"__unittestfiles__/test_harmonic_wf.dat\")[:, 1:]\n elif file == \"test_pot.txt\":\n wavefuncsmat = np.loadtxt\\\n (\"__unittestfiles__/test_pot_wf.dat\")[:, 1:]\n elif file == \"test_dualpot_lin.txt\":\n wavefuncsmat = np.loadtxt\\\n (\"__unittestfiles__/test_dualpot_lin_wf.dat\")[:, 1:]\n elif file == \"test_dualpot_cspline.txt\":\n wavefuncsmat = np.loadtxt\\\n (\"__unittestfiles__/test_dualpot_cspline_wf.dat\")[:, 1:]\n elif file == \"test_asympot.txt\":\n wavefuncsmat = np.loadtxt\\\n (\"__unittestfiles__/test_asympot_wf.dat\")[:, 1:]\n else:\n wavefuncsmat = np.ones((len(x_vals), eigmax - eigmin + 1))\n # checking if the norm of the wavefunctions is equal to testdata\n sol.run(filedir, \"__output__\")\n testwavefuncs = np.loadtxt(\"__output__/wavefuncs.dat\")[:, 1:]\n assert np.all(np.abs(np.abs(wavefuncsmat)**2 - np.abs(testwavefuncs)**2)\n < ERROR)", "def test_getNewTimes_with_half_phase_two_day_bin():\n times = np.random.uniform(0, 10, 75)\n newtimes = wm.getNewTimes(times, 2.)\n newtimes2 = wm.getNewTimes(times, 2., phase=0.5)\n assert np.round((np.min(newtimes2) - np.min(newtimes)), 7) == 1.000", "def _sigma8_dyn(self, z, w0 = -1, wa = 0, pkarray = None, npoints = 513):\n #print('In sigma8_dyn, the Om used is:')\n #print(self._Om)\n if pkarray != None:\n kh, z, P = pkarray\n else:\n kh, z, P = self._p(z, w0, wa, npoints = npoints)[:-1] #Default value of power spectrum is obtained from CAMB\n itgd = P * (3 * special.spherical_jn(1, kh * 8)/(kh * 8)) ** 2 * (kh ** 2)\n integ = integrate.simps(itgd, x = kh)\n integ = np.sqrt(integ/(2 * (np.pi) ** 2))\n return z, integ", "def waveElevNowave(self,maxIt,dt):\n t = np.arange(maxIt+1)*dt\n initialZeros = np.zeros((maxIt+1))\n self.waveAmpTime = [t,initialZeros] # since this is for no wave type wave height will be all zeros\n self.waveAmpTime1 = self.waveAmpTime # since this is for no wave type wave height will be all zeros\n self.waveAmpTime2 = self.waveAmpTime # since this is for no wave type wave height will be all zeros\n self.waveAmpTime3 = self.waveAmpTime # since this is for no wave type wave height will be all zeros", "def waviness(self):\n if self.fibre_l > 0:\n return self.euclid_l / self.fibre_l\n return np.nan", "def bounds(step_test, delta_phi_star):\n\n # define integration for one step\n def step_integrate(phi0, u_val, step):\n \"\"\" function that integrates one step forward. returns final phase,\n total shift value \"\"\"\n def dphidt(phi, t):\n return ((2*np.pi)/pmodel.T\n - u_val*prc_spl(start_time+(phi)*pmodel.T/(2*np.pi)))\n\n int_times = np.linspace(0,step,101) # in hours\n phis = integrate.odeint(dphidt, [phi0], int_times, hmax=0.01)\n return int_times, phis, phis[-1][0]-phi0-2*np.pi/pmodel.T*step\n\n # find the max advance or delay in each cycle\n def dphitot_dt(phis, t):\n [phi_osc_pos, phi_osc_neg, phi_shift_pos, phi_shift_neg] = phis\n dphi_osc_pos_dt = (2*np.pi)/pmodel.T +\\\n umax*prc_pos_spl(phi_osc_pos*pmodel.T/(2*np.pi))\n dphi_osc_neg_dt = (2*np.pi)/pmodel.T +\\\n umax*prc_neg_spl(phi_osc_neg*pmodel.T/(2*np.pi))\n dphi_shft_pos_dt = umax*prc_pos_spl(phi_osc_pos*pmodel.T/(2*np.pi))\n dphi_shft_neg_dt = umax*prc_neg_spl(phi_osc_neg*pmodel.T/(2*np.pi))\n return dphi_osc_pos_dt, dphi_osc_neg_dt, dphi_shft_pos_dt, dphi_shft_neg_dt\n\n int_times = np.linspace(0,200, 10001)\n delta_phis_total = integrate.odeint(dphitot_dt, [0,0,0,0], int_times,\n hmax=0.001)\n phis_adv = delta_phis_total[:,0]\n phis_del = delta_phis_total[:,1]\n advs = delta_phis_total[:,2]\n dels = delta_phis_total[:,3]\n delta_phi_star_calc = delta_phis_total[np.min(\n np.where(delta_phis_total[:,2]-delta_phis_total[:,3]>2*np.pi)\n ), 2]\n\n # max 1 cycle advances are where the oscillator reaches 0 again\n max_1cyc_adv = advs[np.min(\n np.where(phis_adv>2*np.pi)[0]\n )]\n max_1cyc_del = dels[np.min(\n np.where(phis_del>2*np.pi)[0]\n )]\n\n\n\n def loss_zero_cross(umax, stepsize, cross=6, start_bound=[0,12]):\n \"\"\"\n calculates the max loss for a specific zero-crossing of the PRC\n \"\"\"\n # first, find where the pulse lines up the worst\n def min_shift(init):\n init = init[0]\n times, phases, shift = step_integrate(init*2*np.pi/pmodel.T,\n umax, stepsize)\n return np.abs(shift)\n # get alignment\n mins = optimize.minimize(min_shift, cross, bounds = [start_bound])\n even_start = mins.x[0]\n\n times, phases, shift = step_integrate(even_start*2*np.pi/pmodel.T,\n umax, stepsize)\n stim_PRC = prc_spl(start_time+phases*pmodel.T/(2*np.pi))\n ePRC = interpolate.UnivariateSpline(times, stim_PRC, k=3, s=0)\n loss = np.max(umax*np.abs(integrate.cumtrapz(ePRC(times), times)))\n zero_cross = times[np.argmax(umax*np.abs(integrate.cumtrapz(ePRC(times),\n times)))]\n return even_start, zero_cross, loss\n\n\n # find the loss for each crossing, where it starts, where it crosses\n zero_neg_start, zero_neg_cross, loss_neg = loss_zero_cross(0.06, step_test)\n zero_pos_start, zero_pos_cross, loss_pos = loss_zero_cross(0.06, step_test,\n cross=22, start_bound=[18,27])\n\n adv_per_cycle = max_1cyc_adv - loss_neg - loss_pos\n del_per_cycle = max_1cyc_del + loss_neg + loss_pos\n\n # for the advance, there is also the slowdown loss - the phase advance lost\n # by the oscillator not advancing\n slowdown_pos = np.abs(step_integrate(zero_pos_start*2*np.pi/pmodel.T,\n 0.06, zero_pos_cross)[-1])\n slowdown_neg = np.abs(step_integrate(zero_neg_start*2*np.pi/pmodel.T,\n 0.06, zero_neg_cross)[-1])\n # slowdown_loss is how much phase shift we miss at most due to this\n def max_shift_pos(init):\n init = init[0]\n times, phases, shift = step_integrate(init*2*np.pi/pmodel.T,\n umax, slowdown_pos*pmodel.T/(2*np.pi))\n return -shift\n def max_shift_neg(init):\n init = init[0]\n times, phases, shift = step_integrate(init*2*np.pi/pmodel.T,\n umax, slowdown_neg*pmodel.T/(2*np.pi))\n return shift\n\n pos_loss_maximization = optimize.minimize(max_shift_pos, [0], bounds=[[0,8]])\n neg_loss_maximization = optimize.minimize(max_shift_neg, [0], bounds=[[12,24]])\n slowdown_pos_loss = pos_loss_maximization.fun\n slowdown_neg_loss = neg_loss_maximization.fun\n\n\n # figure out the direction and number of cycle bounds\n delta_phi_fs = np.arange(-2*np.pi,2*np.pi,0.01)\n adv_del = [] #0 if advance, 1 if delay\n numcycles = []\n del_phis = []\n directions = []\n regions_missed = []\n cyc_to_reachs = []\n for delta_phi in delta_phi_fs:\n direction = int(delta_phi > delta_phi_star)\n if delta_phi>0:\n ncyc = 1 + delta_phi//max_1cyc_adv\n cyc_to_reach = 1 + delta_phi//adv_per_cycle\n adv_del.append(0)\n # upper limit of how much can be missed\n region_missed = (ncyc)*(\n np.abs(slowdown_pos_loss+slowdown_pos_loss)+loss_neg+loss_pos)\n del_phi = region_missed\n elif delta_phi<=0:\n ncyc = 1+ -delta_phi//-max_1cyc_del\n cyc_to_reach = 1+ -delta_phi//-del_per_cycle\n adv_del.append(1)\n # upper limit of how much can be missed\n region_missed = (ncyc)*(loss_neg+loss_pos)\n # will the minimum achieved be better or worse than the max lost\n del_phi = region_missed\n\n del_phis.append(del_phi)\n directions.append(direction)\n numcycles.append(ncyc)\n cyc_to_reachs.append(cyc_to_reach)\n regions_missed.append(region_missed)\n\n result_dict = {'delta_phi_fs' : delta_phi_fs,\n 'directions' : directions,\n 'numcycles' : numcycles,\n 'regions_missed' : regions_missed,\n 'cyc_to_reachs' : cyc_to_reachs,\n 'del_phis' : del_phis}\n\n return result_dict" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculate wave solution using 4th order finite difference
def solve_wave_FD4(U,Up,h,c,ncpml,b,psi,phi): ny , nx = U.shape for i in range(2,ny-2): for j in range(2,nx-2): Up[i,j] = 2.0*U[i,j] - Up[i,j] + c[i-2,j-2]* \ ((-1*U[i-2,j]+16*U[i-1,j]-30*U[i,j]+16*U[i+1,j]-1*U[i+2,j]) + \ (-1*U[i,j-2]+16*U[i,j-1]-30*U[i,j]+16*U[i,j+1]-1*U[i,j+2]))/ \ (12*1.0*h**2) #CPML boundary in X-domain for i in range(2+ncpml,ny-ncpml-2): for j in range(2,ncpml+1): phi[i,j]=b[j-1]*phi[i,j]+(b[j-1]-1.0)*(U[i,j+1]-U[i,j])/h phi[i,-j-1]=b[j-1]*phi[i,-j-1]+(b[j-1]-1.0)*(U[i,-j-1]-U[i,-j-2])/h for j in range(2,ncpml): psi[i,j]=b[j-1]*psi[i,j]+(b[j-1]-1.0)*\ ((U[i,j-1]-2*U[i,j]+U[i,j+1])/h/h \ +(phi[i,j+1]-phi[i,j])/h) psi[i,-j-1]=b[j-1]*psi[i,-j-1]+(b[j-1]-1.0)*\ ((U[i,-j-2]-2*U[i,-j-1]+U[i,-j])/h/h \ +(phi[i,-j-1]-phi[i,-j-2])/h) Up[i,j] += c[i-2,j-2]*((phi[i,j+1]-phi[i,j])/h+psi[i,j]) Up[i,-j-1] += c[i-2,-j-3]*((phi[i,-j-1]-phi[i,-j-2])/h+psi[i,-j-1]) #CPML boundary in Y-domain for i in range(2,ncpml+1): for j in range(2,nx-2): phi[i,j]=b[i-1]*phi[i,j]+(b[i-1]-1.0)*(U[i+1,j]-U[i,j])/h phi[-i-1,j]=b[i-1]*phi[-i-1,j]+(b[i-1]-1.0)*(U[-i-1,j]-U[-i-2,j])/h for i in range(2,ncpml): for j in range(2,nx-2): psi[i,j]=b[i-1]*psi[i,j]+(b[i-1]-1.0)*\ ((U[i-1,j]-2*U[i,j]+U[i+1,j])/h/h \ +(phi[i+1,j]-phi[i,j])/h) psi[-i-1,j]=b[i-1]*psi[-i-1,j]+(b[i-1]-1.0)*\ ((U[-i-2,j]-2*U[-i-1,j]+U[-i,j])/h/h \ +(phi[-i-1,j]-phi[-i-2,j])/h) Up[i,j] += c[i-2,j-2]*((phi[i+1,j]-phi[i,j])/h+psi[i,j]) Up[-i-1,j] += c[-i-3,j-2]*((phi[-i-1,j]-phi[-i-2,j])/h+psi[-i-1,j])
[ "def solve_wave_FD12(U,Up,h,c,ncpml,b,psi,phi):\n ny , nx = U.shape\n for i in range(6,ny-6):\n for j in range(6,nx-6):\n Up[i,j] = 2.0*U[i,j] - Up[i,j] + c[i-8,j-6]* \\\n ((-50*U[i-6,j]+864*U[i-5,j]-7425*U[i-4,j]+44000*U[i-3,j]-222750*U[i-2,j]+1425600*U[i-1,j]-2480478*U[i+0,j]+1425600*U[i+1,j]-222750*U[i+2,j]+44000*U[i+3,j]-7425*U[i+4,j]+864*U[i+5,j]-50*U[i+6,j])+ \\\n (-50*U[i,j-6]+864*U[i,j-5]-7425*U[i,j-4]+44000*U[i,j-3]-222750*U[i,j-2]+1425600*U[i,j-1]-2480478*U[i,j+0]+1425600*U[i,j+1]-222750*U[i,j+2]+44000*U[i,j+3]-7425*U[i,j+4]+864*U[i,j+5]-50*U[i,j+6]))/ \\\n (831600*1.0*h**2)\n \n #CPML boundary in X-domain\n for i in range(6+ncpml,ny-ncpml-6):\n for j in range(6,ncpml+1):\n phi[i,j]=b[j-1]*phi[i,j]+(b[j-1]-1.0)*(U[i,j+1]-U[i,j])/h\n phi[i,-j-1]=b[j-1]*phi[i,-j-1]+(b[j-1]-1.0)*(U[i,-j-1]-U[i,-j-2])/h\n for j in range(6,ncpml):\n psi[i,j]=b[j-1]*psi[i,j]+(b[j-1]-1.0)*\\\n ((U[i,j-1]-2*U[i,j]+U[i,j+1])/h/h \\\n +(phi[i,j+1]-phi[i,j])/h)\n psi[i,-j-1]=b[j-1]*psi[i,-j-1]+(b[j-1]-1.0)*\\\n ((U[i,-j-2]-2*U[i,-j-1]+U[i,-j])/h/h \\\n +(phi[i,-j-1]-phi[i,-j-2])/h)\n Up[i,j] += c[i-6,j-6]*((phi[i,j+1]-phi[i,j])/h+psi[i,j])\n Up[i,-j-1] += c[i-6,-j-7]*((phi[i,-j-1]-phi[i,-j-2])/h+psi[i,-j-1])\n \n #CPML boundary in Y-domain\n for i in range(6,ncpml+1):\n for j in range(6,nx-6):\n phi[i,j]=b[i-1]*phi[i,j]+(b[i-1]-1.0)*(U[i+1,j]-U[i,j])/h\n phi[-i-1,j]=b[i-1]*phi[-i-1,j]+(b[i-1]-1.0)*(U[-i-1,j]-U[-i-2,j])/h\n for i in range(6,ncpml):\n for j in range(6,nx-6):\n psi[i,j]=b[i-1]*psi[i,j]+(b[i-1]-1.0)*\\\n ((U[i-1,j]-2*U[i,j]+U[i+1,j])/h/h \\\n +(phi[i+1,j]-phi[i,j])/h)\n psi[-i-1,j]=b[i-1]*psi[-i-1,j]+(b[i-1]-1.0)*\\\n ((U[-i-2,j]-2*U[-i-1,j]+U[-i,j])/h/h \\\n +(phi[-i-1,j]-phi[-i-2,j])/h)\n Up[i,j] += c[i-6,j-6]*((phi[i+1,j]-phi[i,j])/h+psi[i,j])\n Up[-i-1,j] += c[-i-7,j-6]*((phi[-i-1,j]-phi[-i-2,j])/h+psi[-i-1,j])", "def solve_wave_FD8(U,Up,h,c,ncpml,b,psi,phi):\n ny , nx = U.shape\n for i in range(4,ny-4):\n for j in range(4,nx-4):\n Up[i,j] = 2.0*U[i,j] - Up[i,j] + c[i-4,j-4]* \\\n ((-9*U[i,j-4]+128*U[i,j-3]-1008*U[i,j-2]+8064*U[i,j-1]-14350*U[i,j+0]+8064*U[i,j+1]-1008*U[i,j+2]+128*U[i,j+3]-9*U[i,j+4])+ \\\n (-9*U[i-4,j]+128*U[i-3,j]-1008*U[i-2,j]+8064*U[i-1,j]-14350*U[i+0,j]+8064*U[i+1,j]-1008*U[i+2,j]+128*U[i+3,j]-9*U[i+4,j]))/ \\\n (5040*1.0*h**2)\n \n #CPML boundary in X-domain\n for i in range(4+ncpml,ny-ncpml-4):\n for j in range(4,ncpml+1):\n phi[i,j]=b[j-1]*phi[i,j]+(b[j-1]-1.0)*(U[i,j+1]-U[i,j])/h\n phi[i,-j-1]=b[j-1]*phi[i,-j-1]+(b[j-1]-1.0)*(U[i,-j-1]-U[i,-j-2])/h\n for j in range(4,ncpml):\n psi[i,j]=b[j-1]*psi[i,j]+(b[j-1]-1.0)*\\\n ((U[i,j-1]-2*U[i,j]+U[i,j+1])/h/h \\\n +(phi[i,j+1]-phi[i,j])/h)\n psi[i,-j-1]=b[j-1]*psi[i,-j-1]+(b[j-1]-1.0)*\\\n ((U[i,-j-2]-2*U[i,-j-1]+U[i,-j])/h/h \\\n +(phi[i,-j-1]-phi[i,-j-2])/h)\n Up[i,j] += c[i-4,j-4]*((phi[i,j+1]-phi[i,j])/h+psi[i,j])\n Up[i,-j-1] += c[i-4,-j-5]*((phi[i,-j-1]-phi[i,-j-2])/h+psi[i,-j-1])\n \n #CPML boundary in Y-domain\n for i in range(4,ncpml+1):\n for j in range(4,nx-4):\n phi[i,j]=b[i-1]*phi[i,j]+(b[i-1]-1.0)*(U[i+1,j]-U[i,j])/h\n phi[-i-1,j]=b[i-1]*phi[-i-1,j]+(b[i-1]-1.0)*(U[-i-1,j]-U[-i-2,j])/h\n for i in range(4,ncpml):\n for j in range(4,nx-4):\n psi[i,j]=b[i-1]*psi[i,j]+(b[i-1]-1.0)*\\\n ((U[i-1,j]-2*U[i,j]+U[i+1,j])/h/h \\\n +(phi[i+1,j]-phi[i,j])/h)\n psi[-i-1,j]=b[i-1]*psi[-i-1,j]+(b[i-1]-1.0)*\\\n ((U[-i-2,j]-2*U[-i-1,j]+U[-i,j])/h/h \\\n +(phi[-i-1,j]-phi[-i-2,j])/h)\n Up[i,j] += c[i-4,j-4]*((phi[i+1,j]-phi[i,j])/h+psi[i,j])\n Up[-i-1,j] += c[-i-5,j-4]*((phi[-i-1,j]-phi[-i-2,j])/h+psi[-i-1,j])", "def solve_wave_FD16(U,Up,h,c,ncpml,b,psi,phi):\n ny , nx = U.shape\n for i in range(8,ny-8):\n for j in range(8,nx-8):\n Up[i,j] = 2.0*U[i,j] - Up[i,j] + c[i-8,j-8]* \\\n ((-735*U[i-8,j]+15360*U[i-7,j]-156800*U[i-6,j]+1053696*U[i-5,j]-5350800*U[i-4,j]+22830080*U[i-3,j]-94174080*U[i-2,j]+538137600*U[i-1,j]-924708642*U[i+0,j]+538137600*U[i+1,j]-94174080*U[i+2,j]+22830080*U[i+3,j]-5350800*U[i+4,j]+1053696*U[i+5,j]-156800*U[i+6,j]+15360*U[i+7,j]-735*U[i+8,j])+ \\\n (-735*U[i,j-8]+15360*U[i,j-7]-156800*U[i,j-6]+1053696*U[i,j-5]-5350800*U[i,j-4]+22830080*U[i,j-3]-94174080*U[i,j-2]+538137600*U[i,j-1]-924708642*U[i,j+0]+538137600*U[i,j+1]-94174080*U[i,j+2]+22830080*U[i,j+3]-5350800*U[i,j+4]+1053696*U[i,j+5]-156800*U[i,j+6]+15360*U[i,j+7]-735*U[i,j+8]))/ \\\n (302702400*1.0*h**2)\n \n #CPML boundary in X-domain\n for i in range(8+ncpml,ny-ncpml-8):\n for j in range(8,ncpml+1):\n phi[i,j]=b[j-8]*phi[i,j]+(b[j-8]-1.0)*(U[i,j+1]-U[i,j])/h\n phi[i,-j-1]=b[j-8]*phi[i,-j-1]+(b[j-8]-1.0)*(U[i,-j-1]-U[i,-j-2])/h\n for j in range(8,ncpml):\n psi[i,j]=b[j-8]*psi[i,j]+(b[j-8]-1.0)*\\\n ((U[i,j-1]-2*U[i,j]+U[i,j+1])/h/h \\\n +(phi[i,j+1]-phi[i,j])/h)\n psi[i,-j-1]=b[j-8]*psi[i,-j-1]+(b[j-8]-1.0)*\\\n ((U[i,-j-2]-2*U[i,-j-1]+U[i,-j])/h/h \\\n +(phi[i,-j-1]-phi[i,-j-2])/h)\n Up[i,j] += c[i-8,j-8]*((phi[i,j+1]-phi[i,j])/h+psi[i,j])\n Up[i,-j-1] += c[i-8,-j-9]*((phi[i,-j-1]-phi[i,-j-2])/h+psi[i,-j-1])\n \n #CPML boundary in Y-domain\n for i in range(8,ncpml+1):\n for j in range(8,nx-8):\n phi[i,j]=b[i-8]*phi[i,j]+(b[i-8]-1.0)*(U[i+1,j]-U[i,j])/h\n phi[-i-1,j]=b[i-8]*phi[-i-1,j]+(b[i-8]-1.0)*(U[-i-1,j]-U[-i-2,j])/h\n for i in range(8,ncpml):\n for j in range(8,nx-8):\n psi[i,j]=b[i-8]*psi[i,j]+(b[i-8]-1.0)*\\\n ((U[i-1,j]-2*U[i,j]+U[i+1,j])/h/h \\\n +(phi[i+1,j]-phi[i,j])/h)\n psi[-i-1,j]=b[i-8]*psi[-i-1,j]+(b[i-8]-1.0)*\\\n ((U[-i-2,j]-2*U[-i-1,j]+U[-i,j])/h/h \\\n +(phi[-i-1,j]-phi[-i-2,j])/h)\n \n Up[i,j] += c[i-8,j-8]*((phi[i+1,j]-phi[i,j])/h+psi[i,j])\n Up[-i-1,j] += c[-i-9,j-8]*((phi[-i-1,j]-phi[-i-2,j])/h+psi[-i-1,j])", "def solve_wave_FD2(U,Up,h,c,ncpml,b,psi,phi):\n ny , nx = U.shape\n for i in range(1,ny-1):\n for j in range(1,nx-1):\n Up[i,j] = 2.0*U[i,j] - Up[i,j] + c[i-1,j-1]* \\\n (U[i-1,j]-2*U[i,j]+U[i+1,j]+ \\\n (U[i,j-1]-2*U[i,j]+U[i,j+1]))/h/h\n #CPML boundary in X-domain\n for i in range(1+ncpml,ny-ncpml-1):\n for j in range(1,ncpml+1):\n phi[i,j]=b[j-1]*phi[i,j]+(b[j-1]-1.0)*(U[i,j+1]-U[i,j])/h\n phi[i,-j-1]=b[j-1]*phi[i,-j-1]+(b[j-1]-1.0)*(U[i,-j-1]-U[i,-j-2])/h\n for j in range(1,ncpml):\n psi[i,j]=b[j-1]*psi[i,j]+(b[j-1]-1.0)*\\\n ((U[i,j-1]-2*U[i,j]+U[i,j+1])/h/h \\\n +(phi[i,j+1]-phi[i,j])/h)\n psi[i,-j-1]=b[j-1]*psi[i,-j-1]+(b[j-1]-1.0)*\\\n ((U[i,-j-2]-2*U[i,-j-1]+U[i,-j])/h/h \\\n +(phi[i,-j-1]-phi[i,-j-2])/h)\n Up[i,j] += c[i-1,j-1]*((phi[i,j+1]-phi[i,j])/h+psi[i,j])\n Up[i,-j-1] += c[i-1,-j-2]*((phi[i,-j-1]-phi[i,-j-2])/h+psi[i,-j-1])\n \n #CPML boundary in Y-domain\n for i in range(1,ncpml+1):\n for j in range(1,nx-1):\n phi[i,j]=b[i-1]*phi[i,j]+(b[i-1]-1.0)*(U[i+1,j]-U[i,j])/h\n phi[-i-1,j]=b[i-1]*phi[-i-1,j]+(b[i-1]-1.0)*(U[-i-1,j]-U[-i-2,j])/h\n for i in range(1,ncpml):\n for j in range(1,nx-1):\n psi[i,j]=b[i-1]*psi[i,j]+(b[i-1]-1.0)*\\\n ((U[i-1,j]-2*U[i,j]+U[i+1,j])/h/h \\\n +(phi[i+1,j]-phi[i,j])/h)\n psi[-i-1,j]=b[i-1]*psi[-i-1,j]+(b[i-1]-1.0)*\\\n ((U[-i-2,j]-2*U[-i-1,j]+U[-i,j])/h/h \\\n +(phi[-i-1,j]-phi[-i-2,j])/h)\n Up[i,j] += c[i-1,j-1]*((phi[i+1,j]-phi[i,j])/h+psi[i,j])\n Up[-i-1,j] += c[-i-2,j-1]*((phi[-i-1,j]-phi[-i-2,j])/h+psi[-i-1,j])", "def solver(I, w, dt, T, V, f):\n dt = float(dt)\n Nt = int(round(T/dt)) # 100000\n u = np.zeros(Nt+1)\n t = np.linspace(0, Nt*dt, Nt+1)\n\n u[0] = I\n u[1] = u[0] + dt*V + 0.5*(f(t[0]) - w**2*u[0])*dt**2#compute first step by 1'st order difference\n for n in range(1, Nt):\n u[n+1] = (f(t[n])-w**2*u[n])*dt**2 + 2*u[n]-u[n-1]\n return u, t", "def wfDerivative(signalRaw,sp=10.):\n signalDeriv = np.zeros(len(signalRaw))\n for i in range(len(signalRaw)-1):\n signalDeriv[i] = (signalRaw[i+1] - signalRaw[i])/sp\n return signalDeriv", "def find_s0(wavelet, dt):\n def f(s):\n return wavelet.fourier_period(s) - 2 * dt\n return scipy.optimize.fsolve(f, 1)[0]", "def wah_wah(x, fs):\n\n # buffer size\n wah_length = fs * 2\n\n # damping factor\n # lower the damping factor the smaller the pass band\n damp = 1.8\n\n # min and max centre cutoff frequency of variable bandpass filter\n minf = 500\n maxf = 3000\n\n # wah frequency, how many Hz per second are cycled through\n fw = 2000\n #########################################################################\n\n # change in centre frequency per sample (Hz)\n # delta = 0.2\n delta = fw / fs \n #0.1 => at 44100 samples per second should mean 4.41kHz Fc shift per sec\n\n # create triangle wave of centre frequency values\n fc = np.arange(minf, maxf, delta)\n while len(fc) < len(x):\n fc = np.append(fc, np.arange(maxf, minf, -delta))\n fc = np.append(fc, np.arange(minf, maxf, delta))\n \n # trim tri wave to size of input\n fc = fc[:len(x)]\n\n # difference equation coefficients\n F1 = 2 * np.sin((np.pi * fc[1]) / fs) # must be recalculated each time Fc changes\n Q1 = 2 * damp # this dictates size of the pass bands\n\n yh = np.zeros(x.shape[0]) # create emptly out vectors\n yb = np.zeros(x.shape[0])\n yl = np.zeros(x.shape[0])\n\n # first sample, to avoid referencing of negative signals\n yh[1] = x[1]\n yb[1] = F1 * yh[1]\n yl[1] = F1 * yb[1]\n\n # apply difference equation to the sample\n for n in range(2, len(x) - 1):\n yh[n] = x[n] - yl[n - 1] - Q1 * yb[n - 1]\n yb[n] = F1 * yh[n] + yb[n - 1]\n yl[n] = F1 * yb[n] + yl[n - 1]\n \n F1 = 2 * np.sin((np.pi * fc[n]) / fs)\n\n #normalise\n maxyb = max(abs(yb))\n y = yb / (maxyb + Epsilon)\n\n return shape_check(y)", "def Y2W(r, Y, mode, F): #im ana, and i want to make some mess in my boyfriend's code :)\n\n [h, vr] = Y\n Fphi, Fz = F(r)[2:]\n\n kappa = mode.disk.kappa(r)\n Omega = mode.disk.Omega(r)\n Omegav = mode.disk.Omegav(r)\n dkappa = mode.disk.dkappa(r)\n c = mode.disk.cs\n \n m, n = mode.m, mode.n\n omegat = mode.omegat(r)\n \n [h, vr] = Y\n vphi = -(-2*h*m*Omega + 1j*(-2*Fphi*Omega*r**2 + kappa**2*r*vr))/(2.*Omega*omegat*r**2) \n vz = 1j*(c*Fz - h*n*Omegav)/(c*omegat) \t \n \n # solution vector:\n W = np.array([h, vr, vphi, vz])\n \n # derivatives of h and vr are calculated by calling ode_rhs:\n [dh, dvr] = ode_rhs(r, Y, mode, F)\n\n # derivative of the force:\n dFphi, dFz = F.der(r)[2:]\n \n # derivatives of the two other velocities are: \n \n dvphi = (-(-2*dh*m*Omega - 2*h*m*(kappa**2/(2.*Omega*r) - (2*Omega)/r) + \n 1j*(dvr*kappa**2*r - 4*Fphi*Omega*r - 2*dFphi*Omega*r**2 - \n 2*Fphi*(kappa**2/(2.*Omega*r) - (2*Omega)/r)*r**2 + kappa**2*vr + 2*dkappa*kappa*r*vr))/\n (2.*Omega*omegat*r**2) + (-2*h*m*Omega + 1j*(-2*Fphi*Omega*r**2 + kappa**2*r*vr))/\n (Omega*omegat*r**3) - (m*(kappa**2/(2.*Omega*r) - (2*Omega)/r)*\n (-2*h*m*Omega + 1j*(-2*Fphi*Omega*r**2 + kappa**2*r*vr)))/(2.*Omega*omegat**2*r**2) + \n ((kappa**2/(2.*Omega*r) - (2*Omega)/r)*(-2*h*m*Omega + 1j*(-2*Fphi*Omega*r**2 + kappa**2*r*vr)))/\n (2.*Omega**2*omegat*r**2))\n\n dvz = (0.5j*(c*(Fz*m*(kappa**2 - 4*Omega**2) + 2*dFz*Omega*omegat*r) - \n n*Omegav*(h*m*(kappa**2 - 4*Omega**2) + 2*dh*Omega*omegat*r)))/(c*Omega*omegat**2*r)\n \n dW =np.array([dh, dvr, dvphi, dvz])\n \n return [W, dW]", "def gen_powphase2d_old(si, phiF, rF, inner, outer, dx, dy, xW, yW, normfres=True, debug=True):\r\n # specified diffraction and refraction scales\r\n ld = rF / phiF \r\n lr = rF * phiF \r\n\r\n nx = int(xW/dx)\r\n ny = nx\r\n if debug: print 'targeted number of x,y samples = ', nx,ny\n \n #print \"nx\", nx\n #print \"ny\", ny\n \r\n xvec = (arange(0.,nx)-nx/2+1)*dx\r\n yvec = (arange(0.,ny)-ny/2+1)*dy\r\n\r\n dqx = 2.*pi / xW \r\n dqy = 2.*pi / yW\r\n qmaxx = (2.*pi) / (2.*dx)\r\n qmaxy = (2.*pi) / (2.*dy)\r\n\r\n nqx = 2*int(qmaxx/dqx)\r\n nqy = 2*int(qmaxy/dqy)\r\n if debug: print 'targeted number of q samples = ', nqx, nqy \r\n if nqx != nx: \r\n print \"Forcing nqx = nx = \", nx\r\n nqx = nx\r\n if nqy != ny: \r\n print \"Forcing nqy = ny = \", ny\r\n nqy = ny\r\n qxvec = (arange(0.,nqx)-nqx/2+1)*dqx\r\n qxvec = roll(qxvec,nqx/2+1)\r\n qyvec = (arange(0.,nqy)-nqy/2+1)*dqy\r\n qyvec = roll(qyvec,nqy/2+1)\r\n\r\n qin = 2.*pi / inner\r\n qout = 2.*pi / outer\r\n qshape = zeros((nqx, nqy))\r\n \r\n for i, qxi in enumerate(qxvec):\r\n for j, qyj in enumerate(qyvec):\r\n qsq = qxi**2 + qyj**2\r\n qshape[i,j] = (qout**2 + qsq)**(-si/4.) \r\n #qshape[i,j] = (qout**2 + qsq)**(-si/4.) * exp(-(qsq/(2.*qin**2))) \r\n npoints = size(qshape)\r\n\r\n if debug:\r\n print si, inner, outer, dx, npoints\r\n print dqx, dqy, qin, qout\r\n\r\n xformr=randn(nqx, nqy)*qshape\r\n xformi=randn(nqx, nqy)*qshape\r\n xform = xformr + 1j*xformi\r\n spectrum=real(xform*conj(xform))\r\n xseries = real(ifft2(xform))\r\n\r\n if normfres:\r\n frindx = int(rF/dx)\r\n x1dcut = xseries[0,:]\r\n var_fres_in = var(x1dcut[0:size(x1dcut)-frindx]-x1dcut[frindx:])\r\n xseries_norm = xseries * rF / sqrt(var_fres_in) \r\n xn1dcut = xseries_norm[0,:]\r\n var_fres_out = var(xn1dcut[0:size(xn1dcut)-frindx]-xn1dcut[frindx:])\r\n #var_fres_out = var(xseries_norm[0:size(xseries_norm)-frindx]-xseries_norm[frindx:])\r\n print \"index of fresnel scale = \", frindx\r\n print var_fres_in, var_fres_out\r\n\r\n return xvec, yvec, xseries, xseries_norm, qxvec, qyvec, qshape", "def test_wavefunc(file):\n filedir = \"__testfiles__/\" + file\n interpdata = sol.input_reader(filedir)[1]\n x_min, x_max = interpdata[:2]\n length = x_max - x_min\n methode, potar = sol.input_reader(filedir)[2:4]\n eigmin, eigmax = sol.input_reader(filedir)[4:6]\n x_vals = sol.potential_interpolate(interpdata, methode, potar)[:, 0]\n # getting the wavefunctions for the specific problem from data or equations\n wavefuncsmat = np.empty((len(x_vals), eigmax - eigmin + 1))\n if file == \"test_infpot.txt\":\n for nn in range(eigmin, eigmax + 1):\n wavefuncs = []\n if nn % 2 == 0:\n for val in enumerate(x_vals):\n wavefunc = np.sqrt(2 / length) * np.sin(nn * np.pi /\n length * val[1])\n wavefuncs.append(wavefunc)\n else:\n for val in enumerate(x_vals):\n wavefunc = np.sqrt(2 / length) * np.cos(nn * np.pi /\n length * val[1])\n wavefuncs.append(wavefunc)\n wavefuncsmat[:, nn - 1] = wavefuncs\n elif file == \"test_harmonic.txt\":\n wavefuncsmat = np.loadtxt\\\n (\"__unittestfiles__/test_harmonic_wf.dat\")[:, 1:]\n elif file == \"test_pot.txt\":\n wavefuncsmat = np.loadtxt\\\n (\"__unittestfiles__/test_pot_wf.dat\")[:, 1:]\n elif file == \"test_dualpot_lin.txt\":\n wavefuncsmat = np.loadtxt\\\n (\"__unittestfiles__/test_dualpot_lin_wf.dat\")[:, 1:]\n elif file == \"test_dualpot_cspline.txt\":\n wavefuncsmat = np.loadtxt\\\n (\"__unittestfiles__/test_dualpot_cspline_wf.dat\")[:, 1:]\n elif file == \"test_asympot.txt\":\n wavefuncsmat = np.loadtxt\\\n (\"__unittestfiles__/test_asympot_wf.dat\")[:, 1:]\n else:\n wavefuncsmat = np.ones((len(x_vals), eigmax - eigmin + 1))\n # checking if the norm of the wavefunctions is equal to testdata\n sol.run(filedir, \"__output__\")\n testwavefuncs = np.loadtxt(\"__output__/wavefuncs.dat\")[:, 1:]\n assert np.all(np.abs(np.abs(wavefuncsmat)**2 - np.abs(testwavefuncs)**2)\n < ERROR)", "def wind_stress(uw, vw):\n \n nx = len(uw[:,0])\n ny = len(uw[0,:])\n nz = 2 \n Fx = numpy.zeros(((nz,nx,ny)))\n Fy = numpy.zeros(((nz,nx,ny)))\n k = 0.001\n Fx[1,:,:]= k*uw[:,:]*numpy.sqrt((uw[:,:]**2)+(vw[:,:]**2))\n Fy[1,:,:]= k*vw[:,:]*numpy.sqrt((uw[:,:]**2)+(vw[:,:]**2))\n return Fx, Fy", "def solver(I, V, f, w, dt, T):\n dt = float(dt)\n Nt = int(round(T/dt))\n u = np.zeros(Nt+1)\n t = np.linspace(0, Nt*dt, Nt+1)\n\n u[0] = I\n u[1] = u[0] - 0.5*dt**2*w**2*u[0] + dt*V + 0.5*dt**2*f(t[0])\n for n in range(1,Nt):\n u[n+1] = dt**2*f(t[n]) + 2*u[n] - u[n-1] - dt**2*w**2*u[n]\n return u,t", "def f(u):\n \n #h = u[0] # Not used anywhere\n v = u[1]\n \n return numpy.array([v,-g + mDot_p*v_e/(m_s+m_p) - 0.5*rho*v*abs(v)*A*C_D/(m_s+m_p) ]) # ohh abs(v) is sooo much important, for downward velocity, the drag must be up!", "def rickerwave(f = 25, length = 0.512, dt = 0.004): \n time = np.arange(-length/2, (length-dt)/2, dt)\n amplitude = (1.0 - 2.0*(np.pi**2)*(f**2)*(time**2))* \\\n np.exp(-(np.pi**2)*(f**2)*(time**2))\n return (time, amplitude)", "def converged_MFS(mesh,plotx,ploty,plotz,k,incDir,incAmp=1.0,mintau=1,maxtau=20,steps=38):\n \n testx=plotx[0]\n testy=ploty[0]\n testz=plotz[0]\n taus=np.linspace(mintau,maxtau,steps+1)\n vals = np.zeros((steps+1,),dtype=np.complex)\n for i in xrange(steps+1):\n\tvals[i] = MFS(mesh,testx,testy,testz,k,incDir,incAmp,taus[i])[0]\n #vals=[MFS(mesh,testx,testy,testz,k,incDir,incAmp,tau) for tau in taus]\n vals = np.array([np.abs(vals[i]-vals[i+1]) for i in xrange(steps)])\n vals[np.where(vals==0)[0]]=100\n tau = taus[ np.where(vals==np.min(vals))[0][0] +1 ]\n print vals\n print \"MFS solution settled at tau: %.2f\" % (tau)\n return MFS(mesh,plotx,ploty,plotz,k,incDir,incAmp,tau)", "def inferred_wfo(s_orig, s_new, volume):\n \n p = 1027 # kg/m3; average density of global ocean - could calculate from rhopoto data\n m_globe = volume * p\n \n delta_m = -1 * m_globe * (1 - (s_orig / s_new)) \n \n return delta_m", "def get_solution(self):\n # TODO: enter your code here\n solution = 0.0\n f = domain[:, 0]\n for idx, item in enumerate(self.x):\n if self.v[idx][0] >= self.v_min and self.f[idx][0] > f:\n f = self.f[idx][0]\n solution = item[0]\n return solution", "def waveElevIrreg(self,rampTime,dt,maxIt,df):\n t = np.arange(maxIt+1)*dt # array of time with dt time steps\n initialZeros = np.zeros((maxIt+1))\n self.waveAmpTime = [t,initialZeros]\n maxRampIT=int(np.round(rampTime/dt))\n iiter = np.size(self.waveDir)\n tmp = np.sqrt(np.matlib.repmat(self.A,iiter,1)*np.matlib.repmat(df,iiter,1)*np.transpose([self.waveSpread,]))\n c1 = np.matlib.repmat(self.w,iiter,1) # matlib.repmat method that repeats arrays which results in matrix form of arrays\n if rampTime == 0:\n for i in range(maxIt+1): # keeping for loop was faster than changing it to all matrix computation even when there were multiple wave direction\n t = (i)*dt\n tmp1 = tmp*np.real(np.exp(((-1)**0.5)*(c1*t + self.phase))) \n self.waveAmpTime[1][i] = np.sum(tmp1)\n else:\n for i in range(maxRampIT):\n t = (i)*dt\n tmp1 = tmp*np.real(np.exp(((-1)**0.5)*(c1*t + self.phase))) \n ad = (1+np.cos(np.pi+np.pi*(i)/maxRampIT))/2\n self.waveAmpTime[1][i] = np.sum(np.sum(tmp1, axis=1)*ad)\n for i in range(maxRampIT, maxIt+1):\n t = (i)*dt\n tmp1 = tmp*np.real(np.exp(((-1)**0.5)*(c1*t + self.phase))) \n self.waveAmpTime[1][i] = np.sum(tmp1)\n self.waveAmpTime1 = self.waveAmpTime # if wave guage location is not set, wave elevation is same as waveAmpTime\n self.waveAmpTime2 = self.waveAmpTime # if wave guage location is not set, wave elevation is same as waveAmpTime\n self.waveAmpTime3 = self.waveAmpTime # if wave guage location is not set, wave elevation is same as waveAmpTime \n if self.wavegauge1loc[0] != 0 or self.wavegauge1loc[1] != 0 or self.wavegauge2loc[0] != 0 or self.wavegauge2loc[1] != 0 or self.wavegauge3loc[0] != 0 or self.wavegauge3loc[1] != 0:\n c2 = np.matlib.repmat(self.k,iiter,1)\n c_cos = np.cos(np.transpose([self.waveDir,])*np.pi/180)\n c_sin = np.sin(np.transpose([self.waveDir,])*np.pi/180)\n t = np.arange(maxIt+1)*dt # array of time with dt time steps\n self.waveAmpTime1 = [t,np.zeros((maxIt+1))] # set to arrays of zero get an error if it is not set individually\n self.waveAmpTime2 = [t,np.zeros((maxIt+1))] # set to arrays of zero get an error if it is not set individually\n self.waveAmpTime3 = [t,np.zeros((maxIt+1))] # set to arrays of zero get an error if it is not set individually\n if rampTime == 0:\n for i in range(maxIt+1):\n t = (i)*dt\n tmp11 = tmp*np.real(np.exp(((-1)**0.5)*(c1*t - c2*(self.wavegauge1loc[0]*c_cos + self.wavegauge1loc[1]*c_sin) + self.phase)))\n tmp12 = tmp*np.real(np.exp(((-1)**0.5)*(c1*t - c2*(self.wavegauge2loc[0]*c_cos + self.wavegauge2loc[1]*c_sin) + self.phase)))\n tmp13 = tmp*np.real(np.exp(((-1)**0.5)*(c1*t - c2*(self.wavegauge3loc[0]*c_cos + self.wavegauge3loc[1]*c_sin) + self.phase)))\n self.waveAmpTime1[1][i] = np.sum(tmp11)\n self.waveAmpTime2[1][i] = np.sum(tmp12)\n self.waveAmpTime3[1][i] = np.sum(tmp13)\n else:\n for i in range(maxRampIT):\n t = (i)*dt\n tmp11 = tmp*np.real(np.exp(((-1)**0.5)*(c1*t - c2*(self.wavegauge1loc[0]*c_cos + self.wavegauge1loc[1]*c_sin) + self.phase)))\n tmp12 = tmp*np.real(np.exp(((-1)**0.5)*(c1*t - c2*(self.wavegauge2loc[0]*c_cos + self.wavegauge2loc[1]*c_sin) + self.phase)))\n tmp13 = tmp*np.real(np.exp(((-1)**0.5)*(c1*t - c2*(self.wavegauge3loc[0]*c_cos + self.wavegauge3loc[1]*c_sin) + self.phase)))\n ad = (1+np.cos(np.pi+np.pi*(i)/maxRampIT))/2\n self.waveAmpTime1[1][i] = np.sum(np.sum(tmp11, axis=1)*ad)\n self.waveAmpTime2[1][i] = np.sum(np.sum(tmp12, axis=1)*ad)\n self.waveAmpTime3[1][i] = np.sum(np.sum(tmp13, axis=1)*ad)\n for i in range(maxRampIT, maxIt+1):\n t = (i)*dt\n tmp11 = tmp*np.real(np.exp(((-1)**0.5)*(c1*t - c2*(self.wavegauge1loc[0]*c_cos + self.wavegauge1loc[1]*c_sin) + self.phase)))\n tmp12 = tmp*np.real(np.exp(((-1)**0.5)*(c1*t - c2*(self.wavegauge2loc[0]*c_cos + self.wavegauge2loc[1]*c_sin) + self.phase)))\n tmp13 = tmp*np.real(np.exp(((-1)**0.5)*(c1*t - c2*(self.wavegauge3loc[0]*c_cos + self.wavegauge3loc[1]*c_sin) + self.phase)))\n self.waveAmpTime1[1][i] = np.sum(tmp11)\n self.waveAmpTime2[1][i] = np.sum(tmp12)\n self.waveAmpTime3[1][i] = np.sum(tmp13)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculate wave solution using 2nd order finite difference
def solve_wave_FD2(U,Up,h,c,ncpml,b,psi,phi): ny , nx = U.shape for i in range(1,ny-1): for j in range(1,nx-1): Up[i,j] = 2.0*U[i,j] - Up[i,j] + c[i-1,j-1]* \ (U[i-1,j]-2*U[i,j]+U[i+1,j]+ \ (U[i,j-1]-2*U[i,j]+U[i,j+1]))/h/h #CPML boundary in X-domain for i in range(1+ncpml,ny-ncpml-1): for j in range(1,ncpml+1): phi[i,j]=b[j-1]*phi[i,j]+(b[j-1]-1.0)*(U[i,j+1]-U[i,j])/h phi[i,-j-1]=b[j-1]*phi[i,-j-1]+(b[j-1]-1.0)*(U[i,-j-1]-U[i,-j-2])/h for j in range(1,ncpml): psi[i,j]=b[j-1]*psi[i,j]+(b[j-1]-1.0)*\ ((U[i,j-1]-2*U[i,j]+U[i,j+1])/h/h \ +(phi[i,j+1]-phi[i,j])/h) psi[i,-j-1]=b[j-1]*psi[i,-j-1]+(b[j-1]-1.0)*\ ((U[i,-j-2]-2*U[i,-j-1]+U[i,-j])/h/h \ +(phi[i,-j-1]-phi[i,-j-2])/h) Up[i,j] += c[i-1,j-1]*((phi[i,j+1]-phi[i,j])/h+psi[i,j]) Up[i,-j-1] += c[i-1,-j-2]*((phi[i,-j-1]-phi[i,-j-2])/h+psi[i,-j-1]) #CPML boundary in Y-domain for i in range(1,ncpml+1): for j in range(1,nx-1): phi[i,j]=b[i-1]*phi[i,j]+(b[i-1]-1.0)*(U[i+1,j]-U[i,j])/h phi[-i-1,j]=b[i-1]*phi[-i-1,j]+(b[i-1]-1.0)*(U[-i-1,j]-U[-i-2,j])/h for i in range(1,ncpml): for j in range(1,nx-1): psi[i,j]=b[i-1]*psi[i,j]+(b[i-1]-1.0)*\ ((U[i-1,j]-2*U[i,j]+U[i+1,j])/h/h \ +(phi[i+1,j]-phi[i,j])/h) psi[-i-1,j]=b[i-1]*psi[-i-1,j]+(b[i-1]-1.0)*\ ((U[-i-2,j]-2*U[-i-1,j]+U[-i,j])/h/h \ +(phi[-i-1,j]-phi[-i-2,j])/h) Up[i,j] += c[i-1,j-1]*((phi[i+1,j]-phi[i,j])/h+psi[i,j]) Up[-i-1,j] += c[-i-2,j-1]*((phi[-i-1,j]-phi[-i-2,j])/h+psi[-i-1,j])
[ "def wfDerivative(signalRaw,sp=10.):\n signalDeriv = np.zeros(len(signalRaw))\n for i in range(len(signalRaw)-1):\n signalDeriv[i] = (signalRaw[i+1] - signalRaw[i])/sp\n return signalDeriv", "def solve_wave_FD4(U,Up,h,c,ncpml,b,psi,phi):\n ny , nx = U.shape\n for i in range(2,ny-2):\n for j in range(2,nx-2):\n Up[i,j] = 2.0*U[i,j] - Up[i,j] + c[i-2,j-2]* \\\n ((-1*U[i-2,j]+16*U[i-1,j]-30*U[i,j]+16*U[i+1,j]-1*U[i+2,j]) + \\\n (-1*U[i,j-2]+16*U[i,j-1]-30*U[i,j]+16*U[i,j+1]-1*U[i,j+2]))/ \\\n (12*1.0*h**2)\n #CPML boundary in X-domain\n for i in range(2+ncpml,ny-ncpml-2):\n for j in range(2,ncpml+1):\n phi[i,j]=b[j-1]*phi[i,j]+(b[j-1]-1.0)*(U[i,j+1]-U[i,j])/h\n phi[i,-j-1]=b[j-1]*phi[i,-j-1]+(b[j-1]-1.0)*(U[i,-j-1]-U[i,-j-2])/h\n for j in range(2,ncpml):\n psi[i,j]=b[j-1]*psi[i,j]+(b[j-1]-1.0)*\\\n ((U[i,j-1]-2*U[i,j]+U[i,j+1])/h/h \\\n +(phi[i,j+1]-phi[i,j])/h)\n psi[i,-j-1]=b[j-1]*psi[i,-j-1]+(b[j-1]-1.0)*\\\n ((U[i,-j-2]-2*U[i,-j-1]+U[i,-j])/h/h \\\n +(phi[i,-j-1]-phi[i,-j-2])/h)\n Up[i,j] += c[i-2,j-2]*((phi[i,j+1]-phi[i,j])/h+psi[i,j])\n Up[i,-j-1] += c[i-2,-j-3]*((phi[i,-j-1]-phi[i,-j-2])/h+psi[i,-j-1])\n \n #CPML boundary in Y-domain\n for i in range(2,ncpml+1):\n for j in range(2,nx-2):\n phi[i,j]=b[i-1]*phi[i,j]+(b[i-1]-1.0)*(U[i+1,j]-U[i,j])/h\n phi[-i-1,j]=b[i-1]*phi[-i-1,j]+(b[i-1]-1.0)*(U[-i-1,j]-U[-i-2,j])/h\n for i in range(2,ncpml):\n for j in range(2,nx-2):\n psi[i,j]=b[i-1]*psi[i,j]+(b[i-1]-1.0)*\\\n ((U[i-1,j]-2*U[i,j]+U[i+1,j])/h/h \\\n +(phi[i+1,j]-phi[i,j])/h)\n psi[-i-1,j]=b[i-1]*psi[-i-1,j]+(b[i-1]-1.0)*\\\n ((U[-i-2,j]-2*U[-i-1,j]+U[-i,j])/h/h \\\n +(phi[-i-1,j]-phi[-i-2,j])/h)\n Up[i,j] += c[i-2,j-2]*((phi[i+1,j]-phi[i,j])/h+psi[i,j])\n Up[-i-1,j] += c[-i-3,j-2]*((phi[-i-1,j]-phi[-i-2,j])/h+psi[-i-1,j])", "def solver(I, w, dt, T, V, f):\n dt = float(dt)\n Nt = int(round(T/dt)) # 100000\n u = np.zeros(Nt+1)\n t = np.linspace(0, Nt*dt, Nt+1)\n\n u[0] = I\n u[1] = u[0] + dt*V + 0.5*(f(t[0]) - w**2*u[0])*dt**2#compute first step by 1'st order difference\n for n in range(1, Nt):\n u[n+1] = (f(t[n])-w**2*u[n])*dt**2 + 2*u[n]-u[n-1]\n return u, t", "def solve_wave_FD12(U,Up,h,c,ncpml,b,psi,phi):\n ny , nx = U.shape\n for i in range(6,ny-6):\n for j in range(6,nx-6):\n Up[i,j] = 2.0*U[i,j] - Up[i,j] + c[i-8,j-6]* \\\n ((-50*U[i-6,j]+864*U[i-5,j]-7425*U[i-4,j]+44000*U[i-3,j]-222750*U[i-2,j]+1425600*U[i-1,j]-2480478*U[i+0,j]+1425600*U[i+1,j]-222750*U[i+2,j]+44000*U[i+3,j]-7425*U[i+4,j]+864*U[i+5,j]-50*U[i+6,j])+ \\\n (-50*U[i,j-6]+864*U[i,j-5]-7425*U[i,j-4]+44000*U[i,j-3]-222750*U[i,j-2]+1425600*U[i,j-1]-2480478*U[i,j+0]+1425600*U[i,j+1]-222750*U[i,j+2]+44000*U[i,j+3]-7425*U[i,j+4]+864*U[i,j+5]-50*U[i,j+6]))/ \\\n (831600*1.0*h**2)\n \n #CPML boundary in X-domain\n for i in range(6+ncpml,ny-ncpml-6):\n for j in range(6,ncpml+1):\n phi[i,j]=b[j-1]*phi[i,j]+(b[j-1]-1.0)*(U[i,j+1]-U[i,j])/h\n phi[i,-j-1]=b[j-1]*phi[i,-j-1]+(b[j-1]-1.0)*(U[i,-j-1]-U[i,-j-2])/h\n for j in range(6,ncpml):\n psi[i,j]=b[j-1]*psi[i,j]+(b[j-1]-1.0)*\\\n ((U[i,j-1]-2*U[i,j]+U[i,j+1])/h/h \\\n +(phi[i,j+1]-phi[i,j])/h)\n psi[i,-j-1]=b[j-1]*psi[i,-j-1]+(b[j-1]-1.0)*\\\n ((U[i,-j-2]-2*U[i,-j-1]+U[i,-j])/h/h \\\n +(phi[i,-j-1]-phi[i,-j-2])/h)\n Up[i,j] += c[i-6,j-6]*((phi[i,j+1]-phi[i,j])/h+psi[i,j])\n Up[i,-j-1] += c[i-6,-j-7]*((phi[i,-j-1]-phi[i,-j-2])/h+psi[i,-j-1])\n \n #CPML boundary in Y-domain\n for i in range(6,ncpml+1):\n for j in range(6,nx-6):\n phi[i,j]=b[i-1]*phi[i,j]+(b[i-1]-1.0)*(U[i+1,j]-U[i,j])/h\n phi[-i-1,j]=b[i-1]*phi[-i-1,j]+(b[i-1]-1.0)*(U[-i-1,j]-U[-i-2,j])/h\n for i in range(6,ncpml):\n for j in range(6,nx-6):\n psi[i,j]=b[i-1]*psi[i,j]+(b[i-1]-1.0)*\\\n ((U[i-1,j]-2*U[i,j]+U[i+1,j])/h/h \\\n +(phi[i+1,j]-phi[i,j])/h)\n psi[-i-1,j]=b[i-1]*psi[-i-1,j]+(b[i-1]-1.0)*\\\n ((U[-i-2,j]-2*U[-i-1,j]+U[-i,j])/h/h \\\n +(phi[-i-1,j]-phi[-i-2,j])/h)\n Up[i,j] += c[i-6,j-6]*((phi[i+1,j]-phi[i,j])/h+psi[i,j])\n Up[-i-1,j] += c[-i-7,j-6]*((phi[-i-1,j]-phi[-i-2,j])/h+psi[-i-1,j])", "def solve_wave_FD16(U,Up,h,c,ncpml,b,psi,phi):\n ny , nx = U.shape\n for i in range(8,ny-8):\n for j in range(8,nx-8):\n Up[i,j] = 2.0*U[i,j] - Up[i,j] + c[i-8,j-8]* \\\n ((-735*U[i-8,j]+15360*U[i-7,j]-156800*U[i-6,j]+1053696*U[i-5,j]-5350800*U[i-4,j]+22830080*U[i-3,j]-94174080*U[i-2,j]+538137600*U[i-1,j]-924708642*U[i+0,j]+538137600*U[i+1,j]-94174080*U[i+2,j]+22830080*U[i+3,j]-5350800*U[i+4,j]+1053696*U[i+5,j]-156800*U[i+6,j]+15360*U[i+7,j]-735*U[i+8,j])+ \\\n (-735*U[i,j-8]+15360*U[i,j-7]-156800*U[i,j-6]+1053696*U[i,j-5]-5350800*U[i,j-4]+22830080*U[i,j-3]-94174080*U[i,j-2]+538137600*U[i,j-1]-924708642*U[i,j+0]+538137600*U[i,j+1]-94174080*U[i,j+2]+22830080*U[i,j+3]-5350800*U[i,j+4]+1053696*U[i,j+5]-156800*U[i,j+6]+15360*U[i,j+7]-735*U[i,j+8]))/ \\\n (302702400*1.0*h**2)\n \n #CPML boundary in X-domain\n for i in range(8+ncpml,ny-ncpml-8):\n for j in range(8,ncpml+1):\n phi[i,j]=b[j-8]*phi[i,j]+(b[j-8]-1.0)*(U[i,j+1]-U[i,j])/h\n phi[i,-j-1]=b[j-8]*phi[i,-j-1]+(b[j-8]-1.0)*(U[i,-j-1]-U[i,-j-2])/h\n for j in range(8,ncpml):\n psi[i,j]=b[j-8]*psi[i,j]+(b[j-8]-1.0)*\\\n ((U[i,j-1]-2*U[i,j]+U[i,j+1])/h/h \\\n +(phi[i,j+1]-phi[i,j])/h)\n psi[i,-j-1]=b[j-8]*psi[i,-j-1]+(b[j-8]-1.0)*\\\n ((U[i,-j-2]-2*U[i,-j-1]+U[i,-j])/h/h \\\n +(phi[i,-j-1]-phi[i,-j-2])/h)\n Up[i,j] += c[i-8,j-8]*((phi[i,j+1]-phi[i,j])/h+psi[i,j])\n Up[i,-j-1] += c[i-8,-j-9]*((phi[i,-j-1]-phi[i,-j-2])/h+psi[i,-j-1])\n \n #CPML boundary in Y-domain\n for i in range(8,ncpml+1):\n for j in range(8,nx-8):\n phi[i,j]=b[i-8]*phi[i,j]+(b[i-8]-1.0)*(U[i+1,j]-U[i,j])/h\n phi[-i-1,j]=b[i-8]*phi[-i-1,j]+(b[i-8]-1.0)*(U[-i-1,j]-U[-i-2,j])/h\n for i in range(8,ncpml):\n for j in range(8,nx-8):\n psi[i,j]=b[i-8]*psi[i,j]+(b[i-8]-1.0)*\\\n ((U[i-1,j]-2*U[i,j]+U[i+1,j])/h/h \\\n +(phi[i+1,j]-phi[i,j])/h)\n psi[-i-1,j]=b[i-8]*psi[-i-1,j]+(b[i-8]-1.0)*\\\n ((U[-i-2,j]-2*U[-i-1,j]+U[-i,j])/h/h \\\n +(phi[-i-1,j]-phi[-i-2,j])/h)\n \n Up[i,j] += c[i-8,j-8]*((phi[i+1,j]-phi[i,j])/h+psi[i,j])\n Up[-i-1,j] += c[-i-9,j-8]*((phi[-i-1,j]-phi[-i-2,j])/h+psi[-i-1,j])", "def find_s0(wavelet, dt):\n def f(s):\n return wavelet.fourier_period(s) - 2 * dt\n return scipy.optimize.fsolve(f, 1)[0]", "def solve_wave_FD8(U,Up,h,c,ncpml,b,psi,phi):\n ny , nx = U.shape\n for i in range(4,ny-4):\n for j in range(4,nx-4):\n Up[i,j] = 2.0*U[i,j] - Up[i,j] + c[i-4,j-4]* \\\n ((-9*U[i,j-4]+128*U[i,j-3]-1008*U[i,j-2]+8064*U[i,j-1]-14350*U[i,j+0]+8064*U[i,j+1]-1008*U[i,j+2]+128*U[i,j+3]-9*U[i,j+4])+ \\\n (-9*U[i-4,j]+128*U[i-3,j]-1008*U[i-2,j]+8064*U[i-1,j]-14350*U[i+0,j]+8064*U[i+1,j]-1008*U[i+2,j]+128*U[i+3,j]-9*U[i+4,j]))/ \\\n (5040*1.0*h**2)\n \n #CPML boundary in X-domain\n for i in range(4+ncpml,ny-ncpml-4):\n for j in range(4,ncpml+1):\n phi[i,j]=b[j-1]*phi[i,j]+(b[j-1]-1.0)*(U[i,j+1]-U[i,j])/h\n phi[i,-j-1]=b[j-1]*phi[i,-j-1]+(b[j-1]-1.0)*(U[i,-j-1]-U[i,-j-2])/h\n for j in range(4,ncpml):\n psi[i,j]=b[j-1]*psi[i,j]+(b[j-1]-1.0)*\\\n ((U[i,j-1]-2*U[i,j]+U[i,j+1])/h/h \\\n +(phi[i,j+1]-phi[i,j])/h)\n psi[i,-j-1]=b[j-1]*psi[i,-j-1]+(b[j-1]-1.0)*\\\n ((U[i,-j-2]-2*U[i,-j-1]+U[i,-j])/h/h \\\n +(phi[i,-j-1]-phi[i,-j-2])/h)\n Up[i,j] += c[i-4,j-4]*((phi[i,j+1]-phi[i,j])/h+psi[i,j])\n Up[i,-j-1] += c[i-4,-j-5]*((phi[i,-j-1]-phi[i,-j-2])/h+psi[i,-j-1])\n \n #CPML boundary in Y-domain\n for i in range(4,ncpml+1):\n for j in range(4,nx-4):\n phi[i,j]=b[i-1]*phi[i,j]+(b[i-1]-1.0)*(U[i+1,j]-U[i,j])/h\n phi[-i-1,j]=b[i-1]*phi[-i-1,j]+(b[i-1]-1.0)*(U[-i-1,j]-U[-i-2,j])/h\n for i in range(4,ncpml):\n for j in range(4,nx-4):\n psi[i,j]=b[i-1]*psi[i,j]+(b[i-1]-1.0)*\\\n ((U[i-1,j]-2*U[i,j]+U[i+1,j])/h/h \\\n +(phi[i+1,j]-phi[i,j])/h)\n psi[-i-1,j]=b[i-1]*psi[-i-1,j]+(b[i-1]-1.0)*\\\n ((U[-i-2,j]-2*U[-i-1,j]+U[-i,j])/h/h \\\n +(phi[-i-1,j]-phi[-i-2,j])/h)\n Up[i,j] += c[i-4,j-4]*((phi[i+1,j]-phi[i,j])/h+psi[i,j])\n Up[-i-1,j] += c[-i-5,j-4]*((phi[-i-1,j]-phi[-i-2,j])/h+psi[-i-1,j])", "def wah_wah(x, fs):\n\n # buffer size\n wah_length = fs * 2\n\n # damping factor\n # lower the damping factor the smaller the pass band\n damp = 1.8\n\n # min and max centre cutoff frequency of variable bandpass filter\n minf = 500\n maxf = 3000\n\n # wah frequency, how many Hz per second are cycled through\n fw = 2000\n #########################################################################\n\n # change in centre frequency per sample (Hz)\n # delta = 0.2\n delta = fw / fs \n #0.1 => at 44100 samples per second should mean 4.41kHz Fc shift per sec\n\n # create triangle wave of centre frequency values\n fc = np.arange(minf, maxf, delta)\n while len(fc) < len(x):\n fc = np.append(fc, np.arange(maxf, minf, -delta))\n fc = np.append(fc, np.arange(minf, maxf, delta))\n \n # trim tri wave to size of input\n fc = fc[:len(x)]\n\n # difference equation coefficients\n F1 = 2 * np.sin((np.pi * fc[1]) / fs) # must be recalculated each time Fc changes\n Q1 = 2 * damp # this dictates size of the pass bands\n\n yh = np.zeros(x.shape[0]) # create emptly out vectors\n yb = np.zeros(x.shape[0])\n yl = np.zeros(x.shape[0])\n\n # first sample, to avoid referencing of negative signals\n yh[1] = x[1]\n yb[1] = F1 * yh[1]\n yl[1] = F1 * yb[1]\n\n # apply difference equation to the sample\n for n in range(2, len(x) - 1):\n yh[n] = x[n] - yl[n - 1] - Q1 * yb[n - 1]\n yb[n] = F1 * yh[n] + yb[n - 1]\n yl[n] = F1 * yb[n] + yl[n - 1]\n \n F1 = 2 * np.sin((np.pi * fc[n]) / fs)\n\n #normalise\n maxyb = max(abs(yb))\n y = yb / (maxyb + Epsilon)\n\n return shape_check(y)", "def Y2W(r, Y, mode, F): #im ana, and i want to make some mess in my boyfriend's code :)\n\n [h, vr] = Y\n Fphi, Fz = F(r)[2:]\n\n kappa = mode.disk.kappa(r)\n Omega = mode.disk.Omega(r)\n Omegav = mode.disk.Omegav(r)\n dkappa = mode.disk.dkappa(r)\n c = mode.disk.cs\n \n m, n = mode.m, mode.n\n omegat = mode.omegat(r)\n \n [h, vr] = Y\n vphi = -(-2*h*m*Omega + 1j*(-2*Fphi*Omega*r**2 + kappa**2*r*vr))/(2.*Omega*omegat*r**2) \n vz = 1j*(c*Fz - h*n*Omegav)/(c*omegat) \t \n \n # solution vector:\n W = np.array([h, vr, vphi, vz])\n \n # derivatives of h and vr are calculated by calling ode_rhs:\n [dh, dvr] = ode_rhs(r, Y, mode, F)\n\n # derivative of the force:\n dFphi, dFz = F.der(r)[2:]\n \n # derivatives of the two other velocities are: \n \n dvphi = (-(-2*dh*m*Omega - 2*h*m*(kappa**2/(2.*Omega*r) - (2*Omega)/r) + \n 1j*(dvr*kappa**2*r - 4*Fphi*Omega*r - 2*dFphi*Omega*r**2 - \n 2*Fphi*(kappa**2/(2.*Omega*r) - (2*Omega)/r)*r**2 + kappa**2*vr + 2*dkappa*kappa*r*vr))/\n (2.*Omega*omegat*r**2) + (-2*h*m*Omega + 1j*(-2*Fphi*Omega*r**2 + kappa**2*r*vr))/\n (Omega*omegat*r**3) - (m*(kappa**2/(2.*Omega*r) - (2*Omega)/r)*\n (-2*h*m*Omega + 1j*(-2*Fphi*Omega*r**2 + kappa**2*r*vr)))/(2.*Omega*omegat**2*r**2) + \n ((kappa**2/(2.*Omega*r) - (2*Omega)/r)*(-2*h*m*Omega + 1j*(-2*Fphi*Omega*r**2 + kappa**2*r*vr)))/\n (2.*Omega**2*omegat*r**2))\n\n dvz = (0.5j*(c*(Fz*m*(kappa**2 - 4*Omega**2) + 2*dFz*Omega*omegat*r) - \n n*Omegav*(h*m*(kappa**2 - 4*Omega**2) + 2*dh*Omega*omegat*r)))/(c*Omega*omegat**2*r)\n \n dW =np.array([dh, dvr, dvphi, dvz])\n \n return [W, dW]", "def delta(self,element1,element2):\n \n delta = (self.model[element1]/self.model[element2]*self.solar[element2].loc[0]/self.solar[element1].loc[0]-1)*1000\n return delta", "def wind_stress(uw, vw):\n \n nx = len(uw[:,0])\n ny = len(uw[0,:])\n nz = 2 \n Fx = numpy.zeros(((nz,nx,ny)))\n Fy = numpy.zeros(((nz,nx,ny)))\n k = 0.001\n Fx[1,:,:]= k*uw[:,:]*numpy.sqrt((uw[:,:]**2)+(vw[:,:]**2))\n Fy[1,:,:]= k*vw[:,:]*numpy.sqrt((uw[:,:]**2)+(vw[:,:]**2))\n return Fx, Fy", "def inferred_wfo(s_orig, s_new, volume):\n \n p = 1027 # kg/m3; average density of global ocean - could calculate from rhopoto data\n m_globe = volume * p\n \n delta_m = -1 * m_globe * (1 - (s_orig / s_new)) \n \n return delta_m", "def get_solution(self):\n # TODO: enter your code here\n solution = 0.0\n f = domain[:, 0]\n for idx, item in enumerate(self.x):\n if self.v[idx][0] >= self.v_min and self.f[idx][0] > f:\n f = self.f[idx][0]\n solution = item[0]\n return solution", "def gen_powphase2d_old(si, phiF, rF, inner, outer, dx, dy, xW, yW, normfres=True, debug=True):\r\n # specified diffraction and refraction scales\r\n ld = rF / phiF \r\n lr = rF * phiF \r\n\r\n nx = int(xW/dx)\r\n ny = nx\r\n if debug: print 'targeted number of x,y samples = ', nx,ny\n \n #print \"nx\", nx\n #print \"ny\", ny\n \r\n xvec = (arange(0.,nx)-nx/2+1)*dx\r\n yvec = (arange(0.,ny)-ny/2+1)*dy\r\n\r\n dqx = 2.*pi / xW \r\n dqy = 2.*pi / yW\r\n qmaxx = (2.*pi) / (2.*dx)\r\n qmaxy = (2.*pi) / (2.*dy)\r\n\r\n nqx = 2*int(qmaxx/dqx)\r\n nqy = 2*int(qmaxy/dqy)\r\n if debug: print 'targeted number of q samples = ', nqx, nqy \r\n if nqx != nx: \r\n print \"Forcing nqx = nx = \", nx\r\n nqx = nx\r\n if nqy != ny: \r\n print \"Forcing nqy = ny = \", ny\r\n nqy = ny\r\n qxvec = (arange(0.,nqx)-nqx/2+1)*dqx\r\n qxvec = roll(qxvec,nqx/2+1)\r\n qyvec = (arange(0.,nqy)-nqy/2+1)*dqy\r\n qyvec = roll(qyvec,nqy/2+1)\r\n\r\n qin = 2.*pi / inner\r\n qout = 2.*pi / outer\r\n qshape = zeros((nqx, nqy))\r\n \r\n for i, qxi in enumerate(qxvec):\r\n for j, qyj in enumerate(qyvec):\r\n qsq = qxi**2 + qyj**2\r\n qshape[i,j] = (qout**2 + qsq)**(-si/4.) \r\n #qshape[i,j] = (qout**2 + qsq)**(-si/4.) * exp(-(qsq/(2.*qin**2))) \r\n npoints = size(qshape)\r\n\r\n if debug:\r\n print si, inner, outer, dx, npoints\r\n print dqx, dqy, qin, qout\r\n\r\n xformr=randn(nqx, nqy)*qshape\r\n xformi=randn(nqx, nqy)*qshape\r\n xform = xformr + 1j*xformi\r\n spectrum=real(xform*conj(xform))\r\n xseries = real(ifft2(xform))\r\n\r\n if normfres:\r\n frindx = int(rF/dx)\r\n x1dcut = xseries[0,:]\r\n var_fres_in = var(x1dcut[0:size(x1dcut)-frindx]-x1dcut[frindx:])\r\n xseries_norm = xseries * rF / sqrt(var_fres_in) \r\n xn1dcut = xseries_norm[0,:]\r\n var_fres_out = var(xn1dcut[0:size(xn1dcut)-frindx]-xn1dcut[frindx:])\r\n #var_fres_out = var(xseries_norm[0:size(xseries_norm)-frindx]-xseries_norm[frindx:])\r\n print \"index of fresnel scale = \", frindx\r\n print var_fres_in, var_fres_out\r\n\r\n return xvec, yvec, xseries, xseries_norm, qxvec, qyvec, qshape", "def converged_MFS(mesh,plotx,ploty,plotz,k,incDir,incAmp=1.0,mintau=1,maxtau=20,steps=38):\n \n testx=plotx[0]\n testy=ploty[0]\n testz=plotz[0]\n taus=np.linspace(mintau,maxtau,steps+1)\n vals = np.zeros((steps+1,),dtype=np.complex)\n for i in xrange(steps+1):\n\tvals[i] = MFS(mesh,testx,testy,testz,k,incDir,incAmp,taus[i])[0]\n #vals=[MFS(mesh,testx,testy,testz,k,incDir,incAmp,tau) for tau in taus]\n vals = np.array([np.abs(vals[i]-vals[i+1]) for i in xrange(steps)])\n vals[np.where(vals==0)[0]]=100\n tau = taus[ np.where(vals==np.min(vals))[0][0] +1 ]\n print vals\n print \"MFS solution settled at tau: %.2f\" % (tau)\n return MFS(mesh,plotx,ploty,plotz,k,incDir,incAmp,tau)", "def _calc_psi_deriv(self):\n try:\n self.bkg['psi'].mean()\n except:\n self.build_bkg()\n \n # psi = self.eqdsk.psi\n # self.dpsidR = np.zeros((self.eqdsk.nzbox, self.eqdsk.nrbox))\n # self.dpsidZ = np.zeros((self.eqdsk.nzbox, self.eqdsk.nrbox))\n psi = self.bkg['psi']\n self.dpsidR = np.zeros((self.nz, self.nR))\n self.dpsidZ = np.zeros((self.nz, self.nR)) \n deriv = np.gradient(psi)\n # Note np.gradient gives y\n # derivative first, then x derivative\n ddR = deriv[1]\n ddZ = deriv[0]\n # dRdi = np.asarray(1.0)/np.gradient(self.R_eqd)\n # dRdi = np.tile(dRdi, [self.eqdsk.nzbox,1])\n # dZdi = np.asarray(1.0)/np.gradient(self.Z_eqd)\n # dZdi = np.tile(dZdi, [self.eqdsk.nrbox,1])\n # dZdi = np.transpose(dZdi)\n dRdi = np.asarray(1.0)/np.gradient(self.bkg['R'])\n dRdi = np.tile(dRdi, [self.nz,1])\n dZdi = np.asarray(1.0)/np.gradient(self.bkg['z'])\n dZdi = np.tile(dZdi, [self.nR,1])\n dZdi = np.transpose(dZdi)\n #print(\"shape ddR:\",np.shape(ddR),'shape dRdi:', np.shape(dRdi))\n #print('shape ddZ:',np.shape(ddZ),'shape dZdi:', np.shape(dZdi))\n \n self.dpsidR[:, :] = ddR*dRdi\n self.dpsidZ[:, :] = ddZ*dZdi", "def f(u):\n \n #h = u[0] # Not used anywhere\n v = u[1]\n \n return numpy.array([v,-g + mDot_p*v_e/(m_s+m_p) - 0.5*rho*v*abs(v)*A*C_D/(m_s+m_p) ]) # ohh abs(v) is sooo much important, for downward velocity, the drag must be up!", "def solver(I, V, f, w, dt, T):\n dt = float(dt)\n Nt = int(round(T/dt))\n u = np.zeros(Nt+1)\n t = np.linspace(0, Nt*dt, Nt+1)\n\n u[0] = I\n u[1] = u[0] - 0.5*dt**2*w**2*u[0] + dt*V + 0.5*dt**2*f(t[0])\n for n in range(1,Nt):\n u[n+1] = dt**2*f(t[n]) + 2*u[n] - u[n-1] - dt**2*w**2*u[n]\n return u,t", "def rickerwave(f = 25, length = 0.512, dt = 0.004): \n time = np.arange(-length/2, (length-dt)/2, dt)\n amplitude = (1.0 - 2.0*(np.pi**2)*(f**2)*(time**2))* \\\n np.exp(-(np.pi**2)*(f**2)*(time**2))\n return (time, amplitude)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Transforms a given value into a node
def to_node(value: str) -> Node: if not value: res = Empty() elif value in CONCATENATION_SYMBOLS: res = Concatenation() elif value in UNION_SYMBOLS: res = Union() elif value in KLEENE_STAR_SYMBOLS: res = KleeneStar() elif value in EPSILON_SYMBOLS: res = Epsilon() elif value[0] == "\\": res = Symbol(value[1:]) else: res = Symbol(value) return res
[ "def convert(gr, raw_node):\r\n type, value, context, children = raw_node\r\n if children or type in gr.number2symbol:\r\n # If there's exactly one child, return that child instead of\r\n # creating a new node.\r\n if len(children) == 1:\r\n return children[0]\r\n return Node(type, children, context=context)\r\n else:\r\n return Leaf(type, value, context=context)", "def transform(self, data_value, lvl):\n if lvl == 0:\n return data_value\n\n if self.root_node.nodes is None:\n return self.root_node.value\n\n data_node = self.get_leaf_node(data_value)\n if data_node is None:\n data_node = self.find_node(data_value)\n\n if data_node is not None:\n transformed_node = self.get_generalization_level_representation(data_node, lvl)\n return transformed_node.value\n\n raise InfoException(\"Couldnt find node with the value: %s\" % data_value)", "def node_conv(obj):\n try:\n get = obj.get\n except AttributeError:\n if isinstance(obj, SCons.Node.Node) or SCons.Util.is_Sequence( obj ):\n result = obj\n else:\n result = str(obj)\n else:\n result = get()\n return result", "def _convert_value(self, value):\n if isinstance(value, (neo4j.Node, neo4j.Relationship)):\n properties = value.get_properties()\n obj = self.type_registry.dict_to_object(properties)\n\n if isinstance(value, neo4j.Relationship):\n obj.start = self._convert_value(value.start_node)\n obj.end = self._convert_value(value.end_node)\n else:\n set_store_for_object(obj, self)\n return obj\n return value", "def visit(value):\n if isinstance(value, Node):\n return value.traverse(fun)\n if isinstance(value, list):\n return fun(list(map(visit, value)))\n else:\n return fun(value)", "def convert(self, value):", "def update_value(self, value):\n self.node_value = value", "def _try_convert_to_node(value: Any) -> Any:\n if isinstance(value, channel.BaseChannel):\n return resolver_op.InputNode(value)\n if typing_utils.is_compatible(value, Mapping[str, channel.BaseChannel]):\n return resolver_op.DictNode(\n {\n input_key: resolver_op.InputNode(input_channel)\n for input_key, input_channel in value.items()\n }\n )\n return value", "def _(self, node: AnnCastUnaryOp):\n val = self.visit(node.value)\n node_uid = uuid.uuid4()\n self.G.add_node(node_uid, label=node.op)\n self.G.add_edge(node_uid, val)\n\n return node_uid", "def add_value_node(self, node_name):\n\t\tadd_value_node(node_name)", "def build(self, value):\r\n if value is not None:\r\n return self.token(value)\r\n else:\r\n return None", "def set_value(self,value):\n self.node.set(value)", "def _(self, node: AnnCastModelReturn):\n value = self.visit(node.value)\n node_uid = uuid.uuid4()\n self.G.add_node(node_uid, label=\"Return\")\n self.G.add_edge(node_uid, value)\n\n return node_uid", "def filter_node_id(value):\n if not value:\n return None\n\n if isinstance(value, str):\n if value.isnumeric():\n return int(value)\n return None\n\n if isinstance(value, int):\n if value < 0:\n return None\n\n return value\n\n return None", "def add_value(self, value: T) -> None:\n self.len+=1\n z = BSTNode(value)\n y = None\n x = self.root\n while(x!=None):\n y = x\n if(z.value < x.value):\n x = x.left\n else:\n x = x.right\n z.parent = y\n if(y == None):\n self.root = z\n elif (z.value < y.value):\n y.left = z\n else:\n y.right = z\n ...", "def add(self, value):\n node = TreeNode(value)\n if self.root == None:\n self.root = node\n else:\n self.__add(node)", "def _make_node(self, fabric):\n\t\tnode = VariableTree.TreeNode(str(fabric.id))\n\t\tfor parameter, value in fabric.__dict__.items():\n\t\t\tif parameter != \"id\":\n\t\t\t\tnode.childs.append(self._makers[parameter](value))\n\t\treturn node", "def visit_value_node(self, value_node):\n if value_node not in self._cached_value_nodes_values:\n self._visit_operation(value_node.parent_operation)\n return self._cached_value_nodes_values[value_node]", "def _substitute_tree_node(data, path, value):\n if not path or not data:\n return\n path_head, *path_tail = path\n if path_head not in data:\n return\n if not path_tail:\n data[path_head] = value\n else:\n _substitute_tree_node(data[path_head], path_tail, value)", "def sort_value_node(value_node: ValueNode) -> ValueNode:\n if isinstance(value_node, ObjectValueNode):\n value_node = copy(value_node)\n value_node.fields = sort_fields(value_node.fields)\n elif isinstance(value_node, ListValueNode):\n value_node = copy(value_node)\n value_node.values = tuple(sort_value_node(value) for value in value_node.values)\n return value_node" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Find if x is a member of the tree in O(lg lg u) time
def vEBTreeSearch(self, x): if self.min == x or self.max == x: return True elif self.u <= 2: return False else: cluster_of_x = self.clusters[self.high(x)] if cluster_of_x is not None: return cluster_of_x.isMember(self.low(x)) else: return False
[ "def _is_member(self, leaf):\n\n return leaf in self.leaves", "def __contains__ (self, target):\n node = self.root\n while node:\n rc = node.compareTo(target)\n if rc > 0:\n node = node.left\n elif rc < 0:\n node = node.right\n else:\n return True\n \n \n return False", "def __contains__(self, id):\n\n return id in self.nodes", "def _insideTree(self, node):\r\n lastIndex = len(self._heap) - 1\r\n if node <= lastIndex:\r\n return True\r\n else:\r\n return False", "def __contains__(self, item: Any) -> bool:\n if len(self.subtrees) == 0:\n return self.value == item\n else:\n for subtree in self.subtrees:\n if item in subtree:\n return True\n return self.value == item", "def __is_member_of(self, group, recursive=False):\n return group in self.get_memberOfs(recursive=recursive)", "def test_contains_returns_node(self):\n node = Node(10)\n node.insert(5)\n node.insert(15)\n node.insert(20)\n node.insert(0)\n node.insert(-5)\n node.insert(3)\n three = node.left.left.right\n self.assertEqual(node.contains(3), three)", "def __contains__(self, el):\n # BEGIN SOLUTION\n # current version:\n cur = self.root_versions[-1]\n\n # find element\n def find(t, x):\n # if None, so not there, return False\n if not t:\n return False\n # if val equals x, then returns true.\n if t.val == x:\n return True\n # if val is grater then key, then get left.\n if t.val > x:\n return find(t.left, x)\n # if val is less then key, then get right.\n if t.val < x:\n return find(t.right, x)\n\n # return if there in current version of binary search tree.\n return find(cur, el)\n # END SOLUTION", "def contains(self, n):\n if n < self.n: # if passed-in n < current n\n if self.left is None:\n return False\n else:\n return self.left.contains(n) # recursive\n elif n > self.n:\n if self.right is None:\n return False\n else:\n return self.right.contains(n) # recursive\n else:\n return True", "def is_in_tree(self, type_to_search):\n return self.get_sub_tree(type_to_search) is not None", "def _is_root(obj: LazyUnionObj) -> bool:\n return obj.parent is obj\n # Running time complexity: O(1)", "def contains(self, value: object) -> bool:\n if self.root is None:\n return False\n else:\n current = self.root\n\n while current is not None:\n if value == current.value:\n return True\n elif current.value > value:\n current = current.left\n elif current.value < value:\n current = current.right\n return False", "def contains(node, value):\n if node is None:\n return False\n else:\n return (node.data == value or\n contains(node.left, value) or\n contains(node.right, value))", "def is_member(x,array):\n for member in array:\n if x == member:\n return True\n return False", "def element_of_set(x, set):\n if set is nil:\n return False\n if x == entry(set):\n return True\n if x < entry(set):\n return element_of_set(x, left_branch(set))\n if x > entry(set):\n return element_of_set(x, right_branch(set))", "def is_in_tree(self, value):\n \n if self.data == value:\n return True\n\n if value <= self.data:\n if self.left:\n return self.left.is_in_tree(value)\n else:\n if self.right:\n return self.right.is_in_tree(value)\n\n return False", "def exists(self, idx: int, d: int, node: TreeNode) -> bool:\n left, right = 0, 2**d - 1\n for _ in range(d):\n pivot = (left + right) // 2\n if idx <= pivot:\n node = node.left\n right = pivot\n else:\n node = node.right\n left = pivot + 1\n return node is not None", "def contains(s, v):\n if s is BTree.empty:\n return False\n elif s.root == v:\n return True\n elif s.root < v:\n return contains(s.right, v)\n else:\n return contains(s.left, v)", "def __contains__(self, key):\n for node in self.nodes:\n if node.key == key:\n return True\n return False" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compute the mean and variance of the latent function at some new points Xnew.
def predict_f(self, Xnew: InputData, full_cov: bool = False, full_output_cov: bool = False) -> MeanAndVariance: # metadata X_data, Y_data = self.data num_inducing = self.inducing_variable.num_inducing # compute initial matrices err = Y_data - self.mean_function(X_data) kuf = Kuf(self.inducing_variable, self.kernel, X_data) kuu = Kuu(self.inducing_variable, self.kernel) kus = Kuf(self.inducing_variable, self.kernel, Xnew) L = robust_cholesky(kuu) theta = tf.transpose(self.likelihood.compute_theta()) theta_sqrt = tf.sqrt(theta) theta_sqrt_inv = tf.math.reciprocal(theta_sqrt) # compute intermediate matrices A = tf.linalg.triangular_solve(L, kuf, lower=True) * theta_sqrt AAT = tf.matmul(A, A, transpose_b=True) B = AAT + tf.eye(num_inducing, dtype=default_float()) LB = robust_cholesky(B) A_theta_sqrt_inv_err = tf.matmul(A * theta_sqrt_inv, err) c = 0.5 * tf.linalg.triangular_solve(LB, A_theta_sqrt_inv_err) # compute predictive tmp1 = tf.linalg.triangular_solve(L, kus, lower=True) tmp2 = tf.linalg.triangular_solve(LB, tmp1, lower=True) mean = tf.matmul(tmp2, c, transpose_a=True) if full_cov: var = ( self.kernel(Xnew) + tf.matmul(tmp2, tmp2, transpose_a=True) - tf.matmul(tmp1, tmp1, transpose_a=True) ) var = tf.tile(var[None, ...], [self.num_latent_gps, 1, 1]) # [P, N, N] else: var = ( self.kernel(Xnew, full_cov=False) + tf.reduce_sum(tf.square(tmp2), 0) - tf.reduce_sum(tf.square(tmp1), 0) ) var = tf.tile(var[:, None], [1, self.num_latent_gps]) return mean + self.mean_function(Xnew), var
[ "def predict_f(\n self,\n params: dict,\n Xnew: InputData,\n key: jnp.DeviceArray = None,\n num_inducing_samples: int = None,\n full_cov: bool = False,\n full_output_cov: bool = False,\n ) -> MeanAndCovariance:\n if num_inducing_samples is None:\n mean, cov = conditional(\n params[\"kernel\"],\n Xnew,\n params[\"inducing_variable\"],\n self.kernel,\n f=params[\"q_mu\"],\n full_cov=full_cov,\n full_output_cov=full_output_cov,\n q_sqrt=params[\"q_sqrt\"],\n white=self.whiten,\n )\n else:\n q_mu_samples = self.sample_inducing_variables(\n params, key, num_inducing_samples\n )\n\n def conditional_wrapper(f_sample):\n return conditional(\n params[\"kernel\"],\n Xnew,\n params[\"inducing_variable\"],\n self.kernel,\n f=f_sample,\n full_cov=full_cov,\n full_output_cov=full_output_cov,\n q_sqrt=None,\n white=self.whiten,\n )\n\n mean, cov = jax.vmap(conditional_wrapper, out_axes=(0, 0))(q_mu_samples)\n return mean + self.mean_function(params[\"mean_function\"], Xnew), cov", "def predict_f_samples(self, Xnew, num_samples):\n mu, var, _ = self._build_predict(Xnew, full_cov=True) # N x P, # P x N x N\n jitter = tf.eye(tf.shape(mu)[0], dtype=settings.float_type) * settings.numerics.jitter_level\n samples = []\n for i in range(self.num_latent):\n L = tf.cholesky(var[i, :, :] + jitter)\n shape = tf.stack([tf.shape(L)[0], num_samples])\n V = tf.random_normal(shape, dtype=settings.float_type)\n samples.append(mu[:, i:i + 1] + tf.matmul(L, V))\n return tf.transpose(tf.stack(samples))", "def compute_prior_mean_var(self, test_points, num_latent):\n return self.build_prior_mean_var(test_points, num_latent, False)", "def __call__(self, xnew):\n xnew = np.array(xnew)\n x = self.x\n c = self.c\n f = np.zeros(xnew.shape[0])\n\n for k in range(xnew.shape[0]):\n ind = np.abs(x - xnew[k]).argmin()\n\n if (x[ind] > xnew[k] or ind == x.shape[0] - 1) and not ind == 0:\n ind -= 1\n n = ind * 4\n f[k] = c[n] * xnew[k] ** 3 + c[n + 1] * xnew[k] ** 2 + c[n + 2] * xnew[k] + c[n + 3]\n\n return f", "def update_mean(X):\n\n return X.sum(axis=0) / X.shape[0]", "def _get_mean_var(X):\n mean = X.mean()\n var = X.var()\n\n return [mean, var]", "def varnewover(self, i):\n result=[]\n for j in range(int(self.N/(2**i))):\n result.append(np.var(self.clustertrain(i,j)))\n result=np.mean(np.array(result))\n return result", "def predict_density(self, Xnew, Ynew):\n pred_f_mean, pred_f_var, _ = self._build_predict(Xnew)\n return self.likelihood.predict_density(pred_f_mean, pred_f_var, Ynew)", "def gp_prediction(self, Xnew, **kwargs):\n \n # Predict mean and covariance\n mean, cov = self.gp.predict(Xnew, **kwargs)\n # Predict quantiles\n lower, upper = self.gp.predict_quantiles(Xnew)\n \n # Invert the transformation:\n if self.transformation == \"wsabi-l\":\n mean, cov, lower, upper = self.sqrt_transform_inv(mean, cov)\n \n # Return all\n return(mean, cov, lower, upper)", "def get_mean(original_points):\n\n global points\n mean_result = []\n\n for i in range(total_number_of_features):\n sum = 0\n for index in original_points:\n sum += points[index][i]\n\n mean_result.append(sum / len(original_points))\n return mean_result", "def compute_posterior_mean_var(self, X, Y, test_points):\n return self.build_posterior_mean_var(X, Y, test_points, full_cov=False)", "def gaussian_process_pointwise_variance(kernel, pred_samples, train_samples,\n nugget=0):\n K_train = kernel(train_samples.T)\n # add small number to diagonal to ensure covariance matrix is\n # positive definite\n ntrain_samples = train_samples.shape[1]\n K_train[np.arange(ntrain_samples), np.arange(ntrain_samples)] += nugget\n k_pred = kernel(train_samples.T, pred_samples.T)\n L = np.linalg.cholesky(K_train)\n tmp = solve_triangular(L, k_pred, lower=True)\n variance = kernel.diag(pred_samples.T) - np.sum(tmp*tmp, axis=0)\n return variance", "def calculate_variance(X):\n return np.var(X,axis=0)", "def normalize(X, mu=None, stdev=None):\n ### START YOUR CODE ###\n if mu == None:\n mu = np.mean(X)\n if stdev == None:\n stdev = np.std(X, ddof=1)\n X1 = (X - mu)/stdev\n ### END YOUR CODE ###\n \n return X1,mu,stdev", "def compute_prior_mean_cov(self, test_points, num_latent):\n return self.build_prior_mean_var(test_points, num_latent, True)", "def update(self, last_avg: Tensor):\n self.avg_latent.copy_(\n self.beta * self.avg_latent + (1.0 - self.beta) * last_avg\n )", "def setMeanAndVariance(self, mean, var=0.0):\n #---+----|----+----|----+----|----+----|----+----|----+----|----+----|\n return ExponentialDistBase.setMeanAndVariance(self, mean, var)", "def update_avg_variance(self, spikes):\n\n delta = spikes - self.spikerate\n spikerate_new = self.spikerate + delta / self.time\n var_new = self.var + delta * (spikes - spikerate_new)\n self.var.assign(var_new / self.time)\n self.spikerate.assign(spikerate_new)", "def normalize_data(x_train, x_test):\n train_mean_1 = np.mean(x_train[:,:,:,:,0])\n train_mean_2 = np.mean(x_train[:,:,:,:,1])\n train_std_dev_1 = np.std(x_train[:,:,:,:,0])\n train_std_dev_2 = np.std(x_train[:,:,:,:,1])\n x_train[:,:,:,:,0] = (x_train[:,:,:,:,0] - train_mean_1) / train_std_dev_1 # element-wise operations\n x_train[:,:,:,:,1] = (x_train[:,:,:,:,1] - train_mean_2) / train_std_dev_2 # element-wise operations\n x_test[:,:,:,:,0] = (x_test[:,:,:,:,0] - train_mean_1) / train_std_dev_1 # element-wise operations\n x_test[:,:,:,:,1] = (x_test[:,:,:,:,1] - train_mean_2) / train_std_dev_2 # element-wise operations\n return x_train, x_test" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Predict the mean and variance for unobserved values at some new points Xnew.
def predict_y(self, Xnew: InputData, full_cov: bool = False, full_output_cov: bool = False) -> MeanAndVariance: mean, var = self.predict_f(Xnew) return mean, var + self.likelihood.noise_variance(mean, var)
[ "def predict(self, Xnew):\n if self.compute_invcdf:\n for _, x in np.ndenumerate(self.X):\n x.compute_inv_cdf(self.spline_basis)\n\n scores = np.ones(Xnew.shape[0]) * self.intercept\n for i in range(Xnew.shape[0]):\n for j in range(self.n_predictors):\n scores[i] += \\\n np.dot(Xnew[i, j].phi, self.phi[j, :]) + \\\n np.dot(Xnew[i, j].inv_cdf.inv_cdf_coeffs,\n np.dot(self.spline_basis.metric, self.beta[j, :]))\n \n preds = 1.0 / (1.0 + np.exp(-scores))\n preds[preds >= 0.5] = 1.0\n preds[preds < 0.5] = 0.0\n return preds", "def gp_prediction(self, Xnew, **kwargs):\n \n # Predict mean and covariance\n mean, cov = self.gp.predict(Xnew, **kwargs)\n # Predict quantiles\n lower, upper = self.gp.predict_quantiles(Xnew)\n \n # Invert the transformation:\n if self.transformation == \"wsabi-l\":\n mean, cov, lower, upper = self.sqrt_transform_inv(mean, cov)\n \n # Return all\n return(mean, cov, lower, upper)", "def predict_f(self, Xnew: InputData, full_cov: bool = False, full_output_cov: bool = False) -> MeanAndVariance:\n\n # metadata\n X_data, Y_data = self.data\n num_inducing = self.inducing_variable.num_inducing\n\n # compute initial matrices\n err = Y_data - self.mean_function(X_data)\n kuf = Kuf(self.inducing_variable, self.kernel, X_data)\n kuu = Kuu(self.inducing_variable, self.kernel)\n kus = Kuf(self.inducing_variable, self.kernel, Xnew)\n L = robust_cholesky(kuu)\n theta = tf.transpose(self.likelihood.compute_theta())\n theta_sqrt = tf.sqrt(theta)\n theta_sqrt_inv = tf.math.reciprocal(theta_sqrt)\n\n # compute intermediate matrices\n A = tf.linalg.triangular_solve(L, kuf, lower=True) * theta_sqrt\n AAT = tf.matmul(A, A, transpose_b=True)\n B = AAT + tf.eye(num_inducing, dtype=default_float())\n LB = robust_cholesky(B)\n A_theta_sqrt_inv_err = tf.matmul(A * theta_sqrt_inv, err)\n c = 0.5 * tf.linalg.triangular_solve(LB, A_theta_sqrt_inv_err)\n\n # compute predictive\n tmp1 = tf.linalg.triangular_solve(L, kus, lower=True)\n tmp2 = tf.linalg.triangular_solve(LB, tmp1, lower=True)\n mean = tf.matmul(tmp2, c, transpose_a=True)\n if full_cov:\n var = (\n self.kernel(Xnew)\n + tf.matmul(tmp2, tmp2, transpose_a=True)\n - tf.matmul(tmp1, tmp1, transpose_a=True)\n )\n var = tf.tile(var[None, ...], [self.num_latent_gps, 1, 1]) # [P, N, N]\n else:\n var = (\n self.kernel(Xnew, full_cov=False)\n + tf.reduce_sum(tf.square(tmp2), 0)\n - tf.reduce_sum(tf.square(tmp1), 0)\n )\n var = tf.tile(var[:, None], [1, self.num_latent_gps])\n\n return mean + self.mean_function(Xnew), var", "def predict_density(self, Xnew, Ynew):\n pred_f_mean, pred_f_var, _ = self._build_predict(Xnew)\n return self.likelihood.predict_density(pred_f_mean, pred_f_var, Ynew)", "def predict_f_samples(self, Xnew, num_samples):\n mu, var, _ = self._build_predict(Xnew, full_cov=True) # N x P, # P x N x N\n jitter = tf.eye(tf.shape(mu)[0], dtype=settings.float_type) * settings.numerics.jitter_level\n samples = []\n for i in range(self.num_latent):\n L = tf.cholesky(var[i, :, :] + jitter)\n shape = tf.stack([tf.shape(L)[0], num_samples])\n V = tf.random_normal(shape, dtype=settings.float_type)\n samples.append(mu[:, i:i + 1] + tf.matmul(L, V))\n return tf.transpose(tf.stack(samples))", "def predict_f(\n self,\n params: dict,\n Xnew: InputData,\n key: jnp.DeviceArray = None,\n num_inducing_samples: int = None,\n full_cov: bool = False,\n full_output_cov: bool = False,\n ) -> MeanAndCovariance:\n if num_inducing_samples is None:\n mean, cov = conditional(\n params[\"kernel\"],\n Xnew,\n params[\"inducing_variable\"],\n self.kernel,\n f=params[\"q_mu\"],\n full_cov=full_cov,\n full_output_cov=full_output_cov,\n q_sqrt=params[\"q_sqrt\"],\n white=self.whiten,\n )\n else:\n q_mu_samples = self.sample_inducing_variables(\n params, key, num_inducing_samples\n )\n\n def conditional_wrapper(f_sample):\n return conditional(\n params[\"kernel\"],\n Xnew,\n params[\"inducing_variable\"],\n self.kernel,\n f=f_sample,\n full_cov=full_cov,\n full_output_cov=full_output_cov,\n q_sqrt=None,\n white=self.whiten,\n )\n\n mean, cov = jax.vmap(conditional_wrapper, out_axes=(0, 0))(q_mu_samples)\n return mean + self.mean_function(params[\"mean_function\"], Xnew), cov", "def predict(self, X, return_std=..., return_cov=...):\n ...", "def predict_dists(self, params: dict, Xnew: InputData, **kwargs):\n raise NotImplementedError", "def predict(self,newdata):\n root=self.root\n while not self.is_leaf(root):\n x=newdata[root.var]\n if root.dtype!=\"Continuous\":\n if x in root.cut:\n root=root.get_left\n else:\n root=root.get_right\n else:\n if x<=root.cut:\n root=root.get_left\n else:\n root=root.get_right\n return root.pred", "def predictMean(self, Xstar):\n return _core.CGPbase_predictMean(self, Xstar)", "def get_predictions(new_data, weights):\n return insert_ones(new_data).dot(weights)", "def predict(self, X):\n n = X.shape[0]\n m = self.num_obj\n Y_m = np.ndarray((n, m))\n Y_v = np.ndarray((n, m))\n for i in xrange(m):\n if self.denoised:\n if hasattr(self.surrogates[i],'likelihood') and hasattr(self.surrogates[i].likelihood,'variance'):\n noise = self.surrogates[i].likelihood.variance\n else:\n noise = 0.\n else:\n noise = 0.\n m, v = self.surrogates[i].predict(X)\n Y_m[:, i] = m.flatten()\n Y_v[:, i] = v.flatten() - noise\n return Y_m, Y_v", "def predict(self, X):\n return predicted_value", "def fit_precomputed(self, D_new, target):\n self.D_new = D_new\n self.information_gain, self.delta, self.f_c_delta = self.train(D_new, target)\n return self.information_gain, self.delta, self.f_c_delta", "def predict(model, X_test):", "def predict_rent(X_train, X_test, y_train, y_test):\n clf = Ridge(alpha=110)\n clf.fit(X_train, y_train)\n predicted = clf.predict(X_test)\n return X_test, y_test, predicted", "def predictVar(self, Xstar):\n return _core.CGPbase_predictVar(self, Xstar)", "def _predict(self, t_fin,g_std, l_0 = None, t_0 = 0, dt = 3.,seed=None):\n t_fin+=1000*dt#ensure to be in stationary phase\n if seed is not None: np.random.seed(seed)\n l_0 = l_0 if l_0 is not None else self.mu #initialize at the mean\n t = np.arange(t_0, t_fin+dt ,dt)\n dw = self._dW(dt,len(t))\n for i,j in enumerate(t):\n if i == 0:\n x = np.array([l_0])\n else:\n x = np.append(x, x[i-1] + self._mu(x[i-1])*dt +\\\n self.sigma*dw[i-1])\n t=t[1000:]-t[1000]; x=x[1000:]#cancel the added 100 points\n xnoise = np.random.normal(loc=x ,scale = g_std*np.ones_like(x))\n return t, x, xnoise", "def predict(self, X, return_std=False):\n X = check_array(X)\n if not hasattr(self, \"estimators_\"):\n raise NotFittedError(\"The model has to be fit before prediction.\")\n ensemble_mean = np.zeros(X.shape[0])\n exp_y_sq = np.zeros_like(ensemble_mean)\n\n for est in self.estimators_:\n if return_std:\n mean, std = est.predict(X, return_std=True)\n exp_y_sq += (std**2 + mean**2)\n else:\n mean = est.predict(X, return_std=False)\n ensemble_mean += mean\n\n ensemble_mean /= len(self.estimators_)\n exp_y_sq /= len(self.estimators_)\n\n if not return_std:\n return ensemble_mean\n std = exp_y_sq - ensemble_mean**2\n std[std <= 0.0] = 0.0\n std **= 0.5\n return ensemble_mean, std", "def learn(self, Xtrain, ytrain):\n\n ### YOUR CODE HERE\n if self.params['usecolumnones']:\n self.numfeatures = Xtrain.shape[1]\n \n else:\n self.numfeatures = Xtrain.shape[1] - 1\n\n ### END YOUR CODE\n\n origin_shape = (self.numclasses, self.numfeatures)\n self.means = np.zeros(origin_shape)\n self.stds = np.zeros(origin_shape)\n self.prior_prob = np.zeros(2)\n \n\n ### YOUR CODE HERE\n for clas in range(self.numclasses):\n indices = np.where(ytrain == clas)\n trainclass = Xtrain[indices]\n ## calculating prior probability for each class\n self.prior_prob[clas] = np.size(indices)/(float)(Xtrain.shape[0])\n #print(np.size(indices))\n for i in range(self.numfeatures):\n self.means[clas, i] = np.mean(trainclass[:, i])\n self.stds[clas, i] = np.std(trainclass[:, i])\n \n ### END YOUR CODE\n\n assert self.means.shape == origin_shape\n assert self.stds.shape == origin_shape" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Inspects each line of the command output and checks to see if the command errored. This check is used for API's that get data and do not simply report a success message.
def _no_error_in_output(self, stdout): for line in stdout: if line.startswith("ERROR:"): return False return True
[ "def command_error(self, response):\n # The command should be echoed back accurately (might be\n # preceeded by a '- ' if it is part of a program definition) and\n # no errors should be returned, if it has no errors.\n return (response[2] not in [response[0], '- ' + response[0]]\n or response[3] is not None)", "def check_results(self):\n try:\n while True:\n item = self._pop_completed() # will throw Empty\n if not item.get_results().wasSuccessful():\n raise ExecutionError(\"Error Executing Command: \", item)\n except Empty:\n return", "def test_check_output_failure(self):\n self.check_output.side_effect = actions.actions.CalledProcessError(\n 1, \"Failure\")\n\n actions.actions.diskusage([])\n self.check_output.assert_called_once_with(['swift-recon', '-d'])\n\n self.action_set.assert_called()\n self.action_fail.assert_called()", "def read_errors(self):\n self.output.append(str(self.process.readAllStandardError()))", "def test_check_true_missing_prog_output(self):\n with self.assertRaises(rh.utils.CalledProcessError) as e:\n rh.utils.run(['./!~a/b/c/d/'], check=True, capture_output=True)\n err = e.exception\n self.assertNotEqual(0, err.returncode)\n self.assertIn('a/b/c/d', str(err))", "def check_log_for_errors(\n cutechess_output: List[str],\n) -> None:\n logger = logging.getLogger(LOGGER)\n for line in cutechess_output:\n\n # Check for forwarded errors:\n pattern = r\"[0-9]+ [<>].+: error (.+)\"\n match = re.search(pattern=pattern, string=line)\n if match is not None:\n logger.warning(f\"cutechess-cli error: {match.group(1)}\")\n\n # Check for unknown UCI option\n pattern = r\"Unknown (?:option|command): (.+)\"\n match = re.search(pattern=pattern, string=line)\n if match is not None:\n logger.error(\n f\"UCI option {match.group(1)} was unknown to the engine. \"\n f\"Check if the spelling is correct.\"\n )\n continue\n\n # Check for loss on time\n pattern = (\n r\"Finished game [0-9]+ \\((.+) vs (.+)\\): [0-9]-[0-9] {(\\S+) \"\n r\"(?:loses on time)}\"\n )\n match = re.search(pattern=pattern, string=line)\n if match is not None:\n engine = match.group(1) if match.group(3) == \"White\" else match.group(2)\n logger.warning(f\"Engine {engine} lost on time as {match.group(3)}.\")\n continue\n\n # Check for connection stall:\n pattern = (\n r\"Finished game [0-9]+ \\((.+) vs (.+)\\): [0-9]-[0-9] {(\\S+)'s \"\n r\"(?:connection stalls)}\"\n )\n match = re.search(pattern=pattern, string=line)\n if match is not None:\n engine = match.group(1) if match.group(3) == \"White\" else match.group(2)\n logger.error(\n f\"{engine}'s connection stalled as {match.group(3)}. \"\n f\"Game result is unreliable.\"\n )", "def getoutputerror(self,cmd):\n\n return getoutputerror(cmd,self.verbose,self.debug,self.header,self.split)", "def test_error(self):\n results = yield self.runCommand(\n command_bogusCommand,\n script=\"calendarserver_config\")\n self.assertEquals(results[\"error\"], \"Unknown command 'bogus'\")", "def check_stderr(err):\n global to_print\n if 'IFJ15' not in err:\n to_print += \"UNexpected error output: {}\\n\".format(err)\n return False\n return True", "def test_incorrect_command_return_err_output() -> None:\n session = BashProcess(return_err_output=True)\n output = session.run([\"invalid_command\"])\n assert output == \"/bin/sh: 1: invalid_command: not found\\n\"", "def check_output_errtext(args):\n\n p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n (p_out, p_err) = p.communicate()\n if p.returncode != 0:\n raise Exception(\"Command >>%s<< failed, exit code %i, stderr:\\n%s\"\n % (\" \".join(args), p.returncode, p_err))\n return (p_out, p_err)", "def error(self, message, command):\n if \"error\" in message.trailing:\n print(10 / 0)", "def test_check_false_missing_prog_combined_output(self):\n with self.assertRaises(rh.utils.CalledProcessError) as e:\n rh.utils.run(['./!~a/b/c/d/'], check=True,\n combine_stdout_stderr=True)\n err = e.exception\n self.assertNotEqual(0, err.returncode)\n self.assertIn('a/b/c/d', str(err))", "def run_and_log_error(command):\n try:\n output = subprocess.check_output(command)\n except subprocess.CalledProcessError as e:\n logger.error(e.output)\n logger.error(str(e))\n raise e\n return output.decode()", "def handleErrors(datadogResponse):\n if datadogResponse.get(\"errors\"):\n print(\"One or more errors occurred:\")\n for error in datadogResponse.get(\"errors\"):\n print(\"- %s\" % error)\n exit(1)", "async def read_errors(self) -> list[int]:\n last_5_errors = await self.create_and_send_command(ERRORS)\n logger.debug(f\"Error reading returns {last_5_errors}\")\n return [int(err_code) for err_code in last_5_errors.split(\",\")]", "def test_good_output():\n\n rv, out = getstatusoutput(f'{prg} \"{good_input}\"')\n assert rv == 0\n assert out == good_output\n assert len(out.split()) == 4", "def check_result(result):\n if not result.is_successful():\n print(result.get_message())\n sys.exit()", "def check_output(self, *cmd):\n if self.batch:\n return check_output('bazel', '--batch', *cmd)\n return check_output('bazel', *cmd)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Send request via RabbitMQ
def send_to_rabbit(dialogue: Dialogue): global channel_send _prepare() channel_send.basic_publish( exchange='', routing_key=QUEUE_REQUESTS, body=dumps({'id': dialogue.id, 'request': dialogue.request, 'meta': dialogue.meta}) )
[ "def setup_amqp_req(amqp):\n amqp.request_access(username=hookenv.config('rabbit-user'),\n vhost=hookenv.config('rabbit-vhost'))\n trove.assess_status()", "def test_send_message(self):\n query_string = [('type', 'private'),\n ('to', [56]),\n ('content', 'Hello'),\n ('topic', 'Castle'),\n ('queue_id', '1593114627:0'),\n ('local_id', '100.01')]\n response = self.client.open(\n '/api/v1/messages',\n method='POST',\n query_string=query_string)\n self.assert200(response,\n 'Response body is : ' + response.data.decode('utf-8'))", "def _push_to_amqp(self, msg):\n StatsClientSingleton().incr('amqp.output', count=1)\n payload = dict()\n path = self.request.uri.split('/')[1:]\n payload['type'] = path[0]\n payload['parser_ver'] = path[1]\n payload['env'] = path[2]\n payload['app'] = path[3]\n payload['message'] = msg\n payload['http_content_length'] = len(msg)\n routing_key = \"{}.{}.{}.{}\".format(payload['type'],\n payload['parser_ver'],\n payload['env'], payload['app'])\n\n self.amqp_con.publish(routing_key, json.dumps(payload))", "def keystone_amq_rabbitmq(self):\n\n #Khai báo kết nối\n connection = pika.BlockingConnection(pika.ConnectionParameters(host=self.rpc_host,\n credentials=pika.PlainCredentials(\n username=self.rpc_user,\n password=self.rpc_pass)))\n #Khai báo channel\n channel = connection.channel()\n #Khai báo queue, tạo nếu cần thiết,\n # exclusive chỉ cho phép thao tác bởi phiên hiện tại\n result = channel.queue_declare(exclusive=True)\n #Lấy tên của queue vừa tạo\n queue_name = result.method.queue\n\n # exchange name should be made available as option, maybe advanced\n try:\n #Khởi tạo một exchange mới, nếu tồn tại kiểm tra xem exchange đó có được tạo đúng hay không.\n #http://pika.readthedocs.org/en/latest/modules/channel.html\n channel.exchange_declare(exchange='keystone', type='topic')\n #tạo queue trong một exchange cụ thể\n channel.queue_bind(exchange='keystone', queue=queue_name, routing_key='notifications.info')\n #consumer_callback (method)–The method to callback when consuming with the signature consumer_callback\n # (channel, method, properties,body), where\n # channel: pika.Channel method: pika.spec.Basic.Deliver properties: pika.spec.BasicProperties body: str, unicode, or bytes (python 3.x)\n channel.basic_consume(self.keystone_callback_rabbitmq, queue=queue_name, no_ack=True)\n channel.start_consuming()\n except Exception,e:\n print e", "def test_send_positive():\n init_test_objects.init_env_variables()\n test_client = columba.app.test_client()\n response = test_client.post('/send', data={\n 'from': 'sender@columba.com',\n 'to': 'recipient@columba.com',\n 'subject': 'test subject',\n 'body': 'test body'\n })\n assert response.status_code == 200", "def main():\n RabbitMQVhost()", "def send_to_info_queue(body):\n print(\"trying connection to publisher\")\n connection = pika.BlockingConnection(pika.ConnectionParameters(host='rabbitmq'))\n channel = connection.channel()\n\n channel.queue_declare(queue='infos')\n data = body\n channel.basic_publish(exchange='', routing_key='infos', body=(data)) # TODO: conferir esse dumps, (colocar body=body se der ruim)\n print(\" [x] {body} sent to infos queue\")\n connection.close()", "def _send(self, ready):\n with Sender(self.amqp_url, self.exchange_name, self.topic) as sender:\n # Tell the start() method that we have set up the AMQP\n # communication stuff and are ready to do some work.\n ready.set()\n\n while True:\n msg = self._q.get()\n if msg is None:\n break\n LOG.debug('sending notification %r', msg)\n try:\n sender.send(msg)\n except Exception:\n LOG.exception('could not publish notification')", "def send(self, request, pk=None):\n schedule = self.get_object()\n queue_subscription_send.delay(str(schedule.id))\n\n return Response({}, status=status.HTTP_202_ACCEPTED)", "def mq(request):\n\n\tdef finalizer():\n\t\tsubprocess_call(['docker', 'stop', 'test-mq'], stdout=DEVNULL)\n\t\tsubprocess_call(['docker', 'rm', 'test-mq'], stdout=DEVNULL)\n\n\trequest.addfinalizer(finalizer)\n\tPopen(['docker', 'run', '--name', 'test-mq', '-d', '-p', f'{TEST_MQ_PORT}:5672', 'rabbitmq'], stdout=DEVNULL)\n\n\tdef get():\n\t\treturn MessageQueue.MessageQueue(TEST_MQ_ADDR)\n\n\ttime.sleep(11) # Take time to make sure the docker is up\n\tget.url = TEST_MQ_ADDR\n\treturn get", "def launch(args, message, headers, formatter, position=0):\n credentials = pika.PlainCredentials(args.username, args.password)\n props = pika.BasicProperties(content_type='application/json',\n headers=headers,\n delivery_mode=2)\n connection = pika.BlockingConnection(pika.ConnectionParameters(\n host=args.host,\n port=args.port,\n credentials=credentials))\n channel = connection.channel()\n\n # tqdm the range for pretty metrics\n for i in tqdm(range(args.bunnos), position=position):\n channel.basic_publish(exchange=args.exchange,\n routing_key=args.routing_key,\n properties=props,\n body=formatter.format(message))\n\n connection.close()", "def publish_message(self, message, queue):", "def send_message(queue_name, message, delay_seconds=0):\n queue = sqs_get_queue(queue_name)\n queue.send_message(MessageBody=json.dumps(message), DelaySeconds=delay_seconds)", "def connect_to_rabbitmq():\n credentials = pika.PlainCredentials(os.getenv(\"RABBITUSERNAME\"), os.getenv(\"RABBITPASSWORD\"))\n # establishes connections\n connection = pika.BlockingConnection(\n pika.ConnectionParameters(\n os.getenv(\"RABBITHOSTNAME\"),\n os.getenv(\"RABBITPORTNUM\"),\n '/',\n credentials)\n )\n channel = connection.channel()\n\n return connection, channel", "def sendQueueServiceRequest(self, method, path, query='', data='', content_type='text/plain'):\n date = time.strftime('%a, %d %b %Y %H:%M:%S %Z', time.localtime())\n content_md5 = base64.encodestring(md5.new(data).digest()).strip()\n authorization = '%s:%s' % (base64.encodestring(\n hmac.new(self.secret_key, '%(method)s\\n%(content_md5)s\\n%(path)s' % locals(), sha).digest()).strip())\n\n headers = {\n 'Date': date,\n 'Content-Type': content_type,\n 'Content-Length': len(data)\n }\n\n while True:\n try:\n conn = httplib.HTTPConnection(self.service_host)\n conn.request(method, path + query, data, headers)\n return conn.getresponse()\n except:\n print 'Failed request, sleeping for 15 seconds...'\n time.sleep(15)", "def send(self, command, payload):\n request = WorkRequest(command, payload)\n logging.info(\"Sending {} message to queue {}.\".format(request.command, self.queue_name))\n # setting protocol to version 2 to be compatible with python2\n self.connection.send_durable_message(self.queue_name, pickle.dumps(request, protocol=2))\n logging.info(\"Sent {} message.\".format(request.command, self.queue_name))", "def mq_send(channel, exchange, routing_key, message):\n return channel.basic_publish(exchange, routing_key, message,\n pika.BasicProperties(content_type='text/plain',\n delivery_mode=1))", "def send_durable_message(self, queue_name, body):\n self.connect()\n channel = self.create_channel(queue_name)\n channel.basic_publish(exchange='',\n routing_key=queue_name,\n body=body,\n properties=pika.BasicProperties(\n delivery_mode=2, # make message persistent\n ))\n self.close()", "def send_request_ms(message):\n rospy.wait_for_service(\"message_sending_service\")\n try:\n service = rospy.ServiceProxy(\"message_sending_service\", MessageSendingService)\n\n rospy.loginfo(\"SENDING MESSAGE...\")\n\n response = service(message)\n\n if response.sent:\n rospy.loginfo(\"MESSAGE SENT SUCCESSFULLY!\")\n except rospy.ServiceException as e:\n rospy.loginfo(\"Service access failed: %s\" % e)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Receive request from RabbitMQ. Dialogue and other dialogues may be updated in the database
def receive_from_rabbit(dialogue: Dialogue) -> Dialogue: dialogue_from_db = Dialogue.objects.get(id=dialogue.id) if dialogue_from_db.rabbit_updated: dialogue_from_db.rabbit_updated = False dialogue_from_db.save() return dialogue_from_db global channel_receive _prepare() while True: ok, prop, body = channel_receive.basic_get(queue=QUEUE_RESPONSES, auto_ack=True) if ok is None: # break continue rabbit_response = loads(body) print('RECEIVED {}'.format(rabbit_response)) try: current_dialogue = Dialogue.objects.get(id=int(rabbit_response['id'])) except ObjectDoesNotExist: continue current_dialogue.response = rabbit_response.get('response') current_dialogue.meta = rabbit_response.get('meta', '') if current_dialogue.id == dialogue.id: current_dialogue.rabbit_updated = False else: current_dialogue.rabbit_updated = True current_dialogue.save() if current_dialogue.id == dialogue.id: return current_dialogue
[ "def handle_request(self, cleanup=True):\n try:\n self.amqp_channel.wait()\n finally:\n if cleanup:\n self._cleanup()", "def handle(self):\n request_data = parse_request_json(self.request)\n response = None\n if request_data[SC.MSG_TITLE] == SC.MESSAGE_GET_ROLE:\n response = self.handle_get_role(request_data)\n elif request_data[SC.MSG_TITLE] == SC.MESSAGE_BROADCAST_ROLES:\n response = self.handle_get_network_information(request_data)\n elif request_data[SC.MSG_TITLE] == SC.MESSAGE_PRODUCE_VOTES:\n response = self.handle_produce_votes(request_data)\n elif request_data[SC.MSG_TITLE] == SC.MESSAGE_DISTRIBUTE_VOTES:\n response = self.handle_distribute_votes(request_data)\n else:\n response = self.handle_unexpected_request()\n send_response_json(self.request, response, request_data[SC.MSG_ORIGIN])", "def receive(self):\n self.respone = None\n try:\n def callback(ch, method, properties, body):\n # print(\" [x] Received data\")\n self.response = body\n\n # stops listening\n self.channel.stop_consuming()\n\n self.channel.basic_consume(callback, queue=QUEUENAME, no_ack=True)\n\n print(\" [*] Waiting for messages. To exit press CTRL+C\")\n self.channel.start_consuming()\n return self.response\n # must exit program if user interruption\n except(KeyboardInterrupt, SystemExit):\n raise\n except Exception as e:\n print(e)", "def send_to_rabbit(dialogue: Dialogue):\n global channel_send\n _prepare()\n\n channel_send.basic_publish(\n exchange='',\n routing_key=QUEUE_REQUESTS,\n body=dumps({'id': dialogue.id, 'request': dialogue.request, 'meta': dialogue.meta})\n )", "def handle(self):\n #Send connection confirmation to client\n msg = \"CONNECTED {}\".format(self.client_address[0])\n self.queue.put(msg)\n while True:\n msg = self.queue.get(block=True)\n self.request.sendall(msg)", "def handle_inbound(self):\n while True:\n message = self.inbound_serial_queue.get()", "def __on_request_response__(self, ch, method, props, body):\r\n\t\ttry:\r\n\t\t\tself.last_message = json.loads(body)\r\n\t\texcept ValueError:\r\n\t\t\tprint 'encountered an error while decoding the message'\r\n\t\t\tself.last_message = body\r\n\r\n\t\tself.response = 'received'", "def _handle_comm_message(self, msg):\n\n if 'request_type' in msg['content']['data']:\n r_type = msg['content']['data']['request_type']\n job_id = msg['content']['data'].get('job_id', None)\n parent_job_id = msg['content']['data'].get('parent_job_id', None)\n if job_id is not None and job_id not in self._running_jobs and not parent_job_id:\n # If it's not a real job, just silently ignore the request.\n # Unless it has a parent job id, then its a child job, so things get muddled. If there's 100+ child jobs,\n # then this might get tricky to look up all of them. Let it pass through and fail if it's not real.\n #\n # TODO: perhaps we should implement request/response here. All we really need is to thread a message\n # id through\n self._send_comm_message('job_does_not_exist', {'job_id': job_id, 'request_type': r_type})\n return\n elif parent_job_id is not None:\n try:\n self._verify_job_parentage(parent_job_id, job_id)\n except ValueError as e:\n self._send_comm_message('job_does_not_exist', {'job_id': job_id, 'parent_job_id': parent_job_id, 'request_type': r_type})\n\n if r_type == 'all_status':\n self._lookup_all_job_status(ignore_refresh_flag=True)\n\n elif r_type == 'job_status':\n if job_id is not None:\n self._lookup_job_status(job_id, parent_job_id=parent_job_id)\n\n elif r_type == 'job_info':\n if job_id is not None:\n self._lookup_job_info(job_id, parent_job_id=parent_job_id)\n\n elif r_type == 'stop_update_loop':\n self.cancel_job_lookup_loop()\n\n elif r_type == 'start_update_loop':\n self._start_job_status_loop()\n\n elif r_type == 'stop_job_update':\n if job_id is not None:\n if self._running_jobs[job_id]['refresh'] > 0:\n self._running_jobs[job_id]['refresh'] -= 1\n\n elif r_type == 'start_job_update':\n if job_id is not None:\n self._running_jobs[job_id]['refresh'] += 1\n self._start_job_status_loop()\n\n elif r_type == 'delete_job':\n if job_id is not None:\n try:\n self.delete_job(job_id, parent_job_id=parent_job_id)\n except Exception as e:\n self._send_comm_message('job_comm_error', {'message': str(e), 'request_type': r_type, 'job_id': job_id})\n\n elif r_type == 'cancel_job':\n if job_id is not None:\n try:\n self.cancel_job(job_id, parent_job_id=parent_job_id)\n except Exception as e:\n self._send_comm_message('job_comm_error', {'message': str(e), 'request_type': r_type, 'job_id': job_id})\n\n elif r_type == 'job_logs':\n if job_id is not None:\n first_line = msg['content']['data'].get('first_line', 0)\n num_lines = msg['content']['data'].get('num_lines', None)\n self._get_job_logs(job_id, parent_job_id=parent_job_id, first_line=first_line, num_lines=num_lines)\n else:\n raise ValueError('Need a job id to fetch jobs!')\n\n elif r_type == 'job_logs_latest':\n if job_id is not None:\n num_lines = msg['content']['data'].get('num_lines', None)\n try:\n self._get_latest_job_logs(job_id, parent_job_id=parent_job_id, num_lines=num_lines)\n except Exception as e:\n self._send_comm_message('job_comm_error', {\n 'job_id': job_id,\n 'message': str(e),\n 'request_type': r_type})\n else:\n raise ValueError('Need a job id to fetch jobs!')\n\n else:\n self._send_comm_message('job_comm_error', {'message': 'Unknown message', 'request_type': r_type})\n raise ValueError('Unknown KBaseJobs message \"{}\"'.format(r_type))", "def on_mdp_request(self, msg):\n Plugin.on_mdp_request(self, msg)\n # self.log.info(u\"==> Received 0MQ messages: %s\" % format(msg))\n if msg.get_action() == \"client.cmd\":\n reason = None\n status = True\n data = msg.get_data()\n \n device_id = data[\"device_id\"]\n command_id = data[\"command_id\"]\n if device_id not in self.device_list:\n self.log.error(u\"### MQ REQ command, Device ID '%s' unknown, Have you restarted the plugin after device creation ?\" % device_id)\n status = False\n reason = u\"Plugin onewired: Unknown device ID %d\" % device_id\n self.send_rep_ack(status, reason, command_id, \"unknown\") ; # Reply MQ REP (acq) to REQ command\n return\n\n device_name = self.device_list[device_id][\"name\"]\n self.log.info(u\"==> Received for device '%s' MQ REQ command message: %s\" % (device_name, format(data))) # {u'command_id': 70, u'value': u'1', u'device_id': 169}\n\n status, reason = self.onewire.writeSensor(self.device_list[device_id][\"address\"], self.device_list[device_id][\"properties\"], data[\"value\"])\n if status:\n self.send_pub_data(device_id, data[\"value\"]) # Update sensor command.\n \n # Reply MQ REP (acq) to REQ command\n self.send_rep_ack(status, reason, command_id, device_name) ;", "def handle_offer(self, message):", "def on_message_handled(self, event):\n self.accept(event.delivery)\n print('job accepted: ' + str(event.subject))", "def handle(self) -> None:\n while True:\n raw_command = self.request.recv(1024)\n if not raw_command:\n break\n result = dispatch(self.state, raw_command)\n self.request.send(result)", "def receive_request_message(self):\n if self._current_request:\n try:\n return self._current_request\n finally:\n self._current_request = None\n else:\n raise RuntimeError('Local server tried to receive message more than once')", "def receive(self, input_message):\n request = self._request\n input_message._src_session = self.session_dao.get_session(request)\n logger.debug('Received from %r: %s', request, input_message)\n return self.controller.handle(input_message)", "async def receiver(self):\n try:\n async for serialized_aio_message in self._connection_stream:\n aio_message = AIOMessage()\n aio_message.ParseFromString(serialized_aio_message)\n print(f'AIOConnection:{self._uuid.hex[:8]} got data: {aio_message}')\n await self._server_event_handler(\n self._aio_msg_to_service_request(aio_message))\n\n except trio.BrokenResourceError as e:\n print(f'{e}')", "def consume(self, message: Dict):", "async def consume_messages_from_bus(loop):\n connection = await rabbitmq.get_aio_connection(loop)\n async with connection:\n channel = await connection.channel()\n exchange = await channel.declare_exchange(\n '/messages/:POST', type=aio_pika.exchange.ExchangeType.FANOUT)\n queue = await channel.declare_queue('liveupdate', durable=True)\n await queue.bind(exchange)\n logger.info('waiting for messages...')\n\n async with queue.iterator() as message_iterator:\n async for message in message_iterator:\n with message.process():\n logger.info(\n \"message with delivery_tag={}\".format(\n message.delivery_tag))\n for websocket in connections:\n try:\n await websocket.send(\n json.dumps(\n json.loads(\n message.body.decode()\n )['data']\n ).encode()\n )\n except ConnectionClosed:\n connections.remove(websocket)\n # don't wait until ping finds this dead connection\n logger.info(\n 'connection {} already closed'\n .format(websocket))", "async def handle_msg(self, msg):\n msg = msg.split('|')\n ignore_msg = ['', 'customgroups', 'formats', 'j']\n if len(msg) < 2 or msg[1] in ignore_msg:\n return\n elif msg[1] == 'challstr':\n self.challstr = f'{msg[2]}|{msg[3]}'\n payload = {\n 'act': 'getassertion',\n 'userid': self.name,\n 'challstr': self.challstr,\n }\n res = requests.post(self.http_uri, data=payload)\n await self.sock.send(f'|/trn {self.name},0,{res.text}')\n elif msg[1] == 'updateuser':\n if msg[2] == self.name:\n await self.sock.send('|/utm null')\n await self.on_login()\n else:\n print(f'Unhandled command {msg}')", "async def message_handled(self):\n self.message_queue.task_done()" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Shift f0 by a number of octaves.
def shift_f0(audio_features, f0_octave_shift=0.0): audio_features['f0_hz'] *= 2.0 ** (f0_octave_shift) audio_features['f0_hz'] = np.clip( audio_features['f0_hz'], 0.0, librosa.midi_to_hz(110.0) ) return audio_features
[ "def setNumOfOctaves(self, octaves) -> None:\n ...", "def zero_base_shift(*args):\n return [arg - 1 for arg in args]", "def bandpass_octaves(x, fs, frequencies=NOMINAL_OCTAVE_CENTER_FREQUENCIES, order=8, purge=False, zero_phase=False):\n return bandpass_fractional_octaves(x, fs, frequencies, fraction=1, order=order, purge=purge, zero_phase=zero_phase)", "def bandpass_third_octaves(x, fs, frequencies=NOMINAL_THIRD_OCTAVE_CENTER_FREQUENCIES, order=8, purge=False,\n zero_phase=False):\n return bandpass_fractional_octaves(x, fs, frequencies, fraction=3, order=order, purge=purge, zero_phase=zero_phase)", "def shift(x, n):\n if n > 0:\n return np.pad(x, (n, 0), mode='constant')[:len(x)]\n else:\n return np.pad(x, (0, -n), mode='constant')[-len(x):]", "def x_shift(self, value: int = None):\n if value is None:\n value = 0\n assert value >= 0\n self._x_shift = value", "def octavepass(signal, center, fs, fraction, order=8, zero_phase=True):\n sos = octave_filter(center, fs, fraction, order)\n if zero_phase:\n return _sosfiltfilt(sos, signal)\n else:\n return sosfilt(sos, signal)", "def eval_f_0123(f):\n return [f(0), f(1), f(2), f(3)]", "def unshift(self):\n factor = 1./self.xshift\n self.shift(factor)", "def shift_dft(f):\n y = np.array(f) # copy\n for k, n in enumerate(f.shape):\n mid = (n + 1) / 2\n indices = np.concatenate((np.arange(mid, n), np.arange(mid)))\n y = np.take(y, indices, k) # rearrange each axes\n return y", "def shift_frame_with_wraparound(self, index, shift_x, shift_y):\n\n pil_image = Image.fromarray(self.frames[index])\n im2_offset = ImageChops.offset(pil_image, xoffset=shift_x, yoffset=shift_y)\n self.frames[index] = array(im2_offset)", "def execute_shifts(node):\n shift = 0\n change = 0\n for child in node.children[::-1]: # all children from right to left\n child.prelim += shift\n child.mod += shift\n change += child.change\n shift += child.shift + change", "def SetShift(self, _arg: 'itkOffset2') -> \"void\":\n return _itkCyclicShiftImageFilterPython.itkCyclicShiftImageFilterICVF32ICVF32_SetShift(self, _arg)", "def SetShift(self, _arg: 'itkOffset3') -> \"void\":\n return _itkCyclicShiftImageFilterPython.itkCyclicShiftImageFilterICVF43ICVF43_SetShift(self, _arg)", "def shift(self, dt):\n self.times += dt\n self._t0s = [t+dt for t in self._t0s]", "def getNumOfOctaves(self) -> retval:\n ...", "def octaves_for_note(note):\n return sorted([n for n in range(note,minC-1,-12)] + [n for n in range(note,maxC+1,12)])", "def main():\n\n octal_text = input().strip()\n value = int(octal_text, base=8)\n print(\"{:X}\".format(value))", "def rvShift(wave, **kwargs):\n \n rv = kwargs.get('rv', 0) \n\n shift = 1. + rv/299792.\n rv_wave = wave*shift\n\n return rv_wave", "def SetShift(self, _arg: 'itkOffset3') -> \"void\":\n return _itkCyclicShiftImageFilterPython.itkCyclicShiftImageFilterICVF23ICVF23_SetShift(self, _arg)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get content from all url
def get_content(self, content_url): response = requests.get(content_url) page = response.json() content = page['results'] while page['next'] is not None: content_url = page['next'] response = requests.get(content_url) page = response.json() content += page['results'] return content
[ "def fetch_url_content(self, url):\n response = requests.get(url)\n response.raise_for_status()\n return response.content", "def get_content(nothing):\n url = 'http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing=%s' % nothing\n \n return fetch_url(url)", "def _get_all_url(cls) -> str:", "def get_all_requests():", "def _extract_urls(self, request):\n root = ET.fromstring(request.content)\n self.urls = [child[0].text for child in root]\n # for child in root:\n # self.urls.append(child[0].text)", "def get_page_content(url):\n try:\n res=requests.get(url)\n\n except Exception as e:\n logging.error(e)\n\n if res.ok:\n cont=res.text\n content=cont.replace(\"\\n\",\" \")\n return content\n logging.error(\"can't get content from url: \"+url)\n return None", "def get_html(url): \n \n return requests.get(url)", "def fetch(self, url):\n\n response = self.s.get(url)\n print(\"Getting content from %s, length: %d\" % (url,\n len(response.content)))\n return response", "def get_site_content(url):\n\n req = urllib.request.Request(\n url,\n data=None,\n headers={\n 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47 Safari/537.36'\n }\n )\n\n response = urllib.request.urlopen(\n req,\n timeout=4\n )\n \n return response.read().decode(\"utf-8\", \"ignore\")", "def read_content():\n content = []\n with open(\"index.html\", \"r\") as html:\n content = html.readlines()\n \n return content", "def get(self):\n req = requests.get(self.url_base+self.url_archive, headers=self.headers)\n LOGGER.debug('Got the response for the archive page')\n while req.status_code != 200:\n LOGGER.error('Response was not 200. Trying again...')\n req = requests.get(self.url_base+self.url_archive)\n soup = BeautifulSoup(req.text, 'lxml')\n links = soup.find_all(self.paste_tag)\n LOGGER.debug('Got %d links from page', len(links))\n return [self.paste(urljoin(self.url_base, link.a.get('href'))) for link in links]", "def get_page_content(url):\n\t\n\ttry:\n\t\tresponse = requests.get(url)\n\t\t#print(response.ok)\n\texcept requests.exceptions.RequestException as e:\n\t\tlogging.error(e)\n\n\n\tif(response.ok):\n\t\treturn response.text\n\n\tlogging.error(\"Cannot get content from URL: \" + url)\n\n\treturn None", "def download_all_htmls():\n htmls = []\n\n for idx in range(24):\n url = f\"http://www.crazyant.net/page/{idx+1}\"\n print(\"Crawl html: \", url)\n r = requests.get(url)\n\n if r.status_code != 200:\n raise Exception(\"Error!\")\n htmls.append(r.text)\n \n return htmls", "def fetch_page_content(url):\n try: \n page = requests.get(url)\n soup = BeautifulSoup(page.text, \"html.parser\")\n\n #Checking if the page is a redirected page.\n redirectedSpan = soup.find_all(\"span\", {\"class\" : \"mw-redirectedfrom\"})\n if redirectedSpan:\n print(\"Skipping redirected page . . .\")\n return None\n\n #download the document\n download_page(url,soup)\n append_url_to_file(url)\n\n # Fetch relevant content\n return soup.find(\"div\", id=\"bodyContent\")\n\n except Exception as e:\n print(\"Error occured while fetching page. .\")", "def content_and_links(url: str) -> Tuple[str, Set[str]]:\n\n content = get(url)\n links = set()\n if content is not None:\n links = links_from_text_file(content)\n\n return content, links", "def get_links(url):\n links = []\n res = requests.get(url,headers=header).content\n s = etree.HTML(res)\n for i in s.xpath('//img/@src'):\n if i.startswith('http') and i.endswith('.jpg'):\n links.append(i)\n # print(links[3])\n return links", "def fetch_url(self, url):\n url_data = {\n \"url\": url,\n \"content\": None,\n \"size\": 0\n }\n corp_file_name = self.corpus.get_file_name(url) #Using Corpus method to get file_name associated with URL\n content = b'' #To initialize binary content\n for data in open(corp_file_name, mode = 'rb'):\n content += data #To iterate through the data by opening the file\n if corp_file_name != None: #Updating the dictionary with newly obtained content and size of file\n url_data[\"content\"] = content \n url_data[\"size\"] = os.path.getsize(corp_file_name) \n return url_data", "def get_content(url):\n host = 'https://www.ted.com'\n html = get_html(url)\n\n soup = BeautifulSoup(html, 'html.parser')\n desc = soup.find('p', {'class': \"talk-description\"}).contents[0].strip()\n location = soup.find('div', {'class': \"player-hero__meta\"}).strong.contents[0].strip()\n filmed_time = soup.find('div', {'class': \"player-hero__meta\"}).findAll('span')[1].contents[-1].strip()\n subtitle_url = host + soup.find('div', {'class': \"talk-more\"}).a.get('href', '')\n subtitle = get_subtitle(subtitle_url)\n author = soup.find('div', {'class': \"talk-speaker__details media__message\"})\n author_info = {'name': author.find('div', {'class': \"talk-speaker__name h10\"}).a.contents[0].strip(),\n 'url': host + author.find('div', {'class': \"talk-speaker__name h10\"}).a.get('href', ''),\n 'position': author.find('div', {'class': \"talk-speaker__description\"}).contents[0].strip(),\n 'desc': author.find('div', {'class': \"talk-speaker__bio\"}).contents[0].strip()}\n return author_info, desc, subtitle, location, filmed_time", "def get_all_books(self, url):\n soup = self.get_soup(url)\n base_url = \"/\".join(url.split(\"/\")[:-1]) + \"/\" \n all_books_on_page = [base_url + x.div.a.get('href') for x in soup.findAll(\"article\", class_ = \"product_pod\")]\n \n return all_books_on_page" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return whether exactly two of the arguments are equal and the third is not. >>> two_equal(1, 2, 3) False >>> two_equal(1, 2, 1) True >>> two_equal(1, 1, 1) False >>> result = two_equal(5, 1, 1) return, don't print >>> result True
def two_equal(a, b, c): l = [a,b,c] if len(set(l)) == 2: return True else: return False
[ "def two_equal(a, b, c):\n if a == b and b != c:\n return True\n elif b == c and c != a:\n return True\n elif c == a and a != b:\n return True\n else:\n return False", "def is_same_or_all_different(a: T, b: T, c: T) -> bool:\n is_same = a == b and b == c\n if is_same:\n return True\n is_different = a != b and b != c and a != c\n if is_different:\n return True\n return False", "def eq_(a, b, msg=None):\n assert a == b, msg or \"%r != %r\" % (a, b)", "def compare_values(self, x, y):\n return x == y", "def _equal(self, condition: bool) -> bool:\n return not(condition ^ self.same)", "def are_equal(self, other):\n warn( \"Use is_equal instead of are_equal\", DeprecationWarning, 2)\n return self.is_equal(other)", "def assert_not_equal(first, second, msg=\"\"):\n if first == second:\n raise AssertionError(\"%s and %s are equal, message: %s\" % (first, second, msg))", "def test_assertNotEqual_equal(self):\n for first, second in self.equal_pairs:\n try:\n self.assertNotEqual(first, second)\n except:\n message = str(exc_info()[1])\n self.assertEqual(message,\n 'Observed %s and expected %s: shouldn\\'t test equal' \\\n % (`first`, `second`))\n else:\n raise AssertionError, \\\n \"unit_test.assertNotEqual failed on input %s and %s\" \\\n % (`first`, `second`)", "def equal_fractions(a, b):\n if type(compare(a, b)) != bool:\n raise Exception(\"compare method is not implemented correctly!\")\n if type(compare(b, a)) != bool:\n raise Exception(\"compare method is not implemented correctly!\")\n return (not compare(a, b)) and (not compare(b, a))", "def equals(point1, point2):\n return point1[0] == point2[0] and point1[1] == point2[1]", "def equal(x1: ArrayOrScalar, x2: ArrayOrScalar) -> Union[Array, bool]:\n return _compare(x1, x2, \"==\")", "def qthread_equal(*args) -> \"bool\":\n return _ida_pro.qthread_equal(*args)", "def test_assertNotEqual_unequal(self):\n for first, second in self.unequal_pairs:\n try:\n self.assertNotEqual(first, second)\n except:\n raise AssertionError, \\\n \"unit_test.assertNotEqual failed on input %s and %s\" \\\n % (`first`, `second`)", "def assertEqual(a, b):\n assert a == b", "def same_values(self, v1, v2):\n return v1 == v2", "def type_safe_eq(first, second):\n if isinstance(first, _STRUCT_TYPES) or isinstance(second, _STRUCT_TYPES):\n return first is second\n\n # If the values are empty or of the same type, no coersion necessary.\n # TODO(dcphillips): Do a more basic type equality check if it's not slower\n # (b/16661176).\n if first is None or second is None or type(first) == type(second):\n return first == second\n\n try:\n # TODO(dcphillips): This potentially loses precision for very large numbers.\n # See b/16241488.\n if isinstance(first, _NUMBER_TYPES) and not isinstance(first, bool):\n return first == float(second)\n if isinstance(second, _NUMBER_TYPES) and not isinstance(second, bool):\n return float(first) == second\n\n if isinstance(first, six.string_types):\n return first == str(second)\n if isinstance(second, six.string_types):\n return str(first) == second\n except ValueError:\n # Ignore type coersion failures\n pass\n\n return first == second", "def _two_pairs(self, cards: List[Card]) -> bool:\n counts_per_rank = self._get_counts_per_rank(cards)\n return list(counts_per_rank).count(2) == 2", "def nets_equal(net1, net2, check_only_results=False, check_without_results=False, exclude_elms=None,\n name_selection=None, **kwargs):\n if not (isinstance(net1, pandapowerNet) and isinstance(net2, pandapowerNet)):\n logger.warning(\"At least one net is not of type pandapowerNet.\")\n return False\n not_equal, not_checked_keys = nets_equal_keys(\n net1, net2, check_only_results, check_without_results, exclude_elms, name_selection,\n **kwargs)\n if len(not_checked_keys) > 0:\n logger.warning(\"These keys were ignored by the comparison of the networks: %s\" % (', '.join(\n not_checked_keys)))\n\n if len(not_equal) > 0:\n logger.warning(\"Networks do not match in DataFrame(s): %s\" % (', '.join(not_equal)))\n return False\n else:\n return True", "def equals(tile1, tile2) -> bool:\n\n # compare y dim\n if len(tile1) != len(tile2):\n return False\n\n # compare x dim\n if len(tile1[0]) != len(tile2[0]):\n return False\n\n # compare square by square\n for i in range(len(tile1)):\n for j in range(len(tile1[0])):\n if tile1[i][j] != tile2[i][j]:\n return False\n\n return True" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the integer height of a neargolden rectangle with PERIMETER. >>> near_golden(42) 8 x 13 rectangle has perimeter 42 8 >>> near_golden(68) 13 x 21 rectangle has perimeter 68 13 >>> result = near_golden(100) return, don't print >>> result 19
def near_golden(perimeter): smallest = perimeter for w in range(1, perimeter//2): h = perimeter//2 - w dif = abs(h/w - (w/h-1) ) if dif < smallest: smallest = dif h_best = h return h_best
[ "def near_golden(perimeter):\n height = 1\n while height < perimeter/2:\n width = perimeter/2 - height\n if abs(height/width - width/height + 1) < 0.02:\n return height\n height += 1cd", "def height_tree(tree: Tree) -> int:\n if tree is None:\n return -1\n left_heigth = height_tree(tree.left)\n right_heigth = height_tree(tree.right)\n return 1 + max([left_heigth, right_heigth])", "def get_area_rectangle(w, h):\n return -1.0", "def height(self) -> int:\n node = self.root\n return self.height_help(node)", "def getHeight(self):\n return self.tree_height", "def get_height():\n while True:\n val = get_int(\"Height: \")\n if 0 <= val <= 23:\n return val", "def rectangle_area(w,h):\n return w*h", "def height(t):\n\tif t is None:\n\t\treturn 0\n\treturn 1 + max( height(t.left) , height(t.right) )", "def maxHeightOfGround(self, vertices=[\"nearMiddle\"]):\n\t\th = []\n\t\tfor v in vertices:\n\t\t\th.append(self.dots[v].heightFromGround)\n\t\th.sort(reverse=True)\n\t\treturn h[0]", "def get_height(self):\n\t\treturn self.y[1] - self.y[0]", "def bottom_height_px(self):\n return self.bottom_pieces * PIPE_PIECE_HEIGHT", "def get_height(self):\n try:\n return self.image.height\n except Exception:\n return 0", "def bottom_height_px(self):\n return self.bottom_pieces * PipePair.PIECE_HEIGHT", "def rectangle_perimeter(w,h):\n return 2.0*(w+h)", "def getFrameHeight(self):\n hebs = self.getGitesForProprio()\n hebCount = len(hebs)\n height = 135\n if hebCount > 1:\n baseHeight = 100\n height = baseHeight + (hebCount * 55)\n return height", "def _get_height(self) -> \"double\" :\n return _core.OrientedBoundingBox3D__get_height(self)", "def height(self):\n return self.tree_height", "def _get_height(self) -> \"int\" :\n return _core.Palette__get_height(self)", "def tree_height(self)->int:\n #---- to do ----\n # complete this method by calling bst.tree_height()\n # return the height of the tree\n # return -1 if the tree is empty\n #---------------\n if self.num_items == 0:\n return -1\n return bst.tree_height(self.tree)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the case insensitive word in text that has most vowels. Return a tuple of the matching word and the vowel count, e.g. ('objectoriented', 6)
def get_word_max_vowels(text): count = 0 max_vowel_count = [] text = [word.lower() for word in text.split()] for word in text: num_vowels = Counter([letter for letter in word\ if letter in VOWELS]) vowel_sum = sum(num_vowels.values()) if vowel_sum >= count: count = vowel_sum max_vowel_count.append((word, vowel_sum)) return [tup for tup in max_vowel_count if tup[1] == count]
[ "def get_word_max_vowels(text):\r\n vowel_counts = [(word, sum(word.count(vowel) for vowel in VOWELS)) for word in text.split()]\r\n return max(vowel_counts, key=itemgetter(1))", "def num_vowels(word):\n return sum(char in VOWELS for char in word.lower())", "def search4vowels(word):\n vowels = set('aeiou')\n return vowels.intersection(set(word))", "def count_vowels(string):\n count = 0\n for character in string.lower():\n if character in \"aeiou\":\n count += 1\n return count", "def count_vowels(string):\n vowel_counter = Counter()\n char_list = []\n\n for char in string:\n if char in vowels:\n char_list.append(char)\n vowel_counter[char] += 1\n str_list = list(set(char_list))\n vowel_string = ''.join(str_list)\n\n duplicates = 0\n\n for value in vowel_counter.values():\n if value >= 2:\n duplicates += 1\n return (vowel_string, duplicates)", "def eng_word_candidates(word, language_model):\n res_list = [x[0] for x in language_model[word].most_common()]\n return res_list", "def count_vowel(s):\n count = 0\n for i in s:\n\tif i == 'a' or i == 'e' or i == 'i' or i == 'o' or i == 'u':\n\t count += 1\n print \"Number of vowels:%d\" %count", "def vowel_count(phrase):\n # Add a comment to practice committing from VS Code\n low_phrase = phrase.lower()\n d = {}\n for l in low_phrase:\n if l in \"aeiou\":\n if l in d:\n d[l] = d[l] + 1\n else:\n d[l] = 1\n return d", "def count_vowels(s):\r\n\r\n count_vowels = 0\r\n\r\n for char in s:\r\n if char in \"aeiouAEIOU\":\r\n count_vowels = count_vowels + 1\r\n return count_vowels", "def calc_word_value(w):\n som = 0\n q = list(w)\n for i in q:\n if (i in string.ascii_lowercase) or (i in string.ascii_uppercase):\n som += LETTER_SCORES[i.upper()]\n return som", "def number_of_vowels_and_consonants(string: str) -> Tuple[int, int]:\n string = string.lower()\n all_letters = set('abcdefghijklmnopqrstuvwxyz')\n vowels = set('aeiou')\n vowel_count = sum([string.count(v) for v in vowels])\n consonant_count = sum([string.count(c) for c in all_letters.difference(vowels)])\n return vowel_count, consonant_count", "def vowel_indices(word):\n return [i + 1 for i, j in enumerate(word) if j.lower() in \"aeiouy\"]", "def CountVowels(phrase):\n ALWAYS_VOWELS = \"aeiou\"\n spurious = string.punctuation + '0123456789_'\n count = 0\n for word in phrase.lower().split():\n word = word.strip(spurious)\n l_word = len(word)\n for index, char in enumerate(word):\n if char in ALWAYS_VOWELS:\n count += 1\n continue\n if char != 'y' or index == 0:\n # now, char is 'y' and not the first char\n continue\n if word[index-1] in ALWAYS_VOWELS:\n # preceded by a vowel\n continue\n if word.endswith('ying') and index == l_word - 4:\n count += 1\n continue\n # now, it is a 'y' preceded by a consonant\n if (index == l_word - 1 # at end of word\n or word[index+1] not in ALWAYS_VOWELS):\n # or followed by a consonant\n count += 1\n continue\n return count", "def max_wupa(context_sentence, ambiguous_word):\n \n result = {}\n for i in wn.synsets(ambiguous_word):\n result[i] = sum(max([i.wup_similarity(k) for k in wn.synsets(j)]+[0]) \\\n for j in word_tokenize(context_sentence))\n result = sorted([(v,k) for k,v in result.items()],reverse=True)\n return result", "def search4vowels(word):\n vowels = {'a','e','i','o','u'} #or vowels = set('aeiou')\n found = vowels.intersection(set(word))\n for vowel in found:\n print(vowel)", "def maxchar_option_1(string):\n return Counter(string).most_common()[0][0]", "def GetTopWord(text,num_w):\n cc = Counter(text.split()).most_common(num_w)\n return ' '.join([cw[0] for cw in cc])", "def calc_word_value(word):\n score = 0\n for w in word.upper():\n for k, v in LETTER_SCORES.items():\n if k == w:\n score += v\n return score", "def most_common_word(words, text):\n word_frequency = {w: text.count(w) for w in words}\n return sorted(words, key=word_frequency.get)[-1]" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get seasonlevel Fielding Statistics for Specific Team (from BaseballReference)
def team_fielding_bref(team: str, start_season: int, end_season: Optional[int]=None) -> pd.DataFrame: if start_season is None: raise ValueError( "You need to provide at least one season to collect data for. " + "Try team_fielding_bref(season) or team_fielding_bref(start_season, end_season)." ) if end_season is None: end_season = start_season url = "https://www.baseball-reference.com/teams/{}".format(team) raw_data = [] headings: Optional[List[str]] = None for season in range(start_season, end_season+1): stats_url = "{}/{}-fielding.shtml".format(url, season) response = session.get(stats_url) soup = BeautifulSoup(response.content, 'html.parser') fielding_div = soup.find('div', {'id': 'all_standard_fielding'}) comment = fielding_div.find( string=lambda text: isinstance(text, Comment)) fielding_hidden = BeautifulSoup(comment.extract(), 'html.parser') table = fielding_hidden.find('table') thead = table.find('thead') if headings is None: headings = [row.text.strip() for row in thead.find_all('th')] rows = table.find('tbody').find_all('tr') for row in rows: cols = row.find_all(['td', 'th']) cols = [ele.text.strip() for ele in cols] # Removes '*' and '#' from some names cols = [col.replace('*', '').replace('#', '') for col in cols] # Removes Team Totals and other rows cols = [ col for col in cols if 'Team Runs' not in col ] cols.insert(2, season) raw_data.append(cols) assert headings is not None headings.insert(2, "Year") data = pd.DataFrame(data=raw_data, columns=headings) data = data.dropna() # Removes Row of All Nones postprocessing.coalesce_nulls(data) postprocessing.convert_percentages(data, ['CS%', 'lgCS%']) postprocessing.convert_numeric( data, postprocessing.columns_except( data, ['Team', 'Name', 'Pos\xa0Summary'] ) ) return data
[ "def test_fantasy_defense_season_stats_by_team(self):\n pass", "def test_player_season_stats_by_team(self):\n pass", "def test_team_season_stats(self):\n pass", "def get_seasonal_statistics(self, season_id, wnba_season, team_id):\n path = \"wnba/trial/v4/en/seasons/{season_id}/{wnba_season}/teams/{team_id}/statistics\".format(\n season_id=season_id, wnba_season=wnba_season, team_id=team_id)\n print(path)\n return self._make_request(path)", "def _get_defense_stats(self, team):\n pass", "def season_statsheet(self, request):\n return request.getfixturevalue(request.param)", "def team_info(self):\n df_team = pd.read_csv(datadir / 'TEAM.csv.gz')\n\n team_cols = {\n 'gid': 'game_id',\n 'tname': 'team',\n #'pts': 'tm_pts',\n 'ry': 'tm_rush_yds',\n 'ra': 'tm_rush_att',\n 'py': 'tm_pass_yds',\n 'pa': 'tm_pass_att',\n 'pc': 'tm_pass_comp',\n 'sk': 'tm_sacks',\n 'sky': 'tm_sack_yds',\n 'ints': 'tm_ints',\n 'iry': 'tm_int_yds',\n 'fum': 'tm_fumbles',\n 'pu': 'tm_punts',\n 'gpy': 'tm_punt_yds',\n 'fgm': 'tm_field_goals',\n 'fgat': 'tm_field_goal_att',\n 'pen': 'tm_penalty_yds',\n 'top': 'tm_possess_time',\n 'tdp': 'tm_pass_tds',\n 'tdr': 'tm_rush_tds',\n 'td': 'tm_tds',\n 'qba': 'tm_qb_rush_att',\n 'qby': 'tm_qb_rush_yds'}\n\n df_team = df_team[team_cols.keys()].rename(team_cols, axis=1)\n\n df_team = df_team.merge(self.quarterback_info, on=['game_id', 'team'])\n\n return df_team", "def _gather_stats(self):\n # Set all values to zero\n self.wins = 0\n self.ties = 0\n self.losses = 0\n self.season_len = 0\n self.points = 0\n self.vs_points = 0\n self.win_percentage = 0.0\n self.point_difference = 0\n self.wins_vs_teams = []\n self.losses_vs_teams = []\n self.ties_vs_teams = []\n self.record_vs_teams = []\n self.f_record_vs_teams = []\n wins_list = []\n losses_list = []\n ties_list = []\n opponents = []\n # Gather statistics\n for g in self.season:\n # Gather the number of games won, lost, and tied\n g_result = g['result']\n opponent = g['vs']\n if opponent not in opponents:\n opponents.append(opponent)\n if g_result == 'w':\n self.wins += 1\n wins_list.append(g)\n elif g_result == 'l':\n self.losses += 1\n losses_list.append(g)\n elif g_result == 't':\n self.ties += 1\n ties_list.append(g)\n self.season_len += 1\n # Gather the number of runs scored\n g_points = g['points']\n self.points += g_points\n # Gather the number of runs scored by opponents\n g_vs_points = g['vs_points']\n self.vs_points += g_vs_points\n\n for opponent in opponents:\n self.wins_vs_teams.append(self._records_vs(wins_list, opponent))\n self.losses_vs_teams.append(self._records_vs(losses_list, opponent))\n self.ties_vs_teams.append(self._records_vs(ties_list, opponent))\n # Calculate win percentage\n try:\n self.win_percentage = self.wins / self.season_len\n except ZeroDivisionError:\n self.win_percentage = None\n\n # Calculate difference in points\n self.point_difference = self.points - self.vs_points\n\n # Calculate record against opponents\n for x in range(len(opponents)):\n self.record_vs_teams.append({opponents[x]: {'w': self.wins_vs_teams[x][opponents[x]],\n 'l': self.losses_vs_teams[x][opponents[x]],\n 't': self.ties_vs_teams[x][opponents[x]]}})\n self.f_record_vs_teams.append(\n f\"\"\"{opponents[x]}: {self.wins_vs_teams[x][opponents[x]]}-{self.losses_vs_teams[x][opponents[x]]}-{self.ties_vs_teams[x][opponents[x]]}\"\"\")", "def test_game_stats_by_season_deprecated_use_team_game_stats_instead(self):\n pass", "def test_teams_by_season(self):\n pass", "def test_fantasy_defense_game_stats_by_team(self):\n pass", "def _get_league_score_on_year(league_name, season): \n # get table with team name along with home goal and away goal.\n query = \"select r3.name as League_name, r.team_long_name as home_team_name1, \\\n r.team_short_name as home_team_name2,r2.team_long_name as away_team_name1, r2.team_short_name as \\\n away_team_name2,l.season,l.home_team_goal,l.away_team_goal from Match as l left join Team as r \\\n on l.home_team_api_id = r.team_api_id \\\n left join Team as r2 \\\n on l.away_team_api_id=r2.team_api_id\\\n left join League as r3\\\n on l.league_id = r3.id;\"\n df = _get_table(query, conn)\n # get all matches in one season for one league.\n res_df = df[(df.League_name == league_name) & (df.season == season)]\n # get all goals scored in home and away team.\n all_goals = [sum(res_df.home_team_goal),sum(res_df.away_team_goal)]\n # get individual teams goal\n teams_goals_df = res_df.groupby(by = \"home_team_name1\").sum()[[\"home_team_goal\",\"away_team_goal\"]]\n teams_goals_df[\"tot_goals\"] = teams_goals_df.home_team_goal + teams_goals_df.away_team_goal\n top_4_home_teams = teams_goals_df.sort_values(by=\"tot_goals\",ascending=False).head(4)\n return top_4_home_teams", "def test_fantasy_defense_season_stats(self):\n pass", "def team_quality(self, season):\n formula = 'win~-1+T1_TeamID+T2_TeamID'\n glm = sm.GLM.from_formula(formula=formula, \n data=self.regular_results.loc[self.regular_results.Season==season,:], \n family=sm.families.Binomial()).fit()\n \n # extracting parameters from glm\n quality = pd.DataFrame(glm.params).reset_index()\n quality.columns = ['TeamID','beta']\n quality['Season'] = season\n # taking exp due to binomial model being used\n quality['quality'] = np.exp(quality['beta'])\n # only interested in glm parameters with T1_, as T2_ should be mirroring T1_ ones\n quality = quality.loc[quality.TeamID.str.contains('T1_')].reset_index(drop=True)\n quality['TeamID'] = quality['TeamID'].apply(lambda x: x[10:14]).astype(int)\n return quality\n \n\n return quality", "def get_stats():\n input = request.get_json()\n query = input[\"query\"]\n print(\"Stats query received:\", input)\n \"\"\"\n # Differentiate between a query for season, or team (TODO)\n if any(char.isdigit() for char in query):\n # If query contains digits, probably a season year query, e.g. \"2019\"\n\n else:\n \"\"\"\n # Otherwise, a team name\n try:\n team = SD.get_team(query)\n except:\n return jsonify({\"/api/get-stats\": \"Team name query failed to load.\"})\n return jsonify(team.stats_json())", "def _getSeason(self):\n # TODO: Add a RegEx for matching out the Season Number\n pass", "def player_season_stats(player_name, player_id):\n\n try:\n player_gamelog = playergamelog.PlayerGameLog(player_id=str(player_id), season='2020',\n season_type_all_star='Regular Season')\n except:\n raise Exception(f'Failed to get data on player {player_name}')\n sleep(0.25)\n temp = required_stats.copy()\n temp.extend(['GAME_DATE', 'Player_ID'])\n data = player_gamelog.get_data_frames()[0][temp]\n\n return data # return data as df which will be added to another larger df as a dictionary", "def _get_offense_stats(self, team):\n pass", "def team_statsheet(self, request):\n return request.getfixturevalue(request.param)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Updates the character whether the user got the question right or wrong.
def update_character(both_correct, character, is_complete, is_correct, type, user, session_number): now = datetime.datetime.now() base_character = BaseCharacter.objects.get(character=character) user_object = User.objects.get(username=user.username) character_object = ProgressCharacter.objects.get(character=base_character, user=user_object) if is_complete: character_object.num_times_shown += 1 if is_correct: character_object.last_correct = True character_object.num_correct[type] += 1 else: character_object.last_correct = False character_object.num_current_incorrect[type] += 1 if both_correct: new_level = get_level(character_object) character_object.num_correct['all'] += 1 character_object.last_reviewed_date = now character_object.upcoming_review_date = get_upcoming_review_date(now, new_level) character_object.level = new_level character_object.num_current_incorrect['pinyin'] = 0 character_object.num_current_incorrect['definitions'] = 0 character_object.last_session = session_number user_object.last_session = session_number character_object.save() if check_level_up(user_object): level_up(user_object) return character_object.to_json()
[ "def process_question(self):\n for rb in self.rbs:\n rb.configure(state = DISABLED)\n if self.var.get()==self.questions[self.index].answer: \n self.correct += 1\n self.feedback.config(text = \"Correct! \" + str(self.correct) + \"/\" + str(self.index + 1))\n else:\n self.feedback.config(text = \"Incorrect! The answer is \"+ self.questions[self.index].answer + \" \" +\n str(self.correct) + \"/\" + str(self.index + 1))", "def correcting(self):\n self.current = State.CORRECTING", "def checkAnswer(self):\n if self.translate == self.user_response:\n return True\n else:\n return False", "def correct_answer_response():\n return '\\nCorrect!'", "def update_question(self, question):\r\n self.question = question\r\n self.question_text.configure(\r\n text=self.question['Question']\r\n )\r\n self.question_text.update()", "def _do_updates(self):\n player = self._roster.get_current()\n guess = player.get_guess()\n #self._console.write(self.hint_key)\n self._board.current_guess(player, guess)", "def checkCorrect(word, guessedLetters):\n #return True or False", "def is_player_ready(question, answer_type):\n answer = str(input(question))\n return True if answer.lower() in answer_type else False", "def check_button_clicked(self):\n\n all_line_edit_fields = (self.ja, self.ty, self.on_ona_ono, self.my, self.wy, self.oni_one)\n right_answers = 0\n current_verb = self.verb.text().encode('utf-8')\n #print current_verb, type(current_verb)\n self.dbCursor.execute('SELECT * FROM Main WHERE verb=?', (current_verb,))\n allForms = self.dbCursor.fetchall()\n for form in allForms:\n for x in range(2, 8):\n this_line_edit = all_line_edit_fields[x-2]\n what_user_enters = this_line_edit.text().encode('utf-8')\n if form[x] == what_user_enters:\n right_answers += 1\n this_line_edit.setStyleSheet(\"\"\"border: 2px solid #00c322; border-style: outset;\n border-radius: 3px; background-color: white\"\"\")\n else:\n this_line_edit.setStyleSheet(\"\"\"border: 2px solid #ff3300; border-style: outset;\n border-radius: 3px; background-color: white\"\"\")\n\n if right_answers == 6:\n if self.can_take_point:\n self.number_of_right_answers += 1\n self.label_with_result.setText(`self.number_of_right_answers`)\n self.can_take_point = False\n else:\n pass", "def cmd_wrmpractice(self, data, client, cmd=None):\n # we need the cvar of the practice mode\n var_practice = self.console.getCvar('wrm_practiceMode')[0]\n var_practicedefault = self.console.getCvar('wrm_practiceMode')[1] \n if not data: \n if not var_practicedefault:\n # it hasnt been set in the config yet, no problem \n client.message('^7Unable to find WRM cvar')\n return False\n else:\n cmd.sayLoudOrPM(client, '^7Practice mode : ^1%s' % var_practice) \n return False\n else:\n # check to see what they entered\n if data == 'on': \n self.console.setCvar( 'wrm_practiceMode', '1')\n self.console.say('^9Practice Mode: ^1ON')\n else: \n self.console.setCvar( 'wrm_practiceMode', '0')\n self.console.say('^9Practice Mode: ^1OFF')\n return True", "def update_question(questid, userid):\n\n quest = db(current.db.question.id == questid).select().first()\n\n answers_per_level = 3\n\n # first step is to select the related user and question records their should\n # only ever be one of each of these and we update as much as possible here \n # because it's interesting to see as much as possible on viewquest rather\n # than waiting until 3 people have answered and it can be scored - however this can result in\n # a degree of double updating\n\n if quest.intunpanswers >= answers_per_level:\n redirect(URL('score_question', args=quest.id))\n else:\n # need to have another look at this \n # intunpanswers < answers_per_level\n # the general requirement here is to do nothing - however because the\n # solution focuses on solving the highest priority question at all times\n # different users may be sent the same question at the same time and\n # answers may be received for a level after the question is either promoted\n # or resolved - promotions shouldn't be an issue but resolved questions are\n # because the user should probably get credit if right and nothing if wrong\n # and an explanation of what happend\n\n if quest.status == 'Resolved' or quest.status == 'Agreed':\n # get the score - if right add to score - if wrong same\n # update userquestion and user - other stuff doesn't apply\n # scoretable = current.db(current.db.scoring.level == quest.level).select(cache=(cache.ram, 1200), cacheable=True).first()\n scoretable = current.db(current.db.scoring.level == quest.level).select().first()\n if scoretable is None:\n score = 30\n wrong = 1\n else:\n if quest.qtype != 'action':\n score = scoretable.correct\n wrong = scoretable.wrong\n else:\n score = scoretable.rightaction\n wrong = scoretable.wrongaction\n numcorrect = 0\n numwrong = 0\n numpassed = 0\n\n if uq.answer == quest.correctans:\n updscore = score\n numcorrect = 1\n elif uq.answer == 0:\n updscore = 1\n numpasse = 1\n else:\n updscore = wrong\n numwrong = 1\n\n uq.update_record(status='Resolved', score=updscore, resolvedate=request.utcnow)\n\n updateuser(userid, updscore, numcorrect, numwrong, numpassed)\n\n redirect(URL('viewquest', 'index', args=quest.id))", "def question(self, text):\n\t\tself.resetBuffer()\n\t\tself.font = ['Arial', 11]\n\t\tquestion_width, question_height = self.lineText(text, [3, 25])\n\n\t\tself.font = ['Arial', 12]\n\t\t#button OK\n\t\tself.rectangle([[150,0],[192,20]], False)\n\t\tself.rectangle([[153,3],[192,17]], False)\n\t\tself.line([[150,0],[153,3]], 1)\n\t\tself.line([[150,20],[153,17]], 1)\n\n\t\tself.lineText('OK', [164, 4])\n\t\t#button NG\n\t\tself.rectangle([[150,43],[192,63]], False)\n\t\tself.rectangle([[153,46],[192,60]], False)\n\t\tself.line([[150,43],[153,46]], 1)\n\t\tself.line([[150,63],[153,60]], 1)\n\t\tself.lineText('NG', [164, 47])\n\t\tself.rewrite()\n\n\t\t#set buttons\n\t\tself.readyButtons('BOTH')\n\t\twhile 1:\n\t\t\t#load buttons and w8 for push OK or NG\n\t\t\tbuttons = self.buttons()\n\t\t\tif buttons in ['OK', 'NG']:\n\t\t\t\tself.readyButtons('BOTH', False)\n\t\t\t\treturn buttons\n\t\t\ttime.sleep(0.1)", "def update_security_question(self, password, question, answer):\n url = f'{self._okta.api}/users/{self.id}/credentials/change_recovery_question'\n payload = {\"password\": {\"value\": password},\n \"recovery_question\": {\"question\": question,\n \"answer\": answer}}\n response = self._okta.session.post(url, data=json.dumps(payload))\n if not response.ok:\n self._logger.error(response.text)\n return response.ok", "def _wrong_answer(self):\n self.chances -= 1\n if self.chances > 0:\n text = (\n Dialogues.KREUZER_WRONG_CHOICE_LAST\n if self.question_state.fifth\n else Dialogues.KREUZER_WRONG_CHOICE_DEFAULT\n )\n else:\n text = Dialogues.KREUZER_TOO_MANY_WRONG_CHOICES\n self.quiz_over = True\n self.dialogue_box.make_textbox(text)\n self._update_and_wait()\n while self.quiz_over:\n self.menu.leave = True\n self.quiz_failed = True\n self.window.screen.fill(Colors.BLACK)\n self.dialogue_box.make_textbox(NarrationTexts.QUIZ_FAILED, True)\n if utils.continue_text():\n self.quiz_over = False\n return\n self._decide_next_question()", "def ask_and_evaluate(self):\n answer = raw_input(self.question + \" > \")\n if answer == self.correct_answer:\n return True\n return False", "def inputs_wrong_letter(self):\n if self.num_guesses > 1 and self.game_active == True:\n if self.num_guesses > 2 and self.game_active == True:\n print(\n f\"\\nNo, that letter is not in the word. \\nYou have {self.num_guesses - 1} attempts at guessing the wrong letter left.\"\n )\n else:\n print(\n \"\\nNo, that letter is not in the word. \\nYou have 1 attempt at guessing the wrong letter left.\"\n )\n print(f\"The letters you have choseen ==> {self.given_letters}\")\n\n self.num_guesses -= 1\n self.check_num_guesses_left()\n\n if self.game_active == False:\n pass\n else:\n self.run_game()", "def question():\n quest = raw_input(\"Do you want to Insert another article? Y/N\\n\")\n quest = quest.lower()\n if quest == \"y\" or quest == \"yes\":\n os.system(\"cls\")\n os.system(\"clear\")\n articles()\n elif quest == \"n\" or quest == \"no\":\n menu()\n else:\n print \"Insert a valid option\"\n question()", "def control_if_empty(self):\n if self.user_question == \"\": # if input is empty\n self.user_interaction.response_from_papybot = GRANDPY_BOT_QUESTION_EMPTY\n self.list_dialog.extend([self.user_question, self.user_interaction.response_from_papybot])\n self.loop = False\n self.case = 1\n else:\n self.user_interaction.modification_process(self.user_question)", "def test_check_guess(self):\n question = Question(\"Test\", \"correct\", [\"correct\", \"incorrect\"])\n self.assertTrue(question.check_guess(\"correct\"))\n self.assertFalse(question.check_guess(\"incorrect\"))\n self.assertFalse(question.check_guess(\"not an option\"))" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert any valid color format black and white rgb tuple >>> bw((0, 4, 210)) (71.333333333333329, 71.333333333333329, 71.333333333333329) >>> bw([0, 4, 210]) (71.333333333333329, 71.333333333333329, 71.333333333333329)
def bw(value): r, g, b = _int2rgbtuple(rgb(value)) g = (r + g + b) / 3.0 return g, g, g
[ "def white_rgb(w,h):\n m = []\n for i in range(h):\n fila = []\n for j in range(w):\n fila += [(255,255,255)]\n m += [fila]\n return (\"RGB\", m)", "def toRGB(self, _rgbu):\n newRGB = 0\n for iVal, val in enumerate(_rgbu):\n if self.bitDepths[iVal] > 0:\n depth = 2**self.bitDepths[iVal]\n newVal = min(depth-1, int(val *depth))\n newRGB = newRGB | (newVal << self.bitOffsets[iVal])\n #print(\"0x{:06X}\".format(newRGB))\n\n if self.blackBit > 0:\n newRGB = newRGB & ~self.blackBit\n\n rgb = [] \n rgb.append(int( newRGB & 0x0000FF))\n rgb.append(int((newRGB & 0x00FF00) >> 8))\n rgb.append(int((newRGB & 0xFF0000) >> 16))\n\n #print(_rgbu, \"0x{:024b}\".format(newRGB), rgb)\n return (tuple(rgb), newRGB)", "def check_color(c_tuple):\n for i in range(len(c_tuple)):\n if c_tuple[i]>255:\n c_tuple[i] = 255\n elif c_tuple[i]<0:\n c_tuple[i] = 0\n return c_tuple", "def to_rgb(value: TypeColor) -> Tuple[int, int, int]:\n if isinstance(value, tuple):\n return value\n\n if isinstance(value, int):\n value = (value, value, value)\n\n elif isinstance(value, str):\n value = COLORS[value]\n\n return value", "def white_bn(w, h):\n return (\"1\", white(w, h))", "def colorTuple(c):\n return c.getRgb()", "def rgb_from_int(val):\n return tuple([\n ((val >> 16) & 0xff) / 0xff,\n ((val >> 8) & 0xff) / 0xff,\n (val & 0xff) / 0xff])", "def hex_to_rgb(value):\n value = value.strip(\"#\") # removes hash symbol if present\n lv = len(value)\n return tuple(int(value[i:i + lv//3], 16) for i in range(0, lv, lv//3))", "def color_to_tuple(value):\n if isinstance(value, tuple):\n return value\n if isinstance(value, int):\n if value >> 24:\n raise ValueError(\"Only bits 0->23 valid for integer input\")\n r = value >> 16\n g = (value >> 8) & 0xFF\n b = value & 0xFF\n return [r, g, b]\n\n raise ValueError(\"Color must be a tuple or 24-bit integer value.\")", "def get_rgb_from_value(v: float) -> Tuple[int, int, int]:\n # colorsys returns rgb values between 0 and 1\n r, g, b = colorsys.hls_to_rgb(v, 0.5, 1)\n\n # multiply by 255 to get values between 0 and 255\n red = round(r * 255)\n green = round(g * 255)\n blue = round(b * 255)\n return red, green, blue", "def white(w,h):\n m = []\n for i in range(h):\n fila = []\n for j in range(w):\n fila += [255]\n m += [fila]\n return m", "def naivecolormap(value):\r\n # value2pixel(0.5) -> (0.5,0.5,0.5)\r\n red = (value & 0x00ff0000) >> 16\r\n green = (value & 0x0000ff00) >> 8\r\n blue = (value & 0x000000ff) >> 0\r\n \r\n return (int(red), int(green), int(blue)) # rgb\r", "def rgb2wb(pixel, size, thresh = 128):\n w, h = size\n for i in range(w):\n for j in range(h):\n pixel[i, j] = BLACK if sum(pixel[i, j])/3 < thresh else WHITE", "def just_check_rgb(value):\n # TODO\n return value", "def flow2rgb(flow):\n\n return hsv2rgb(flow2hsv(flow))", "def __tuple__(self):\n return (self.color & 0xff0000, self.color & 0xff00, self.color & 0xff)", "def init_rgb(self, cfg, tip, podtip):\r\n podtip += '_rgb_'\r\n rgb = pomocne_funkcije.load_config_item(cfg, tip, podtip, (0, 0, 255), tuple)\r\n # dohvati samo prva 3 elementa\r\n rgb = rgb[:3]\r\n #convert to integer vrijednost\r\n rgb = tuple([int(i) for i in rgb])\r\n if self.test_rgb(rgb):\r\n return rgb\r\n else:\r\n return 0, 0, 255", "def rgb_to_bytes(color):\n\treturn tuple(int(round(i * 255)) for i in color)", "def to_list(rgb):\n return [\n int(rgb[1:3], 16),\n int(rgb[3:5], 16),\n int(rgb[5:7], 16)\n ]" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert any valid color format to cmyk tuple >>> cmyk((0, 4, 210)) (0.82352941176470584, 0.80784313725490198, 0, 0.17647058823529416) >>> cmyk([0, 4, 210]) (0.82352941176470584, 0.80784313725490198, 0, 0.17647058823529416) >>> cmyk([0.1, 0.1, 0.2, 0.2]) [0.10000000000000001, 0.10000000000000001, 0.20000000000000001, 0.20000000000000001] >>> cmyk('335566') (0.20000000000000007, 0.066666666666666763, 0, 0.59999999999999998) >>> cmyk('P300') [1, 0.44, 0, 0] >>> cmyk('blue') (1, 1, 0, 0)
def cmyk(value): cvalue, type = convertcolor(value) if cvalue is None: raise ValueError, ('Unknown color type: "%s"' % value) if type == ISCMYKFLAG: return cvalue elif type == ISRGBFLAG: return _rgb2cmyk(_int2rgbtuple(cvalue))
[ "def rgb_to_cmyk(self,tup):\n if sum(tup) == 0: # black\n return 0, 0, 0, self.cmyk_scale\n \n # set values and normalize\n r,g,b = tup\n r /= self.rgb_scale\n g /= self.rgb_scale\n b /= self.rgb_scale\n \n # extract CMYK values\n k = 1 - max(r,g,b)\n c = (1-r-k)/(1-k)\n m = (1-g-k)/(1-k)\n y = (1-b-k)/(1-k)\n \n # scale and return\n return c*self.cmyk_scale, m*self.cmyk_scale, y*self.cmyk_scale, k*self.cmyk_scale", "def cmyk_to_rgb(self,tup):\n # set values and normalize\n c,m,y,k = tup\n c /= self.cmyk_scale\n m /= self.cmyk_scale\n y /= self.cmyk_scale\n k /= self.cmyk_scale\n \n # convert to RGB and scale\n r = int(round(self.rgb_scale*(1.0-c)*(1.0-k),0))\n g = int(round(self.rgb_scale*(1.0-m)*(1.0-k),0))\n b = int(round(self.rgb_scale*(1.0-y)*(1.0-k),0))\n return r,g,b", "def _rgb2cmyk((r, g, b)):\n c = 1 - (r / 255.0)\n m = 1 - (g / 255.0)\n y = 1 - (b / 255.0)\n k = min(c, m, y)\n c = min(1, max(0, c - k))\n m = min(1, max(0, m - k))\n y = min(1, max(0, y - k))\n k = min(1, max(0, k))\n return float(c), float(m), float(y), float(k)", "def _cmyk2rgb((c, m, y, k), density=1):\n r = 1.0 - min(1.0, c + k)\n g = 1.0 - min(1.0, m + k)\n b = 1.0 - min(1.0, y + k)\n return (r * 255, g * 255, b * 255)", "def validatecmyk(self,tup):\n for val in tup:\n if type(val) != int and type(val) != float:\n raise ValueError('One of the values in the CMYK colour tuple is not a number (%s).\\n%s' %(str(val),self.__class__.__doc__))\n if val > self.cmyk_scale or val < 0:\n raise ValueError('One of the values in the CMYK colour tuple (%s) is outside of the valid range (0-%d)' %(str(val),self.cmyk_scale,self.__class__.__doc__))", "def colorTuple(c):\n return c.getRgb()", "def color_to_tuple(value):\n if isinstance(value, tuple):\n return value\n if isinstance(value, int):\n if value >> 24:\n raise ValueError(\"Only bits 0->23 valid for integer input\")\n r = value >> 16\n g = (value >> 8) & 0xFF\n b = value & 0xFF\n return [r, g, b]\n\n raise ValueError(\"Color must be a tuple or 24-bit integer value.\")", "def to_rgb(value: TypeColor) -> Tuple[int, int, int]:\n if isinstance(value, tuple):\n return value\n\n if isinstance(value, int):\n value = (value, value, value)\n\n elif isinstance(value, str):\n value = COLORS[value]\n\n return value", "def color_to_triple(color: Optional[str] = None) -> Tuple[int, int, int]:\n if color is None:\n r = np.random.randint(0, 0x100)\n g = np.random.randint(0, 0x100)\n b = np.random.randint(0, 0x100)\n return (r, g, b)\n else:\n return ImageColor.getrgb(color)", "def parse_color(val, dflt=None):\n if val in named_colors:\n return named_colors[val]\n\n vals = val.split(':')\n if len(vals) == 3:\n return tuple(float(v) / 255 for v in vals)\n\n return dflt", "def color_string_to_tuple(s):\n if isinstance(s, tuple): # CIETmap requirement\n return s\n if s.startswith('('): # assume this is '(r,g,b,a)' (or '(r g b a)')\n s = s[1:-1]\n sep = None\n if ',' in s: # in case this is a space separated variant\n sep = ','\n rgba = s.split(sep)\n return tuple([float(c) for c in rgba])", "def getColorCairo(name: str, default: str = None) -> tuple[float, float, float]:\n color = getColorRGB(name, default)\n if color is None:\n return None\n try:\n r, g, b = color\n return r / 255.0, g / 255.0, b / 255.0\n except Exception:\n return None", "def mkColor(*args):\n err = 'Not sure how to make a color from \"%s\"' % str(args)\n if len(args) == 1:\n if isinstance(args[0], str):\n c = args[0]\n if len(c) == 1:\n try:\n return Colors[c]\n except KeyError:\n raise ValueError('No color named \"%s\"' % c)\n have_alpha = len(c) in [5, 9] and c[0] == '#' # \"#RGBA\" and \"#RRGGBBAA\"\n if not have_alpha:\n # try parsing SVG named colors, including \"#RGB\" and \"#RRGGBB\".\n # note that QColor.setNamedColor() treats a 9-char hex string as \"#AARRGGBB\".\n qcol = QtGui.QColor()\n qcol.setNamedColor(c)\n if qcol.isValid():\n return qcol\n # on failure, fallback to pyqtgraph parsing\n # this includes the deprecated case of non-#-prefixed hex strings\n if c[0] == '#':\n c = c[1:]\n else:\n raise ValueError(f\"Unable to convert {c} to QColor\")\n if len(c) == 3:\n r = int(c[0]*2, 16)\n g = int(c[1]*2, 16)\n b = int(c[2]*2, 16)\n a = 255\n elif len(c) == 4:\n r = int(c[0]*2, 16)\n g = int(c[1]*2, 16)\n b = int(c[2]*2, 16)\n a = int(c[3]*2, 16)\n elif len(c) == 6:\n r = int(c[0:2], 16)\n g = int(c[2:4], 16)\n b = int(c[4:6], 16)\n a = 255\n elif len(c) == 8:\n r = int(c[0:2], 16)\n g = int(c[2:4], 16)\n b = int(c[4:6], 16)\n a = int(c[6:8], 16)\n else:\n raise ValueError(f\"Unknown how to convert string {c} to color\")\n elif isinstance(args[0], QtGui.QColor):\n return QtGui.QColor(args[0])\n elif np.issubdtype(type(args[0]), np.floating):\n r = g = b = int(args[0] * 255)\n a = 255\n elif hasattr(args[0], '__len__'):\n if len(args[0]) == 3:\n r, g, b = args[0]\n a = 255\n elif len(args[0]) == 4:\n r, g, b, a = args[0]\n elif len(args[0]) == 2:\n return intColor(*args[0])\n else:\n raise TypeError(err)\n elif np.issubdtype(type(args[0]), np.integer):\n return intColor(args[0])\n else:\n raise TypeError(err)\n elif len(args) == 3:\n r, g, b = args\n a = 255\n elif len(args) == 4:\n r, g, b, a = args\n else:\n raise TypeError(err)\n args = [int(a) if np.isfinite(a) else 0 for a in (r, g, b, a)]\n return QtGui.QColor(*args)", "def kelvin_to_rgb(cls, colour_temperature):\n if isinstance(colour_temperature, (six.text_type, six.binary_type)):\n colour_temperature = six.u(colour_temperature)\n colour_temperature = colour_temperature.strip(\" \").strip(\"K\")\n colour_temperature = round(float(colour_temperature)) # May raise ValueError\n\n # range check\n if colour_temperature < 1000:\n colour_temperature = 1000\n elif colour_temperature > 40000:\n colour_temperature = 40000\n\n tmp_internal = colour_temperature / 100.0\n\n # red\n if tmp_internal <= 66:\n red = 255\n else:\n tmp_red = 329.698727446 * math.pow(tmp_internal - 60, -0.1332047592)\n if tmp_red < 0:\n red = 0\n elif tmp_red > 255:\n red = 255\n else:\n red = tmp_red\n\n # green\n if tmp_internal <= 66:\n tmp_green = 99.4708025861 * math.log(tmp_internal) - 161.1195681661\n if tmp_green < 0:\n green = 0\n elif tmp_green > 255:\n green = 255\n else:\n green = tmp_green\n else:\n tmp_green = 288.1221695283 * math.pow(tmp_internal - 60, -0.0755148492)\n if tmp_green < 0:\n green = 0\n elif tmp_green > 255:\n green = 255\n else:\n green = tmp_green\n\n # blue\n if tmp_internal >= 66:\n blue = 255\n elif tmp_internal <= 19:\n blue = 0\n else:\n tmp_blue = 138.5177312231 * math.log(tmp_internal - 10) - 305.0447927307\n if tmp_blue < 0:\n blue = 0\n elif tmp_blue > 255:\n blue = 255\n else:\n blue = tmp_blue\n\n return red, green, blue", "def hue_to_cmy(hue_value):\n # Red-Yellow range. M100 = red. M0 = Yelow.\n if hue_value in range(0, 60):\n c = 0\n m = int((60 - hue_value) / 60 * 100)\n y = 100\n print(\"C: \" + str(c) + \" M: \" + str(m) + \" Y: \" + str(y))\n # Yellow-Green range. C0 = Yellow. C=100 = green.\n elif hue_value in range(60, 120):\n hue_value = hue_value - 60\n c = int(hue_value / 60 * 100)\n m = 0\n y = 100\n print(\"C: \" + str(c) + \" M: \" + str(m) + \" Y: \" + str(y))\n # Green-Cyan range. Y100 = Green. Y0 = Cyan.\n elif hue_value in range(120, 180):\n c = 100\n m = 0\n y = int((180 - hue_value) / 60 * 100)\n print(\"C: \" + str(c) + \" M: \" + str(m) + \" Y: \" + str(y))\n # Cyan-Blue range. M0 = Cyan. M100 = Blue.\n elif hue_value in range(180, 240):\n hue_value = hue_value - 180\n c = 100\n m = int(hue_value / 60 * 100)\n y = 0\n print(\"C: \" + str(c) + \" M: \" + str(m) + \" Y: \" + str(y))\n #Blue-Magenta range. C100 = Blue. C0 = Magenta.\n elif hue_value in range(240, 300):\n c = int((300 - hue_value) / 60 * 100)\n m = 100\n y = 0\n print(\"C: \" + str(c) + \" M: \" + str(m) + \" Y: \" + str(y))\n #Magenta-Red range. Y0 = Magenta. Y100 = Red.\n elif hue_value in range(300, 361):\n hue_value = hue_value - 300\n c = 0\n m = 100\n y = int(hue_value / 60 * 100)\n print(\"C: \" + str(c) + \" M: \" + str(m) + \" Y: \" + str(y))\n else:\n pass\n return [c, m, y]", "def subrgb(c0, c1): # Color Tuple 0 and 1.\n\tif c0 == BLACK or c1 == BLACK:\n\t\treturn (0, 0, 0)\n\telse:\n\t\tcd = lambda value: True if c0[value] > DARKNESS_THRESHOLD else False # Color Delimiter.\n\t\tif cd(0) or cd(1) or cd(2):\n\t\t\tr = c0[0] - c1[0]\n\t\t\tg = c0[1] - c1[1]\n\t\t\tb = c0[2] - c1[2]\n\t\telse:\n\t\t\tr = c0[0] - int(c1[0]/2)\n\t\t\tg = c0[1] - int(c1[0]/2)\n\t\t\tb = c0[2] - int(c1[0]/2)\n\t\tif r < VOID:\n\t\t\tr = 1\n\t\tif g < VOID:\n\t\t\tg = 1\n\t\tif b < VOID:\n\t\t\tb = 1\n\t\treturn (r, g, b)", "def check_color(c_tuple):\n for i in range(len(c_tuple)):\n if c_tuple[i]>255:\n c_tuple[i] = 255\n elif c_tuple[i]<0:\n c_tuple[i] = 0\n return c_tuple", "def getColor(rgb=None, hsv=None):\n # recursion, return a list if input is list of colors:\n if _isSequence(rgb) and (len(rgb) > 3 or _isSequence(rgb[0])):\n seqcol = []\n for sc in rgb:\n seqcol.append(getColor(sc))\n return seqcol\n\n # because they are most common:\n if rgb=='r':\n return (0.9960784313725, 0.11764705882352, 0.121568627450980)\n elif rgb=='g':\n return (0.0156862745098, 0.49803921568627, 0.062745098039215)\n elif rgb=='b':\n return (0.0588235294117, 0.0, 0.984313725490196)\n\n if str(rgb).isdigit():\n rgb = int(rgb)\n\n if hsv:\n c = hsv2rgb(hsv)\n else:\n c = rgb\n\n if _isSequence(c):\n if c[0] <= 1 and c[1] <= 1 and c[2] <= 1:\n return c # already rgb\n else:\n if len(c) == 3:\n return list(np.array(c) / 255.0) # RGB\n else:\n return (c[0] / 255.0, c[1] / 255.0, c[2] / 255.0, c[3]) # RGBA\n\n elif isinstance(c, str): # is string\n c = c.replace(\"grey\", \"gray\").replace(\" \", \"\")\n if 0 < len(c) < 3: # single/double letter color\n if c.lower() in color_nicks.keys():\n c = color_nicks[c.lower()]\n else:\n vedo.logger.warning(f\"Unknown color nickname {c}\\nAvailable abbreviations: {color_nicks}\")\n return (0.5, 0.5, 0.5)\n\n if c.lower() in colors.keys(): # matplotlib name color\n c = colors[c.lower()]\n # from now format is hex!\n\n if c.startswith(\"#\"): # hex to rgb\n h = c.lstrip(\"#\")\n rgb255 = list(int(h[i : i + 2], 16) for i in (0, 2, 4))\n rgbh = np.array(rgb255) / 255.0\n if np.sum(rgbh) > 3:\n vedo.logger.error(f\"in getColor(): Wrong hex color {c}\")\n return (0.5, 0.5, 0.5)\n return tuple(rgbh)\n\n else: # vtk name color\n namedColors = vtk.vtkNamedColors()\n rgba = [0, 0, 0, 0]\n namedColors.GetColor(c, rgba)\n return (rgba[0]/255.0, rgba[1]/255.0, rgba[2]/255.0)\n\n elif isinstance(c, int): # color number\n if c >= 0:\n return colors1[c % 10]\n else:\n return colors2[-c % 10]\n\n elif isinstance(c, float):\n if c >= 0:\n return colors1[int(c) % 10]\n else:\n return colors2[int(-c) % 10]\n\n # print(\"Unknown color:\", c)\n return (0.5, 0.5, 0.5)", "def getColorRGB(name: str, default: str = None) -> tuple[int, int, int]:\n s = getColor(name, default)\n try:\n color = int(s[1:3], 16), int(s[3:5], 16), int(s[5:7], 16)\n except Exception:\n color = None\n return color" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert from a RGB color tuple to RGB integer >>> _rgbtuple2int((0, 4, 210)) 1234L >>> _rgbtuple2int((0, 48, 57)) 12345L >>> _rgbtuple2int((0, 214, 216)) 55000L >>> _rgbtuple2int((6, 241, 88)) 455000L
def _rgbtuple2int(t): r = int(round(t[0])) # Not all r,g,b values are necessarily g = int(round(t[1])) # integers, eg from _cmyk2rgb b = int(round(t[2])) # so we round and truncate them return long(r) * 65536 + g * 256 + b
[ "def int_from_rgb(rgb):\n return (round(rgb[0] * 0xff) << 16) + \\\n (round(rgb[1] * 0xff) << 8) + \\\n round(rgb[2] * 0xff)", "def rgb_from_int(val):\n return tuple([\n ((val >> 16) & 0xff) / 0xff,\n ((val >> 8) & 0xff) / 0xff,\n (val & 0xff) / 0xff])", "def to_rgb(value: TypeColor) -> Tuple[int, int, int]:\n if isinstance(value, tuple):\n return value\n\n if isinstance(value, int):\n value = (value, value, value)\n\n elif isinstance(value, str):\n value = COLORS[value]\n\n return value", "def color_to_tuple(value):\n if isinstance(value, tuple):\n return value\n if isinstance(value, int):\n if value >> 24:\n raise ValueError(\"Only bits 0->23 valid for integer input\")\n r = value >> 16\n g = (value >> 8) & 0xFF\n b = value & 0xFF\n return [r, g, b]\n\n raise ValueError(\"Color must be a tuple or 24-bit integer value.\")", "def float_tuple_to_int(float_tuple):\n new_list = []\n for i in range(len(float_tuple)):\n new_list.append(int(float_tuple[i]))\n return tuple(new_list)", "def tuple_to_int(t):\n return sum(digit * pow(10, p) for p, digit in enumerate(reversed(t)))", "def colorTuple(c):\n return c.getRgb()", "def bgr2id(color):\n if isinstance(color, np.ndarray) and len(color.shape) == 3:\n if color.dtype == np.uint8:\n color = color.astype(np.uint32)\n return color[:, :, 2] + 256 * color[:, :, 1] + 256 * 256 * color[:, :, 0]\n return int(color[2] + 256 * color[1] + 256 * 256 * color[0])", "def hex_to_rgb(value):\n value = value.strip(\"#\") # removes hash symbol if present\n lv = len(value)\n return tuple(int(value[i:i + lv//3], 16) for i in range(0, lv, lv//3))", "def _int2rgbtuple(i):\n if not isinstance(i, int): # We need to have an integer here\n try: # so we try to make it\n i = int(i) # otherwise return and error message\n except:\n raise ValueError, ('Value is not an integer: \"%s\"' % `i`)\n return (i >> 16) & 0xff, (i >> 8) & 0xff, i & 0xff", "def matplotlib_rgb_color(rgb_color):\n return tuple([i/255. for i in rgb_color])", "def t2i(tuple_):\n return int(''.join(map(str, tuple_)))", "def color_to_rle(color: Tuple[int, int, int, int]) -> int:\n rgb = color[:3]\n if rgb == (0, 0, 0):\n return 0\n elif rgb == _FUCHSIA_LOGO_COLOR:\n # When we match the hardcoded color, the alpha becomes the value.\n return color[3]\n else:\n raise ValueError(f\"Pixel has unsupported color {color}\")", "def cmyk_to_rgb(self,tup):\n # set values and normalize\n c,m,y,k = tup\n c /= self.cmyk_scale\n m /= self.cmyk_scale\n y /= self.cmyk_scale\n k /= self.cmyk_scale\n \n # convert to RGB and scale\n r = int(round(self.rgb_scale*(1.0-c)*(1.0-k),0))\n g = int(round(self.rgb_scale*(1.0-m)*(1.0-k),0))\n b = int(round(self.rgb_scale*(1.0-y)*(1.0-k),0))\n return r,g,b", "def color_string_to_tuple(s):\n if isinstance(s, tuple): # CIETmap requirement\n return s\n if s.startswith('('): # assume this is '(r,g,b,a)' (or '(r g b a)')\n s = s[1:-1]\n sep = None\n if ',' in s: # in case this is a space separated variant\n sep = ','\n rgba = s.split(sep)\n return tuple([float(c) for c in rgba])", "def __colour_int_to_float(self, colour):\n return (float(colour[0])/255, float(colour[1])/255, float(colour[2])/255)", "def color_to_triple(color: Optional[str] = None) -> Tuple[int, int, int]:\n if color is None:\n r = np.random.randint(0, 0x100)\n g = np.random.randint(0, 0x100)\n b = np.random.randint(0, 0x100)\n return (r, g, b)\n else:\n return ImageColor.getrgb(color)", "def get_color(obj) -> int:\n if type(obj) == Color:\n return int(obj)\n elif type(obj) == int:\n if obj < 0 or obj > 0xffffff:\n raise ValueError(\"Invalid int color\")\n return int\n elif type(obj) == list and len(obj) == 3:\n if any(color < 0 or color > 255 for color in obj):\n raise ValueError(\"Invalid rgb tuple\")\n return int(\"\".join(f\"{c:02x}\" for c in obj), 16)\n elif type(obj) == str:\n if re.search(r\"^\\#[A-Fa-f0-9]{6}$\", obj):\n return int(obj[1:], 16)\n if re.search(r\"^\\#[A-Fa-f0-9]{3}$\", obj):\n return int(re.sub(r\"\\#(.)(.)(.)\", r\"\\1\\1\\2\\2\\3\\3\", obj), 16)\n raise ValueError(\"Invalid color value for `hex_color`\")\n raise ValueError(\"Invalid color\")", "def color_tuple_to_gdk(color):\n r,g,b,a = color\n return gtk.gdk.Color(int(r*MAX_COLOR), int(g*MAX_COLOR), int(b*MAX_COLOR))" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert from a RGB color integer to RGB tuple >>> _int2rgbtuple(1234) (0, 4, 210) >>> _int2rgbtuple(12345) (0, 48, 57) >>> _int2rgbtuple(55000) (0, 214, 216) >>> _int2rgbtuple(455000) (6, 241, 88)
def _int2rgbtuple(i): if not isinstance(i, int): # We need to have an integer here try: # so we try to make it i = int(i) # otherwise return and error message except: raise ValueError, ('Value is not an integer: "%s"' % `i`) return (i >> 16) & 0xff, (i >> 8) & 0xff, i & 0xff
[ "def rgb_from_int(val):\n return tuple([\n ((val >> 16) & 0xff) / 0xff,\n ((val >> 8) & 0xff) / 0xff,\n (val & 0xff) / 0xff])", "def _rgbtuple2int(t):\n r = int(round(t[0])) # Not all r,g,b values are necessarily\n g = int(round(t[1])) # integers, eg from _cmyk2rgb\n b = int(round(t[2])) # so we round and truncate them\n return long(r) * 65536 + g * 256 + b", "def color_to_tuple(value):\n if isinstance(value, tuple):\n return value\n if isinstance(value, int):\n if value >> 24:\n raise ValueError(\"Only bits 0->23 valid for integer input\")\n r = value >> 16\n g = (value >> 8) & 0xFF\n b = value & 0xFF\n return [r, g, b]\n\n raise ValueError(\"Color must be a tuple or 24-bit integer value.\")", "def to_rgb(value: TypeColor) -> Tuple[int, int, int]:\n if isinstance(value, tuple):\n return value\n\n if isinstance(value, int):\n value = (value, value, value)\n\n elif isinstance(value, str):\n value = COLORS[value]\n\n return value", "def _color_int2tuple(bitmask):\n return (\n (bitmask >> 2) & 1,\n (bitmask >> 1) & 1,\n bitmask & 1\n )", "def toRGB(self, _rgbu):\n newRGB = 0\n for iVal, val in enumerate(_rgbu):\n if self.bitDepths[iVal] > 0:\n depth = 2**self.bitDepths[iVal]\n newVal = min(depth-1, int(val *depth))\n newRGB = newRGB | (newVal << self.bitOffsets[iVal])\n #print(\"0x{:06X}\".format(newRGB))\n\n if self.blackBit > 0:\n newRGB = newRGB & ~self.blackBit\n\n rgb = [] \n rgb.append(int( newRGB & 0x0000FF))\n rgb.append(int((newRGB & 0x00FF00) >> 8))\n rgb.append(int((newRGB & 0xFF0000) >> 16))\n\n #print(_rgbu, \"0x{:024b}\".format(newRGB), rgb)\n return (tuple(rgb), newRGB)", "def hex_to_rgb(value):\n value = value.strip(\"#\") # removes hash symbol if present\n lv = len(value)\n return tuple(int(value[i:i + lv//3], 16) for i in range(0, lv, lv//3))", "def colorTuple(c):\n return c.getRgb()", "def color_to_triple(color: Optional[str] = None) -> Tuple[int, int, int]:\n if color is None:\n r = np.random.randint(0, 0x100)\n g = np.random.randint(0, 0x100)\n b = np.random.randint(0, 0x100)\n return (r, g, b)\n else:\n return ImageColor.getrgb(color)", "def int_from_rgb(rgb):\n return (round(rgb[0] * 0xff) << 16) + \\\n (round(rgb[1] * 0xff) << 8) + \\\n round(rgb[2] * 0xff)", "def color_string_to_tuple(s):\n if isinstance(s, tuple): # CIETmap requirement\n return s\n if s.startswith('('): # assume this is '(r,g,b,a)' (or '(r g b a)')\n s = s[1:-1]\n sep = None\n if ',' in s: # in case this is a space separated variant\n sep = ','\n rgba = s.split(sep)\n return tuple([float(c) for c in rgba])", "def get_rgb_from_value(v: float) -> Tuple[int, int, int]:\n # colorsys returns rgb values between 0 and 1\n r, g, b = colorsys.hls_to_rgb(v, 0.5, 1)\n\n # multiply by 255 to get values between 0 and 255\n red = round(r * 255)\n green = round(g * 255)\n blue = round(b * 255)\n return red, green, blue", "def hex_to_rgb(self, hex_string):\n if hex_string.startswith('#'):\n hex_string = hex_string[1:]\n\n if len(hex_string) != 6:\n raise IndexError('hex string must have 6 characters starting with an optional # symbol')\n\n return tuple(int(hex_string[i:i + 2], 16)\n for i in range(0, len(hex_string), 2))", "def matplotlib_rgb_color(rgb_color):\n return tuple([i/255. for i in rgb_color])", "def polpair_int2tuple(polpair, pol_strings=False):\n # Recursive evaluation\n if isinstance(polpair, (list, np.ndarray)):\n return [polpair_int2tuple(p, pol_strings=pol_strings) for p in polpair]\n\n # Check for integer type\n assert isinstance(polpair, (int, np.integer)), \\\n \"polpair must be integer: %s\" % type(polpair)\n\n # Split into pol1 and pol2 integers\n pol1 = int(str(polpair)[:-2]) - 20\n pol2 = int(str(polpair)[-2:]) - 20\n\n # Check that pol1 and pol2 are in the allowed range (-8, 4)\n if (pol1 < -8 or pol1 > 4) or (pol2 < -8 or pol2 > 4):\n raise ValueError(\"polpair integer evaluates to an invalid \"\n \"polarization pair: (%d, %d)\"\n % (pol1, pol2))\n # Convert to strings if requested\n if pol_strings:\n return (polnum2str(pol1), polnum2str(pol2))\n else:\n return (pol1, pol2)", "def color_tuple_to_gdk(color):\n r,g,b,a = color\n return gtk.gdk.Color(int(r*MAX_COLOR), int(g*MAX_COLOR), int(b*MAX_COLOR))", "def _color_to_tripple( color ):\n from paramio import pget, plist\n\n if color in plist(\"colors.par\"):\n rgb = pget('colors.par', color ) \n rgb = rgb.split()\n rgb = [float(x) for x in rgb]\n return rgb\n\n if len(color.split()) == 3:\n rgb = color.split()\n rgb = [float(x) for x in rgb]\n if max(rgb) > 1.0:\n rgb = [x/255.0 for x in rgb]\n if max(rgb) > 1.0 or min(rgb) < 0.0:\n raise ValueError(\"Color values must be between 0 and 255\")\n return rgb\n\n if len(color) == 8 and color.lower().startswith('0x') is True:\n def __hex_to_int(cc):\n return int( '0x'+cc, base=16 )\n \n rr = __hex_to_int( color[2:4])\n gg = __hex_to_int( color[4:6])\n bb = __hex_to_int( color[6:])\n rgb = [ rr/255.0, gg/255.0, bb/255.0] \n return rgb\n \n\n raise ValueError(\"Unable to parse color value and cannot locate color='{}' in colors.par\".format(color))", "def cmyk_to_rgb(self,tup):\n # set values and normalize\n c,m,y,k = tup\n c /= self.cmyk_scale\n m /= self.cmyk_scale\n y /= self.cmyk_scale\n k /= self.cmyk_scale\n \n # convert to RGB and scale\n r = int(round(self.rgb_scale*(1.0-c)*(1.0-k),0))\n g = int(round(self.rgb_scale*(1.0-m)*(1.0-k),0))\n b = int(round(self.rgb_scale*(1.0-y)*(1.0-k),0))\n return r,g,b", "def xyz_from_rgb(rgb):\n return tuple([\n 0.412453 * rgb[0] + 0.357580 * rgb[1] + 0.180423 * rgb[2],\n 0.212671 * rgb[0] + 0.715160 * rgb[1] + 0.072169 * rgb[2],\n 0.019334 * rgb[0] + 0.119193 * rgb[1] + 0.950227 * rgb[2]])" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert from a CMYK color tuple to an RGB color tuple From the Adobe Postscript Ref. Manual 2nd ed. Page 306 >>> _cmyk2rgb((1, 1, 1, 1)) (0.0, 0.0, 0.0) >>> _cmyk2rgb((0, 0, 0, 0)) (255.0, 255.0, 255.0) >>> _cmyk2rgb((0.2, 0.6, 0.8, 0.2)) (153.0, 50.999999999999986, 0.0)
def _cmyk2rgb((c, m, y, k), density=1): r = 1.0 - min(1.0, c + k) g = 1.0 - min(1.0, m + k) b = 1.0 - min(1.0, y + k) return (r * 255, g * 255, b * 255)
[ "def cmyk_to_rgb(self,tup):\n # set values and normalize\n c,m,y,k = tup\n c /= self.cmyk_scale\n m /= self.cmyk_scale\n y /= self.cmyk_scale\n k /= self.cmyk_scale\n \n # convert to RGB and scale\n r = int(round(self.rgb_scale*(1.0-c)*(1.0-k),0))\n g = int(round(self.rgb_scale*(1.0-m)*(1.0-k),0))\n b = int(round(self.rgb_scale*(1.0-y)*(1.0-k),0))\n return r,g,b", "def rgb_to_cmyk(self,tup):\n if sum(tup) == 0: # black\n return 0, 0, 0, self.cmyk_scale\n \n # set values and normalize\n r,g,b = tup\n r /= self.rgb_scale\n g /= self.rgb_scale\n b /= self.rgb_scale\n \n # extract CMYK values\n k = 1 - max(r,g,b)\n c = (1-r-k)/(1-k)\n m = (1-g-k)/(1-k)\n y = (1-b-k)/(1-k)\n \n # scale and return\n return c*self.cmyk_scale, m*self.cmyk_scale, y*self.cmyk_scale, k*self.cmyk_scale", "def _rgb2cmyk((r, g, b)):\n c = 1 - (r / 255.0)\n m = 1 - (g / 255.0)\n y = 1 - (b / 255.0)\n k = min(c, m, y)\n c = min(1, max(0, c - k))\n m = min(1, max(0, m - k))\n y = min(1, max(0, y - k))\n k = min(1, max(0, k))\n return float(c), float(m), float(y), float(k)", "def to_rgb(value: TypeColor) -> Tuple[int, int, int]:\n if isinstance(value, tuple):\n return value\n\n if isinstance(value, int):\n value = (value, value, value)\n\n elif isinstance(value, str):\n value = COLORS[value]\n\n return value", "def colorTuple(c):\n return c.getRgb()", "def subrgb(c0, c1): # Color Tuple 0 and 1.\n\tif c0 == BLACK or c1 == BLACK:\n\t\treturn (0, 0, 0)\n\telse:\n\t\tcd = lambda value: True if c0[value] > DARKNESS_THRESHOLD else False # Color Delimiter.\n\t\tif cd(0) or cd(1) or cd(2):\n\t\t\tr = c0[0] - c1[0]\n\t\t\tg = c0[1] - c1[1]\n\t\t\tb = c0[2] - c1[2]\n\t\telse:\n\t\t\tr = c0[0] - int(c1[0]/2)\n\t\t\tg = c0[1] - int(c1[0]/2)\n\t\t\tb = c0[2] - int(c1[0]/2)\n\t\tif r < VOID:\n\t\t\tr = 1\n\t\tif g < VOID:\n\t\t\tg = 1\n\t\tif b < VOID:\n\t\t\tb = 1\n\t\treturn (r, g, b)", "def hue2rgb(hue):\n #TODO: are those the same results than on the real controller?\n if hue == 0:\n return 0,0,0\n elif hue >= 127:\n return 255,255,255\n hue = hue << 3\n\n if hue < 341:\n hue = (hue*3)/4\n r = 255 - hue\n g = hue\n b = 1\n elif hue < 682:\n hue = ((hue-341)*3)/4\n r = 1\n g = 255 - hue\n b = hue\n else:\n hue = ((hue-683)*3)/4\n r = hue\n g = 1\n b = 255 - hue\n\n return (r,g,b)", "def kelvin_to_rgb(cls, colour_temperature):\n if isinstance(colour_temperature, (six.text_type, six.binary_type)):\n colour_temperature = six.u(colour_temperature)\n colour_temperature = colour_temperature.strip(\" \").strip(\"K\")\n colour_temperature = round(float(colour_temperature)) # May raise ValueError\n\n # range check\n if colour_temperature < 1000:\n colour_temperature = 1000\n elif colour_temperature > 40000:\n colour_temperature = 40000\n\n tmp_internal = colour_temperature / 100.0\n\n # red\n if tmp_internal <= 66:\n red = 255\n else:\n tmp_red = 329.698727446 * math.pow(tmp_internal - 60, -0.1332047592)\n if tmp_red < 0:\n red = 0\n elif tmp_red > 255:\n red = 255\n else:\n red = tmp_red\n\n # green\n if tmp_internal <= 66:\n tmp_green = 99.4708025861 * math.log(tmp_internal) - 161.1195681661\n if tmp_green < 0:\n green = 0\n elif tmp_green > 255:\n green = 255\n else:\n green = tmp_green\n else:\n tmp_green = 288.1221695283 * math.pow(tmp_internal - 60, -0.0755148492)\n if tmp_green < 0:\n green = 0\n elif tmp_green > 255:\n green = 255\n else:\n green = tmp_green\n\n # blue\n if tmp_internal >= 66:\n blue = 255\n elif tmp_internal <= 19:\n blue = 0\n else:\n tmp_blue = 138.5177312231 * math.log(tmp_internal - 10) - 305.0447927307\n if tmp_blue < 0:\n blue = 0\n elif tmp_blue > 255:\n blue = 255\n else:\n blue = tmp_blue\n\n return red, green, blue", "def hex_to_rgb(value):\n value = value.strip(\"#\") # removes hash symbol if present\n lv = len(value)\n return tuple(int(value[i:i + lv//3], 16) for i in range(0, lv, lv//3))", "def matplotlib_rgb_color(rgb_color):\n return tuple([i/255. for i in rgb_color])", "def bgr_to_rgb(color):\n return color[::-1]", "def rgb_from_int(val):\n return tuple([\n ((val >> 16) & 0xff) / 0xff,\n ((val >> 8) & 0xff) / 0xff,\n (val & 0xff) / 0xff])", "def color_rgb_to_cairo(color): \n return (color[0] / 255.0, color[1] / 255.0, color[2] / 255.0)", "def get_rgb_from_value(v: float) -> Tuple[int, int, int]:\n # colorsys returns rgb values between 0 and 1\n r, g, b = colorsys.hls_to_rgb(v, 0.5, 1)\n\n # multiply by 255 to get values between 0 and 255\n red = round(r * 255)\n green = round(g * 255)\n blue = round(b * 255)\n return red, green, blue", "def color_to_tuple(value):\n if isinstance(value, tuple):\n return value\n if isinstance(value, int):\n if value >> 24:\n raise ValueError(\"Only bits 0->23 valid for integer input\")\n r = value >> 16\n g = (value >> 8) & 0xFF\n b = value & 0xFF\n return [r, g, b]\n\n raise ValueError(\"Color must be a tuple or 24-bit integer value.\")", "def getColor(rgb=None, hsv=None):\n # recursion, return a list if input is list of colors:\n if _isSequence(rgb) and (len(rgb) > 3 or _isSequence(rgb[0])):\n seqcol = []\n for sc in rgb:\n seqcol.append(getColor(sc))\n return seqcol\n\n # because they are most common:\n if rgb=='r':\n return (0.9960784313725, 0.11764705882352, 0.121568627450980)\n elif rgb=='g':\n return (0.0156862745098, 0.49803921568627, 0.062745098039215)\n elif rgb=='b':\n return (0.0588235294117, 0.0, 0.984313725490196)\n\n if str(rgb).isdigit():\n rgb = int(rgb)\n\n if hsv:\n c = hsv2rgb(hsv)\n else:\n c = rgb\n\n if _isSequence(c):\n if c[0] <= 1 and c[1] <= 1 and c[2] <= 1:\n return c # already rgb\n else:\n if len(c) == 3:\n return list(np.array(c) / 255.0) # RGB\n else:\n return (c[0] / 255.0, c[1] / 255.0, c[2] / 255.0, c[3]) # RGBA\n\n elif isinstance(c, str): # is string\n c = c.replace(\"grey\", \"gray\").replace(\" \", \"\")\n if 0 < len(c) < 3: # single/double letter color\n if c.lower() in color_nicks.keys():\n c = color_nicks[c.lower()]\n else:\n vedo.logger.warning(f\"Unknown color nickname {c}\\nAvailable abbreviations: {color_nicks}\")\n return (0.5, 0.5, 0.5)\n\n if c.lower() in colors.keys(): # matplotlib name color\n c = colors[c.lower()]\n # from now format is hex!\n\n if c.startswith(\"#\"): # hex to rgb\n h = c.lstrip(\"#\")\n rgb255 = list(int(h[i : i + 2], 16) for i in (0, 2, 4))\n rgbh = np.array(rgb255) / 255.0\n if np.sum(rgbh) > 3:\n vedo.logger.error(f\"in getColor(): Wrong hex color {c}\")\n return (0.5, 0.5, 0.5)\n return tuple(rgbh)\n\n else: # vtk name color\n namedColors = vtk.vtkNamedColors()\n rgba = [0, 0, 0, 0]\n namedColors.GetColor(c, rgba)\n return (rgba[0]/255.0, rgba[1]/255.0, rgba[2]/255.0)\n\n elif isinstance(c, int): # color number\n if c >= 0:\n return colors1[c % 10]\n else:\n return colors2[-c % 10]\n\n elif isinstance(c, float):\n if c >= 0:\n return colors1[int(c) % 10]\n else:\n return colors2[int(-c) % 10]\n\n # print(\"Unknown color:\", c)\n return (0.5, 0.5, 0.5)", "def toRGB(self, _rgbu):\n newRGB = 0\n for iVal, val in enumerate(_rgbu):\n if self.bitDepths[iVal] > 0:\n depth = 2**self.bitDepths[iVal]\n newVal = min(depth-1, int(val *depth))\n newRGB = newRGB | (newVal << self.bitOffsets[iVal])\n #print(\"0x{:06X}\".format(newRGB))\n\n if self.blackBit > 0:\n newRGB = newRGB & ~self.blackBit\n\n rgb = [] \n rgb.append(int( newRGB & 0x0000FF))\n rgb.append(int((newRGB & 0x00FF00) >> 8))\n rgb.append(int((newRGB & 0xFF0000) >> 16))\n\n #print(_rgbu, \"0x{:024b}\".format(newRGB), rgb)\n return (tuple(rgb), newRGB)", "def _colors_to_rgb(colorscale):\n if colorscale[0][1][0] == \"#\":\n plotly_colors = np.array(colorscale)[:, 1].tolist()\n for k, hexcode in enumerate(plotly_colors):\n hexcode = hexcode.lstrip(\"#\")\n hex_len = len(hexcode)\n step = hex_len // 3\n colorscale[k][1] = \"rgb\" + str(\n tuple(int(hexcode[j : j + step], 16) for j in range(0, hex_len, step))\n )\n\n return colorscale", "def cmyk(value):\n cvalue, type = convertcolor(value)\n if cvalue is None:\n raise ValueError, ('Unknown color type: \"%s\"' % value)\n if type == ISCMYKFLAG:\n return cvalue\n elif type == ISRGBFLAG:\n return _rgb2cmyk(_int2rgbtuple(cvalue))" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
One way to get cmyk from rgb." >>> _rgb2cmyk((100, 100, 100)) (0, 0, 0, 0.60784313725490202) >>> _rgb2cmyk((0, 0, 0)) (0, 0, 0, 1) >>> _rgb2cmyk((1, 1, 1)) (0, 0, 0, 0.99607843137254903)
def _rgb2cmyk((r, g, b)): c = 1 - (r / 255.0) m = 1 - (g / 255.0) y = 1 - (b / 255.0) k = min(c, m, y) c = min(1, max(0, c - k)) m = min(1, max(0, m - k)) y = min(1, max(0, y - k)) k = min(1, max(0, k)) return float(c), float(m), float(y), float(k)
[ "def rgb_to_cmyk(self,tup):\n if sum(tup) == 0: # black\n return 0, 0, 0, self.cmyk_scale\n \n # set values and normalize\n r,g,b = tup\n r /= self.rgb_scale\n g /= self.rgb_scale\n b /= self.rgb_scale\n \n # extract CMYK values\n k = 1 - max(r,g,b)\n c = (1-r-k)/(1-k)\n m = (1-g-k)/(1-k)\n y = (1-b-k)/(1-k)\n \n # scale and return\n return c*self.cmyk_scale, m*self.cmyk_scale, y*self.cmyk_scale, k*self.cmyk_scale", "def cmyk(value):\n cvalue, type = convertcolor(value)\n if cvalue is None:\n raise ValueError, ('Unknown color type: \"%s\"' % value)\n if type == ISCMYKFLAG:\n return cvalue\n elif type == ISRGBFLAG:\n return _rgb2cmyk(_int2rgbtuple(cvalue))", "def _cmyk2rgb((c, m, y, k), density=1):\n r = 1.0 - min(1.0, c + k)\n g = 1.0 - min(1.0, m + k)\n b = 1.0 - min(1.0, y + k)\n return (r * 255, g * 255, b * 255)", "def cmyk_to_rgb(self,tup):\n # set values and normalize\n c,m,y,k = tup\n c /= self.cmyk_scale\n m /= self.cmyk_scale\n y /= self.cmyk_scale\n k /= self.cmyk_scale\n \n # convert to RGB and scale\n r = int(round(self.rgb_scale*(1.0-c)*(1.0-k),0))\n g = int(round(self.rgb_scale*(1.0-m)*(1.0-k),0))\n b = int(round(self.rgb_scale*(1.0-y)*(1.0-k),0))\n return r,g,b", "def kelvin_to_rgb(cls, colour_temperature):\n if isinstance(colour_temperature, (six.text_type, six.binary_type)):\n colour_temperature = six.u(colour_temperature)\n colour_temperature = colour_temperature.strip(\" \").strip(\"K\")\n colour_temperature = round(float(colour_temperature)) # May raise ValueError\n\n # range check\n if colour_temperature < 1000:\n colour_temperature = 1000\n elif colour_temperature > 40000:\n colour_temperature = 40000\n\n tmp_internal = colour_temperature / 100.0\n\n # red\n if tmp_internal <= 66:\n red = 255\n else:\n tmp_red = 329.698727446 * math.pow(tmp_internal - 60, -0.1332047592)\n if tmp_red < 0:\n red = 0\n elif tmp_red > 255:\n red = 255\n else:\n red = tmp_red\n\n # green\n if tmp_internal <= 66:\n tmp_green = 99.4708025861 * math.log(tmp_internal) - 161.1195681661\n if tmp_green < 0:\n green = 0\n elif tmp_green > 255:\n green = 255\n else:\n green = tmp_green\n else:\n tmp_green = 288.1221695283 * math.pow(tmp_internal - 60, -0.0755148492)\n if tmp_green < 0:\n green = 0\n elif tmp_green > 255:\n green = 255\n else:\n green = tmp_green\n\n # blue\n if tmp_internal >= 66:\n blue = 255\n elif tmp_internal <= 19:\n blue = 0\n else:\n tmp_blue = 138.5177312231 * math.log(tmp_internal - 10) - 305.0447927307\n if tmp_blue < 0:\n blue = 0\n elif tmp_blue > 255:\n blue = 255\n else:\n blue = tmp_blue\n\n return red, green, blue", "def name_to_cik(self, name):\n return self.name_cik[name]", "def kpc2cm(x):\n return x * 1e3 * 3.085678e16 * 1e2", "def hue_to_cmy(hue_value):\n # Red-Yellow range. M100 = red. M0 = Yelow.\n if hue_value in range(0, 60):\n c = 0\n m = int((60 - hue_value) / 60 * 100)\n y = 100\n print(\"C: \" + str(c) + \" M: \" + str(m) + \" Y: \" + str(y))\n # Yellow-Green range. C0 = Yellow. C=100 = green.\n elif hue_value in range(60, 120):\n hue_value = hue_value - 60\n c = int(hue_value / 60 * 100)\n m = 0\n y = 100\n print(\"C: \" + str(c) + \" M: \" + str(m) + \" Y: \" + str(y))\n # Green-Cyan range. Y100 = Green. Y0 = Cyan.\n elif hue_value in range(120, 180):\n c = 100\n m = 0\n y = int((180 - hue_value) / 60 * 100)\n print(\"C: \" + str(c) + \" M: \" + str(m) + \" Y: \" + str(y))\n # Cyan-Blue range. M0 = Cyan. M100 = Blue.\n elif hue_value in range(180, 240):\n hue_value = hue_value - 180\n c = 100\n m = int(hue_value / 60 * 100)\n y = 0\n print(\"C: \" + str(c) + \" M: \" + str(m) + \" Y: \" + str(y))\n #Blue-Magenta range. C100 = Blue. C0 = Magenta.\n elif hue_value in range(240, 300):\n c = int((300 - hue_value) / 60 * 100)\n m = 100\n y = 0\n print(\"C: \" + str(c) + \" M: \" + str(m) + \" Y: \" + str(y))\n #Magenta-Red range. Y0 = Magenta. Y100 = Red.\n elif hue_value in range(300, 361):\n hue_value = hue_value - 300\n c = 0\n m = 100\n y = int(hue_value / 60 * 100)\n print(\"C: \" + str(c) + \" M: \" + str(m) + \" Y: \" + str(y))\n else:\n pass\n return [c, m, y]", "def validatecmyk(self,tup):\n for val in tup:\n if type(val) != int and type(val) != float:\n raise ValueError('One of the values in the CMYK colour tuple is not a number (%s).\\n%s' %(str(val),self.__class__.__doc__))\n if val > self.cmyk_scale or val < 0:\n raise ValueError('One of the values in the CMYK colour tuple (%s) is outside of the valid range (0-%d)' %(str(val),self.cmyk_scale,self.__class__.__doc__))", "def _cie_rgb_OECF(value):\n\n value = np.asarray(value)\n\n return value ** (1 / 2.2)", "def subrgb(c0, c1): # Color Tuple 0 and 1.\n\tif c0 == BLACK or c1 == BLACK:\n\t\treturn (0, 0, 0)\n\telse:\n\t\tcd = lambda value: True if c0[value] > DARKNESS_THRESHOLD else False # Color Delimiter.\n\t\tif cd(0) or cd(1) or cd(2):\n\t\t\tr = c0[0] - c1[0]\n\t\t\tg = c0[1] - c1[1]\n\t\t\tb = c0[2] - c1[2]\n\t\telse:\n\t\t\tr = c0[0] - int(c1[0]/2)\n\t\t\tg = c0[1] - int(c1[0]/2)\n\t\t\tb = c0[2] - int(c1[0]/2)\n\t\tif r < VOID:\n\t\t\tr = 1\n\t\tif g < VOID:\n\t\t\tg = 1\n\t\tif b < VOID:\n\t\t\tb = 1\n\t\treturn (r, g, b)", "def hue2clr(hue):\n num = len(hue)\n\n #print 'hue=',hue\n #print 'hue.shape=',hue.shape\n\n rgb = n.zeros([hue.shape[0],3])\n\n #print 'rgb =', rgb\n\n\n for k in range(0,num):\n\n\tif (hue[k] >= 0) & (hue[k] < 0.167):\n\n\t rgb[k,0] = 1\n\t rgb[k,1] = hue[k]/0.167\n\n\telif (hue[k]>= 0.167) & (hue[k] < 0.333):\n\n\t rgb[k,0] = 1-(hue[k]-0.167)/0.167\n\t rgb[k,1] = 1\n\n\telif (hue[k] >= 0.333) & (hue[k] < 0.500):\n\n\t rgb[k,1] = 1\n\t rgb[k,2] = (hue[k]-0.333)/0.167\n\n\telif (hue[k] >= 0.500) & (hue[k] < 0.667):\n\n\t rgb[k,1] = 1-(hue[k]-0.500)/0.167\n\t rgb[k,2] = 1\n\n\telif (hue[k] >= 0.667) & (hue[k] < 0.883):\n\n\t rgb[k,0] = (hue[k]-0.667)/0.167\n\t rgb[k,2] = 1\n\n\telif (hue[k] >= 0.883) & (hue[k] <= 1):\n\n\t rgb[k,0] = 1\n\t rgb[k,2] = 1-(hue[k]-0.883)/0.167\n\n\t#print 'k=',k\n\t#print 'rgb=',rgb\n return rgb", "def closest_colour(requested_colour):\n rlab = RGBColor(*requested_colour).convert_to(\"lab\")\n if (30 < rlab.lab_l < 70) and abs(rlab.lab_a) + abs(rlab.lab_b) == 0:\n # This is a greyscale colour\n return \"#817066\"\n better_colours = {}\n for key, bits in kelly_colours.items():\n lab_diff = rlab.delta_e(bits[1])\n better_colours[lab_diff] = key\n return better_colours[min(better_colours.keys())]", "def get_channel_clrs():\n return dict(b='blue', r='red', z='purple')", "def colorCIELab(qcol):\n srgb = qcol.getRgbF()[:3] # get sRGB values from QColor\n # convert gamma-encoded sRGB to linear:\n vec_RGB = np.zeros(3)\n for idx, val in enumerate( srgb ):\n if val > (12.92 * 0.0031308): # coefficients (s) * (t)\n vec_RGB[idx] = ((val+0.055)/1.055)**2.4\n else:\n vec_RGB[idx] = val / 12.92 # (s) coefficient\n # converted linear RGB to tristimulus XYZ:\n vec_XYZ = MATRIX_XYZ_FROM_RGB @ vec_RGB\n # normalize with white reference and convert to L*a*b* values\n vec_XYZ1 = vec_XYZ / VECTOR_XYZn \n for idx, val in enumerate(vec_XYZ1):\n if val > 0.008856:\n vec_XYZ1[idx] = vec_XYZ1[idx]**(1/3)\n else:\n vec_XYZ1[idx] = 7.787*vec_XYZ1[idx] + 16/116\n vec_Lab = np.array([\n 116 * vec_XYZ1[1] - 16, # Y1\n 500 * (vec_XYZ1[0] - vec_XYZ1[1]), # X1 - Y1\n 200 * (vec_XYZ1[1] - vec_XYZ1[2])] ) # Y1 - Z1\n return vec_Lab", "def _cie_rgb_EOCF(value):\n\n value = np.asarray(value)\n\n return value ** 2.2", "def cmyk_to_rgb(image_str):\n image = tf.io.decode_jpeg(image_str)\n image = tf.io.encode_jpeg(image, format=\"rgb\", quality=100)\n return image", "def convert_color_to_label(self):\n label_map = np.ndarray(shape=self.proj_color.shape[:2], dtype=int)\n label_map[:, :] = -1\n for idx, rgb in self.color_dict.items():\n label_map[((self.proj_color * 255).astype(np.uint8) == rgb).all(2)] = idx\n return label_map", "def warmOrCool(rgb):\n if rgb[0] > rgb[2]:\n return \"Warm\"\n else:\n return \"Cool\"" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Traverse instructions in array, incrementing accumulator, until an instruction repeats
def processor(instruction_array): processed_array = [True] * len(instruction_array) current_iter = 0 accumulation = 0 while processed_array[current_iter]: processed_array[current_iter] = False if instruction_array[current_iter][0] == "n": current_iter += 1 elif instruction_array[current_iter][0] == "a": test_iter = instruction_array[current_iter].split() accumulation += int(test_iter[1]) current_iter += 1 elif instruction_array[current_iter][0] == "j": test_iter = instruction_array[current_iter].split() current_iter += int(test_iter[1]) return accumulation
[ "def find_acc(inputs):\n acc = i = 0\n length = len(inputs)\n visited = set()\n\n while True:\n visited.add(i)\n\n instr, num = inputs[i]\n delta = 1\n if instr == \"acc\":\n acc += num\n elif instr == \"jmp\":\n delta = num\n\n i += delta\n if i in visited or i == length:\n return acc, i", "def execute(instructions):\n index = 0\n accumulator = 0\n list_of_pc = set()\n while True:\n if index in list_of_pc:\n return (accumulator, \"cycle\")\n if index == len(instructions):\n return (accumulator, \"termination\")\n\n list_of_pc.add(index)\n # print(f\"index {index}\")\n instruction = instructions[index]\n # print(f\"instruction {instruction}\")\n if instruction[\"operation\"] == \"nop\":\n index += 1\n continue\n if instruction[\"operation\"] == \"acc\":\n accumulator += instruction[\"argument\"]\n index += 1\n continue\n if instruction[\"operation\"] == \"jmp\":\n index += instruction[\"argument\"]\n continue", "def run_all(self) -> int:\n while self.instruction_pointer != len(self.instruction_set):\n self.run()\n return self.accumulator", "def count_steps(instructions: list, update: Callable = lambda n: n + 1) -> int:\n index, steps = 0, 0\n instructions = array('i', instructions[:])\n while True:\n try:\n index = jump(instructions, index, update)\n steps += 1\n except IndexError:\n return steps", "def accumulate(combiner, start, n, term):\n \"*** YOUR CODE HERE ***\"\n result = start\n while n >= 1:\n result = combiner(result , term(n))\n n = n - 1\n return result", "def binary_inc(array):\n i_ct = 0\n while i_ct < len(array) and array[i_ct] == 1:\n array[i_ct] = 0\n i_ct += 1\n if i_ct < len(array):\n array[i_ct] = 1\n return array", "def test_foreach_accum(self):\n with mn.model() as m:\n mn.variable('Baz', (12, 13))\n mn.variable('Waldo', (1, 2))\n Corge = mn.accum('Corge', \n mn.foreach(lambda b: b+2), ('Baz',), \n lambda w: w, ('Waldo',))\n m.step()\n self.assertEqual(Corge[''], (15, 17))\n m.step(2)\n self.assertEqual(Corge[''], (43, 47))", "def count_mr( iterable ):\n return map_reduce( lambda y: 1, lambda x,y: x+y, iterable )", "def visit(nbrs, atom, visited):\n visited[atom] = 1\n result = 1 # To be returned.\n for nbr in nbrs[atom]:\n if visited[nbr] > 0:\n continue\n result += visit(nbrs, nbr, visited)\n\n return result", "def step(self):\n\n\tif self.stopped: return # Do nothing when the machine is stopped\n\t# 2.3: \"The CI is always incremented prior to fetching an\n\t# instruction for execution...\"\n\tself.CI = comp2( (self.CI + 1) )\n\n\t# Fetch the instruction\n\tinst = self.store[ self.CI & 31]\n\n\t# Decode the line number affected by the instruction, and the\n\t# function number\n\tlineno, funcno = inst & 31, (inst >> 13) & 7\n\n\tassert 0<= funcno <=7\n\tif funcno == 0:\n\t # s,C : JMP : Copy content of Store line to CI\n\t self.CI = self.store[ lineno ]\n\telif funcno == 1:\n\t # c+s,C : JRP : Add content of Store line to CI\n\t self.CI = comp2(self.CI + self.store[ lineno ])\n\telif funcno == 2:\n\t # -s,A : LDN : Copy content of Store line, negated, to accum\n\t self.accum = comp2 (- self.store[ lineno ])\n\telif funcno == 3:\n\t # a,S : STO : Copy content of acc. to Store line\n\t self.store[ lineno ] = self.accum\n\telif funcno == 4 or funcno==5:\n\t # a-s,A : SUB : Subtract content of Store line from accum\n\t self.accum = comp2( self.accum - self.store[ lineno ] )\n\telif funcno == 6:\n\t # Test : CMP : Skip next instruction if content of accum\n\t # is negative\n\t if self.accum < 0: self.CI = comp2(self.CI + 1)\n\telif funcno == 7:\n\t # Stop : STOP : Light \"Stop\" neon and halt the machine\n\t self.stopped = 1\n\t\n\t# Assertions to test invariants\n\tassert -pow(2,31) <= self.accum <pow(2,31)\n\tassert -pow(2,31) <= self.store[ lineno ] <pow(2,31)\n\tassert -pow(2,31) <= self.CI <pow(2,31)", "def accumulate(combiner, start, n, term):\n k = start\n total = term(k)\n while k < n:\n k = k + 1\n total = combiner(total, term(k))\n return total", "def cumsum(array):\n if len(array) <= 1:\n return list(array)\n ret = list(array)\n for i in xrange(1, len(ret)):\n ret[i] += ret[i - 1]\n return ret", "def step_program(program, program_counter=-1, acc=0):\r\n\r\n instruction = program[program_counter][1]\r\n arg = program[program_counter][2]\r\n\r\n if instruction == \"acc\":\r\n acc = acc + arg\r\n program_counter += 1\r\n\r\n elif instruction == \"jmp\":\r\n program_counter += arg\r\n\r\n elif instruction == \"nop\":\r\n program_counter += 1\r\n\r\n\r\n state = (program_counter, acc)\r\n return state", "def array_prefix_sum_pythonista_style_immutable(arr):\n from itertools import accumulate\n return list(accumulate(arr, lambda a, b: a + b))", "def iterSum(ar, m):", "def test_foreach_accum(self):\n with mn.model() as m:\n mn.variable('Baz', {'foo': 12, 'bar': 13})\n mn.variable('Waldo', {'foo': 1, 'bar': 2})\n Corge = mn.accum('Corge', \n mn.foreach(lambda b: b+2), ('Baz',), \n mn.foreach(lambda w: w), ('Waldo',))\n m.step()\n self.assertEqual(Corge[''], {'foo':15, 'bar': 17} )\n m.step(2)\n self.assertEqual(Corge[''], {'foo':43, 'bar': 47} )", "def acc(self, argument: int):\n self.accumulator += argument\n self.jmp(1)", "def acc(self, value: int) -> None:\n self.accumulator += value\n self.pointer += 1", "def step(self):\n self.state[self.curr_iter] =\\\n self.iter_func(self.state[self.curr_iter - 1])\n self.curr_iter += 1" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Redirect client to camera feed
async def index(request): # Parse URL for camera ID cam_id = request.args.get(CAM_ID_PARAM) if cam_id: # Get camera data from source JSON cam = get_camera_by_id(CAM_ID_KEY, cam_id) if cam: ip = cam[CAM_IP_FIELD] # Redirect to camera feed return response.html(f"<h1><a href=\"http://{ip}\">Click here to view camera feed for camera {cam_id}</a></h1>") else: return response.text(f"Camera ID {cam_id} not found :/") else: return response.text("No camera specified.")
[ "def capture():\r\n (x, y) = global_camera.get_coordinates()\r\n # Label snapshot image with the x- and y-coordinates:\r\n path = \"/capture/X{}Y{}.jpeg\".format(x,y)\r\n return redirect(path)", "def get_camera_url(self):\n return self._url + '/camera'", "def video_feed():\n return Response(gen(Camera_person_online()),\n mimetype='multipart/x-mixed-replace; boundary=frame')", "def _proxy_camera_image(handler, path_match, data):\n entity_id = path_match.group(ATTR_ENTITY_ID)\n\n camera = None\n if entity_id in component.entities.keys():\n camera = component.entities[entity_id]\n\n if camera:\n response = camera.camera_image()\n handler.wfile.write(response)\n else:\n handler.send_response(HTTP_NOT_FOUND)", "def _proxy_camera_mjpeg_stream(handler, path_match, data):\n entity_id = path_match.group(ATTR_ENTITY_ID)\n\n camera = None\n if entity_id in component.entities.keys():\n camera = component.entities[entity_id]\n\n if not camera:\n handler.send_response(HTTP_NOT_FOUND)\n handler.end_headers()\n return\n\n try:\n camera.is_streaming = True\n camera.update_ha_state()\n\n handler.request.sendall(bytes('HTTP/1.1 200 OK\\r\\n', 'utf-8'))\n handler.request.sendall(bytes(\n 'Content-type: multipart/x-mixed-replace; \\\n boundary=--jpgboundary\\r\\n\\r\\n', 'utf-8'))\n handler.request.sendall(bytes('--jpgboundary\\r\\n', 'utf-8'))\n\n # MJPEG_START_HEADER.format()\n\n while True:\n\n img_bytes = camera.camera_image()\n\n headers_str = '\\r\\n'.join((\n 'Content-length: {}'.format(len(img_bytes)),\n 'Content-type: image/jpeg',\n )) + '\\r\\n\\r\\n'\n\n handler.request.sendall(\n bytes(headers_str, 'utf-8') +\n img_bytes +\n bytes('\\r\\n', 'utf-8'))\n\n handler.request.sendall(\n bytes('--jpgboundary\\r\\n', 'utf-8'))\n\n except (requests.RequestException, IOError):\n camera.is_streaming = False\n camera.update_ha_state()\n\n camera.is_streaming = False", "def redirect_request(self, req, fp, code, msg, headers, newurl):\n return None", "def viewCamera(camera, move=\"string\", sideView=bool, topView=bool):\n pass", "def setup_camera():\n requests.post(API_URL, json={\n \t\"method\": \"startRecMode\",\n \t\"params\": [],\n \t\"id\": 1,\n \t\"version\": \"1.0\"\n })\n requests.post(API_URL, json={\n\t\"method\": \"setPostviewImageSize\",\n\t\"params\": [\"Original\"],\n\t\"id\": 1,\n\t\"version\": \"1.0\"\n })", "def start_preview_stream(self) -> GoProResp:", "def echo():\n return redirect(\"https://api.imgur.com/oauth2/authorize?client_id=\" + request.form['client_id'] + \"&response_type=token&state=sssss\", code=302)", "def redirect(self) -> 'outputs.GoogleCloudRecaptchaenterpriseV1FirewallActionRedirectActionResponse':\n return pulumi.get(self, \"redirect\")", "def viewHeadOn(camera):\n pass", "def activate_camera():\n # avoid accidental access to /activate to change the status of system\n if current_user.is_authenticated:\n res = notify_camera(True)\n if res:\n return jsonify({'result': 'success'})\n return jsonify({'result': 'fail'})", "def set_Redirect(self, value):\n super(PictureInputSet, self)._set_input('Redirect', value)", "def redirect(self, uri):\n self.context.session.save()\n\n redirect(self.context.request.getMPRequest(), uri)", "def get_camera_url(location):\n # Parse SSDP get request as XML\n urn = \"{urn:schemas-sony-com:av}\"\n service = urn + \"X_ScalarWebAPI_Service\"\n service_type = urn + \"X_ScalarWebAPI_ServiceType\"\n action = urn + \"X_ScalarWebAPI_ActionList_URL\"\n\n root = ET.fromstring(requests.get(location).content)\n for service in root.iter(service):\n if service.find(service_type).text == \"camera\":\n camera_url = service.find(action).text + \"/camera\"\n return camera_url", "def redirect_from_posts_to_brightnews():\n\n return redirect(\"brightnews\")", "def cameraView(object, bookmarkType=int, camera=\"string\", setView=bool, removeBookmark=bool, addBookmark=bool, setCamera=bool, name=\"string\"):\n pass", "async def test_camera_returns_stream_url(hass, success_requests_mock):\n await setup_platform(hass, CAMERA_DOMAIN)\n component = hass.data.get(CAMERA_DOMAIN)\n\n camera = component.get_entity(\"camera.camera_name_1\")\n\n een_subdomain = fixture_een_subdomain()\n success_requests_mock.get(\n f\"https://{een_subdomain}.eagleeyenetworks.com/g/aaa/isauth\", text=\"true\"\n )\n\n url = await camera.stream_source()\n\n assert f\"https://{een_subdomain}.eagleeyenetworks.com/asset/play/video.flv\" in url\n assert \"id=\" in url\n assert \"start_timestamp=\" in url\n assert \"end_timestamp=\" in url\n assert \"A=\" in url" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get the security token by connecting to TouchWorks API
def get_token(self, appname, username, password): ext_exception = TouchWorksException( TouchWorksErrorMessages.GET_TOKEN_FAILED_ERROR) data = {'Username': username, 'Password': password} resp = self._http_request(TouchWorksEndPoints.GET_TOKEN, data) try: logger.debug('token : %s' % resp) if not resp.text: raise ext_exception try: uuid.UUID(resp.text, version=4) return SecurityToken(resp.text) except ValueError: logger.error('response was not valid uuid string. %s' % resp.text) raise ext_exception except Exception as ex: logger.exception(ex) raise ext_exception
[ "def _getToken(self):\n\n url = \"https://login.microsoftonline.com/{0!s}/oauth2/token\".format(self._tenant_id)\n \n payload = {\n \"grant_type\":\"client_credentials\",\n \"client_id\":self._client_id,\n \"client_secret\": self._client_secret,\n \"resource\":\"https%3A%2F%2Fapi.timeseries.azure.com%2F&undefined=\"\n }\n \n payload = \"grant_type={grant_type}&client_id={client_id}&client_secret={client_secret}&resource={resource}\".format(**payload)\n\n headers = {\n 'Content-Type': \"application/x-www-form-urlencoded\",\n 'cache-control': \"no-cache\"\n }\n\n try:\n response = requests.request(\"POST\", url, data=payload, headers=headers, timeout=10)\n response.raise_for_status()\n except requests.exceptions.ConnectTimeout:\n logging.error(\"TSIClient: The request to the TSI api timed out.\")\n raise\n except requests.exceptions.HTTPError as e:\n status_code = e.response.status_code\n if status_code == 401:\n logging.error(\"TSIClient: Authentication with the TSI api was unsuccessful. Check your client secret.\")\n else:\n logging.error(\"TSIClient: The request to the TSI api returned an unsuccessfull status code. Check the stack trace\")\n raise\n\n jsonResp = json.loads(response.text)\n tokenType = jsonResp['token_type']\n authorizationToken = tokenType +\" \" + jsonResp['access_token']\n return authorizationToken", "def get_token(self):\n client_auth = requests.auth.HTTPBasicAuth(self.client, self.secret)\n post_data = {'grant_type': 'password', 'username': self.user, 'password': self.password}\n headers = {'User-Agent': self.user_agent}\n response = requests.Session()\n response2 = response.post(self.token_url, auth=client_auth, data=post_data, headers=headers)\n self.token = response2.json()['access_token']\n self.t_type = response2.json()['token_type']", "def get_token(self) -> None:\n logging.info('QivivoAPI: Asking for token')\n send_data = urllib.parse.urlencode({'grant_type': 'client_credentials',\n 'client_id': self.client_id,\n 'client_secret': self.client_secret,\n })\n send_data = send_data.encode('ascii')\n try:\n r = json.load(urllib.request.urlopen(self.oauth_url, send_data))\n except urllib.error.HTTPError as e:\n logging.error(\"QivivoAPI: urllib error: \" + e.reason)\n logging.error(\"QivivoAPI; API error: \" + e.read())\n self.token = r['access_token']\n self.token_date = datetime.now()\n logging.info('QivivoAPI: token initialised with: ' + self.token)\n return", "def get_token():\n token_json = requests.get(token_issuer)\n return token_json.json()['token']", "def get_token(self):\n # payload = {\"username\": \"Your ZoomEye account\", \"password\": \"Your ZoomEye password\"}\n try:\n res = req.post('https://api.zoomeye.org/user/login',\n data=json.dumps(payload))\n except Exception as e:\n print e\n sys.exit()\n return json.loads(res.text)['access_token']", "def get_token():\n set_token(reset=False)\n return AuthInfo.ACCESS_TOKEN", "def token(self):\n try:\n return self.api.token\n except:\n raise NoLoginError()", "def auth_client(self):\n auth_url = f\"{self.url}/auth\"\n response = requests.post(auth_url, json={\"username\": self.user, \"password\": self.pwd})\n if response.status_code != 200:\n print(\"couldn't authenticate\")\n return None\n auth_token = response.json()[\"access_token\"]\n return auth_token", "def get_token(self):\n url = 'https://www.greenrush.com/api/v2/authorize'\n # token = '$2y$10$ehNDTqORidMNnL4xDW.bTemFH3/\n # YENp7qzlrXRRx971tielybhNE6'\n try:\n headers = {'accept': 'application/vnd.greenrush.v2+json',\n 'content-type': 'application/json'}\n data = {\"token\": self.key}\n\n print \"data:\", data\n flog(data)\n r = requests.post(url, headers=headers, data=json.dumps(data))\n print r.status_code\n print r.headers\n print r.content\n\n resp = json.loads(r.content)\n token = resp['token']\n print \"[INFO] token:\", token\n return token\n except Exception as exp:\n print \"get_token() :: Got exception: %s\" % exp\n print(traceback.format_exc())", "def _request_token(self):\n headers = {'Content-Type': 'application/x-www-form-urlencoded'}\n # required credentials when request for a token.\n data = {\n 'grant_type': 'password',\n 'client_id': self._config.auth['client_id'],\n 'client_secret': self._config.auth['client_secret'],\n 'username': self._config.auth['username'],\n 'password': '{}{}'.format(\n self._config.auth['password'], self._config.auth['security_token']\n ),\n 'response_type': 'code',\n 'redirect_uri': self._SALESFORCE_TOKEN_URL\n }\n success, response = self._make_post_request(\n self._SALESFORCE_TOKEN_URL, headers, data, False\n )\n\n if not (success and response):\n return False\n\n if not (response.get('access_token') and response.get('instance_url')):\n LOGGER.error('Response invalid generating headers for service \\'%s\\'',\n self._type())\n return False\n\n bearer = 'Bearer {}'.format(response.get('access_token'))\n self._auth_headers = {\n 'Content-Type': 'application/json',\n 'Authorization': bearer\n }\n self._instance_url = response.get('instance_url')\n LOGGER.debug('Successfully obtain OAuth token and instance URL')\n return True", "def token_generator():\n key = constants.CLIENT_ID + ':' + constants.SECRET_KEY\n key_base64 = encode(key)\n key_base64 = 'Basic ' + key_base64\n header = {\n 'authorization': key_base64,\n 'content-type': 'application/x-www-form-urlencoded'\n }\n body = \"grant_type=client_credentials&scope=urn:opc:resource:consumer::all\"\n response = requests.post(url=constants.AUTH_URL, headers=header, data=body)\n response_json = json.loads(response.content.decode('ascii'))\n return response_json['access_token']", "def get_access_token(self):\n url = urlparse(TOKEN_ENDPOINT))\n http = Net::HTTP.new(url.host, url.port)\n http.use_ssl = true\n req = Net::HTTP::Post.new(url.path)\n req.basic_auth(@clientId, @clientSecret)\n req.set_form_data({'grant_type' => 'client_credentials'})\n res = http.request(req)\n JSON.parse(res.body)['access_token']", "def _get_token(self):\n with requests.Session() as session:\n # This first request is to get redirected and get the token\n url = 'https://omsweb.public-safety-cloud.com/jtclientweb/jailtracker/index/Greene_County_MO'\n response = session.get(url, allow_redirects=True)\n url_split = response.url.split('/')\n token = url_split[4]\n # Cleaning your token\n token = token[3:-2]\n return token", "def read_token(self):\n return self.config.get('auth', 'token')", "def login(self):\n start_time = datetime.datetime.now()\n global auth_token\n user_cert, plugin_key = create_cert_session()\n app_token_payload = {\"aaaAppToken\": {\"attributes\": {\"appName\": \"Cisco_AppIQ\"}}}\n data = json.dumps(app_token_payload)\n pay_load = \"POST\" + urls.LOGIN_URL_SUFFIX + data\n private_key = load_privatekey(FILETYPE_PEM, plugin_key)\n signed_digest = sign(private_key, pay_load.encode(), 'sha256')\n signature = base64.b64encode(signed_digest).decode()\n\n token = \"APIC-Request-Signature=\" + signature + \";\"\n token += \"APIC-Certificate-Algorithm=v1.0;\"\n token += \"APIC-Certificate-Fingerprint=fingerprint;\"\n token += \"APIC-Certificate-DN=\" + str(user_cert.dn)\n try:\n response = self.session.post(urls.LOGIN_URL.format(self.proto, self.apic_ip), data=data, headers={'Cookie': token},timeout=10, verify=False)\n status_code = response.status_code\n if status_code == 200 or status_code == 201:\n auth = json.loads(response.text)\n auth_token = auth['imdata'][0]['aaaLogin']['attributes']['token']\n return auth_token\n else:\n return None\n except Exception as e:\n logger.exception('Unable to connect with APIC. Exception: '+str(e))\n return None\n finally:\n end_time = datetime.datetime.now()\n logger.info(\"Time for ACI login: \" + str(end_time - start_time))", "def get_auth_token():\n global _auth_token\n return _auth_token", "def get_jwt_token():\n return make_jwt(user=frappe.session.user)", "def get_bearer():\n token_url = conf.token_url\n data = conf.bearer_data\n logging.info(\"Login to \" + token_url + \" to get token\")\n try:\n token_response = requests.post(url=token_url, data=data) # making post call to anypoint\n logging.info(token_response)\n token_response_json = token_response.json() # extracting response text\n bearer = token_response_json[\"access_token\"] # parsing bearer frm json\n return bearer\n except ValueError:\n logging.info(\"Parsing response as JSON failed\")\n except Exception as e:\n logging.info(str(e))", "def get_api(token):\n squareconnect.configuration.access_token = token\n return TransactionsApi()" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
checks if the token cached is valid or has expired by comparing the time token was created with current time
def _token_valid(self): if not self._cache_token: return False now = time.time() if now - self._token.acquired_time > self._token_timeout: logger.debug('token needs to be reset') return False return True
[ "def is_token_expired(self):\n now = datetime.now()\n dt = now - self.token_time\n return dt.total_seconds() > (60 * 30)", "def is_token_valid(self):\r\n if not self.auth_token:\r\n return False\r\n\r\n if not self.auth_token_expires:\r\n return False\r\n\r\n expires = self.auth_token_expires - \\\r\n datetime.timedelta(seconds=AUTH_TOKEN_EXPIRES_GRACE_SECONDS)\r\n\r\n time_tuple_expires = expires.utctimetuple()\r\n time_tuple_now = datetime.datetime.utcnow().utctimetuple()\r\n\r\n if time_tuple_now < time_tuple_expires:\r\n return True\r\n\r\n return False", "def check_token_expiration(token):\n expiration = parse_datetime(token.expires)\n if settings.USE_TZ and timezone.is_naive(expiration):\n # Presumes that the Keystone is using UTC.\n expiration = timezone.make_aware(expiration, timezone.utc)\n # In case we get an unparseable expiration timestamp, return False\n # so you can't have a \"forever\" token just by breaking the expires param.\n if expiration:\n return expiration > NOW()\n else:\n return False", "def is_token_expired(token_initiate_time: float, token_expiration_seconds: float) -> bool:\n return time.time() - token_initiate_time >= token_expiration_seconds - ONE_MINUTE", "def get_token(user='omar'):\n\n token = cache.get('token')\n\n # if the token is found in the cache, check the last_verified. if it's less then 10 min, return\n # the token. else verify it. \n\n if token: # token in the cache. check verify timestamp\n token = token.decode('ASCII')\n logger.debug(\"token found in the cache\")\n\n # if the token has been verified less than 10 minutes ago, return it\n if get_token_cached_times_diff(cached_key='last_verified', unit='minutes') < 10:\n logger.debug(\"token was verified in less then 10 minutes\")\n return token\n\n # token has been verified more than 10 minutes. going to verify it now\n else: \n logger.debug(\"token was checked more then 10 minutes. going to verify it\")\n token_status = verify_token(token=token)\n\n # if the verify api returns 200, return token\n if token_status:\n logger.debug(\"response from verify is OK\")\n return token\n\n # token is invalid. going to call the refresh api\n else:\n logger.debug(\"response is not 200. token is not valid anymore. going to get a new one from the refresh api\")\n refresh_response_token = refresh_token()\n if refresh_response_token:\n logger.debug(\"get new token from refresher\")\n return refresh_response_token\n\n else: # going to call the set_token as the refresh_token doesn't have a valid token\n try:\n set_response_token = set_token(user=user)\n #if set_response_token:\n logger.debug(\"got a new token from the set_token\")\n return set_response_token\n\n except Exception as e: # unable to get a new token\n logger.error(\"token can not be set: %s\", str(e))\n print(\"token can not be set retrieved\")\n return False\n\n # if there is no token in the session, call the set_token to retrieve a new one \n else:\n try:\n set_response_token = set_token(user=user)\n logger.debug(\"got a new token from the set_token\")\n return set_response_token\n\n except Exception as e: # unable to get a new token\n logger.error(\"token can not be set\")\n print(\"token can not be set\")\n return False", "def is_expired_token(self, client):\n if 'expires' not in client:\n return True\n\n expires = dateutil.parser.parse(client['expires'])\n if expires < datetime.datetime.now():\n return True\n\n return False", "def test_is_expired(self):\n refresh_token = self.refresh_token_instance\n refresh_token.created_at = timezone.now()\n refresh_token.save()\n\n self.assertTrue(refresh_token.is_expired)\n self.assertFalse(refresh_token.is_active)", "def is_refresh_token_expired(request):\n now = time.time()\n return 'REFRESH_TOKEN' not in request.session \\\n or 'REFRESH_TOKEN_EXPIRES_AT' not in request.session \\\n or request.session['REFRESH_TOKEN_EXPIRES_AT'] < now", "def _validate_token_date(self, token_datetime):\n token_date = datetime.strptime(token_datetime, TIME_STAMP_FORMAT)\n now = datetime.utcnow()\n past_expiration_date = now - timedelta(\n seconds=self.expiration_in_seconds)\n future_expiration_date = now + timedelta(\n seconds=self.expiration_in_seconds)\n\n if token_date >= past_expiration_date \\\n and token_date <= future_expiration_date:\n return True\n\n return False", "def token_expires(self):\n # TODO: add lock.acquire / lock.release\n return self.token_map.get(self.key, {}).get('token_expires')", "def is_cache_valid(self):\n\n if os.path.isfile(self.cache_path):\n mod_time = os.path.getmtime(self.cache_path)\n current_time = time()\n return (mod_time + self.cache_max_age) > current_time\n else:\n return False", "def is_csrf_token_expired(token):\n from datetime import datetime\n expiry = token.split('##')[0]\n if expiry <= datetime.now().strftime('%Y%m%d%H%M%S'):\n return True\n return False", "def jwt_expired(token: str) -> bool:\n payload = base64.b64decode(token.split('.')[1]).decode()\n if time.time() > json.loads(payload)['exp']:\n return True\n else:\n return False", "def test_token_expire_after_renewal(self):\n self.token.created = self.token.created - datetime.timedelta(days=40)\n self.token.save()\n response = self.csrf_client.post(\n '/auth-token/', {'username': self.username,\n 'password': self.password}, format='json')\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n self.assertNotEqual(response.data['token'], self.key)", "def expired(self, now=None):\n if now is None:\n now = time.time()\n if self.expires_time is None:\n return False\n else:\n return now > self.expires_time", "def check_token_validity(self, verify=False, refresh_if_needed=True):\n\t\tif verify:\n\t\t\ttry:\n\t\t\t\tself.make_request(\n\t\t\t\t\t'GET',\n\t\t\t\t\t'server-time'\n\t\t\t\t).raise_for_status()\n\t\t\t\tself.is_authenticated = True\n\t\t\texcept (AuthenticationError, requests.exceptions.HTTPError):\n\t\t\t\tself.is_authenticated = False\n\t\t\t\treturn self.is_authenticated\n\t\tif not self.is_authenticated:\n\t\t\treturn self.is_authenticated\n\t\tif datetime.now() >= self.token_info['expire_time']:\n\t\t\tself.is_authenticated = False\n\t\t\treturn self.is_authenticated\n\t\tif all([\n\t\t\trefresh_if_needed,\n\t\t\tdatetime.now() > self.refresh_info['refresh_time']\n\t\t]):\n\t\t\tself.get_refresh()\n\t\treturn self.is_authenticated", "def test_token_expired(self):\n self.token.created = self.token.created - datetime.timedelta(days=40)\n self.token.save()\n response = self.csrf_client.post(\n '/token/', {'example': 'example'},\n HTTP_AUTHORIZATION='Token %s' % self.token.key, format='json')\n self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)", "def test_expires_at(self):\n refresh_token = self.refresh_token_instance\n exp_delta = jwt_settings.get('REFRESH_TOKEN_EXPIRATION_DELTA')\n expires_at = refresh_token.created_at + exp_delta\n\n self.assertEqual(refresh_token.expires_at, expires_at)", "def get_token(self):\n token, created = Token.objects.get_or_create(user=self)\n expiry_date = token.created + datetime.timedelta(\n days=settings.AUTH_TOKEN_EXPIRY_TIME)\n\n if not created and expiry_date < timezone.now():\n # delete token\n token.delete()\n # generate a new one\n token = Token.objects.create(user=self)\n\n return token" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
search document types by name and active(Y/N) status
def find_document_type_by_name(self, entity_name, active='Y', match_case=True): all_types = self.get_dictionary('Document_Type_DE') if match_case: filtered = filter( lambda x: x['Active'] == active and x['EntryName'].find(entity_name) >= 0, all_types) else: token = entity_name.lower() filtered = filter( lambda x: x['Active'] == active and x['EntryName'].lower().find(token) >= 0, all_types) return filtered
[ "def search_items(keywords, meta_types=None):", "def find_by_type(cls, rec_type):\n return (cls.query.filter_by(rec_type_id = rec_type.id)\n .filter(cls.rec_type.has(RecommendationType.is_active == True))).all()", "def searchObjTypeDerive(self,keys_list=None,query_objType=\".obj.pub\"):\n\t\tif not keys_list:\n\t\t\tkeys_list = self.getEntryList()\n\t\t\t\n\t\treturn [k for k in keys_list if k in self.getEntryList() and self.entries[k].objType[:len(query_objType)] == query_objType]", "def get(self):\n return get_all_type_docs()", "def searchObjTypeList(self,keys_list=None,objType_list=[\".obj.pub\",\".obj.pub.article\",\".obj.pub.book\"]):\n\t\tif not keys_list:\n\t\t\tkeys_list = self.getEntryList()\n\n\t\treturn [k for k in keys_list if k in self.getEntryList() and self.entries[k].objType in objType_list]", "def get_types():\n try:\n return list(mongo.db.documents.distinct(\"dataType\"))\n except:\n abort(500)", "def supports_authorization_search_record_type(self, authorization_search_record_type):\n return # boolean", "def _searcher(searchdata, candidates, typeclass, exact=False):\r\n if attribute_name:\r\n # attribute/property search (always exact).\r\n matches = self.get_objs_with_db_property_value(attribute_name, searchdata, candidates=candidates, typeclasses=typeclass)\r\n if matches:\r\n return matches\r\n return self.get_objs_with_attr_value(attribute_name, searchdata, candidates=candidates, typeclasses=typeclass)\r\n else:\r\n # normal key/alias search\r\n return self.get_objs_with_key_or_alias(searchdata, exact=exact, candidates=candidates, typeclasses=typeclass)", "def _search(self):", "def supports_vault_search_record_type(self, vault_search_record_type):\n return # boolean", "def supports_parameter_search_record_type(self, parameter_search_record_type):\n return # boolean", "def document_type(self, operator: Enum, document_type: list | str):\n if isinstance(document_type, list) and operator not in self.list_types:\n raise RuntimeError(\n 'Operator must be CONTAINS, NOT_CONTAINS, IN'\n 'or NOT_IN when filtering on a list of values.'\n )\n\n self._tql.add_filter('documentType', operator, document_type, TqlType.STRING)", "def supports_function_search_record_type(self, function_search_record_type):\n return # boolean", "def get_term_types():\n term_types = ['_Wq_', '_Wa_', '_Wd_']\n if common_flags.USE_DOCUMENT_TITLE.value == 1:\n term_types.append('_Wt_')\n return term_types", "def get_parameter_search_record_types(self):\n return # osid.type.TypeList", "def getFilter(self, type: int) -> bool:\n ...", "def get_search_filters(self):\r\n return {'type': self.comp_type}", "def search_by_org_type(self, query, max_results=10, print_results=True):\n if query in self.org_types:\n result_indices = np.ravel(\n [\n list(item.values())\n for item in self.assets.orgtype_idx_map\n if list(item.keys())[0] == query\n ]\n )\n if self.error_handle == True:\n print(\n \"{} of {} results for `organization type` - `{}`\".format(\n min(len(result_indices), max_results),\n len(result_indices),\n query,\n )\n )\n else:\n pass\n results = [{r: self.idxtitlemap[r]} for r in result_indices][:max_results]\n if print_results == True:\n pp_results(results)\n return results\n else:\n try:\n close_match = difflib.get_close_matches(\n query, self.org_types, n=1, cutoff=0.5\n )[0]\n if self.error_handle == True:\n print(\n \"No `organization type` named - `{}`. Did you mean - `{}`?\".format(\n query, close_match\n )\n )\n else:\n pass\n except:\n if self.error_handle == True:\n print(\n \"No `organization type` named - `{}`\".format(query),\n \"Try using `.list_org_types()` to see a list of available organization types\",\n sep=\"\\n\",\n )\n else:\n pass\n return []", "def get_doc(self, type_, name):\n if type_ == \"doxygen\":\n return self.doxydocs.get(name)\n if type_ == \"sphinx\":\n return self.sphinxdocs.get(name)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
utility method to create a magic json object needed to invoke TouchWorks APIs
def _magic_json(self, action='', user_id='', app_name='', patient_id='', token='', parameter1='', parameter2='', parameter3='', parameter4='', parameter5='', parameter6='', data=''): if not token: token = self._token.token if not app_name: app_name = self._app_name if not user_id: if self._ehr_username: user_id = self._ehr_username return { 'Action': action, 'AppUserID': user_id, 'Appname': app_name, 'PatientID': patient_id, 'Token': token, 'Parameter1': parameter1, 'Parameter2': parameter2, 'Parameter3': parameter3, 'Parameter4': parameter4, 'Parameter5': parameter5, 'Parameter6': parameter6, 'Data': data }
[ "def makeJson(self, lstype='lsys', payload=''): \n return self.mapping.prepareJson(lstype, payload)", "def _generate_json_response(self, context):\n raise NotImplementedError", "def _reprJSON(self):\n return {'__Fgi__': self.__dict__}", "def _generate_swagger_json(self, app):\n self._paths.extract_from_app(app)\n\n swagger_object = {\n \"swagger\": self.swagger_version,\n \"info\": {\n \"title\": self._title,\n \"version\": self._version\n },\n \"paths\": {}\n }\n self._paths.add_to_spec(swagger_object)\n self._definitions.add_to_spec(swagger_object)\n\n return swagger_object", "def create_json_from_model(self):\n json = {\n \"accessWindow\": self.access_window,\n \"disposition\": self.disposition\n }\n return json", "def _as_json(self):\r\n berry = {\r\n 'guid': self.guid,\r\n 'name': self.name,\r\n 'type': self.berry_type,\r\n 'ip': self.ip_address,\r\n }\r\n\r\n logging.info('Berry as an object: {}'.format(json.dumps(berry)))\r\n\r\n return berry", "def dispatch_request(self, *args, **kwargs):\n _ret = super(JsonEndpoint, self).dispatch_request(*args, **kwargs)\n return jsonify(_ret)", "def create_json(api_key, event_type, payload):\n json_dict = dict(api_key=api_key, event_type=event_type, payload=payload)\n return json.dumps(json_dict)", "def jsonHook(encoded):\n if '__Fgi__' in encoded:\n return Fgi._fromJSON(encoded['__Fgi__'])\n else:\n return encoded", "def handle_cmd_get():\n return json.dumps(cmd.getDefaultDict().toJSON())", "def get_json(self):\n json_format = {'request': {}}\n json_format['request']['passengers'] = self.passengers\n json_format['request']['slice'] = self.slices\n json_format['request']['refundable'] = False\n return json.dumps(json_format)", "def json(self) -> dict:\n return {\n 'forcasting_engine' : self.forcasting_engine,\n 'mean_absolute_percentage_error' :\n self.mean_absolute_percentage_error,\n 'attribute_table': self.attribute_table,\n 'sensor_id': self.sensor_id,\n 'num_predictions': self.num_predictions,\n 'result': self.result\n }", "async def direct_orjson_response():\n return CustomORJSONResponse(CONTENT)", "def initial_json(cls):\n\n return json.dumps(cls.INITIAL)", "def handle_evr_get():\n return json.dumps(evr.getDefaultDict().toJSON())", "def get_json(self) -> str:\n return json.dumps(self._raw_meta)", "def json(self):\n return json.dumps(self._spec)", "def GetFeatures(self):\n return json.dumps(FEATURES)", "def py_to_json(performer):\n\n if isinstance(performer, Performer):\n return {'__Performer__': performer.__dict__}\n return {'__{}__'.format(performer.__class__.__name__): performer.__dict__}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This should return some meaningful result. You could do something like check to make sure both the input and output files are identical, or that some other aspect of your test passed. This is called automatically once the forwarder has finished executing the test. You can return whatever you like, or even just print a message saying the test passed. Alternatively, you could use the return value to automate testing (i.e., return "True" for every test that passes, "False" for every test that fails).
def result(self, receiver_outfile): if not os.path.exists(receiver_outfile): raise ValueError("No such file %s" % str(receiver_outfile)) if self.files_are_the_same(self.input_file, receiver_outfile): print "Test passes!" return True else: print "Test fails: original file doesn't match received. :(" wait = input("PRESS ENTER TO CONTINUE.") return False
[ "def _succeed(self):\n print(self.test_case + ': succeeded')\n exit(0)", "def _process_output(port, options, test_input, test_types, test_args,\r\n test_output, worker_name):\r\n failures = []\r\n\r\n if test_output.crash:\r\n failures.append(test_failures.FailureCrash())\r\n if test_output.timeout:\r\n failures.append(test_failures.FailureTimeout())\r\n\r\n test_name = port.relative_test_filename(test_input.filename)\r\n if test_output.crash:\r\n _log.debug(\"%s Stacktrace for %s:\\n%s\" % (worker_name, test_name,\r\n test_output.error))\r\n filename = os.path.join(options.results_directory, test_name)\r\n filename = os.path.splitext(filename)[0] + \"-stack.txt\"\r\n port.maybe_make_directory(os.path.split(filename)[0])\r\n with codecs.open(filename, \"wb\", \"utf-8\") as file:\r\n file.write(test_output.error)\r\n elif test_output.error:\r\n _log.debug(\"%s %s output stderr lines:\\n%s\" % (worker_name, test_name,\r\n test_output.error))\r\n\r\n expected_test_output = _expected_test_output(port, test_input.filename)\r\n\r\n # Check the output and save the results.\r\n start_time = time.time()\r\n time_for_diffs = {}\r\n for test_type in test_types:\r\n start_diff_time = time.time()\r\n new_failures = test_type.compare_output(port, test_input.filename,\r\n test_args, test_output,\r\n expected_test_output)\r\n # Don't add any more failures if we already have a crash, so we don't\r\n # double-report those tests. We do double-report for timeouts since\r\n # we still want to see the text and image output.\r\n if not test_output.crash:\r\n failures.extend(new_failures)\r\n time_for_diffs[test_type.__class__.__name__] = (\r\n time.time() - start_diff_time)\r\n\r\n total_time_for_all_diffs = time.time() - start_diff_time\r\n return test_results.TestResult(test_input.filename, failures, test_output.test_time,\r\n total_time_for_all_diffs, time_for_diffs)", "def test_get_checker_result(self):\n pass", "def test_case_passed(self):\n self.__set_test_case_result(result='PASSED', message='')", "def _expected_test_output(port, filename):\r\n return test_output.TestOutput(port.expected_text(filename),\r\n port.expected_image(filename),\r\n port.expected_checksum(filename))", "def test_send_result(self):\n pass", "def test_get_checker_results(self):\n pass", "def test_output(self):\n self.logger.debug('Starting unit_test on output state')\n for out in [True, False]:\n self.inst.output = out\n assert out == self.inst.output\n self.logger.info('Output assertion passed for state: {}'.format(out))\n\n self.logger.info('Test output passed.')", "def runf2test(self):\n return self.runtest(self.f2) == \"fail\"", "def testTestResult(self):\n # Write test results file\n result_file = os.path.join(TEST_DATA_DIR, 'test_result.xml')\n output_file = (\n '/data/app_default_bucket/test_runs/%s/output/%s/%s/test_result.xml' %\n (self.test_run_id, self.task['command_id'], self.task['attempt_id']))\n self.container.CopyFile(result_file, output_file)\n # Verify that test results were parsed on completion\n self.container.SubmitCommandEvent(self.task, 'InvocationCompleted')\n self.container.WaitForState(self.test_run_id, 'COMPLETED')\n time.sleep(10) # Wait for test result processing to complete.\n test_run = self.container.GetTestRun(self.test_run_id)\n self.assertEqual('4', test_run['failed_test_count'])\n self.assertEqual('1', test_run['failed_test_run_count'])\n self.assertEqual('297', test_run['total_test_count'])", "def verify_output(file1, file2):\n print(\"\\n\\n***TESTING***\")\n if filecmp.cmp(file1, file2, shallow=False):\n print(\"Output verified\")\n else:\n print(\"Output is not equal to test file (doccafe/Types.yaml)!\")\n print(\"1 n n\")", "def compare_output(self, port, filename, output, test_args, configuration):\n failures = []\n\n # If we didn't produce a hash file, this test must be text-only.\n if test_args.hash is None:\n return failures\n\n # If we're generating a new baseline, we pass.\n if test_args.new_baseline:\n self._save_baseline_files(filename, test_args.png_path,\n test_args.hash)\n return failures\n\n # Compare hashes.\n expected_hash_file = self._port.expected_filename(filename,\n '.checksum')\n expected_png_file = self._port.expected_filename(filename, '.png')\n\n if test_args.show_sources:\n _log.debug('Using %s' % expected_hash_file)\n _log.debug('Using %s' % expected_png_file)\n\n # FIXME: We repeat this pattern often, we should share code.\n try:\n with codecs.open(expected_hash_file, \"r\", \"ascii\") as file:\n expected_hash = file.read()\n except IOError, e:\n if errno.ENOENT != e.errno:\n raise\n expected_hash = ''\n\n\n if not os.path.isfile(expected_png_file):\n # Report a missing expected PNG file.\n self.write_output_files(port, filename, '.checksum',\n test_args.hash, expected_hash,\n encoding=\"ascii\",\n print_text_diffs=False)\n self._copy_output_png(filename, test_args.png_path, '-actual.png')\n failures.append(test_failures.FailureMissingImage(self))\n return failures\n elif test_args.hash == expected_hash:\n # Hash matched (no diff needed, okay to return).\n return failures\n\n self.write_output_files(port, filename, '.checksum',\n test_args.hash, expected_hash,\n encoding=\"ascii\",\n print_text_diffs=False)\n self._copy_output_png(filename, test_args.png_path, '-actual.png')\n self._copy_output_png(filename, expected_png_file, '-expected.png')\n\n # Even though we only use the result in one codepath below but we\n # still need to call CreateImageDiff for other codepaths.\n images_are_different = self._create_image_diff(port, filename, configuration)\n if expected_hash == '':\n failures.append(test_failures.FailureMissingImageHash(self))\n elif test_args.hash != expected_hash:\n if images_are_different:\n failures.append(test_failures.FailureImageHashMismatch(self))\n else:\n failures.append(test_failures.FailureImageHashIncorrect(self))\n\n return failures", "def test_writeResults(self):\n stringIO = StringIO()\n result = DistReporter(Reporter(stringIO))\n runner = self.getRunner()\n runner.writeResults(result)\n self.assertTrue(stringIO.tell() > 0)", "def test_output_was(self):\n print('Some output')\n self._io.assert_output_was('Some output')\n print('Some more output')\n self._io.assert_output_was('Some more output')", "def test_run(self):\n fuzzer = TestEngineFuzzer()\n result = fuzzer.run('/input', '/output', 1)\n\n self.assertEqual(\n 'Generated 1 testcase for fuzzer target.\\n'\n 'metadata::fuzzer_binary_name: target\\n'\n 'metadata::issue_owners: dev1@example1.com,dev2@example2.com\\n',\n result.output)\n self.assertEqual('/input/proj_target', result.corpus_directory)\n\n self.assertTrue(os.path.exists('/output/fuzz-0'))\n self.assertTrue(os.path.exists('/output/flags-0'))\n\n with open('/output/fuzz-0') as f:\n self.assertEqual(' ', f.read())\n\n with open('/output/flags-0') as f:\n self.assertEqual('%TESTCASE% target -arg1 -arg2', f.read())", "def test_create_checker_result(self):\n pass", "def check_outputs(self):\n for key, fnames in OUTFILES.items():\n tdir = os.path.join(TARGETDIR, key)\n odir = os.path.join(OUTDIR, key)\n for fname in fnames:\n with open(os.path.join(odir, fname), \"r\") as ofh:\n with open(os.path.join(tdir, fname), \"r\") as tfh:\n self.assertEqual(ofh.read(), tfh.read())", "def testResultDone(self):\n ray.init(num_cpus=1, num_gpus=1)\n runner = TrialRunner(BasicVariantGenerator())\n kwargs = {\n \"stopping_criterion\": {\n \"training_iteration\": 2\n },\n \"resources\": Resources(cpu=1, gpu=1),\n }\n runner.add_trial(Trial(\"__fake\", **kwargs))\n trials = runner.get_trials()\n\n runner.step()\n self.assertEqual(trials[0].status, Trial.RUNNING)\n runner.step()\n self.assertNotEqual(trials[0].last_result[DONE], True)\n runner.step()\n self.assertEqual(trials[0].last_result[DONE], True)", "def test_returnCodeMatch(self):\n proc = self.process([self.retcode, \"0\"])\n self.assert_exit_status(proc, 0)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Show all rides rides in the database (for testing).
def all_rides(request): context_instance=RequestContext(request) data = { 'subtitle': 'Current Rides', 'matching': False, 'rides': Ride.get_all_rides()} return render_to_response('rides.html', data, context_instance=context_instance)
[ "def get_all_rides():", "def get_all_rides():\n return jsonify({'RideIds': listdir(RIDE_LOCATIONS)})", "def get_rides(self):\n self.driver.get(self.STRAVA + \"/athlete/training\")\n # Switch form to only bike rides\n self.driver.find_element_by_xpath(\"//select[@id='activity_type']\"\n \"/option[@value='Ride']\").click()\n self.all_rides = []\n while True:\n time.sleep(self.TIME_OUT)\n page = BeautifulSoup(self.driver.page_source)\n dates = page.find_all(\"td\", class_=\"view-col col-date\")\n date_check = [date.get_text()[-4:] != str(self.CURRENT_YEAR)\n for date in dates]\n links_on_page = page.find_all(\"td\", class_=\"view-col col-title\")\n self.all_rides.extend([a_link.a[\"href\"] for date, a_link in\n zip(date_check, links_on_page) if not date])\n if any(date_check):\n break # found a date not in CURRENT_YEAR\n try:\n self.driver.find_element_by_class_name(\"next_page\").click()\n except selenium.common.exceptions.NoSuchElementException:\n break", "def get_all(): \n db.query_db(\n \"SELECT * FROM ride_offers;\"\n )\n ride_offers = db.cursor.fetchall()\n if not ride_offers:\n return{\"message\":\"no ride offers yet, sorry\"}, 404\n # else convert data to dict\n rides = []\n for item in ride_offers:\n ride_dict = {\n \"ride_id\":item[0],\n \"driver_id\":item[1],\n \"location\":item[2],\n \"departure_time\":item[3],\n \"destination\":item[4]\n }\n rides.append(ride_dict)\n return rides, 200", "def current_rides(request):\n context_instance=RequestContext(request)\n user = context_instance['user']\n data = {\n 'subtitle': 'Current Rides',\n 'matching': False,\n 'rides': Ride.get_all_rides_for_user(user)}\n return render_to_response('rides.html', data,\n context_instance=context_instance)", "def list(self, request):\n ride_reviews = RideReview.objects.all()\n\n ride = self.request.query_params.get('ride_id', None)\n min_rating = self.request.query_params.get('min_rating', None)\n rating = self.request.query_params.get('rating', None)\n \n if ride is not None:\n ride_reviews = ride_reviews.filter(ride_id=ride)\n \n if rating is not None:\n ride_reviews = ride_reviews.filter(rating=rating)\n \n if min_rating is not None:\n ride_reviews = ride_reviews.filter(rating__gte=min_rating)\n\n serializer = RideReviewSerializer(ride_reviews, many=True,context={'request': request})\n return Response(serializer.data)", "def search_rides(request):\n context_instance=RequestContext(request)\n \n # Store the valid form in the user's session so new_ride or ride_info can\n # pick it up.\n if request.method == 'POST':\n rr_form = RideRequestForm(request.POST)\n request.session['_search_request'] = request.POST\n elif '_search_request' in request.session:\n rr_form = RideRequestForm(request.session['_search_request'])\n else:\n messages.add_message(request, messages.WARNING,\n \"Please make a search request before you attempt\" +\n \" to search\")\n return redirect('/')\n\n if rr_form.is_valid():\n sr = rr_form.save(commit = False)\n sr.user = context_instance['user']\n else:\n return HttpResponse(\"Unexpected error: form not valid \" +\n str(rr_form.errors), status=500)\n\n # Set up the template\n data = {}\n data['subtitle'] = 'Search Results'\n data['matching'] = True\n data['rides'] = Ride.get_results_for_searchrequest(sr)\n data['search_request'] = sr\n\n return render_to_response('rides.html', data, context_instance)", "def get(self, ride_id):\n self.id = ride_id\n return rides.fetch_one(self.id)", "def index(request):\n latest_cab_rides = Ride.objects.order_by('ride_date')\n user = request.user\n if user.is_authenticated:\n latest_rides_tup = [(ride, ride.is_participant(user), ride.is_owner(user))\n for ride in latest_cab_rides if not ride.ride_in_past()]\n else:\n latest_rides_tup = [(ride, False, False) for ride in latest_cab_rides]\n context = {\n 'latest_rides': latest_rides_tup, \n 'user': request.user\n }\n return render(request, 'cabrides/index.html', context)", "def show_restaurants():\n restaurants = session.query(Restaurant).all()\n return render_template(\"restaurants.html\", restaurants=restaurants)", "def showAllEats():\n\n eats = session.query(Eats).all()\n return render_template('alleats.html', eats=eats,\n login_session=login_session)", "def show_all_movies():\n\n movies = crud.get_movies()\n\n return render_template('all_movies.html', movies = movies)", "def readAll(self):\n print(\"Reading all restaurants from database...\")\n result = session.query(Restaurant).all()\n return result", "def test_roster_by_day_view(init_db, client):\n client.login(username=\"temporary\", password=\"temporary\")\n response = client.get(reverse(\"timeslot_list\"))\n assert response.status_code == 200\n assert \"Roster By Day:\" in response.rendered_content\n assert \"timeslot_list.html\" in [t.name for t in response.templates]", "def get(self, ride_id):\n request = Ride.read(ride_id)\n return {'status':'success', 'message': 'Fetch successful', 'data': request}", "def showAllLocs():\n\n locations = session.query(Locations).all()\n return render_template('locations.html',\n locations=locations, login_session=login_session)", "def get(self):\n elections = models.Election.gql('WHERE owner = :1', self.user).fetch(1000)\n self.response.out.write(render('elections',\n elections=elections,\n user=self.user))", "def ride_info(request, ride_id):\n context_instance = RequestContext(request)\n user = context_instance['user']\n ride = Ride.objects.get(pk=ride_id).filled_out()\n\n # If they have submitted a request and it is in bounds of the ride, let them\n # see this ride.\n # Next, check if they are part of this ride. If they are, let them see it.\n # Otherwise, don't let them see it\n user_sr = ride.get_sr_for_user(user)\n if not user_sr:\n if '_search_request' in request.session:\n # user is attempting to add this ride\n sr_post = request.session['_search_request']\n rr_form = RideRequestForm(sr_post)\n user_sr = rr_form.save(commit = False)\n user_sr.user = context_instance['user']\n ride.update_with_sr(user_sr)\n if not ride.in_bounds():\n messages.add_message(request, messages.ERROR,\n \"Error: This ride is out of your bounds.\" +\n \" You do not have access to this ride.\")\n return redirect('/rides/search/')\n else:\n messages.add_message(request, messages.ERROR,\n \"Error: You do not have access to this ride.\")\n return redirect('/')\n else:\n \tride.update_with_sr(user_sr)\n \t\n # encrypt the ride id and user_name\n enc_name = 'not implemented'\n enc_ride_id = 0\n\n data = {\n 'subtitle': 'Ride Details',\n 'ride': ride,\n 'enc_name': enc_name,\n 'enc_ride_id': enc_ride_id,\n 'user_names': ','.join(['\"%s %s\"' % (rider.first_name, rider.last_name) for rider in ride.riders]),\n 'start_latlongs': ['new google.maps.LatLng(%f, %f)' % (req.start_lat, req.start_long) for req in ride.requests],\n 'end_latlongs': [ 'new google.maps.LatLng(%f, %f)' % (req.end_lat, req.end_long) for req in ride.requests],\n 'user_in_ride': user in ride.riders}\n \n return render_to_response('detail.html', data,\n context_instance=context_instance)", "def index(request):\n resepies_list = Resepi.objects.all()\n context = {'resepies_list': resepies_list}\n return render(request, 'myresepies/index.html', context)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Show all rides that the user has ever taken.
def current_rides(request): context_instance=RequestContext(request) user = context_instance['user'] data = { 'subtitle': 'Current Rides', 'matching': False, 'rides': Ride.get_all_rides_for_user(user)} return render_to_response('rides.html', data, context_instance=context_instance)
[ "def all_rides(request):\n context_instance=RequestContext(request)\n data = {\n 'subtitle': 'Current Rides',\n 'matching': False,\n 'rides': Ride.get_all_rides()}\n return render_to_response('rides.html', data,\n context_instance=context_instance)", "def get_all_rides():", "def get_rides(self):\n self.driver.get(self.STRAVA + \"/athlete/training\")\n # Switch form to only bike rides\n self.driver.find_element_by_xpath(\"//select[@id='activity_type']\"\n \"/option[@value='Ride']\").click()\n self.all_rides = []\n while True:\n time.sleep(self.TIME_OUT)\n page = BeautifulSoup(self.driver.page_source)\n dates = page.find_all(\"td\", class_=\"view-col col-date\")\n date_check = [date.get_text()[-4:] != str(self.CURRENT_YEAR)\n for date in dates]\n links_on_page = page.find_all(\"td\", class_=\"view-col col-title\")\n self.all_rides.extend([a_link.a[\"href\"] for date, a_link in\n zip(date_check, links_on_page) if not date])\n if any(date_check):\n break # found a date not in CURRENT_YEAR\n try:\n self.driver.find_element_by_class_name(\"next_page\").click()\n except selenium.common.exceptions.NoSuchElementException:\n break", "def view_user(request):\n user = request.user\n latest_user_rides = Ride.objects.filter(\n participants__email=user.email).order_by('ride_date')\n latest_rides_tup = [(ride, True, ride.is_owner(user)) \n for ride in latest_user_rides if not ride.ride_in_past()]\n context = {\n 'latest_rides': latest_rides_tup,\n 'user': request.user,\n 'user_rides': True\n }\n return render(request, 'cabrides/index.html', context)", "def get_all_rides():\n return jsonify({'RideIds': listdir(RIDE_LOCATIONS)})", "def index(request):\n latest_cab_rides = Ride.objects.order_by('ride_date')\n user = request.user\n if user.is_authenticated:\n latest_rides_tup = [(ride, ride.is_participant(user), ride.is_owner(user))\n for ride in latest_cab_rides if not ride.ride_in_past()]\n else:\n latest_rides_tup = [(ride, False, False) for ride in latest_cab_rides]\n context = {\n 'latest_rides': latest_rides_tup, \n 'user': request.user\n }\n return render(request, 'cabrides/index.html', context)", "def ride_info(request, ride_id):\n context_instance = RequestContext(request)\n user = context_instance['user']\n ride = Ride.objects.get(pk=ride_id).filled_out()\n\n # If they have submitted a request and it is in bounds of the ride, let them\n # see this ride.\n # Next, check if they are part of this ride. If they are, let them see it.\n # Otherwise, don't let them see it\n user_sr = ride.get_sr_for_user(user)\n if not user_sr:\n if '_search_request' in request.session:\n # user is attempting to add this ride\n sr_post = request.session['_search_request']\n rr_form = RideRequestForm(sr_post)\n user_sr = rr_form.save(commit = False)\n user_sr.user = context_instance['user']\n ride.update_with_sr(user_sr)\n if not ride.in_bounds():\n messages.add_message(request, messages.ERROR,\n \"Error: This ride is out of your bounds.\" +\n \" You do not have access to this ride.\")\n return redirect('/rides/search/')\n else:\n messages.add_message(request, messages.ERROR,\n \"Error: You do not have access to this ride.\")\n return redirect('/')\n else:\n \tride.update_with_sr(user_sr)\n \t\n # encrypt the ride id and user_name\n enc_name = 'not implemented'\n enc_ride_id = 0\n\n data = {\n 'subtitle': 'Ride Details',\n 'ride': ride,\n 'enc_name': enc_name,\n 'enc_ride_id': enc_ride_id,\n 'user_names': ','.join(['\"%s %s\"' % (rider.first_name, rider.last_name) for rider in ride.riders]),\n 'start_latlongs': ['new google.maps.LatLng(%f, %f)' % (req.start_lat, req.start_long) for req in ride.requests],\n 'end_latlongs': [ 'new google.maps.LatLng(%f, %f)' % (req.end_lat, req.end_long) for req in ride.requests],\n 'user_in_ride': user in ride.riders}\n \n return render_to_response('detail.html', data,\n context_instance=context_instance)", "def list(self, request):\n ride_reviews = RideReview.objects.all()\n\n ride = self.request.query_params.get('ride_id', None)\n min_rating = self.request.query_params.get('min_rating', None)\n rating = self.request.query_params.get('rating', None)\n \n if ride is not None:\n ride_reviews = ride_reviews.filter(ride_id=ride)\n \n if rating is not None:\n ride_reviews = ride_reviews.filter(rating=rating)\n \n if min_rating is not None:\n ride_reviews = ride_reviews.filter(rating__gte=min_rating)\n\n serializer = RideReviewSerializer(ride_reviews, many=True,context={'request': request})\n return Response(serializer.data)", "def search_rides(request):\n context_instance=RequestContext(request)\n \n # Store the valid form in the user's session so new_ride or ride_info can\n # pick it up.\n if request.method == 'POST':\n rr_form = RideRequestForm(request.POST)\n request.session['_search_request'] = request.POST\n elif '_search_request' in request.session:\n rr_form = RideRequestForm(request.session['_search_request'])\n else:\n messages.add_message(request, messages.WARNING,\n \"Please make a search request before you attempt\" +\n \" to search\")\n return redirect('/')\n\n if rr_form.is_valid():\n sr = rr_form.save(commit = False)\n sr.user = context_instance['user']\n else:\n return HttpResponse(\"Unexpected error: form not valid \" +\n str(rr_form.errors), status=500)\n\n # Set up the template\n data = {}\n data['subtitle'] = 'Search Results'\n data['matching'] = True\n data['rides'] = Ride.get_results_for_searchrequest(sr)\n data['search_request'] = sr\n\n return render_to_response('rides.html', data, context_instance)", "def get(self, ride_id):\n self.id = ride_id\n return rides.fetch_one(self.id)", "def get_one_ride():", "def search_term(request, term):\n user = request.user\n search_rides = Ride.objects.filter(\n destination__contains=term).order_by('ride_date')\n if user.is_authenticated:\n rides_tup = [(ride, ride.is_participant(user), ride.is_owner(user)) \n for ride in search_rides if not ride.ride_in_past()]\n else:\n rides_tup = [(ride, False, False) for ride in search_rides]\n context = {\n 'latest_rides': rides_tup,\n 'user': request.user,\n }\n return render(request, 'cabrides/index.html', context)", "def new_ride(request):\n context = {'user': request.user}\n return render(request, 'cabrides/new_ride.html', context)", "def get_queryset(self):\n user = self.request.user\n return Trip.objects.filter(owner=user)", "def get_all(): \n db.query_db(\n \"SELECT * FROM ride_offers;\"\n )\n ride_offers = db.cursor.fetchall()\n if not ride_offers:\n return{\"message\":\"no ride offers yet, sorry\"}, 404\n # else convert data to dict\n rides = []\n for item in ride_offers:\n ride_dict = {\n \"ride_id\":item[0],\n \"driver_id\":item[1],\n \"location\":item[2],\n \"departure_time\":item[3],\n \"destination\":item[4]\n }\n rides.append(ride_dict)\n return rides, 200", "def get(self, ride_id):\n request = Ride.read(ride_id)\n return {'status':'success', 'message': 'Fetch successful', 'data': request}", "def get_queryset(self):\n user = self.request.user\n\n if is_athlete(user):\n return TimingSession.objects.filter(\n splits__athlete=user.athlete).distinct()\n elif is_coach(user):\n return TimingSession.objects.filter(coach=user.coach)\n else:\n return TimingSession.objects.filter(private=False)", "def request_ride(self):\n result = \"Invalid id\"\n for ride_info in rides.all_rides:\n if ride_info['ride_id'] == self.ride_id:\n result ={\"success\": (\"you have requested to join the ride from\",\n ride_info['from_where'], \"to\", ride_info[\"to\"],\n \"on\", ride_info[\"date\"])}\n requestClass.requested_rides.append(result) \n\n return result", "def request_ride(request):\n data = {'subtitle': 'Request or Create New Ride'}\n return render_to_response('new_ride.html', data,\n RequestContext(request))" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given a ride_id and a previous search request, allow the user to join the ride.
def join_ride(request, ride_id): context_instance = RequestContext(request) user = context_instance['user'] ride = Ride.objects.get(pk=ride_id) if '_search_request' in request.session: # user is attempting to add this ride sr_post = request.session['_search_request'] rr_form = RideRequestForm(sr_post) user_sr = rr_form.save(commit = False) user_sr.user = context_instance['user'] ride = ride.filled_out(user_sr) if ride.in_bounds(): user_sr.submission_time = datetime.now() # return HttpResponse(str(ride.num_of_people() + 1)) if (ride.num_people + user_sr.num_people) <= Ride.MAX_PEOPLE: user_sr.ride = ride # TODO: Make sure the ride is not full and this person can still join # the ride. If not, then throw an error. # FIXME: Potential race condition with transaction.autocommit(): user_sr.save() ride = ride.filled_out(user_sr) if ride.num_people > Ride.MAX_PEOPLE: user_sr.delete() messages.add_message(request, messages.ERROR, "Sorry, someone beat you to that ride!" + " Pick another or create a new ride.") return redirect('/rides/search/') else: messages.add_message(request, messages.ERROR, "Sorry, someone beat you to that ride!" + " Pick another.") return redirect('/rides/search/') del request.session['_search_request'] messages.add_message(request, messages.SUCCESS, "Thank you for" + " joining a ride! Coordinate with the others" + " to meet and share the fare!" ) #Send e-mail notification to other riders subject = '%s %s has joined your ride!' % (user.first_name, user.last_name) body = '%s has joined a ride you are a part of at CabFriendly.com. Go to http://cabfriendly.com/rides/%d/ to view updated details and coordinate the ride.' % (user.first_name, ride.id) emails = [] for rider in ride.riders: if rider != user: emails.append((subject, body, OUR_EMAIL, [rider.email])) send_mass_mail(emails, fail_silently=False) return redirect('/rides/%d/' % ride.id) else: messages.add_message(request, messages.ERROR, "Sorry, you aren't" + " compatible with this ride." ) return redirect('/rides/search/') else: return redirect('/rides/current/') return redirect('/')
[ "def request_ride(self):\n result = \"Invalid id\"\n for ride_info in rides.all_rides:\n if ride_info['ride_id'] == self.ride_id:\n result ={\"success\": (\"you have requested to join the ride from\",\n ride_info['from_where'], \"to\", ride_info[\"to\"],\n \"on\", ride_info[\"date\"])}\n requestClass.requested_rides.append(result) \n\n return result", "def request_ride(request):\n data = {'subtitle': 'Request or Create New Ride'}\n return render_to_response('new_ride.html', data,\n RequestContext(request))", "def search_term(request, term):\n user = request.user\n search_rides = Ride.objects.filter(\n destination__contains=term).order_by('ride_date')\n if user.is_authenticated:\n rides_tup = [(ride, ride.is_participant(user), ride.is_owner(user)) \n for ride in search_rides if not ride.ride_in_past()]\n else:\n rides_tup = [(ride, False, False) for ride in search_rides]\n context = {\n 'latest_rides': rides_tup,\n 'user': request.user,\n }\n return render(request, 'cabrides/index.html', context)", "def search_rides(request):\n context_instance=RequestContext(request)\n \n # Store the valid form in the user's session so new_ride or ride_info can\n # pick it up.\n if request.method == 'POST':\n rr_form = RideRequestForm(request.POST)\n request.session['_search_request'] = request.POST\n elif '_search_request' in request.session:\n rr_form = RideRequestForm(request.session['_search_request'])\n else:\n messages.add_message(request, messages.WARNING,\n \"Please make a search request before you attempt\" +\n \" to search\")\n return redirect('/')\n\n if rr_form.is_valid():\n sr = rr_form.save(commit = False)\n sr.user = context_instance['user']\n else:\n return HttpResponse(\"Unexpected error: form not valid \" +\n str(rr_form.errors), status=500)\n\n # Set up the template\n data = {}\n data['subtitle'] = 'Search Results'\n data['matching'] = True\n data['rides'] = Ride.get_results_for_searchrequest(sr)\n data['search_request'] = sr\n\n return render_to_response('rides.html', data, context_instance)", "def ride_info(request, ride_id):\n context_instance = RequestContext(request)\n user = context_instance['user']\n ride = Ride.objects.get(pk=ride_id).filled_out()\n\n # If they have submitted a request and it is in bounds of the ride, let them\n # see this ride.\n # Next, check if they are part of this ride. If they are, let them see it.\n # Otherwise, don't let them see it\n user_sr = ride.get_sr_for_user(user)\n if not user_sr:\n if '_search_request' in request.session:\n # user is attempting to add this ride\n sr_post = request.session['_search_request']\n rr_form = RideRequestForm(sr_post)\n user_sr = rr_form.save(commit = False)\n user_sr.user = context_instance['user']\n ride.update_with_sr(user_sr)\n if not ride.in_bounds():\n messages.add_message(request, messages.ERROR,\n \"Error: This ride is out of your bounds.\" +\n \" You do not have access to this ride.\")\n return redirect('/rides/search/')\n else:\n messages.add_message(request, messages.ERROR,\n \"Error: You do not have access to this ride.\")\n return redirect('/')\n else:\n \tride.update_with_sr(user_sr)\n \t\n # encrypt the ride id and user_name\n enc_name = 'not implemented'\n enc_ride_id = 0\n\n data = {\n 'subtitle': 'Ride Details',\n 'ride': ride,\n 'enc_name': enc_name,\n 'enc_ride_id': enc_ride_id,\n 'user_names': ','.join(['\"%s %s\"' % (rider.first_name, rider.last_name) for rider in ride.riders]),\n 'start_latlongs': ['new google.maps.LatLng(%f, %f)' % (req.start_lat, req.start_long) for req in ride.requests],\n 'end_latlongs': [ 'new google.maps.LatLng(%f, %f)' % (req.end_lat, req.end_long) for req in ride.requests],\n 'user_in_ride': user in ride.riders}\n \n return render_to_response('detail.html', data,\n context_instance=context_instance)", "def startRide(trip, passenger):\n try:\n is_already_participating = models.Participation.objects.filter(trip=trip, author=passenger).exists()\n\n if not is_already_participating:\n resp = models.Response(models.Response.NOT_FOUND,\n \"Message\", models.Response.MUST_FIRST_REQUEST_RIDE)\n return resp\n except (KeyError,models.Participation.DoesNotExist):\n resp = models.Response(models.Response.NOT_FOUND,\n \"Message\", models.Response.TRIP_NOT_FOUND)\n return resp\n\n try:\n participation = trip.get_participations().only('started',\n 'started_timestamp',\n 'started_position') \\\n .get(author=passenger)\n participation.started = True\n participation.started_timestamp = datetime.datetime.now()\n participation.started_position_id = passenger.location_id\n participation.save()\n except Exception, e:\n resp = models.Response(models.Response.BAD_REQUEST,\n \"Message\", e)\n return resp\n resp = models.Response(models.Response.ALL_OK,\n \"Participation\", participation)\n return resp", "def requestRide(trip, passenger):\n passenger_active_participation = passenger.get_active_participation()\n\n if passenger_active_participation:\n resp = models.Response(models.Response.FORBIDDEN,\n \"Trip\", passenger_active_participation.trip)\n return resp\n\n participation = models.Participation(trip_id = trip.id,\n author_id = passenger.id,\n role = 'rider',\n requested = True,\n requested_timestamp =\n datetime.datetime.now())\n\n if passenger.location:\n participation.requested_position_id = passenger.location_id\n try:\n participation.save()\n resp = models.Response(models.Response.CREATED,\n \"Participation\", participation)\n except django.db.IntegrityError, e:\n resp = models.Response(models.Response.BAD_REQUEST,\n \"Message\", e)\n return resp", "def post(self, ride_id):\n self.id = ride_id\n return ride_requests.create_request(ride_id=self.id)", "def drop_ride(request, ride_id):\n context_instance = RequestContext(request)\n user = context_instance['user']\n query = Q(ride__id=ride_id) &\\\n Q(user__id=user.id)\n sr = SearchRequest.objects.filter(query)\n if sr:\n sr = sr[0]\n ride = sr.ride\n \t\t\n sr.delete()\n messages.add_message(request, messages.SUCCESS,\n \"Success! You were removed from the ride.\")\n #Send e-mail notification to other riders\n subject = '%s %s has left your ride' % (user.first_name, user.last_name)\n body = 'Sorry, but %s has left a ride you are a part of at CabFriendly.com. Go to http://cabfriendly.com/rides/%d/ to view updated details and coordinate the ride.' % (user.first_name, ride.id)\n emails = []\n ride.filled_out()\n for rider in ride.riders:\n if rider.id != user.id:\n emails.append((subject, body, OUR_EMAIL, [rider.email]))\n send_mass_mail(emails, fail_silently=False)\n else:\n messages.add_message(request, messages.WARNING,\n \"You actually weren't part of ride %s to begin with :)\"\n % (ride_id))\n return redirect('/')", "def get_ride_or_abort(ride_id):\n ride = [ride for ride in rides if ride['id'] == ride_id]\n if len(ride) == 0:\n abort(404)\n\n return ride", "def on_make_join_request(self, room_id, user_id):\n builder = self.event_builder_factory.new({\n \"type\": EventTypes.Member,\n \"content\": {\"membership\": Membership.JOIN},\n \"room_id\": room_id,\n \"sender\": user_id,\n \"state_key\": user_id,\n })\n\n event, context = yield self._create_new_client_event(\n builder=builder,\n )\n\n self.auth.check(event, auth_events=context.auth_events)\n\n pdu = event\n\n defer.returnValue(pdu)", "def handle_client_join(self, user):\n\n if not self.context.lte_props:\n return\n\n if user.plmnid == self.context.lte_props.plmnid:\n self.handle_ue_join(user)", "def handle_ue_join(self, user):", "def searchRide(source, destination, passenger):\n passenger_active_participation = passenger.get_active_participation()\n if passenger_active_participation:\n resp = models.Response(models.Response.FORBIDDEN,\n \"Trip\", passenger_active_participation.trip)\n return resp\n\n if passenger.location.georss_point != source.georss_point:\n passenger.location = source\n try:\n passenger.location.full_clean()\n except django.core.exceptions.ValidationError, e:\n resp = models.Response(models.Response.BAD_REQUEST,\n \"Message\", e)\n return resp\n passenger.location.save()\n\n trips = matching.search_ride(destination,passenger)\n\n if not trips:\n return models.Response(models.Response.NOT_FOUND,\n \"Trip[]\", [])\n\n return models.Response(models.Response.ALL_OK,\n \"Trip[]\", trips)", "def start_ride():\n try:\n booking_id = request.form.get('booking_id')\n start_km = request.form.get('start_km')\n except (KeyError, TypeError):\n return {\"status\": bad_request_status, \"message\": req_param_missing}\n\n response = BookingBasics.start_ride(booking_id, start_km)\n\n\n return response", "def on_join(self, source):\n # They shouldn't be able to join twice\n if source.name in self.participants:\n log = self._parent.logger.entry()\n log.color(\"warn\")\n log.title(f\"You're already in the battle, {source.name}\")\n log.desc(\"Just be patient, it will begin soon\")\n log.buffer(self.ctx.channel)\n return\n\n self.participants[source.name] = source\n log = self._parent.logger.entry()\n log.title(f\"{source.name} has entered the battle field!\")\n log.desc(\"TODO: User descriptions\")\n log.buffer(self.ctx.channel)", "def do_select_request(self, arg): # TODO make testable\n cur = self.database.cursor()\n parser = get_select_request_parser()\n try:\n args = parser.parse_args(arg.split())\n cur.execute(\n \"SELECT * \"\n \"FROM requests \"\n \"WHERE rid = ?\",\n (args.rid,)\n )\n selected = cur.fetchone()\n\n if selected is None:\n print(\"There is no ride request with rid={}\".format(args.rid))\n return\n\n print(\"You have selected: {}\".format(selected))\n while True:\n response = \\\n input(\"Would you like to message the poster? [y|n]\\n\")\n if response == \"y\":\n message = input(\"Your message: \")\n cur.execute(\n \"SELECT email \"\n \"FROM requests \"\n \"WHERE rid = ?\",\n (args.rid,)\n )\n poster = cur.fetchone()[0]\n\n cur.execute(\n \"INSERT INTO inbox VALUES (?, ?, ?, ?, ?, ?);\",\n (poster,\n pendulum.now().to_datetime_string(),\n self.login_session.get_email(),\n message,\n None,\n \"n\")\n )\n self.database.commit()\n print(\"Successfully sent message to {}\".format(poster))\n break\n elif response == \"n\":\n break\n except ShellArgumentException:\n __log__.error(\"invalid argument\")", "def add_to_my_races(request):\n user = request.user.get_profile()\n event_id = request.GET.get('event_id')\n event = Event.objects.get(pk=event_id)\n user.races.add(event)\n return HttpResponseRedirect(event.race.get_absolute_url())\n return HttpResponse()", "def cancel_ride(self, rideID):\n ride=Ride.objects.get(id=rideID)\n if ride.ride_started:\n return 0\n\n ride.offer.status = 'C'\n ride.offer.save() \n\n pickup_point = self.global_address_cache.get_address((ride.offer.pickup_point.latitude,ride.offer.pickup_point.longitude))\n drop_point = self.global_address_cache.get_address((ride.offer.drop_point.latitude,ride.offer.drop_point.longitude))\n \n \n message_for_proposal=\"Your ride with \"+ride.offer.request.user.user.first_name +\" \"+ride.offer.request.user.user.last_name+\" \"+\"is cancelled\"+\"\\n\"\n message_for_proposal+=\"Information of ride: \"+\"\\n\"\n message_for_proposal+=\"The pick up point was at \"+pickup_point+\"\\n\"\n message_for_proposal+=\"The ride started at: \"+str(ride.offer.pickup_time)+\"\\n\"\n message_for_proposal+=\"The drop point was at \"+drop_point+\"\\n\"\n message_for_proposal+=\"The drop time was at \"+str(ride.offer.drop_time)+\"\\n\"\n message_for_proposal+=\"Please visit your account for further information\"\n\n message_for_request=\"You have ride with \"+ride.offer.proposal.user.user.first_name +\" \"+ride.offer.proposal.user.user.last_name+\" \"+\"is cancelled\"+\"\\n\"\n message_for_request+=\"Information of ride: \"+\"\\n\"\n message_for_request+=\"The pick up point was at \"+pickup_point+\"\\n\"\n message_for_request+=\"The ride started at: \"+str(ride.offer.pickup_time)+\"\\n\"\n message_for_request+=\"The drop point was at \"+drop_point+\"\\n\"\n message_for_request+=\"The drop time was\"+str(ride.offer.drop_time)+\"\\n\"\n message_for_request+=\"Please visit your account for further information\" \n \n self.send_to(self.usernotifier_port, ('newmsg', ride.offer.request.user.id, message_for_request))\n self.send_to(self.usernotifier_port, ('newmsg', ride.offer.proposal.user.id, message_for_proposal))\n return 1" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function drops a user from a ride if they are part of it. Otherwise, it does nothing and reports an error.
def drop_ride(request, ride_id): context_instance = RequestContext(request) user = context_instance['user'] query = Q(ride__id=ride_id) &\ Q(user__id=user.id) sr = SearchRequest.objects.filter(query) if sr: sr = sr[0] ride = sr.ride sr.delete() messages.add_message(request, messages.SUCCESS, "Success! You were removed from the ride.") #Send e-mail notification to other riders subject = '%s %s has left your ride' % (user.first_name, user.last_name) body = 'Sorry, but %s has left a ride you are a part of at CabFriendly.com. Go to http://cabfriendly.com/rides/%d/ to view updated details and coordinate the ride.' % (user.first_name, ride.id) emails = [] ride.filled_out() for rider in ride.riders: if rider.id != user.id: emails.append((subject, body, OUR_EMAIL, [rider.email])) send_mass_mail(emails, fail_silently=False) else: messages.add_message(request, messages.WARNING, "You actually weren't part of ride %s to begin with :)" % (ride_id)) return redirect('/')
[ "def cancel_ride(self, rideID):\n ride=Ride.objects.get(id=rideID)\n if ride.ride_started:\n return 0\n\n ride.offer.status = 'C'\n ride.offer.save() \n\n pickup_point = self.global_address_cache.get_address((ride.offer.pickup_point.latitude,ride.offer.pickup_point.longitude))\n drop_point = self.global_address_cache.get_address((ride.offer.drop_point.latitude,ride.offer.drop_point.longitude))\n \n \n message_for_proposal=\"Your ride with \"+ride.offer.request.user.user.first_name +\" \"+ride.offer.request.user.user.last_name+\" \"+\"is cancelled\"+\"\\n\"\n message_for_proposal+=\"Information of ride: \"+\"\\n\"\n message_for_proposal+=\"The pick up point was at \"+pickup_point+\"\\n\"\n message_for_proposal+=\"The ride started at: \"+str(ride.offer.pickup_time)+\"\\n\"\n message_for_proposal+=\"The drop point was at \"+drop_point+\"\\n\"\n message_for_proposal+=\"The drop time was at \"+str(ride.offer.drop_time)+\"\\n\"\n message_for_proposal+=\"Please visit your account for further information\"\n\n message_for_request=\"You have ride with \"+ride.offer.proposal.user.user.first_name +\" \"+ride.offer.proposal.user.user.last_name+\" \"+\"is cancelled\"+\"\\n\"\n message_for_request+=\"Information of ride: \"+\"\\n\"\n message_for_request+=\"The pick up point was at \"+pickup_point+\"\\n\"\n message_for_request+=\"The ride started at: \"+str(ride.offer.pickup_time)+\"\\n\"\n message_for_request+=\"The drop point was at \"+drop_point+\"\\n\"\n message_for_request+=\"The drop time was\"+str(ride.offer.drop_time)+\"\\n\"\n message_for_request+=\"Please visit your account for further information\" \n \n self.send_to(self.usernotifier_port, ('newmsg', ride.offer.request.user.id, message_for_request))\n self.send_to(self.usernotifier_port, ('newmsg', ride.offer.proposal.user.id, message_for_proposal))\n return 1", "def decline_invitation(user: models.User, game: models.Game):\n if game.invited != user:\n raise RequestError(2111)\n _end_socket_session(game.host, game)\n game.delete_instance()", "def cancel_ride(self, rider):\n if rider in self._riders:\n self._riders.remove(rider)", "def test_kick_without_room(self, disconnect_user):\n\n res = self.chat_command(self.resource, \"User\")\n self.assertEqual(len(res), 1)\n self.assertRegex(res[0], \"Unknown user\")\n\n disconnect_user.assert_not_called()\n\n user = UserFactory(online=True, connection=self.connection)\n\n target_user = UserFactory(online=True)\n\n res = self.chat_command(self.resource, target_user.name)\n self.assertEqual(len(res), 1)\n self.assertRegex(res[0], \"Not authorize\")\n disconnect_user.assert_not_called()\n\n user.rank = self.chat_command.permission.value\n res = self.chat_command(self.resource, target_user.name)\n\n self.assertFalse(models.Ban.is_ban(self.session, user_id=target_user.id))\n disconnect_user.assert_called_with(target_user.id)\n\n self.assertIsNone(res)", "def test_see_airline_after_user_deletion(self):\n pass", "def do_cancel_reservation (self, user):\n try:\n if not user:\n ret = self.trex.cancel_reservation()\n else:\n ret = self.trex.cancel_reservation(user.split(' ')[0])\n print termstyle.green(\"*** T-Rex reservation canceled successfully ***\")\n except TRexException as inst:\n print termstyle.red(inst)", "def delete_ride():", "def delete_user(self, name):\n\n # If the user exists delete it, else throw 'user not found'\n if os.path.exists(f\"./Residents/{name}.jpeg\"):\n os.remove(f\"./Residents/{name}.jpeg\")\n print(f\"[INFO] The user {name} removed from the database\")\n else:\n print(\"[INFO] The user does not exist\")", "def remove_user(username, steamid, discorduser=\"\"):\n\tpass", "def test_remove_card(self) -> None:\r\n self.localisation.apply_user_change(3, self.user)\r\n ownership = self.localisation.ownerships.get(owner=self.user)\r\n self.assertEqual(ownership.count, 3)\r\n self.localisation.apply_user_change(-3, self.user)\r\n self.assertFalse(self.localisation.ownerships.filter(owner=self.user).exists())", "async def player_kicked(self, ctx, user):\r\n await ctx.send(f\"{user.mention} You have been removed from the game as \" +\r\n \"there are not enough players\")", "async def on_reaction_remove(reaction, user):\n server = reaction.message.server\n message = reaction.message\n if user == server.me:\n return\n\n if reaction.emoji == get_join_emoji():\n raid_channel = lookup_raid_channel(message)\n if is_raid_channel(raid_channel):\n # NB: use overwrites for, since admins otherwise won't be notified\n # we know the channel is private and only overwrites matter\n if not raid_channel.overwrites_for(user).is_empty():\n await uninvite_user_from_raid(raid_channel, user)", "def remove_user(self, user, room_number):\n if user in self.users:\n self.users.remove(user)\n user.set_room(room_number)\n self.write_to_logs(f\">>> Client has been disconnected. {user} <<<\")", "def abort_if_not_own(user_id: int, message: Message):\n if message.sender_id != user_id:\n logger.info(\"Abort because user does not own\")\n abort(403, message=f'Message {message.message_id} does not belong to you')", "def __remove_from_event(self, user_id: int, room: str):\n if room in self.connected_by_jap_event.keys():\n self.connected_by_jap_event[room] = [\n user\n for user in self.connected_by_jap_event[room]\n if user.get(\"id\") != user_id\n ]\n else:\n app.logger.info(\"Should not happen: User left jap_event but was not on it\")", "def remove(self, user: Optional[str] = None):\n raise NotImplementedError", "async def botunban(self, ctx, user: discord.User):\n\t\tif checks.is_owner_check(user) or user == self.bot.user:\n\t\t\tawait self.bot.say(\"Ha ha. Very funny.\")\n\t\t\treturn\n\t\tbotdata.serverinfo(ctx.message.server).botunban(user)\n\t\tawait self.bot.say(\"{} is free of their restraints and may once again use commands\".format(user.mention))", "def remove_player_from_room(room_id, user):\n # Check if the user is logged in\n if not user.is_authenticated:\n raise ClientError(\"USER_HAS_TO_LOGIN\")\n # Find the room they requested (by ID)\n try:\n user.game_room = None\n user.save()\n except User.DoesNotExist:\n raise ClientError(\"USER_INVALID\")\n except Room.DoesNotExist:\n raise ClientError(\"ROOM_INVALID\")\n return True", "async def drop_passenger(self):\n await self.inform_passenger(PASSENGER_IN_DEST)\n self.status = TAXI_WAITING\n logger.debug(\"Taxi {} has dropped the passenger {} in destination.\".format(self.agent_id,\n self.get(\n \"current_passenger\")))\n self.set(\"current_passenger\", None)\n self.set(\"passenger_in_taxi\", None)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Page displaying ride information, along with a chat window. First, confirm that the user is or has been part of this ride. Then, fetch the ride information.
def ride_info(request, ride_id): context_instance = RequestContext(request) user = context_instance['user'] ride = Ride.objects.get(pk=ride_id).filled_out() # If they have submitted a request and it is in bounds of the ride, let them # see this ride. # Next, check if they are part of this ride. If they are, let them see it. # Otherwise, don't let them see it user_sr = ride.get_sr_for_user(user) if not user_sr: if '_search_request' in request.session: # user is attempting to add this ride sr_post = request.session['_search_request'] rr_form = RideRequestForm(sr_post) user_sr = rr_form.save(commit = False) user_sr.user = context_instance['user'] ride.update_with_sr(user_sr) if not ride.in_bounds(): messages.add_message(request, messages.ERROR, "Error: This ride is out of your bounds." + " You do not have access to this ride.") return redirect('/rides/search/') else: messages.add_message(request, messages.ERROR, "Error: You do not have access to this ride.") return redirect('/') else: ride.update_with_sr(user_sr) # encrypt the ride id and user_name enc_name = 'not implemented' enc_ride_id = 0 data = { 'subtitle': 'Ride Details', 'ride': ride, 'enc_name': enc_name, 'enc_ride_id': enc_ride_id, 'user_names': ','.join(['"%s %s"' % (rider.first_name, rider.last_name) for rider in ride.riders]), 'start_latlongs': ['new google.maps.LatLng(%f, %f)' % (req.start_lat, req.start_long) for req in ride.requests], 'end_latlongs': [ 'new google.maps.LatLng(%f, %f)' % (req.end_lat, req.end_long) for req in ride.requests], 'user_in_ride': user in ride.riders} return render_to_response('detail.html', data, context_instance=context_instance)
[ "def join_ride(request, ride_id):\n context_instance = RequestContext(request)\n user = context_instance['user']\n ride = Ride.objects.get(pk=ride_id)\n if '_search_request' in request.session:\n # user is attempting to add this ride\n sr_post = request.session['_search_request']\n rr_form = RideRequestForm(sr_post)\n user_sr = rr_form.save(commit = False)\n user_sr.user = context_instance['user']\n ride = ride.filled_out(user_sr)\n if ride.in_bounds():\n user_sr.submission_time = datetime.now()\n # return HttpResponse(str(ride.num_of_people() + 1))\n if (ride.num_people + user_sr.num_people) <= Ride.MAX_PEOPLE:\n user_sr.ride = ride\n # TODO: Make sure the ride is not full and this person can still join\n # the ride. If not, then throw an error.\n # FIXME: Potential race condition\n with transaction.autocommit():\n user_sr.save()\n \n ride = ride.filled_out(user_sr)\n if ride.num_people > Ride.MAX_PEOPLE:\n user_sr.delete()\n messages.add_message(request, messages.ERROR,\n \"Sorry, someone beat you to that ride!\" +\n \" Pick another or create a new ride.\")\n return redirect('/rides/search/')\n else:\n messages.add_message(request, messages.ERROR,\n \"Sorry, someone beat you to that ride!\" +\n \" Pick another.\")\n return redirect('/rides/search/')\n \n del request.session['_search_request']\n messages.add_message(request, messages.SUCCESS, \"Thank you for\" +\n \" joining a ride! Coordinate with the others\" +\n \" to meet and share the fare!\" )\n \n #Send e-mail notification to other riders\n subject = '%s %s has joined your ride!' % (user.first_name, user.last_name)\n body = '%s has joined a ride you are a part of at CabFriendly.com. Go to http://cabfriendly.com/rides/%d/ to view updated details and coordinate the ride.' % (user.first_name, ride.id)\n emails = []\n for rider in ride.riders:\n if rider != user:\n emails.append((subject, body, OUR_EMAIL, [rider.email]))\n send_mass_mail(emails, fail_silently=False) \n return redirect('/rides/%d/' % ride.id)\n else:\n messages.add_message(request, messages.ERROR, \"Sorry, you aren't\" +\n \" compatible with this ride.\" )\n return redirect('/rides/search/')\n else:\n return redirect('/rides/current/')\n\n return redirect('/')", "def current_rides(request):\n context_instance=RequestContext(request)\n user = context_instance['user']\n data = {\n 'subtitle': 'Current Rides',\n 'matching': False,\n 'rides': Ride.get_all_rides_for_user(user)}\n return render_to_response('rides.html', data,\n context_instance=context_instance)", "def request_ride(request):\n data = {'subtitle': 'Request or Create New Ride'}\n return render_to_response('new_ride.html', data,\n RequestContext(request))", "def new_ride(request):\n context = {'user': request.user}\n return render(request, 'cabrides/new_ride.html', context)", "def view_user(request):\n user = request.user\n latest_user_rides = Ride.objects.filter(\n participants__email=user.email).order_by('ride_date')\n latest_rides_tup = [(ride, True, ride.is_owner(user)) \n for ride in latest_user_rides if not ride.ride_in_past()]\n context = {\n 'latest_rides': latest_rides_tup,\n 'user': request.user,\n 'user_rides': True\n }\n return render(request, 'cabrides/index.html', context)", "def confirm_uber():\n if type(uber_client) == None:\n redirect('/')\n\n user_lat = flask.request.form['user_lat']\n user_long = flask.request.form['user_long']\n business_lat = flask.request.form['business_lat']\n business_long = flask.request.form['business_long']\n product_id = flask.request.form['product_id']\n fare_id = flask.request.form['fare_id']\n try:\n response = uber_client.request_ride(\n product_id=product_id,\n start_latitude=float(user_lat),\n start_longitude=float(user_long),\n end_latitude=float(business_lat),\n end_longitude=float(business_long),\n seat_count=2,\n fare_id=fare_id\n )\n except ClientError as error:\n return \"Uber Error: {0}, {1}\".format(error.errors, error.message)\n \n request = response.json \n request_id = request.get('request_id')\n\n return render_template('ride_request.html',\n request=False,\n confirmed=True,\n request_id=request_id)", "def index(request):\n latest_cab_rides = Ride.objects.order_by('ride_date')\n user = request.user\n if user.is_authenticated:\n latest_rides_tup = [(ride, ride.is_participant(user), ride.is_owner(user))\n for ride in latest_cab_rides if not ride.ride_in_past()]\n else:\n latest_rides_tup = [(ride, False, False) for ride in latest_cab_rides]\n context = {\n 'latest_rides': latest_rides_tup, \n 'user': request.user\n }\n return render(request, 'cabrides/index.html', context)", "def cancel_ride(self, rideID):\n ride=Ride.objects.get(id=rideID)\n if ride.ride_started:\n return 0\n\n ride.offer.status = 'C'\n ride.offer.save() \n\n pickup_point = self.global_address_cache.get_address((ride.offer.pickup_point.latitude,ride.offer.pickup_point.longitude))\n drop_point = self.global_address_cache.get_address((ride.offer.drop_point.latitude,ride.offer.drop_point.longitude))\n \n \n message_for_proposal=\"Your ride with \"+ride.offer.request.user.user.first_name +\" \"+ride.offer.request.user.user.last_name+\" \"+\"is cancelled\"+\"\\n\"\n message_for_proposal+=\"Information of ride: \"+\"\\n\"\n message_for_proposal+=\"The pick up point was at \"+pickup_point+\"\\n\"\n message_for_proposal+=\"The ride started at: \"+str(ride.offer.pickup_time)+\"\\n\"\n message_for_proposal+=\"The drop point was at \"+drop_point+\"\\n\"\n message_for_proposal+=\"The drop time was at \"+str(ride.offer.drop_time)+\"\\n\"\n message_for_proposal+=\"Please visit your account for further information\"\n\n message_for_request=\"You have ride with \"+ride.offer.proposal.user.user.first_name +\" \"+ride.offer.proposal.user.user.last_name+\" \"+\"is cancelled\"+\"\\n\"\n message_for_request+=\"Information of ride: \"+\"\\n\"\n message_for_request+=\"The pick up point was at \"+pickup_point+\"\\n\"\n message_for_request+=\"The ride started at: \"+str(ride.offer.pickup_time)+\"\\n\"\n message_for_request+=\"The drop point was at \"+drop_point+\"\\n\"\n message_for_request+=\"The drop time was\"+str(ride.offer.drop_time)+\"\\n\"\n message_for_request+=\"Please visit your account for further information\" \n \n self.send_to(self.usernotifier_port, ('newmsg', ride.offer.request.user.id, message_for_request))\n self.send_to(self.usernotifier_port, ('newmsg', ride.offer.proposal.user.id, message_for_proposal))\n return 1", "def requestRide(trip, passenger):\n passenger_active_participation = passenger.get_active_participation()\n\n if passenger_active_participation:\n resp = models.Response(models.Response.FORBIDDEN,\n \"Trip\", passenger_active_participation.trip)\n return resp\n\n participation = models.Participation(trip_id = trip.id,\n author_id = passenger.id,\n role = 'rider',\n requested = True,\n requested_timestamp =\n datetime.datetime.now())\n\n if passenger.location:\n participation.requested_position_id = passenger.location_id\n try:\n participation.save()\n resp = models.Response(models.Response.CREATED,\n \"Participation\", participation)\n except django.db.IntegrityError, e:\n resp = models.Response(models.Response.BAD_REQUEST,\n \"Message\", e)\n return resp", "def all_rides(request):\n context_instance=RequestContext(request)\n data = {\n 'subtitle': 'Current Rides',\n 'matching': False,\n 'rides': Ride.get_all_rides()}\n return render_to_response('rides.html', data,\n context_instance=context_instance)", "def new_ride(request):\n\n context_instance = RequestContext(request)\n\n # A POST request indicates that a DescriptionForm has been submitted.\n if request.method == 'POST':\n rr_form = RideRequestForm(request.session['_search_request'])\n if rr_form.is_valid():\n sr = rr_form.save(commit = False)\n sr.user = context_instance['user']\n sr.submission_time = datetime.now()\n else:\n return HttpResponse(\"Unexpected error: bad rr_form\")\n\n desc_form = DescriptionForm(request.POST) \n if desc_form.is_valid():\n ride = Ride()\n ride.description = desc_form.cleaned_data['description']\n ride.save()\n sr.ride = ride\n sr.save()\n messages.add_message(request, messages.SUCCESS, THANK_YOU_MESSAGE)\n else:\n return HttpResponse(\"Error: Invalid description in form.\")\n\n del request.session['_search_request']\n return redirect('/')\n\n else:\n return render_to_response('add_description.html',\n context_instance)", "def search_rides(request):\n context_instance=RequestContext(request)\n \n # Store the valid form in the user's session so new_ride or ride_info can\n # pick it up.\n if request.method == 'POST':\n rr_form = RideRequestForm(request.POST)\n request.session['_search_request'] = request.POST\n elif '_search_request' in request.session:\n rr_form = RideRequestForm(request.session['_search_request'])\n else:\n messages.add_message(request, messages.WARNING,\n \"Please make a search request before you attempt\" +\n \" to search\")\n return redirect('/')\n\n if rr_form.is_valid():\n sr = rr_form.save(commit = False)\n sr.user = context_instance['user']\n else:\n return HttpResponse(\"Unexpected error: form not valid \" +\n str(rr_form.errors), status=500)\n\n # Set up the template\n data = {}\n data['subtitle'] = 'Search Results'\n data['matching'] = True\n data['rides'] = Ride.get_results_for_searchrequest(sr)\n data['search_request'] = sr\n\n return render_to_response('rides.html', data, context_instance)", "def request_ride(self):\n result = \"Invalid id\"\n for ride_info in rides.all_rides:\n if ride_info['ride_id'] == self.ride_id:\n result ={\"success\": (\"you have requested to join the ride from\",\n ride_info['from_where'], \"to\", ride_info[\"to\"],\n \"on\", ride_info[\"date\"])}\n requestClass.requested_rides.append(result) \n\n return result", "def view_client():\n\n\tclient_id = request.args.get('client_id')\n\tclient_result = Client.query.filter_by(id=client_id).first()\n\tinteraction_results = db.session.query(Interaction).filter_by(client_id=client_id)[:-30:-1]\n\tnote_results = db.session.query(ClientNote).filter_by(client_id=client_id)[:-30:-1]\n\n\treturn render_template('specific_client.html', client=client_result, \n\t\t\t\t\t\t interactions=interaction_results, yearsList = years, \n\t\t\t\t\t\t notes=note_results, pretty_date=pretty_date)", "def get(self, ride_id):\n request = Ride.read(ride_id)\n return {'status':'success', 'message': 'Fetch successful', 'data': request}", "def create_ride(request):\n from datetime import datetime\n try:\n origin = request.POST['origin']\n destination = request.POST['destination']\n if origin == '' or destination == '':\n return HttpResponse(\"fill everything in!\")\n else:\n date = request.POST['date']\n time = request.POST['time']\n datetime_string = ' '.join([date, time])\n max_riders = request.POST['max_riders']\n date_object = datetime.strptime(datetime_string, '%m/%d/%Y %I:%M %p')\n new_ride = Ride(origin=origin, destination=destination,\n ride_owner=request.user, max_riders=max_riders, ride_date=date_object)\n new_ride.save()\n new_ride.participants.add(request.user)\n return redirect('/cabrides/')\n except KeyError:\n return HttpResponse(\"Not all fields were filled out.\")", "def startRide(trip, passenger):\n try:\n is_already_participating = models.Participation.objects.filter(trip=trip, author=passenger).exists()\n\n if not is_already_participating:\n resp = models.Response(models.Response.NOT_FOUND,\n \"Message\", models.Response.MUST_FIRST_REQUEST_RIDE)\n return resp\n except (KeyError,models.Participation.DoesNotExist):\n resp = models.Response(models.Response.NOT_FOUND,\n \"Message\", models.Response.TRIP_NOT_FOUND)\n return resp\n\n try:\n participation = trip.get_participations().only('started',\n 'started_timestamp',\n 'started_position') \\\n .get(author=passenger)\n participation.started = True\n participation.started_timestamp = datetime.datetime.now()\n participation.started_position_id = passenger.location_id\n participation.save()\n except Exception, e:\n resp = models.Response(models.Response.BAD_REQUEST,\n \"Message\", e)\n return resp\n resp = models.Response(models.Response.ALL_OK,\n \"Participation\", participation)\n return resp", "def update_ride():", "def get_one_ride():" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Form to request a new ride.
def request_ride(request): data = {'subtitle': 'Request or Create New Ride'} return render_to_response('new_ride.html', data, RequestContext(request))
[ "def new_ride(request):\n\n context_instance = RequestContext(request)\n\n # A POST request indicates that a DescriptionForm has been submitted.\n if request.method == 'POST':\n rr_form = RideRequestForm(request.session['_search_request'])\n if rr_form.is_valid():\n sr = rr_form.save(commit = False)\n sr.user = context_instance['user']\n sr.submission_time = datetime.now()\n else:\n return HttpResponse(\"Unexpected error: bad rr_form\")\n\n desc_form = DescriptionForm(request.POST) \n if desc_form.is_valid():\n ride = Ride()\n ride.description = desc_form.cleaned_data['description']\n ride.save()\n sr.ride = ride\n sr.save()\n messages.add_message(request, messages.SUCCESS, THANK_YOU_MESSAGE)\n else:\n return HttpResponse(\"Error: Invalid description in form.\")\n\n del request.session['_search_request']\n return redirect('/')\n\n else:\n return render_to_response('add_description.html',\n context_instance)", "def post(self, ride_id):\n self.id = ride_id\n return ride_requests.create_request(ride_id=self.id)", "def post(self):\n args = self.reqparse.parse_args()\n check_for_empty_fields(args)\n validate_date(args['date'])\n ride = Ride(\n args['date'],\n args['time'],\n args['pickup'],\n args['dropoff'],\n args['driver_id'],\n args['price']\n )\n return ride.add()", "def create_ride(request):\n from datetime import datetime\n try:\n origin = request.POST['origin']\n destination = request.POST['destination']\n if origin == '' or destination == '':\n return HttpResponse(\"fill everything in!\")\n else:\n date = request.POST['date']\n time = request.POST['time']\n datetime_string = ' '.join([date, time])\n max_riders = request.POST['max_riders']\n date_object = datetime.strptime(datetime_string, '%m/%d/%Y %I:%M %p')\n new_ride = Ride(origin=origin, destination=destination,\n ride_owner=request.user, max_riders=max_riders, ride_date=date_object)\n new_ride.save()\n new_ride.participants.add(request.user)\n return redirect('/cabrides/')\n except KeyError:\n return HttpResponse(\"Not all fields were filled out.\")", "def new_ride(request):\n context = {'user': request.user}\n return render(request, 'cabrides/new_ride.html', context)", "def start_ride():\n try:\n booking_id = request.form.get('booking_id')\n start_km = request.form.get('start_km')\n except (KeyError, TypeError):\n return {\"status\": bad_request_status, \"message\": req_param_missing}\n\n response = BookingBasics.start_ride(booking_id, start_km)\n\n\n return response", "def ride_info(request, ride_id):\n context_instance = RequestContext(request)\n user = context_instance['user']\n ride = Ride.objects.get(pk=ride_id).filled_out()\n\n # If they have submitted a request and it is in bounds of the ride, let them\n # see this ride.\n # Next, check if they are part of this ride. If they are, let them see it.\n # Otherwise, don't let them see it\n user_sr = ride.get_sr_for_user(user)\n if not user_sr:\n if '_search_request' in request.session:\n # user is attempting to add this ride\n sr_post = request.session['_search_request']\n rr_form = RideRequestForm(sr_post)\n user_sr = rr_form.save(commit = False)\n user_sr.user = context_instance['user']\n ride.update_with_sr(user_sr)\n if not ride.in_bounds():\n messages.add_message(request, messages.ERROR,\n \"Error: This ride is out of your bounds.\" +\n \" You do not have access to this ride.\")\n return redirect('/rides/search/')\n else:\n messages.add_message(request, messages.ERROR,\n \"Error: You do not have access to this ride.\")\n return redirect('/')\n else:\n \tride.update_with_sr(user_sr)\n \t\n # encrypt the ride id and user_name\n enc_name = 'not implemented'\n enc_ride_id = 0\n\n data = {\n 'subtitle': 'Ride Details',\n 'ride': ride,\n 'enc_name': enc_name,\n 'enc_ride_id': enc_ride_id,\n 'user_names': ','.join(['\"%s %s\"' % (rider.first_name, rider.last_name) for rider in ride.riders]),\n 'start_latlongs': ['new google.maps.LatLng(%f, %f)' % (req.start_lat, req.start_long) for req in ride.requests],\n 'end_latlongs': [ 'new google.maps.LatLng(%f, %f)' % (req.end_lat, req.end_long) for req in ride.requests],\n 'user_in_ride': user in ride.riders}\n \n return render_to_response('detail.html', data,\n context_instance=context_instance)", "def create_ride():", "def requestRide(trip, passenger):\n passenger_active_participation = passenger.get_active_participation()\n\n if passenger_active_participation:\n resp = models.Response(models.Response.FORBIDDEN,\n \"Trip\", passenger_active_participation.trip)\n return resp\n\n participation = models.Participation(trip_id = trip.id,\n author_id = passenger.id,\n role = 'rider',\n requested = True,\n requested_timestamp =\n datetime.datetime.now())\n\n if passenger.location:\n participation.requested_position_id = passenger.location_id\n try:\n participation.save()\n resp = models.Response(models.Response.CREATED,\n \"Participation\", participation)\n except django.db.IntegrityError, e:\n resp = models.Response(models.Response.BAD_REQUEST,\n \"Message\", e)\n return resp", "def create(self, request):\n reviewer = QueueUser.objects.get(user=request.auth.user)\n ride_review = RideReview()\n ride = Ride.objects.get(pk=request.data[\"ride_id\"])\n ride_review.ride = ride\n ride_review.rating = request.data[\"rating\"]\n ride_review.review = request.data[\"review\"]\n ride_review.reviewer = reviewer\n try:\n rides = RideReview.objects.all()\n ridecheck = rides.filter(reviewer=reviewer, ride=request.data[\"ride_id\"]).exists()\n if ridecheck:\n return Response({'message': 'Already exists'}, status=status.HTTP_409_CONFLICT)\n else:\n ride_review.save()\n serializer = RideReviewSerializer(ride_review, context={'request': request})\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n except ValidationError as ex:\n return Response({\"reason\": ex.message}, status=status.HTTP_400_BAD_REQUEST)", "def put(self, ride_id):\n args = self.reqparse.parse_args()\n check_for_empty_fields(args)\n return Ride.edit(\n args['date'], \n args['time'], \n args['pickup'], \n args['dropoff'], \n args['driver_id'], \n args['price'], \n args['status'], \n ride_id\n )", "def save_request_ride(self):\n db.cursor.execute(\n \"\"\"\n INSERT INTO ride_requests(user_id, offer_id)\n VALUES(%s, %s)\n \"\"\",\n (self.user_id, self.offer_id)\n )\n db.commit()\n return", "def rota_detail_form(**kwargs):\n return RotaDetailForm(**kwargs)", "def request_ride(self):\n result = \"Invalid id\"\n for ride_info in rides.all_rides:\n if ride_info['ride_id'] == self.ride_id:\n result ={\"success\": (\"you have requested to join the ride from\",\n ride_info['from_where'], \"to\", ride_info[\"to\"],\n \"on\", ride_info[\"date\"])}\n requestClass.requested_rides.append(result) \n\n return result", "def join_ride(request, ride_id):\n context_instance = RequestContext(request)\n user = context_instance['user']\n ride = Ride.objects.get(pk=ride_id)\n if '_search_request' in request.session:\n # user is attempting to add this ride\n sr_post = request.session['_search_request']\n rr_form = RideRequestForm(sr_post)\n user_sr = rr_form.save(commit = False)\n user_sr.user = context_instance['user']\n ride = ride.filled_out(user_sr)\n if ride.in_bounds():\n user_sr.submission_time = datetime.now()\n # return HttpResponse(str(ride.num_of_people() + 1))\n if (ride.num_people + user_sr.num_people) <= Ride.MAX_PEOPLE:\n user_sr.ride = ride\n # TODO: Make sure the ride is not full and this person can still join\n # the ride. If not, then throw an error.\n # FIXME: Potential race condition\n with transaction.autocommit():\n user_sr.save()\n \n ride = ride.filled_out(user_sr)\n if ride.num_people > Ride.MAX_PEOPLE:\n user_sr.delete()\n messages.add_message(request, messages.ERROR,\n \"Sorry, someone beat you to that ride!\" +\n \" Pick another or create a new ride.\")\n return redirect('/rides/search/')\n else:\n messages.add_message(request, messages.ERROR,\n \"Sorry, someone beat you to that ride!\" +\n \" Pick another.\")\n return redirect('/rides/search/')\n \n del request.session['_search_request']\n messages.add_message(request, messages.SUCCESS, \"Thank you for\" +\n \" joining a ride! Coordinate with the others\" +\n \" to meet and share the fare!\" )\n \n #Send e-mail notification to other riders\n subject = '%s %s has joined your ride!' % (user.first_name, user.last_name)\n body = '%s has joined a ride you are a part of at CabFriendly.com. Go to http://cabfriendly.com/rides/%d/ to view updated details and coordinate the ride.' % (user.first_name, ride.id)\n emails = []\n for rider in ride.riders:\n if rider != user:\n emails.append((subject, body, OUR_EMAIL, [rider.email]))\n send_mass_mail(emails, fail_silently=False) \n return redirect('/rides/%d/' % ride.id)\n else:\n messages.add_message(request, messages.ERROR, \"Sorry, you aren't\" +\n \" compatible with this ride.\" )\n return redirect('/rides/search/')\n else:\n return redirect('/rides/current/')\n\n return redirect('/')", "def confirm_uber():\n if type(uber_client) == None:\n redirect('/')\n\n user_lat = flask.request.form['user_lat']\n user_long = flask.request.form['user_long']\n business_lat = flask.request.form['business_lat']\n business_long = flask.request.form['business_long']\n product_id = flask.request.form['product_id']\n fare_id = flask.request.form['fare_id']\n try:\n response = uber_client.request_ride(\n product_id=product_id,\n start_latitude=float(user_lat),\n start_longitude=float(user_long),\n end_latitude=float(business_lat),\n end_longitude=float(business_long),\n seat_count=2,\n fare_id=fare_id\n )\n except ClientError as error:\n return \"Uber Error: {0}, {1}\".format(error.errors, error.message)\n \n request = response.json \n request_id = request.get('request_id')\n\n return render_template('ride_request.html',\n request=False,\n confirmed=True,\n request_id=request_id)", "def create(self, validated_data):\n\n circle = self.context['circle']\n membership = self.context['membership']\n profile = validated_data['offered_by'].profile\n\n ride = Ride.objects.create(\n offered_in=circle,\n **validated_data\n )\n\n # Updating data\n circle.rides_offered += 1\n circle.save()\n\n membership.rides_offered += 1\n membership.save()\n\n profile.rides_offered += 1\n profile.save()\n\n return ride", "def create(self, data):\n circle = self.context['circle']\n ride = Ride.objects.create(**data, offered_in=circle)\n\n #Circle\n circle.rides_offered += 1\n circle.save()\n\n #Membership\n membership = self.context['membership']\n membership.rides_offered += 1\n membership.save()\n\n #Profile\n profile = data['offered_by'].profile\n profile.rides_offered += 1\n profile.save()\n\n return ride", "def save(self, **kwargs):\n\n rating = self.context['rating']\n\n rating.score = self.validated_data['qualification']\n\n rating.save()\n\n ride = self.context['ride']\n\n return ride" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Show rides matching the search criteria of the request.
def search_rides(request): context_instance=RequestContext(request) # Store the valid form in the user's session so new_ride or ride_info can # pick it up. if request.method == 'POST': rr_form = RideRequestForm(request.POST) request.session['_search_request'] = request.POST elif '_search_request' in request.session: rr_form = RideRequestForm(request.session['_search_request']) else: messages.add_message(request, messages.WARNING, "Please make a search request before you attempt" + " to search") return redirect('/') if rr_form.is_valid(): sr = rr_form.save(commit = False) sr.user = context_instance['user'] else: return HttpResponse("Unexpected error: form not valid " + str(rr_form.errors), status=500) # Set up the template data = {} data['subtitle'] = 'Search Results' data['matching'] = True data['rides'] = Ride.get_results_for_searchrequest(sr) data['search_request'] = sr return render_to_response('rides.html', data, context_instance)
[ "def all_rides(request):\n context_instance=RequestContext(request)\n data = {\n 'subtitle': 'Current Rides',\n 'matching': False,\n 'rides': Ride.get_all_rides()}\n return render_to_response('rides.html', data,\n context_instance=context_instance)", "def get_all_rides():", "def list(self, request):\n ride_reviews = RideReview.objects.all()\n\n ride = self.request.query_params.get('ride_id', None)\n min_rating = self.request.query_params.get('min_rating', None)\n rating = self.request.query_params.get('rating', None)\n \n if ride is not None:\n ride_reviews = ride_reviews.filter(ride_id=ride)\n \n if rating is not None:\n ride_reviews = ride_reviews.filter(rating=rating)\n \n if min_rating is not None:\n ride_reviews = ride_reviews.filter(rating__gte=min_rating)\n\n serializer = RideReviewSerializer(ride_reviews, many=True,context={'request': request})\n return Response(serializer.data)", "def get_rides(self):\n self.driver.get(self.STRAVA + \"/athlete/training\")\n # Switch form to only bike rides\n self.driver.find_element_by_xpath(\"//select[@id='activity_type']\"\n \"/option[@value='Ride']\").click()\n self.all_rides = []\n while True:\n time.sleep(self.TIME_OUT)\n page = BeautifulSoup(self.driver.page_source)\n dates = page.find_all(\"td\", class_=\"view-col col-date\")\n date_check = [date.get_text()[-4:] != str(self.CURRENT_YEAR)\n for date in dates]\n links_on_page = page.find_all(\"td\", class_=\"view-col col-title\")\n self.all_rides.extend([a_link.a[\"href\"] for date, a_link in\n zip(date_check, links_on_page) if not date])\n if any(date_check):\n break # found a date not in CURRENT_YEAR\n try:\n self.driver.find_element_by_class_name(\"next_page\").click()\n except selenium.common.exceptions.NoSuchElementException:\n break", "def search_term(request, term):\n user = request.user\n search_rides = Ride.objects.filter(\n destination__contains=term).order_by('ride_date')\n if user.is_authenticated:\n rides_tup = [(ride, ride.is_participant(user), ride.is_owner(user)) \n for ride in search_rides if not ride.ride_in_past()]\n else:\n rides_tup = [(ride, False, False) for ride in search_rides]\n context = {\n 'latest_rides': rides_tup,\n 'user': request.user,\n }\n return render(request, 'cabrides/index.html', context)", "def current_rides(request):\n context_instance=RequestContext(request)\n user = context_instance['user']\n data = {\n 'subtitle': 'Current Rides',\n 'matching': False,\n 'rides': Ride.get_all_rides_for_user(user)}\n return render_to_response('rides.html', data,\n context_instance=context_instance)", "def ride_info(request, ride_id):\n context_instance = RequestContext(request)\n user = context_instance['user']\n ride = Ride.objects.get(pk=ride_id).filled_out()\n\n # If they have submitted a request and it is in bounds of the ride, let them\n # see this ride.\n # Next, check if they are part of this ride. If they are, let them see it.\n # Otherwise, don't let them see it\n user_sr = ride.get_sr_for_user(user)\n if not user_sr:\n if '_search_request' in request.session:\n # user is attempting to add this ride\n sr_post = request.session['_search_request']\n rr_form = RideRequestForm(sr_post)\n user_sr = rr_form.save(commit = False)\n user_sr.user = context_instance['user']\n ride.update_with_sr(user_sr)\n if not ride.in_bounds():\n messages.add_message(request, messages.ERROR,\n \"Error: This ride is out of your bounds.\" +\n \" You do not have access to this ride.\")\n return redirect('/rides/search/')\n else:\n messages.add_message(request, messages.ERROR,\n \"Error: You do not have access to this ride.\")\n return redirect('/')\n else:\n \tride.update_with_sr(user_sr)\n \t\n # encrypt the ride id and user_name\n enc_name = 'not implemented'\n enc_ride_id = 0\n\n data = {\n 'subtitle': 'Ride Details',\n 'ride': ride,\n 'enc_name': enc_name,\n 'enc_ride_id': enc_ride_id,\n 'user_names': ','.join(['\"%s %s\"' % (rider.first_name, rider.last_name) for rider in ride.riders]),\n 'start_latlongs': ['new google.maps.LatLng(%f, %f)' % (req.start_lat, req.start_long) for req in ride.requests],\n 'end_latlongs': [ 'new google.maps.LatLng(%f, %f)' % (req.end_lat, req.end_long) for req in ride.requests],\n 'user_in_ride': user in ride.riders}\n \n return render_to_response('detail.html', data,\n context_instance=context_instance)", "def get_all_rides():\n return jsonify({'RideIds': listdir(RIDE_LOCATIONS)})", "def find_park_and_rides(cls):\n pass", "def request_ride(self):\n result = \"Invalid id\"\n for ride_info in rides.all_rides:\n if ride_info['ride_id'] == self.ride_id:\n result ={\"success\": (\"you have requested to join the ride from\",\n ride_info['from_where'], \"to\", ride_info[\"to\"],\n \"on\", ride_info[\"date\"])}\n requestClass.requested_rides.append(result) \n\n return result", "def help_search_rides():\n get_search_for_ride_parser().print_help()", "def display_recipe_search_results():\n### FROM random_recipes_search.html\n\n q = request.args.get(\"search\")\n calories = request.args.get(\"calories\")\n dietary = request.args.get(\"dietary\")\n health = request.args.getlist(\"health\")\n\n payload = get_edamam_payload()\n\n if q:\n payload.update({'q': q})\n if calories:\n payload.update({'calories': calories})\n if dietary:\n payload.update({'diet': dietary})\n if health:\n payload.update({'health': health})\n recipes = request_edamam_api(payload)\n\n return render_template(\"random_recipes_search.html\", recipes=recipes)", "def searchRide(source, destination, passenger):\n passenger_active_participation = passenger.get_active_participation()\n if passenger_active_participation:\n resp = models.Response(models.Response.FORBIDDEN,\n \"Trip\", passenger_active_participation.trip)\n return resp\n\n if passenger.location.georss_point != source.georss_point:\n passenger.location = source\n try:\n passenger.location.full_clean()\n except django.core.exceptions.ValidationError, e:\n resp = models.Response(models.Response.BAD_REQUEST,\n \"Message\", e)\n return resp\n passenger.location.save()\n\n trips = matching.search_ride(destination,passenger)\n\n if not trips:\n return models.Response(models.Response.NOT_FOUND,\n \"Trip[]\", [])\n\n return models.Response(models.Response.ALL_OK,\n \"Trip[]\", trips)", "def get(self, ride_id):\n request = Ride.read(ride_id)\n return {'status':'success', 'message': 'Fetch successful', 'data': request}", "def index(request):\n latest_cab_rides = Ride.objects.order_by('ride_date')\n user = request.user\n if user.is_authenticated:\n latest_rides_tup = [(ride, ride.is_participant(user), ride.is_owner(user))\n for ride in latest_cab_rides if not ride.ride_in_past()]\n else:\n latest_rides_tup = [(ride, False, False) for ride in latest_cab_rides]\n context = {\n 'latest_rides': latest_rides_tup, \n 'user': request.user\n }\n return render(request, 'cabrides/index.html', context)", "def search():\n recipes = get_creator_details(\n list(mongo.db.recipes.find(\n {\"$text\": {\"$search\": request.form.get(\"search\")}}))\n )\n return render_template(\"recipes.html\", recipes=recipes)", "def get_all(): \n db.query_db(\n \"SELECT * FROM ride_offers;\"\n )\n ride_offers = db.cursor.fetchall()\n if not ride_offers:\n return{\"message\":\"no ride offers yet, sorry\"}, 404\n # else convert data to dict\n rides = []\n for item in ride_offers:\n ride_dict = {\n \"ride_id\":item[0],\n \"driver_id\":item[1],\n \"location\":item[2],\n \"departure_time\":item[3],\n \"destination\":item[4]\n }\n rides.append(ride_dict)\n return rides, 200", "def get(self, ride_id):\n self.id = ride_id\n return rides.fetch_one(self.id)", "def search():\n query = request.form.get(\"query\")\n wines = list(mongo.db.wines.find({\"$text\": {\"$search\": query}}))\n types = list(mongo.db.wine_type.find())\n return render_template(\"wines.html\", wines=wines,\n types=types)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Page to enter description of new ride, and submit it.
def new_ride(request): context_instance = RequestContext(request) # A POST request indicates that a DescriptionForm has been submitted. if request.method == 'POST': rr_form = RideRequestForm(request.session['_search_request']) if rr_form.is_valid(): sr = rr_form.save(commit = False) sr.user = context_instance['user'] sr.submission_time = datetime.now() else: return HttpResponse("Unexpected error: bad rr_form") desc_form = DescriptionForm(request.POST) if desc_form.is_valid(): ride = Ride() ride.description = desc_form.cleaned_data['description'] ride.save() sr.ride = ride sr.save() messages.add_message(request, messages.SUCCESS, THANK_YOU_MESSAGE) else: return HttpResponse("Error: Invalid description in form.") del request.session['_search_request'] return redirect('/') else: return render_to_response('add_description.html', context_instance)
[ "def request_ride(request):\n data = {'subtitle': 'Request or Create New Ride'}\n return render_to_response('new_ride.html', data,\n RequestContext(request))", "def new_ride(request):\n context = {'user': request.user}\n return render(request, 'cabrides/new_ride.html', context)", "def create_ride(request):\n from datetime import datetime\n try:\n origin = request.POST['origin']\n destination = request.POST['destination']\n if origin == '' or destination == '':\n return HttpResponse(\"fill everything in!\")\n else:\n date = request.POST['date']\n time = request.POST['time']\n datetime_string = ' '.join([date, time])\n max_riders = request.POST['max_riders']\n date_object = datetime.strptime(datetime_string, '%m/%d/%Y %I:%M %p')\n new_ride = Ride(origin=origin, destination=destination,\n ride_owner=request.user, max_riders=max_riders, ride_date=date_object)\n new_ride.save()\n new_ride.participants.add(request.user)\n return redirect('/cabrides/')\n except KeyError:\n return HttpResponse(\"Not all fields were filled out.\")", "def create_ride():", "def post(self):\n args = self.reqparse.parse_args()\n check_for_empty_fields(args)\n validate_date(args['date'])\n ride = Ride(\n args['date'],\n args['time'],\n args['pickup'],\n args['dropoff'],\n args['driver_id'],\n args['price']\n )\n return ride.add()", "def ride_info(request, ride_id):\n context_instance = RequestContext(request)\n user = context_instance['user']\n ride = Ride.objects.get(pk=ride_id).filled_out()\n\n # If they have submitted a request and it is in bounds of the ride, let them\n # see this ride.\n # Next, check if they are part of this ride. If they are, let them see it.\n # Otherwise, don't let them see it\n user_sr = ride.get_sr_for_user(user)\n if not user_sr:\n if '_search_request' in request.session:\n # user is attempting to add this ride\n sr_post = request.session['_search_request']\n rr_form = RideRequestForm(sr_post)\n user_sr = rr_form.save(commit = False)\n user_sr.user = context_instance['user']\n ride.update_with_sr(user_sr)\n if not ride.in_bounds():\n messages.add_message(request, messages.ERROR,\n \"Error: This ride is out of your bounds.\" +\n \" You do not have access to this ride.\")\n return redirect('/rides/search/')\n else:\n messages.add_message(request, messages.ERROR,\n \"Error: You do not have access to this ride.\")\n return redirect('/')\n else:\n \tride.update_with_sr(user_sr)\n \t\n # encrypt the ride id and user_name\n enc_name = 'not implemented'\n enc_ride_id = 0\n\n data = {\n 'subtitle': 'Ride Details',\n 'ride': ride,\n 'enc_name': enc_name,\n 'enc_ride_id': enc_ride_id,\n 'user_names': ','.join(['\"%s %s\"' % (rider.first_name, rider.last_name) for rider in ride.riders]),\n 'start_latlongs': ['new google.maps.LatLng(%f, %f)' % (req.start_lat, req.start_long) for req in ride.requests],\n 'end_latlongs': [ 'new google.maps.LatLng(%f, %f)' % (req.end_lat, req.end_long) for req in ride.requests],\n 'user_in_ride': user in ride.riders}\n \n return render_to_response('detail.html', data,\n context_instance=context_instance)", "def post(self, ride_id):\n self.id = ride_id\n return ride_requests.create_request(ride_id=self.id)", "def render_new_request_page():\n title = 'New Request'\n return render_template('new_request.html', page_title=title)", "def update_ride():", "def new_page(request):\n\n if request.method != \"POST\":\n return render(request, \"encyclopedia/new_page.html\", {\n \"form\": New_page_form()\n })\n\n form = New_page_form(request.POST)\n if form.is_valid():\n title = form.cleaned_data[\"title\"]\n page_contents = form.cleaned_data[\"page_contents\"]\n util.save_entry(title, page_contents)\n\n return HttpResponseRedirect(reverse(\"encyclopedia:entry\", args=[title]))\n else:\n return render(request, \"encyclopedia/new_page.html\", {\n \"form\": form\n })", "def put(self, ride_id):\n args = self.reqparse.parse_args()\n check_for_empty_fields(args)\n return Ride.edit(\n args['date'], \n args['time'], \n args['pickup'], \n args['dropoff'], \n args['driver_id'], \n args['price'], \n args['status'], \n ride_id\n )", "def save_request_ride(self):\n db.cursor.execute(\n \"\"\"\n INSERT INTO ride_requests(user_id, offer_id)\n VALUES(%s, %s)\n \"\"\",\n (self.user_id, self.offer_id)\n )\n db.commit()\n return", "def add_review(): \n return render_template('addReview.html')", "def start_ride():\n try:\n booking_id = request.form.get('booking_id')\n start_km = request.form.get('start_km')\n except (KeyError, TypeError):\n return {\"status\": bad_request_status, \"message\": req_param_missing}\n\n response = BookingBasics.start_ride(booking_id, start_km)\n\n\n return response", "def show_create_hiring_post_page():\n\n # form = CreateHiringPostForm()\n\n return render_template(\"create_hiring_post.html\")", "def save(self, **kwargs):\n\n rating = self.context['rating']\n\n rating.score = self.validated_data['qualification']\n\n rating.save()\n\n ride = self.context['ride']\n\n return ride", "def snippet_new(request, template_name='libpaste/snippet_new.html'):\n if request.method == \"POST\":\n snippet_form = SnippetForm(data=request.POST, request=request)\n if snippet_form.is_valid():\n new_snippet = snippet_form.save()\n url = new_snippet.get_absolute_url()\n return HttpResponseRedirect(url)\n else:\n snippet_form = SnippetForm(request=request)\n\n return render(request, template_name, {\n 'snippet_form': snippet_form,\n 'lexer_list': LEXER_LIST,\n 'is_new': True,\n 'page': 'snippet_new',\n })", "def add_RoutingStepDescription(row, traveler):\r\n tech_entry_box = row[0]\r\n row_label = row[1]\r\n routing_step_number = row[2]\r\n routing_step_description = row[3]\r\n working_paragraph = add_RoutingStepNumber(routing_step_number,traveler)\r\n paragraph_format = working_paragraph.paragraph_format\r\n paragraph_format.space_after = Pt(6)\r\n new_run = working_paragraph.add_run(routing_step_description.text()) #the routing step description is added as a run\r\n # to the paragraph that contains just the routing step number\r\n if new_run != None:\r\n font = new_run.font\r\n font.name = 'Arial'\r\n font.size = Pt(9)\r\n font.bold = True\r\n last_run = tech_entry_input(tech_entry_box,working_paragraph)\r\n if last_run != None:\r\n font = last_run.font\r\n font.name = 'Arial'\r\n font.size = Pt(9)\r\n font.bold = False", "def test_edit_step_description_saved(self, browser, login, logout):\n step_description_locator = RunTestPageLocators.TC_N_STEP_DESCRIPTION\n self.open_run_test_page_for_1st_test(browser)\n run_test_page = RunTestPage(browser)\n run_test_page.step_1_double_click()\n step_description = run_test_page.visible_element_get_text(step_description_locator)\n run_test_page.visible_element_click(step_description_locator)\n run_test_page.step_alt_click(step_description_locator)\n run_test_page.step_alt_click(step_description_locator)\n run_test_page.visible_element_send_text(step_description_locator, \" New Added Description\")\n run_test_page.visible_element_double_click(RunTestPageLocators.TC_N_STEP_DESCRIPTION) # to exit editing mode\n run_test_page.failed_btn_1_step_click()\n run_test_page.passed_btn_1_step_click()\n run_test_page.save_and_close_btn_click()\n run_test_page.wait_new_page_load()\n cases_page = CasesPage(browser)\n cases_page.wait_new_page_load()\n cases_page.click_first_case()\n cases_page.click_mb3_first_case()\n cases_page.click_run_test_option()\n new_description_text = run_test_page.visible_element_get_text(step_description_locator)\n assert new_description_text == step_description + ' New Added Description', \\\n \"Added Description should be seen in the end\"\n run_test_page.step_alt_click(step_description_locator)\n run_test_page.step_alt_click(step_description_locator)\n run_test_page.visible_element_clear_text(step_description_locator) # clear text\n run_test_page.visible_element_send_text(step_description_locator,\n step_description) # paste original text\n run_test_page.visible_element_double_click(step_description_locator) # exit editing\n run_test_page.failed_btn_1_step_click()\n run_test_page.passed_btn_1_step_click()\n run_test_page.save_and_close_btn_click()\n cases_page.wait_new_page_load()" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test the get_project by using KECHAIN_FORCE_ENV_USE=True
def test_get_project__force_env_use_no_vars(self): self.env.set("KECHAIN_FORCE_ENV_USE", "True") with self.env: self.assertTrue(env.bool(KechainEnv.KECHAIN_FORCE_ENV_USE)) with self.assertRaisesRegex(ClientError, "should be provided as environment variable"): # KECHAIN_SCOPE or KECHAIN_SCOPE_ID should be provided as environment variable get_project()
[ "def test_runtime_envs_get(self):\n pass", "def test_env_init(generic_task):\n assert generic_task.get_env() == 'KKK'", "def test_env(self, env_flag, env, fake_project_cli, fake_metadata, mocker):\n mock_environ = mocker.patch(\"os.environ\", {})\n result = CliRunner().invoke(\n fake_project_cli,\n [\"jupyter\", \"lab\", env_flag, env],\n obj=fake_metadata,\n )\n assert not result.exit_code, result.stdout\n assert mock_environ[\"KEDRO_ENV\"] == env", "def test_env(self, env_flag, env, fake_project_cli, fake_metadata, mocker):\n mock_environ = mocker.patch(\"os.environ\", {})\n result = CliRunner().invoke(\n fake_project_cli,\n [\"jupyter\", \"notebook\", env_flag, env],\n obj=fake_metadata,\n )\n assert not result.exit_code, result.stdout\n assert mock_environ[\"KEDRO_ENV\"] == env", "def test_prepare_environment(self):\n pass", "def test_on_prem_runtime_envs_plan_get(self):\n pass", "def test_environment(self):\n pass", "def test_env_change(generic_task):\n generic_task.set_env('DEFF')\n assert generic_task.get_env() == 'DEFF'", "def test__test_environment():\n environment = os.getenv('ENV_FOR_DYNACONF')\n\n assert environment == 'test'", "def test_zephyr_from_env(mockfs, monkeypatch, fake_project):\n zephyr_sdk_path = mockfs / \"zsdk\"\n zephyr_sdk_path.mkdir()\n\n environ = {\"ZEPHYR_SDK_INSTALL_DIR\": str(zephyr_sdk_path)}\n monkeypatch.setattr(os, \"environ\", environ)\n\n chain = fake_project.get_toolchain(module_paths)\n assert isinstance(chain, toolchains.ZephyrToolchain)\n\n config = chain.get_build_config()\n assert config.cmake_defs == {\n \"ZEPHYR_TOOLCHAIN_VARIANT\": \"zephyr\",\n \"ZEPHYR_SDK_INSTALL_DIR\": str(zephyr_sdk_path),\n }", "def setup_environment():", "def _env_get(target):\n if target == 'vagrant':\n # vagrant specific settings\n env.user = 'vagrant'\n raw_ssh_config = subprocess.Popen([\"vagrant\", \"ssh-config\"], stdout=subprocess.PIPE).communicate()[0]\n ssh_config = dict([l.strip().split() for l in raw_ssh_config.split(\"\\n\") if l])\n env.user = ssh_config[\"User\"]\n env.hosts = [\"127.0.0.1:%s\" % (ssh_config[\"Port\"])]\n env.host_string = env.hosts[0] # We need to explicitly specify this for sudo and run.\n env.key_filename = ssh_config[\"IdentityFile\"]\n return\n elif target == 'localhost':\n # all environment variables relating to a developer's localhost\n env.project_home = os.getenv(\"PROJECT_HOME\")\n env.project_path = '%(project_home)s/%(project_name)s' % env\n env.user = env.local_user\n return\n elif target not in list(env.project_sites.viewkeys()):\n # handle environment that isn't specified\n print (\"Oops. There's no such site. try `fab _env_get:dev` or `fab env_get:prod`\")\n return\n\n # handle environment that was specified\n env.user = 'web'\n env.hosts = [env.project_sites[target]['NAME']]\n env.host_string = env.hosts[0]\n env.path = '/var/www/%s/%s' % (target, env.project_name)\n env.path_releases = '/var/www/%s/%s/releases' % (target, env.project_name)\n env.path_release_current = '/var/www/%s/%s/releases/current' % (target, env.project_name)\n env.project_path = '%(path_release_current)s/%(project_name)s' % env # slash prepended", "def test_check_env(self):\n self.assertEqual(check_env(), {'TURBODIR':'/share/apps/turbomole/6.5',\n 'TURBOMOLE_SYSNAME': 'em64t-unknown-linux-gnu'})", "def test_toolchain_override(mockfs, fake_project):\n chain = fake_project.get_toolchain(module_paths, override=\"foo\")\n config = chain.get_build_config()\n assert isinstance(chain, toolchains.GenericToolchain)\n assert config.cmake_defs == {\"ZEPHYR_TOOLCHAIN_VARIANT\": \"foo\"}", "def test_zephyr(fake_project: project.Project, zephyr_exists, no_environ):\n chain = fake_project.get_toolchain(module_paths)\n assert isinstance(chain, toolchains.ZephyrToolchain)\n\n config = chain.get_build_config()\n assert config.cmake_defs == {\n \"ZEPHYR_TOOLCHAIN_VARIANT\": \"zephyr\",\n \"ZEPHYR_SDK_INSTALL_DIR\": str(pathlib.Path(\"/opt/zephyr-sdk\")),\n }", "def test_import_project():\n\n from {{ cookiecutter.project_slug }}.main import main\n\n assert main() is None", "def validate_environment(\n cpix_client: clients.cpix_client.CpixClient,\n) -> Union[None, str]:\n required_vars = [\"PROJECT\"]\n required_vars.extend(cpix_client.required_env_vars())\n for required_var in required_vars:\n if required_var not in os.environ:\n return http_response(\n f\"environment variable '{required_var}' must be set\", 400\n )\n return None", "def test_runtime_envs_update(self):\n pass", "def test_no_toolchains(fake_project: project.Project, mockfs, no_environ):\n with pytest.raises(\n OSError, match=r\"No supported toolchains could be found on your system\"\n ):\n fake_project.get_toolchain(module_paths)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
compute the Laplacian of phi
def lap(gr, phi): lapphi = gr.scratch_array() ib = gr.ilo ie = gr.ihi lapphi[ib:ie+1] = (phi[ib-1:ie] - 2.0*phi[ib:ie+1] + phi[ib+1:ie+2])/gr.dx**2 return lapphi
[ "def laplacian(self,W):\n # Degree matrix.\n d = W.sum(axis=0)\n # Laplacian matrix.\n d = 1 / np.sqrt(d)\n D = sp.diags(d.A.squeeze(), 0)\n I = sp.identity(d.size, dtype=W.dtype)\n L = I - D * W * D\n\n assert type(L) is sp.csr.csr_matrix\n return L", "def var_laplacian(self):\n if self.data is not None and self.trans:\n gray = cv2.cvtColor(self.data, cv2.COLOR_BGR2GRAY)\n return cv2.Laplacian(gray, cv2.CV_64F).var()\n else:\n raise Exception('Image not yet transformed')", "def compute_laplacians(dim):\n\n adjacency_matrix = compute_adjacency_matrix(dim=dim)\n laplacian_matrix = compute_normalized_laplacian(sparse_adjacency_matrix=adjacency_matrix)\n shifted_laplacian_matrix = shift_laplacian(laplacian_matrix, dim).to(DEVICE)\n \n return laplacian_matrix, shifted_laplacian_matrix", "def discrete_laplacian(M):\n L = -4*M\n L += np.roll(M, (0,-1), (0,1)) # right neighbor\n L += np.roll(M, (0,+1), (0,1)) # left neighbor\n L += np.roll(M, (-1,0), (0,1)) # top neighbor\n L += np.roll(M, (+1,0), (0,1)) # bottom neighbor\n \n return L", "def shift_laplacian(laplacian_matrix, dim):\n \n #laplacian_matrix = laplacian_matrix/2\n idendity_matrix = torch.eye(dim**2)\n shifted_laplacian_matrix = laplacian_matrix - idendity_matrix\n\n return shifted_laplacian_matrix", "def phi(x1, x2):\n return np.array([x1, x2, x1**2.0 + x2**2.0])", "def phi_c(self):\n return self._phi_c", "def phi_to_theta(phi):\n return - np.log(phi)", "def test_laplacian(self):\n for case in all_cases:\n sc = simplicial_complex(case)\n f = sc.get_cochain_basis(0)\n assert_equal((laplace_beltrami(f) - laplace_derham(f)).v.nnz, 0)", "def FD_2D_Laplacian_matrix (Nx_phys, Ny_phys, Δx, Δy, BCdir_left=True, BCdir_right=True, BCdir_top=True, BCdir_bot=True):\n\n\tDXX = FD_1D_Laplacian_matrix(Nx_phys, Δx, BCdir_left, BCdir_right)\n\tDYY = FD_1D_Laplacian_matrix(Ny_phys, Δy, BCdir_bot, BCdir_top)\n\t\n\t####### 2D Laplace operator\n\tLAP = sp.kron(DXX,sp.eye(Ny_phys,Ny_phys)) + sp.kron(sp.eye(Nx_phys,Nx_phys),DYY)\n\t\n\t####### Correction matrix\n\n\t### Upper Diagonal terms\n\tdataNYNXi = [np.zeros(Ny_phys*Nx_phys)]\n\toffset = np.array([1])\n\n\t### Fix coef: 2+(-1) = 1 ==> Dirichlet at a single point\n\t# The value is set at one point (here [0][1]) to ensure uniqueness\n\tdataNYNXi[0][1] = -1 / Δx**2\n\n\tLAP0 = sp.dia_matrix((dataNYNXi,offset), shape=(Ny_phys*Nx_phys,Ny_phys*Nx_phys))\n \n#\treturn LAP + LAP0\n\treturn LAP", "def gOfPhi(p):\r\n return 1 / math.sqrt(1 + 3 * p **2 / math.pi **2)", "def laplacian(features, n_neighbours, sigma):\n W = adjacency(features, n_neighbours, sigma)\n D,DPM = diagonals(W)\n L = D - W\n DLD = DPM @ L @ DPM\n return DLD", "def calcPhi( U, T, F, NCs, pops):\n\n phi = dot( NCs[T], pops[T] ) - dot( NCs[U], pops[U] )\n phi = phi / ( dot( NCs[F], pops[F] ) - dot( NCs[U], pops[U] ) )\n\n return phi", "def subphi(self):\n array_ndim, array_type, array_shape, array_handle = \\\n _bcs.f90wrap_laplace_iterator__array__subphi(self._handle)\n if array_handle in self._arrays:\n subphi = self._arrays[array_handle]\n else:\n subphi = f90wrap.runtime.get_array(f90wrap.runtime.sizeof_fortran_t,\n self._handle,\n _bcs.f90wrap_laplace_iterator__array__subphi)\n self._arrays[array_handle] = subphi\n return subphi", "def test_laplacian_energy():\n\n # Data\n X = np.load(\"sample_data/graphs/spectral_mtx1_10x10.npy\")\n\n # Run\n result = laplacian_energy(X)\n\n # Test against the groundtruth\n np.testing.assert_almost_equal(result, 57.178145779690524)", "def unnormalized_graph_Laplacian(adjacency_matrix):\n diag_matrix = diagonal_matrix(adjacency_matrix)\n if diag_matrix.shape == adjacency_matrix.shape:\n return(diag_matrix - adjacency_matrix)", "def LMLgrad_covar(self, columns):\n return _core.CGPkronecker_LMLgrad_covar(self, columns)", "def langevin(x):\n return np.coth(x)-1/x", "def _calculate_lll(self, delta: float = 0.75) -> Tuple[np.ndarray, np.ndarray]:\n # Transpose the lattice matrix first so that basis vectors are columns.\n # Makes life easier.\n a = self._matrix.copy().T\n\n b = np.zeros((3, 3)) # Vectors after the Gram-Schmidt process\n u = np.zeros((3, 3)) # Gram-Schmidt coeffieicnts\n m = np.zeros(3) # These are the norm squared of each vec.\n\n b[:, 0] = a[:, 0]\n m[0] = dot(b[:, 0], b[:, 0])\n for i in range(1, 3):\n u[i, 0:i] = dot(a[:, i].T, b[:, 0:i]) / m[0:i]\n b[:, i] = a[:, i] - dot(b[:, 0:i], u[i, 0:i].T)\n m[i] = dot(b[:, i], b[:, i])\n\n k = 2\n\n mapping = np.identity(3, dtype=np.double)\n while k <= 3:\n # Size reduction.\n for i in range(k - 1, 0, -1):\n q = round(u[k - 1, i - 1])\n if q != 0:\n # Reduce the k-th basis vector.\n a[:, k - 1] = a[:, k - 1] - q * a[:, i - 1]\n mapping[:, k - 1] = mapping[:, k - 1] - q * mapping[:, i - 1]\n uu = list(u[i - 1, 0: (i - 1)])\n uu.append(1)\n # Update the GS coefficients.\n u[k - 1, 0:i] = u[k - 1, 0:i] - q * np.array(uu)\n\n # Check the Lovasz condition.\n if dot(b[:, k - 1], b[:, k - 1]) >= (\n delta - abs(u[k - 1, k - 2]) ** 2\n ) * dot(b[:, (k - 2)], b[:, (k - 2)]):\n # Increment k if the Lovasz condition holds.\n k += 1\n else:\n # If the Lovasz condition fails,\n # swap the k-th and (k-1)-th basis vector\n v = a[:, k - 1].copy()\n a[:, k - 1] = a[:, k - 2].copy()\n a[:, k - 2] = v\n\n v_m = mapping[:, k - 1].copy()\n mapping[:, k - 1] = mapping[:, k - 2].copy()\n mapping[:, k - 2] = v_m\n\n # Update the Gram-Schmidt coefficients\n for s in range(k - 1, k + 1):\n u[s - 1, 0: (s - 1)] = (\n dot(a[:, s - 1].T, b[:, 0: (s - 1)]) / m[0: (s - 1)]\n )\n b[:, s - 1] = a[:, s - 1] - dot(\n b[:, 0: (s - 1)], u[s - 1, 0: (s - 1)].T\n )\n m[s - 1] = dot(b[:, s - 1], b[:, s - 1])\n\n if k > 2:\n k -= 1\n else:\n # We have to do p/q, so do lstsq(q.T, p.T).T instead.\n p = dot(a[:, k:3].T, b[:, (k - 2): k])\n q = np.diag(m[(k - 2): k])\n result = np.linalg.lstsq(q.T, p.T, rcond=None)[0].T\n u[k:3, (k - 2): k] = result\n\n return a.T, mapping.T", "def lapv(Ar, Aphi, Az, r=None, z=None, npts=3, geom='tor'):\n r, z = get_deriv_r_z(Ar, r, z)\n if geom == 'tor':\n rcomp = laps(Ar, r, z, npts=npts, geom=geom) - Ar/r**2\n phicomp = laps(Aphi, r, z, npts=npts) - Aphi/r**2\n elif geom == 'lin':\n rcomp = laps(Ar, r, z, npts=npts, geom=geom)\n phicomp = laps(Aphi, r, z, npts=npts)\n zcomp = laps(Az, r, z, npts=npts)\n return rcomp, phicomp, zcomp" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
the main evolution loop. Evolve phi_t = k phi_{xx} from t = 0 to tmax
def evolve(nx, k, t0, phi1, phi2, C, tmax): # create the grid gr = diffimplicit.Grid(nx, ng=1, xmax=1.0) # time info dt = C*0.5*gr.dx**2/k t = 0.0 # initialize the data gr.phi[:] = gr.phi_a(0.0, k, t0, phi1, phi2) while t < tmax: gr.fill_BCs() # make sure we end right at tmax if t + dt > tmax: dt = tmax - t # diffuse for dt phinew = diffuse_CN(gr, k, dt) gr.phi[:] = phinew[:] t += dt return gr
[ "def setup_phi_eff(self):\n momentum = self.p0\n time = 0.\n phi_eff = 0.\n for turn in range(self.n_turns+5):\n # evolve through one full revolution\n time += self.tof(momentum)\n self.phase_list[0].append(momentum)\n # phi_eff is the phase that a particle on the synchronous phase \n # passes through the reference surface\n phi_eff = time*self.omega + 2.*math.pi*self.phi_s\n self.phase_list[1].append(phi_eff)\n # increment the energy\n energy = (momentum**2+self.mass**2)**0.5\n delta_energy = self.v_eff*math.sin(2.*math.pi*self.phi_s)\n energy += delta_energy\n momentum = (energy**2-self.mass**2)**0.5", "def evolve(vi,theta,h,t_end,dt):\n\n# Initialize everything\n x,y,vx,vy = initialize(vi,theta,h)\n\n fig,axes,data = initialize_plot(h,x,y,vx,vy)\n\n# Start moving the ball from t=0 to t=t_end in steps of dt\n t = 0\n while t <= t_end:\n x,y,vx,vy,t = update_simple(x,y,vx,vy,t,dt)\n update_plot(fig,axes,data,t,h,x,y,vx,vy)\n\n return", "def integrate_eke_kernel(state):\n vs = state.variables\n settings = state.settings\n\n c_int = allocate(state.dimensions, (\"xt\", \"yt\", \"zt\"))\n\n flux_east = allocate(state.dimensions, (\"xt\", \"yt\", \"zt\"))\n flux_north = allocate(state.dimensions, (\"xt\", \"yt\", \"zt\"))\n flux_top = allocate(state.dimensions, (\"xt\", \"yt\", \"zt\"))\n\n \"\"\"\n forcing by dissipation by lateral friction and GM using TRM formalism or skew diffusion\n \"\"\"\n forc = vs.K_diss_gm + vs.K_diss_h - vs.P_diss_skew\n\n \"\"\"\n store transfer due to isopycnal and horizontal mixing from dyn. enthalpy\n by non-linear eq.of state either to EKE or to heat\n \"\"\"\n if not settings.enable_store_cabbeling_heat:\n forc = forc - vs.P_diss_hmix - vs.P_diss_iso\n\n conditional_outputs = {}\n\n \"\"\"\n dissipation by local interior loss of balance with constant coefficient\n \"\"\"\n c_int = settings.eke_c_eps * vs.sqrteke / vs.eke_len * vs.maskW\n\n \"\"\"\n vertical diffusion of EKE,forcing and dissipation\n \"\"\"\n _, water_mask, edge_mask = utilities.create_water_masks(vs.kbot[2:-2, 2:-2], settings.nz)\n\n delta, a_tri, b_tri, c_tri, d_tri = (\n allocate(state.dimensions, (\"xt\", \"yt\", \"zt\"))[2:-2, 2:-2, :] for _ in range(5)\n )\n delta = update(\n delta,\n at[:, :, :-1],\n settings.dt_tracer\n / vs.dzt[npx.newaxis, npx.newaxis, 1:]\n * 0.5\n * (vs.kappaM[2:-2, 2:-2, :-1] + vs.kappaM[2:-2, 2:-2, 1:])\n * settings.alpha_eke,\n )\n a_tri = update(a_tri, at[:, :, 1:-1], -delta[:, :, :-2] / vs.dzw[1:-1])\n a_tri = update(a_tri, at[:, :, -1], -delta[:, :, -2] / (0.5 * vs.dzw[-1]))\n b_tri = update(\n b_tri,\n at[:, :, 1:-1],\n 1 + (delta[:, :, 1:-1] + delta[:, :, :-2]) / vs.dzw[1:-1] + settings.dt_tracer * c_int[2:-2, 2:-2, 1:-1],\n )\n b_tri = update(\n b_tri, at[:, :, -1], 1 + delta[:, :, -2] / (0.5 * vs.dzw[-1]) + settings.dt_tracer * c_int[2:-2, 2:-2, -1]\n )\n b_tri_edge = 1 + delta / vs.dzw[npx.newaxis, npx.newaxis, :] + settings.dt_tracer * c_int[2:-2, 2:-2, :]\n c_tri = update(c_tri, at[:, :, :-1], -delta[:, :, :-1] / vs.dzw[npx.newaxis, npx.newaxis, :-1])\n d_tri = update(d_tri, at[:, :, :], vs.eke[2:-2, 2:-2, :, vs.tau] + settings.dt_tracer * forc[2:-2, 2:-2, :])\n\n sol = utilities.solve_implicit(a_tri, b_tri, c_tri, d_tri, water_mask, b_edge=b_tri_edge, edge_mask=edge_mask)\n vs.eke = update(vs.eke, at[2:-2, 2:-2, :, vs.taup1], npx.where(water_mask, sol, vs.eke[2:-2, 2:-2, :, vs.taup1]))\n\n \"\"\"\n store eke dissipation\n \"\"\"\n vs.eke_diss_iw = c_int * vs.eke[:, :, :, vs.taup1]\n vs.eke_diss_tke = update(vs.eke_diss_tke, at[...], 0.0)\n\n \"\"\"\n add tendency due to lateral diffusion\n \"\"\"\n flux_east = update(\n flux_east,\n at[:-1, :, :],\n 0.5\n * npx.maximum(500.0, vs.K_gm[:-1, :, :] + vs.K_gm[1:, :, :])\n * (vs.eke[1:, :, :, vs.tau] - vs.eke[:-1, :, :, vs.tau])\n / (vs.cost[npx.newaxis, :, npx.newaxis] * vs.dxu[:-1, npx.newaxis, npx.newaxis])\n * vs.maskU[:-1, :, :],\n )\n flux_east = update(flux_east, at[-1, :, :], 0.0)\n flux_north = update(\n flux_north,\n at[:, :-1, :],\n 0.5\n * npx.maximum(500.0, vs.K_gm[:, :-1, :] + vs.K_gm[:, 1:, :])\n * (vs.eke[:, 1:, :, vs.tau] - vs.eke[:, :-1, :, vs.tau])\n / vs.dyu[npx.newaxis, :-1, npx.newaxis]\n * vs.maskV[:, :-1, :]\n * vs.cosu[npx.newaxis, :-1, npx.newaxis],\n )\n flux_north = update(flux_north, at[:, -1, :], 0.0)\n vs.eke = update_add(\n vs.eke,\n at[2:-2, 2:-2, :, vs.taup1],\n settings.dt_tracer\n * vs.maskW[2:-2, 2:-2, :]\n * (\n (flux_east[2:-2, 2:-2, :] - flux_east[1:-3, 2:-2, :])\n / (vs.cost[npx.newaxis, 2:-2, npx.newaxis] * vs.dxt[2:-2, npx.newaxis, npx.newaxis])\n + (flux_north[2:-2, 2:-2, :] - flux_north[2:-2, 1:-3, :])\n / (vs.cost[npx.newaxis, 2:-2, npx.newaxis] * vs.dyt[npx.newaxis, 2:-2, npx.newaxis])\n ),\n )\n\n \"\"\"\n add tendency due to advection\n \"\"\"\n if settings.enable_eke_superbee_advection:\n flux_east, flux_north, flux_top = advection.adv_flux_superbee_wgrid(state, vs.eke[:, :, :, vs.tau])\n\n if settings.enable_eke_upwind_advection:\n flux_east, flux_north, flux_top = advection.adv_flux_upwind_wgrid(state, vs.eke[:, :, :, vs.tau])\n\n if settings.enable_eke_superbee_advection or settings.enable_eke_upwind_advection:\n vs.deke = update(\n vs.deke,\n at[2:-2, 2:-2, :, vs.tau],\n vs.maskW[2:-2, 2:-2, :]\n * (\n -(flux_east[2:-2, 2:-2, :] - flux_east[1:-3, 2:-2, :])\n / (vs.cost[npx.newaxis, 2:-2, npx.newaxis] * vs.dxt[2:-2, npx.newaxis, npx.newaxis])\n - (flux_north[2:-2, 2:-2, :] - flux_north[2:-2, 1:-3, :])\n / (vs.cost[npx.newaxis, 2:-2, npx.newaxis] * vs.dyt[npx.newaxis, 2:-2, npx.newaxis])\n ),\n )\n vs.deke = update_add(vs.deke, at[:, :, 0, vs.tau], -flux_top[:, :, 0] / vs.dzw[0])\n vs.deke = update_add(\n vs.deke,\n at[:, :, 1:-1, vs.tau],\n -(flux_top[:, :, 1:-1] - flux_top[:, :, :-2]) / vs.dzw[npx.newaxis, npx.newaxis, 1:-1],\n )\n vs.deke = update_add(\n vs.deke, at[:, :, -1, vs.tau], -(flux_top[:, :, -1] - flux_top[:, :, -2]) / (0.5 * vs.dzw[-1])\n )\n \"\"\"\n Adam Bashforth time stepping\n \"\"\"\n vs.eke = update_add(\n vs.eke,\n at[:, :, :, vs.taup1],\n settings.dt_tracer\n * (\n (1.5 + settings.AB_eps) * vs.deke[:, :, :, vs.tau]\n - (0.5 + settings.AB_eps) * vs.deke[:, :, :, vs.taum1]\n ),\n )\n\n conditional_outputs.update(deke=vs.deke)\n\n return KernelOutput(eke=vs.eke, eke_diss_iw=vs.eke_diss_iw, eke_diss_tke=vs.eke_diss_tke, **conditional_outputs)", "def evolve(self):\n\n tm_evolve = self.tc.timer(\"evolve\")\n tm_evolve.begin()\n\n myd = self.cc_data\n\n method = self.rp.get_param(\"compressible.temporal_method\")\n\n rk = integration.RKIntegrator(myd.t, self.dt, method=method)\n rk.set_start(myd)\n\n for s in range(rk.nstages()):\n ytmp = rk.get_stage_start(s)\n ytmp.fill_BC_all()\n k = self.substep(ytmp)\n rk.store_increment(s, k)\n\n rk.compute_final_update()\n\n if self.particles is not None:\n self.particles.update_particles(self.dt)\n\n # increment the time\n myd.t += self.dt\n self.n += 1\n\n tm_evolve.end()", "def evolve(self, t: float, pop_init: np.array) -> np.array:\n if pop_init is None:\n # if no pop_init is given in the input, give a default initialization\n pop_init = np.zeros(self.num_state)\n # this is the initialization for 1-e case\n pop_init[0] = 1\n\n return linalg.expm(self.K * t) @ pop_init", "def compute_deltaB_deltaE(x, t):\r\n Nx = len(x[:,0]) # number of particles = number of positions to calculate the fields at\r\n innx = np.indices( (Nx,Nx) ) # indices of raws and columns to vectorize the computation\r\n \r\n # dot product of k and x: k.x = k_x*x + k_z*z = k*x*sin(theta_k) + k*z*cos(theta_k)\r\n # ... compute (Np x 1) vectors of x and y, so we can multiply each by the k vector\r\n xvec = x[:,0][innx][0,:,0][:,np.newaxis]\r\n yvec = x[:,1][innx][0,:,0][:,np.newaxis]\r\n # ... and now compute the dot product\r\n k_dot_x = xvec*k_array*np.sin(theta_k) + yvec*k_array*np.cos(theta_k)\r\n\r\n # phase of deltaB_k\r\n phaseB_k = np.cos(omegak*t - k_dot_x + phi_k)\r\n # phase of deltaE_k\r\n phaseE_k = np.sin(omegak*t - k_dot_x + phi_k)\r\n \r\n # deltaB at position i, at time t\r\n deltaB = np.sum(amplB_k*phaseB_k, axis=1)\r\n # deltaE at position i, at time t\r\n deltaE = np.sum(amplE_k*phaseE_k, axis=1)\r\n\r\n return deltaB, deltaE", "def evolve(self, dt, t_final, H, psi, mu=0, method='rk4', imaginary_time=False,\n output_interval=100, output_directory=None, post_step_callback=None, flush_output=True,\n estimate_error=True):\n if not self.simulator.MPI_rank: # Only one process prints to stdout:\n print('\\n==========')\n if imaginary_time:\n print(\"Beginning {}{} of imaginary time evolution\".format(format_float(t_final), self.time_units))\n else:\n print(\"Beginning {}{} of time evolution\".format(format_float(t_final), self.time_units))\n print('Using method: {} with dt = {}{}'.format(method, format_float(dt), self.time_units))\n print('==========')\n\n # Pick a differential equation based on the requirements of the method\n # being used, and whether we are evolving in imaginary time or not:\n if method == 'rk4':\n if imaginary_time:\n\n def dpsi_dt(t, psi):\n \"\"\"The differential equation for psi in imaginary time\"\"\"\n K, H_local_lin, H_local_nonlin = H(t, psi)\n K_psi = self.simulator.par_operator(K, psi, use_ffts=self.use_ffts)\n return -1 / self.hbar * (K_psi + (H_local_lin + H_local_nonlin - mu) * psi)\n\n else:\n\n def dpsi_dt(t, psi):\n \"\"\"The differential equation for psi\"\"\"\n K, H_local_lin, H_local_nonlin = H(t, psi)\n K_psi = self.simulator.par_operator(K, psi, use_ffts=self.use_ffts)\n d_psi_dt = -1j / self.hbar * (K_psi + (H_local_lin + H_local_nonlin - mu) * psi)\n return d_psi_dt\n\n elif method in ['rk4ip', 'fss2', 'fss4']:\n if imaginary_time:\n K, _, _ = H(0, psi)\n nonlocal_operator = -1/self.hbar * K\n\n def local_operator(t, psi):\n K, H_local_lin, H_local_nonlin = H(t, psi)\n local_operator = -1/self.hbar * (H_local_lin + H_local_nonlin - mu)\n return local_operator\n\n else:\n K, _, _ = H(0, psi)\n nonlocal_operator = -1j/self.hbar * K\n\n def local_operator(t, psi):\n K, H_local_lin, H_local_nonlin = H(t, psi)\n local_operator = -1j/self.hbar * (H_local_lin + H_local_nonlin - mu)\n return local_operator\n\n elif method == 'rk4ilip':\n if imaginary_time:\n omega_imag_provided=True\n\n def dpsi_dt(t, psi):\n \"\"\"The differential equation for psi in imaginary time, as\n well as the angular frequencies corresponding to the spatial\n part of the Hamiltonian for use with the RK4ILIP method\"\"\"\n K, H_local_lin, H_local_nonlin = H(t, psi)\n K_psi = self.simulator.par_operator(K, psi, use_ffts=self.use_ffts)\n omega_imag = -(H_local_lin + H_local_nonlin - mu)/self.hbar\n d_psi_dt = -1 / self.hbar * K_psi + omega_imag * psi\n return d_psi_dt, omega_imag\n else:\n omega_imag_provided=False\n\n def dpsi_dt(t, psi):\n \"\"\"The differential equation for psi, as well as the angular\n frequencies corresponding to the spatial part of the\n Hamiltonian for use with the RK4ILIP method\"\"\"\n K, H_local_lin, H_local_nonlin = H(t, psi)\n K_psi = self.simulator.par_operator(K, psi, use_ffts=self.use_ffts)\n omega = (H_local_lin + H_local_nonlin - mu)/self.hbar\n d_psi_dt = -1j / self.hbar * K_psi -1j*omega * psi\n return d_psi_dt, omega\n\n else:\n msg = \"method must be one of 'rk4', 'rk4ilip', 'rk4ip', 'fss2' or 'fss4'\"\n raise ValueError(msg)\n\n def output_callback(i, t, psi, infodict):\n energy_err = self.compute_energy(t, psi, H) / E_initial - 1\n number_err = self.compute_number(psi) / n_initial - 1\n time_per_step = infodict['time per step']\n step_err = infodict['step error']\n\n if imaginary_time:\n convergence = self.compute_mu_convergence(t, psi, H, mu)\n output_log_dtype = [('step', int), ('time', float),\n ('dN/N', float), ('convergence', float),\n ('step err', float), ('time per step', float)]\n\n output_log_data = np.array((i, t, number_err, convergence, step_err, time_per_step),\n dtype=output_log_dtype)\n else:\n output_log_dtype = [('step', int), ('time', float),\n ('dN/N', float), ('dE/E', float),\n ('step err', float), ('time per step', float)]\n\n output_log_data = np.array((i, t, number_err, energy_err, step_err, time_per_step),\n dtype=output_log_dtype)\n if output_directory is not None:\n hdf_output.save(psi, output_log_data)\n\n message = ('step: %d' % i +\n ' | t = {}'.format(format_float(t, units=self.time_units)) +\n ' | dN/N: %+.02E' % number_err +\n ((' | convergence: %E' % convergence) if imaginary_time else (' | dE/E: %+.02E' % energy_err)) +\n ' | step err: %.03E' % step_err +\n ' | time per step: {}'.format(format_float(time_per_step, units='s')))\n if not self.simulator.MPI_rank: # Only rank 0 should print\n print(message)\n\n if output_directory is not None:\n hdf_output = HDFOutput(self.simulator, output_directory, flush_output=flush_output)\n\n E_initial = self.compute_energy(0, psi, H)\n n_initial = self.compute_number(psi)\n\n # Start the integration:\n if method == 'rk4':\n self.simulator.rk4(dt, t_final, dpsi_dt, psi, output_interval=output_interval,output_callback=output_callback,\n post_step_callback=post_step_callback, estimate_error=estimate_error)\n elif method == 'rk4ip':\n self.simulator.rk4ip(dt, t_final, nonlocal_operator, local_operator, psi,\n output_interval=output_interval, output_callback=output_callback,\n post_step_callback=post_step_callback, estimate_error=estimate_error)\n elif method == 'rk4ilip':\n self.simulator.rk4ilip(dt, t_final, dpsi_dt, psi, omega_imag_provided, output_interval=output_interval,\n output_callback=output_callback, post_step_callback=post_step_callback,\n estimate_error=estimate_error)\n elif method == 'fss2':\n self.simulator.split_step(dt, t_final, nonlocal_operator, local_operator, psi, method_order=2,\n output_interval=output_interval, output_callback=output_callback,\n post_step_callback=post_step_callback,\n estimate_error=estimate_error)\n elif method == 'fss4':\n self.simulator.split_step(dt, t_final, nonlocal_operator, local_operator, psi, method_order=4,\n output_interval=output_interval, output_callback=output_callback,\n post_step_callback=post_step_callback,\n estimate_error=estimate_error)\n\n return psi", "def process_particles(n: int, l: int, t: int, r: float, v: float, nu: float, kappa: float) -> \\\n Generator[Tuple[Tensor, Tensor], None, None]:\n von_mises = VonMises(tensor(0, torch.float), tensor(kappa, torch.float))\n\n dt = 0.01 / nu\n max_iter = int(t / dt) * 5\n scaled_velocity = l * v\n rr = l / int(l / r)\n map_size = int(l / rr)\n pos = torch.mul(torch.rand(n, 3, device=gpu_cuda), l)\n vel = torch.cat((torch.mul(torch.rand(n, 1, device=gpu_cuda), 2 * math.pi),\n torch.mul(torch.rand(n, 1, device=gpu_cuda), math.pi)), 1)\n\n print(f\"\"\"Calculated Parameters:-\n Time Discretisation Step: {dt}\n Max Iteration: {max_iter}\n Scaled Velocity of Particles: {scaled_velocity}\n Adjusted Interaction Radius: {rr}\n Particle Map Size: {map_size}\"\"\")\n\n index = index_map(pos, rr)\n particle_map = fill_map(map_size, index)\n\n for t in range(max_iter + 1):\n jump = torch.rand(n, 1, device=gpu_cuda)\n who = torch.where(torch.gt(jump, torch.exp(tensor(-nu * dt, torch.float))),\n tensor(1, torch.int64),\n tensor(0, torch.int64))\n condition = torch.where(torch.eq(who[:, 0], 1))\n\n target = deepcopy(vel)\n target[condition] = average_orientation(pos, target, index[condition], particle_map, r)\n vel[condition] = target[condition] + von_mises.sample((who.sum(), 2))\n vel[:, 0][condition] = torch.remainder(vel[:, 0][condition], 2 * math.pi)\n vel[:, 1][condition] = torch.remainder(vel[:, 1][condition], math.pi)\n\n x = torch.sin(vel[:, 1]) * torch.cos(vel[:, 0])\n y = torch.sin(vel[:, 1]) * torch.sin(vel[:, 0])\n z = torch.cos(vel[:, 1])\n pos = torch.remainder(pos + torch.mul(torch.cat((x.reshape(x.size()[0], 1),\n y.reshape(y.size()[0], 1),\n z.reshape(z.size()[0], 1)), 1), dt * scaled_velocity), l)\n\n if t % 10 == 0:\n print(f\"Iteration number: {t} (out of {max_iter} iterations) [{(100 * t) // max_iter}% complete]\")\n yield pos, vel\n\n index = index_map(pos, rr)\n particle_map = fill_map(map_size, index)", "def EM(self, num_gq_mu, num_gq_phi, num_pre_mu, num_pre_phi, num_iter):\n N = len(self.points_hawkes)\n P, Pij_flat, tau_phi_md, num_Pij_row = self.ini_P()\n tau_phi = sum(tau_phi_md,[])\n N_phi = len(tau_phi)\n M_mu = len(self.ind_p_mu)\n M_phi = len(self.ind_p_phi)\n\n K_MM_mu = self.rbf_kernel(self.theta0_mu, self.theta1_mu, self.noise_var_mu, self.ind_p_mu, self.ind_p_mu)\n K_MM_mu_inv = np.linalg.inv(K_MM_mu)\n K_MM_phi = self.rbf_kernel(self.theta0_phi, self.theta1_phi, self.noise_var_phi, self.ind_p_phi, self.ind_p_phi)\n K_MM_phi_inv = np.linalg.inv(K_MM_phi)\n\n K_NM_mu = self.rbf_kernel(self.theta0_mu, self.theta1_mu, 0, np.array(self.points_hawkes), self.ind_p_mu)\n K_NM_phi = self.rbf_kernel(self.theta0_phi, self.theta1_phi, 0, np.array(tau_phi), self.ind_p_phi)\n\n # initial gm_mu and lamda_mu, gm_phi and lamda_phi\n gm_mu = np.random.uniform(-1, 1, size = M_mu)\n gm_phi = np.random.uniform(-1, 1, size = M_phi)\n lamda_mu = sum(np.diag(P))*2/self.T\n lamda_phi = sum(Pij_flat)*2/N/self.T_phi\n\n # gaussian quadreture points and weights\n p_gq_mu, w_gq_mu = self.gq_points_weights(0,self.T,num_gq_mu)\n p_gq_phi, w_gq_phi = self.gq_points_weights(0,self.T_phi,num_gq_phi)\n\n K_gqM_mu = self.rbf_kernel(self.theta0_mu, self.theta1_mu, 0, p_gq_mu, self.ind_p_mu)\n K_gqM_phi = self.rbf_kernel(self.theta0_phi, self.theta1_phi, 0, p_gq_phi, self.ind_p_phi)\n\n mu_list=[]\n phi_list=[]\n lamda_mu_list=[]\n lamda_phi_list=[]\n logl_train_list=[]\n logl_test_list=[]\n\n for iteration in range(num_iter):\n # update distribution of w_ii and w_ij\n a_ii = self.a_predict(self.ind_p_mu, gm_mu, self.theta0_mu, self.theta1_mu, K_MM_mu_inv, np.array(self.points_hawkes))\n E_w_ii = 1/2/a_ii*np.tanh(a_ii/2)\n a_ij = self.a_predict(self.ind_p_phi, gm_phi, self.theta0_phi, self.theta1_phi, K_MM_phi_inv, np.array(tau_phi))\n E_w_ij = 1/2/a_ij*np.tanh(a_ij/2)\n \n # update lamda_mu and lamda_phi\n a_gq_mu = self.a_predict(self.ind_p_mu, gm_mu, self.theta0_mu, self.theta1_mu, K_MM_mu_inv, p_gq_mu)\n int_intensity = np.sum(w_gq_mu*lamda_mu*expit(-a_gq_mu))\n lamda_mu = (np.sum(np.diag(P))+int_intensity)/self.T\n \n a_gq_phi = self.a_predict(self.ind_p_phi, gm_phi, self.theta0_phi, self.theta1_phi, K_MM_phi_inv, p_gq_phi)\n int_intensity = np.sum(w_gq_phi*lamda_phi*expit(-a_gq_phi))\n lamda_phi = (np.sum(Pij_flat) + N*int_intensity)/N/self.T_phi\n \n # update gm_mu and gm_phi\n int_A_mu=np.zeros((M_mu,M_mu))\n for i in range(N):\n int_A_mu+=P[i][i]*E_w_ii[i]*np.outer(K_NM_mu[i],K_NM_mu[i])\n for i in range(num_gq_mu):\n int_A_mu+=w_gq_mu[i]*(lamda_mu/2/a_gq_mu[i]*np.tanh(a_gq_mu[i]/2)*expit(-a_gq_mu[i])*np.outer(K_gqM_mu[i],K_gqM_mu[i]))\n int_B_mu=np.zeros(M_mu)\n for i in range(N):\n int_B_mu+=0.5*P[i][i]*K_NM_mu[i]\n for i in range(num_gq_mu):\n int_B_mu+=-w_gq_mu[i]/2*(lamda_mu*expit(-a_gq_mu[i])*K_gqM_mu[i])\n gm_mu=np.dot(np.dot(np.linalg.inv(np.dot(np.dot(K_MM_mu_inv,int_A_mu),K_MM_mu_inv)+K_MM_mu_inv),K_MM_mu_inv),int_B_mu)\n \n int_A_phi=np.zeros((M_phi,M_phi))\n for i in range(N_phi):\n int_A_phi+=Pij_flat[i]*E_w_ij[i]*np.outer(K_NM_phi[i],K_NM_phi[i])\n for i in range(num_gq_phi):\n int_A_phi+=w_gq_phi[i]*N*lamda_phi/2/a_gq_phi[i]*np.tanh(a_gq_phi[i]/2)*expit(-a_gq_phi[i])*np.outer(K_gqM_phi[i],K_gqM_phi[i])\n int_B_phi=np.zeros(M_phi)\n for i in range(N_phi):\n int_B_phi+=0.5*Pij_flat[i]*K_NM_phi[i]\n for i in range(num_gq_phi):\n int_B_phi+=-w_gq_phi[i]/2*N*lamda_phi*expit(-a_gq_phi[i])*K_gqM_phi[i]\n gm_phi=np.dot(np.dot(np.linalg.inv(np.dot(np.dot(K_MM_phi_inv,int_A_phi),K_MM_phi_inv)+K_MM_phi_inv),K_MM_phi_inv),int_B_phi)\n \n # update \\mu, \\phi and P\n Pij_flat=[]\n for i in range(N): # updata of P\n mu_ti=lamda_mu*expit(a_ii[i])\n phi_ti=lamda_phi*expit(a_ij[sum(num_Pij_row[:i]):sum(num_Pij_row[:i+1])])\n intensity_total=mu_ti+np.sum(phi_ti)\n P[i][i]=mu_ti/intensity_total\n P_i_j=phi_ti/intensity_total\n P[i][i-len(phi_ti):i]=P_i_j\n Pij_flat+=list(P_i_j)\n\n # compute g_{\\mu}(t) and g_{\\phi}(\\tau) on finer grid and the corresponding train/test loglikelihood\n g_mu_em = self.a_predict(self.ind_p_mu, gm_mu, self.theta0_mu, self.theta1_mu, K_MM_mu_inv, np.linspace(0, self.T, num_pre_mu))\n g_phi_em = self.a_predict(self.ind_p_phi, gm_phi, self.theta0_phi, self.theta1_phi, K_MM_phi_inv, np.linspace(0, self.T_phi, num_pre_phi))\n mu_em = lamda_mu*expit(g_mu_em)\n phi_em = lamda_phi*expit(g_phi_em)\n logl_train = self.loglikelihood_discrete_phi_mu(self.points_hawkes, mu_em, phi_em, self.T_phi, self.T)\n logl_test = self.loglikelihood_discrete_phi_mu(self.points_hawkes_test, mu_em, phi_em, self.T_phi, self.T_test)\n\n # record\n mu_list.append(mu_em)\n phi_list.append(phi_em)\n lamda_mu_list.append(lamda_mu)\n lamda_phi_list.append(lamda_phi)\n logl_train_list.append(logl_train)\n logl_test_list.append(logl_test)\n return mu_list,phi_list,lamda_mu_list,lamda_phi_list,logl_train_list,logl_test_list", "def evolve(self, stage):", "def relax_continuum_orbital(atomlist, phi0, potential_ee, E,\n max_iter=100, thresh=1.0e-6):\n # DOES NOT WORK\n w = 1.0\n # right hand side of A.x = b\n # b = (H-E)^2 phi0\n residual1 = residual_ee_func(atomlist, phi0, potential_ee, E)\n residual2 = residual_ee_func(atomlist, residual1, potential_ee, E)\n b = residual2\n\n def null(x,y,z):\n return 0*x\n \n x = null\n for i in range(0, max_iter):\n # compute A.x^(k) = (H-E)^2 phi_k\n print \"residuals...\"\n residual1 = residual_ee_func(atomlist, x, potential_ee, E)\n residual2 = residual_ee_func(atomlist, residual1, potential_ee, E)\n Ax = residual2\n # b - A.x^(k)\n print \"error...\"\n bmAx = add_two_functions(atomlist, b, Ax, 1.0, -1.0)\n error = np.sqrt(overlap(atomlist, bmAx, bmAx))\n print \"iteration i= %d error |b-Ax|= %e\" % (i, error)\n if error < thresh:\n print \"CONVERGED\"\n break\n \n # x^(k+1) = x^(k) + w * (b - A.x^(k))\n x_next = add_two_functions(atomlist, x, bmAx, 1.0, w)\n\n x = x_next\n\n phi = add_two_functions(atomlist, phi0, x, 1.0, 1.0)\n residual = residual_ee_func(atomlist, phi, potential_ee, E)\n\n import matplotlib.pyplot as plt\n plt.clf()\n plt.title(\"Iteration i=%d\" % (i+1))\n plt.xlabel(\"z / bohr\")\n plt.ylim((-0.6, +0.6))\n\n r = np.linspace(-10.0, 10.0, 1000)\n plt.plot(r, phi(0*r,0*r,r), label=r\"$\\phi$\")\n plt.plot(r, residual(0*r,0*r,r), ls=\"-.\", label=\"residual $(H-E)\\phi$\")\n\n plt.legend()\n plt.savefig(\"/tmp/relaxation_%3.3d.png\" % (i+1))\n plt.show()\n \n else:\n msg = \"Orbital relaxation did not converge in '%s' iterations!\" % max_iter\n print \"WARNING: %s\" % msg\n #raise RuntimeError(msg) \n return phi", "def euler_method(t, f_y_t, y0, vin):\n \n y = np.zeros((len(y0), len(t)+1))\n dt = t[1]-t[0]\n print(y.shape)\n y[:,0] = y0\n \n\n \n for index, tn in enumerate(t):\n \n y[:,index+1] = dt * (f_y_t(tn, y[:,index], dt)) + y[:,index]\n \n return y[:,:len(t)]", "def phi(self, t):\n phi = np.zeros([self.d + 1])\n phi[0] = 1/2*(1 + self.y(t, 0))\n for i in range(1, self.d + 1):\n phi[i] = 1/2*self.y(t, i)\n return phi", "def improve_continuum_orbital(atomlist, phi0, potential_ee, E,\n max_iter=100, thresh=1.0e-6):\n # attraction potential between nuclei and electrons\n nuclear_potential = nuclear_potential_func(atomlist)\n # effective potential (electron-electron interaction + nuclei-electrons)\n def potential(x,y,z):\n return potential_ee(x,y,z) + nuclear_potential(x,y,z)\n \n print \"orbital corrections...\"\n\n phi = phi0\n for i in range(0, max_iter):\n residual = residual_ee_func(atomlist, phi, potential_ee, E)\n def source(x,y,z):\n return -residual(x,y,z)\n # orbital correction\n delta_phi = inhomogeneous_schroedinger(atomlist, potential, source, E)\n\n a,b = variational_mixture_continuum(atomlist, phi, delta_phi, potential_ee, E)\n\n # The error is estimated as the norm^2 of the orbital correction:\n # error = <delta_phi|delta_phi>\n # For large radii, we cannot expect the solution to be correct since\n # the density of points is far too low. Therefore we exclude all points\n # outside the radius `rlarge` from the integration.\n rlarge = 10.0\n def error_density(x,y,z):\n err = abs(delta_phi(x,y,z))**2\n r = np.sqrt(x**2+y**2+z**2)\n err[rlarge < r] = 0.0\n return err\n error = integral(atomlist, error_density)\n print \" iteration i= %d |dphi|^2= %e b^2= %e (threshold= %e )\" % (i+1, error, b**2, thresh)\n # The solution is converged, when the weight of the\n # correction term b**2 is small enough.\n if b**2 < thresh:\n print \"CONVERGED\"\n break\n \n # next approximation for phi\n phi_next = add_two_functions(atomlist, phi, delta_phi, a, b)\n\n ### DEBUG\n import matplotlib.pyplot as plt\n plt.clf()\n # plot cuts along z-axis\n r = np.linspace(-40.0, 40.0, 10000)\n x = 0.0*r\n y = 0.0*r\n z = r\n\n plt.title(\"Iteration i=%d\" % (i+1))\n plt.xlabel(\"z / bohr\")\n plt.ylim((-0.6, +0.6))\n \n plt.plot(r, phi(x,y,z), label=r\"$\\phi$\")\n plt.plot(r, delta_phi(x,y,z), ls=\"--\", label=r\"$\\Delta \\phi$\")\n plt.plot(r, phi_next(x,y,z), label=r\"$a \\phi + b \\Delta \\phi$\")\n plt.plot(r, residual(x,y,z), ls=\"-.\", label=\"residual $(H-E)\\phi$\")\n plt.legend()\n plt.savefig(\"/tmp/iteration_%3.3d.png\" % (i+1))\n# plt.show()\n\n ###\n \n # prepare for next iteration\n phi = phi_next\n else:\n msg = \"Orbital corrections did not converge in '%s' iterations!\" % max_iter\n print \"WARNING: %s\" % msg\n #raise RuntimeError(msg) \n return phi", "def rk4_mass_spring_system(amp,omega,k_spr_m,n_balls,t_f,delta_t):\n\n t_steps = int(t_f/delta_t)\n\n t = np.arange(0,t_f,delta_t)\n x = np.empty([n_balls, t_steps])\n v = np.empty([n_balls, t_steps])\n\n #k factors of Runge Kutta 4\n kx = np.empty([4,n_balls])\n kv = np.empty([4,n_balls])\n\n #Initial Conditions\n x[:,0] = 0.0\n v[:,0] = 0.0\n\n #Motion of the 0 mass\n x[0,:] = amp*np.sin(omega*t)*(1-0.5*(np.sign(t-5)+1.0))\n # v[0,:] = omega*amp*np.sin(omega*t)\n\n #Only the proportion between k_spr and m appears, not k_spr or m_b alone\n # k_spr_m = k_spr/m_b\n\n for jt in range(t_steps-1):\n\n #k1 factors\n for n in range(1,n_balls):\n if n <= (n_balls-2):\n kx[0,n] = delta_t*v[n,jt]\n kv[0,n] = delta_t*(k_spr_m)*f_n_in(x[n,jt], x[n+1,jt], x[n-1,jt])\n elif n == (n_balls-1):\n kx[0,n] = delta_t*v[n,jt]\n kv[0,n] = delta_t*(k_spr_m)*f_n_out(x[n,jt], x[n-1,jt])\n\n #k2 factors\n for n in range(1,n_balls):\n if n <= (n_balls-2):\n kx[1,n] = delta_t*(v[n,jt]+kv[0,n])\n kv[1,n] = delta_t* (k_spr_m)*f_n_in(x[n,jt]+0.5*kx[0,n], x[n+1,jt]+0.5*kx[0,n+1], x[n-1,jt]+0.5*kx[0,n-1])\n elif n == (n_balls-1):\n kx[1,n] = delta_t*(v[n,jt]+kv[0,n])\n kv[1,n] = delta_t*(k_spr_m)*f_n_out(x[n,jt]+0.5*kx[0,n], x[n-1,jt]+0.5*kx[0,n-1])\n\n #k3 factors\n for n in range(1,n_balls):\n if n <= (n_balls-2):\n kx[2,n] = delta_t*(v[n,jt]+kv[1,n])\n kv[2,n] = delta_t* (k_spr_m)*f_n_in(x[n,jt]+0.5*kx[1,n], x[n+1,jt]+0.5*kx[1,n+1], x[n-1,jt]+0.5*kx[1,n-1])\n elif n == (n_balls-1):\n kx[2,n] = delta_t*(v[n,jt]+kv[1,n])\n kv[2,n] = delta_t* (k_spr_m)*f_n_out(x[n,jt]+0.5*kx[1,n],x[n-1,jt]+0.5*kx[1,n-1])\n\n #k4 factors\n for n in range(1,n_balls):\n if n <= (n_balls-2):\n kx[3,n] = delta_t*(v[n,jt]+kv[2,n])\n kv[3,n] = delta_t* (k_spr_m)*f_n_in(x[n,jt]+kx[2,n],x[n+1,jt]+0.5*kx[2,n+1],x[n-1,jt]+0.5*kx[2,n-1])\n elif n == (n_balls-1):\n kx[3,n] = delta_t* (v[n,jt]+kv[2,n])\n kv[3,n] = delta_t* (k_spr_m)*f_n_out(x[n,jt]+kx[2,n],x[n-1,jt]+kx[2,n-1])\n\n #next position/velocity\n\n for n in range(1,n_balls):\n x[n,jt+1] = x[n,jt] + (kx[0,n]+2*kx[1,n]+2*kx[2,n]+kx[3,n])/6.0\n v[n,jt+1] = v[n,jt] + (kv[0,n]+2*kv[1,n]+2*kv[2,n]+kv[3,n])/6.0\n\n del(kx,kv,v)\n return t_steps,t,x", "def advance(self, phi_k):\n phi = phi_k + self.dt * 1.2345\n return phi", "def bounds(step_test, delta_phi_star):\n\n # define integration for one step\n def step_integrate(phi0, u_val, step):\n \"\"\" function that integrates one step forward. returns final phase,\n total shift value \"\"\"\n def dphidt(phi, t):\n return ((2*np.pi)/pmodel.T\n - u_val*prc_spl(start_time+(phi)*pmodel.T/(2*np.pi)))\n\n int_times = np.linspace(0,step,101) # in hours\n phis = integrate.odeint(dphidt, [phi0], int_times, hmax=0.01)\n return int_times, phis, phis[-1][0]-phi0-2*np.pi/pmodel.T*step\n\n # find the max advance or delay in each cycle\n def dphitot_dt(phis, t):\n [phi_osc_pos, phi_osc_neg, phi_shift_pos, phi_shift_neg] = phis\n dphi_osc_pos_dt = (2*np.pi)/pmodel.T +\\\n umax*prc_pos_spl(phi_osc_pos*pmodel.T/(2*np.pi))\n dphi_osc_neg_dt = (2*np.pi)/pmodel.T +\\\n umax*prc_neg_spl(phi_osc_neg*pmodel.T/(2*np.pi))\n dphi_shft_pos_dt = umax*prc_pos_spl(phi_osc_pos*pmodel.T/(2*np.pi))\n dphi_shft_neg_dt = umax*prc_neg_spl(phi_osc_neg*pmodel.T/(2*np.pi))\n return dphi_osc_pos_dt, dphi_osc_neg_dt, dphi_shft_pos_dt, dphi_shft_neg_dt\n\n int_times = np.linspace(0,200, 10001)\n delta_phis_total = integrate.odeint(dphitot_dt, [0,0,0,0], int_times,\n hmax=0.001)\n phis_adv = delta_phis_total[:,0]\n phis_del = delta_phis_total[:,1]\n advs = delta_phis_total[:,2]\n dels = delta_phis_total[:,3]\n delta_phi_star_calc = delta_phis_total[np.min(\n np.where(delta_phis_total[:,2]-delta_phis_total[:,3]>2*np.pi)\n ), 2]\n\n # max 1 cycle advances are where the oscillator reaches 0 again\n max_1cyc_adv = advs[np.min(\n np.where(phis_adv>2*np.pi)[0]\n )]\n max_1cyc_del = dels[np.min(\n np.where(phis_del>2*np.pi)[0]\n )]\n\n\n\n def loss_zero_cross(umax, stepsize, cross=6, start_bound=[0,12]):\n \"\"\"\n calculates the max loss for a specific zero-crossing of the PRC\n \"\"\"\n # first, find where the pulse lines up the worst\n def min_shift(init):\n init = init[0]\n times, phases, shift = step_integrate(init*2*np.pi/pmodel.T,\n umax, stepsize)\n return np.abs(shift)\n # get alignment\n mins = optimize.minimize(min_shift, cross, bounds = [start_bound])\n even_start = mins.x[0]\n\n times, phases, shift = step_integrate(even_start*2*np.pi/pmodel.T,\n umax, stepsize)\n stim_PRC = prc_spl(start_time+phases*pmodel.T/(2*np.pi))\n ePRC = interpolate.UnivariateSpline(times, stim_PRC, k=3, s=0)\n loss = np.max(umax*np.abs(integrate.cumtrapz(ePRC(times), times)))\n zero_cross = times[np.argmax(umax*np.abs(integrate.cumtrapz(ePRC(times),\n times)))]\n return even_start, zero_cross, loss\n\n\n # find the loss for each crossing, where it starts, where it crosses\n zero_neg_start, zero_neg_cross, loss_neg = loss_zero_cross(0.06, step_test)\n zero_pos_start, zero_pos_cross, loss_pos = loss_zero_cross(0.06, step_test,\n cross=22, start_bound=[18,27])\n\n adv_per_cycle = max_1cyc_adv - loss_neg - loss_pos\n del_per_cycle = max_1cyc_del + loss_neg + loss_pos\n\n # for the advance, there is also the slowdown loss - the phase advance lost\n # by the oscillator not advancing\n slowdown_pos = np.abs(step_integrate(zero_pos_start*2*np.pi/pmodel.T,\n 0.06, zero_pos_cross)[-1])\n slowdown_neg = np.abs(step_integrate(zero_neg_start*2*np.pi/pmodel.T,\n 0.06, zero_neg_cross)[-1])\n # slowdown_loss is how much phase shift we miss at most due to this\n def max_shift_pos(init):\n init = init[0]\n times, phases, shift = step_integrate(init*2*np.pi/pmodel.T,\n umax, slowdown_pos*pmodel.T/(2*np.pi))\n return -shift\n def max_shift_neg(init):\n init = init[0]\n times, phases, shift = step_integrate(init*2*np.pi/pmodel.T,\n umax, slowdown_neg*pmodel.T/(2*np.pi))\n return shift\n\n pos_loss_maximization = optimize.minimize(max_shift_pos, [0], bounds=[[0,8]])\n neg_loss_maximization = optimize.minimize(max_shift_neg, [0], bounds=[[12,24]])\n slowdown_pos_loss = pos_loss_maximization.fun\n slowdown_neg_loss = neg_loss_maximization.fun\n\n\n # figure out the direction and number of cycle bounds\n delta_phi_fs = np.arange(-2*np.pi,2*np.pi,0.01)\n adv_del = [] #0 if advance, 1 if delay\n numcycles = []\n del_phis = []\n directions = []\n regions_missed = []\n cyc_to_reachs = []\n for delta_phi in delta_phi_fs:\n direction = int(delta_phi > delta_phi_star)\n if delta_phi>0:\n ncyc = 1 + delta_phi//max_1cyc_adv\n cyc_to_reach = 1 + delta_phi//adv_per_cycle\n adv_del.append(0)\n # upper limit of how much can be missed\n region_missed = (ncyc)*(\n np.abs(slowdown_pos_loss+slowdown_pos_loss)+loss_neg+loss_pos)\n del_phi = region_missed\n elif delta_phi<=0:\n ncyc = 1+ -delta_phi//-max_1cyc_del\n cyc_to_reach = 1+ -delta_phi//-del_per_cycle\n adv_del.append(1)\n # upper limit of how much can be missed\n region_missed = (ncyc)*(loss_neg+loss_pos)\n # will the minimum achieved be better or worse than the max lost\n del_phi = region_missed\n\n del_phis.append(del_phi)\n directions.append(direction)\n numcycles.append(ncyc)\n cyc_to_reachs.append(cyc_to_reach)\n regions_missed.append(region_missed)\n\n result_dict = {'delta_phi_fs' : delta_phi_fs,\n 'directions' : directions,\n 'numcycles' : numcycles,\n 'regions_missed' : regions_missed,\n 'cyc_to_reachs' : cyc_to_reachs,\n 'del_phis' : del_phis}\n\n return result_dict", "def evolve(self, *args, debugging=False, **kwargs):\n \n core_evolution(self, *args, debugging=debugging, **kwargs)", "def evaluation_step(self):\n current_step = self.n\n # first ode: d beta(t) = (beta0(t) + beta1(t)beta(t))dt\n beta0 = [-(self.b_f + self.c_f*self.p1_grid[current_step-1][t]**2) for t in range(len(self.time))]\n beta1 = [-(2*self.b + 2*self.c*self.p1_grid[current_step-1][t]) for t in range(len(self.time))]\n if self.solver=='Euler':\n self.beta.append(self._solve_ode_euler(beta0, beta1, self.gamma)) # beta is a funcation lambda\n else:\n self.beta.append(self._solve_ode_explicit(beta0, beta1, self.gamma)) # beta is a funcation lambda\n \n # second ode: d delta(t) = (delta0(t) + delta1(t)delta(t))dt\n delta0 = [-(2*self.c_f * self.p1_grid[current_step-1][t] * self.p2_grid[current_step-1][t] + 2*self.c*self.beta[current_step-1][t]*self.p2_grid[current_step-1][t]) for t in range(len(self.time))]\n delta1 = [-(self.b + self.c*self.p1_grid[current_step-1][t]) for t in range(len(self.time))]\n if self.solver == 'Euler':\n self.delta.append(self._solve_ode_euler(delta0, delta1, 0)) # delta is a function lambda\n else:\n self.delta.append(self._solve_ode_explicit(delta0, delta1, 0)) # delta is a function lambda\n \n # third ode: d phi = (phi0(t) + phi1(t)phi(t))dt\n phi0 = [-(self.sigma**2*self.beta[current_step-1][t] + self.c_f*self.p2_grid[current_step-1][t]**2 + self.c*self.delta[current_step-1][t]*self.p2_grid[current_step-1][t]) for t in range(len(self.time))]\n phi1 = [0]*len(self.time)\n if self.solver == 'Euler':\n self.phi.append(self._solve_ode_euler(phi0, phi1, 0)) # phi is a function lambda`A\n else:\n self.phi.append(self._solve_ode_explicit(phi0, phi1, 0)) # phi is a function lambda`A\n \n \n # we update p1 and p2:\n p1_new = np.array([-self.c/(2*self.c_f)*2*self.beta[current_step-1][t] for t in range(len(self.time))])\n p2_new = np.array([-self.c/(2*self.c_f)*self.delta[current_step-1][t] for t in range(len(self.time))])\n self.p1_grid.append(p1_new)\n self.p2_grid.append(p2_new)\n self.n += 1" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compute and return a person's age in years.
def compute_age(birth): birthday = datetime.strptime(birth, "%Y-%m-%d") today = datetime.now() # Compute the difference between today and the birthday in years. years = today.year - birthday.year # If necessary, subtract one from the difference. if birthday.month > today.month or \ (birthday.month == today.month and birthday.day > today.day): years -= 1 return years
[ "def get_age(self):\n if self.basics['death']:\n return self.basics['death'] - self.basics['birth']\n else:\n return datetime.datetime.now().year - self.basics['birth']", "def age_calc(self):\n if self.professor_dob is not False:\n self.age = (datetime.today().date()-datetime.strptime(\n str(self.professor_dob), '%Y-%m-%d').date()) // timedelta(days=365)", "def age(self) -> int:\n return calculate_age(self.date_of_birth, date.today())", "def age(self):\n birth_date = self.patient.get('birth_date', None)\n if birth_date:\n diff = self.created.date() - birth_date\n return int(diff.days / 30.475)", "def academic_age(self) -> int:\n if self.first_pub_year is None:\n return 0\n else:\n return self.date.year - self.first_pub_year + 1", "def determine_age(dob, date):\n age = date.year - dob.year - ((dob.month, dob.day) > (date.month, date.day))\n\n # age = abs((date – dob)).days / 365.25\n\n return age", "def age(self):\n age = _f.getage(self.pvec)\n return age", "def age_in_planet_years(self, age_in_years):\n return age_in_years * self.orbital_period / Decimal(365.256363)", "def get_age(self):\n\t\tif self.birthday is None:\n\t\t\traise ValueError\n\t\treturn (datetime.date.today() - self.birthday).days", "def age(self, reference_date, age_type_calc = \"schoolyear\"):\n if (self.birthdate):\n bd = self.birthdate.timetuple()\n rd = reference_date.timetuple()\n #first calculate the effective \"current year\"\n # if not during the schoolyear then it is just the actual\n #if it is during the school year jun-dec, actual\n #if it is during the schoolyear jan-mar then year-1 to keep same\n #\"year' for age computation throughout the school year\n ref_year = rd.tm_year\n if (rd.tm_mon <4):\n ref_year -= 1\n base_age = ref_year - bd.tm_year\n #now adjust from the quarter of the year of the birthdate\n if (bd.tm_mon < 4):\n age = base_age + 0.5\n elif (bd.tm_mon > 9):\n age = base_age - 0.5\n else:\n age = base_age\n if age_type_calc == \"endyear\":\n age += 0.75\n if age_type_calc == \"actual\":\n #for out of school -- just real age rounded to 0.5 years\n real_age = reference_date - self.birthdate\n years = real_age.days / 365.0\n #perform rounding\n age = round(years * 2) / 2.0\n return age\n else:\n return 0", "def average_age(self):\n current_year = int(str(datetime.date.today())[:4])\n avg_age = 0\n no = 0\n for prof in self.profiles:\n year = int(str(prof['birthdate'])[:4])\n age = current_year - year\n avg_age = (avg_age+age)\n no+=1\n return avg_age/no", "def total_years_experience(self):\n\n durations = [x.duration_months for x in self.work_experience]\n return sum(durations) /12", "def average_age(self):\n current_year = int(str(datetime.date.today())[:4])\n avg_age = 0\n no = 0\n for prof in self.profiles_nt:\n year = int(str(prof.birthdate)[:4])\n age = current_year - year\n avg_age = (avg_age+age)\n no+=1\n return avg_age/no", "def birth_growth(self):\n\t\tbirth_year_growth = (60/self.birth_rate)*60*24*365\n\n\t\treturn birth_year_growth", "def oldest_person(self):\n current_year = int(str(datetime.date.today())[:4])\n oldest_year = current_year\n for prof in self.profiles:\n year = int(str(prof['birthdate'])[:4])\n if year<oldest_year:\n oldest_year = year\n oldest_person_age = current_year-oldest_year\n return oldest_person_age", "def GetActualAge(self):\n return self.__age", "def oldest_person(self):\n current_year = int(str(datetime.date.today())[:4])\n oldest_year = current_year\n for prof in self.profiles_nt:\n year = int(str(prof.birthdate)[:4])\n if year<oldest_year:\n oldest_year = year\n oldest_person_age = current_year-oldest_year\n return oldest_person_age", "def date_age(datestr):\n year = datetime.today().year\n yday_today = datetime.today().timetuple().tm_yday\n yday_input = datetime.strptime(str(year) + ' ' + datestr, '%Y %B %d').timetuple().tm_yday\n diff = yday_today - yday_input\n if diff < 0:\n diff += 365\n # TODO: leap years. If the span between input & today contains feb\n # in a leap year, then add 1\n return diff", "def calcul_age_2050(age):\n return age+(2050-2016)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tries to cast value to bool. Raises ValueError if value is ambiguous. Raises TypeError for unsupported types.
def cast_bool(value) -> bool: if isinstance(value, bool): return value if isinstance(value, str): if value.lower() == 'true': return True elif value.lower() == 'false': return False else: raise ValueError("Ambiguous value of " + value) else: raise TypeError("Unsupported type of {} with value {}" .format(type(value), value))
[ "def convert_to_bool(value: object) -> bool:\n # if number, then bool it\n # if string, try to convert to float\n # if float converts, then bool the result\n # if float does not convert then look for truthy string and bool True\n # else False\n truthy = ['y', 'yes', 'true', '*']\n\n if isinstance(value, (int, float)):\n return bool(value)\n\n if isinstance(value, str):\n try:\n test_value = convert_to_float(value)\n if test_value is not None:\n return bool(test_value)\n except Exception:\n pass\n\n if value:\n return value.lower() in truthy\n\n return False", "def bool_converter(val):\n return bool(strtobool(str(val)))", "def validate_boolean(self, value):\n if value is not None:\n assert isinstance(value, bool)\n return value", "def validate_bool(value: Union[bool, Boolean]) -> None:\r\n from apysc.type import type_util\r\n is_bool: bool = type_util.is_bool(value=value)\r\n if is_bool:\r\n return\r\n raise ValueError(\r\n f'Specified value is not bool or Boolean type: {type(value)}')", "def Bool(val):\n if type(val) is bool:\n return val\n if isinstance(val, str):\n v = val.upper()\n if v in {'TRUE', 'YES', 'T', 'Y', '1'}:\n return True\n if v in {'FALSE', 'NO', 'F', 'N', '0'}:\n return False\n elif int(val) == float(val):\n v = int(val)\n if v in {0, 1}:\n return bool(v)\n raise ValueError(\"Expected Boolean, but received %s\" % (val,))", "def ensure_boolean(val):\n if isinstance(val, bool):\n return val\n elif isinstance(val, str):\n return val.lower() == 'true'\n else:\n return False", "def int_to_bool(value):\n try:\n return bool(int(value))\n except ValueError:\n raise TypeError('must supply integer string')", "def parse_bool(value):\n return bool({\n 'True': True,\n 'False': False\n }.get(value, value))", "def __num_to_bool(self, field, value):\n if abs(value) < 1e-10:\n return False\n\n if abs(1 - value) < 1e-10:\n return True\n\n return self.__conversion_error(field, value, \"boolean\")", "def is_bool(self) -> \"bool\":\n return self._value.getType() == Value.BVAL", "def test_bool_caster():\n convert, noconvert = m.bool_passthrough, m.bool_passthrough_noconvert\n\n def require_implicit(v):\n pytest.raises(TypeError, noconvert, v)\n\n def cant_convert(v):\n pytest.raises(TypeError, convert, v)\n\n # straight up bool\n assert convert(True) is True\n assert convert(False) is False\n assert noconvert(True) is True\n assert noconvert(False) is False\n\n # None requires implicit conversion\n require_implicit(None)\n assert convert(None) is False\n\n class A:\n def __init__(self, x):\n self.x = x\n\n def __nonzero__(self):\n return self.x\n\n def __bool__(self):\n return self.x\n\n class B:\n pass\n\n # Arbitrary objects are not accepted\n cant_convert(object())\n cant_convert(B())\n\n # Objects with __nonzero__ / __bool__ defined can be converted\n require_implicit(A(True))\n assert convert(A(True)) is True\n assert convert(A(False)) is False", "def normalize_boolean(val):\n if val is None:\n return val\n else:\n return ensure_boolean(val)", "def asGenericBool(*args, **kwargs):\n \n pass", "def is_bool(x):\n return type(x) == bool", "def boolify(val):\n if isinstance(val, bool):\n return val\n return val in ['TRUE', 'True', 'true', '1', 1, 'Yes', 'Y', 'YES', 'y']", "def value2Bool(cls, v):\n if (isinstance(v, (tuple, list))):\n for vv in v:\n if cls.value2Bool(vv):\n return True\n return False\n return not str(v).lower() in cls.C.FALSEVALUES", "def cfg_tobool(v):\n if v in (True, False, None):\n return v\n if not v:\n return False\n if v.upper()[0] in ('T', 'Y'):\n return True\n if v.upper()[0] in ('F', 'N'):\n return False\n return bool(int(v))", "def get_as_bool(driver_id, bool_value):\n if driver_id == 'pgsql':\n if bool_value is True:\n return 'Y'\n else:\n return 'N'\n else:\n if type(bool_value) == bool and bool_value:\n return 'true'\n else:\n return 'false'", "def writeBoolValue(self, value):\n if isBool(value):\n if value:\n self._writeValue(True)\n else:\n self._writeValue(False)\n else:\n raise InvalidTypeError" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Recursively iterates on dictionary and swaps booleanlike values with proper booleans.
def swap_booleans(dictionary: dict, inplace: bool=True) -> dict: # TODO: Extend functionality to lists too if not inplace: dictionary = copy.deepcopy(dictionary) for key in dictionary.keys(): if isinstance(dictionary[key], dict): dictionary[key] = swap_booleans(dictionary[key], inplace=inplace) elif is_booleanlike(dictionary[key]): dictionary[key] = cast_bool(dictionary[key]) return dictionary
[ "def replace_string_bool_to_bool(dictionary: Dict[str, Any]) -> Dict[str, Any]:\n for key, item in dictionary.items():\n if isinstance(item, str):\n if item.lower() == \"true\":\n dictionary[key] = True\n elif item.lower() == \"false\":\n dictionary[key] = False\n return dictionary", "def boolean_convert(d, convert_keys=None, level=0):\n convert_keys = convert_keys or []\n for key, val in d.items():\n if isinstance(val, dict):\n d[key] = boolean_convert(val, convert_keys)\n if key in [ak.split(\".\")[level] for ak in convert_keys if len(ak.split(\".\")) > level]:\n if isinstance(val, list) or isinstance(val, tuple):\n if val and isinstance(val[0], dict):\n d[key] = [boolean_convert(v, convert_keys, level + 1) for v in val]\n else:\n d[key] = [to_boolean(x) for x in val]\n elif isinstance(val, dict) or isinstance(val, OrderedDict):\n d[key] = boolean_convert(val, convert_keys, level + 1)\n else:\n d[key] = to_boolean(val)\n return d", "def json_dict_type_correction(aDict):\n\n # loop through the items in the dictionary\n for key, value in aDict.items():\n if value == \"None\":\n aDict[key] = None\n elif value == \"True\":\n aDict[key] = True\n elif value == \"False\":\n aDict[key] = False", "def cast_boolean_args(args):\n for key in args.keys():\n value = args[key]\n if (type(value) == str) and (value in [\"True\", \"False\"]):\n if value == \"True\":\n args[key] = True\n elif value == \"False\":\n args[key] = False\n\n return args", "def _fix_json_values(data: Dict) -> Dict:\n return json.loads(json.dumps(data).replace('\"true\"', \"true\").replace('\"false\"', \"false\"))", "def _compact_dict(dict):\n out_dict = {}\n for key, value in dict.items():\n if value is not None and value is not False:\n out_dict[key] = value\n return out_dict", "def experience_to_boolean(player_dicts):\n for individual in player_dicts:\n if individual['experience'] == 'YES':\n individual['experience'] = True\n else:\n individual['experience'] = False\n return player_dicts", "def set_true_for_empty_dict(d):\n if not isinstance(d, (dict, list)):\n return d\n elif isinstance(d, list):\n return [value for value in (set_true_for_empty_dict(value) for value in d)]\n else:\n if d == {}:\n return True\n return {key: True if value == {} else value for key, value in ((key, set_true_for_empty_dict(value))\n for key, value in d.items())}", "def reconstruct_boolean_into(value, into):\n if value:\n value_representation = VALUE_BOOLEAN_TRUE\n else:\n value_representation = VALUE_BOOLEAN_FALSE\n \n into.append(value_representation)", "def dictSwitch(oldDict, transformer, related_transformer=None, ignore_unknown=False):\n if related_transformer is None:\n related_transformer = {}\n newDict = {}\n for key, value in oldDict.iteritems():\n try:\n new_key = transformer[key]\n newDict[new_key] = value\n except KeyError:\n if not ignore_unknown:\n newDict[key] = value\n for key, value in related_transformer.iteritems():\n keys = key.split('#')\n if len(keys) == 2:\n try:\n newDict[value] = oldDict[int(keys[0])]['value']['values'][int(keys[1])]\n except KeyError as e:\n print oldDict\n print keys[0]\n print keys[1]\n print e\n elif len(keys) == 3:\n newDict[value] = oldDict[int(keys[0])]['value']['values'][int(keys[1])]['value']['values'][int(keys[2])]\n #print newDict\n return newDict", "def _transform_1d_boolean_indexers(key):\n key = [\n np.asanyarray(k).nonzero()[0]\n if isinstance(k, (np.ndarray, list)) and type(k[0]) in (bool, np.bool_)\n else k\n for k in key\n ]\n return tuple(key)", "def map_with_boolean_array(array, selector, values):\n true_value, false_value = values[True], values[False]\n return dict(\n chain(\n zip(array[selector], repeat(true_value)),\n zip(array[numpy.invert(selector)], repeat(false_value)),\n )\n )", "def clean(form):\n result = defaultdict(lambda: None)\n for k, v in form.items():\n if v is None or v == \"None\":\n result[k] = None\n continue\n if v is True or v == \"True\":\n result[k] = True\n continue\n if v is False or v == \"False\":\n result[k] = False\n continue\n if isinstance(v, (int, float)):\n result[k] = v\n continue\n try:\n result[k] = int(v)\n continue\n except ValueError:\n try:\n result[k] = float(v)\n continue\n except ValueError:\n result[k] = v\n return result", "def bool_replace(text):\n if text == \"false\":\n return False\n elif text == \"true\":\n return True\n else:\n return text", "def test_adjust_bool_keyval(self):\n self.setting.value = u\"no\"\n self.setting.adjust_value_to_type(\"keyval list\")\n self.assertEqual(self.setting.value, False)", "def bool2json(value):\n if isinstance(value, bool):\n return str(value).lower()\n return value", "def test_adjust_bool_keyval(self):\n self.setting.value = u\"true\"\n self.setting.adjust_value_to_type(\"keyval list\")\n self.assertEqual(self.setting.value, u\"true\")\n self.assert_(isinstance(self.setting.value, unicode))", "def replace_password(d : dict) -> dict:\n _d = d.copy()\n for k, v in d.items():\n if isinstance(v, dict):\n _d[k] = replace_password(v)\n elif 'password' in str(k).lower():\n _d[k] = ''.join(['*' for char in str(v)])\n return _d", "def test_boolean_overrides(self):\n\n self.check_override({'bool': False}, {})\n self.check_override({}, {'bool': False}, {'bool': False})\n self.check_override({'bool': True}, {})\n self.check_override({}, {'bool': True}, {'bool': True})\n self.check_override({'bool': True}, {'bool': False}, {'bool': False})\n self.check_override({'bool': False}, {'bool': True}, {'bool': True})" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns ix, bitsa, bitsb where ix is the first different index and bitsa has a 1 there.
def __find_one_zero(self, bits1, bits2): for ix in range(len(bits1)): if bits1[ix] != bits2[ix]: return (ix, bits1, bits2) if bits1[ix] else (ix, bits2, bits1) return (-1, bits1, bits2)
[ "def getBit( value , index ):\n return (value >> index) & 1", "def get_bit(number, bit_index):\n return number >> bit_index & 1", "def get_bit(k, i):\n return k[0][i]", "def positions_mask_to_tuple(self,positions):\n return tuple(i for i in range(16) if (positions & (1 << i)) != 0)", "def getBitValue(self, byteval, idx):\n # print byteval, idx, byteval & 1 << idx != 0\n if byteval & 1 << idx != 0:\n return 1\n return 0", "def get_bit(data, bit_index):\n if bit_index < 8 * len(data):\n cur_byte = data[bit_index // 8]\n return (cur_byte >> (7 - bit_index % 8)) & 0x1\n raise RuntimeError(\"Out of bound index %s\" % bit_index)", "def _get_index(self, a, a_star, s, s_star):\n idx_a = np.logical_or(a > 0., a_star > 0.)\n idx_s = np.logical_or(s > 0., s_star > 0.)\n idx_weight = np.concatenate([idx_a, idx_s, np.ones(1)])\n idx_weight = np.ndarray.astype(idx_weight, dtype=bool)\n return idx_a, idx_s, idx_weight", "def get_set_bits_list(x):\n idx = 0\n \"\"\"idx represents position from end\n hence bitboard can be prepared by simply shifting 1\n by the idx\"\"\"\n l = []\n while(x):\n if(x & 1):\n l.append(idx)\n x = x >> 1\n idx += 1\n return l", "def get_whole(*bits):\n n = 0\n\n for bit in bits:\n n <<= 1\n n |= bit\n return n", "def test_nth_bit_set():\n for _ in range(0, 10000):\n number = random.randint(0, 100000000)\n bits = bin(number)[2:]\n for i, b in enumerate(reversed(bits)):\n assert has_nth_bit_set(number, i) == (int(b) == 1)", "def extract(x):\n ans = 0\n i = 0\n while x > 0:\n ans = ans | ((x & 1) << i)\n i += 1\n x = x >> 3\n return ans", "def match_point(click,bitmasks):\n for mask in bitmasks:\n if mask[int(click[0][1]),int(click[0][0])] > 0:\n return i", "def get_bit(self):\n\tnext_bit = False;\n\tfor i in range(0, len(self.cl)):\n\t if self.cl[i]:\n\t\tnext_bit = self.graine[i]\n\t\tfor j in range(i+1, len(self.cl)):\n\t\t if self.cl[j]:\n\t\t\tnext_bit = next_bit ^ self.graine[j]\n\t\tbreak\n\treturn next_bit", "def readBitsFromByte(value, startIndex, bitCount): \n return (value & (2**startIndex -1)) >> (startIndex - bitCount)", "def getNthBit(num, n): \n return (num>>n)&1", "def test_middle_bits(self):\r\n middle_bits = BitField(5,9)\r\n self.assertEqual(middle_bits.extract(0b1010101101101011), 0b11011)", "def getBit(num, i):\n if i < 0 or i >= numOfBits(num):\n return 0\n\n mask = (1 << i)\n currBit = num & mask\n return int(currBit != 0)", "def swap_bits(x, i, j):\n bit_i, bit_j = (x >> i) & 1, (x >> j) & 1\n # Only swap if bits are not the same\n if bit_i ^ bit_j: \n # If the bits differ than we just need to flip both of them\n mask = (1 << i) | (1 << j)\n x ^= mask\n return x", "def win_indexes(n: int) -> tuple[int, int]:\n if n < 1:\n return []\n\n # Rows\n for r in range(n):\n yield [(r, c) for c in range(n)]\n # Columns\n for c in range(n):\n yield [(r, c) for r in range(n)]\n # Diagonal top left to bottom right\n yield [(i, i) for i in range(n)]\n # Diagonal top right to bottom left\n yield [(i, n - 1 - i) for i in range(n)]", "def xor(a, b):\n return tuple((a[i] + b[i]) % 2 for i in range(len(a)))" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Fill a feed dictionary with the actual set of images and labels for this particular training step.
def feed_dict(is_train, data_set): feed_images, feed_labels = data_set.next_batch(Utils.batch_size) return {x_placeholder: feed_images, y_placeholder: feed_labels, is_training: is_train}
[ "def fill_feed_dict(self, batch):\n feed_dict = {\n self.inputs: batch.data,\n self.targets: batch.labels,\n }\n return feed_dict", "def fill_feed_dict(self, data):\n\n feed_dict = {\n self.encode_input_placeholder : data[\"encoder_inputs\"],\n self.decode_input_placeholder : data[\"decoder_inputs\"],\n self.label_placeholder : data[\"labels\"],\n self.query_input_placeholder : data[\"query\"], \n self.weights_placeholder : data[\"weights\"],\n self.feed_previous_placeholder: data[\"feed_previous\"],\n self.query_sequence_length : data[\"query_seq_length\"], \n self.encode_sequence_length : data[\"encode_seq_length\"],\n }\n\n if \"sequence_indices_encoder\" in data and \"sequence_indices_query\" in data:\n feed_dict.update({self.encode_sequence_indices: data[\"sequence_indices_encoder\"],\n self.query_sequence_indices: data[\"sequence_indices_query\"]})\n\n return feed_dict", "def build_train_feed_dict(state, input_data):\n feed_dict = {\n state.labels: input_data['labels'],\n state.fm_feat_indices: input_data['fm_feat_indices'],\n state.fm_feat_values: input_data['fm_feat_values'],\n state.fm_feat_shape: input_data['fm_feat_shape'],\n state.dnn_feat_indices: input_data['dnn_feat_indices'],\n state.dnn_feat_values: input_data['dnn_feat_values'],\n state.dnn_feat_weights: input_data['dnn_feat_weights'],\n state.dnn_feat_shape: input_data['dnn_feat_shape'],\n state.layer_keeps: state.keep_prob_train\n }\n return feed_dict", "def _setup_train_feed_dict(self, batch_type, training_handle):\n\n feed_dict_batch_type = {}\n component_batch_type_pl = self._component.get_batch_type() # dic -> (component, batch type)\n\n for c in component_batch_type_pl:\n feed_dict_batch_type[component_batch_type_pl[c]] = batch_type['episodic/' + c] # dict->(episodic/'c', batch_type)\n\n feed_dict = {\n self._placeholders['dataset_handle']: training_handle\n }\n\n feed_dict.update(feed_dict_batch_type)\n\n return feed_dict", "def build_eval_feed_dict(state, input_data):\n feed_dict = {\n state.labels: input_data['labels'],\n state.fm_feat_indices: input_data['fm_feat_indices'],\n state.fm_feat_values: input_data['fm_feat_values'],\n state.fm_feat_shape: input_data['fm_feat_shape'],\n state.dnn_feat_indices: input_data['dnn_feat_indices'],\n state.dnn_feat_values: input_data['dnn_feat_values'],\n state.dnn_feat_weights: input_data['dnn_feat_weights'],\n state.dnn_feat_shape: input_data['dnn_feat_shape'],\n state.layer_keeps: state.keep_prob_test\n }\n return feed_dict", "def fill_feed_dict(instance_iter, input_ph, target_ph, neg_ph, embeddings):\n\n shape = np.array([FLAGS.batch_size, embeddings.vocab_size])\n embed_dim = embeddings.dim\n\n input_subject_ph = input_ph[0]\n input_verb_ph = input_ph[1]\n input_object_ph = input_ph[2]\n input_subject_w_ph = input_ph[3]\n input_verb_w_ph = input_ph[4]\n input_object_w_ph = input_ph[5]\n\n target_subject_ph =target_ph[0]\n target_verb_ph =target_ph[1]\n target_object_ph =target_ph[2]\n target_subject_w_ph =target_ph[3]\n target_verb_w_ph =target_ph[4]\n target_object_w_ph =target_ph[5]\n\n neg_subject_ph =neg_ph[0]\n neg_verb_ph =neg_ph[1]\n neg_object_ph =neg_ph[2]\n neg_subject_w_ph =neg_ph[3]\n neg_verb_w_ph =neg_ph[4]\n neg_object_w_ph =neg_ph[5]\n\n input_sub_id_values = []\n input_sub_weight_values = []\n input_verb_id_values = []\n input_verb_weight_values = []\n input_obj_id_values = []\n input_obj_weight_values = []\n\n target_sub_id_values = []\n target_sub_weight_values = []\n target_verb_id_values = []\n target_verb_weight_values = []\n target_obj_id_values = []\n target_obj_weight_values = []\n \n neg_sub_id_values = []\n neg_sub_weight_values = []\n neg_verb_id_values = []\n neg_verb_weight_values = []\n neg_obj_id_values = []\n neg_obj_weight_values = []\n\n done = False\n for i in range(FLAGS.batch_size):\n inst = next(instance_iter)\n input_inst = inst[0]\n target_inst = inst[1]\n neg_inst = inst[2]\n #print(\"Input: {}, Target: {}\".format(inst[2], inst[3]))\n if input_inst and target_inst and neg_inst:\n\n input_sub_id, input_sub_w = input_inst[0]\n input_verb_id, input_verb_w = input_inst[1]\n input_obj_id, input_obj_w = input_inst[2]\n\n target_sub_id, target_sub_w = target_inst[0]\n target_verb_id, target_verb_w = target_inst[1]\n target_obj_id, target_obj_w = target_inst[2]\n \n neg_sub_id, neg_sub_w = neg_inst[0]\n neg_verb_id, neg_verb_w = neg_inst[1]\n neg_obj_id, neg_obj_w = neg_inst[2]\n\n input_sub_id_values.extend(input_sub_id)\n input_sub_weight_values.extend(input_sub_w)\n input_verb_id_values.extend(input_verb_id)\n input_verb_weight_values.extend(input_verb_w)\n input_obj_id_values.extend(input_obj_id)\n input_obj_weight_values.extend(input_obj_w)\n\n target_sub_id_values.extend(target_sub_id)\n target_sub_weight_values.extend(target_sub_w)\n target_verb_id_values.extend(target_verb_id)\n target_verb_weight_values.extend(target_verb_w)\n target_obj_id_values.extend(target_obj_id)\n target_obj_weight_values.extend(target_obj_w)\n\n neg_sub_id_values.extend(neg_sub_id)\n neg_sub_weight_values.extend(neg_sub_w)\n neg_verb_id_values.extend(neg_verb_id)\n neg_verb_weight_values.extend(neg_verb_w)\n neg_obj_id_values.extend(neg_obj_id)\n neg_obj_weight_values.extend(neg_obj_w)\n\n else: #reached the end of instances\n done = True\n break\n\n input_sub_weight_values = np.array(input_sub_weight_values)\n input_verb_weight_values = np.array(input_verb_weight_values)\n input_obj_weight_values = np.array(input_obj_weight_values)\n input_sub_id_values = np.array(input_sub_id_values)\n input_verb_id_values = np.array(input_verb_id_values)\n input_obj_id_values = np.array(input_obj_id_values)\n\n target_sub_weight_values = np.array(target_sub_weight_values)\n target_verb_weight_values = np.array(target_verb_weight_values)\n target_obj_weight_values = np.array(target_obj_weight_values)\n target_sub_id_values = np.array(target_sub_id_values)\n target_verb_id_values = np.array(target_verb_id_values)\n target_obj_id_values = np.array(target_obj_id_values)\n\n neg_sub_weight_values = np.array(neg_sub_weight_values)\n neg_verb_weight_values = np.array(neg_verb_weight_values)\n neg_obj_weight_values = np.array(neg_obj_weight_values)\n neg_sub_id_values = np.array(neg_sub_id_values)\n neg_verb_id_values = np.array(neg_verb_id_values)\n neg_obj_id_values = np.array(neg_obj_id_values)\n\n feed_dict = {\n input_subject_ph: input_sub_id_values,\n input_verb_ph: input_verb_id_values,\n input_object_ph: input_obj_id_values,\n input_subject_w_ph: input_sub_weight_values,\n input_verb_w_ph: input_verb_weight_values,\n input_object_w_ph: input_obj_weight_values,\n\n target_subject_ph: target_sub_id_values,\n target_verb_ph: target_verb_id_values,\n target_object_ph: target_obj_id_values,\n target_subject_w_ph: target_sub_weight_values,\n target_verb_w_ph: target_verb_weight_values,\n target_object_w_ph: target_obj_weight_values,\n\n neg_subject_ph: neg_sub_id_values,\n neg_verb_ph: neg_verb_id_values,\n neg_object_ph: neg_obj_id_values,\n neg_subject_w_ph: neg_sub_weight_values,\n neg_verb_w_ph: neg_verb_weight_values,\n neg_object_w_ph: neg_obj_weight_values\n }\n return feed_dict,done", "def _build_feed_dict(self, trees):\n\n # Values to prepare\n is_leaf_vals = []\n word_index_vals = []\n left_child_vals = []\n right_child_vals = []\n label_vals = []\n is_root_vals = []\n weight_vals = []\n\n start_idx = 0\n\n # Process all trees\n for tree_idx in range(len(trees)):\n tree_dict = self._tree_feed_data(trees[tree_idx], start_idx)\n is_leaf_vals.extend(tree_dict['is_leaf'])\n word_index_vals.extend(tree_dict['word_index'])\n left_child_vals.extend(tree_dict['left_child'])\n right_child_vals.extend(tree_dict['right_child'])\n label_vals.extend(tree_dict['label'])\n is_root_vals.extend(tree_dict['is_root'])\n weight_vals.extend(tree_dict['weight'])\n start_idx += len(tree_dict['is_leaf'])\n\n # Check whether tensors are written before read.\n assert np.all([left_child_vals[i] < i for i in range(len(left_child_vals))])\n assert np.all([right_child_vals[i] < i for i in range(len(right_child_vals))])\n\n # Get Placeholders\n graph = tf.get_default_graph()\n is_leaf = graph.get_tensor_by_name('Inputs/is_leaf:0')\n word_index = graph.get_tensor_by_name('Inputs/word_index:0')\n left_child = graph.get_tensor_by_name('Inputs/left_child:0')\n right_child = graph.get_tensor_by_name('Inputs/right_child:0')\n label = graph.get_tensor_by_name('Inputs/label:0')\n is_root = graph.get_tensor_by_name('Inputs/is_root:0')\n weight = graph.get_tensor_by_name('Inputs/weight:0')\n\n # Create feed dict\n feed_dict = {\n is_leaf: is_leaf_vals,\n word_index: word_index_vals,\n left_child: left_child_vals,\n right_child: right_child_vals,\n label: label_vals,\n is_root: is_root_vals,\n weight: weight_vals\n }\n\n return feed_dict", "def _load_train_images(self):\n self._load_images(\n self.image_info.train_img_files,\n self.image_info.num_classes,\n self.train_data, self.train_labels, disp='train')\n self.train_data = self.train_data.astype('float32') / 255\n self.train_labels = self._format_labels(self.train_labels,\n self.image_info.train_img_files,\n self.image_info.num_classes)", "def update_feed_dict(self):\n gp = self.gaussian_process\n feed_dict = self.feed_dict\n\n gp.update_feed_dict(gp.get_feed_dict_keys(), feed_dict)\n feed_dict[self.hyperparameters[0]] = gp.get_free_state()", "def load_train(self):\n images, labels = self.load(os.path.join('mnist', 'train', 'images'),\n os.path.join('mnist', 'train', 'labels'))\n self.train_data = zip(images, labels)", "def _set_task(self):\r\n for k in self.train_tasks:\r\n k_dict = {'train/'+k: \r\n {'train': self.train_steps[k],\r\n 'global_step': self.gs,\r\n 'loss': self.losses[k+'/sum'] if self.is_multi_gpu else self.losses[k]\r\n }}\r\n self.run_op.update(k_dict)\r\n\r\n self.run_op.update({\r\n 'predict': {\r\n 'inf': self.nodes['inf']\r\n },\r\n 'summary': {\r\n 'summary': self.summary_ops['all']\r\n },\r\n 'interp': {\r\n 'itp': self.nodes['itp']\r\n }\r\n })\r\n\r\n self.feed_dict.update({\r\n # 'train/main': ['data_'+self.sk[-1], 'label_'+self.sk[0]],\r\n \"train/main\": ['data_'+k for k in self.sk] + ['label_'+k for k in self.sk],\r\n 'predict': ['data_'+self.sk[-1], 'label_'+self.sk[-1]],\r\n 'interp': ['data_'+self.sk[-1], 'label_'+self.sk[-1]],\r\n 'summary': ['data_'+k for k in self.sk] + ['label_'+k for k in self.sk],\r\n })", "def _get_feed_dict(self, batch):\n try:\n # sometimes batch is a dict of numpy.ndarrays\n feed_dict = {\n self._observations_ph: batch['observations'],\n self._actions_ph: batch['actions'],\n self._next_observations_ph: batch['next_observations'],\n self._rewards_ph: batch['rewards'],\n self._dones_ph: batch['dones']}\n except TypeError:\n # sometimes batch is a list of namedtuples\n states, actions, rewards, next_states, dones = zip(*batch)\n feed_dict = {\n self._observations_ph: states,\n self._actions_ph: actions,\n self._next_observations_ph: next_states,\n self._rewards_ph: rewards,\n self._dones_ph: dones}\n return feed_dict", "def _parse_train_cfg(self):\n if self.train_cfg is None:\n self.train_cfg = dict()\n # control the work flow in train step\n self.disc_steps = self.train_cfg.get('disc_steps', 1)\n\n # whether to use exponential moving average for training\n self.use_ema = self.train_cfg.get('use_ema', False)\n if self.use_ema:\n # use deepcopy to guarantee the consistency\n self.generator_ema = deepcopy(self.generator)\n\n self.real_img_key = self.train_cfg.get('real_img_key', 'real_img')", "def load_train(self):\n images, labels = self.load(os.path.join('mnist', 'train', 'images'),\n os.path.join('mnist', 'train', 'labels'))\n self.train_data = list(zip(images, labels))", "def __init__(self, confTrain):\n\n BatchGenerator.__init__(self, confTrain)\n\n # List of currently loaded channel images\n self.currentChannelImages = []\n # List of currently loaded GT images\n self.currentGt = []\n # List of list of labels available in currently loaded GT images\n self.availableLabels = []\n\n\n # ===================================== ABOUT THE IMAGE CHANNELS LIST INDEXING ================================\n\n # IMPORTANT: The indices in the lists of channel filenames are inverted with respect to the currently loaded images\n # self.currentChannelImages is [img][channel] while the filenames list self.allChannelsFilenames is [channel][img]\n\n # =================================================================================================================\n\n # List of lists of filenames (size: numChannels x numOfFilenames)\n self.allChannelsFilenames = []\n # List of GT filenames (size:numOfFilenames)\n self.gtFilenames = []\n\n self.allowedIndicesPerVolumePerLabel = {}\n\n self.numClasses = len(self.confTrain['labels'])\n\n # Load the filenames from the configuration files and the parameters\n self.numChannels = len(self.confTrain['channelsTraining'])\n self.numOfCasesLoadedPerSubepoch = self.confTrain['numOfCasesLoadedPerSubepochTraining']\n self.loadFilenames(self.confTrain['channelsTraining'], self.confTrain['gtLabelsTraining'])\n\n # Check if, given the number of cases loaded per subepoch and the total number of samples, we\n # will need to load new data in every subepoch or not.\n self.loadNewFilesEverySubepoc = len(self.allChannelsFilenames[0]) > self.numOfCasesLoadedPerSubepoch\n\n\n self.tileSize = self.confTrain['patchSizeTrain']\n self.gtSize = self.confTrain['patchSizeGt']", "def init_parameters(self):\r\n self.guessed_fishes_dict = {}\r\n self.train_index = 0", "def make_img_dict(self):\n img_dict = dict()\n for img in self.imgs:\n classes = self.get_classes(get_label_path(img))\n if len(classes) != 0:\n img_dict[img] = classes\n return img_dict", "def get_train_batch(batch_size=12):\n \n image_paths = glob(os.path.join(data_dir, 'images', '*.jpg'))\n if shuffle:\n random.shuffle(image_paths)\n for i in range(0, len(image_paths), batch_size):\n images = []\n labels = []\n names = []\n for path in image_paths[i:i+batch_size]:\n image_name = os.path.basename(path)\n names.append(image_name)\n label_name = image_name[:-4] + '_train_id.png'\n label_path = os.path.join(data_dir, 'labels', label_name)\n label = imageio.imread(label_path)\n image = imageio.imread(path)\n if relabel:\n relabel_vehicles(label)\n relabel_pedestrian(label)\n relabel_background(label)\n if new_labels:\n new_label_20(label)\n new_label_30(label)\n if trim:\n image = image[trim_ind[0]:trim_ind[1]]\n label = label[trim_ind[0]:trim_ind[1]]\n if reshape:\n image = cv2.resize(image, new_shape)\n label = cv2.resize(label, new_shape, interpolation=cv2.INTER_NEAREST)\n if preprocess:\n image = image_preprocessing(image, denoise=denoise)\n label = one_hot_label(label, values)\n images.append(image)\n labels.append(label)\n \n images = np.array(images, dtype=np.uint8)\n labels = np.array(labels, dtype=np.uint8)\n \n yield images, labels, names", "def train_feed(idx, models, **kw):\n feed = {}\n for m in models:\n feed[m.is_train] = True\n for dictionary in [kw, kw.get('feed_dict', {})]:\n for key, val in six.iteritems(dictionary):\n attr = getattr(m, key) if isinstance(key, str) and hasattr(m, key) else key\n if type(attr) == type(m.X):\n if len(attr.shape) >= 1:\n if attr.shape[0].value is None:\n feed[attr] = val[idx]\n return feed" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Runs one evaluation against the full epoch of data.
def eval_full_epoch(data_set): true_count = 0 # Counts the number of correct predictions. data_set.start_new_epoch() # Start new epoch for evaluation steps_per_epoch = data_set.num_examples // Utils.batch_size num_examples = steps_per_epoch * Utils.batch_size for _ in xrange(steps_per_epoch): true_count += sess.run(EVAL, feed_dict=feed_dict(False, data_set)) accuracy = true_count / num_examples print(' Num examples: %d Num correct: %d Accuracy: %0.04f' % (num_examples, true_count, accuracy))
[ "def train_one_epoch(self, *args, **kwargs):\r\n raise NotImplementedError", "def eval_one_epoch(sess, ops, test_writer,tracks=False,lstm_params=None):\n global EPOCH_CNT\n is_training = False\n log_string(str(datetime.now()))\n log_string('---- EPOCH %03d EVALUATION ----' % (EPOCH_CNT))\n test_idxs = np.arange(0, len(TEST_DATASET))\n num_batches = len(TEST_DATASET) / BATCH_SIZE\n\n # To collect statistics\n total_correct = 0\n total_seen = 0\n loss_sum = 0\n total_seen_class = [0 for _ in range(NUM_CLASSES)]\n total_correct_class = [0 for _ in range(NUM_CLASSES)]\n iou2ds_sum = 0\n iou3ds_sum = 0\n iou3d_correct_cnt = 0\n iou3d_correct_cnt_old = 0\n iou3d_correct_cnt_05=0\n # E: This is necessary to collect features of batches before the evaluation\n if tracks:\n for batch_idx in range(int(num_batches)):\n start_idx = batch_idx * BATCH_SIZE\n end_idx = (batch_idx + 1) * BATCH_SIZE\n # E: Get also batch_indices which shows the (world_id,frame_id,track_id) of the objects in the batch\n # E: Batch indices are valid (non-empty) only if the tracks flag is True\n batch_data, batch_label, batch_center, \\\n batch_hclass, batch_hres, \\\n batch_sclass, batch_sres, \\\n batch_rot_angle, batch_one_hot_vec, batch_indices = \\\n get_batch(TEST_DATASET, test_idxs, start_idx, end_idx,\n NUM_POINT, NUM_CHANNEL,tracks=tracks)\n\n # Emec added the feature line\n # E: Get the features at the prev time steps of the objects in the batch\n batch_feat_lstm = get_batch_features(TEST_DATASET.feature_dict,\n batch_wft=batch_indices,tau=lstm_params['tau'],\n feat_len=lstm_params['feat_vec_len'],rev_order=True)\n # E: Get the number of tracks at the tau prev. time steps for each object in the batch: How many of the tau-1 frames before the current frames of the objects contain the same object with the same track id \n batch_seq_len = batch_track_num(feature_dict=TEST_DATASET.feature_dict,wfts=batch_indices)\n\n feed_dict = {ops['pointclouds_pl']: batch_data,\n ops['one_hot_vec_pl']: batch_one_hot_vec,\n ops['labels_pl']: batch_label,\n ops['centers_pl']: batch_center,\n ops['heading_class_label_pl']: batch_hclass,\n ops['heading_residual_label_pl']: batch_hres,\n ops['size_class_label_pl']: batch_sclass,\n ops['size_residual_label_pl']: batch_sres,\n ops['is_training_pl']: is_training,\n ops['end_points']['lstm_layer']['feat_input']:batch_feat_lstm,\n ops['end_points']['lstm_layer']['pf_seq_len']:batch_seq_len}\n '''\n summary, step, loss_val, logits_val, iou2ds, iou3ds, box_est_feature_vec = \\\n sess.run([ops['merged'], ops['step'],\n ops['loss'], ops['logits'],\n ops['end_points']['iou2ds'], ops['end_points']['iou3ds'],\n ops['end_points']['box_est_feature_vec']],\n feed_dict=feed_dict)\n '''\n box_est_feature_vec = \\\n sess.run(ops['end_points']['box_est_feature_vec'],\n feed_dict=feed_dict)\n \n update_batch_features(feature_dict=TEST_DATASET.feature_dict,batch_wft=batch_indices,\n batch_feat_vecs=box_est_feature_vec)\n\n # Simple evaluation with batches\n for batch_id in range(int(num_batches)):\n start_idx = batch_id * BATCH_SIZE\n end_idx = (batch_id + 1) * BATCH_SIZE\n # E: Get also batch_indices which shows the (world_id,frame_id,track_id) of the objects in the batch\n # E: Batch indices are valid (non-empty) only if the tracks flag is True\n batch_data, batch_label, batch_center, \\\n batch_hclass, batch_hres, \\\n batch_sclass, batch_sres, \\\n batch_rot_angle, batch_one_hot_vec, batch_indices = \\\n get_batch(TEST_DATASET, test_idxs, start_idx, end_idx,\n NUM_POINT, NUM_CHANNEL,tracks=tracks)\n \n if tracks:\n # Emec added the feature line\n # E: Get the features at the prev time steps of the objects in the batch\n batch_feat_lstm = get_batch_features(TEST_DATASET.feature_dict,\n batch_wft=batch_indices,tau=lstm_params['tau'],\n feat_len=lstm_params['feat_vec_len'],rev_order=True)\n # E: Get the number of tracks at the tau prev. time steps for each object in the batch: How many of the tau-1 frames before the current frames of the objects contain the same object with the same track id \n batch_seq_len = batch_track_num(feature_dict=TEST_DATASET.feature_dict,wfts=batch_indices)\n \n feed_dict = {ops['pointclouds_pl']: batch_data,\n ops['one_hot_vec_pl']: batch_one_hot_vec,\n ops['labels_pl']: batch_label,\n ops['centers_pl']: batch_center,\n ops['heading_class_label_pl']: batch_hclass,\n ops['heading_residual_label_pl']: batch_hres,\n ops['size_class_label_pl']: batch_sclass,\n ops['size_residual_label_pl']: batch_sres,\n ops['is_training_pl']: is_training,\n ops['end_points']['lstm_layer']['feat_input']:batch_feat_lstm,\n ops['end_points']['lstm_layer']['pf_seq_len']:batch_seq_len}\n \n summary, step, loss_val, logits_val, iou2ds, iou3ds, box_est_feature_vec = \\\n sess.run([ops['merged'], ops['step'],\n ops['loss'], ops['logits'],\n ops['end_points']['iou2ds'], ops['end_points']['iou3ds'],\n ops['end_points']['box_est_feature_vec']],\n feed_dict=feed_dict)\n \n update_batch_features(feature_dict=TEST_DATASET.feature_dict,batch_wft=batch_indices,\n batch_feat_vecs=box_est_feature_vec)\n else:\n feed_dict = {ops['pointclouds_pl']: batch_data,\n ops['one_hot_vec_pl']: batch_one_hot_vec,\n ops['labels_pl']: batch_label,\n ops['centers_pl']: batch_center,\n ops['heading_class_label_pl']: batch_hclass,\n ops['heading_residual_label_pl']: batch_hres,\n ops['size_class_label_pl']: batch_sclass,\n ops['size_residual_label_pl']: batch_sres,\n ops['is_training_pl']: is_training}\n \n summary, step, loss_val, logits_val, iou2ds, iou3ds = \\\n sess.run([ops['merged'], ops['step'],\n ops['loss'], ops['logits'],\n ops['end_points']['iou2ds'], ops['end_points']['iou3ds']],\n feed_dict=feed_dict)\n test_writer.add_summary(summary, step+batch_id)\n\n preds_val = np.argmax(logits_val, 2)\n correct = np.sum(preds_val == batch_label)\n total_correct += correct\n total_seen += (BATCH_SIZE * NUM_POINT)\n loss_sum += loss_val\n for l in range(NUM_CLASSES):\n total_seen_class[l] += np.sum(batch_label == l)\n total_correct_class[l] += (np.sum((preds_val == l) & (batch_label == l)))\n iou2ds_sum += np.sum(iou2ds)\n iou3ds_sum += np.nansum(iou3ds)\n #IPython.embed()\n iou3d_correct_cnt_old += np.sum(iou3ds >= 0.7)\n #iou3d_correct_cnt += np.sum(iou3ds >= 0.7)\n # class specific IoU-based accuracy calculation\n cl = np.argmax(batch_one_hot_vec,axis=1)\n cl_ids = list(set(cl))\n for _cl in cl_ids:\n cl_iou3ds = iou3ds[np.where(cl==_cl)]\n if _cl == 0:\n iou3d_correct_cnt += np.sum(cl_iou3ds>=0.7)\n else:\n iou3d_correct_cnt += np.sum(cl_iou3ds>=0.5)\n \n iou3d_correct_cnt_05 += np.sum(iou3ds >= 0.5)\n for i in range(BATCH_SIZE):\n segp = preds_val[i, :]\n segl = batch_label[i, :]\n part_ious = [0.0 for _ in range(NUM_CLASSES)]\n for l in range(NUM_CLASSES):\n if (np.sum(segl == l) == 0) and (np.sum(segp == l) == 0):\n part_ious[l] = 1.0 # class not present\n else:\n part_ious[l] = np.sum((segl == l) & (segp == l)) / \\\n float(np.sum((segl == l) | (segp == l)))\n \n log_string('eval mean loss: %f' % (loss_sum / float(num_batches)))\n log_string('eval segmentation accuracy: %f' % \\\n (total_correct / float(total_seen)))\n log_string('eval segmentation avg class acc: %f' % \\\n (np.mean(np.array(total_correct_class) / \\\n np.array(total_seen_class, dtype=np.float))))\n log_string('eval box IoU (ground/3D): %f / %f' % \\\n (iou2ds_sum / float(num_batches * BATCH_SIZE), iou3ds_sum / \\\n float(num_batches * BATCH_SIZE)))\n log_string('eval box estimation accuracy (IoU=0.7&0.5): %f' % \\\n (float(iou3d_correct_cnt) / float(num_batches * BATCH_SIZE)))\n log_string('eval box estimation accuracy (IoU=0.7): %f' % \\\n (float(iou3d_correct_cnt_old) / float(num_batches * BATCH_SIZE)))\n log_string('eval box estimation accuracy (IoU=0.5): %f' % \\\n (float(iou3d_correct_cnt_05) / float(num_batches * BATCH_SIZE)))\n\n EPOCH_CNT += 1\n eval_box_est_acc = float(iou3d_correct_cnt_old) / float(num_batches * BATCH_SIZE)\n return eval_box_est_acc", "def _run_evaluation(self) -> None:", "def _evaluate_once(checkpoint_path,\n master='',\n scaffold=None,\n eval_ops=None,\n feed_dict=None,\n final_ops=None,\n final_ops_feed_dict=None,\n hooks=None,\n config=None):\n eval_step = _get_or_create_eval_step()\n\n # Prepare the run hooks.\n hooks = list(hooks or [])\n\n if eval_ops is not None:\n if any(isinstance(h, _MultiStepStopAfterNEvalsHook) for h in hooks):\n steps_per_run_variable = \\\n basic_session_run_hooks.get_or_create_steps_per_run_variable()\n update_eval_step = state_ops.assign_add(\n eval_step,\n math_ops.cast(steps_per_run_variable, dtype=eval_step.dtype),\n use_locking=True)\n else:\n update_eval_step = state_ops.assign_add(eval_step, 1, use_locking=True)\n\n if isinstance(eval_ops, dict):\n eval_ops['update_eval_step'] = update_eval_step\n elif isinstance(eval_ops, (tuple, list)):\n eval_ops = list(eval_ops) + [update_eval_step]\n else:\n eval_ops = [eval_ops, update_eval_step]\n\n eval_step_value = _get_latest_eval_step_value(eval_ops)\n\n for h in hooks:\n if isinstance(h, (_StopAfterNEvalsHook, _MultiStepStopAfterNEvalsHook)):\n h._set_evals_completed_tensor(eval_step_value) # pylint: disable=protected-access\n\n logging.info('Starting evaluation at ' +\n time.strftime('%Y-%m-%dT%H:%M:%S', time.localtime()))\n start = time.time()\n # Prepare the session creator.\n session_creator = monitored_session.ChiefSessionCreator(\n scaffold=scaffold,\n checkpoint_filename_with_path=checkpoint_path,\n master=master,\n config=config)\n\n final_ops_hook = basic_session_run_hooks.FinalOpsHook(final_ops,\n final_ops_feed_dict)\n hooks.append(final_ops_hook)\n\n with monitored_session.MonitoredSession(\n session_creator=session_creator, hooks=hooks) as session:\n if eval_ops is not None:\n while not session.should_stop():\n session.run(eval_ops, feed_dict)\n logging.info('Inference Time : {:0.5f}s'.format(time.time() - start))\n\n logging.info('Finished evaluation at ' +\n time.strftime('%Y-%m-%d-%H:%M:%S', time.localtime()))\n return final_ops_hook.final_ops_values", "def repeated_checkpoint_run(self):\n\n if not os.path.exists(self.checkpoint_dir):\n raise ValueError('{} must have at least one checkpoint entry.'\n .format(self.checkpoint_dir))\n\n # Copy kitti native eval code into the predictions folder\n if self.do_kitti_native_eval:\n evaluator_utils.copy_kitti_native_code(\n self.model_config.checkpoint_name)\n\n if self.skip_evaluated_checkpoints:\n already_evaluated_ckpts = self.get_evaluated_ckpts()\n tf.logging.info(\n 'Starting evaluation at ' +\n time.strftime(\n '%Y-%m-%d-%H:%M:%S',\n time.gmtime()))\n\n last_checkpoint_id = -1\n number_of_evaluations = 0\n while True:\n # Load current checkpoints available\n trainer_utils.load_checkpoints(self.checkpoint_dir,\n self._saver)\n num_checkpoints = len(self._saver.last_checkpoints)\n\n start = time.time()\n\n if number_of_evaluations >= num_checkpoints:\n tf.logging.info('No new checkpoints found in %s.'\n 'Will try again in %d seconds',\n self.checkpoint_dir,\n self.eval_wait_interval)\n else:\n for ckpt_idx in range(num_checkpoints):\n checkpoint_to_restore = \\\n self._saver.last_checkpoints[ckpt_idx]\n ckpt_id = evaluator_utils.strip_checkpoint_id(\n checkpoint_to_restore)\n\n # Check if checkpoint has been evaluated already\n already_evaluated = ckpt_id in already_evaluated_ckpts\n if already_evaluated or ckpt_id <= last_checkpoint_id:\n number_of_evaluations = max((ckpt_idx + 1,\n number_of_evaluations))\n continue\n\n self.run_checkpoint_once(checkpoint_to_restore)\n number_of_evaluations += 1\n\n # Save the id of the latest evaluated checkpoint\n last_checkpoint_id = ckpt_id\n\n time_to_next_eval = start + self.eval_wait_interval - time.time()\n if time_to_next_eval > 0:\n time.sleep(time_to_next_eval)", "def run_eval_step(self, sess, batch):\n feed_dict = self._make_feed_dict(batch)\n to_return = {\n 'summaries': self._summaries,\n 'loss': self._loss,\n 'global_step': self.global_step,\n }\n if self._hps.coverage:\n to_return['coverage_loss'] = self._coverage_loss\n return sess.run(to_return, feed_dict)", "def train_one_epoch(self):\n loss, n = 0, 0\n for x, y in self.train_dl:\n y_hat = self.model.forward(x)\n batch_loss = self.model.criterion.forward(y_hat, y).sum()\n self.model.backward()\n self.optimizer.step()\n loss += batch_loss\n n += len(y)\n return loss / n", "def _train_one_epoch(self) -> float:\n if self._cameras is None:\n raise TypeError('The camera should be a PinholeCamera. Gotcha None. You init the training before train?')\n\n ray_dataset = RayDataset(\n self._cameras, self._min_depth, self._max_depth, self._ndc, device=self._device, dtype=self._dtype\n )\n\n if isinstance(self._num_img_rays, int):\n raise TypeError(\n 'The number of images of Ray should be a tensor. Gotcha an integer. You init the training before train?'\n )\n ray_dataset.init_ray_dataset(self._num_img_rays)\n\n if self._imgs is None:\n raise TypeError('Invalid image list object')\n ray_dataset.init_images_for_training(self._imgs) # FIXME: Do we need to load the same images on each Epoch?\n\n ray_data_loader = instantiate_ray_dataloader(ray_dataset, self._batch_size, shuffle=True)\n total_psnr = tensor(0.0, device=self._device, dtype=self._dtype)\n for i_batch, (origins, directions, rgbs) in enumerate(ray_data_loader):\n rgbs_model = self._nerf_model(origins, directions)\n loss = F.mse_loss(rgbs_model, rgbs)\n\n total_psnr = psnr(rgbs_model, rgbs, 1.0) + total_psnr\n\n self._opt_nerf.zero_grad()\n loss.backward()\n self._opt_nerf.step()\n return float(total_psnr / (i_batch + 1))", "def evaluate_once(checkpoint_path,\n master='',\n scaffold=None,\n eval_ops=None,\n feed_dict=None,\n final_ops=None,\n final_ops_feed_dict=None,\n hooks=None,\n config=None):\n eval_step = get_or_create_eval_step()\n\n # Prepare the run hooks.\n hooks = list(hooks or [])\n\n if eval_ops is not None:\n if any(isinstance(h, MultiStepStopAfterNEvalsHook) for h in hooks):\n steps_per_run_variable = \\\n basic_session_run_hooks.get_or_create_steps_per_run_variable()\n update_eval_step = tf.compat.v1.assign_add(\n eval_step,\n tf.cast(steps_per_run_variable, dtype=eval_step.dtype),\n use_locking=True)\n else:\n update_eval_step = tf.compat.v1.assign_add(eval_step, 1, use_locking=True)\n\n if isinstance(eval_ops, dict):\n eval_ops['update_eval_step'] = update_eval_step\n elif isinstance(eval_ops, (tuple, list)):\n eval_ops = list(eval_ops) + [update_eval_step]\n else:\n eval_ops = [eval_ops, update_eval_step]\n\n eval_step_value = get_latest_eval_step_value(eval_ops)\n\n for h in hooks:\n if isinstance(h, (StopAfterNEvalsHook, MultiStepStopAfterNEvalsHook)):\n h._set_evals_completed_tensor(eval_step_value) # pylint: disable=protected-access\n\n tf.compat.v1.logging.info(\n 'Starting evaluation at ' +\n time.strftime('%Y-%m-%dT%H:%M:%SZ', time.localtime()))\n\n # Prepare the session creator.\n session_creator = tf.compat.v1.train.ChiefSessionCreator(\n scaffold=scaffold,\n checkpoint_filename_with_path=checkpoint_path,\n master=master,\n config=config)\n\n final_ops_hook = tf_estimator.FinalOpsHook(final_ops, final_ops_feed_dict)\n hooks.append(final_ops_hook)\n\n with tf.compat.v1.train.MonitoredSession(\n session_creator=session_creator, hooks=hooks) as session:\n if eval_ops is not None:\n while not session.should_stop():\n session.run(eval_ops, feed_dict)\n\n tf.compat.v1.logging.info(\n 'Finished evaluation at ' +\n time.strftime('%Y-%m-%d-%H:%M:%S', time.localtime()))\n return final_ops_hook.final_ops_values", "def run_eval_step(self, sess, batch):\n feed_dict = self._make_feed_dict(batch)\n to_return = {\n 'summaries': self._summaries,\n 'loss': self._loss,\n 'acc': self._acc,\n 'global_step': self.global_step,\n }\n return sess.run(to_return, feed_dict)", "def run_eval(self, num_episodes):\n for i in xrange(num_episodes):\n state = self.env.reset()\n total_reward = 0\n steps = 0\n done = False\n while not done:\n action = self.actor.action_given([state], add_noise=False)\n state, reward, done, _ = self.env.step(action)\n# print \"EVALSTEP r%s %s %s %s\" % (i, steps, np.linalg.norm(action), reward)\n total_reward += reward\n steps += 1\n print \"EVAL\", i, steps, total_reward\n self.env.reset() # just to flush logging, clumsy :/", "def eval(\n self,\n checkpoint_path: str,\n save_path = \"\"\n ) -> None:\n # * The evaluation code path has legacy code (and will not run).\n # * Evaluation / analysis is done in analysis scripts.\n self.logger.info(f\"Starting evaluation\")\n\n self.load_device()\n self.masker = Masker(self.config.TRAIN, self.device)\n\n # Not using a generator atm because we can fit the whole set onto GPU\n test_set = SpikesDataset(self.config, self.config.DATA.TEST_FILENAME, mode=\"test\", logger=self.logger)\n self.logger.info(f\"Evaluating on {len(test_set)} samples.\")\n\n train_cfg = self.config.TRAIN\n ckpt_dict = self.load_checkpoint(checkpoint_path, map_location=\"cpu\")\n assert test_set.get_num_neurons() == self.num_neurons # Compatibility check\n update = ckpt_dict[\"extra_state\"][\"update\"]\n test_set.clip_spikes(self.max_spikes)\n self.model.eval()\n\n with TensorboardWriter(\n self.config.TENSORBOARD_DIR, flush_secs=self.flush_secs\n ) as writer:\n with torch.no_grad():\n spikes, rates, heldout_spikes, forward_spikes = test_set.get_dataset()\n spikes = spikes.to(self.device)\n rates = rates.to(self.device)\n if test_set.has_heldout:\n heldout_spikes = heldout_spikes.to(self.device)\n forward_spikes = forward_spikes.to(self.device)\n else:\n heldout_spikes = None\n forward_spikes = None\n masked_spikes, labels = self.masker.mask_batch(\n spikes,\n train_cfg,\n max_spikes=self.max_spikes,\n should_mask=is_input_masked_model(self.config.MODEL.NAME),\n heldout_spikes=heldout_spikes,\n forward_spikes=forward_spikes\n )\n loss, pred_rates, *_ = self.model(masked_spikes, mask_labels=labels)\n test_loss = loss.mean()\n\n writer.add_scalar(\n \"test_loss\",\n test_loss,\n update,\n )\n\n # Ideally we could do this just on masked areas\n selected_mask = labels != UNMASKED_LABEL\n masked_rates = torch.masked_select(rates, selected_mask).cpu()\n masked_pred_rates = torch.masked_select(pred_rates, selected_mask).cpu()\n r2 = r2_score(masked_rates, masked_pred_rates, multioutput='uniform_average')\n writer.add_scalar(\"test_r2\", r2, update)\n self.logger.queue_stat(\"test r2\", r2)\n\n self.logger.queue_stat(\"test loss\", test_loss.item())\n\n stat_str = \"\\t\".join([f\"{stat[0]}: {stat[1]:.3f}\" for stat in self.logger.empty_queue()])\n self.logger.info(\"update: {}\\t{}\".format(update, stat_str))", "def run_eval(self, filename):\n load_sess = self.sess\n preds = []\n labels = []\n for batch_data_input in self.iterator.load_data_from_file(filename):\n _, _, step_pred, step_labels = self.eval(load_sess, batch_data_input)\n preds.extend(np.reshape(step_pred, -1))\n labels.extend(np.reshape(step_labels, -1))\n res = cal_metric(labels, preds, self.hparams.metrics)\n return res", "def on_eval_epoch_end(self, state: State) -> None:\n pass", "def evaluate_validation(self):\n self.model.eval()\n\n val_loss = 0.0\n val_losses = []\n val_accuracies = []\n\n with torch.no_grad():\n for data in self.val_set:\n X, labels = data[0].to(self.device), data[1].to(self.device)\n\n outputs = self.model(X)\n loss = self.loss_function(outputs, labels)\n val_losses.append(loss.item())\n val_accuracies.append(self.accuracy(outputs, labels))\n val_loss += loss.item()\n\n self.val_loss.append(np.mean(val_losses))\n self.val_accuracy.append(np.mean(val_accuracies))\n\n print('Validation loss %.3f' % (val_loss / len(self.val_set)))\n\n self.model.train()", "def validateAndLog(train_engine,eval_engine,test_loader,train_writer,test_writer):\n eval_engine.run(test_loader,1)\n epoch = train_engine.state.epoch\n logResults(train_engine,epoch,train_writer)\n logResults(eval_engine,epoch,test_writer)", "def incremental_train_eval(\n trainer, start_time_index, end_time_index, input_dir, training_args, data_args\n):\n results_over_time = {}\n for time_index in range(start_time_index, end_time_index):\n # 1. Set data\n time_index_train = time_index\n time_index_eval = time_index + 1\n train_paths = glob.glob(\n os.path.join(\n input_dir,\n str(time_index_train).zfill(data_args.time_window_folder_pad_digits),\n \"train.parquet\",\n )\n )\n eval_paths = glob.glob(\n os.path.join(\n input_dir,\n str(time_index_eval).zfill(data_args.time_window_folder_pad_digits),\n \"test.parquet\" if training_args.eval_on_test_set else \"valid.parquet\",\n )\n )\n\n # 2. Train on train data of time_index\n if training_args.do_train:\n print(\"\\n***** Launch training for day %s: *****\" % time_index)\n trainer.train_dataset_or_path = train_paths\n trainer.reset_lr_scheduler()\n trainer.train()\n\n if training_args.do_eval:\n\n # 3. Evaluate on train data of time_index\n trainer.eval_dataset_or_path = train_paths\n train_metrics = trainer.evaluate(metric_key_prefix=\"train\")\n print(\"\\n***** Evaluation results for day %s (train set):*****\\n\" % time_index_eval)\n print(train_metrics)\n\n log_metric_results(\n training_args.output_dir,\n train_metrics,\n prefix=\"train\",\n time_index=time_index_eval,\n )\n\n # free GPU for next day training\n wipe_memory()\n\n # 4. Evaluate on valid/test data of time_index+1\n trainer.eval_dataset_or_path = eval_paths\n eval_metrics = trainer.evaluate(metric_key_prefix=\"eval\")\n print(\"\\n***** Evaluation results for day %s (eval set):*****\\n\" % time_index_eval)\n print(eval_metrics)\n\n log_metric_results(\n training_args.output_dir,\n eval_metrics,\n prefix=\"eval\",\n time_index=time_index_eval,\n )\n\n # free GPU for next day training\n wipe_memory()\n\n results_over_time[time_index_eval] = {\n **eval_metrics,\n **train_metrics,\n }\n\n return results_over_time", "def prepare_next_epoch(self, model, data, sess, epoch):\n raise NotImplementedError()", "def pre_epoch(self):\n pass" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Private method that changes the value into baseline type (chooses between int and float).
def __set_value_type(self, baseline, value): if ( isinstance(baseline, int | numpy.int32 | numpy.int64) ): return round(value) if isinstance(baseline, float): return float(value) return None
[ "def record(self, value: typing.Union[float, int]) -> None:", "def test__get_value_types_float(self):\n value, m_type = formatters._get_value_types(1.1)\n assert value == 1.1\n assert m_type == 'float'", "def setGenericFloat(*args, **kwargs):\n \n pass", "def _set_float(self, param, value, index):\n if type(value) == float or value == 0:\n self.data[param][index] = value\n elif type(value) == int:\n self.data[param][index] = value\n print('Warning: {} was read from the base file as a float.'.format(param))\n else:\n raise ValueError('{0} must be type float. No update made.'.format(param))", "def _set_types(self):\n # If we given something that is not an int or a float we raise\n # a RuntimeError as we do not want to have to guess if the given\n # input should be interpreted as an int or a float, for example the\n # interpretation of the string \"1\" vs the interpretation of the string\n # \"1.0\".\n for c in (self.x, self.y, self.z):\n if not (isinstance(c, int) or isinstance(c, float)):\n raise(RuntimeError('x, y coords should be int or float'))\n\n if (isinstance(self.x, int)\n and isinstance(self.y, int) and isinstance(self.z, int)):\n self._dtype = \"int\"\n else:\n # At least one value is a float so promote both to float.\n self.x = float(self.x)\n self.y = float(self.y)\n self.z = float(self.z)\n self._dtype = \"float\"", "def _set_types(self):\n # If we given something that is not an int or a float we raise\n # a RuntimeError as we do not want to have to guess if the given\n # input should be interpreted as an int or a float, for example the\n # interpretation of the string \"1\" vs the interpretation of the string\n # \"1.0\".\n for c in (self.x, self.y):\n if not (isinstance(c, int) or isinstance(c, float)):\n raise(RuntimeError('x, y coords should be int or float'))\n\n if isinstance(self.x, int) and isinstance(self.y, int):\n self._dtype = \"int\"\n else:\n # At least one value is a float so promote both to float.\n self.x = float(self.x)\n self.y = float(self.y)\n self._dtype = \"float\"", "def asGenericFloat(*args, **kwargs):\n \n pass", "def _cast_type(self, value, obj=None):\n return value", "def _check_intable(f):\n if(_is_int(f)):\n return(int(float(f)))\n else:\n return(float(f))", "def _type_cast(item: str) -> Union[int, float, str]:\n try:\n i = int(item)\n return i\n except (TypeError, ValueError):\n pass\n try:\n f = float(item)\n return f\n except (TypeError, ValueError):\n pass\n return item", "def __is_int_or_float(self,val):\n if isinstance(val,int) or isinstance(val,float):\n return True\n else:\n return False", "def test_univGroupsFromFloats(self):\n self.setAs(float)\n self._tester()", "def convert(self, value, param, ctx):\n if isinstance(value, str):\n if value.lower() == 'none':\n return None\n else:\n try:\n value = float(value)\n except ValueError:\n pass\n return value\n else:\n self.fail('Cannot recognize str or float type: {} {}'\n .format(value, type(value)), param, ctx)", "def dtype(self, value):\n value = np.dtype(value)\n if value.kind not in \"iuf\":\n raise RuntimeError(\"Unsupported dtype. Only integer/floating-point types are supported.\")\n ok = False\n if np.issubdtype(value, np.integer):\n if np.issubdtype(self.dtype, np.integer):\n ok = True\n elif np.array_equal(self._frequencies, self._errors2):\n ok = True\n elif np.issubdtype(value, np.float):\n ok = True\n if ok:\n self._dtype = value\n self._frequencies = self._frequencies.astype(value)\n self._errors2 = self._errors2.astype(value)\n self._missed = self._missed.astype(value)\n # TODO: Overflows and underflows and stuff...\n else:\n raise RuntimeError(\"Cannot change histogram dtype.\")", "def test_adjust_float_keyval(self):\n self.setting.value = u\"2.1\"\n self.setting.adjust_value_to_type(\"keyval list\")\n self.assertEqual(self.setting.value, 2.1)\n self.assert_(isinstance(self.setting.value, float))", "def set2Float(*args, **kwargs):\n \n pass", "def adjust(self, p_float, p_float_1, p_float_2, p_float_3): # real signature unknown; restored from __doc__\n pass", "def CheckNumericalTypes(*baseType):\n\tbReturn=None\n\tfor b in baseType:\n\t\tif b is None:\n\t\t\tcontinue\n\t\telif b not in (BaseType.float,BaseType.integer):\n\t\t\traise core.ProcessingError(\"Numeric type required, found: %s\"%BaseType.EncodeValue(b))\n\t\telif bReturn is None:\n\t\t\tbReturn=b\n\t\telif b!=bReturn:\n\t\t\t# we only return integer when all values are of type integer, so we must return float!\n\t\t\tbReturn=BaseType.float\n\treturn bReturn", "def new_number_type(a, b):\n if isinstance(a, mt.TlFloat) or isinstance(b, mt.TlFloat):\n return mt.TlFloat\n else:\n return mt.TlInt" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function that lineary fills missing values, if the successive missing values are up to (max_seconds) apart.
def linear_fill_missing_values(self, activity, key, max_seconds=15): index = 0 count = len(activity[key]) while index < count: if activity[key][index] is None: to = self.__missing_from_to(activity[key], index) if to + 1 < len(activity[key]): time_between = ( activity['timestamps'][to] - activity['timestamps'][index] ).total_seconds() if ( to + 1 < count and index - 1 > 0 and time_between <= max_seconds ): starting_value = activity[key][index - 1] ending_value = activity[key][to] denominator = (to + 1) - (index - 1) - 1 numerator = 1 id = 0 for _i in activity[key][index:to]: value = None try: value = starting_value * ( (denominator - numerator) / denominator ) + ending_value * (numerator / denominator) value = self.__set_value_type( activity[key][index - 1], value, ) except Exception as e: print(str(e)) activity[key][index + id] = value numerator += 1 id += 1 index = to index += 1
[ "def fill_nan(train_raw):\n return train_raw.fillna(method='ffill')", "def gap_filling(data,NoDataValue):\n\t \n # fill the no data values\n if NoDataValue is np.nan:\n mask = ~(np.isnan(data))\n else:\n mask = ~(data==NoDataValue)\n xx, yy = np.meshgrid(np.arange(data.shape[1]), np.arange(data.shape[0]))\n xym = np.vstack( (np.ravel(xx[mask]), np.ravel(yy[mask])) ).T\n data0 = np.ravel( data[:,:][mask] )\n interp0 = scipy.interpolate.NearestNDInterpolator( xym, data0 )\n data_end = interp0(np.ravel(xx), np.ravel(yy)).reshape( xx.shape )\n\t\t\n return (data_end)", "def fill_with_lin(df):\n df = df.fillna(df.interpolate(method=\"linear\"))\n assert df.count().min() >= len(df) - 1\n # fill the first item with second item\n return df.fillna(df.iloc[1])", "def test_fill_null_values_last(self):\n data.fill_null_values(self._fillna_df, data.FillMethod.REPEAT_LAST)\n testing.assert_allclose(\n np.transpose(\n [[1, 2, 2, 4, 5, 6, 7, 8, 9, 9, 11, 12],\n [3, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 12]]), self._fillna_df)", "def fill_gaps(df):\n idx = pd.period_range(df.index.min(), df.index.max(), freq=\"D\")\n # idx_forecast = pd.period_range(start_datetime, end_datetime, freq=\"H\")\n ts = pd.DataFrame({\"empty\": [0 for i in range(idx.shape[0])]}, index=idx)\n ts = ts.to_timestamp()\n df_filled = pd.concat([df, ts], axis=1)\n del df_filled[\"empty\"]\n return df_filled", "def shift_and_fill(self, periods: int, fill_value: int | pli.Expr) -> Series:", "def fill_blanks(tdict):\n for idx in tdict['mis_vals']:\n y_id = idx % YLEN\n mu = tdict['laer_yavg'][y_id]\n sigma = tdict['laer_ystd'][y_id]\n tdict['laer_days'][idx] = np.random.normal(mu, sigma / 2.)\n del(tdict['mis_vals'])\n del(tdict['laer_ystd'])\n return tdict", "def _fill_last(self, v) :\n import pandas as pd \n df=pd.DataFrame(v)\n df.fillna(method='ffill',inplace=True)\n df.fillna(method='bfill',inplace=True)", "def fillNA(data):\r\n\r\n return data.fillna(method='ffill').fillna(method='bfill').fillna(1.0)", "def fill_missing_values(df_data): \n df_data.fillna(method=\"ffill\", inplace=\"True\")\n df_data.fillna(method='bfill', inplace=\"True\")", "def fill_nan(self, fill_value: int | float | pli.Expr | None) -> Series:", "def fill_gaps(self):\n frame_gaps, time_gaps = self.get_frame_gaps()\n max_skip_index = int(np.nanargmax(time_gaps))\n n = frame_gaps[max_skip_index]\n if n == 0:\n return\n if n > 10:\n raise ValueError(\n f\"Large gap of {n} frames at \"\n f\"index {self.frames.fixed_index[max_skip_index]}, \"\n f\"MJD: {self.frames.mjd[max_skip_index]}\")\n\n add_frames = np.clip(frame_gaps, 0, None)\n log.debug(f\"Padding with {add_frames.sum()} empty frames.\")\n\n insert_at = np.nonzero(add_frames)[0]\n insert_indices = []\n for ii in insert_at:\n insert_indices.extend([ii] * add_frames[ii])\n\n insert_indices = np.asarray(insert_indices, dtype=int)\n self.frames.insert_blanks(insert_indices)\n\n # Add bad MJDs so no further blanks are inserted\n inserted_indices = insert_indices + np.arange(insert_indices.size)\n self.frames.mjd[inserted_indices] = np.nan\n self.reindex()", "def interpolate_by_average(self, data, missing_values):\n for column, set in enumerate(missing_values):\n for index in set:\n # looking for indexes of entries with available data, which will be a base for interpolation\n lower_index = -1\n upper_index = 9999\n\n for j in range(index - 24, -1, -24):\n if j not in set:\n lower_index = j\n break\n\n for j in range(index + 24, len(data), 24):\n if j not in set:\n upper_index = j\n break\n\n # set consists all of missing values\n if lower_index == -1 and upper_index == 9999:\n break\n\n # missing values at the start of set\n # new value is equal to the next non-missing value (24h gap)\n elif lower_index == -1 and upper_index != 9999:\n data[index][column] = data[upper_index][column]\n\n # missing values at the end of the set\n # new value is equal to the last non-missing value (24h gap)\n elif lower_index != -1 and upper_index == 9999:\n data[index][column] = data[lower_index][column]\n\n # missing values in the middle of the set\n else:\n data[index][column] = (float(data[upper_index][column]) + float(data[lower_index][column])) / 2", "def temporal_fill_func(sub_array, sub_i_array, block_mask, fill_method='linear'):\n # Skip block if array is all nodata\n if not np.any(block_mask):\n return sub_array\n # Skip block if array is all nodata\n # elif np.all(np.isnan(data_array)):\n # return sub_array\n\n # Begin interpolating scene days with missing values\n # for interp_i, interp_doy in enumerate(sub_i_array):\n for interp_sub_i, interp_full_i in enumerate(sub_i_array):\n # Interp mask is False where pixels have data\n # (i.e. True for pixels that will be interpolated)\n interp_mask = np.isnan(sub_array[interp_sub_i, :, :])\n interp_mask &= block_mask\n if not np.any(interp_mask):\n continue\n # logging.info(' INTERP {} {}'.format(\n # interp_sub_i, interp_full_i))\n\n # list of subsequent days\n for anchor_sub_i, anchor_full_i in enumerate(sub_i_array):\n if anchor_sub_i <= interp_sub_i:\n continue\n # Interpolate when next DOY has data\n anchor_mask = np.copy(interp_mask)\n anchor_mask &= np.isfinite(sub_array[anchor_sub_i, :, :])\n if not np.any(anchor_mask):\n continue\n # logging.info(' ANCHOR {} {}'.format(\n # anchor_sub_i, anchor_full_i))\n if fill_method == 'cubicspline':\n for cubic_sub_i, cubic_full_i in enumerate(sub_i_array):\n if cubic_sub_i <= anchor_sub_i:\n continue\n cubic_mask = np.copy(anchor_mask)\n cubic_mask &= np.isfinite(sub_array[cubic_sub_i, :, :])\n if not np.any(cubic_mask):\n continue\n # logging.info(' CUBIC {} {}'.format(\n # cubic_sub_i, cubic_full_i))\n interp_i_array = np.array([\n sub_i_array[interp_sub_i-2], sub_i_array[interp_sub_i-1],\n sub_i_array[anchor_sub_i], sub_i_array[cubic_sub_i]])\n interp_i_mask = np.in1d(sub_i_array, interp_i_array)\n interp_array = sub_array[interp_i_mask, :, :][:, cubic_mask]\n f = interpolate.interp1d(\n interp_i_array, interp_array,\n axis=0, kind=3)\n sub_array[interp_sub_i, :, :][cubic_mask] = f(interp_full_i)\n # sub_array[interp_sub_i,:,:][anchor_mask] = f(interp_full_i).astype(np.float32)\n interp_mask[cubic_mask] = False\n anchor_mask[cubic_mask] = False\n del f, interp_i_array, interp_i_mask\n del cubic_mask, interp_array\n if not np.any(interp_mask):\n break\n elif fill_method == 'linear':\n interp_i_array = np.array(\n [sub_i_array[interp_sub_i-1], sub_i_array[anchor_sub_i]])\n interp_i_mask = np.in1d(sub_i_array, interp_i_array)\n interp_array = sub_array[interp_i_mask, :, :][:, anchor_mask]\n f = interpolate.interp1d(\n interp_i_array, interp_array, axis=0, kind=fill_method)\n sub_array[interp_sub_i, :, :][anchor_mask] = f(interp_full_i)\n # sub_array[interp_sub_i,:,:][anchor_mask] = f(interp_full_i).astype(np.float32)\n interp_mask[anchor_mask] = False\n del f, interp_i_array, interp_i_mask, interp_array\n if not np.any(interp_mask):\n break\n elif fill_method == 'nearest':\n pass\n # There is a memory leak with f/interp1d\n # gc.collect()\n del interp_mask\n return sub_array", "def fill_nas(data):\n data = data.where(~np.isinf(data)).fillna(np.nan)\n data = data.where(data < 1).fillna(np.nan)\n data = data.where(data > 0).fillna(np.nan)\n\n return data", "def gap_fill_temporal(rasterlist, outdir = False):\n\n #enforce the list of rasters to ensure it's sanitized\n rasterlist = core.enf_filelist(rasterlist)\n\n #create an empty list to store output arrays in\n arr_list = []\n\n #convert each raster in the input list to an array, and save its data to the list\n for i, raster in enumerate(rasterlist):\n item = rasterlist[i]\n item_arr = to_numpy(item)\n arr_list.append(item_arr[0].data)\n\n #convert the list to a numpy array\n arr_list = np.array(arr_list)\n\n #set the lists of ranges of values for each dimension of the output array\n xrange = range(0, np.shape(arr_list)[2])\n yrange = range(0, np.shape(arr_list)[1])\n zrange = range(0, np.shape(arr_list)[0])\n\n #pull out the first array to be edited\n new_arr = arr_list[0]\n\n #loop through each x, y value\n #if the first array's value at each location is \"Not A Number\",\n #attempt to fill it with the corresponding value from the next array\n #if no array has a corresponding value, it will be left as a \"nan\"\n for i in yrange:\n for j in xrange:\n if np.isnan(new_arr[i,j]) == True:\n x = 1\n while x <= zrange[-1]:\n if np.isnan(arr_list[x,i,j]) == False:\n new_arr[i,j] = arr_list[x,i,j]\n break\n x = x + 1\n\n #separate the filename from the first input array \n inname = os.path.splitext(rasterlist[0])[0]\n\n #create an output name\n if outdir:\n outdir = os.path.abspath(outdir)\n name = \"{0}_gapfilled.tif\".format(os.path.split(inname)[1])\n outname = os.path.join(outdir, name)\n else:\n outname = \"{0}_gapfilled.tif\".format(inname)\n\n #convert the edited array to a tiff\n from_numpy(new_arr, item_arr[1], outname, \"NoData\")\n\n return outname", "def clean_time (self):\n badrows=[] # List of bad rows indexes \n self.df['DATE']=pd.to_datetime(self.df['DATE'],format='%d/%m/%Y %H:%M:%S',errors='coerce') # Define the format of the date\n self.df['DATE'] = self.df['DATE'].interpolate().ffill().bfill() # Interpolate also the first and last lines with np.nan values if required\n for j in range(0,len(self.df.index)-2): # Test if a bad character is inserted in the date\n if self.df['DATE'].iloc[j] <= self.df['DATE'].iloc[j+1]: \n None\n else:\n if self.df['DATE'].iloc[j] <= self.df['DATE'].iloc[j+2]: \n badrows.append(j+1)\n else:\n badrows.append(j)\n for k in badrows:\n self.df['DATE'].iloc[k]=np.nan\n self.df['DATE'] = self.df['DATE'].interpolate().ffill().bfill() # Interpolate also the first and last lines with np.nan values if required\n self.df.set_index('DATE', inplace=True) # Put the DATA column as index column\n for i in range (0,len(self.df.index)-1):\n self.tdelta.append((self.df.index[i+1]-self.df.index[i]).total_seconds()) # Calculate the delay in second between two dates\n self.tdelta.append((self.df.index[-1]-self.df.index[-2]).total_seconds())\n self.df['TIMELAG'] = pd.Series(self.tdelta,index=self.df.index) \n return self.df", "def test_fill_null_values_daily(self):\n data.fill_null_values(self._fillna_df, data.FillMethod.REPEAT_DAILY)\n testing.assert_allclose(\n np.transpose(\n [[1, 2, 9, 4, 5, 6, 7, 8, 9, 4, 11, 12],\n [8, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 7]]), self._fillna_df)", "def fill_if_missing(df: pd.DataFrame, periodicity: int = 1) -> pd.DataFrame:\n if df.isnull().values.any():\n logger.info(\"Some values are NaN. They are being filled...\")\n df = custom_interpolate(df, periodicity)\n logger.info(\"...interpolation finished! No missing data left.\")\n else:\n logger.info(\"No missing data\")\n return df" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add group to pickUpQueue
def enqueueGroup(self, group): # Tell the group that it's enqueued group.enqueue(self.genTimeToPickUp()) # and store it on the vehicle self.pickUpQueue.append(group) self.occupancy += group.groupSize
[ "def pickUpGroup(self, group):\n\n self.pickUpQueue.remove(group)\n group.pickUp()\n self.groups.append(group)\n self.genHoldTime()", "def newGroup(self):\n self.appendJobGroup()\n self.currentGroup = self.groupInstance(subscription=self.subscription)\n map(lambda x: x.startGroup(self.currentGroup), self.generators)", "def appendJobGroup(self):\n\n if self.currentGroup:\n map(lambda x: x.finishGroup(self.currentGroup), self.generators)\n if self.currentGroup:\n self.jobGroups.append(self.currentGroup)\n self.currentGroup = None\n\n return", "def _additem(self):\n\n self.queue.put(self._genitem())", "def addgroup(self, func):\r\n return self._subscribe(\"addgroup\", func)", "def add_group(self, name):\n if self.in_group(name):\n # We're already in this group.\n return\n\n self.groups.append(Group.get_or_create(name=name))", "def add_to_group(self):\n self.simulator.devices['bulbs'].add(self)", "def test_group_append(self):\n original_group = Group.objects.create(name='waffle_group')\n Group.objects.create(name='append_group')\n flag = Flag.objects.create(name='test')\n flag.groups.add(original_group)\n flag.refresh_from_db()\n\n self.assertEqual(list(flag.groups.values_list('name', flat=True)),\n ['waffle_group'])\n\n call_command('waffle_flag', 'test', group=['append_group'],\n append=True)\n\n flag.refresh_from_db()\n self.assertEqual(list(flag.groups.values_list('name', flat=True)),\n ['waffle_group', 'append_group'])\n self.assertIsNone(flag.everyone)", "def create(self, group):\n self.request.mongo_connection.shinken.hostgroups.insert(\n group.as_dict()\n )", "def test_add_group(self):\n\t\tdraft = ReviewRequestDraft.create(self.review_request)\n\t\tdraft.summary = \"Test Summary\"\n\t\tdraft.target_groups.add(self.group)\n\t\tself._check_counters(total_outgoing=1, pending_outgoing=1)\n\t\tself.review_request.publish(self.user)\n\t\tself._check_counters(total_outgoing=1, pending_outgoing=1, total_incoming=1, group_incoming=1, starred_public=1)", "def push(queue, item):\n queue.append(item)", "def add_to_queue(self, data):\n self.registration_queue.put(data)", "def group_tracker(self, group, opp):\n if self.groupChanges is None:\n self.groupChanges = {}\n self.groupChanges[\"Added\"] = []\n\n if self.groupChanges is not None:\n if opp == \"add\":\n self.groupChanges[\"Added\"].append(group)", "def test_fusion_group_from_queue_two_groups():\n queue = [gates.X(0), gates.H(1),\n gates.RX(2, theta=0.1234).controlled_by(1),\n gates.H(2), gates.Y(1),\n gates.H(0)]\n fused_groups = fusion.FusionGroup.from_queue(queue)\n assert len(fused_groups) == 2\n group1, group2 = fused_groups\n assert group1.gates0 == [[queue[0], queue[5]]]\n assert group1.gates1 == [[queue[1]]]\n assert group1.two_qubit_gates == []\n assert group2.gates0 == [[], [queue[4]]]\n assert group2.gates1 == [[], [queue[3]]]\n assert group2.two_qubit_gates == [queue[2]]", "def add_job(self, job):\n if isinstance(job, BaseJob):\n if isinstance(job.GROUPS, list):\n for i, group in enumerate(job.GROUPS):\n if isinstance(group, str) and group == self.name:\n job.GROUPS[i] = self\n elif isinstance(job.GROUPS, str):\n job.GROUPS = [self]\n else:\n raise TypeError(\n f\"GROUPS of {type(job)} is {type(job.GROUPS)}\")\n\n self.jobs.append(job)\n else:\n raise TypeError(f\"Can not add {type(job)} as job to a group.\")", "def a_group(self):\n self.group_cache = {}\n self._insert = self._insert_group\n yield\n self._insert = self._insert_one\n self.data.append(self.group_cache)\n self.group_cache = None", "def push_to_queue(self):\n redis = self.redis_pool.get_connection()\n redis.publish(self.collection_name, self.worker_id)", "def _addRefereesGroup(self,group,refpool=None):\n # pokud byl predan refpool\n if refpool:\n self.refPool = refpool\n # priravim si refPool\n else:\n # TODO dopredu vypocist velikost ref pool\n self._initRefPool(group.referee_group,100)\n # df zapasy skupiny\n group_matches_df = self.tdo.DfTester._getGroupMatchesDf(group)\n # projdu zapasy skupiny\n for pitch in group_matches_df.columns:\n for match_ind in group_matches_df.index:\n match = group_matches_df.iloc[match_ind,pitch]\n if match:\n if not match.referee:\n # zkontrolujeme, zda tym muze piskat\n for refPool_index in range(len(self.refPool)):\n # TODO zbytecne prochazime cely pool, stacila by jedna obratka\n if self.tdo.DfTester._canPlaceTph(self.refPool[refPool_index],match_ind):\n match.referee = self.refPool.pop(refPool_index)\n match.save()\n break", "def enter_new_group(self):\n while True:\n inp_url_group = input(\"Please enter the 'URL' of the 'VK' group: \")\n last_part = self.last_part_url(inp_url_group)\n pars_gr = self.request_id_group(str(last_part))\n if pars_gr:\n resp_add_new_gr = self.request_db.add_new_group(last_part)\n if resp_add_new_gr:\n print('The new group was added successfully.')\n break\n print('Opps! This group already exists!')\n continue\n else:\n print('Opps! There is something wrong!')\n continue" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Move group from pickUpQueue to car
def pickUpGroup(self, group): self.pickUpQueue.remove(group) group.pickUp() self.groups.append(group) self.genHoldTime()
[ "def enqueueGroup(self, group):\n\n # Tell the group that it's enqueued\n group.enqueue(self.genTimeToPickUp())\n\n # and store it on the vehicle\n self.pickUpQueue.append(group)\n\n self.occupancy += group.groupSize", "def move_people(self):\n people = self.people.customer_queue\n people_lock = self.people.queue_lock\n window0 = self.window0.queue\n window1 = self.window1.queue\n queue_message = \"Customer {} has been put into {}'s queue\"\n\n while self.status:\n if len(people) is not 0:\n queue_message = \"Customer {} has been put into {}'s queue\"\n # CASE: Both window queues are full\n if window0.full() and window1.full():\n def waiting(customer):\n \"\"\"This is the waiting sequence for a customer who cannot be put into a queue right away\"\"\"\n clock = RealtimeEnvironment(initial_time=0, factor=speed, strict=False)\n customer.action() # Waiting for queue to open\n # Try to get into a queue every seconds\n for i in range(1, 20):\n clock.run(until=i)\n if not (window0.full and window1.full):\n customer.queue_action()\n customer.add_time(i)\n if window0.qsize() < window1.qsize():\n window0.put(customer)\n print(queue_message.format(customer.id, self.window0.id))\n else:\n window1.put(customer)\n print(queue_message.format(customer.id, self.window1.id))\n if not customer.in_window():\n # leave and put them back into the queue\n print(\"Customer {} has left and will try again later\".format(customer.id))\n customer.action() # Leaving the line\n customer.add_time(600)\n clock.run(until=620)\n people_lock.acquire()\n people.append(customer)\n\n customer.action() # Rejoining the line\n people_lock.release()\n print(\"Customer {} had rejoined the waiting list\".format(customer.id))\n\n # Leave permanently\n clock.run(until=660)\n people_lock.acquire()\n if not customer.in_window():\n customer.action() # Leaving Permanently\n customer.add_time(40)\n people.remove(customer)\n print(\"Customer {} has left permanently\".format(customer.id))\n people_lock.release()\n\n # Execute waiting sequence\n people_lock.acquire()\n if people:\n if people[0].in_window() is False and people[0].actions == 0:\n customer = people.pop(0)\n customer.action()\n people_lock.release()\n\n # Execute waiting sequence\n waiting = Thread(target=waiting, args=(customer,))\n waiting.start()\n clock = RealtimeEnvironment(initial_time=0, factor=speed, strict=False)\n clock.run(until=20)\n else:\n people_lock.release()\n else:\n people_lock.release()\n\n # CASE: There is available space in a window queue\n else:\n people_lock.acquire()\n customer = people.pop(0)\n customer.queue_action()\n people_lock.release()\n if window0.qsize() < window1.qsize():\n window0.put(customer)\n print(queue_message.format(customer.id, self.window0.id))\n else:\n window1.put(customer)\n print(queue_message.format(customer.id, self.window1.id))", "def move_group_forward(self, group):\n self._move_group_forward(group.encode())", "def pick_up(self, target):\r\n self.cur_plan.append('picking up target')\r\n self.plan += ['pick', target, 'back', target]\r\n self.plan_status = False\r\n self.run()", "def move_group_to_front(self, group):\n self._move_group_to_front(group.encode())", "def move_group_to_back(self, group):\n self._move_group_to_back(group.encode())", "def moveToGroup(self, group):\r\n if self.currentWindow and group:\r\n self.addGroup(group)\r\n self.currentWindow.togroup(group)", "def moveToGroup(self, group):\n if self.currentWindow and group:\n self.addGroup(group)\n self.currentWindow.togroup(group)", "def apply_cart_transfer_group(self, order):\n for card in self.cart_cards.all():\n card.update_transfer_group(order.transfer_group)\n card.save()", "def pick_up(self, pickup):\n pickup.delete()\n pickup.take_effect( self )", "def move(self, distance):\n for tile in self.group:\n tile.move_relative(distance, False)", "def newGroup(self):\n self.appendJobGroup()\n self.currentGroup = self.groupInstance(subscription=self.subscription)\n map(lambda x: x.startGroup(self.currentGroup), self.generators)", "def move_substructure(self):\n\n yield self.task(\"Move Substructure\", 8)", "def queue(position):\n global _playlist\n collection = get_collection()\n _playlist.append(collection[position])\n log.info(\"Adding : %s\" % collection[position])\n start_player()", "def pop(self, composer):\n\t\tif self.split > 1:\n\t\t\tfor firework in range(round(random.random()*75+75)):\n\t\t\t\tcomposer.add_firework(Firework(self.position.copy(), random.random()*5, random.random()*360, 20, '#', '~', 10, self.split - 1))\n\t\telif self.split > 0:\n\t\t\tfor firework in range(round(random.random()*50+50)):\n\t\t\t\tcomposer.add_firework(Firework(self.position.copy(), random.random()*5, random.random()*360, random.random()*15, '*', '.', 3, self.split - 1))\n\t\tcomposer.remove_firework(self)", "def queue_reposition(self, queue):\n bisect.insort(queue, queue.pop(queue.index(self)))", "def stage_card(self, i, j):\n self._stage.insert(j, self._hand.pop(i))", "def deliver_packages(truck, truck_load, start_address):\n visited_queue = []\n\n while len(truck_load) > 0:\n for package in truck_load:\n # Gets shortest route from truck's starting point to closest available package destination.\n # Appends trip mileage into mileage list to be summed later\n delivery_distance, delivery_index = get_shortest_route(truck_load, start_address)\n\n truck_mileage_list.append(delivery_distance)\n\n # Calculates trip time based on mileage\n trip_time = miles_to_time(delivery_distance)\n delivery_time_list.append(trip_time)\n\n # Searches hash table and sets next stop as next package's address\n package = hashtable.search(int(package))\n start_address = package.address\n package.hub_departure = truck.departure_time\n\n package.delivery_time = sum(delivery_time_list, timedelta()) + truck.departure_time\n # print(f\"delivery time of package {package.package_id}: {package.delivery_time}\")\n truck.truck_location = package.address\n\n visited_queue.append(package.address)\n set_package_status(package)\n truck_load.remove(package.package_id)\n\n # When truck is empty of package objects, it returns back to the hub and appends mileage and time to lists for further\n # calculations.\n # O(1)\n if len(truck_load) == 0:\n return_distance, index = new_distance_search(visited_queue[-1], hub_address)\n truck_mileage_list.append(return_distance)\n delivery_time_list.append(miles_to_time(return_distance))\n truck.truck_location = hub_address\n delivery_time_list.clear()\n\n # Sums mileage for entire delivery route\n total_miles = sum(truck_mileage_list)\n\n # Records total truck mileage and returns truck back to hub\n truck.mileage = round(total_miles, 2)\n delivery_time_spent = miles_to_time(truck.mileage)\n return_time = delivery_time_spent + truck.departure_time\n truck.return_time = return_time\n\n all_trucks_mileage.append(truck.mileage)\n truck_mileage_list.clear()", "def queue_insertion(self):\n count = 1\n print(\"After inserting each player in a queue,we got: \")\n for lst in self.player:\n obj = Queue()\n obj.en_queue(lst)\n print(f\"The cards of player {count} are: \")\n count += 1\n obj.print_list()\n print()" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Use the credentials to authenticate the Azure CLI.
def login_cli(creds_data): app_id = creds_data['application-id'] app_pass = creds_data['application-password'] sub_id = creds_data['subscription-id'] tenant_id = _get_tenant_id(sub_id) try: log('Forcing logout of Azure CLI') _azure('logout') except AzureError: pass try: log('Logging in to Azure CLI') _azure('login', '--service-principal', '-u', app_id, '-p', app_pass, '-t', tenant_id) # cache the subscription ID for use in roles kv().set('charm.azure.sub-id', sub_id) except AzureError as e: # redact the credential info from the exception message stderr = re.sub(app_id, '<app-id>', e.args[0]) stderr = re.sub(app_pass, '<app-pass>', stderr) stderr = re.sub(tenant_id, '<tenant-id>', stderr) # from None suppresses the previous exception from the stack trace raise AzureError(stderr) from None
[ "def azure_credentials(self) -> 'outputs.AzureCredentialsResponse':\n return pulumi.get(self, \"azure_credentials\")", "def _get_resource_creds_from_cli(\n cloud: dict, args: Namespace\n ) -> Tuple[identity.AzureCliCredential, identity_aio.AzureCliCredential]:\n try:\n logger.info(f\"Authenticating to {cloud['AD']} with CLI credentials.\")\n return [\n identity.AzureCliCredential(),\n identity_aio.AzureCliCredential(),\n ]\n\n except Exception as e:\n logger.warning(e)\n exit()", "def environment_credential(account: Account):\n # --- Environment Variables, service principal with secret (based on subscription) ---\n # https://pypi.org/project/azure-identity\n # ID of the application's Azure AD tenant\n sh.environment_set('AZURE_TENANT_ID', account.tenantId)\n if account.login_sp:\n # ID of an Azure AD application\n sh.environment_set('AZURE_CLIENT_ID', account.login_sp.appId)\n # one of the application's client secrets\n sh.environment_set('AZURE_CLIENT_SECRET', account.login_sp.password)", "def __init__(self, creds_path=None, sa_name=None, sa_group=None, use_envs=True):\n self.colored_print = ColoredPrint()\n if creds_path is None and use_envs is False:\n err_msg = (\n \"You need to specify if you want to use authentication \"\n \"data from configuration file or from environment variables!\"\n )\n self.colored_print(err_msg, level=\"error\")\n raise Exception(err_msg)\n if use_envs:\n self.tenant = os.environ[\"ARM_TENANT_ID\"]\n self.secret = os.environ[\"ARM_CLIENT_SECRET\"]\n self.client_id = os.environ[\"ARM_CLIENT_ID\"]\n self.subscription_id = os.environ[\"ARM_SUBSCRIPTION_ID\"]\n else:\n self.creds_manager = azure_creds_manager.AzureCredentialsManager(\n config_path=creds_path\n )\n self.tenant = self.creds_manager.credentials[\"ARM_TENANT_ID\"]\n self.secret = self.creds_manager.credentials[\"ARM_CLIENT_SECRET\"]\n self.client_id = self.creds_manager.credentials[\"ARM_CLIENT_ID\"]\n self.subscription_id = self.creds_manager.credentials[\"ARM_SUBSCRIPTION_ID\"]\n\n self.credentials = ServicePrincipalCredentials(\n client_id=self.client_id, secret=self.secret, tenant=self.tenant\n )\n self.storage_client = StorageManagementClient(\n self.credentials, self.subscription_id\n )\n self.storage_acc_name = sa_name\n self.storage_acc_group = sa_group\n\n self._storage_acc_key_1 = None\n self._storage_acc_key_2 = None\n self._blob_srv = None\n self._file_srv = None\n self._table_service = None\n self._changed_properties = {\n \"storage_acc_key_1\": False,\n \"storage_acc_key_2\": False,\n \"storage_acc_name\": False,\n }", "def oauth2_authenticate(self, credentials):\n self.http = credentials.authorize(self.http)", "def __init__(self,\n account: str = None,\n password: str = None,\n existing_auth: ExistingAuthEnum = EXISTING_AUTH_IGNORE,\n vault: str = None,\n password_prompt: bool = True,\n op_path: str = OP_PATH,\n logger: logging.Logger = None):\n super().__init__()\n if not logger:\n logger = logging.getLogger(self.__class__.__name__)\n logger.setLevel(logging.INFO)\n\n self.vault = vault\n self.logger = logger\n self.op_path = op_path\n self._account_identifier = account\n self._signed_in_account: OPAccount = None\n\n self._cli_version: OPCLIVersion\n self._op_config: OPCLIConfig = None\n self._account_list: OPAccountList = None\n self._uses_bio: bool = False\n self._sess_var: str = None\n # gathering facts will attempt to set the above instance variables\n # that got initialized to None or False\n self._gather_facts()\n\n # Coerce existing_auth to an Enum in case it was passed in as a legacy bool\n # False -> ExistingAuthFlag.NONE, True -> ExistingAuthFlag.AVAILABLE\n existing_auth = ExistingAuthEnum(existing_auth)\n\n # part of exception message in case incompatible authentication parameters\n # are provided\n auth_pref_source = \"preference passed as argument\"\n if self.svc_account_env_var_set():\n # - 'op' won't prompt for authentication of OP_SERVICE_ACCOUNT_TOKEN is set\n # - Even if we explicitly call signin and succeed, it ignores that authentication\n # so we need to suppress any path that tries to or expects to authenticate\n if self._cli_version < MINIMUM_SERVICE_ACCOUNT_VERSION:\n raise OPAuthenticationException(\n f\"Version {self._cli_version} not supported with service accounts. Minimum version: {MINIMUM_SERVICE_ACCOUNT_VERSION}\")\n if existing_auth != EXISTING_AUTH_REQD:\n auth_pref_source = \"preference upgraded due to service account environment variable\"\n self.logger.info(\n f\"{self.OP_SVC_ACCOUNT_ENV_VAR} was set. Upgrading existing auth flag to REQUIRED\")\n existing_auth = EXISTING_AUTH_REQD\n\n if existing_auth == EXISTING_AUTH_REQD and password is not None:\n # if a password is passed in but existing_auth is required, caller may be confused:\n # - intentionally passed in incompatible options\n # - possibly has OP_SERVICE_ACCOUNT_TOKEN set accidentally\n msg = f\"Password argument passed but EXISTING_AUTH_REQD flag is set. flag source: {auth_pref_source}\"\n self.logger.error(msg)\n raise OPAuthenticationException(msg)\n\n # So far everything above has been fairly lightweight, with no remote\n # contact to the 1Password account.\n # The next steps will attempt to talk to the 1Password account, and\n # failing that, may attempt to authenticate to the 1Password account\n account_obj, token = self._new_or_existing_signin(\n existing_auth, password, password_prompt)\n self._signed_in_account = account_obj\n self._token = token\n if self._signed_in_account.is_service_account():\n self.logger.debug(\"Signed in as a service account\")\n else:\n self.logger.debug(\n f\"Signed in as User ID: {self._signed_in_account.sanitized_user_uuid}\")\n # export OP_SESSION_<use_id>\n if self.token:\n if not self._account_identifier:\n # if we weren't provided an account identifier,\n # we can now get it from the signed-in account object\n # and compute the session environment variable name\n self._account_identifier = account_obj.user_uuid\n self._sess_var = self._compute_session_var_name()\n environ[self._sess_var] = self.token", "def set_credentials(self, credentials):\n self._aws_access_key_id = credentials['aws_access_key_id']\n self._aws_secret_access_key = credentials['aws_secret_access_key']\n self._aws_session_token = None\n if 'aws_session_token' in credentials:\n self._aws_session_token = credentials['aws_session_token']", "def install_creds(arguments):\n\n global credentials\n if arguments.verbose:\n print \"Installing credentials...\"\n credentials = storage.get()", "def osf_credentials():\n from datalad_osf.utils import get_credentials\n cred = get_credentials(allow_interactive=False)\n yield cred", "def initialize_credentials():\n\n # import credentials\n # https://kedro.readthedocs.io/en/stable/04_kedro_project_setup/02_configuration.html\n from kedro.config import ConfigLoader\n\n # conf_paths = [\"../conf/base\", \"../conf/local\"]\n conf_paths = [Path(BASE_DIR, \"conf/local\")]\n print(f\"conf_paths are: {conf_paths}\")\n\n print\n conf_loader = ConfigLoader(conf_paths)\n credentials = conf_loader.get(\"credentials*\", \"credentials*/**\")\n\n # Environment setup\n os.environ[\"X_NFER_BASEURL\"] = \"https://preview.nferx.com\"\n os.environ[\"NFERENCE_USER\"] = credentials[\"nfer_access_key\"] # \"yash@nference.net\"\n os.environ[\"NFERENCE_TOKEN\"] = credentials[\"nfer_secret_key\"] # \"<api_token>\"\n\n print(\"Loaded credentials. Nference SDK ready to use.\\n\")", "def init(self, args):\n client = self.get_client(args)\n if args[\"--username\"]:\n username = args[\"--username\"]\n else:\n username = None\n if args[\"--password\"]:\n password = args[\"--password\"]\n else:\n password = None\n if username:\n if not password:\n # Request password from interactive prompt\n password = getpass(\"Password: \")\n\n res = client.authenticate(username, password)\n if res.ok():\n print(\n \"{0.bold_green}Success{0.normal} - {1} as \"\n \"{0.bold}{2}{0.normal}\".format(self.terminal, res.msg(), username)\n )\n else:\n print(\"{0.bold_red}Failed{0.normal} - {1}\".format(\n self.terminal, res.msg()\n ))\n # Failed to log in\n # Exit without saving client\n return res.code()\n else:\n print(\n \"{0.bold_green}Connected{0.normal} -\"\n \" Anonymous access\".format(self.terminal)\n )\n # Save the client for future use\n self.save_client(client)\n return 0", "def set_credentials(self, username, password):\n self.credentials = (username, password,)", "def credential_get(scope: str = 'default', tenant_id: str = '', client_id: str = '', client_secret: str = '') -> Credential:\n # https://pypi.org/project/azure-identity\n if scope == 'cli':\n credential = azid.AzureCliCredential()\n if scope == 'env':\n # https://learn.microsoft.com/en-us/python/api/azure-identity/azure.identity.environmentcredential\n credential = azid.EnvironmentCredential()\n if scope == 'secret':\n # https://learn.microsoft.com/en-us/python/api/azure-identity/azure.identity.clientsecretcredential\n credential = azid.ClientSecretCredential(tenant_id, client_id, client_secret)\n else:\n # https://learn.microsoft.com/en-us/python/api/azure-identity/azure.identity.defaultazurecredential\n # credential = azid.DefaultAzureCredential(logging_enable=True)\n credential = azid.DefaultAzureCredential()\n return credential", "def aws_cli_credentials():\n # Saving initial state of env variables\n env_var_saved = {}\n for env_var in env_var_save_restore:\n env_var_saved[env_var] = os.getenv(env_var, default=None)\n if env_var_saved[env_var] is not None:\n del os.environ[env_var]\n\n # Set AWS_PROFILE\n os.environ[AWS_PROFILE] = PROFILE_NAME\n\n # Set AWS_CONFIG_FILE\n with tempfile.NamedTemporaryFile(delete=False) as config_file:\n config_file.write(b\"[profile \" + PROFILE_NAME.encode(\"utf\") + b\"]\\n\")\n aws_config_file = config_file.name\n os.environ[AWS_CONFIG_FILE] = aws_config_file\n\n # Set AWS_SHARED_CREDENTIALS_FILE\n with tempfile.NamedTemporaryFile(delete=False) as credentials_file:\n credentials_file.write(b\"[profile \" + PROFILE_NAME.encode(\"utf\") + b\"]\\n\")\n aws_shared_credentials_file = credentials_file.name\n os.environ[AWS_SHARED_CREDENTIALS_FILE] = aws_shared_credentials_file\n\n try:\n yield\n finally:\n # Remove all modified env variables\n for env_var in env_var_save_restore:\n if env_var in os.environ:\n del os.environ[env_var]\n\n # Restore original env variables\n for env_var, env_var_value in env_var_saved.items():\n if env_var_value is not None:\n os.environ[env_var] = env_var_value\n\n # Remove tmp files\n os.remove(aws_config_file)\n os.remove(aws_shared_credentials_file)", "def create_auth_client(self):\n client = APIClient()\n client.credentials(HTTP_AUTHORIZATION=self.auth_token)\n return client", "def basicAuth(self):\n # Use basic authentication\n\n authstring = bytes(\"{u}:{p}\".format(u=self.username, p=self.password), \"ascii\")\n\n # Use \"basic\" auth by default\n auth = b64encode(authstring).decode(\"ascii\")\n self.client.credentials(HTTP_AUTHORIZATION=\"Basic {auth}\".format(auth=auth))", "def _azure(cmd, *args, return_stderr=False):\n cmd = ['az', cmd]\n cmd.extend(args)\n result = subprocess.run(cmd,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE)\n stdout = result.stdout.decode('utf8').strip()\n stderr = result.stderr.decode('utf8').strip()\n if result.returncode != 0:\n raise AzureError.get(stderr)\n if return_stderr:\n return stderr\n if stdout:\n stdout = json.loads(stdout)\n return stdout", "def __connect_with_credentials(self):\n\t\tself.client_.username_pw_set(\"xgvutxaa\", \"9cMIpVoL4Ujj\")\n\t\tself.client_.connect('spectacular-pharmacist.cloudmqtt.com',1883,3600)", "def _client(self) -> hvac.Client:\n if \"session\" not in self.kwargs:\n # If no session object provide one with retry as per hvac documentation:\n # https://hvac.readthedocs.io/en/stable/advanced_usage.html#retrying-failed-requests\n adapter = HTTPAdapter(\n max_retries=Retry(\n total=3,\n backoff_factor=0.1,\n status_forcelist=[412, 500, 502, 503],\n raise_on_status=False,\n )\n )\n session = Session()\n session.mount(\"http://\", adapter)\n session.mount(\"https://\", adapter)\n self.kwargs[\"session\"] = session\n\n _client = hvac.Client(url=self.url, **self.kwargs)\n if self.auth_type == \"approle\":\n self._auth_approle(_client)\n elif self.auth_type == \"aws_iam\":\n self._auth_aws_iam(_client)\n elif self.auth_type == \"azure\":\n self._auth_azure(_client)\n elif self.auth_type == \"gcp\":\n self._auth_gcp(_client)\n elif self.auth_type == \"github\":\n self._auth_github(_client)\n elif self.auth_type == \"kubernetes\":\n self._auth_kubernetes(_client)\n elif self.auth_type == \"ldap\":\n self._auth_ldap(_client)\n elif self.auth_type == \"radius\":\n self._auth_radius(_client)\n elif self.auth_type == \"token\":\n self._set_token(_client)\n elif self.auth_type == \"userpass\":\n self._auth_userpass(_client)\n else:\n raise VaultError(f\"Authentication type '{self.auth_type}' not supported\")\n\n if _client.is_authenticated():\n return _client\n else:\n raise VaultError(\"Vault Authentication Error!\")" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tag the given instance with the given tags.
def tag_instance(request): log('Tagging instance with: {}', request.instance_tags) _azure('vm', 'update', '--name', request.vm_name, '--resource-group', request.resource_group, '--set', *['tags.{}={}'.format(tag, value) for tag, value in request.instance_tags.items()])
[ "def set_tags(self, url_prefix, microver, instance, tags):\n try:\n for tag in tags:\n instance.add_tag(self.conn, tag)\n except AttributeError:\n # Try a low-level access if SDK version is old\n for tag in tags:\n response = self.conn.put(\n self._get_tag_url(url_prefix, instance, tag),\n microversion=microver)\n if response.status_code not in [201, 204]:\n self.fail_json(\n msg='API returned something bad %s' % response.reason)\n return self.fetch_tags(url_prefix, microver, instance)", "def attach_tags(self, package_name, instance_id, tags, caller, now=None):\n assert tags and all(is_valid_instance_tag(tag) for tag in tags), tags\n self._assert_instance_is_ready(package_name, instance_id)\n\n # Grab info about existing tags, register new ones.\n now = now or utils.utcnow()\n existing = ndb.get_multi(\n instance_tag_key(package_name, instance_id, tag)\n for tag in tags)\n to_create = [\n InstanceTag(\n key=instance_tag_key(package_name, instance_id, tag),\n tag=tag,\n registered_by=caller,\n registered_ts=now)\n for tag, ent in zip(tags, existing) if not ent\n ]\n ndb.put_multi(to_create)\n\n attached = {}\n attached.update({e.tag: e for e in existing if e})\n attached.update({e.tag: e for e in to_create})\n return attached", "def tag(self, mode, *tags):\n\n if mode == utils.TAGMODE.ADD:\n self.add_tags(*tags)\n elif mode == utils.TAGMODE.REMOVE:\n self.remove_tags(*tags)\n else:\n log.error(\"Invalid mode! {}. Please provide one between utils.TAGMODE.ADD and utils.TAGMODE.REMOVE\".format(mode))", "def update_tags(instance, **kwargs):\n old_tags = list(instance.tags.all())\n for token in instance.content.tags:\n tag, t_is_new = Tag.objects.get_or_create(content=token,\n defaults={'creator':instance.author})\n\n taggedNote, tn_is_new = TaggedNote.objects.get_or_create(\n note=instance, tag=tag,\n defaults={'tagged_by':instance.author})\n if tag in old_tags:\n # old tags that remain in the content are removed from\n # the `old_tags` list, which in the end contains only \n # tags that are not longer used by `instance`\n old_tags.remove(tag)\n\n for tag in old_tags:\n taggedNote = TaggedNote.objects.get(note=instance,\n tag=tag)\n taggedNote.delete()", "def ex_create_tags(self, resource, tags):\r\n pass", "def instance_selection_tags(self, instance_selection_tags):\n self._instance_selection_tags = instance_selection_tags", "def get_tags(self, package_name, instance_id, tags):\n assert is_valid_package_name(package_name), package_name\n assert is_valid_instance_id(instance_id), instance_id\n assert tags and all(is_valid_instance_tag(tag) for tag in tags), tags\n attached = ndb.get_multi(\n instance_tag_key(package_name, instance_id, tag)\n for tag in tags)\n return dict(zip(tags, attached))", "def apply_tags_to_instances_and_cluster(instanceIdentifiers):\n\trds = boto3.client('rds', region_name = regionName)\n\ttry:\n\t\tclusterARN = generate_ARN_for_resource(clusterIdentifier, True)\n\t\trds.add_tags_to_resource(ResourceName=clusterARN,Tags=tags)\n\t\tprint(\"Succesfully applied tags to cluster \" + clusterIdentifier)\n\t\tfor instanceId in instanceIdentifiers:\n\t\t\tinstanceARN = generate_ARN_for_resource(instanceId, False)\n\t\t\trds.add_tags_to_resource(ResourceName=instanceARN,Tags=tags)\n\t\t\tprint(\"Succesfully applied tags to instance \" + instanceId)\n\texcept Exception as e:\n\t\tprint(\"Error while applying tags: \", e)\n\t\traise e", "def make_tag(\n class_name: str, subs: Optional[List[SubAnnotation]] = None, slot_names: Optional[List[str]] = None\n) -> Annotation:\n return Annotation(AnnotationClass(class_name, \"tag\"), {}, subs or [], slot_names=slot_names or [])", "def add_tags(self, tags: List[str]) -> None:\n for t in tags:\n self.add_tag(t)", "def addtags( self, tags ) :\n return self.client.tagwiki( self.project, self, addtags=tags )", "def _set_tags(self, tags: dict[any, any]) -> None:\n\n self.set_tags(tags, inplace=True)", "def add_tags(self, tags):\n if tags is None:\n tags = []\n if isinstance(tags, basestring):\n tags = [tags]\n for tag_str in tags:\n for tag in tag_str.split():\n if tag not in self.tags:\n self.tags.append(tag)\n return self", "def detach_tags(self, package_name, instance_id, tags):\n # TODO(vadimsh): Write performed actions into some audit log.\n assert tags and all(is_valid_instance_tag(tag) for tag in tags), tags\n ndb.delete_multi(\n instance_tag_key(package_name, instance_id, tag)\n for tag in tags)", "def add_tags(self, *tags):\n\n try:\n tag_list = self.data[\"tags\"]\n except KeyError:\n tag_list = []\n\n tag_list.extend(tags)\n \n self.data[\"tags\"] = list(set(tag_list))", "def update_tags(self):\n raise NotImplementedError", "def addtags( self, tags ) :\n return self.client.tagticket( self.project, self, addtags=tags )", "def setTag(self, t):\r\n self.tag = t", "def put(self, item: T, **tags) -> None:\n if not tags or \"id\" not in tags:\n raise Exception(\n \"You need to pass in some tags, and the tags must contain \"\n \"at least the `id` key.\"\n )\n\n registration = CounterTypeRegistration(\n item=item,\n tags=tags,\n )\n\n for tag_name, tag_value in tags.items():\n try:\n reverse_index = self._indexes[tag_name]\n except KeyError:\n reverse_index = dict()\n self._indexes[tag_name] = reverse_index\n\n try:\n set_items = reverse_index[tag_value]\n except KeyError:\n set_items = set()\n reverse_index[tag_value] = set_items\n\n set_items.add(registration)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Enable instance inspection access for the given application.
def enable_instance_inspection(request): log('Enabling instance inspection') _assign_role(request, _get_role('vm-reader'))
[ "def setAppInstance(self, instance):\n pass", "def requested_instance_inspection(self):\n return bool(self._unit.received[\"enable-instance-inspection\"])", "def application_enableapi(self, application_enableapi):\n\n self._application_enableapi = application_enableapi", "def application_enable(self, application_enable):\n\n self._application_enable = application_enable", "def appdev_enable(self, appdev_enable):\n\n self._appdev_enable = appdev_enable", "def set_application(app):", "def set_app(cls, app):\n cls.app = app", "def enable(app, user_class, role_class):\n app.logger.info('Enabling security')\n user_class.add_cross_reference(role_class)\n\n # configure security with role and user classes\n user_datastore = SQLAlchemyUserDatastore(app.db, user_class, role_class)\n app.security = Security(app, user_datastore)\n app.security.user_datastore = user_datastore\n\n return app.security", "def enable_app_for_project(self, txapp, project):\r\n txapp.projects.add(project)", "def enable() -> None:\n global _CHECK_ACCESS # pylint: disable=global-statement\n _CHECK_ACCESS = True", "def init_app(self, app):\r\n self.app = app\r\n app.extensions = getattr(app, 'extensions', {})\r\n app.extensions['oauthlib.provider.oauth1'] = self", "def sentry_logging(app_instance):\n if not app_instance.debug:\n app_instance.sentry = Sentry()\n app_instance.sentry.init_app(app_instance, logging=True, level=logging.ERROR)", "def enable(cls, run_module=False):\n # type: (bool) -> None\n if cls._instance is not None:\n log.debug(\"%s already enabled\", cls.__name__)\n return\n\n log.debug(\"Enabling %s\", cls.__name__)\n\n di_config.enabled = True\n\n cls.__watchdog__.install()\n\n if di_config.metrics:\n metrics.enable()\n\n cls._instance = debugger = cls()\n\n debugger.start()\n\n forksafe.register(cls._restart)\n atexit.register(cls.disable)\n register_post_run_module_hook(cls._on_run_module)\n\n log.debug(\"%s enabled\", cls.__name__)", "def init_app(self, app):\r\n self.app = app\r\n app.extensions = getattr(app, 'extensions', {})\r\n app.extensions['oauthlib.provider.oauth2'] = self", "def enable(id, session_key=None):\n\n return NotableEventSuppression.set_suppression(id, True, session_key)", "def applicationcredentials_enable(self, applicationcredentials_enable):\n\n self._applicationcredentials_enable = applicationcredentials_enable", "def register_application_for_autosummary(app):\n # type: (Sphinx) -> None\n if 'sphinx.ext.autosummary' in sys.modules:\n from sphinx.ext import autosummary\n autosummary._app = app", "def init_app(self, app):\n\n app.session_interface = self._get_interface(app)", "def __init__(self, app, options=None):\n self.options = options or {}\n self.application = app\n super(StandaloneApplication, self).__init__()" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Enable network management for the given application.
def enable_network_management(request): log('Enabling network management') _assign_role(request, StandardRole.NETWORK_MANAGER)
[ "def enable_network(self):\n if self._is_admin():\n completed = subprocess.run(args=['netsh', 'interface', 'set', 'interface', '\"Wi-Fi\"', 'enable'])\n print(\"Enable Wi-Fi \", completed.returncode)\n completed = subprocess.run(args=['netsh', 'interface', 'set', 'interface', '\"Ethernet\"', 'enable'])\n print(\"Enable Ethernet\", completed.returncode)\n else:\n # Re-run the program with admin rights\n ctypes.windll.shell32.ShellExecuteW(None, \"runas\", 'netsh', ' interface set interface \"Ethernet\" enable', None, 1)\n ctypes.windll.shell32.ShellExecuteW(None, \"runas\", 'netsh', ' interface set interface \"Wi-Fi\" enable', None, 1)", "def enable_app() -> None:\n \n copyfile(\"config/hostapd\", \"/etc/default/hostapd\")\n copyfile(\"config/dhcpcd.conf\", \"/etc/dhcpcd.conf\")\n copyfile(\"config/dnsmasq.conf\", \"/etc/dnsmasq.conf\")\n\n subprocess.run([\"systemctl\", \"daemon-reload\"])", "def configure_control_network(module, network, task, msg):\n cli = pn_cli(module)\n cli += ' fabric-info format control-network '\n time.sleep(4)\n current_control_network = run_command(module, cli, task, msg).split()[1]\n\n if current_control_network != network:\n cli = pn_cli(module)\n cli += ' fabric-local-modify control-network %s ' % network\n run_command(module, cli, task, msg)", "def application_enable(self, application_enable):\n\n self._application_enable = application_enable", "def enable(self):\n interface_name = self.device_delegate.setup(self.network,\n reuse_existing=True)\n if self.active:\n self.restart()\n elif self._enable_dhcp():\n self.interface_name = interface_name\n self.spawn_process()", "def configureAndStartMgmtServer(self):\n self.configureAndEnableOobm()\n self.startMgmtServer()", "def enable_module(address, name, module):\n explore = explorepy.explore.Explore()\n explore.connect(mac_address=address, device_name=name)\n explore.enable_module(module)", "def configManagementNet(self):\n networks = self.handler.getNetworks(self.osid)\n for net in networks['networks']:\n if net['name'] == \"management\":\n net[\"ip_ranges\"] = [[\"10.20.2.5\", \"10.20.2.254\"]]\n net[\"cidr\"] = \"10.20.2.0/24\"\n net[\"meta\"][\"notation\"] = \"ip_ranges\"\n net[\"meta\"][\"use_gateway\"] = True\n net[\"gateway\"] = \"10.20.2.1\"\n net[\"vlan_start\"] = None\n self.handler.uploadNetworks(networks, self.osid)", "def enable_private_networking(self):\n return self.act_on_droplets(type='enable_private_networking')", "def enable_dns_management(request):\n log('Enabling DNS management')\n _assign_role(request, StandardRole.DNS_MANAGER)", "def configNetworks(self):\n self.configPublicNet()\n self.configStorageNet()\n self.configManagementNet()", "def _configure_manager(self):\r\n self._manager = CloudNetworkManager(self, resource_class=CloudNetwork,\r\n response_key=\"network\", uri_base=\"os-networksv2\")", "def application_enableapi(self, application_enableapi):\n\n self._application_enableapi = application_enableapi", "def add_extra_net_configuration(self, netdata):\n return", "def enable_app_for_project(self, txapp, project):\r\n txapp.projects.add(project)", "def disable_network(self):\n if self._is_admin():\n completed = subprocess.run(args=['netsh', 'interface', 'set', 'interface', '\"Wi-Fi\"', 'disable'])\n print(\"Disable Wi-Fi \", completed.returncode)\n completed = subprocess.run(args=['netsh', 'interface', 'set', 'interface', '\"Ethernet\"', 'disable'])\n print(\"Disable Ethernet\", completed.returncode)\n else:\n # Re-run the program with admin rights\n ctypes.windll.shell32.ShellExecuteW(None, \"runas\", 'netsh', ' interface set interface \"Wi-Fi\" disable', None, 1)\n ctypes.windll.shell32.ShellExecuteW(None, \"runas\", 'netsh', ' interface set interface \"Ethernet\" disable', None, 1)", "def requested_network_management(self):\n return bool(self._unit.received[\"enable-network-management\"])", "def attach_internet_gateway(DryRun=None, InternetGatewayId=None, VpcId=None):\n pass", "def appdev_enable(self, appdev_enable):\n\n self._appdev_enable = appdev_enable" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Enable security management for the given application.
def enable_security_management(request): log('Enabling security management') _assign_role(request, StandardRole.SECURITY_MANAGER)
[ "def enable(app, user_class, role_class):\n app.logger.info('Enabling security')\n user_class.add_cross_reference(role_class)\n\n # configure security with role and user classes\n user_datastore = SQLAlchemyUserDatastore(app.db, user_class, role_class)\n app.security = Security(app, user_datastore)\n app.security.user_datastore = user_datastore\n\n return app.security", "def application_enable(self, application_enable):\n\n self._application_enable = application_enable", "def test_put_re_enable_security_disabled(self):\n self.user = self._login_user(admin=True)\n doc = User.objects.get(username='doc')\n local_site = LocalSite.objects.get(pk=1)\n app = self.create_oauth_application(user=doc, local_site=local_site)\n\n original_secret = app.client_secret\n\n local_site.users.remove(doc)\n\n app = Application.objects.get(pk=app.pk)\n\n self.assertTrue(app.is_disabled_for_security)\n self.assertEqual(app.user, self.user)\n self.assertEqual(app.original_user, doc)\n\n rsp = self.api_put(get_oauth_app_item_url(app.pk, local_site.name),\n {'enabled': '1'},\n expected_status=400)\n\n app = Application.objects.get(pk=app.pk)\n\n self.assertIn('stat', rsp)\n self.assertEqual(rsp['stat'], 'fail')\n self.assertIn('fields', rsp)\n self.assertIn('__all__', rsp['fields'])\n self.assertEqual(rsp['fields']['__all__'][0],\n ApplicationChangeForm.DISABLED_FOR_SECURITY_ERROR)\n self.assertEqual(app.original_user, doc)\n self.assertEqual(app.client_secret, original_secret)", "def application_enableapi(self, application_enableapi):\n\n self._application_enableapi = application_enableapi", "def handle_enable_app(self, hermes, intent_message):\n self.chmod_app(hermes, intent_message, i18n.RESULT_ENABLE_APP, 0o755)", "def test_set_security_id_for_application(self):\n ezdiscovery.register_endpoint('foo', 'bar', 'localhost', 8000)\n ezdiscovery.set_security_id_for_application('foo', 'bar')\n path = '/'.join([\n ezdiscovery.NAMESPACE,\n 'foo',\n ezdiscovery.SECURITY,\n ezdiscovery.SECURITY_ID\n ])\n self.assertTrue(self.client.exists(path))\n self.assertEquals('bar', self.client.get(path)[0])", "def __check_security_policy(self):\n\n cmd = \"setenforce 0; \"\n\n cmd = cmd + \"supolicy --live \\\"allow init logd dir getattr\\\";\"\n\n # # Depreciated supolicies. Still keep them for backup purpose\n cmd = cmd + \"supolicy --live \\\"allow init init process execmem\\\";\"\n cmd = cmd + \\\n \"supolicy --live \\\"allow atfwd diag_device chr_file {read write open ioctl}\\\";\"\n cmd = cmd + \"supolicy --live \\\"allow init properties_device file execute\\\";\"\n cmd = cmd + \\\n \"supolicy --live \\\"allow system_server diag_device chr_file {read write}\\\";\"\n\n # # Suspicious supolicies: MI works without them, but it seems that they SHOULD be enabled...\n\n # # mi2log permission denied (logcat | grep denied), but no impact on log collection/analysis\n cmd = cmd + \\\n \"supolicy --live \\\"allow untrusted_app app_data_file file {rename}\\\";\"\n\n # # Suspicious: why still works after disabling this command? Won't FIFO fail?\n cmd = cmd + \\\n \"supolicy --live \\\"allow init app_data_file fifo_file {write open getattr}\\\";\"\n cmd = cmd + \\\n \"supolicy --live \\\"allow init diag_device chr_file {getattr write ioctl}\\\"; \"\n\n # Nexus 6 only\n cmd = cmd + \\\n \"supolicy --live \\\"allow untrusted_app diag_device chr_file {write open getattr}\\\";\"\n cmd = cmd + \\\n \"supolicy --live \\\"allow system_server diag_device chr_file {read write}\\\";\"\n cmd = cmd + \\\n \"supolicy --live \\\"allow netmgrd diag_device chr_file {read write}\\\";\"\n cmd = cmd + \\\n \"supolicy --live \\\"allow rild diag_device chr_file {read write}\\\";\"\n cmd = cmd + \\\n \"supolicy --live \\\"allow rild debuggerd app_data_file {read open getattr}\\\";\"\n\n cmd = cmd + \\\n \"supolicy --live \\\"allow wcnss_service mnt_user_file dir {search}\\\";\"\n\n cmd = cmd + \\\n \"supolicy --live \\\"allow wcnss_service fuse dir {read open search}\\\";\"\n\n cmd = cmd + \\\n \"supolicy --live \\\"allow wcnss_service mnt_user_file lnk_file {read}\\\";\"\n\n cmd = cmd + \\\n \"supolicy --live \\\"allow wcnss_service fuse file {read append getattr}\\\";\"\n\n main_utils.run_shell_cmd(cmd)", "def appdev_enable(self, appdev_enable):\n\n self._appdev_enable = appdev_enable", "def add_auth_middleware(app):\n auth_conf = dict(CONF.keystone_authtoken)\n # These items should only be used for accessing Ironic API.\n # For keystonemiddleware's authentication,\n # keystone_authtoken's items will be used and\n # these items will be unsupported.\n # [ironic]/os_password\n # [ironic]/os_username\n # [ironic]/os_auth_url\n # [ironic]/os_tenant_name\n auth_conf.update({'admin_password':\n CONF.ironic.os_password or\n CONF.keystone_authtoken.admin_password,\n 'admin_user':\n CONF.ironic.os_username or\n CONF.keystone_authtoken.admin_user,\n 'auth_uri':\n CONF.ironic.os_auth_url or\n CONF.keystone_authtoken.auth_uri,\n 'admin_tenant_name':\n CONF.ironic.os_tenant_name or\n CONF.keystone_authtoken.admin_tenant_name,\n 'identity_uri':\n CONF.ironic.identity_uri or\n CONF.keystone_authtoken.identity_uri})\n auth_conf['delay_auth_decision'] = True\n app.wsgi_app = auth_token.AuthProtocol(app.wsgi_app, auth_conf)", "def enable_instance_inspection(request):\n log('Enabling instance inspection')\n _assign_role(request, _get_role('vm-reader'))", "def init_app(self, app):\n\n app.wsgi_app = Middleware(app.wsgi_app)", "def set_security(self, doc):\n self.server._PUT(self.name, \"_security\", json=doc)", "def applicationcredentials_enable(self, applicationcredentials_enable):\n\n self._applicationcredentials_enable = applicationcredentials_enable", "def test_get_security_id_for_application(self):\n # Fetch one that does not exist.\n self.assertEquals(\n None,\n ezdiscovery.get_security_id_for_application('foo')\n )\n ezdiscovery.register_endpoint('foo', 'bar', 'localhost', 8000)\n ezdiscovery.set_security_id_for_application('foo', 'bar')\n self.assertEquals(\n 'bar',\n ezdiscovery.get_security_id_for_application('foo')\n )", "def setup_permission(self) :\n cmd = IPNETNSEXEC % ( self.hostname, PermCMD % (ConfigDIR, ConfigDIR))\n runOS(cmd)", "def get_security_config(app):\n items = app.config.items()\n prefix = 'SECURITY_'\n\n def strip_prefix(tup):\n return (tup[0].replace('SECURITY_', ''), tup[1])\n\n return dict([strip_prefix(i) for i in items if i[0].startswith(prefix)])", "def set_application(app):", "def EnableApiSecurityContext(self, Context):\n self._Api.enable_security_context(Context)", "def load_middlewares(app):\n\n # Error handlers\n app.register_blueprint(mod_err)\n\n # Handles the service id checking\n get_user_id(app)\n\n # CORS\n CORS(app, allow_headers=app.config['ALLOWED_HEADERS'],\n origins=app.config['ALLOWED_ORIGINS'],\n methods=app.config['ALLOWED_METHODS'],\n support_credentials=True)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Enable block storage (disk) management for the given application.
def enable_block_storage_management(request): log('Enabling block storage management') _assign_role(request, _get_role('disk-manager'))
[ "def enable_storage(self):\n self.storage_enabled = True", "def attach_and_activate_disks(request, storage):\n self = request.node.cls\n\n read_only = getattr(self, 'read_only', False)\n storage_helpers.prepare_disks_for_vm(\n self.vm_name, self.disk_names, read_only\n )", "def requested_block_storage_management(self):\n return bool(self._unit.received[\"enable-block-storage-management\"])", "def enable_object_storage_management(request):\n log('Enabling object store management')\n _assign_role(request, StandardRole.OBJECT_STORE_MANAGER)", "def prepare_disks_with_fs_for_vm(request, storage):\n self = request.node.cls\n\n testflow.setup(\n \"Creating disks with filesystem and attach to VM %s\", self.vm_name,\n )\n disks, mount_points = storage_helpers.prepare_disks_with_fs_for_vm(\n self.storage_domain, self.vm_name,\n executor=getattr(self, 'vm_executor', None)\n )\n self.disks_to_remove = disks\n config.MOUNT_POINTS = mount_points", "def create_controller_filesystems(self, context, rootfs_device):\n database_storage = 0\n\n # Get the distributed cloud role to determine filesystems size\n system = self.dbapi.isystem_get_one()\n system_dc_role = system.get(\"distributed_cloud_role\", None)\n system_type = system.get(\"system_type\", None)\n\n # Set default filesystem sizes\n platform_storage = constants.DEFAULT_PLATFORM_STOR_SIZE\n if (system_dc_role == constants.DISTRIBUTED_CLOUD_ROLE_SYSTEMCONTROLLER and\n system_type == constants.TIS_STD_BUILD):\n platform_storage = constants.DEFAULT_PLATFORM_SYSTEMCONTROLLER_STOR_SIZE\n extension_lv_size = constants.DEFAULT_EXTENSION_STOR_SIZE\n etcd_lv_size = constants.ETCD_STOR_SIZE\n docker_distribution_lv_size = \\\n constants.DOCKER_DISTRIBUTION_STOR_SIZE\n\n LOG.info(\"Local Region Name: %s\" % system.region_name)\n\n disk_size = cutils.get_disk_capacity_mib(rootfs_device)\n disk_size = int(disk_size // 1024)\n\n if disk_size > constants.DEFAULT_SMALL_DISK_SIZE:\n\n LOG.info(\"Disk size : %s ... large disk defaults\" % disk_size)\n\n # Defaults: 500G root disk\n #\n # 8 G - /var/log (reserved in kickstart)\n # 16 G - /scratch (reserved in kickstart)\n # 2 G - pgsql_lv (DRBD bootstrap manifest)\n # 2 G - rabbit_lv (DRBD bootstrap manifest)\n # 10 G - platform_lv (DRBD bootstrap manifest)\n # (20 G if Standard System Controller)\n # 1 G - extension_lv (DRBD bootstrap manifest)\n # -----\n # 39 G - cgts-vg contents when we get to these checks\n # (49 G if Standard System Controller)\n #\n # Final defaults view after controller manifests\n # 8 G - /var/log (reserved in kickstart)\n # 16 G - /scratch (reserved in kickstart)\n # 20 G - /var/lib/postgresql\n # 2 G - /var/lib/rabbitmq\n # 10 G - /opt/platform\n # (20 G if Standard System Controller)\n # 1 G - /opt/extension\n # 25 G - /opt/backup\n # (35 G if Standard System Controller)\n # 30 G - /var/lib/docker\n # 16 G - /var/lib/docker-distribution\n # 5 G - /opt/etcd\n # 10 G - /var/lib/kubelet\n # 20 G - /var/lib/ceph/mon\n # 15 G - /opt/dc-vault (DRBD ctlr manifest for DCSC)\n # -----\n # 178 G\n # (198 G if Standard System Controller)\n #\n # The absolute minimum disk size for these default settings:\n # 2.0 G - buffer\n # 0.5 G - /boot\n # 10.0 G - /opt/platform-backup\n # 20.0 G - /\n # 178.0 G - cgts-vg PV\n # -------\n # ~ 210 G min size disk\n # (230 G if Standard System Controller)\n #\n database_storage = constants.DEFAULT_DATABASE_STOR_SIZE\n\n elif disk_size >= constants.MINIMUM_SMALL_DISK_SIZE:\n\n LOG.info(\"Disk size : %s ... small disk defaults\" % disk_size)\n\n # Small disk: under 240G and over 196G root disk\n #\n # 8 G - /var/log (reserved in kickstart)\n # 16 G - /scratch (reserved in kickstart)\n # 2 G - pgsql_lv (DRBD bootstrap manifest)\n # 2 G - rabbit_lv (DRBD bootstrap manifest)\n # 10 G - platform_lv (DRBD bootstrap manifest)\n # 1 G - extension_lv (DRBD bootstrap manifest)\n # -----\n # 39 G - cgts-vg contents when we get to these checks\n #\n #\n # Final defaults view after controller manifests\n # 8 G - /var/log (reserved in kickstart)\n # 16 G - /scratch (reserved in kickstart)\n # 10 G - /var/lib/postgresql\n # 2 G - /var/lib/rabbitmq\n # 10 G - /opt/platform\n # 1 G - /opt/extension\n # 20 G - /opt/backup\n # 30 G - /var/lib/docker\n # 16 G - /var/lib/docker-distribution\n # 20 G - /var/lib/ceph/mon\n # 5 G - /opt/etcd\n # 10 G - /var/lib/kubelet\n # 15 G - /opt/dc-vault (DRBD ctlr manifest for DCSC)\n # -----\n # 163 G\n #\n # The absolute minimum disk size for these default settings:\n # 2.0 G - buffer\n # 0.5 G - /boot\n # 10.0 G - /opt/platform-backup\n # 20.0 G - /\n # 163.0 G - cgts-vg PV\n # -------\n # ~ 196 G min size disk\n #\n database_storage = \\\n constants.DEFAULT_SMALL_DATABASE_STOR_SIZE\n\n elif (disk_size >= constants.MINIMUM_TINY_DISK_SIZE and\n cutils.is_virtual_system_config(self.dbapi) and\n cutils.is_aio_system(self.dbapi)):\n\n LOG.info(\"Disk size : %s ... tiny disk defaults for virtual system configruation\" % disk_size)\n\n # Tiny disk(StarlingX running in VM, AIO only): under 154G and over 60G root disk\n #\n # 3 G - /var/log (reserved in kickstart)\n # 2 G - /scratch (reserved in kickstart)\n # 2 G - pgsql_lv (DRBD bootstrap manifest)\n # 2 G - rabbit_lv (DRBD bootstrap manifest)\n # 1 G - platform_lv (DRBD bootstrap manifest)\n # 1 G - extension_lv (DRBD bootstrap manifest)\n # -----\n # 11 G - cgts-vg contents when we get to these checks\n #\n #\n # Final defaults view after controller manifests\n # 3 G - /var/log (reserved in kickstart)\n # 2 G - /scratch (reserved in kickstart)\n # 2 G - /var/lib/postgresql\n # 2 G - /var/lib/rabbitmq\n # 1 G - /opt/platform\n # 1 G - /opt/extension\n # 1 G - /opt/backup\n # 20 G - /var/lib/docker\n # 8 G - /var/lib/docker-distribution\n # 2 G - /var/lib/kubelet\n # 1 G - /opt/etcd\n # -----\n # 43 G\n #\n # The absolute minimum disk size for these default settings:\n # 0.5 G - /boot\n # 1.0 G - /opt/platform-backup\n # 15.0 G - /\n # 43.0 G - cgts-vg PV\n # -------\n # ~ 60 G min size disk\n #\n\n database_storage = \\\n constants.DEFAULT_TINY_DATABASE_STOR_SIZE\n platform_storage = \\\n constants.DEFAULT_TINY_PLATFORM_STOR_SIZE\n docker_distribution_lv_size = \\\n constants.TINY_DOCKER_DISTRIBUTION_STOR_SIZE\n etcd_lv_size = constants.TINY_ETCD_STOR_SIZE\n\n else:\n LOG.info(\"Disk size : %s ... disk too small\" % disk_size)\n raise exception.SysinvException(\"Disk size requirements not met.\")\n\n # platform fs added to platform-lv\n data = {\n 'name': constants.FILESYSTEM_NAME_PLATFORM,\n 'size': platform_storage,\n 'logical_volume': constants.FILESYSTEM_LV_DICT[\n constants.FILESYSTEM_NAME_PLATFORM],\n 'replicated': True,\n }\n LOG.info(\"Creating FS:%s:%s %d\" % (\n data['name'], data['logical_volume'], data['size']))\n self.dbapi.controller_fs_create(data)\n\n # pgsql fs added to pgsql-lv\n data = {\n 'name': constants.FILESYSTEM_NAME_DATABASE,\n 'size': database_storage,\n 'logical_volume': constants.FILESYSTEM_LV_DICT[\n constants.FILESYSTEM_NAME_DATABASE],\n 'replicated': True,\n }\n LOG.info(\"Creating FS:%s:%s %d\" % (\n data['name'], data['logical_volume'], data['size']))\n self.dbapi.controller_fs_create(data)\n\n # extension fs added to extension-lv\n data = {\n 'name': constants.FILESYSTEM_NAME_EXTENSION,\n 'size': extension_lv_size,\n 'logical_volume': constants.FILESYSTEM_LV_DICT[\n constants.FILESYSTEM_NAME_EXTENSION],\n 'replicated': True,\n }\n LOG.info(\"Creating FS:%s:%s %d\" % (\n data['name'], data['logical_volume'], data['size']))\n self.dbapi.controller_fs_create(data)\n\n # ETCD fs added to etcd-lv\n data_etcd = {\n 'name': constants.FILESYSTEM_NAME_ETCD,\n 'size': etcd_lv_size,\n 'logical_volume': constants.FILESYSTEM_LV_DICT[\n constants.FILESYSTEM_NAME_ETCD],\n 'replicated': True,\n }\n LOG.info(\"Creating FS:%s:%s %d\" % (\n data_etcd['name'], data_etcd['logical_volume'], data_etcd['size']))\n self.dbapi.controller_fs_create(data_etcd)\n\n # docker-distribution fs added to dockerdistribution-lv\n data = {\n 'name': constants.FILESYSTEM_NAME_DOCKER_DISTRIBUTION,\n 'size': docker_distribution_lv_size,\n 'logical_volume': constants.FILESYSTEM_LV_DICT[\n constants.FILESYSTEM_NAME_DOCKER_DISTRIBUTION],\n 'replicated': True,\n }\n LOG.info(\"Creating FS:%s:%s %d\" % (\n data['name'], data['logical_volume'], data['size']))\n self.dbapi.controller_fs_create(data)\n\n # dc-vault fs added to dc-vault-lv\n if system_dc_role == constants.DISTRIBUTED_CLOUD_ROLE_SYSTEMCONTROLLER:\n data = {\n 'name': constants.FILESYSTEM_NAME_DC_VAULT,\n 'size': constants.DEFAULT_DC_VAULT_STOR_SIZE,\n 'logical_volume': constants.FILESYSTEM_LV_DICT[\n constants.FILESYSTEM_NAME_DC_VAULT],\n 'replicated': True,\n }\n LOG.info(\"Creating FS:%s:%s %d\" % (\n data['name'], data['logical_volume'], data['size']))\n self.dbapi.controller_fs_create(data)", "def allow_block_device(self, mac_addr, device_status=c.BLOCK):\n return self._set(\n c.SERVICE_DEVICE_CONFIG,\n \"SetBlockDeviceByMAC\",\n {\"NewAllowOrBlock\": device_status, \"NewMACAddress\": mac_addr},\n )", "def makeExtended(self):\n print \"Making extended\"\n if self.mode != \"LUKS\":\n if not self.openTrueCryptVolume():\n self.failed(_(\"Could not open Container\"))\n mapperDevice = self.getTrueCryptMapperDevice()\n if not mapperDevice:\n self.closeTrueCryptVolume()\n self.failed(_(\"Could not find device for Container\"))\n else:\n mapperDevice = \"/dev/mapper/lukstmp\"\n if not self.makeExt3FileSystem(mapperDevice):\n self.closeVolume()\n self.failed(_(\"Could not create filesystem on Container\"))\n if not self.useBackup:\n self.createExtendedMarker(mapperDevice)\n self.closeVolume()\n self.finish()", "def _process_block_device_mappings(self, launch_config,\n vm_name, zone=None):\n data_disks = []\n root_disk_size = None\n\n def append_disk(disk_def, device_no, delete_on_terminate):\n # In azure, there is no option to specify terminate disks\n # (similar to AWS delete_on_terminate) on VM delete.\n # This method uses the azure tags functionality to store\n # the delete_on_terminate option when the virtual machine\n # is deleted, we parse the tags and delete accordingly\n disk_def['lun'] = device_no\n disk_def['tags'] = {\n 'delete_on_terminate': delete_on_terminate\n }\n data_disks.append(disk_def)\n\n for device_no, device in enumerate(launch_config.block_devices):\n if device.is_volume:\n if device.is_root:\n root_disk_size = device.size\n else:\n # In azure, os disk automatically created,\n # we are ignoring the root disk, if specified\n if isinstance(device.source, Snapshot):\n snapshot_vol = device.source.create_volume()\n disk_def = {\n # pylint:disable=protected-access\n 'name': snapshot_vol._volume.name,\n 'create_option': DiskCreateOption.attach,\n 'managed_disk': {\n 'id': snapshot_vol.id\n }\n }\n elif isinstance(device.source, Volume):\n disk_def = {\n # pylint:disable=protected-access\n 'name': device.source._volume.name,\n 'create_option': DiskCreateOption.attach,\n 'managed_disk': {\n 'id': device.source.id\n }\n }\n elif isinstance(device.source, MachineImage):\n disk_def = {\n # pylint:disable=protected-access\n 'name': device.source._volume.name,\n 'create_option': DiskCreateOption.from_image,\n 'source_resource_id': device.source.id\n }\n else:\n disk_def = {\n # pylint:disable=protected-access\n 'create_option': DiskCreateOption.empty,\n 'disk_size_gb': device.size\n }\n append_disk(disk_def, device_no,\n device.delete_on_terminate)\n else: # device is ephemeral\n # in azure we cannot add the ephemeral disks explicitly\n pass\n\n return data_disks, root_disk_size", "def attach_volume(self, node, volume, device=None, ex_mode=None,\r\n ex_boot=False):\r\n volume_data = {}\r\n if volume is None:\r\n volume_data['type'] = 'SCRATCH'\r\n else:\r\n volume_data['type'] = 'PERSISTENT'\r\n volume_data['source'] = volume.extra['selfLink']\r\n volume_data['kind'] = 'compute#attachedDisk'\r\n volume_data['mode'] = ex_mode or 'READ_WRITE'\r\n\r\n if device:\r\n volume_data['deviceName'] = device\r\n else:\r\n volume_data['deviceName'] = volume.name\r\n\r\n volume_data['boot'] = ex_boot\r\n\r\n request = '/zones/%s/instances/%s/attachDisk' % (\r\n node.extra['zone'].name, node.name)\r\n self.connection.async_request(request, method='POST',\r\n data=volume_data)\r\n return True", "def enable_mounting_volume_over_smb(mnode, volname, smb_users_info):\n g.log.info(\"Enable mounting volume over SMB\")\n # Create a temp mount to provide required permissions to the smb user\n mount = {\n 'protocol': 'glusterfs',\n 'server': mnode,\n 'volname': volname,\n 'client': {\n 'host': mnode\n },\n 'mountpoint': '/tmp/gluster_smb_set_user_permissions_%s' % volname,\n 'options': 'acl'\n }\n mount_obj = GlusterMount(mount)\n ret = mount_obj.mount()\n if not ret:\n g.log.error(\"Unable to create temporary mount for providing \"\n \"required permissions to the smb users\")\n return False\n g.log.info(\"Successfully created temporary mount for providing \"\n \"required permissions to the smb users\")\n\n # Provide required permissions to the smb user\n for smb_user in smb_users_info.keys():\n if smb_user != 'root':\n if 'acl' in smb_users_info[smb_user]:\n acl = smb_users_info[smb_user]['acl']\n if not acl:\n acl = \"rwx\"\n else:\n acl = \"rwx\"\n\n cmd = (\"setfacl -m user:%s:%s %s\" % (smb_user, acl,\n mount_obj.mountpoint))\n ret, _, _ = g.run(mnode, cmd)\n if ret != 0:\n g.log.error(\"Unable to provide required permissions to the \"\n \"smb user %s \", smb_user)\n return False\n g.log.info(\"Successfully provided required permissions to the \"\n \"smb user %s \", smb_user)\n\n # Verify SMB/CIFS share can be accessed by the user\n\n # Unmount the temp mount created\n ret = mount_obj.unmount()\n if not ret:\n g.log.error(\"Unable to unmount the temp mount\")\n g.log.info(\"Successfully unmounted the temp mount\")\n\n return True", "def attach_volume(self, context, **kwargs):\n # TODO(lyarwood): Remove this encryptor and refactor the LUKS based\n # encryptors in the U release.\n versionutils.report_deprecated_feature(\n LOG,\n \"The plain CryptsetupEncryptor is deprecated and will be removed \"\n \"in a future release. Existing users are encouraged to retype \"\n \"any existing volumes using this encryptor to the 'luks' \"\n \"LuksEncryptor or 'luks2' Luks2Encryptor encryptors as soon as \"\n \"possible.\")\n key = self._get_key(context).get_encoded()\n passphrase = self._get_passphrase(key)\n\n self._open_volume(passphrase, **kwargs)\n\n # modify the original symbolic link to refer to the decrypted device\n self._execute('ln', '--symbolic', '--force',\n '/dev/mapper/%s' % self.dev_name, self.symlink_path,\n root_helper=self._root_helper,\n run_as_root=True, check_exit_code=True)", "def install_storage():\n metadata = get_storage_metadata()\n\n # Install packages\n command = 'yum install -y nfs-utils'\n run(command)\n\n # Configure mount points\n\n file_name = '/etc/fstab'\n flags = 'nfs rw,async,hard,intr,noexec 0 0'\n mount_points = [volume['local'] for volume in metadata['volumes'].values()]\n\n # Make sure mount points are added only once to fstab\n with open(file_name, 'r+') as stream:\n # read current mount points\n existing_lines = stream.read().split('\\n')\n\n # prune lines to be replaced by new volumes\n new_lines = []\n for existing_line in existing_lines:\n # skip line if it matches a mount point\n found = False\n for mount_point in mount_points:\n if mount_point in existing_line and not existing_line.startswith('#'):\n found = True\n break\n # no match, then preserve line\n if not found:\n new_lines.append(existing_line)\n\n # Add mount points for volumes\n for volume in metadata['volumes'].values():\n line = '{server}:{remote} {local} {flags}'.format(flags=flags, **volume)\n new_lines.append(line)\n\n # Update contents\n stream.seek(0)\n stream.write('\\n'.join(new_lines))\n stream.truncate()\n\n # Create local mount point directories\n for mount_point in mount_points:\n command = 'mkdir -m 0777 {}'.format(mount_point)\n run(command)", "def _configure_storage_host(self, context, host):\n\n # Update cluster and peers model.\n # We call this function when setting the personality of a storage host.\n # In cases where we configure the storage-backend before unlocking\n # controller-0, and then configuring all other hosts, ceph will not be\n # responsive (and self._ceph not be set) when setting the storage\n # personality.\n # But that's ok, because this function is also called when unlocking a\n # storage node and we are guaranteed (by consistency checks) a\n # responsive ceph cluster at that point in time and we can update the\n # ceph cluster information succesfully.\n if self._ceph is not None:\n self._ceph.update_ceph_cluster(host)\n else:\n # It's ok, we just log a message for debug purposes\n LOG.debug(\"Error updating cluster information\")\n\n # Only update the manifest if the host is running the same version as\n # the active controller.\n if self.host_load_matches_sw_version(host):\n # Only generate the manifest files if the storage host is unlocked.\n # At that point changes are no longer allowed to the hostname, so\n # it is OK to allow the node to boot and configure the platform\n # services.\n if (host.administrative == constants.ADMIN_UNLOCKED or\n host.action == constants.FORCE_UNLOCK_ACTION or\n host.action == constants.UNLOCK_ACTION):\n # Generate host configuration files\n self._puppet.update_host_config(host)\n else:\n LOG.info(\"Host %s is not running active load. \"\n \"Skipping manifest generation\" % host.hostname)\n\n self._allocate_addresses_for_host(context, host)\n\n # Set up the PXE config file for this host so it can run the installer\n self._update_pxe_config(host)\n if host['hostname'] == constants.STORAGE_0_HOSTNAME:\n self._ceph_mon_create(host)", "def mount_ephemeral_storage():\r\n sudo_as(\"if [ ! $(mount | grep -i 'mnt') ];then mkfs.ext3 /dev/sdf && mount /dev/sdf /mnt; mkdir -p /mnt/%(application)s/var; chmod -R a+rw /mnt/%(application)s; fi\" % env)\r\n run('mkdir -p %(script_working_path)s' % env)", "def enable_api(event, data):\n DriveDevice.storage.api_enabled = data", "def attach_disk(self, instance, size=10, volume_type=None, iops=None, device=None):\n conn = self.conn or self.vpc_conn\n # Add EBS volume DONE\n ebs_vol = conn.create_volume(size, self.zone, volume_type=volume_type, iops=iops)\n self.wait_for_state(ebs_vol, 'status', 'available')\n if not device:\n device = '/dev/sdx'\n conn.attach_volume(ebs_vol.id, instance.id, device=device)\n self.ebs_vols.append(ebs_vol)\n return ebs_vol", "def attach_disk(request, storage):\n self = request.node.cls\n\n attach_kwargs = config.attach_disk_params.copy()\n if hasattr(self, 'update_attach_params'):\n attach_kwargs.update(self.update_attach_params)\n\n attach_to_vm = getattr(self, 'vm_to_attach_disk', self.vm_name)\n\n testflow.setup(\"Attach disk %s to VM %s\", self.disk_name, attach_to_vm)\n assert ll_disks.attachDisk(\n True, alias=self.disk_name, vm_name=attach_to_vm, **attach_kwargs\n ), (\"Failed to attach disk %s to VM %s\" % (self.disk_name, attach_to_vm))\n ll_disks.wait_for_disks_status([self.disk_name])", "def attach_volume(self, context, connection_info, instance, mountpoint,\n disk_bus=None, device_type=None, encryption=None):\n instance_name = instance['name']\n if instance_name not in self.__mounts:\n self.__mounts[instance_name] = {}\n self.__mounts[instance_name][mountpoint] = connection_info" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Enable DNS management for the given application.
def enable_dns_management(request): log('Enabling DNS management') _assign_role(request, StandardRole.DNS_MANAGER)
[ "def enable_app() -> None:\n \n copyfile(\"config/hostapd\", \"/etc/default/hostapd\")\n copyfile(\"config/dhcpcd.conf\", \"/etc/dhcpcd.conf\")\n copyfile(\"config/dnsmasq.conf\", \"/etc/dnsmasq.conf\")\n\n subprocess.run([\"systemctl\", \"daemon-reload\"])", "def update_dns_config(self, context):\n personalities = [constants.CONTROLLER]\n config_uuid = self._config_update_hosts(context, personalities)\n config_dict = {\n \"personalities\": personalities,\n \"classes\": ['platform::dns::resolv::runtime'],\n }\n self._config_apply_runtime_manifest(context, config_uuid, config_dict)", "def update_dnsmasq_config(self, context):\n personalities = [constants.CONTROLLER]\n config_uuid = self._config_update_hosts(context, personalities)\n config_dict = {\n \"personalities\": personalities,\n \"classes\": ['platform::dns::dnsmasq::runtime'],\n }\n self._config_apply_runtime_manifest(context, config_uuid, config_dict)", "async def sync_dns(self) -> None:\n # Update hosts\n add_host_coros: list[Awaitable[None]] = []\n for addon in self.installed:\n try:\n if not await addon.instance.is_running():\n continue\n except DockerError as err:\n _LOGGER.warning(\"Add-on %s is corrupt: %s\", addon.slug, err)\n self.sys_resolution.create_issue(\n IssueType.CORRUPT_DOCKER,\n ContextType.ADDON,\n reference=addon.slug,\n suggestions=[SuggestionType.EXECUTE_REPAIR],\n )\n capture_exception(err)\n else:\n add_host_coros.append(\n self.sys_plugins.dns.add_host(\n ipv4=addon.ip_address, names=[addon.hostname], write=False\n )\n )\n\n await asyncio.gather(*add_host_coros)\n\n # Write hosts files\n with suppress(CoreDNSError):\n await self.sys_plugins.dns.write_hosts()", "def update_dns_config(self, context):\n return self.call(context, self.make_msg('update_dns_config'))", "def SetUseGlobalDNS(self, use):\n print 'setting use global dns to', use\n use = misc.to_bool(use)\n self.config.set(\"Settings\", \"use_global_dns\", use, write=True)\n self.use_global_dns = use\n self.wifi.use_global_dns = use\n self.wired.use_global_dns = use", "def requested_dns_management(self):\n return bool(self._unit.received[\"enable-dns-management\"])", "def add(self, app, domain, port):\n self.apps[(domain, port)] = wsgi.WSGIAdaptor(\n app,\n domain,\n port,\n version.NAMEVERSION\n )", "def setDNS(prim, sec):\n logging.debugv(\"functions/linux.py->setDNS(prim, sec)\", [prim, sec])\n logging.info(\"Setting DNS to %s and %s\" % (prim, sec) )\n resolv = open('/etc/resolv.conf', 'w')\n if prim != \"\":\n resolv.write(\"nameserver %s\\n\" % (prim))\n logging.debug(\"Writing primary server %s\" % str(prim))\n if sec != \"\":\n resolv.write(\"nameserver %s\\n\" % (sec))\n logging.debug(\"Writing secondary server % s\" % str(sec))\n resolv.close()", "def dns(ip_addr: str = \"\"):\n return _run_speedify_cmd([\"dns\", ip_addr])", "def test_dnssec_activate():\n response = zone.dnssec_activate('example.com')\n assert response.success\n\n payload = response.payload\n assert payload['url'] == 'https://api.cloudns.net/dns/activate-dnssec.json'", "def add_settings(app):\n try:\n app.host = config[\"server\"][\"host\"]\n app.port = config[\"server\"][\"port\"]\n app.debug = config[\"server\"][\"debug\"]\n except KeyError:\n sys.exit(\"Config file corrupt. Execution aborted.\")\n\n return app", "async def defcon_enable_alias(self, ctx: Context) -> None:\n await self.invoke(ctx, \"defcon enable\")", "def do_dns_check(self):\n\n print \"\\nPerforming DNS queries against dnsmasq...\\n\"\n\n dns_resolver = resolver.Resolver(configure=False)\n dns_resolver.nameservers.append(self.dns_host_ip)\n\n # Set dns_check to 1 (good) by default\n dns_check = 1\n\n name_to_resolve = 'www.redhat.com'\n\n try:\n dns_answer = dns_resolver.query(name_to_resolve, 'A')\n except dns_exception.DNSException as e:\n print \"Failed DNS lookup of %s. Error: %s\" % (name_to_resolve, e)\n print \"\\nTroubleshoot command: dig @%s %s A\\n\" % (self.dns_host_ip, name_to_resolve)\n dns_check = 0\n # break\n\n if self.args.verbose:\n print \"\\nQueryring for A record of %s on server %s\" %(name_to_resolve, self.dns_host_ip)\n print \"DNS Answer: %s\" % dns_answer.rrset[0].address\n\n print \"================================================\\n\"\n\n self.metric_sender.add_metric({'dnsmasq.query' : dns_check})", "def enable(self):\n interface_name = self.device_delegate.setup(self.network,\n reuse_existing=True)\n if self.active:\n self.restart()\n elif self._enable_dhcp():\n self.interface_name = interface_name\n self.spawn_process()", "def configureAndStartMgmtServer(self):\n self.configureAndEnableOobm()\n self.startMgmtServer()", "def create_route53_elb_dns(elb_name, app_type):\n try:\n aws_cfg\n except NameError:\n aws_cfg = load_aws_cfg()\n\n try:\n app_settings\n except NameError:\n app_settings = loadsettings(app_type)\n\n elb = connect_to_elb()\n r53 = connect_to_r53()\n\n lb = elb.get_all_load_balancers(load_balancer_names=elb_name)[0]\n app_zone_name = app_settings[\"DOMAIN_NAME\"] + \".\"\n app_host_name = app_settings[\"HOST_NAME\"] + \".\"\n\n print _green(\"Creating DNS for \" + elb_name + \" and app_type \" + app_type)\n if r53.get_zone(app_zone_name) is None:\n print _yellow(\"creating zone \" + _green(app_zone_name))\n zone = r53.create_zone(app_zone_name)\n else:\n # print _yellow(\"zone \" + _green(app_zone_name) + _yellow(\" already exists. skipping creation\"))\n zone = r53.get_zone(app_zone_name)\n\n records = r53.get_all_rrsets(zone.id)\n\n if app_type == 'app':\n try:\n change = records.add_change('CREATE', zone.name, 'A', ttl=300, alias_hosted_zone_id=lb.canonical_hosted_zone_name_id, alias_dns_name=lb.canonical_hosted_zone_name)\n change.add_value('ALIAS %s (%s)' % (lb.canonical_hosted_zone_name, lb.canonical_hosted_zone_name_id))\n change_id = records.commit()['ChangeResourceRecordSetsResponse']['ChangeInfo']['Id'].split('/')[-1]\n status = r53.get_change(change_id)['GetChangeResponse']['ChangeInfo']['Status']\n spinner = Spinner(_yellow('[%s]waiting for route53 change to coalesce... ' % zone.name), hide_cursor=False)\n while status != 'INSYNC':\n spinner.next()\n time.sleep(1)\n status = r53.get_change(change_id)['GetChangeResponse']['ChangeInfo']['Status']\n print(_green('\\n[%s]route53 change coalesced' % zone.name))\n except Exception as error:\n if 'already exists' in error.message:\n # print _yellow(\"address record \" + _green(app_zone_name + \" \" + lb.canonical_hosted_zone_name) + _yellow(\" already exists. skipping creation\"))\n pass\n else:\n raise\n\n try:\n change = records.add_change('CREATE', app_host_name, 'A', ttl=300, alias_hosted_zone_id=lb.canonical_hosted_zone_name_id, alias_dns_name=lb.canonical_hosted_zone_name)\n change.add_value('ALIAS %s (%s)' % (lb.canonical_hosted_zone_name, lb.canonical_hosted_zone_name_id))\n change_id = records.commit()['ChangeResourceRecordSetsResponse']['ChangeInfo']['Id'].split('/')[-1]\n status = r53.get_change(change_id)['GetChangeResponse']['ChangeInfo']['Status']\n spinner = Spinner(_yellow('[%s]waiting for route53 change to coalesce... ' % app_host_name), hide_cursor=False)\n while status != 'INSYNC':\n spinner.next()\n time.sleep(1)\n status = r53.get_change(change_id)['GetChangeResponse']['ChangeInfo']['Status']\n print(_green('\\n[%s]route53 change coalesced' % app_host_name))\n except Exception as error:\n if 'already exists' in error.message:\n print _yellow(\"cname record \" + _green(app_host_name) + _yellow(\" already exists. skipping creation\"))\n else:\n raise", "def create_route53_ec2_dns(name, app_type):\n try:\n aws_cfg\n except NameError:\n aws_cfg = load_aws_cfg()\n\n try:\n app_settings\n except NameError:\n app_settings = loadsettings(app_type)\n\n try:\n ec2host = open(\"fab_hosts/{}.txt\".format(name)).readline().strip() + \".\"\n except IOError:\n print _red(\"{name} is not reachable. either run fab getec2instances or fab create_ec2:{name} to create the instance\".format(name=name))\n return 1\n\n app_zone_name = app_settings[\"DOMAIN_NAME\"] + \".\"\n app_host_name = app_settings[\"HOST_NAME\"] + \".\"\n\n print _green(\"Creating DNS for \" + name + \" and app_type \" + app_type)\n conn = connect_to_r53()\n if conn.get_zone(app_zone_name) is None:\n print _yellow(\"creating zone \" + _green(app_zone_name))\n zone = conn.create_zone(app_zone_name)\n else:\n print _yellow(\"zone \" + _green(app_zone_name) + _yellow(\" already exists. skipping creation\"))\n zone = conn.get_zone(app_zone_name)\n\n if app_type == 'app':\n # TODO: cleanup parser\n # ex: ec2-54-204-216-244.compute-1.amazonaws.com\n ec2ip = '.'.join(ec2host.split('.')[0].split('-')[1:5])\n try:\n apex = zone.add_a(app_zone_name, ec2ip, ttl=300)\n while apex.status != 'INSYNC':\n print _yellow(\"creation of A record: \" + _green(app_zone_name + \" \" + ec2ip) + _yellow(\" is \") + _red(apex.status))\n apex.update()\n time.sleep(10)\n print _green(\"creation of A record: \" + app_zone_name + \" is now \" + apex.status)\n except Exception as error:\n if 'already exists' in error.message:\n print _yellow(\"address record \" + _green(app_zone_name + \" \" + ec2ip) + _yellow(\" already exists. skipping creation\"))\n else:\n raise\n\n try:\n cname = zone.add_cname(app_host_name, ec2host, ttl=300, comment=\"expa \" + app_type + \" entry\")\n while cname.status != 'INSYNC':\n print _yellow(\"creation of cname: \" + _green(app_host_name) + _yellow(\" is \") + _red(cname.status))\n cname.update()\n time.sleep(10)\n print _green(\"creation of cname: \" + app_host_name + \" is now \" + cname.status)\n except Exception as error:\n if 'already exists' in error.message:\n print _yellow(\"cname record \" + _green(app_host_name) + _yellow(\" already exists. skipping creation\"))\n else:\n raise", "def configure_app(app) -> NoReturn:\n ma.init_app(app)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Enable object storage readonly access for the given application.
def enable_object_storage_access(request): log('Enabling object storage read') _assign_role(request, StandardRole.OBJECT_STORE_READER)
[ "def enable_object_storage_management(request):\n log('Enabling object store management')\n _assign_role(request, StandardRole.OBJECT_STORE_MANAGER)", "def enable_storage(self):\n self.storage_enabled = True", "def read_only(self):\n\n self._read_only = True", "def make_readonly(path: str):\n assert os.path.isfile(path)\n os.chmod(path, stat.S_IROTH | stat.S_IRUSR | stat.S_IRGRP)", "def enable_api(event, data):\n DriveDevice.storage.api_enabled = data", "def read_only(self, enabled):\n self.set_variable(\"READ_ONLY\", \"ON\" if enabled else \"OFF\")\n self._check_read_only()", "def readonly(self, readonly):\n \n self._readonly = readonly", "def enable() -> None:\n global _CHECK_ACCESS # pylint: disable=global-statement\n _CHECK_ACCESS = True", "def s3_readonly(self):\n return os.environ.get('PIP_ACCEL_S3_READONLY')", "def setAccessMode(self, mode): \n self.__accessMode = mode", "def setReadOnly(self, readOnly):\n self.listener.setReadOnly(readOnly)", "def requested_object_storage_access(self):\n return bool(self._unit.received[\"enable-object-storage-access\"])", "def set_view_read_only(self):\n if self.reh is not None:\n self.reh.set_read_only()", "def OSSupportsExtendedProtection(self) -> bool:", "def isReadOnly():\n\n # XXX Note that this method doesn't really buy us much,\n # especially since we have to account for the fact that a\n # ostensibly non-read-only storage may be read-only\n # transiently. It would be better to just have read-only errors.", "def read_only(self, value: bool) -> None:\n if value:\n self._core = self._read_only_core\n elif self._authorized_core is None:\n msg = (\n \"read_only cannot be unset as only the ReadOnlyAuthorizer is available.\"\n )\n raise ClientException(msg)\n else:\n self._core = self._authorized_core", "def read_only_root_filesystem(self, read_only_root_filesystem):\n if read_only_root_filesystem is None:\n raise ValueError(\"Invalid value for `read_only_root_filesystem`, must not be `None`\")\n\n self._read_only_root_filesystem = read_only_root_filesystem", "def application_enableapi(self, application_enableapi):\n\n self._application_enableapi = application_enableapi", "def enable(app, user_class, role_class):\n app.logger.info('Enabling security')\n user_class.add_cross_reference(role_class)\n\n # configure security with role and user classes\n user_datastore = SQLAlchemyUserDatastore(app.db, user_class, role_class)\n app.security = Security(app, user_datastore)\n app.security.user_datastore = user_datastore\n\n return app.security" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Enable object storage management for the given application.
def enable_object_storage_management(request): log('Enabling object store management') _assign_role(request, StandardRole.OBJECT_STORE_MANAGER)
[ "def enable_storage(self):\n self.storage_enabled = True", "def enable_object_storage_access(request):\n log('Enabling object storage read')\n _assign_role(request, StandardRole.OBJECT_STORE_READER)", "def enable_block_storage_management(request):\n log('Enabling block storage management')\n _assign_role(request, _get_role('disk-manager'))", "def requested_object_storage_management(self):\n return bool(self._unit.received[\"enable-object-storage-management\"])", "def set_object_store_backend(backend):\n global _objstore_backend\n\n if backend == _objstore_backend:\n return\n\n if _objstore_backend is not None:\n from Acquire.ObjectStore import ObjectStoreError\n raise ObjectStoreError(\"You cannot change the object store \"\n \"backend once it has been already set!\")\n\n _objstore_backend = backend", "def enable_api(event, data):\n DriveDevice.storage.api_enabled = data", "def storage(ctx):\n pass", "async def _start_storage(self) -> None:\n if self._storage is not None:\n self._storage.start()\n await self._storage.wait_completed()", "async def start_persistence(self):\n await self.tasks.start_persistence()", "def storage_setup(arguments):\n logger.info(\"Setting storage structure.\")\n setup_database()\n logger.info(\"Storage setup successful.\")", "def OnStorageMode(self, event):\n self._CreateThread(self._SwitchStorageMode)", "def upload_objdb_config(self, config):\n self.set(DBOBJ_CONFIG_PATH, config, system_obj=True)", "def start_persistence(self):\n self.tasks.start_persistence()", "async def create_storage(config, plugin_manager, loop):\n\n storage = StorageControl(config, plugin_manager, loop)\n await storage._init()\n return storage", "def register_filesystem(self, filesystem_class):\n self.filesystems.append(filesystem_class)", "def enableMaintenance(self, api_client):\n\n cmd = {'id': self.id}\n return api_client.enableStorageMaintenance(**cmd)", "def enable_app_for_project(self, txapp, project):\r\n txapp.projects.add(project)", "def storage_mode(self, storage_mode):\n\n self._storage_mode = storage_mode", "def has_storage(self, cls):\r\n return True" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Update all custom roles based on current definition file.
def update_roles(): sub_id = kv().get('charm.azure.sub-id') known_roles = {} for role_file in Path('files/roles/').glob('*.json'): role_name = role_file.stem role_data = json.loads(role_file.read_text()) role_fullname = role_data['Name'].format(sub_id) scope = role_data['AssignableScopes'][0].format(sub_id) role_data['Name'] = role_fullname role_data['AssignableScopes'][0] = scope try: # assume already exists, so try updating first _azure('role', 'definition', 'update', '--role-definition', json.dumps(role_data)) log('Updated existing role {}', role_fullname) except DoesNotExistAzureError: # doesn't exist, so create _azure('role', 'definition', 'create', '--role-definition', json.dumps(role_data)) log('Created new role {}', role_fullname) known_roles[role_name] = role_fullname kv().set('charm.azure.roles', known_roles)
[ "def apply_roles(self):\n minion_sets = []\n role_sets = []\n for instance in self.instances:\n minion = instance.get('minion')\n roles = set(minion.roles or [])\n for role in instance.get('roles', []):\n roles.add(role)\n roles = list(roles)\n minion_sets.append([minion])\n role_sets.append(roles)\n self.client.set_roles(minion_sets, role_sets, timeout=30)", "def updateRoleMappings(context):\n if isNotCMFPlominoProfile(context):\n return\n shortContext = context._profile_path.split(os.path.sep)[-3]\n if shortContext != 'CMFPlomino': # avoid infinite recursions\n return\n # THIS STEP MUST BE REMOVED\n # (but as it is permanent we need to unregister it properly)\n # wft = getToolByName(context.getSite(), 'portal_workflow')\n # wft.updateRoleMappings()", "def update_roles():\n\n roles = list_required_roles()\n\n roles_updated = 0\n updated_roles = []\n\n for role in roles:\n updated_role = get_updated_role(role)\n if updated_role and updated_role[\"version\"] != role[\"version\"]:\n print(\n \"update {role}: {version} -> {latest_version}\".format(\n role=role[\"name\"],\n version=role[\"version\"],\n latest_version=updated_role[\"version\"],\n )\n )\n roles_updated += 1\n updated_roles.append(updated_role)\n else:\n updated_roles.append(role)\n\n if roles_updated > 0:\n if len(roles) > len(updated_roles):\n print(\"update failed: roles missing from updated roles list\")\n sys.exit(1)\n\n update_required_roles(updated_roles)", "def update_roles(db, entity, roles):\n for rolename in roles:\n grant_role(db, entity=entity, rolename=rolename)", "def setRoles(self, roles):\n pass", "def reset_roles(self, new_roles):\n self.roles = new_roles", "async def roles(self, ctx):\n pass", "async def readd_roles(self, ctx):\n config = hf.database_toggle(ctx, self.bot.db['readd_roles'])\n if config['enable']:\n if not ctx.me.guild_permissions.manage_roles:\n await ctx.send(\"I lack permission to manage roles. Please fix that before enabling this\")\n hf.database_toggle(ctx, self.bot.db['readd_roles'])\n return\n await ctx.send(f\"I will readd roles to people who have previously left the server\")\n else:\n await ctx.send(\"I will NOT readd roles to people who have previously left the server\")\n if 'users' not in config:\n config['users'] = {}\n await hf.dump_json()", "def setup_roles(self):\n\t\tif self.data.restricted_roles:\n\t\t\tuser = frappe.get_doc(\"User\", frappe.session.user)\n\t\t\tfor role_name in self.data.restricted_roles:\n\t\t\t\tuser.append(\"roles\", {\"role\": role_name})\n\t\t\t\tif not frappe.db.get_value(\"Role\", role_name):\n\t\t\t\t\tfrappe.get_doc(dict(doctype=\"Role\", role_name=role_name)).insert()\n\t\t\t\t\tcontinue\n\n\t\t\t\trole = frappe.get_doc(\"Role\", role_name)\n\t\t\t\trole.disabled = 0\n\t\t\t\trole.save()\n\t\t\tuser.save()", "def test__Guild__update_roles():\n guild_id = 202306230110\n \n old_roles = [\n Role.precreate(202306230111),\n Role.precreate(202306230112),\n ]\n \n new_roles = [\n Role.precreate(202306230113),\n Role.precreate(202306230114),\n ]\n \n guild = Guild.precreate(guild_id, roles = old_roles)\n \n data = [role.to_data(include_internals = True) for role in new_roles]\n \n guild._update_roles(data)\n \n vampytest.assert_eq(guild.roles, {role.id: role for role in new_roles})", "def test_roles_update(self):\n pass", "def auto_assign_roles(self):\n self._put(\"service/autoAssignRoles\", None, api_version=6)", "def _update_role(self):\r\n postdata = self._portal._postdata()\r\n postdata['name'] = self._name\r\n postdata['description'] = self._description\r\n\r\n resp = self._portal.con.post('portals/self/roles/' + self.role_id + '/update', postdata)\r\n if resp:\r\n return resp.get('success')", "def test_roles_partial_update(self):\n pass", "def expand_roles(self):\n for i in range(len(self.roles)):\n role = self.roles[i]\n if role in NodeLayout.DEPRECATED_ROLES:\n AppScaleLogger.warn(\"'{}' role has been deprecated, please use '{}'\"\n .format(role, NodeLayout.DEPRECATED_ROLES[role]))\n self.roles.remove(role)\n self.roles.append(NodeLayout.DEPRECATED_ROLES[role])\n\n if 'master' in self.roles:\n self.roles.remove('master')\n self.roles.append('shadow')\n self.roles.append('load_balancer')\n\n # TODO: remove these, db_slave and taskqueue_slave are currently deprecated.\n if 'db_slave' in self.roles or 'db_master' in self.roles \\\n and 'database' not in self.roles:\n self.roles.append('database')\n\n if 'taskqueue_slave' in self.roles or 'taskqueue_master' in self.roles \\\n and 'taskqueue' not in self.roles:\n self.roles.append('taskqueue')\n\n # Remove any duplicate roles\n self.roles = list(set(self.roles))", "def load(self):\n self.update({\n \"roles\": {\n \"default\": [],\n \"admin\": []\n },\n \"files\": {},\n \"general\": {\n \"users_remove_locks\": [],\n \"roles_remove_locks\": [\"default\", \"admin\"],\n \"users_add_locks\": [],\n \"roles_add_locks\": [\"default\", \"admin\"],\n \"users_write\": [],\n \"roles_write\": [\"default\", \"admin\"],\n \"users_grant\": [],\n \"roles_grant\": [\"default\", \"admin\"],\n \"users_modify_roles\": [],\n \"roles_modify_roles\": [\"default\", \"admin\"]\n }\n })\n try:\n self.update(json.load(open(self.__path)))\n except FileNotFoundError:\n # Log that loading the configuration failed\n Logger.info('MEG PERMISSIONS: Could not load permissions file <' + self.__path + '>, using default permissions')", "def add_roles(self, roles):\n for role in roles:\n self.add_role(role)", "async def _courses_roles(self, ctx):\n pass", "def _get_custom_roles(self):\n print('Getting custom roles...')\n\n return self._run_az([\n 'role', 'definition', 'list',\n '--custom-role-only', 'true'\n ])" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Elide s in the middle to ensure it is under max_len. That is, shorten the string, inserting an ellipsis where the removed characters were to show that they've been removed.
def _elide(s, max_len, ellipsis='...'): if len(s) > max_len: hl = (max_len - len(ellipsis)) / 2 headl, taill = floor(hl), ceil(hl) s = s[:headl] + ellipsis + s[-taill:] return s
[ "def shorten(s, maxlen=20):\n halflen = int(maxlen / 2) - 2\n return s if len(s) <= maxlen else (s[:halflen]+'...'+s[-halflen:])[:maxlen]", "def _truncate(s, limit): \n\ts = force_unicode(s) \n\tif len(s) <= limit: \n\t\treturn s \n\treturn '%s...' % s[:max(1, limit - 3)] \n\ttruncate = allow_lazy(truncate, unicode)", "def truncate_str(s: str, max_len: int, *, suffix: str = \"[...]\") -> str:\n if len(s) <= max_len:\n return s\n else:\n adj_len = max_len - len(suffix)\n if adj_len > 0:\n return s[:adj_len] + suffix\n else:\n return suffix", "def str_ellipsis(string: str, max_length: int = 40) -> str:\n if len(string) <= max_length:\n return string\n n_2 = int(max_length) / 2 - 3\n n_1 = max_length - n_2 - 3\n\n return f\"{string[:int(n_1)]}...{string[-int(n_2):]}\"", "def truncate(s, output_length, ellipsis_count=3):\n if len(s) > output_length:\n return s[:output_length - ellipsis_count] + ellipsis_count * '.'\n else:\n return s", "def shorten_msg(msg,max_len):\n if len(msg) > max_len:\n h0=floor(max_len/2)\n h1=max_len-h0\n msg=msg[:h0]+\"\\n ---skipped--- \\n\" + msg[ - h1:]\n return msg", "def trim_string(text: str, max_length: int = 200, ellipsis: str = \"...\") -> str:\n assert max_length >= len(ellipsis)\n if len(text) > max_length:\n return text[: max_length - len(ellipsis)] + ellipsis\n else:\n return text", "def ellipsisify(s, n):\n if len(s) <= n:\n return s\n else:\n return (textwrap.wrap(s, n-3)[0] + '...')", "def smart_truncate(text, limit=100, suffix='...'):\n if len(text) <= limit:\n return text\n\n return text[:limit].rsplit(' ', 1)[0]+suffix", "def elipses(long_string,max_length=40,elipses='...'):\n strlen=len(long_string)\n if strlen<max_length:\n return long_string\n else:\n return long_string[0:max_length-len(elipses)]+elipses", "def truncate(value, max_length):\n if len(value) < max_length:\n return value\n return value[:max_length-1] + u'…'", "def truncate_string_from_end(string: str, max_len: int) -> str:\n\tif len(string) <= max_len:\n\t\treturn string\n\treturn f'Last {max_len} chars: \"...{string[-max_len:]}\"'", "def ellipsis(v: str, width: int) -> str:\n lv = len(v)\n if lv <= width:\n return v\n assert width >= 5\n wl = (width - 3) // 2\n return v[: wl + 1] + \"...\" + v[-wl:]", "def truncate(string, length, ellipsis='…'):\n if len(string) > length:\n return string[:length - len(ellipsis)] + ellipsis\n return string", "def truncate(msg, limit):\n if len(msg) <= limit:\n return msg\n\n half = limit // 2\n return '\\n'.join([\n msg[:half],\n '...%d characters truncated...' % (len(msg) - limit), msg[-half:]\n ])", "def shorten(string, max_length, methods=\"right\"):\n overhead = len(string) - max_length\n if overhead <= 0:\n return string\n\n if \"signs\" in methods:\n signs = [\"-\", \"_\", \".\"]\n s = \"\"\n for l in string[::-1]:\n if l in signs and overhead > 0:\n overhead -= 1\n else:\n s += l\n string = s[::-1]\n\n if \"vowels\" in methods:\n vowels = [\"a\", \"e\", \"i\", \"o\", \"u\"]\n s = \"\"\n for l in string[::-1]:\n if l in vowels and overhead > 0:\n overhead -= 1\n else:\n s += l\n string = s[::-1]\n\n if \"right\" in methods:\n string = string[:max_length]\n elif \"left\" in methods:\n string = string[len(string) - max_length :]\n elif \"center\" in methods:\n string = string[: ceil(max_length / 2)] + string[len(string) - floor(max_length / 2) :]\n\n return string", "def abbreviate(cls, s, length=None):\n if not s is None:\n s = s.strip()\n if length is not None and len(s) > length:\n return s[:length] + '...'\n return s", "def cut(string, l):\n\tif len(string) <= l:\n\t\treturn string\n\treturn string[:l-3]+\"...\"", "def shorten_name(name, max_length, remain_start, remain_end):\n if len(name) > max_length:\n return f'{name[:remain_start]} ... {name[-remain_end:]}'\n return name" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Translate the subscription ID into a tenant ID by making an unauthorized request to the API and extracting the tenant ID from the WWWAuthenticate header in the error response.
def _get_tenant_id(subscription_id): url = ('https://management.azure.com/subscriptions/' '{}?api-version=2018-03-01-01.6.1'.format(subscription_id)) try: urlopen(url) log_err('Error getting tenant ID: did not get "unauthorized" response') return None except HTTPError as e: if 'WWW-Authenticate' not in e.headers: log_err('Error getting tenant ID: missing WWW-Authenticate header') return None www_auth = e.headers['WWW-Authenticate'] match = re.search(r'authorization_uri="[^"]*/([^/"]*)"', www_auth) if not match: log_err('Error getting tenant ID: unable to find in {}', www_auth) return None return match.group(1)
[ "def http_get_tenant_id(tenant_id):\n my = config_dic['http_threads'][threading.current_thread().name]\n\n try:\n tenant = my.ovim.show_tenant_id(tenant_id)\n delete_nulls(tenant)\n change_keys_http2db(tenant, http2db_tenant, reverse=True)\n data = {'tenant': tenant}\n return format_out(data)\n except ovim.ovimException as e:\n my.logger.error(str(e), exc_info=True)\n bottle.abort(e.http_code, str(e))\n except Exception as e:\n my.logger.error(str(e), exc_info=True)\n bottle.abort(HTTP_Bad_Request, str(e))", "def subscription_tenant_id(self) -> Optional[pulumi.Input[str]]:\n return pulumi.get(self, \"subscription_tenant_id\")", "def _getToken(self):\n\n url = \"https://login.microsoftonline.com/{0!s}/oauth2/token\".format(self._tenant_id)\n \n payload = {\n \"grant_type\":\"client_credentials\",\n \"client_id\":self._client_id,\n \"client_secret\": self._client_secret,\n \"resource\":\"https%3A%2F%2Fapi.timeseries.azure.com%2F&undefined=\"\n }\n \n payload = \"grant_type={grant_type}&client_id={client_id}&client_secret={client_secret}&resource={resource}\".format(**payload)\n\n headers = {\n 'Content-Type': \"application/x-www-form-urlencoded\",\n 'cache-control': \"no-cache\"\n }\n\n try:\n response = requests.request(\"POST\", url, data=payload, headers=headers, timeout=10)\n response.raise_for_status()\n except requests.exceptions.ConnectTimeout:\n logging.error(\"TSIClient: The request to the TSI api timed out.\")\n raise\n except requests.exceptions.HTTPError as e:\n status_code = e.response.status_code\n if status_code == 401:\n logging.error(\"TSIClient: Authentication with the TSI api was unsuccessful. Check your client secret.\")\n else:\n logging.error(\"TSIClient: The request to the TSI api returned an unsuccessfull status code. Check the stack trace\")\n raise\n\n jsonResp = json.loads(response.text)\n tokenType = jsonResp['token_type']\n authorizationToken = tokenType +\" \" + jsonResp['access_token']\n return authorizationToken", "def test_process_get_tenant(self):\n error, out = self.process_get_tenant()\n for err in error: assert err == 0", "def test_create_tenant_request_without_token(self):\n tenant_name = data_utils.rand_name(name='tenant')\n token = self.client.auth_provider.get_token()\n self.client.delete_token(token)\n self.assertRaises(lib_exc.Unauthorized,\n self.tenants_client.create_tenant,\n name=tenant_name)\n self.client.auth_provider.clear_auth()", "def _extract_token() -> str:\n auth_header = request.headers.get(\"Authorization\")\n\n try:\n if auth_header:\n bearer, id_token = auth_header.split(\" \")\n assert bearer.lower() == \"bearer\"\n else:\n id_token = request.json[\"id_token\"]\n except (AssertionError, AttributeError, KeyError, TypeError, ValueError):\n raise Unauthorized(\n \"Either the 'Authorization' header must be set with structure 'Authorization: Bearer <id token>' \"\n 'or \"id_token\" must be present in the JSON body of the request.'\n )\n\n return id_token", "def parse_auth_response(auth_response):\r\n\r\n def _service_ep(scat, types_list):\r\n for srv in scat:\r\n if srv.get('name') in types_list:\r\n index_id = types_list.index(srv.get('name'))\r\n index = types_list[index_id]\r\n if srv.get('name') == index:\r\n return srv.get('endpoints')\r\n else:\r\n return None\r\n\r\n access = auth_response.get('access')\r\n token = access.get('token').get('id')\r\n\r\n if 'tenant' in access.get('token'):\r\n tenant = access.get('token').get('tenant').get('name')\r\n user = access.get('user').get('name')\r\n elif 'user' in access:\r\n tenant = None\r\n user = access.get('user').get('name')\r\n else:\r\n LOG.error('No Token Found to Parse.\\nHere is the DATA: %s\\n%s',\r\n auth_response, traceback.format_exc())\r\n raise turbo.NoTenantIdFound('When attempting to grab the '\r\n 'tenant or user nothing was found.')\r\n\r\n if ARGS.get('os_rax_auth') is not None:\r\n region = ARGS.get('os_rax_auth')\r\n elif ARGS.get('os_hp_auth') is not None:\r\n if ARGS.get('os_tenant') is None:\r\n raise turbo.NoTenantIdFound(\r\n 'You need to have a tenant set to use HP Cloud'\r\n )\r\n region = ARGS.get('os_hp_auth')\r\n elif ARGS.get('os_region') is not None:\r\n region = ARGS.get('os_region')\r\n else:\r\n raise turbo.SystemProblem('No Region Set')\r\n\r\n scat = access.pop('serviceCatalog')\r\n\r\n cfl = _service_ep(scat, info.__srv_types__)\r\n cdn = _service_ep(scat, info.__cdn_types__)\r\n\r\n if cfl is not None:\r\n inet = get_surl(region=region, cf_list=cfl, lookup='internalURL')\r\n enet = get_surl(region=region, cf_list=cfl, lookup='publicURL')\r\n else:\r\n need_tenant = ' Maybe you need to specify \"os-tenant\"?'\r\n gen_message = ('No Service Endpoints were found for use with Swift.'\r\n ' If you have Swift available to you,'\r\n ' Check Your Credentials and/or Swift\\'s availability'\r\n ' using Token Auth.')\r\n if ARGS.get('os_tenant') is None:\r\n gen_message += need_tenant\r\n raise turbo.SystemProblem(gen_message)\r\n\r\n if cdn is not None:\r\n cnet = get_surl(region=region, cf_list=cdn, lookup='publicURL')\r\n else:\r\n cnet = None\r\n\r\n return token, tenant, user, inet, enet, cnet, cfl", "def _get_tenant_id_for_message(message):\n\n # give priority to the tenant_id in the router dict if one\n # exists in the message\n payload = message.get('payload', {})\n\n for key in ('router', 'port', 'subnet'):\n if key in payload and payload[key].get('tenant_id'):\n val = payload[key]['tenant_id']\n # LOG.debug('using tenant id from payload[\"%s\"][\"tenant_id\"] = %s',\n # key, val)\n return val\n\n for key in ['_context_tenant_id', '_context_project_id']:\n if key in message:\n val = message[key]\n # Some notifications have None as the tenant id, but we\n # can't shard on None in the dispatcher, so treat those as\n # invalid.\n if val is not None:\n # LOG.debug('using tenant id from message[\"%s\"] = %s',\n # key, val)\n return val\n return None", "def test_list_tenant_request_without_token(self):\n token = self.client.auth_provider.get_token()\n self.client.delete_token(token)\n self.assertRaises(lib_exc.Unauthorized,\n self.tenants_client.list_tenants)\n self.client.auth_provider.clear_auth()", "def _validate_id_token_data(token_data):\n aud = token_data.get(\"aud\")\n if not aud or aud != settings.COGNITO_USER_LOGIN_CLIENT_ID:\n raise exceptions.AuthenticationFailed(\"Invalid id token\")", "def get_tenant(request):\n if hasattr(request, 'tenant'):\n return request.tenant\n return None", "def subscription():\n\n if request.method == \"GET\":\n return Response(response=json.dumps({\"public_key\": os.getenv(\"VAPID_PUBLIC_KEY\")}),\n headers={\"Access-Control-Allow-Origin\": \"*\"}, content_type=\"application/json\")\n\n subscription_token = request.get_json(\"subscription_token\")\n return Response(status=201, mimetype=\"application/json\")", "def tenant_id(self, tenant_name, auth_ref=None, cache_ref=None):\n all_tenants = self.list_tenants_admin(auth_ref=auth_ref)\n for t in all_tenants['tenants']:\n if t['name'].lower() == tenant_name.lower():\n return t['id']\n raise Exception('not found')", "def test_tenant_delete_request_without_token(self):\n tenant = self.setup_test_tenant()\n token = self.client.auth_provider.get_token()\n self.client.delete_token(token)\n self.assertRaises(lib_exc.Unauthorized,\n self.tenants_client.delete_tenant,\n tenant['id'])\n self.client.auth_provider.clear_auth()", "def test_get_an_interest_by_unauthenticated_user_fails(self):\n response = self.client.get(self.endpoint_url)\n response_body = response.get_json()\n self.assertEqual(response.status_code, 401)\n self.assertEqual(response_body[\"SubCode\"], \"InvalidToken\")", "def tenant(self, tenant):\n\n self.errors[tenant] = defaultdict(list)\n self.current_tenant = tenant", "def challenge():\n return Response(\n status=401, headers={\n \"WWW-Authenticate\": \"Basic realm=\\\"Dummy API\\\"\"\n })", "def _create_signed_id_token(self,\n client_id, # type: str\n sub, # type: str\n user_claims=None, # type: Optional[Mapping[str, Union[str, List[str]]]]\n nonce=None, # type: Optional[str]\n authorization_code=None, # type: Optional[str]\n access_token_value=None, # type: Optional[str]\n extra_id_token_claims=None): # type: Optional[Mappings[str, Union[str, List[str]]]]\n # type: (...) -> str\n\n alg = self.clients[client_id].get('id_token_signed_response_alg',\n self.configuration_information['id_token_signing_alg_values_supported'][0])\n args = {}\n\n hash_alg = 'HS{}'.format(alg[-3:])\n if authorization_code:\n args['c_hash'] = jws.left_hash(authorization_code.encode('utf-8'), hash_alg)\n if access_token_value:\n args['at_hash'] = jws.left_hash(access_token_value.encode('utf-8'), hash_alg)\n\n if user_claims:\n args.update(user_claims)\n\n if extra_id_token_claims:\n args.update(extra_id_token_claims)\n\n id_token = IdToken(iss=self.configuration_information['issuer'],\n sub=sub,\n aud=client_id,\n iat=int(time.time()),\n exp=int(time.time()) + self.id_token_lifetime,\n **args)\n\n if nonce:\n id_token['nonce'] = nonce\n\n logger.debug('signed id_token with kid=%s using alg=%s', self.signing_key, alg)\n return id_token.to_jwt([self.signing_key], alg)", "def test_custom_sub_generator(self):\n code = self._create_code()\n\n post_data = self._auth_code_post_data(code=code.code)\n\n response = self._post_request(post_data)\n\n response_dic = json.loads(response.content.decode('utf-8'))\n id_token = JWT().unpack(response_dic['id_token'].encode('utf-8')).payload()\n\n self.assertEqual(id_token.get('sub'), self.user.email)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Call the azurecli tool.
def _azure(cmd, *args, return_stderr=False): cmd = ['az', cmd] cmd.extend(args) result = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout = result.stdout.decode('utf8').strip() stderr = result.stderr.decode('utf8').strip() if result.returncode != 0: raise AzureError.get(stderr) if return_stderr: return stderr if stdout: stdout = json.loads(stdout) return stdout
[ "def cli():\n\n parser = argparse.ArgumentParser()\n\n parser.add_argument(\n '-U', '--cot_url', help='URL to CoT Destination.',\n required=True\n )\n parser.add_argument(\n '-K', '--fts_token', help='FreeTAKServer REST API Token.'\n )\n parser.add_argument(\n '-S', '--cot_stale', help='CoT Stale period, in seconds',\n )\n\n parser.add_argument(\n '-c', '--callsign', help='APRS-IS Login Callsign',\n required=True\n )\n parser.add_argument(\n '-p', '--passcode', help='APRS-IS Passcode', default='-1'\n )\n parser.add_argument(\n '-a', '--aprs_host', help='APRS-IS Host (or Host:Port).',\n default='rotate.aprs.net:14580'\n )\n parser.add_argument(\n '-f', '--aprs_filter',\n help='APRS-IS Filter, see: http://www.aprs-is.net/javAPRSFilter.aspx',\n default='m/10'\n )\n\n opts = parser.parse_args()\n\n if sys.version_info[:2] >= (3, 7):\n asyncio.run(main(opts), debug=bool(os.environ.get('DEBUG')))\n else:\n loop = asyncio.get_event_loop()\n try:\n loop.run_until_complete(main(opts))\n finally:\n loop.close()", "def login_cli(creds_data):\n app_id = creds_data['application-id']\n app_pass = creds_data['application-password']\n sub_id = creds_data['subscription-id']\n tenant_id = _get_tenant_id(sub_id)\n try:\n log('Forcing logout of Azure CLI')\n _azure('logout')\n except AzureError:\n pass\n try:\n log('Logging in to Azure CLI')\n _azure('login',\n '--service-principal',\n '-u', app_id,\n '-p', app_pass,\n '-t', tenant_id)\n # cache the subscription ID for use in roles\n kv().set('charm.azure.sub-id', sub_id)\n except AzureError as e:\n # redact the credential info from the exception message\n stderr = re.sub(app_id, '<app-id>', e.args[0])\n stderr = re.sub(app_pass, '<app-pass>', stderr)\n stderr = re.sub(tenant_id, '<tenant-id>', stderr)\n # from None suppresses the previous exception from the stack trace\n raise AzureError(stderr) from None", "def _run_az(self, cmd: List[str]) -> [list, dict]:\n az_cmd = [self._cli_path]\n az_cmd.extend(cmd)\n\n try:\n result = json.loads(self._run_cmd(az_cmd))\n except Exception as ex:\n if str(ex).startswith('ERROR'):\n raise APIError(str(ex))\n else:\n raise\n\n return result", "def cli() -> callable:\n return _cli", "def _find_cli(self) -> str:\n cli_path = self._run_cmd(['which', 'az'])\n if not cli_path:\n raise Exception('Azure CLI not found')\n\n return cli_path", "def main(n: int = None, verbose: bool = False) -> None:\n try:\n # Using --query to map subset of fields and sort by name (ascending)\n list_cmd = 'account list --all --output json ' \\\n '--query \"sort_by([].{name:name, isDefault:isDefault, id:id, state:state}, &name)\"'\n if verbose:\n click.echo(f'Issuing AZ CLI command: {list_cmd}')\n\n exit_code, subscriptions, logs = az(list_cmd)\n if exit_code != 0:\n raise ValueError(logs)\n\n if len(subscriptions) == 0:\n click.echo(click.style(\"No subscriptions found, requires: az login!\", fg='yellow'))\n return\n\n current_nr = _print_options(subscriptions)\n\n if not n:\n n = click.prompt('Switch', type=int, default=str(current_nr))\n\n if n not in range(1, len(subscriptions) + 1):\n raise ValueError(\"Value not in range! Not changing subscription.\")\n\n if n == current_nr:\n click.echo(\"Selection is same as current. Not changing subscription.\")\n else:\n _select_subscription(n, subscriptions, verbose)\n\n active = subscriptions[n-1]\n click.echo(\"Active: \" + click.style(active['id'] + \": \" + active['name'], fg='green', bold=True))\n\n if active['state'].lower() == 'disabled':\n click.echo(click.style(\"Subscription state is Disabled, requires: az login!\", fg='yellow'))\n\n except click.exceptions.Abort:\n # No need to raise exception when CTRL-C out of the cli\n pass\n except ValueError as e:\n print(e)", "def run_cli_command():\n\n def _run_cli_command(command, options):\n \"\"\"Run the command and check the result.\"\"\"\n import traceback\n\n from click.testing import CliRunner\n\n runner = CliRunner()\n result = runner.invoke(command, options)\n\n assert result.exception is None, ''.join(traceback.format_exception(*result.exc_info))\n assert result.exit_code == 0, result.output\n\n return _run_cli_command", "def executor_cli():", "def get_cli_active_cloud():\n\n try:\n from azure.cli.core.cloud import get_active_cloud\n except ImportError:\n raise ImportError(\"You need to install 'azure-cli-core' to load CLI active Cloud\")\n return get_active_cloud()", "def testdoc_cli(arguments):\n TestDoc().execute_cli(arguments)", "def run_from_cli():\n\n arg_parser = argparse.ArgumentParser(\n description='Backup and restore all your self-hosted WordPress '\n 'content.',\n prog='python -m wordpressbackup')\n\n arg_parser.add_argument('--backup',\n action='store_true',\n help='Perform a backup')\n\n arg_parser.add_argument('--restore',\n action='store_true',\n help='Perform a restoration')\n\n arg_parser.add_argument('--wp-dir',\n help='Path to the root of the WordPress directory',\n required=True)\n\n arg_parser.add_argument('--archive',\n help='Path and filename of the archive (.tar.gz) '\n 'to backup to/restore from.',\n required=True)\n\n arg_parser.add_argument('--admin-username',\n help='Database admin username. Required only for '\n 'restorations.',\n required=False)\n\n arg_parser.add_argument('--admin-password',\n help='Database admin password. Required only for '\n 'restorations.',\n required=False)\n\n arg_parser.add_argument('--admin-credentials-aws-secret-id',\n help='Database admin credentials secret ID. '\n 'Required only for restorations.',\n required=False)\n\n arg_parser.add_argument('--admin-credentials-aws-region',\n help='Region in which the database admin '\n 'credentials secret resides. Required only '\n 'for restorations.',\n required=False)\n\n arg_parser.add_argument('--log-level',\n default='CRITICAL',\n help='Log level',\n required=False)\n\n arg_parser.add_argument('--only-appointed-in-asg',\n action='store_true',\n help='Ensure that only one AWS EC2 instance in '\n 'this auto-scaling group performs the '\n 'action.')\n\n args = arg_parser.parse_args()\n\n if args.backup == args.restore:\n arg_parser.error('Must specify either --backup or --restore.')\n\n logging.basicConfig(level=str(args.log_level).upper())\n log = logging.getLogger(__name__)\n\n if args.only_appointed_in_asg:\n if not chesney.is_appointed():\n log.fatal('This EC2 instance is not appointed.')\n exit(0)\n\n if args.backup:\n wpbackup.backup(wp_directory=args.wp_dir,\n archive_filename=args.archive)\n elif args.restore:\n if args.admin_credentials_aws_secret_id:\n credentials = wpbackup.Credentials.from_aws_secrets_manager(\n secret_id=args.admin_credentials_aws_secret_id,\n region=args.admin_credentials_aws_region\n )\n else:\n credentials = wpbackup.Credentials.from_username_and_password(\n username=args.admin_username,\n password=args.admin_password\n )\n\n wpbackup.restore(wp_directory=args.wp_dir,\n archive_filename=args.archive,\n admin_credentials=credentials)", "def cli_cmd(host, module, args):\n if len(args) > 1:\n args = [' '.join(args)]\n\n command = ['ansible', host, '-m', module, '-a'] + args\n process = LocalExec(command)\n process.run_and_wait()\n return process", "def main():\n CLI.from_command_line()\n exit(0)", "def test_cli_help():\n runner = CliRunner()\n help_result = runner.invoke(cli.main, ['--help'])\n assert help_result.exit_code == 0\n assert 'Show this message and exit.' in help_result.output", "def run_amtool(args):\n # TODO(jelmer): Support setting the current user, e.g. for silence\n # ownership.\n ret = subprocess.run(\n [\"amtool\"] + args, shell=False, universal_newlines=True,\n stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n return ret.stdout", "def test_cli_help():\n runner = CliRunner()\n help_result = runner.invoke(cli.main, [\"--help\"])\n assert help_result.exit_code == 0\n assert \"Show this message and exit.\" in help_result.output", "def call_casa_task(task, script, task_options={}, casa_options={}, delete=True, verbose=True):\n # creating casa script\n scriptname = '{}.py'.format(script)\n if os.path.exists(scriptname):\n os.system('rm -r {}'.format(scriptname))\n stdout = open(scriptname, 'wb')\n line = 'default({})\\n'.format(task)\n for key in task_options.keys():\n line += '{}={}\\n'.format(key, task_options[key])\n line += 'go()'\n line = line.encode() # converting to bytes\n stdout.write(line)\n stdout.close()\n # casa otpions\n casa_out = ''\t\n keys = casa_options.keys()\n # location of startup file\n if 'rcdir' in keys:\n casa_out += '--rcdir {} '.format(casa_options['rcdir'])\n # path to logfile\n if 'logfile' in keys:\n casa_out += '--logfile {} '.format(casa_options['logfile'])\n # logger to use on Apple systems\n if 'maclogger' in keys:\n casa_out += '--maclogger '\n # direct output to terminal\n if 'log2term' in keys:\n casa_out += '--log2term '\n # do not start CASA logger\n if 'nologger' in keys:\n casa_out += '--nologger '\n # do not creat log file \n if 'nologfile' in keys:\n casa_out += '--nologfile '\n # avoid starting GUI tools\n if 'nogui' in keys:\n casa_out += '--nogui'\n # prompt color [NoColor, Linux, LightBG]\n if 'colors' in keys:\n casa_out += '--colors {} '.format(casa_options['colors'])\n # do not create ipython log\n if 'noipython' in keys:\n casa_out += '--noipython '\n command = 'casa {} -c {}'.format(casa_out, scriptname)\n if verbose:\n print ('CMD: {}'.format(command))\n os.system(command)\n if delete: \n os.system('rm -r {}'.format(scriptname))", "def run_cli():\n\n parser = argparse.ArgumentParser(\n description=\"Starts the T2K Data Manager - Command Line Interface.\"\n )\n args = parser.parse_args()\n\n try:\n T2KDmCli().cmdloop()\n except KeyboardInterrupt: # Exit gracefully on CTRL-C\n print_(\"\")", "def run_amtool(args):\n # TODO(jelmer): Support setting the current user, e.g. for silence ownership.\n ret = subprocess.run(\n [\"/usr/bin/amtool\"] + args, shell=False, text=True,\n stdout=subprocess.PIPE)\n return ret.stdout" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Translate short role name into a full role name and ensure that the custom role is loaded. The custom roles have to be applied to a specific subscription ID, but the subscription ID applies to the entire credential, so will almost certainly be reused, so there's not much danger in hitting the 2k custom role limit.
def _get_role(role_name): known_roles = kv().get('charm.azure.roles', {}) if role_name in known_roles: return known_roles[role_name] sub_id = kv().get('charm.azure.sub-id') role_file = Path('files/roles/{}.json'.format(role_name)) role_data = json.loads(role_file.read_text()) role_fullname = role_data['Name'].format(sub_id) scope = role_data['AssignableScopes'][0].format(sub_id) role_data['Name'] = role_fullname role_data['AssignableScopes'][0] = scope try: log('Ensuring role {}', role_fullname) _azure('role', 'definition', 'create', '--role-definition', json.dumps(role_data)) except AlreadyExistsAzureError: pass known_roles[role_name] = role_fullname kv().set('charm.azure.roles', known_roles) return role_fullname
[ "async def role(self, context, *text):\n \n if text[0] in config[\"roles\"].keys():\n subrole = \" \".join(text[1:])\n if subrole in config[\"roles\"].keys():\n await self.bot.say(toggle_role_subrole(text[0], subrole))\n else:\n await self.bot.say(\"One or more of the roles you used is not yet configured or does not exist.\")", "def _get_custom_roles(self):\n print('Getting custom roles...')\n\n return self._run_az([\n 'role', 'definition', 'list',\n '--custom-role-only', 'true'\n ])", "async def set_submod_role(self, ctx, *, role_name):\n config = hf.database_toggle(ctx, self.bot.db['submod_role'])\n if 'enable' in config:\n del (config['enable'])\n submod_role = discord.utils.find(lambda role: role.name == role_name, ctx.guild.roles)\n if not submod_role:\n await ctx.send(\"The role with that name was not found\")\n return None\n config['id'] = submod_role.id\n await ctx.send(f\"Set the submod role to {submod_role.name} ({submod_role.id})\")\n await hf.dump_json()", "def prepare_account_name_for_jwt(self, raw_account: str) -> str:\n account = raw_account\n if \".global\" not in account:\n # Handle the general case.\n idx = account.find(\".\")\n if idx > 0:\n account = account[0:idx]\n else:\n # Handle the replication case.\n idx = account.find(\"-\")\n if idx > 0:\n account = account[0:idx] # pragma: no cover\n # Use uppercase for the account identifier.\n return account.upper()", "def system_wide_role(self):\n # FIXME: This method should be in `ggrc_basic_permissions`, since it\n # depends on `Role` and `UserRole` objects\n\n if self.email in getattr(settings, \"BOOTSTRAP_ADMIN_USERS\", []):\n return u\"Superuser\"\n\n role_hierarchy = {\n u'Administrator': 0,\n u'Editor': 1,\n u'Reader': 2,\n u'Creator': 3,\n }\n unique_roles = set([\n user_role.role.name\n for user_role in self.user_roles\n if user_role.role.name in role_hierarchy\n ])\n if len(unique_roles) == 0:\n return u\"No Access\"\n else:\n # -1 as default to make items not in this list appear on top\n # and thus shown to the user\n sorted_roles = sorted(unique_roles,\n key=lambda x: role_hierarchy.get(x, -1))\n return sorted_roles[0]", "def expected_meta_rolename(meta_rolename):\n \n return string.capwords(meta_rolename)", "def get_role_name(self):\n try:\n return self.tags['Role']\n except KeyError:\n return None", "def update_roles():\n sub_id = kv().get('charm.azure.sub-id')\n known_roles = {}\n for role_file in Path('files/roles/').glob('*.json'):\n role_name = role_file.stem\n role_data = json.loads(role_file.read_text())\n role_fullname = role_data['Name'].format(sub_id)\n scope = role_data['AssignableScopes'][0].format(sub_id)\n role_data['Name'] = role_fullname\n role_data['AssignableScopes'][0] = scope\n try:\n # assume already exists, so try updating first\n _azure('role', 'definition', 'update',\n '--role-definition', json.dumps(role_data))\n log('Updated existing role {}', role_fullname)\n except DoesNotExistAzureError:\n # doesn't exist, so create\n _azure('role', 'definition', 'create',\n '--role-definition', json.dumps(role_data))\n log('Created new role {}', role_fullname)\n known_roles[role_name] = role_fullname\n kv().set('charm.azure.roles', known_roles)", "def role(default='default', role_prefix='haproxy'):\n haproxy_role = None\n for role in __salt__['grains.get']('roles', []):\n assert isinstance(role, basestring)\n if role.startswith(role_prefix):\n if haproxy_role:\n raise CommandExecutionError('Error executing haproxy.role(default={0}, role_prefix={1}): ambiguous role prefix'.format(default, role_prefix))\n haproxy_role = role.lstrip(role_prefix).lstrip('.') or default\n\n if haproxy_role is None:\n haproxy_role = default\n return haproxy_role", "async def get_role(\n guild: discord.Guild,\n name: str,\n overwrite: discord.PermissionOverwrite = None,\n permissions: discord.Permissions = None,\n) -> discord.Role:\n role = discord.utils.find(lambda r: r.name.lower() == name.lower(), guild.roles)\n\n if role is None:\n role = await guild.create_role(name=name, permissions=permissions or discord.Permissions.none())\n elif permissions is not None and role.permissions != permissions:\n await role.edit(permissions=permissions)\n\n if overwrite is None:\n return role\n\n for channel in guild.channels:\n if channel.category and channel.permissions_synced:\n channel = channel.category\n if channel.overwrites_for(role) != overwrite:\n await channel.set_permissions(role, overwrite=overwrite)\n\n return role", "def get_role(obj, role_name):\n for role in obj.roles:\n if role.name == role_name:\n return role\n return None", "def expand_roles(self):\n for i in range(len(self.roles)):\n role = self.roles[i]\n if role in NodeLayout.DEPRECATED_ROLES:\n AppScaleLogger.warn(\"'{}' role has been deprecated, please use '{}'\"\n .format(role, NodeLayout.DEPRECATED_ROLES[role]))\n self.roles.remove(role)\n self.roles.append(NodeLayout.DEPRECATED_ROLES[role])\n\n if 'master' in self.roles:\n self.roles.remove('master')\n self.roles.append('shadow')\n self.roles.append('load_balancer')\n\n # TODO: remove these, db_slave and taskqueue_slave are currently deprecated.\n if 'db_slave' in self.roles or 'db_master' in self.roles \\\n and 'database' not in self.roles:\n self.roles.append('database')\n\n if 'taskqueue_slave' in self.roles or 'taskqueue_master' in self.roles \\\n and 'taskqueue' not in self.roles:\n self.roles.append('taskqueue')\n\n # Remove any duplicate roles\n self.roles = list(set(self.roles))", "def lookup_role_arn(roleName):\n lastSlash = roleName.rfind(\"/\")\n if lastSlash >= 0:\n prefix = roleName[:lastSlash+1]\n baseName = roleName[lastSlash+1:]\n else:\n prefix = \"/\"\n baseName = roleName\n for page in iam_client.get_paginator('list_roles').paginate(PathPrefix=prefix):\n for role in page['Roles']:\n if baseName == role['RoleName']:\n return role['Arn']\n raise Exception(f'Unable to find role with name \"{roleName}\"')", "async def add_sub_role(self, ctx, *, role:discord.Role):\n roles = self.egl_db.get('sub_roles', [])\n if role.name in roles:\n await self.bot.say('This role is already subscribable')\n return\n\n if role.permissions.value > 0:\n await self.bot.say('You cannot add a role with any permissions for server security reasons.')\n return\n\n await self.bot.say('You can add this role to the list of subscribable roles.')", "async def get_role_by_name(guild: Guild, role_name: str) -> Role:\n role = None\n if guild is not None:\n roles = guild.roles\n role = utils.get(roles, name=role_name)\n if role is None:\n try:\n roles = await guild.fetch_roles()\n except HTTPException:\n pass\n else:\n role = utils.get(roles, name=role_name)\n\n return role", "def get_by_name(self, name: str) -> tp.Optional[RoleType]:\n pass", "def my_role_sub(self):\n namespace = \"/aimbot_\" + self.team_side + \"/team/roles/\"\n rospy.Subscriber(namespace + 'ally' + str(self.num), Int16, lambda msg: self.import_role(msg))", "async def assign_role(self, ctx, * , role: CustomRoleConverter):\n settable_role = find(lambda r: r.id in self.settable_roles, ctx.guild.roles)\n if role == settable_role and self.lockdown:\n await ctx.send(\"Server on lockdown due to high amount of people joining try again in a day or two\")\n return\n if role.position > settable_role.position:\n if ctx.channel.name != \"have-you-read-the-rules\":\n await ctx.send(\"can't give you that role\")\n return\n try:\n admin_cog = self.bot.get_cog(\"Admin\")\n if admin_cog:\n if admin_cog.mute_role == role:\n return\n member = ctx.message.author\n await member.add_roles(role)\n await ctx.send(f\"Assigned you the following role: {role.name}\")\n except discord.Forbidden as fb:\n await ctx.send(\"Sorry I don't have the permission to give you that role\")", "def get_extra_character_role() -> str:\n config = load_config(get_path())\n return config[\"roles\"][\"extra-character\"]" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert to the key to PEM format. Expects bytes
def _convert_ec_pub_to_pem(raw_pub_key): public_key_der = bytearray.fromhex( '3059301306072A8648CE3D020106082A8648CE3D03010703420004') + raw_pub_key public_key_b64 = base64.b64encode(public_key_der).decode('ascii') public_key_pem = '-----BEGIN PUBLIC KEY-----\n%s\n-----END PUBLIC KEY-----' % '\n'.join( _split_equal_parts(public_key_b64, 64)) return public_key_pem
[ "def pem(self) -> str:\n return self.key.private_bytes(\n encoding=serialization.Encoding.PEM,\n format=serialization.PrivateFormat.TraditionalOpenSSL,\n encryption_algorithm=serialization.NoEncryption(),\n )", "def toPEM(self):\n return self.x509.as_pem()", "def encode_key(key: ec.EllipticCurvePrivateKeyWithSerialization) -> str:\n return key.private_bytes(\n encoding=serialization.Encoding.PEM,\n format=serialization.PrivateFormat.PKCS8,\n encryption_algorithm=serialization.NoEncryption()\n ).decode(\"ascii\")", "def marshal(cls, public_key):\n public_key_bytes = public_key.public_bytes( encoding=Encoding.Raw, format=PublicFormat.Raw )\n return public_key_bytes # raw", "def pem(self) -> str:\n return self.crt.public_bytes(serialization.Encoding.PEM)", "def unmarshal(cls, public_key_bytes):", "def serialize_public_key(self):\n # reassign public_key to decoded version\n self.public_key = self.public_key.public_bytes(\n encoding = serialization.Encoding.PEM, \n format = serialization.PublicFormat.SubjectPublicKeyInfo # represent public key as a byte string\n ).decode('utf-8') # back to a regular string ", "def pem(self) -> str:\n return self.csr.public_bytes(serialization.Encoding.PEM)", "def raw_public_key(self):\n return self.verifying_key.to_bytes()", "def x509_get_PEM_certificate_from_obj(x509cert) -> bytes:\n return x509cert.public_bytes(serialization.Encoding.PEM)", "def get_public_key() -> bytes:\n return b64encode(rsa_info['public_key'])", "def ec_private_pem_to_private_bin(pem):\n return \"\".join(pem.split(\"\\n\")[1:-2]).decode(\"BASE64\")", "def DER_cert_to_PEM_cert(DER_cert_bytes):\n\tpass", "def get_public_key_text(public_key):\n return public_key.public_bytes(encoding=serialization.Encoding.PEM, format=serialization.PublicFormat.SubjectPublicKeyInfo)", "def rsa_key_b64(self):\n return test_keys.rsa_key.get_base64()", "def base64(self) -> str:\n return base64.b64encode(self.pem).decode(\"utf-8\")", "def _rsa_private_key_bare_base64(key):\n return base64.b64encode(\n key.private_bytes(serialization.Encoding.DER,\n format=serialization.PrivateFormat.TraditionalOpenSSL,\n encryption_algorithm=serialization.NoEncryption()))", "def deserialize_key_RSA(pem_format_key):\n\ttry:\n\t\tpublic_key = serialization.load_pem_public_key(pem_format_key,backend = default_backend())\n\texcept:\n\t\treturn 0\n\telse:\n\t\treturn public_key", "def as_bytes(self):\n return self.key" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the I2C address of the crypto chip or None if chip is not installed.
def ecc608_find_chip(): for addr in (0x30, 0x60, 0x62): if _ecc608_check_address(addr): logger.info('Found crypto chip at 0x%x', addr) return addr logger.warning('No crypto detected, using SW.') return None
[ "def get_i2c_address(self):\n return self.i2c_address", "def i2c_config(self) -> int:\n return self._read_reg(_REG_I2C_CONFIG, 1)[0]", "def getPiI2CBusNumber() -> int:\n rev = _getPiRevision()\n if rev > 1:\n return 1\n elif rev == 1:\n return 0\n return -1", "def ProbeECI2C(self, bus, addr):\n cmd = ['ectool', 'i2cxfer', bus, addr, '1', '0']\n return subprocess.call(cmd) == 0", "def _get_secondary_ip_node_():\n all_instances = _ec2_instances_()\n for instance in all_instances:\n for interface in instance.interfaces:\n for address in interface.private_ip_addresses:\n if address.private_ip_address == env.secondary_ip and not address.primary:\n return instance\n return None", "def get_active_image_addr(conn, portID, slaveID, chipID):\n\td = spi.generic_nand_flash_read(conn, portID, slaveID, chipID, 0x0, 256)\n\n\tboot_sector_addr = (d[22*4+0] << 24) | (d[22*4+1] << 16) | (d[22*4+2] << 8) | d[22*4+3];\n\tboot_sector_addr &= 0xFFFFFF\n\n\n\tif d == make_boot_sector(boot_sector_addr):\n\t\t# Boot sector matches the boot sector by this software\n\t\treturn boot_sector_addr\n\n\telse:\n\t\t# Boot sector contains something else (eg, complete image written via JTAG)\n\t\treturn None", "def get_easy_ec2(self):\n aws = self.get_aws_credentials()\n try:\n ec2 = awsutils.EasyEC2(**aws)\n return ec2\n except TypeError:\n raise exception.ConfigError(\"no aws credentials found\")", "def _get_chip(self) -> int:\n self.log.info('Get the active chip number.')\n actual_ww = ctypes.c_float()\n units = ctypes.c_uint8()\n light_valid = ctypes.c_bool()\n tuned_ww = ctypes.c_float()\n chip = ctypes.c_uint8()\n self._execute('MIRcatSDK_GetActualWW',\n [ctypes.byref(actual_ww),\n ctypes.byref(units),\n ctypes.byref(light_valid)])\n self._execute('MIRcatSDK_GetTuneWW',\n [ctypes.byref(tuned_ww),\n ctypes.byref(units),\n ctypes.byref(chip)])\n time.sleep(.05)\n return chip.value", "def getCryptoDriver():\n global _cryptoDriver\n if _cryptoDriver is None:\n setCryptoDriver(POWCryptoDriver())\n return _cryptoDriver", "def choose_ioport_device2(*args):\n return _ida_diskio.choose_ioport_device2(*args)", "def test_set_i2c_address_without_current_address(self):\n # Set a new address\n new_addr = 0x70\n ThunderBorg.set_i2c_address(new_addr)\n found = ThunderBorg.find_board()\n found = found[0] if found else 0\n msg = \"Found address '0x{:02X}', should be '0x{:02X}'.\".format(\n found, new_addr)\n self.assertEqual(found, new_addr, msg)", "def getChipInfo(self):\n reg = self.chip['ChipVer']\n VER = reg['VER<4:0>']\n REV = reg['REV<4:0>']\n MASK = reg['MASK<5:0>']\n return (VER, REV, MASK)", "def read_address_twobyte(self, addr):\n data = self.i2c.read_i2c_block_data(self.i2c_addr, addr, 2)\n return data[0] + (data[1] << 8)", "def test_set_i2c_address_with_current_address(self):\n # Set a new address\n new_addr = 0x70\n cur_addr = ThunderBorg.DEFAULT_I2C_ADDRESS\n ThunderBorg.set_i2c_address(new_addr, cur_addr=cur_addr)\n found = ThunderBorg.find_board()\n found = found[0] if found else 0\n msg = \"Found address '0x{:02X}', should be '0x{:02X}'.\".format(\n found, new_addr)\n self.assertEqual(found, new_addr, msg)", "def __init__(self, pi, bus=1, addr=0x47):\n self.pi = pi\n self._h = pi.i2c_open(bus, addr)", "def cep2(self):\n return self._cep2", "def __internal_ip_from_app(self, app):\n try:\n nic = self.__primary_nic_from_app(app)\n return IPv4Address(nic.find('vcd:IpAddress', _NS).text)\n except (AttributeError, AddressValueError):\n return None", "def i2(self):\n return self.input_get('I2')", "def get_device_gps():\r\n pi1 = ['0002','0003','0004','0005','0006','0007','0008','0009','000d','000e','000f','0010','0011','0012','0013']\r\n pi2 = ['a01041','a21041']\r\n pi0 = ['900092']\r\n pi3 = ['a02082','a22082']\r\n rpi_revision = rpi_utils.get_revision()\r\n if rpi_revision in pi1 or rpi_revision in pi2 or rpi_revision in pi0:\r\n # Pi 2 or lower\r\n device = '/dev/ttyAMA0'\r\n else:\r\n # Pi 3 or higher\r\n device = '/dev/ttyS0'\r\n return device" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get the current user's tracking_id, sets new one if blank;
def tracking_id(request): if request.session.get(TRACKING_ID_SESSION_KEY, '') == '': request.session[TRACKING_ID_SESSION_KEY] = _generate_tracking_id() return request.session[TRACKING_ID_SESSION_KEY]
[ "def current_user_id():\n if not hasattr(g, 'current_user_id'):\n try:\n id = int(request.headers.get(HEADER_CURRENT_USER_ID_KEY))\n except:\n id = 1\n if not id:\n id = 1\n setattr(g, 'current_user_id', id)\n return g.current_user_id", "def ga_tracking_id(request):\n if hasattr(settings, 'GOOGLE_ANALYTICS_ID'):\n return {\n 'ga_tracking_id': settings.GOOGLE_ANALYTICS_ID\n }\n return {}", "def user_id(self):\n return self.auth.get_user_by_session()[\"user_id\"]", "def has_ga_tracking_id(request):\n if hasattr(settings, 'GOOGLE_ANALYTICS_ID'):\n has_ga_id = settings.GOOGLE_ANALYTICS_ID is not None\n else:\n has_ga_id = False\n\n return {\n 'has_ga_tracking_id': has_ga_id\n }", "def _get_user_id(self) -> str:\n return self._uid[0]", "def current_user():\n\n if not session.get('user_id', False):\n # Get and store user info in session.\n g_user = google.user_info()\n user, created = User.objects.get_or_create(google_id=g_user['id'], email=g_user['email'])\n user.name = g_user['name']\n user.picture = g_user.get('picture', url_for('static', filename='/assets/img/default_pic.png', _external=True))\n user.save()\n session['user_id'] = g_user['id']\n else:\n user = User.objects.get(google_id=session['user_id'])\n return user", "def googleplus_user_id(self):\n return self.key.string_id()", "def _get_user_id(self):\n return self._api_query_request('me')['id']", "def _generate_tracking_id():\n tracking_id_length = 48\n characters = string.ascii_letters + string.digits + string.punctuation\n tracking_id = ''.join((secrets.choice(characters)\n for _ in range(tracking_id_length)))\n return tracking_id", "def session_user_id(self):\n ret = int(self.session.split('-')[0]) if self.session else None\n return ret", "def before_request():\n g.user = None\n if 'user_id' in session:\n g.user = User.query.get(session['user_id'])", "def anonymous_vote_id(poll_uid):", "def useridentifier(self):\n return self._useridentifier", "def __int__(self):\n return self.userid", "def get_user_id():\n return SessionHandler.__get_session_var(SessionVariableKeys.USER_ID)", "def write_tracking_id(self, global_key_group, tracking_id):\n tracking_id_group = global_key_group.create_group(self.__tracking_id__)\n attrs = tracking_id_group.attrs\n for k, v in tracking_id.items():\n attrs[k] = v", "def getStatusIdOfUser(self,user):\n return user.status_id", "def geo_backup_user_assigned_identity_id(self) -> Optional[str]:\n return pulumi.get(self, \"geo_backup_user_assigned_identity_id\")", "def _get_greynoise_id(self) -> int:\n\n if self.greynoise_id is not None:\n return self.greynoise_id\n\n greynoise_entity = self.helper.api.stix_domain_object.get_by_stix_id_or_name(\n name=self.greynoise_ent_name\n )\n if not greynoise_entity:\n self.helper.log_info(f\"Create {self.greynoise_ent_name}\")\n self.greynoise_id = self.helper.api.identity.create(\n type=\"Organization\",\n name=self.greynoise_ent_name,\n description=self.greynoise_ent_desc,\n )[\"id\"]\n return self.greynoise_id\n else:\n self.helper.log_info(f\"Cache {self.greynoise_ent_name} id\")\n self.greynoise_id = greynoise_entity[\"id\"]\n return self.greynoise_id" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
function for generating secure random tracking ID values
def _generate_tracking_id(): tracking_id_length = 48 characters = string.ascii_letters + string.digits + string.punctuation tracking_id = ''.join((secrets.choice(characters) for _ in range(tracking_id_length))) return tracking_id
[ "def gen_id():\n return \"{:04x}\".format(random.randint(0, int(0xFFFF)))", "def get_random_sensor_id():\n return \"\".join(random.choice(\"0123456789abcdef\") for i in range(12))", "def new_id():\n bs = uuid4().bytes\n return urlsafe_b64encode(bs).strip().replace('=', '')", "def generate_id():\n length = 6\n return ''.join(random.choices(string.ascii_lowercase + string.digits, k=length))", "def generate_id():\n numeric_id = random.getrandbits(64) - 2 ** 63\n return base64.urlsafe_b64encode(struct.pack('q', numeric_id))[:-1]", "def generate_session_id():\n return str(secrets.randbits(32))", "def _generateId(self):\n while True:\n if self._v_nextid is None:\n self._v_nextid = random.randrange(0, 2**31)\n uid = self._v_nextid\n self._v_nextid += 1\n if uid not in self._tagid_to_obj:\n return uid\n #self._v_nextid = None", "def _new_session_id(self):\n return os.urandom(32).encode('hex')", "def random_id():\n return str(uuid.uuid5(uuid.uuid4(), socket.gethostname())).replace(\"-\", \"\")", "def random_client_id():\r\n return 'py_%s' % base64.b64encode(str(random.randint(1, 0x40000000)))", "def __gen_id(self):\n self.igv_id = 'igv_' + str(random.randint(1, 10000000))", "def generate_fake_userid():\n return str(uuid.uuid4())", "def generate_random_id() -> str:\n random_id = \"\"\n characters = list('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ')\n for _ in range(12):\n random_id += random.choice(characters)\n return random_id", "def __generate_random():\n random_hash = ''.join(\n (\n random.choice(string.ascii_letters + string.digits + string.punctuation)\n )\n for _ in range(16)\n )\n return random_hash", "def _createIdentifier(bits=160, _urandom=urandom):\n return urandom(bits // 8).encode(\"hex\")", "def get_unique_id(length=5):\n return str(int(time.time())) + base_token_factory(length)", "def _gen_uuid(self):\r\n return uuid.uuid4().hex", "def randId(n):\n return str(n) +\"-\" + str(+random.randint(1,10000))", "def make_session_id() -> str:\n return hashlib.sha1(\n (f'{time.time()}' + f'{random.randint(0, 1000)}').encode()\n ).hexdigest()" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
strip out common words, limit to 5 words
def _prepare_words(search_text): words = search_text.split() for common in STRIP_WORDS: if common in words: words.remove(common) return words[0:100]
[ "def delete_common_words(data):", "def remove_common_words(words):\n common_words = [\"the\", \"for\", \"of\" ]\n return [w for w in words if w not in common_words ]", "def prepare_words(search_text):\n for common in STRIP_SYMBOLS:\n if common in search_text:\n search_text = search_text.replace(common, ' ')\n words = search_text.split()\n return words[0:5]", "def trim_words(vocabulary, pairs, min_count):\n vocabulary.trim(min_count)\n # pairs kept\n keep_pairs = []\n for pair in pairs:\n query = pair[0]\n answer = pair[1]\n keep_query = True\n keep_answer = True\n # if query contains trimmed words or not:\n for word in query.split(' '):\n if word not in vocabulary.word2index:\n keep_query = False\n # dont forget break\n break\n # it's turn to answer\n for word in answer.split(' '):\n if word not in vocabulary.word2index:\n keep_answer = False\n break\n if keep_query and keep_answer:\n keep_pairs.append(pair)\n return keep_pairs", "def keepGloVeWords(s, GloVe_words):\n MAX_WORDS_IN_CAPTION = 40\n individual_words = s.split()\n res = []\n for word in individual_words:\n if word in GloVe_words:\n res.append(word)\n if len(res) == MAX_WORDS_IN_CAPTION:\n break\n return \" \".join(res)", "def cleanup(words):\n cleaned_words = set(\n filter(lambda x: len(x) > WORD_MIN_LENGTH, words)\n )\n return cleaned_words", "def filter_words(sentence):\r\n words = sentence.split(' ')\r\n relevant_words = []\r\n for word in words:\r\n if len(word) > 4:\r\n relevant_words += [word]\r\n print(word)\r\n else:\r\n print(len(word))\r\n return relevant_words", "def filter_long_words(list_of_words, n):\r\n result = []\r\n for item in list_of_words :\r\n item = item.strip()\r\n if len(item) > n :\r\n result.append(item)\r\n return result", "def get_rare_words(corpus_file):\n word_counts = defaultdict(int)\n rare_words = []\n\n for l in corpus_file:\n line = l.strip()\n if line:\n linew = line.split(' ')\n if (linew[0]) in word_counts:\n word_counts[(linew[0])] += 1\n else:\n word_counts[(linew[0])] = 1\n \n for key in word_counts:\n if word_counts[key] < 5:\n rare_words.append(key)\n #print(rare_words)\n #print(len(rare_words))\n return rare_words", "def remove_common_and_rare_words(corpus_dir, max_allowable_percentage = 90,\n min_wordfreq = 3):\n assert(os.path.exists(corpus_dir) and os.path.isdir(corpus_dir))\n assert(max_allowable_percentage <= 100 and max_allowable_percentage > 0)\n\n corpus_size = 0\n docfreq_counter = Counter()\n wordfreq_counter = Counter()\n terms_2_filenames_set = dict()\n\n # Parsing corpus and computing terms statistics\n print('Collecting corpus terms statistics...')\n for filename in os.listdir(corpus_dir):\n filepath = os.path.join(corpus_dir, filename)\n corpus_size += 1\n\n file_reader = open(filepath, encoding='utf-8', errors='ignore')\n content = file_reader.read()\n tokens = tokenize_string(content)\n tokens_set = set(tokens)\n docfreq_counter.update(tokens_set)\n wordfreq_counter.update(tokens)\n\n max_allowable_docfreq = corpus_size * max_allowable_percentage / 100\n\n\n # TODO: Debugging\n print('Removing words that appear less than {} times in corpus:'.format(min_wordfreq))\n print(str([term for (term, wordfreq)\n in sorted(wordfreq_counter.items())\n if wordfreq < min_wordfreq]))\n print('Removing words that appear in more than {}({}%) documents:'.format(max_allowable_docfreq, max_allowable_percentage))\n for (term, doc_freq) in ((term, doc_freq) for (term, doc_freq) in sorted(docfreq_counter.items(), key=lambda x: x[1], reverse=True)\n if doc_freq > max_allowable_docfreq):\n print(\"\\t'{}': Found in {}({}%) documents\".format(term, doc_freq, doc_freq/corpus_size * 100))\n \n for filename in os.listdir(corpus_dir):\n filepath = os.path.join(corpus_dir, filename)\n corpus_size += 1\n\n file_reader = open(filepath, encoding='utf-8', errors='ignore')\n content = file_reader.read()\n tokens = tokenize_string(content)\n\n filtered_tokens = []\n for token in tokens:\n if (docfreq_counter[token] <= max_allowable_docfreq) and (wordfreq_counter[token] >= min_wordfreq):\n filtered_tokens.append(token)\n\n s = ' '.join(filtered_tokens)\n\n file_writer = open(filepath, 'w', encoding='utf-8')\n file_writer.write(s)\n file_writer.close()", "def removeStopWords(tweetData, num):\n\n commonWords = findMostCommonWords(tweetData, num)\n tweetIDs = tweetData[\"tweets\"].keys()\n for tweetID in tweetIDs:\n words = tweetData[\"tweets\"][tweetID][\"words\"]\n newWords = []\n newTags = []\n for word in words:\n if not word in commonWords:\n newWords.append(word)\n tweetData[\"tweets\"][tweetID][\"words\"] = newWords", "def remove_custom_words(text, custom_wordlist):\n result = [word for word in text.split() if word.lower() not in custom_wordlist]\n return \" \".join(result)", "def trimRareWords(voc: Voc, pairs: List[List[str]], MIN_COUNT:int) -> List[List[str]]:\n voc.trim(MIN_COUNT)\n # Filter out pairs with trimmed words\n keep_pairs = []\n for pair in pairs:\n input_sentence = pair[0]\n output_sentence = pair[1]\n keep_input = True\n keep_output = True\n # Check input sentence\n for word in input_sentence.split(' '):\n if word not in voc.word2index:\n keep_input = False\n break\n # Check output sentence\n for word in output_sentence.split(' '):\n if word not in voc.word2index:\n keep_output = False\n break\n\n # Only keep pairs that do not contain trimmed word(s) in their input or output sentence\n if keep_input and keep_output:\n keep_pairs.append(pair)\n\n print(\"\\nRemoving pairs that contain sentence in either query or reply with words encountered <= than MIN_COUNT...\\n\"\n \"trimmed from {} pairs to {}, {:.4f} of total\\n\".format(len(pairs), len(keep_pairs),\n len(keep_pairs) / len(pairs)))\n return keep_pairs", "def remove_shortwords(text, length=3):\n token_words = re.split(r\"\\W+\", text)\n long_words_list = [i for i in token_words if len(i) > int(length)]\n return \" \".join(long_words_list)", "def infrequent_word_removal(self, dataframe):\n word_dict = {}\n text = dataframe.apply(lambda x: nltk.word_tokenize(x))\n\n for _, row in text.iteritems():\n for word in row:\n if word not in word_dict.keys():\n word_dict[word] = 1\n else:\n word_dict[word] += 1\n # Check vocab size before word removal\n print(\"Word Count Before Uncommon Word Removal: \")\n print(len(word_dict))\n sorted_dict = sorted(word_dict.items(), key=lambda x: x[1], reverse=True)\n print(sorted_dict)\n # x, y = zip(*sorted_dict)\n\n # only accept words that occur more than UNCOMMON_WORD_THRESHOLD times\n accept_words = []\n for word, occ in sorted_dict:\n if int(occ) > self.UNCOMMON_WORD_THRESHOLD:\n accept_words.append(word)\n else:\n break\n # remove uncommon words \n accept_words = [x.lower() for x in accept_words]\n print(text[2])\n text = text.apply(lambda x: nltk.word_tokenize(x)).apply(lambda x: \" \".join([word for word in x if word.lower() in accept_words]))\n print(text[2])\n\n # Check vocab size after word removal\n word_dict_after = {}\n text2 = text.apply(lambda x: nltk.word_tokenize(x))\n\n for _, row in text2.iteritems():\n for word in row:\n if word not in word_dict_after.keys():\n word_dict_after[word] = 1\n else:\n word_dict_after[word] += 1\n\n print(\"Word Count After Uncommon Word Removal: \")\n print(len(word_dict_after))\n # return the new dataframe that has had uncommon words removed\n return text", "def filter_poor_langs(self):\n\t\tpoor_langs = set()\n\t\t\n\t\tfor lang in self.langs:\n\t\t\tcount = sum([1 for w in self.words if w['language'] == lang])\n\t\t\tif count <= 10:\n\t\t\t\tpoor_langs.add(lang)\n\t\t\n\t\tself.words = [\n\t\t\tw for w in self.words if w['language'] not in poor_langs\n\t\t]", "def trimVocab(self):\n # Trim the vocabulary in terms of the minimum word count\n if self.min_word_count and not self.max_vocab_size:\n # If min_word_count <= 1, use the quantile approach\n if self.min_word_count <= 1:\n # Create the list of words count\n word_stat = [count for count in self.word_count.values()]\n # Calculate the quantile of words count\n quantile = int(np.quantile(word_stat, self.min_word_count))\n print('Trimmed vocabulary using as mininum count threashold: quantile({:3.2f}) = {}'. format(self.min_word_count, quantile))\n # Filter words using quantile threshold\n self.trimmed_word_count = {word: count for word, count in self.word_count.items() if count >= quantile}\n # If min_word_count > 1 use standard approach\n else:\n # Filter words using count threshold\n self.trimmed_word_count = {word: count for word, count in self.word_count.items() if count >= self.min_word_count}\n print('Trimmed vocabulary using as minimum count threashold: count = {:3.2f}'.format(self.min_word_count))\n \n # Trim the vocabulary in terms of its maximum size\n elif self.max_vocab_size and not self.min_word_count:\n self.trimmed_word_count = {word: count for word, count in self.word_count.most_common(self.max_vocab_size)}\n print('Trimmed vocabulary using maximum size of: {}'.format(self.max_vocab_size))\n else:\n raise ValueError('Use min_word_count or max_vocab_size, not both!')\n \n print('{}/{} tokens has been retained'.format(len(self.trimmed_word_count.keys()),\n len(self.word_count.keys())))", "def trim(self, min_count: int):\n if self.trimmed:\n return\n self.trimmed = True\n\n keep_words = []\n\n for k, v in self.word2count.items():\n if v >= min_count:\n keep_words.append(k)\n\n print('keep_words {} / {} = {:.4f}'.format(\n len(keep_words), len(self.word2index), len(keep_words) / len(self.word2index)\n ))\n\n # Reinitialize dictionaries\n self.word2index = {}\n self.word2count = {}\n self.index2word = {PAD_token: \"PAD\", SOS_token: \"SOS\", EOS_token: \"EOS\"}\n self.num_words = 3 # Count default tokens\n\n for word in keep_words:\n self.addWord(word)", "def filter_shakesperean_words(mysonnets):\n\n shakesperean_words = ['thou', 'thy', 'thine', 'thee', 'ye', 'doth', 'dost', 'hath', 'nor', 'th', 'shalt']\n\n result = []\n\n for sonnet in mysonnets:\n \tnewsonnet = Sonnet()\n \ttext = sonnet.gettext()\n \tfor word in text:\n \t\tif (word not in shakesperean_words):\n \t\t\tnewsonnet.addword(word)\n \tresult.append(newsonnet)\n return result" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Prepends a column of ones to the design matrix (bias term)
def prepend_bias_term(X): return np.column_stack((np.ones(X.shape[0]), X))
[ "def zero_bias(matrix):\n matrix[:,0] = 0\n return(matrix)", "def add_bias_feature(data,bias):\n for n in range(len(data)):\n l = len(data[n])\n data[n] = np.c_[ data[n], bias*np.ones((l,1)) ]", "def add_ones_column_to_matrix(mat):\n\tshape = list(mat.shape)\n\tshape[1] += 1\n\tres = np.ones(shape)\n\tres[:, 1:] = mat\n\treturn res", "def add_bias(self, X):\r\n bias = np.ones((X.shape[0],1))\r\n return np.concatenate((bias,X), axis=1)", "def drop_bias(matrix):\n return matrix[:,1:]", "def one_hot_encode(self, columns, prefix):\n\n self.df = pd.get_dummies(self.df, columns=columns, prefix=prefix)", "def prepareJacobian(self):\n self.jac.clear()\n self.nm = self.regionManager().parameterCount()\n self.nf = len(self.fops)\n print(self.nm, \"model cells\")\n nd = 0\n for i, fop in enumerate(self.fops):\n self.jac.addMatrix(fop.jacobian(), nd, i*self.nm)\n nd += fop.data.size()\n\n self.jac.recalcMatrixSize()\n self.setJacobian(self.jac)", "def ones(self):\n return self.constantVector('__ones',self.db.ones())", "def add_ones_column(self, X_features):\n X = np.ones((X_features.shape[0], X_features.shape[1] + 1))\n X[:,1:] = X_features\n return X", "def _relation_bias(self, vocab_size):\n bias = nn.Embedding(vocab_size + 1, 1, padding_idx=-1, sparse=False)\n bias.weight = nn.Parameter(torch.zeros(vocab_size + 1, 1))\n return bias", "def _to_matrix_func(self) -> np.ndarray:\n empty_matrix = np.diag(np.ones(4, dtype=float))\n\n empty_matrix[2, 3] += self._meta[\"bias\"]\n\n return empty_matrix", "def apply_bias(self, bias):\n x = self.structure['x']\n x = np.insert(x, 0, 0)\n # E field V/m\n E_field = bias / (x[-1]-x[0])\n self.biased_structure['U'] = (self.structure['U'] /\n nu.eV-E_field*x[1:])*nu.eV\n return", "def predict_zero_one(self, input_matrix: np.ndarray) -> np.ndarray:\n self.hidden_matrix_2_activation_binary=np.where(self.predict(input_matrix) < .5 , 0 , 1)\n return self.hidden_matrix_2_activation_binary", "def test_padb_1(self):\n # regular matrix\n tr = padb(self.tv1, n=25, val=2)\n res = np.concatenate((self.tv1, 2.*np.ones((10, 15))), axis=0)\n self.assertTrue(np.allclose(tr, res, atol=1e-8, rtol=1e-5))", "def weight(self):\n matrix = self.matrix.copy()\n self.matrix[:, :len(self.xdef)] = (\n self.matrix[:, :len(self.xdef)] * self.matrix[:, [-1]])\n return self.matrix", "def _set_dummies(self):\n data_reduced = self.data[self.antecedent]\n self.data_dummies = pd.get_dummies(data_reduced, columns=self.antecedent)", "def one_hot_encode(board):\n\n flat = (board.reshape(SIZE ** 2)).tolist()\n\n X = []\n for i in np.arange(1,17): \n encoding = np.zeros(SIZE ** 2)\n encoding[flat.index(i)] = 1\n\n X.append(encoding)\n\n X = (np.asarray(X).reshape(SIZE ** 4))\n\n # Potentially append Manhattan distance. \n # np.append(X, manhattan(board))\n\n return X", "def one_hot_encoder(y):\n\n letter = np.zeros((10, 1))\n letter[int(y)] = 1\n return letter", "def apply_bin_labels(X):\n\tA = np.copy(X)\n\tlabel_i = A.shape[1] - 1\n\tA[A[:,label_i]==0,label_i] = -1\n\tA[A[:,label_i]>0,label_i] = 1\n\treturn A", "def set_bone_extra_matrix_inv(self, bonename, mat):\n self.bones_extra_matrix_inv[self.get_bone_name_for_blender(bonename)] = mat" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the hash of a given file, using either MD5 or just the size in bytes If the size is too big, MD5 will not be run and the byte size will be used instead This is to save some power and time, as large files are unlikely to have byte size conflict Also for Cloud files it avoids downloading the file again
def get_hash(self, file_path: pathlib.Path): size = os.path.getsize(file_path) if size > self.size_threshold: return str(os.path.getsize(file_path)) return hashlib.md5(open(file_path, 'rb').read()).hexdigest()
[ "def filehash(file):\n hasher = hashlib.md5()\n f = open(file, 'rb')\n buf = f.read()\n hasher.update(buf)\n return hasher.hexdigest()", "def calc_md5( path_filename ):\n hash_md5 = hashlib.md5()\n with open( path_filename , \"rb\") as f:\n for chunk in iter(lambda: f.read(4096), b\"\"):\n hash_md5.update(chunk)\n return hash_md5.hexdigest()", "def calcFileMd5sum(filename): \n\n m = hashlib.md5()\n\n # Read file in as 128 byte chunks\n with open(filename) as f: m.update(f.read(128))\n \n return m.hexdigest()", "def _get_file_md5sum(file_name):\n hash_obj = hashlib.md5()\n with open(file_name, 'rb') as f:\n hash_obj.update(f.read())\n return hash_obj.hexdigest().encode('utf-8')", "def get_md5(data):\n if hasattr(data, \"read\") and hasattr(data, 'seek'):\n m = md5()\n chunk = data.read(1024*1024) # 1Mb\n f_size = 0\n while(chunk):\n f_size += len(chunk)\n m.update(chunk)\n chunk = data.read(1024*1024)\n data.seek(0)\n return m.hexdigest(), f_size\n else: # normal str\n m = md5()\n f_size = len(data)\n m.update(data)\n return m.hexdigest(), f_size", "def calculate_md5_checksum(filename):\n\n length = io.DEFAULT_BUFFER_SIZE\n md5 = hashlib.md5()\n\n with io.open(filename, mode=\"rb\") as fd:\n for chunk in iter(lambda: fd.read(length), b''):\n md5.update(chunk)\n\n return md5.hexdigest()", "def checksum_md5 (filename) :\n fname = filename\n block_size = 0x10000\n fd = open(fname, \"rb\")\n try:\n block = [ fd.read(block_size) ]\n while len(block[-1]) > 0 :\n block.append ( fd.read(block_size) )\n contents = block\n zero = hashlib.md5()\n i = 0 \n for el in contents :\n i += 1\n zero.update( el )\n m = zero\n return m.hexdigest()\n finally:\n fd.close()\n return None", "def compute_md5(file):\n md5 = hashlib.md5()\n while True:\n buf = file.read(8192)\n if not buf:\n break\n md5.update(buf)\n return md5", "def hash_file(path):\n\n md5_hash = hashlib.md5()\n sha256_hash = hashlib.sha256()\n with open(path, 'rb') as f:\n while True:\n data = f.read(BUF_SIZE)\n if not data:\n break\n md5_hash.update(data)\n sha256_hash.update(data)\n return md5_hash.hexdigest(), sha256_hash.hexdigest()", "def calculate_file_hash(\n filepath, hashmethod='md5',\n read_start=0, read_limit=0, chunk_size=CHUNK_SIZE, return_type='hex'):\n if isinstance(hashmethod, str):\n hashfactory = getattr(hashlib, hashmethod)\n hashmethod = hashfactory()\n with open(filepath, \"rb\") as f:\n if read_start and read_start > 0:\n f.seek(read_start)\n n_bytes_read = 0\n for chunk in iter(lambda: f.read(chunk_size), b\"\"):\n hashmethod.update(chunk)\n n_bytes_read += chunk_size\n if 0 < read_limit < n_bytes_read:\n break\n if return_type == 'hex':\n return hashmethod.hexdigest()\n elif return_type == 'int':\n # Note: Python ints limited to 64bits = 8 bytes, else error: \"int too big to convert\".\n return int.from_bytes(hashmethod.digest()[:8], byteorder='little')\n else:\n return hashmethod.digest()", "def compute_file_hash(file_path, alg='md5'):\n if alg == 'md5':\n md5_obj = hashlib.md5()\n block_size = 65536\n # read chunk by chunk for big file\n with open(file_path, 'r+b') as f:\n for block in iter(lambda: f.read(block_size), \"\"):\n md5_obj.update(block)\n local_md5 = md5_obj.hexdigest()\n file_hash = local_md5\n\n else:\n raise NotImplementedError(\"ALGORITHM {0} NOT IMPLEMENTED!\".format(alg))\n return file_hash", "def file_md5(filename):\r\n file_o = read_file(filename)\r\n file_str = file_o.read()\r\n file_o.close()\r\n return string_md5(file_str)", "def blob_hash(self, stream, size):\n hasher = sha1()\n hasher.update(('blob %u\\0' % size).encode('ascii'))\n nread = 0\n while True:\n # We read just 64K at a time to be kind to\n # runtime storage requirements.\n data = stream.read(65536)\n if data == b'':\n break\n nread += len(data)\n hasher.update(data)\n if nread != size:\n # TODO(phlax): move this to pytooling asap.\n # This would not pass type checking `BytesIO` has no `stream.name`\n raise ValueError('%s: expected %u bytes, found %u bytes' % (stream.name, size, nread))\n return hasher.hexdigest()[:10]", "def filehash(filepath, blocksize=4096):\n sha = hashlib.sha256()\n with open(filepath, 'rb') as fp:\n while True:\n data = fp.read(blocksize)\n if data:\n sha.update(data)\n else:\n break\n return sha.hexdigest()", "def md5_for_file(f, block_size=2**20):\n m = hashlib.md5()\n with open(f , \"rb\" ) as f:\n while True:\n buf = f.read(block_size)\n if not buf:\n break\n m.update( buf )\n return m.hexdigest()", "def checksum_file(path, hash_type='sha-1'):\n digestor = hashlib.new(hash_type)\n with open(path, 'rb') as fh:\n chunk_size = 2 ** 16\n chunk = fh.read(chunk_size)\n while chunk:\n digestor.update(chunk)\n chunk = fh.read(chunk_size)\n return digestor.hexdigest()", "def hashFile(path):\n import hashlib\n blockSize = 64*1024*1024\n \n h = hashlib.sha3_512()\n f1 = open(filepath, 'br')\n #parses data 1MB at a time, to avoid loading the entirety of a file into memory\n data = f1.read(blockSize)\n while len(data) == blockSize:\n h.update(data)\n data = f1.read(blockSize)\n f1.close()\n if len(data) > 0:\n h.update(data)\n return h.digest()", "def hash_file(self, filename):\n with open(filename, mode=\"rb\", buffering=0) as fp:\n hash_func = _ALGORITHM_MAP[self.hash_algorithm]()\n buffer = fp.read(self.chunk_size)\n while len(buffer) > 0:\n hash_func.update(buffer)\n buffer = fp.read(self.chunk_size)\n return hash_func.hexdigest()", "def md5_filelike(filelike):\n m = hashlib.md5()\n while True:\n s = filelike.read()\n if len(s) == 0:\n break\n else:\n m.update(s)\n return m.hexdigest()" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Plot a 3D pose 4x4 homogenous transform on given axis 'axes' with given 'axis_length'.
def plot_pose3_on_axes(axes, T, axis_length=0.1, center_plot=False, line_obj_list=None): return plot_pose3RT_on_axes(axes, *decompose_T(T), axis_length, center_plot, line_obj_list)
[ "def plot_pose3RT_on_axes(axes, gRp, origin, axis_length=0.1, center_plot=False, line_obj_list=None):\n # draw the camera axes\n x_axis = origin + gRp[:, 0] * axis_length\n linex = np.append(origin, x_axis, axis=0)\n \n y_axis = origin + gRp[:, 1] * axis_length\n liney = np.append(origin, y_axis, axis=0)\n\n z_axis = origin + gRp[:, 2] * axis_length\n linez = np.append(origin, z_axis, axis=0)\n\n\n if line_obj_list is None:\n xaplt = axes.plot(linex[:, 0], linex[:, 1], linex[:, 2], 'r-') \n yaplt = axes.plot(liney[:, 0], liney[:, 1], liney[:, 2], 'g-') \n zaplt = axes.plot(linez[:, 0], linez[:, 1], linez[:, 2], 'b-')\n \n if center_plot:\n #center_3d_plot_around_pt(axes,origin[0])\n pass\n return [xaplt, yaplt, zaplt]\n \n else:\n line_obj_list[0][0].set_data(linex[:, 0], linex[:, 1])\n line_obj_list[0][0].set_3d_properties(linex[:,2])\n \n line_obj_list[1][0].set_data(liney[:, 0], liney[:, 1])\n line_obj_list[1][0].set_3d_properties(liney[:,2])\n \n line_obj_list[2][0].set_data(linez[:, 0], linez[:, 1])\n line_obj_list[2][0].set_3d_properties(linez[:,2])\n\n if center_plot:\n #center_3d_plot_around_pt(axes,origin[0])\n pass\n return line_obj_list", "def draw_axes(axes, origin=(-1, -1, -1), length=(2, 2, 2)):\n x, y, z = origin\n dx, dy, dz = length\n axes.plot([x, x+dx], [y, y], [z, z], color='black')\n axes.plot([x, x], [y, y+dy], [z, z], color='black')\n axes.plot([x, x], [y, y], [z, z+dz], color='black')", "def plot_pose(pose):\n import mpl_toolkits.mplot3d.axes3d as p3\n _CONNECTION = [\n [0, 1], [1, 2], [2, 3], [0, 4], [4, 5], [5, 6], [0, 7], [7, 8],\n [8, 9], [9, 10], [8, 11], [11, 12], [12, 13], [8, 14], [14, 15],\n [15, 16]]\n\n # fig = plt.figure()\n # ax = fig.gca(projection='3d')\n for c in _CONNECTION:\n col = '#%02x%02x%02x' % joint_color(c[0])\n ax.plot([pose[0, c[0]], pose[0, c[1]]],\n [pose[1, c[0]], pose[1, c[1]]],\n [pose[2, c[0]], pose[2, c[1]]], c=col)\n\n\n for j in range(pose.shape[1]):\n col = '#%02x%02x%02x' % joint_color(j)\n ax.scatter(pose[0, j], pose[1, j], pose[2, j],\n c=col, marker='*', edgecolor=col)\n smallest = pose.min()\n largest = pose.max()\n ax.set_xlim3d(smallest, largest)\n ax.set_ylim3d(smallest, largest)\n ax.set_zlim3d(smallest, largest)\n\n return fig", "def drawWorldAxes(axesLength):\n xpointer = vp.arrow(pos=vp.vector(0, 0, 0), axis=vp.vector(axesLength, 0, 0), color=vp.color.green) # to the right\n ypointer = vp.arrow(pos=vp.vector(0, 0, 0), axis=vp.vector(0, axesLength, 0), color=vp.color.red) # (up)\n zpointer = vp.arrow(pos=vp.vector(0, 0, 0), axis=vp.vector(0, 0, axesLength), color=vp.color.blue) # out of the page\n return (xpointer, ypointer, zpointer)", "def show_axes(ax3d, equal=True):\n if equal is True:\n set_axes3d_equal(ax3d)\n plt.show()", "def plotPath_3D(self, seq, poses_gt, poses_result, plot_path_dir):\n from mpl_toolkits.mplot3d import Axes3D\n\n start_point = [[0], [0], [0]]\n fontsize_ = 8\n style_pred = 'b-'\n style_gt = 'r-'\n style_O = 'ko'\n\n poses_dict = {} \n poses_dict[\"Ours\"] = poses_result\n if poses_gt:\n poses_dict[\"Ground Truth\"] = poses_gt\n\n fig = plt.figure(figsize=(8,8), dpi=110)\n ax = fig.gca(projection='3d')\n\n for key,_ in poses_dict.items():\n plane_point = []\n for frame_idx in sorted(poses_dict[key].keys()):\n pose = poses_dict[key][frame_idx]\n plane_point.append([pose[0,3], pose[2,3], pose[1,3]])\n plane_point = np.asarray(plane_point)\n style = style_pred if key == 'Ours' else style_gt\n plt.plot(plane_point[:,0], plane_point[:,1], plane_point[:,2], style, label=key) \n plt.plot(start_point[0], start_point[1], start_point[2], style_O, label='Start Point')\n\n xlim = ax.get_xlim3d()\n ylim = ax.get_ylim3d()\n zlim = ax.get_zlim3d()\n xmean = np.mean(xlim)\n ymean = np.mean(ylim)\n zmean = np.mean(zlim)\n plot_radius = max([abs(lim - mean_)\n for lims, mean_ in ((xlim, xmean),\n (ylim, ymean),\n (zlim, zmean))\n for lim in lims])\n ax.set_xlim3d([xmean - plot_radius, xmean + plot_radius])\n ax.set_ylim3d([ymean - plot_radius, ymean + plot_radius])\n ax.set_zlim3d([zmean - plot_radius, zmean + plot_radius])\n\n ax.legend()\n # plt.legend(loc=\"upper right\", prop={'size':fontsize_}) \n ax.set_xlabel('x (m)', fontsize=fontsize_)\n ax.set_ylabel('z (m)', fontsize=fontsize_)\n ax.set_zlabel('y (m)', fontsize=fontsize_)\n ax.view_init(elev=20., azim=-35)\n\n png_title = \"{}_path_3D\".format(seq)\n plt.savefig(plot_path_dir+\"/\"+png_title+\".png\", bbox_inches='tight', pad_inches=0.1)\n pdf = matplotlib.backends.backend_pdf.PdfPages(plot_path_dir + \"/\" + png_title + \".pdf\") \n fig.tight_layout()\n pdf.savefig(fig) \n # plt.show()\n plt.close()", "def plot(self, q, ee=True, axlimits=None, elev=25, azim=45, ascale=0.4, cscale=0.1):\n # Compute intermediate DH homogeneous transformations\n pcnt = 0\n # Initial intermediate point\n if (not self.isdzero[0]):\n if self.type[0]=='r':\n self.p[pcnt] = np.array([0.,0.,self.d[0],1.])\n pcnt+=1\n elif self.type[0]=='p':\n self.p[pcnt] = np.array([0.,0.,self.d[0]+q[0],1.])\n pcnt+=1\n # Loop around all the ndofs\n for k in range(self.ndof):\n if self.type[k]=='r':\n T = self._Tdh(k, 0., q[k])\n if (not self.isdzero[k] and k!=0):\n self.p[pcnt] = np.array([0.,0.,self.d[k],1.])\n elif self.type[k]=='p':\n T = self._Tdh(k, q[k], 0.)\n if (not self.isdzero[k] and k!=0):\n self.p[pcnt] = np.array([0.,0.,self.d[k]+q[k],1.])\n else:\n print('wrong joint type')\n if k==0:\n self.Ts[k] = T\n self.p[pcnt] = self.Ts[k][:,3]\n pcnt+=1\n else:\n self.Ts[k] = self.Ts[k-1].dot(T)\n if (not self.isdzero[k]):\n self.p[pcnt] = self.Ts[k-1].dot(self.p[pcnt])\n pcnt+=1\n self.p[pcnt] = self.Ts[k][:,3]\n pcnt+=1\n # Clear the figure\n plt.clf()\n ax = plt.axes(projection='3d')\n # Names for the axes\n ax.set_xlabel('x'); ax.set_ylabel('y'); ax.set_zlabel('z')\n # Points (base of the robot)\n ax.scatter(0, 0, 0, color='g', s=50)\n # Body of the robot\n ax.plot([0, self.p[0][0]], [0, self.p[0][1]], [0, self.p[0][2]], linewidth=3, color='k')\n for k in range(1, len(self.p)):\n ax.plot([self.p[k-1][0],self.p[k][0]], [self.p[k-1][1],self.p[k][1]],\n [self.p[k-1][2], self.p[k][2]], linewidth=3, color='k')\n e = 0\n # Ensure cylinders for end-effector are not so large\n if ee:\n e = 1\n # scale for the cylinders of the end effector\n escale = cscale*0.5\n for k in np.flip(range(self.ndof)):\n if np.linalg.norm(self.Ts[k][:,3]-self.Ts[k-1][:,3])<1e-6:\n e=e+1\n else:\n break\n # Fake \"cylinders\" that represent the joint directions (except for the last joint)\n ax.plot([0,0], [0,0], [0-cscale,0+cscale], linewidth=10, color='g')\n for k in range(self.ndof-e):\n ax.plot([self.Ts[k][0,3]-cscale*self.Ts[k][0,2], self.Ts[k][0,3]+cscale*self.Ts[k][0,2]], \n [self.Ts[k][1,3]-cscale*self.Ts[k][1,2], self.Ts[k][1,3]+cscale*self.Ts[k][1,2]], \n [self.Ts[k][2,3]-cscale*self.Ts[k][2,2], self.Ts[k][2,3]+cscale*self.Ts[k][2,2]], \n linewidth=10, color='g')\n for k in range(self.ndof-e, self.ndof):\n ax.plot([self.Ts[k][0,3]-escale*self.Ts[k][0,2], self.Ts[k][0,3]+escale*self.Ts[k][0,2]], \n [self.Ts[k][1,3]-escale*self.Ts[k][1,2], self.Ts[k][1,3]+escale*self.Ts[k][1,2]], \n [self.Ts[k][2,3]-escale*self.Ts[k][2,2], self.Ts[k][2,3]+escale*self.Ts[k][2,2]], \n linewidth=10, color='g')\n # Plot an end effector\n if ee:\n # End effector (defined by 4 points)\n p1 = np.array([0, 0.1, 0, 1]); p2 = np.array([0, 0.1, 0.2, 1])\n p3 = np.array([0, -0.1, 0, 1]); p4 = np.array([0, -0.1, 0.2, 1])\n p1 = self.Ts[-1].dot(p1); p2 = self.Ts[-1].dot(p2); p3 = self.Ts[-1].dot(p3); p4 = self.Ts[-1].dot(p4)\n # Plot an end effector\n ax.plot([p1[0],p2[0]], [p1[1],p2[1]], [p1[2],p2[2]], color='k', linewidth=3)\n ax.plot([p3[0],p4[0]], [p3[1],p4[1]], [p3[2],p4[2]], color='k', linewidth=3)\n ax.plot([p1[0],p3[0]], [p1[1],p3[1]], [p1[2],p3[2]], color='k', linewidth=3)\n # Reference frame for the end effector (with respect to frame 0)\n ax.plot([self.Ts[-1][0,3],self.Ts[-1][0,3]+ascale*self.Ts[-1][0,0]], \n [self.Ts[-1][1,3],self.Ts[-1][1,3]+ascale*self.Ts[-1][1,0]], \n [self.Ts[-1][2,3],self.Ts[-1][2,3]+ascale*self.Ts[-1][2,0]], color='r')\n ax.plot([self.Ts[-1][0,3],self.Ts[-1][0,3]+ascale*self.Ts[-1][0,1]], \n [self.Ts[-1][1,3],self.Ts[-1][1,3]+ascale*self.Ts[-1][1,1]], \n [self.Ts[-1][2,3],self.Ts[-1][2,3]+ascale*self.Ts[-1][2,1]], color='g')\n ax.plot([self.Ts[-1][0,3],self.Ts[-1][0,3]+ascale*self.Ts[-1][0,2]], \n [self.Ts[-1][1,3],self.Ts[-1][1,3]+ascale*self.Ts[-1][1,2]], \n [self.Ts[-1][2,3],self.Ts[-1][2,3]+ascale*self.Ts[-1][2,2]], color='b')\n # Reference frame for the base (0)\n ax.plot([0,ascale], [0,0], [0,0], color='r')\n ax.plot([0,0], [0,ascale], [0,0], color='g')\n ax.plot([0,0], [0,0], [0,ascale], color='b')\n # Point of view\n ax.view_init(elev=elev, azim=azim)\n # Limits fot the figure axes\n if axlimits!=None:\n ax.set_xlim3d(axlimits[0][0], axlimits[0][1])\n ax.set_ylim3d(axlimits[1][0], axlimits[1][1])\n ax.set_zlim3d(axlimits[2][0], axlimits[2][1])", "def show_shape3d(self, fov=400, fig=None, ax=None):\n if fig is None:\n fig = plt.figure()\n ax = fig.add_subplot(111,projection='3d')\n # Set fov\n ax.set_xlim(-fov, fov)\n ax.set_ylim(-fov, fov)\n ax.set_zlim(-fov, fov)\n ax.set_aspect(\"equal\")\n\n# data = self.sections[\"soma\"][1]\n for sec in self.sections.values():\n self.lines = add_line3d(ax, self.lines, sec[0])", "def plot_projections(state_array, x_axis=None, y_axis=None, qubit_index=None,\n projection_axes=None, axes_labels=None, title=None):\n projection_axes = projection_axes or ['X', 'Y', 'Z']\n projection_axes = [p.upper() for p in projection_axes]\n state_array = np.array(state_array)\n\n fig = plt.figure()\n gs = gridspec.GridSpec(len(projection_axes), 2, width_ratios=(9.5, 0.5))\n\n for i, p in enumerate(projection_axes):\n if p.upper() not in ['X', 'Y', 'Z']:\n raise RuntimeError('projection_axes must be in [X, Y, Z], '\n 'got {}'.format(projection_axes))\n\n axes_labels = axes_labels or ['time', 'input', 'qubit']\n if len(state_array.shape) > 2 and 1 in state_array.shape:\n redundant_index = state_array.shape.index(1)\n new_shape = tuple([s for s in state_array.shape if s != 1])\n state_array = state_array.reshape(new_shape)\n if redundant_index == 0:\n try:\n axes_labels.remove('input')\n except ValueError:\n pass\n if redundant_index == 1:\n try:\n axes_labels.remove('time')\n except ValueError:\n pass\n elif len(state_array.shape) == 2:\n try:\n axes_labels.remove('input')\n except ValueError:\n pass\n if state_array.shape[-1] == 2 or qubit_index is not None:\n try:\n axes_labels.remove('qubit')\n except ValueError:\n pass\n if state_array.shape[-1] == 2 and qubit_index is None:\n qubit_index = 0\n\n if len(axes_labels) > 2:\n raise RuntimeError(\n 'cannot plot 3d, array provided has multiple qubits, inputs'\n ' and times, shape {}. Specify qubit ot slice array'\n ''.format(state_array.shape))\n elif len(axes_labels) == 0:\n raise RuntimeError(\n 'why are you here {}'.format(state_array.shape))\n\n projection_values = [[]] * len(projection_axes)\n if 'qubit' not in axes_labels and len(axes_labels) == 2: # [time, input]\n if x_axis is None:\n x_axis = np.arange(state_array.shape[1])\n if y_axis is None:\n y_axis = np.arange(state_array.shape[0] + 1)\n elif len(y_axis) == state_array.shape[0]:\n y_axis = np.append(y_axis, y_axis[-1] + (y_axis[-1] - y_axis[-2]))\n for i in range(len(projection_axes)):\n projection_values[i] = np.zeros(\n (state_array.shape[1], state_array.shape[0]), dtype=complex)\n for i, state in enumerate(state_array):\n for j, p in enumerate(projection_axes):\n projection_values[j][:, i] = projection(\n state, axis=p)[:, qubit_index]\n elif len(axes_labels) == 2: # [time, qubit], [input, qubit]\n if x_axis is None:\n x_axis = np.arange(state_array.shape[0])\n if y_axis is None:\n y_axis = np.arange(np.log2(state_array.shape[1]) + 1)\n elif len(y_axis) == state_array.shape[0]:\n y_axis = np.append(y_axis, y_axis[-1] + (y_axis[-1] - y_axis[-2]))\n for j, p in enumerate(projection_axes):\n projection_values[j] = projection(state_array, axis=p)\n elif 'qubit' not in axes_labels: # [input], [time]\n if x_axis is None:\n x_axis = np.arange(state_array.shape[0])\n for j, p in enumerate(projection_axes):\n projection_values[j] = projection(\n state_array, axis=p)[:, qubit_index]\n else: # [qubit]\n if x_axis is None:\n x_axis = np.arange(np.log2(len(state_array)))\n state_array = [state_array]\n for j, p in enumerate(projection_axes):\n projection_values[j] = projection(state_array, axis=p)\n\n for i, p in enumerate(projection_axes):\n proj = projection_values[i]\n ax = plt.subplot(gs[i, 0])\n if len(proj.shape) == 1:\n plot1d(x_axis, np.real(proj), ax)\n ax.set_ylim([-1.1, 1.1])\n ax.set_ylabel('{}_proj'.format(p))\n ax.set_xlabel(axes_labels[0])\n else:\n x_axis_2d, y_axis_2d = np.meshgrid(x_axis, y_axis)\n cax = plt.subplot(gs[i, 1])\n plot2d(x_axis_2d, y_axis_2d, np.real(proj.T), ax, cax,\n cbarlimits='{}_proj'.format(p))\n ax.yaxis.set_major_formatter(\n ticker.ScalarFormatter(useMathText=True))\n ax.set_xlabel(axes_labels[0])\n ax.set_ylabel(axes_labels[1])\n ax.set_title((title or '') + '{} projection'.format(p))\n\n gs.tight_layout(fig, rect=[0, 0, 1, 0.95])\n return fig", "def plotPointCloud(object, model=None):\n\n # Layout for plot\n fig = make_subplots(\n rows=2, cols=2,\n vertical_spacing=0.05,\n horizontal_spacing=0.05,\n specs=[[{'type': 'scatter3d'}, {'type': 'scatter3d'}],\n [{'type': 'scatter3d'}, {'type': 'scatter3d'}]])\n \n objlst = Data(object)\n\n device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n\n\n for i in range(4):\n point_cloud = objlst[np.random.randint(len(objlst))]\n\n if model is not None and 'Autoencoder' in model.name:\n point_cloud = model(point_cloud[None,:].to(device))\n point_cloud = torch.squeeze(point_cloud,0)\n \n if model is not None and 'Generator' in model.name:\n noise = noiseFunc(0, 0.2, 1, device)\n point_cloud = model(noise)\n point_cloud = torch.squeeze(point_cloud,0)\n\n\n np_point_cloud = point_cloud.detach().cpu().numpy()\n \n fig.add_trace(\n go.Scatter3d(x=np_point_cloud[:,0], \n y=np_point_cloud[:,1], \n z=np_point_cloud[:,2],\n mode='markers',\n marker=dict(size=1,\n color=np_point_cloud[:,2], \n colorscale='Viridis', \n opacity=0.8\n )),\n row=i//2 + 1, col=i%2 + 1\n )\n \n fig.update_layout(\n showlegend=False,\n height=800,\n width=1500\n )\n\n fig.show()", "def plot_phase_plane_trajectory(self, x0, tf=10, x_axis=0, y_axis=1):\n \n self.sim = simulation.CLosedLoopSimulation( self , tf )\n \n self.sim.x0 = x0\n self.sim.compute()\n self.sim.phase_plane_trajectory_closed_loop( x_axis , y_axis )", "def plot_surface_mpl(vtx,tri,data=None,rm=None,reorient='tvb',view='superior',\n shaded=False,ax=None,figsize=(6,4), title=None,\n lthr=None,uthr=None, nz_thr = 1E-20,\n shade_kwargs = {'edgecolors': 'k', 'linewidth': 0.1,\n 'alpha': None, 'cmap': 'coolwarm',\n 'vmin': None, 'vmax': None}):\n \n # Copy things to make sure we don't modify things \n # in the namespace inadvertently. \n \n vtx,tri = vtx.copy(),tri.copy()\n if data is not None: data = data.copy()\n\n # 1. Set the viewing angle \n \n if reorient == 'tvb':\n # The tvb default brain has coordinates in the order \n # yxz for some reason. So first change that: \n vtx = np.array([vtx[:,1],vtx[:,0],vtx[:,2]]).T.copy()\n \n # Also need to reflect in the x axis\n vtx[:,0]*=-1\n\n # (reorient == 'fs' is same as reorient=None; so not strictly needed\n # but is included for clarity)\n \n\n\n # ...get rotations for standard view options\n \n if view == 'lh_lat' : rots = [(0,-90),(1,90) ]\n elif view == 'lh_med' : rots = [(0,-90),(1,-90) ] \n elif view == 'rh_lat' : rots = [(0,-90),(1,-90) ]\n elif view == 'rh_med' : rots = [(0,-90),(1,90) ]\n elif view == 'superior' : rots = None\n elif view == 'inferior' : rots = (1,180)\n elif view == 'anterior' : rots = (0,-90)\n elif view == 'posterior' : rots = [(0, -90),(1,180)]\n elif (type(view) == tuple) or (type(view) == list): rots = view \n\n # (rh_lat is the default 'view' argument because no rotations are \n # for that one; so if no view is specified when the function is called, \n # the 'rh_lat' option is chose here and the surface is shown 'as is' \n \n \n # ...apply rotations \n \n if rots is None: rotmat = np.eye(3)\n else: rotmat = get_combined_rotation_matrix(rots)\n vtx = np.dot(vtx,rotmat)\n\n \n \n # 2. Sort out the data\n \n \n # ...if no data is given, plot a vector of 1s. \n # if using region data, create corresponding surface vector \n if data is None: \n data = np.ones(vtx.shape[0]) \n elif data.shape[0] != vtx.shape[0]: \n data = np.array([data[r] for r in rm])\n \n # ...apply thresholds\n if uthr: data *= (data < uthr)\n if lthr: data *= (data > lthr)\n data *= (np.abs(data) > nz_thr)\n\n \n # 3. Create the surface triangulation object \n \n x,y,z = vtx.T\n tx,ty,tz = vtx[tri].mean(axis=1).T\n tr = Triangulation(x,y,tri[np.argsort(tz)])\n \n # 4. Make the figure \n\n if ax is None: fig, ax = plt.subplots(figsize=figsize) \n \n #if shade = 'gouraud': shade_opts['shade'] = \n tc = ax.tripcolor(tr, np.squeeze(data), **shade_kwargs)\n \n ax.set_aspect('equal')\n ax.axis('off')\n \n if title is not None: ax.set_title(title)", "def plot_transformation(args):\n import matplotlib as mpl\n import matplotlib.pyplot as plt\n\n MEDIUM_SIZE = 18\n BIGGER_SIZE = 24\n\n plt.rc('text', usetex=True) # controls default text sizes\n plt.rc('font', size=BIGGER_SIZE) # controls default text sizes\n plt.rc('font', family=\"serif\") # controls default text sizes\n plt.rc('axes', titlesize=MEDIUM_SIZE) # fontsize of the x and y labels\n plt.rc('axes', labelsize=MEDIUM_SIZE) # fontsize of the x and y labels\n plt.rc('xtick', labelsize=MEDIUM_SIZE) # fontsize of the tick labels\n plt.rc('ytick', labelsize=MEDIUM_SIZE) # fontsize of the tick labels\n plt.rc('legend', fontsize=MEDIUM_SIZE) # legend fontsize\n\n model: GraphObjectIDFeaturizerEmbedder = cast(GraphObjectIDFeaturizerEmbedder,\n GraphEmbedder.from_file(args.model_file))\n\n inputs_tensor = model.get_featurizer_graph_embedder().retrieve_nodes(\n model.graph_dataset.n_nodes()\n )\n inputs = inputs_tensor.detach().numpy()\n\n if args.input:\n fig = plt.figure(figsize=(8, 8))\n ax = fig.add_subplot(111)\n draw_wireframe(ax, inputs)\n plot_input(ax, model, inputs)\n fig.tight_layout()\n\n if args.input_path:\n fig.savefig(args.input_path)\n else:\n fig.show()\n input(\"Press any key to exit.\")\n if args.output:\n output_tensor = model.retrieve_nodes(model.graph_dataset.n_nodes())\n outputs = output_tensor.detach().numpy()\n\n outputs = project_to_ambient(model.out_manifold, outputs)\n fig = plt.figure(figsize=(8, 8))\n if outputs.shape[-1] == 2:\n ax = fig.add_subplot(111)\n else:\n assert outputs.shape[-1] == 3\n ax = fig.add_subplot(111, projection='3d')\n\n draw_manifold_wireframe(ax, model.out_manifold)\n draw_wireframe(ax, inputs, model.model)\n plot_output(ax, model.graph_dataset, model.out_manifold, inputs, outputs)\n\n fig.tight_layout()\n if args.output_path:\n fig.savefig(args.output_path)\n else:\n fig.show()\n input(\"Press any key to exit.\")", "def draw_beam(axes, view=(0, 0), alpha=0.5, steps=25):\n #axes.plot([0,0],[0,0],[1,-1])\n #axes.scatter([0]*100,[0]*100,np.linspace(1, -1, 100), alpha=alpha)\n\n u = np.linspace(0, 2 * pi, steps)\n v = np.linspace(-1, 1, 2)\n\n r = 0.02\n x = r*np.outer(cos(u), np.ones_like(v))\n y = r*np.outer(sin(u), np.ones_like(v))\n z = 1.3*np.outer(np.ones_like(u), v)\n\n theta, phi = view\n shape = x.shape\n points = np.array([x.flatten(), y.flatten(), z.flatten()])\n points = Rz(phi)@Ry(theta)@points\n x, y, z = [v.reshape(shape) for v in points]\n axes.plot_surface(x, y, z, color='yellow', alpha=alpha)\n\n # TODO: draw endcaps on beam\n ## Drawing tiny balls on the end will work\n #draw_sphere(axes, radius=0.02, center=(0, 0, 1.3), color='yellow', alpha=alpha)\n #draw_sphere(axes, radius=0.02, center=(0, 0, -1.3), color='yellow', alpha=alpha)\n ## The following does not work\n #triangles = [(0, i+1, i+2) for i in range(steps-2)]\n #x_cap, y_cap = x[:, 0], y[:, 0]\n #for z_cap in z[:, 0], z[:, -1]:\n # axes.plot_trisurf(x_cap, y_cap, z_cap, triangles,\n # color='yellow', alpha=alpha)", "def plot_surface_components(components: List[SurfaceComponent], plot_normals=True, quiver_len=0.2):\n\n import matplotlib.pyplot as plt\n from mpl_toolkits.mplot3d import Axes3D\n\n fig = plt.figure()\n ax = fig.gca(projection='3d')\n\n for comp in components:\n for surf in comp.surfaces:\n for patch in surf.patches:\n ax.plot_surface(patch.x, patch.y, patch.z)\n if plot_normals:\n ax.quiver(patch.x, patch.y, patch.z, patch.nx, patch.ny, patch.nz, length=quiver_len)\n\n vsp.set_3d_axis_equal(ax)\n\n return ax", "def show_axes(self):\n\n tprop = vtk.vtkTextProperty()\n tprop.SetColor(0., 0., 0.)\n tprop.ShadowOn()\n\n axes = vtk.vtkCubeAxesActor2D()\n if vtk.VTK_MAJOR_VERSION <= 5:\n axes.SetInput(self.polydatas[0])\n else:\n axes.SetInputData(self.polydatas[0])\n\n axes.SetCamera(self.renderer.GetActiveCamera())\n axes.SetLabelFormat(\"%6.4g\")\n axes.SetFlyModeToOuterEdges()\n axes.SetFontFactor(0.8)\n axes.SetAxisTitleTextProperty(tprop)\n axes.SetAxisLabelTextProperty(tprop)\n # axes.DrawGridLinesOn()\n\n self.renderer.AddViewProp(axes)\n self.axes.append(axes)", "def __init__(self):\n fig = plt.figure(figsize=(10, 10))\n self._axes = fig.add_subplot(111, projection='3d')\n self._axes.set_xlabel('X')\n self._axes.set_ylabel('Y')\n self._axes.set_zlabel('Z')", "def plot_3d(pts):\n fig = plt.figure()\n ax = fig.add_subplot(111, projection='3d')\n xs, ys, zs = zip(*pts)\n ax.scatter(xs, ys, zs, c='r', marker='o')\n ax.set_xlabel('X')\n ax.set_ylabel('Y')\n ax.set_zlabel('Z')\n plt.show()", "def plotGlobe3D():", "def ThreeDPositionPlot(self):\r\n try:\r\n numberOfParticles = len(self.LoadSim.Simulation[0])\r\n lengthOfSimulation = len(self.LoadSim.Time)\r\n # creates a list of three lists per particle.\r\n inputData = [[[], [], []] for i in range(numberOfParticles)]\r\n for i in range(lengthOfSimulation):\r\n for j in range(numberOfParticles):\r\n for k in range(3):\r\n inputData[j][k].append(self.LoadSim.Simulation[i][j].position[k])\r\n\r\n fig = plt.figure()\r\n ax = fig.gca(projection='3d')\r\n for j in range(numberOfParticles):\r\n ax.plot(inputData[j][0], inputData[j][1], inputData[j][2]\r\n , label='%s'%(self.LoadSim.Simulation[0][j].name))\r\n plt.title(\"Position of particles over time\")\r\n ax.set_xlabel(\"x position (m)\"), ax.set_ylabel(\"y position (m)\"), ax.set_zlabel(\"z position (m)\")\r\n ax.legend()\r\n plt.savefig(\"%s 3D position.jpg\"%(self.fileName))\r\n plt.show()\r\n\r\n except:\r\n AttributeError\r\n print(\"You cannot plot this figure with the data you have provided.\")" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Plot a 3D pose on given axis 'axes' with given 'axis_length'.
def plot_pose3RT_on_axes(axes, gRp, origin, axis_length=0.1, center_plot=False, line_obj_list=None): # draw the camera axes x_axis = origin + gRp[:, 0] * axis_length linex = np.append(origin, x_axis, axis=0) y_axis = origin + gRp[:, 1] * axis_length liney = np.append(origin, y_axis, axis=0) z_axis = origin + gRp[:, 2] * axis_length linez = np.append(origin, z_axis, axis=0) if line_obj_list is None: xaplt = axes.plot(linex[:, 0], linex[:, 1], linex[:, 2], 'r-') yaplt = axes.plot(liney[:, 0], liney[:, 1], liney[:, 2], 'g-') zaplt = axes.plot(linez[:, 0], linez[:, 1], linez[:, 2], 'b-') if center_plot: #center_3d_plot_around_pt(axes,origin[0]) pass return [xaplt, yaplt, zaplt] else: line_obj_list[0][0].set_data(linex[:, 0], linex[:, 1]) line_obj_list[0][0].set_3d_properties(linex[:,2]) line_obj_list[1][0].set_data(liney[:, 0], liney[:, 1]) line_obj_list[1][0].set_3d_properties(liney[:,2]) line_obj_list[2][0].set_data(linez[:, 0], linez[:, 1]) line_obj_list[2][0].set_3d_properties(linez[:,2]) if center_plot: #center_3d_plot_around_pt(axes,origin[0]) pass return line_obj_list
[ "def draw_axes(axes, origin=(-1, -1, -1), length=(2, 2, 2)):\n x, y, z = origin\n dx, dy, dz = length\n axes.plot([x, x+dx], [y, y], [z, z], color='black')\n axes.plot([x, x], [y, y+dy], [z, z], color='black')\n axes.plot([x, x], [y, y], [z, z+dz], color='black')", "def plot_pose(pose):\n import mpl_toolkits.mplot3d.axes3d as p3\n _CONNECTION = [\n [0, 1], [1, 2], [2, 3], [0, 4], [4, 5], [5, 6], [0, 7], [7, 8],\n [8, 9], [9, 10], [8, 11], [11, 12], [12, 13], [8, 14], [14, 15],\n [15, 16]]\n\n # fig = plt.figure()\n # ax = fig.gca(projection='3d')\n for c in _CONNECTION:\n col = '#%02x%02x%02x' % joint_color(c[0])\n ax.plot([pose[0, c[0]], pose[0, c[1]]],\n [pose[1, c[0]], pose[1, c[1]]],\n [pose[2, c[0]], pose[2, c[1]]], c=col)\n\n\n for j in range(pose.shape[1]):\n col = '#%02x%02x%02x' % joint_color(j)\n ax.scatter(pose[0, j], pose[1, j], pose[2, j],\n c=col, marker='*', edgecolor=col)\n smallest = pose.min()\n largest = pose.max()\n ax.set_xlim3d(smallest, largest)\n ax.set_ylim3d(smallest, largest)\n ax.set_zlim3d(smallest, largest)\n\n return fig", "def drawWorldAxes(axesLength):\n xpointer = vp.arrow(pos=vp.vector(0, 0, 0), axis=vp.vector(axesLength, 0, 0), color=vp.color.green) # to the right\n ypointer = vp.arrow(pos=vp.vector(0, 0, 0), axis=vp.vector(0, axesLength, 0), color=vp.color.red) # (up)\n zpointer = vp.arrow(pos=vp.vector(0, 0, 0), axis=vp.vector(0, 0, axesLength), color=vp.color.blue) # out of the page\n return (xpointer, ypointer, zpointer)", "def show_axes(ax3d, equal=True):\n if equal is True:\n set_axes3d_equal(ax3d)\n plt.show()", "def plotPath_3D(self, seq, poses_gt, poses_result, plot_path_dir):\n from mpl_toolkits.mplot3d import Axes3D\n\n start_point = [[0], [0], [0]]\n fontsize_ = 8\n style_pred = 'b-'\n style_gt = 'r-'\n style_O = 'ko'\n\n poses_dict = {} \n poses_dict[\"Ours\"] = poses_result\n if poses_gt:\n poses_dict[\"Ground Truth\"] = poses_gt\n\n fig = plt.figure(figsize=(8,8), dpi=110)\n ax = fig.gca(projection='3d')\n\n for key,_ in poses_dict.items():\n plane_point = []\n for frame_idx in sorted(poses_dict[key].keys()):\n pose = poses_dict[key][frame_idx]\n plane_point.append([pose[0,3], pose[2,3], pose[1,3]])\n plane_point = np.asarray(plane_point)\n style = style_pred if key == 'Ours' else style_gt\n plt.plot(plane_point[:,0], plane_point[:,1], plane_point[:,2], style, label=key) \n plt.plot(start_point[0], start_point[1], start_point[2], style_O, label='Start Point')\n\n xlim = ax.get_xlim3d()\n ylim = ax.get_ylim3d()\n zlim = ax.get_zlim3d()\n xmean = np.mean(xlim)\n ymean = np.mean(ylim)\n zmean = np.mean(zlim)\n plot_radius = max([abs(lim - mean_)\n for lims, mean_ in ((xlim, xmean),\n (ylim, ymean),\n (zlim, zmean))\n for lim in lims])\n ax.set_xlim3d([xmean - plot_radius, xmean + plot_radius])\n ax.set_ylim3d([ymean - plot_radius, ymean + plot_radius])\n ax.set_zlim3d([zmean - plot_radius, zmean + plot_radius])\n\n ax.legend()\n # plt.legend(loc=\"upper right\", prop={'size':fontsize_}) \n ax.set_xlabel('x (m)', fontsize=fontsize_)\n ax.set_ylabel('z (m)', fontsize=fontsize_)\n ax.set_zlabel('y (m)', fontsize=fontsize_)\n ax.view_init(elev=20., azim=-35)\n\n png_title = \"{}_path_3D\".format(seq)\n plt.savefig(plot_path_dir+\"/\"+png_title+\".png\", bbox_inches='tight', pad_inches=0.1)\n pdf = matplotlib.backends.backend_pdf.PdfPages(plot_path_dir + \"/\" + png_title + \".pdf\") \n fig.tight_layout()\n pdf.savefig(fig) \n # plt.show()\n plt.close()", "def show_shape3d(self, fov=400, fig=None, ax=None):\n if fig is None:\n fig = plt.figure()\n ax = fig.add_subplot(111,projection='3d')\n # Set fov\n ax.set_xlim(-fov, fov)\n ax.set_ylim(-fov, fov)\n ax.set_zlim(-fov, fov)\n ax.set_aspect(\"equal\")\n\n# data = self.sections[\"soma\"][1]\n for sec in self.sections.values():\n self.lines = add_line3d(ax, self.lines, sec[0])", "def plot_3d(pts):\n fig = plt.figure()\n ax = fig.add_subplot(111, projection='3d')\n xs, ys, zs = zip(*pts)\n ax.scatter(xs, ys, zs, c='r', marker='o')\n ax.set_xlabel('X')\n ax.set_ylabel('Y')\n ax.set_zlabel('Z')\n plt.show()", "def plot_projections(state_array, x_axis=None, y_axis=None, qubit_index=None,\n projection_axes=None, axes_labels=None, title=None):\n projection_axes = projection_axes or ['X', 'Y', 'Z']\n projection_axes = [p.upper() for p in projection_axes]\n state_array = np.array(state_array)\n\n fig = plt.figure()\n gs = gridspec.GridSpec(len(projection_axes), 2, width_ratios=(9.5, 0.5))\n\n for i, p in enumerate(projection_axes):\n if p.upper() not in ['X', 'Y', 'Z']:\n raise RuntimeError('projection_axes must be in [X, Y, Z], '\n 'got {}'.format(projection_axes))\n\n axes_labels = axes_labels or ['time', 'input', 'qubit']\n if len(state_array.shape) > 2 and 1 in state_array.shape:\n redundant_index = state_array.shape.index(1)\n new_shape = tuple([s for s in state_array.shape if s != 1])\n state_array = state_array.reshape(new_shape)\n if redundant_index == 0:\n try:\n axes_labels.remove('input')\n except ValueError:\n pass\n if redundant_index == 1:\n try:\n axes_labels.remove('time')\n except ValueError:\n pass\n elif len(state_array.shape) == 2:\n try:\n axes_labels.remove('input')\n except ValueError:\n pass\n if state_array.shape[-1] == 2 or qubit_index is not None:\n try:\n axes_labels.remove('qubit')\n except ValueError:\n pass\n if state_array.shape[-1] == 2 and qubit_index is None:\n qubit_index = 0\n\n if len(axes_labels) > 2:\n raise RuntimeError(\n 'cannot plot 3d, array provided has multiple qubits, inputs'\n ' and times, shape {}. Specify qubit ot slice array'\n ''.format(state_array.shape))\n elif len(axes_labels) == 0:\n raise RuntimeError(\n 'why are you here {}'.format(state_array.shape))\n\n projection_values = [[]] * len(projection_axes)\n if 'qubit' not in axes_labels and len(axes_labels) == 2: # [time, input]\n if x_axis is None:\n x_axis = np.arange(state_array.shape[1])\n if y_axis is None:\n y_axis = np.arange(state_array.shape[0] + 1)\n elif len(y_axis) == state_array.shape[0]:\n y_axis = np.append(y_axis, y_axis[-1] + (y_axis[-1] - y_axis[-2]))\n for i in range(len(projection_axes)):\n projection_values[i] = np.zeros(\n (state_array.shape[1], state_array.shape[0]), dtype=complex)\n for i, state in enumerate(state_array):\n for j, p in enumerate(projection_axes):\n projection_values[j][:, i] = projection(\n state, axis=p)[:, qubit_index]\n elif len(axes_labels) == 2: # [time, qubit], [input, qubit]\n if x_axis is None:\n x_axis = np.arange(state_array.shape[0])\n if y_axis is None:\n y_axis = np.arange(np.log2(state_array.shape[1]) + 1)\n elif len(y_axis) == state_array.shape[0]:\n y_axis = np.append(y_axis, y_axis[-1] + (y_axis[-1] - y_axis[-2]))\n for j, p in enumerate(projection_axes):\n projection_values[j] = projection(state_array, axis=p)\n elif 'qubit' not in axes_labels: # [input], [time]\n if x_axis is None:\n x_axis = np.arange(state_array.shape[0])\n for j, p in enumerate(projection_axes):\n projection_values[j] = projection(\n state_array, axis=p)[:, qubit_index]\n else: # [qubit]\n if x_axis is None:\n x_axis = np.arange(np.log2(len(state_array)))\n state_array = [state_array]\n for j, p in enumerate(projection_axes):\n projection_values[j] = projection(state_array, axis=p)\n\n for i, p in enumerate(projection_axes):\n proj = projection_values[i]\n ax = plt.subplot(gs[i, 0])\n if len(proj.shape) == 1:\n plot1d(x_axis, np.real(proj), ax)\n ax.set_ylim([-1.1, 1.1])\n ax.set_ylabel('{}_proj'.format(p))\n ax.set_xlabel(axes_labels[0])\n else:\n x_axis_2d, y_axis_2d = np.meshgrid(x_axis, y_axis)\n cax = plt.subplot(gs[i, 1])\n plot2d(x_axis_2d, y_axis_2d, np.real(proj.T), ax, cax,\n cbarlimits='{}_proj'.format(p))\n ax.yaxis.set_major_formatter(\n ticker.ScalarFormatter(useMathText=True))\n ax.set_xlabel(axes_labels[0])\n ax.set_ylabel(axes_labels[1])\n ax.set_title((title or '') + '{} projection'.format(p))\n\n gs.tight_layout(fig, rect=[0, 0, 1, 0.95])\n return fig", "def show_axes(self):\n\n tprop = vtk.vtkTextProperty()\n tprop.SetColor(0., 0., 0.)\n tprop.ShadowOn()\n\n axes = vtk.vtkCubeAxesActor2D()\n if vtk.VTK_MAJOR_VERSION <= 5:\n axes.SetInput(self.polydatas[0])\n else:\n axes.SetInputData(self.polydatas[0])\n\n axes.SetCamera(self.renderer.GetActiveCamera())\n axes.SetLabelFormat(\"%6.4g\")\n axes.SetFlyModeToOuterEdges()\n axes.SetFontFactor(0.8)\n axes.SetAxisTitleTextProperty(tprop)\n axes.SetAxisLabelTextProperty(tprop)\n # axes.DrawGridLinesOn()\n\n self.renderer.AddViewProp(axes)\n self.axes.append(axes)", "def ThreeDPositionPlot(self):\r\n try:\r\n numberOfParticles = len(self.LoadSim.Simulation[0])\r\n lengthOfSimulation = len(self.LoadSim.Time)\r\n # creates a list of three lists per particle.\r\n inputData = [[[], [], []] for i in range(numberOfParticles)]\r\n for i in range(lengthOfSimulation):\r\n for j in range(numberOfParticles):\r\n for k in range(3):\r\n inputData[j][k].append(self.LoadSim.Simulation[i][j].position[k])\r\n\r\n fig = plt.figure()\r\n ax = fig.gca(projection='3d')\r\n for j in range(numberOfParticles):\r\n ax.plot(inputData[j][0], inputData[j][1], inputData[j][2]\r\n , label='%s'%(self.LoadSim.Simulation[0][j].name))\r\n plt.title(\"Position of particles over time\")\r\n ax.set_xlabel(\"x position (m)\"), ax.set_ylabel(\"y position (m)\"), ax.set_zlabel(\"z position (m)\")\r\n ax.legend()\r\n plt.savefig(\"%s 3D position.jpg\"%(self.fileName))\r\n plt.show()\r\n\r\n except:\r\n AttributeError\r\n print(\"You cannot plot this figure with the data you have provided.\")", "def plot(self, q, ee=True, axlimits=None, elev=25, azim=45, ascale=0.4, cscale=0.1):\n # Compute intermediate DH homogeneous transformations\n pcnt = 0\n # Initial intermediate point\n if (not self.isdzero[0]):\n if self.type[0]=='r':\n self.p[pcnt] = np.array([0.,0.,self.d[0],1.])\n pcnt+=1\n elif self.type[0]=='p':\n self.p[pcnt] = np.array([0.,0.,self.d[0]+q[0],1.])\n pcnt+=1\n # Loop around all the ndofs\n for k in range(self.ndof):\n if self.type[k]=='r':\n T = self._Tdh(k, 0., q[k])\n if (not self.isdzero[k] and k!=0):\n self.p[pcnt] = np.array([0.,0.,self.d[k],1.])\n elif self.type[k]=='p':\n T = self._Tdh(k, q[k], 0.)\n if (not self.isdzero[k] and k!=0):\n self.p[pcnt] = np.array([0.,0.,self.d[k]+q[k],1.])\n else:\n print('wrong joint type')\n if k==0:\n self.Ts[k] = T\n self.p[pcnt] = self.Ts[k][:,3]\n pcnt+=1\n else:\n self.Ts[k] = self.Ts[k-1].dot(T)\n if (not self.isdzero[k]):\n self.p[pcnt] = self.Ts[k-1].dot(self.p[pcnt])\n pcnt+=1\n self.p[pcnt] = self.Ts[k][:,3]\n pcnt+=1\n # Clear the figure\n plt.clf()\n ax = plt.axes(projection='3d')\n # Names for the axes\n ax.set_xlabel('x'); ax.set_ylabel('y'); ax.set_zlabel('z')\n # Points (base of the robot)\n ax.scatter(0, 0, 0, color='g', s=50)\n # Body of the robot\n ax.plot([0, self.p[0][0]], [0, self.p[0][1]], [0, self.p[0][2]], linewidth=3, color='k')\n for k in range(1, len(self.p)):\n ax.plot([self.p[k-1][0],self.p[k][0]], [self.p[k-1][1],self.p[k][1]],\n [self.p[k-1][2], self.p[k][2]], linewidth=3, color='k')\n e = 0\n # Ensure cylinders for end-effector are not so large\n if ee:\n e = 1\n # scale for the cylinders of the end effector\n escale = cscale*0.5\n for k in np.flip(range(self.ndof)):\n if np.linalg.norm(self.Ts[k][:,3]-self.Ts[k-1][:,3])<1e-6:\n e=e+1\n else:\n break\n # Fake \"cylinders\" that represent the joint directions (except for the last joint)\n ax.plot([0,0], [0,0], [0-cscale,0+cscale], linewidth=10, color='g')\n for k in range(self.ndof-e):\n ax.plot([self.Ts[k][0,3]-cscale*self.Ts[k][0,2], self.Ts[k][0,3]+cscale*self.Ts[k][0,2]], \n [self.Ts[k][1,3]-cscale*self.Ts[k][1,2], self.Ts[k][1,3]+cscale*self.Ts[k][1,2]], \n [self.Ts[k][2,3]-cscale*self.Ts[k][2,2], self.Ts[k][2,3]+cscale*self.Ts[k][2,2]], \n linewidth=10, color='g')\n for k in range(self.ndof-e, self.ndof):\n ax.plot([self.Ts[k][0,3]-escale*self.Ts[k][0,2], self.Ts[k][0,3]+escale*self.Ts[k][0,2]], \n [self.Ts[k][1,3]-escale*self.Ts[k][1,2], self.Ts[k][1,3]+escale*self.Ts[k][1,2]], \n [self.Ts[k][2,3]-escale*self.Ts[k][2,2], self.Ts[k][2,3]+escale*self.Ts[k][2,2]], \n linewidth=10, color='g')\n # Plot an end effector\n if ee:\n # End effector (defined by 4 points)\n p1 = np.array([0, 0.1, 0, 1]); p2 = np.array([0, 0.1, 0.2, 1])\n p3 = np.array([0, -0.1, 0, 1]); p4 = np.array([0, -0.1, 0.2, 1])\n p1 = self.Ts[-1].dot(p1); p2 = self.Ts[-1].dot(p2); p3 = self.Ts[-1].dot(p3); p4 = self.Ts[-1].dot(p4)\n # Plot an end effector\n ax.plot([p1[0],p2[0]], [p1[1],p2[1]], [p1[2],p2[2]], color='k', linewidth=3)\n ax.plot([p3[0],p4[0]], [p3[1],p4[1]], [p3[2],p4[2]], color='k', linewidth=3)\n ax.plot([p1[0],p3[0]], [p1[1],p3[1]], [p1[2],p3[2]], color='k', linewidth=3)\n # Reference frame for the end effector (with respect to frame 0)\n ax.plot([self.Ts[-1][0,3],self.Ts[-1][0,3]+ascale*self.Ts[-1][0,0]], \n [self.Ts[-1][1,3],self.Ts[-1][1,3]+ascale*self.Ts[-1][1,0]], \n [self.Ts[-1][2,3],self.Ts[-1][2,3]+ascale*self.Ts[-1][2,0]], color='r')\n ax.plot([self.Ts[-1][0,3],self.Ts[-1][0,3]+ascale*self.Ts[-1][0,1]], \n [self.Ts[-1][1,3],self.Ts[-1][1,3]+ascale*self.Ts[-1][1,1]], \n [self.Ts[-1][2,3],self.Ts[-1][2,3]+ascale*self.Ts[-1][2,1]], color='g')\n ax.plot([self.Ts[-1][0,3],self.Ts[-1][0,3]+ascale*self.Ts[-1][0,2]], \n [self.Ts[-1][1,3],self.Ts[-1][1,3]+ascale*self.Ts[-1][1,2]], \n [self.Ts[-1][2,3],self.Ts[-1][2,3]+ascale*self.Ts[-1][2,2]], color='b')\n # Reference frame for the base (0)\n ax.plot([0,ascale], [0,0], [0,0], color='r')\n ax.plot([0,0], [0,ascale], [0,0], color='g')\n ax.plot([0,0], [0,0], [0,ascale], color='b')\n # Point of view\n ax.view_init(elev=elev, azim=azim)\n # Limits fot the figure axes\n if axlimits!=None:\n ax.set_xlim3d(axlimits[0][0], axlimits[0][1])\n ax.set_ylim3d(axlimits[1][0], axlimits[1][1])\n ax.set_zlim3d(axlimits[2][0], axlimits[2][1])", "def plotPointCloud(object, model=None):\n\n # Layout for plot\n fig = make_subplots(\n rows=2, cols=2,\n vertical_spacing=0.05,\n horizontal_spacing=0.05,\n specs=[[{'type': 'scatter3d'}, {'type': 'scatter3d'}],\n [{'type': 'scatter3d'}, {'type': 'scatter3d'}]])\n \n objlst = Data(object)\n\n device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n\n\n for i in range(4):\n point_cloud = objlst[np.random.randint(len(objlst))]\n\n if model is not None and 'Autoencoder' in model.name:\n point_cloud = model(point_cloud[None,:].to(device))\n point_cloud = torch.squeeze(point_cloud,0)\n \n if model is not None and 'Generator' in model.name:\n noise = noiseFunc(0, 0.2, 1, device)\n point_cloud = model(noise)\n point_cloud = torch.squeeze(point_cloud,0)\n\n\n np_point_cloud = point_cloud.detach().cpu().numpy()\n \n fig.add_trace(\n go.Scatter3d(x=np_point_cloud[:,0], \n y=np_point_cloud[:,1], \n z=np_point_cloud[:,2],\n mode='markers',\n marker=dict(size=1,\n color=np_point_cloud[:,2], \n colorscale='Viridis', \n opacity=0.8\n )),\n row=i//2 + 1, col=i%2 + 1\n )\n \n fig.update_layout(\n showlegend=False,\n height=800,\n width=1500\n )\n\n fig.show()", "def __init__(self):\n fig = plt.figure(figsize=(10, 10))\n self._axes = fig.add_subplot(111, projection='3d')\n self._axes.set_xlabel('X')\n self._axes.set_ylabel('Y')\n self._axes.set_zlabel('Z')", "def plot_phase_plane_trajectory(self, x0, tf=10, x_axis=0, y_axis=1):\n \n self.sim = simulation.CLosedLoopSimulation( self , tf )\n \n self.sim.x0 = x0\n self.sim.compute()\n self.sim.phase_plane_trajectory_closed_loop( x_axis , y_axis )", "def plotGlobe3D():", "def set_axes3d_equal(ax3d):\n x_limits = ax3d.get_xlim3d()\n y_limits = ax3d.get_ylim3d()\n z_limits = ax3d.get_zlim3d()\n x_range = abs(x_limits[1] - x_limits[0])\n x_middle = np.mean(x_limits)\n y_range = abs(y_limits[1] - y_limits[0])\n y_middle = np.mean(y_limits)\n z_range = abs(z_limits[1] - z_limits[0])\n z_middle = np.mean(z_limits)\n # The plot bounding box is a sphere in the sense of the infinity\n # norm, hence I call half the max range the plot radius.\n plot_radius = 0.5 * max([x_range, y_range, z_range])\n ax3d.set_xlim3d([x_middle - plot_radius, x_middle + plot_radius])\n ax3d.set_ylim3d([y_middle - plot_radius, y_middle + plot_radius])\n ax3d.set_zlim3d([z_middle - plot_radius, z_middle + plot_radius])", "def __qupulse_template_plot(sequence, sampling_rate, axes):\n ns_sample_rate = sampling_rate / Sequencer.__sec_to_ns\n plot(sequence['wave'], sample_rate=ns_sample_rate, axes=axes, show=False)", "def set_aspect_equal_3d(ax):\n xlim = (-1, 1)\n ylim = (-1, 1)\n zlim = (-1, 1)\n\n xmean = mean(xlim)\n ymean = mean(ylim)\n zmean = mean(zlim)\n\n plot_radius = max([\n abs(lim - mean_)\n for lims, mean_ in ((xlim, xmean), (ylim, ymean), (zlim, zmean))\n for lim in lims\n ])\n\n factor = 1\n ax.set_xlim3d([xmean - factor * plot_radius, xmean + factor * plot_radius])\n ax.set_ylim3d([ymean - factor * plot_radius, ymean + factor * plot_radius])\n ax.set_zlim3d([zmean - 1 * plot_radius, zmean + 1 * plot_radius])", "def draw_beam(axes, view=(0, 0), alpha=0.5, steps=25):\n #axes.plot([0,0],[0,0],[1,-1])\n #axes.scatter([0]*100,[0]*100,np.linspace(1, -1, 100), alpha=alpha)\n\n u = np.linspace(0, 2 * pi, steps)\n v = np.linspace(-1, 1, 2)\n\n r = 0.02\n x = r*np.outer(cos(u), np.ones_like(v))\n y = r*np.outer(sin(u), np.ones_like(v))\n z = 1.3*np.outer(np.ones_like(u), v)\n\n theta, phi = view\n shape = x.shape\n points = np.array([x.flatten(), y.flatten(), z.flatten()])\n points = Rz(phi)@Ry(theta)@points\n x, y, z = [v.reshape(shape) for v in points]\n axes.plot_surface(x, y, z, color='yellow', alpha=alpha)\n\n # TODO: draw endcaps on beam\n ## Drawing tiny balls on the end will work\n #draw_sphere(axes, radius=0.02, center=(0, 0, 1.3), color='yellow', alpha=alpha)\n #draw_sphere(axes, radius=0.02, center=(0, 0, -1.3), color='yellow', alpha=alpha)\n ## The following does not work\n #triangles = [(0, i+1, i+2) for i in range(steps-2)]\n #x_cap, y_cap = x[:, 0], y[:, 0]\n #for z_cap in z[:, 0], z[:, -1]:\n # axes.plot_trisurf(x_cap, y_cap, z_cap, triangles,\n # color='yellow', alpha=alpha)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Take a file in binary format and a dictionary of hashes and run a fixity check against the first one found that's supported by hashlib.
def download_fixity_checker(resource_dict): fixity_obj = { 'hash_algorithm': None, 'source_hash': None, 'presqt_hash': None, 'fixity': None, 'fixity_details': None, 'title': resource_dict['title'], 'path': resource_dict['path'] } fixity_match = True for hash_algorithm, hash_value in resource_dict['hashes'].items(): # If the current hash_value is not None and the hash algorithm is supported by hashlib # then this is the hash we will run our fixity checker against. if hash_value and hash_algorithm in hashlib.algorithms_available: # Run the file through the hash algorithm hash_hex = hash_generator(resource_dict['file'], hash_algorithm) fixity_obj['hash_algorithm'] = hash_algorithm fixity_obj['presqt_hash'] = hash_hex fixity_obj['source_hash'] = hash_value # Compare the given hash with the calculated hash. if hash_hex == hash_value: fixity_obj['fixity'] = True fixity_obj['fixity_details'] = 'Source Hash and PresQT Calculated hash matched.' else: fixity_obj['fixity'] = False fixity_obj['fixity_details'] = ( 'Source Hash and PresQT Calculated hash do not match.') fixity_match = False break else: # If either there is no matching algorithms in hashlib or the provided hashes # don't have values then we assume fixity has remained and we calculate a new hash # using md5 to give to the user. h = hashlib.md5(resource_dict['file']) hash_hex = h.hexdigest() fixity_obj['hash_algorithm'] = 'md5' fixity_obj['presqt_hash'] = hash_hex fixity_obj['fixity_details'] = ( 'Either a Source Hash was not provided or the source hash algorithm is not supported.') fixity_match = False return fixity_obj, fixity_match
[ "def verify(hash_file, path, exclude=None, relaxed=False, quiet=False):\n is_file = False\n if os.path.isdir(path):\n pass\n elif os.path.isfile(path):\n is_file = True\n else:\n return HashResult.BAD_PATH\n\n # load hashes\n try:\n hash_info = load(hash_file)\n except BadFileHashLoadError:\n return HashResult.BAD_PATH\n except BadFormatHashLoadError as e:\n if not quiet:\n err('''\\\nhash file is not properly formatted\n\nThe hash file provided is incorrectly formatted. The hash file expects lines\nwith the hash type, hash and target file provided. For example:\n\n sha1 f572d396fae9206628714fb2ce00f72e94f2258f my-file\n\nPlease correct the following hash file:\n\n Hash File: {}\n Details: {}''', hash_file, e)\n\n return HashResult.BAD_FORMAT\n\n # no hash information\n if not hash_info:\n return HashResult.EMPTY\n\n # if this is a target file, filter out other hash entries\n if is_file:\n target = os.path.basename(path)\n path = os.path.abspath(os.path.join(path, os.pardir))\n hash_info = [x for x in hash_info if x[2] == target]\n if not hash_info:\n return HashResult.MISSING_ARCHIVE\n\n # filter out excluded assets (if any)\n if exclude:\n hash_info = [x for x in hash_info if x[2] not in exclude]\n if not hash_info:\n return HashResult.EMPTY\n\n hash_catalog = {}\n for type_, hash_, asset in hash_info:\n types = hash_catalog.setdefault(asset, {})\n types.setdefault(type_, []).append(hash_.lower())\n\n for asset, type_hashes in hash_catalog.items():\n hashers = {}\n for hash_entry in type_hashes:\n # extract the specific hash type, if the entry includes a key length\n hash_type, _, _ = hash_entry.partition(':')\n\n hashers[hash_entry] = _get_hasher(hash_type)\n if not hashers[hash_entry]:\n if not quiet:\n err('''\\\nunsupported hash type\n\nThe hash file defines a hash type not supported by the releng-tool. Officially\nsupported hash types are FIPS supported algorithms provided by the Python\ninterpreter (e.g. sha1, sha224, sha256, sha384, sha512). Other algorithms,\nwhile unofficially supported, can be used if provided by the system's OpenSSL\nlibrary.\n\n Hash File: {}\n Provided Type: {}''', hash_file, hash_type)\n\n debug('unsupported hash type: {}', hash_type)\n return HashResult.UNSUPPORTED\n\n target_file = os.path.join(path, asset)\n try:\n with open(target_file, 'rb') as f:\n buf = f.read(HASH_READ_BLOCKSIZE)\n while buf:\n for hasher in hashers.values():\n hasher.update(buf)\n buf = f.read(HASH_READ_BLOCKSIZE)\n except IOError:\n if not quiet:\n if relaxed:\n warn('missing expected file for verification: ' + asset)\n else:\n err('''\\\nmissing expected file for verification\n\nA defined hash entry cannot be verified since the target file does not exist.\nEnsure the hash file correctly names an expected file.\n\n Hash File: {}\n File: {}''', hash_file, asset)\n\n return HashResult.MISSING_LISTED\n\n for hash_entry, hasher in hashers.items():\n _, _, hash_len = hash_entry.partition(':')\n if hash_len:\n digest = hasher.hexdigest(int(hash_len))\n else:\n digest = hasher.hexdigest()\n\n debug('calculated-hash: {} {}:{}', asset, hash_entry, digest)\n hashes = type_hashes[hash_entry]\n if digest not in hashes:\n if not quiet:\n if relaxed:\n warn('hash mismatch detected: ' + asset)\n else:\n provided = ''\n for hash_ in hashes:\n provided += '\\n Provided: {}'.format(hash_)\n\n err('''\\\nhash mismatch detected\n\n Hash File: {}\n File: {}\n Detected: {}{}''', hash_file, asset, digest, provided)\n\n return HashResult.MISMATCH\n\n return HashResult.VERIFIED", "def check_file_hashes(self):\n for filepath in pathlib.Path(self.dir.name).glob(\"**/*.*\"):\n filename = os.path.basename(filepath)\n if filename != \"datapackage.json\" and filename != \"datapackage-digest.json\":\n file = open(filepath, \"rb\").read()\n hash = support_hash_file(self.hash_type, file)\n file = str(filepath).split(\"/\")[-2:]\n file = \"/\".join(file)\n res = None\n for item in self.datapackage[\"resources\"]:\n if item[\"path\"] == file:\n res = item\n if res == None or (res[\"hash\"] != hash):\n print(\n \"\\nfile %s's hash does not match the hash listed in the datapackage\"\n % file\n )\n return False\n return True", "def compare_checksum(info, f):\n pieces = info['pieces']\n\n def getchunks(f, size):\n while True:\n chunk = f.read(size)\n if chunk == '':\n break\n yield hashlib.sha1(chunk).digest()\n\n calc = getchunks(f, info['piece length'])\n ref = (pieces[i:i + 20] for i in xrange(0, len(pieces), 20))\n for expected, actual in itertools.izip(calc, ref):\n if expected != actual:\n return False\n return ensure_empty(calc) and ensure_empty(ref)", "def _verify_hash(filename: Path, access_calculated_hash: str) -> None:\n calculated_hash = FileAPI.calculate_hash(filename)\n if access_calculated_hash != calculated_hash:\n raise ValueError(\n f\"access log contains hash {access_calculated_hash} but calculated hash of {filename} is {calculated_hash}\"\n )", "def check_recompilation_needed_hash_based(\n self,\n clifford_rb_oql: str,\n recompile: bool = True,\n ) -> dict:\n\n hashes_ext = \".hashes\"\n tmp_ext = \".tmp\"\n rb_system_hashes_fn = self.filename + hashes_ext\n tmp_fn = rb_system_hashes_fn + tmp_ext\n\n platf_cfg_hash = get_file_sha256_hash(self._platf_cfg, return_hexdigest=True)\n this_file_hash = get_file_sha256_hash(clifford_rb_oql, return_hexdigest=True)\n file_hashes = {self._platf_cfg: platf_cfg_hash, clifford_rb_oql: this_file_hash}\n\n _recompile = False\n if not isfile(self.filename):\n if recompile is False:\n raise ValueError('No file:\\n{}'.format(self.filename))\n else:\n # Force recompile, there is no program file\n _recompile |= True # FIXME: why \"|=\"?\n\n # Determine if compilation is needed based on the hashed files\n if not isfile(rb_system_hashes_fn):\n # There is no file with the hashes, we must compile to be safe\n _recompile |= True\n else:\n # Hashes exist, we use them to determine if recompilations is needed\n with open(rb_system_hashes_fn) as json_file:\n hashes_dict = json.load(json_file)\n # Remove file to signal a compilation in progress\n remove(rb_system_hashes_fn)\n\n for fn in file_hashes.keys():\n # Recompile becomes true if any of the hashed files has a different\n # hash now\n _recompile |= hashes_dict.get(fn, \"\") != file_hashes[fn]\n\n # Write the updated hashes\n # We use a temporary file such that for parallel compilations, if the\n # process is interrupted before the end there will be no hash and\n # recompilation will be forced\n pathlib.Path(tmp_fn).parent.mkdir(parents=True, exist_ok=True)\n pathlib.Path(tmp_fn).write_text(json.dumps(file_hashes))\n\n res_dict = {\n \"file\": rb_system_hashes_fn,\n \"tmp_file\": tmp_fn\n }\n\n if recompile is False:\n if _recompile is True:\n log.warning(\n \"`{}` or\\n`{}`\\n might have been modified! Are you sure you didn't\"\n \" want to compile?\".format(self._platf_cfg, clifford_rb_oql)\n )\n res_dict[\"recompile\"] = False\n elif recompile is True:\n # Enforce recompilation\n res_dict[\"recompile\"] = True\n elif recompile == \"as needed\":\n res_dict[\"recompile\"] = _recompile\n\n return res_dict", "def test_compute_hashes(self):\n sha, md5 = file_hash.compute_hashes('/hello_world')\n self.assertEqual(hashlib.sha256(self._test_contents.encode('utf-8')).hexdigest(), sha)\n self.assertEqual(hashlib.md5(self._test_contents.encode('utf-8')).hexdigest(), md5)", "def hash_file(file):\n chunksize = 2**16\n\n hashes_algos = [\n \"sha1\",\n \"sha256\",\n \"sha512\",\n \"md5\"\n ]\n\n hashes = {}\n\n with file.open(mode='rb') as f:\n for algo in hashes_algos:\n f.seek(0)\n m = hashlib.new(algo)\n\n chunk = f.read(chunksize)\n while len(chunk) > 0:\n m.update(chunk)\n chunk = f.read(chunksize)\n\n hashes[algo] = m.hexdigest()\n \n return hashes", "def _match_hash(file_path: pathlib.Path) -> bool:\n hash_file_path = _add_suffix(file_path, '.xxh')\n if hash_file_path.is_file() and file_path.is_file():\n with hash_file_path.open('r') as f:\n saved_hash = f.read().strip()\n if saved_hash == _get_xxhash(file_path):\n return True\n return False", "def check_sha256(file_path, target_sha256):\n # check target_sha256\n sha256 = hashlib.sha256()\n with open(file_path, 'rb') as f:\n while True:\n data = f.read()\n if not data:\n break\n sha256.update(data)\n return sha256.hexdigest() == target_sha256", "def keyfile_hash_verification():\n try:\n check1 = Checksum(secret_key_file, \"sha256\").get()\n check2 = open(secret_key_file + \".sha256\", \"rb\").read()\n except:\n return -1\n\n if check1 == check2:\n return 0\n\n return 1", "def verify_checksum(filepath):\n file_obj = file_factory(filepath)\n return file_obj.verify_checksum()", "def do_test_file_sha(self, dir_struc, hashtype):\n\n u_dir = UDir(U_PATH, dir_struc, hashtype)\n self.assertEqual(u_dir.u_path, U_PATH)\n self.assertEqual(u_dir.dir_struc, dir_struc)\n self.assertEqual(u_dir.hashtype, hashtype)\n\n (d_len, d_path) = self.rng.next_data_file(DATA_PATH, 16 * 1024, 1)\n with open(d_path, 'rb') as file:\n data = file.read()\n if hashtype == HashTypes.SHA1:\n digest = XLSHA1()\n elif hashtype == HashTypes.SHA2:\n digest = XLSHA2()\n elif hashtype == HashTypes.SHA3:\n digest = XLSHA3()\n elif hashtype == HashTypes.BLAKE2B_256:\n digest = XLBLAKE2B_256()\n digest.update(data)\n d_key = digest.hexdigest()\n if hashtype == HashTypes.SHA1:\n fsha = file_sha1hex(d_path)\n elif hashtype == HashTypes.SHA2:\n fsha = file_sha2hex(d_path)\n elif hashtype == HashTypes.SHA3:\n fsha = file_sha3hex(d_path)\n elif hashtype == HashTypes.BLAKE2B_256:\n fsha = file_blake2b_256_hex(d_path)\n self.assertEqual(d_key, fsha)", "def metadefender_cloud_hash_scan(file_sha256):\r\n headers = {\r\n \"apikey\" : APIKEY,\r\n }\r\n\r\n # Make a request to metadefender cloud to scan file SHA256\r\n response = requests.get(\"https://api.metadefender.com/v4/hash/\" + file_sha256, headers=headers)\r\n return json.loads(response.text)", "def hash_of_file(file_name):\n\ttry:\n\t\thasher=hashlib.sha256()\n\t\twith open(file_name, 'rb') as fp:\n\t\t\thasher.update(fp.read())\n\t\t\tprint(file_name,hasher.hexdigest())\n\t\tdel hasher\n\texcept Exception as e:\n\t\tprint(e)\n\t\tsys.exit(0)", "def validate_file_md5_hash(file, original_hash):\n\n if get_file_md5_hash(file) == original_hash:\n return True\n\n return False", "def read_hash_file(hash_filename):\n global hash_whitelist\n hash_file_handle = open(hash_filename, newline='', encoding='utf-8')\n reader = csv.reader(hash_file_handle)\n for hash_line in reader:\n hashval = hash_line[0]\n try:\n if int(hashval, 16) and (len(hashval) == 32 or len(hashval) == 40 or len(hashval) == 64):\n hash_whitelist.append(hashval)\n except (TypeError, ValueError):\n pass", "def _validate_random_hashes(self):\n if not os.path.exists(self.src_path) or os.path.isdir(self.src_path) or self.maintype == 'image':\n # Images are converted, we don't have to fear TOCTOU\n return True\n for start_pos, hashed_src in self.random_hashes:\n with open(self.dst_path, 'rb') as f:\n f.seek(start_pos)\n hashed = hashlib.sha256(f.read(self.block_length)).hexdigest()\n if hashed != hashed_src:\n # Something fucked up happened\n return False\n return True", "def test_compute_hashes_empty_file(self):\n sha, md5 = file_hash.compute_hashes('/empty_file')\n self.assertEqual(hashlib.sha256().hexdigest(), sha)\n self.assertEqual(hashlib.md5().hexdigest(), md5)", "def has_filehash(self, filehash):\n cur = self.conn.cursor()\n rows = cur.execute(\n '''\n SELECT * FROM metadata\n WHERE mkey = 'hash' AND mvalue_str = :filehash\n ''',\n {'filehash': filehash})\n try:\n next(rows)\n return True\n except StopIteration:\n return False" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reads the most recent system activities files into a Pandas DataFrame. Combines data from the latest file in all existing directories and removes duplicates.
def get_all_system_activities( base_directory: str, nrows: Union[int, None] = None ) -> pd.DataFrame: files = fr.get_system_activities_files(base_directory) if files is None or len(files) == 0: return _default() df_list = list() for f in files: df_list.append(_read_csv(f, nrows)) df = pd.concat(df_list) df.drop_duplicates(inplace=True) return df
[ "def df_from_files(self):\n print('Creating dataframe...')\n num = len([name for name in os.listdir(self.raw) if not name[0] == '.'])\n files = os.path.join(self.raw, '~.info.json') # This is a weird hack\n files = files.replace('~', '{:05d}') # It allows path joining to work on Windows\n data = [json.load(open(files.format(i))) for i in range(1, num + 1)]\n\n columns = ['formats', 'tags', 'categories', 'thumbnails']\n lists = [[], [], [], []]\n deletes = {k: v for k, v in zip(columns, lists)}\n for dt in data:\n for col, ls in deletes.items():\n ls.append(dt[col])\n del dt[col]\n\n self.df = pd.DataFrame(data)\n self.df['upload_date'] = pd.to_datetime(self.df['upload_date'], format='%Y%m%d')\n self.df.to_csv(os.path.join(self.ran, 'df.csv'))\n\n self.tags = deletes['tags']\n pickle.dump(self.tags, open(os.path.join(self.ran, 'tags.txt'), 'wb'))", "def CombineFiles():\r\n \r\n # current list of files\r\n current_logs = os.listdir('logs')\r\n\r\n # split files into groups\r\n expecetimaxGroup = [file for file in current_logs if 'Star' in file]\r\n mctsGroup = [file for file in current_logs if 'MCTS' in file or 'M_RAVE' in file]\r\n statsGroup = [file for file in current_logs if 'Match_Stats' in file]\r\n\r\n groups = [expecetimaxGroup, mctsGroup, statsGroup]\r\n fileNames = ['ExpectimaxStats', 'MCTSStats', 'PlayerStats']\r\n\r\n i = 0\r\n\r\n for group in groups:\r\n if group == []:\r\n i += 1\r\n continue\r\n first = True\r\n \r\n for file in group:\r\n if first:\r\n df = pd.read_csv('logs/' + file)\r\n first = False\r\n else:\r\n dfNew = pd.read_csv('logs/' + file)\r\n df = df.append(dfNew)\r\n \r\n df.to_csv('logs/' + fileNames[i] + '.csv', index=False)\r\n i += 1", "def read_all_files():\n # Setting up pool with 8 processes.\n pool = Pool(processes=8) \n\n # Get the list of file names.\n path = \"DATA/votes-all/\"\n files = os.listdir(path)\n file_list = [filename for filename in files if filename.split('.')[1]=='csv']\n\n # Using the pool to map the file names to dataframes.\n df_list = pool.map(read_csv, file_list)\n pool.close() \n pool.join()\n \n # Reducing list of dataframes to single dataframe.\n df_final = reduce(lambda left,right: pd.merge(left,right,on=['uin','title','date'],how='outer'), df_list)\n return df_final", "def read_data_batch(self, dirname: str) -> pd.DataFrame:\n LOGGER.info(f\"Reading data from source {dirname}.\")\n cate_key_bias = max(self.cate_mapping.keys()) # indicate the adding bias for newly inserted key number.\n\n data_list = []\n for file in os.listdir(dirname):\n if not (file.endswith(\"xlsx\") or file.endswith(\"xls\")):\n continue\n data = self.read_data(os.path.join(dirname, file))\n\n # Identify the cate_id and cate_name\n cate_name = data[\"cate_id\"].unique()\n if len(cate_name) > 1:\n raise ValueError(f\"The category in file {file} is not unique.\")\n cate_name = cate_name[0]\n cate_id = int(file.split(\"-\")[0]) + cate_key_bias\n self.cate_mapping[cate_id] = cate_name\n\n data[\"cate_id\"] = cate_id # replace category with its id.\n data_list.append(data)\n\n return pd.concat(data_list, axis=0, ignore_index=True)", "def merge_metric_files(metric_files):\n df = pd.read_pickle(metric_files[0])\n for item in metric_files[1:]:\n df = df.append(pd.read_pickle(item))\n return df", "def merge_metadata_files(metadata_files, output_file):\n if len(metadata_files) > 1:\n merged_metadata_df = pd.concat(metadata_files)\n \n # If we have duplicate rows we currently are going to drop the last\n # set of rows until update logic is put in place\n merged_metadata_df = merged_metadata_df.drop_duplicates(subset=['Site/Sub/Coll ID', 'data_type'], \n keep='last')\n merged_metadata_df.to_csv(output_file, index=False)\n else:\n output_file = metadata_files[0]\n\n return output_file", "def merge_csv(path, verbose=False):\n table = []\n\n for file_name in next(os.walk(path))[2]:\n next_table = pd.read_csv(os.path.join(path, file_name), sep=\";\", engine=\"python\", encoding=\"utf-8\")\n next_table[\"by_tag\"] = file_name.split(\"_\")[0]\n if verbose:\n print(f\"Reading table: {file_name}\")\n table.append(next_table)\n\n return pd.concat(table, sort=False)", "def extract_data(data_path: str) -> DataFrame:\n raw_data = {\n COL_QUERY: [],\n COL_RUN: [],\n COL_TIME: [],\n }\n for filename in os.listdir(data_path):\n split_filename = filename.split('-')\n raw_data[COL_QUERY].append(int(split_filename[1]))\n raw_data[COL_RUN].append(int(split_filename[4]))\n with open(f'{data_path}/{filename}') as f:\n lines = f.readlines()\n time_line = lines[-19] # Large cerebrum\n time_regex = r'Elapsed \\(wall clock\\) time \\(h:mm:ss or m:ss\\): (.*)'\n time = re.findall(time_regex, time_line)\n time = time.pop()\n raw_data[COL_TIME].append(time)\n d = pd.DataFrame(data=raw_data)\n d = d.sort_values(by=[COL_QUERY, COL_RUN],\n ascending=[True, True])\n return d", "def parse_most_recent_eia860M_data(eia860_annual_input_dir, eia860_monthly_input_dir):\n\n #only run this function for the last year of the data, which is 2018 as of this writing\n year = int(2018)\n\n if year == end_year:\n\n print \"=============================\"\n print \"Processing data for year {}.\".format(year)\n\n rows_to_skip = 1\n\n for f in os.listdir(eia860_annual_input_dir):\n path = os.path.join(eia860_annual_input_dir, f)\n f = f.lower()\n\n # look for files with \"Plant\" and \"Generator\" in their name.\n\n if 'plant' in f and '~' not in f:\n dataframe = pd.read_excel(path, sheet_name=0, skiprows=rows_to_skip)\n plants = uniformize_names(dataframe)\n if 'generator' in f and '~' not in f:\n dataframe = pd.read_excel(path, sheet_name=0, skiprows=rows_to_skip)\n existing_generators = uniformize_names(dataframe)\n try:\n existing_generators = existing_generators.astype({'Utility Id': 'int64'})\n except ValueError:\n # The data frame may have an extra information row. If so, drop it.\n existing_generators.drop(existing_generators.tail(1).index,inplace=True)\n existing_generators = existing_generators.astype({'Utility Id': 'int64'})\n existing_generators['Operational Status'] = 'Operable'\n\n dataframe = pd.read_excel(path, sheet_name=1, skiprows=rows_to_skip)\n proposed_generators = uniformize_names(dataframe)\n proposed_generators['Operational Status'] = 'Proposed'\n #join the existing generator and existing plant level data, and append list of proposed generators to dataframe\n generators = pd.merge(existing_generators, plants,\n on=['Utility Id','Plant Code', 'Plant Name','State'],\n suffixes=('_units', ''))\n generators = generators.append(proposed_generators)\n print \"Read in data for {} existing and {} proposed generation units in \"\\\n \"the US.\".format(len(existing_generators), len(proposed_generators))\n\n # Filter projects according to status (operable or proposed and far along in regulatory and/or construction process)\n generators = generators.loc[generators['Status'].isin(accepted_status_codes)]\n print \"Filtered to {} existing and {} proposed generation units by removing inactive \"\\\n \"and planned projects not yet started.\".format(\n len(generators[generators['Operational Status']=='Operable']),\n len(generators[generators['Operational Status']=='Proposed']))\n\n # Manually set Prime Mover of combined cycle plants before aggregation because CA, CT, and CS all\n # describe different components of a combined cycle (CC) plant\n generators.loc[generators['Prime Mover'].isin(['CA','CT','CS']),'Prime Mover'] = 'CC'\n\n #reading in list of retired plants from monthly EIA 860 form which is 2 years ahead of annual EIA 860 form\n print \"=============================\"\n print \"Processing cumulative retired plant data as of {} {}.\".format(end_month, end_year+2)\n\n for f in os.listdir(eia860_monthly_input_dir):\n\n path = os.path.join(eia860_monthly_input_dir, f)\n f = f.lower()\n rows_to_skip = 1\n\n # Look for files with End month and \"Generator\" in their name. Note that monthly data is 2 years ahead of annual data, hence you need to add 2 below\n if 'generator' in f and str(end_month) in f and str(year+2) in f and f.endswith('xlsx'):\n\n dataframe = pd.read_excel(path, sheet_name=2, skiprows=rows_to_skip)\n\n retired_generators = uniformize_names(dataframe)\n\n # Manually set Prime Mover of combined cycle plants before aggregation because CA, CT, and CS all\n # describe different components of a combined cycle (CC) plant\n retired_generators.loc[retired_generators['Prime Mover'].isin(['CA','CT','CS']),'Prime Mover'] = 'CC'\n\n #join the existing and proposed generator list from most recent annual 860 list with the most recent monthly 860 retired\n # generator list by generator\n\n retired_generators_in_project_list = pd.merge(generators[['Cogen','County',\n 'Energy Source','Generator Id','Nameplate Capacity (MW)','Nerc Region',\n 'Operating Year','Operational Status','Plant Code','Plant Name',\n 'Prime Mover','Regulatory Status','State','Technology','Unit Code','Utility Id','Utility Name']],\n retired_generators[['Entity Id','Plant Code','Generator Id','State','Prime Mover','Nameplate Capacity (MW)',\n 'Retirement Month','Retirement Year','Operating Year']],\n left_on=['Utility Id','Plant Code','Generator Id','State','Prime Mover','Operating Year','Nameplate Capacity (MW)'],\n right_on = ['Entity Id','Plant Code','Generator Id','State','Prime Mover','Operating Year','Nameplate Capacity (MW)'],\n how = 'inner')\n\n print \"There are {} retired generation units as of {} {} that are still in the most recent {} annual generation project list \"\\\n \"in the US.\".format(len(retired_generators_in_project_list), end_month, end_year+2, end_year)\n\n retired_generators_in_project_list = retired_generators_in_project_list.rename(columns={'Plant Code':'EIA Plant Code'})\n\n #filtering out just generators in WECC states\n wecc_filter = retired_generators_in_project_list['State'].isin(wecc_states)\n wecc_retired_generators_in_project_list = retired_generators_in_project_list[wecc_filter]\n\n print \"There are {} retired generation units as of {} {} that are still in the most recent {} annual generation project list \"\\\n \"in the WECC states.\".format(len(wecc_retired_generators_in_project_list), end_month, end_year+2, end_year)\n\n #Only keep subset of columns\n wecc_retired_generators_in_project_list_condensed = wecc_retired_generators_in_project_list[['EIA Plant Code', 'Plant Name', 'Nameplate Capacity (MW)', 'Operating Year',\n 'Prime Mover', 'Energy Source', 'State','County','Retirement Year','Generator Id', 'Unit Code', 'Regulatory Status']]\n\n #output to CSV list of retired (or planned retired) WECC generator units still in generator project list\n fname = 'retired_WECC_generation_units_still_in_generator_projects_{}.tab'.format(end_year)\n with open(os.path.join(outputs_directory, fname),'w') as f:\n wecc_retired_generators_in_project_list_condensed.to_csv(f, sep='\\t', encoding='utf-8', index=False)\n print \"Saved data to {} file.\\n\".format(fname)\n\n wecc_retired_generators_in_project_list = wecc_retired_generators_in_project_list.rename(columns={'EIA Plant Code':'Plant Code', 'Operational Status':'Status'})\n\n gen_relevant_data2 = ['Plant Code', 'Plant Name', 'Nameplate Capacity (MW)', 'Operating Year','Prime Mover', 'Energy Source', 'State','County',\n 'Retirement Year','Generator Id', 'Unit Code', 'Regulatory Status']\n\n # Aggregate retired plants according to user criteria (same as operating plants)\n agg_list = ['Plant Code', 'Prime Mover', 'Energy Source','Operating Year']\n # Assign unique values to empty cells in columns that will be aggregated upon\n for col in agg_list:\n if wecc_retired_generators_in_project_list[col].dtype == np.float64:\n wecc_retired_generators_in_project_list[col].fillna(\n {i:10000000+i for i in wecc_retired_generators_in_project_list.index}, inplace=True)\n else:\n wecc_retired_generators_in_project_list[col].fillna(\n {i:'None'+str(i) for i in wecc_retired_generators_in_project_list.index}, inplace=True)\n wecc_retired_gb = wecc_retired_generators_in_project_list.groupby(agg_list)\n\n # Nameplate capacity will be summed and all others will get the 'max' value\n # Columns are reordered after aggregation for easier inspection\n wecc_retired_agg = wecc_retired_gb.agg({datum:('max' if datum not in gen_data_to_be_summed else sum)\n for datum in gen_relevant_data2}).loc[:,gen_relevant_data2]\n wecc_retired_agg.reset_index(drop=True, inplace=True)\n print \"Aggregated to {} retired generation units by aggregating \"\\\n \"through {}.\".format(len(wecc_retired_agg[wecc_retired_agg['Retirement Year']>=2017]), agg_list)\n\n # Drop columns that are no longer needed\n wecc_retired_agg = wecc_retired_agg.drop(['Unit Code','Generator Id','Energy Source'], axis=1)\n\n wecc_retired_agg = wecc_retired_agg.rename(columns={'Plant Code':'EIA Plant Code'})\n\n #export aggregated list of retired plants still in dataset into csv for analyis\n fname = 'retired_WECC_aggregated_generation_projects_{}.tab'.format(year)\n with open(os.path.join(outputs_directory, fname),'w') as f:\n wecc_retired_agg.to_csv(f, sep='\\t', encoding='utf-8', index=False)\n print \"Saved data to {} file.\\n\".format(fname)", "def divide_csv_daily(file_path):\n daily_files = []\n directory = os.path.dirname(file_path)\n\n try:\n data_frame = pd.read_csv(file_path)\n except Exception as error:\n LOG.error(f\"File {file_path} could not be parsed. Reason: {str(error)}\")\n raise error\n\n unique_times = data_frame.usage_start_time.unique()\n days = list({cur_dt[:10] for cur_dt in unique_times})\n daily_data_frames = [\n {\"data_frame\": data_frame[data_frame.usage_start_time.str.contains(cur_day)], \"date\": cur_day}\n for cur_day in days\n ]\n\n for daily_data in daily_data_frames:\n day = daily_data.get(\"date\")\n df = daily_data.get(\"data_frame\")\n day_file = f\"{day}.csv\"\n day_filepath = f\"{directory}/{day_file}\"\n df.to_csv(day_filepath, index=False, header=True)\n daily_files.append({\"filename\": day_file, \"filepath\": day_filepath})\n return daily_files", "def log_folder_to_dataframe(folder_path: path_t) -> pd.DataFrame:\n file_list = sorted(folder_path.glob(\"*.csv\"))\n return pd.concat([_load_log_file_csv(file) for file in file_list])", "def process_files(folder):\n #\n df = pd.DataFrame()\n for root, dirs, files in os.walk(folder):\n for file in files:\n if file.endswith(\".json\"):\n df_new = pd.read_json(os.path.join(root, file), lines=True)\n df = df.append(df_new, ignore_index=True)\n return df", "def swipe_ts():\n\t\"\"\" Copy files to dataSets_Results_ts from psychopy \"\"\"\n\n\ttotalDf = []\t\t\t\t\t\t\t\t\t\t\t\t\t\t ## init empty list\n\n\tfor file in os.listdir(thisDirPath + '\\\\R\\\\dataSets_Results_ts'): ## loop throught dataSets_Results_ts dir\n\t\tresultsFile = pd.read_csv(thisDirPath + targetFile + str(file)) ## read files\n\t\ttotalDf.append(resultsFile)\t\t\t\t\t\t\t\t\t\t ## append the dfs to the empty list\n\n\ttotalDf_2 = pd.concat(totalDf, sort=False)\t\t\t\t\t\t\t ## concatanate the dfs in one df\n\tpd.DataFrame(totalDf_2).to_csv(\"dataSetsFromPy\\\\ts_tot.csv\")\t\t ## output csv to dataSetsFromPy - maybe adjust that", "def read_dir(base_dir):\n all_files = os.listdir(base_dir)\n outs = [pd.read_csv(os.path.join(base_dir, f), index_col=0) for f in all_files]\n concat = pd.concat(outs, axis=1)\n cols = list(map(lambda x: \"model_\" + str(x + 1), range(len(concat.columns))))\n concat.columns = cols\n return concat", "def _parse_lma_files(files, dates):\n\n try:\n ref = datetime.datetime.strptime(dates[0], '%m/%d/%y')\n except ValueError:\n try:\n ref = datetime.datetime.strptime(dates[0], '%Y-%m-%d')\n except ValueError:\n ref = datetime.datetime.strptime(dates[0], '%m/%d/%Y')\n\n pds = []\n\n # Read in the files\n for i, f in enumerate(files):\n pds.append(pd.read_csv(f))\n\n # Add a Series to each DataFrame containing the time of each source\n # in datetime form\n for i, p in enumerate(pds):\n if len(dates) > 1:\n try:\n date = datetime.datetime.strptime(dates[i], '%m/%d/%y')\n except ValueError:\n try:\n date = datetime.datetime.strptime(dates[i], '%Y-%m-%d')\n except ValueError:\n date = datetime.datetime.strptime(dates[i], '%m/%d/%Y')\n\n series = [date + datetime.timedelta(seconds=entry) for entry\n in p['time(UT-sec-of-day)']]\n\n p.insert(0, 'DateTime', series)\n p['DateTime'] = pd.to_datetime(p['DateTime'])\n\n # Replace the values of the seconds of day column\n # to allow for storms to span multiple days\n series = [(entry - ref).total_seconds() for entry in\n p['DateTime']]\n p.drop('time(UT-sec-of-day)', axis=1, inplace=True)\n p.insert(1, 'time(UT-sec-of-day)', series)\n\n else:\n try:\n date = datetime.datetime.strptime(dates[0], '%m/%d/%y')\n except ValueError:\n try:\n date = datetime.datetime.strptime(dates[0], '%Y-%m-%d')\n except ValueError:\n date = datetime.datetime.strptime(dates[0], '%m/%d/%Y')\n\n series = [date + datetime.timedelta(seconds=entry) for entry\n in p['time(UT-sec-of-day)']]\n\n p.insert(0, 'DateTime', series)\n p['DateTime'] = pd.to_datetime(p['DateTime'])\n\n # Replace the values of the seconds of day column\n # to allow for storms to span multiple days\n series = [(entry - ref).total_seconds() for entry in\n p['DateTime']]\n p.drop('time(UT-sec-of-day)', axis=1, inplace=True)\n p.insert(1, 'time(UT-sec-of-day)', series)\n\n # Remove all flash-numbers that are == -1\n for i in range(len(pds)):\n row_index = pds[i][pds[i]['flash-number'] != -1].index\n pds[i] = pds[i].loc[row_index]\n\n # print(-1 in pds[i]['flash-number'])\n\n # Correct the flash numbers so that there are no duplicates\n for i in range(len(pds) - 1):\n # Get the largest flash number of the current file\n max_flash_number = pds[i]['flash-number'].max() + 1\n\n # Apply the offset to the next file\n pds[i + 1]['flash-number'] += max_flash_number\n\n # Make the final Pandas DataFrame\n if len(pds) > 1:\n storm = pd.concat(pds, ignore_index=True)\n else:\n storm = pds[0]\n\n # Sort the data frame by time\n storm.set_index('DateTime', inplace=True)\n storm.sort_index(inplace=True)\n\n # Reset the index\n storm.reset_index(inplace=True)\n\n return storm", "def read_write(self):\n X = self.data\n #For each directory in data parent directory open it, read csv files and\n #add to the dataset\n for key in self._target.keys():\n dir_list = [n for n in os.listdir() if '_{}'.format(key) in n]\n dir_list = [n for n in dir_list if self.subject in n]\n for z in dir_list:\n print(z)\n t = self._create_array(z)\n X = np.vstack((X,t))\n X = X[1:]\n self.data = X", "def merge_csv(path):\n merged_paths = []\n all_size_file = gather_csv(path)\n mean_path = '/'.join(path.split('/')[:-2]) + '/mean/'\n os.makedirs(mean_path, exist_ok=True)\n for count in range(len(all_size_file)):\n df_all = pd.read_csv(path + all_size_file[count][0])\n for i in range(len(all_size_file[count])):\n cur_file = path + all_size_file[count][i]\n df_cur = pd.read_csv(cur_file)\n df_all = pd.concat([df_all, df_cur], axis=0)\n cur_csv_name = mean_path + 'text_all_' + str((count + 1) * 5000) + '.csv'\n df_all.to_csv(cur_csv_name)\n print(cur_csv_name)\n merged_paths.append(cur_csv_name)\n return merged_paths", "def read_clickstream_data() -> pd.DataFrame:\n df1 = read_data_with_columns(r'data/interim/clickstream/clickstream_data.csv', r'data/raw/clickstream/clickstream_columns.txt')\n df2 = read_data_with_columns(r'data/raw/clickstream/clickstream_data_part_2.csv', r'data/raw/clickstream/clickstream_columns.txt')\n combined_clickstream_df = pd.concat([df1, df2])\n return combined_clickstream_df", "def bid_update_data(file_path: str) -> pd.DataFrame:\n with open(file_path, 'r') as f:\n data = json.load(f)\n\n max_dispatch = [0] * len(data['data']['assets'][0]['maximum_dispatch_schedule'])\n for t, _ in enumerate(data['data']['assets'][0]['maximum_dispatch_schedule']):\n for ast_num, _ in enumerate(data['data']['assets']):\n max_dispatch[t] += data['data']['assets'][ast_num]['maximum_dispatch_schedule'][t][\n 'maximum_dispatch']\n\n load_reduction = []\n reference_load = []\n start_time = []\n\n for _, dct in enumerate(data['data']['meter_point_schedule']):\n load_reduction.append(dct['load_reduction'])\n reference_load.append(dct['reference_load'])\n start_time.append(datetime.datetime.fromisoformat(dct['start_time']))\n\n df = pd.DataFrame(data=start_time, columns=['Start Time'])\n df['Max Dispatch'] = max_dispatch\n df['Load Reduction'] = load_reduction\n df['Reference Load'] = reference_load\n df['Date'] = [i.date() for i in start_time]\n df['Time'] = [i.time() for i in start_time]\n\n asset_id = []\n asset_max_dptch = []\n for i, dct in enumerate(data['data']['assets']):\n asset_id.append(dct['id'])\n asset_max_dptch.append([dct['maximum_dispatch_schedule'][md]['maximum_dispatch'] for md in\n range(len(dct['maximum_dispatch_schedule']))])\n\n for i in range(len(asset_id)):\n df[asset_id[i] + 'bu'] = asset_max_dptch[i]\n\n return df" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reads the most recent section associations file for the given section into a Pandas DataFrame.
def get_section_associations( base_directory: str, section_id: int, nrows: Union[int, None] = None ) -> pd.DataFrame: file = fr.get_section_associations_file(base_directory, section_id) if file is not None: return _read_csv(file, nrows) return _default()
[ "def get_all_section_associations(\r\n base_directory: str, sections: pd.DataFrame, nrows: Union[int, None] = None\r\n) -> pd.DataFrame:\r\n return _get_data_for_section(\r\n base_directory, sections, get_section_associations, nrows\r\n )", "def get_section_activities(\r\n base_directory: str, section_id: int, nrows: Union[int, None] = None\r\n) -> pd.DataFrame:\r\n file = fr.get_section_activities_file(base_directory, section_id)\r\n\r\n if file is not None:\r\n return _read_csv(file, nrows)\r\n\r\n return _default()", "def _read_dwarf_section(self, section, relocate_dwarf_sections):\r\n self.stream.seek(section['sh_offset'])\r\n # The section data is read into a new stream, for processing\r\n section_stream = BytesIO()\r\n section_stream.write(self.stream.read(section['sh_size']))\r\n\r\n if relocate_dwarf_sections:\r\n reloc_handler = RelocationHandler(self)\r\n reloc_section = reloc_handler.find_relocations_for_section(section)\r\n if reloc_section is not None:\r\n reloc_handler.apply_section_relocations(\r\n section_stream, reloc_section)\r\n\r\n return DebugSectionDescriptor(\r\n stream=section_stream,\r\n name=section.name,\r\n global_offset=section['sh_offset'],\r\n size=section['sh_size'])", "def get_assignments(\r\n base_directory: str, section_id: int, nrows: Union[int, None] = None\r\n) -> pd.DataFrame:\r\n file = fr.get_assignments_file(base_directory, section_id)\r\n\r\n if file is not None:\r\n return _read_csv(file, nrows)\r\n\r\n return _default()", "def get_section(section):", "def get_all_section_activities(\r\n base_directory: str, sections: pd.DataFrame, nrows: Union[int, None] = None\r\n) -> pd.DataFrame:\r\n return _get_data_for_section(\r\n base_directory, sections, get_section_activities, nrows\r\n )", "def get_section_df(self, track_id):\n analysis_res = self.si.analysis(track_id)\n # bars, beats, sections, segments, tatums\n sections_df = pd.DataFrame(analysis_res[\"sections\"])\n sections_df = sections_df[[\"start\", \"duration\", \"loudness\", \"tempo\", \"key\", \"mode\"]]\n sections_df[\"duration\"] = sections_df[\"duration\"] / sum(sections_df[\"duration\"])\n sections_df[\"loudness\"] = sections_df[\"loudness\"].apply(lambda x: abs(x))\n sections_df[\"loudness\"] = sections_df[\"loudness\"] / sum(sections_df[\"loudness\"])\n return sections_df", "def read_in_sequencing_summary(summary_path):\n data = pd.read_csv(summary_path, sep=\"\\t\")\n return data", "def merge(df: pd.DataFrame, comment) -> pd.DataFrame:\n with io.StringIO(comment.body) as body:\n for line in body:\n if line.startswith('<!--ghr-report:full-->'):\n body.readline() # Blank line before table.\n cols, rows = memdf.util.markdown.read_hierified(body)\n break\n logging.debug('REC: read %d rows', len(rows))\n attrs = df.attrs\n df = pd.concat([df, pd.DataFrame(data=rows, columns=cols).astype(df.dtypes)],\n ignore_index=True)\n df.attrs = attrs\n return df.sort_values(\n by=['platform', 'target', 'config', 'section']).drop_duplicates()", "def get_attendance_events(\r\n base_directory: str, section_id: int, nrows: Union[int, None] = None\r\n) -> pd.DataFrame:\r\n file = fr.get_attendance_events_file(base_directory, section_id)\r\n\r\n if file is not None:\r\n return _read_csv(file, nrows)\r\n\r\n return _default()", "def get_section(cfg, section):\n section_lines = []\n is_append_section = False\n\n for line in cfg.splitlines():\n line = line.strip()\n\n if line.startswith('section') and not is_append_section:\n cfg_section = line.split('=', 1)[1].strip()\n if cfg_section == section:\n is_append_section = True\n elif line.startswith('section') and is_append_section:\n break # skip any subsequent sections\n\n if is_append_section:\n section_lines.append(line)\n\n return section_lines", "def read_obstab(gfzdir: str, obstabf: str, gnss: str, hdr: str, logger: logging.Logger) -> Union[pd.DataFrame, list, list]:\n cFuncName = colored(os.path.basename(__file__), 'yellow') + ' - ' + colored(sys._getframe().f_code.co_name, 'green')\n\n # retain lines that start with \"OBS GNSS\"\n # create temporay file with only data for selected GNSS\n tmp_obstabf = os.path.join(tempfile.gettempdir(), obstabf)\n\n # read in the lines according to the selected GNSS\n with open(os.path.join(gfzdir, obstabf), 'r') as finp:\n hdr_line = amutils.lines_that_start_with('#HD {gnss:s}'.format(gnss=gnss), finp)\n finp.seek(0, 0)\n gnss_lines = amutils.lines_that_start_with('OBS {gnss:s}'.format(gnss=gnss), finp)\n # xrite these lines to a temporary file for loading into a dataframe\n with open(tmp_obstabf, 'w') as fout:\n fout.writelines(hdr_line)\n fout.writelines(gnss_lines)\n\n # dfobs = pd.DataFrame(columns=hdr)\n dfobs = pd.read_csv(tmp_obstabf, sep='\\\\s+', usecols=hdr, parse_dates=[['DATE', 'TIME']], na_values=['9999999999.999'])\n amutils.logHeadTailDataFrame(df=dfobs, dfName='dfobs[{gnss:s}]'.format(gnss=gnss), logger=logger, callerName=cFuncName)\n\n # get list of observed SVs\n lst_svs = sorted(dfobs['PRN'].unique())\n logger.info('{func:s} lst_svs = {svs!s}'.format(svs=lst_svs, func=cFuncName))\n\n return dfobs, lst_svs, [dfobs['DATE_TIME'].iloc[0], dfobs['DATE_TIME'].iloc[-1]]", "def _read(self, profile_filename):\n # header=0 because docs say to if using skip rows and columns\n df = pd.read_csv(profile_filename, header=0,\n skiprows=self.hdr.header_pos,\n names=self.hdr.columns,\n encoding='latin')\n\n # Special SMP specific tasks\n depth_fmt = 'snow_height'\n is_smp = False\n if 'force' in df.columns:\n # Convert depth from mm to cm\n df['depth'] = df['depth'].div(10)\n is_smp = True\n # Make the data negative from snow surface\n depth_fmt = 'surface_datum'\n\n # SMP serial number and original filename for provenance to the comment\n f = basename(profile_filename)\n serial_no = f.split('SMP_')[-1][1:3]\n\n df['comments'] = f\"fname = {f}, \" \\\n f\"serial no. = {serial_no}\"\n\n # Standardize all depth data\n new_depth = standardize_depth(df['depth'],\n desired_format=depth_fmt,\n is_smp=is_smp)\n\n if 'bottom_depth' in df.columns:\n delta = df['depth'] - new_depth\n df['bottom_depth'] = df['bottom_depth'] - delta\n\n df['depth'] = new_depth\n\n delta = abs(df['depth'].max() - df['depth'].min())\n self.log.info('File contains {} profiles each with {} layers across '\n '{:0.2f} cm'.format(len(self.hdr.data_names), len(df), delta))\n return df", "def merge_modified_section_data(self):\n\n for section in self.sections:\n section_data_start = self.adjust_FileAlignment( section.PointerToRawData,\n self.OPTIONAL_HEADER.FileAlignment )\n section_data_end = section_data_start+section.SizeOfRawData\n if section_data_start < len(self.__data__) and section_data_end < len(self.__data__):\n self.__data__ = self.__data__[:section_data_start] + section.get_data() + self.__data__[section_data_end:]", "def read_manifest(self, manifest):\n # Read manifest file\n with open(manifest) as file:\n reader = csv.DictReader(file)\n for line in reader:\n assert len(line) == 4\n\n # Find seating information\n section_id = line['section_id'].strip().lstrip('0').lower()\n section_name = line['section_name'].strip().lower()\n row_id = line['row_id'].strip().lower()\n row_name = line['row_name'].strip().lstrip('0').lower()\n\n # Obtain section number from section name\n section_name_int = ''.join(\n digit for digit in section_name if digit.isdigit())\n\n # Created abbreviated version of section_name\n builder = ''\n splitted = section_name.split(' ')\n for word in splitted:\n if word.isalpha():\n builder += word[0]\n elif word.isdigit():\n if len(builder) == 0:\n builder = word\n else:\n builder += ' ' + word\n\n # Added each row to self.data dictionary\n if section_name_int in self.data.keys():\n match = self.data[section_name_int]\n\n if builder in match.keys():\n section_match = match[builder]\n assert section_match[0] == section_id\n\n self.data[section_name_int][builder][1].update(\n {row_name: row_id})\n\n else:\n self.data[section_name_int][builder] = [\n section_id, {row_name: row_id}]\n\n else:\n self.data[section_name_int] = {\n builder: [section_id, {row_name: row_id}]}", "def load_data_impl() -> pd.DataFrame:\n # The source for this file is at https://ssd.jpl.nasa.gov/?sb_elem\n fname: str = '../jpl/orb_elements_asteroid.txt'\n\n # The field names in the JPL file and their column positions\n names: List[str] = ['Num', 'Name', 'Epoch', 'a', 'e', 'i', 'w', 'Node', 'M', 'H', 'G', 'Ref']\n colspec_tbl: Dict[str, Tuple[int, int]] = {\n 'Num': (0,6), \n 'Name': (7, 25), \n 'Epoch': (25, 30), \n 'a': (31, 41), \n 'e': (42, 52), \n 'i': (54, 62), \n 'w': (63, 72),\n 'Node': (73, 82),\n 'M': (83, 94),\n 'H': (95, 100),\n 'G': (101, 105),\n 'Ref': (106, 113),\n }\n \n # Other arguments for Pandas file import\n colspecs: List[Tuple[int, int]] = [colspec_tbl[nm] for nm in names]\n header: int = 0\n skiprows: List[int] = [1]\n dtype: Dict[str, int] = {\n 'Num': int,\n 'Name': str,\n 'Epoch': float,\n 'a': float,\n 'e': float,\n 'i': float,\n 'w': float,\n 'Node': float,\n 'M': float,\n 'H': float,\n 'G': float,\n 'Ref': str,\n }\n\n # Read the DataFrame\n df: pd.DataFrame = pd.read_fwf(fname, colspecs=colspecs, header=header, names=names, skiprows=skiprows, dtype=dtype)\n # Set the asteroid number field to be the index\n df.set_index(keys=['Num'], drop=False, inplace=True)\n return df", "def load_metadata(metadatafile):\n with open(metadatafile, \"r\", encoding=\"utf8\") as infile:\n metadata = pd.read_csv(infile, sep=\"\\t\")\n return metadata", "def import_VCF42_cohort_pandas(vcf_file, sep='\\t'):\n header_lines = 0\n\n if vcf_file.endswith(\".gz\"):\n with gzip.open(vcf_file, 'rb') as f:\n first_line = f.readline().decode().strip()\n next_line = f.readline().decode().strip()\n while next_line.startswith(\"##\"):\n header_lines = header_lines + 1\n next_line = f.readline().decode().strip()\n else:\n with open(vcf_file, 'r') as f:\n first_line = f.readline().strip()\n next_line = f.readline().strip()\n while next_line.startswith(\"##\"):\n header_lines = header_lines + 1\n next_line = f.readline().strip()\n \n if first_line.endswith('VCFv4.2'):\n dataframe = pd.read_csv(vcf_file, sep=sep, skiprows=[header_lines], header=header_lines)\n else:\n print(\"This vcf file is not v4.2\")\n sys.exit(1)\n\n return dataframe", "def read_section(ws, row, fields, asset_class, currency, port_values):\n\tlogger.debug('read_section() at row {0}, asset class {1}'.format(row, asset_class))\n\t\n\t# currently only handle these two types of asset class\n\tif not asset_class in ['equity', 'bond']:\n\t\tlogger.error('read_section(): invalid asset class: {0}'.format(asset_class))\n\t\traise BadAssetClass()\n\n\trows_read = 1\n\tholding = retrieve_or_create(port_values, asset_class)\n\n\t# while (row+rows_read < ws.nrows):\n\t# \tcell_value = ws.cell_value(row+rows_read, 0)\n\t# \tif start_of_sub_section(cell_value):\n\t# \t\taccounting_treatment = get_accounting_treatment(cell_value)\n\t# \t\tfields = adjust_fields(port_values, fields, asset_class, accounting_treatment)\n\t# \t\tn = read_sub_section(ws, row+rows_read, accounting_treatment, \n\t# \t\t\t\t\t\t\t\tfields, asset_class, currency, holding)\n\t# \t\trows_read = rows_read + n\n\n\t# \t# elif end_of_section(cell_value):\n\t# \tif end_of_section(ws.cell_value(row+rows_read, 0)):\n\t# \t\tbreak\n\n\t# \trows_read = rows_read + 1\t# move to next row\n\n\twhile (row+rows_read < ws.nrows):\n\t\tif start_of_sub_section(ws.cell_value(row+rows_read, 0)):\n\t\t\tbreak\n\t\trows_read = rows_read + 1\t# move to next row\n\n\t# when the sub section reading ends, we are either at the start of the next\n\t# sub section or end of the section.\n\twhile start_of_sub_section(ws.cell_value(row+rows_read, 0)):\n\t\taccounting_treatment = get_accounting_treatment(ws.cell_value(row+rows_read, 0))\n\t\tfields = adjust_fields(port_values, fields, asset_class, accounting_treatment)\n\t\tn, fx_rate = read_sub_section(ws, row+rows_read, accounting_treatment, \n\t\t\t\t\t\t\t\t\t\tfields, asset_class, currency, holding)\n\t\trows_read = rows_read + n\n\t\tif fx_rate != 0:\n\t\t\t# print('currency: {0}, fx: {1}'.format(currency, fx_rate))\n\t\t\tget_holding_fx(port_values)[currency] = fx_rate\n\n\treturn rows_read" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reads the most recent section associations files for all given sections into a Pandas DataFrame.
def get_all_section_associations( base_directory: str, sections: pd.DataFrame, nrows: Union[int, None] = None ) -> pd.DataFrame: return _get_data_for_section( base_directory, sections, get_section_associations, nrows )
[ "def get_section_associations(\r\n base_directory: str, section_id: int, nrows: Union[int, None] = None\r\n) -> pd.DataFrame:\r\n file = fr.get_section_associations_file(base_directory, section_id)\r\n\r\n if file is not None:\r\n return _read_csv(file, nrows)\r\n\r\n return _default()", "def get_all_section_activities(\r\n base_directory: str, sections: pd.DataFrame, nrows: Union[int, None] = None\r\n) -> pd.DataFrame:\r\n return _get_data_for_section(\r\n base_directory, sections, get_section_activities, nrows\r\n )", "def get_section_activities(\r\n base_directory: str, section_id: int, nrows: Union[int, None] = None\r\n) -> pd.DataFrame:\r\n file = fr.get_section_activities_file(base_directory, section_id)\r\n\r\n if file is not None:\r\n return _read_csv(file, nrows)\r\n\r\n return _default()", "def get_all_assignments(\r\n base_directory: str, sections: pd.DataFrame, nrows: Union[int, None] = None\r\n) -> pd.DataFrame:\r\n return _get_data_for_section(base_directory, sections, get_assignments, nrows)", "def get_all_attendance_events(\r\n base_directory: str, sections: pd.DataFrame, nrows: Union[int, None] = None\r\n) -> pd.DataFrame:\r\n return _get_data_for_section(base_directory, sections, get_attendance_events, nrows)", "def get_assignments(\r\n base_directory: str, section_id: int, nrows: Union[int, None] = None\r\n) -> pd.DataFrame:\r\n file = fr.get_assignments_file(base_directory, section_id)\r\n\r\n if file is not None:\r\n return _read_csv(file, nrows)\r\n\r\n return _default()", "def get_attendance_events(\r\n base_directory: str, section_id: int, nrows: Union[int, None] = None\r\n) -> pd.DataFrame:\r\n file = fr.get_attendance_events_file(base_directory, section_id)\r\n\r\n if file is not None:\r\n return _read_csv(file, nrows)\r\n\r\n return _default()", "def load_merged_summary(date_lo, date_hi):\n\n # Build list of file dates to read\n date_lo = pd.to_datetime(date_lo)\n date_hi = pd.to_datetime(date_hi)\n date = date_lo\n dfsums = []\n fdates = []\n while date <= date_hi:\n date_str = date.strftime('%Y-%m-%d')\n try:\n _find_casus_fpath(date_str)\n except FileNotFoundError:\n print(f'Using casus data before {date_str}.')\n break\n fdates.append(date_str)\n date += pd.Timedelta(1, 'd')\n\n msg = f'Loading casus data for {len(fdates)} days (using {{ncpu}} processes)'\n with PoolNCPU(msg) as pool:\n dfsums = pool.map(_load_one_df, fdates)\n print()\n dfsmerged = pd.concat(dfsums)\n return dfsmerged", "def df_from_files(self):\n print('Creating dataframe...')\n num = len([name for name in os.listdir(self.raw) if not name[0] == '.'])\n files = os.path.join(self.raw, '~.info.json') # This is a weird hack\n files = files.replace('~', '{:05d}') # It allows path joining to work on Windows\n data = [json.load(open(files.format(i))) for i in range(1, num + 1)]\n\n columns = ['formats', 'tags', 'categories', 'thumbnails']\n lists = [[], [], [], []]\n deletes = {k: v for k, v in zip(columns, lists)}\n for dt in data:\n for col, ls in deletes.items():\n ls.append(dt[col])\n del dt[col]\n\n self.df = pd.DataFrame(data)\n self.df['upload_date'] = pd.to_datetime(self.df['upload_date'], format='%Y%m%d')\n self.df.to_csv(os.path.join(self.ran, 'df.csv'))\n\n self.tags = deletes['tags']\n pickle.dump(self.tags, open(os.path.join(self.ran, 'tags.txt'), 'wb'))", "def merge(df: pd.DataFrame, comment) -> pd.DataFrame:\n with io.StringIO(comment.body) as body:\n for line in body:\n if line.startswith('<!--ghr-report:full-->'):\n body.readline() # Blank line before table.\n cols, rows = memdf.util.markdown.read_hierified(body)\n break\n logging.debug('REC: read %d rows', len(rows))\n attrs = df.attrs\n df = pd.concat([df, pd.DataFrame(data=rows, columns=cols).astype(df.dtypes)],\n ignore_index=True)\n df.attrs = attrs\n return df.sort_values(\n by=['platform', 'target', 'config', 'section']).drop_duplicates()", "def get_sections(module):\n\n sections_path = \"/sys/module/{module}/sections/.*\".format(module=module)\n output_file = \"/tmp/{module}.sections\".format(module=module)\n\n with open(output_file, \"wt\") as out:\n for filepath in glob.glob(sections_path):\n filename = os.path.basename(filepath)\n out.write(\"%s,%s\\n\" % (filename, open(filepath, 'r').read().strip()))", "def load_sections(self):\n pass", "def get_all_grades(\r\n base_directory: str, sections: pd.DataFrame, nrows: Union[int, None] = None\r\n) -> pd.DataFrame:\r\n return _get_data_for_section(base_directory, sections, get_grades, nrows)", "def read_in_sequencing_summary(summary_path):\n data = pd.read_csv(summary_path, sep=\"\\t\")\n return data", "def get_section_df(self, track_id):\n analysis_res = self.si.analysis(track_id)\n # bars, beats, sections, segments, tatums\n sections_df = pd.DataFrame(analysis_res[\"sections\"])\n sections_df = sections_df[[\"start\", \"duration\", \"loudness\", \"tempo\", \"key\", \"mode\"]]\n sections_df[\"duration\"] = sections_df[\"duration\"] / sum(sections_df[\"duration\"])\n sections_df[\"loudness\"] = sections_df[\"loudness\"].apply(lambda x: abs(x))\n sections_df[\"loudness\"] = sections_df[\"loudness\"] / sum(sections_df[\"loudness\"])\n return sections_df", "def load_sequences(datf, length):\n dirname = CHROM_DIR\n seqdat = pd.DataFrame()\n for gen, chrom in datf[['genome', 'chromosome']] \\\n .groupby(['genome', 'chromosome']).count().index:\n\n chrom_file = dirname + gen + \"_\" + chrom.strip(\"chr\") + \".fasta\"\n chrom_record = SeqIO.read(chrom_file, 'fasta')\n\n # get rows for organism and chromosome\n startstops = datf.loc[(datf['genome'] == gen) & (datf['chromosome'] == chrom)]\n # retrive motif + indent\n motifs, mstarts, mstops = search_chromosome(chrom_record,\n startstops[\"start\"],\n startstops[\"stop\"],\n startstops[\"strand\"],\n length)\n rows = pd.concat([startstops, motifs, mstarts, mstops], axis=1)\n rows.columns = [\"motif-id\", \"organism\", \"genome\", \"chromosome\", \"start\",\n \"stop\", \"strand\", \"seq\", \"mstart\", \"mstop\"]\n seqdat = seqdat.append(rows, ignore_index=True)\n\n return seqdat", "def fetchFromOutpatientDataset(self) -> pd.DataFrame:\n dataframe_list = []\n for i in self.subset_list:\n data_outpatient_claims = pd.read_csv(\n f\"..\\input\\DE1.0 Sample{i}\\DE1_0_2008_to_2010_Outpatient_Claims_Sample_{i}.zip\",\n parse_dates=[\"CLM_FROM_DT\", \"CLM_THRU_DT\",],\n infer_datetime_format=True,\n )\n dataframe_list.append(data_outpatient_claims)\n\n final_outpatient_data = pd.concat(dataframe_list, axis=0)\n\n return final_outpatient_data", "def load_courses_data():\n user_course_views = load('user_course_views.csv')\n course_tags = load('course_tags.csv')\n data = user_course_views.merge(\n course_tags,\n left_on='course_id',\n right_on='course_id',\n how = 'inner',\n )\n data.drop(columns='view_time_seconds')\n \n return data", "def load_all_records(file_list: list, columns: list) -> pd.DataFrame: \n dfs = [pd.read_csv(f, usecols=columns) for f in file_list]\n combined_df = pd.concat(dfs)\n \n return combined_df" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reads the most recent section activities file for the given section into a Pandas DataFrame.
def get_section_activities( base_directory: str, section_id: int, nrows: Union[int, None] = None ) -> pd.DataFrame: file = fr.get_section_activities_file(base_directory, section_id) if file is not None: return _read_csv(file, nrows) return _default()
[ "def get_all_section_activities(\r\n base_directory: str, sections: pd.DataFrame, nrows: Union[int, None] = None\r\n) -> pd.DataFrame:\r\n return _get_data_for_section(\r\n base_directory, sections, get_section_activities, nrows\r\n )", "def get_attendance_events(\r\n base_directory: str, section_id: int, nrows: Union[int, None] = None\r\n) -> pd.DataFrame:\r\n file = fr.get_attendance_events_file(base_directory, section_id)\r\n\r\n if file is not None:\r\n return _read_csv(file, nrows)\r\n\r\n return _default()", "def get_section_associations(\r\n base_directory: str, section_id: int, nrows: Union[int, None] = None\r\n) -> pd.DataFrame:\r\n file = fr.get_section_associations_file(base_directory, section_id)\r\n\r\n if file is not None:\r\n return _read_csv(file, nrows)\r\n\r\n return _default()", "def read_in_sequencing_summary(summary_path):\n data = pd.read_csv(summary_path, sep=\"\\t\")\n return data", "def get_section_df(self, track_id):\n analysis_res = self.si.analysis(track_id)\n # bars, beats, sections, segments, tatums\n sections_df = pd.DataFrame(analysis_res[\"sections\"])\n sections_df = sections_df[[\"start\", \"duration\", \"loudness\", \"tempo\", \"key\", \"mode\"]]\n sections_df[\"duration\"] = sections_df[\"duration\"] / sum(sections_df[\"duration\"])\n sections_df[\"loudness\"] = sections_df[\"loudness\"].apply(lambda x: abs(x))\n sections_df[\"loudness\"] = sections_df[\"loudness\"] / sum(sections_df[\"loudness\"])\n return sections_df", "def read_clickstream_data() -> pd.DataFrame:\n df1 = read_data_with_columns(r'data/interim/clickstream/clickstream_data.csv', r'data/raw/clickstream/clickstream_columns.txt')\n df2 = read_data_with_columns(r'data/raw/clickstream/clickstream_data_part_2.csv', r'data/raw/clickstream/clickstream_columns.txt')\n combined_clickstream_df = pd.concat([df1, df2])\n return combined_clickstream_df", "def get_assignments(\r\n base_directory: str, section_id: int, nrows: Union[int, None] = None\r\n) -> pd.DataFrame:\r\n file = fr.get_assignments_file(base_directory, section_id)\r\n\r\n if file is not None:\r\n return _read_csv(file, nrows)\r\n\r\n return _default()", "def load_data(name: str, location: str = SAVE_LOCATION) -> pd.DataFrame:\n df = pd.read_feather(location + name + '.feather')\n if 'date' in df.columns.values:\n df = df.set_index('date')\n return df", "def get_all_attendance_events(\r\n base_directory: str, sections: pd.DataFrame, nrows: Union[int, None] = None\r\n) -> pd.DataFrame:\r\n return _get_data_for_section(base_directory, sections, get_attendance_events, nrows)", "def get_tab_as_df_or_empty_df_with_index(file):\n\n nlines = len([l for l in open(file, \"r\").readlines() if len(l)>1])\n\n if nlines==0: return pd.DataFrame()\n else: return pd.read_csv(file, sep=\"\\t\", index_col=0)", "def load_dataframe(self):\n parse_dates = [\n feature\n for feature, metadata in self.feature_metadata.items()\n if metadata.dtype == DType.DATETIME\n ]\n self.dataframe = pd.read_csv(\n self.dataset_path,\n dtype={\n feature: PANDAS_DTYPE_MAPPING[metadata.dtype]\n for feature, metadata in self.feature_metadata.items()\n if metadata.dtype != DType.DATETIME\n },\n parse_dates=parse_dates,\n )", "def load_raw_head_data(filename):\n hd = pd.read_csv(filename)\n hd['Timestamp'] = hd['Timestamp'].apply(_parse_dates)\n hd = hd.set_index('Timestamp')\n return hd", "def read_in_data(training_data_url, file=\"hour.csv\"):\n try:\n zipped = urlopen(training_data_url)\n myzip = ZipFile(BytesIO(zipped.read())).extract(file)\n except AttributeError:\n print(\"Check the URL in cofig currently inputting: {}\".format(\n training_data_url))\n raise\n try:\n df = pd.read_csv(myzip)\n except IOError:\n print(\"Reading the pandas file didn't work.: {}\".format(file))\n print(df.head())\n # Just drop rows with nans\n df.dropna(inplace=True)\n\n assert df.shape[0] > 0, \"Empty file!\"\n\n # Check all columns present\n expected_keys = [\n 'instant',\n 'dteday',\n 'season',\n 'yr',\n 'mnth',\n 'hr',\n 'holiday',\n 'weekday',\n 'workingday',\n 'weathersit',\n 'temp',\n 'atemp',\n 'hum',\n 'windspeed',\n 'casual',\n 'registered',\n 'cnt']\n assert all([key in df.keys() for key in expected_keys]\n ), \"Column missing from original training data, check data source\"\n\n return df", "def read_data(source, stage, timestamp='most_recent', refresh_id=None):\n\n\n if timestamp == 'specific_refresh':\n assert refresh_id is not None\n assert type(refresh_id) == int\n timestamp = db_tools.ezfuncs.query(\n \"\"\"\n SQL\n \"\"\".format(source, stage, refresh_id),\n conn_def='cod'\n )\n assert timestamp.shape == (1, 1)\n timestamp = timestamp.iloc[0, 0]\n\n if timestamp == 'most_recent':\n df = pd.read_csv(\n \"FILENAME\"\n \"FILEPATH\".format(source, stage)\n )\n else:\n df = pd.read_csv(\n \"FILENAME\"\n \"FILEPATH\".format(source, stage, timestamp)\n )\n return df", "def _fetch_data(self) -> pandas.DataFrame:\n\n # generate file paths to locally stored 'full' data\n data_title = _FULL_INPUT_DATA_TITLE.format(self._exchange, self._symbol, self._timeperiod)\n file_path = _FULL_INPUT_DATA_PATH.format(data_title)\n\n # check that the full csv files exist\n if not (os.path.isfile(file_path)):\n raise Exception(f\"failed to build DataBook; full data does not exist!\\n\"\n f\"{file_path} not found in library; try building the full dataframe first.\")\n\n # load csv as pandas df\n df = pandas.read_csv(file_path)\n\n return df", "def read_demand_dataframe():\n \n # Point to where you've stored the CSV file on your local machine\n \"remember read demandv1.2 file attached as modified datset \"\n \"original demand file wil not work \"\n desktop = os.path.join(os.path.expanduser('~'),\"Desktop\")\n filepath = os.path.join(desktop,\"Demandv1.2.csv\")\n \n \n\n dataframe = pd.read_csv(filepath, sep=\",\",names=['Month DD Raised','No. of FTE Request Raised','SkillList','Location'], header=1)\n\n \n\n\n return dataframe", "def get_df(name: str, begin_date: datetime.date, end_date: datetime.date) -> pd.DataFrame:\n base_df = pd.concat(\n [pd.read_csv(get_csv(name, date)) for date in datetime_ext.date_range(begin_date, end_date)], axis=0\n )\n\n if name == 'pres_state_2020':\n base_df = _process_pres_state_2020(base_df)\n\n return base_df", "def read_act():\n\n starnames = np.genfromtxt('Star Information/keck_activity_log.txt', dtype = str, skip_header = 1, usecols = 1)\n svals = np.genfromtxt('Star Information/keck_activity_log.txt', dtype = None, skip_header = 1, usecols = 2)\n dates = np.genfromtxt('Star Information/keck_activity_log.txt', dtype = None, skip_header = 1, usecols = 3)\n\n return starnames, svals, dates", "def get_all_section_associations(\r\n base_directory: str, sections: pd.DataFrame, nrows: Union[int, None] = None\r\n) -> pd.DataFrame:\r\n return _get_data_for_section(\r\n base_directory, sections, get_section_associations, nrows\r\n )" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reads the most recent section activities files for all given sections into a Pandas DataFrame.
def get_all_section_activities( base_directory: str, sections: pd.DataFrame, nrows: Union[int, None] = None ) -> pd.DataFrame: return _get_data_for_section( base_directory, sections, get_section_activities, nrows )
[ "def get_section_activities(\r\n base_directory: str, section_id: int, nrows: Union[int, None] = None\r\n) -> pd.DataFrame:\r\n file = fr.get_section_activities_file(base_directory, section_id)\r\n\r\n if file is not None:\r\n return _read_csv(file, nrows)\r\n\r\n return _default()", "def get_all_attendance_events(\r\n base_directory: str, sections: pd.DataFrame, nrows: Union[int, None] = None\r\n) -> pd.DataFrame:\r\n return _get_data_for_section(base_directory, sections, get_attendance_events, nrows)", "def get_section_associations(\r\n base_directory: str, section_id: int, nrows: Union[int, None] = None\r\n) -> pd.DataFrame:\r\n file = fr.get_section_associations_file(base_directory, section_id)\r\n\r\n if file is not None:\r\n return _read_csv(file, nrows)\r\n\r\n return _default()", "def get_attendance_events(\r\n base_directory: str, section_id: int, nrows: Union[int, None] = None\r\n) -> pd.DataFrame:\r\n file = fr.get_attendance_events_file(base_directory, section_id)\r\n\r\n if file is not None:\r\n return _read_csv(file, nrows)\r\n\r\n return _default()", "def get_all_section_associations(\r\n base_directory: str, sections: pd.DataFrame, nrows: Union[int, None] = None\r\n) -> pd.DataFrame:\r\n return _get_data_for_section(\r\n base_directory, sections, get_section_associations, nrows\r\n )", "def get_all_system_activities(\r\n base_directory: str, nrows: Union[int, None] = None\r\n) -> pd.DataFrame:\r\n files = fr.get_system_activities_files(base_directory)\r\n\r\n if files is None or len(files) == 0:\r\n return _default()\r\n\r\n df_list = list()\r\n for f in files:\r\n df_list.append(_read_csv(f, nrows))\r\n\r\n df = pd.concat(df_list)\r\n df.drop_duplicates(inplace=True)\r\n\r\n return df", "def get_assignments(\r\n base_directory: str, section_id: int, nrows: Union[int, None] = None\r\n) -> pd.DataFrame:\r\n file = fr.get_assignments_file(base_directory, section_id)\r\n\r\n if file is not None:\r\n return _read_csv(file, nrows)\r\n\r\n return _default()", "def read_clickstream_data() -> pd.DataFrame:\n df1 = read_data_with_columns(r'data/interim/clickstream/clickstream_data.csv', r'data/raw/clickstream/clickstream_columns.txt')\n df2 = read_data_with_columns(r'data/raw/clickstream/clickstream_data_part_2.csv', r'data/raw/clickstream/clickstream_columns.txt')\n combined_clickstream_df = pd.concat([df1, df2])\n return combined_clickstream_df", "def get_all_assignments(\r\n base_directory: str, sections: pd.DataFrame, nrows: Union[int, None] = None\r\n) -> pd.DataFrame:\r\n return _get_data_for_section(base_directory, sections, get_assignments, nrows)", "def df_from_files(self):\n print('Creating dataframe...')\n num = len([name for name in os.listdir(self.raw) if not name[0] == '.'])\n files = os.path.join(self.raw, '~.info.json') # This is a weird hack\n files = files.replace('~', '{:05d}') # It allows path joining to work on Windows\n data = [json.load(open(files.format(i))) for i in range(1, num + 1)]\n\n columns = ['formats', 'tags', 'categories', 'thumbnails']\n lists = [[], [], [], []]\n deletes = {k: v for k, v in zip(columns, lists)}\n for dt in data:\n for col, ls in deletes.items():\n ls.append(dt[col])\n del dt[col]\n\n self.df = pd.DataFrame(data)\n self.df['upload_date'] = pd.to_datetime(self.df['upload_date'], format='%Y%m%d')\n self.df.to_csv(os.path.join(self.ran, 'df.csv'))\n\n self.tags = deletes['tags']\n pickle.dump(self.tags, open(os.path.join(self.ran, 'tags.txt'), 'wb'))", "def read_in_sequencing_summary(summary_path):\n data = pd.read_csv(summary_path, sep=\"\\t\")\n return data", "def createDataFrame():\n\n # first CSV spans time frame 7/1/18 - 3/11/19\n # second CSV spans time frame 3/12/19 - 6/30/19\n library_stats1 = pd.read_csv(\"library_stats_page1.csv\", nrows=24)\n library_stats2 = pd.read_csv(\"library_stats_page2.csv\")\n\n frames = [library_stats1, library_stats2]\n df = pd.concat(frames, axis=1)\n\n del df['Time']\n\n return df", "def load_courses_data():\n user_course_views = load('user_course_views.csv')\n course_tags = load('course_tags.csv')\n data = user_course_views.merge(\n course_tags,\n left_on='course_id',\n right_on='course_id',\n how = 'inner',\n )\n data.drop(columns='view_time_seconds')\n \n return data", "def get_df(name: str, begin_date: datetime.date, end_date: datetime.date) -> pd.DataFrame:\n base_df = pd.concat(\n [pd.read_csv(get_csv(name, date)) for date in datetime_ext.date_range(begin_date, end_date)], axis=0\n )\n\n if name == 'pres_state_2020':\n base_df = _process_pres_state_2020(base_df)\n\n return base_df", "def get_section_df(self, track_id):\n analysis_res = self.si.analysis(track_id)\n # bars, beats, sections, segments, tatums\n sections_df = pd.DataFrame(analysis_res[\"sections\"])\n sections_df = sections_df[[\"start\", \"duration\", \"loudness\", \"tempo\", \"key\", \"mode\"]]\n sections_df[\"duration\"] = sections_df[\"duration\"] / sum(sections_df[\"duration\"])\n sections_df[\"loudness\"] = sections_df[\"loudness\"].apply(lambda x: abs(x))\n sections_df[\"loudness\"] = sections_df[\"loudness\"] / sum(sections_df[\"loudness\"])\n return sections_df", "def get_submissions(\r\n base_directory: str,\r\n section_id: int,\r\n assignment_id: int,\r\n nrows: Union[int, None] = None,\r\n) -> pd.DataFrame:\r\n file = fr.get_submissions_file(base_directory, section_id, assignment_id)\r\n\r\n if file is not None:\r\n return _read_csv(file, nrows)\r\n\r\n return _default()", "def load_merged_summary(date_lo, date_hi):\n\n # Build list of file dates to read\n date_lo = pd.to_datetime(date_lo)\n date_hi = pd.to_datetime(date_hi)\n date = date_lo\n dfsums = []\n fdates = []\n while date <= date_hi:\n date_str = date.strftime('%Y-%m-%d')\n try:\n _find_casus_fpath(date_str)\n except FileNotFoundError:\n print(f'Using casus data before {date_str}.')\n break\n fdates.append(date_str)\n date += pd.Timedelta(1, 'd')\n\n msg = f'Loading casus data for {len(fdates)} days (using {{ncpu}} processes)'\n with PoolNCPU(msg) as pool:\n dfsums = pool.map(_load_one_df, fdates)\n print()\n dfsmerged = pd.concat(dfsums)\n return dfsmerged", "def get_all_grades(\r\n base_directory: str, sections: pd.DataFrame, nrows: Union[int, None] = None\r\n) -> pd.DataFrame:\r\n return _get_data_for_section(base_directory, sections, get_grades, nrows)", "def readData(self, startTimestamp, endTimestamp, componentTypes = []):\n\n\t\t#THIS MUST BE PARALLELIZED IN ORDER TO ACHIEVE ITS MAXIMUM PERFORMANCE\n\n\t\tif self.dbSession == None:\n\t\t\tself.logger.error('Session not initialized')\n\t\t\treturn\n\n\t\tdataFrames = dict()\n\t\treadings = dict()\n\n\t\tcount = 0\n\n\t\tcomponentsReadingClass = list()\n\n\t\tfor component in componentTypes:\n\n\t\t\treadingClass = self.getComponentReadingClassByType(component)\n\t\t\tif readingClass != None:\n\t\t\t\tcomponentsReadingClass.append(readingClass)\n\n\t\t#This goes to the log\n\t\tself.logger.debug('Loading data for components {} from {} to {}'.format(componentsReadingClass, startTimestamp, endTimestamp))\n\n\t\t#Create the dataframes for each component\n\t\tfor componentReadingClass in componentsReadingClass:\n\t\t\treadings = \\\n\t\t\tself.dbSession.query(componentReadingClass).filter(and_(componentReadingClass._timestamp >= startTimestamp, componentReadingClass._timestamp < endTimestamp)).all()\n\n\t\t\tif readings != []:\n\t\t\t\t#build the dictionary object\n\t\t\t\tdictionaryOfReadings = copy(readings[0]).__dict__\n\t\t\t\t#print(dictionaryOfReadings)\n\t\t\t\tdictionaryOfReadings.pop('_sa_instance_state')\n\n\t\t\t\t#This is performed fast, no need to change it\n\t\t\t\tfor key in dictionaryOfReadings:\n\t\t\t\t\tdictionaryOfReadings[key] = list()\n\n\t\t\t\tkeys = dictionaryOfReadings.keys()\n\t\t\t\t\n\t\t\t\t#Can we make this perform faster?\n\t\t\t\tfor reading in readings:\n\t\t\t\t\treadingAsDict = reading.__dict__\n\t\t\t\t\treadingAsDict.pop('_sa_instance_state')\n\n\t\t\t\t\t#Can we write a map function (functional programming) for this?\n\t\t\t\t\tfor key in keys:\n\t\t\t\t\t\tdictionaryOfReadings[key].append(readingAsDict[key])\n\n\t\t\t\tdataFrames[componentTypes[count] + 'Readings'] = pd.DataFrame.from_dict(dictionaryOfReadings)\n\n\t\t\tcount += 1\n\n\t\treturn dataFrames" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reads the most recent assignments file for the given section into a Pandas DataFrame.
def get_assignments( base_directory: str, section_id: int, nrows: Union[int, None] = None ) -> pd.DataFrame: file = fr.get_assignments_file(base_directory, section_id) if file is not None: return _read_csv(file, nrows) return _default()
[ "def get_all_assignments(\r\n base_directory: str, sections: pd.DataFrame, nrows: Union[int, None] = None\r\n) -> pd.DataFrame:\r\n return _get_data_for_section(base_directory, sections, get_assignments, nrows)", "def get_submissions(\r\n base_directory: str,\r\n section_id: int,\r\n assignment_id: int,\r\n nrows: Union[int, None] = None,\r\n) -> pd.DataFrame:\r\n file = fr.get_submissions_file(base_directory, section_id, assignment_id)\r\n\r\n if file is not None:\r\n return _read_csv(file, nrows)\r\n\r\n return _default()", "def get_section_associations(\r\n base_directory: str, section_id: int, nrows: Union[int, None] = None\r\n) -> pd.DataFrame:\r\n file = fr.get_section_associations_file(base_directory, section_id)\r\n\r\n if file is not None:\r\n return _read_csv(file, nrows)\r\n\r\n return _default()", "def get_section_activities(\r\n base_directory: str, section_id: int, nrows: Union[int, None] = None\r\n) -> pd.DataFrame:\r\n file = fr.get_section_activities_file(base_directory, section_id)\r\n\r\n if file is not None:\r\n return _read_csv(file, nrows)\r\n\r\n return _default()", "def load_data_impl() -> pd.DataFrame:\n # The source for this file is at https://ssd.jpl.nasa.gov/?sb_elem\n fname: str = '../jpl/orb_elements_asteroid.txt'\n\n # The field names in the JPL file and their column positions\n names: List[str] = ['Num', 'Name', 'Epoch', 'a', 'e', 'i', 'w', 'Node', 'M', 'H', 'G', 'Ref']\n colspec_tbl: Dict[str, Tuple[int, int]] = {\n 'Num': (0,6), \n 'Name': (7, 25), \n 'Epoch': (25, 30), \n 'a': (31, 41), \n 'e': (42, 52), \n 'i': (54, 62), \n 'w': (63, 72),\n 'Node': (73, 82),\n 'M': (83, 94),\n 'H': (95, 100),\n 'G': (101, 105),\n 'Ref': (106, 113),\n }\n \n # Other arguments for Pandas file import\n colspecs: List[Tuple[int, int]] = [colspec_tbl[nm] for nm in names]\n header: int = 0\n skiprows: List[int] = [1]\n dtype: Dict[str, int] = {\n 'Num': int,\n 'Name': str,\n 'Epoch': float,\n 'a': float,\n 'e': float,\n 'i': float,\n 'w': float,\n 'Node': float,\n 'M': float,\n 'H': float,\n 'G': float,\n 'Ref': str,\n }\n\n # Read the DataFrame\n df: pd.DataFrame = pd.read_fwf(fname, colspecs=colspecs, header=header, names=names, skiprows=skiprows, dtype=dtype)\n # Set the asteroid number field to be the index\n df.set_index(keys=['Num'], drop=False, inplace=True)\n return df", "def read_in_sequencing_summary(summary_path):\n data = pd.read_csv(summary_path, sep=\"\\t\")\n return data", "def get_grades(\r\n base_directory: str, section_id: int, nrows: Union[int, None] = None\r\n) -> pd.DataFrame:\r\n file = fr.get_grades_file(base_directory, section_id)\r\n\r\n if file is not None:\r\n return _read_csv(file, nrows)\r\n\r\n return _default()", "def _read(self, profile_filename):\n # header=0 because docs say to if using skip rows and columns\n df = pd.read_csv(profile_filename, header=0,\n skiprows=self.hdr.header_pos,\n names=self.hdr.columns,\n encoding='latin')\n\n # Special SMP specific tasks\n depth_fmt = 'snow_height'\n is_smp = False\n if 'force' in df.columns:\n # Convert depth from mm to cm\n df['depth'] = df['depth'].div(10)\n is_smp = True\n # Make the data negative from snow surface\n depth_fmt = 'surface_datum'\n\n # SMP serial number and original filename for provenance to the comment\n f = basename(profile_filename)\n serial_no = f.split('SMP_')[-1][1:3]\n\n df['comments'] = f\"fname = {f}, \" \\\n f\"serial no. = {serial_no}\"\n\n # Standardize all depth data\n new_depth = standardize_depth(df['depth'],\n desired_format=depth_fmt,\n is_smp=is_smp)\n\n if 'bottom_depth' in df.columns:\n delta = df['depth'] - new_depth\n df['bottom_depth'] = df['bottom_depth'] - delta\n\n df['depth'] = new_depth\n\n delta = abs(df['depth'].max() - df['depth'].min())\n self.log.info('File contains {} profiles each with {} layers across '\n '{:0.2f} cm'.format(len(self.hdr.data_names), len(df), delta))\n return df", "def get_tab_as_df_or_empty_df_with_index(file):\n\n nlines = len([l for l in open(file, \"r\").readlines() if len(l)>1])\n\n if nlines==0: return pd.DataFrame()\n else: return pd.read_csv(file, sep=\"\\t\", index_col=0)", "def ReadData( fileName ):\n \n # define column names\n colNames = ['Date','Precip','Max Temp', 'Min Temp','Wind Speed']\n\n # open and read the file\n DataDF = pd.read_csv(\"DataQualityChecking.txt\",header=None, names=colNames, \n delimiter=r\"\\s+\",parse_dates=[0])\n DataDF = DataDF.set_index('Date')\n \n # define and initialize the missing data dictionary\n ReplacedValuesDF = pd.DataFrame(0, index=[\"1. No Data\", \"2. Gross Error\", \"3. Swapped\", \"4. Range Fail\"], columns=colNames[1:]) ##added row names 2-4\n \n return( DataDF, ReplacedValuesDF )", "def get_attendance_events(\r\n base_directory: str, section_id: int, nrows: Union[int, None] = None\r\n) -> pd.DataFrame:\r\n file = fr.get_attendance_events_file(base_directory, section_id)\r\n\r\n if file is not None:\r\n return _read_csv(file, nrows)\r\n\r\n return _default()", "def import_VCF42_cohort_pandas(vcf_file, sep='\\t'):\n header_lines = 0\n\n if vcf_file.endswith(\".gz\"):\n with gzip.open(vcf_file, 'rb') as f:\n first_line = f.readline().decode().strip()\n next_line = f.readline().decode().strip()\n while next_line.startswith(\"##\"):\n header_lines = header_lines + 1\n next_line = f.readline().decode().strip()\n else:\n with open(vcf_file, 'r') as f:\n first_line = f.readline().strip()\n next_line = f.readline().strip()\n while next_line.startswith(\"##\"):\n header_lines = header_lines + 1\n next_line = f.readline().strip()\n \n if first_line.endswith('VCFv4.2'):\n dataframe = pd.read_csv(vcf_file, sep=sep, skiprows=[header_lines], header=header_lines)\n else:\n print(\"This vcf file is not v4.2\")\n sys.exit(1)\n\n return dataframe", "def load_edits(edit_path=None, sensordata_path=None, assignment_col='assignment'):\n if not edit_path and not sensordata_path:\n raise ValueError(\"Either edit_path or sensordata_path must be specified and non-empty\")\n\n if edit_path:\n try:\n edits = pd.read_csv(edit_path) # no formatting needed\n return edits\n except FileNotFoundError:\n if not sensordata_path:\n raise ValueError(\"edit_path is invalid and sensordata_path not specified.\")\n \n # edit_path was invalid, so we need to get edit events from all sensordata\n dtypes = {\n 'email': str,\n assignment_col: str,\n 'time': int,\n 'Class-Name': object,\n 'Unit-Type': object,\n 'Type': object,\n 'Subtype': object,\n 'Subsubtype': object,\n 'onTestCase': object,\n 'Current-Statements': object,\n 'Current-Methods': object,\n 'Current-Size': object,\n 'Current-Test-Assertions': object\n }\n data = pd.read_csv(sensordata_path, dtype=dtypes, usecols=dtypes.keys())\n data = data[(data['Type'] == 'Edit') & (data['Class-Name'] != '')]\n data = (\n data\n .fillna('')\n .sort_values(by=['email', assignment_col, 'time'], ascending=[1,1,1])\n .rename(columns={ 'email': 'userName', assignment_col: 'assignment' })\n )\n data['userName'] = data.userName.apply(lambda u: u.split('@')[0])\n data = data.set_index(['userName', 'assignment'])\n return data", "def get_df(name: str, begin_date: datetime.date, end_date: datetime.date) -> pd.DataFrame:\n base_df = pd.concat(\n [pd.read_csv(get_csv(name, date)) for date in datetime_ext.date_range(begin_date, end_date)], axis=0\n )\n\n if name == 'pres_state_2020':\n base_df = _process_pres_state_2020(base_df)\n\n return base_df", "def read_demand_dataframe():\n \n # Point to where you've stored the CSV file on your local machine\n \"remember read demandv1.2 file attached as modified datset \"\n \"original demand file wil not work \"\n desktop = os.path.join(os.path.expanduser('~'),\"Desktop\")\n filepath = os.path.join(desktop,\"Demandv1.2.csv\")\n \n \n\n dataframe = pd.read_csv(filepath, sep=\",\",names=['Month DD Raised','No. of FTE Request Raised','SkillList','Location'], header=1)\n\n \n\n\n return dataframe", "def read_assignments(filename):\n personal_spots = [ ]\n trackleaders_spots = [ ]\n support_spots = [ ]\n wb = load_workbook(filename)\n sheet = wb.active\n for row in sheet.rows:\n tag = row[0].value\n if tag == \"TL\":\n # TrackLeader rented spot\n record = { \"rider\": (row[2].value or \"_\") + \" \" + (row[3].value or \"_\"),\n \"esn\": row[4].value,\n \"unit\": row[1].value\n }\n trackleaders_spots.append(record)\n elif tag == \"PS\" or tag == \"SV\":\n # Personal spot; we have a URL\n url = row[4].value\n gid = url.split(\"=\")[-1]\n record = { \"rider\": (row[2].value or \"_\") + \" \" + (row[3].value or \"_\"),\n \"gid\": gid\n }\n if tag == \"PS\":\n personal_spots.append(record)\n elif tag == \"SV\":\n support_spots.append(record)\n assignments = {\"kind\": \"assignments\",\n \"personal_spots\": personal_spots,\n \"trackleaders_spots\": trackleaders_spots,\n \"support_spots\": support_spots\n }\n return assignments", "def read_data(source, stage, timestamp='most_recent', refresh_id=None):\n\n\n if timestamp == 'specific_refresh':\n assert refresh_id is not None\n assert type(refresh_id) == int\n timestamp = db_tools.ezfuncs.query(\n \"\"\"\n SQL\n \"\"\".format(source, stage, refresh_id),\n conn_def='cod'\n )\n assert timestamp.shape == (1, 1)\n timestamp = timestamp.iloc[0, 0]\n\n if timestamp == 'most_recent':\n df = pd.read_csv(\n \"FILENAME\"\n \"FILEPATH\".format(source, stage)\n )\n else:\n df = pd.read_csv(\n \"FILENAME\"\n \"FILEPATH\".format(source, stage, timestamp)\n )\n return df", "def load_raw_head_data(filename):\n hd = pd.read_csv(filename)\n hd['Timestamp'] = hd['Timestamp'].apply(_parse_dates)\n hd = hd.set_index('Timestamp')\n return hd", "def read_in_data(training_data_url, file=\"hour.csv\"):\n try:\n zipped = urlopen(training_data_url)\n myzip = ZipFile(BytesIO(zipped.read())).extract(file)\n except AttributeError:\n print(\"Check the URL in cofig currently inputting: {}\".format(\n training_data_url))\n raise\n try:\n df = pd.read_csv(myzip)\n except IOError:\n print(\"Reading the pandas file didn't work.: {}\".format(file))\n print(df.head())\n # Just drop rows with nans\n df.dropna(inplace=True)\n\n assert df.shape[0] > 0, \"Empty file!\"\n\n # Check all columns present\n expected_keys = [\n 'instant',\n 'dteday',\n 'season',\n 'yr',\n 'mnth',\n 'hr',\n 'holiday',\n 'weekday',\n 'workingday',\n 'weathersit',\n 'temp',\n 'atemp',\n 'hum',\n 'windspeed',\n 'casual',\n 'registered',\n 'cnt']\n assert all([key in df.keys() for key in expected_keys]\n ), \"Column missing from original training data, check data source\"\n\n return df" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reads the most recent assignments files for all given sections into a Pandas DataFrame.
def get_all_assignments( base_directory: str, sections: pd.DataFrame, nrows: Union[int, None] = None ) -> pd.DataFrame: return _get_data_for_section(base_directory, sections, get_assignments, nrows)
[ "def get_assignments(\r\n base_directory: str, section_id: int, nrows: Union[int, None] = None\r\n) -> pd.DataFrame:\r\n file = fr.get_assignments_file(base_directory, section_id)\r\n\r\n if file is not None:\r\n return _read_csv(file, nrows)\r\n\r\n return _default()", "def get_submissions(\r\n base_directory: str,\r\n section_id: int,\r\n assignment_id: int,\r\n nrows: Union[int, None] = None,\r\n) -> pd.DataFrame:\r\n file = fr.get_submissions_file(base_directory, section_id, assignment_id)\r\n\r\n if file is not None:\r\n return _read_csv(file, nrows)\r\n\r\n return _default()", "def get_all_section_activities(\r\n base_directory: str, sections: pd.DataFrame, nrows: Union[int, None] = None\r\n) -> pd.DataFrame:\r\n return _get_data_for_section(\r\n base_directory, sections, get_section_activities, nrows\r\n )", "def get_all_grades(\r\n base_directory: str, sections: pd.DataFrame, nrows: Union[int, None] = None\r\n) -> pd.DataFrame:\r\n return _get_data_for_section(base_directory, sections, get_grades, nrows)", "def get_all_attendance_events(\r\n base_directory: str, sections: pd.DataFrame, nrows: Union[int, None] = None\r\n) -> pd.DataFrame:\r\n return _get_data_for_section(base_directory, sections, get_attendance_events, nrows)", "def get_all_section_associations(\r\n base_directory: str, sections: pd.DataFrame, nrows: Union[int, None] = None\r\n) -> pd.DataFrame:\r\n return _get_data_for_section(\r\n base_directory, sections, get_section_associations, nrows\r\n )", "def get_section_associations(\r\n base_directory: str, section_id: int, nrows: Union[int, None] = None\r\n) -> pd.DataFrame:\r\n file = fr.get_section_associations_file(base_directory, section_id)\r\n\r\n if file is not None:\r\n return _read_csv(file, nrows)\r\n\r\n return _default()", "def get_section_activities(\r\n base_directory: str, section_id: int, nrows: Union[int, None] = None\r\n) -> pd.DataFrame:\r\n file = fr.get_section_activities_file(base_directory, section_id)\r\n\r\n if file is not None:\r\n return _read_csv(file, nrows)\r\n\r\n return _default()", "def get_grades(\r\n base_directory: str, section_id: int, nrows: Union[int, None] = None\r\n) -> pd.DataFrame:\r\n file = fr.get_grades_file(base_directory, section_id)\r\n\r\n if file is not None:\r\n return _read_csv(file, nrows)\r\n\r\n return _default()", "def df_from_files(self):\n print('Creating dataframe...')\n num = len([name for name in os.listdir(self.raw) if not name[0] == '.'])\n files = os.path.join(self.raw, '~.info.json') # This is a weird hack\n files = files.replace('~', '{:05d}') # It allows path joining to work on Windows\n data = [json.load(open(files.format(i))) for i in range(1, num + 1)]\n\n columns = ['formats', 'tags', 'categories', 'thumbnails']\n lists = [[], [], [], []]\n deletes = {k: v for k, v in zip(columns, lists)}\n for dt in data:\n for col, ls in deletes.items():\n ls.append(dt[col])\n del dt[col]\n\n self.df = pd.DataFrame(data)\n self.df['upload_date'] = pd.to_datetime(self.df['upload_date'], format='%Y%m%d')\n self.df.to_csv(os.path.join(self.ran, 'df.csv'))\n\n self.tags = deletes['tags']\n pickle.dump(self.tags, open(os.path.join(self.ran, 'tags.txt'), 'wb'))", "def get_df(name: str, begin_date: datetime.date, end_date: datetime.date) -> pd.DataFrame:\n base_df = pd.concat(\n [pd.read_csv(get_csv(name, date)) for date in datetime_ext.date_range(begin_date, end_date)], axis=0\n )\n\n if name == 'pres_state_2020':\n base_df = _process_pres_state_2020(base_df)\n\n return base_df", "def get_attendance_events(\r\n base_directory: str, section_id: int, nrows: Union[int, None] = None\r\n) -> pd.DataFrame:\r\n file = fr.get_attendance_events_file(base_directory, section_id)\r\n\r\n if file is not None:\r\n return _read_csv(file, nrows)\r\n\r\n return _default()", "def load_data_impl() -> pd.DataFrame:\n # The source for this file is at https://ssd.jpl.nasa.gov/?sb_elem\n fname: str = '../jpl/orb_elements_asteroid.txt'\n\n # The field names in the JPL file and their column positions\n names: List[str] = ['Num', 'Name', 'Epoch', 'a', 'e', 'i', 'w', 'Node', 'M', 'H', 'G', 'Ref']\n colspec_tbl: Dict[str, Tuple[int, int]] = {\n 'Num': (0,6), \n 'Name': (7, 25), \n 'Epoch': (25, 30), \n 'a': (31, 41), \n 'e': (42, 52), \n 'i': (54, 62), \n 'w': (63, 72),\n 'Node': (73, 82),\n 'M': (83, 94),\n 'H': (95, 100),\n 'G': (101, 105),\n 'Ref': (106, 113),\n }\n \n # Other arguments for Pandas file import\n colspecs: List[Tuple[int, int]] = [colspec_tbl[nm] for nm in names]\n header: int = 0\n skiprows: List[int] = [1]\n dtype: Dict[str, int] = {\n 'Num': int,\n 'Name': str,\n 'Epoch': float,\n 'a': float,\n 'e': float,\n 'i': float,\n 'w': float,\n 'Node': float,\n 'M': float,\n 'H': float,\n 'G': float,\n 'Ref': str,\n }\n\n # Read the DataFrame\n df: pd.DataFrame = pd.read_fwf(fname, colspecs=colspecs, header=header, names=names, skiprows=skiprows, dtype=dtype)\n # Set the asteroid number field to be the index\n df.set_index(keys=['Num'], drop=False, inplace=True)\n return df", "def read_all_files():\n # Setting up pool with 8 processes.\n pool = Pool(processes=8) \n\n # Get the list of file names.\n path = \"DATA/votes-all/\"\n files = os.listdir(path)\n file_list = [filename for filename in files if filename.split('.')[1]=='csv']\n\n # Using the pool to map the file names to dataframes.\n df_list = pool.map(read_csv, file_list)\n pool.close() \n pool.join()\n \n # Reducing list of dataframes to single dataframe.\n df_final = reduce(lambda left,right: pd.merge(left,right,on=['uin','title','date'],how='outer'), df_list)\n return df_final", "def load_merged_summary(date_lo, date_hi):\n\n # Build list of file dates to read\n date_lo = pd.to_datetime(date_lo)\n date_hi = pd.to_datetime(date_hi)\n date = date_lo\n dfsums = []\n fdates = []\n while date <= date_hi:\n date_str = date.strftime('%Y-%m-%d')\n try:\n _find_casus_fpath(date_str)\n except FileNotFoundError:\n print(f'Using casus data before {date_str}.')\n break\n fdates.append(date_str)\n date += pd.Timedelta(1, 'd')\n\n msg = f'Loading casus data for {len(fdates)} days (using {{ncpu}} processes)'\n with PoolNCPU(msg) as pool:\n dfsums = pool.map(_load_one_df, fdates)\n print()\n dfsmerged = pd.concat(dfsums)\n return dfsmerged", "def read_in_sequencing_summary(summary_path):\n data = pd.read_csv(summary_path, sep=\"\\t\")\n return data", "def _parse_lma_files(files, dates):\n\n try:\n ref = datetime.datetime.strptime(dates[0], '%m/%d/%y')\n except ValueError:\n try:\n ref = datetime.datetime.strptime(dates[0], '%Y-%m-%d')\n except ValueError:\n ref = datetime.datetime.strptime(dates[0], '%m/%d/%Y')\n\n pds = []\n\n # Read in the files\n for i, f in enumerate(files):\n pds.append(pd.read_csv(f))\n\n # Add a Series to each DataFrame containing the time of each source\n # in datetime form\n for i, p in enumerate(pds):\n if len(dates) > 1:\n try:\n date = datetime.datetime.strptime(dates[i], '%m/%d/%y')\n except ValueError:\n try:\n date = datetime.datetime.strptime(dates[i], '%Y-%m-%d')\n except ValueError:\n date = datetime.datetime.strptime(dates[i], '%m/%d/%Y')\n\n series = [date + datetime.timedelta(seconds=entry) for entry\n in p['time(UT-sec-of-day)']]\n\n p.insert(0, 'DateTime', series)\n p['DateTime'] = pd.to_datetime(p['DateTime'])\n\n # Replace the values of the seconds of day column\n # to allow for storms to span multiple days\n series = [(entry - ref).total_seconds() for entry in\n p['DateTime']]\n p.drop('time(UT-sec-of-day)', axis=1, inplace=True)\n p.insert(1, 'time(UT-sec-of-day)', series)\n\n else:\n try:\n date = datetime.datetime.strptime(dates[0], '%m/%d/%y')\n except ValueError:\n try:\n date = datetime.datetime.strptime(dates[0], '%Y-%m-%d')\n except ValueError:\n date = datetime.datetime.strptime(dates[0], '%m/%d/%Y')\n\n series = [date + datetime.timedelta(seconds=entry) for entry\n in p['time(UT-sec-of-day)']]\n\n p.insert(0, 'DateTime', series)\n p['DateTime'] = pd.to_datetime(p['DateTime'])\n\n # Replace the values of the seconds of day column\n # to allow for storms to span multiple days\n series = [(entry - ref).total_seconds() for entry in\n p['DateTime']]\n p.drop('time(UT-sec-of-day)', axis=1, inplace=True)\n p.insert(1, 'time(UT-sec-of-day)', series)\n\n # Remove all flash-numbers that are == -1\n for i in range(len(pds)):\n row_index = pds[i][pds[i]['flash-number'] != -1].index\n pds[i] = pds[i].loc[row_index]\n\n # print(-1 in pds[i]['flash-number'])\n\n # Correct the flash numbers so that there are no duplicates\n for i in range(len(pds) - 1):\n # Get the largest flash number of the current file\n max_flash_number = pds[i]['flash-number'].max() + 1\n\n # Apply the offset to the next file\n pds[i + 1]['flash-number'] += max_flash_number\n\n # Make the final Pandas DataFrame\n if len(pds) > 1:\n storm = pd.concat(pds, ignore_index=True)\n else:\n storm = pds[0]\n\n # Sort the data frame by time\n storm.set_index('DateTime', inplace=True)\n storm.sort_index(inplace=True)\n\n # Reset the index\n storm.reset_index(inplace=True)\n\n return storm", "def fetchFromInpatientDataset(self) -> pd.DataFrame:\n dataframe_list = []\n for i in self.subset_list:\n data_inpatient_claims = pd.read_csv(\n f\"..\\input\\DE1.0 Sample{i}\\DE1_0_2008_to_2010_Inpatient_Claims_Sample_{i}.zip\",\n parse_dates=[\n \"CLM_FROM_DT\",\n \"CLM_THRU_DT\",\n \"CLM_ADMSN_DT\",\n \"NCH_BENE_DSCHRG_DT\",\n ],\n infer_datetime_format=True,\n )\n dataframe_list.append(data_inpatient_claims)\n\n final_inpatient_data = pd.concat(dataframe_list, axis=0)\n\n return final_inpatient_data", "def get_events_from_study_guide(filename):\n\n df = get_df_from_pdf(filename)\n\n due_column = df.columns[-1] # Usually \"Due\" or \"Due Date\"\n\n # slice df only where df[due_column] is not empty, then save to_dict,\n # orient='records' to create a separate dict with all keys for each event\n assignments = df[df[due_column].apply(is_empty)].to_dict(orient='records')\n\n events = []\n for hw in assignments:\n title = 'Section ' + hw['Section']\n desc = hw['Topic'].replace('\\n', '') + ' --- Problems: ' \\\n + hw['Exercises'].replace('\\n', '')\n date = get_assignment_datetime(hw[due_column])\n\n event = {\n \"title\": title,\n \"description\": desc,\n \"begin\": date,\n }\n\n events.append(event)\n\n return events" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reads the most recent submissions file for the given section into a Pandas DataFrame.
def get_submissions( base_directory: str, section_id: int, assignment_id: int, nrows: Union[int, None] = None, ) -> pd.DataFrame: file = fr.get_submissions_file(base_directory, section_id, assignment_id) if file is not None: return _read_csv(file, nrows) return _default()
[ "def load_submission_data(webcat_path, onlyfinal=True):\n\n cols_of_interest = [\n 'userName',\n 'assignment',\n 'submissionNo',\n 'score.correctness',\n 'max.score.correctness',\n 'elements',\n 'elementsCovered',\n 'submissionTimeRaw',\n 'dueDateRaw'\n ]\n date_parser = lambda d: datetime.datetime.fromtimestamp(int(float(d)) / 1000)\n data = pd.read_csv(webcat_path, \\\n usecols=cols_of_interest, \\\n parse_dates=['dueDateRaw', 'submissionTimeRaw'], \\\n date_parser=date_parser)\n data.sort_values(by=['assignment', 'userName', 'submissionNo'], ascending=[1,1,0], inplace=True)\n\n if onlyfinal:\n # get the last submission from each user on each project\n data.drop_duplicates(subset=['assignment', 'userName'], keep='first', inplace=True)\n\n # calculate reftest percentages and discretised project grades\n data['score.correctness'] = data['score.correctness'] / data['max.score.correctness']\n data['elementsCovered'] = (data['elementsCovered'] / data['elements']) / 0.98\n data['elementsCovered'] = data['elementsCovered'].apply(lambda x: x if x <= 1 else 1)\n data['score.reftest'] = data['score.correctness'] / data['elementsCovered']\n data['score.reftest'] = data['score.reftest'].apply(lambda x: x if x <= 1 else 1)\n\n # calculate submission time outcomes \n hours_from_deadline = (data['dueDateRaw'] - data['submissionTimeRaw'])\n data['finishedHoursFromDeadline'] = hours_from_deadline.apply(lambda diff: diff.total_seconds() / 3600)\n data['onTimeSubmission'] = data['finishedHoursFromDeadline'].apply(lambda h: 1 if h >= 0 else 0)\n\n data.set_index(['userName', 'assignment'], inplace=True)\n return data", "def get_assignments(\r\n base_directory: str, section_id: int, nrows: Union[int, None] = None\r\n) -> pd.DataFrame:\r\n file = fr.get_assignments_file(base_directory, section_id)\r\n\r\n if file is not None:\r\n return _read_csv(file, nrows)\r\n\r\n return _default()", "def get_tab_as_df_or_empty_df_with_index(file):\n\n nlines = len([l for l in open(file, \"r\").readlines() if len(l)>1])\n\n if nlines==0: return pd.DataFrame()\n else: return pd.read_csv(file, sep=\"\\t\", index_col=0)", "def _fetch_data(self) -> pandas.DataFrame:\n\n # generate file paths to locally stored 'full' data\n data_title = _FULL_INPUT_DATA_TITLE.format(self._exchange, self._symbol, self._timeperiod)\n file_path = _FULL_INPUT_DATA_PATH.format(data_title)\n\n # check that the full csv files exist\n if not (os.path.isfile(file_path)):\n raise Exception(f\"failed to build DataBook; full data does not exist!\\n\"\n f\"{file_path} not found in library; try building the full dataframe first.\")\n\n # load csv as pandas df\n df = pandas.read_csv(file_path)\n\n return df", "def get_section_activities(\r\n base_directory: str, section_id: int, nrows: Union[int, None] = None\r\n) -> pd.DataFrame:\r\n file = fr.get_section_activities_file(base_directory, section_id)\r\n\r\n if file is not None:\r\n return _read_csv(file, nrows)\r\n\r\n return _default()", "def load_raw_head_data(filename):\n hd = pd.read_csv(filename)\n hd['Timestamp'] = hd['Timestamp'].apply(_parse_dates)\n hd = hd.set_index('Timestamp')\n return hd", "def read_in_data(training_data_url, file=\"hour.csv\"):\n try:\n zipped = urlopen(training_data_url)\n myzip = ZipFile(BytesIO(zipped.read())).extract(file)\n except AttributeError:\n print(\"Check the URL in cofig currently inputting: {}\".format(\n training_data_url))\n raise\n try:\n df = pd.read_csv(myzip)\n except IOError:\n print(\"Reading the pandas file didn't work.: {}\".format(file))\n print(df.head())\n # Just drop rows with nans\n df.dropna(inplace=True)\n\n assert df.shape[0] > 0, \"Empty file!\"\n\n # Check all columns present\n expected_keys = [\n 'instant',\n 'dteday',\n 'season',\n 'yr',\n 'mnth',\n 'hr',\n 'holiday',\n 'weekday',\n 'workingday',\n 'weathersit',\n 'temp',\n 'atemp',\n 'hum',\n 'windspeed',\n 'casual',\n 'registered',\n 'cnt']\n assert all([key in df.keys() for key in expected_keys]\n ), \"Column missing from original training data, check data source\"\n\n return df", "def df_from_files(self):\n print('Creating dataframe...')\n num = len([name for name in os.listdir(self.raw) if not name[0] == '.'])\n files = os.path.join(self.raw, '~.info.json') # This is a weird hack\n files = files.replace('~', '{:05d}') # It allows path joining to work on Windows\n data = [json.load(open(files.format(i))) for i in range(1, num + 1)]\n\n columns = ['formats', 'tags', 'categories', 'thumbnails']\n lists = [[], [], [], []]\n deletes = {k: v for k, v in zip(columns, lists)}\n for dt in data:\n for col, ls in deletes.items():\n ls.append(dt[col])\n del dt[col]\n\n self.df = pd.DataFrame(data)\n self.df['upload_date'] = pd.to_datetime(self.df['upload_date'], format='%Y%m%d')\n self.df.to_csv(os.path.join(self.ran, 'df.csv'))\n\n self.tags = deletes['tags']\n pickle.dump(self.tags, open(os.path.join(self.ran, 'tags.txt'), 'wb'))", "def __parse_quic_timing_from_scenario(in_dir: str, scenario_name: str, pep: bool = False) -> pd.DataFrame:\n\n logger.debug(\"Parsing quic%s timing files in %s\", \" (pep)\" if pep else \"\", scenario_name)\n df = pd.DataFrame(columns=['run', 'con_est', 'ttfb'])\n\n for file_name in os.listdir(os.path.join(in_dir, scenario_name)):\n file_path = os.path.join(in_dir, scenario_name, file_name)\n if not os.path.isfile(file_path):\n continue\n match = re.search(r\"^quic%s_ttfb_(\\d+)_client\\.txt$\" % (\"_pep\" if pep else \"\",), file_name)\n if not match:\n continue\n\n logger.debug(\"%s: Parsing '%s'\", scenario_name, file_name)\n run = int(match.group(1))\n con_est = None\n ttfb = None\n with open(file_path) as file:\n for line in file:\n if line.startswith('connection establishment time:'):\n if con_est is not None:\n logger.warning(\"Found duplicate value for con_est in '%s', ignoring\", file_path)\n else:\n con_est = float(line.split(':', 1)[1].strip()[:-2])\n elif line.startswith('time to first byte:'):\n if ttfb is not None:\n logger.warning(\"Found duplicate value for ttfb in '%s', ignoring\", file_path)\n else:\n ttfb = float(line.split(':', 1)[1].strip()[:-2])\n df = df.append({\n 'run': run,\n 'con_est': con_est,\n 'ttfb': ttfb\n }, ignore_index=True)\n\n with_na = len(df.index)\n df.dropna(subset=['con_est', 'ttfb'], inplace=True)\n without_na = len(df.index)\n if with_na != without_na:\n logger.warning(\"%s: Dropped %d lines with NaN values\", scenario_name, with_na - without_na)\n\n if df.empty:\n logger.warning(\"%s: No quic%s timing data found\", scenario_name, \" (pep)\" if pep else \"\")\n\n return df", "def read_data(source, stage, timestamp='most_recent', refresh_id=None):\n\n\n if timestamp == 'specific_refresh':\n assert refresh_id is not None\n assert type(refresh_id) == int\n timestamp = db_tools.ezfuncs.query(\n \"\"\"\n SQL\n \"\"\".format(source, stage, refresh_id),\n conn_def='cod'\n )\n assert timestamp.shape == (1, 1)\n timestamp = timestamp.iloc[0, 0]\n\n if timestamp == 'most_recent':\n df = pd.read_csv(\n \"FILENAME\"\n \"FILEPATH\".format(source, stage)\n )\n else:\n df = pd.read_csv(\n \"FILENAME\"\n \"FILEPATH\".format(source, stage, timestamp)\n )\n return df", "def get_section_associations(\r\n base_directory: str, section_id: int, nrows: Union[int, None] = None\r\n) -> pd.DataFrame:\r\n file = fr.get_section_associations_file(base_directory, section_id)\r\n\r\n if file is not None:\r\n return _read_csv(file, nrows)\r\n\r\n return _default()", "def _read_external_data(self):\n return pd.read_csv(\n os.path.join(\n self._path,\n self._submissions_dir,\n self._submission,\n self._f_names['external_data']\n )\n )", "def read_demand_dataframe():\n \n # Point to where you've stored the CSV file on your local machine\n \"remember read demandv1.2 file attached as modified datset \"\n \"original demand file wil not work \"\n desktop = os.path.join(os.path.expanduser('~'),\"Desktop\")\n filepath = os.path.join(desktop,\"Demandv1.2.csv\")\n \n \n\n dataframe = pd.read_csv(filepath, sep=\",\",names=['Month DD Raised','No. of FTE Request Raised','SkillList','Location'], header=1)\n\n \n\n\n return dataframe", "def extract_data(data_path: str) -> DataFrame:\n raw_data = {\n COL_QUERY: [],\n COL_RUN: [],\n COL_TIME: [],\n }\n for filename in os.listdir(data_path):\n split_filename = filename.split('-')\n raw_data[COL_QUERY].append(int(split_filename[1]))\n raw_data[COL_RUN].append(int(split_filename[4]))\n with open(f'{data_path}/{filename}') as f:\n lines = f.readlines()\n time_line = lines[-19] # Large cerebrum\n time_regex = r'Elapsed \\(wall clock\\) time \\(h:mm:ss or m:ss\\): (.*)'\n time = re.findall(time_regex, time_line)\n time = time.pop()\n raw_data[COL_TIME].append(time)\n d = pd.DataFrame(data=raw_data)\n d = d.sort_values(by=[COL_QUERY, COL_RUN],\n ascending=[True, True])\n return d", "def import_VCF42_cohort_pandas(vcf_file, sep='\\t'):\n header_lines = 0\n\n if vcf_file.endswith(\".gz\"):\n with gzip.open(vcf_file, 'rb') as f:\n first_line = f.readline().decode().strip()\n next_line = f.readline().decode().strip()\n while next_line.startswith(\"##\"):\n header_lines = header_lines + 1\n next_line = f.readline().decode().strip()\n else:\n with open(vcf_file, 'r') as f:\n first_line = f.readline().strip()\n next_line = f.readline().strip()\n while next_line.startswith(\"##\"):\n header_lines = header_lines + 1\n next_line = f.readline().strip()\n \n if first_line.endswith('VCFv4.2'):\n dataframe = pd.read_csv(vcf_file, sep=sep, skiprows=[header_lines], header=header_lines)\n else:\n print(\"This vcf file is not v4.2\")\n sys.exit(1)\n\n return dataframe", "def read_in_sequencing_summary(summary_path):\n data = pd.read_csv(summary_path, sep=\"\\t\")\n return data", "def process_submissions_made_on(period):\n warnings = ['\\nProcessing Submissions Made data Warnings:\\n']\n warnings_to_process = False\n print('\\nSubmissions Made data.')\n # Confirm the required files are in place\n required_files = ['Submissions Made report']\n ad.confirm_files('Submissions Made Report', required_files)\n # Get name for Submissions Made Report data file and then load\n report_data, to_add, warnings_to_add = load_data('Submissions_Made_')\n # print('Check loaded data:')\n # ad.debug_list(report_data)\n if to_add:\n warnings_to_process = True\n for line in warnings_to_add:\n warnings.append(line)\n # Create a dataframe for Submissions Made report data\n headings = ['Student ID', 'Student', 'Course', 'Tutor', 'Assignment name',\n 'Last submission date']\n subs = pd.DataFrame(data = report_data, columns = headings)\n # Change value in Course column to 'Skip' if not an online course\n subs['Course'] = subs['Course'].apply(list_non_on)\n # Remove courses that are not Online ('Skip' in 'Course')\n subs = subs.drop(subs.index[subs['Course'] == 'Skip'])\n # Clean the Last submission date\n last_col = 'Last submission date'\n # print(subs)\n subs[last_col] = subs[last_col].apply(da.clean_date, args=('-','-',''))\n # Replace 01-01-1970 with an empty string in date column Last Submission\n subs[last_col] = subs[last_col].apply(da.replace_nil_date)\n # Remove Assessment name column\n headings = ['Student ID', 'Student', 'Course', 'Tutor',\n 'Last submission date']\n subs = subs[headings]\n # Sort by Last submission date\n subs = subs.sort_values(['Tutor', 'Last submission date'])\n # Save a master file\n f_name = 'Submitted_All_{}{}.xls'.format(period, ft.generate_time_string())\n subs.to_excel(f_name, index=False)\n print('\\nSubmitted_All_ has been saved to {}'.format(f_name))\n ft.process_warning_log(warnings, warnings_to_process)", "def bid_update_data(file_path: str) -> pd.DataFrame:\n with open(file_path, 'r') as f:\n data = json.load(f)\n\n max_dispatch = [0] * len(data['data']['assets'][0]['maximum_dispatch_schedule'])\n for t, _ in enumerate(data['data']['assets'][0]['maximum_dispatch_schedule']):\n for ast_num, _ in enumerate(data['data']['assets']):\n max_dispatch[t] += data['data']['assets'][ast_num]['maximum_dispatch_schedule'][t][\n 'maximum_dispatch']\n\n load_reduction = []\n reference_load = []\n start_time = []\n\n for _, dct in enumerate(data['data']['meter_point_schedule']):\n load_reduction.append(dct['load_reduction'])\n reference_load.append(dct['reference_load'])\n start_time.append(datetime.datetime.fromisoformat(dct['start_time']))\n\n df = pd.DataFrame(data=start_time, columns=['Start Time'])\n df['Max Dispatch'] = max_dispatch\n df['Load Reduction'] = load_reduction\n df['Reference Load'] = reference_load\n df['Date'] = [i.date() for i in start_time]\n df['Time'] = [i.time() for i in start_time]\n\n asset_id = []\n asset_max_dptch = []\n for i, dct in enumerate(data['data']['assets']):\n asset_id.append(dct['id'])\n asset_max_dptch.append([dct['maximum_dispatch_schedule'][md]['maximum_dispatch'] for md in\n range(len(dct['maximum_dispatch_schedule']))])\n\n for i in range(len(asset_id)):\n df[asset_id[i] + 'bu'] = asset_max_dptch[i]\n\n return df", "def read_pandas(run, infile):\n if infile is None:\n hfile = \"{}/hdf5/mjd_run{}.h5\".format(os.environ[\"MJDDATADIR\"], run)\n else:\n hfile = infile\n\n with pd.HDFStore(hfile,'r') as f:\n keys = f.keys()\n\n print(\"Reading file: {}\\nFound keys: {}\".format(hfile, keys))\n\n df_evts = pd.read_hdf(hfile, key=\"events\") # event-level data\n df_hits = pd.read_hdf(hfile, key=\"hits\") # hit-level data\n df_waves = pd.read_hdf(hfile, key=\"waves\") # waveform data\n df_waves.reset_index(inplace=True) # required step -- fix hdf5 \"append\"\n\n print(df_evts)\n print(df_hits)\n print(df_waves)\n # print(df_evts.columns)\n\n # align skim file dataframes to create a \"lookup list\"\n if infile is not None and \"skim\" in infile:\n df1 = df_evts[[\"run\", \"mH\", \"iEvent\"]]\n df2 = df_hits[[\"iHit\", \"channel\"]]\n tmp = df1.align(df2, axis=0) # returns a tuple\n df_skim = pd.concat(tmp, axis=1)\n # df_skim = pd.merge(df_evts, df_hits) # doesn't work, no common columns\n else:\n # align gatified dataframes\n tmp = df_evts.align(df_hits, axis=0)\n df_skim = pd.concat(tmp, axis=1)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reads the most recent grades file for the given section into a Pandas DataFrame.
def get_grades( base_directory: str, section_id: int, nrows: Union[int, None] = None ) -> pd.DataFrame: file = fr.get_grades_file(base_directory, section_id) if file is not None: return _read_csv(file, nrows) return _default()
[ "def get_all_grades(\r\n base_directory: str, sections: pd.DataFrame, nrows: Union[int, None] = None\r\n) -> pd.DataFrame:\r\n return _get_data_for_section(base_directory, sections, get_grades, nrows)", "def _read(self, profile_filename):\n # header=0 because docs say to if using skip rows and columns\n df = pd.read_csv(profile_filename, header=0,\n skiprows=self.hdr.header_pos,\n names=self.hdr.columns,\n encoding='latin')\n\n # Special SMP specific tasks\n depth_fmt = 'snow_height'\n is_smp = False\n if 'force' in df.columns:\n # Convert depth from mm to cm\n df['depth'] = df['depth'].div(10)\n is_smp = True\n # Make the data negative from snow surface\n depth_fmt = 'surface_datum'\n\n # SMP serial number and original filename for provenance to the comment\n f = basename(profile_filename)\n serial_no = f.split('SMP_')[-1][1:3]\n\n df['comments'] = f\"fname = {f}, \" \\\n f\"serial no. = {serial_no}\"\n\n # Standardize all depth data\n new_depth = standardize_depth(df['depth'],\n desired_format=depth_fmt,\n is_smp=is_smp)\n\n if 'bottom_depth' in df.columns:\n delta = df['depth'] - new_depth\n df['bottom_depth'] = df['bottom_depth'] - delta\n\n df['depth'] = new_depth\n\n delta = abs(df['depth'].max() - df['depth'].min())\n self.log.info('File contains {} profiles each with {} layers across '\n '{:0.2f} cm'.format(len(self.hdr.data_names), len(df), delta))\n return df", "def get_assignments(\r\n base_directory: str, section_id: int, nrows: Union[int, None] = None\r\n) -> pd.DataFrame:\r\n file = fr.get_assignments_file(base_directory, section_id)\r\n\r\n if file is not None:\r\n return _read_csv(file, nrows)\r\n\r\n return _default()", "def read_grade_data(file_name, STUDENTS):\n\n\tgdf = pd.read_csv(file_name, header=None)\n\tkey = gdf[gdf.columns[0]] # student ID column\n\tgrades = gdf[gdf.columns[1]] # Grade column\n\t\n\tGRADES = {}\n\ti = 0\n\tfor s in STUDENTS:\n\t GRADES[s] = grades[i] # doing this key so that it matches with STUDENTS\n\t i += 1\n\n\treturn GRADES", "def get_submissions(\r\n base_directory: str,\r\n section_id: int,\r\n assignment_id: int,\r\n nrows: Union[int, None] = None,\r\n) -> pd.DataFrame:\r\n file = fr.get_submissions_file(base_directory, section_id, assignment_id)\r\n\r\n if file is not None:\r\n return _read_csv(file, nrows)\r\n\r\n return _default()", "def get_attendance_events(\r\n base_directory: str, section_id: int, nrows: Union[int, None] = None\r\n) -> pd.DataFrame:\r\n file = fr.get_attendance_events_file(base_directory, section_id)\r\n\r\n if file is not None:\r\n return _read_csv(file, nrows)\r\n\r\n return _default()", "def readgra(self) -> None:\n path :str = os.path.join(self.directory_path,\"grades.txt\")\n for stucwid, coursename, grade, instcwid in file_reader(path, 4, sep='\\t',header=True): \n if stucwid not in self.studict.keys():\n print(f\" There is no Student with CWID: {stucwid}\")\n continue\n if instcwid not in self.instdict.keys():\n print(f\" There is no Instructor with CWID: {instcwid}\")\n continue\n self.studict[stucwid].set_courses(coursename,grade)\n self.instdict[instcwid].set_courses(coursename)", "def get_section_associations(\r\n base_directory: str, section_id: int, nrows: Union[int, None] = None\r\n) -> pd.DataFrame:\r\n file = fr.get_section_associations_file(base_directory, section_id)\r\n\r\n if file is not None:\r\n return _read_csv(file, nrows)\r\n\r\n return _default()", "def get_tab_as_df_or_empty_df_with_index(file):\n\n nlines = len([l for l in open(file, \"r\").readlines() if len(l)>1])\n\n if nlines==0: return pd.DataFrame()\n else: return pd.read_csv(file, sep=\"\\t\", index_col=0)", "def bed_to_df(bed_file):\n header_lines = 0\n #Handle likely header by checking colums 2 and 3 as numbers\n with open(bed_file, 'r') as f:\n next_line = f.readline().strip()\n line_split = next_line.split(None) #This split by any blank character\n start = line_split[1]\n end = line_split[2]\n while not start.isdigit() and not end.isdigit():\n header_lines = header_lines + 1\n next_line = f.readline().strip()\n line_split = next_line.split(None) #This split by any blank character\n start = line_split[1]\n end = line_split[2]\n\n if header_lines == 0:\n dataframe = pd.read_csv(bed_file, sep=\"\\t\", header=None) #delim_whitespace=True\n else:\n dataframe = pd.read_csv(bed_file, sep=\"\\t\", skiprows=header_lines, header=None) #delim_whitespace=True\n if dataframe.shape[1] == 3:\n dataframe['description'] = True\n dataframe.columns = [\"#CHROM\", \"start\", \"end\", \"description\"]\n else:\n dataframe.columns = [\"#CHROM\", \"start\", \"end\", \"description\"]\n \n return dataframe", "def get_school(self, columns):\n df = pd.read_csv('./data/school.zip', header=None, nrows=self.nrows)\n df.columns = columns['school']\n\n return df", "def extract_grades(input_file, left_side):\n \n # Load your PDF\n with open(input_file, \"rb\") as f:\n \n pdf = pdftotext.PDF(f)\n \n semester = re.findall(r'\\n +([A-Z][a-z]+ \\d{4}|Transfer Work|Summer .{1,2} \\d{4})',pdf[0])\n grades = re.findall(r'\\n {0,1}LAW +(\\w{3}) +' # class number\n r'(.+?) +?' # class name\n r'(\\d{1,2})[.]\\d\\d' # number of credit hours\n r'(.*)', # class letter grade \n pdf[0])\n new_lines = re.findall(r'\\n {0,1}LAW|\\n +Term|\\n *---', pdf[0])\n semesters = left_classes_per_semester(new_lines, semester)\n \n df = pd.DataFrame(grades, columns=['class_num', 'class_name', 'credits', 'grade'])\n\n # some classes don't have semesters (law review / moot court)\n # add 'no semester' value to end of semester list for the difference\n # in length between the number of total classes in the dataframe \n # and number of semester classes, if the two are different\n if len(df) != len(semesters):\n\n # calculate the number of no semester classes\n num_no_semester = len(df) - len(semesters)\n \n # create list with phrase 'no semester' for this length\n no_semester = ['no semester'] * num_no_semester\n\n # add this list to the end of the semeter list\n semesters.extend(no_semester)\n \n # semesters will be separated into semster and year post processing\n df['semester'] = semesters\n \n # the left side includes the name, so if we are scraping the right side\n # pull the name and include it in the dataframe\n if left_side:\n \n name = re.search(r' \\d{4}\\n +(.+?, \\w+)', pdf[0])\n \n # name will be separated into first and last post-processing\n df['name'] = name.group(1)\n \n return df", "def get_section_activities(\r\n base_directory: str, section_id: int, nrows: Union[int, None] = None\r\n) -> pd.DataFrame:\r\n file = fr.get_section_activities_file(base_directory, section_id)\r\n\r\n if file is not None:\r\n return _read_csv(file, nrows)\r\n\r\n return _default()", "def load_data_impl() -> pd.DataFrame:\n # The source for this file is at https://ssd.jpl.nasa.gov/?sb_elem\n fname: str = '../jpl/orb_elements_asteroid.txt'\n\n # The field names in the JPL file and their column positions\n names: List[str] = ['Num', 'Name', 'Epoch', 'a', 'e', 'i', 'w', 'Node', 'M', 'H', 'G', 'Ref']\n colspec_tbl: Dict[str, Tuple[int, int]] = {\n 'Num': (0,6), \n 'Name': (7, 25), \n 'Epoch': (25, 30), \n 'a': (31, 41), \n 'e': (42, 52), \n 'i': (54, 62), \n 'w': (63, 72),\n 'Node': (73, 82),\n 'M': (83, 94),\n 'H': (95, 100),\n 'G': (101, 105),\n 'Ref': (106, 113),\n }\n \n # Other arguments for Pandas file import\n colspecs: List[Tuple[int, int]] = [colspec_tbl[nm] for nm in names]\n header: int = 0\n skiprows: List[int] = [1]\n dtype: Dict[str, int] = {\n 'Num': int,\n 'Name': str,\n 'Epoch': float,\n 'a': float,\n 'e': float,\n 'i': float,\n 'w': float,\n 'Node': float,\n 'M': float,\n 'H': float,\n 'G': float,\n 'Ref': str,\n }\n\n # Read the DataFrame\n df: pd.DataFrame = pd.read_fwf(fname, colspecs=colspecs, header=header, names=names, skiprows=skiprows, dtype=dtype)\n # Set the asteroid number field to be the index\n df.set_index(keys=['Num'], drop=False, inplace=True)\n return df", "def load_raw_eeg(participants_index):\n if insight:\n eeg_path = os.path.join(configuration.get('insight_raw_data_path'), str(participants_index)+\"\\\\eeg.csv\")\n\n eeg_df = pd.read_csv(eeg_path)\n print(\"Shape of eeg file: \", eeg_df.shape)\n\n eeg_df = pd.DataFrame(eeg_df[['COUNTER', 'AF3', 'AF4', 'T7', 'T8']])\n else:\n eeg_path = os.path.join(configuration.get('epoc_raw_data_path'), str(participants_index)+\"\\\\eeg.csv\")\n\n eeg_df = pd.read_csv(eeg_path)\n print(\"Shape of eeg file: \", eeg_df.shape)\n\n eeg_df = pd.DataFrame(eeg_df[['COUNTER', 'F3', 'F4', 'AF3', 'AF4', 'F7', 'F8',\n 'FC5', 'FC6', 'T7', 'T8', 'P7', 'P8', 'O1', 'O2']])\n\n return eeg_df", "def parse_samplesheet(samplesheet: Path) -> pd.DataFrame:\n counter = 1\n with open(str(samplesheet)) as f:\n for line in f:\n if '[Data]' in line:\n break\n else:\n counter += 1\n df = pd.read_csv(samplesheet, sep=\",\", index_col=False, skiprows=counter)\n return df", "def get_school_profile(self, columns):\n df = pd.read_csv('./data/school-profile.zip', header=None, nrows=self.nrows)\n df.columns = columns['school_profile']\n\n return df", "def get_events_from_study_guide(filename):\n\n df = get_df_from_pdf(filename)\n\n due_column = df.columns[-1] # Usually \"Due\" or \"Due Date\"\n\n # slice df only where df[due_column] is not empty, then save to_dict,\n # orient='records' to create a separate dict with all keys for each event\n assignments = df[df[due_column].apply(is_empty)].to_dict(orient='records')\n\n events = []\n for hw in assignments:\n title = 'Section ' + hw['Section']\n desc = hw['Topic'].replace('\\n', '') + ' --- Problems: ' \\\n + hw['Exercises'].replace('\\n', '')\n date = get_assignment_datetime(hw[due_column])\n\n event = {\n \"title\": title,\n \"description\": desc,\n \"begin\": date,\n }\n\n events.append(event)\n\n return events", "def read_in_sequencing_summary(summary_path):\n data = pd.read_csv(summary_path, sep=\"\\t\")\n return data" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reads the most recent grades files for all given sections into a Pandas DataFrame.
def get_all_grades( base_directory: str, sections: pd.DataFrame, nrows: Union[int, None] = None ) -> pd.DataFrame: return _get_data_for_section(base_directory, sections, get_grades, nrows)
[ "def get_grades(\r\n base_directory: str, section_id: int, nrows: Union[int, None] = None\r\n) -> pd.DataFrame:\r\n file = fr.get_grades_file(base_directory, section_id)\r\n\r\n if file is not None:\r\n return _read_csv(file, nrows)\r\n\r\n return _default()", "def get_all_assignments(\r\n base_directory: str, sections: pd.DataFrame, nrows: Union[int, None] = None\r\n) -> pd.DataFrame:\r\n return _get_data_for_section(base_directory, sections, get_assignments, nrows)", "def get_assignments(\r\n base_directory: str, section_id: int, nrows: Union[int, None] = None\r\n) -> pd.DataFrame:\r\n file = fr.get_assignments_file(base_directory, section_id)\r\n\r\n if file is not None:\r\n return _read_csv(file, nrows)\r\n\r\n return _default()", "def get_all_attendance_events(\r\n base_directory: str, sections: pd.DataFrame, nrows: Union[int, None] = None\r\n) -> pd.DataFrame:\r\n return _get_data_for_section(base_directory, sections, get_attendance_events, nrows)", "def get_submissions(\r\n base_directory: str,\r\n section_id: int,\r\n assignment_id: int,\r\n nrows: Union[int, None] = None,\r\n) -> pd.DataFrame:\r\n file = fr.get_submissions_file(base_directory, section_id, assignment_id)\r\n\r\n if file is not None:\r\n return _read_csv(file, nrows)\r\n\r\n return _default()", "def extract_grades(input_file, left_side):\n \n # Load your PDF\n with open(input_file, \"rb\") as f:\n \n pdf = pdftotext.PDF(f)\n \n semester = re.findall(r'\\n +([A-Z][a-z]+ \\d{4}|Transfer Work|Summer .{1,2} \\d{4})',pdf[0])\n grades = re.findall(r'\\n {0,1}LAW +(\\w{3}) +' # class number\n r'(.+?) +?' # class name\n r'(\\d{1,2})[.]\\d\\d' # number of credit hours\n r'(.*)', # class letter grade \n pdf[0])\n new_lines = re.findall(r'\\n {0,1}LAW|\\n +Term|\\n *---', pdf[0])\n semesters = left_classes_per_semester(new_lines, semester)\n \n df = pd.DataFrame(grades, columns=['class_num', 'class_name', 'credits', 'grade'])\n\n # some classes don't have semesters (law review / moot court)\n # add 'no semester' value to end of semester list for the difference\n # in length between the number of total classes in the dataframe \n # and number of semester classes, if the two are different\n if len(df) != len(semesters):\n\n # calculate the number of no semester classes\n num_no_semester = len(df) - len(semesters)\n \n # create list with phrase 'no semester' for this length\n no_semester = ['no semester'] * num_no_semester\n\n # add this list to the end of the semeter list\n semesters.extend(no_semester)\n \n # semesters will be separated into semster and year post processing\n df['semester'] = semesters\n \n # the left side includes the name, so if we are scraping the right side\n # pull the name and include it in the dataframe\n if left_side:\n \n name = re.search(r' \\d{4}\\n +(.+?, \\w+)', pdf[0])\n \n # name will be separated into first and last post-processing\n df['name'] = name.group(1)\n \n return df", "def get_attendance_events(\r\n base_directory: str, section_id: int, nrows: Union[int, None] = None\r\n) -> pd.DataFrame:\r\n file = fr.get_attendance_events_file(base_directory, section_id)\r\n\r\n if file is not None:\r\n return _read_csv(file, nrows)\r\n\r\n return _default()", "def get_all_section_associations(\r\n base_directory: str, sections: pd.DataFrame, nrows: Union[int, None] = None\r\n) -> pd.DataFrame:\r\n return _get_data_for_section(\r\n base_directory, sections, get_section_associations, nrows\r\n )", "def readgra(self) -> None:\n path :str = os.path.join(self.directory_path,\"grades.txt\")\n for stucwid, coursename, grade, instcwid in file_reader(path, 4, sep='\\t',header=True): \n if stucwid not in self.studict.keys():\n print(f\" There is no Student with CWID: {stucwid}\")\n continue\n if instcwid not in self.instdict.keys():\n print(f\" There is no Instructor with CWID: {instcwid}\")\n continue\n self.studict[stucwid].set_courses(coursename,grade)\n self.instdict[instcwid].set_courses(coursename)", "def get_all_section_activities(\r\n base_directory: str, sections: pd.DataFrame, nrows: Union[int, None] = None\r\n) -> pd.DataFrame:\r\n return _get_data_for_section(\r\n base_directory, sections, get_section_activities, nrows\r\n )", "def df_from_files(self):\n print('Creating dataframe...')\n num = len([name for name in os.listdir(self.raw) if not name[0] == '.'])\n files = os.path.join(self.raw, '~.info.json') # This is a weird hack\n files = files.replace('~', '{:05d}') # It allows path joining to work on Windows\n data = [json.load(open(files.format(i))) for i in range(1, num + 1)]\n\n columns = ['formats', 'tags', 'categories', 'thumbnails']\n lists = [[], [], [], []]\n deletes = {k: v for k, v in zip(columns, lists)}\n for dt in data:\n for col, ls in deletes.items():\n ls.append(dt[col])\n del dt[col]\n\n self.df = pd.DataFrame(data)\n self.df['upload_date'] = pd.to_datetime(self.df['upload_date'], format='%Y%m%d')\n self.df.to_csv(os.path.join(self.ran, 'df.csv'))\n\n self.tags = deletes['tags']\n pickle.dump(self.tags, open(os.path.join(self.ran, 'tags.txt'), 'wb'))", "def load_all_marks_df():\n combined_marks_df = pd.DataFrame()\n df_filename_list = get_marks_df_list()\n utils.sts(f\"Total of {len(df_filename_list)} marks_df chunks detected.\", 3)\n for df_file in df_filename_list:\n marks_df = load_one_marks_df(df_file)\n combined_marks_df = combined_marks_df.append(marks_df, sort=False, ignore_index=True)\n utils.sts(f\"appended {df_file} chunk, {len(marks_df.index)} records, total of {len(combined_marks_df.index)} records.\", 3)\n return combined_marks_df", "def fetch_grades(self) -> None:\n try:\n for Student_CWID, Course, Letter_Grade, Instr_CWID in file_reader(os.path.join(self.file_path, \"grades.txt\"), 4, sep='\\t', header=False):\n # Check if student exists\n if Student_CWID in self.all_students:\n add_grade_Student: Student = self.all_students[Student_CWID]\n else:\n raise KeyError(\n f\"ERROR! No student with the CWID: {Student_CWID}\")\n # Check if instructor exists\n if Instr_CWID in self.all_instructors:\n add_course_Instr: Instructor = self.all_instructors[Instr_CWID]\n else:\n raise KeyError(\n f\"ERROR! No instructor with the CWID: {Instr_CWID}\")\n\n # Add course and grade to student record\n add_grade_Student.class_taken(Course, Letter_Grade)\n\n # Add course to instructor record\n add_course_Instr.add_course_and_student(Course)\n except FileNotFoundError:\n raise FileNotFoundError(f\"ERROR! File not found\")\n except ValueError:\n raise ValueError(\"ERROR! Some inputs or data may be incorrect \")", "def get_section_associations(\r\n base_directory: str, section_id: int, nrows: Union[int, None] = None\r\n) -> pd.DataFrame:\r\n file = fr.get_section_associations_file(base_directory, section_id)\r\n\r\n if file is not None:\r\n return _read_csv(file, nrows)\r\n\r\n return _default()", "def get_events_from_study_guide(filename):\n\n df = get_df_from_pdf(filename)\n\n due_column = df.columns[-1] # Usually \"Due\" or \"Due Date\"\n\n # slice df only where df[due_column] is not empty, then save to_dict,\n # orient='records' to create a separate dict with all keys for each event\n assignments = df[df[due_column].apply(is_empty)].to_dict(orient='records')\n\n events = []\n for hw in assignments:\n title = 'Section ' + hw['Section']\n desc = hw['Topic'].replace('\\n', '') + ' --- Problems: ' \\\n + hw['Exercises'].replace('\\n', '')\n date = get_assignment_datetime(hw[due_column])\n\n event = {\n \"title\": title,\n \"description\": desc,\n \"begin\": date,\n }\n\n events.append(event)\n\n return events", "def read_grade_data(file_name, STUDENTS):\n\n\tgdf = pd.read_csv(file_name, header=None)\n\tkey = gdf[gdf.columns[0]] # student ID column\n\tgrades = gdf[gdf.columns[1]] # Grade column\n\t\n\tGRADES = {}\n\ti = 0\n\tfor s in STUDENTS:\n\t GRADES[s] = grades[i] # doing this key so that it matches with STUDENTS\n\t i += 1\n\n\treturn GRADES", "def _read(self, profile_filename):\n # header=0 because docs say to if using skip rows and columns\n df = pd.read_csv(profile_filename, header=0,\n skiprows=self.hdr.header_pos,\n names=self.hdr.columns,\n encoding='latin')\n\n # Special SMP specific tasks\n depth_fmt = 'snow_height'\n is_smp = False\n if 'force' in df.columns:\n # Convert depth from mm to cm\n df['depth'] = df['depth'].div(10)\n is_smp = True\n # Make the data negative from snow surface\n depth_fmt = 'surface_datum'\n\n # SMP serial number and original filename for provenance to the comment\n f = basename(profile_filename)\n serial_no = f.split('SMP_')[-1][1:3]\n\n df['comments'] = f\"fname = {f}, \" \\\n f\"serial no. = {serial_no}\"\n\n # Standardize all depth data\n new_depth = standardize_depth(df['depth'],\n desired_format=depth_fmt,\n is_smp=is_smp)\n\n if 'bottom_depth' in df.columns:\n delta = df['depth'] - new_depth\n df['bottom_depth'] = df['bottom_depth'] - delta\n\n df['depth'] = new_depth\n\n delta = abs(df['depth'].max() - df['depth'].min())\n self.log.info('File contains {} profiles each with {} layers across '\n '{:0.2f} cm'.format(len(self.hdr.data_names), len(df), delta))\n return df", "def get_school(self, columns):\n df = pd.read_csv('./data/school.zip', header=None, nrows=self.nrows)\n df.columns = columns['school']\n\n return df", "def read_files(file):\n # TODO Fix search into the dictionary for increased speed\n file_path, filename = rename_to_text(file)\n print('\\n\\n')\n print(file_path)\n print('\\n\\n')\n # find the exposure (L)\n # langmuir.append(langmuir_determination(filename=filename))\n try:\n # read file\n file_read = pd.read_csv(file_path, sep='\\t', header=3)\n\n # remove whitespace\n column_names = [file_read.keys()[i].lstrip() for i in range(0, len(file_read.keys()))]\n # rename columns\n file_read.columns = column_names\n # drop the time column and mse=8\n # file_read = file_read.drop([column_names[0], column_names[-1]], axis=1)\n file_read = file_read.drop([column_names[0]], axis=1)\n temp = file_read[file_read != 0]\n temp = temp.dropna(axis=0)\n\n\n file_read = file_read.dropna(axis=1)\n\n # for the bug in the labview that the temperature cuts out\n temp = file_read[file_read != 0]\n file_read = temp.dropna(axis=0)\n\n # set the index to be temperature\n file_read = file_read.set_index(file_read.keys()[0])\n except IndexError:\n \"except it is a hiden mass spec file!\"\n file_read = pd.read_csv(file_path, header=29)\n file_read = file_read.dropna(axis=1)\n file_read.drop(['Time', 'ms'],axis=1, inplace=True)\n file_read.set_index('Temperature', inplace=True)\n # pseudo code...\n # pd.DataFrame(molecule_area[i], index=langmuir) and append all of them\n\n return file_read, filename" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reads the most recent attendance events file for the given section into a Pandas DataFrame.
def get_attendance_events( base_directory: str, section_id: int, nrows: Union[int, None] = None ) -> pd.DataFrame: file = fr.get_attendance_events_file(base_directory, section_id) if file is not None: return _read_csv(file, nrows) return _default()
[ "def get_all_attendance_events(\r\n base_directory: str, sections: pd.DataFrame, nrows: Union[int, None] = None\r\n) -> pd.DataFrame:\r\n return _get_data_for_section(base_directory, sections, get_attendance_events, nrows)", "def get_events_from_study_guide(filename):\n\n df = get_df_from_pdf(filename)\n\n due_column = df.columns[-1] # Usually \"Due\" or \"Due Date\"\n\n # slice df only where df[due_column] is not empty, then save to_dict,\n # orient='records' to create a separate dict with all keys for each event\n assignments = df[df[due_column].apply(is_empty)].to_dict(orient='records')\n\n events = []\n for hw in assignments:\n title = 'Section ' + hw['Section']\n desc = hw['Topic'].replace('\\n', '') + ' --- Problems: ' \\\n + hw['Exercises'].replace('\\n', '')\n date = get_assignment_datetime(hw[due_column])\n\n event = {\n \"title\": title,\n \"description\": desc,\n \"begin\": date,\n }\n\n events.append(event)\n\n return events", "def get_section_activities(\r\n base_directory: str, section_id: int, nrows: Union[int, None] = None\r\n) -> pd.DataFrame:\r\n file = fr.get_section_activities_file(base_directory, section_id)\r\n\r\n if file is not None:\r\n return _read_csv(file, nrows)\r\n\r\n return _default()", "def get_section_associations(\r\n base_directory: str, section_id: int, nrows: Union[int, None] = None\r\n) -> pd.DataFrame:\r\n file = fr.get_section_associations_file(base_directory, section_id)\r\n\r\n if file is not None:\r\n return _read_csv(file, nrows)\r\n\r\n return _default()", "def load_events_data(path='data/active1000', num_days=None):\n df = read_event_data(path, num_days)\n df = df[df['documentId'].notnull()]\n df.loc[:, (\"publishtime\")] = pd.to_datetime(df.publishtime)\n return df", "def load_data(self):\n self.event_df = pd.DataFrame({'Time': [0.1, 0.2, 0.3, 0.4, 0.5],\n '1_sig': [1, 2, 3, 4, 5],\n '2_sig': [2, 5, 6, 7, 9]})", "def import_events(fileName):\n \n try:\n file = open(fileName, \"rb\")\n except:\n errorString = \"Error while reading file {} , file doesn't exist: \".format(fileName)\n raise NameError(errorString)\n \n done_reading = False\n \n # skip comment header of file\n skip_header(file)\n \n # prepare lists\n core_id_tot = []\n chip_id_tot = []\n neuron_id_tot = []\n ts_tot = []\n # special events\n spec_type_tot = []\n spec_ts_tot = []\n \n while(done_reading == False): # cycle on all the packets inside the file\n try:\n core_id, chip_id, neuron_id, ts, spec_type, spec_ts = read_packet(file)\n core_id_tot.extend(np.array(core_id))\n chip_id_tot.extend(np.array(chip_id))\n neuron_id_tot.extend(np.array(neuron_id))\n ts_tot.extend(np.array(ts))\n spec_type_tot.extend(np.array(spec_type))\n spec_ts_tot.extend(np.array(spec_ts))\n except NameError:\n file.close()\n done_reading = True\n \n \n # make all arrays\n core_id_tot = np.array(core_id_tot)\n chip_id_tot = np.array(chip_id_tot)\n neuron_id_tot = np.array(neuron_id_tot)\n ts_tot = np.array(ts_tot)\n\n return EventsSet(ts_tot, chip_id_tot, core_id_tot, neuron_id_tot)", "def get_all_section_activities(\r\n base_directory: str, sections: pd.DataFrame, nrows: Union[int, None] = None\r\n) -> pd.DataFrame:\r\n return _get_data_for_section(\r\n base_directory, sections, get_section_activities, nrows\r\n )", "def read_pandas(run, infile):\n if infile is None:\n hfile = \"{}/hdf5/mjd_run{}.h5\".format(os.environ[\"MJDDATADIR\"], run)\n else:\n hfile = infile\n\n with pd.HDFStore(hfile,'r') as f:\n keys = f.keys()\n\n print(\"Reading file: {}\\nFound keys: {}\".format(hfile, keys))\n\n df_evts = pd.read_hdf(hfile, key=\"events\") # event-level data\n df_hits = pd.read_hdf(hfile, key=\"hits\") # hit-level data\n df_waves = pd.read_hdf(hfile, key=\"waves\") # waveform data\n df_waves.reset_index(inplace=True) # required step -- fix hdf5 \"append\"\n\n print(df_evts)\n print(df_hits)\n print(df_waves)\n # print(df_evts.columns)\n\n # align skim file dataframes to create a \"lookup list\"\n if infile is not None and \"skim\" in infile:\n df1 = df_evts[[\"run\", \"mH\", \"iEvent\"]]\n df2 = df_hits[[\"iHit\", \"channel\"]]\n tmp = df1.align(df2, axis=0) # returns a tuple\n df_skim = pd.concat(tmp, axis=1)\n # df_skim = pd.merge(df_evts, df_hits) # doesn't work, no common columns\n else:\n # align gatified dataframes\n tmp = df_evts.align(df_hits, axis=0)\n df_skim = pd.concat(tmp, axis=1)", "def load_raw_eeg(participants_index):\n if insight:\n eeg_path = os.path.join(configuration.get('insight_raw_data_path'), str(participants_index)+\"\\\\eeg.csv\")\n\n eeg_df = pd.read_csv(eeg_path)\n print(\"Shape of eeg file: \", eeg_df.shape)\n\n eeg_df = pd.DataFrame(eeg_df[['COUNTER', 'AF3', 'AF4', 'T7', 'T8']])\n else:\n eeg_path = os.path.join(configuration.get('epoc_raw_data_path'), str(participants_index)+\"\\\\eeg.csv\")\n\n eeg_df = pd.read_csv(eeg_path)\n print(\"Shape of eeg file: \", eeg_df.shape)\n\n eeg_df = pd.DataFrame(eeg_df[['COUNTER', 'F3', 'F4', 'AF3', 'AF4', 'F7', 'F8',\n 'FC5', 'FC6', 'T7', 'T8', 'P7', 'P8', 'O1', 'O2']])\n\n return eeg_df", "def fetchFromOutpatientDataset(self) -> pd.DataFrame:\n dataframe_list = []\n for i in self.subset_list:\n data_outpatient_claims = pd.read_csv(\n f\"..\\input\\DE1.0 Sample{i}\\DE1_0_2008_to_2010_Outpatient_Claims_Sample_{i}.zip\",\n parse_dates=[\"CLM_FROM_DT\", \"CLM_THRU_DT\",],\n infer_datetime_format=True,\n )\n dataframe_list.append(data_outpatient_claims)\n\n final_outpatient_data = pd.concat(dataframe_list, axis=0)\n\n return final_outpatient_data", "def read_clickstream_data() -> pd.DataFrame:\n df1 = read_data_with_columns(r'data/interim/clickstream/clickstream_data.csv', r'data/raw/clickstream/clickstream_columns.txt')\n df2 = read_data_with_columns(r'data/raw/clickstream/clickstream_data_part_2.csv', r'data/raw/clickstream/clickstream_columns.txt')\n combined_clickstream_df = pd.concat([df1, df2])\n return combined_clickstream_df", "def get_section_df(self, track_id):\n analysis_res = self.si.analysis(track_id)\n # bars, beats, sections, segments, tatums\n sections_df = pd.DataFrame(analysis_res[\"sections\"])\n sections_df = sections_df[[\"start\", \"duration\", \"loudness\", \"tempo\", \"key\", \"mode\"]]\n sections_df[\"duration\"] = sections_df[\"duration\"] / sum(sections_df[\"duration\"])\n sections_df[\"loudness\"] = sections_df[\"loudness\"].apply(lambda x: abs(x))\n sections_df[\"loudness\"] = sections_df[\"loudness\"] / sum(sections_df[\"loudness\"])\n return sections_df", "def get_events(event_dir, games):\n events = pd.DataFrame\n\n # go through each game and get events\n for game in games:\n if events.empty:\n events = pd.read_csv('%s/%s.csv' % (event_dir, game))\n else:\n game_events = pd.read_csv('%s/%s.csv' % (event_dir, game))\n events.append(game_events)\n\n events['GAME_ID'] = '00' + events['GAME_ID'].astype(int).astype(str)\n\n return events", "def import_events(self, fname):\n if fname.lower().endswith(\".csv\"):\n pos, desc = [], []\n with open(fname) as f:\n f.readline() # skip header\n for line in f:\n p, d = [int(token.strip()) for token in line.split(\",\")]\n pos.append(p)\n desc.append(d)\n events = np.column_stack((pos, desc))\n events = np.insert(events, 1, 0, axis=1) # insert zero column\n if self.current[\"events\"] is not None:\n events = np.row_stack((self.current[\"events\"], events))\n events = np.unique(events, axis=0)\n self.current[\"events\"] = events\n elif fname.lower().endswith(\".fif\"):\n self.current[\"events\"] = mne.read_events(fname)\n else:\n raise ValueError(f\"Unsupported event file: {fname}\")", "def read_ROOT_file(filename): \n file = uproot.open(filename)\n tree = file[\"simpleEvent\"]\n Tracks = tree.arrays(['Tracks'])\n SingleTrack = tree.arrays(['SingleTrack'])\n df = pd.DataFrame.from_dict(Tracks[b'Tracks'])\n return df[SingleTrack[b'SingleTrack']==1].copy()", "def read(read_events: bool = True, read_activities: bool = True, read_timetable: bool = False,\n event_file_name: str = \"\", activity_file_name: str = \"\", timetable_file_name: str = \"\",\n periodic_ean: Graph[PeriodicEvent, PeriodicActivity]=None, periodic_timetable: PeriodicTimetable = None,\n time_units_per_minute: int = None, period_length: int = None, config: Config = Config.getDefaultConfig()) \\\n -> (Graph[PeriodicEvent, PeriodicActivity], PeriodicTimetable):\n if not periodic_ean:\n periodic_ean = SimpleDictGraph()\n if read_events and not event_file_name:\n event_file_name = config.getStringValue(\"default_events_periodic_file\")\n if read_activities and not activity_file_name:\n activity_file_name = config.getStringValue(\"default_activities_periodic_file\")\n if read_timetable and not timetable_file_name:\n timetable_file_name = config.getStringValue(\"default_timetable_periodic_file\")\n if read_timetable and not periodic_timetable:\n if not time_units_per_minute:\n time_units_per_minute = config.getIntegerValue(\"time_units_per_minute\")\n if not period_length:\n period_length = config.getIntegerValue(\"period_length\")\n periodic_timetable = PeriodicTimetable(time_units_per_minute, period_length)\n reader = PeriodicEANReader(activity_file_name, event_file_name,\n timetable_file_name, periodic_ean, periodic_timetable)\n\n if read_events:\n CsvReader.readCsv(event_file_name, reader.processPeriodicEvent)\n if read_activities:\n CsvReader.readCsv(activity_file_name, reader.processPeriodicActivity)\n if read_timetable:\n CsvReader.readCsv(timetable_file_name, reader.processPeriodicTimetable)\n return periodic_ean, periodic_timetable", "def load_data(name: str, location: str = SAVE_LOCATION) -> pd.DataFrame:\n df = pd.read_feather(location + name + '.feather')\n if 'date' in df.columns.values:\n df = df.set_index('date')\n return df", "def get_eaf_tier_as_df(eaf_fname, tier_id):\n tier_as_df = pd.DataFrame(columns=[tier_id, 'ts_ref1', 'ts_ref2'])\n\n tree = ET.parse(eaf_fname)\n root = tree.getroot()\n time_order = root.findall('TIME_ORDER')[0]\n\n # Create a dictionary for time slots (keys are time slots ids,\n # values are time values).\n time_slots = {}\n for time_slot in time_order:\n try:\n time_slots[time_slot.get('TIME_SLOT_ID')] = int(\n time_slot.get('TIME_VALUE'))\n except TypeError:\n continue\n\n # Create a pd.DataFrame containing all annotations in the tier.\n try:\n for annotation in root.findall(\"TIER[@TIER_ID=\\'\" + tier_id + \"\\']\") \\\n [0]:\n try:\n ts_ref1 = annotation.findall(\"ALIGNABLE_ANNOTATION\")[0].get(\n 'TIME_SLOT_REF1')\n ts_ref2 = annotation.findall(\"ALIGNABLE_ANNOTATION\")[0].get(\n 'TIME_SLOT_REF2')\n except TypeError:\n continue\n\n annotation_value = annotation.findall(\"./*ANNOTATION_VALUE\")[\n 0].text\n new_row = pd.DataFrame([{tier_id: annotation_value,\n 'ts_ref1': time_slots[ts_ref1],\n 'ts_ref2': time_slots[ts_ref2]}])\n tier_as_df = pd.concat([tier_as_df, new_row])\n except IndexError:\n print(\n 'The file {} does not seem to have a tier whose ID is \\'{}\\'.'\n .format(eaf_fname, tier_id))\n\n tier_as_df = tier_as_df.reset_index(drop=True)\n\n return tier_as_df" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reads the most recent attendance events files for all given sections into a Pandas DataFrame.
def get_all_attendance_events( base_directory: str, sections: pd.DataFrame, nrows: Union[int, None] = None ) -> pd.DataFrame: return _get_data_for_section(base_directory, sections, get_attendance_events, nrows)
[ "def get_attendance_events(\r\n base_directory: str, section_id: int, nrows: Union[int, None] = None\r\n) -> pd.DataFrame:\r\n file = fr.get_attendance_events_file(base_directory, section_id)\r\n\r\n if file is not None:\r\n return _read_csv(file, nrows)\r\n\r\n return _default()", "def get_events_from_study_guide(filename):\n\n df = get_df_from_pdf(filename)\n\n due_column = df.columns[-1] # Usually \"Due\" or \"Due Date\"\n\n # slice df only where df[due_column] is not empty, then save to_dict,\n # orient='records' to create a separate dict with all keys for each event\n assignments = df[df[due_column].apply(is_empty)].to_dict(orient='records')\n\n events = []\n for hw in assignments:\n title = 'Section ' + hw['Section']\n desc = hw['Topic'].replace('\\n', '') + ' --- Problems: ' \\\n + hw['Exercises'].replace('\\n', '')\n date = get_assignment_datetime(hw[due_column])\n\n event = {\n \"title\": title,\n \"description\": desc,\n \"begin\": date,\n }\n\n events.append(event)\n\n return events", "def get_all_section_activities(\r\n base_directory: str, sections: pd.DataFrame, nrows: Union[int, None] = None\r\n) -> pd.DataFrame:\r\n return _get_data_for_section(\r\n base_directory, sections, get_section_activities, nrows\r\n )", "def get_section_activities(\r\n base_directory: str, section_id: int, nrows: Union[int, None] = None\r\n) -> pd.DataFrame:\r\n file = fr.get_section_activities_file(base_directory, section_id)\r\n\r\n if file is not None:\r\n return _read_csv(file, nrows)\r\n\r\n return _default()", "def load_events_data(path='data/active1000', num_days=None):\n df = read_event_data(path, num_days)\n df = df[df['documentId'].notnull()]\n df.loc[:, (\"publishtime\")] = pd.to_datetime(df.publishtime)\n return df", "def get_events(event_dir, games):\n events = pd.DataFrame\n\n # go through each game and get events\n for game in games:\n if events.empty:\n events = pd.read_csv('%s/%s.csv' % (event_dir, game))\n else:\n game_events = pd.read_csv('%s/%s.csv' % (event_dir, game))\n events.append(game_events)\n\n events['GAME_ID'] = '00' + events['GAME_ID'].astype(int).astype(str)\n\n return events", "def fetchFromOutpatientDataset(self) -> pd.DataFrame:\n dataframe_list = []\n for i in self.subset_list:\n data_outpatient_claims = pd.read_csv(\n f\"..\\input\\DE1.0 Sample{i}\\DE1_0_2008_to_2010_Outpatient_Claims_Sample_{i}.zip\",\n parse_dates=[\"CLM_FROM_DT\", \"CLM_THRU_DT\",],\n infer_datetime_format=True,\n )\n dataframe_list.append(data_outpatient_claims)\n\n final_outpatient_data = pd.concat(dataframe_list, axis=0)\n\n return final_outpatient_data", "def load_data(self):\n self.event_df = pd.DataFrame({'Time': [0.1, 0.2, 0.3, 0.4, 0.5],\n '1_sig': [1, 2, 3, 4, 5],\n '2_sig': [2, 5, 6, 7, 9]})", "def load_event_datafile():\n # Get your current folder and subfolder event data\n filepath = os.getcwd() + '/event_data'\n\n # Create a for loop to create a list of files and collect each filepath\n for root, dirs, files in os.walk(filepath):\n\n # join the file path and roots with the subdirectories using glob\n file_path_list = glob.glob(os.path.join(root,'*'))\n \n # initiating an empty list of rows that will be generated from each file\n full_data_rows_list = [] \n num_files = len(file_path_list)\n \n # for every filepath in the file path list \n for f in file_path_list:\n\n # reading csv file \n with open(f, 'r', encoding = 'utf8', newline='') as csvfile: \n # creating a csv reader object \n csvreader = csv.reader(csvfile) \n next(csvreader)\n\n # extracting each data row one by one and append it \n for line in csvreader:\n full_data_rows_list.append(line)\n print(\"{} data files are loaded.\\n\".format(num_files))\n return full_data_rows_list", "def get_all_section_associations(\r\n base_directory: str, sections: pd.DataFrame, nrows: Union[int, None] = None\r\n) -> pd.DataFrame:\r\n return _get_data_for_section(\r\n base_directory, sections, get_section_associations, nrows\r\n )", "def read_pandas(run, infile):\n if infile is None:\n hfile = \"{}/hdf5/mjd_run{}.h5\".format(os.environ[\"MJDDATADIR\"], run)\n else:\n hfile = infile\n\n with pd.HDFStore(hfile,'r') as f:\n keys = f.keys()\n\n print(\"Reading file: {}\\nFound keys: {}\".format(hfile, keys))\n\n df_evts = pd.read_hdf(hfile, key=\"events\") # event-level data\n df_hits = pd.read_hdf(hfile, key=\"hits\") # hit-level data\n df_waves = pd.read_hdf(hfile, key=\"waves\") # waveform data\n df_waves.reset_index(inplace=True) # required step -- fix hdf5 \"append\"\n\n print(df_evts)\n print(df_hits)\n print(df_waves)\n # print(df_evts.columns)\n\n # align skim file dataframes to create a \"lookup list\"\n if infile is not None and \"skim\" in infile:\n df1 = df_evts[[\"run\", \"mH\", \"iEvent\"]]\n df2 = df_hits[[\"iHit\", \"channel\"]]\n tmp = df1.align(df2, axis=0) # returns a tuple\n df_skim = pd.concat(tmp, axis=1)\n # df_skim = pd.merge(df_evts, df_hits) # doesn't work, no common columns\n else:\n # align gatified dataframes\n tmp = df_evts.align(df_hits, axis=0)\n df_skim = pd.concat(tmp, axis=1)", "def import_events(fileName):\n \n try:\n file = open(fileName, \"rb\")\n except:\n errorString = \"Error while reading file {} , file doesn't exist: \".format(fileName)\n raise NameError(errorString)\n \n done_reading = False\n \n # skip comment header of file\n skip_header(file)\n \n # prepare lists\n core_id_tot = []\n chip_id_tot = []\n neuron_id_tot = []\n ts_tot = []\n # special events\n spec_type_tot = []\n spec_ts_tot = []\n \n while(done_reading == False): # cycle on all the packets inside the file\n try:\n core_id, chip_id, neuron_id, ts, spec_type, spec_ts = read_packet(file)\n core_id_tot.extend(np.array(core_id))\n chip_id_tot.extend(np.array(chip_id))\n neuron_id_tot.extend(np.array(neuron_id))\n ts_tot.extend(np.array(ts))\n spec_type_tot.extend(np.array(spec_type))\n spec_ts_tot.extend(np.array(spec_ts))\n except NameError:\n file.close()\n done_reading = True\n \n \n # make all arrays\n core_id_tot = np.array(core_id_tot)\n chip_id_tot = np.array(chip_id_tot)\n neuron_id_tot = np.array(neuron_id_tot)\n ts_tot = np.array(ts_tot)\n\n return EventsSet(ts_tot, chip_id_tot, core_id_tot, neuron_id_tot)", "def get_section_associations(\r\n base_directory: str, section_id: int, nrows: Union[int, None] = None\r\n) -> pd.DataFrame:\r\n file = fr.get_section_associations_file(base_directory, section_id)\r\n\r\n if file is not None:\r\n return _read_csv(file, nrows)\r\n\r\n return _default()", "def read_clickstream_data() -> pd.DataFrame:\n df1 = read_data_with_columns(r'data/interim/clickstream/clickstream_data.csv', r'data/raw/clickstream/clickstream_columns.txt')\n df2 = read_data_with_columns(r'data/raw/clickstream/clickstream_data_part_2.csv', r'data/raw/clickstream/clickstream_columns.txt')\n combined_clickstream_df = pd.concat([df1, df2])\n return combined_clickstream_df", "def fetchFromInpatientDataset(self) -> pd.DataFrame:\n dataframe_list = []\n for i in self.subset_list:\n data_inpatient_claims = pd.read_csv(\n f\"..\\input\\DE1.0 Sample{i}\\DE1_0_2008_to_2010_Inpatient_Claims_Sample_{i}.zip\",\n parse_dates=[\n \"CLM_FROM_DT\",\n \"CLM_THRU_DT\",\n \"CLM_ADMSN_DT\",\n \"NCH_BENE_DSCHRG_DT\",\n ],\n infer_datetime_format=True,\n )\n dataframe_list.append(data_inpatient_claims)\n\n final_inpatient_data = pd.concat(dataframe_list, axis=0)\n\n return final_inpatient_data", "def get_pollution_24h_data(files, column_name):\n\n frames = list()\n out_df = pd.DataFrame()\n for f in files:\n print(\"Getting daily pollution from:\", f)\n df = pd.read_excel(f, index_col=0)\n if \"2016\" in f:\n df[column_name] = df[column_name].str.replace(',', '.')\n frames.append(df[column_name].iloc[0:])\n else:\n frames.append(df[column_name].iloc[2:])\n\n out_df = pd.concat(frames)\n return out_df", "def get_all_assignments(\r\n base_directory: str, sections: pd.DataFrame, nrows: Union[int, None] = None\r\n) -> pd.DataFrame:\r\n return _get_data_for_section(base_directory, sections, get_assignments, nrows)", "def _parse_lma_files(files, dates):\n\n try:\n ref = datetime.datetime.strptime(dates[0], '%m/%d/%y')\n except ValueError:\n try:\n ref = datetime.datetime.strptime(dates[0], '%Y-%m-%d')\n except ValueError:\n ref = datetime.datetime.strptime(dates[0], '%m/%d/%Y')\n\n pds = []\n\n # Read in the files\n for i, f in enumerate(files):\n pds.append(pd.read_csv(f))\n\n # Add a Series to each DataFrame containing the time of each source\n # in datetime form\n for i, p in enumerate(pds):\n if len(dates) > 1:\n try:\n date = datetime.datetime.strptime(dates[i], '%m/%d/%y')\n except ValueError:\n try:\n date = datetime.datetime.strptime(dates[i], '%Y-%m-%d')\n except ValueError:\n date = datetime.datetime.strptime(dates[i], '%m/%d/%Y')\n\n series = [date + datetime.timedelta(seconds=entry) for entry\n in p['time(UT-sec-of-day)']]\n\n p.insert(0, 'DateTime', series)\n p['DateTime'] = pd.to_datetime(p['DateTime'])\n\n # Replace the values of the seconds of day column\n # to allow for storms to span multiple days\n series = [(entry - ref).total_seconds() for entry in\n p['DateTime']]\n p.drop('time(UT-sec-of-day)', axis=1, inplace=True)\n p.insert(1, 'time(UT-sec-of-day)', series)\n\n else:\n try:\n date = datetime.datetime.strptime(dates[0], '%m/%d/%y')\n except ValueError:\n try:\n date = datetime.datetime.strptime(dates[0], '%Y-%m-%d')\n except ValueError:\n date = datetime.datetime.strptime(dates[0], '%m/%d/%Y')\n\n series = [date + datetime.timedelta(seconds=entry) for entry\n in p['time(UT-sec-of-day)']]\n\n p.insert(0, 'DateTime', series)\n p['DateTime'] = pd.to_datetime(p['DateTime'])\n\n # Replace the values of the seconds of day column\n # to allow for storms to span multiple days\n series = [(entry - ref).total_seconds() for entry in\n p['DateTime']]\n p.drop('time(UT-sec-of-day)', axis=1, inplace=True)\n p.insert(1, 'time(UT-sec-of-day)', series)\n\n # Remove all flash-numbers that are == -1\n for i in range(len(pds)):\n row_index = pds[i][pds[i]['flash-number'] != -1].index\n pds[i] = pds[i].loc[row_index]\n\n # print(-1 in pds[i]['flash-number'])\n\n # Correct the flash numbers so that there are no duplicates\n for i in range(len(pds) - 1):\n # Get the largest flash number of the current file\n max_flash_number = pds[i]['flash-number'].max() + 1\n\n # Apply the offset to the next file\n pds[i + 1]['flash-number'] += max_flash_number\n\n # Make the final Pandas DataFrame\n if len(pds) > 1:\n storm = pd.concat(pds, ignore_index=True)\n else:\n storm = pds[0]\n\n # Sort the data frame by time\n storm.set_index('DateTime', inplace=True)\n storm.sort_index(inplace=True)\n\n # Reset the index\n storm.reset_index(inplace=True)\n\n return storm", "def attendance_report(linuxData, outFolder):\n\n # making new folders to store outputs in\n attendReports = make_directory(f\"{outFolder}\\\\Attendance Reports\")\n attendReportsNV = make_directory(f\"{outFolder}\\\\Attendance Reports NV\")\n\n # making a list of files inside attendance report destination that ends with AR.csv and has course name\n files = glob.glob(f\"{str(options.Ar_sheet)}\\\\*AR.csv\")\n files = file_name_check(files, linuxData.get_courseName())\n dateOfLecture = []\n for f in files:\n date = f.split('\\\\')\n dateOfLecture.append(date[1][-17:-7])\n\n # invalid attendance will go in this list\n invalid = []\n\n numberOfFiles = len(files) # will be used in later compares\n minimum_duration = int(options.P) # minimum duration allowed to be considered as attended\n\n # looping on all students registered in the course to check their state\n index = -1\n count = 0\n for k in linuxData.get_studentsList():\n index += 1\n for f in files:\n csvFile = pd.read_csv(f)\n j = 0\n count += 1\n absentFlag = 0\n for _ in csvFile.values:\n if j <= len(csvFile):\n flag = 0\n flag3 = 0\n\n # reading name and duration and id number if available\n regex2 = re.compile('[^0-9]')\n substring = str(csvFile['Name (Original Name)'][j])\n duration = int(csvFile['Total Duration (Minutes)'][j])\n checkNumber = regex2.sub('', substring)\n if checkNumber == '':\n checkNumber = '0'\n\n # taking first and last names of student and make them lower case to compare\n namesRegex = re.compile('[^a-zA-Z ]')\n namesRegex = namesRegex.sub('', substring)\n namesRegex = namesRegex.lower()\n names = namesRegex.split()\n if len(names) < 2:\n names.append('')\n regex1 = re.compile('[^a-zA-Z ]')\n name1 = regex1.sub('', k.get_name())\n name1 = name1.lower()\n checkName = name1.split()\n\n # check using id number\n if str(k.get_id()) == checkNumber:\n linux.get_student(index).add_attend('x')\n absentFlag = -1\n flag3 = -1\n\n # check using the name\n elif (nltk.edit_distance(names[0], checkName[0]) <= (\n int(len(checkName[0]) * 0.4)) and (nltk.edit_distance(names[1], checkName[1]) <= (\n int(len(checkName[1]) * 0.4)) or (nltk.edit_distance(names[1], checkName[2]) <= (\n int(len(checkName[2]) * 0.4))) or (nltk.edit_distance(names[1], checkName[-1]) <= (\n int(len(checkName[-1]) * 0.4))))) and absentFlag == 0 and duration > minimum_duration:\n linux.get_student(index).add_attend('x')\n absentFlag = -1\n flag3 = -1\n if flag3 == 0:\n for st in linuxData.get_studentsList():\n checkName = st.get_name().split()\n checkName[-1] = checkName[-1].lower()\n if nltk.edit_distance(checkName[-1], names[1]) <= (\n int(len(checkName[-1]) * 0.4)) or checkNumber == str(st.get_id()):\n flag = -1\n break\n\n # check for invalid students\n if flag != -1 and flag3 != -1 and count <= numberOfFiles:\n fullname = names[0] + \" \" + names[1] + \",\" + str(duration)\n invalid.append(fullname.split(\",\"))\n j = j + 1\n\n # make Non Valid report\n if count <= numberOfFiles:\n filename = f\"{course_name}-{dateOfLecture[count - 1]}-AR-NV.csv\"\n header = (\"Name (Original Name)\", \"Total Duration (Minutes)\")\n with open(f\"{attendReportsNV}\\\\{filename}\", 'w', newline='') as f:\n write = csv.writer(f)\n write.writerow(header)\n write.writerows(invalid)\n invalid.clear()\n\n # check if absent flag did not change, which means student is absent we add 'a' to his record\n if absentFlag == 0:\n linux.get_student(index).add_attend('a')\n\n # making final attendance report\n # column represent the header\n column = [\"Student ID\", \"Student Name\"]\n # adding dates to header column\n for dateX in dateOfLecture:\n column.append(dateX)\n\n # making final array of students records and put it in final report\n attendReportArray = []\n for v in linux.get_studentsList():\n attendReportArray.append(v.toArray())\n\n reportAR = pd.DataFrame(attendReportArray, columns=column)\n reportAR.to_csv(f\"{attendReports}\\\\{course_name}-AR.csv\", index=False)\n return" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return True if answer_id found in answer table.
def valid_answer_id(answer_id): SQL = """SELECT id FROM answer WHERE id = %s;""" data = (answer_id,) fetch = "one" try: found_id = db.run_statements(((SQL, data, fetch),))[0][0] except (DatabaseError, TypeError): return False return True
[ "def _is_answer_correct(self, answer_id=int, question_id=int):\n try:\n for question in self.questions_json_list:\n print question\n print \"Q_ID: \" + str(question['id'])\n print \"PASSED Q_ID: \" + str(question_id)\n if question['id'] == question_id:\n print True\n for alternative in question['alternatives']:\n if alternative['id'] == answer_id:\n return alternative['isCorrect']\n\n # for alternative in self.questions_json_list[question_id]['alternatives']:\n # print self.questions_json_list[question_id]['id']\n # print alternative\n # if alternative['id'] == answer_id:\n # return alternative['isCorrect']\n except Exception as ex:\n print ex", "def is_this_record_exist(table, id_):\n if id_[0] not in [record[0] for record in table]:\n\n ui.print_error_message(\"Record with this ID not found\")\n return False\n return True", "def existsEntry(self, id, lex):\r\n return self.tables[id].contains(lex)", "def get_answer_by_id(answer_id):\n\n return Answer.query.get(answer_id)", "def is_answered(self):\n return self.answer_post_id is not None or self.answer is not None", "def exists(id):\n return (id in emp_map)", "def has_answerpool(self):\n return hasattr(self, '_has_answerpool')", "def row_exists(db, table, row, id):\n\tq = db.execute(\"select id from %s where %s = ?\" % (table,row) , [id])\n\tres = q.fetchall()\n\treturn True if res else False", "def has(self, post):\n if self.dry_run and post.id:\n return False\n with dbm.open(self.path, 'c') as handle:\n return post.id in handle", "def exists(self, identifier):\n return False", "def test_student_has_answer_return_true() -> None:\n student = Student(1, 'John')\n q1 = MultipleChoiceQuestion(1, \"a b c or d?\", ['a', 'b', 'c', 'd'])\n a1 = Answer('a')\n q2 = CheckboxQuestion(5, \"do you like dogs?\", ['yes', 'no', 'sometimes'])\n a2 = Answer([\"yes\", \"sometimes\"])\n q3 = NumericQuestion(2, \"Pick num\", 1, 5)\n a3 = Answer(3)\n q4 = YesNoQuestion(4, \"T or F\")\n a4 = Answer(True)\n student.set_answer(q1, a1)\n student.set_answer(q2, a2)\n student.set_answer(q3, a3)\n student.set_answer(q4, a4)\n assert len(student._answers) == 4\n assert student.has_answer(q1) is True\n assert student.has_answer(q2) is True\n assert student.has_answer(q3) is True\n assert student.has_answer(q4) is True", "def is_book_exist(self, book_dic):\r\n book_id = book_dic['book_id']\r\n book_info = self.books_tb.find_one({'book_id': book_id})\r\n if book_info:\r\n return True\r\n return False", "def has_key(self, outcomeLabel):\n return outcomeLabel in self.counts", "def verify_problem_answer(self, answer: models.ProblemAnswer):", "def check_user_question_nouns_in_df_answer_and_question(self, user_question_nouns, index):\n log.debug(f'Entering: \"{inspect.currentframe().f_code.co_name}\"')\n log.debug(f\"clean_answer: {self.df._get_value(int(index), 'clean_answer')}, index: {index}\")\n log.debug(\n f\"clean_question: {self.df._get_value(int(index), 'clean_question')}, index: {index}\"\n )\n if (any([noun in self.df._get_value(int(index) ,'clean_answer') for noun in user_question_nouns])\n or any([noun in self.df._get_value(int(index), 'clean_question') for noun in user_question_nouns])):\n return True\n\n return False", "def get(self, answer_id):\n le_answer = get_an_answer(answer_id)\n if not le_answer:\n return {'success': False, 'message': 'answer not found'}\n else:\n return le_answer", "def abort_if_answer_already_exists(answer_text):\n\n session = db_session.create_session()\n answer = session.query(Answer).filter(Answer.text == answer_text).all()\n if answer:\n abort(404, message=f\"Answer \\\"{answer[0].text}\\\" already exists.\")", "def valid_id(option, idd, db_name = \"database.json\"):\n dbs = load_json(db_name)\n if option == \"user\" or option == \"users\":\n if str(idd) in dbs[\"USER_DB\"]:\n return True\n elif option == \"product\" or option == \"products\":\n if str(idd) in dbs[\"PRODUCT_DB\"]:\n return True\n elif option == \"admin\" or option == \"admins\":\n if str(idd) in dbs[\"ADMIN_DB\"]:\n return True\n elif option == \"order\" or option == \"orders\":\n if str(idd) in dbs[\"ORDER_DB\"]:\n return True\n\n # raise key error if id not found\n raise KeyError()", "def notebook_exists(self, notebook_id):\n n = Notebook.objects.filter(id=notebook_id)\n return len(n) == 1" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Answer message must be at least 10 characters long to return True, else False.
def valid_answer_message(a_form): answer_message = len(a_form.get("message", '')) if answer_message >= 10: return True return False
[ "def check_message(message):\n return False if len(message) > 20000 else True", "def is_length(message):\n\n if len(message) <= 25:\n return True\n else:\n return False", "def tweetswarm_string_validate(s):\n return s.__len__() < 140 and s.__len__() > 0", "def check_size(msg):\n\n if len(msg) > TWEET_SIZE:\n return False\n return True", "def test_validate_with_short_message_is_large(self):\n messages = [\"I am a wolf\"]\n short_message = \"I am a wolf\" * 10\n is_valid, errors = TweeterThread.objects._validate(\n short_message,\n messages)\n self.assertEqual(errors, [\"Snippet is above 20 charaters\"])\n self.assertFalse(is_valid)", "def is_message_too_long(message):\n if len(message) > 1000:\n raise error.InputError(\"Message is too long.\")", "def check_answer(answer):\n\n if len(answer) > 140:\n return False, 'Réponse trop longue'\n elif url_exist(answer):\n return False, 'Les liens sont interdits'\n else:\n return True, 'Réponse de la bonne forme !'", "def validate_string(m,min, max):\n while True:\n my_string = input(m)\n if len(my_string) < min:\n print(\"Your entry is too short. The minimum required characters is {}.\".format(min))\n elif len(my_string) > max:\n print(\"your entry is too many characters\")\n else:\n return my_string", "def check_input(self, desired_input_text):\n result = False\n\n check_str_len = len(desired_input_text.strip()) > 0\n\n if check_str_len:\n result = True\n\n return result", "def validate_string(m,min, max):\n while True:\n user_input = input(m)\n if len(user_input) < min:\n print(\"Your entry is too short. The minimum required characters is {}.\".format(min))\n elif len(user_input) > max:\n print(\"your entry is too many characters\")\n else:\n return user_input", "def passwordcheck(password):\n\t\tif len(password) >= 5:\n\t\t\treturn True\n\t\telse:\n\t\t\tprint(\"Invalid password: Must be at least 5 characters.\\n\")\n\t\t\treturn False", "def is_min_length(text, min_length):\n return len(text) >= min_length", "def length(self):\n return len(self.password) >= 12", "def _sms_test(log, ads):\n for length in message_lengths:\n message_array = [rand_ascii_str(length)]\n if not sms_send_receive_verify(log, ads[0], ads[1],\n message_array):\n ads[0].log.error(\"SMS of length %s test failed\", length)\n return False\n else:\n ads[0].log.info(\"SMS of length %s test succeeded\", length)\n log.info(\"SMS test of length %s characters succeeded.\",\n message_lengths)\n return True", "def test_check_field_length(self):\n form = EditCouponForm(data={\n 'headline': 'This headline is over twenty-five characters'})\n self.assertFalse(form.is_valid())\n self.assertEqual(form.errors['headline'][0], \n 'Please limit this field to 25 characters')", "def test_too_long_username_registration(self):\n errorMsg = 'The username must be between 3 and 100 chars long.'\n rv = self.register('a'*101, 'mister_test@example.com',\n 'password', 'password')\n assert errorMsg in rv.data", "def checkChars(self):\r\n\r\n text = self.textEdit.toPlainText()\r\n numLens = 140 - tweetLength(text)\r\n if numLens == 140 and (not self.action == \"retweet\"):\r\n # you can not send empty tweet, except retweet\r\n self.pushButton_send.setEnabled(False)\r\n elif numLens >= 0:\r\n # length is okay\r\n self.label.setStyleSheet(\"color:black;\")\r\n self.pushButton_send.setEnabled(True)\r\n else:\r\n # text is too long\r\n self.label.setStyleSheet(\"color:red;\")\r\n self.pushButton_send.setEnabled(False)\r\n self.label.setText(str(numLens))", "def test_too_long_text(self):\r\n long_text = \"Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown\" # noqa\r\n serializer = self.message_serializer(data={\"text\": long_text})\r\n assert not serializer.is_valid()\r\n assert serializer.validated_data == {}\r\n assert serializer.data == {\"text\": long_text}\r\n assert serializer.errors == {\r\n \"text\": [\"Ensure this field has no more than 160 characters.\"]\r\n }", "def ValidateStringLenth(value, max_length=_MAX_STRING_LENGTH):\n if isinstance(value, basestring):\n if len(value) <= max_length:\n return True\n return False", "def _validate_length(self, string, length):\n assert len(string) == length, \\\n 'String %s length\\'s not %s' % (string, length,)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add 1 to answer counter of question with question_id, or reduce counter by one, depending on operation.
def update_answer_counter(question_id, operation): number = 1 if operation == "ADD" else 0 if number: SQL = """UPDATE question SET answer_count = answer_count + 1 WHERE id = %s;""" else: SQL = """UPDATE question SET answer_count = answer_count - 1 WHERE id = %s;""" data = (question_id,) fetch = None db.run_statements(((SQL, data, fetch),))
[ "def change_vote_count(conn, direction, question_id=None, answer_id=None):\n if question_id:\n table = \"question\"\n the_id = question_id\n elif answer_id:\n table = \"answer\"\n the_id = answer_id\n SQL2 = \"\"\"SELECT question_id FROM answer WHERE id = %s;\"\"\"\n data2 = (answer_id,)\n\n if direction == \"up\":\n SQL1 = \"\"\"UPDATE {} SET vote_number = vote_number + 1 WHERE id = %s;\"\"\".format(table)\n elif direction == \"down\":\n SQL1 = \"\"\"UPDATE {} SET vote_number = vote_number - 1 WHERE id = %s;\"\"\".format(table)\n data1 = (the_id,)\n\n with conn.cursor() as cursor:\n cursor.execute(SQL1, data1)\n if answer_id:\n cursor.execute(SQL2, data2)\n result = cursor.fetchone()[0]\n\n if answer_id:\n return result", "def UpdateApiQueryCounter(query_id):\r\n request_counter_key = co.REQUEST_COUNTER_KEY_TEMPLATE.format(query_id)\r\n request_counter_shard.Increment(request_counter_key)", "def _increase_competency_attempt_counter(learner_dict, mastery_prob):\n if 'competencyAttemptCounters' in learner_dict:\n competency_counters = learner_dict['competencyAttemptCounters']\n else:\n competency_counters = []\n learner_dict['competencyAttemptCounters'] = competency_counters\n\n competency_id = mastery_prob['competencyId']\n competency_counter = next((x for x in competency_counters if x['competencyId'] == competency_id), None)\n\n if competency_counter:\n updated_counter = competency_counter['attempts'] + 1\n competency_counter['attempts'] = updated_counter\n competency_counter['lastAttemptDateTime'] = mastery_prob['timestamp']\n else:\n updated_counter = 1\n competency_counter = {\n \"@context\": \"tla-declarations.jsonld\",\n \"@type\": \"CompetencyAttemptCounter\",\n \"competencyId\": competency_id,\n \"attempts\": updated_counter,\n \"lastAttemptDateTime\": mastery_prob['timestamp']\n }\n\n competency_counters.append(competency_counter)\n\n print_with_time('INFO: Updated competency attempt counter to {0} for learner {1}, competency {2}'\n .format(str(updated_counter), learner_dict['identifier'], competency_id))\n log_data = {\n \"learnerId\": learner_dict['identifier'],\n \"competencyId\": competency_id,\n \"attemptCounter\": competency_counter['attempts']\n }\n statement = create_learner_inference_log_xapi(verb_id=\"https://w3id.org/xapi/dod-isd/verbs/saved\", verb_en_name=\"saved\",\n activity_id=\"insertIPAddr/save-competency-attempt-counter\",\n activity_en_name=\"Save Competency Attempt Counter\",\n obj_extensions={\"insertIPAddr/learner-inferences/log-data\": log_data},\n profile_id=\"https://w3id.org/xapi/dod-isd/v1.0\")\n if Config.LOG_TO_LRS:\n log_to_lrs(statement)\n if Config.LOG_XAPI_TO_FILE:\n print_with_time(\"[XAPI LOG]: {}\".format(json.dumps(statement)))", "def update_question(questid, userid):\n\n quest = db(current.db.question.id == questid).select().first()\n\n answers_per_level = 3\n\n # first step is to select the related user and question records their should\n # only ever be one of each of these and we update as much as possible here \n # because it's interesting to see as much as possible on viewquest rather\n # than waiting until 3 people have answered and it can be scored - however this can result in\n # a degree of double updating\n\n if quest.intunpanswers >= answers_per_level:\n redirect(URL('score_question', args=quest.id))\n else:\n # need to have another look at this \n # intunpanswers < answers_per_level\n # the general requirement here is to do nothing - however because the\n # solution focuses on solving the highest priority question at all times\n # different users may be sent the same question at the same time and\n # answers may be received for a level after the question is either promoted\n # or resolved - promotions shouldn't be an issue but resolved questions are\n # because the user should probably get credit if right and nothing if wrong\n # and an explanation of what happend\n\n if quest.status == 'Resolved' or quest.status == 'Agreed':\n # get the score - if right add to score - if wrong same\n # update userquestion and user - other stuff doesn't apply\n # scoretable = current.db(current.db.scoring.level == quest.level).select(cache=(cache.ram, 1200), cacheable=True).first()\n scoretable = current.db(current.db.scoring.level == quest.level).select().first()\n if scoretable is None:\n score = 30\n wrong = 1\n else:\n if quest.qtype != 'action':\n score = scoretable.correct\n wrong = scoretable.wrong\n else:\n score = scoretable.rightaction\n wrong = scoretable.wrongaction\n numcorrect = 0\n numwrong = 0\n numpassed = 0\n\n if uq.answer == quest.correctans:\n updscore = score\n numcorrect = 1\n elif uq.answer == 0:\n updscore = 1\n numpasse = 1\n else:\n updscore = wrong\n numwrong = 1\n\n uq.update_record(status='Resolved', score=updscore, resolvedate=request.utcnow)\n\n updateuser(userid, updscore, numcorrect, numwrong, numpassed)\n\n redirect(URL('viewquest', 'index', args=quest.id))", "def updatequestcounts(qtype, oldcategory, newcategory, oldstatus, newstatus, answergroup):\n\n if oldcategory == newcategory and oldstatus == newstatus:\n return\n\n # get existing category record should always exist\n existrow = current.db((current.db.questcount.groupcatname == oldcategory) & (current.db.questcount.groupcat == 'C')).select().first()\n\n oldindex = getindex(qtype, oldstatus)\n newindex = getindex(qtype, newstatus)\n qcount = existrow.questcounts\n qcount[oldindex] -= 1\n \n if oldcategory == newcategory:\n qcount[newindex] += 1\n existrow.update_record(questcounts=qcount)\n\n if oldcategory != newcategory:\n newrows = current.db((current.db.questcount.groupcatname == newcategory) & (current.db.questcount.groupcat == 'C')).select()\n if newrows:\n newrow = newrows.first()\n qcount = newrow.questcounts\n qcount[newindex] += 1\n newrow.update_record(questcounts=qcount)\n else:\n createcount = [0] * 18\n createcount[newindex] = 1\n current.db.questcount.insert(groupcat='C', groupcatname=newcategory, questcounts=createcount)\n # udpate the group count record if status changed\n if oldstatus != newstatus:\n grouprow = current.db((current.db.questcount.groupcatname == answergroup) & (current.db.questcount.groupcat == 'G')).select().first()\n if grouprow:\n qcount = grouprow.questcounts\n qcount[oldindex] -= 1\n qcount[newindex] += 1\n grouprow.update_record(questcounts=qcount)\n else:\n print('An error occurred updating group quest counts')\n return", "def _inc_query_counter(self):\n self.query_counter += 1", "def question_number(self) -> int:\n return self.index + 1", "async def add_answer(self, ctx: Context, content: str, is_correct: bool, *, question: str):\n question_id = await ctx.db.fetchval(\"SELECT question_id from question where LOWER(content) = $1\",\n question.lower())\n if not question_id:\n return await ctx.send(\":no_entry: This question doesn't exist.\")\n\n async with ctx.db.acquire():\n await ctx.db.execute(\"\"\"INSERT INTO answer (question_id, content, is_correct) \n VALUES ($1,$2,$3) ON CONFLICT DO NOTHING\"\"\", question_id, content, is_correct)\n\n await ctx.send(\"> successfully updated.\")", "def _update_roll_counter(self):\n self._rolls_since_last_hit += 1\n self._rolls_since_last_hit[self._last_result] = 1\n return None", "def update(self, answer):\n item = self.items[answer.user_id, answer.place_id]\n\n if not item.practices:\n self.prior.update(answer)\n\n prediction = self.predict(answer)\n self.predictions[answer.id] = prediction\n\n item.add_practice(answer)\n\n if answer.is_correct:\n item.inc_knowledge(self.gamma * (1 - prediction))\n else:\n item.inc_knowledge(self.delta * prediction)", "def answer_question(self, student_id, question_id, option_id):\n ques = self.get_question(question_id)\n is_student_eligible, student = self.student_eligible(student_id)\n if ques and is_student_eligible:\n if ques.get_right_answer() and option_id == ques.get_right_answer().option_id:\n self.add_student_score(student, 1)", "def increment_vote(self, poll_key, choice_key):\n try:\n self.collection.update(\n {\n \"_id\": ObjectId(poll_key),\n \"choices.id\": int(choice_key),\n },\n {\n \"$inc\": {\"choices.$.votes\": 1}\n }\n )\n except(InvalidId, ValueError):\n raise PollNotFound()", "def update(self, answer):\n item = self.items[answer.user_id, answer.place_id]\n\n if not item.practices:\n self.prior.update(answer)\n\n prediction = self.predict(answer)\n self.predictions[answer.id] = prediction\n\n item.add_practice(answer)\n level = tools.automaticity_level(answer.response_time) / self.zeta\n\n if answer.is_correct:\n item.inc_knowledge(self.gamma * (1 - prediction) + level)\n else:\n item.inc_knowledge(self.delta * prediction + level)", "def incAppCount(keydicCntr, q):\n if q in keydicCntr:\n keydicCntr[q] += 1\n return\n else:\n keydicCntr[q] = 1\n return", "def post(self, answerid):\n db = Database()\n votes = db.get_by_argument(\"answers\", \"answer_id\", answerid)\n if votes:\n upvote = votes[5] + 1\n db.update_answer_record(\"answers\", \"up_vote\",\n upvote, \"answer_id\", answerid)\n return{\"message\": \"answer upvoted\"}, 201\n return{\"message\": \"No answer by that answer_id\"}, 404", "def administer(self):\n\n score = 0\n\n for question in self.questions:\n evaluation = question.ask_and_evaluate()\n\n if evaluation:\n score += 1\n\n return score", "def score_answer(self, answer, answer_spec):\n raise NotImplementedError", "def increment_api_rate_limit_counter(username, action):\n last_window_time = misc_util.align_timestamp(\n misc_util.time(), FLAGS.contest_start_time, FLAGS.api_rate_limit_window_size)\n key = '%s:%d:%s' % (action, last_window_time, username)\n try:\n entry = _db.api_rate_limits.find_one_and_update(\n {'_id': key},\n {\n '$setOnInsert': {'_id': key},\n '$inc': {'value': 1},\n },\n upsert=True,\n return_document=pymongo.collection.ReturnDocument.AFTER)\n except pymongo.errors.DuplicateKeyError:\n entry = _db.api_rate_limits.find_one_and_update(\n {'_id': key},\n {'$inc': {'value': 1}},\n return_document=pymongo.collection.ReturnDocument.AFTER)\n return entry['value']", "def administer(self):\n score = 0\n\n for question in self.questions:\n result = Question.ask_and_evaluate()\n if result is True:\n score += 1\n\n return score" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return new answer with message from form, initialized without image.
def create_new_answer_no_image(message, question_id, user_name): init_time = helper.create_timestamp() init_votes = 0 init_image = None accepted = False new_answer = [init_time, init_votes, question_id, message, init_image, accepted, user_name] return new_answer
[ "def to_form(self, message):\n form = GameForm()\n form.urlsafe_key = self.key.urlsafe()\n form.user_one = self.user_one.get().name\n form.user_two = self.user_two.get().name\n form.turn = self.turn.get().name\n form.current_round = self.current_round\n form.game_over = self.game_over\n form.message = message\n form.bait = self.target[:self.current_round]\n return form", "def create_new_message():\n return questionary.confirm(\"Create widgets for another message?\").ask()", "def get_answer_from_form(self, form, index):\n text_answer = form.get(\"question-{}\".format(index), \"\").strip()\n return text_answer if len(text_answer) > 0 else None", "def _basicAnswerCreation(self, survey, slide, answer, label = ''):\n if not getSurveyAnswer(survey, slide, c.authuser):\n sa = SurveyAnswer(survey, slide, answer, label)\n result = 'create'\n else:\n sa = editSurveyAnswer(survey, slide, answer, label)\n result = 'modify'\n return sa, result", "def __init__(self, master, question):\r\n # On initialization create and pack a frame for\r\n # the view.\r\n self.frame = Tk.Frame(master, bg=BGB)\r\n self.frame.pack(side=Tk.TOP)\r\n self.question = question\r\n self.user_answer = None\r\n self.question_text = Tk.Label(\r\n self.frame,\r\n text=self.question['Question'],\r\n wraplength=450,\r\n justify=Tk.LEFT,\r\n font=FONT,\r\n fg=FGY,\r\n bg=BGB\r\n )\r\n self.question_text.pack(side=Tk.TOP)\r\n self.answer_frame = Tk.Frame(self.frame, bg=BGB)\r\n self.answer_frame.pack(side=Tk.TOP)\r\n self.update_answers(init=True)\r\n self.submit_but = Tk.Button(\r\n self.frame,\r\n text='Submit',\r\n font=FONT,\r\n bg=BGB,\r\n fg=BGB\r\n )\r\n self.submit_but.pack(side=Tk.RIGHT, anchor='w')", "def form(self):\n return self.question.form_class(question=self.question)", "def create(question: str) -> Asker:\n if question.startswith(\"/imagine\"):\n return ImagineAsker()\n return TextAsker()", "def form_with_captcha(form_class, request):\n\n assert 'captcha' not in form_class.base_fields\n assert 'is_bot' not in form_class.base_fields\n\n if is_human(request):\n return form_class\n else:\n class FormWithCaptcha(form_class):\n captcha = forms.CharField(max_length=10, label='Word', help_text='Enter the text in the image above. This word verification helps Vibha discourage spammers.')\n is_bot = True\n\n def clean_captcha(self):\n if check_captcha(request, self.cleaned_data['captcha']):\n self.is_bot = False\n else:\n raise forms.ValidationError(u'Incorrect captcha value')\n # Always return None, we do not need the captcha value\n return None\n\n return FormWithCaptcha", "def to_message(self):\n return QuestionResponseMessage(id=self.key.id(),\n text=self.text,\n asker_id=self.asker_id,\n asker_name=None,\n time_asked = self.timestamp,\n yes_count = self.yes_count,\n no_count = self.no_count)", "def contact():\r\n form = QuestionForm()\r\n if form.validate_on_submit():\r\n flash(f'Tack för din fråga, vi återkommer så fort vi vi kan!', 'success')\r\n return render_template(\"contact.html\", form=form)", "def inner():\n form = forms.ContactForm()\n if form.validate_on_submit():\n msg = Message(title, recipients=[recipient])\n msg.body = form.content.data\n mail.send(msg)\n return 'OK'", "def prepare_form(self):\n raise NotImplementedError(\"Just use get_form() method instead\")", "def createReply(title, text, REQUEST, RESPONSE):", "def create(question, answer):\n new_question = Question(question=question, answer = answer)\n new_question.save()\n print(\"Questão salva no banco de dados\")\n return new_question", "def test_failed_form_validation_without_user(self):\n\n form = AnswerForm(self.params, question=self.question)\n self.assertFalse(form.is_valid())", "def fromMsg(msg):\n return Question({\n \"question\": msg.getMeta(\"question\"),\n \"A\": msg.getMeta(\"answerA\"),\n \"B\": msg.getMeta(\"answerB\"),\n \"C\": msg.getMeta(\"answerC\"),\n \"D\": msg.getMeta(\"answerD\"),\n \"correctAnswer\": msg.getMeta(\"correctAnswer\"),\n }, msg.getMeta(\"id\"))", "def createConversationFromForm(self, data):\n form = ConversationCreateForm(data)\n\n form.is_valid()\n\n if not form.is_valid():\n return None\n\n return form.create()", "def get_feedback_form(self, request):\n return self.feedback_form(request.POST or None)", "def update_result() -> bool:\n if flask.request.method == \"POST\":\n message = flask.request.form[\"message\"]\n if message is not None:\n # Update session's message with the message from the form\n flask.session.clear()\n flask.session[\"message\"] = message\n return True\n return False" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Rename answer image and question_id as tuple from answer table.
def rename_answer_image(filename, answer_id): SQL = """UPDATE answer SET image = %s WHERE id = %s;""" data = (filename, answer_id) fetch = None db.run_statements(((SQL, data, fetch),))
[ "def get_answer_image_and_q_id(answer_id):\n SQL = \"\"\"SELECT image, question_id FROM answer WHERE id = %s;\"\"\"\n data = (answer_id,)\n fetch = \"one\"\n\n a_img_and_id = db.run_statements(((SQL, data, fetch),))[0]\n return a_img_and_id", "def remove_answer_image(answer_id):\n SQL = \"\"\"UPDATE answer SET image = NULL WHERE id = %s;\"\"\"\n data = (answer_id,)\n fetch = None\n db.run_statements(((SQL, data, fetch),))", "def save_answer(self, index):\n subset = self.dt.save_answer(index)\n self.load_ref_img_list(None, subset)\n self.next_question()", "def remove_answer_and_get_q_id(answer_id):\n image_to_delete, question_id = get_answer_image_and_q_id(answer_id)\n if image_to_delete:\n try:\n os.remove(\"static/uploads/\" + image_to_delete)\n except (FileNotFoundError, TypeError):\n pass\n\n delete_answer_by_id(answer_id)\n return question_id", "def get_data_image_qa(obj, sample):\n question = sample['question'].strip().split(' ')\n answer = sample['answer'].strip().split(' ')\n coding_q = [obj.word_dict.get(word, 0) for word in question]\n coding_a = [obj.word_dict.get(word, 0) for word in answer]\n img_feat = get_image_feature(obj.features, sample['image_id'])\n if img_feat is not None:\n img_feat = img_feat * obj.feat_avg_norm_factor\n question_id = int(sample['question_id'])\n return question_id, img_feat, coding_q, coding_a", "def delete_a_image(answer_id):\n current_image = get_answer_image(answer_id)\n if current_image:\n remove_answer_image(answer_id)\n try:\n os.remove(\"static/uploads/\" + current_image)\n except FileNotFoundError:\n pass", "def get_answer_details(answer_id):\n SQL = \"\"\"SELECT id, submission_time, vote_number, question_id, message, image\n FROM answer WHERE id = %s;\"\"\"\n data = (answer_id,)\n fetch = \"one\"\n\n answer = db.run_statements(((SQL, data, fetch),))[0]\n return answer", "def upgrade_row(answers):\n con = sqlite3.connect('RNP.db')\n cur = con.cursor()\n\n for i in answers:\n\n if answers[i][1] is not None:\n add = [i, answers[i][0], answers[i][1], 1, 1]\n else:\n add = [i, answers[i][0], answers[i][1], 1, 0]\n\n cur.execute(f'''SELECT decision_number FROM RNP WHERE decision_number={i}''')\n exists = cur.fetchall()\n if not exists:\n cur.execute('INSERT INTO RNP VALUES(?,?,?,?,?)', add)\n con.commit()\n else:\n print(f\"url alredy in table.{add}\")\n\n continue\n\n con.commit()\n con.close()", "def rename_imgs(path):", "def create_new_answer_no_image(message, question_id, user_name):\n init_time = helper.create_timestamp()\n init_votes = 0\n init_image = None\n accepted = False\n new_answer = [init_time, init_votes, question_id, message, init_image, accepted, user_name]\n return new_answer", "def get_data_image_caption(obj, sample):\n caption = sample['caption'].strip().split(' ')\n coding_q = [0]\n coding_a = [obj.word_dict.get(word, 0) for word in caption]\n img_feat = get_image_feature(obj.features, sample['image_id'])\n if img_feat is not None:\n img_feat = img_feat * obj.feat_avg_norm_factor\n question_id = int(sample['image_id'])\n return question_id, img_feat, coding_q, coding_a", "def _read_answer(line):\n id_string, answer_string = line.split(' ')\n id = int(id_string[len('Image'):])\n answer = int(answer_string)\n return id, answer", "def datapoint2id(self, question, answer, resources):\n question2id = self.string2id(question, False)\n answer2id = self.string2id(answer, False)\n resources2id = []\n for resource in resources:\n resources2id.append(self.string2id(resource, False))\n \n return question2id, answer2id, resources2id", "def set_answer(answers, assessment_name, answer):\n if not answers.data:\n score_dict = {}\n else:\n score_dict = json.loads(answers.data)\n score_dict[assessment_name] = answer\n answers.data = json.dumps(score_dict)", "async def delete_answer(self, ctx: Context, question: str, *, answer: str):\n question = await ctx.db.fetchval(\"SELECT question_id from question where content = $1\", question)\n\n if not question:\n return await ctx.send(f\":no_entry: | a question with id `{question}` does not exist.\")\n\n async with ctx.db.acquire():\n check = await ctx.db.execute(\"\"\"DELETE FROM answer where question_id = $1 and LOWER(content) = $2 \n RETURNING answer\"\"\", question, answer.lower())\n\n if check == \"DELETE 0\":\n return await ctx.send(f\"The answer `{answer}` does not exist.\")\n\n await ctx.send(\"> successfully updated.\")", "def change_image_name(self, img, newname):\r\n return self.update(img, {\"name\": newname})", "def manage_ques(ques):\n ques = ques['questions']\n qid_q = {\n q['question_id']:{\n 'image_id': q['image_id'], 'question': q['question']\n }\n for q in ques}\n return qid_q", "def create(self, answer):\n\t\tService.db.query(\"INSERT INTO answers (question_id, session_id, answer) VALUES (%s, %s, %s)\",\n\t\t\tanswer.questionId, answer.sessionId, answer.answer)\n\t\tService.db.commit()", "async def add_answer(self, ctx: Context, content: str, is_correct: bool, *, question: str):\n question_id = await ctx.db.fetchval(\"SELECT question_id from question where LOWER(content) = $1\",\n question.lower())\n if not question_id:\n return await ctx.send(\":no_entry: This question doesn't exist.\")\n\n async with ctx.db.acquire():\n await ctx.db.execute(\"\"\"INSERT INTO answer (question_id, content, is_correct) \n VALUES ($1,$2,$3) ON CONFLICT DO NOTHING\"\"\", question_id, content, is_correct)\n\n await ctx.send(\"> successfully updated.\")" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return answer image and question_id based on answer_id.
def get_answer_image_and_q_id(answer_id): SQL = """SELECT image, question_id FROM answer WHERE id = %s;""" data = (answer_id,) fetch = "one" a_img_and_id = db.run_statements(((SQL, data, fetch),))[0] return a_img_and_id
[ "def get_answer_details(answer_id):\n SQL = \"\"\"SELECT id, submission_time, vote_number, question_id, message, image\n FROM answer WHERE id = %s;\"\"\"\n data = (answer_id,)\n fetch = \"one\"\n\n answer = db.run_statements(((SQL, data, fetch),))[0]\n return answer", "def get_data_image_qa(obj, sample):\n question = sample['question'].strip().split(' ')\n answer = sample['answer'].strip().split(' ')\n coding_q = [obj.word_dict.get(word, 0) for word in question]\n coding_a = [obj.word_dict.get(word, 0) for word in answer]\n img_feat = get_image_feature(obj.features, sample['image_id'])\n if img_feat is not None:\n img_feat = img_feat * obj.feat_avg_norm_factor\n question_id = int(sample['question_id'])\n return question_id, img_feat, coding_q, coding_a", "def remove_answer_and_get_q_id(answer_id):\n image_to_delete, question_id = get_answer_image_and_q_id(answer_id)\n if image_to_delete:\n try:\n os.remove(\"static/uploads/\" + image_to_delete)\n except (FileNotFoundError, TypeError):\n pass\n\n delete_answer_by_id(answer_id)\n return question_id", "def _read_answer(line):\n id_string, answer_string = line.split(' ')\n id = int(id_string[len('Image'):])\n answer = int(answer_string)\n return id, answer", "def get_answer_to_question(question_id):\n return Question.query.filter_by(id=question_id).first_or_404().answer", "def remove_answer_image(answer_id):\n SQL = \"\"\"UPDATE answer SET image = NULL WHERE id = %s;\"\"\"\n data = (answer_id,)\n fetch = None\n db.run_statements(((SQL, data, fetch),))", "def rename_answer_image(filename, answer_id):\n SQL = \"\"\"UPDATE answer SET image = %s WHERE id = %s;\"\"\"\n data = (filename, answer_id)\n fetch = None\n db.run_statements(((SQL, data, fetch),))", "def get(self, answer_id):\n le_answer = get_an_answer(answer_id)\n if not le_answer:\n return {'success': False, 'message': 'answer not found'}\n else:\n return le_answer", "def get_answer_by_id(answer_id):\n\n return Answer.query.get(answer_id)", "def view_answers(self, id):\n answers = self.db\n quiz_and_answers = answers[id-1]\n return quiz_and_answers", "def get_data_image_caption(obj, sample):\n caption = sample['caption'].strip().split(' ')\n coding_q = [0]\n coding_a = [obj.word_dict.get(word, 0) for word in caption]\n img_feat = get_image_feature(obj.features, sample['image_id'])\n if img_feat is not None:\n img_feat = img_feat * obj.feat_avg_norm_factor\n question_id = int(sample['image_id'])\n return question_id, img_feat, coding_q, coding_a", "def get_test_question_answer(self):\n query_string = \"\"\"\n {\n \"query\": {\n \"term\" : {\"test_completed\": false}\n }\n }\n \"\"\"\n answer_doc = None\n test_answer_es = Elasticsearch([self.application.es_test_host])\n search_results = test_answer_es.search(self.application.es_test_index,\n self.application.es_test_type,\n body=query_string, size=10)\n if search_results['hits']['total'] > 0:\n answer_doc = random.choice(search_results['hits']['hits'])\n\n if not answer_doc:\n return self.generate_done_message()\n\n answer = answer_doc['_source']['answer']\n test_answer_id = answer_doc['_id']\n c_id = answer_doc['_source']['c_id']\n\n query_string = \"\"\"\n {\n \"query\": {\n \"term\" : {\"c_id\": %s}\n }\n }\n \"\"\" % c_id\n test_question_es = Elasticsearch([self.application.es_test_question_host])\n search_results = test_question_es.search(\n self.application.es_test_question_index,\n self.application.es_test_question_type, body=query_string, size=1)\n question = search_results['hits']['hits'][0]['_source']['question']\n\n return (question, answer, test_answer_id)", "def delete_a_image(answer_id):\n current_image = get_answer_image(answer_id)\n if current_image:\n remove_answer_image(answer_id)\n try:\n os.remove(\"static/uploads/\" + current_image)\n except FileNotFoundError:\n pass", "def answerset(answerset_id):\n return render_template('answerset.html', answerset_id=answerset_id, answer_id=[])", "def _get_answer(self, answer_id):\n return self._translate_sent(self.answer_pool[answer_id])", "def create_new_answer_no_image(message, question_id, user_name):\n init_time = helper.create_timestamp()\n init_votes = 0\n init_image = None\n accepted = False\n new_answer = [init_time, init_votes, question_id, message, init_image, accepted, user_name]\n return new_answer", "def get_question_id(answer_id):\n SQL = \"\"\"SELECT question_id FROM answer WHERE id = %s;\"\"\"\n data = (answer_id,)\n fetch = \"one\"\n\n question_id = db.run_statements(((SQL, data, fetch),))[0][0]\n return question_id", "def datapoint2id(self, question, answer, resources):\n question2id = self.string2id(question, False)\n answer2id = self.string2id(answer, False)\n resources2id = []\n for resource in resources:\n resources2id.append(self.string2id(resource, False))\n \n return question2id, answer2id, resources2id", "def __repr__(self):\n return \"MultipleAnswer: {id: '%s', answer: '%s'}\" % (self.id, self.answer)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return whole answer with all details where answer_id found.
def get_answer_details(answer_id): SQL = """SELECT id, submission_time, vote_number, question_id, message, image FROM answer WHERE id = %s;""" data = (answer_id,) fetch = "one" answer = db.run_statements(((SQL, data, fetch),))[0] return answer
[ "def view_answers(self, id):\n answers = self.db\n quiz_and_answers = answers[id-1]\n return quiz_and_answers", "def get_answer_by_id(answer_id):\n\n return Answer.query.get(answer_id)", "def get_answer_to_question(question_id):\n return Question.query.filter_by(id=question_id).first_or_404().answer", "def get_answers(self, obj):\n answer_list = Answer.objects.filter(question=obj.pk)\n serializer = AnswerSerializer(instance=answer_list, many=True)\n return serializer.data", "def get(self, answer_id):\n le_answer = get_an_answer(answer_id)\n if not le_answer:\n return {'success': False, 'message': 'answer not found'}\n else:\n return le_answer", "def get_test_question_answer(self):\n query_string = \"\"\"\n {\n \"query\": {\n \"term\" : {\"test_completed\": false}\n }\n }\n \"\"\"\n answer_doc = None\n test_answer_es = Elasticsearch([self.application.es_test_host])\n search_results = test_answer_es.search(self.application.es_test_index,\n self.application.es_test_type,\n body=query_string, size=10)\n if search_results['hits']['total'] > 0:\n answer_doc = random.choice(search_results['hits']['hits'])\n\n if not answer_doc:\n return self.generate_done_message()\n\n answer = answer_doc['_source']['answer']\n test_answer_id = answer_doc['_id']\n c_id = answer_doc['_source']['c_id']\n\n query_string = \"\"\"\n {\n \"query\": {\n \"term\" : {\"c_id\": %s}\n }\n }\n \"\"\" % c_id\n test_question_es = Elasticsearch([self.application.es_test_question_host])\n search_results = test_question_es.search(\n self.application.es_test_question_index,\n self.application.es_test_question_type, body=query_string, size=1)\n question = search_results['hits']['hits'][0]['_source']['question']\n\n return (question, answer, test_answer_id)", "def get_answers(self):\n answers = {}\n for answer in Answer.objects.filter(answer_sheet=self):\n answers[answer.question.id] = answer\n return answers", "def get(self, question_id):\n return specific_question(question_id)", "def get_questions_answered(attempt_id, quiz_id):\n params = {\n 'filter': '{{\"$and\": [{{\"relatedActivities\": {{\"$elemMatch\":{{\"$eq\":\"{u}/mod/quiz/attempt'\n '.php?attempt={a}&cmid={q}\"}}}}}}, {{\"statement.verb.id\":'\n '\"http://adlnet.gov/expapi/verbs/answered\"}}]}}'.format(a=attempt_id, q=quiz_id,\n u=settings.MOODLE_BASE_URL)\n }\n\n resp = connect('api/connection/statement/', 200, 'get', params=params)\n json = resp.json()\n return json", "def get_other_answer_ids(answer_id, question_id):\n SQL = \"\"\"SELECT id FROM answer WHERE question_id = %s AND id != %s;\"\"\"\n data = (question_id, answer_id)\n fetch = \"col\"\n other_answer_ids = db.run_statements(((SQL, data, fetch),))[0]\n return other_answer_ids", "def answerset(answerset_id):\n return render_template('answerset.html', answerset_id=answerset_id, answer_id=[])", "def question(request, id):\r\n q = Question.objects.get(pk = id)\r\n a = q.answer_set.filter(deleted = False).order_by('-created')[:20]\r\n if request.method == 'GET':\r\n aform = aforms.AnswerForm()\r\n payload = {'question':q, 'answers':a, 'aform':aform, }\r\n return render_to_response('moments/question.html', payload, RequestContext(request))", "def get_answer_image_and_q_id(answer_id):\n SQL = \"\"\"SELECT image, question_id FROM answer WHERE id = %s;\"\"\"\n data = (answer_id,)\n fetch = \"one\"\n\n a_img_and_id = db.run_statements(((SQL, data, fetch),))[0]\n return a_img_and_id", "def getSessionAnswers(self, sessionId):\n\t\tanswerResults = Service.db.query(\"SELECT * FROM answers WHERE session_id = %s\", sessionId)\n\t\treturn [self._map(answerResult) for answerResult in answerResults]", "def get_answers(self, workspace_id):\n return QuestionAnswer.objects.filter(\n Q(\n workspace_id=workspace_id,\n document__document_type__stage_num=2\n ) |\n Q(\n workspace_id=workspace_id,\n document__document_type__stage_num=6\n )\n )", "def _get_answer(self, answer_id):\n return self._translate_sent(self.answer_pool[answer_id])", "def get(self):\n return get_all_answers()", "def get(self, course_id, question_id):\n Courses.exists_or_404(course_id)\n question = PostsForQuestions.query.get_or_404(question_id)\n require(READ, question)\n restrict_users = not allow(MANAGE, question)\n\n params = answer_list_parser.parse_args()\n\n if restrict_users and not question.after_judging:\n # only the answer from student himself/herself should be returned\n params['author'] = current_user.id\n\n # this query could be further optimized by reduction the selected columns\n query = PostsForAnswers.query. \\\n with_entities(PostsForAnswers). \\\n options(contains_eager('post').joinedload('files')). \\\n options(contains_eager('post').joinedload('user')). \\\n options(joinedload('scores')). \\\n options(undefer_group('counts')). \\\n join(Posts). \\\n filter(PostsForAnswers.questions_id == question.id)\n\n user_ids = []\n if params['author']:\n query = query.filter(Posts.users_id == params['author'])\n user_ids.append(params['author'])\n elif params['group']:\n # get all user ids in the group\n users = Users.query. \\\n with_entities(Users.id). \\\n join(GroupsAndUsers). \\\n filter(GroupsAndUsers.groups_id == params['group']). \\\n all()\n user_ids = [x[0] for x in users]\n\n if params['ids']:\n query = query.filter(PostsForAnswers.id.in_(params['ids'].split(',')))\n\n # place instructor and TA's answer at the top of the list\n inst_subquery = PostsForAnswers.query.with_entities(PostsForAnswers.id.label('inst_answer')). \\\n join(Posts). \\\n join(CoursesAndUsers, Posts.users_id == CoursesAndUsers.users_id).filter_by(courses_id=course_id). \\\n join(CoursesAndUsers.usertypeforcourse).filter_by(name=UserTypesForCourse.TYPE_INSTRUCTOR)\n ta_subquery = PostsForAnswers.query.with_entities(PostsForAnswers.id.label('ta_answer')). \\\n join(Posts). \\\n join(CoursesAndUsers, Posts.users_id == CoursesAndUsers.users_id).filter_by(courses_id=course_id). \\\n join(CoursesAndUsers.usertypeforcourse).filter_by(name=UserTypesForCourse.TYPE_TA)\n query = query.order_by(PostsForAnswers.id.in_(inst_subquery).desc(), PostsForAnswers.id.in_(ta_subquery).desc())\n\n if params['orderBy'] and len(user_ids) != 1:\n # order answer ids by one criterion and pagination, in case there are multiple criteria in question\n # left join on Scores and add or condition for criteriaandquestions_id is None to include all answers\n # that don't have scores yet\n query = query.outerjoin(Scores).filter(\n or_(Scores.criteriaandquestions_id == params['orderBy'], Scores.criteriaandquestions_id.is_(None)))\n query = query.order_by(Scores.score.desc(), Posts.created.desc())\n else:\n query = query.order_by(Posts.created.desc())\n\n if user_ids:\n query = query.filter(Posts.users_id.in_(user_ids))\n\n page = query.paginate(params['page'], params['perPage'])\n\n on_answer_list_get.send(\n self,\n event_name=on_answer_list_get.name,\n user=current_user,\n course_id=course_id,\n data={'question_id': question_id})\n\n return {\"objects\": marshal(page.items, dataformat.get_posts_for_answers(restrict_users)), \"page\": page.page,\n \"pages\": page.pages, \"total\": page.total, \"per_page\": page.per_page}", "def _is_answer_correct(self, answer_id=int, question_id=int):\n try:\n for question in self.questions_json_list:\n print question\n print \"Q_ID: \" + str(question['id'])\n print \"PASSED Q_ID: \" + str(question_id)\n if question['id'] == question_id:\n print True\n for alternative in question['alternatives']:\n if alternative['id'] == answer_id:\n return alternative['isCorrect']\n\n # for alternative in self.questions_json_list[question_id]['alternatives']:\n # print self.questions_json_list[question_id]['id']\n # print alternative\n # if alternative['id'] == answer_id:\n # return alternative['isCorrect']\n except Exception as ex:\n print ex" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Update answer message in answer tabel where answer_id found.
def update_answer_message(answer_id, message): SQL = """UPDATE answer SET message = %s WHERE id = %s;""" data = (message, answer_id) fetch = None db.run_statements(((SQL, data, fetch),))
[ "def reply_update(self, tweet_id):\n data = self.get_update()\n form = self.format_block_data(data)\n first = General().reply(form[0], tweet_id)\n General().reply(form[1], first)", "def post(self, answerid):\n db = Database()\n votes = db.get_by_argument(\"answers\", \"answer_id\", answerid)\n if votes:\n upvote = votes[5] + 1\n db.update_answer_record(\"answers\", \"up_vote\",\n upvote, \"answer_id\", answerid)\n return{\"message\": \"answer upvoted\"}, 201\n return{\"message\": \"No answer by that answer_id\"}, 404", "def post(self, answerid):\n db = Database()\n votes = db.get_by_argument(\"answers\", \"answer_id\", answerid)\n if votes:\n downvote = votes[6] + 1\n db.update_answer_record(\"answers\", \"down_vote\",\n downvote, \"answer_id\", answerid)\n return{\"message\": \"answer downvoted\"}, 201\n return{\"message\": \"No answer by that answer_id\"}, 404", "def __update_questionnaire(self, patient, answers):\n # Format the answers from list to string like \"[1,0,0,-1]\"\n formatted_answers_str = Questionnaire(). \\\n get_formatted_answers_to_save(answers)\n # Update patient object with answers string\n patient.set_questionnaire(formatted_answers_str)\n\n # Update the patient record for questionnaire.\n FileHandlerUtility().update_a_record(\n patient.get_list_template_to_save(),\n patient.get_patient_id())", "async def delete_answer(self, ctx: Context, question: str, *, answer: str):\n question = await ctx.db.fetchval(\"SELECT question_id from question where content = $1\", question)\n\n if not question:\n return await ctx.send(f\":no_entry: | a question with id `{question}` does not exist.\")\n\n async with ctx.db.acquire():\n check = await ctx.db.execute(\"\"\"DELETE FROM answer where question_id = $1 and LOWER(content) = $2 \n RETURNING answer\"\"\", question, answer.lower())\n\n if check == \"DELETE 0\":\n return await ctx.send(f\"The answer `{answer}` does not exist.\")\n\n await ctx.send(\"> successfully updated.\")", "def _answer_question(self):\n clear_screen()\n print('ANSWER QUESTION')\n body = input('\\nPlease enter the text corresponding to your answer:\\n> ')\n self.db_manager.add_answer(self.question_data['Id'], body, self.user_id)\n clear_screen()\n print('ANSWER QUESTION')\n input('\\nAnswer successfully posted - please enter any key to return to the main menu:\\n> ')", "async def add_answer(self, ctx: Context, content: str, is_correct: bool, *, question: str):\n question_id = await ctx.db.fetchval(\"SELECT question_id from question where LOWER(content) = $1\",\n question.lower())\n if not question_id:\n return await ctx.send(\":no_entry: This question doesn't exist.\")\n\n async with ctx.db.acquire():\n await ctx.db.execute(\"\"\"INSERT INTO answer (question_id, content, is_correct) \n VALUES ($1,$2,$3) ON CONFLICT DO NOTHING\"\"\", question_id, content, is_correct)\n\n await ctx.send(\"> successfully updated.\")", "def submitanswer(request,id):\n if request.method == 'GET':\n return render_to_response('frontend/submit-answer.html',locals())\n \n if request.method == 'POST':\n answer=request.POST.get('answer')\n if answer == '':\n response = \"Please Enter Message.\"\n return render_to_response('frontend/submit-answer.html',locals())\n \n questionobj=Questions.objects.get(id=int(id))\n Answers.objects.create(fk_questions=questionobj,answer=answer)\n \n \n string='done' \n return render_to_response('frontend/submit-answer.html',locals())", "def update_question(questid, userid):\n\n quest = db(current.db.question.id == questid).select().first()\n\n answers_per_level = 3\n\n # first step is to select the related user and question records their should\n # only ever be one of each of these and we update as much as possible here \n # because it's interesting to see as much as possible on viewquest rather\n # than waiting until 3 people have answered and it can be scored - however this can result in\n # a degree of double updating\n\n if quest.intunpanswers >= answers_per_level:\n redirect(URL('score_question', args=quest.id))\n else:\n # need to have another look at this \n # intunpanswers < answers_per_level\n # the general requirement here is to do nothing - however because the\n # solution focuses on solving the highest priority question at all times\n # different users may be sent the same question at the same time and\n # answers may be received for a level after the question is either promoted\n # or resolved - promotions shouldn't be an issue but resolved questions are\n # because the user should probably get credit if right and nothing if wrong\n # and an explanation of what happend\n\n if quest.status == 'Resolved' or quest.status == 'Agreed':\n # get the score - if right add to score - if wrong same\n # update userquestion and user - other stuff doesn't apply\n # scoretable = current.db(current.db.scoring.level == quest.level).select(cache=(cache.ram, 1200), cacheable=True).first()\n scoretable = current.db(current.db.scoring.level == quest.level).select().first()\n if scoretable is None:\n score = 30\n wrong = 1\n else:\n if quest.qtype != 'action':\n score = scoretable.correct\n wrong = scoretable.wrong\n else:\n score = scoretable.rightaction\n wrong = scoretable.wrongaction\n numcorrect = 0\n numwrong = 0\n numpassed = 0\n\n if uq.answer == quest.correctans:\n updscore = score\n numcorrect = 1\n elif uq.answer == 0:\n updscore = 1\n numpasse = 1\n else:\n updscore = wrong\n numwrong = 1\n\n uq.update_record(status='Resolved', score=updscore, resolvedate=request.utcnow)\n\n updateuser(userid, updscore, numcorrect, numwrong, numpassed)\n\n redirect(URL('viewquest', 'index', args=quest.id))", "def remove_accept_mark(answer_id):\n SQL = \"\"\"UPDATE answer SET accepted = false WHERE accepted = true and id = %s;\"\"\"\n data = (answer_id,)\n fetch = None\n db.run_statements(((SQL, data, fetch),))", "def delete(self, answer_id):\n le_answer = get_an_answer(answer_id)\n if not le_answer:\n return {'success': False, 'msg': 'answer does not exist'}\n else:\n return delete_a_answer(answer_id)", "def _get_answer(self, answer_id):\n return self._translate_sent(self.answer_pool[answer_id])", "def set_answer(answers, assessment_name, answer):\n if not answers.data:\n score_dict = {}\n else:\n score_dict = json.loads(answers.data)\n score_dict[assessment_name] = answer\n answers.data = json.dumps(score_dict)", "def update(self, answer):\n item = self.items[answer.user_id, answer.place_id]\n\n if not item.practices:\n self.prior.update(answer)\n\n prediction = self.predict(answer)\n self.predictions[answer.id] = prediction\n\n item.add_practice(answer)\n\n if answer.is_correct:\n item.inc_knowledge(self.gamma * (1 - prediction))\n else:\n item.inc_knowledge(self.delta * prediction)", "def update(self, message_json):\n message_in_db = self.load_by_id(message_json['uid'])[0]\n if message_in_db:\n query = \"\"\"UPDATE message SET sender=\"{0}\", receiver=\"{1}\", \n message=\"{2}\", subject=\"{3}\", unread={4} WHERE id={5}\"\"\".format(\n message_json['sender'],\n message_json['receiver'],\n message_json['message'],\n message_json['subject'],\n 1,\n message_in_db['uid']\n )\n\n db = get_db()\n db.execute(query)\n db.commit()", "def answer_question(self, student_id, question_id, option_id):\n ques = self.get_question(question_id)\n is_student_eligible, student = self.student_eligible(student_id)\n if ques and is_student_eligible:\n if ques.get_right_answer() and option_id == ques.get_right_answer().option_id:\n self.add_student_score(student, 1)", "def patch(self, _id: str) -> tuple:\n json_data = json.loads(request.data, encoding='utf-8')\n result = QuestionDao.update(_id, json_data), 200\n if result:\n return result\n api.abort(400)", "def answer(self, answer):\n if answer is None:\n raise ValueError(\"Invalid value for `answer`, must not be `None`\")\n\n self._answer = answer", "def test_api_update_question(self):\r\n chg_question = {'question_text': 'Are you hungery?'}\r\n res = self.client.put(\r\n reverse('details', kwargs={'pk': question.id}),\r\n chg_question, format='json'\r\n )\r\n self.assertEqual(res.status_code, status.HTTP_200_OK)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove answer record and its image, then return its question_id.
def remove_answer_and_get_q_id(answer_id): image_to_delete, question_id = get_answer_image_and_q_id(answer_id) if image_to_delete: try: os.remove("static/uploads/" + image_to_delete) except (FileNotFoundError, TypeError): pass delete_answer_by_id(answer_id) return question_id
[ "def remove_answer_image(answer_id):\n SQL = \"\"\"UPDATE answer SET image = NULL WHERE id = %s;\"\"\"\n data = (answer_id,)\n fetch = None\n db.run_statements(((SQL, data, fetch),))", "def delete_a_image(answer_id):\n current_image = get_answer_image(answer_id)\n if current_image:\n remove_answer_image(answer_id)\n try:\n os.remove(\"static/uploads/\" + current_image)\n except FileNotFoundError:\n pass", "def delete_selected_answer(self, instance, answer):\n\n del instance\n if answer == 'yes':\n app = App.get_running_app()\n self.viewer.stop()\n fullpath = self.fullpath\n filename = self.photo\n if self.type == 'Tag':\n app.Tag.remove(fullpath, self.target, message=True)\n deleted = True\n else:\n photo_info = app.Photo.exist(fullpath)\n deleted = app.Photo.delete_file(fullpath, filename, message=True)\n if deleted:\n if photo_info:\n app.update_photoinfo(folders=photo_info[1])\n if deleted:\n app.photos.commit()\n if len(self.photos) == 1:\n app.show_database()\n else:\n self.next_photo()\n Cache.remove('kv.loader')\n self.cache_nearby_images()\n #Cache.remove('kv.image')\n #Cache.remove('kv.texture')\n self.update_tags()\n self.update_treeview()\n self.dismiss_popup()", "def delete_question(self,iQuestionID):", "def get_answer_image_and_q_id(answer_id):\n SQL = \"\"\"SELECT image, question_id FROM answer WHERE id = %s;\"\"\"\n data = (answer_id,)\n fetch = \"one\"\n\n a_img_and_id = db.run_statements(((SQL, data, fetch),))[0]\n return a_img_and_id", "def delquestion():\n try:\n id = request.form['id']\n models.Question.objects.get(id=id).delete()\n return \"\"\n except:\n print traceback.print_exc()", "async def remove_question(self, ctx, question_number:int):\n return", "async def delete_answer(self, ctx: Context, question: str, *, answer: str):\n question = await ctx.db.fetchval(\"SELECT question_id from question where content = $1\", question)\n\n if not question:\n return await ctx.send(f\":no_entry: | a question with id `{question}` does not exist.\")\n\n async with ctx.db.acquire():\n check = await ctx.db.execute(\"\"\"DELETE FROM answer where question_id = $1 and LOWER(content) = $2 \n RETURNING answer\"\"\", question, answer.lower())\n\n if check == \"DELETE 0\":\n return await ctx.send(f\"The answer `{answer}` does not exist.\")\n\n await ctx.send(\"> successfully updated.\")", "def delete(self, answer_id):\n le_answer = get_an_answer(answer_id)\n if not le_answer:\n return {'success': False, 'msg': 'answer does not exist'}\n else:\n return delete_a_answer(answer_id)", "def remove_attachment(self, request, pk):\n answer = self.get_object()\n\n if answer.state == models.ReferralAnswerState.PUBLISHED:\n return Response(\n status=400,\n data={\n \"errors\": [\"attachments cannot be removed from a published answer\"]\n },\n )\n\n try:\n attachment = answer.attachments.get(id=request.data.get(\"attachment\"))\n except models.ReferralAnswerAttachment.DoesNotExist:\n return Response(\n status=400,\n data={\n \"errors\": [\n (\n f\"referral answer attachment {request.data.get('attachment')} \"\n \"does not exist\"\n )\n ]\n },\n )\n\n answer.attachments.remove(attachment)\n answer.refresh_from_db()\n\n return Response(status=200, data=ReferralAnswerSerializer(answer).data)", "def delete_answer_by_id(answer_id):\n SQL = \"\"\"DELETE FROM answer WHERE id = %s;\"\"\"\n data = (answer_id,)\n fetch = None\n db.run_statements(((SQL, data, fetch),))", "def delete_answer_by_id(conn, answer_id):\n SQL = \"\"\"DELETE FROM answer WHERE id = %s;\"\"\"\n data = (answer_id,)\n with conn.cursor() as cursor:\n cursor.execute(SQL, data)", "def delete_survey(self,iSurveyID):", "def img_delete_by_id(self, img_id: int) -> None:\n img = self.img_by_id(img_id)\n if img:\n self.__session.delete(img)\n self.commit()\n else:\n print('No such image')", "def db_delete_one_image(imgId):\n\tprint \"delete one image from database: \"+ str(imgId)\n\timage\t\t\t= Picture.objects.get(pk=imgId)\n\timage.visible \t= False\n\timage.save()", "def delete_image(self, http_request, image_id):\n image = self.image_by_id(image_id)\n if image:\n self.glance_admin_image_store.remove(image)\n http_request.setResponseCode(204)\n return b''\n http_request.setResponseCode(404)\n return b''", "def delete_answer(request, pk):\n return delete(request, pk, True)", "def delete_image(self, index):\n if isinstance(index, int) == False or index > self.maximum_image_count:\n raise Exception(\n \"Index for deletion should be smaller integer than maximum_image_count\")\n # Delete the image from the image list by\n # poping the entry out of the dictionary!\n self.image_list.pop(index, None)", "def delete_question(self, data, suffix=''):\n q_id = int(data['question_id'])\n print self.questions_json_list\n try:\n for i in range(0, len(self.questions_json_list)):\n # print self.questions_json_list[i]['id']\n # print q_id\n if self.questions_json_list[i]['id'] == q_id:\n del self.questions_json_list[i]\n break\n print self.questions_json_list\n return {'status': 'successful'}\n except Exception as ex:\n return {'status': 'unsuccessful', 'message': str(ex), 'pos': self.questions_json_list[0],\n 'index': q_id}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Deletes answer by answer ID.
def delete_answer_by_id(answer_id): SQL = """DELETE FROM answer WHERE id = %s;""" data = (answer_id,) fetch = None db.run_statements(((SQL, data, fetch),))
[ "def delete(self, answer_id):\n le_answer = get_an_answer(answer_id)\n if not le_answer:\n return {'success': False, 'msg': 'answer does not exist'}\n else:\n return delete_a_answer(answer_id)", "def delete_answer_by_id(conn, answer_id):\n SQL = \"\"\"DELETE FROM answer WHERE id = %s;\"\"\"\n data = (answer_id,)\n with conn.cursor() as cursor:\n cursor.execute(SQL, data)", "async def delete_answer(self, ctx: Context, question: str, *, answer: str):\n question = await ctx.db.fetchval(\"SELECT question_id from question where content = $1\", question)\n\n if not question:\n return await ctx.send(f\":no_entry: | a question with id `{question}` does not exist.\")\n\n async with ctx.db.acquire():\n check = await ctx.db.execute(\"\"\"DELETE FROM answer where question_id = $1 and LOWER(content) = $2 \n RETURNING answer\"\"\", question, answer.lower())\n\n if check == \"DELETE 0\":\n return await ctx.send(f\"The answer `{answer}` does not exist.\")\n\n await ctx.send(\"> successfully updated.\")", "def delquestion():\n try:\n id = request.form['id']\n models.Question.objects.get(id=id).delete()\n return \"\"\n except:\n print traceback.print_exc()", "def delete_answer(request, pk):\n return delete(request, pk, True)", "def delete_question(self,iQuestionID):", "def delete(self, _id: str):\n result = QuestionDao.delete(_id), 204\n if result:\n return '', 204\n api.abort(400)", "def remove_answer_and_get_q_id(answer_id):\n image_to_delete, question_id = get_answer_image_and_q_id(answer_id)\n if image_to_delete:\n try:\n os.remove(\"static/uploads/\" + image_to_delete)\n except (FileNotFoundError, TypeError):\n pass\n\n delete_answer_by_id(answer_id)\n return question_id", "def quiz_delete(request, quiz_id):\n quiz = get_object_or_404(Quiz, id=quiz_id)\n quiz.delete()\n request.user.message_set.create(message=_(\"Quiz Deleted.\"))\n \n return HttpResponseRedirect(reverse(\"quiz.views.quiz_view_all\"))", "def delete_survey(self,iSurveyID):", "def delete_selected_answer(self, instance, answer):\n\n del instance\n if answer == 'yes':\n app = App.get_running_app()\n self.viewer.stop()\n fullpath = self.fullpath\n filename = self.photo\n if self.type == 'Tag':\n app.Tag.remove(fullpath, self.target, message=True)\n deleted = True\n else:\n photo_info = app.Photo.exist(fullpath)\n deleted = app.Photo.delete_file(fullpath, filename, message=True)\n if deleted:\n if photo_info:\n app.update_photoinfo(folders=photo_info[1])\n if deleted:\n app.photos.commit()\n if len(self.photos) == 1:\n app.show_database()\n else:\n self.next_photo()\n Cache.remove('kv.loader')\n self.cache_nearby_images()\n #Cache.remove('kv.image')\n #Cache.remove('kv.texture')\n self.update_tags()\n self.update_treeview()\n self.dismiss_popup()", "def delete_example(self, id):\n if id in self.examples:\n del self.examples[id]", "def delete(self, request, pk):\n answer = get_object_or_404(Answer, pk=pk)\n user = request.user\n\n answer.down_voters.remove(user)\n answer.save()\n\n serializer_context = {\"request\": request}\n serializer = self.serializer_class(answer, context=serializer_context)\n\n return Response(serializer.data, status=status.HTTP_200_OK)", "def delete_question(payload, drink_id):\n try:\n drink = Drink.query.get(drink_id)\n except Exception:\n abort(422)\n # Make sure the question we want to delete exists\n if not drink:\n abort(404)\n try:\n drink.delete()\n except Exception:\n abort(422)\n return jsonify({\n 'success': True,\n 'deleted': drink_id\n })", "def test_delete_question_successfully(self):\n response = self.client().post(\n '/questions', json=self.test_question, headers=self.admin_header)\n response_id = json.loads(response.data).get('id')\n\n response = self.client().delete(\n f'/questions/{response_id}', headers=self.admin_header)\n self.assertEqual(response.status_code, HTTP_STATUS.NO_CONTENT)", "def delete(self, request, pk):\n answer = get_object_or_404(Answer, pk=pk)\n user = request.user\n\n answer.up_voters.remove(user)\n answer.save()\n\n serializer_context = {\"request\": request}\n serializer = self.serializer_class(answer, context=serializer_context)\n\n return Response(serializer.data, status=status.HTTP_200_OK)", "def delete_a_image(answer_id):\n current_image = get_answer_image(answer_id)\n if current_image:\n remove_answer_image(answer_id)\n try:\n os.remove(\"static/uploads/\" + current_image)\n except FileNotFoundError:\n pass", "def del_exam_result_by_id(f,exam_result_id): # noqa: E501\n if check_authorization(f,\"can_delete_exam_result_by_id\") == False:\n return jsonify({\"message\":\"the user dont has permision to request\"}), 400\n \n item= session.query(Exam_results_instants).filter(Exam_results_instants.id == exam_result_id).first()\n if item == None:\n return errors[\"404\"][0],errors[\"404\"][1]\n delete_data(item)\n return 'success'", "def delete(self, id): \n post = delete(id)\n return post" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }