def get_sms(): phone_num = request.form['phone_num'] pass_word = request.form['password'] user = db_session.query(User).filter(User.phone == phone_num, User.password == pass_word).first() if not user: return jsonify({'success': False, 'msg': '用户名或密码不正确!'}) user_code = redis_db.get(phone_num) if user_code: is_send = redis_db.get('today:%s' % phone_num) sms_limit = int(redis_db.get('last:%s' % phone_num)) if is_send: return jsonify({'success': False, 'msg': '验证码已发送,请60秒后重试'}) elif sms_limit > 11: return jsonify({'success': False, 'msg': '当日尝试次数超过30次'}) send_sms(phone_num, '登录验证', "SMS_137365090", user_code) redis_db.set('last:%s' % phone_num, sms_limit + 1) return jsonify({'success': False, 'msg': '验证码已发送'}) # 缓存内无验证码,发送并存入数据库 else: code = ''.join(random.sample(string.digits, 6)) print("验证码:", code) send_sms(user.phone, '登录验证', "SMS_137365090", code) redis_db.set(phone_num, code, ex=300) redis_db.set('last:%s' % phone_num, 1, ex=86400) redis_db.set('today:%s' % phone_num, 1, ex=60) return jsonify({'success': False, 'msg': '验证码已发送'})
def createUser(): if request.method == "POST": try: userData = request.form.to_dict(flat=False) print(userData["zipCode1"][0]) # Hash password salt = "5gz" password = userData["password"][0] + salt hashedPassword = hashlib.md5(password.encode()).hexdigest() newUser = User(username=userData["username"][0], password=hashedPassword, zipCode1=int(userData["zipCode1"][0]), zipCode2=int(userData["zipCode2"][0]), zipCode3=int(userData["zipCode3"][0]), phone=userData["phone"][0]) session['zipCode1'], session['zipCode2'], session['zipCode3'] = userData["zipCode1"][0], userData["zipCode2"][0], userData["zipCode3"][0] db.session.add(newUser) session['uid'] = User.query.filter_by(username=userData["username"][0]).first().id session['uname'] = userData["zipCode1"][0] #uid = newUser.id send_sms(userData["phone"][0], getAqi(userData["zipCode1"][0])) except Exception as e: pass return redirect("/")
def disk_monitor(): # 遍历主机ip for i in range(len(ip_list)): # os.system("ssh "+ip_list[i]+" df -h" ) ip = ip_list[i].replace('\n', '') disk_sh = "ssh " + ip + " df -h" # print 'disk_sh', disk_sh disk_list = os.popen(disk_sh).readlines() # print disk_list # 遍历磁盘 for j in range(1, len(disk_list)): # print disk_list[j], '\n' disk_size = disk_list[j].replace('\n', '').split(' ') # print disk_size disk_size_new = [x.strip() for x in disk_size if x.strip() != ''] # print disk_size_new disk_space = int(disk_size_new[4].replace('%', '')) if disk_space > 80: sms_info = "磁盘空间告警,主机:%s,已用空间%s,挂载分区:%s" % (ip, disk_space, disk_size_new[5]) print 'sms_info:', sms_info send_sms.send_sms(sms_info)
def antarctica_analysis(self, csv_file): try: all_db_patients = self.select_all_tasks("patients") with open(csv_file, encoding="utf-8-sig") as an_file: all_rows = csv.reader(an_file, delimiter=';') for one_row in all_rows: #print(one_row) for one_patient in all_db_patients: #print(type(one_row[2]), one_row[2], type(one_patient[3]), one_patient[3]) if one_row[0] != 'id': if one_row[2] == str(one_patient[3]): #porównuje pesele aby dostać id one_row[4] = str(datetime.strptime(one_row[4], "%d.%m.%Y %H:%M")) if one_row[5] == 'T': one_row[5] = 'True' else: one_row[5] = 'False' self.insert_analysis( probe_number=one_row[1], analysis_id=one_row[3], patient_id=one_patient[0], #odnosimy się do bazy danych do tablicy patients i wyciągamy id collection_time=one_row[4], result=one_row[5] ) if one_row[5] == "False": week_days = ["Poniedzialek", "Wtorek", "Środa", "Czwartek", "Piątek", "Sobota", "Niedziela"] obj_datetime = datetime.strptime(one_row[6], "%d.%m.%Y %H:%M") week_number = obj_datetime.weekday() msg = f'Dzień dobry, ' \ f'Zapraszamy na wizytę kontrolną w {week_days[week_number]} dokładna data ' \ f'{one_row[6]} o godzinie {obj_datetime.time()}' send_sms(msg, one_row[7]) except Exception as e: logger.error("Antarctica analysis failed ", exc_info=True)
def forget_pass(): phone_num = request.form['phone_num'] pass_word = request.form['new_password'] try: sms_code = int(request.form['sms_code']) except ValueError: sms_code = 0000 user = db_session.query(User).filter(User.phone == phone_num, User.password == pass_word).first() if not user: return jsonify({}) user_code = redis_db.get(phone_num) if not user_code: code = ''.join(random.sample(string.digits, 6)) send_sms(user.phone, '登录验证', "SMS_137365090", code) redis_db.set(phone_num, code, ex=300) redis_db.set('last:%s' % phone_num, 1, ex=86400) redis_db.set('today:%s' % phone_num, 1, ex=120) user_code = code if sms_code != 0000 and sms_code == int(user_code): user.password = pass_word db_session.commit() return redirect('/query') else: return jsonify({'success': False, 'msg': '验证码错误'})
def leader_determine(): # BEGIN LEADER SORTITION lowest_sortition_hash = None for host in hosts: # THIS ASSUMES A PERFECT CONSENSUS OF THE BLOCK HASH res = requests.get('http://' + host + ':5000/pub-key', headers={"Accept": "text/plaintext"}) remote_pub_key = res._content sha = hasher.sha256() sha.update((str(BLOCKCHAIN[-1].hash_block()) + str(remote_pub_key)).encode('utf-8')) sortition_hash = sha.hexdigest() if lowest_sortition_hash == None or\ sortition_hash < lowest_sortition_hash: lowest_sortition_hash = sortition_hash # poll your own key sha = hasher.sha256() sha.update( (str(BLOCKCHAIN[-1].hash_block()) + str(PUB_KEY_STR)).encode('utf-8')) sortition_hash = sha.hexdigest() if sortition_hash < lowest_sortition_hash: lowest_sortition_hash = sortition_hash print("LOWEST HASH: ", str(lowest_sortition_hash)) print("MY hASH: ", str(sortition_hash)) if sortition_hash == lowest_sortition_hash: print("YOU ARE THE LEADER") send_sms() return '\n'.join(open('static/leader.html').readlines()) else: print("YOU ARE NOT THE LEADER") return '\n'.join(open('static/transfer.html').readlines())
def check_order_valid(): orders = query_db('select * from orders where deal_state = ?', [0]) for i in orders: if i['deal_time'] - int(time.time()) > 900: g.db.execute('update orders set deal_state = ? where uuid = ?', [4, i['uuid']]) g.db.commit() user = query_db('select * from users where uuid = ?', [i['user_uuid']], one=True) send_sms(user['phone_number'], "抱歉,您的订单已经失效。")
def generate_authentication(phone): account = is_account(phone) otp, otp_hash, otp_expiration = create_otp() otp_data = {"otp": otp_hash, "otp_expiration": otp_expiration} account.update(otp_data) e164_phone = "+1" + phone text_message = f'Your commute check verification code is {otp}.' send_sms(e164_phone, text_message) return "otp updated"
def suggest_alt_route(default_seconds, best_available_seconds, delta, phone): """Sends an SMS suggesting the user take an alternate route.""" import send_sms default = convert_secs_to_hr_min_string(default_seconds) best = convert_secs_to_hr_min_string(best_available_seconds) delta = convert_secs_to_hr_min_string(delta) text_body = f'Save {delta}, your usual route is {default} and a {best} alternative exists.' print(text_body) if send_texts: send_sms.send_sms(phone, text_body)
def suggest_usual_route(default_seconds, best_available_seconds, delta, phone, tolerance_seconds): """Sends an SMS suggesting the user take their usual route. Note: This is for testing purposes. Eventually the suggestion of a user's "usual" route would be indicated by a non-notificaiton.""" import send_sms default = convert_secs_to_hr_min_string(default_seconds) best = convert_secs_to_hr_min_string(best_available_seconds) delta = convert_secs_to_hr_min_string(delta) tolerance = convert_secs_to_hr_min_string(tolerance_seconds) text_body = f'Stick to your usual route, at {default}. The best route available is {best}. Your threshold for an alternative is {tolerance}.' print(text_body) if send_texts: send_sms.send_sms(phone, text_body)
def get_prediction(): if request.method == 'POST': output_values = ["Non-Diabetic", "Diabetic"] data = request.form data = dict(data) type_to_learn = data.pop("types_to_learn", None) get_model(type_to_learn) # print(data, types_to_learn) data = pd.DataFrame(data, index=[0]) prediction = loaded_models.predict(data) prediction_string = str(output_values[prediction[0]]) return_str = f'The Prediction is: {prediction_string}' send_sms(prediction_string, type_to_learn) return return_str
def get(self): phone = request.args['phone'] user = User.query.filter_by(phone=phone).first() digits = generate_rand_digits(6) if not user: u = User(phone=phone, verify_code=digits) db.session.add(u) elif time.time( ) - user.launch_timestamp > app.config['GET_CODE_PERIOD']: user.launch_timestamp = time.time() user.verify_code = digits db.session.add(user) else: msg = '<h1>user resubmit to frequent please resubmit after %d ' \ 'seconds</h1>' % app.config.get('GET_CODE_PERIOD', 60) return make_response(jsonify({'message': msg}), 400) if 'PRODUCT_MODE' in app.config and app.config['PRODUCT_MODE']: from send_sms import send_sms, SIGN_NAME, TEMPLATE_CODE params = {'code': digits, 'product': 'aida'} send_state = send_sms(business_id, phone, SIGN_NAME, TEMPLATE_CODE, params) app.logger.debug('the send state %s', send_state) db.session.commit() if app.config.get('TESTING'): return make_response( jsonify({ 'phone': phone, 'verify_code': digits })), 200 else: return make_response(jsonify({}), 200)
def sms_view(request): form_class = SendSmsForm if request.method == "POST": sms = form_class(data=request.POST) if sms.is_valid(): phone = sms.cleaned_data['phone'] message = sms.cleaned_data['message'] if send_sms(phone, message) == True: return render(request, 'sms/successful.html', { 'phone': phone, 'message': message }) else: return render( request, 'sms/error.html', {'error': 'Unable to send SMS. Please Try Again.'}) else: #form data is not valid. return HttpResponse("Invalid phone number or Message. Try again.") elif request.method == "GET": #sms = SendSmsForm() return render(request, 'sms/index.html', {'form': form_class}) else: #form data is not valid. return HttpResponse("Bad request. Try again.")
def prepare_sms(file_paths): ''' Prepare sms to be sent''' file_names = [fp.split('/')[-1] for fp in file_paths] subject = "NMU " + FACULTY + " Results Found" message = "\r\n".join([ "", "{}\n".format(subject), "Hi There!", "I'm ResultBot. I keep searching for NMU results.", "I found the following files" " related to NMU {} results.".format(FACULTY), "", ] + file_names) end_message = ("\n\nCheers,\n ResultBot") message += end_message print ("Sending sms...") send_sms(message)
def sms_reply(): location = request.values.get('Body', None) contact = request.values.get('From', None) res = send_sms.send_sms(location, contact) resp = MessagingResponse() resp.message(res) return str(resp)
def recognise(args): # loop over the testing images for imagePath in paths.list_images(args["testing"]): # load the image, convert it to grayscale, describe it, # and classify it image = cv2.imread(imagePath) gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) hist = desc.describe(gray) prediction = model.predict(hist)[0] # display the image and the prediction cv2.putText(image, prediction, (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1.0, (0, 0, 255), 3) cv2.imshow("Image", image) print prediction if re.search(r'adult', prediction, flags=re.I): message = "Recognised {person_type}".format(person_type=prediction) send_sms(message=message) exit(0)
def send_coupon(phone_number, id): p = query_db('select * from coupon_template where uuid = ?', [id], one=True) # 如果优惠券模板找不到,则直接返回。 if p is None: print ">>>send_coupon: can not find the template!!!" return False u = query_db('select * from coupons where phone_number = ? and coupon_uuid = ?', [phone_number, id]) if u: print u print ">>>send_coupon: there exists coupon!!!" return False print ">>>send_coupon: success!!!" u = str(uuid.uuid4()) g.db.execute('insert into coupons (uuid, coupon_uuid, coupon_name, phone_number, coupon_limit, coupon_discount, create_time, limit_time, coupon_remark, coupon_color) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)', [u, id, p['coupon_name'], phone_number, p['coupon_limit'], p['coupon_discount'], int(time.time()), p['limit_time']+int(time.time()), p['coupon_remark'], p['coupon_color']]) g.db.execute('update coupon_template set coupon_stock = ? where uuid = ?', [p['coupon_stock']-1, id]) g.db.commit() send_sms(phone_number, "亲,您的其乐账户中成功添加" + str(p['coupon_discount']) + "元红包噢,记得尽快使用哦!微信关注其乐,即享更多精彩活动!") return True
def send_coupon_init(phone_number): total = 80 # if send_coupon_init_base('init0', phone_number): # total -= 40 # if send_coupon_init_base('init1', phone_number): # total -= 20 # if send_coupon_init_base('init2', phone_number): # total -= 10 # if send_coupon_init_base('init3', phone_number): # total -= 10 # if total > 0: # send_sms(phone_number, "亲,您的其乐账户中成功添加" + str(total) + "元红包噢,记得尽快使用哦!微信关注其乐,即享更多精彩活动!") send_coupon_init_base('init0', phone_number) send_coupon_init_base('init1', phone_number) send_coupon_init_base('init2', phone_number) send_coupon_init_base('init3', phone_number) send_coupon_init_base('init4', phone_number) send_coupon_init_base('init5', phone_number) send_coupon_init_base('init6', phone_number) send_sms(phone_number, "亲,您的其乐账户中成功添加" + str(total) + "元红包噢,记得尽快使用哦!微信关注其乐,即享更多精彩活动!")
def post(self): self.response.headers['Content-Type'] = 'application/json' self.response.headers['Access-Control-Allow-Origin'] = '*' message = self.request.POST.get('message', None) teacher = self.request.POST.get('teacher', None) student = self.request.POST.get('student', None) if not message or not teacher or not student: logging.exception('Check arguments, please: %s, %s, %s' % (message, teacher, student)) self.response.write( json.dumps({ 'Check': 'parameters, please! %s, %s, %s' % (message, teacher, student) })) else: send_sms.send_sms(from_phone='12016958217', to_phone=USER_TO_PHONE.get(student), message=message) self.response.write(json.dumps({'ok': True}))
def suggest_alt_route(preferred_duration_w_traffic, best_avail_duration_w_traffic, delta, phone): """Sends an SMS suggesting the user take an alternate route.""" preferred = convert_secs_to_hr_min_string(preferred_duration_w_traffic) best = convert_secs_to_hr_min_string(best_avail_duration_w_traffic) delta = convert_secs_to_hr_min_string(delta) text_body = f'Save {delta}, your usual route is {preferred} and a {best} alternative exists.' sns_api_response = send_sms.send_sms(phone, text_body) return text_body, sns_api_response
def agentcontrol_menu(key=None): if key == None: key = raw_input(color(33, '\n[-] Enter agent control key [None]: ')) try: key = key.lower() except: pass if key in ('', 'none', '\n', None): key = None if key == None: print color(31, '[!] No key was provided, communicating with an agent will not work') print color(31, '[!] Returning...') return 1 menu_list = ['Send SMS' , 'Take Picture' , 'Get Contacts' , 'Get SMS Database' , 'Privilege Escalation' ] choice = menu(menu_list, color(35, '\n[*] Agent Control Commands:\n')) if choice is 0: return_code = 0 elif choice is 1: return_code = send_sms(key) elif choice is 2: return_code = take_picture(key) elif choice is 3: return_code = get_contacts(key) elif choice is 4: return_code = get_sms_database(key) elif choice is 5: return_code = privilege_escalation(key) # elif choice is my_number: # return_code = custom_module() # etc... else: return_code = 1 return return_code
def alarm(message): ## This function is triggered when a alarm is detected. Alarm can be triggered: ## - through the web interface ## - through a SMS with the code ALARM at the beginning ## Check if there is already a mission if missions.objects.filter(disabled=0).count() != 0: ##for testing purposes set it to 1 m = missions.objects.get(disabled=0) m.disabled = 1 m.save() ## take message and relay it to all people ## create mission newmission = missions(startTime=timezone.now(), missionTitle=message) newmission.save() ## TODO: check that only one mission is active at once! all_people = people.objects.all() for p in all_people: send_sms(message, p.phoneNumber)
def login(): if request.method == 'GET': return render_template('login.html') elif request.method == "POST": phone_num = request.form['phone_num'] pass_word = request.form['password'] try: sms_code = int(request.form['sms_code']) except ValueError: sms_code = 0000 user = db_session.query(User).filter( User.phone == phone_num, User.password == pass_word).first() if not user: return jsonify({}) user_code = redis_db.get(phone_num) if not user_code: code = ''.join(random.sample(string.digits, 6)) send_sms(user.phone, '登录验证', "SMS_137365090", code) redis_db.set(phone_num, code, ex=300) redis_db.set('last:%s' % phone_num, 1, ex=86400) redis_db.set('today:%s' % phone_num, 1, ex=120) user_code = code # 如表单内有验证码,且验证码与缓存内一致,则登录成功 if sms_code != 0000 and sms_code == int(user_code): sess['phone'] = user.phone sess['name'] = user.name sess['rank'] = user.rank user.last_login = datetime.now() user.last_ip = request.remote_addr loginfo = LoginInfo(user_id=user.id, time=datetime.now(), ip=request.remote_addr) db_session.add(loginfo) db_session.commit() print('ssssssss') return redirect('/query') else: return jsonify({'success': False, 'msg': '验证码错误'})
def alarm(message): ## This function is triggered when a alarm is detected. Alarm can be triggered: ## - through the web interface ## - through a SMS with the code ALARM at the beginning ## Check if there is already a mission if missions.objects.filter(disabled=0).count() != 0: ##for testing purposes set it to 1 m = missions.objects.get(disabled=0) m.disabled = 1 m.save() ## take message and relay it to all people ## create mission newmission = missions(startTime = timezone.now(), missionTitle=message); newmission.save() ## TODO: check that only one mission is active at once! all_people = people.objects.all() for p in all_people: send_sms(message, p.phoneNumber)
def antarctica_analysis(self, csv_antarctica_path): try: with open(csv_antarctica_path, encoding="UTF-8-SIG") as csv_antarctica: all_row = csv.reader(csv_antarctica, delimiter=';') all_row_db = self.select_all_tasks("patients") week_days = [ "Poniedzialek", "Wtorek", "Środa", "Czwartek", "Piątek", "Sobota", "Niedziela" ] for row in all_row: for row_db in all_row_db: if row[2] == str(row_db[3]): if row[4] != 'collection_time': row[4] = str( datetime.strptime(row[4], "%d.%m.%Y %H:%M")) if row[5] == 'T': row[5] = 'True' if row[5] == 'F': row[5] = 'False' if row[0] != "id": # opuszczamy 1 wiersz self.insert_analysis(probe_number=row[1], analysis_id=row[3], patient_id=row_db[0], collection_time=row[4], result=row[5]) if row[5] == 'False': obj_date = datetime.strptime( row[6], "%d.%m.%Y %H:%M") week_num = obj_date.weekday() send_sms( f'Zapraszamy na wizyte kontrolna w {week_days[week_num]} dokładna data {obj_date.date()} ' f'o godzinie {obj_date.time()}', row[7]) except Exception as e: logger.error("Antarctica analysis failed", exc_info=True)
def enviro_detect(self): print "Start environment detection..." pic_count = 0 # keep detecting before the owen is inside while (self.cap.isOpened()): if_pupil_detection = {} for i in self.col_account.find({"car": self.car_number}): if_pupil_detection[i['_id']] = i['ifStart'] if True in if_pupil_detection.values(): break ret, frame = self.cap.read() if ret == True: eye = cv2.CascadeClassifier('haarcascade_eye.xml') detected = eye.detectMultiScale(frame, 1.3, 3) if detected != () and pic_count < 3: print 'somebody come in...' cv2.imwrite('temp' + str(pic_count) + '.png', frame) pic_count += 1 time.sleep(3) elif pic_count >= 3: print 'Pics has been taken...' fd = face_detection.face_detection(self.url,self.car_number) result = fd.detection() print result serious = True for i in result: if i: serious = False break if serious: # lat, lon = self.get_geolocation() # warning_info = {"car": self.car_number, "time": datetime.datetime.now(), # "geolocation": [lat, lon], # "illegal_time": self.warning, "type": 'car'} # self.save_warning(warning_info) print "car warning!!!" for i in range(3): os.remove('temp' + str(i) + '.png') ss = send_sms.send_sms(self.car_number) ss.send("Warning: An unauthenticated person is inside your car!!!") pic_count = 0 break else: print "This guy is the owner" for i in range(3): os.remove('temp' + str(i) + '.png') pic_count = 0 break
def monitor_course(course_form_link_element, course_number, course_name): print('monitoring course number : ' + course_number) course_form_link_element.find_elements_by_tag_name('input')[-1].click() courses_description_table = driver.find_element_by_xpath( '//table[@summary="This layout table is used to present the sections found"]' ) course_options = courses_description_table.find_elements_by_tag_name( 'tbody') course_options = course_options[0].find_elements_by_tag_name('tr') is_available = False for row in course_options[2:]: columns = row.find_elements_by_tag_name('td') crn, subj, crse, sec, cmp, cred = [ element.text for element in columns[1:7] ] s = '' s += 'crn: ' + str(crn) + '\n' s += 'subj: ' + str(subj) + '\n' s += 'crse: ' + str(crse) + '\n' s += 'sec: ' + str(sec) + '\n' s += 'cmp: ' + str(cmp) + '\n' s += 'cred: ' + str(cred) print(s) try: checkboxes = columns[0].find_elements_by_tag_name('input') if len(checkboxes) > 0: print('course is available') if str(crse) in AUTOMATICALLY_REGISTER_COURSE_NUMBERS and str( cred) == '4.000': # AUTOMATICALLY REGISTER FOR THIS COURSE print('automatically registering for this course!') checkbox = checkboxes[0] checkbox.click() register_button = driver.find_element_by_xpath( '//input[@value="Register"]') register_button.click() time.sleep(5) submit_changes_button = driver.find_element_by_xpath( '//input[@value="Submit Changes"]') submit_changes_button.click() send_sms( 'Automatically registered for the following course, Hurray!\n' + s) driver.back() time.sleep(5) driver.back() time.sleep(5) elif str(cred) == '4.000': # DO NOT REGISTER FOR THIS COURSE AUTOMATICALLY print('not registering for this course') is_available = True else: print('course is not available') except: print('course is not available') driver.back() if course_number not in course_availability_status_dictionary.keys(): # no previous records course_availability_status_dictionary[course_number] = is_available send_sms('course number : ' + course_number + '\ncourse name : ' + course_name + '\nis available : ' + str(is_available)) else: # yes previous records if course_availability_status_dictionary[course_number] != is_available: course_availability_status_dictionary[course_number] = is_available send_sms('course number : ' + course_number + '\ncourse name : ' + course_name + '\nis available : ' + str(is_available))
import send_sms send_sms.send_sms( from_phone='12016958217', to_phone='12016877934', message='Please send your SSN.')
""" Main file """ from send_sms import send_sms current_weather = "20 C" #testing sending sms through twilio api send_sms('+917798487388', current_weather)
received_data_str = received_data.decode('utf-8') gps_data_array = str(received_data_str).split('\r') lat = 0 long = 0 lat_direction = '' long_direction = '' for gps_data in gps_data_array: if gps_data.startswith('$GPGGA'): GPGGA = gps_data.split(',') print(GPGGA) lat = float(GPGGA[2][0:2]) + float(GPGGA[2][2:]) / 60 lat_direction = GPGGA[3] print(lat, lat_direction) long = float(GPGGA[4][0:3]) + float(GPGGA[4][3:]) / 60 long_direction = GPGGA[5] print(long, long_direction) if lat_direction is 'S': lat *= -1 if long_direction is 'W': long *= -1 gmaps_url = 'http://maps.google.com/maps?q=' + str(lat) + ',' + str(long) send_sms('082255805036', 'Tolong aku... \n' + gmaps_url) print(gmaps_url)
if __name__ == '__main__': from scipy.stats import uniform, randint from src.kernels.mismatch import MismatchKernel from src.kernels.spectral import SpectralKernel, SpectralConcatKernel from src.kernels.wd import WDKernel from src.kernels.la import LAKernel from src.kernels.gappy import GappyKernel from src.kernels.wildcard import WildcardKernel from src.methods.ksvm import KSVM from src.methods.klr import KLR from src.data.seq import AllSeqData from send_sms import send_sms alldata = AllSeqData(parameters={"nsmall": 200, "small": False}) data0 = alldata[0]["train"] parameter_grid = { 'kernel': [SpectralConcatKernel], 'g': 10, 'l': 8, 'C': uniform(loc=1 / 2, scale=2), } rand_klr = RandomHyperParameterTuning(KSVM, data0, n_sampling=3, parameter_grid=parameter_grid, kfold=5) rand_klr.fit() print(rand_klr.best_parameters()) send_sms("Finished random search")
from is_online import is_online from send_sms import send_sms # Players to get notified on playerids = [""] while True: for playerid in playerids: if is_online(playerid): print(f"Player {playerid} is online") send_sms(playerid) playerids.remove(playerid) else: pass
from bs4 import BeautifulSoup from selenium import webdriver from selenium.webdriver.support.ui import Select from send_sms import send_sms driver = webdriver.Firefox() driver.get('http://www.reg.uci.edu/perl/WebSoc') department_select = Select(driver.find_element_by_name('Dept')) department_select.select_by_value("EECS") coursenum_element = driver.find_element_by_xpath("//input[@name='CourseNum']") coursenum_element.send_keys("213") submit_element = driver.find_element_by_xpath( "//input[@value='Display Web Results']") submit_element.click() html = driver.page_source soup = BeautifulSoup(html, 'html.parser') course_table = soup.find('div', {'class': 'course-list'}) rows = course_table.findAll('tr') for tr in rows: for l in tr.findAll('td'): row = l.getText().strip() if row.startswith("EECS"): print(row) if row.startswith("OPEN"): send_sms() driver.close()
def sendVerifyCode(): vcode = random.randint(10000, 99999) session['vcode'] = vcode send_sms(request.form.get("t1"), '验证码:' + str(vcode)) print vcode return jsonify({"data": 100})
def api_text_me(state, city): send_sms("You should visit {}, {}".format(city, state)) # TODO - Can you change the result from 'success' if the sms fails? return jsonify({"result": "success"})
from bs4 import BeautifulSoup from send_sms import send_sms page = requests.get('https://www.worldometers.info/coronavirus/country/nepal/') soup = BeautifulSoup(page.content, 'html.parser') total_cases_div = soup.find_all(class_="maincounter-number") # brief_update is a list which have # 1st element gives total no. of cased till date # 2nd gives total deaths # 3rd gives total patients recovered brief_update = [items.find('span').get_text() for items in total_cases_div] # print(brief_update) new_update = soup.find('li', class_="news_li") new_cases = new_update.find('strong').get_text() new_cases_splitted = new_cases.split(" ", 1) new_cases_num = int(new_cases_splitted[0]) msg_one = "Hey buds " + "\n\nNew " + str( new_cases_num ) + " cases added today. \nPlease stay at home and take care. \n\n " msg_two = "Todays update:\n New cases: " + brief_update[ 0] + " \n Deaths : " + brief_update[1] + "\n Recovered : " + brief_update[2] msg = msg_one + msg_two # sends msg if new cases is greater then 100 if new_cases_num > 100: send_sms(msg)
return jsonify({"data": 101}) try: g.db.execute('update rooms set stock = ? where uuid = ?', [str(p), room['uuid']]) g.db.commit() except Exception, e: raise e return jsonify({"data": 102}) try: if order['coupon_uuid']: g.db.execute('update coupons set coupon_state = 0 where phone_number = ? and uuid = ?', [user['phone_number'], order['coupon_uuid']]) g.db.commit() except Exception, e: raise e return jsonify({"data": 103}) try: send_sms(user['phone_number'], '订单确认:' + liverstr(order['liver_info']) + '在' + str(order['date1']) + '至' + str(order['date2']) + '入住' + str(merchant['merchant_name']) + str(room['room_name']) + str(timedate2timedelta(order['date2'], order['date1'])) + '晚' + '总价:¥' + str(order['deal_price']) + '地址:' + str(room['room_address']) + '电话:' + str(merchant['merchant_phone_number1']) + '其乐客服:4000125176,关注微信公众号其乐,更多惊喜等待你!') except Exception, e: raise e return jsonify({"data": 104}) send_sms('13564204618', '订单确认:' + liverstr(order['liver_info']) + '在' + str(order['date1']) + '至' + str(order['date2']) + '入住' + str(merchant['merchant_name']) + str(room['room_name']) + str(timedate2timedelta(order['date2'], order['date1'])) + '晚' + '总价:¥' + str(order['deal_price']) + '地址:' + str(room['room_address']) + '电话:' + str(merchant['merchant_phone_number1']) + '其乐客服:4000125176,关注微信公众号其乐,更多惊喜等待你!') return jsonify({"data": 100}) # boom shakalaka @app.route('/crash_all-back/<key>') def crash_all(key): if key == '5120309188': g.db.execute('delete from users') g.db.execute('delete from orders') g.db.execute('delete from coupons') g.db.execute('delete from rooms') g.db.execute('delete from merchants') g.db.commit()
def text_me(state, city): send_sms("You should visit {}, {}".format(city, state)) return redirect(url_for('get_city', state=state, city=city))
cv2.imshow("output1", color_map_frame) key1 = cv2.waitKey(10) if key1 == 27: # exit on ESC break if fire_prob > 99: print("..............Fire Detected .. ") #Give the filename img_name = "{}.png".format(imgCount) #save image file with the above file name cv2.imwrite(img_name, orig) #upload the frame where fire was detected upload_to_aws(img_name, 'fire-detection-ads', img_name) #send sms link = send_sms("FIRE DETECTED ", img_name) publish.single(MQTT_PATH, link, hostname=MQTT_SERVER) time.sleep(100) label = "Fire Probability: " + str(fire_prob) cv2.putText(orig, label, (10, 25), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 255, 0), 2) cv2.imshow("Output", orig) key = cv2.waitKey(10) if key == 27: # exit on ESC break elif rval == False: break end = time.time()