seq_id
stringlengths
7
11
text
stringlengths
156
1.7M
repo_name
stringlengths
7
125
sub_path
stringlengths
4
132
file_name
stringlengths
4
77
file_ext
stringclasses
6 values
file_size_in_byte
int64
156
1.7M
program_lang
stringclasses
1 value
lang
stringclasses
38 values
doc_type
stringclasses
1 value
stars
int64
0
24.2k
dataset
stringclasses
1 value
pt
stringclasses
1 value
7161765994
from typing import List class Solution: def calculate(self, nums, k, max_len, s, nums_len): if nums[s:] == []: print("max_len=",max_len) return max_len else: i = 0 temp = k ans = [] temp_nums = nums[s:] print("nums=", temp_nums) while i != len(temp_nums): if temp == 0 and temp_nums[i] == 0: break else: print("*=", temp_nums[i]) if temp_nums[i] == 1: ans.append(temp_nums[i]) elif temp_nums[i] == 0: temp = temp - 1 ans.append(1) i += 1 print("###########################") max_len = max(max_len, len(ans)) print("max=",max_len) s = s + 1 print("s=",s) self.calculate(nums, k, max_len, s, nums_len) def longestOnes(self, nums: List[int], k: int) -> int: max_len = 0 max_len = self.calculate(nums, k, max_len, 0, len(nums)) # print(max_len) obj = Solution() obj.longestOnes([1,1,1,0,0,0,1,1,1,1,0],2) obj.longestOnes([0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1],3)
CompetitiveCodingLeetcode/LeetcodeEasy
JuneLeetcodeChallenge/MaxConsecutiveOnesIII.py
MaxConsecutiveOnesIII.py
py
1,280
python
en
code
0
github-code
6
22095502736
from django.urls import path from user import views urlpatterns = [ path('fun',views.fun), path('fun1',views.fun1), path('u',views.us, name='uuu'), path('user',views.user, name='aaaa'), ]
anshifmhd/demo
user/urls.py
urls.py
py
205
python
en
code
0
github-code
6
37895365689
# Python Number Guessing Game import random game_over = False # To check if out of guesses. guesses = 0 # Set value for guesses def play_again(): """Function to reset game""" global game_over if again == 'y': game_over = False def check_num(): """Function to check if guess is correct, if not tell high or low.""" global guesses global game_over if current_guess > 100 or current_guess < 1: print("You number is not in range.") elif current_guess == secret_number: print("You are correct!") game_over = True elif current_guess < secret_number: print("That is too low.") elif current_guess > secret_number: print("That is too high.") while not game_over: # Pick random number between 1 - 100 for player to guess. secret_number = random.randint(1, 100) # Ask if easy or hard mode, set guesses hard = 5, easy = 10. mode = input("Do you wish to play on Easy 'e' or Hard 'h' mode?: ") if mode == "e": guesses = 10 elif mode == "h": guesses = 5 # Ask player to guess a number current_guess = int(input("What number do you guess?: ")) while guesses > 0: check_num() guesses -= 1 if game_over: again = input("Do you wish to play again?: ") play_again() break # Tell number of remaining guesses and ask for new guess. current_guess = int(input(f"You have {guesses} guesses remaining. Pick another number.: "))
agentc13/number-guessing-project
main.py
main.py
py
1,530
python
en
code
0
github-code
6
14565939884
# Input: s and t : strings # Output: bool # Input: s = "anagram", t = "nagaram" # Output: true # QED def is_anagram(s: str, t: str) -> bool: return sorted(s) == sorted(t) # Input: s and t: str # Output: true or false: bool # We'll frequency count # Loop through strings s and t, then store the chars # and freqs for s in s_dict. do the same for t in the same loop # Loop through one of the maps and check if the value at that key # corresponds with the value at that key in the other map # If there's a mismatch, return false early # Once loop ends return true def is_anagram_2(s: str, t: str) -> bool: if len(s) != len(t): return False s_map = {} t_map = {} for idx in range(len(s)): s_char = s[idx] t_char = t[idx] s_map[s_char] = s_map.get(s_char, 0) + 1 t_map[t_char] = t_map.get(t_char, 0) + 1 for k, v in s_map: if v != t_map.get(k): return False return True # Longest substring without repeating characters # Given a string s, find the length of the longest substring without repeating characters. # Sample input: "abcabcbb" # Expected output: 3 # We need a count and a map to store characters # Double loop through the string # if we have not seen a character in our current iteration (if map value is 0) # - increase the freq of the char in the map # - update max # - update max_count if it is longer # else # - add item to map # - break inner loop def length_of_longest_substring_naive(s: str) -> int: max_count = 0 for start_idx in range(len(s)): char_map = {} curr_count = 0 for end_idx in range(start_idx, len(s)): curr_char = s[end_idx] curr_char_count = char_map.get(curr_char, 0) if curr_char_count != 0: break else: char_map[curr_char] = 1 curr_count = curr_count + 1 max_count = max(max_count, curr_count) return max_count # Loop through string with a dynamic sliding window # If char exists in map # - Move window start forward until no duplicates exist in the window # - reduce the curr window count # Else # - Add the char to map # - update the window count # - update the max count # Sample input: "abcabcbb" # Expected output:3 def length_of_longest_substring_optimised(s: str) -> int: window_start = 0 curr_count = 0 max_count = 0 s_map = {} for window_end in range(len(s)): curr_count = curr_count + 1 curr_char = s[window_end] char_frequency = s_map.get(curr_char, 0) + 1 s_map[curr_char] = char_frequency while char_frequency > 1: char_frequency = char_frequency - 1 s_map[curr_char] = char_frequency window_start = window_start + 1 curr_count = curr_count - 1 max_count = max(max_count, curr_count) return max_count
HemlockBane/ds_and_algo
strings/study_questions.py
study_questions.py
py
2,921
python
en
code
0
github-code
6
29214262320
import os.path import unittest from pathlib import Path from sflkit.analysis.analysis_type import AnalysisType from sflkit.analysis.spectra import Spectrum from sflkit.analysis.suggestion import Location from tests4py import framework from tests4py.constants import DEFAULT_WORK_DIR from utils import BaseTest class TestSFL(BaseTest): @unittest.skip def test_middle(self): project_name = "middle" bug_id = 2 report = framework.default.tests4py_checkout(project_name, bug_id) if report.raised: raise report.raised src = Path(report.location) dst = DEFAULT_WORK_DIR / "sfl" report = framework.sfl.tests4py_sfl_instrument(src, dst) if report.raised: raise report.raised dst_src = dst / "src" dst_src_middle = dst_src / "middle" dst_src_middle___init___py = dst_src_middle / "__init__.py" dst_tests = dst / "tests" dst_tests_test_middle_py = dst_tests / "test_middle.py" dst_gitignore = dst / ".gitignore" dst_license = dst / "LICENSE" dst_readme_md = dst / "README.md" dst_setup_cfg = dst / "setup.cfg" dst_setup_py = dst / "setup.py" src_src = src / "src" src_src_middle = src_src / "middle" src_src_middle___init___py = src_src_middle / "__init__.py" src_tests = src / "tests" src_tests_test_middle_py = src_tests / "test_middle.py" src_gitignore = src / ".gitignore" src_license = src / "LICENSE" src_readme_md = src / "README.md" src_setup_cfg = src / "setup.cfg" src_setup_py = src / "setup.py" exist_files = [ dst_src_middle___init___py, dst_tests_test_middle_py, dst_gitignore, dst_license, dst_readme_md, dst_setup_cfg, dst_setup_py, ] exist_dirs = [dst_src, dst_src_middle, dst_tests] for d in exist_dirs: self.assertTrue(d.exists()) self.assertTrue(d.is_dir()) for f in exist_files: self.assertTrue(f.exists()) self.assertTrue(f.is_file()) for d, s in [ (dst_tests_test_middle_py, src_tests_test_middle_py), (dst_gitignore, src_gitignore), (dst_license, src_license), (dst_readme_md, src_readme_md), (dst_setup_cfg, src_setup_cfg), (dst_setup_py, src_setup_py), ]: with open(d, "r") as fp: d_content = fp.read() with open(s, "r") as fp: s_content = fp.read() self.assertEqual(s_content, d_content, f"{d} has other content then {s}") for d, s in [ (dst_src_middle___init___py, src_src_middle___init___py), ]: with open(d, "r") as fp: d_content = fp.read() with open(s, "r") as fp: s_content = fp.read() self.assertNotEqual( s_content, d_content, f"{d} has the same content then {s}" ) report = framework.sfl.tests4py_sfl_events(dst) if report.raised: raise report.raised report = framework.sfl.tests4py_sfl_analyze(dst, src, predicates="line") if report.raised: raise report.raised suggestions = report.analyzer.get_sorted_suggestions( base_dir=src, type_=AnalysisType.LINE, metric=Spectrum.Ochiai, ) self.assertAlmostEqual( 0.7071067811865475, suggestions[0].suspiciousness, delta=0.0000001 ) self.assertEqual(1, len(suggestions[0].lines)) self.assertIn( Location(os.path.join("src", "middle", "__init__.py"), 6), suggestions[0].lines, )
smythi93/Tests4Py
tests/test_sfl.py
test_sfl.py
py
3,851
python
en
code
8
github-code
6
22175885434
# Author:Zhang Yuan from MyPackage import * import numpy as np import pandas as pd import matplotlib.pyplot as plt import matplotlib.patches as patches import seaborn as sns import statsmodels.api as sm from scipy import stats # ------------------------------------------------------------ __mypath__ = MyPath.MyClass_Path("") # 路径类 mylogging = MyDefault.MyClass_Default_Logging(activate=False) # 日志记录类,需要放在上面才行 myfile = MyFile.MyClass_File() # 文件操作类 myword = MyFile.MyClass_Word() # word生成类 myexcel = MyFile.MyClass_Excel() # excel生成类 myini = MyFile.MyClass_INI() # ini文件操作类 mytime = MyTime.MyClass_Time() # 时间类 myparallel = MyTools.MyClass_ParallelCal() # 并行运算类 myplt = MyPlot.MyClass_Plot() # 直接绘图类(单个图窗) mypltpro = MyPlot.MyClass_PlotPro() # Plot高级图系列 myfig = MyPlot.MyClass_Figure(AddFigure=False) # 对象式绘图类(可多个图窗) myfigpro = MyPlot.MyClass_FigurePro(AddFigure=False) # Figure高级图系列 myplthtml = MyPlot.MyClass_PlotHTML() # 画可以交互的html格式的图 mypltly = MyPlot.MyClass_Plotly() # plotly画图相关 mynp = MyArray.MyClass_NumPy() # 多维数组类(整合Numpy) mypd = MyArray.MyClass_Pandas() # 矩阵数组类(整合Pandas) mypdpro = MyArray.MyClass_PandasPro() # 高级矩阵数组类 myDA = MyDataAnalysis.MyClass_DataAnalysis() # 数据分析类 myDefault = MyDefault.MyClass_Default_Matplotlib() # 画图恢复默认设置类 # myMql = MyMql.MyClass_MqlBackups() # Mql备份类 # myBaidu = MyWebCrawler.MyClass_BaiduPan() # Baidu网盘交互类 # myImage = MyImage.MyClass_ImageProcess() # 图片处理类 myBT = MyBackTest.MyClass_BackTestEvent() # 事件驱动型回测类 myBTV = MyBackTest.MyClass_BackTestVector() # 向量型回测类 myML = MyMachineLearning.MyClass_MachineLearning() # 机器学习综合类 mySQL = MyDataBase.MyClass_MySQL(connect=False) # MySQL类 mySQLAPP = MyDataBase.MyClass_SQL_APPIntegration() # 数据库应用整合 myWebQD = MyWebCrawler.MyClass_QuotesDownload(tushare=False) # 金融行情下载类 myWebR = MyWebCrawler.MyClass_Requests() # Requests爬虫类 myWebS = MyWebCrawler.MyClass_Selenium(openChrome=False) # Selenium模拟浏览器类 myWebAPP = MyWebCrawler.MyClass_Web_APPIntegration() # 爬虫整合应用类 myEmail = MyWebCrawler.MyClass_Email() # 邮箱交互类 myReportA = MyQuant.MyClass_ReportAnalysis() # 研报分析类 myFactorD = MyQuant.MyClass_Factor_Detection() # 因子检测类 myKeras = MyDeepLearning.MyClass_tfKeras() # tfKeras综合类 myTensor = MyDeepLearning.MyClass_TensorFlow() # Tensorflow综合类 myMT5 = MyMql.MyClass_ConnectMT5(connect=False) # Python链接MetaTrader5客户端类 myMT5Pro = MyMql.MyClass_ConnectMT5Pro(connect=False) # Python链接MT5高级类 myMT5Indi = MyMql.MyClass_MT5Indicator() # MT5指标Python版 myMT5Report = MyMT5Report.MyClass_StratTestReport(AddFigure=False) # MT5策略报告类 myMT5Analy = MyMT5Analysis.MyClass_ForwardAnalysis() # MT5分析类 myMT5Lots_Fix = MyMql.MyClass_Lots_FixedLever(connect=False) # 固定杠杆仓位类 myMT5Lots_Dy = MyMql.MyClass_Lots_DyLever(connect=False) # 浮动杠杆仓位类 myMT5run = MyMql.MyClass_RunningMT5() # Python运行MT5 myMT5code = MyMql.MyClass_CodeMql5() # Python生成MT5代码 myMoneyM = MyTrade.MyClass_MoneyManage() # 资金管理类 myDefault.set_backend_default("Pycharm") # Pycharm下需要plt.show()才显示图 # ------------------------------------------------------------ # Jupyter Notebook 控制台显示必须加上:%matplotlib inline ,弹出窗显示必须加上:%matplotlib auto # %matplotlib inline # import warnings # warnings.filterwarnings('ignore') # %% # 简介 # A CNN-LSTM-Based Model to Forecast Stock Prices (Wenjie Lu, Jiazheng Li, Yifan Li, Aijun Sun, Jingyang Wang, Complexity magazine, vol. 2020, Article ID 6622927, 10 pages, 2020) 一文的作者比较了各种股票价格预测模型: # 股票价格数据具有时间序列的特点。 # 同时,基于机器学习长短期记忆(LSTM)具有通过记忆功能分析时间序列数据之间关系的优势,我们提出了一种基于CNN-LSTM的股票价格预测方法。 # 同时,我们使用MLP、CNN、RNN、LSTM、CNN-RNN等预测模型逐一对股票价格进行了预测。此外,还对这些模型的预测结果进行了分析和比较。 # 本研究利用的数据涉及1991年7月1日至2020年8月31日的每日股票价格,包括7127个交易日。 # 在历史数据方面,我们选择了八个特征,包括开盘价、最高价、最低价、收盘价、成交量、成交额、涨跌幅和变化。 # 首先,我们采用CNN从数据中有效提取特征,即前10天的项目。然后,我们采用LSTM,用提取的特征数据来预测股票价格。 # 根据实验结果,CNN-LSTM可以提供可靠的股票价格预测,并且预测精度最高。 # 这种预测方法不仅为股票价格预测提供了一种新的研究思路,也为学者们研究金融时间序列数据提供了实践经验。 # 在所有考虑的模型中,CNN-LSTM模型在实验中产生了最好的结果。在这篇文章中,我们将考虑如何创建这样一个模型来预测金融时间序列,以及如何在MQL5专家顾问中使用创建的ONNX模型。 #%% #Python libraries import matplotlib.pyplot as plt import MetaTrader5 as mt5 import tensorflow as tf import numpy as np import pandas as pd import tf2onnx from sklearn.model_selection import train_test_split from sys import argv #check tensorflow version print(tf.__version__) #check GPU support print(len(tf.config.list_physical_devices('GPU'))>0) #initialize MetaTrader5 for history data if not mt5.initialize(): print("initialize() failed, error code =",mt5.last_error()) quit() #show terminal info terminal_info=mt5.terminal_info() print(terminal_info) #show file path file_path=terminal_info.data_path+"\\MQL5\\Files\\" print(file_path) #data path to save the model # data_path=argv[0] # last_index=data_path.rfind("\\")+1 # data_path=data_path[0:last_index] data_path = __mypath__.get_desktop_path() + "\\" print("data path to save onnx model",data_path) #set start and end dates for history data from datetime import timedelta,datetime end_date = datetime.now() start_date = end_date - timedelta(days=120) #print start and end dates print("data start date=",start_date) print("data end date=",end_date) #get EURUSD rates (H1) from start_date to end_date eurusd_rates = mt5.copy_rates_range("EURUSD", mt5.TIMEFRAME_H1, start_date, end_date) #create dataframe df = pd.DataFrame(eurusd_rates) df.head() df.shape #prepare close prices only data = df.filter(['close']).values #show close prices plt.figure(figsize = (18,10)) plt.plot(data,'b',label = 'Original') plt.xlabel("Hours") plt.ylabel("Price") plt.title("EURUSD_H1") plt.legend() plt.show() #%% #scale data using MinMaxScaler from sklearn.preprocessing import MinMaxScaler scaler=MinMaxScaler(feature_range=(0,1)) scaled_data = scaler.fit_transform(data) #training size is 80% of the data training_size = int(len(scaled_data)*0.80) print("training size:",training_size) #create train data and check size train_data_initial = scaled_data[0:training_size,:] print(len(train_data_initial)) #create test data and check size test_data_initial= scaled_data[training_size:,:1] print(len(test_data_initial)) #split a univariate sequence into samples def split_sequence(sequence, n_steps): X, y = list(), list() for i in range(len(sequence)): #find the end of this pattern end_ix = i + n_steps #check if we are beyond the sequence if end_ix > len(sequence)-1: break #gather input and output parts of the pattern seq_x, seq_y = sequence[i:end_ix], sequence[end_ix] X.append(seq_x) y.append(seq_y) return np.array(X), np.array(y) #split into samples time_step = 120 x_train, y_train = split_sequence(train_data_initial, time_step) x_test, y_test = split_sequence(test_data_initial, time_step) #reshape input to be [samples, time steps, features] which is required for LSTM x_train =x_train.reshape(x_train.shape[0],x_train.shape[1],1) x_test = x_test.reshape(x_test.shape[0],x_test.shape[1],1) #%% #import keras libraries for the model import math from keras.models import Sequential from keras.layers import Dense,Activation,Conv1D,MaxPooling1D,Dropout from keras.layers import LSTM from keras.utils.vis_utils import plot_model from keras.metrics import RootMeanSquaredError as rmse from keras import optimizers #define the model model = Sequential() model.add(Conv1D(filters=256, kernel_size=2,activation='relu',padding = 'same',input_shape=(120,1))) model.add(MaxPooling1D(pool_size=2)) model.add(LSTM(100, return_sequences = True)) model.add(Dropout(0.3)) model.add(LSTM(100, return_sequences = False)) model.add(Dropout(0.3)) model.add(Dense(units=1, activation = 'sigmoid')) model.compile(optimizer='adam', loss= 'mse' , metrics = [rmse()]) #show model model.summary() #measure time import time time_calc_start = time.time() #fit model with 300 epochs history=model.fit(x_train,y_train,epochs=300,validation_data=(x_test,y_test),batch_size=32,verbose=1) #calculate time fit_time_seconds = time.time() - time_calc_start print("fit time =",fit_time_seconds," seconds.") #show training history keys history.history.keys() #show iteration-loss graph for training and validation plt.figure(figsize = (18,10)) plt.plot(history.history['loss'],label='Training Loss',color='b') plt.plot(history.history['val_loss'],label='Validation-loss',color='g') plt.xlabel("Iteration") plt.ylabel("Loss") plt.title("LOSS") plt.legend() plt.show() #show iteration-rmse graph for training and validation plt.figure(figsize = (18,10)) plt.plot(history.history['root_mean_squared_error'],label='Training RMSE',color='b') plt.plot(history.history['val_root_mean_squared_error'],label='Validation-RMSE',color='g') plt.xlabel("Iteration") plt.ylabel("RMSE") plt.title("RMSE") plt.legend() plt.show() #evaluate training data model.evaluate(x_train, y_train, batch_size = 32) #evaluate testing data model.evaluate(x_test, y_test, batch_size = 32) #prediction using training data train_predict = model.predict(x_train) plot_y_train = y_train.reshape(-1,1) #show actual vs predicted (training) graph plt.figure(figsize=(18,10)) plt.plot(scaler.inverse_transform(plot_y_train),color = 'b', label = 'Original') plt.plot(scaler.inverse_transform(train_predict),color='red', label = 'Predicted') plt.title("Prediction Graph Using Training Data") plt.xlabel("Hours") plt.ylabel("Price") plt.legend() plt.show() #prediction using testing data test_predict = model.predict(x_test) plot_y_test = y_test.reshape(-1,1) #%% # 为了计算度量,我们需要将数据从区间[0,1]转换过来。同样,我们使用MinMaxScaler。 #calculate metrics from sklearn import metrics from sklearn.metrics import r2_score #transform data to real values value1=scaler.inverse_transform(plot_y_test) value2=scaler.inverse_transform(test_predict) #calc score score = np.sqrt(metrics.mean_squared_error(value1,value2)) print("RMSE : {}".format(score)) print("MSE :", metrics.mean_squared_error(value1,value2)) print("R2 score :",metrics.r2_score(value1,value2)) #show actual vs predicted (testing) graph plt.figure(figsize=(18,10)) plt.plot(scaler.inverse_transform(plot_y_test),color = 'b', label = 'Original') plt.plot(scaler.inverse_transform(test_predict),color='g', label = 'Predicted') plt.title("Prediction Graph Using Testing Data") plt.xlabel("Hours") plt.ylabel("Price") plt.legend() plt.show() # save model to ONNX output_path = data_path+"model.eurusd.H1.120.onnx" onnx_model = tf2onnx.convert.from_keras(model, output_path=output_path) print(f"model saved to {output_path}") # 保存到MQL5的Files中 output_path = file_path+"model.eurusd.H1.120.onnx" onnx_model = tf2onnx.convert.from_keras(model, output_path=output_path) print(f"saved model to {output_path}") # finish mt5.shutdown() # Python脚本的完整代码附在文章的Jupyter笔记本中。 # 在《基于CNN-LSTM的模型预测股票价格》一文中,采用CNN-LSTM架构的模型获得了R^2=0.9646的最佳结果。在我们的例子中,CNN-LSTM网络产生的最佳结果是R^2=0.9684。根据这些结果,这种类型的模型在解决预测问题时可以很有效率。 # 我们考虑了一个Python脚本的例子,它建立和训练CNN-LSTM模型来预测金融时间序列。 #%% Using the Model in MetaTrader 5 # 2.1. 在你开始之前要知道的好事 # 有两种方法来创建一个模型: 你可以使用OnnxCreate从onnx文件创建模型,或者使用OnnxCreateFromBuffer从数据阵列创建模型。 # 如果ONNX模型被用作EA中的资源,你需要在每次改变模型时重新编译EA。 # 并非所有模型都有完全定义的尺寸输入和/或输出张量。这通常是负责包尺寸的第一个维度。在运行一个模型之前,你必须使用OnnxSetInputShape和OnnxSetOutputShape函数明确指定尺寸。模型的输入数据应该以训练模型时的相同方式准备。 # 对于输入和输出数据,我们建议使用模型中使用的相同类型的数组、矩阵和/或向量。在这种情况下,你将不必在运行模型时转换数据。如果数据不能以所需类型表示,数据将被自动转换。 # 使用OnnxRun来推理(运行)你的模型。请注意,一个模型可以被多次运行。使用模型后,使用 OnnxRelease 函数释放它。 # 2.2. 读取onnx文件并获得输入和输出的信息 # 为了使用我们的模型,我们需要知道模型的位置、输入数据类型和形状,以及输出数据类型和形状。根据之前创建的脚本,model.eurusd.H1.120.onnx与生成onnx文件的Python脚本位于同一个文件夹中。输入是float32,120个归一化的收盘价(用于在批量大小等于1的情况下工作);输出是float32,这是一个由模型预测的归一化价格。 # 我们还在MQL5\Files文件夹中创建了onnx文件,以便使用MQL5脚本获得模型输入和输出数据。 # 参见MT5
MuSaCN/PythonProjects2023-02-14
Project_Papers文章调试/4.如何在MQL5中使用ONNX模型.py
4.如何在MQL5中使用ONNX模型.py
py
14,235
python
zh
code
1
github-code
6
5384270592
from Chem_Equation_Balancer import * from EmpiricalFormulas import * from Number_Validation import * def Chapter4_Menu(): #Submenu for Chaper 4 print ("\nChapter 4 Menu:\n") while True: print ("Enter 0 to find total mass of a compound") print ("Enter 1 to test whether an equation is balanced") print ("Enter 2 to get the percent of a compund by mass") print ("Enter 3 to get the Emperical formula by mass % of each element") print ("Enter 4 to return to the main Menu") inp = input('\n') while inp not in ["1", "2", "3", "0", "4"]: inp = input("Enter either 0, 1, 2, 3, or 4 please! ") if inp == '0': Total_Mass_Menu() if inp == '1': Balanced_Check_Menu() if inp == '2': Perc_Mass_Menu() if inp == '3': GetEP_Menu() if inp == '4': return () print ("\n") def Total_Mass_Menu(): # Finds the total mass per mol of a substance equation = input("Please input a chemical compund (Letters that are not chemicals will be equal to 0) ") try: print ("One mol of", equation,'is',get_total_mass(equation), "g") except: print ("This is not a valid compound") Total_Mass_Menu() def Balanced_Check_Menu(): # Checks to see if a chemical equation is balanced #Example of balanced equation- NO2 + H2O -> HNO3 equation = input("Please input a chemical equation ") try: # Equations without 2 sides will result in a failure if is_balanced_equ(equation): print ("The equation is balanced") else: print ("The equation is not balanced") except ValueError: # Catches this Error print ("You must have exactly 1 recactant and exactly 1 product") def Perc_Mass_Menu(): # Gets each elements mass percentage in the compound equation = input("Please input a chemical compund to calculate the percent of each element by mass ") try: # Any non-elements put into the equation will result in failure GetPercByMass(equation) except: print ("This is not a valid compound") Perc_Mass_Menu() def GetEP_Menu(): # Inverse of the previous function rem_perc = 100 total_input = [] while rem_perc >1: # Needs sum of percents to total 99 - 101 ele = input("Input an element ") perc = input("What percent "+ele+" by mass is the compund? ").replace("%", "") if perc == "a" or perc == "all": perc = str(rem_perc) while valid_num(perc, domain = "(0, "+str(rem_perc)+"]") == False: print ("You must input a number greater than 0 and less than or equal to "+ str(rem_perc) + " because you cannot have more than 100% total") if perc == "a" or perc == "all": perc = rem_perc perc = input("What percent "+ele+" by mass is the compund? ").replace("%", "") total_input.append([ele, float(perc)]) rem_perc -= float(perc) try: print ("The emperical formula of this compound is "+GetEP(total_input)) except: print ("One or more of the inputted elements were not actual elements")
NightHydra/HonChemCalc
Chapter_1_4_Menu.py
Chapter_1_4_Menu.py
py
3,255
python
en
code
0
github-code
6
43213705575
#!/usr/bin/env python3 """ Program to decode the first sprite of a CTHG 2 file. Mainly intended as a test for the checking the encoder, but also a demonstration of how to decode. """ _license = """ Copyright (c) 2013 Alberth "Alberth" Hofkamp Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ from PIL import Image class Infile: def __init__(self, fname): self.fname = fname self.handle = open(self.fname, "rb") # Read header for h in [ord('C'), ord('T'), ord('H'), ord('G'), 2, 0]: v = self.getByte() assert v == h def getByte(self): v = self.handle.read(1)[0] return v def getWord(self): b = self.getByte() return b | (self.getByte() << 8) def getLong(self): w = self.getWord() return w | (self.getWord() << 16) def getData(self, size): data = [] for i in range(size): data.append(self.getByte()) return data def decode_xy(pix_idx, w, h): y = pix_idx // w x = pix_idx - w * y assert x >= 0 and x < w assert y >= 0 and y < h return x, y def get_colour(table, idx): if table == 0: return (0, 0, 0, 255) if table == 1: return (idx, 0, 0, 255) if table == 2: return (0, idx, 0, 255) if table == 3: return (0, 0, idx, 255) if table == 4: return (0, idx, idx, 255) if table == 5: return (idx, 0, idx, 255) assert False class Sprite: def __init__(self, infile): size = infile.getLong() - 2 - 2 - 2 self.number = infile.getWord() self.width = infile.getWord() self.height = infile.getWord() self.data = infile.getData(size) print("Sprite number {}".format(self.number)) print("Width {}".format(self.width)) print("Height {}".format(self.height)) print("Size {}".format(size)) print("Data size {}".format(len(self.data))) def get_data(self, idx): return self.data[idx], idx + 1 def save(self): im = Image.new("RGBA", (self.width, self.height), (0, 0, 0, 0)) pix = im.load() idx = 0 pix_idx = 0 while idx < len(self.data): length, idx = self.get_data(idx) if length <= 63: # Fixed non-transparent 32bpp pixels (RGB) length = length & 63 x, y = decode_xy(pix_idx, self.width, self.height) for i in range(length): d = (self.data[idx], self.data[idx+1], self.data[idx+2], 255) pix[x, y] = d idx = idx + 3 pix_idx = pix_idx + 1 x = x + 1 if x == self.width: x = 0 y = y + 1 continue elif length <= 64+63: # Partially transparent 32bpp pixels (RGB) length = length & 63 opacity, idx = self.get_data(idx) x, y = decode_xy(pix_idx, self.width, self.height) for i in range(length): d = (self.data[idx], self.data[idx+1], self.data[idx+2], opacity) pix[x, y] = d idx = idx + 3 pix_idx = pix_idx + 1 x = x + 1 if x == self.width: x = 0 y = y + 1 continue elif length <= 128+63: # Fixed fully transparent pixels length = length & 63 pix_idx = pix_idx + length continue else: # Recolour layer. length = length & 63 table, idx = self.get_data(idx) opacity, idx = self.get_data(idx) x, y = decode_xy(pix_idx, self.width, self.height) for i in range(length): col, idx = self.get_data(idx) pix[x, y] = get_colour(table, col) pix_idx = pix_idx + 1 x = x + 1 if x == self.width: x = 0 y = y + 1 continue im.save("sprite_{}.png".format(self.number)) inf = Infile("x.out") spr = Sprite(inf) spr.save()
CorsixTH/CorsixTH
SpriteEncoder/decode.py
decode.py
py
5,314
python
en
code
2,834
github-code
6
5216056710
"""Pure Python implementation of EM algorithm.""" from array import array import random class Cluster: """Implementation of EM clustering.""" def __init__(self, filename, dim, num_entry, num_cluster=10): self.float_size = 4 self.dim = dim self.num_entry = num_entry self.data = self.import_data(filename) self.num_cluster = num_cluster self.centroids = random.sample(self.data, self.num_cluster) self.labels = {cluster_idx: [] for cluster_idx in range(self.num_cluster)} def import_data(self, filename): """Read and process the binary data.""" raw_data = array('f') with open(filename, 'rb') as file_desc: raw_data.frombytes(file_desc.read()) data = [[] for _ in range(self.num_entry)] for i in range(self.num_entry): for j in range(self.dim): idx = i * self.dim + j data[i].append(raw_data[idx]) return data def distance(self, lhs, rhs): """Euclidean distance between two vectors 'lhs' and 'rhs'.""" return sum([(lhs[idx] - rhs[idx]) ** 2 for idx in range(self.dim)]) ** 0.5 def vectors_mean(self, vectors): """Calculate the mean of a set of vectors.""" total = [0 for _ in range(self.dim)] for vector in vectors: total = [lhs + rhs for lhs, rhs in zip(total, vector)] return [elem / len(vectors) for elem in total] def e_step(self): """E-step in EM algorithm: Expectation.""" self.labels = {cluster_idx: [] for cluster_idx in range(self.num_cluster)} for vector_idx, vector in enumerate(self.data): distances_to_clusters = [] for cluster in self.centroids: distances_to_clusters.append(self.distance(vector, cluster)) min_cluster = distances_to_clusters.index(min(distances_to_clusters)) self.labels[min_cluster].append(vector_idx) def m_step(self): """M-step in EM algorithm: Maximization.""" new_centroids = [] for _, member_indices in self.labels.items(): member_vectors = [self.data[idx] for idx in member_indices] new_centroids.append(self.vectors_mean(member_vectors)) loss = sum([self.distance(new, old) for new, old in zip(new_centroids, self.centroids)]) / self.num_cluster self.centroids = new_centroids return loss def fit(self, epsilon=0.001, max_iter=200): """Fitting to data.""" for idx in range(max_iter): self.e_step() loss = self.m_step() print('step {}: loss {}.'.format(idx, loss)) if loss < epsilon: for member_indices in self.labels.items(): print(member_indices) for cluster_idx, centroid in enumerate(self.centroids): print('cluster {}: {}'.format(cluster_idx, centroid)) break def cluster_vectors(self, cluster): """Return vectors of a cluster.""" return [self.data[idx] for idx in self.labels[cluster]]
uniglot/pure-python-em
clustering.py
clustering.py
py
3,163
python
en
code
0
github-code
6
23950521358
#!/usr/bin/python3 import argparse from iCEburn.libiceblink import ICE40Board def rtype(x): return ('R', int(x, 16)) def wtype(x): return ('W', [int(i,16) for i in x.split(':')]) def main(): ap = argparse.ArgumentParser() ap.add_argument("-r", "--read", dest='actions', type=rtype, action='append') ap.add_argument("-w", "--write", dest='actions', type=wtype, action='append') args = ap.parse_args() board = ICE40Board() with board.get_board_comm() as comm: for atype, arg in args.actions: if atype == 'R': addr = arg print("READ %02x: %02x" % (addr, comm.readReg(addr))) elif atype == 'W': addr, value = arg print("WRITE %02x: %02x" % (addr, value)) comm.writeReg(addr, value) if __name__ == "__main__": main()
davidcarne/iceBurn
iCEburn/regtool.py
regtool.py
py
868
python
en
code
32
github-code
6
21812044102
import pytest from src.error import InputError from src.auth import auth_register_v2 from src.user import user_profile_v2 from src.other import clear_v1 @pytest.fixture def register_user(): clear_v1() user = auth_register_v2("[email protected]", "123456", "john", "smith") token = user['token'] id = user['auth_user_id'] return token, id def test_valid_input(register_user): token, id = register_user res = user_profile_v2(token, id) assert res['user']['u_id'] == id assert res['user']['email'] == '[email protected]' assert res['user']['name_first'] == 'john' assert res['user']['name_last'] == 'smith' assert res['user']['handle_str'] == 'johnsmith' def test_invalid_uid(register_user): token, id = register_user id += 1 with pytest.raises(InputError): user_profile_v2(token, id)
TanitPan/comp1531_UNSW_Dreams
tests/user_profile_test.py
user_profile_test.py
py
857
python
en
code
0
github-code
6
39252790870
import time import logging from django.contrib import admin from django.contrib import messages from django.contrib.admin import helpers from django.urls import reverse from django.db import transaction from django.db.models import Count from django.template.response import TemplateResponse from django.utils.html import format_html, format_html_join from mangaki.models import ( Work, TaggedWork, WorkTitle, Genre, Track, Tag, Artist, Studio, Editor, Rating, Page, Suggestion, Evidence, Announcement, Recommendation, Pairing, Reference, Top, Ranking, Role, Staff, FAQTheme, FAQEntry, Trope, Language, ExtLanguage, WorkCluster, UserBackgroundTask, ActionType, get_field_changeset ) from mangaki.utils.anidb import AniDBTag, client, diff_between_anidb_and_local_tags from mangaki.utils.db import get_potential_posters from collections import defaultdict from enum import Enum from mangaki.utils.work_merge import WorkClusterMergeHandler ActionTypeColors = { ActionType.DO_NOTHING: 'black', # INFO_ONLY ActionType.JUST_CONFIRM: 'green', ActionType.CHOICE_REQUIRED: 'red' } class MergeErrors(Enum): NO_ID = 'no ID' FIELDS_MISSING = 'missing fields' NOT_ENOUGH_WORKS = 'not enough works' def handle_merge_errors(response, request, final_work, nb_merged, message_user): if response == MergeErrors.NO_ID: message_user(request, "Aucun ID n'a été fourni pour la fusion.", level=messages.ERROR) if response == MergeErrors.FIELDS_MISSING: message_user(request, """Un ou plusieurs des champs requis n'ont pas été remplis. (Détails: {})""".format(", ".join(final_work)), level=messages.ERROR) if response == MergeErrors.NOT_ENOUGH_WORKS: message_user(request, "Veuillez sélectionner au moins 2 œuvres à fusionner.", level=messages.WARNING) if response is None: # Confirmed message_user(request, format_html('La fusion de {:d} œuvres vers <a href="{:s}">{:s}</a> a bien été effectuée.' .format(nb_merged, final_work.get_absolute_url(), final_work.title))) def create_merge_form(works_to_merge_qs): work_dicts_to_merge = list(works_to_merge_qs.values()) field_changeset = get_field_changeset(work_dicts_to_merge) fields_to_choose = [] fields_required = [] template_rows = [] suggestions = {} for field, choices, action, suggested, _ in field_changeset: suggestions[field] = suggested template_rows.append({ 'field': field, 'choices': choices, 'action_type': action, 'suggested': suggested, 'color': ActionTypeColors[action], }) if field != 'id' and action != ActionType.DO_NOTHING: fields_to_choose.append(field) if action == ActionType.CHOICE_REQUIRED: fields_required.append(field) template_rows.sort(key=lambda row: int(row['action_type']), reverse=True) rating_samples = [(Rating.objects.filter(work_id=work_dict['id']).count(), Rating.objects.filter(work_id=work_dict['id'])[:10]) for work_dict in work_dicts_to_merge] # FIXME: too many queries return fields_to_choose, fields_required, template_rows, rating_samples, suggestions @transaction.atomic # In case trouble happens def merge_works(request, selected_queryset, force=False, extra=None): user = request.user if request else None if selected_queryset.model == WorkCluster: # Author is reviewing an existing WorkCluster from_cluster = True cluster = selected_queryset.first() works_to_merge_qs = cluster.works.order_by('id').prefetch_related('rating_set', 'genre') else: # Author is merging those works from a Work queryset from_cluster = False works_to_merge_qs = selected_queryset.order_by('id').prefetch_related('rating_set', 'genre') nb_works_to_merge = works_to_merge_qs.count() if request and request.POST.get('confirm'): # Merge has been confirmed rich_context = request.POST else: fields_to_choose, fields_required, template_rows, rating_samples, suggestions = create_merge_form(works_to_merge_qs) context = { 'fields_to_choose': ','.join(fields_to_choose), 'fields_required': ','.join(fields_required), 'template_rows': template_rows, 'rating_samples': rating_samples, 'queryset': selected_queryset, 'opts': Work._meta if not from_cluster else WorkCluster._meta, 'action': 'merge' if not from_cluster else 'trigger_merge', 'action_checkbox_name': helpers.ACTION_CHECKBOX_NAME } if all(field in suggestions for field in fields_required): rich_context = dict(context) for field in suggestions: rich_context[field] = suggestions[field] if extra is not None: for field in extra: rich_context[field] = extra[field] if force: rich_context['confirm'] = True if rich_context.get('confirm'): # Merge has been confirmed works_to_merge = list(works_to_merge_qs) if not from_cluster: cluster = WorkCluster(user=user, checker=user) cluster.save() # Otherwise we cannot add works cluster.works.add(*works_to_merge) # Happens when no ID was provided if not rich_context.get('id'): return None, None, MergeErrors.NO_ID final_id = int(rich_context.get('id')) final_work = Work.objects.get(id=final_id) # Notice how `cluster` always exist in this scope. # noinspection PyUnboundLocalVariable merge_handler = WorkClusterMergeHandler(cluster, works_to_merge, final_work) missing_required_fields = merge_handler.overwrite_fields( set(filter(None, rich_context.get('fields_to_choose').split(','))), set(filter(None, rich_context.get('fields_required').split(','))), rich_context) # Happens when a required field was left empty if missing_required_fields: return None, missing_required_fields, MergeErrors.FIELDS_MISSING merge_handler.perform_redirections() merge_handler.accept_cluster(user) return len(works_to_merge), merge_handler.target_work, None # Just show a warning if only one work was checked if nb_works_to_merge < 2: return None, None, MergeErrors.NOT_ENOUGH_WORKS return nb_works_to_merge, None, TemplateResponse(request, 'admin/merge_selected_confirmation.html', context) logger = logging.getLogger(__name__) class TaggedWorkInline(admin.TabularInline): model = TaggedWork fields = ('work', 'tag', 'weight') def get_queryset(self, request): qs = super().get_queryset(request) return qs.select_related('work', 'tag') class StaffInline(admin.TabularInline): model = Staff fields = ('role', 'artist') raw_id_fields = ('artist',) class WorkTitleInline(admin.TabularInline): model = WorkTitle fields = ('title', 'language', 'type') class ReferenceInline(admin.TabularInline): model = Reference fields = ('source', 'identifier') class AniDBaidListFilter(admin.SimpleListFilter): title = 'AniDB aid' parameter_name = 'AniDB aid' def lookups(self, request, model_admin): return ('Vrai', 'Oui'), ('Faux', 'Non') def queryset(self, request, queryset): if self.value() == 'Faux': return queryset.filter(anidb_aid=0) elif self.value() == 'Vrai': return queryset.exclude(anidb_aid=0) else: return queryset @admin.register(FAQTheme) class FAQAdmin(admin.ModelAdmin): ordering = ('order',) search_fields = ('theme',) list_display = ('theme', 'order') @admin.register(Work) class WorkAdmin(admin.ModelAdmin): search_fields = ('id', 'title', 'worktitle__title') list_display = ('id', 'category', 'title', 'nsfw') list_filter = ('category', 'nsfw', AniDBaidListFilter) raw_id_fields = ('redirect',) actions = ['make_nsfw', 'make_sfw', 'refresh_work_from_anidb', 'merge', 'refresh_work', 'update_tags_via_anidb', 'change_title'] inlines = [StaffInline, WorkTitleInline, ReferenceInline, TaggedWorkInline] readonly_fields = ( 'sum_ratings', 'nb_ratings', 'nb_likes', 'nb_dislikes', 'controversy', ) def make_nsfw(self, request, queryset): rows_updated = queryset.update(nsfw=True) if rows_updated == 1: message_bit = "1 œuvre est" else: message_bit = "%s œuvres sont" % rows_updated self.message_user(request, "%s désormais NSFW." % message_bit) make_nsfw.short_description = "Rendre NSFW les œuvres sélectionnées" def update_tags_via_anidb(self, request, queryset): works = queryset.all() if request.POST.get('confirm'): # Updating tags has been confirmed to_update_work_ids = set(map(int, request.POST.getlist('to_update_work_ids'))) nb_updates = len(to_update_work_ids) work_ids = list(map(int, request.POST.getlist('work_ids'))) tag_titles = request.POST.getlist('tag_titles') tag_weights = list(map(int, request.POST.getlist('weights'))) tag_anidb_tag_ids = list(map(int, request.POST.getlist('anidb_tag_ids'))) tags = list(map(AniDBTag, tag_titles, tag_weights, tag_anidb_tag_ids)) # Checkboxes to know which tags have to be kept regardless of their pending status tag_checkboxes = request.POST.getlist('tag_checkboxes') tags_to_process = set(tuple(map(int, tag_checkbox.split(':'))) for tag_checkbox in tag_checkboxes) # Make a dict with work_id -> tags to keep tags_final = {} for index, work_id in enumerate(work_ids): if work_id not in to_update_work_ids: continue if work_id not in tags_final: tags_final[work_id] = [] if (work_id, tags[index].anidb_tag_id) in tags_to_process: tags_final[work_id].append(tags[index]) # Process selected tags for works that have been selected for work in works: if work.id in to_update_work_ids: client.update_tags(work, tags_final[work.id]) if nb_updates == 0: self.message_user(request, "Aucune oeuvre n'a été marquée comme devant être mise à jour.", level=messages.WARNING) elif nb_updates == 1: self.message_user(request, "Mise à jour des tags effectuée pour une œuvre.") else: self.message_user(request, "Mise à jour des tags effectuée pour {} œuvres.".format(nb_updates)) return None # Check for works with missing AniDB AID if not all(work.anidb_aid for work in works): self.message_user(request, """Certains de vos choix ne possèdent pas d'identifiant AniDB. Le rafraichissement de leurs tags a été omis. (Détails: {})""" .format(", ".join(map(lambda w: w.title, filter(lambda w: not w.anidb_aid, works)))), level=messages.WARNING) # Retrieve and send tags information to the appropriate form all_information = {} for index, work in enumerate(works, start=1): if work.anidb_aid: if index % 25 == 0: logger.info('(AniDB refresh): Sleeping...') time.sleep(1) # Don't spam AniDB. anidb_tags = client.get_tags(anidb_aid=work.anidb_aid) tags_diff = diff_between_anidb_and_local_tags(work, anidb_tags) tags_count = 0 for tags_info in tags_diff.values(): tags_count += len(tags_info) if tags_count > 0: all_information[work.id] = { 'title': work.title, 'deleted_tags': tags_diff["deleted_tags"], 'added_tags': tags_diff["added_tags"], 'updated_tags': tags_diff["updated_tags"], 'kept_tags': tags_diff["kept_tags"] } if all_information: context = { 'all_information': all_information.items(), 'queryset': queryset, 'opts': TaggedWork._meta, 'action': 'update_tags_via_anidb', 'action_checkbox_name': helpers.ACTION_CHECKBOX_NAME } return TemplateResponse(request, "admin/update_tags_via_anidb.html", context) else: self.message_user(request, "Aucune des œuvres sélectionnées n'a subit de mise à jour des tags chez AniDB.", level=messages.WARNING) return None update_tags_via_anidb.short_description = "Mettre à jour les tags des œuvres depuis AniDB" def make_sfw(self, request, queryset): rows_updated = queryset.update(nsfw=False) if rows_updated == 1: message_bit = "1 œuvre n'est" else: message_bit = "%s œuvres ne sont" % rows_updated self.message_user(request, "%s désormais plus NSFW." % message_bit) make_sfw.short_description = "Rendre SFW les œuvres sélectionnées" @transaction.atomic def refresh_work_from_anidb(self, request, queryset): works = queryset.all() # Check for works with missing AniDB AID offending_works = [] if not all(work.anidb_aid for work in works): offending_works = [work for work in works if not work.anidb_aid] self.message_user(request, "Certains de vos choix ne possèdent pas d'identifiant AniDB. " "Leur rafraichissement a été omis. (Détails: {})" .format(", ".join(map(lambda w: w.title, offending_works))), level=messages.WARNING) # Check for works that have a duplicate AniDB AID aids_with_works = defaultdict(list) for work in works: if work.anidb_aid: aids_with_works[work.anidb_aid].append(work) aids_with_potdupe_works = defaultdict(list) for work in Work.objects.filter(anidb_aid__in=aids_with_works.keys()): aids_with_potdupe_works[work.anidb_aid].append(work) works_with_conflicting_anidb_aid = [] for anidb_aid, potdupe_works in aids_with_potdupe_works.items(): if len(potdupe_works) > 1: works_with_conflicting_anidb_aid.extend(aids_with_works[anidb_aid]) # Alert the user for each work he selected that has a duplicate AniDB ID self.message_user( request, """Le rafraichissement de {} a été omis car d'autres œuvres possèdent le même identifiant AniDB #{}. (Œuvres en conflit : {})""" .format( ", ".join(map(lambda w: w.title, aids_with_works[anidb_aid])), anidb_aid, ", ".join(map(lambda w: w.title, aids_with_potdupe_works[anidb_aid])) ), level=messages.WARNING ) # Refresh works from AniDB refreshed = 0 for index, work in enumerate(works, start=1): if work.anidb_aid and work not in works_with_conflicting_anidb_aid: logger.info('Refreshing {} from AniDB.'.format(work)) if client.get_or_update_work(work.anidb_aid) is not None: refreshed += 1 if index % 25 == 0: logger.info('(AniDB refresh): Sleeping...') time.sleep(1) # Don't spam AniDB. if refreshed > 0: self.message_user(request, "Le rafraichissement de {} œuvre(s) a été effectué avec succès." .format(refreshed)) refresh_work_from_anidb.short_description = "Rafraîchir les œuvres depuis AniDB" def merge(self, request, queryset): nb_merged, final_work, response = merge_works(request, queryset) handle_merge_errors(response, request, final_work, nb_merged, self.message_user) return response merge.short_description = "Fusionner les œuvres sélectionnées" def refresh_work(self, request, queryset): if request.POST.get('confirm'): # Confirmed downloaded_titles = [] for obj in queryset: chosen_poster = request.POST.get('chosen_poster_{:d}'.format(obj.id)) if not chosen_poster: continue if obj.retrieve_poster(chosen_poster): downloaded_titles.append(obj.title) if downloaded_titles: self.message_user( request, "Des posters ont été trouvés pour les anime suivants : %s." % ', '.join(downloaded_titles)) else: self.message_user(request, "Aucun poster n'a été trouvé, essayez de changer le titre.") return None bundle = [] for work in queryset: bundle.append((work.id, work.title, get_potential_posters(work))) context = { 'queryset': queryset, 'bundle': bundle, 'opts': self.model._meta, 'action_checkbox_name': helpers.ACTION_CHECKBOX_NAME } return TemplateResponse(request, 'admin/refresh_poster_confirmation.html', context) refresh_work.short_description = "Mettre à jour la fiche de l'anime (poster)" @transaction.atomic def change_title(self, request, queryset): if request.POST.get('confirm'): # Changing default title has been confirmed work_ids = request.POST.getlist('work_ids') titles_ids = request.POST.getlist('title_ids') titles = WorkTitle.objects.filter( pk__in=titles_ids, work__id__in=work_ids ).values_list('title', 'work__title', 'work__id') for new_title, current_title, work_id in titles: if new_title != current_title: Work.objects.filter(pk=work_id).update(title=new_title) self.message_user(request, 'Les titres ont bien été changés pour les œuvres sélectionnées.') return None work_titles = WorkTitle.objects.filter(work__in=queryset.values_list('pk', flat=True)) full_infos = work_titles.values( 'pk', 'title', 'language__code', 'type', 'work_id', 'work__title' ).order_by('title').distinct('title') titles = {} for infos in full_infos: if infos['work_id'] not in titles: titles[infos['work_id']] = {} titles[infos['work_id']].update({ infos['pk']: { 'title': infos['title'], 'language': infos['language__code'] if infos['language__code'] else 'inconnu', 'type': infos['type'] if infos['title'] != infos['work__title'] else 'current' } }) if titles: context = { 'work_titles': titles, 'queryset': queryset, 'opts': Work._meta, 'action': 'change_title', 'action_checkbox_name': helpers.ACTION_CHECKBOX_NAME } return TemplateResponse(request, 'admin/change_default_work_title.html', context) else: self.message_user(request, 'Aucune des œuvres sélectionnées ne possèdent de titre alternatif.', level=messages.WARNING) return None change_title.short_description = "Changer le titre par défaut" @admin.register(Artist) class ArtistAdmin(admin.ModelAdmin): search_fields = ('id', 'name') @admin.register(Tag) class TagAdmin(admin.ModelAdmin): list_display = ("title",) readonly_fields = ("nb_works_linked",) def get_queryset(self, request): qs = super().get_queryset(request) return qs.annotate(works_linked=Count('work')) def nb_works_linked(self, obj): return obj.works_linked nb_works_linked.short_description = 'Nombre d\'œuvres liées au tag' @admin.register(TaggedWork) class TaggedWorkAdmin(admin.ModelAdmin): search_fields = ('work__title', 'tag__title') @admin.register(WorkCluster) class WorkClusterAdmin(admin.ModelAdmin): list_display = ('user', 'get_work_titles', 'resulting_work', 'reported_on', 'merged_on', 'checker', 'status', 'difficulty') list_filter = ('status',) list_select_related = ('user', 'resulting_work', 'checker') raw_id_fields = ('user', 'works', 'checker', 'resulting_work', 'origin') search_fields = ('id',) actions = ('trigger_merge', 'reject') def get_queryset(self, request): qs = super().get_queryset(request) return qs.prefetch_related('works') def trigger_merge(self, request, queryset): nb_merged, final_work, response = merge_works(request, queryset) handle_merge_errors(response, request, final_work, nb_merged, self.message_user) return response trigger_merge.short_description = "Fusionner les œuvres de ce cluster" def reject(self, request, queryset): rows_updated = queryset.update(status='rejected') if rows_updated == 1: message_bit = "1 cluster" else: message_bit = "%s clusters" % rows_updated self.message_user(request, "Le rejet de %s a été réalisé avec succès." % message_bit) reject.short_description = "Rejeter les clusters sélectionnés" def get_work_titles(self, obj): cluster_works = obj.works.all() # Does not include redirected works if cluster_works: def get_admin_url(work): if work.redirect is None: return reverse('admin:mangaki_work_change', args=(work.id,)) else: return '#' return ( '<ul>' + format_html_join('', '<li>{} ({}<a href="{}">{}</a>)</li>', ((work.title, 'was ' if work.redirect is not None else '', get_admin_url(work), work.id) for work in cluster_works)) + '</ul>' ) else: return '(all deleted)' get_work_titles.allow_tags = True @admin.register(Suggestion) class SuggestionAdmin(admin.ModelAdmin): list_display = ('work', 'problem', 'date', 'user', 'is_checked') list_filter = ('problem',) actions = ['check_suggestions', 'uncheck_suggestions'] raw_id_fields = ('work',) search_fields = ('work__title', 'user__username') def view_on_site(self, obj): return obj.work.get_absolute_url() def check_suggestions(self, request, queryset): rows_updated = queryset.update(is_checked=True) for suggestion in queryset: if suggestion.problem == 'ref': # Reference suggestion reference, created = Reference.objects.get_or_create(work=suggestion.work, url=suggestion.message) reference.suggestions.add(suggestion) if rows_updated == 1: message_bit = "1 suggestion" else: message_bit = "%s suggestions" % rows_updated self.message_user(request, "La validation de %s a été réalisé avec succès." % message_bit) check_suggestions.short_description = "Valider les suggestions sélectionnées" def uncheck_suggestions(self, request, queryset): rows_updated = queryset.update(is_checked=False) if rows_updated == 1: message_bit = "1 suggestion" else: message_bit = "%s suggestions" % rows_updated self.message_user(request, "L'invalidation de %s a été réalisé avec succès." % message_bit) uncheck_suggestions.short_description = "Invalider les suggestions sélectionnées" @admin.register(Announcement) class AnnouncementAdmin(admin.ModelAdmin): exclude = ('title',) @admin.register(Pairing) class PairingAdmin(admin.ModelAdmin): list_display = ('artist', 'work', 'date', 'user', 'is_checked') actions = ['make_director', 'make_composer', 'make_author'] def make_director(self, request, queryset): rows_updated = 0 director = Role.objects.get(slug='director') for pairing in queryset: _, created = Staff.objects.get_or_create(work_id=pairing.work_id, artist_id=pairing.artist_id, role=director) if created: pairing.is_checked = True pairing.save() rows_updated += 1 if rows_updated == 1: message_bit = "1 réalisateur a" else: message_bit = "%s réalisateurs ont" % rows_updated self.message_user(request, "%s été mis à jour." % message_bit) make_director.short_description = "Valider les appariements sélectionnés pour réalisation" def make_composer(self, request, queryset): rows_updated = 0 composer = Role.objects.get(slug='composer') for pairing in queryset: _, created = Staff.objects.get_or_create(work_id=pairing.work_id, artist_id=pairing.artist_id, role=composer) if created: pairing.is_checked = True pairing.save() rows_updated += 1 if rows_updated == 1: message_bit = "1 compositeur a" else: message_bit = "%s compositeurs ont" % rows_updated self.message_user(request, "%s été mis à jour." % message_bit) make_composer.short_description = "Valider les appariements sélectionnés pour composition" def make_author(self, request, queryset): rows_updated = 0 author = Role.objects.get(slug='author') for pairing in queryset: _, created = Staff.objects.get_or_create(work_id=pairing.work_id, artist_id=pairing.artist_id, role=author) if created: pairing.is_checked = True pairing.save() rows_updated += 1 if rows_updated == 1: message_bit = "1 auteur a" else: message_bit = "%s auteurs ont" % rows_updated self.message_user(request, "%s été mis à jour." % message_bit) make_author.short_description = "Valider les appariements sélectionnés pour écriture" @admin.register(Rating) class RatingAdmin(admin.ModelAdmin): raw_id_fields = ('user', 'work') @admin.register(Reference) class ReferenceAdmin(admin.ModelAdmin): list_display = ['work', 'url'] raw_id_fields = ('work', 'suggestions') class RankingInline(admin.TabularInline): model = Ranking fields = ('content_type', 'object_id', 'name', 'score', 'nb_ratings', 'nb_stars',) readonly_fields = ('name',) def name(self, instance): return str(instance.content_object) @admin.register(Top) class TopAdmin(admin.ModelAdmin): inlines = [ RankingInline, ] readonly_fields = ('category', 'date',) def has_add_permission(self, request): return False @admin.register(Role) class RoleAdmin(admin.ModelAdmin): model = Role prepopulated_fields = {'slug': ('name',)} @admin.register(Evidence) class EvidenceAdmin(admin.ModelAdmin): list_display = ['user', 'suggestion', 'agrees', 'needs_help'] admin.site.register(Genre) admin.site.register(Track) admin.site.register(Studio) admin.site.register(Editor) admin.site.register(Page) admin.site.register(FAQEntry) admin.site.register(Recommendation) admin.site.register(Trope) admin.site.register(Language) admin.site.register(ExtLanguage) admin.site.register(UserBackgroundTask) admin.site.site_header = "Administration Mangaki"
mangaki/mangaki
mangaki/mangaki/admin.py
admin.py
py
28,860
python
en
code
137
github-code
6
70063460029
MAX_QSIZE = 10 class CircularQueue : def __init__( self ) : self.front = 0 self.rear = 0 self.items = [None] * MAX_QSIZE def isEmpty( self ) : return self.front == self.rear def isFull( self ) : return self.front == (self.rear+1)%MAX_QSIZE def clear( self ) : self.front = self.rear def enqueue( self, item ): if not self.isFull(): self.rear = (self.rear+1)% MAX_QSIZE self.items[self.rear] = item def dequeue( self ): if not self.isEmpty(): self.front = (self.front+1)% MAX_QSIZE return self.items[self.front] def peek( self ): if not self.isEmpty(): return self.items[(self.front + 1) % MAX_QSIZE] def size( self ) : return (self.rear - self.front + MAX_QSIZE) % MAX_QSIZE def display( self ): out = [] if self.front < self.rear : out = self.items[self.front+1:self.rear+1] else: out = self.items[self.front+1:MAX_QSIZE] \ + self.items[0:self.rear+1] print("[f=%s,r=%d] ==> "%(self.front, self.rear), out) class TNode: def __init__ (self, data, left, right): self.data = data self.left = left self.right = right def preorder(n) : if n is not None : print(n.data, end=' ') preorder(n.left) preorder(n.right) def inorder(n) : if n is not None : inorder(n.left) print(n.data, end=' ') inorder(n.right) def postorder(n) : if n is not None : postorder(n.left) postorder(n.right) print(n.data, end=' ') def levelorder(root) : queue = CircularQueue() queue.enqueue(root) while not queue.isEmpty() : n = queue.dequeue() if n is not None : print(n.data, end=' ') queue.enqueue(n.left) queue.enqueue(n.right) def count_node(n) : if n is None : return 0 else : return 1 + count_node(n.left) + count_node(n.right) def count_leaf(n) : if n is None : return 0 elif n.left is None and n.right is None : return 1 else : return count_leaf(n.left) + count_leaf(n.right) def calc_height(n) : if n is None : return 0 hLeft = calc_height(n.left) hRight = calc_height(n.right) if (hLeft > hRight) : return hLeft + 1 else: return hRight + 1 def full_tree(root): if root.left != None and root.right != None: return True else: return False def is_complete_binary_tree(root): queue = CircularQueue() queue.enqueue(root) while not queue.size != 0 : n = queue.dequeue() if not full_tree(root): if n.left == None and n.right == None: return False else: if n.left != None: queue.enqueue(n.left) queue.dequeue() break else: queue.enqueue(n.left) queue.enqueue(n.right) queue.dequeue(); while queue.size != 0: n = queue.dequeue() if root.left != None and root.right != None: return False else: return True def is_balanced(root): if root == None: return True leftheigh = calc_height(root.left) rightheigh = calc_height(root.right) if (leftheigh - rightheigh <2) and (leftheigh - rightheigh > -1): return True return False d = TNode('D', None, None) b = TNode('B', d, None) g = TNode('G', None, None) h = TNode('H',None, None) e = TNode('E', g,h) f = TNode('F', None, None) c = TNode('C', f,e) root = TNode('A', b, c) a2 = TNode('A', None, None) b2 = TNode('B', None, None) sla = TNode('/', a2, b2) c2 = TNode('C', None, None) star = TNode('*', sla, c2) d2 = TNode('D', None, None) star2 = TNode('*', star, d2) e2 = TNode('E', None, None) root2 = TNode('+', star2, e2) c3 = TNode('C', None, None) d3 = TNode('D', None, None) b3 = TNode('B', c3,d3) f2 = TNode('F',None, None) e3 = TNode('E', f2, None) root3 = TNode('A', b3,e3) print('\n In-Order : ', end='') inorder(root) print('\n Pre-Order : ', end='') preorder(root) print('\n Post-Order : ', end='') postorder(root) print('\nLevel-Order : ', end='') levelorder(root) print() print('\n In-Order : ', end='') inorder(root2) print('\n Pre-Order : ', end='') preorder(root2) print('\n Post-Order : ', end='') postorder(root2) print('\nLevel-Order : ', end='') levelorder(root2) print() print('\n In-Order : ', end='') inorder(root3) print('\n Pre-Order : ', end='') preorder(root3) print('\n Post-Order : ', end='') postorder(root3) print('\nLevel-Order : ', end='') levelorder(root3) print() print(" 노드의 개수 = %d개" % count_node(root)) print(" 단말의 개수 = %d개" % count_leaf(root)) print(" 트리의 높이 = %d" % calc_height(root)) print() print(" 노드의 개수 = %d개" % count_node(root2)) print(" 단말의 개수 = %d개" % count_leaf(root2)) print(" 트리의 높이 = %d" % calc_height(root2)) print() print(" 노드의 개수 = %d개" % count_node(root3)) print(" 단말의 개수 = %d개" % count_leaf(root3)) print(" 트리의 높이 = %d" % calc_height(root3)) print() if is_complete_binary_tree(root3) == True: print('완전 이진 트리입니다.') else: print('완전 이진 트리가 아닙니다.') print() if is_balanced(root3) == True: print('균형잡힌 트리입니다.') else: print('균형이 안 잡힌 트리입니다.')
kimmoonwoong/Data-Structures-using-python
실습과제7.py
실습과제7.py
py
5,896
python
en
code
0
github-code
6
38591123500
class Item: owners = [] def __init__(self, name, quantity, price, owners): self.name = name self.quantity = quantity self.price = price self.owners = owners # Define the parts of a basic restaurant check class Check: def __init__(self, items): self.title = "" self.items = items # creates a new list of items in the check def addItem(self, item): self.items.append(item) def print(self): for i in self.items: print(i.name, i.price, i.quantity, i.owners) itemsList = [Item('steak tacos', 3, 42, []), Item('chicken taco', 1, 12, [])] itemsList[0].owners = ['Johnny', 'Billy', 'Samantha'] print(itemsList[0].owners) checkTest = Check(itemsList) checkTest.print() checkTest.addItem(Item('carnitas', 17, 1, [])) checkTest.print()
curtis-marten/check-split
src/check.py
check.py
py
838
python
en
code
0
github-code
6
72005748348
lista = [] try: #assert False # lista[0] a = 1 / 0 #except: <-- łap wszystkie błędy - zła praktyka #except Exception: --//-- except ZeroDivisionError: print("Dzielono przez zero, ale idziemy dalej") a = 0 except IndexError as e: print("Pojwił się błąd indeksowania:", e) a = None else: # kiedy nie ma żadnego wyjątu print("Wszystko ok, nie ma co się zatrzymywać, idziemy dalej") finally: print("Zamykamy pliki itp.") print(a) print("Reszta programu") # ----- rzucanie błędów class DistanceTooLarge(ValueError): pass class ContentCensored(Exception): pass def _czas_przejazdu(odleglosc): if odleglosc < 0: raise ValueError("Odległość nie może być mniejsza od zera") if odleglosc > 400000: raise DistanceTooLarge("Odległość zbyt duża") if odleglosc == 666: raise ContentCensored(f"Nieetyczna treść: {odleglosc}") czas = 1 / (24.5 / odleglosc) return czas def czas_przejazdu(odleglosc): try: _czas_przejazdu(odleglosc) except ValueError as e: print("Nie można policzyć czasu przejazdu ponieważ:", e) except ZeroDivisionError: print("O, dzielenie przez zero! tego nie oczekiwaliśmy") raise # <-- ponowne rzucenie wyjątku który złapaliśmy except ContentCensored: print("Zablokowano nieetyczne użycie programu") finally: print("Zdziałało finally") czas_przejazdu(-1) czas_przejazdu(1000000) czas_przejazdu(666) czas_przejazdu(0)
jakubnowicki/python-prog
wyjatki.py
wyjatki.py
py
1,528
python
pl
code
0
github-code
6
40458088335
# general imports for EMISSOR and the BRAIN from cltl import brain from emissor.representation.scenario import ImageSignal # specific imports from datetime import datetime import time import cv2 import pathlib import emissor_api #### The next utils are needed for the interaction and creating triples and capsules import chatbots.util.driver_util as d_util import chatbots.util.capsule_util as c_util import chatbots.util.face_util as f_util def get_next_image(camera, imagefolder): what_is_seen = None success, frame = camera.read() if success: current_time = int(time.time() * 1e3) imagepath = f"{imagefolder}/{current_time}.png" image_bbox = (0, 0, frame.shape[1], frame.shape[0]) cv2.imwrite(imagepath, frame) print(imagepath) what_is_seen = f_util.detect_objects(imagepath) return what_is_seen, current_time, image_bbox def create_imageSignal_and_annotations_in_emissor (results, image_time, image_bbox, scenario_ctrl): #### We create an imageSignal imageSignal = d_util.create_image_signal(scenario_ctrl, f"{image_time}.png", image_bbox, image_time) scenario_ctrl.append_signal(imageSignal) what_is_seen = [] ## The next for loop creates a capsule for each object detected in the image and posts a perceivedIn property for the object in the signal ## The "front_camera" is the source of the signal for result in results: current_time = int(time.time() * 1e3) bbox = [int(num) for num in result['yolo_bbox']] object_type = result['label_string'] object_prob = result['det_score'] what_is_seen.append(object_type) mention = f_util.create_object_mention(imageSignal, "front_camera", current_time, bbox, object_type, object_prob) imageSignal.mentions.append(mention) return what_is_seen, imageSignal def add_perception_to_episodic_memory (imageSignal: ImageSignal, object_list, my_brain, scenario_ctrl, location, place_id): response_list = [] for object in object_list: ### We created a perceivedBy triple for this experience, ### @TODO we need to include the bouding box somehow in the object #print(object) capsule = c_util.scenario_image_triple_to_capsule(scenario_ctrl, imageSignal, location, place_id, "front_camera", object, "perceivedIn", imageSignal.id) #print(capsule) # Create the response from the system and store this as a new signal # We use the throughts to respond response = my_brain.update(capsule, reason_types=True, create_label=True) response_list.append(response) return response_list def watch_and_remember(scenario_ctrl, camera, imagefolder, my_brain, location, place_id): t1 = datetime.now() while (datetime.now()-t1).seconds <= 60: ###### Getting the next input signals what_did_i_see, current_time, image_bbox = get_next_image(camera, imagefolder) object_list, imageSignal = create_imageSignal_and_annotations_in_emissor(what_did_i_see, current_time, image_bbox, scenario_ctrl) response = add_perception_to_episodic_memory(imageSignal, object_list, my_brain, scenario_ctrl, location, place_id) print(response) reply = "\nI saw: " if len(object_list) > 1: for index, object in enumerate(object_list): if index == len(object_list) - 1: reply += " and" reply += " a " + object elif len(object_list) == 1: reply += " a " + object_list[0] else: reply = "\nI cannot see! Something wrong with my camera." print(reply + "\n") def main(): ### Link your camera camera = cv2.VideoCapture(0) # Initialise the brain in GraphDB ##### Setting the agents AGENT = "Leolani2" HUMAN_NAME = "Stranger" HUMAN_ID = "stranger" scenarioStorage, scenario_ctrl, imagefolder, rdffolder, location, place_id = emissor_api.start_a_scenario(AGENT, HUMAN_ID, HUMAN_NAME) log_path = pathlib.Path(rdffolder) my_brain = brain.LongTermMemory(address="http://localhost:7200/repositories/sandbox", log_dir=log_path, clear_all=True) watch_and_remember(scenario_ctrl, camera, imagefolder, my_brain, location, place_id) scenario_ctrl.scenario.ruler.end = int(time.time() * 1e3) scenarioStorage.save_scenario(scenario_ctrl) camera.release() if __name__ == '__main__': main()
leolani/cltl-chatbots
src/chatbots/bots/episodic_image_memory.py
episodic_image_memory.py
py
5,114
python
en
code
0
github-code
6
8926064474
import pandas as pd from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains import time import requests import shutil import os.path import docx2txt from webdriver_manager.chrome import ChromeDriverManager from datetime import datetime from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC driver = webdriver.Chrome(ChromeDriverManager().install()) action = ActionChains(driver) url_path = pd.read_csv("urls_data.csv") url_list = list(url_path['0']) base_dir = './ctcfp.org' for i in url_list: title1 = '' title = '' transcript = '' audio_path = '' audio = '' post_date = '' file_name = '' try: print(i) driver.get(i) time.sleep(5) CHECK=driver.find_element_by_xpath('//li[@class="jupiterx-post-meta-categories list-inline-item"]/a') CHECK=CHECK.text if CHECK=="Podcasts": title1 = driver.find_element_by_xpath('//div[@class="container-fluid"]/h1') title = title1.text print(title) # transcript = driver.find_element_by_xpath('//div[@class="jet-button__container"]/a') # transcript = transcript.get_attribute('href') date_ = driver.find_element_by_xpath('//li[@class="jupiterx-post-meta-date list-inline-item"]/time') date_ = date_.text from dateutil.parser import parse date_ = parse(date_, fuzzy=True) print(date_, 'parse') post_date = datetime.strptime(str(date_), '%Y-%m-%d %H:%M:%S').strftime('%m/%d/%Y') print(post_date, "post_date") file_name = title.replace(" ", "_") if os.path.exists('./ctcfp.org/' + file_name): pass else: time.sleep(10) try: try: try: audio_path = driver.find_element_by_xpath('//div[@class="jet-button__container"]/a') except: audio_path = driver.find_element_by_xpath('//div[@class ="jupiterx-content"]/article/div/div[1]/ul/li[1]/a') except: audio_path = driver.find_element_by_xpath('//div[@class="jupiterx-post-content clearfix"]/div/div[1]/a') link = audio_path.get_attribute('href') print(link, "audio_link") text = "audio_file" params = { "ie": "UTF-8", "client": "tw-ob", "q": text, "tl": "en", "total": "1", "idx": "0", "textlen": str(len(text)) } response = requests.get(link, params=params) response.raise_for_status() assert response.headers["Content-Type"] == "audio/mpeg" with open("output.mp3", "wb") as file: file.write(response.content) print("Done.") os.rename("output.mp3", file_name + ".mp3") path = os.path.join(base_dir, file_name) os.mkdir(path) try: try: driver.find_element_by_xpath('//div[@class="elementor-container elementor-column-gap-default"]/div[2]/div/div/div/div/div/a/div[4]/span').click() except: driver.find_element_by_xpath('//div[@class ="jupiterx-content"]/article/div/div[1]/ul/li[2]/a').click() except: try: driver.find_element_by_xpath('//div[@class="jupiterx-post-content clearfix"]/ul/li[1]/a').click() except: driver.find_element_by_xpath('//div[@class="jupiterx-post-content clearfix"]/div/div[2]/a').click() time.sleep(20) filepath = '/home/webtunixi5/Downloads' filename = max([filepath + "/" + f for f in os.listdir(filepath)], key=os.path.getctime) print(filename) time.sleep(10) shutil.move(os.path.join('.', filename), file_name + '_orig.docx') text = docx2txt.process(file_name + '_orig.docx') time.sleep(5) with open(file_name + '_orig.txt', 'w') as f: for line in text: f.write(line) with open(file_name + '.txt', 'w') as f: for line in title: f.write(line) with open(file_name + '_info.txt', 'w') as f: f.write(i + '\n') f.write(post_date) print("Scraped transcript data") shutil.move(file_name + ".mp3", path + "/" + file_name + ".mp3") print('audio moved successful') shutil.move(file_name + '_orig.txt', path + '/' + file_name + '_orig.txt') shutil.move(file_name + '.txt', path + '/' + file_name + '.txt') shutil.move(file_name + '_info.txt', path + '/' + file_name + '_info.txt') print("Done.") if os.path.exists('./'+file_name + '_orig.docx'): os.remove('./'+file_name + '_orig.docx') except Exception as e: print(e) pass else: print("Not a podcast.") pass except Exception as e: print("++++++++++++++++++") pass
priyankathakur6321/WebScraping-Automation
ctcfp/main.py
main.py
py
5,904
python
en
code
0
github-code
6
32058216442
import sys input = sys.stdin.readline n = int(input()) sell = {} for i in range(n): name = input() if name not in sell: sell[name] = 1 else: sell[name] += 1 max_value = max(sell.values()) best = [] for key, value in sell.items(): if value == max_value: best.append(key) best = sorted(best) print(best[0])
doll2gom/Algorithm
백준/Silver/1302. 베스트셀러/베스트셀러.py
베스트셀러.py
py
378
python
en
code
0
github-code
6
27592910479
import numpy as np from collaborativefiltering import top_users, b2 from cfub import cfub from cfib import recommend_similar_books from new import new_user # Initialisation de l'utilisateur def run(): print("(paramètre de requête API) : ID utilisateur, ou 'NEW' pour un nouvel utilisateur.") print("Liste d'ID utilisateur ayant servi à entraîner l'IA.",top_users, "\n") ID = input() print ('(paramètre de requête API) : au moins un genre de livre renseigné par l\'utilisateur parmis la liste \n') reco_u1 = new_user() print('(paramètre de requête API) : id du livre actuellement ou récemment consulté\n', b2) iid = int(input()) if ID.isnumeric(): if int(ID) in top_users: cfub(int(ID)) else : print('l\'id renseigné n\'est pas dans la liste proposée') print("(réponse de requête API) recommandation basée sur les genres favoris :\n", list(reco_u1['original_title'])) recommend_similar_books(iid) run()
Thuy9906/bookreco
test.py
test.py
py
1,028
python
fr
code
0
github-code
6
37600184033
import torch from safetensors.torch import save_file import argparse from pathlib import Path def main(args): input_path = Path(args.input_path).resolve() output_path = args.output_path overwrite = args.overwrite if input_path.suffix == ".safetensors": raise ValueError( f"{input_path} is already a safetensors file. / {input_path} は既に safetensors ファイルです。" ) if output_path is None: output_path = input_path.parent / f"{input_path.stem}.safetensors" else: output_path = Path(output_path).resolve() if output_path.exists() and not overwrite: raise FileExistsError( f"{output_path.name} already exists. Use '--overwrite' or '-w' to overwite. / {output_path.name} は既に存在します。'--overwrite' か '-w' を指定すると上書きします。" ) print(f"Loading...") model = torch.load(input_path, map_location="cpu") save_file(model, output_path) print("Done!") print(f"Saved to {output_path} /\n {output_path} に保存しました。") if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument( "input_path", type=str, help="input path", ) parser.add_argument( "--output_path", "-o", type=str, help="output path", ) parser.add_argument( "--overwrite", "-w", action="store_true", help="overwrite output file", ) args = parser.parse_args() main(args)
p1atdev/sd_ti_merge
to_safetensors.py
to_safetensors.py
py
1,560
python
en
code
0
github-code
6
10233643835
from typing import List, Optional from twitchio import PartialUser, Client, Channel, CustomReward, parse_timestamp __all__ = ( "PoolError", "PoolFull", "PubSubMessage", "PubSubBitsMessage", "PubSubBitsBadgeMessage", "PubSubChatMessage", "PubSubBadgeEntitlement", "PubSubChannelPointsMessage", "PubSubModerationAction", "PubSubModerationActionModeratorAdd", "PubSubModerationActionBanRequest", "PubSubModerationActionChannelTerms", "PubSubChannelSubscribe", ) class PubSubError(Exception): pass class ConnectionFailure(PubSubError): pass class PoolError(PubSubError): pass class PoolFull(PoolError): pass class PubSubChatMessage: """ A message received from twitch. Attributes ----------- content: :class:`str` The content received id: :class:`str` The id of the payload type: :class:`str` The payload type """ __slots__ = "content", "id", "type" def __init__(self, content: str, id: str, type: str): self.content = content self.id = id self.type = type class PubSubBadgeEntitlement: """ A badge entitlement Attributes ----------- new: :class:`int` The new badge old: :class:`int` The old badge """ __slots__ = "new", "old" def __init__(self, new: int, old: int): self.new = new self.old = old class PubSubMessage: """ A message from the pubsub websocket Attributes ----------- topic: :class:`str` The topic subscribed to """ __slots__ = "topic", "_data" def __init__(self, client: Client, topic: Optional[str], data: dict): self.topic = topic self._data = data class PubSubBitsMessage(PubSubMessage): """ A Bits message Attributes ----------- message: :class:`PubSubChatMessage` The message sent along with the bits. badge_entitlement: Optional[:class:`PubSubBadgeEntitlement`] The badges received, if any. bits_used: :class:`int` The amount of bits used. channel_id: :class:`int` The channel the bits were given to. user: Optional[:class:`twitchio.PartialUser`] The user giving the bits. Can be None if anonymous. version: :class:`str` The event version. """ __slots__ = "badge_entitlement", "bits_used", "channel_id", "context", "anonymous", "message", "user", "version" def __init__(self, client: Client, topic: str, data: dict): super().__init__(client, topic, data) data = data["message"] self.message = PubSubChatMessage(data["data"]["chat_message"], data["message_id"], data["message_type"]) self.badge_entitlement = ( PubSubBadgeEntitlement( data["data"]["badge_entitlement"]["new_version"], data["data"]["badge_entitlement"]["old_version"] ) if data["data"]["badge_entitlement"] else None ) self.bits_used: int = data["data"]["bits_used"] self.channel_id: int = int(data["data"]["channel_id"]) self.user = ( PartialUser(client._http, data["data"]["user_id"], data["data"]["user_name"]) if data["data"]["user_id"] else None ) self.version: str = data["version"] class PubSubBitsBadgeMessage(PubSubMessage): """ A Badge message Attributes ----------- user: :class:`twitchio.PartialUser` The user receiving the badge. channel: :class:`twitchio.Channel` The channel the user received the badge on. badge_tier: :class:`int` The tier of the badge message: :class:`str` The message sent in chat. timestamp: :class:`datetime.datetime` The time the event happened """ __slots__ = "user", "channel", "badge_tier", "message", "timestamp" def __init__(self, client: Client, topic: str, data: dict): super().__init__(client, topic, data) data = data["message"] self.user = PartialUser(client._http, data["user_id"], data["user_name"]) self.channel: Channel = client.get_channel(data["channel_name"]) or Channel( name=data["channel_name"], websocket=client._connection ) self.badge_tier: int = data["badge_tier"] self.message: str = data["chat_message"] self.timestamp = parse_timestamp(data["time"]) class PubSubChannelPointsMessage(PubSubMessage): """ A Channel points redemption Attributes ----------- timestamp: :class:`datetime.datetime` The timestamp the event happened. channel_id: :class:`int` The channel the reward was redeemed on. id: :class:`str` The id of the reward redemption. user: :class:`twitchio.PartialUser` The user redeeming the reward. reward: :class:`twitchio.CustomReward` The reward being redeemed. input: Optional[:class:`str`] The input the user gave, if any. status: :class:`str` The status of the reward. """ __slots__ = "timestamp", "channel_id", "user", "id", "reward", "input", "status" def __init__(self, client: Client, topic: str, data: dict): super().__init__(client, topic, data) redemption = data["message"]["data"]["redemption"] self.timestamp = parse_timestamp(redemption["redeemed_at"]) self.channel_id: int = int(redemption["channel_id"]) self.id: str = redemption["id"] self.user = PartialUser(client._http, redemption["user"]["id"], redemption["user"]["display_name"]) self.reward = CustomReward(client._http, redemption["reward"], PartialUser(client._http, self.channel_id, None)) self.input: Optional[str] = redemption.get("user_input") self.status: str = redemption["status"] class PubSubModerationAction(PubSubMessage): """ A basic moderation action. Attributes ----------- action: :class:`str` The action taken. args: List[:class:`str`] The arguments given to the command. created_by: :class:`twitchio.PartialUser` The user that created the action. message_id: Optional[:class:`str`] The id of the message that created this action. target: :class:`twitchio.PartialUser` The target of this action. from_automod: :class:`bool` Whether this action was done automatically or not. """ __slots__ = "action", "args", "created_by", "message_id", "target", "from_automod" def __init__(self, client: Client, topic: str, data: dict): super().__init__(client, topic, data) self.action: str = data["message"]["data"]["moderation_action"] self.args: List[str] = data["message"]["data"]["args"] self.created_by = PartialUser( client._http, data["message"]["data"]["created_by_user_id"], data["message"]["data"]["created_by"] ) self.message_id: Optional[str] = data["message"]["data"].get("msg_id") self.target = ( PartialUser( client._http, data["message"]["data"]["target_user_id"], data["message"]["data"]["target_user_login"] ) if data["message"]["data"]["target_user_id"] else None ) self.from_automod: bool = data["message"]["data"].get("from_automod", False) class PubSubModerationActionBanRequest(PubSubMessage): """ A Ban/Unban event Attributes ----------- action: :class:`str` The action taken. args: List[:class:`str`] The arguments given to the command. created_by: :class:`twitchio.PartialUser` The user that created the action. target: :class:`twitchio.PartialUser` The target of this action. """ __slots__ = "action", "args", "created_by", "message_id", "target" def __init__(self, client: Client, topic: str, data: dict): super().__init__(client, topic, data) self.action: str = data["message"]["data"]["moderation_action"] self.args: List[str] = data["message"]["data"]["moderator_message"] self.created_by = PartialUser( client._http, data["message"]["data"]["created_by_id"], data["message"]["data"]["created_by_login"] ) self.target = ( PartialUser( client._http, data["message"]["data"]["target_user_id"], data["message"]["data"]["target_user_login"] ) if data["message"]["data"]["target_user_id"] else None ) class PubSubModerationActionChannelTerms(PubSubMessage): """ A channel Terms update. Attributes ----------- type: :class:`str` The type of action taken. channel_id: :class:`int` The channel id the action occurred on. id: :class:`str` The id of the Term. text: :class:`str` The text of the modified Term. requester: :class:`twitchio.PartialUser` The requester of this Term. """ __slots__ = "type", "channel_id", "id", "text", "requester", "expires_at", "updated_at" def __init__(self, client: Client, topic: str, data: dict): super().__init__(client, topic, data) self.type: str = data["message"]["data"]["type"] self.channel_id = int(data["message"]["data"]["channel_id"]) self.id: str = data["message"]["data"]["id"] self.text: str = data["message"]["data"]["text"] self.requester = PartialUser( client._http, data["message"]["data"]["requester_id"], data["message"]["data"]["requester_login"] ) self.expires_at = ( parse_timestamp(data["message"]["data"]["expires_at"]) if data["message"]["data"]["expires_at"] else None ) self.updated_at = ( parse_timestamp(data["message"]["data"]["updated_at"]) if data["message"]["data"]["updated_at"] else None ) class PubSubChannelSubscribe(PubSubMessage): """ Channel subscription Attributes ----------- channel: :class:`twitchio.Channel` Channel that has been subscribed or subgifted. context: :class:`str` Event type associated with the subscription product. user: Optional[:class:`twitchio.PartialUser`] The person who subscribed or sent a gift subscription. Can be None if anonymous. message: :class:`str` Message sent with the sub/resub. emotes: Optional[List[:class:`dict`]] Emotes sent with the sub/resub. is_gift: :class:`bool` If this sub message was caused by a gift subscription. recipient: Optional[:class:`twitchio.PartialUser`] The person the who received the gift subscription. sub_plan: :class:`str` Subscription Plan ID. sub_plan_name: :class:`str` Channel Specific Subscription Plan Name. time: :class:`datetime.datetime` Time when the subscription or gift was completed. RFC 3339 format. cumulative_months: :class:`int` Cumulative number of tenure months of the subscription. streak_months: Optional[:class:`int`] Denotes the user's most recent (and contiguous) subscription tenure streak in the channel. multi_month_duration: Optional[:class:`int`] Number of months gifted as part of a single, multi-month gift OR number of months purchased as part of a multi-month subscription. """ __slots__ = ( "channel", "context", "user", "message", "emotes", "is_gift", "recipient", "sub_plan", "sub_plan_name", "time", "cumulative_months", "streak_months", "multi_month_duration", ) def __init__(self, client: Client, topic: str, data: dict): super().__init__(client, topic, data) subscription = data["message"] self.channel: Channel = client.get_channel(subscription["channel_name"]) or Channel( name=subscription["channel_name"], websocket=client._connection ) self.context: str = subscription["context"] try: self.user = PartialUser(client._http, int(subscription["user_id"]), subscription["user_name"]) except KeyError: self.user = None self.message: str = subscription["sub_message"]["message"] try: self.emotes = subscription["sub_message"]["emotes"] except KeyError: self.emotes = None self.is_gift: bool = subscription["is_gift"] try: self.recipient = PartialUser( client._http, int(subscription["recipient_id"]), subscription["recipient_user_name"] ) except KeyError: self.recipient = None self.sub_plan: str = subscription["sub_plan"] self.sub_plan_name: str = subscription["sub_plan_name"] self.time = parse_timestamp(subscription["time"]) try: self.cumulative_months = int(subscription["cumulative_months"]) except KeyError: self.cumulative_months = None try: self.streak_months = int(subscription["streak_months"]) except KeyError: self.streak_months = None try: self.multi_month_duration = int(subscription["multi_month_duration"]) except KeyError: self.multi_month_duration = None class PubSubModerationActionModeratorAdd(PubSubMessage): """ A moderator add event. Attributes ----------- channel_id: :class:`int` The channel id the moderator was added to. moderation_action: :class:`str` Redundant. target: :class:`twitchio.PartialUser` The person who was added as a mod. created_by: :class:`twitchio.PartialUser` The person who added the mod. """ __slots__ = "channel_id", "target", "moderation_action", "created_by" def __init__(self, client: Client, topic: str, data: dict): super().__init__(client, topic, data) self.channel_id = int(data["message"]["data"]["channel_id"]) self.moderation_action: str = data["message"]["data"]["moderation_action"] self.target = PartialUser( client._http, data["message"]["data"]["target_user_id"], data["message"]["data"]["target_user_login"] ) self.created_by = PartialUser( client._http, data["message"]["data"]["created_by_user_id"], data["message"]["data"]["created_by"] ) _mod_actions = { "approve_unban_request": PubSubModerationActionBanRequest, "deny_unban_request": PubSubModerationActionBanRequest, "channel_terms_action": PubSubModerationActionChannelTerms, "moderator_added": PubSubModerationActionModeratorAdd, "moderation_action": PubSubModerationAction, } def _find_mod_action(client: Client, topic: str, data: dict): typ = data["message"]["type"] if typ in _mod_actions: return _mod_actions[typ](client, topic, data) else: raise ValueError(f"unknown pubsub moderation action '{typ}'") _mapping = { "channel-bits-events-v2": ("pubsub_bits", PubSubBitsMessage), "channel-bits-badge-unlocks": ("pubsub_bits_badge", PubSubBitsBadgeMessage), "channel-subscribe-events-v1": ("pubsub_subscription", PubSubChannelSubscribe), "chat_moderator_actions": ("pubsub_moderation", _find_mod_action), "channel-points-channel-v1": ("pubsub_channel_points", PubSubChannelPointsMessage), "whispers": ("pubsub_whisper", None), } def create_message(client, msg: dict): topic = msg["data"]["topic"].split(".")[0] r = _mapping[topic] return r[0], r[1](client, topic, msg["data"])
PythonistaGuild/TwitchIO
twitchio/ext/pubsub/models.py
models.py
py
15,690
python
en
code
714
github-code
6
20538355959
# https://leetcode.com/problems/trim-a-binary-search-tree/ """ Time complexity:- O(N) Space Complexity:- O(H) H = height of BST (call stack ) """ # Definition for a binary tree node. class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def trimBST(self, root, low, high): # Base case: If the root is None, return None (no tree). if not root: return None # If the current node's value is greater than 'high', trim the right subtree. if root.val > high: return self.trimBST(root.left, low, high) # If the current node's value is less than 'low', trim the left subtree. if root.val < low: return self.trimBST(root.right, low, high) # If the current node's value is within the [low, high] range, recursively trim both left and right subtrees. else: root.left = self.trimBST(root.left, low, high) root.right = self.trimBST(root.right, low, high) return root # Return the trimmed tree rooted at the current node.
Amit258012/100daysofcode
Day49/trim_a_bst.py
trim_a_bst.py
py
1,165
python
en
code
0
github-code
6
25503087204
from django.shortcuts import render, redirect from django.urls import reverse from django.contrib.auth.decorators import login_required from .models import ListingComment, Listing, Bid, Category from .forms import CreateListingForm import os import boto3 def home(request): listings = Listing.objects.filter(is_active=True) categories = Category.objects.all() return render(request, "auction/home.html", { 'listings': listings, 'categories': categories }) @login_required def createListing(request): if request.method == 'POST': form = CreateListingForm(request.POST , request.FILES) if form.is_valid(): listing = form.save(commit=False) listing.owner = request.user price = form.cleaned_data['price'] or 1 bid = Bid(bid=price, bid_owner=request.user) bid.save() listing.bid_price = bid if request.FILES['image']: image_file = request.FILES['image'] # Connect to S3 s3 = boto3.client('s3') # Upload the image file to S3 s3.upload_fileobj(image_file, os.getenv('AWS_STORAGE_BUCKET_NAME'), 'static/auction_images/' + image_file.name) # Get the URL of the uploaded image url = f"https://s3.amazonaws.com/{os.getenv('AWS_STORAGE_BUCKET_NAME')}/{'static/auction_images/' + image_file.name}" listing.image_url = url listing.save() return redirect(reverse('auction:home')) else: print(form.errors) form = CreateListingForm() return render(request, 'auction/createListing.html', { 'form': form }) def category(request): if request.method == 'POST': category = request.POST['category'] category_object = Category.objects.get(category_name=category) categories = Category.objects.exclude(category_name=category) listings = Listing.objects.filter(is_active=True, category=category_object) return render(request, 'auction/category.html', { 'listings': listings, 'categories': categories, 'category': category }) @login_required def listing(request, listing_id): listing = Listing.objects.get(id=listing_id) comments = ListingComment.objects.filter(listing=listing) if listing in request.user.user_watchlists.all(): watchlist = True else: watchlist = False return render(request, 'auction/listing.html', { 'listing': listing, 'watchlist': watchlist, 'comments': comments }) @login_required def addWatchlist(request): if request.method == 'POST': listing = Listing.objects.get(id=request.POST['listing_id']) listing.watchlist.add(request.user) listing.save() return redirect(reverse('auction:listing', args = (listing.id,))) @login_required def removeWatchlist(request): if request.method == 'POST': listing = Listing.objects.get(id=request.POST['listing_id']) listing.watchlist.remove(request.user) listing.save() return redirect(reverse('auction:listing', args = (listing.id,))) @login_required def watchlist(request): watchlists = request.user.user_watchlists.all() return render(request, 'auction/watchlist.html', { 'watchlists': watchlists }) @login_required def addComment(request): if request.method == 'POST': id = request.POST['listing_id'] listing = Listing.objects.get(id=id) content = request.POST['comment'] comment = ListingComment(content=content, listing=listing, author=request.user) comment.save() return redirect(reverse('auction:listing', args = (listing.id,))) @login_required def addBid(request): if request.method == 'POST': id = request.POST['listing_id'] listing = Listing.objects.get(id=id) bid = float(request.POST['bid']) current_bid = listing.bid_price.bid comments = ListingComment.objects.filter(listing=listing) if listing in request.user.user_watchlists.all(): watchlist = True else: watchlist = False if bid > current_bid: newBid = Bid(bid=bid, bid_owner=request.user) newBid.save() listing.bid_price = newBid listing.save() return render(request, 'auction/listing.html', { 'listing': listing, 'comments': comments, 'update': True, 'watchlist': watchlist }) else: return render(request, 'auction/listing.html', { 'listing': listing, 'comments': comments, 'update': False, 'watchlist': watchlist }) @login_required def removeListing(request, listing_id): if request.method == 'POST': listing = Listing.objects.get(id=listing_id) listing.delete() return redirect(reverse('auction:home')) @login_required def sellListing(request, listing_id): if request.method == 'POST': listing = Listing.objects.get(id=listing_id) listing.is_active = False listing.save() buyer = listing.bid_price.bid_owner comments = ListingComment.objects.filter(listing=listing) return render(request, 'auction/listing.html', { 'listing': listing, 'comments': comments, 'message': f'Sold to {buyer} for ${listing.bid_price.bid}' })
samyarsworld/social-network
auction/views.py
views.py
py
5,652
python
en
code
0
github-code
6
35416294037
import rdflib from rdflib import Graph from scipy.special import comb, perm from itertools import combinations g = Graph() g.parse(r'/Users/shenghua/Desktop/ontology/ontology.owl') deleted_str=r"http://www.semanticweb.org/zhou/ontologies/2020/3/untitled-ontology-19#" len_deleted_st=len(deleted_str) query = """ SELECT * WHERE { ?s rdfs:range ?o . } """ query_class = """ SELECT ?o WHERE { ?s rdfs:subClassOf ?o . } """ query1 = """SELECT ?downp ?downq ?action WHERE { ?action rdfs:domain ?dp. ?action rdfs:range ?rq. ?dcp rdfs:subClassOf ?dp. ?rcq rdfs:subClassOf ?rq. ?downp rdfs:subClassOf ?dcp. ?downq rdfs:subClassOf ?rcq. } """ query2 = """SELECT ?dp ?rq ?action WHERE { ?action rdfs:domain ?dcp. ?action rdfs:range ?rcq. ?dp rdfs:subClassOf ?dcp. ?rq rdfs:subClassOf ?rcq. } """ query3 = """SELECT ?dcp ?downq ?action WHERE { ?action rdfs:domain ?dp. ?action rdfs:range ?rq. ?dcp rdfs:subClassOf ?dp. ?rcq rdfs:subClassOf ?rq. ?downq rdfs:subClassOf ?rcq. } """ query4 = """SELECT ?downp ?rcq ?action WHERE { ?action rdfs:domain ?dp. ?action rdfs:range ?rq. ?dcp rdfs:subClassOf ?dp. ?rcq rdfs:subClassOf ?rq. ?downp rdfs:subClassOf ?dcp. } """ #print (g.subject_objects(predicate=None)) a=[] for row in g.query(query): for i in range(0,len(row)): if (str(row[0])[len_deleted_st:])=='detect': #print(str(row[1])[len_deleted_st:]) a.append(str(row[1])[len_deleted_st:]) #print (set(a)) detected_elements=set(a) print ("detected_elements:") print (detected_elements) allclass=[] for row in g.query(query_class): allclass.append(str(row[0])[len_deleted_st:]) all_high_level_class=set(allclass) print (all_high_level_class) track=[] for row in g.query(query): for i in range(0,len(row)): if (str(row[0])[len_deleted_st:])=='track': #print(str(row[1])[len_deleted_st:]) track.append(str(row[1])[len_deleted_st:]) #print (set(a)) tracked_elements=set(track) print ("tracked_elements:") print (tracked_elements) detected_or_tracked_elements=tracked_elements.union(detected_elements) d=[] for row in g.query(query1): #3-3 for i in range(0,len(row)): if ((str(row[2])[len_deleted_st:len_deleted_st+6])=='affect')and ((str(row[0])[len_deleted_st:]) !=(str(row[1])[len_deleted_st:]) )and ((str(row[0])[len_deleted_st:]) in (detected_or_tracked_elements)) and ((str(row[1])[len_deleted_st:]) in (detected_or_tracked_elements)) and ((str(row[0])[len_deleted_st:]) not in all_high_level_class) and ((str(row[1])[len_deleted_st:]) not in all_high_level_class): #print(str(row[0])[len_deleted_st:],str(row[1])[len_deleted_st:]) d.append((str(row[0])[len_deleted_st:],str(row[1])[len_deleted_st:])) #print(len(d)) affected_elements_3_3=set(d) print("affected_elements_3_3") print(affected_elements_3_3) d=[] for row in g.query(query2): #2-2 print (row) for i in range(0,len(row)): if ((str(row[2])[len_deleted_st:len_deleted_st+6])=='affect')and ((str(row[0])[len_deleted_st:]) !=(str(row[1])[len_deleted_st:]) )and ((str(row[0])[len_deleted_st:]) in (detected_or_tracked_elements)) and ((str(row[1])[len_deleted_st:]) in (detected_or_tracked_elements)) and ((str(row[0])[len_deleted_st:]) not in all_high_level_class) and ((str(row[1])[len_deleted_st:]) not in all_high_level_class): #print(str(row[0])[len_deleted_st:],str(row[1])[len_deleted_st:]) d.append((str(row[0])[len_deleted_st:],str(row[1])[len_deleted_st:])) print(d) #print(len(d)) affected_elements_2_2=set(d) print("affected_elements_2_2") print(affected_elements_2_2) d=[] for row in g.query(query3): #2-3 for i in range(0,len(row)): if ((str(row[2])[len_deleted_st:len_deleted_st+6])=='affect')and ((str(row[0])[len_deleted_st:]) !=(str(row[1])[len_deleted_st:]) )and ((str(row[0])[len_deleted_st:]) in (detected_or_tracked_elements)) and ((str(row[1])[len_deleted_st:]) in (detected_or_tracked_elements)) and ((str(row[0])[len_deleted_st:]) not in all_high_level_class) and ((str(row[1])[len_deleted_st:]) not in all_high_level_class): #print(str(row[0])[len_deleted_st:],str(row[1])[len_deleted_st:]) d.append((str(row[0])[len_deleted_st:],str(row[1])[len_deleted_st:])) #print(len(d)) affected_elements_2_3=set(d) print("affected_elements_2_3") print(affected_elements_2_3) d=[] for row in g.query(query4): #3-2 for i in range(0,len(row)): if ((str(row[2])[len_deleted_st:len_deleted_st+6])=='affect')and ((str(row[0])[len_deleted_st:]) !=(str(row[1])[len_deleted_st:]) )and ((str(row[0])[len_deleted_st:]) in (detected_or_tracked_elements)) and ((str(row[1])[len_deleted_st:]) in (detected_or_tracked_elements)) and ((str(row[0])[len_deleted_st:]) not in all_high_level_class) and ((str(row[1])[len_deleted_st:]) not in all_high_level_class): #print(str(row[0])[len_deleted_st:],str(row[1])[len_deleted_st:]) d.append((str(row[0])[len_deleted_st:],str(row[1])[len_deleted_st:])) #print(len(d)) affected_elements_3_2=set(d) print("affected_elements_3_2") print(affected_elements_3_2) affected_elements=((affected_elements_3_3.union(affected_elements_2_2)).union(affected_elements_3_2)).union(affected_elements_2_3) set(affected_elements) print ("affected_elements") for i in affected_elements: print(i) print (affected_elements) print (len(affected_elements)) potential_applications=[] number_of_potential_applications=0 for j in range(1, len(affected_elements)+1): number_of_potential_applications=number_of_potential_applications+comb(len(affected_elements), i) print (number_of_potential_applications) for p in list(combinations(affected_elements, 3)): potential_applications.append(p)
0AnonymousSite0/Data-and-Codes-for-Integrating-Computer-Vision-and-Traffic-Modelling
3. Shared codes/Codes for SPARQL query in the CV-TM ontology/Query of CV-TM Ontology.py
Query of CV-TM Ontology.py
py
5,900
python
en
code
4
github-code
6
36025283136
from ..Model import BootQModel from Agent import Agent import random from chainer import cuda try: import cupy except: pass import numpy as np import logging logger = logging.getLogger() logger.setLevel(logging.DEBUG) class BootQAgent(Agent): """ Deep Exploration via Bootstrapped DQN Args: _shard (class): necessary, shared part of q func _head (class): necessary, head part of q func _env (Env): necessary, env to learn, should be rewritten from Env _is_train (bool): default True _optimizer (chainer.optimizers): not necessary, if not then func won't be updated _replay (Replay): necessary for training _K (int): how many heads to use _mask_p (float): p to be passed when train for each head _gpu (bool): whether to use gpu _gamma (float): reward decay _batch_size (int): how much tuples to pull from replay _epsilon (float): init epsilon, p for choosing randomly _epsilon_decay (float): epsilon *= epsilon_decay _epsilon_underline (float): epsilon = max(epsilon_underline, epsilon) _grad_clip (float): clip grad, 0 is no clip """ def __init__(self, _shared, _head, _env, _is_train=True, _optimizer=None, _replay=None, _K=10, _mask_p=0.5, _gpu=False, _gamma=0.99, _batch_size=32, _epsilon=0.5, _epsilon_decay=0.995, _epsilon_underline=0.01, _grad_clip=1.): super(BootQAgent, self).__init__() self.is_train = _is_train self.q_func = BootQModel(_shared, _head, _K) if _gpu: self.q_func.to_gpu() self.env = _env if self.is_train: self.target_q_func = BootQModel(_shared, _head, _K) if _gpu: self.target_q_func.to_gpu() self.target_q_func.copyparams(self.q_func) if _optimizer: self.q_opt = _optimizer self.q_opt.setup(self.q_func) self.replay = _replay self.config.K = _K self.config.mask_p = _mask_p self.config.gpu = _gpu self.config.gamma = _gamma self.config.batch_size = _batch_size self.config.epsilon = _epsilon self.config.epsilon_decay = _epsilon_decay self.config.epsilon_underline = _epsilon_underline self.config.grad_clip = _grad_clip def startNewGame(self): super(BootQAgent, self).startNewGame() # randomly choose head self.use_head = random.randint(0, self.config.K - 1) logger.info('Use head: ' + str(self.use_head)) def step(self): if not self.env.in_game: return False # get current state cur_state = self.env.getState() # choose action in step action = self.chooseAction(self.q_func, cur_state) # do action and get reward reward = self.env.doAction(action) logger.info('Action: ' + str(action) + '; Reward: %.3f' % (reward)) if self.is_train: # get new state next_state = self.env.getState() # store replay_tuple into memory pool self.replay.push( cur_state, action, reward, next_state, np.random.binomial(1, self.config.mask_p, (self.config.K)).tolist() ) return self.env.in_game def forward(self, _cur_x, _next_x, _state_list): # get cur outputs cur_output = self.func(self.q_func, _cur_x, True) # get next outputs, NOT target next_output = self.func(self.q_func, _next_x, False) # choose next action for each output next_action = [ self.env.getBestAction( o.data, _state_list ) for o in next_output # for each head in Model ] # get next outputs, target next_output = self.func(self.target_q_func, _next_x, False) return cur_output, next_output, next_action def grad(self, _cur_output, _next_output, _next_action, _batch_tuples, _err_list, _err_count, _k): # alloc if self.config.gpu: _cur_output.grad = cupy.zeros_like(_cur_output.data) else: _cur_output.grad = np.zeros_like(_cur_output.data) # compute grad from each tuples for i in range(len(_batch_tuples)): # if use bootstrap and masked if not _batch_tuples[i].mask[_k]: continue cur_action_value = \ _cur_output.data[i][_batch_tuples[i].action].tolist() reward = _batch_tuples[i].reward target_value = reward # if not empty position, not terminal state if _batch_tuples[i].next_state.in_game: next_action_value = \ _next_output.data[i][_next_action[i]].tolist() target_value += self.config.gamma * next_action_value loss = cur_action_value - target_value _cur_output.grad[i][_batch_tuples[i].action] = 2 * loss _err_list[i] += abs(loss) _err_count[i] += 1 def doTrain(self, _batch_tuples, _weights): cur_x = self.getCurInputs(_batch_tuples) next_x = self.getNextInputs(_batch_tuples) # if bootstrap, they are all list for heads cur_output, next_output, next_action = self.forward( cur_x, next_x, [t.next_state for t in _batch_tuples]) # compute grad for each head err_list = [0.] * len(_batch_tuples) err_count = [0.] * len(_batch_tuples) for k in range(self.config.K): self.grad(cur_output[k], next_output[k], next_action[k], _batch_tuples, err_list, err_count, k) if _weights is not None: if self.config.gpu: _weights = cuda.to_gpu(_weights) self.gradWeight(cur_output[k], _weights) if self.config.grad_clip: self.gradClip(cur_output[k], self.config.grad_clip) # backward cur_output[k].backward() # adjust grads of shared for param in self.q_func.shared.params(): param.grad /= self.config.K # avg err for i in range(len(err_list)): if err_count[i] > 0: err_list[i] /= err_count[i] else: err_list[i] = None return err_list def chooseAction(self, _model, _state): if self.is_train: # update epsilon self.updateEpsilon() random_value = random.random() if random_value < self.config.epsilon: # randomly choose return self.env.getRandomAction(_state) else: # use model to choose x_data = self.env.getX(_state) output = self.func(_model, x_data, False) output = output[self.use_head] logger.info(str(output.data)) return self.env.getBestAction(output.data, [_state])[0] else: x_data = self.env.getX(_state) output = self.func(_model, x_data, False) action_dict = {} for o in output: action = self.env.getBestAction(o.data, [_state])[0] if action not in action_dict.keys(): action_dict[action] = 1 else: action_dict[action] += 1 logger.info(str(action_dict)) max_k = -1 max_v = 0 for k, v in zip(action_dict.keys(), action_dict.values()): if v > max_v: max_k = k max_v = v return max_k
ppaanngggg/DeepRL
DeepRL/Agent/BootQAgent.py
BootQAgent.py
py
7,856
python
en
code
29
github-code
6
8649575468
# 2839 : 설탕 배달 *** 해결 x while True : n = int(input("킬로그램 수 : ")) k5 = int(n / 5) k3 = int((n - 5*k5) / 3) if n % 5 == 0 : print(n / 5) elif (3*k3 + 5*k5) == n : print(k3 + k5) elif (3*k3 + 5*k5) != n : if k5 <= 2 : if (n-5*(k5-1)) % 3 == 0 : print( (n-5*(k5-1)) / 3 + k5-1) # else : 3으로도 안나눠떨어질 때 #수행문장 for i in range(1, k5) : if (n-5*(k5-i)) % 3 == 0 : print( (n-5*(k5-i)) / 3 + k5-i) else : print("-1") # 1) 5로 다 나눠지는지 확인 # 2) 5로 최대한 나눠보고 3의 배수를 늘려감 # 3) 3으로만 다 나눠지는지 확인 # 4) 그래도 안되면 -1 출력
kimhn0605/BOJ
fail/2839.py
2839.py
py
729
python
ko
code
0
github-code
6
10711040761
import tensorflow as tf from tensorflow import keras import numpy as np import os import sys sys.path.append(os.getcwd()) from utils.prepareReviewDataset import intToWord, return_processed_data_and_labels def decode_review(text): return " ".join([intToWord.get(i, "?") for i in text]) train_data, train_labels, test_data, test_labels = return_processed_data_and_labels(250) model = keras.Sequential() model.add(keras.layers.Embedding(88000, 16)) model.add(keras.layers.GlobalAveragePooling1D()) model.add(keras.layers.Dense(16, activation="relu")) model.add(keras.layers.Dense(1, activation="sigmoid")) model.summary() # prints a summary of the model model.compile(optimizer="adam", loss="binary_crossentropy", metrics = ["accuracy"]) x_val = train_data[:10000] x_train = train_data[10000:] y_val = train_labels[:10000] y_train = train_labels[10000:] fitModel = model.fit(x_train, y_train, epochs=40, batch_size=512, validation_data=(x_val, y_val), verbose=1) def saveTheModel(): model.save("model.h5") def printModelEvaluation(): results = model.evaluate(test_data, test_labels) print(results) def testModelOnTestData(): test_review = test_data[0] predict = model.predict([test_review]) print("Review: ") print(decode_review(test_review)) print("Prediction: " + str(predict[0])) print("Actual: " + str(test_labels[0]))
tung2389/Deep-Learning-projects
Text Classification/trainModel.py
trainModel.py
py
1,347
python
en
code
0
github-code
6
40080606131
import os import connexion from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_marshmallow import Marshmallow from flask_bcrypt import Bcrypt basedir = os.path.abspath(os.path.dirname(__file__)) # Create the Connexion application instance connex_app = connexion.App(__name__, specification_dir=basedir) # Get the underlying Flask app instance app = connex_app.app bcrypt = Bcrypt(app) # Configure the SQLAlchemy part of the app instance app.config['SQLALCHEMY_ECHO'] = True app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////' + os.path.join(basedir, 'database.db') app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False app.config["DEBUG"] = True # Create the SQLAlchemy db instance db = SQLAlchemy(app) # Initialize Marshmallow ma = Marshmallow(app) SECRET_KEY="\xb3\x88e\x0e\xab\xa93\x01x\x82\xd1\xe0\x1b\xb6f;\x1a\x91d\x91\xc1-I\x00" TIME_FOR_TOKEN_DAYS = 0 TIME_FOR_TOKEN_SECONDS = 600 BCRYPT_LOG_ROUNDS = 13
tuvetula/ApiRestFlask_videos
config.py
config.py
py
950
python
en
code
0
github-code
6
41543430774
import re import sys from .ply import lex from .ply.lex import TOKEN class CLexer(object): """ A lexer for the C- language. After building it, set the input text with input(), and call token() to get new tokens. The public attribute filename can be set to an initial filaneme, but the lexer will update it upon #line directives. """ def __init__(self, error_func, on_lbrace_func, on_rbrace_func, type_lookup_func): """ Create a new Lexer. error_func: An error function. Will be called with an error message, line and column as arguments, in case of an error during lexing. on_lbrace_func, on_rbrace_func: Called when an LBRACE or RBRACE is encountered (likely to push/pop type_lookup_func's scope) type_lookup_func: A type lookup function. Given a string, it must return True IFF this string is a name of a type that was defined with a typedef earlier. """ self.error_func = error_func self.on_lbrace_func = on_lbrace_func self.on_rbrace_func = on_rbrace_func self.type_lookup_func = type_lookup_func self.filename = '' # Keeps track of the last token returned from self.token() self.last_token = None # Allow either "# line" or "# <num>" to support GCC's # cpp output # self.line_pattern = re.compile(r'([ \t]*line\W)|([ \t]*\d+)') self.pragma_pattern = re.compile(r'[ \t]*pragma\W') def build(self, **kwargs): """ Builds the lexer from the specification. Must be called after the lexer object is created. This method exists separately, because the PLY manual warns against calling lex.lex inside __init__ """ self.lexer = lex.lex(object=self, **kwargs) def reset_lineno(self): """ Resets the internal line number counter of the lexer. """ self.lexer.lineno = 1 def input(self, text): self.lexer.input(text) def token(self): self.last_token = self.lexer.token() return self.last_token def find_tok_column(self, token): """ Find the column of the token in its line. """ last_cr = self.lexer.lexdata.rfind('\n', 0, token.lexpos) return token.lexpos - last_cr def _error(self, msg, token): location = self._make_tok_location(token) self.error_func(msg, location[0], location[1]) self.lexer.skip(1) def _make_tok_location(self, token): return (token.lineno, self.find_tok_column(token)) ## ## Reserved keywords ## keywords = ( 'BOOL', 'BREAK', 'ELSE', 'FALSE', 'FOR', 'IF', 'INT', 'READ', 'RETURN', 'STRING', 'TRUE', 'VOID', 'WHILE', 'WRITE' ) keyword_map = {} for keyword in keywords: if keyword == '_BOOL': keyword_map['_Bool'] = keyword elif keyword == '_COMPLEX': keyword_map['_Complex'] = keyword else: keyword_map[keyword.lower()] = keyword ## ## All the tokens recognized by the lexer ## tokens = keywords + ( # Identifiers 'ID', # Type identifiers (identifiers previously defined as # types with typedef) 'TYPEID', # String literals 'STRING_LITERAL', 'WSTRING_LITERAL', # Operators 'PLUS', 'MINUS', 'TIMES', 'DIVIDE', 'MOD', 'AND', 'OR', 'NOT', 'LSHIFT', 'RSHIFT', # Relations 'EQ', 'NE', 'LT', 'LE', 'GT', 'GE', # Assignment 'EQUALS', 'TIMESEQUAL', 'DIVEQUAL', 'MODEQUAL', 'PLUSEQUAL', 'MINUSEQUAL', 'LSHIFTEQUAL','RSHIFTEQUAL', 'ANDEQUAL', 'XOREQUAL', 'OREQUAL', # Increment/decrement 'PLUSPLUS', 'MINUSMINUS', # Conditional operator (?) 'CONDOP', # Delimeters 'LPAREN', 'RPAREN', # ( ) 'LBRACKET', 'RBRACKET', # [ ] 'LBRACE', 'RBRACE', # { } 'COMMA', 'PERIOD', # . , 'SEMI', 'COLON', # ; : # Ellipsis (...) 'ELLIPSIS', # pre-processor 'PPHASH', # '#' 'PPPRAGMA', # 'pragma' 'PPPRAGMASTR', )
ricoms/mips
compiladorCminus/pycminus/c_lexer.py
c_lexer.py
py
4,426
python
en
code
0
github-code
6
24370177566
import unittest class TestImageGen(unittest.TestCase): def test_image_gen(self): from src.dataio import GridIO, FlowIO from src.create_particles import Particle, LaserSheet, CreateParticles from src.ccd_projection import CCDProjection from src.intensity import Intensity from src.image_gen import ImageGen # Read-in the grid and flow file grid = GridIO('../data/shocks/interpolated_data/mgrd_to_p3d.x') grid.read_grid() grid.compute_metrics() flow = FlowIO('../data/shocks/interpolated_data/mgrd_to_p3d_particle.q') flow.read_flow() # Set particle data p = Particle() p.min_dia = 144e-9 # m p.max_dia = 573e-9 # m p.mean_dia = 281e-9 # m p.std_dia = 97e-9 # m p.density = 810 # kg/m3 p.n_concentration = 25 p.compute_distribution() # Read-in the laser sheet laser = LaserSheet(grid) # z-location laser.position = 0.00025 # in m laser.thickness = 0.0001 # in m (Data obtained from LaVision) laser.pulse_time = 1e-9 laser.compute_bounds() # path to save files path = '../data/shocks/interpolated_data/particle_snaps/' for i in range(1): # Create particle locations array ia_bounds = [None, None, None, None] loc = CreateParticles(grid, flow, p, laser, ia_bounds) # x_min, x_max, y_min, y_max --> ia_bounds loc.ia_bounds = [0.0016, 0.0025, 0.0002, 0.0004] # in m loc.in_plane = 70 loc.compute_locations() loc.compute_locations2() # Create particle projections (Simulating data from EUROPIV) proj = CCDProjection(loc) proj.dpi = 72 proj.xres = 1024 proj.yres = 1024 # Set distance based on similar triangles relationship proj.d_ccd = proj.xres * 25.4e-3 / proj.dpi # in m proj.d_ia = 0.0009 # in m; ia_bounds (max - min) proj.compute() cache = (proj.projections[:, 2], proj.projections[:, 2], proj.projections[:, 0], proj.projections[:, 1], 2.0, 2.0, 1.0, 1.0) intensity = Intensity(cache, proj) intensity.setup() intensity.compute() snap = ImageGen(intensity) snap.snap(snap_num=1) # snap.save_snap(fname=path + str(i) + '_1.tif') snap.check_data(snap_num=1) print('Done with image 1 for pair number ' + str(i) + '\n') cache2 = (proj.projections2[:, 2], proj.projections2[:, 2], proj.projections2[:, 0], proj.projections2[:, 1], 2.0, 2.0, 1.0, 1.0) intensity2 = Intensity(cache2, proj) intensity2.setup() intensity2.compute() # snap2 = ImageGen(intensity2) snap2.snap(snap_num=2) # snap2.save_snap(fname=path + str(i) + '_2.tif') snap2.check_data(snap_num=2) print('Done with image 2 for pair number ' + str(i) + '\n') if __name__ == '__main__': unittest.main()
kalagotla/syPIV
test/test_image_gen.py
test_image_gen.py
py
3,247
python
en
code
0
github-code
6
40029073689
from_path = "D:/PasaOpasen.github.io/images/Миша Светлов/вторая съемка/отбор2" to_path = "D:/PasaOpasen.github.io/images/Миша Светлов/вторая съемка/отбор2ориги" where = "C:/Users/qtckp/YandexDisk/Загрузки/ДИМА" import glob import os import shutil files = [ os.path.splitext(os.path.basename(file))[0] + '.cr2' for file in glob.glob(os.path.join(from_path,'*'))] print(files) for file in files: shutil.copyfile(os.path.join(where, file), os.path.join(to_path, file))
PasaOpasen/PasaOpasen.github.io
images/Миша Светлов/вторая съемка/migrate.py
migrate.py
py
551
python
en
code
2
github-code
6
24046293426
# Autor: João PauLo Falcão # Github: https://github.com/jplfalcao # Data de criação: 09/10/2023 # Data de modificação: # Versão: 1.0 # Importando a biblioteca import yt_dlp # Endereço do vídeo a ser baixado url = input("Digite a url do vídeo: ") # Especificando o formato '.mp4' para o vídeo ydl_opts = { 'format': 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/mp4' } # Usando a classe YoutubeDL para baixar o vídeo with yt_dlp.YoutubeDL(ydl_opts) as ydl: ydl.download([url]) print("Vídeo baixado com sucesso!")
jplfalcao/python
youtube_video_download/ytvd.py
ytvd.py
py
532
python
pt
code
0
github-code
6
21763755802
# Approach 1: Coloring by Depth-First Search # Time: O(N + E), N = no. of node_idxs, E = no. of edges # Space: O(N) class Solution: def isBipartite(self, graph: List[List[int]]) -> bool: color = {} for node_idx in range(len(graph)): if node_idx not in color: stack = [node_idx] color[node_idx] = 0 while stack: node_idx = stack.pop() for neighbor in graph[node_idx]: if neighbor not in color: stack.append(neighbor) color[neighbor] = color[node_idx] ^ 1 elif color[neighbor] == color[node_idx]: return False return True
jimit105/leetcode-submissions
problems/is_graph_bipartite?/solution.py
solution.py
py
785
python
en
code
0
github-code
6
22340672031
#!/usr/bin/env python def read_input(): with open('./inputs/day04') as f: return [l.strip() for l in f.readlines()] def _to_range(pair): return range(int(pair[0]), int(pair[1]) + 1) def get_pairs(): for line in read_input(): yield ( set(_to_range(p.split('-'))) for p in line.split(',') ) def part1(): total = 0 for p1, p2 in get_pairs(): if p1 >= p2 or p1 <= p2: total += 1 print(f'part 1: {total}') def part2(): total = 0 for p1, p2 in get_pairs(): if p1 & p2: total += 1 print(f'part 2: {total}') if __name__ == '__main__': part1() part2()
denkl/advent-of-code
day04.py
day04.py
py
685
python
en
code
1
github-code
6
30311558976
# -*- coding: utf-8 -*- from __future__ import print_function from os import sep from os.path import dirname, normpath from pickle import HIGHEST_PROTOCOL #------------------------------------------------------------------------- # Paths #------------------------------------------------------------------------- PROGRAM_DIR = dirname(__file__) # location of const.py ! PROTO_DIR = PROGRAM_DIR + sep + 'proto' + sep DATA_DIR = normpath(PROGRAM_DIR + sep + '..' + sep + 'data') print('Program and data directory set to:', PROGRAM_DIR, DATA_DIR) CSV_DIR = DATA_DIR + sep + 'csv' INI_DIR = DATA_DIR + sep + 'datafiles' FIGS_DIR = DATA_DIR + sep + 'datafiles' #------------------------------------------------------------------------- # Default file and directory names #------------------------------------------------------------------------- DEFAULTS_ININAME = 'defaults.ini' CONSTANTS_ININAME = 'constants.ini' MEASUREMENTS_ININAME = 'measurements.ini' PLOTSTYLE_ININAME = 'plotstyles.ini' MASKS_DIRNAME = 'masks' DUMP_DATA_FILENAME = 'data.dat' #------------------------------------------------------------------------- # Plotting #------------------------------------------------------------------------- # Dumping data format: This specifies the format used for data dumping. # For compatibility with python 2.x the value of '2' is used. In general, # if compatibility is not needed, the HIGHEST_PROTOCOL value could be used DUMP_DATA_VERSION=2 DIFFPROG = "diff"
bmcage/centrifuge-1d
centrifuge1d/const.py
const.py
py
1,505
python
en
code
0
github-code
6
45517639514
company_motto = "Copeland's Corporate Company helps you capably cope with the constant cacophony of daily life" # Find the second to last character in company_motto. second_to_last = company_motto[-2:-1] print(second_to_last) # f # create a slice of the last 4 characters in company_motto. final_word = company_motto[-4:] print(final_word) # life # get_length() that takes a string as an input and returns the number of characters in that string. # Do this by iterating through the string, don’t cheat and use len() def get_length(input): char_num = 0 for letter in input: #print(letter) char_num += 1 return char_num print(get_length("Albus")) # 5 # Find / count characters within a string favorite_fruit = "blueberry" counter = 0 for character in favorite_fruit: if character == "b": counter = counter + 1 print(counter) # 2 def letter_check(word, letter): for character in word: if character == letter: return True return False # This function should return True if the word contains the letter and False if it does not. def letter_check(word, letter): for char in word: if char == letter: return True return False print(letter_check("Albus", "u")) # True # "letter in word" is a boolean expression that is True if the string letter is in the string word. Here are some examples. It not only works with letters, but with entire strings as well. print("melon" in "watermelon") # True print("melon" in "butterfly") # False # Write a function called contains that takes two arguments, big_string and little_string and returns True if big_string contains little_string. For example contains("watermelon", "melon") should return True and contains("watermelon", "berry") should return False. def contains_long(big_string, little_string): if little_string in big_string: return True return False # Better solution: def contains(big_string, little_string): return little_string in big_string # Write a function called common_letters that takes two arguments, string_one and string_two and then returns a list with all of the letters they have in common. def common_letters(string_one, string_two): common = [] for letter in string_one: if (letter in string_two) and not (letter in common): common.append(letter) return common print(common_letters("butterfly", "fly")) # ['f', 'l', 'y'] print(common_letters("mississippi", "pizza")) # ['i', 'p'] print(common_letters("mississippi", "bear")) # []
candytale55/working-with-strings
working_with_strings_all.py
working_with_strings_all.py
py
2,505
python
en
code
0
github-code
6
10699368918
# -*- coding:utf-8 -*- import cv2 import os from glob import glob import numpy as np import shutil '''处理原图片得到人物脸部图片并按比例分配train和test用于训练模型''' SRC = "Raw" # 待处理的文件路径 DST = "data2" # 处理后的文件路径 TRAIN_PER = 5 # train的图片比例 TEST_PER = 1 # test的图片比例 def rename_file(path, new_name="", start_num=0, file_type=""): if not os.path.exists(path): return count = start_num files = os.listdir(path) for file in files: old_path = os.path.join(path, file) if os.path.isfile(old_path): if file_type == "": file_type = os.path.splitext(old_path)[1] new_path = os.path.join(path, new_name + str(count) + file_type) if not os.path.exists(new_path): os.rename(old_path, new_path) count = count + 1 # print("Renamed %d file(s)" % (count - start_num)) def get_faces(src, dst, cascade_file="lbpcascade_animeface.xml"): if not os.path.isfile(cascade_file): raise RuntimeError("%s: not found" % cascade_file) # Create classifier cascade = cv2.CascadeClassifier(cascade_file) files = [y for x in os.walk(src) for y in glob(os.path.join(x[0], '*.*'))] # 妙啊,一句话得到一个文件夹中所有文件 for image_file in files: image_file = image_file.replace('\\', '/') # 解决Windows下的文件路径问题 target_path = "/".join(image_file.strip("/").split('/')[1:-1]) target_path = os.path.join(dst, target_path) + "/" if not os.path.exists(target_path): os.makedirs(target_path) count = len(os.listdir(target_path)) + 1 image = cv2.imdecode(np.fromfile(image_file, dtype=np.uint8), -1) # 解决中文路径读入图片问题 gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) gray = cv2.equalizeHist(gray) faces = cascade.detectMultiScale(gray, # detector options scaleFactor=1.05, # 指定每个图像缩放比例缩小图像大小的参数 minNeighbors=4, # 此参数将影响检测到的面孔。值越高,检测结果越少,但质量越高 minSize=(24, 24) # 最小对象大小。小于此值的对象将被忽略 ) for (x, y, w, h) in faces: crop_img = image[y:y + h, x:x + w] crop_img = cv2.resize(crop_img, (96, 96)) # 重置为96*96 # filename = os.path.basename(image_file).split('.')[0] cv2.imencode('.jpg', crop_img)[1].tofile(os.path.join(target_path, str(count) + ".jpg")) print("All images are cropped") def divide_train_test(src, train_percentage=5, test_percentage=1): if not os.path.exists(src): print("folder %s is not exist" % src) return dirs = os.listdir(src) test_dir = os.path.join(src, "test") train_dir = os.path.join(src, "train") if not os.path.exists(test_dir): os.mkdir(test_dir) if not os.path.exists(train_dir): os.mkdir(train_dir) for dir_name in dirs: if dir_name != "test" and dir_name != "train": current_dir = os.path.join(src, dir_name) test_dir = os.path.join(src, "test", dir_name) train_dir = os.path.join(src, "train", dir_name) if not os.path.exists(test_dir): os.mkdir(test_dir) if not os.path.exists(train_dir): os.mkdir(train_dir) if os.path.isdir(current_dir): images = os.listdir(current_dir) image_num = len(images) for image in images: filename = os.path.basename(image).split('.')[0] if filename.isdigit(): percentage = train_percentage + test_percentage test_num = (image_num / percentage) * test_percentage + 1 if int(filename) <= test_num: if not os.path.exists(os.path.join(test_dir, image)): shutil.move(os.path.join(current_dir, image), os.path.join(test_dir)) else: os.remove(os.path.join(current_dir, image)) else: if not os.path.exists(os.path.join(train_dir, image)): shutil.move(os.path.join(current_dir, image), os.path.join(train_dir)) else: os.remove(os.path.join(current_dir, image)) shutil.rmtree(current_dir) for dirs in os.listdir(src): for name in os.listdir(os.path.join(src, dirs)): if os.path.isdir(os.path.join(src, dirs, name)): rename_file(os.path.join(src, dirs, name)) print("Set all cropped images to train and test") def main(): get_faces(SRC, DST) divide_train_test(src=DST, train_percentage=TRAIN_PER, test_percentage=TEST_PER) if __name__ == '__main__': main()
mikufanliu/AnimeCharacterRecognition
get_faces.py
get_faces.py
py
5,231
python
en
code
4
github-code
6
6814941665
from urllib.request import urlopen from pdfminer.high_level import extract_text def pdf_to_text(data): with urlopen(data) as wFile: text = extract_text(wFile) return text docUrl = 'https://diavgeia.gov.gr/doc/ΩΕΚ64653ΠΓ-2ΞΡ' print(pdf_to_text(docUrl))
IsVeneti/greek-gov-nlp
Preprocessing/ConvertPdf.py
ConvertPdf.py
py
280
python
en
code
1
github-code
6
70159895227
__all__ = [ 'points_to_morton', 'morton_to_points', 'points_to_corners', 'coords_to_trilinear', 'unbatched_points_to_octree', 'quantize_points' ] import torch from kaolin import _C def quantize_points(x, level): r"""Quantize :math:`[-1, 1]` float coordinates in to :math:`[0, (2^{level})-1]` integer coords. If a point is out of the range :math:`[-1, 1]` it will be clipped to it. Args: x (torch.FloatTensor): Floating point coordinates, must be of last dimension 3. level (int): Level of the grid Returns (torch.ShortTensor): Quantized 3D points, of same shape than x. """ res = 2 ** level qpts = torch.floor(torch.clamp(res * (x + 1.0) / 2.0, 0, res - 1.)).short() return qpts def unbatched_points_to_octree(points, level, sorted=False): r"""Convert (quantized) 3D points to an octree. This function assumes that the points are all in the same frame of reference of :math:`[0, 2^level]`. Note that SPC.points does not satisfy this constraint. Args: points (torch.ShortTensor): The Quantized 3d points. This is not exactly like SPC points hierarchies as this is only the data for a specific level. level (int): Max level of octree, and the level of the points. sorted (bool): True if the points are unique and sorted in morton order. Returns: (torch.ByteTensor): the generated octree, of shape :math:`(2^\text{level}, 2^\text{level}, 2^\text{level})`. """ if not sorted: unique = torch.unique(points.contiguous(), dim=0).contiguous() morton = torch.sort(points_to_morton(unique).contiguous())[0] points = morton_to_points(morton.contiguous()) return _C.ops.spc.points_to_octree(points.contiguous(), level) def points_to_morton(points): r"""Convert (quantized) 3D points to morton codes. Args: points (torch.ShortTensor): Quantized 3D points. This is not exactly like SPC points hierarchies as this is only the data for a specific level, of shape :math:`(\text{num_points}, 3)`. Returns: (torch.LongTensor): The morton code of the points, of shape :math:`(\text{num_points})` Examples: >>> inputs = torch.tensor([ ... [0, 0, 0], ... [0, 0, 1], ... [0, 0, 2], ... [0, 0, 3], ... [0, 1, 0]], device='cuda', dtype=torch.int16) >>> points_to_morton(inputs) tensor([0, 1, 8, 9, 2], device='cuda:0') """ shape = list(points.shape)[:-1] points = points.reshape(-1, 3) return _C.ops.spc.points_to_morton_cuda(points.contiguous()).reshape(*shape) def morton_to_points(morton): r"""Convert morton codes to points. Args: morton (torch.LongTensor): The morton codes of quantized 3D points, of shape :math:`(\text{num_points})`. Returns: (torch.ShortInt): The points quantized coordinates, of shape :math:`(\text{num_points}, 3)`. Examples: >>> inputs = torch.tensor([0, 1, 8, 9, 2], device='cuda') >>> morton_to_points(inputs) tensor([[0, 0, 0], [0, 0, 1], [0, 0, 2], [0, 0, 3], [0, 1, 0]], device='cuda:0', dtype=torch.int16) """ shape = list(morton.shape) shape.append(3) morton = morton.reshape(-1) return _C.ops.spc.morton_to_points_cuda(morton.contiguous()).reshape(*shape) def points_to_corners(points): r"""Calculates the corners of the points assuming each point is the 0th bit corner. Args: points (torch.ShortTensor): Quantized 3D points, of shape :math:`(\text{num_points}, 3)`. Returns: (torch.ShortTensor): Quantized 3D new points, of shape :math:`(\text{num_points}, 8, 3)`. Examples: >>> inputs = torch.tensor([ ... [0, 0, 0], ... [0, 2, 0]], device='cuda', dtype=torch.int16) >>> points_to_corners(inputs) tensor([[[0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 1, 1], [1, 0, 0], [1, 0, 1], [1, 1, 0], [1, 1, 1]], <BLANKLINE> [[0, 2, 0], [0, 2, 1], [0, 3, 0], [0, 3, 1], [1, 2, 0], [1, 2, 1], [1, 3, 0], [1, 3, 1]]], device='cuda:0', dtype=torch.int16) """ shape = list(points.shape) shape.insert(-1, 8) return _C.ops.spc.points_to_corners_cuda(points.contiguous()).reshape(*shape) def coords_to_trilinear(coords, points): r"""Calculates the coefficients for trilinear interpolation. To interpolate with the coefficients, do: ``torch.sum(features * coeffs, dim=-1)`` with ``features`` of shape :math:`(\text{num_points}, 8)` Args: coords (torch.FloatTensor): Floating point 3D points, of shape :math:`(\text{num_points}, 3)`. points (torch.ShortTensor): Quantized 3D points (the 0th bit of the voxel x is in), of shape :math:`(\text{num_points}, 3)`. Returns: (torch.FloatTensor): The trilinear interpolation coefficients, of shape :math:`(\text{num_points}, 8)`. """ shape = list(points.shape) shape[-1] = 8 points = points.reshape(-1, 3) coords = coords.reshape(-1, 3) return _C.ops.spc.coords_to_trilinear_cuda(coords.contiguous(), points.contiguous()).reshape(*shape)
silence394/GraphicsSamples
Nvida Samples/kaolin/kaolin/ops/spc/points.py
points.py
py
5,820
python
en
code
0
github-code
6
30099457858
from unittest.mock import Mock from .imapclient_test import IMAPClientTest class TestFolderStatus(IMAPClientTest): def test_basic(self): self.client._imap.status.return_value = ( "OK", [b"foo (MESSAGES 3 RECENT 0 UIDNEXT 4 UIDVALIDITY 1435636895 UNSEEN 0)"], ) out = self.client.folder_status("foo") self.client._imap.status.assert_called_once_with( b'"foo"', "(MESSAGES RECENT UIDNEXT UIDVALIDITY UNSEEN)" ) self.assertDictEqual( out, { b"MESSAGES": 3, b"RECENT": 0, b"UIDNEXT": 4, b"UIDVALIDITY": 1435636895, b"UNSEEN": 0, }, ) def test_literal(self): self.client._imap.status.return_value = ( "OK", [(b"{3}", b"foo"), b" (UIDNEXT 4)"], ) out = self.client.folder_status("foo", ["UIDNEXT"]) self.client._imap.status.assert_called_once_with(b'"foo"', "(UIDNEXT)") self.assertDictEqual(out, {b"UIDNEXT": 4}) def test_extra_response(self): # In production, we've seen folder names containing spaces come back # like this and be broken into two components in the tuple. server_response = [b"My files (UIDNEXT 24369)"] mock = Mock(return_value=server_response) self.client._command_and_check = mock resp = self.client.folder_status("My files", ["UIDNEXT"]) self.assertEqual(resp, {b"UIDNEXT": 24369}) # We've also seen the response contain mailboxes we didn't # ask for. In all known cases, the desired mailbox is last. server_response = [b"sent (UIDNEXT 123)\nINBOX (UIDNEXT 24369)"] mock = Mock(return_value=server_response) self.client._command_and_check = mock resp = self.client.folder_status("INBOX", ["UIDNEXT"]) self.assertEqual(resp, {b"UIDNEXT": 24369})
mjs/imapclient
tests/test_folder_status.py
test_folder_status.py
py
1,969
python
en
code
466
github-code
6
18020255074
import random,argparse,sys parser = argparse.ArgumentParser() import numpy as np class PlannerEncoder: def __init__(self, opponent, p,q) -> None: self.p = p; self.q = q self.idx_to_states = {} self.opp_action_probs = {} with open(opponent,'r') as file: i = 0 for line in file: parts = line.split() if parts[0] == 'state': continue if len(parts[0]) == 7: self.idx_to_states[i] = parts[0] self.opp_action_probs[parts[0]] = [float(parts[1]), float(parts[2]), float(parts[3]), float(parts[4])] i+=1 self.idx_to_states[i] = 'lost' # both of these are terminal states self.idx_to_states[i+1] = 'goal' self.states_to_idx = {} for i in self.idx_to_states: self.states_to_idx[self.idx_to_states[i]] = i self.S = len(self.idx_to_states) self.A = 10 # Next step is to calculate probs based on different situations def player_pos(self, player, action): new = None if action ==0: new = player -1 if (new-1)//4 == (player-1)//4 and new > 0 and new < 17: player = new elif action == 1: new = player +1 if (new-1)//4 == (player-1)//4 and new > 0 and new < 17: player = new elif action ==2: new = player - 4 if new > 0 and new < 17: player = new elif action ==3: new = player + 4 if new > 0 and new < 17: player = new return player def state_after_action(self, curr_state, a): b1_int = int(curr_state[:2]) b2_int = int(curr_state[2:4]) r_int = int(curr_state[4:6]) ball_int = int(curr_state[-1]) if a <4: b1_int = self.player_pos(b1_int, a) elif a < 8: b2_int = self.player_pos(b2_int, a - 4) elif a == 8: if ball_int ==1: ball_int = 2 elif ball_int ==2: ball_int = 1 elif a == 9: return 'goal' b1_str = str(b1_int) ; b2_str = str(b2_int) r_str = str(r_int) ball_str = str(ball_int) if len(b1_str)==1: b1_str = '0' + b1_str if len(b2_str)==1: b2_str = '0' + b2_str if len(r_str)==1: r_str = '0' + r_str new_state = b1_str + b2_str + r_str + ball_str return new_state def cordinates(self, state): b1 = int(state[:2]); b2 = int(state[2:4]); r = int(state[-3:-1]) b1_cor = ( (b1 -1)//4 , (b1-1)%4 ) b2_cor = ( (b2 -1)//4 , (b2-1)%4 ) r_cor = ( (r -1)//4 , (r-1)%4 ) return [b1_cor, b2_cor, r_cor] def transition_function(self, current_s, next_s, action): ball_pos = int(current_s[-1]) if action <4: if ball_pos == 1: b1_old = current_s[:2] ; r_old = current_s[-3:-1] b1_new = next_s[:2] ; r_new = next_s[-3:-1] if b1_new == r_new: return (0.5 - self.p, 0.5 + self.p) elif b1_old == r_new and b1_new == r_old: return (0.5 - self.p, 0.5 + self.p) else: return (1- self.p, self.p) elif ball_pos == 2: return (1- self.p, self.p) elif action <8: if ball_pos == 1: return (1-self.p, self.p) elif ball_pos == 2: b2_old = current_s[2:4] ; r_old = current_s[-3:-1] b2_new = next_s[2:4] ; r_new = next_s[-3:-1] if b2_new == r_new: return (0.5 - self.p, 0.5 + self.p) elif b2_old == r_new and b2_new == r_old: return (0.5 - self.p, 0.5 + self.p) else: return (1- self.p, self.p) if action ==8: b1_cor, b2_cor, r_cor = self.cordinates(next_s) val = self.q - 0.1*max( abs(b1_cor[0] - b2_cor[0]), abs(b1_cor[1] - b2_cor[1])) if b1_cor[0] == r_cor[0] and b2_cor[0] == r_cor[0]: return (0.5*val, 1 - 0.5*val) elif b1_cor == r_cor or b2_cor == r_cor: return (0.5*val, 1 - 0.5*val) elif ((b1_cor[1]- r_cor[1])/(b1_cor[0] - r_cor[0] + 1e-3)) == ((r_cor[1] - b2_cor[1])/(r_cor[0]- b2_cor[0] + 1e-3)): return (0.5*val, 1 - 0.5*val) else: return (val, 1- val) if action ==9: b1_cor, b2_cor, r_cor = self.cordinates(next_s) ball_pos = int(current_s[-1]) if ball_pos ==1: val = self.q - 0.2*(3 - b1_cor[1]) # NOTE my x,y are reverse to the one used in the assgn description # I use like the matrix 0,1 axis if r_cor[0]>0 and r_cor[0]<3 and r_cor[1]>1: return (0.5*val, 1- 0.5*val) else: return( val, 1-val) elif ball_pos ==2: val = self.q - 0.2*(3 - b2_cor[1]) # NOTE if r_cor[0]>0 and r_cor[0]<3 and r_cor[1]>1: return (0.5*val, 1- 0.5*val) else: return( val, 1-val) def calculate_trans_probs(self): self.trans_probs = np.zeros((self.S, self.A, self.S)) for s in range(self.S - 2): # we don't start from lost and goal state current_s = self.idx_to_states[s] for a in range(self.A): if a <9: new_state = self.state_after_action(current_s, a) if new_state != current_s: r_int = int(current_s[-3:-1]) for i, prob_opp in enumerate(self.opp_action_probs[current_s]): # now for the current_s you will get a reaction from the opponent if prob_opp !=0: r_str = str(self.player_pos(r_int, i)) # 'i' would give the action for R if len(r_str)==1: r_str = '0' + r_str # NOTE: I hope the prob's are zero when the R is at the edge next_s = new_state[:4] + r_str + new_state[-1] # Now let's call a helper function to give prob. # It looks if there is tackling or intergecting etc... # it's inputs would be current_s and next_s and the action taking place. prob_s, prob_f = self.transition_function(current_s, next_s, a) self.trans_probs[self.states_to_idx[current_s], a, self.states_to_idx[next_s]] = prob_opp*prob_s self.trans_probs[self.states_to_idx[current_s], a, self.states_to_idx['lost']] = prob_opp*prob_f else: self.trans_probs[self.states_to_idx[current_s], a, self.states_to_idx['lost']] = 1 # regardless of what R does if you take a non feasible action then lossing is 1 elif a ==9: # this has to be separate because state_after_action function gives 'goal' for this so u can't slice like before. new_state = current_s[:] for i, prob_opp in enumerate(self.opp_action_probs[current_s]): if prob_opp != 0: r_int = int(current_s[-3:-1]) r_str = str(self.player_pos(r_int, i)) # 'i' would give the action for R if len(r_str)==1: r_str = '0' + r_str # NOTE: I hope the prob's are zero when the R is at the edge next_s = new_state[:4] + r_str + new_state[-1] prob_s, prob_f = self.transition_function(current_s, next_s, a) self.trans_probs[self.states_to_idx[current_s], a, self.states_to_idx['goal']] = prob_opp*prob_s self.trans_probs[self.states_to_idx[current_s], a, self.states_to_idx['lost']] = prob_opp*prob_f self.rewards = np.zeros((self.S, self.A, self.S)) self.rewards[:,:,8192] = -1 self.rewards[:,:,8193] = 1 def save_transition_probabilities_and_rewards(self, filename): self.calculate_trans_probs() trans_probs = self.trans_probs rewards = self.rewards num_states, num_actions, _ = trans_probs.shape with open(filename, 'w') as file: file.write(f"numStates {num_states}\n") file.write(f"numActions {num_actions}\n") file.write("end 8192 8193\n") for s in range(num_states - 2): # Exclude terminal states 'lost' and 'goal' for a in range(num_actions): for s_prime in range(num_states): prob = trans_probs[s, a, s_prime] reward = rewards[s, a, s_prime] if prob != 0 or reward != 0: file.write(f"transition {s} {a} {s_prime} {prob} {reward}\n") file.write("mdptype episodic\n") file.write("discount 0.9\n") # Example usage: if __name__ == "__main__": parser.add_argument("--opponent",type=str,default='./data/football/test-1.txt') parser.add_argument("--p", type=float) parser.add_argument("--q", type=float) args = parser.parse_args() if not (args.p <=1.0 and args.p >=0.0): print("p is a probability, should be btw 0,1") sys.exit(0) if not (args.q<=1.0 and args.q >=0.0): print("q is a probability, should be btw 0,1") sys.exit(0) enco = PlannerEncoder(args.opponent, args.p, args.q) enco.save_transition_probabilities_and_rewards('t-2.txt')
kiluazen/ReinforcementLearning
Policy Iteration/encoder.py
encoder.py
py
10,197
python
en
code
0
github-code
6
37686992982
import socket import random server_address = ('127.0.0.1', 5001) server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) server_socket.bind(server_address) while True: data, client_address = server_socket.recvfrom(1024) if random.randint(0, 1): server_socket.sendto(data, client_address) print('data:', data, 'client address', client_address) print('sock name', server_socket.getsockname()) else: print('server is down')
studiawan/network-programming
bab07/server-udp2.py
server-udp2.py
py
549
python
en
code
10
github-code
6
25145650810
import pytest import datetime import pytz from mixer.backend.django import mixer from telegram_message_api.helpers import ( ParsedData, ParseText, CategoryData, ) @pytest.mark.parametrize( 'text', [ '150 test', '150 test 150', '150', ] ) def test_parsetext_dataclass(text): """Testing a ParseText parse text method""" result = ParseText(text)() if result: assert result.amount == '150' assert result.expense == 'test' else: assert result == None def test_categorydata_dataclass(db): """Testing a CategoryData""" category = mixer.blend('core.category') result = CategoryData( expense_text='150 test', category=category )() tz = pytz.timezone("Europe/Moscow") now = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S") assert result == { 'amount': '150', 'created': now, 'category': category, 'expense_text': '150 test', }
enamsaraev/telegram_bot_api
telegram_message_api/tests/test_helpers.py
test_helpers.py
py
1,071
python
en
code
0
github-code
6
30455799471
import pandas as pd import tensorflow as tf import argparse from . import data TRAIN_URL = data.TRAIN_URL TEST_URL = data.TEST_URL CSV_COLUMN_NAMES = data.CSV_COLUMN_NAMES LABELS = data.LABELS def maybe_download(): train_path = tf.keras.utils.get_file(TRAIN_URL.split('/')[-1], TRAIN_URL) test_path = tf.keras.utils.get_file(TEST_URL.split('/')[-1], TEST_URL) return train_path, test_path def load_data(y_name='Labels'): """Returns the dataset as (train_x, train_y), (test_x, test_y).""" train_path, test_path = maybe_download() train = pd.read_csv(train_path, names=CSV_COLUMN_NAMES, header=0) train_x, train_y = train, train.pop(y_name) test = pd.read_csv(test_path, names=CSV_COLUMN_NAMES, header=0) test_x, test_y = test, test.pop(y_name) return (train_x, train_y), (test_x, test_y) def train_input_fn(features, labels, batch_size): """An input function for training""" # Convert the inputs to a Dataset. dataset = tf.data.Dataset.from_tensor_slices((dict(features), labels)) # Shuffle, repeat, and batch the examples. dataset = dataset.shuffle(1000).repeat().batch(batch_size) # Return the dataset. return dataset def eval_input_fn(features, labels, batch_size): """An input function for evaluation""" features = dict(features) if labels is None: # No labels, use only features. inputs = features else: inputs = (features, labels) # Convert the inputs to a Dataset. dataset = tf.data.Dataset.from_tensor_slices(inputs) # Batch the examples assert batch_size is not None, "batch_size must not be None" dataset = dataset.batch(batch_size) # Return the dataset. return dataset parser = argparse.ArgumentParser() parser.add_argument('--batch_size', default=100, type=int, help='batch size') parser.add_argument('--train_steps', default=1000, type=int, help='number of training steps') globalClassifier = None globalArgs = None def main(argv): args = parser.parse_args(argv[1:]) # Fetch the data (train_x, train_y), (test_x, test_y) = load_data() # Feature columns describe how to use the input. my_feature_columns = [] for key in train_x.keys(): my_feature_columns.append(tf.feature_column.numeric_column(key=key)) # Build 2 hidden layer DNN with 10, 10 units respectively. classifier = tf.estimator.DNNClassifier( feature_columns=my_feature_columns, hidden_units=[10, 10], n_classes=25) # Train the Model. classifier.train(input_fn=lambda: train_input_fn( train_x, train_y, args.batch_size), steps=args.train_steps) # Evaluate the model. eval_result = classifier.evaluate( input_fn=lambda: eval_input_fn(test_x, test_y, args.batch_size)) # Set global variables global globalClassifier global globalArgs globalClassifier = classifier globalArgs = args print('\nTest set accuracy: {accuracy:0.3f}\n'.format(**eval_result)) def getModelData(): return globalClassifier, globalArgs
RajithaKumara/Best-Fit-Job-ML
classifier/estimator/model.py
model.py
py
3,077
python
en
code
1
github-code
6
858848514
from __future__ import division from HTMLParser import HTMLParser import os import re from .https_if_available import build_opener re_url = re.compile(r'^(([a-zA-Z_-]+)://([^/]+))(/.*)?$') def resolve_link(link, url): m = re_url.match(link) if m is not None: if not m.group(4): # http://domain -> http://domain/ return link + '/' else: return link elif link[0] == '/': # /some/path murl = re_url.match(url) return murl.group(1) + link else: # relative/path if url[-1] == '/': return url + link else: return url + '/' + link class ListingParser(HTMLParser): """Parses an HTML file and build a list of links. Links are stored into the 'links' set. They are resolved into absolute links. """ def __init__(self, url): HTMLParser.__init__(self) if url[-1] != '/': url += '/' self.__url = url self.links = set() def handle_starttag(self, tag, attrs): if tag == 'a': for key, value in attrs: if key == 'href': if not value: continue value = resolve_link(value, self.__url) self.links.add(value) break def download_directory(url, target, insecure=False): def mkdir(): if not mkdir.done: try: os.mkdir(target) except OSError: pass mkdir.done = True mkdir.done = False opener = build_opener(insecure=insecure) response = opener.open(url) if response.info().type == 'text/html': contents = response.read() parser = ListingParser(url) parser.feed(contents) for link in parser.links: link = resolve_link(link, url) if link[-1] == '/': link = link[:-1] if not link.startswith(url): continue name = link.rsplit('/', 1)[1] if '?' in name: continue mkdir() download_directory(link, os.path.join(target, name), insecure) if not mkdir.done: # We didn't find anything to write inside this directory # Maybe it's a HTML file? if url[-1] != '/': end = target[-5:].lower() if not (end.endswith('.htm') or end.endswith('.html')): target = target + '.html' with open(target, 'wb') as fp: fp.write(contents) else: buffer_size = 4096 with open(target, 'wb') as fp: chunk = response.read(buffer_size) while chunk: fp.write(chunk) chunk = response.read(buffer_size) ############################################################################### import unittest class TestLinkResolution(unittest.TestCase): def test_absolute_link(self): self.assertEqual( resolve_link('http://website.org/p/test.txt', 'http://some/other/url'), 'http://website.org/p/test.txt') self.assertEqual( resolve_link('http://website.org', 'http://some/other/url'), 'http://website.org/') def test_absolute_path(self): self.assertEqual( resolve_link('/p/test.txt', 'http://some/url'), 'http://some/p/test.txt') self.assertEqual( resolve_link('/p/test.txt', 'http://some/url/'), 'http://some/p/test.txt') self.assertEqual( resolve_link('/p/test.txt', 'http://site'), 'http://site/p/test.txt') self.assertEqual( resolve_link('/p/test.txt', 'http://site/'), 'http://site/p/test.txt') def test_relative_path(self): self.assertEqual( resolve_link('some/file', 'http://site/folder'), 'http://site/folder/some/file') self.assertEqual( resolve_link('some/file', 'http://site/folder/'), 'http://site/folder/some/file') self.assertEqual( resolve_link('some/dir/', 'http://site/folder'), 'http://site/folder/some/dir/') class TestParser(unittest.TestCase): def test_parse(self): parser = ListingParser('http://a.remram.fr/test') parser.feed(""" <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"><html><head><title> Index of /test</title></head><body><h1>Index of /test</h1><table><tr><th> <img src="/icons/blank.gif" alt="[ICO]"></th><th><a href="?C=N;O=D">Name</a> </th><th><a href="?C=M;O=A">Last modified</a></th><th><a href="?C=S;O=A">Size </a></th><th><a href="?C=D;O=A">Description</a></th></tr><tr><th colspan="5"> <hr></th></tr><tr><td valign="top"><img src="/icons/back.gif" alt="[DIR]"></td> <td><a href="/">Parent Directory</a></td><td>&nbsp;</td><td align="right"> - </td><td>&nbsp;</td></tr><tr><td valign="top"> <img src="/icons/unknown.gif" alt="[ ]"></td><td><a href="a">a</a></td> <td align="right">11-Sep-2013 15:46 </td><td align="right"> 3 </td><td>&nbsp; </td></tr><tr><td valign="top"><img src="/icons/unknown.gif" alt="[ ]"></td> <td><a href="/bb">bb</a></td><td align="right">11-Sep-2013 15:46 </td> <td align="right"> 3 </td><td>&nbsp;</td></tr><tr><td valign="top"> <img src="/icons/folder.gif" alt="[DIR]"></td><td><a href="/cc/">cc/</a></td> <td align="right">11-Sep-2013 15:46 </td><td align="right"> - </td><td>&nbsp; </td></tr><tr><td valign="top"><img src="/icons/folder.gif" alt="[DIR]"></td> <td><a href="http://a.remram.fr/dd">dd/</a></td><td align="right"> 11-Sep-2013 15:46 </td><td align="right"> - </td><td>&nbsp;</td></tr><tr> <th colspan="5"><hr></th></tr></table></body></html> """) links = set(l for l in parser.links if '?' not in l) self.assertEqual(links, set([ 'http://a.remram.fr/', 'http://a.remram.fr/test/a', 'http://a.remram.fr/bb', 'http://a.remram.fr/cc/', 'http://a.remram.fr/dd', ]))
VisTrails/VisTrails
vistrails/packages/URL/http_directory.py
http_directory.py
py
6,294
python
en
code
100
github-code
6
5432720139
from sklearn.metrics import pairwise_distances import numpy as np import pandas as pd from scipy.sparse import spmatrix from anndata import AnnData from scipy.stats import rankdata from typing import Optional from . import logger from .symbols import NOVEL, REMAIN, UNASSIGN class Distance(): """ Class that deals with the cross-dataset cell-by-cell-type distance matrix. Parameters ---------- dist_mat Cell-by-cell-type distance matrix. cell Cell meta-information including at least `'dataset'`, `'ID'` and `'cell_type'`. cell_type Cell type meta-information including at least `'dataset'` and `'cell_type'`. Attributes ---------- dist_mat A cell-by-cell-type distance matrix. cell Cell meta-information including `'dataset'`, `'ID'` and `'cell_type'`. cell_type Cell type meta-information including `'dataset'` and `'cell_type'`. n_cell Number of cells involved. n_cell_type Number of cell types involved. shape Tuple of number of cells and cell types. assignment Assignment of each cell to the most similar cell type in each dataset (obtained through the `assign` method). """ def __init__(self, dist_mat: np.ndarray, cell: pd.DataFrame, cell_type: pd.DataFrame): self.dist_mat = dist_mat if cell.shape[0] != self.dist_mat.shape[0]: raise ValueError( f"🛑 Number of cells in `cell` does not match the cell number in `dist_mat`") if cell_type.shape[0] != self.dist_mat.shape[1]: raise ValueError( f"🛑 Number of cell types in `cell_type` does not match the cell type number in `dist_mat`") if not {'dataset', 'ID', 'cell_type'}.issubset(set(cell.columns)): raise KeyError( f"🛑 Please include `'dataset'`, `'ID'` and `'cell_type'` as the cell meta-information") if not {'dataset', 'cell_type'}.issubset(set(cell_type.columns)): raise KeyError( f"🛑 Please include `'dataset'` and `'cell_type'` as the cell type meta-information") self.cell = cell self.cell_type = cell_type @property def n_cell(self) -> int: """Number of cells.""" return self.dist_mat.shape[0] @property def n_cell_type(self) -> int: """Number of cell types.""" return self.dist_mat.shape[1] @property def shape(self) -> tuple: """Numbers of cells and cell types.""" return self.dist_mat.shape def __repr__(self): lend = len(np.unique(self.cell_type.dataset)) if lend > 1: base = f"Cross-dataset distance matrix between {self.n_cell} cells and {self.n_cell_type} cell types from {lend} datasets" else: base = f"Distance matrix between {self.n_cell} cells and {self.n_cell_type} cell types" base += f"\n dist_mat: distance matrix between {self.n_cell} cells and {self.n_cell_type} cell types" base += f"\n cell: cell meta-information ({str(list(self.cell.columns))[1:-1]})" base += f"\n cell_type: cell type meta-information ({str(list(self.cell_type.columns))[1:-1]})" if hasattr(self, 'assignment'): base += f"\n assignment: data frame of cross-dataset cell type assignment" return base @staticmethod def from_adata(adata: AnnData, dataset: str, cell_type: str, use_rep: Optional[str] = None, metric: Optional[str] = None, n_jobs: Optional[int] = None, check_params: bool = True, **kwargs): """ Generate a :class:`~cellhint.distance.Distance` object from the :class:`~anndata.AnnData` given. Parameters ---------- adata An :class:`~anndata.AnnData` object containing different datasets/batches and cell types. In most scenarios, the format of the expression `.X` in the AnnData is flexible (normalized, log-normalized, z-scaled, etc.). However, when `use_rep` is specified as `'X'` (or `X_pca` is not detected in `.obsm` and no other latent representations are provided), `.X` should be log-normalized (to a constant total count per cell). dataset Column name (key) of cell metadata specifying dataset information. cell_type Column name (key) of cell metadata specifying cell type information. use_rep Representation used to calculate distances. This can be `'X'` or any representations stored in `.obsm`. Default to the PCA coordinates if present (if not, use the expression matrix `X`). metric Metric to calculate the distance between each cell and each cell type. Can be `'euclidean'`, `'cosine'`, `'manhattan'` or any metrics applicable to :func:`sklearn.metrics.pairwise_distances`. Default to `'euclidean'` if latent representations are used for calculating distances, and to `'correlation'` if the expression matrix is used. n_jobs Number of CPUs used. Default to one CPU. `-1` means all CPUs are used. check_params Whether to check (or set the default) for `dataset`, `cell_type`, `use_rep` and `metric`. (Default: `True`) **kwargs Other keyword arguments passed to :func:`sklearn.metrics.pairwise_distances`. Returns ---------- :class:`~cellhint.distance.Distance` A :class:`~cellhint.distance.Distance` object representing the cross-dataset cell-by-cell-type distance matrix. """ #Use `check_params = False` if `dataset`, `cell_type`, `use_rep` and `metric` are already provided correctly. if check_params: if dataset not in adata.obs: raise KeyError( f"🛑 '{dataset}' is not found in the provided AnnData") if cell_type not in adata.obs: raise KeyError( f"🛑 '{cell_type}' is not found in the provided AnnData") if use_rep is None: if 'X_pca' in adata.obsm.keys(): logger.info(f"👀 Detected PCA coordinates in the object, will use these to calculate distances") use_rep = 'X_pca' else: logger.info(f"🧙 Using the expression matrix to calculate distances") use_rep = 'X' elif (use_rep not in adata.obsm.keys()) and (use_rep != 'X'): raise KeyError( f"🛑 '{use_rep}' is not found in `.obsm`") if use_rep == 'X' and adata.n_vars > 15000: logger.warn(f"⚠️ Warning: {adata.n_vars} features are used for calculating distances. Subsetting the AnnData into HVGs is recommended") if metric is None: metric = 'correlation' if use_rep == 'X' else 'euclidean' Cell_X = adata.X if use_rep == 'X' else adata.obsm[use_rep] IDs = adata.obs_names datasets = adata.obs[dataset].astype(str).values celltypes = adata.obs[cell_type].astype(str).values use_Cell_X = Cell_X if use_rep != 'X' else np.expm1(Cell_X) Celltype_X = [] col_ds = [] col_cs =[] for d in np.unique(datasets): for c in np.unique(celltypes[datasets == d]): col_cs.append(c) col_ds.append(d) m = use_Cell_X[(datasets == d) & (celltypes == c), :].mean(axis = 0) Celltype_X.append(m.A1 if isinstance(m, np.matrix) else m) Celltype_X = np.log1p(np.array(Celltype_X)) if use_rep == 'X' else np.array(Celltype_X) if metric not in ['cityblock', 'cosine', 'euclidean', 'l1', 'l2', 'manhattan']: if isinstance(Cell_X, spmatrix): Cell_X = Cell_X.toarray() if isinstance(Celltype_X, spmatrix): Celltype_X = Celltype_X.toarray() dist_mat = pairwise_distances(Cell_X, Celltype_X, metric = metric, n_jobs = n_jobs, **kwargs) cell = pd.DataFrame(dict(dataset=datasets, ID=IDs, cell_type=celltypes)) cell_type = pd.DataFrame(dict(dataset=col_ds, cell_type=col_cs)) return Distance(dist_mat, cell, cell_type) def normalize(self, Gaussian_kernel: bool = False, rank: bool = True, normalize: bool = True) -> None: """ Normalize the distance matrix with a Gaussian kernel. Parameters ---------- Gaussian_kernel Whether to apply the Gaussian kernel to the distance matrix. (Default: `False`) rank Whether to turn the matrix into a rank matrx. (Default: `True`) normalize Whether to maximum-normalize the distance matrix. (Default: `True`) Returns ---------- None The :class:`~cellhint.distance.Distance` object modified with a normalized distance matrix. """ if Gaussian_kernel: sds = np.sqrt((self.dist_mat ** 2).sum(axis = 1) / self.n_cell_type)[:, np.newaxis] self.dist_mat = np.exp(- self.dist_mat / (2 / sds)**2) self.dist_mat = 1 - self.dist_mat / self.dist_mat.sum(axis = 1)[:, np.newaxis] if rank: self.dist_mat = rankdata(self.dist_mat).reshape(self.dist_mat.shape) if normalize: self.dist_mat = self.dist_mat / self.dist_mat.max() def concatenate(self, *distances, by: str = 'cell', check: bool = False): """ Concatenate by either cells (rows) or cell types (columns). Parameters ---------- distances A :class:`~cellhint.distance.Distance` object or a list of such objects. by The direction of concatenation, joining either cells (`'cell'`, rows) or cell types (`'cell_type'`, columns). (Default: `'cell'`) check Check whether the concatenation is feasible. (Default: `False`) Returns ---------- :class:`~cellhint.distance.Distance` A :class:`~cellhint.distance.Distance` object concatenated along cells (`by = 'cell'`) or cell types (`by = 'cell_type'`). """ distances = distances[0] if isinstance(distances[0], (list, tuple, set)) else distances distances = tuple(distances) all_distances = (self,) + distances if by not in ['cell', 'cell_type']: raise ValueError( f"🛑 Unrecognized `by` value, should be one of `'cell'` or `'cell_type'`") if check: series_compare = [(x.cell_type.dataset+x.cell_type.cell_type).sort_values() for x in all_distances] if by == 'cell' else [(x.cell.dataset+x.cell.ID).sort_values() for x in all_distances] if pd.concat(series_compare, axis = 1).T.drop_duplicates().shape[0] > 1: raise Exception( f"🛑 Concatenation is not feasible. Please ensure the meta-information is matched") if by == 'cell': dist_mat = np.concatenate([x.dist_mat for x in all_distances], axis = 0) cell = pd.concat([x.cell for x in all_distances], axis = 0, ignore_index = True) return Distance(dist_mat, cell, self.cell_type) else: match_base = (self.cell.dataset+self.cell.ID).reset_index().set_index(0) indices = [np.argsort(match_base.loc[x.cell.dataset+x.cell.ID, 'index'].values) for x in distances] dist_mat = np.concatenate([self.dist_mat] + [x.dist_mat[y, :] for x,y in zip(distances, indices)], axis = 1) cell_type = pd.concat([x.cell_type for x in all_distances], axis = 0, ignore_index = True) return Distance(dist_mat, self.cell, cell_type) def symmetric(self) -> bool: """ Check whether the distance matrix is symmetric in terms of datasets and cell types. Returns ---------- bool `True` or `False` indicating whether all datasets and cell types are included in the object (thus symmetric). """ return np.array_equal(np.unique(self.cell.dataset + self.cell.cell_type), np.unique(self.cell_type.dataset + self.cell_type.cell_type)) def filter_cells(self, check_symmetry: bool = True) -> None: """ Filter out cells whose gene expression profiles do not correlate most with the eigen cell they belong to (i.e., correlate most with other cell types). Parameters ---------- check_symmetry Whether to check the symmetry of the distance matrix in terms of datasets and cell types. (Default: `True`) Returns ---------- None A :class:`~cellhint.distance.Distance` object with undesirable cells filtered out. """ if check_symmetry and not self.symmetric(): raise ValueError( f"🛑 Cell filtering is not possible. Please provide the matrix with symmetric datasets and cell types") bool_cell = np.ones(self.n_cell, dtype=bool) for i, s in self.cell.iterrows(): flag_dataset = self.cell_type.dataset == s['dataset'] if self.cell_type.cell_type.values[flag_dataset][self.dist_mat[i][flag_dataset].argmin()] != s['cell_type']: bool_cell[i] = False if (~bool_cell).sum() == 0: logger.info(f"✂️ No cells are filtered out") else: ds_unique, ds_table = np.unique(self.cell.dataset.values[~bool_cell], return_counts = True) if len(ds_unique) == 1: logger.info(f"✂️ {(~bool_cell).sum()} cells are filtered out from {ds_unique[0]}") else: logger.info(f"✂️ {(~bool_cell).sum()} cells are filtered out, including:") for m, n in zip(ds_unique, ds_table): logger.info(f" {n} cells from {m}") self.dist_mat = self.dist_mat[bool_cell] self.cell = self.cell[bool_cell] all_combine = (self.cell_type.dataset + ': ' + self.cell_type.cell_type).values left_combine = np.unique(self.cell.dataset + ': ' + self.cell.cell_type) if len(left_combine) < len(all_combine): column_keep = np.isin(all_combine, left_combine) self.dist_mat = self.dist_mat[:, column_keep] self.cell_type = self.cell_type[column_keep] logger.info(f"✂️ The following cell types are discarded due to low confidence in annotation:") for rec in all_combine[~column_keep]: logger.info(f" {rec}") def to_meta(self, check_symmetry: bool = True, turn_binary: bool = False, return_symmetry: bool = True) -> pd.DataFrame: """ Meta-analysis of cross-dataset cell type dissimilarity or membership. Parameters ---------- check_symmetry Whether to check the symmetry of the distance matrix in terms of datasets and cell types. (Default: `True`) turn_binary Whether to turn the distance matrix into a cell type membership matrix before meta analysis. (Default: `False`) return_symmetry Whether to return a symmetric dissimilarity matrix by averaging with its transposed form. (Default: `True`) Returns ---------- :class:`~pandas.DataFrame` A :class:`~pandas.DataFrame` object representing the cell-type-level dissimilarity matrix (`turn_binary = False`) or membership matrix (`turn_binary = True`). """ if check_symmetry and not self.symmetric(): raise ValueError( f"🛑 Meta cell analysis is not possible. Concatenate all datasets and cell types beforehand using `concatenate`") use_mat = self.to_binary(False if check_symmetry else True).dist_mat if turn_binary else self.dist_mat meta_cell = [] for _, s in self.cell_type.iterrows(): meta_cell.append(use_mat[(self.cell.dataset == s['dataset']) & (self.cell.cell_type == s['cell_type']), :].mean(axis = 0)) meta_cell = pd.DataFrame(np.array(meta_cell)) meta_cell.index = (self.cell_type.dataset + ': ' + self.cell_type.cell_type).values meta_cell.columns = meta_cell.index return (meta_cell + meta_cell.T)/2 if return_symmetry else meta_cell def to_binary(self, check_symmetry: bool = True): """ Turn the distance matrix into a binary matrix representing the estimated cell type membership across datasets. Parameters ---------- check_symmetry Whether to check the symmetry of the distance matrix in terms of datasets and cell types. (Default: `True`) Returns ---------- :class:`~cellhint.distance.Distance` A :class:`~cellhint.distance.Distance` object representing the estimated cell type membership across datasets. """ if check_symmetry and not self.symmetric(): raise ValueError( f"🛑 Cannot convert to a binary matrix. Please provide the matrix with symmetric datasets and cell types") member_mat = np.zeros(self.shape, dtype = int) datasets = self.cell_type.dataset.values for dataset in np.unique(datasets): indices = np.where(datasets == dataset)[0] member_mat[range(member_mat.shape[0]), indices[self.dist_mat[:, indices].argmin(axis = 1)]] = 1 return Distance(member_mat, self.cell, self.cell_type) def assign(self) -> None: """ Assign each cell to its most similar cell type in each dataset. Returns ---------- None Modified object with the result of cell assignment added as `.assignment`. """ assignment = {} for dataset in np.unique(self.cell_type.dataset): flag = self.cell_type.dataset == dataset assignment[dataset] = self.cell_type.cell_type.values[flag][self.dist_mat[:, flag].argmin(axis = 1)] assignment = pd.DataFrame(assignment, index = self.cell.index) #no need to assign cells for the dataset they belong to for dataset in assignment.columns: flag = self.cell.dataset == dataset assignment.loc[flag, dataset] = self.cell.cell_type.values[flag] self.assignment = assignment def to_confusion(self, D1: str, D2: str, check: bool = True) -> tuple: """ This function is deprecated. Use `to_pairwise_confusion` and `to_multi_confusion` instead. Extract the dataset1-by-dataset2 and dataset2-by-dataset1 confusion matrices. Note this function is expected to be applied to a binary membership matrix. Parameters ---------- D1 Name of the first dataset. D2 Name of the second dataset. check Whether to check names of the two datasets are contained. (Default: `True`) Returns ---------- tuple The dataset1-by-dataset2 and dataset2-by-dataset1 confusion matrices. """ if check and not {D1, D2}.issubset(np.unique(self.cell_type.dataset)): raise ValueError( f"🛑 Please provide correct dataset names") D1_col_flag = self.cell_type.dataset == D1 D2_col_flag = self.cell_type.dataset == D2 D1_celltypes = self.cell_type.cell_type.values[D1_col_flag] D2_celltypes = self.cell_type.cell_type.values[D2_col_flag] D1_row_flag = self.cell.dataset == D1 D2_row_flag = self.cell.dataset == D2 D1byD2 = pd.DataFrame(np.array([self.dist_mat[D1_row_flag & (self.cell.cell_type == x)][:, D2_col_flag].sum(axis=0) for x in D1_celltypes]), columns = D2_celltypes, index = D1_celltypes) D2byD1 = pd.DataFrame(np.array([self.dist_mat[D2_row_flag & (self.cell.cell_type == x)][:, D1_col_flag].sum(axis=0) for x in D2_celltypes]), columns = D1_celltypes, index = D2_celltypes) return D1byD2, D2byD1 def to_pairwise_confusion(self, D1: str, D2: str, check: bool = True) -> tuple: """ Extract the dataset1-by-dataset2 and dataset2-by-dataset1 confusion matrices. Parameters ---------- D1 Name of the first dataset. D2 Name of the second dataset. check Whether to check names of the two datasets are contained. (Default: `True`) Returns ---------- tuple The dataset1-by-dataset2 and dataset2-by-dataset1 confusion matrices. """ if check and not {D1, D2}.issubset(np.unique(self.cell_type.dataset)): raise ValueError( f"🛑 Please provide correct dataset names") if not hasattr(self, 'assignment'): raise AttributeError( f"🛑 No `.assignment` attribute in the object. Use the `.assign` method first") D1_flag = (self.cell.dataset == D1) D2_flag = (self.cell.dataset == D2) D1byD2 = pd.crosstab(self.cell.cell_type[D1_flag], self.assignment.loc[D1_flag, D2]) D2byD1 = pd.crosstab(self.cell.cell_type[D2_flag], self.assignment.loc[D2_flag, D1]) D1byD2_lack_columns = D2byD1.index.difference(D1byD2.columns) if len(D1byD2_lack_columns) > 0: D1byD2 = D1byD2.join(pd.DataFrame(np.zeros((len(D1byD2.index), len(D1byD2_lack_columns)), dtype=int), index = D1byD2.index, columns = D1byD2_lack_columns)) D2byD1_lack_columns = D1byD2.index.difference(D2byD1.columns) if len(D2byD1_lack_columns) > 0: D2byD1 = D2byD1.join(pd.DataFrame(np.zeros((len(D2byD1.index), len(D2byD1_lack_columns)), dtype=int), index = D2byD1.index, columns = D2byD1_lack_columns)) return D1byD2, D2byD1.loc[D1byD2.columns, D1byD2.index] def to_multi_confusion(self, relation: pd.DataFrame, D: str, check: bool = True) -> tuple: """ Extract the confusion matrices between meta-cell-types defined prior and cell types from a new dataset. Parameters ---------- relation A :class:`~pandas.DataFrame` object representing the cell type harmonization result across multiple datasets. D Name of the new dataset to be aligned. check Whether to check names of the datasets are contained. (Default: `True`) Returns ---------- tuple The confusion matrices between meta-cell-types defined prior and cell types from a new dataset. """ datasets = relation.columns[0::2] if check: if not set(datasets).issubset(np.unique(self.cell_type.dataset)): raise ValueError( f"🛑 `relation` contains unexpected dataset names") if D not in np.unique(self.cell_type.dataset) or D in datasets: raise ValueError( f"🛑 Please provide a valid dataset name `D`") if not hasattr(self, 'assignment'): raise AttributeError( f"🛑 No `.assignment` attribute in the object. Use the `.assign` method first") #D1byD2 D1_flag = self.cell.dataset.isin(datasets) D1_assign = self.assignment[D1_flag] D1_truth = np.full(D1_assign.shape[0], UNASSIGN, dtype = object) for _, s in relation.iterrows(): celltypes = s.values[0::2] non_blank_flag = ~np.isin(celltypes, [NOVEL, REMAIN]) existing_datasets = datasets[non_blank_flag] existing_celltypes = celltypes[non_blank_flag] flag = np.all(D1_assign[existing_datasets] == existing_celltypes, axis = 1).values & self.cell[D1_flag].dataset.isin(existing_datasets).values D1_truth[flag] = ' '.join(s.values) D1_used = D1_truth != UNASSIGN D1byD2 = pd.crosstab(D1_truth[D1_used], D1_assign.loc[D1_used, D]) #D2byD1 D2_flag = self.cell.dataset == D D2_assign = self.assignment[D2_flag] D2_predict = np.full(D2_assign.shape[0], UNASSIGN, dtype = object) for _, s in relation.iterrows(): celltypes = s.values[0::2] flags = (D2_assign[datasets] == celltypes) | np.isin(celltypes, [NOVEL, REMAIN]) D2_predict[np.all(flags, axis = 1).values] = ' '.join(s.values) D2_used = D2_predict != UNASSIGN D2byD1 = pd.crosstab(self.cell.cell_type[D2_flag][D2_used], D2_predict[D2_used]) #warning if relation.shape[0] > D1byD2.shape[0]: lost_celltypes = np.setdiff1d(relation.apply(lambda row: ' '.join(row.values), axis = 1).values, D1byD2.index) logger.warn(f"⚠️ Warning: no cells are found to match these patterns: {set(lost_celltypes)}. Double check the harmonized relationships before integrating '{D}'") D1byD2 = pd.concat([D1byD2, pd.DataFrame(np.zeros((len(lost_celltypes), len(D1byD2.columns)), dtype=int), index = lost_celltypes, columns = D1byD2.columns)], axis = 0) #a unique cell type in D2 may be annotated to nothing and filtered lost_celltypes = np.setdiff1d(np.unique(self.cell.cell_type[D2_flag]), D2byD1.index) if len(lost_celltypes) > 0: D2byD1 = pd.concat([D2byD1, pd.DataFrame(np.zeros((len(lost_celltypes), len(D2byD1.columns)), dtype=int), index = lost_celltypes, columns = D2byD1.columns)], axis = 0) #return D1byD2_lack_columns = D2byD1.index.difference(D1byD2.columns) if len(D1byD2_lack_columns) > 0: D1byD2 = D1byD2.join(pd.DataFrame(np.zeros((len(D1byD2.index), len(D1byD2_lack_columns)), dtype=int), index = D1byD2.index, columns = D1byD2_lack_columns)) D2byD1_lack_columns = D1byD2.index.difference(D2byD1.columns) if len(D2byD1_lack_columns) > 0: D2byD1 = D2byD1.join(pd.DataFrame(np.zeros((len(D2byD1.index), len(D2byD1_lack_columns)), dtype=int), index = D2byD1.index, columns = D2byD1_lack_columns)) return D1byD2, D2byD1.loc[D1byD2.columns, D1byD2.index]
Teichlab/cellhint
cellhint/distance.py
distance.py
py
26,272
python
en
code
4
github-code
6
709779467
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import string import pandas as pd from gensim.models import KeyedVectors import time from sklearn.feature_extraction.stop_words import ENGLISH_STOP_WORDS #x=find_department('Mortage requirements specified are incorrect', False) def find_department(single_query,only_department): #Load model---------------------------------------------------------------------- st = time.time() wordmodelfile = '~/Documents/STUDY/Hackathon/NLP/GoogleNews-vectors-negative300.bin' wordmodel = KeyedVectors.load_word2vec_format(wordmodelfile, binary = True, limit=200000) et = time.time() s = 'Word embedding loaded in %f secs.' % (et-st) print(s) #Preprocessing---------------------------------------------------------------------- single_query_cleaned = clean_set([single_query])[0] if(len(single_query_cleaned)==0): return False data = pd.read_csv("~/Documents/STUDY/Hackathon/NLP/dataset/resolved.csv") if(only_department == False): queries = data['query'] _list = queries.values.tolist() #Cleaned data newDataset = clean_set(_list) x=return_key(3,single_query_cleaned,newDataset,wordmodel) if(x!=0): x=_list[newDataset.index(x)] return fetch_query_details(x,0,'resolved') #print('here 2') #departments = pd.unique(data['Product']) Sample departments keys = ['security', 'loans', 'accounts', 'insurance', 'investments', 'fundstransfer', 'cards'] #For each element in newDataset (Query) we find the most similar key (Department) mode=0 department=return_key(5,single_query_cleaned,keys,wordmodel) #Returning depart q_id = log_query(max(data['query_id'])+1,single_query,department) return department,q_id def change_department(q_id, new_department): data = pd.read_csv("~/Documents/STUDY/Hackathon/NLP/dataset/unresolved.csv") i=data[data['query_id']==q_id].index.values[0] #print(i) data.set_value(i,"department", new_department) data.to_csv('~/Documents/STUDY/Hackathon/NLP/dataset/unresolved.csv', encoding='utf-8', index=False) def clean_set(_list): newDataset=[] for response in _list: #Lower, remove punctuations and strip white-spaces and split by spaces response_words=response.lower().translate(str.maketrans('', '', string.punctuation)).strip().split() response='' for word in response_words: if word not in ENGLISH_STOP_WORDS: response+=word+' ' newDataset.append(response[:-1]) return newDataset #resolve_query(62,521,'What to do eh?') def resolve_query(query_id,employee_id,solution): from datetime import date today = date.today().strftime("%d/%m/%Y") d = fetch_query_details('',query_id,'unresolved') query_date = d[0][3] d[0][3] = solution d[0] = d[0] + [query_date,today,employee_id] unresolved_data = pd.read_csv("~/Documents/STUDY/Hackathon/NLP/dataset/unresolved.csv") unresolved_data = unresolved_data[unresolved_data.query_id != query_id] unresolved_data.to_csv('~/Documents/STUDY/Hackathon/NLP/dataset/unresolved.csv', encoding='utf-8', index=False) new_data = pd.DataFrame(d, columns = ['query_id','query','department','solution','query_date','date_solved','employee_id']) data = pd.read_csv("~/Documents/STUDY/Hackathon/NLP/dataset/resolved.csv") data = pd.concat([data, new_data]) data.to_csv('~/Documents/STUDY/Hackathon/NLP/dataset/resolved.csv', encoding='utf-8', index=False) #new_data = pd.DataFrame([d], columns = ['query_id','query','department','query_date']) def log_query(query_id, query, department): from datetime import date today = date.today().strftime("%d/%m/%Y") d=[query_id,query,department,today] new_data = pd.DataFrame([d], columns = ['query_id','query','department','query_date']) try: data = pd.read_csv("~/Documents/STUDY/Hackathon/NLP/dataset/unresolved.csv") if(len(data)>0): test = True else: test = False except: test = False if(test): new_data.at[0, 'query_id'] = max(max(data['query_id'])+1,query_id) data = pd.concat([data, new_data]) else: data = new_data data.to_csv('~/Documents/STUDY/Hackathon/NLP/dataset/unresolved.csv', encoding='utf-8', index=False) return data.loc[data['query'] == query].values.tolist()[0] #---------------------------------------------------------------------- def fetch_query_details(text,query_id,file_name): data = pd.read_csv("~/Documents/STUDY/Hackathon/NLP/dataset/"+file_name+".csv") if(text == 'all'): return data.values.tolist() elif(query_id==0): return data.loc[data['query'] == text].values.tolist() else: return data.loc[data['query_id'] == query_id].values.tolist() def return_key(threshold,sentence_a,keys,wordmodel): sentence_a = sentence_a.lower().split() distance_list = [] for key in keys: sentence_b = key.lower().split() distance_list.append(wordmodel.wmdistance(sentence_a, sentence_b)) #print(min(distance_list)) if(min(distance_list)>threshold): return 0 return(keys[distance_list.index(min(distance_list))]) ''' data = pd.read_csv("~/Documents/STUDY/Hackathon/NLP/Consumer_Complaints.csv",nrows=500) #218 queries xtrain = data.loc[data['Consumer complaint narrative'].notnull(), ['Consumer complaint narrative','Product','Company public response']] xtrain = xtrain.loc[xtrain['Company public response'].notnull(), ['Consumer complaint narrative','Product','Company public response']] xtrain.to_csv('./dataset/resolved.csv', encoding='utf-8', index=False) ''' #print(find_department('credit repair services')) #SAVING----------------------------------------------------------------------
ankitd3/Assist-ANS
NLP/distance.py
distance.py
py
6,026
python
en
code
1
github-code
6
74059033149
#coding:utf-8 class Fiab(object): def __init__(self, num): self.num = num self.a = 0 self.b = 1 self.n = 0 def __iter__(self): return self def __next__(self): self.a, self.b = self.b, self.a + self.b self.n += 1 if self.n > self.num: raise StopIteration return self.a if __name__ == "__main__": f = Fiab(int(input("Please input a num:"))) for i in f: print(i, end=" ") print()
HarveyWang81/PythonScript
Study-01/fibs/by_iter.py
by_iter.py
py
497
python
en
code
0
github-code
6
18718175573
from django.shortcuts import render, HttpResponse, redirect from .models import Note from django.urls import reverse # Create your views here. def index(request): context = { "notes": Note.objects.all(), } return render(request, 'notes/index.html', context) def create(request): if request.method == 'POST': title = request.POST['title'] description = request.POST['description'] Note.objects.create(title=title, description=description) context = { 'notes': Note.objects.all(), } return render(request, 'notes/notes_index.html', context) def destroy(request, note_id): if request.method == 'POST': Note.objects.get(id=int(note_id)).delete() context = { 'notes': Note.objects.all() } return render(request, 'notes/notes_index.html', context)
mtjhartley/codingdojo
dojoassignments/python/django/full_stack_django/ajax_notes/apps/notes/views.py
views.py
py
846
python
en
code
1
github-code
6
42924345016
import sys import os import time import re import csv import cv2 import tensorflow as tf import numpy as np #import pandas as pd from PIL import Image from matplotlib import pyplot as plt from object_detection.utils import label_map_util from object_detection.utils import visualization_utils as vis_util # if len(sys.argv) < 0: # print('Usage: python {} test_image_path checkpoint_path'.format(sys.argv[0])) # exit() def name_path_files(file_dir): # 文件名及文件路径列表 path_files = [] name_files = [] for roots, dirs, files in os.walk(file_dir): for f in files: tmp = os.path.join(roots, f) if ('.jpg' in tmp): path_files.append(tmp) name_files.append(f) try: # user enters in the filename of the csv file to convert # in_filename = argv[1:] print("files received list :" + str(path_files)) except (IndexError, IOError) as e: print("invalid file detected...") exit(1) # print(path_filename) # print(only_filename) path_files_name = np.ravel(path_files) only_file_name = np.ravel(name_files) # print(path_files) # print('#####' * 10) # print(name_files) return path_files, name_files PATH_TO_CKPT = sys.argv[1] PATH_TO_LABELS = 'annotations/label_map.pbtxt' NUM_CLASSES = 4 IMAGE_SIZE = (48, 32) label_map = label_map_util.load_labelmap(PATH_TO_LABELS) categories = label_map_util.convert_label_map_to_categories( label_map, max_num_classes=NUM_CLASSES, use_display_name=True) category_index = label_map_util.create_category_index(categories) detection_graph = tf.Graph() with detection_graph.as_default(): od_graph_def = tf.GraphDef() with tf.gfile.GFile(PATH_TO_CKPT, 'rb') as fid: serialized_graph = fid.read() od_graph_def.ParseFromString(serialized_graph) tf.import_graph_def(od_graph_def, name='') config = tf.ConfigProto() config.gpu_options.allow_growth = True with detection_graph.as_default(): with tf.Session(graph=detection_graph, config=config) as sess: path_files, name_files = name_path_files('./images/verification/') writer_lists = [] for path_f in path_files: start_time = time.time() print(time.ctime()) image = Image.open(path_f) image_np = np.array(image).astype(np.uint8) image_np_expanded = np.expand_dims(image_np, axis=0) image_tensor = detection_graph.get_tensor_by_name('image_tensor:0') boxes = detection_graph.get_tensor_by_name('detection_boxes:0') scores = detection_graph.get_tensor_by_name('detection_scores:0') classes = detection_graph.get_tensor_by_name('detection_classes:0') num_detections = detection_graph.get_tensor_by_name('num_detections:0') (boxes, scores, classes, num_detections) = sess.run( [boxes, scores, classes, num_detections], feed_dict={image_tensor: image_np_expanded}) # print(classes) # print(num_detections) eval_dicts = {'boxes':boxes, 'scores':scores, 'classes':classes, 'num_detections':num_detections} use_time = time.time() - start_time vis_util.visualize_boxes_and_labels_on_image_array( image_np, np.squeeze(boxes), np.squeeze(classes).astype(np.int32), np.squeeze(scores), category_index, use_normalized_coordinates=True, min_score_thresh=0.5, line_thickness=2) #vis_util.VisualizeSingleFrameDetections.images_from_evaluation_dict(image_np,eval_dict=eval_dicts) #categories_glob = [] print(category_index) f_name = re.split('/',path_f) #print(category_index.get(value)) for index, value in enumerate(classes[0]): if scores[0, index] > 0.5: score = scores[0, index] categories_glob = category_index.get(value) writer_list = [f_name[-1], categories_glob['id'], categories_glob['name'], score, use_time] writer_lists.append(writer_list) # print(writer_list) # print(index, '---', categories_glob,'---', score ) print(boxes) plt.figure(figsize=IMAGE_SIZE) plt.imshow(image_np) #plt.savefig('./test_result/predicted_' + f_name[-1]) cv2.imwrite('./test_result/predicted_' + f_name[-1] + ".jpg", image_np) #writer_lists.append(writer_list) #print('Image:{} Num: {} classes:{} scores:{} Time: {:.3f}s'.format(f_name[-1], num_detections, 'np.squeeze(classes[:2])', np.max(np.squeeze(scores)), use_time)) with open('./test_result/test_result.csv', 'w') as csv_file: writer = csv.writer(csv_file) writer.writerow(['test file', 'id', 'classes', 'scores', 'time/s']) writer.writerows(writer_lists)
ppalantir/axjingWorks
AcademicAN/TwoStage/test_batch.py
test_batch.py
py
5,072
python
en
code
1
github-code
6
31525994513
# _*_ coding: utf-8 _*_ __author__ = 'Steven' __date__ = '2017/8/21 21:47' import xadmin from .models import BugetItem class BugetItemAdmin(object): list_display = ["custom_id", "buget_type", "name", "desc", "standard", "edit_dept", "approve_dept", "account_item", "add_user", "add_time"] search_fields = ["custom_id", "buget_type", "name", "desc", "standard", "edit_dept", "approve_dept", "account_item", "add_user"] list_filter = ["custom_id", "buget_type", "name", "desc", "standard", "edit_dept", "approve_dept", "account_item", "add_user", "add_time"] xadmin.site.register(BugetItem, BugetItemAdmin)
stevenlu77/HOMS
apps/buget/adminx.py
adminx.py
py
682
python
en
code
0
github-code
6
8768680597
dict1 = { 'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5 } dict2 = { 'a': 1, 'b': 2, 'g': 33, 'h': 44, 'e': 55 } output = "" for key1 in dict1.keys(): for key2 in dict2.keys(): if key2 == key1: output += key1 + " " print(output.rstrip())
barelyturner/hometask5
hometask5.1/main.py
main.py
py
298
python
en
code
0
github-code
6
25178584436
from summarize import * from rbm_dae.deepAE import * import rouge def summarize_sentence_vectors(df, vector_set): """ Function applying the summarization function to get the ranked sentences. Parameters: df: dataframe containing the data to summarize vector_set: the column name of the vector set to rank on Returns the ranked sentences """ print('summarizing sentence vectors..') sentence_vectors = df[vector_set].tolist() sentence_vectors = np.array(sentence_vectors) #Create a list of ranked sentences. ranked_sentences = summarize_emails(df, sentence_vectors[0]) # display_summary(df, ranked_sentences) return ranked_sentences def summarize_autoencoder_vectors(df, net, vector_set): """ Function applying the autoencoder to the df vectors and the applying the summarization function to get the ranked sentences. Parameters: df: dataframe containing the data to summarize net: trained autoencoder vector_set: the column name of the vector set to rank on Returns the ranked sentences """ print('summarizing autoencoder sentence vectors..') sentence_vectors = df[vector_set].tolist() torch_vectors = torch.tensor(sentence_vectors[0], dtype=torch.float32) output_vectors = net(torch_vectors) #Create a list of ranked sentences. ranked_sentences = summarize_emails(df, output_vectors, True) # display_summary(df, ranked_sentences) return ranked_sentences def evaluate_rankings(df_train, df_test, target, sum_lens, corpus_ae=True, vector_set='sentence_vectors'): """ Funtion to evaluate the returned summaries. the summaries are created baased on the raw sentence vectors and the autoencoder vectors Parameters: df_train: dataframe with the training data df_test: dataframe with the test data target: string containing the column that should be used as the summary reference sum_len: An array holding the number of sentences to include in the summary corpus_as: Boolean deciding wether to train the autoencoder on the entire corpus or on each document vector_set: column name of the column with the sentence vectors (can be glove vectors or tf vectors) Returns: the scores for the rouge parameters (3D matrix) """ evaluator = rouge.Rouge() #create and train the autoencoder (see autoencoder module) net = None if corpus_ae: net = train_autoencoder(df_train, vector_set) # loop through all docs in the corpus print('evaluating summaries..') df_len = int(df_test.shape[0]) sum_scores = np.zeros((len(sum_lens), 3, 3, df_len)) ae_sum_scores = np.zeros((len(sum_lens), 3, 3, df_len)) curr_row = 0 for index, row in df_test.iterrows(): print('iteration: ', index) df_c = pd.DataFrame([row]) df_c['body'].iloc[0] # Only proceed if the vectors of the current row are of correct dimensions (not []) if len(df_c[vector_set].tolist()[0]) > 0: # train AE on the current document only if not corpus_ae : net = train_autoencoder(df_c, vector_set) reference = df_c[target].iloc[0] # reference that we score against (could be summary or subject)! print('reference: ', reference) # get the ranked sentences for the original and the ae modified sentence vectors ranked_sentences = summarize_sentence_vectors(df_c, vector_set) ranked_ae_sentences = summarize_autoencoder_vectors(df_c, net, vector_set) # collecting the scores for the specified summary lengths for s_len in sum_lens: print('s_len: ', s_len) if len(ranked_sentences) >= s_len: # get the top ranked sentences sum = [] sum_ae = [] for i in range(s_len): sum.append(ranked_sentences[i][2]) sum_ae.append(ranked_ae_sentences[i][2]) sum_str = ' '.join(sum) sum_ae_str = ' '.join(sum_ae) print('summary: ', sum_str) print('ae summary: ', sum_ae_str) # get the ROUGE scores for the ranked sentences and add to plot data sum_score = evaluator.get_scores(sum_str, reference) sum_ae_score = evaluator.get_scores(sum_ae_str, reference) sum_scores[s_len-1, 0, 0, curr_row] = sum_score[0]['rouge-1']['f'] sum_scores[s_len-1, 0, 1, curr_row] = sum_score[0]['rouge-1']['p'] sum_scores[s_len-1, 0, 2, curr_row] = sum_score[0]['rouge-1']['r'] sum_scores[s_len-1, 1, 0, curr_row] = sum_score[0]['rouge-2']['f'] sum_scores[s_len-1, 1, 1, curr_row] = sum_score[0]['rouge-2']['p'] sum_scores[s_len-1, 1, 2, curr_row] = sum_score[0]['rouge-2']['r'] sum_scores[s_len-1, 2, 0, curr_row] = sum_score[0]['rouge-l']['f'] sum_scores[s_len-1, 2, 1, curr_row] = sum_score[0]['rouge-l']['p'] sum_scores[s_len-1, 2, 2, curr_row] = sum_score[0]['rouge-l']['r'] ae_sum_scores[s_len-1, 0, 0, curr_row] = sum_ae_score[0]['rouge-1']['f'] ae_sum_scores[s_len-1, 0, 1, curr_row] = sum_ae_score[0]['rouge-1']['p'] ae_sum_scores[s_len-1, 0, 2, curr_row] = sum_ae_score[0]['rouge-1']['r'] ae_sum_scores[s_len-1, 1, 0, curr_row] = sum_ae_score[0]['rouge-2']['f'] ae_sum_scores[s_len-1, 1, 1, curr_row] = sum_ae_score[0]['rouge-2']['p'] ae_sum_scores[s_len-1, 1, 2, curr_row] = sum_ae_score[0]['rouge-2']['r'] ae_sum_scores[s_len-1, 2, 0, curr_row] = sum_ae_score[0]['rouge-l']['f'] ae_sum_scores[s_len-1, 2, 1, curr_row] = sum_ae_score[0]['rouge-l']['p'] ae_sum_scores[s_len-1, 2, 2, curr_row] = sum_ae_score[0]['rouge-l']['r'] curr_row += 1 sum_scores = sum_scores[:, :, :, 0:curr_row] ae_sum_scores = ae_sum_scores[:, :, :, 0:curr_row] return sum_scores, ae_sum_scores # calculating averages def analyze_and_plot_rouge_scores(sum_scores, ae_sum_scores, metric, dataset_name, summary_len): avg_scores = np.mean(sum_scores) avg_scores_ae = np.mean(ae_sum_scores) print(dataset_name) print('Summary length: ', summary_len) raw_mean = 'Mean ' + metric + ' for raw vectors: ' + str(round(avg_scores, 3)) dae_mean = 'Mean ' + metric + ' for DAE vectors: ' + str(round(avg_scores_ae, 3)) print(raw_mean) print(dae_mean) # Add to plot graphs for the extracted sentences """ x = np.arange(len(sum_scores)).tolist() label_1 = "Raw " + metric label_2 = "AE vector " + metric plt.plot(x, sum_scores.tolist(), label = label_1) plt.plot(x, ae_sum_scores.tolist(), label = label_2) plt.xlabel('Sentence') plt.ylabel('ROUGE score') title = "ROUGE " +metric + " for raw (mean: " + str(round(avg_scores, 3)) +") and AE (mean: "+str(round(avg_scores_ae, 3)) +") for " + dataset_name plt.title(title) plt.legend() plt.show() """ def evaluate_bc3(): """ Base function to run and plot the ROUGE scores for the bc3 dataset """ BC3_PICKLE_LOC = "./final_data/BC3_127.pkl" BC3_df = pd.read_pickle(BC3_PICKLE_LOC) # df contains 127 rows that all have df_vectors representation! # Split into training and test set BC3_df_train = BC3_df.iloc[:117] BC3_df_test = BC3_df.iloc[117:] # evaluate on 'summary' or 'subject' target = 'summary' summary_len = [1] # can set to use the df vectors ('df_vectors') or the glove vectors ('sentence_vectors') corpus_ae = True vector_set = 'sentence_vectors' #df_vectors sum_scores, ae_sum_scores = evaluate_rankings(BC3_df_train, BC3_df_test, target, summary_len, corpus_ae, vector_set) plot_all_scores(sum_scores, ae_sum_scores, 'bc3 dataset', summary_len[0]) def evaluate_spotify(): """ Base function to run and plot the ROUGE scores for the spotify dataset """ SPOTIFY_PICKLE_TRAIN_LOC = "./final_data/spotify_train_422.pkl" SPOTIFY_PICKLE_TEST_LOC = "./final_data/spotify_test_45.pkl" df_train = pd.read_pickle(SPOTIFY_PICKLE_TRAIN_LOC) df_test = pd.read_pickle(SPOTIFY_PICKLE_TEST_LOC) # section to get the summary for a specidic episode # df_sent = df_train.loc[df_train['episode_id'] == '7DoDuJE4sCBu2jJlOgCrwA'] # df_test = df_sent target = 'episode_desc' summary_len = [1] corpus_ae = True # if false, the autoencoder is only trained on the sentences in the current document # can set to use the df vectors (t-idf) ('df_vectors') or the glove vectors ('sentence_vectors') vector_set = 'sentence_vectors' sum_scores, ae_sum_scores = evaluate_rankings(df_train, df_test, target, summary_len, corpus_ae, vector_set) plot_all_scores(sum_scores, ae_sum_scores, 'spotify dataset', summary_len[0]) def plot_all_scores(sum_scores, ae_sum_scores, dataset, summary_len): """ Base function to plot ROUGE scores. Parameters: - sum_scores: Matirx of scores for the raw vectors. - as_sum_scores: Matrix of scores for the vectors produced by autoencoder """ analyze_and_plot_rouge_scores(sum_scores[0][0][0], ae_sum_scores[0][0][0], 'rouge-1 f-score', dataset, summary_len) analyze_and_plot_rouge_scores(sum_scores[0][0][1], ae_sum_scores[0][0][1], 'rouge-1 precision', dataset, summary_len) analyze_and_plot_rouge_scores(sum_scores[0][0][2], ae_sum_scores[0][0][2], 'rouge-1 recall', dataset, summary_len) # plot rouge-2 scores: analyze_and_plot_rouge_scores(sum_scores[0][1][0], ae_sum_scores[0][1][0], 'rouge-2 f-score', dataset, summary_len) analyze_and_plot_rouge_scores(sum_scores[0][1][1], ae_sum_scores[0][1][1], 'rouge-2 precision', dataset, summary_len) analyze_and_plot_rouge_scores(sum_scores[0][1][2], ae_sum_scores[0][1][2], 'rouge-2 recall', dataset, summary_len) # plot rouge-l scores: analyze_and_plot_rouge_scores(sum_scores[0][2][0], ae_sum_scores[0][2][0], 'rouge-l f-score', dataset, summary_len) analyze_and_plot_rouge_scores(sum_scores[0][2][1], ae_sum_scores[0][2][1], 'rouge-l precision', dataset, summary_len) analyze_and_plot_rouge_scores(sum_scores[0][2][2], ae_sum_scores[0][2][2], 'rouge-l recall', dataset, summary_len) def get_mean(sum_scores, ae_sum_scores): """ Function to get the mean of a vector of scores. """ avg_scores = np.mean(sum_scores) avg_scores_ae = np.mean(ae_sum_scores) return avg_scores, avg_scores_ae def evaluate_sentence_length_performance(df_train, df_test, target, summary_len, corpus_ae, vector_set, dataset): """ Function to cumpute the rouge scores for a range of summary lengths. """ averages_p = np.zeros((summary_len, 2)) averages_ae_p = np.zeros((summary_len, 2)) averages_r = np.zeros((summary_len, 2)) averages_ae_r = np.zeros((summary_len, 2)) summary_lengths = [1, 2, 3, 4, 5, 6] sum_scores, ae_sum_scores = evaluate_rankings(df_train, df_test, target, summary_lengths, corpus_ae, vector_set) for i in range(1, summary_len): print('evaluating rankings for # sentences: ', i) for j in range(2): # for rouge-1 and rouge-2 avg_score_p, avg_score_ae_p = get_mean(sum_scores[i-1][j][1], ae_sum_scores[i-1][j][1]) avg_score_r, avg_score_ae_r = get_mean(sum_scores[i-1][j][2], ae_sum_scores[i-1][j][2]) averages_p[i, j] = avg_score_p averages_ae_p[i, j] = avg_score_ae_p averages_r[i, j] = avg_score_r averages_ae_r[i, j] = avg_score_ae_r print('averages: ', averages_p) print('averages ae: ', averages_ae_p) averages_p = averages_p[1:].transpose() averages_ae_p = averages_ae_p[1:].transpose() averages_r = averages_r[1:].transpose() averages_ae_r = averages_ae_r[1:].transpose() return averages_p, averages_ae_p, averages_r, averages_ae_r def plot_sentences(glove_averages, glove_averages_ae, df_averages, df_averages_ae, title, dataset): """ Function to plot the mean scores vs sentence lengths for the different sentence encodings """ x = np.arange(1,7).tolist() plt.plot(x, glove_averages.tolist(), label = "Glove vector") plt.plot(x, glove_averages_ae.tolist(), label = "Glove DAE vector") plt.plot(x, df_averages.tolist(), label = 'tf-idf vector') plt.plot(x, df_averages_ae.tolist(), label = 'tf-idf DAE vector') plt.xlabel('Number of sentences') plt.ylabel(title) t = title + ' for ' + dataset plt.title(t) plt.legend() plt.show() def run_sentence_length_evaluation(): """ Main function to compute the mean scores for each summary length for the two datasets. """ BC3_PICKLE_LOC = "./final_data/BC3_127.pkl" BC3_df = pd.read_pickle(BC3_PICKLE_LOC) # df contains 127 rows that all have df_vectors representation! # Split into training and test set bc3_df_train = BC3_df.iloc[:117] bc3_df_test = BC3_df.iloc[117:] bc3_target = 'summary' SPOTIFY_PICKLE_TRAIN_LOC = "./final_data/spotify_train_422.pkl" SPOTIFY_PICKLE_TEST_LOC = "./final_data/spotify_test_45.pkl" s_df_train = pd.read_pickle(SPOTIFY_PICKLE_TRAIN_LOC) s_df_test = pd.read_pickle(SPOTIFY_PICKLE_TEST_LOC) s_target = 'episode_desc' summary_len = 7 corpus_ae = True vector_set = 'sentence_vectors' df_vector_set = 'df_vectors' # metric = 0 # 0 = f-score, 1 = precision, 2 = recall bc3_glove_p, bc3_glove_ae_p, bc3_glove_r, bc3_glove_ae_r = evaluate_sentence_length_performance(bc3_df_train, bc3_df_test, bc3_target, summary_len, corpus_ae, vector_set, 'bc3 dataset') bc3_df_p, bc3_df_ae_p, bc3_df_r, bc3_df_ae_r = evaluate_sentence_length_performance(bc3_df_train, bc3_df_test, bc3_target, summary_len, corpus_ae, df_vector_set, 'bc3 dataset') plot_sentences(bc3_glove_p[0], bc3_glove_ae_p[0], bc3_df_p[0], bc3_df_ae_p[0], 'ROUGE-1 scores precision', 'BC3 dataset') plot_sentences(bc3_glove_p[1], bc3_glove_ae_p[1], bc3_df_p[1], bc3_df_ae_p[1], 'ROUGE-2 scores precision', 'BC3 dataset') plot_sentences(bc3_glove_r[0], bc3_glove_ae_r[0], bc3_df_r[0], bc3_df_ae_r[0], 'ROUGE-1 scores recall', 'BC3 dataset') plot_sentences(bc3_glove_r[1], bc3_glove_ae_r[1], bc3_df_r[1], bc3_df_ae_r[1], 'ROUGE-2 scores recall', 'BC3 dataset') s_glove_p, s_glove_ae_p, s_glove_r, s_glove_ae_r = evaluate_sentence_length_performance(s_df_train, s_df_test, s_target, summary_len, corpus_ae, vector_set, 'Spotify dataset') s_df_p, s_df_ae_p, s_df_r, s_df_ae_r = evaluate_sentence_length_performance(s_df_train, s_df_test, s_target, summary_len, corpus_ae, df_vector_set, 'Spotify dataset') plot_sentences(s_glove_p[0], s_glove_ae_p[0], s_df_p[0], s_df_ae_p[0], 'ROUGE-1 scores precision', 'Spotify dataset') plot_sentences(s_glove_p[1], s_glove_ae_p[1], s_df_p[1], s_df_ae_p[1], 'ROUGE-2 scores precision', 'Spotify dataset') plot_sentences(s_glove_r[0], s_glove_ae_r[0], s_df_r[0], s_df_ae_r[0], 'ROUGE-1 scores recall', 'Spotify dataset') plot_sentences(s_glove_r[1], s_glove_ae_r[1], s_df_r[1], s_df_ae_r[1], 'ROUGE-2 scores recall', 'Spotify dataset') # evaluate_bc3() evaluate_spotify() # run_sentence_length_evaluation()
MikaelTornwall/dd2424_project
evaluate.py
evaluate.py
py
15,618
python
en
code
1
github-code
6
9093463058
def load_data(file): with open(file) as f: data = f.readlines() data = [line.strip() for line in data] # убираем переносы строк data = [x.rsplit() for x in data] # разбиваем линию на команду и шаг data = [(x[0], int(x[1])) for x in data] # приводим элементы к кортежам return data def calculate_position(data): x, y = 0, 0 for i in data: if i[0] == 'forward': x = x + i[1] elif i[0] == 'down': y = y + i[1] elif i[0] == 'up': y = y - i[1] else: print('error data!') print('position is ', x, y) return x * y def calculate_with_aim(data): x, depth = 0, 0 aim = 0 for i in data: if i[0] == 'forward': x = x + i[1] depth = depth + (i[1] * aim) elif i[0] == 'down': aim = aim + i[1] elif i[0] == 'up': aim = aim - i[1] else: print('error data!') print('position with aim is ', x, depth) return x * depth test_file = 'test_input.txt' filename = 'input.txt' print(load_data(test_file)) print('\n', 'Task #1') print('new coordinates multiply:', calculate_position(load_data(test_file))) print() print('new coordinates multiply:', calculate_position(load_data(filename))) print('\n', 'Task #2') print('coordinates with aim test:', calculate_with_aim(load_data(test_file))) print('coordinates with aim:', calculate_with_aim(load_data(filename)))
lapssh/advent_of_code
2021/day02/02-position.py
02-position.py
py
1,569
python
en
code
0
github-code
6
73968831228
"""Analyzes the MCTS explanations output by run_mcts.py in terms of stress and context entropy.""" import pickle from pathlib import Path import matplotlib.pyplot as plt import numpy as np from scipy.stats import wilcoxon def analyze_mcts_explanations(explanations_path: Path, save_dir: Path) -> None: """Analyzes the MCTS explanations output by run_mcts.py in terms of stress and context entropy. :param explanations_path: Path to a pickle file containing the explanations from run_mcts.py. :param save_dir: Path to a directory where analysis plots will be saved. """ # Load MCTS results with open(explanations_path, 'rb') as f: results = pickle.load(f) # Create save_dir save_dir.mkdir(parents=True, exist_ok=True) # Extract MCTS results original_stress = results['original_stress'] masked_stress_dependent = results['masked_stress_dependent'] masked_stress_independent = results['masked_stress_independent'] original_entropy = results['original_entropy'] masked_entropy_dependent = results['masked_entropy_dependent'] masked_entropy_independent = results['masked_entropy_independent'] # Plot stress stress_bins = np.linspace(0, 1, 20) plt.clf() plt.figure(figsize=(12, 8)) plt.hist(original_stress, stress_bins, alpha=0.5, label='Original') plt.hist(masked_stress_dependent, stress_bins, alpha=0.5, label='Context-Dependent') plt.hist(masked_stress_independent, stress_bins, alpha=0.5, label='Context-Independent') plt.legend(fontsize=20) plt.ylabel('Count', fontsize=20) plt.yticks(fontsize=16) plt.xlabel('Stress Score', fontsize=20) plt.xticks(fontsize=16) plt.title(rf'Stress Score for Original Text and Explanations', fontsize=24) plt.savefig(save_dir / f'stress.pdf', bbox_inches='tight') # Plot entropy max_entropy = -np.log2(1 / 3) entropy_bins = np.linspace(0, max_entropy, 20) plt.clf() plt.figure(figsize=(12, 8)) plt.hist(original_entropy, entropy_bins, alpha=0.5, label='Original') plt.hist(masked_entropy_dependent, entropy_bins, alpha=0.5, label='Context-Dependent') plt.hist(masked_entropy_independent, entropy_bins, alpha=0.5, label='Context-Independent') plt.legend(fontsize=20) plt.ylabel('Count', fontsize=20) plt.yticks(fontsize=16) plt.xlabel('Context Entropy', fontsize=20) plt.xticks(fontsize=16) plt.title(rf'Context Entropy for Original Text and Explanations', fontsize=24) plt.savefig(save_dir / f'entropy.pdf', bbox_inches='tight') # Print stress and entropy results print(f'Average stress (original) = ' f'{np.mean(original_stress):.3f} +/- {np.std(original_stress):.3f}') print(f'Average stress (dependent) = ' f'{np.mean(masked_stress_dependent):.3f} +/- {np.std(masked_stress_dependent):.3f}') print(f'Average stress (independent) = ' f'{np.mean(masked_stress_independent):.3f} +/- {np.std(masked_stress_independent):.3f}') print() print(f'Average entropy (original) = ' f'{np.mean(original_entropy):.3f} +/- {np.std(original_entropy):.3f}') print(f'Average entropy (dependent) = ' f'{np.mean(masked_entropy_dependent):.3f} +/- {np.std(masked_entropy_dependent):.3f}') print(f'Average entropy (independent) = ' f'{np.mean(masked_entropy_independent):.3f} +/- {np.std(masked_entropy_independent):.3f}') # Compute stress and entropy diffs diff_stress_dependent_original = masked_stress_dependent - original_stress diff_stress_independent_original = masked_stress_independent - original_stress diff_stress_dependent_independent = masked_stress_dependent - masked_stress_independent diff_entropy_dependent_original = masked_entropy_dependent - original_entropy diff_entropy_independent_original = masked_entropy_independent - original_entropy diff_entropy_dependent_independent = masked_entropy_dependent - masked_entropy_independent # Print stress and entropy diffs print(f'Average difference in stress (dependent - original) = ' f'{np.mean(diff_stress_dependent_original):.3f} +/- {np.std(diff_stress_dependent_original):.3f} ' f'(p = {wilcoxon(masked_stress_dependent, original_stress).pvalue:.4e})') print(f'Average difference in stress (independent - original) = ' f'{np.mean(diff_stress_independent_original):.3f} +/- {np.std(diff_stress_independent_original):.3f} ' f'(p = {wilcoxon(masked_stress_independent, original_stress).pvalue:.4e})') print(f'Average difference in stress (dependent - independent) = ' f'{np.mean(diff_stress_dependent_independent):.3f} +/- {np.std(diff_stress_dependent_independent):.3f} ' f'(p = {wilcoxon(masked_stress_dependent, masked_stress_independent).pvalue:.4e})') print() print(f'Average difference in entropy (dependent - original) = ' f'{np.mean(diff_entropy_dependent_original):.3f} +/- {np.std(diff_entropy_dependent_original):.3f} ' f'(p = {wilcoxon(masked_entropy_dependent, original_entropy).pvalue:.4e})') print(f'Average difference in entropy (independent - original) = ' f'{np.mean(diff_entropy_independent_original):.3f} +/- {np.std(diff_entropy_independent_original):.3f} ' f'(p = {wilcoxon(masked_entropy_independent, original_entropy).pvalue:.4e})') print(f'Average difference in entropy (dependent - independent) = ' f'{np.mean(diff_entropy_dependent_independent):.3f} +/- {np.std(diff_entropy_dependent_independent):.3f} ' f'(p = {wilcoxon(masked_entropy_dependent, masked_entropy_independent).pvalue:.4e})') if __name__ == '__main__': from tap import Tap class Args(Tap): explanations_path: Path """Path to a pickle file containing the explanations from run_mcts.py.""" save_dir: Path """Path to a directory where analysis plots will be saved.""" analyze_mcts_explanations(**Args().parse_args().as_dict())
swansonk14/MCTS_Interpretability
analyze_mcts_explanations.py
analyze_mcts_explanations.py
py
6,053
python
en
code
3
github-code
6
40876617434
"""All formatters from this pacakge should be easily mixed whith default ones using this pattern: >>> from code_formatter.base import formatters >>> from code_formatter import extras >>> custom_formatters = formatters.copy() >>> custom_formatters.register(extras.UnbreakableTupleFormatter, extras.ListOfExpressionsWithSingleLineContinuationsFormatter) """ import ast from .. import base from ..code import CodeBlock, CodeLine from ..exceptions import NotEnoughSpace __all__ = ['UnbreakableListOfExpressionFormatter', 'LinebreakingListOfExpressionFormatter', 'UnbreakableTupleFormatter', 'LinebreakingAttributeFormatter'] class ListOfExpressionsWithSingleLineContinuationsFormatter(base.ListOfExpressionsFormatter): multiline_continuation = False class UnbreakableListOfExpressionFormatter(base.ListOfExpressionsFormatter): def _format_code(self, width, continuation, suffix, line_width=None): line_width = line_width or width return self._format_line_continuation(width, continuation, suffix, line_width) class LinebreakingListOfExpressionFormatter(base.ListOfExpressionsFormatter): def _format_code(self, width, continuation, suffix, line_width=None): return self._format_line_break(width, continuation, suffix, line_width or width) class UnbreakableTupleFormatter(base.TupleFormatter): """Keep tuples in one line - for example: [('Alternative', 'Alternative'), ('Blues', 'Blues'), ('Classical', 'Classical')] """ ListOfExpressionsFormatter = UnbreakableListOfExpressionFormatter # FIXME: we should refactor this so "fallback" behaviour will be provided # by generic Formatter aggregator class CallFormatterWithLinebreakingFallback(base.CallFormatter): def _format_code(self, width, continuation, suffix): try: return super(CallFormatterWithLinebreakingFallback, self)._format_code(width, continuation, suffix) except NotEnoughSpace: if not self._arguments_formatters: raise suffix = self._append_to_suffix(suffix, ')') for i in range(width+1): curr_width = width - i block = self._func_formatter.format_code(curr_width) block.append_tokens('(') try: subblock = self._arguments_formatter.format_code(width - len(CodeLine.INDENT), suffix=suffix) except NotEnoughSpace: continue else: # FIXME: this is really ugly way to detect last method access subexpression indent = max(unicode(block.last_line).rfind('.'), 0) + len(CodeLine.INDENT) if indent + 1 >= block.last_line.width: continue block.extend(subblock, indent=indent) break return block class LinebreakingAttributeFormatter(base.AttributeFormatter): """This is really expermiental (as it API requires cleanup and it hacks `ast` structure in many places) formatter. It handles line breaking on attributes references, and alignes indentation to first attribute reference in expression. For example this piece: instance.method().attribute can be formatted into: (instance.method() .attribute) During registration this formatter replaces `AttributeFormatter` (which is quite obvious) but also `CallFormatter` and `SubscriptionFormatter` by derived formatters from current formatters - so simple `formatters.register(LinebreakingAttributeFormatter)` follows below logic: >>> from ast import Attribute, Call, Subscript >>> from code_formatter import base, format_code >>> from code_formatter.extra import LinebreakingAttributeFormatter >>> formatters = dict(base.formatters, ... **{Call: LinebreakingAttributeFormatter.call_formatter_factory(base.formatters[ast.Call]), ... Attribute: LinebreakingAttributeFormatter, ... Subscript: LinebreakingAttributeFormatter.subscription_formatter_factory(base.formatters[ast.Subscript])}) >>> print format_code('instance.identifier.identifier()', ... formatters_register=formatters, width=3, force=True) (instance.identifier .identifier()) """ class AttrsRefsListFormatter(base.ListOfExpressionsFormatter): separator = '.' class _IdentifierFormatter(base.CodeFormatter): def __init__(self, identifier, formatters_register, parent): self.identifier = identifier self.parent = parent super(LinebreakingAttributeFormatter._IdentifierFormatter, self).__init__(formatters_register) def _format_code(self, width, continuation, suffix): block = CodeBlock.from_tokens(self.identifier) if suffix is not None: block.merge(suffix) return block @classmethod def call_formatter_factory(cls, CallFormatter): class RedirectingCallFormatter(CallFormatter): def __new__(cls, expr, formatters_register, parent=None, func_formatter=None): # if func_formatter is not provided check whether we are not part of method call if func_formatter is None and isinstance(expr.func, ast.Attribute): return LinebreakingAttributeFormatter(expr, formatters_register, parent) return super(RedirectingCallFormatter, cls).__new__(cls, expr=expr, formatters_register=formatters_register, parent=parent, func_formatter=func_formatter) def __init__(self, expr, formatters_register, parent=None, func_formatter=None): super(RedirectingCallFormatter, self).__init__(expr, formatters_register, parent) if func_formatter: self._func_formatter = func_formatter return RedirectingCallFormatter @classmethod def subscription_formatter_factory(cls, SubscriptionFormatter): class RedirectingSubsriptionFormatter(SubscriptionFormatter): def __new__(cls, expr, formatters_register, parent=None, value_formatter=None): # if value_formatter is not provided check wether we are not part of attribute ref if value_formatter is None and isinstance(expr.value, ast.Attribute): return LinebreakingAttributeFormatter(expr, formatters_register, parent) return super(RedirectingSubsriptionFormatter, cls).__new__(cls, expr=expr, formatters_register=formatters_register, parent=parent, value_formatter=value_formatter) def __init__(self, expr, formatters_register, parent=None, value_formatter=None): super(RedirectingSubsriptionFormatter, self).__init__(expr, formatters_register, parent) if value_formatter: self._value_formatter = value_formatter return RedirectingSubsriptionFormatter @classmethod def register(cls, formatters_register): formatters_register[ast.Attribute] = cls formatters_register[ast.Subscript] = cls.subscription_formatter_factory(formatters_register[ast.Subscript]) formatters_register[ast.Call] = cls.call_formatter_factory(formatters_register[ast.Call]) return formatters_register def __init__(self, *args, **kwargs): super(base.AttributeFormatter, self).__init__(*args, **kwargs) self._attrs_formatters = [] expr = self.expr while (isinstance(expr, ast.Attribute) or isinstance(expr, ast.Call) and isinstance(expr.func, ast.Attribute) or isinstance(expr, ast.Subscript) and isinstance(expr.value, ast.Attribute)): if isinstance(expr, ast.Attribute): self._attrs_formatters.insert(0, LinebreakingAttributeFormatter._IdentifierFormatter(expr.attr, self.formatters_register, parent=self)) expr = expr.value elif isinstance(expr, ast.Call): # FIXME: how to fix parent?? should we change type of parent to ast type? func_formatter = LinebreakingAttributeFormatter._IdentifierFormatter( (expr.func .attr), self.formatters_register, parent=self) CallFormatter = self.get_formatter_class(expr) call_formater = CallFormatter(func_formatter=func_formatter, expr=expr, formatters_register=self.formatters_register, parent=self) self._attrs_formatters.insert(0, call_formater) expr = expr.func.value elif isinstance(expr, ast.Subscript): # FIXME: how to fix parent?? should we change type of parent to ast type? value_formatter = LinebreakingAttributeFormatter._IdentifierFormatter( (expr.value.attr), self.formatters_register, parent=self) SubscriptionFormatter = self.get_formatter_class(expr) subscription_formatter = SubscriptionFormatter(value_formatter=value_formatter, expr=expr, formatters_register=self.formatters_register, parent=self) self._attrs_formatters.insert(0, subscription_formatter) expr = expr.value.value self.value_formatter = self.get_formatter(expr) def _format_code(self, width, continuation, suffix): def _format(continuation, prefix=None): block = CodeBlock.from_tokens(prefix) if prefix else CodeBlock() for i in range(0, width - block.width + 1): block.merge(self.value_formatter.format_code(width - block.width - i)) separator = CodeBlock.from_tokens('.') attr_ref_indent = block.width block.merge(separator.copy()) try: block.merge(self._attrs_formatters[0] .format_code(width - block.last_line.width, False, suffix=(suffix if len(self._attrs_formatters) == 1 else None))) for attr_formatter in self._attrs_formatters[1:]: s = suffix if self._attrs_formatters[-1] == attr_formatter else None try: attr_block = attr_formatter.format_code(width - block.last_line.width - separator.width, False, suffix=s) except NotEnoughSpace: if not continuation: raise block.extend(separator, indent=attr_ref_indent) block.merge(attr_formatter.format_code(width - attr_ref_indent, continuation, suffix=s)) else: block.merge(separator) block.merge(attr_block) except NotEnoughSpace: block = CodeBlock.from_tokens(prefix) if prefix else CodeBlock() continue return block try: return _format(continuation) except NotEnoughSpace: if continuation: raise suffix = self._append_to_suffix(suffix, ')') return _format(True, '(')
paluh/code-formatter
code_formatter/extras/__init__.py
__init__.py
py
12,919
python
en
code
8
github-code
6
17519855782
""" Example of custom metric script. The custom metric script must contain the definition of custom_metric_function and a main function that reads the two csv files with pandas and evaluate the custom metric. """ import numpy as np def CAPE_CNR_function(dataframe_y_true, dataframe_y_pred): """ CAPE (Cumulated Absolute Percentage Error) function used by CNR for the evaluation of predictions Args dataframe_y_true: Pandas Dataframe Dataframe containing the true values of y. This dataframe was obtained by reading a csv file with following instruction: dataframe_y_true = pd.read_csv(CSV_1_FILE_PATH, index_col=0, sep=',') dataframe_y_pred: Pandas Dataframe This dataframe was obtained by reading a csv file with following instruction: dataframe_y_pred = pd.read_csv(CSV_2_FILE_PATH, index_col=0, sep=',') Returns score: Float The metric evaluated with the two dataframes. This must not be NaN. """ # CAPE function cape_cnr = 100 * np.sum(np.abs(dataframe_y_pred - dataframe_y_true)) / np.sum(dataframe_y_true) return cape_cnr if __name__ == '__main__': import pandas as pd CSV_FILE_Y_TRUE = 'Y_test.csv' CSV_FILE_Y_PRED = 'Y_test_benchmark.csv' df_y_true = pd.read_csv(CSV_FILE_Y_TRUE, index_col=0, sep=',') df_y_pred = pd.read_csv(CSV_FILE_Y_PRED, index_col=0, sep=',') print(CAPE_CNR_function(df_y_true, df_y_pred))
gaspardbb/astreos
CAPE_CNR_metric.py
CAPE_CNR_metric.py
py
1,479
python
en
code
2
github-code
6
30546132474
# %% import matplotlib.pyplot as plt import networkx as nx import pandas as pd import seaborn as sns from src import consts as const from src.processing import attribute_builder as ab from src.processing import plotting, refactor sns.set(palette="Set2") # Output Configurations pd.set_option('display.max_rows', 60) pd.set_option('display.max_columns', 60) plt.style.use('classic') # Read Dataset date_cols = ['flight_date', 'scheduled_departure_date', 'off_block_date', 'take_off_date', 'landing_date', 'on_block_date', 'scheduled_arrival_date', 'registered_delay_date'] df = pd.read_csv(const.PROCESSED_DATA_DIR / 'full_info.csv', sep='\t', parse_dates=date_cols) # %% [markdown] # ## Overview df.head(5) # %% ### PRELIMINARY SETUP ### df.drop(',', axis=1, inplace=True) df.rename(columns={'size_code': 'fleet'}, inplace=True) print("The dataset size is: {}".format(df.shape)) # %% types = df.dtypes counts = df.apply(lambda x: x.count()) uniques = df.apply(lambda x: [x.unique()]) distincts = df.apply(lambda x: x.unique().shape[0]) missing_ratio = (df.isnull().sum() / df.shape[0]) * 100 cols = ['types', 'counts', 'uniques', 'distincts', 'missing_ratio'] desc = pd.concat([types, counts, uniques, distincts, missing_ratio], axis=1, sort=False) desc.columns = cols # %% ### DELETE BASED ON FILLING FACTOR ### df = refactor.remove_cols_nan_based(df, .7) # remove cols with > 70% nan # %% delayed = df[df['delay_code'].notna()].shape[0] not_delayed = df.shape[0] - delayed plt.subplots() sns.barplot(x=['delayed', 'not delayed'], y=[delayed, not_delayed]) plt.savefig('num_delayed.png', bbox_inches='tight') # %% # using only delayed flights df.drop(df.loc[df['delay_code'].isna()].index, axis=0, inplace=True) # %% edges = df[['origin_airport', 'destination_airport']].values g = nx.from_edgelist(edges) print('There are {} different airports and {} connections'.format( len(g.nodes()), len(g.edges()))) # %% plotting.connections_map(df) # %% plotting.freq_connections(edges, save=True) # %% plotting.absolute_flt_pie(df, save=True) # %% plotting.time_distribution(df, save=True) # %% plotting.simple_bar(df, 'fleet', save=True) # %% ### ADJUST FLEET ### df = refactor.adjust_fleets(df) # %% plotting.airc_model_fleet(df, save=True) # %% plotting.fleet_time_flt(df, save=True) # %% plotting.tail_fleet(df, save=True) # %% plotting.delay_daily_pie(df, save=True) # %% plotting.delay_sample(df, save=True) # %% ### REMOVING BADLY FORMED RECORDS ### same_ori_dest = df.loc[df['origin_airport'] == df['destination_airport']] print( f"# of records with same origin and destination airports: {same_ori_dest.shape[0]}") df.drop(same_ori_dest.index, axis=0, inplace=True) not_take_off = df.loc[df['take_off_date'].isna()] print( f"# of planes that did not take off after same ori-dest instances removed: {not_take_off.shape[0]}") df.drop(not_take_off.index, axis=0, inplace=True) not_landing = df.loc[df['landing_date'].isna()] print( f"# of planes that did not land after same ori-dest instances removed: {not_landing.shape[0]}") df.drop(not_landing.index, axis=0, inplace=True) training_flt = df.loc[df['service_type'] == 'K'] print(f"# of training flights: {training_flt.shape[0]}") df.drop(training_flt.index, axis=0, inplace=True) nan_takeoff = len(df.loc[df['take_off_date'].isna()]) nan_landing = len(df.loc[df['landing_date'].isna()]) nan_offblock = len(df.loc[df['off_block_date'].isna()]) nan_onblock = len(df.loc[df['on_block_date'].isna()]) print(f"Null take-off: {nan_takeoff}") print(f"Null landing: {nan_landing}") print(f"Null off-block: {nan_offblock}") print(f"Null on-block: {nan_onblock}") offblock_takeoff = df.loc[df['off_block_date'] > df['take_off_date']] print(f"off-block > take-off: {len(offblock_takeoff)}") df.drop(offblock_takeoff.index, axis=0, inplace=True) takeoff_landing = df.loc[df['take_off_date'] >= df['landing_date']] print(f"take-off >= landing: {len(takeoff_landing)}") df.drop(takeoff_landing.index, axis=0, inplace=True) landing_onblock = df.loc[df['landing_date'] > df['on_block_date']] print(f"landing > on-block: {len(landing_onblock)}") df.drop(landing_onblock.index, axis=0, inplace=True) print("\nThe dataset size is: {}".format(df.shape)) # %% # plotting.delay_month_weekday(df) # %% plotting.proportion_delay_type(df, save=True) # %% # Build delay codes df = refactor.build_delay_codes(df) # %% plotting.cloud_coverage_dist(df, save=True) # %% df = refactor.fix_cloud_data(df) df = refactor.remove_cols_nan_based(df, .7) # remove cols with > 70% nan # %% df.rename( columns={'origin_cloud_coverage_lvl_1': 'origin_cloud_coverage', 'origin_cloud_height_lvl_1': 'origin_cloud_height', 'destination_cloud_coverage_lvl_1': 'destination_cloud_coverage', 'destination_cloud_height_lvl_1': 'destination_cloud_height'}, inplace=True) # %% plotting.weather_distributions(df, save=True) # %% plotting.cloud_distribution(df, save=True) # %% # Save data df.to_csv(const.PROCESSED_DATA_DIR / 'basic_eda.csv', sep='\t', encoding='utf-8', index=False) # %%
ajmcastro/flight-time-prediction
src/processing/eda.py
eda.py
py
5,177
python
en
code
1
github-code
6
43200145217
"""empty message Revision ID: 5b1f1d56cb45 Revises: 934b5daacc67 Create Date: 2019-06-03 19:02:22.711720 """ from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import postgresql # revision identifiers, used by Alembic. revision = '5b1f1d56cb45' down_revision = '934b5daacc67' branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.alter_column('post', 'date_posted', existing_type=postgresql.TIMESTAMP(), nullable=True) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.alter_column('post', 'date_posted', existing_type=postgresql.TIMESTAMP(), nullable=False) # ### end Alembic commands ###
tgalvinjr/blog-ip
migrations/versions/5b1f1d56cb45_.py
5b1f1d56cb45_.py
py
830
python
en
code
0
github-code
6
3642648813
class CommentStringParser(): def __init__(self,verbose=True): self.verbose = verbose self.special_cases = [['"', '"', 'strings'], ["'", "'", 'strings'], ["//", "\n", 'comments'], ["/*", "*/", 'comments']] def _find_next(self,codigo, i, c): n = len(c) while i < len(codigo) and codigo[i:i + n] != c: i += 1 return i + n def _clean_string(self,s): return s.replace('function','').replace('contract','').replace('{','').replace('}','') def _clean_code(self,codigo): n = len(codigo) i = 0 codigo_final = "" while i < n - 1: addone = True for cin, cout, tp in self.special_cases: if codigo[i:i + len(cin)] == cin: addone = False desde = i i += len(cin) hasta = self._find_next(codigo, i, cout) i = hasta codigo_final += self._clean_string(codigo[desde:hasta]) if addone: codigo_final += codigo[i] i += 1 if self.verbose and len(codigo_final) != codigo: print("Las palabras, function y contract, y los caracteres {} estan reservados. Se borraran de comentarios y strings") return codigo_final def extract_keywords(self,codigo): return self._clean_code(codigo)
matisyo/vulnerability_detection
Notebooks/utils/code_helpers.py
code_helpers.py
py
1,500
python
en
code
0
github-code
6
33628818675
# -*- coding: utf-8 -*- """ Created by Safa Arıman on 12.12.2018 """ import base64 import json import urllib.request, urllib.parse, urllib.error import urllib.request, urllib.error, urllib.parse import urllib.parse from ulauncher.api.client.EventListener import EventListener from ulauncher.api.shared.action.DoNothingAction import DoNothingAction from ulauncher.api.shared.action.OpenUrlAction import OpenUrlAction from ulauncher.api.shared.action.CopyToClipboardAction import CopyToClipboardAction from ulauncher.api.shared.action.RenderResultListAction import RenderResultListAction from ulauncher.api.shared.item.ExtensionResultItem import ExtensionResultItem __author__ = 'safaariman' class ExtensionKeywordListener(EventListener): def __init__(self, icon_file): self.icon_file = icon_file def on_event(self, event, extension): query = event.get_argument() results = [] workspace_url = extension.preferences.get('url') user = extension.preferences.get('username') password = extension.preferences.get('password') token = base64.b64encode(str('%s:%s' % (user, password)).encode()).decode() url = urllib.parse.urljoin(workspace_url, 'rest/internal/2/productsearch/search') get_url = "%s?%s" % (url, urllib.parse.urlencode({'q': query})) req = urllib.request.Request(get_url, headers={'Authorization': 'Basic %s' % token}) result_types = [] try: response = urllib.request.urlopen(req) result_types = json.loads(response.read()) except urllib.error.HTTPError as e: if e.code == 401: results.append( ExtensionResultItem( name='Authentication failed.', description='Please check your username/e-mail and password.', icon=self.icon_file, on_enter=DoNothingAction() ) ) return RenderResultListAction(results) except urllib.error.URLError as e: results.append( ExtensionResultItem( name='Could not connect to Jira.', description='Please check your workspace url and make sure you are connected to the internet.', icon=self.icon_file, on_enter=DoNothingAction() ) ) return RenderResultListAction(results) for rtype in result_types: for item in rtype.get('items', []): key = item.get('subtitle') title = item.get('title') url = item.get('url') results.append( ExtensionResultItem( name=title if not key else '%s - %s' % (key, title), description=key, icon=self.icon_file, on_enter=OpenUrlAction(url=url), on_alt_enter=CopyToClipboardAction(url), ) ) if not results: results.append( ExtensionResultItem( name="Search '%s'" % query, description='No results. Try searching something else :)', icon=self.icon_file, on_enter=DoNothingAction() ) ) return RenderResultListAction(results)
safaariman/ulauncher-jira
jira/listeners/extension_keyword.py
extension_keyword.py
py
3,484
python
en
code
10
github-code
6
72536666107
from dataclasses import asdict, dataclass from functools import cached_property from time import sleep from typing import Any, Dict, List, Optional, Union from airflow import AirflowException from airflow.models.taskinstance import Context from airflow.providers.http.hooks.http import HttpHook from constants import CRYPTO_COMPARE_HTTP_CONN_ID from hooks.wrappers.http_stream import HttpStreamHook from kafka import KafkaProducer from operators.cryptocurrency.price.base import CryptocurrencyBaseOperator from utils.exception import raise_airflow_exception from utils.kafka import kafka_producer_context from utils.request import get_request_json @dataclass class CryptocurrencyMultiPriceApiData: fsyms: str tsyms: str class CryptocurrencyPriceSourcingStreamOperator(CryptocurrencyBaseOperator): cryptocurrency_http_conn_id: str = CRYPTO_COMPARE_HTTP_CONN_ID def __init__( self, symbol_list: List[str], **kwargs, ) -> None: super().__init__(**kwargs) self.symbol_list = symbol_list def read( self, endpoint: str, data: Optional[Dict[str, Any]] = None, ): return self.try_to_get_request_json( http_hook=self.http_hook, endpoint=endpoint, data=data, ) @cached_property def kafka_topic_name(self) -> str: return "cryptocurrency" @cached_property def standard_currency(self) -> str: return "USD" @cached_property def sleep_second(self) -> float: return 1 / len(self.symbol_list) @property def api_endpoint(self): return "pricemulti" def try_to_get_request_json( self, http_hook: Union[HttpHook, HttpStreamHook], endpoint: str, data: Optional[Dict[str, Any]] = None, retry_count: int = 5, err_msg: str = "", ) -> Dict[str, Any]: if retry_count <= 0: raise_airflow_exception( error_msg=err_msg, logger=self.log, ) try: response_json = get_request_json( http_hook=http_hook, endpoint=endpoint, data=data, headers=self.api_header, back_off_cap=self.back_off_cap, back_off_base=self.back_off_base, proxies=self.proxies, ) except AirflowException as e: self.log.info(f"raise AirflowException err_msg: {e}") sleep(10) return self.try_to_get_request_json( http_hook=http_hook, endpoint=endpoint, data=data, retry_count=retry_count - 1, err_msg=f"{err_msg} retry_count : {retry_count}\nerr_msg : {e} \n\n", ) response_status = response_json.get("Response") if response_status == "Error": response_message = response_json.get("Message") if ( response_message == "You are over your rate limit please upgrade your account!" ): self.PROXY_IP_IDX += 1 self.log.info( f"{response_message}, raise PROXY_IP_IDX to {self.PROXY_IP_IDX}" ) return self.try_to_get_request_json( http_hook=http_hook, endpoint=endpoint, data=data, retry_count=retry_count - 1, err_msg=f"{err_msg} retry_count : {retry_count}\nerr_msg : {response_message} \n\n", ) return response_json def write( self, json_data: List[Dict[str, Any]], kafka_producer: KafkaProducer, ) -> None: for data in json_data: kafka_producer.send(self.kafka_topic_name, value=data) kafka_producer.flush() @cached_property def api_data( self, ) -> CryptocurrencyMultiPriceApiData: return CryptocurrencyMultiPriceApiData( fsyms=",".join(self.symbol_list), tsyms=self.standard_currency, ) @staticmethod def transform(data: Dict[str, Any]) -> List[Dict[str, Any]]: return [ {"symbol": symbol, "close": usd.get("USD")} for symbol, usd in data.items() ] def execute(self, context: Context) -> None: # pass with kafka_producer_context() as kafka_producer: while 1: json_data = self.read( endpoint=self.api_endpoint, data=asdict(self.api_data), ) transformed_data = self.transform(data=json_data) self.write( json_data=transformed_data, kafka_producer=kafka_producer, ) sleep(10)
ksh24865/cryptocurrency-data-pipeline
Airflow/dags/operators/cryptocurrency/price/sourcing_stream.py
sourcing_stream.py
py
4,859
python
en
code
0
github-code
6
34958665792
# -*- coding: utf-8 -*- import numpy as np import os import time import torch import torch.nn as nn import torch.backends.cudnn as cudnn import torchvision.transforms as trn import torchvision.datasets as dset import torch.nn.functional as F import json from attack_methods import pgd from models.wrn import WideResNet from option import BaseOptions class PrivateOptions(BaseOptions): def initialize(self): BaseOptions.initialize(self) # WRN Architecture self.parser.add_argument('--layers', default=28, type=int, help='total number of layers') self.parser.add_argument('--widen-factor', default=10, type=int, help='widen factor') self.parser.add_argument('--droprate', default=0.0, type=float, help='dropout probability') # /////////////// Training /////////////// def train(): net.train() # enter train mode loss_avg = 0.0 for bx, by in train_loader: bx, by = bx.cuda(), by.cuda() adv_bx = adversary_train(net, bx, by) # forward logits = net(adv_bx) # backward # scheduler.step() optimizer.zero_grad() loss = F.cross_entropy(logits, by) loss.backward() optimizer.step() # exponential moving average loss_avg = loss_avg * 0.8 + float(loss) * 0.2 state['train_loss'] = loss_avg # test function def test(): net.eval() loss_avg = 0.0 correct = 0 with torch.no_grad(): for data, target in test_loader: data, target = data.cuda(), target.cuda() adv_data = adversary_test(net, data, target) # forward output = net(adv_data) loss = F.cross_entropy(output, target) # accuracy pred = output.data.max(1)[1] correct += pred.eq(target.data).sum().item() # test loss average loss_avg += float(loss.data) state['test_loss'] = loss_avg / len(test_loader) state['test_accuracy'] = correct / len(test_loader.dataset) # overall_test function def test_in_testset(): net.eval() loss_avg = 0.0 correct = 0 adv_loss_avg = 0.0 adv_correct = 0 with torch.no_grad(): for data, target in test_loader: data, target = data.cuda(), target.cuda() adv_data = adversary_test(net, data, target) # forward output = net(data) loss = F.cross_entropy(output, target) # accuracy pred = output.data.max(1)[1] correct += pred.eq(target.data).sum().item() # test loss average loss_avg += float(loss.data) # forward adv_output = net(adv_data) adv_loss = F.cross_entropy(adv_output, target) # accuracy adv_pred = adv_output.data.max(1)[1] adv_correct += adv_pred.eq(target.data).sum().item() # test loss average adv_loss_avg += float(adv_loss.data) state['test_loss'] = loss_avg / len(test_loader) state['test_accuracy'] = correct / len(test_loader.dataset) state['adv_test_loss'] = adv_loss_avg / len(test_loader) state['adv_test_accuracy'] = adv_correct / len(test_loader.dataset) def test_in_trainset(): train_loader = torch.utils.data.DataLoader( train_data, batch_size=opt.test_bs, shuffle=False, num_workers=opt.prefetch, pin_memory=torch.cuda.is_available()) net.eval() loss_avg = 0.0 correct = 0 adv_loss_avg = 0.0 adv_correct = 0 with torch.no_grad(): for data, target in train_loader: data, target = data.cuda(), target.cuda() adv_data = adversary_test(net, data, target) # forward output = net(data) loss = F.cross_entropy(output, target) # accuracy pred = output.data.max(1)[1] correct += pred.eq(target.data).sum().item() # test loss average loss_avg += float(loss.data) # forward adv_output = net(adv_data) adv_loss = F.cross_entropy(adv_output, target) # accuracy adv_pred = adv_output.data.max(1)[1] adv_correct += adv_pred.eq(target.data).sum().item() # test loss average adv_loss_avg += float(adv_loss.data) state['train_loss'] = loss_avg / len(train_loader) state['train_accuracy'] = correct / len(train_loader.dataset) state['adv_train_loss'] = adv_loss_avg / len(train_loader) state['adv_train_accuracy'] = adv_correct / len(train_loader.dataset) opt = PrivateOptions().parse() state = {k: v for k, v in opt._get_kwargs()} torch.manual_seed(opt.random_seed) np.random.seed(opt.random_seed) cudnn.benchmark = True # # mean and standard deviation of channels of CIFAR-10 images # mean = [x / 255 for x in [125.3, 123.0, 113.9]] # std = [x / 255 for x in [63.0, 62.1, 66.7]] train_transform = trn.Compose([trn.RandomHorizontalFlip(), trn.RandomCrop(32, padding=4), trn.ToTensor(), trn.Normalize( mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5])]) test_transform = trn.Compose([trn.ToTensor(), trn.Normalize( mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5])]) if opt.dataset == 'cifar10': train_data = dset.CIFAR10(opt.dataroot, train=True, transform=train_transform, download=True) test_data = dset.CIFAR10(opt.dataroot, train=False, transform=test_transform) num_classes = 10 else: train_data = dset.CIFAR100(opt.dataroot, train=True, transform=train_transform, download=True) test_data = dset.CIFAR100(opt.dataroot, train=False, transform=test_transform) num_classes = 100 train_loader = torch.utils.data.DataLoader( train_data, batch_size=opt.batch_size, shuffle=True, num_workers=opt.prefetch, pin_memory=torch.cuda.is_available()) test_loader = torch.utils.data.DataLoader( test_data, batch_size=opt.test_bs, shuffle=False, num_workers=opt.prefetch, pin_memory=torch.cuda.is_available()) # Create model if opt.model == 'wrn': net = WideResNet(opt.layers, num_classes, opt.widen_factor, dropRate=opt.droprate) else: assert False, opt.model + ' is not supported.' start_epoch = opt.start_epoch if opt.ngpu > 0: net = torch.nn.DataParallel(net, device_ids=list(range(opt.ngpu))) net.cuda() torch.cuda.manual_seed(opt.random_seed) # Restore model if desired if opt.load != '': if opt.test and os.path.isfile(opt.load): net.load_state_dict(torch.load(opt.load)) print('Appointed Model Restored!') else: model_name = os.path.join(opt.load, opt.dataset + opt.model + '_epoch_' + str(start_epoch) + '.pt') if os.path.isfile(model_name): net.load_state_dict(torch.load(model_name)) print('Model restored! Epoch:', start_epoch) else: raise Exception("Could not resume") epoch_step = json.loads(opt.epoch_step) lr = state['learning_rate'] optimizer = torch.optim.SGD( net.parameters(), lr, momentum=state['momentum'], weight_decay=state['decay'], nesterov=True) # def cosine_annealing(step, total_steps, lr_max, lr_min): # return lr_min + (lr_max - lr_min) * 0.5 * ( # 1 + np.cos(step / total_steps * np.pi)) # # # scheduler = torch.optim.lr_scheduler.LambdaLR( # optimizer, # lr_lambda=lambda step: cosine_annealing( # step, # opt.epochs * len(train_loader), # 1, # since lr_lambda computes multiplicative factor # 1e-6 / opt.learning_rate)) # originally 1e-6 adversary_train = pgd.PGD(epsilon=opt.epsilon * 2, num_steps=opt.num_steps, step_size=opt.step_size * 2).cuda() adversary_test = pgd.PGD(epsilon=opt.epsilon * 2, num_steps=opt.test_num_steps, step_size=opt.test_step_size * 2).cuda() if opt.test: test_in_testset() # test_in_trainset() print(state) exit() # Make save directory if not os.path.exists(opt.save): os.makedirs(opt.save) if not os.path.isdir(opt.save): raise Exception('%s is not a dir' % opt.save) with open(os.path.join(opt.save, "log_" + opt.dataset + opt.model + '_training_results.csv'), 'w') as f: f.write('epoch,time(s),train_loss,test_loss,test_accuracy(%)\n') print('Beginning Training\n') # Main loop best_test_accuracy = 0 for epoch in range(start_epoch, opt.epochs + 1): state['epoch'] = epoch begin_epoch = time.time() train() test() # Save model if epoch > 10 and epoch % 10 == 0: torch.save(net.state_dict(), os.path.join(opt.save, opt.dataset + opt.model + '_epoch_' + str(epoch) + '.pt')) if state['test_accuracy'] > best_test_accuracy: best_test_accuracy = state['test_accuracy'] torch.save(net.state_dict(), os.path.join(opt.save, opt.dataset + opt.model + '_epoch_best.pt')) # Show results with open(os.path.join(opt.save, "log_" + opt.dataset + opt.model + '_training_results.csv'), 'a') as f: f.write('%03d,%0.6f,%05d,%0.3f,%0.3f,%0.2f\n' % ( (epoch), lr, time.time() - begin_epoch, state['train_loss'], state['test_loss'], 100. * state['test_accuracy'], )) print('Epoch {0:3d} | LR {1:.6f} | Time {2:5d} | Train Loss {3:.3f} | Test Loss {4:.3f} | Test Acc {5:.2f}'.format( (epoch), lr, int(time.time() - begin_epoch), state['train_loss'], state['test_loss'], 100. * state['test_accuracy']) ) # Adjust learning rate if epoch in epoch_step: lr = optimizer.param_groups[0]['lr'] * opt.lr_decay_ratio optimizer = torch.optim.SGD( net.parameters(), lr, momentum=state['momentum'], weight_decay=state['decay'], nesterov=True) print("new lr:", lr)
arthur-qiu/adv_vis
cifar10_wrn_at.py
cifar10_wrn_at.py
py
10,072
python
en
code
0
github-code
6
8929962174
nums = [1,2,3,4,5,6,7,8,9,10] #Print the even numbers even_numbers = list(filter(lambda x: x % 2 == 0, nums)) print(even_numbers) #Print the odd numbers odd_numbers = list(filter(lambda x: x % 2 != 0, nums)) print(odd_numbers) names = ['Adam', 'Ana', 'Kevin', 'Daniel', 'Michael'] #Filter the names that have more than 5 characters od length filtered_names = list(filter(lambda name: len(name) > 5, names)) print(filtered_names)
moreirafelipegbt/udemy-python
s17/s17-138.py
s17-138.py
py
434
python
en
code
0
github-code
6
39760240581
# -*- coding: utf-8 -*- from django.conf.urls import patterns, include, url urlpatterns = patterns('CiscoDxUketsukeApp.views', # url(r'^$', 'CiscoDxUketsuke.views.home', name='home'), # url(r'^getData/' 'CiscoDxUketsuke.views.getData'), url(r'^member_tsv/$','member_tsv'), url(r'^member_json/$','member_json'), url(r'^room_tsv/$','room_tsv'), url(r'^room_json/$','room_json'), url(r'^folder_tsv/$','folder_tsv'), url(r'^folder_json/$','folder_json'), url(r'^favorite_tsv/$','favorite_tsv'), url(r'^favorite_json/$','favorite_json'), url(r'^test/$','test'), url(r'^test2/$','test2'), url(r'^pad1/$','pad1'), url(r'^pad2/$','pad2'), url(r'^top/$','top'), url(r'^member/$','member'), url(r'^room/$','room'), url(r'^folder/$','folder'), url(r'^folder/(?P<dxId>\d+)/$','folder'), url(r'^folder/(?P<dxId>\d+)/(?P<folderId>\d+)/$','folder'), url(r'^home/$','home'), url(r'^fav/$','fav'), url(r'^index/$','index'), url(r'^list/$','list'), url(r'^add_dx/$','add_dx'), url(r'^edit_dx/$','edit_dx'), url(r'^add_member/$','add_member'), url(r'^add_room/$','add_room'), url(r'^add_folder/$','add_folder'), url(r'^add1/$','add_member_room_db'), )
fjunya/dxApp
src/CiscoDxUketsukeApp/urls.py
urls.py
py
1,254
python
en
code
0
github-code
6
21738440212
import cv2 # Problem 4. # Rescale the video vid1.jpg by 0.5 and display the original video and the rescaled one in separate windows. def rescaleFrame(frame, scale): width = int(frame.shape[1] * scale) height = int(frame.shape[0] * scale) dimensions = (width, height) return cv2.resize(frame, dimensions, interpolation=cv2.INTER_AREA) capture = cv2.VideoCapture('vid1.mp4') while True: frame_loaded, frame = capture.read() if frame is not None: # or if isTrue frame_rescaled = rescaleFrame(frame, 0.5) cv2.imshow('Video', frame) cv2.imshow('Video_rescaled', frame_rescaled) else: print('empty frame') exit(1) if cv2.waitKey(20) & 0xFF == ord('d'): break capture.release() cv2.destroyAllWindows() cv2.waitKey(0)
markhamazaspyan/Python_2_ASDS
opencvHW1/problem4.py
problem4.py
py
799
python
en
code
0
github-code
6
28965388899
from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.remote.webelement import WebElement from selenium.common.exceptions import NoSuchElementException from selenium.common.exceptions import TimeoutException import time import json import os from course import Course # Web Driver configuration PATH = "C:\Program Files (x86)\chromedriver.exe" driver = webdriver.Chrome(PATH) coursesList = [] # getting pages URLs f = open("URL.txt", "r") URLs = [] for x in f: URLs.append(x) f.close() # searching through each page from file and through each subpage (< 1 2 3 ... 7 >) for URL in URLs: emptyPage = False # means that the page number is out of range and there is no more content on this page subpageCounter = 1 while not emptyPage: print(URL+'&p='+str(subpageCounter)) driver.get(URL+'&p='+str(subpageCounter)) subpageCounter += 1 try: # element with this class name is a big container for all smaller divs. If it is not present then there is no content on the page WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CLASS_NAME, 'course-list--container--3zXPS'))) container = driver.find_element_by_class_name('course-list--container--3zXPS') coursesBiggerDivs = container.find_elements_by_class_name('browse-course-card--link--3KIkQ') courses = container.find_elements_by_class_name('course-card--container--3w8Zm') driver.execute_script("window.scrollTo(0, document.body.scrollHeight);") counter = 0 for course in courses: # each course we convert into an object of 'Course' class (data extraction) title = course.find_element_by_class_name('udlite-heading-md').text desc = course.find_element_by_class_name('udlite-text-sm').text author = course.find_element_by_class_name('udlite-text-xs').text try: spanElement = course.find_element_by_css_selector('span.star-rating--rating-number--3lVe8') except NoSuchElementException: ratings = 'Brak ocen' else: ratings = spanElement.text try: details = course.find_elements_by_css_selector('span.course-card--row--1OMjg') courseLength = details[0].text courseLevel = details[len(details)-1].text except NoSuchElementException: print("Brak dodatkowych informacji") courseLength = 'Brak informacji' courseLevel = 'Brak informacji' try: image = course.find_element_by_class_name('course-card--course-image--2sjYP') ActionChains(driver).move_to_element(image).perform() imageSourceURL = image.get_attribute('src') except NoSuchElementException: print("Brak zdjęcia") imageSourceURL = 'https://www.google.com/url?sa=i&url=https%3A%2F%2Fwww.smarthome.com.au%2Faeotec-z-wave-plug-in-smart-switch-6.html&psig=AOvVaw33Vx1wP6a3B3QAn_6WPe4A&ust=1602514347326000&source=images&cd=vfe&ved=0CAIQjRxqFwoTCNitsanlrOwCFQAAAAAdAAAAABAE' try: priceDiv = course.find_element_by_css_selector('div.price-text--price-part--Tu6MH') ActionChains(driver).move_to_element(priceDiv).perform() spans = priceDiv.find_elements_by_tag_name('span') price = spans[len(spans) - 1].text except NoSuchElementException: price = 'Brak ceny' try: courseLink = coursesBiggerDivs[counter].get_attribute('href') except NoSuchElementException: courseLink = None counter += 1 c = Course(title, desc, author, ratings, price, imageSourceURL, courseLength, courseLevel, courseLink) coursesList.append(c) except TimeoutException: print('[INFO] Ostatnia podstrona adresu URL') emptyPage = True os.remove('objectsInJSON.txt') for course in coursesList: #search through each course page and get some more specific information driver.get(course.URL) WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CLASS_NAME, 'topic-menu'))) topicDiv = driver.find_element_by_class_name('topic-menu') elements = topicDiv.find_elements_by_class_name('udlite-heading-sm') course.setCategory(elements[0].text) course.setSubcategory(elements[1].text) courseDescription = driver.find_element_by_class_name('styles--description--3y4KY') course.setExtendedDescription(courseDescription.get_attribute('innerHTML')) # write converted course object into output file string = course.makeJSON() with open('objectsInJSON.txt','a',encoding='utf-8') as file: json.dump(string, file, ensure_ascii=False) file.write("\n") driver.quit() file.close()
krzysztofzajaczkowski/newdemy
utils/WebCrawler/main.py
main.py
py
5,352
python
en
code
0
github-code
6
73813844989
import io import numpy as np import sys from gym.envs.toy_test import discrete from copy import deepcopy as dc UP = 0 RIGHT = 1 DOWN = 2 LEFT = 3 class GridworldEnv(discrete.DiscreteEnv): metadata = {'render.modes': ['human', 'ansi']} def __init__(self, shape = [4, 4]): if not isinstance(shape, (list, tuple)) or not len(shape) == 2: raise ValueError('shape argument must be a list/tuple of length 2') self.shape = shape nS = np.prod(shape) #np.prod : array 내부 element들의 곱 nA = 4 MAX_Y = shape[0] MAX_X = shape[1] P = {} grid = np.arange(nS).reshape(shape) # np.arange(x) 0부터 x까지 [0, 1, ..., x] it = np.nditer(grid, flags=['multi_index']) # iterator while not it.finished: s = it.iterindex y, x = it.multi_index # 왜 y,x 순서? => (row, column)가 (y, x) 에 대응 P[s] = {a: [] for a in range(nA)} # a = 0, ..,3 돌면서 [] 생성 (s = iterindex 이고 state) # P[s][a] = (prob, next_state, reward, is_done) def is_done(s): # terminal or not return s == 0 or s == (nS - 1) reward = 0.0 if is_done(s) else -1.0 # reward는 현재 state와 action 기준 (여기서는 action 종류 관계없이 동일) if is_done(s): P[s][UP] = [(1.0, s, reward, True)] # 왜 [ ]? P[s][RIGHT] = [(1.0, s, reward, True)] P[s][DOWN] = [(1.0, s, reward, True)] P[s][LEFT] = [(1.0, s, reward, True)] else: ns_up = s if y == 0 else s - MAX_X # 맨 윗줄이면 그대로, 아니면 MAX_X 만큼 빼기 (s는 1차원 배열이니까) ns_right = s if x == (MAX_X - 1) else s + 1 ns_down = s if y == (MAX_Y -1) else s + MAX_X ns_left = s if x == 0 else s - 1 P[s][UP] = [(1.0, ns_up, reward, is_done(ns_up))] P[s][RIGHT] = [(1.0, ns_right, reward, is_done(ns_right))] P[s][DOWN] = [(1.0, ns_down, reward, is_done(ns_down))] P[s][LEFT] = [(1.0, ns_left, reward, is_done(ns_left))] it.iternext()
hyeonahkimm/RLfrombasic
src/common/gridworld.py
gridworld.py
py
2,222
python
en
code
0
github-code
6
4206104345
# pylint: disable=no-member, no-name-in-module, import-error from __future__ import absolute_import import glob import distutils.command.sdist import distutils.log import subprocess from setuptools import Command, setup import setuptools.command.sdist # Patch setuptools' sdist behaviour with distutils' sdist behaviour setuptools.command.sdist.sdist.run = distutils.command.sdist.sdist.run class LintCommand(Command): """ Custom setuptools command for running lint """ description = 'run lint against project source files' user_options = [] def initialize_options(self): pass def finalize_options(self): pass def run(self): self.announce("Running pylint", level=distutils.log.INFO) subprocess.check_call(["pylint"] + glob.glob("*.py")) setup( # Package name: name="dxlmisc", # Version number: version="0.0.1", # Requirements install_requires=[ "pylint" ], description="Misc OpenDXL Tools", python_requires='>=2.7.9,!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*', classifiers=[ "Development Status :: 4 - Beta", "Topic :: Software Development :: Libraries :: Python Modules", "License :: OSI Approved :: Apache Software License", "Programming Language :: Python", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.4", "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6" ], cmdclass={ "lint": LintCommand } )
jbarlow-mcafee/opendxl-misc
setup.py
setup.py
py
1,654
python
en
code
0
github-code
6
21998859226
from typing import List class Solution: def deleteAndEarn(self, nums: List[int]) -> int: max_val = max(nums) total = [0] * (max_val + 1) for val in nums: total[val] += val def rob(nums): first = nums[0] second = max(nums[0], nums[1]) for i in range(2, len(nums)): first, second = second, max(second, first + nums[i]) return second return rob(total)
hangwudy/leetcode
700-799/740. 删除并获得点数.py
740. 删除并获得点数.py
py
475
python
en
code
0
github-code
6
17654474137
import string import os import csv from datetime import datetime from datetime import date import re #debugging debug = False print() def extract(inputFile: string, outputFile: string): specialTitle = False fileIndex = 1 with open(outputFile,'w',newline='', encoding="utf8") as writefile,open(inputFile,newline='', encoding="utf8") as readfile: writer = csv.writer(writefile) state = 0 processNum = 0 starti = 0 for line in readfile: #PRELIMINARY---------------------------------------------------------- states = ['', #0 just read line '[MARS]', #1 '[CONFIG LIST]', #2 'Process usage summary', #3 '[Batterystats Collector]', #4 'Daily Summary', #5 '[PowerAnomaly Battery Dump]', #6 'Anomaly List For DeviceCare', #7 '[TCPU dump]', #8 '[UCPU dump]', #9 '------ NETWORK DEV INFO (/proc/net/dev) ------', #10 '------ MEMORY INFO (/proc/meminfo) ------', #11 '------ VIRTUAL MEMORY STATS (/proc/vmstat) ------',#12 '** MEMINFO in pid[com.x3AM.Innovations.Flare.Mobile.App] **'#13 ] data = [''] #///////////////////////////////////////////////////////////////////// #SET STATE------------------------------------------------------------ #enter state 1 ([MARS]) if (line.strip() == states[1]): state = 1 starti = fileIndex print(f"--Changed State to: {state} becasuse of {states[state]}\nExtracting from line {starti}...") #enter state 2 ([CONFIG LIST]) elif (line.strip() == states[2]): state = 2 starti = fileIndex #handle special title specialTitle = True writer.writerows([[states[state]], ['Boot Number', 'Date/Time']]) print(f"--Changed State to: {state} w/ special title becasuse of {states[state]}\nExtracting from line {starti}...") #enter state 3 (Process usage summary) elif (line.strip()[:21] == states[3]): #[:21] take the first 21 characters state = 3 processNum = 0 starti = fileIndex #handle special title specialTitle = True writer.writerow([line]) print(f"--Changed State to: {state} w/ special title becasuse of {states[state]}\nExtracting from line {starti}...") #enter state 4 ([Batterystats Collector]) elif (line.strip() == states[4]): state = 4 processNum = 0 starti = fileIndex #handle special title specialTitle = True writer.writerow([line]) print(f"--Changed State to: {state} w/ special title becasuse of {states[state]}\nExtracting from line {starti}...") #enter state 5 (Daily Summary) elif (line.strip() == states[5]): state = 5 processNum = 0 starti = fileIndex #handle special title specialTitle = True writer.writerow([]) writer.writerow([line]) print(f"--Changed State to: {state} w/ special title becasuse of {states[state]}\nExtracting from line {starti}...") #enter state 6 ([PowerAnomaly Battery Dump]) elif (line.strip() == states[6]): state = 6 processNum = 0 starti = fileIndex #handle special title specialTitle = True writer.writerow([line]) print(f"--Changed State to: {state} w/ special title becasuse of {states[state]}\nExtracting from line {starti}...") #enter state 7 (Anomaly List For DeviceCare) elif (line.strip() == states[7]): state = 7 processNum = 0 starti = fileIndex #handle special title specialTitle = True writer.writerow([]) writer.writerow([line]) print(f"--Changed State to: {state} w/ special title becasuse of {states[state]}\nExtracting from line {starti}...") #enter state 8 ([TCPU dump]) elif (line.strip() == states[8]): state = 8 processNum = 0 starti = fileIndex #handle special title specialTitle = True writer.writerow([]) writer.writerow([line]) print(f"--Changed State to: {state} w/ special title becasuse of {states[state]}\nExtracting from line {starti}...") #enter state 9 ([UCPU dump]) elif (line.strip() == states[9]): state = 9 processNum = 0 starti = fileIndex #handle special title specialTitle = True writer.writerow([]) writer.writerow([line]) print(f"--Changed State to: {state} w/ special title becasuse of {states[state]}\nExtracting from line {starti}...") #enter state 10 (------ NETWORK DEV INFO (/proc/net/dev) ------ ) elif (line.strip() == states[10]): state = 10 starti = fileIndex #handle special title specialTitle = True writer.writerow([line]) print(f"--Changed State to: {state} w/ special title becasuse of {states[state]}\nExtracting from line {starti}...") #enter state 11 (------ MEMORY INFO (/proc/meminfo) ------ ) elif(line.strip() == states[11]): state = 11 processNum = 0 starti = fileIndex #handle special title specialTitle = True writer.writerow([line]) print(f"--Changed State to: {state} w/ special title becasuse of {states[state]}\nExtracting from line {starti}...") #enter state 12 (------ VIRTUAL MEMORY STATS (/proc/vmstat) ------) elif(line.strip() == states[12]): state = 12 processNum = 0 starti = fileIndex #handle special title specialTitle = True writer.writerow([line]) print(f"--Changed State to: {state} w/ special title becasuse of {states[state]}\nExtracting from line {starti}...") ''' #enter state 13 (** MEMINFO in pid[com.x3AM.Innovations.Flare.Mobile.App] **) elif(line.strip()[:17] == states[13][:17] and re.search('[com.x3AM.Innovations.Flare.Mobile.App]', line)==True): state = 13 processNum = 0 starti = fileIndex #handle special title specialTitle = True writer.writerow([line]) print(f"--Changed State to: {state} w/ special title becasuse of {states[state]}\nExtracting from line {starti}...") ''' #debug info #print(f"fileIndex: {fileIndex} | i: {i} | state: {state}") #///////////////////////////////////////////////////////////////////// #PERFORM STATE ACTIONS---------------------------------------------------- #extract MARS (state 1) if(state == 1): #when done, set state to inactive if(line.strip() == ''): state = 0 print(f"--Reverted State to {state} at {fileIndex}--\n") writer.writerow([]) data = line.split() #extract CONFIG LIST (state 2) if(state == 2): #when done, set state to inactive if(line.strip() == ''): state = 0 print(f"--Reverted State to {state} at {fileIndex}--\n") writer.writerow(['']) #close special title if(fileIndex!=starti and specialTitle): specialTitle = False if(debug): print(f"Ended specialTitle at line {fileIndex}") if(not specialTitle and state!=0): raw = line.split() data[0] = (raw[0]) data.append(f"{raw[1]} {raw[2]} ") #extract power usage summary (state 3) if(state == 3): #finish at end flag if(line.strip() == 'SSRM MEMORY DUMP **********'): state = 0 print(f"--Reverted State to {state} at {fileIndex}--\n") writer.writerow([]) #close special title if(fileIndex!=starti and specialTitle): specialTitle = False if(debug): print(f"Ended specialTitle at line {fileIndex}") #take usage title if(processNum!=1 and line[0] == '[' and state!=0): processNum = 1 #collect data for usage title if(processNum == 1 and state!=0): data = line.split('|') for elem in data: elem = elem.strip() #mark new usage title if(line.strip() == '' and state!=0): processNum = 0 #extract Batterystats (state 4) if(state == 4): trimmed = line.strip() #finish will finish when state is changed at 'set state' level #close special title if(fileIndex!=starti and specialTitle): specialTitle = False if(debug): print(f"Ended specialTitle at line {fileIndex}") #mark new usage title if(line.strip() == '' and state==4): processNum = 0 #set process if(trimmed != '' and line[0] == 'S' and state==4): processNum = 3 if(trimmed != '' and line[2] == 'U' and state==4): processNum = 2 if(trimmed != '' and processNum == 2 and line[2] == ' '): processNum = 2 if(trimmed != '' and processNum != 2 and line[0] == ' ' and state==4): processNum = 1 #collect prelim data for usage (process 1) if(processNum == 1 and state==4): data = line.split(":") for elem in data: elem = elem.strip() #collect data for usage title (process 2) if(processNum == 2 and state==4): data = line.split('|') for elem in data: elem = elem.strip() #collect title if(processNum == 3 and state==4): raw = line.split() data[0] = f"{raw[2]} {raw[3]}" data.append(f"{raw[5]} {raw[6]}") #extract Daily Summary (state 5) if(state == 5): #finish at end flag if(line.strip() == ''): state = 0 print(f"--Reverted State to {state} at {fileIndex}--\n") writer.writerow([]) #close special title if(fileIndex>starti+1 and specialTitle and specialTitle): specialTitle = False if(debug): print(f"Ended specialTitle at line {fileIndex}") #parse data data = line.split('|') for elem in data: elem = elem.strip() #extract PowerAnomaly Battery Dump (state 6) if(state == 6): #close special title if(fileIndex>starti and specialTitle and state == 6): specialTitle = False if(debug): print(f"Ended specialTitle at line {fileIndex}") #finish at next title if(line[:3] == '[Ba'): state = 0 print(f"--Reverted State to {state} at {fileIndex}--\n") writer.writerow([]) if(state == 6): data = line.strip() #extract Anomaly List For DeviceCare (state 7) if(state == 7): #finish parsing after second null line if(line.strip() == '' and processNum == 2): state = 0 print(f"--Reverted State to {state} at {fileIndex}--\n") writer.writerow([]) #next process after null line if(line.strip() == '' and state == 7): processNum = 1 print(f"Process Number has been changed to {processNum} at line {fileIndex}") #close special title if(fileIndex>starti and specialTitle): specialTitle = False if(debug): print(f"Ended specialTitle at line {fileIndex}") #parse data by default if(processNum == 0 and state == 7): data = line.split('|') newData = [] for elem in data: elem = elem.strip() newData.append(elem) data = newData #collect stats elif(processNum == 2 and state == 7): data = line.split(':') #print(f"{data[0]} : {data[1]}") #collect stats timestamp elif(line.strip() != '' and processNum == 1): raw = line.split() data[0] = f"{raw[2]} {raw[3]}" data.append(f"{raw[5]} {raw[6]}") processNum = 2 print(f"Process Number has been changed to {processNum} at line {fileIndex}") #extract [TCPU dump] (state 8) if(state == 8): #finish at end flag if(line.strip() == ''): state = 0 print(f"--Reverted State to {state} at {fileIndex}--\n") writer.writerow([]) #close special title if(fileIndex>starti+1 and specialTitle): specialTitle = False if(debug): print(f"Ended specialTitle at line {fileIndex}") #parse data data = line.split('|') for elem in data: elem = elem.strip() #extract [UCPU dump] (state 9) if(state == 9): #finish at end flag if(line.strip() == ''): state = 0 print(f"--Reverted State to {state} at {fileIndex}--\n") writer.writerow([]) #close special title if(fileIndex>starti+1 and specialTitle and specialTitle): specialTitle = False if(debug): print(f"Ended specialTitle at line {fileIndex}") #parse data data = line.split('|') for elem in data: elem = elem.strip() #extract NETWORK DEV INFO (state 10) if(state == 10): #when done, set state to inactive if(line.strip()!='' and line.split()[0] == '------' and not specialTitle): state = 0 print(f"--Reverted State to {state} at {fileIndex}--\n") writer.writerow([]) #close special title if(fileIndex>starti+1 and specialTitle): specialTitle = False if(debug): print(f"Ended specialTitle at line {fileIndex}") #collect data if(state == 10 and not specialTitle): line = line.strip() data = line.split() keep = False for elem in data: if(elem.isnumeric() and int(elem)>10000): keep = True if(not keep): data = [] #extract MEMORY INFO (state 11) if(state == 11): #when done, set state to inactive if(line.strip()!='' and line.split()[0] == '------' and not specialTitle): state = 0 print(f"--Reverted State to {state} at {fileIndex}--\n") writer.writerow([]) #close special title if(fileIndex>starti+1 and specialTitle): specialTitle = False if(debug): print(f"Ended specialTitle at line {fileIndex}") if(line.strip()!='' and not specialTitle and state==11): raw = line.split(':') data[0] = raw[0].strip() data.append(raw[1].strip()) #extract VIRTUAL MEMORY STATS (state 12) if(state == 12): #when done, set state to inactive if(line.strip()!='' and line.split()[0] == '------' and not specialTitle): state = 0 print(f"--Reverted State to {state} at {fileIndex}--\n") writer.writerow([]) #close special title if(fileIndex>starti and specialTitle): specialTitle = False if(debug): print(f"Ended specialTitle at line {fileIndex}") if(line.strip()!='' and not specialTitle and state==11): raw = line.split() data[0] = raw[0].strip() data.append(raw[1].strip()) ''' #extract MEMINFO in pid (state 13) if(state == 13): #when done, set state to inactive if(line.strip()!='' and line.split()[0] == '*' and not specialTitle): state = 0 print(f"--Reverted State to {state} at {fileIndex}--\n") writer.writerow([]) #close special title if(fileIndex>starti and specialTitle): specialTitle = False if(debug): print(f"Ended specialTitle at line {fileIndex}") #collect data if(processNum == 2 and line.strip()!='' and not specialTitle and state==13): data = line.split() for elem in data: elem = elem.strip() #collect title if(processNum == 1): data[0] = line processNum = 2 if(line.strip()=='' and not specialTitle and state==13): processNum = 1 ''' #///////////////////////////////////////////////////////////////////// #output if the state is active (not 0) if(state!=0 and (not specialTitle)): #print(f"writing {data}") isEmpty = True for elem in data: if(elem.strip() != ''): isEmpty = False break if(not isEmpty): writer.writerow(data) elif(debug): print(f"Did not write line {fileIndex} to CSV because data was empty") if(specialTitle and debug): print(f"Did not write line {fileIndex} to CSV because of Special Title") fileIndex += 1 # main inputFiles = os.listdir('INPUT') fileCount = 1 for file in inputFiles: outfile = f"{file.split('.')[0]}-output_{fileCount}.csv" print(f'RUNNING EXTRACT ON [{file}] AND WRITING TO [{outfile}]...') print() extract(f'INPUT\{file}', outfile) print("Exited properly\n") fileCount+=1
ABbuff/DumpstateDataExtraction
Extract.py
Extract.py
py
22,516
python
en
code
0
github-code
6
26257812486
# Imports import sqlalchemy as sa from sqlalchemy.ext.declarative import declarative_base import users from datetime import datetime """ Модуль для поиска атлетов по парамтрам пользователя """ # Variables Base = declarative_base() # Class definitions class Athlette(Base): __tablename__ = "Athelete" id = sa.Column(sa.INTEGER, primary_key=True) age = sa.Column(sa.INTEGER) birthdate = sa.Column(sa.TEXT) gender = sa.Column(sa.TEXT) height = sa.Column(sa.REAL) name = sa.Column(sa.TEXT) weight = sa.Column(sa.INTEGER) gold_medals = sa.Column(sa.INTEGER) silver_medals = sa.Column(sa.INTEGER) bronze_medals = sa.Column(sa.INTEGER) total_medals = sa.Column(sa.INTEGER) sport = sa.Column(sa.TEXT) country = sa.Column(sa.TEXT) # Function definitions def search_id(id, session): query_str = session.query(Athlette).filter(Athlette.id == id).first() usr = f"{query_str}" return usr def height_compare(id, session, bcolors): """ Сравнение роста атлетов с пользовательским """ # берем из базы рост пользователя usr_query = session.query(users.User).filter(users.User.id == id).first() usr_height = usr_query.height # ищем атлетов по росту пользователя ath_query = session.query(Athlette).filter( Athlette.height == usr_height) ath_count = ath_query.count() ath_found = ath_query.all() # выводим содержимое объектов Athlete, если найдены res = "" if ath_found: for ath in ath_found: res += f" {ath.name}, {ath.sport} \n" res = f"{res}\n Всего атлетов с ростом {ath.height} метра: {ath_count}" else: print(bcolors.FAIL + f"\nERROR: Атлет с ростом {usr_height}m не найден" + bcolors.ENDC) return res def bday_compare(id, session): """ Ищем атлета, наиболее близкого по дате рождения к пользователю """ dt_format = '%Y-%m-%d' usr_query = session.query(users.User).filter(users.User.id == id).first() user_bday_str = usr_query.birthdate user_bday_dt_obj = datetime.strptime(user_bday_str, dt_format) ath_query_all_obj = session.query(Athlette).all() ath_bday_all_dt_list = list() for ath in ath_query_all_obj: ath_bday_all_dt_list.append( datetime.strptime(ath.birthdate, dt_format)) closest_bday_dt_obj = ath_bday_all_dt_list[min(range(len(ath_bday_all_dt_list)), key=lambda i: abs(ath_bday_all_dt_list[i]-user_bday_dt_obj))] # выбираем всех атлетов по самой ближней дате рождения closest_bday_str = closest_bday_dt_obj.strftime(dt_format) ath_query_bday_query = session.query(Athlette).filter( Athlette.birthdate == closest_bday_str) # берем из базы данные и считаем ath_bday_obj = ath_query_bday_query.all() ath_bday_count = ath_query_bday_query.count() # формируем возврат res = "" for ath in ath_bday_obj: res = f"{res}\n {ath.name}, д.р.: {ath.birthdate}, {ath.sport}" return res if __name__ == "__main__": print("ERROR: Запуск скрипта через выполнение модуля start.py \n") # DEBUG # print('Info: Module find_athlete.py - imported')
vsixtynine/sf-sql-task
find_athlete.py
find_athlete.py
py
3,609
python
ru
code
0
github-code
6
9324466807
from flask import Blueprint, render_template, url_for lonely = Blueprint('lonely', __name__, template_folder='./', static_folder='./', static_url_path='/') lonely.display_name = 'Lonely' lonely.published = True lonely.description = "An interactive visualization of original music." @lonely.route('/') def _lonely(): return render_template('lonely.html')
connerxyz/exhibits
cxyz/exhibits/lonely/lonely.py
lonely.py
py
437
python
en
code
0
github-code
6
21881174301
from selenium import webdriver from selenium.webdriver.common.by import By import time import os try: link = "http://suninjuly.github.io/file_input.html" browser = webdriver.Chrome() browser.get(link) elements = browser.find_elements(By.CSS_SELECTOR, ".form-control") for element in elements: if element.get_attribute('required') != None: element.send_keys("Мой ответ") print(os.getcwd()) current_dir = os.path.realpath(os.path.dirname(__file__)) file_path = os.path.join(current_dir, 'file.txt') print(file_path) element = browser.find_element(By.CSS_SELECTOR, "#file") element.send_keys(file_path) button = browser.find_element(By.CSS_SELECTOR, "button.btn") button.click() finally: # ожидание чтобы визуально оценить результаты прохождения скрипта time.sleep(10) # закрываем браузер после всех манипуляций browser.quit()
Mayurityan/stepik_auto_tests_course
lesson 2.2 send file form.py
lesson 2.2 send file form.py
py
1,034
python
ru
code
0
github-code
6
11951082453
def convert_ascii(letter): result = ord(letter) return result def convert_binary(num): result = bin(num) return result def menu(): print("=============\nMenu\n=============\n 1. Character\n 2. Word") option = int(input("Please select an option to convert into binary: ")) if option == 1: chosenLetter = input("Write the letter: ") ascii_num = convert_ascii(chosenLetter) print("=============\nResults\n=============\n") print( "ASCII character value of", chosenLetter, "is", ascii_num , "and representation of", chosenLetter, "in a byte is", convert_binary(ascii_num) ) elif option == 2: chosenWord = input("Write the word: ") binaryWord = [] print("=============\nResults\n=============\n") for i in chosenWord: ascii_num = convert_ascii(i) convertion = convert_binary(ascii_num) print( "ASCII character value of", i, "is", ascii_num , "and representation of", i, "in a byte is", convertion ) binaryWord.append(convertion) print(" ".join(binaryWord)) else: exit() menu()
Juanjo2354/EvaluacionFinal
convertBinary.py
convertBinary.py
py
1,250
python
en
code
0
github-code
6
70713803708
import re import os import sys import nltk import json import wandb import joblib import datasets import numpy as np import pandas as pd from time import process_time from nltk import word_tokenize from nltk.stem import WordNetLemmatizer from sklearn.svm import LinearSVC from sklearn.pipeline import make_pipeline from sklearn.feature_extraction.text import TfidfVectorizer np.random.seed(42) class LemmaTokenizer: ignore_tokens = [',', '.', ';', ':', '"', '``', "''", '`'] def __init__(self): self.wnl = WordNetLemmatizer() def __call__(self, doc): return [self.wnl.lemmatize(t) for t in word_tokenize(doc) if t not in self.ignore_tokens] def prepare_dataset(data_folder, label2id, data_types, max_length): def combine_data(example): temp_text = "" for data_type in data_types: temp_text += example[data_type] + " " example["text"] = temp_text[:max_length] return example dataset = datasets.load_from_disk(data_folder + "dataset/") dataset = dataset["train"] dataset_encoded = dataset.class_encode_column("category") dataset_aligned = dataset_encoded.align_labels_with_mapping(label2id, "category") dataset_cleaned = dataset_aligned.map(combine_data) dataset = dataset_cleaned.remove_columns(["title", "body"]) dataset = dataset.rename_column("category", "label") return dataset def main(): hps = { "data_types": ["title", "body"], "loss_function": "squared_hinge", "ngram_range": 3, "max_length": 512, } wandb_id = wandb.util.generate_id() run = wandb.init( project="DMOZ-classification", config=hps, job_type="training", name="SVM_DMOZ_" + str(wandb_id), tags=["SVM", "DMOZ"], ) data_folder = "/ceph/csedu-scratch/other/jbrons/thesis-web-classification/" id2label = {0: "Arts", 1: "Business", 2: "Computers", 3: "Health", 4: "Home", 5: "News", 6: "Recreation", 7: "Reference", 8: "Science", 9: "Shopping", 10: "Society", 11: "Sports", 12: "Games"} label2id = {v: k for k, v in id2label.items()} labels = label2id.keys() dataset = prepare_dataset(data_folder, label2id, hps["data_types"], hps["max_length"]) X_train, y_train = dataset["text"], dataset["label"] tokenizer=LemmaTokenizer() pipeline = make_pipeline( TfidfVectorizer( ngram_range=(1, hps["ngram_range"]), tokenizer=tokenizer, token_pattern=None ), LinearSVC(loss=hps["loss_function"]) ) t0 = process_time() pipeline.fit(X_train, y_train) training_time = process_time() - t0 print("Training time {:5.2f}s for {:0d} samples.".format(training_time, len(y_train))) run.summary["training_time"] = training_time filename = data_folder + "models/SVM/model.pkl" joblib.dump(pipeline, filename, compress=3) model_artifact = wandb.Artifact( name="model_SVM_DMOZ", type="model" ) model_artifact.add_file(thesis_folder + "models/SVM/model.pkl") run.log_artifact(model_artifact) if __name__ == "__main__": main()
JesseBrons/Webpageclassification
training/train_model_SVM.py
train_model_SVM.py
py
3,173
python
en
code
1
github-code
6
27483903677
from django.shortcuts import render, redirect from django.contrib import messages from .models import User from .forms import RegisterForm, LoginForm from .utils import require_login def login_page(request): context = {"reg_form": RegisterForm(), "login_form": LoginForm()} return render(request, "users/login.html", context) def login(request): curr_user = User.user_manager.login(request.POST["email_address"], request.POST["password"]) if not curr_user: messages.error(request, "E-mail or password incorrect") return redirect("login_page") else: request.session["curr_user"] = curr_user.id return redirect("dashboard") def register(request): registered, guy_or_errors = User.user_manager.register(request.POST) if not registered: for error in guy_or_errors: messages.error(request, error) return redirect("login_page") else: request.session["curr_user"] = guy_or_errors.id return redirect("dashboard") def log_off(request): request.session.clear() return redirect("login_page") @require_login def dashboard(request, curr_user): context = { "curr_user": curr_user, "users": User.user_manager.all(), } return render(request, "users/dashboard.html", context) @require_login def show(request, curr_user, id): print("show page") context = { "curr_user": curr_user, "user": User.user_manager.get(id=id), } return render(request, "users/show.html", context) @require_login def edit(request, curr_user, id): context = { "curr_user": curr_user, "user": User.user_manager.get(id=id), } return render(request, "users/edit.html", context) @require_login def update(request, curr_user, id): # Logic to check if curr_user is admin or user being updated if not (curr_user.admin or curr_user.id == int(id)): print(curr_user.id, id, curr_user.id == id) return redirect("/dashboard") # Logic to actually update errors = User.user_manager.update(id, request.POST) if errors: for error in errors: messages.error(request, error) return redirect("edit", id=id) else: return redirect("show", id=id)
madjaqk/django_user_dashboard
apps/users/views.py
views.py
py
2,061
python
en
code
0
github-code
6
35164165716
#!/usr/bin/python3 import subprocess import json import requests import time import logging import os #bin Paths ipfspath = '/usr/local/bin/ipfs' wgetpath = '/usr/bin/wget' wcpath = '/usr/bin/wc' #Basic logging to ipfspodcastnode.log logging.basicConfig(format="%(asctime)s : %(message)s", datefmt="%Y-%m-%d %H:%M:%S", filename="ipfspodcastnode.log", filemode="w", level=logging.INFO) #Create an empty email.cfg (if it doesn't exist) if not os.path.exists('cfg/email.cfg'): with open('cfg/email.cfg', 'w') as ecf: ecf.write('') #Init IPFS (if necessary) if not os.path.exists('ipfs/config'): logging.info('Initializing IPFS') ipfs_init = subprocess.run(ipfspath + ' init', shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) #Start WebUI import webui logging.info('Starting Web UI') #Automatically discover relays and advertise relay addresses when behind NAT. swarmnat = subprocess.run(ipfspath + ' config --json Swarm.RelayClient.Enabled true', shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) #Start IPFS daemon = subprocess.run(ipfspath + ' daemon >/dev/null 2>&1 &', shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) logging.info('Starting IPFS Daemon') time.sleep(10) #Get IPFS ID with open('ipfs/config', 'r') as ipcfg: ipconfig = ipcfg.read() jtxt = json.loads(ipconfig) logging.info('IPFS ID : ' + jtxt['Identity']['PeerID']) #Main loop while True: #Request payload payload = { 'version': 0.6, 'ipfs_id': jtxt['Identity']['PeerID'] } #Read E-mail Config with open('cfg/email.cfg', 'r') as ecf: email = ecf.read() if email == '': email = '[email protected]' payload['email'] = email #Check if IPFS is running, restart if necessary. payload['online'] = False diag = subprocess.run(ipfspath + ' diag sys', shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) if diag.returncode == 0: ipfs = json.loads(diag.stdout) payload['ipfs_ver'] = ipfs['ipfs_version'] payload['online'] = ipfs['net']['online'] if payload['online'] == False: #Start the IPFS daemon daemon = subprocess.run(ipfspath + ' daemon >/dev/null 2>&1 &', shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) logging.info('@@@ IPFS NOT RUNNING !!! Restarting Daemon @@@') #Get Peer Count peercnt = 0 speers = subprocess.run(ipfspath + ' swarm peers|wc -l', shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) if speers.returncode == 0: peercnt = speers.stdout.decode().strip() payload['peers'] = peercnt #Request work logging.info('Requesting Work...') try: response = requests.post("https://IPFSPodcasting.net/Request", timeout=120, data=payload) work = json.loads(response.text) logging.info('Response : ' + str(work)) except requests.RequestException as e: logging.info('Error during request : ' + str(e)) work = { 'message': 'Request Error' } if work['message'] == 'Request Error': logging.info('Error requesting work from IPFSPodcasting.net (check internet / firewall / router).') elif work['message'][0:7] != 'No Work': if work['download'] != '' and work['filename'] != '': logging.info('Downloading ' + str(work['download'])) #Download any "downloads" and Add to IPFS (1hr48min timeout) try: hash = subprocess.run(wgetpath + ' -q --no-check-certificate "' + work['download'] + '" -O - | ' + ipfspath + ' add -q -w --stdin-name "' + work['filename'] + '"', shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=6500) hashcode = hash.returncode except subprocess.SubprocessError as e: logging.info('Error downloading/pinning episode : ' + str(e)) hashcode = 99 if hashcode == 0: #Get file size (for validation) downhash=hash.stdout.decode().strip().split('\n') size = subprocess.run(ipfspath + ' cat ' + downhash[0] + ' | ' + wcpath + ' -c', shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) downsize=size.stdout.decode().strip() logging.info('Added to IPFS ( hash : ' + str(downhash[0]) + ' length : ' + str(downsize) + ')') payload['downloaded'] = downhash[0] + '/' + downhash[1] payload['length'] = downsize else: payload['error'] = hashcode if work['pin'] != '': #Directly pin if already in IPFS logging.info('Pinning hash (' + str(work['pin']) + ')') try: pin = subprocess.run(ipfspath + ' pin add ' + work['pin'], shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=6500) pincode = pin.returncode except subprocess.SubprocessError as e: logging.info('Error direct pinning : ' + str(e)) #Clean up any other pin commands that may have spawned cleanup = subprocess.run('kill `ps aux|grep "ipfs pin ad[d]"|awk \'{ print $2 }\'`', shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) pincode = 98 if pincode == 0: #Verify Success and return full CID & Length pinchk = subprocess.run(ipfspath + ' ls ' + work['pin'], shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) if pinchk.returncode == 0: hashlen=pinchk.stdout.decode().strip().split(' ') payload['pinned'] = hashlen[0] + '/' + work['pin'] payload['length'] = hashlen[1] else: payload['error'] = pinchk.returncode else: payload['error'] = pincode if work['delete'] != '': #Delete/unpin any expired episodes logging.info('Unpinned old/expired hash (' + str(work['delete']) + ')') delete = subprocess.run(ipfspath + ' pin rm ' + work['delete'], shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) payload['deleted'] = work['delete'] #Report Results logging.info('Reporting results...') #Get Usage/Available repostat = subprocess.run(ipfspath + ' repo stat -s|grep RepoSize', shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) if repostat.returncode == 0: repolen = repostat.stdout.decode().strip().split(':') used = int(repolen[1].strip()) else: used = 0 payload['used'] = used df = os.statvfs('/') payload['avail'] = df.f_bavail * df.f_frsize try: response = requests.post("https://IPFSPodcasting.net/Response", timeout=120, data=payload) except requests.RequestException as e: logging.info('Error sending response : ' + str(e)) else: logging.info('No work.') #wait 10 minutes then start again logging.info('Sleeping 10 minutes...') time.sleep(600)
Cameron-IPFSPodcasting/podcastnode-Umbrel
ipfspodcastnode.py
ipfspodcastnode.py
py
6,566
python
en
code
4
github-code
6
33729704432
from flask_app import app, db, render_template, request, redirect, bcrypt, session, flash, url_for, EMAIL_REGEX, verify_logged_in, datetime, timedelta from models import User, Movie, Post, Comment, favorites, post_likes, comment_likes, faved @app.route('/') def index(): upms = db.session.query(User, Post, Movie).select_from(User).join( Post).join(Movie).where(Post.user_id == User.id and Post.movie_id == Movie.id).order_by(Post.created_at.desc()).all() # Set post timestamp for upm in upms: delta = (datetime.now() - upm[1].created_at) seconds = delta.seconds minutes = f"{seconds//60} min. ago" hours = f"{seconds//3600} hr. ago" days = f"{delta.days} d. ago" weeks = f"{delta.days//7} wk. ago" for unit in [weeks, days, hours, minutes]: if int(unit[:1]) > 0: upm[1].time_since = unit break return render_template('feed.html', upms=upms, truncate=True, title='Main Feed | ReDirector') @app.route('/registration', methods=['POST', 'GET']) def register(): if request.method == 'POST': if not User.validate_user(request.form): return redirect('/registration') user = User( request.form['username'], bcrypt.generate_password_hash(request.form['password']), request.form['email'], request.form['first_name'], request.form['last_name'] ) db.session.add(user) db.session.commit() user = User.query.filter_by( email=request.form['email']).first() session['firt_name'] = user.first_name session['user_id'] = user.id session['username'] = user.username print( f"Logged in {session['first_name']} with ID {session['user_id']}") return redirect('/') else: return render_template('registration.html') @app.route('/login', methods=['POST', 'GET']) def login(): if request.method == 'POST': # check if user used email to login if EMAIL_REGEX.match(request.form['username_email']): # check if email is in database user_in_db = User.query.filter_by( email=request.form['username_email']).first() else: # check if username is in database user_in_db = User.query.filter_by( username=request.form['username_email']).first() if not user_in_db: flash('Invalid Username/Email', 'username_email') return redirect('/login') # check password against stored hash if not bcrypt.check_password_hash(user_in_db.password, request.form['log_password']): flash('Invalid Password', 'log_password') return redirect('/login') # email and password are valid session['first_name'] = user_in_db.first_name session['user_id'] = user_in_db.id session['username'] = user_in_db.username print( f"Logged in {session['username']} ({session['first_name']})") return redirect(request.form['last_route']) else: return render_template('login.html', last_route=request.referrer) @app.route('/logout') def logout(): print(f"Logged out {session['username']} ({session['first_name']})") session.pop('user_id', None) session.pop('first_name', None) session.pop('username', None) return redirect(request.referrer)
cmderobertis/ReDirector
flask_app/controllers/users.py
users.py
py
3,467
python
en
code
0
github-code
6
3508455471
#!/usr/bin/env python3 import numpy as np import operator if __name__ == "__main__": log = None for l in open('3-input'): *l, = map(int, l.strip()) if log is None: log = np.ndarray((1, len(l)), dtype=int) log[0] = l else: log = np.vstack([log, l]) gamma = np.mean(log, axis=0) >= 0.5 epsilon = np.mean(log, axis=0) <= 0.5 part1 = int(''.join(np.char.mod('%d', gamma)), 2) * \ int(''.join(np.char.mod('%d', epsilon)), 2) print('part1', part1) def filter(log: np.array, most: bool): c = 0 while len(log) != 1 and c < len(log[0]): thres = np.mean(log[:, c], axis=0) >= 0.5 if most: log = log[log[:, c] == thres] else: log = log[log[:, c] != thres] c += 1 assert len(log) == 1 return int(''.join(np.char.mod('%d', log[0])), 2) CO2 = filter(np.copy(log), True) O = filter(np.copy(log), False) part2 = O * CO2 print('part2', part2)
pboettch/advent-of-code
2021/3.py
3.py
py
1,069
python
en
code
1
github-code
6
30367917171
"""Tutorial 8. Putting two plots on the screen This tutorial sets up for showing how Chaco allows easily opening multiple views into a single dataspace, which is demonstrated in later tutorials. """ from scipy import arange from scipy.special import jn from enable.api import ComponentEditor from traits.api import HasTraits, Instance from traitsui.api import Item, View from chaco.api import create_line_plot, HPlotContainer from chaco.tools.api import PanTool class PlotExample(HasTraits): container = Instance(HPlotContainer) traits_view = View( Item( "container", editor=ComponentEditor(), show_label=False, width=800, height=600, ), title="Chaco Tutorial", ) def _container_default(self): x = arange(-5.0, 15.0, 20.0 / 100) y = jn(0, x) left_plot = create_line_plot( (x, y), bgcolor="white", add_grid=True, add_axis=True ) left_plot.tools.append(PanTool(left_plot)) self.left_plot = left_plot y = jn(1, x) right_plot = create_line_plot( (x, y), bgcolor="white", add_grid=True, add_axis=True ) right_plot.tools.append(PanTool(right_plot)) right_plot.y_axis.orientation = "right" self.right_plot = right_plot # Tone down the colors on the grids right_plot.hgrid.line_color = (0.3, 0.3, 0.3, 0.5) right_plot.vgrid.line_color = (0.3, 0.3, 0.3, 0.5) left_plot.hgrid.line_color = (0.3, 0.3, 0.3, 0.5) left_plot.vgrid.line_color = (0.3, 0.3, 0.3, 0.5) container = HPlotContainer(spacing=20, padding=50, bgcolor="lightgray") container.add(left_plot) container.add(right_plot) return container demo = PlotExample() if __name__ == "__main__": demo.configure_traits()
enthought/chaco
examples/tutorials/tutorial8.py
tutorial8.py
py
1,873
python
en
code
286
github-code
6
42937022866
import datetime import sqlite3 import os import sys from PyQt6.QtWidgets import * from PyQt6.QtCore import Qt from docxtpl import DocxTemplate class mailbackGenWindow(QMainWindow): def __init__(self): super().__init__() self.setWindowTitle("Test Mailback Letter Generator") self.setFixedSize(722, 479) main_layout = QVBoxLayout() self.db = sqlite3.connect("test_mailback.db") self.cur = self.db.cursor() client_label = QLabel("Select Client: ") self.client_select = QComboBox() self.populateClientSelect() def setAndGet(): self.getDefaultAddress() self.setDefaultAddress() self.client_select.currentIndexChanged.connect(setAndGet) reason_label = QLabel("Select All Reasons for Return ") self.reason_select = QFrame() self.reason_layout = QGridLayout() self.reasonCheckBoxList = [] self.address1 = QLineEdit() self.address1.setFixedWidth(200) self.address2 = QLineEdit() self.address2.setFixedWidth(200) self.address3 = QLineEdit() self.address3.setFixedWidth(200) self.clear_address_button = QPushButton("Clear Address") self.clear_address_button.clicked.connect(self.clearAddress) self.default_address_button = QPushButton("Default") self.default_address_button.clicked.connect(self.setDefaultAddress) self.populateReasonLayout() self.reason_select.setLayout(self.reason_layout) self.reason_error = QLabel("Please select at least one reason.") self.reason_error.setStyleSheet("color: red") self.reason_error.hide() self.envelope_button = QPushButton("Generate Envelope") self.envelope_button.clicked.connect(self.printEnvelope) self.large_envelope_button = QPushButton("Large Envelope Sheet") self.large_envelope_button.clicked.connect(self.printLargeEnvelope) self.submit_button = QPushButton("Generate Letter") self.submit_button.clicked.connect(self.generateLetter) widgets = [client_label, self.client_select, reason_label, self.reason_select, self.reason_error, self.submit_button, self.envelope_button, self.large_envelope_button] for w in widgets: main_layout.addWidget(w) widget = QWidget() widget.setLayout(main_layout) # Set the central widget of the Window. Widget will expand # to take up all the space in the window by default. self.setCentralWidget(widget) self.template = DocxTemplate("test_mailback_template.docx") self.envelope = DocxTemplate("mailout.docx") self.big_envelope = DocxTemplate("large envelope template.docx") self.current_date = datetime.date.today().strftime('%m/%d/%Y') self.currentClient = "" self.currentAddr1 = "" self.currentAddr2 = "" self.currentPhoneNumber = "" self.getDefaultAddress() self.setDefaultAddress() def populateClientSelect(self): tups = self.cur.execute("""SELECT query_name FROM client ORDER BY query_name ASC;""") clients = [name for t in tups for name in t] self.client_select.addItems(clients) def getDefaultAddress(self): client_name = self.client_select.currentText() client_row = self.cur.execute("""SELECT full_name, address, phone_number FROM client WHERE query_name = ?""", (client_name,)) self.currentClient, full_addr, self.currentPhoneNumber = [c for t in client_row for c in t] self.currentAddr1, self.currentAddr2 = full_addr.split('*') def setDefaultAddress(self): self.address1.setText(self.currentClient) self.address2.setText(self.currentAddr1) self.address3.setText(self.currentAddr2) def clearAddress(self): self.address1.clear() self.address2.clear() self.address3.clear() def populateReasonLayout(self): reasonTypes = self.cur.execute("""SELECT DISTINCT type FROM mailback_reason;""") reasonTypes = [t for rt in reasonTypes for t in rt] print(reasonTypes) column = 0 row = 0 for t in reasonTypes: if column == 2: column = 0 row += 1 frame = QFrame() layout = QVBoxLayout() layout.addWidget(QLabel(t + ':')) reasons = self.cur.execute("""SELECT reason FROM mailback_reason WHERE type = ?;""", (t,)) reasons = [r for rt in reasons for r in rt] for r in reasons: box = QCheckBox(r) self.reasonCheckBoxList.append(box) layout.addWidget(box) frame.setLayout(layout) self.reason_layout.addWidget(frame, column, row, Qt.AlignmentFlag.AlignTop) column += 1 if column == 2: column = 0 row += 1 frame = QFrame() layout = QGridLayout() layout.addWidget(QLabel('Name:'), 0, 0, Qt.AlignmentFlag.AlignLeft) layout.addWidget(self.address1, 0, 1, Qt.AlignmentFlag.AlignLeft) layout.addWidget(QLabel('Address:'), 1, 0, Qt.AlignmentFlag.AlignLeft) layout.addWidget(self.address2, 1, 1, Qt.AlignmentFlag.AlignLeft) layout.addWidget(QLabel('City/State/Zip:'), 2, 0, Qt.AlignmentFlag.AlignLeft) layout.addWidget(self.address3, 2, 1, Qt.AlignmentFlag.AlignLeft) layout.addWidget(self.clear_address_button, 3, 0, Qt.AlignmentFlag.AlignLeft) layout.addWidget(self.default_address_button, 3, 1, Qt.AlignmentFlag.AlignLeft) frame.setLayout(layout) self.reason_layout.addWidget(frame, column, row, Qt.AlignmentFlag.AlignLeft) def generateLetter(self): #FOR SETTING FIXED WIDTH/HEIGHT #print(self.width()) #print(self.height()) # avoids Microsoft Word opening dialog box saying that letter.docx caused error if os.path.exists("letter.docx"): os.remove("letter.docx") reasons = [] for box in self.reasonCheckBoxList: if box.isChecked(): reasons.append(box.text()) box.setChecked(False) reason = "" rlength = len(reasons) if rlength == 1: reason = reasons[0] elif rlength == 2: reason = reasons[0] + ' and ' + reasons[1] elif rlength > 2: for i in range(0, rlength): if i != rlength - 1: reason += reasons[i] + ', ' else: reason += 'and ' + reasons[i] else: # reasons is empty self.reason_error.show() return 1 self.reason_error.hide() self.submit_button.setEnabled(False) fill_in = {"date": self.current_date, "client": self.currentClient, "reason": reason, "address_1": self.currentAddr1, "address_2": self.currentAddr2, "phone_number": self.currentPhoneNumber } self.template.render(fill_in) self.template.save('letter.docx') os.startfile("letter.docx", "print") self.submit_button.setEnabled(True) def printEnvelope(self): self.envelope_button.setEnabled(False) fill_in = {"client": self.address1.text(), "addr_1": self.address2.text(), "addr_2": self.address3.text()} self.envelope.render(fill_in) self.envelope.save('envelope.docx') os.startfile("envelope.docx", "print") self.envelope_button.setEnabled(True) def printLargeEnvelope(self): self.large_envelope_button.setEnabled(False) fill_in = {"client": self.address1.text(), "addr_1": self.address2.text(), "addr_2": self.address3.text()} self.big_envelope.render(fill_in) self.big_envelope.save('big_envelope.docx') os.startfile("big_envelope.docx", "print") self.large_envelope_button.setEnabled(True) def main(): app = QApplication(sys.argv) window = mailbackGenWindow() window.show() app.exec() if __name__ == "__main__": main()
Centari2013/PublicMailbackGeneratorTest
main.py
main.py
py
8,527
python
en
code
0
github-code
6
41958018958
from waterworld.waterworld import env as custom_waterworld from potential_field.potential_field_policy import PotentialFieldPolicy from utils import get_frames from pettingzoo.utils import average_total_reward from multiprocessing import Pool, cpu_count import tqdm import numpy as np from matplotlib import pyplot as plt import json n_coop_options = [1, 2] n_sensor_options = [1, 2, 5, 20, 30] angle_options = [("randomize_angle",False),("randomize_angle",True), ("spin_angle",0),("spin_angle",0.1),("spin_angle",0.5),("spin_angle",1)] obs_weighting_options=[1, 0.5] poison_weighting_options=[1, 0.5] barrier_weighting_options=[1, 0.5] food_weighting_options=[1, 0.5] def test_policy(config, rounds=100): env = custom_waterworld(**config["env_config"]) policy = PotentialFieldPolicy(**config["potential_field_config"]).get_movement_vector for i in tqdm.tqdm(range(rounds)): reward_sum, frame_list = get_frames(env, policy) config["rewards"].append(reward_sum) env.close() with open(f"potential_field/test_main/{config['config_index']}.json", "x") as f: json.dump(config, f, indent=4) def get_configs(): configs = [] i=0 for n_coop in n_coop_options: for n_sensor in n_sensor_options: for angle_config in angle_options: configs.append({"env_config": {"n_coop": n_coop,"n_sensors": n_sensor,}, "potential_field_config":{ "n_sensors": n_sensor, angle_config[0]: angle_config[1], }, "rewards": [], "config_index": i }) i += 1 for obs_weight in obs_weighting_options: for poison_weight in poison_weighting_options: for barrier_weight in barrier_weighting_options: for food_weight in food_weighting_options: configs.append({"env_config": {"n_coop": n_coop,"n_sensors": 30,}, "potential_field_config":{ "n_sensors": 30, "obs_weight": obs_weight, "poison_weight": poison_weight, "barrier_weight": barrier_weight, "food_weight": food_weight }, "rewards": [], "config_index": i }) i += 1 return configs def get_main_configs(): configs = [] i=0 for n_coop in n_coop_options: for n_sensor in n_sensor_options: for angle_config in angle_options: configs.append({"env_config": {"n_coop": n_coop,"n_sensors": n_sensor,}, "potential_field_config":{ "n_sensors": n_sensor, angle_config[0]: angle_config[1], }, "rewards": [], "config_index": i }) i += 1 return configs def get_env_configs(): configs = [] i=0 for n_coop in n_coop_options: for n_sensor in n_sensor_options: configs.append({"env_config": {"n_coop": n_coop,"n_sensors": n_sensor,}, "rewards": [], "config_index": i }) i += 1 return configs def test_random_env(config, rounds=100): env = custom_waterworld(**config["env_config"]) action_space = env.action_space("pursuer_0") def policy(obs): return action_space.sample() for i in tqdm.tqdm(range(rounds)): reward_sum, frame_list = get_frames(env, policy) config["rewards"].append(reward_sum) env.close() with open(f"potential_field/test_random/{config['config_index']}.json", "x") as f: json.dump(config, f, indent=4) if __name__ == "__main__": configs = get_env_configs() with Pool(processes=int(cpu_count() - 2)) as pool: for _ in tqdm.tqdm(pool.imap_unordered(test_random_env, configs), total=len(configs)): pass
ezxzeng/syde750_waterworld
test_policy.py
test_policy.py
py
4,604
python
en
code
0
github-code
6
32840040688
from scipy.sparse import csr_matrix from .text import WordPieceParser from collections.abc import Mapping, Iterable class RecordVectorMap(Mapping): def __init__(self, records, wp_model_path, vec_format='bag-of-words'): text_parser = WordPieceParser(wp_model_path) self.rec_seq_map, self.record_vecs = self.rec2vecs(records, text_parser, vec_format) def rec2vecs(self, records, text_parser, vec_format): rec_seq_map = {} cols, rows, data = [], [], [] col_dim = 0 if vec_format=='sequence' else text_parser.vocab_size for rec_seq, (rec_id, rec_text) in enumerate(records): rec_seq_map[rec_id] = rec_seq parsed = text_parser.parse(rec_text, parse_format=vec_format) if vec_format=='sequence': if len(parsed)!=0: rows.extend([rec_seq]*len(parsed)) cols.extend(list(range(len(parsed)))) data.extend(parsed) if len(parsed)>col_dim: col_dim = len(parsed) else: for wp_id, tf in parsed.items(): rows.append(rec_seq) cols.append(wp_id) data.append(tf) record_vecs = csr_matrix((data, (rows, cols)), shape=(len(records), col_dim)) return rec_seq_map, record_vecs def __getitem__(self, key): if isinstance(key, str): return self.get_by_seqs(self.rec_seq_map[key]) elif isinstance(key, Iterable): return self.get_by_seqs([self.rec_seq_map[a_key] for a_key in key]) else: raise TypeError('Key must be string (key of record) or iterable (list of key of record).') def get_by_seqs(self, key): if isinstance(key, int): return self.record_vecs[key] elif isinstance(key, Iterable): return self.record_vecs[key] else: raise TypeError('Seqs must be int (seq of record) or iterable (list of seq of record).') def __iter__(self): return iter(self.record_vecs) def __len__(self): return len(self.rec_seq_map)
rmhsiao/CAGNIR
utils/data/record.py
record.py
py
2,182
python
en
code
1
github-code
6
24200508437
# #!/bin/python # # -*- coding: utf8 -*- # import sys # import os # import re #请完成下面这个函数,实现题目要求的功能 #当然,你也可以不按照下面这个模板来作答,完全按照自己的想法来 ^-^ #******************************开始写代码****************************** def pathInZigZagTree(label): """ Args: label: int Return: list[int] """ level = 0 count = 0 while label > count: level += 1 count += 2 ** (level - 1) res = [] while level > 0: res.append(label) index = label2index(level, label) parent_index = (index + 1) // 2 level -= 1 label = index2label(level, parent_index) return res[::-1] def label2index(level, label): """ index 在该层的索引 从1开始 Args: level: int label: int Return: int """ if level % 2 == 0: return 2 ** level - label else: return label - 2 ** (level - 1) + 1 def index2label(level, index): """ index 在该层的索引 从1开始 Args: level: int index: int Return: int """ if level % 2 == 0: return 2 ** level - index else: return 2 ** (level - 1) + index - 1 #******************************结束写代码****************************** if __name__ == "__main__": _label = int(input()) # _label = 14 res = pathInZigZagTree(_label) for res_cur in res: print(str(res_cur))
AiZhanghan/Leetcode
秋招/小米/1/1.py
1.py
py
1,565
python
en
code
0
github-code
6
72531840829
"""Adds column to use scicrunch alternative Revision ID: b60363fe438f Revises: 39fa67f45cc0 Create Date: 2020-12-15 18:26:25.552123+00:00 """ import sqlalchemy as sa from alembic import op # revision identifiers, used by Alembic. revision = "b60363fe438f" down_revision = "39fa67f45cc0" branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.add_column( "group_classifiers", sa.Column("uses_scicrunch", sa.Boolean(), nullable=True, server_default="0"), ) # ### end Alembic commands ### # Applies the default to all query = 'UPDATE "group_classifiers" SET uses_scicrunch=false;' op.execute(query) # makes non nullable # 'ALTER TABLE "group_classifiers" ALTER "uses_scicrunch" SET NOT NULL;' op.alter_column("group_classifiers", "uses_scicrunch", nullable=False) def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_column("group_classifiers", "uses_scicrunch") # ### end Alembic commands ###
ITISFoundation/osparc-simcore
packages/postgres-database/src/simcore_postgres_database/migration/versions/b60363fe438f_adds_column_to_use_scicrunch_alternative.py
b60363fe438f_adds_column_to_use_scicrunch_alternative.py
py
1,066
python
en
code
35
github-code
6
21247913444
import unittest from unittest.mock import patch import os from typing import Optional from dataclasses import dataclass from io import StringIO from ml_project.train_pipeline import run_train_pipeline from ml_project.predict_pipeline import run_predict_pipeline from sklearn.preprocessing import StandardScaler from ml_project.entities import ( TrainingPipelineParams, SplitParams, FeatureParams, TrainingParams ) numerical_features = [ "age", "sex", "cp", "trestbps", "chol", "fbs", "restecg", "thalach", "exang", "oldpeak", "slope", "ca", "thal", ] @dataclass class TestTrainingPipelineParams: input_data_path: str = "data/raw/heart_cleveland_upload.csv" output_model_path: str = "tests/tmp/test_model.pkl" metric_path: str = "tests/tmp/test_metrics.json" split_params: SplitParams = SplitParams( test_size=0.25, random_state=5 ) feature_params: FeatureParams = FeatureParams( numerical_features=numerical_features, target_col="condition" ) train_params: TrainingParams = TrainingParams( model_type="RandomForestClassifier", ) train_dataframe_path: Optional[str] = "data/raw/predict_dataset.csv" scaler: Optional[str] = None @dataclass class TestPredictPipelineParams: input_data_path: str = "data/raw/predict_dataset.csv" input_model_path: str = "models/model.pkl" output_data_path: str = "tests/tmp/test_model_predicts.csv" class TestEnd2End(unittest.TestCase): test_train_piplein_params = TestTrainingPipelineParams() test_test_piplein_params = TestPredictPipelineParams() @unittest.mock.patch("ml_project.train_pipeline.logger") def test_train_end2end(self, mock_log): with patch("sys.stdout", new=StringIO()): path_to_model, metrics = run_train_pipeline(self.test_train_piplein_params) self.assertTrue(os.path.exists(path_to_model)) self.assertTrue(metrics["0"]["f1-score"] > 0.6) self.assertTrue(metrics["1"]["f1-score"] > 0.6) @unittest.mock.patch("ml_project.train_pipeline.logger") def test_predict_end2end(self, mock_log): with patch("sys.stdout", new=StringIO()): run_predict_pipeline(self.test_test_piplein_params) self.assertTrue(os.path.exists(self.test_test_piplein_params.output_data_path))
made-mlops-2022/alexey_sklyannyy
tests/test_end2end_training.py
test_end2end_training.py
py
2,397
python
en
code
0
github-code
6
33124682966
import json import os import docx with open(f'disciplinas.json') as f: data = json.load(f) # print(df.columns.values) for index, discpln in data.items(): print(f'{discpln["sigla"]} - {discpln["nome"]}') doc = docx.Document() doc.add_heading(f'{discpln["sigla"]} - {discpln["nome"]}') doc.add_heading(f'{discpln["nome_en"]}', level=3) doc.add_paragraph() # Dados gerais p = doc.add_paragraph(style = 'List Bullet') p.add_run(f'Créditos-aula: {discpln["CA"]}\n') p.add_run(f'Créditos-trabalho: {discpln["CT"]}\n') p.add_run(f'Carga horária: {discpln["CH"]}\n') p.add_run(f'Ativação: {discpln["ativacao"]}\n') p.add_run(f'Departamento: {discpln["departamento"]}\n') # Cursos e semestres ideais cs = f'Curso (semestre ideal):' for curso, semestre in discpln["semestre"].items(): cs += f' {curso} ({semestre}),' p.add_run(cs[:-1]) # Objetivos doc.add_heading(f'Objetivos', level=2) doc.add_paragraph(f'{discpln["objetivos"]}') if discpln["abstract"]: p = doc.add_paragraph() p.add_run(f'{discpln["objectives"]}').italic = True # Docentes doc.add_heading(f'Docente(s) Responsável(eis) ', level=2) profs = discpln["docentes"] nprofs = discpln["ndoc"] if nprofs: p = doc.add_paragraph(style='List Bullet') for i in range(nprofs-1): p.add_run(f'{profs[i]}\n') p.add_run(f'{profs[-1]}') # programa resumido doc.add_heading(f'Programa resumido', level=2) doc.add_paragraph(f'{discpln["resumo"]}') if discpln["abstract"]: p = doc.add_paragraph() p.add_run(f'{discpln["abstract"]}').italic = True # programa doc.add_heading(f'Programa', level=2) doc.add_paragraph(f'{discpln["programa"]}') if discpln["program"]: p = doc.add_paragraph() p.add_run(f'{discpln["program"]}').italic = True # avaliação doc.add_heading('Avaliação', level=2) p = doc.add_paragraph( style='List Bullet') p.add_run('Método: ').bold = True p.add_run(f'{discpln["metodo"]}\n') p.add_run('Critério: ').bold = True p.add_run(f'{discpln["criterio"]}\n') p.add_run('Norma de recuperação: ').bold = True p.add_run(f'{discpln["exame"]}') # bibliografia doc.add_heading('Bibliografia', level=2) doc.add_paragraph(f'{discpln["bibliografia"]}') # Requisitos nr = discpln['requisitos'] if nr: doc.add_heading('Requisitos', level=2) p = doc.add_paragraph(style='List Bullet') for k, req in nr.items(): p.add_run(f"{req['sigla']} - {req['nome']} ({req['tipo']})\n") # salvando try: os.mkdir(f'../assets/disciplinas/') except FileExistsError: pass docname = f'../assets/disciplinas/{discpln["sigla"]}.docx' doc.save(docname) # exportando pdf os.system(f'abiword --to=pdf {docname}') # break
luizeleno/pyjupiter
_python/gera-doc-pdf-unificado.py
gera-doc-pdf-unificado.py
py
2,978
python
es
code
2
github-code
6
22167366155
import time from functools import wraps from MatrixDecomposition import MatrixDecomposition from MatrixGeneration import MatrixGeneration def fn_timer(function): @wraps(function) def function_timer(*args, **kwargs): t0 = time.time() result = function(*args, **kwargs) t1 = time.time() print("Total time running '%s': %s seconds" % (function.__name__, str(t1 - t0))) return result return function_timer class Analyzer: @staticmethod def analyze_tridiagonal(): Analyzer.analyze_gauss(10, MatrixGeneration.tridiagonal) Analyzer.analyze_seidel(10, MatrixGeneration.tridiagonal) Analyzer.analyze_gauss(50, MatrixGeneration.tridiagonal) Analyzer.analyze_seidel(50, MatrixGeneration.tridiagonal) Analyzer.analyze_gauss(100, MatrixGeneration.tridiagonal) Analyzer.analyze_seidel(100, MatrixGeneration.tridiagonal) @staticmethod def analyze_hilbert(): Analyzer.analyze_gauss(10, MatrixGeneration.hilbert) Analyzer.analyze_seidel(10, MatrixGeneration.hilbert) Analyzer.analyze_gauss(50, MatrixGeneration.hilbert) Analyzer.analyze_seidel(50, MatrixGeneration.hilbert) Analyzer.analyze_gauss(100, MatrixGeneration.hilbert) Analyzer.analyze_seidel(100, MatrixGeneration.hilbert) @staticmethod @fn_timer def analyze_gauss(n, method): print(f'\'{method.__name__}\' {n}') matrix = method(n) right = MatrixGeneration.right(matrix) matrix_decomposition = MatrixDecomposition(matrix) gauss = matrix_decomposition.solve_by_gauss(right) @staticmethod @fn_timer def analyze_seidel(n, method): print(f'\'{method.__name__}\' {n}') matrix = method(n) right = MatrixGeneration.right(matrix) matrix_decomposition = MatrixDecomposition(matrix) seidel = matrix_decomposition.solve_by_seidel(right, 1e-3)
g3tawayfrom/appmath_lab4
Analyzer.py
Analyzer.py
py
1,953
python
en
code
0
github-code
6
35792097840
#!/usr/bin/env python # coding: utf-8 # In[ ]: from selenium import webdriver from selenium.webdriver.common.by import By import time from selenium.webdriver.support.ui import WebDriverWait import random def get_sore_and_Price(store_id,internet_id): driver = webdriver.Chrome('C:/Users/cunzh/Desktop/chromedriver.exe') ## you should change the path before you run start_page = driver.get("https://www.homedepot.com/l/") driver.find_element_by_id("storeSearchBox").send_keys(store_id) driver.find_element_by_class_name("sfSearchbox__button").click() time.sleep(random.randint(3,5)) Message='' try: store = driver.find_element_by_class_name('sfstores') store_name = store.find_element_by_class_name('sfstorename').text #print(store.get_attribute("outerHTML")) except: price="NA" Message="store cannot be found" else: a = store.find_element_by_class_name('sfstorelinks').find_element_by_tag_name('a') time.sleep(random.randint(3,5)) #time.sleep are pretening human behavior; human spend different time on different web. So this website will not recognize this as a bot. a.click() #Randint gives us random integer 3 to 5 time.sleep(random.randint(3,5)) driver.find_element_by_id("headerSearch").send_keys(internet_id) time.sleep(random.randint(3,5)) driver.find_element_by_id("headerSearchButton").click() time.sleep(random.randint(3,5)) try: content = driver.find_element_by_class_name("price-detailed__wrapper") # print(content.get_attribute('innerHTML')) spans = content.find_elements_by_tag_name('span') if len(spans) != 3: price='NA' Message='price cannot be found' else: a = spans[1] b = spans[2] price = a.text + '.' + b.text except: price='NA' Message='price cannot be found' return store_id,price,Message # In[ ]: # We can test the code by using follwing example: store_list = ['954', '907', '6917'] test_list = ['302895490', '302895488', '100561401', '206809290'] list1=[] for store in store_list: for item in test_list: list1.append(get_sore_and_Price(store,item)) # In[ ]: list1
JiyuanZhanglalala/Web-Scraping-
Home Depot Web Scraping Function.py
Home Depot Web Scraping Function.py
py
2,398
python
en
code
0
github-code
6
9634583525
# Builds some spectra and self-energies using the aux.Aux functionality import numpy as np from auxgf import mol, hf, aux, agf2, grids from auxgf.util import Timer timer = Timer() # Build the Molecule object: m = mol.Molecule(atoms='H 0 0 0; Li 0 0 1.64', basis='cc-pvdz') # Build the RHF object: rhf = hf.RHF(m) rhf.run() # Build the grid: refq = grids.ReFqGrid(2**8, minpt=-5, maxpt=5, eta=0.1) # Build the Hartree-Fock Green's function: g_hf = aux.Aux(np.zeros(0), np.zeros((rhf.nao, 0)), chempot=rhf.chempot) # Build the MP2 self-energy: s_mp2 = aux.build_rmp2_iter(g_hf, rhf.fock_mo, rhf.eri_mo) # Build the second-iteration Green's function, which corresponds to the QP spectrum at MP2 level or G^(2): e, c = s_mp2.eig(rhf.fock_mo) g_2 = g_hf.new(e, c[:rhf.nao]) # inherits g_hf.chempot # Run an RAGF2 calcuation and get the converged Green's function and self-energy (we also use the RAGF2 density): gf2 = agf2.RAGF2(rhf, nmom=(2,3), verbose=False) gf2.run() s_gf2 = gf2.se e, c = s_gf2.eig(rhf.get_fock(gf2.rdm1, basis='mo')) g_gf2 = s_gf2.new(e, c[:rhf.nao]) # For each Green's function, get the spectrum (Aux.as_spectrum only represents the function on a grid, we must # also provide ordering='retarded' and then refactor): def aux_to_spectrum(g): a = g.as_spectrum(refq, ordering='retarded') a = a.imag / np.pi a = a.trace(axis1=1, axis2=2) return a a_hf = aux_to_spectrum(g_hf) a_2 = aux_to_spectrum(g_2) a_gf2 = aux_to_spectrum(g_gf2) # Compare the spectra quantitatively: print('| A(hf) - A(2) | = %.12f' % (np.linalg.norm(a_hf - a_2) / refq.npts)) print('| A(gf2) - A(2) | = %.12f' % (np.linalg.norm(a_gf2 - a_2) / refq.npts)) print('| A(gf2) - A(hf) | = %.12f' % (np.linalg.norm(a_gf2 - a_hf) / refq.npts)) print('time elapsed: %d min %.4f s' % (timer.total() // 60, timer.total() % 60))
obackhouse/auxgf
examples/06-spectra.py
06-spectra.py
py
1,839
python
en
code
3
github-code
6
32941642034
import numpy as np import matplotlib from matplotlib.colors import ListedColormap SLACred = '#8C1515' SLACgrey = '#53565A' SLACblue = '#007C92' SLACteal = '#279989' SLACgreen = '#8BC751' SLACyellow = '#FEDD5C' SLACorange = '#E04F39' SLACpurple = '#53284F' SLAClavender = '#765E99' SLACbrown = '#5F574F' SLACcolors = [SLACred, SLACblue, SLACteal, SLACgreen, SLACyellow, SLACgrey, SLACorange, SLACpurple, SLAClavender, SLACbrown, ] # SLACsage = [199./256, 209./256, 197./256] white = [256./256, 256./256, 256./256] SLACpaloverde = [39./256, 153./256, 137./256] matplotlib.cm.register_cmap('SLACverde', ListedColormap(np.array([np.interp(np.linspace(0, 1, 256), [0, 1], [whiteV, pvV]) for whiteV, pvV in zip(white, SLACpaloverde)]).T, name = 'SLACverde')) LaTeXflavor = {"numu": r'$\nu_\mu$', "numubar": r'$\bar{\nu}_\mu$', "nue": r'$\nu_e$', "nuebar": r'$\bar{\nu}_e$', "nutau": r'$\nu_\tau$', "nutaubar": r'$\bar{\nu}_\tau$'} matplotlib.rc('axes', **{"prop_cycle": matplotlib.cycler(color = SLACcolors)}) matplotlib.rc('image', **{"cmap": 'SLACverde'}) matplotlib.rc('font', **{"family": 'sans-serif', "sans-serif": 'Arial', "size": 16, "weight": 'bold'}) matplotlib.rc('text', **{"usetex": True})
DanielMDouglas/SLACplots
SLACplots/colors.py
colors.py
py
1,729
python
en
code
0
github-code
6
72946559547
import socket import struct import os import time import hashlib HOST = '192.168.1.76' PORT = 8000 BUFFER_SIZE = 1024 FILE_NAME = 'usertrj.txt' # Change to your file FILE_SIZE = os.path.getsize(FILE_NAME) HEAD_STRUCT = '128sIq32s' # Structure of file head def send_file(): # Create a TCP/IP socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Connect the socket to the server server_address = (HOST, PORT) #Calculate MD5 print("Calculating MD5...") fr = open(FILE_NAME, 'rb') md5_code = hashlib.md5() md5_code.update(fr.read()) fr.close() print("Calculating success") # Need open again fr = open(FILE_NAME, 'rb') # Pack file info(file name and file size) file_head = struct.pack('128sIq32s', b'usertrj.txt', len(FILE_NAME), FILE_SIZE, md5_code.hexdigest()) try: # Connect sock.connect(server_address) print("Connecting to %s port %s" % server_address) # Send file info sock.send(file_head) send_size = 0 print("Sending data...") time_start = time.time() while send_size < FILE_SIZE: if FILE_SIZE - send_size < BUFFER_SIZE: file_data = fr.read(FILE_SIZE - send_size) send_size = FILE_SIZE else: file_data = fr.read(BUFFER_SIZE) send_size += BUFFER_SIZE sock.send(file_data) time_end = time.time() print("Send success!") print("MD5 : %s" % md5_code.hexdigest()) print("Cost %f seconds" % (time_end - time_start)) fr.close() sock.close() except socket.errno as e: print("Socket error: %s" % str(e)) except Exception as e: print("Other exception : %s" % str(e)) finally: print("Closing connect") if __name__ == '__main__': send_file()
cash2one/brush-1
slave/scripts/test/connect.py
connect.py
py
1,878
python
en
code
0
github-code
6
25847181178
import tkinter as tk import sqlite3 def guardar_palabras(): palabras = [entrada1.get(), entrada2.get(), entrada3.get(), entrada4.get(), entrada5.get()] # Conexión a la base de datos conexion = sqlite3.connect('basedatos.db') cursor = conexion.cursor() # Crear la tabla "palabras" si no existe cursor.execute('''CREATE TABLE IF NOT EXISTS palabras (id INTEGER PRIMARY KEY AUTOINCREMENT, palabra TEXT)''') # Eliminar las palabras anteriores en la tabla cursor.execute("DELETE FROM palabras") # Insertar las últimas 5 palabras en la tabla "palabras" for palabra in palabras: cursor.execute("INSERT INTO palabras (palabra) VALUES (?)", (palabra,)) # Guardar cambios y cerrar conexión conexion.commit() conexion.close() ventana.destroy() ventana = tk.Tk() ventana.title("5 Palabras") frase_inicio = "Si fueras 5 palabras, cuáles serías?:" etiqueta_frase = tk.Label(ventana, text=frase_inicio) etiqueta_frase.pack() entrada1 = tk.Entry(ventana) entrada1.pack() entrada2 = tk.Entry(ventana) entrada2.pack() entrada3 = tk.Entry(ventana) entrada3.pack() entrada4 = tk.Entry(ventana) entrada4.pack() entrada5 = tk.Entry(ventana) entrada5.pack() boton = tk.Button(ventana, text="Aceptar", command=guardar_palabras) boton.pack() ventana.mainloop() def mostrar_ventana1(): ventana1 = tk.Toplevel() ventana1.title("Tus palabras") etiqueta1 = tk.Label(ventana1, text="Estas son tus palabras:") etiqueta1.pack() # Conexión a la base de datos conexion = sqlite3.connect('basedatos.db') cursor = conexion.cursor() # Consulta para recuperar las palabras cursor.execute("SELECT palabra FROM palabras") palabras = cursor.fetchall() for palabra in palabras: etiqueta = tk.Label(ventana1, text=palabra[0]) etiqueta.pack() # Cerrar conexión conexion.close() def mostrar_ventana2(): ventana2 = tk.Toplevel() ventana2.title("Palabras nuevas") frase_inicio = "Si fueras 5 palabras, cuáles serías?:" etiqueta_frase = tk.Label(ventana2, text=frase_inicio) etiqueta_frase.pack() entrada1 = tk.Entry(ventana2) entrada1.pack() entrada2 = tk.Entry(ventana2) entrada2.pack() entrada3 = tk.Entry(ventana2) entrada3.pack() entrada4 = tk.Entry(ventana2) entrada4.pack() entrada5 = tk.Entry(ventana2) entrada5.pack() def guardar_palabras_nuevas(): palabras = [entrada1.get(), entrada2.get(), entrada3.get(), entrada4.get(), entrada5.get()] # Conexión a la base de datos conexion = sqlite3.connect('basedatos.db') cursor = conexion.cursor() # Crear la tabla "palabras" si no existe cursor.execute('''CREATE TABLE IF NOT EXISTS palabras (id INTEGER PRIMARY KEY AUTOINCREMENT, palabra TEXT)''') # Eliminar las palabras anteriores en la tabla cursor.execute("DELETE FROM palabras") # Insertar las últimas 5 palabras en la tabla "palabras" for palabra in palabras: cursor.execute("INSERT INTO palabras (palabra) VALUES (?)", (palabra,)) # Guardar cambios y cerrar conexión conexion.commit() conexion.close() boton = tk.Button(ventana2, text="Aceptar", command=guardar_palabras_nuevas) boton.pack() ventana_principal = tk.Tk() ventana_principal.title("Ventana Principal") boton_ventana1 = tk.Button(ventana_principal, text="Tus palabras", command=mostrar_ventana1) boton_ventana1.pack() boton_ventana2 = tk.Button(ventana_principal, text="Palabras nuevas", command=mostrar_ventana2) boton_ventana2.pack() ventana_principal.mainloop()
AlejandroAntonPineda/ArtPersonality
base_datos.py
base_datos.py
py
3,754
python
es
code
0
github-code
6
27385560013
from road import Road from copy import deepcopy from collections import deque from vehicleGenerator import VehicleGenerators import numpy as np from scipy.spatial import distance import random class Simulator: def __init__(self, config = {}) -> None: self.setDefaultConfig() #update vals for attr, val in config.items(): setattr(self, attr, val) def setDefaultConfig(self): #time self.t = 520.0 #time step self.dt = 1/60 #frames count self.frameCount = 0 #roads self.roads = {} self.vehicleGens = deque() self.trafficSignals = deque() def createTrafficSignals(self, trafficSignal): self.trafficSignals.append(trafficSignal) def createRoad(self, start, end, startCross, endCross): road = Road(start, end, startCross, endCross) self.roads[(startCross, endCross)] = road # return road def createRoads(self, roadsList): for roadCoords in roadsList: self.createRoad(*roadCoords) def createRoadsFromGraph(self, graph): self.graph = graph for idx in range(len(graph)): start = graph[idx][0] if len(graph[idx][1]) > 0: for vertexIdx in graph[idx][1]: end = (graph[vertexIdx][0][0], graph[vertexIdx][0][1]) length = distance.euclidean(start, end) sin = (end[1] - start[1]) / length cos = (end[0] - start[0]) / length self.createRoad((start[0] - 0.3 * sin, start[1] + 0.3 * cos), (end[0] - 0.3 * sin, end[1] + 0.3 * cos), idx, vertexIdx) def createGen(self, genConfig): self.vehicleGens.append(VehicleGenerators(self, genConfig)) def update(self): # Updating every road for roadKey in self.roads: road = self.roads[roadKey] if len(road.vehicles) > 0 and road.vehicles[0].currentRoadIndex + 1 < len(road.vehicles[0].path): vehicle = road.vehicles[0] nextRoad = self.roads[vehicle.path[vehicle.currentRoadIndex + 1]] else: road.update(self.dt, self.t) nextRoad = None road.update(self.dt, self.t, nextRoad) # Checking the roads for out of bounds vehicle for roadKey in self.roads: road = self.roads[roadKey] # If road does not have vehicles, then continue if len(road.vehicles) == 0: continue # If not vehicle = road.vehicles[0] # If the first vehicle is out of road bounds if vehicle.x >= road.length: #if vehicle just wanders: if len(vehicle.path) == 1: vehicle.currentRoadIndex = 1 newVehicle = deepcopy(vehicle) newVehicle.x = 0 crossRoad = self.graph[road.endCross] if len(crossRoad[1]) > 0: if newVehicle.decideToRide(): carNums = [len(self.roads[(road.endCross, k)].vehicles) for k in crossRoad[1]] minNum = np.min(carNums) minIdx = [i for i, x in enumerate(carNums) if x == minNum] nextCross = crossRoad[1][random.choice(minIdx)] self.roads[(road.endCross, nextCross)].vehicles.append(newVehicle) else: pass # If vehicle has a next road if vehicle.currentRoadIndex + 1 < len(vehicle.path): # Updating the current road to next road vehicle.currentRoadIndex += 1 # Creating a copy and reseting some vehicle properties newVehicle = deepcopy(vehicle) newVehicle.x = 0 # Adding it to the next road nextRoadIndex = vehicle.path[vehicle.currentRoadIndex] self.roads[nextRoadIndex].vehicles.append(newVehicle) # In all cases, removing it from its road road.vehicles.popleft() for signal in self.trafficSignals: signal.update(self) for gen in self.vehicleGens: gen.update() if (self.t >= 540 and self.t <= 660) or (self.t >= 1020 and self.t <= 1080): gen.vehicleRate = 190 else: gen.vehicleRate = 40 self.t += self.dt if self.t >= 1440: self.t = 0
EHAT32/alg_labs_sem_7
lab3/simulator.py
simulator.py
py
4,713
python
en
code
0
github-code
6
25971386553
""" .. testsetup:: * from zasim.cagen.utils import * """ # This file is part of zasim. zasim is licensed under the BSD 3-clause license. # See LICENSE.txt for details. from ..features import HAVE_TUPLE_ARRAY_INDEX from itertools import product import numpy as np if HAVE_TUPLE_ARRAY_INDEX: def offset_pos(pos, offset): """Offset a position by an offset. Any amount of dimensions should work. >>> offset_pos((1, ), (5, )) (6,) >>> offset_pos((1, 2, 3), (9, 8, 7)) (10, 10, 10)""" if len(pos) == 1: return (pos[0] + offset[0],) else: return tuple([a + b for a, b in zip(pos, offset)]) else: def offset_pos(pos, offset): """Offset a position by an offset. Only works for 1d.""" if isinstance(pos, tuple): pos = pos[0] if isinstance(offset, tuple): offset = offset[0] return pos + offset def gen_offset_pos(pos, offset): """Generate code to offset a position by an offset. >>> gen_offset_pos(["i", "j"], ["foo", "bar"]) ['i + foo', 'j + bar']""" return ["%s + %s" % (a, b) for a, b in zip(pos, offset)] def dedent_python_code(code): ''' Dedent a bit of python code, like this: >>> print dedent_python_code("""# update the histogram ... if result != center: ... self.target.histogram[result] += 1""") # update the histogram if result != center: self.target.histogram[result] += 1 ''' lines = code.split("\n") resultlines = [lines[0]] # the first line shall never have any whitespace. if len(lines) > 1: common_whitespace = len(lines[1]) - len(lines[1].lstrip()) if common_whitespace > 0: for line in lines[1:]: white, text = line[:common_whitespace], line[common_whitespace:] assert line == "" or white.isspace() resultlines.append(text) else: resultlines.extend(lines[1:]) return "\n".join(resultlines) def rule_nr_to_multidim_rule_arr(number, digits, base=2): """Given the rule `number`, the number of cells the neighbourhood has (as `digits`) and the `base` of the cells, this function calculates the multidimensional rule table for computing that rule.""" if base < 256: dtype = "int8" else: dtype = "int16" # good luck with that. res = np.zeros((base,) * digits, dtype=dtype) entries = base ** digits blubb = base ** entries for position in product(*([xrange(base-1, -1, -1)] * digits)): blubb /= base d = int(number // (blubb)) number -= d * (blubb) res[position] = d return res def rule_nr_to_rule_arr(number, digits, base=2): """Given a rule `number`, the number of cells the neighbourhood has (as `digits`) and the `base` of the cells, this function calculates the lookup array for computing that rule. >>> rule_nr_to_rule_arr(110, 3) [0, 1, 1, 1, 0, 1, 1, 0] >>> rule_nr_to_rule_arr(26, 3, 3) [2, 2, 2, ...] """ entries = base ** digits result = [0 for index in range(entries)] blubb = base ** entries for e in range(entries - 1, -1, -1): blubb /= base d = int(number // (blubb)) number -= d * (blubb) result[e] = d return result def elementary_digits_and_values(neighbourhood, base=2, rule_arr=None): """From a neighbourhood, the base of the values used and the array that holds the results for each combination of neighbourhood values, create a list of dictionaries with the neighbourhood values paired with their result_value ordered by the position like in the rule array. If the rule_arr is None, no result_value field will be generated.""" digits_and_values = [] offsets = neighbourhood.offsets names = neighbourhood.names digits = len(offsets) for i in range(base ** digits): values = rule_nr_to_rule_arr(i, digits, base) asdict = dict(zip(names, values)) digits_and_values.append(asdict) if rule_arr is not None: if not isinstance(rule_arr, np.ndarray) or len(rule_arr.shape) == 1: indices = enumerate(xrange(base ** digits)) else: indices = enumerate(reversed(list(product(*([xrange(base-1,-1,-1)] * digits))))) for index, rule_idx in indices: digits_and_values[index].update(result_value = rule_arr[rule_idx]) return digits_and_values
timo/zasim
zasim/cagen/utils.py
utils.py
py
4,490
python
en
code
4
github-code
6
20043759155
# Given the names and grades for each student in a class of students, store them in a # nested list and print the name(s) of any student(s) having the second lowest grade. # Note: If there are multiple students with the second lowest grade, order their names alphabetically and print each name on a new line. # Print the name(s) of any student(s) having the second lowest grade in. # If there are multiple students, order their names alphabetically and print each one on a new line. std_data = [] n = int(input()) # accept name and grade for i in range(n): name = input() grade = float(input()) std_data.append([name,grade]) std_set = set() for i in range(n): std_set.add(std_data[i][1]) stdList = list(std_set) stdList.sort() grade_list = [] # Fetching data of student whoes marks are same as 2nd lowest student for i in range(n): if stdList[1] == std_data[i][1]: grade_list.append(std_data[i]) grade_list.sort() for i in range(len(grade_list)): print(grade_list[i][0])
Elevenv/HackerRank-Python-challenges
nested_list.py
nested_list.py
py
1,025
python
en
code
2
github-code
6
32787034238
""" URL configuration for backend project. The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/4.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.conf import settings from django.conf.urls.static import static from django.contrib import admin from django.urls import include, path from drf_yasg import openapi from drf_yasg.views import get_schema_view from rest_framework import permissions schema_view = get_schema_view( openapi.Info( title="SoC Portal API", default_version="v1", description="Test description", terms_of_service="https://www.google.com/policies/terms/", contact=openapi.Contact(email="[email protected]"), license=openapi.License(name="BSD License"), ), permission_classes=[], public=True, ) urlpatterns = [ path("admin/", admin.site.urls), path("api/accounts/", include("accounts.urls")), path("api/dashboard/", include("dashboard.urls")), path("api/projects/", include("projects.urls")), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += [ path( "swagger<format>/", schema_view.without_ui(cache_timeout=0), name="schema-json" ), path( "swagger/", schema_view.with_ui("swagger", cache_timeout=0), name="schema-swagger-ui", ), path("redoc/", schema_view.with_ui("redoc", cache_timeout=0), name="schema-redoc"), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
wncc/SoC-Portal
backend/backend/urls.py
urls.py
py
2,001
python
en
code
12
github-code
6
12866597010
import sys from collections import defaultdict def tpsortutil(u, visited, stack, cur): visited[u] = True for i in graph[u]: if not visited[i]: tpsortutil(i, visited, stack, cur) elif i in cur: return stack.append(u) def topologicalsort(graph, vertices): visited = [False] * vertices stack = [] for i in range(vertices): cur = set() if not visited[i] and graph[i]: tpsortutil(i, visited, stack, cur) del cur stack = stack[::-1] print(stack) if __name__ == "__main__": vertices = int(input()) graph = defaultdict(list) edges = int(input()) for _ in range(edges): edge = [int(x) for x in input().split()] graph[edge[0]].append(edge[1]) print(graph) topologicalsort(graph, vertices)
tyao117/AlgorithmPractice
TopologicalSort/TopologicalSort.py
TopologicalSort.py
py
825
python
en
code
0
github-code
6
225835019
import streamlit as st import calculator_logic st.title("Calculator App") num1 = st.number_input("Enter the first number:") num2 = st.number_input("Enter the second number:") operation = st.selectbox("Select an operation", calculator_logic.OPERATIONS) if st.button("Calculate"): result = calculator_logic.calculate(num1, num2, operation) st.success(f"The result is {result}") # Define a function to display the signature def display_signature(): st.markdown( """ <style> .signature { font-size: 1rem; font-style: italic; text-align: center; padding: 1rem 0; color: #333; transition: color 0.5s ease-in-out; } .signature:hover { color: #007bff; } </style> """ , unsafe_allow_html=True ) st.markdown( """ <div class="signature"> Made with ❤️ by Shib Kumar Saraf </div> """ , unsafe_allow_html=True ) # Add the signature to your Streamlit app display_signature()
shib1111111/basic_calculator
app.py
app.py
py
1,113
python
en
code
0
github-code
6