def test_create_combination_list_2(self): calculator = Calculator() _input = ["apple", "orange", "grape", "banana"] _output = [["apple", "orange", "grape"], ["apple", "grape", "banana"], ["orange", "grape", "banana"]] self.assertListEqual(calculator.create_combination_list(_input, 3), _output)
def __init__(self, bot): self.badWordCount = 0 # 나쁜 말 카운트 self.firstBadWordTimestamp = 0 # 나쁜 말 감지기가 최초 활성화된 시점 self.bot = bot self.randomBasedFeatures = RandomBasedFeatures() self.webManager = WebManager() self.calculator = Calculator()
class TestCalculator(unittest.TestCase): def setUp(self): self.calculator = Calculator() def test_add(self): self.assertEqual(15, self.calculator.add(10, 5)) def test_subtract(self): self.assertEqual(5, self.calculator.subtract(10, 5)) def test_multiply(self): self.assertEqual(50, self.calculator.multiply(10, 5)) def test_divide(self): self.assertEqual(2, self.calculator.divide(10, 5))
def main(): """ Starts our main method """ calculator = Calculator() while True: count = 1 cont = "" value1 = None value2 = None calculator.print_menu() operand = input("Your option from the menu (1 - 10): ") if operand in valid_choice and operand not in valid_choice[6:]: value1 = number_validator(operand, count) count += 1 value2 = number_validator(operand, count) elif operand in valid_choice and operand == "7": value1 = number_validator(operand, count) elif operand in valid_choice and operand == "8": value1 = number_validator(operand, count) elif operand in valid_choice and operand == "9": value1 = number_validator(operand, count) elif operand in valid_choice and operand == "10": print("I am here") value1 = number_validator(operand, count) elif operand in valid_choice and operand == "11": value1 = number_validator(operand, count) else: print("\n=================== ERROR =========================") print(f"You chose {operand}. This is NOT a valid option.") print("===================================================") continue # Perform our operation calculator.perform_operation(operand, value1, value2) # Ask if user wants to continue while True: if cont.upper() != "Y" and cont.upper() != "N": cont = input("Do you want to perform another calculation (Y/N): ") else: break # Check if program should exit. if cont.upper() == "N": print("Exiting program...") break
TABLE_NAMES = ["activity", "sleep", "readiness"] ab_normal_column = [ "hypnogram_5min", "hr_5min", "rmssd_5min", "class_5min", "met_1min", ] skip_column = ["met_min_medium_plus", "bedtime_start", "bedtime_end"] db_api = DBapi() grapher = Grapher() caluculator = Calculator() def convert_abnormal_column_list(lists): result = [] for _list in lists: if "," in _list: result.append([float(word) for word in _list.split(",")]) else: result.append([float(word) for word in _list]) return result def cast_list_float(_list): return [float(value) for value in _list]
def test_create_average_list(self): calculator = Calculator() _input = [[1, 2, 3], [4, 5, 6]] _output = [2.0, 5.0] self.assertListEqual(calculator.create_average_list(_input), _output)
def test_create_sum_list(self): calculator = Calculator() _input = [[1, 2, 3, 4, 5], [1, 2, 3, 4, 5]] _output = [15, 15] self.assertListEqual(calculator.create_sum_list(_input), _output)
def test_m_moving_average_even(self): calculator = Calculator() _input = [1, 2, 3, 4, 5, 6, 7, 8, 9] _output = [3.0, 4.0, 5.0, 6.0, 7.0] self.assertListEqual(calculator.m_moving_average(_input, 4), _output)
def setUp(self): self.calculator = Calculator()
class BotFeaturesHub: # init def __init__(self, bot): self.badWordCount = 0 # 나쁜 말 카운트 self.firstBadWordTimestamp = 0 # 나쁜 말 감지기가 최초 활성화된 시점 self.bot = bot self.randomBasedFeatures = RandomBasedFeatures() self.webManager = WebManager() self.calculator = Calculator() # Get current river temperature 현재 강물 온도 정보 획득 def get_temp(self, user_id): site = '' alias = '' self.webManager.update_suon() try: for user in users.user: if user[0] == str(user_id): site = user[2] alias = user[3] except IndexError: pass result = self.webManager.provide_suon(site) result_if_error = self.webManager.provide_suon('구리') # Default : Hangang(Guri) 잘못된 값이 입력된 경우 기본값으로 한강 구리 측정소 정보를 반환 try: if result == 'error': if result_if_error == 'error': return '현재 한강 수온 정보를 가져올 수 없습니다.' else: return '현재 한강 수온은 ' + self.webManager.provide_suon('구리') + '도입니다.' else: return '현재 ' + alias + ' 수온은 ' + self.webManager.provide_suon(site) + '도입니다.' except AttributeError: if result == 'error': if result_if_error == 'error': return '현재 한강 수온 정보를 가져올 수 없습니다.' else: return '현재 한강 수온은 ' + self.webManager.provide_suon('구리') + '도입니다.' # Bad word detector 나쁜말 감지기 def bad_word_detector(self, message, word_type): if not self.firstBadWordTimestamp: self.firstBadWordTimestamp = time.time() self.badWordCount += 1 if ((time.time() - self.firstBadWordTimestamp) <= config.DETECTOR_TIMEOUT) \ and self.badWordCount >= config.DETECTOR_COUNT: if word_type == 'f_word': self.bot.send_message(message.chat.id, random.choice(strings.stopFWord)) elif word_type == 'anitiation': self.bot.send_message(message.chat.id, random.choice(strings.stopAnitiation)) elif ((time.time() - self.firstBadWordTimestamp) >= config.DETECTOR_TIMEOUT) \ and self.badWordCount <= config.DETECTOR_COUNT: self.firstBadWordTimestamp = 0 self.badWordCount = 0 # D-day def d_day(self, message): now = datetime.datetime.now() # today today = datetime.date(now.year, now.month, now.day) split = message.text.split() split = [item for item in split if '/dday' not in item] split = list(map(int, split)) # String to calculable integer values try: dest = datetime.date(split[0], split[1], split[2]) # date that user entered result = (dest - today).days if result == 0: self.bot.reply_to(message, strings.dayDestMsg) elif result > 0: self.bot.reply_to(message, str(result) + strings.dayLeftMsg) elif result < 0: self.bot.reply_to(message, str(-1 * result) + strings.dayPassedMsg) except (ValueError and IndexError): # wrong input self.bot.reply_to(message, strings.dayOutOfRangeMsg) # Geolocation information 위치 기반 정보 제공 def geolocation_info(self, message, latitude, longitude): # location info map_args = {'x': longitude, 'y': latitude} map_url = MAP_BASE_URL + urllib.parse.urlencode(map_args) map_headers = {"Authorization": 'KakaoAK ' + config.KAKAO_TOKEN} map_request = requests.get(map_url, headers=map_headers) # weather info (by OpenWeatherMap) weather_args = {'lang': 'kr', 'appid': config.WEATHER_TOKEN, 'lat': latitude, 'lon': longitude} weather_url = WEATHER_BASE_URL + urllib.parse.urlencode(weather_args) weather_request = requests.get(weather_url) weather_json = json.loads(weather_request.text) # temporarily store weather info weather = weather_json['weather'][0]['description'] temp = str(round(weather_json['main']['temp'] - 273.15)) + '°C' feels_temp = str(round(weather_json['main']['feels_like'] - 273.15)) + '°C' humidity = str(round(weather_json['main']['humidity'])) + '%' # makes script and sends message weather_result = '날씨 ' + weather + ', ' + '기온 ' + temp + ', ' + \ '체감온도 ' + feels_temp + ', ' + '습도 ' + humidity map_location = json.loads(map_request.text)['documents'][0]['address']['address_name'] geo_location = "위도 : " + str(latitude) + ", 경도 : " + str(longitude) result = geo_location + '\n' + map_location + '\n\n' + weather_result self.bot.reply_to(message, result) # Calculator 계산기 def calculator_handler(self, message): # cut command string command = message.text.split()[0] if len(message.text.split()) >= 2: actual_text = message.text[len(command):] # calculate result = self.calculator.operation(actual_text) # error handling if result == 'syntax error': self.bot.reply_to(message, strings.calcSyntaxErrorMsg) elif result == 'division by zero error': self.bot.reply_to(message, strings.calcDivisionByZeroErrorMsg) else: self.bot.reply_to(message, result) # Handling ordinary message 일반 메시지 처리 def ordinary_message(self, message): # print(message) # Bad word detector 나쁜말 감지기 for n in range(len(strings.koreanFWord)): if strings.koreanFWord[n] in message.text: self.bad_word_detector(message, 'f_word') # 아니시에이션 감지기 for n in range(len(strings.anitiationWord)): if strings.anitiationWord[n] in message.text: self.bad_word_detector(message, 'anitiation') # location-based message if user sent message that includes '수온' or '자살' if ('수온' in message.text) or ('자살' in message.text): self.bot.reply_to(message, self.get_temp(message.from_user.id)) # randomly select magic conch message if user sent message that includes '마법의 소라고둥/동' if ('마법의 소라고둥' in message.text) or ('마법의 소라고동' in message.text): self.bot.reply_to(message, self.randomBasedFeatures.magic_conch())
def add(num1, num2): calculator = Calculator() return render_template('calculator.html', result=calculator.add(num1, num2))
def subtract(num1, num2): calculator = Calculator() return render_template('calculator.html', result=calculator.subtract(num1, num2))
def multiply(num1, num2): calculator = Calculator() return render_template('calculator.html', result=calculator.multiply(num1, num2))
def devide(num1, num2): calculator = Calculator() return render_template('calculator.html', result=calculator.divide(num1, num2))