def performTwitterSearch(consumer_key,consumer_secret,access_token_key,access_token_secret,languages): twitter = Twython(consumer_key, consumer_secret, access_token_key, access_token_secret) register(APPLICATION_ID, REST_API_KEY) gs = goslate.Goslate() for language in languages: maxId = 999999999999999999999999 for page in range(1,11): print('page = ' + str(page)) print('maxId = ' + str(maxId)) if page == 1: query = twitter.search(q=language,src='typd',count=100) else: query = twitter.search(q=language,src='typd',count=100,max_id=maxId) for result in query['statuses']: text = result['text'] id = result['id'] if id != maxId: newTweet = Tweet(Text=text, Language=gs.detect(text), tweetId=str(id)) newTweet.save() if id < maxId: maxId = id print('changed maxId to ' + str(maxId))
def send_push_course_update(course_key_string, course_subscription_id, course_display_name): """ Sends a push notification for a course update, given the course's subscription_id and display_name. """ if settings.PARSE_KEYS: try: register(settings.PARSE_KEYS["APPLICATION_ID"], settings.PARSE_KEYS["REST_API_KEY"]) push_payload = { "action": "course.announcement", "notification-id": unicode(uuid4()), "course-id": course_key_string, "course-name": course_display_name, } push_channels = [course_subscription_id] # Push to all Android devices Push.alert(data=push_payload, channels={"$in": push_channels}, where={"deviceType": "android"}) # Push to all iOS devices # With additional payload so that # 1. The push is displayed automatically # 2. The app gets it even in the background. # See http://stackoverflow.com/questions/19239737/silent-push-notification-in-ios-7-does-not-work push_payload.update({"alert": "", "content-available": 1}) Push.alert(data=push_payload, channels={"$in": push_channels}, where={"deviceType": "ios"}) except ParseError as error: log_exception(error.message)
def pushtoken(pushtoken, os, event_type, trans_id, content, title='The Yub', data={}, uid=0, badge=1): """根据token推送 pushtoken: 推送token os: 操作系统 event_type: 事件类型 trans_id: 交易id content: 显示内容 title: 标题,只针对android用户 data: 自定义报文,dict对象 uid: 用户uid badge: APP右上角显示未阅读数 """ if not pushtoken or not os: log_info('[Push][PushError] pushtoken => %s, os => %s' % (pushtoken, os)) return from parse_rest.connection import register from parse_rest.installation import Push as ParsePush parse_app_id = current_app.config['PARSE_APP_ID'] parse_app_key = current_app.config['PARSE_APP_KEY'] register(parse_app_id, parse_app_key) where = {'objectId':pushtoken} push_params = {'badge':badge, 'uid':uid, 'data':data, 'sound':'default', 'event_type':event_type, 'trans_id':trans_id, 'alert':content, 'deviceType':os} ParsePush.alert(push_params, where=where)
def register_app(**kw): register( "KkFLXaPKXsFkBcTonFsPeNHWJmoIX1K4yvIrmI8C", "6qNCyI4r8YGuMnsh5bfejjQnWevfGWBnfP6vebeX", #master_key="MYSUyoDbkeOtEAht7lKr60EvjCXmHntd02e4wNkS", **kw )
def build(self): register('jeV1sPLXL6cq8EsWAK0Zyoac8b97duQWyXYK7sfE','fl6hQ9dv94IbtA0I7kPzSrawL165HqupSjCFdo3D') # Create the screen manager sm = ScreenManager(transition=FadeTransition()) sm.add_widget(LoginScreen(name='login')) return sm
def main(): register( "AKJFNWcTcG6MUeMt1DAsMxjwU62IJPJ8agbwJZDJ", "i8o0t6wg9GOTly0yaApY2c1zZNMvOqNhoWNuzHUS", master_key = "LbaxSV6u64DRUKxdtQphpYQ7kiaopBaRMY1PgCsv") setup_questions(100)
def main(): soup = BeautifulSoup(requests.get('https://www.mturk.com/mturk/viewhits?searchWords=&pageNumber=4&searchSpec=HITGroupSearch%23T%231%2310%23-1%23T%23%21%23%21NumHITs%211%21%23%21&sortType=NumHITs%3A1&selectedSearchType=hitgroups').text, "html.parser") titles = soup.findAll('a', {"class" : "capsulelink"}) num_results = int(soup.findAll('td', {"class" : "title_orange_text"})[0].text.strip()[8:-7]) print("\nTotal number of HITs: " + str(num_results)) count = 0 page = 1 requestErrors = 0 privateCount = 0 register("DKJjvfvhnCGRK0cAdOpJN9MwR7zhIpuYya5xvbuF", "d8hIYrBrcW4r2ujEkL79vE03FmLxE2QCJgSwuXYv") HITClass = ParseObject.factory("HIT") all_hits = HITClass.Query.all() batcher = ParseBatcher() batcher.batch_delete(all_hits) while (count < 200): soup = BeautifulSoup(requests.get('https://www.mturk.com/mturk/viewhits?searchWords=&pageNumber=' + str(page) + '&searchSpec=HITGroupSearch%23T%231%2310%23-1%23T%23%21%23%21NumHITs%211%21%23%21&sortType=NumHITs%3A1&selectedSearchType=hitgroups').text, "html.parser") titles = soup.findAll('a', {"class" : "capsulelink"}) for t in titles: time.sleep(.3) count = count + 1 print("\n" + str(count) + "\nTitle: " + t.text.strip()) linkA = t.parent.parent.findAll('span')[1].a # check if the link is public if linkA.has_attr('href'): link = linkA['href'] hitPage = BeautifulSoup(requests.get('https://www.mturk.com' + link).text, "html.parser") form = hitPage.findAll('form', {'name' : 'hitForm'}) # Check for error if len(form) >= 3: form = form[2] requester = form.find("input", {'name' : 'prevRequester'})['value'] print('Requester: ' + requester) reward = form.find("input", {'name' : 'prevReward'})['value'] print('Reward: ' + reward) groupID = form.find("input", {'name' : 'groupId'})['value'] print('Group id: ' + groupID) anyObject = HIT(requester=requester, reward=float(reward[3:]), title=t.text.strip(), groupID=groupID) anyObject.save() else: requestErrors = requestErrors + 1 print(link) print(form) else: link = linkA['id'] print(link) privateCount = privateCount + 1 page = page + 1 print("\n\nErrors: " + str(requestErrors)) print("Private HITs: " + str(privateCount))
def __init__(self, app_id, api_key, master_key, config=None, system=None, method=None, similarity=None, K=None): register(app_id, api_key) self.old_N = 0 self.config = config self.email_from = '*****@*****.**' self.system = system self.method = method self.similarity = similarity self.K = K
def init(device): io.setwarnings(False) io.setmode(io.BCM) io.setup(POWER_PIN, io.OUT) io.output(POWER_PIN, False) register(APPLICATION_ID, REST_API_KEY) atexit.register(cleanup, device) device.grab()
def __init__(self, fileName='',debug=False,appkey='',apikey=''): Thread.__init__(self) register(appkey,apikey) self.debug = debug self.probes = {} self.tempDir = '/sys/bus/w1/devices/' self.currentTemp = -999 self.correctionFactor = 1; self.enabled = True self.repopulateprobes()
def main(): register( "AKJFNWcTcG6MUeMt1DAsMxjwU62IJPJ8agbwJZDJ", "i8o0t6wg9GOTly0yaApY2c1zZNMvOqNhoWNuzHUS", master_key = "LbaxSV6u64DRUKxdtQphpYQ7kiaopBaRMY1PgCsv" ) # e_num = get_this_event_num() # prefix = make_event_prefix(e_num) print create_event_object()
def __init__(self, options, columns): super(ParseFdw, self).__init__(options, columns) self.columns = columns try: self.application_id = options['application_id'] self.rest_api_key = options['rest_api_key'] self.className = options['class_name'] except KeyError: log_to_postgres("You must specify an application_id, rest_api_key and class_name options when creating this FDW.", ERROR) register(self.application_id, self.rest_api_key) self.object = Object.factory(self.className)
def shell_context(): register(app.config['PARSE_APPLICATION_ID'], app.config['PARSE_REST_API_KEY']) return { 'app': app, 'Merchant': Merchant, 'Beacon': Beacon, 'Coupon': Coupon, 'CustomDemographics': CustomDemographics, 'User': User, 'Statistic': Statistic }
def initParse(sessionToken=None): print "init" if sessionToken == None: register( "Y4Txek5e5lKnGzkArbcNMVKqMHyaTk3XR6COOpg4", "nJOJNtVr1EvNiyjo6F6M8zfiUdzv8lPx31FBHiwO", master_key=None ) else: register( "Y4Txek5e5lKnGzkArbcNMVKqMHyaTk3XR6COOpg4", "nJOJNtVr1EvNiyjo6F6M8zfiUdzv8lPx31FBHiwO", session_token=sessionToken, )
def main(): # Call "register" to allow parse_rest / ParsePy to work. # --> register(APPLICATION_ID, REST_API_KEY, optional MASTER_KEY) register( "AKJFNWcTcG6MUeMt1DAsMxjwU62IJPJ8agbwJZDJ", "i8o0t6wg9GOTly0yaApY2c1zZNMvOqNhoWNuzHUS", master_key = "LbaxSV6u64DRUKxdtQphpYQ7kiaopBaRMY1PgCsv" ) this_event = _Event(0, 50, 50) this_event.simulate() return "Simulation complete."
def main(): # _getJackpot() # _getLatestAward() register(APPLICATION_ID, REST_API_KEY) schedule.every(1).minutes.do(_getJackpot) schedule.every(1).minutes.do(_getLatestAward) while True: schedule.run_pending() time.sleep(1)
def __init__(self, app_id, api_key, master_key): register(app_id, api_key) self.updated_museums = {} self.museums = None self.museum_ticketurls = None self.post_url = "http://www.libraryinsight.net/mpPostCheckOut.asp?jx=y9p" self.museum_list_url = "http://www.libraryinsight.net/mpbymuseum.asp?jx=y9" self.tables = {"Museum": Museum, "PassID": PassID} self.datadir = "../data/" self.passid_local = "PassID_local.json" self.pass_id_cache = None self.pass_id_cache_filename = os.path.join(self.datadir, self.passid_local)
def dispatch_notification_to_user(self, user_id, msg, channel_context=None): """ Send a notification to a user. It is assumed that 'user_id' and 'msg' are valid and have already passed all necessary validations """ # we ONLY can be called with user_id = _PARSE_SERVICE_USER_ID if user_id != _PARSE_SERVICE_USER_ID: raise ValueError( 'You must call dispatch_notification_to_user with ' 'only the _PARSE_SERVICE_USER_ID constant!' ) # we expect parse_channel_id in the channel_context if not channel_context or 'parse_channel_ids' not in channel_context: raise ValueError( 'You must pass in a non-None channel_context with ' 'the "parse_channel_ids" defined!' ) parse_channel_ids = channel_context.get('parse_channel_ids') # parse_channel_ids must be of type list if not isinstance(parse_channel_ids, list): raise TypeError( 'The channel context parameter "parse_channel_ids" ' 'must be of python type "list"!' ) # now connect to the Parse service and publish the mobile # push notification try: register( self.application_id, self.rest_api_key, ) Push.alert( data=msg.payload, channels=parse_channel_ids, ) except ParseError as error: # catch, log, and re-raise log.exception(error) # re-raise exception raise ChannelError( 'ParsePushNotificationChannelProvider failed to call service. ' 'Error msg = {err_msg}'.format(err_msg=str(error)) )
def testCanGetCurrentUser(self): user = User.signup(self.username, self.password) self.assertIsNotNone(user.sessionToken) register( getattr(settings_local, 'APPLICATION_ID'), getattr(settings_local, 'REST_API_KEY'), session_token=user.sessionToken ) current_user = User.current_user() self.assertIsNotNone(current_user) self.assertEqual(current_user.sessionToken, user.sessionToken) self.assertEqual(current_user.username, user.username)
def united_search(): # check to make sure this only runs at certain times during the day. Heroku servers are UTC (+7) currentHour = datetime.datetime.now().hour - 7 awardCount = 0 if (currentHour == 6 or currentHour == 10 or currentHour == 14 or currentHour == 18 or currentHour == 21): print "It is " + str(currentHour) + " o'clock at home. Running this script!" # configure Parse and query for searches register("XXXXXXXXX", "XXXXXXXXXXX") class awardSearch(Object): pass allAwardSearches = awardSearch.Query.all() for awardSearch in allAwardSearches: runSearch(awardSearch.departureLocation, awardSearch.destinationLocation, awardSearch.departureDate, str(awardSearch.numberAdults), awardSearch.alertOnEconomy, awardSearch.alertOnBusiness, awardSearch.alertOnFirst) awardCount+=1 send_message("Search task completed", "The task ran and completed "+str(awardCount)+" searches.")
def parse_connect(config=None): if config is None: config = app.config app_id = config.get("PARSE_APP_ID", None) rest_key = config.get("PARSE_REST_KEY", None) if not (app_id and rest_key): return False try: register(app_id, rest_key) return True except: return False
def send_tag(aps, tag_name): """parse 标签推送""" from parse_rest.connection import register from parse_rest.installation import Push as ParsePush parse_app_id = "d44eWVZMfeiivL8vWg6S9mgiltSTQSrTyoT8sNOZ" parse_app_key = "RrvBWUH6FE1L1V2QcqyhNPbJKGtqKaBWuDWJGmlR" register(parse_app_id, parse_app_key) ParsePush.alert({'alert': aps['alert'], 'badge': aps['badge'], 'sound':aps['sound'], 'event_type':aps['event_type'], 'trans_id':aps['trans_id'], 'data':aps.get('data', {})}, where={"channels": tag_name})
def main(): flag=0 path_to_music="/home/pi/Music/" default_music="Toss_the_Feathers.mp3" music_to_play=default_music last_updated=datetime.datetime.min register('pQCx3CjwJTZgOfoWjrkdAGdKqAxBoXJoSVbltkeB', 'iITWf0dW7MbLy3hv5LwgoQaiIEluK5lfh4apdgDr') while True: sleep(10) print "Fetching data...." interactions = UserInteraction.Query.all().order_by('-updatedAt').limit(1) latest_interaction = interactions[0] print latest_interaction.LightSelection, latest_interaction.MusicSelection, latest_interaction.Type, latest_interaction.updatedAt if(flag == 0): print "Creating a player" player = Popen(["omxplayer","-o", "local",path_to_music+music_to_play],stdin=PIPE,stdout=PIPE,stderr=PIPE) flag=1 if(latest_interaction.updatedAt!=last_updated): print "Recieved new interaction details" last_updated = latest_interaction.updatedAt if(latest_interaction.Type=='Music'): polling_status = player.poll() music_to_play = default_music if(latest_interaction.MusicSelection == 'Symphony-1'): music_to_play = "Happy_Birthday.mp3" if(latest_interaction.MusicSelection == 'Symphony-2'): music_to_play = "bittersweet_symphony.mp3" if(latest_interaction.MusicSelection == 'Symphony-3'): music_to_play = "Jingle_bells.mp3" if(latest_interaction.MusicSelection == 'Symphony-4'): music_to_play = "Game_Of_Thrones.mp3" print "**************Updating music***********" if(flag == 1 and polling_status!=0): print "Stopping music player" player.stdin.write("q") flag=0 if(flag ==0): print "Starting music player " player = Popen(["omxplayer","-o", "local",path_to_music+music_to_play],stdin=PIPE,stdout=PIPE,stderr=PIPE) flag=1
def save_new_record(): application_id = "8rKmv9RfYnu9dZ5zKyEMa4wlHbmGNpapHzLxBEkO" rest_api_key = "3hidri1tNdkMILtv2CM66ppLR7rw8tlQP10k8tx8" register(application_id, rest_api_key) class Entry(Object): pass record_set, columns = entry.sql_select(1) entry_object = Entry() for row in record_set: entry_object.id = row[0] entry_object.current_id = row[1] entry_object.title = row[2] entry_object.image = row[3] entry_object.url = row[4] entry_object.post_text = row[5] entry_object.date_add = row[6] entry_object.clean_date = row[7] entry_object.save()
def get_this_event_num(): """ Get event number by querying and incrementing highest existing eventNum. """ # Call "register" to allow parse_rest / ParsePy to work. # --> register(APPLICATION_ID, REST_API_KEY, optional MASTER_KEY) register( "AKJFNWcTcG6MUeMt1DAsMxjwU62IJPJ8agbwJZDJ", "i8o0t6wg9GOTly0yaApY2c1zZNMvOqNhoWNuzHUS", master_key = "LbaxSV6u64DRUKxdtQphpYQ7kiaopBaRMY1PgCsv" ) class Event(Object): pass q = Event.Query.all().order_by("-eventNum") if len(list(q)) == 0: return 1 highest_event_num = list(q)[0].eventNum this_event_num = highest_event_num + 1 return this_event_num
def send_push_course_update(course_key_string, course_subscription_id, course_display_name): """ Sends a push notification for a course update, given the course's subscription_id and display_name. """ if settings.PARSE_KEYS: try: register( settings.PARSE_KEYS["APPLICATION_ID"], settings.PARSE_KEYS["REST_API_KEY"], ) Push.alert( data={ "course-id": course_key_string, "action": "course.announcement", "action-loc-key": "VIEW_BUTTON", "loc-key": "COURSE_ANNOUNCEMENT_NOTIFICATION_BODY", "loc-args": [course_display_name], "title-loc-key": "COURSE_ANNOUNCEMENT_NOTIFICATION_TITLE", "title-loc-args": [], }, channels=[course_subscription_id], ) except ParseError as error: log_exception(error.message)
def savePhotos(access_token): print '=============== savePhotos start ===============' # GET USER'S BASIC INFORMATION db_client = dropbox.client.DropboxClient(access_token) account_info = db_client.account_info() print 'get account info..........' # save user info to parse reg = register(PARSE_APP_ID, PARSE_KEY); print 'register.......?' userQuery = myUser.Query.filter(username=account_info['email']) if userQuery.count() == 0: user = myUser(username=account_info['email'], auth_code=access_token) user.save() else: user = userQuery.get() user.auth_code = access_token user.save() print 'user save..........' # SEARCH IMAGE FILES image_search_res = [] for file_extension in SEARCH_CRITERIA: image_search_res.extend(db_client.search('/iPhone/', file_extension)) # images = [] print 'image search ........ ' , len(image_search_res) for img in image_search_res: photo = File.Query.filter(path=img['path'], username=account_info['email']) # print 'path = ' , img['path'] if photo.count() == 0: # print 'len = ' , photo.count() photo_s = File(path=img['path'], username=account_info['email'], date=img['modified']) # userName = account_info['email'] # path = img['path'] # link = db_client.share(path)["url"] # TO BE USED LATER photo_s.save() # START SAVE THUMBNAIL '''
from parse_rest.datatypes import Object, GeoPoint from parse_rest.user import User import sys reload(sys) sys.setdefaultencoding('utf-8') users = {"john": "hello", "foo": "food"} parse_credentials = { "application_id": "2wzSL2IYgy38Q378nNoKSJ23qqqSy5Uu1BW7Slax", "rest_api_key": "JwPG9NCK67Yu1Ty96CAunYDs43oRcMsSoipu5qBH", "master_key": "7bgt7qUcm5ein46DuaF1rYV5CboF6SbR9HfaiwoD", } register(parse_credentials["application_id"], parse_credentials["rest_api_key"]) class newsmeme(Object): pass class narrators(Object): pass @auth.get_password def get_pw(username): if username in users: return users.get(username) return None
from credentials import parse_credentials from parse_rest.connection import register from parse_rest.datatypes import Object register(parse_credentials['application_id'], parse_credentials['rest_api_key'])
#!/usr/bin/env python # -*- coding: utf-8 -*- try: from settings_local import * except ImportError as e: from settings import * from parse_rest.connection import register from parse_rest.datatypes import Object register(PARSE['APPLICATION_ID'], PARSE['REST_API_KEY'], master_key=PARSE['MASTER_KEY']) # Daily workouts class Workout(Object): pass def format_workout(obj): if obj.experienced.strip() == obj.open.strip(): return obj.open.strip() else: return 'Open:\n' + obj.open.strip( ) + '\n\n' + 'Experienced:\n' + obj.experienced.strip() # Returns the latest workout object def latest_workout_obj():
from parse_rest.connection import register from parse_rest.datatypes import Object import time register("qjArPWWC0eD8yFmAwRjKkiCQ82Dtgq5ovIbD5ZKW", "9Yl2TD1DcjR6P1XyppzQ9NerO6ZwWBQnpQiM0MkL") class Reporter(Object): pass class Incident(Object): pass reporterName = "Andy Chong" nric = "abcde12345" mobileNumber = "+6583937419" address = "Some address here" typeAssistance = "Emergency Ambulance" incidentName = "Dengue" incidentDescription = "My son get dengue, he is dying soon!" priority = "1" time.sleep(5) reporter = Reporter.Query.all() for r in reporter: if (r.name == reporterName and r.NRIC == nric and r.mobile_no == mobileNumber and r.address == address and r.typeOfAssistance == typeAssistance):
app = FlaskAPI(__name__) cors = CORS(app) app.config['CORS_HEADERS'] = 'Content-Type' app.config['BASIC_AUTH_USERNAME'] = os.environ.get('AUTH_U', 'spam') app.config['BASIC_AUTH_PASSWORD'] = os.environ.get('AUTH_P', 'eggs') basic_auth = BasicAuth(app) port = int(os.environ.get('PORT', 5000)) if port == 5000: app.debug = True # Load up args from env and hop on to parse # Load up from .env for foreman on heroku register(os.environ.get('PARSE_APP_ID'), os.environ.get( 'PARSE_APP_KEY'), master_key=os.environ.get('PARSE_SECRET_KEY')) # Choices can be used for sessions as well as panels by attribution # of appropriate options (yes/no or speaker1/speaker2/speaker3) # TODO: pull from config instead routes = { "08030752691": "Choice 1", "08030752692": "Choice 2", "08030752693": "Choice 3", } class Clap(Object): @classmethod
from flask import Flask,render_template, flash, redirect, \ make_response,request, url_for , session, g, jsonify import urllib2, base64 from tweets import fetchTweet from app import app from dbHelper import DB import json,urllib2,xml,datetime,hashlib,time,requests,base64 from base64 import b64encode from credentials import client_id,client_secret from parse_rest.installation import Push from parse_rest.connection import register register('9nhyJ0OEkfqmGygl44OAYfdFdnapE27d9yj9UI5x', 'xsipM4oBX3sRx415UsWPXHCuuTPhetfmmrubRiPx', master_key=None) import multiprocessing import os from matching import imageMatch from bot import pushTwitter def upload_imgur(img_file): headers = {"Authorization": "Client-ID %s"%client_id} api_key = client_secret url = "https://api.imgur.com/3/upload.json" if not img_file: img_data = b64encode(open('1.png', 'rb').read()) else: img_data = b64encode(img_file.read()) response = requests.post( url, headers = headers,
if location == 'Warren': output_location = 1 elif location == 'Baystate': output_location = 2 elif location == 'West': output_location = 3 menu = Menu.Query.filter(DateAvailable=date, MealTimeAvailable=meal, hallID=output_location) return menu.limit(2000) def getUserItems(self, userName): user = User.Query.get(fullName=userName) tummy = Tummy.Query.filter(User=user) tummy1 = tummy.limit(2000) return tummy register(settings_local.APPLICATION_ID, settings_local.REST_API_KEY) if __name__ == "__main__": t = datetime(2015, 02, 06, 19, 00) test = recEngine(t, 'Santiago Beltran', 'Baystate', 5) test.recommends() print(test.sortedFreq) #print(test.mostHatedItems) #recommends(t,'Carlos Cheung','Baystate',5) #recommend('Erin Dail',t)
from django.db import models from parse_rest.connection import register from parse_rest.datatypes import Object, GeoPoint from parse_rest.user import User import json, requests register('P3N8sjOcUB7pMF3G1miWIfswdXGx6MN2MzBJ8I3M', 'EGxO4lNrnlbYcDz6h36vAFLDTMiLG4tSVyU2RRE0') # Create your models here. class Post(models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now_add=True) title = models.CharField(max_length=255) def __unicode__(self): return self.title class SchoolNames(Object): pass
from config import config C=config() from parse_rest.connection import register register(C['APPLICATION_ID'], C['REST_API_KEY'], master_key=C['MASTER_KEY']) from parse_rest.datatypes import Object class ip(Object): pass import urllib2 def getIP(): try: response = urllib2.urlopen('http://dynupdate.no-ip.com/ip.php') return response.read() except: return false actual_ip = getIP() #actual_ip = "111.111.111.120" thisIP = ip() print actual_ip if actual_ip:
from parse_rest.connection import register from parse_rest.installation import Push from parse_rest.connection import register register( "uBK0GW8nzkRjRD3l1xnlJBTlBk8DdopTEdGddjLz" "AB7zBYrXQCnLOQobtJfluh2Ngqe4hNmbrl8WgUl0", master_key="LRj5tdjuGXwpovAmtZTnSPA5yUTmhFFA4O3Fmozp") ''' register("uBK0GW8nzkRjRD3l1xnlJBTlBk8DdopTEdGddjLz", "AB7zBYrXQCnLOQobtJfluh2Ngqe4hNmbrl8WgUl0", master_key="LRj5tdjuGXwpovAmtZTnSPA5yUTmhFFA4O3Fmozp") Push.message("Giants scored against the A's! It's now 2-2.", where={"device_id": "dasqueel"}) '''
from flask import Flask, request import ast from parse_rest.connection import register #Connects to the PArse Database. Format: <application_id>, <rest_api_key>[, master_key=None] register("HW8S7gMIafiQQszmJme2IS4Be7jFlRHnE0izdtLs", "D0lEeiwQ62X6POKXJ1RTxbHuDPX91aUvditAIjxC", master_key="fDtm8fpoHSxbeH3iUGaEexoRgsSdiBh2MvYGDjej") #File Handling import os from flask import Flask, request, redirect, url_for, jsonify from werkzeug import secure_filename import json, httplib UPLOAD_FOLDER = '/Users/Steven-PC/Desktop/' ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif', 'bin']) #Parse handling from parse_rest.datatypes import Object from PIL import Image import urllib, cStringIO def imagesRetrieve(): class ImageStorageDev(Object): pass #Get data from parse by objectId #dataRow = ImageStorageDev.Query.get(objectId="uqA3Ycyqnq") imageDict = {}
from parse_rest.core import ResourceRequestNotFound from parse_rest.connection import register, ParseBatcher from parse_rest.datatypes import GeoPoint, Object, Function, Pointer from parse_rest.user import User from parse_rest import query from parse_rest.installation import Push try: import settings_local except ImportError: sys.exit('You must create a settings_local.py file with APPLICATION_ID, ' \ 'REST_API_KEY, MASTER_KEY variables set') register(getattr(settings_local, 'APPLICATION_ID'), getattr(settings_local, 'REST_API_KEY'), master_key=getattr(settings_local, 'MASTER_KEY')) GLOBAL_JSON_TEXT = """{ "applications": { "_default": { "link": "parseapi" }, "parseapi": { "applicationId": "%s", "masterKey": "%s" } }, "global": { "parseVersion": "1.1.16" }
import subprocess as sp PARSE_HOSTNAME = os.getenv('PARSE_HOSTNAME', 'http://parse-server:1337/parse') PARSE_APP_ID = os.getenv('PARSE_APP_ID', 'alaska') PARSE_MASTER_KEY = os.getenv('PARSE_MASTER_KEY', 'MASTER_KEY') # Setup for parse_rest os.environ["PARSE_API_ROOT"] = PARSE_HOSTNAME from parse_rest.config import Config from parse_rest.datatypes import Function, Object, GeoPoint from parse_rest.connection import register from parse_rest.query import QueryResourceDoesNotExist from parse_rest.connection import ParseBatcher from parse_rest.core import ResourceRequestBadRequest, ParseError register(PARSE_APP_ID, '', master_key=PARSE_MASTER_KEY) def build_bowtie2(reference, nthreads=1): """ Builds bowtie2 index. """ print('building bowtie index', file=sys.stderr) logfile = os.path.join(reference.paths['root'], 'bowtie2_log.txt') if os.path.isfile(logfile): os.remove(logfile) dna_path = reference.paths['dna'] out_path = reference.paths['bowtieIndex'] # Make output directory.
from parse_rest.connection import register from parse_rest.datatypes import Object import key register(key.APP_ID, key.REST_API_KEY) class KeymochiTest(Object): pass keymochi = KeymochiTest(user="******", mood="happy") keymochi.save()
import os, sys APPLICATION_ID = "15DQ4FEwTwxxXOTwjDKwDsyyZGLfTTZS9WTQlWaN" REST_API_KEY = "RIVWH59VFaPUqER09SjeJbxYA8NwDW1yOisuvBuv" from parse_rest.connection import register, ParseBatcher from parse_rest.datatypes import Object as ParseObject register(APPLICATION_ID, REST_API_KEY) anyObject = ParseObject() name = raw_input("Enter your name: ") zipcode = raw_input("Enter your zip code: ") userObject = ParseObject() userObject.name = name userObject.zipcode = int(zipcode) hates = [] while True: hate = raw_input("Tell me something you hate: ") if(hate == "nothing"): break else: hates.append(hate) userObject.hates = hates def saveToParse(anyObject): print "Saving..." anyObject.save() print "Done!"
pass parser = argparse.ArgumentParser(description='Updated the channels for all Users on OneTap. Defaults to dev, pass the correct keys to use another app.') parser.add_argument('application_key', nargs='?', default='nORiB9P52mCaD1Sm72mKQlhLcjgHGjGkpvW7tZO5') parser.add_argument('rest_api_key', nargs='?', default='0oQwqO36Txv9GeDxkqbi9Fdp3go82BHtNpew18We') parser.add_argument('master_key', nargs='?', default='R5YWuexk6BUdrCGrkz5HqLDvozv5iAzjw4lUC1AX') parser.add_argument('-d', '--delay', type=float, help='The delay between each batch save', default=2.0) parser.add_argument('-u', '--user_id', type=str, help='A specific user id to update') args = parser.parse_args() register(args.application_key, args.rest_api_key, master_key=args.master_key) batch_saver = BatchSaver(args.delay) # PUSH NOTIFICATION CHANNELS # drive-objectid # Friend of the user with this objectid and want drive notifications # ie. Alice wants drive notifications for Bob she will have the channel drive-bob # friend-objectid # Friend of the user with this objectid but don't want drive notifications # ie. Alice does not want drive notifications for Bob she will have the channel friend-bob # user-objectid # The users personal channel for targeting their devices
# Modified: # * # ########################################################################################## import numpy as np import matplotlib.pyplot as plt import datetime from parse_rest.connection import register from parse_rest.datatypes import Object class TestData(Object): pass if __name__ == '__main__': register('mROIEsIqVeYLTXOgrcAODzdWMDiuzmQq6amBecNE', '0mvacQYGeG6136k1xKgMnUSjssdvjnaPge6pfTfE', master_key = 'ZrIxVKXJ5Wo60PIKLpsnzt4y9MJlSJy9DLKarOWX') currentTime = datetime.datetime.now().isoformat(' ') number_squeezed = 6 testData = TestData(Time = currentTime, Location = "UL Lafayette", NumberOfTubes = number_squeezed) testData.save() # Read the data all_data = TestData.Query.all() for data in all_data: print data.Time, data.Location, data.NumberOfTubes
sensor.open = True sensor.save() def smoke_off(all_sensors, all_rules): smoke = False for sensor in all_sensors: if sensor.name == 'Smoke': sensor.open = False sensor.save() def water_on(all_sensors, all_rules): water = True for sensor in all_sensors: if sensor.name == 'Water': sensor.open = True sensor.save() def water_off(all_sensors, all_rules): water = False for sensor in all_sensors: if sensor.name == 'Water': sensor.open = False sensor.save() if __name__ == '__main__': register(APPLICATION_ID, REST_API_KEY) app.run(debug=True)
if ip != None and len(update) == 8: uri = 'http://{}:1337/parse'.format(ip) # Define path to parse app os.environ["PARSE_API_ROOT"] = uri from parse_rest.datatypes import Function, Object, GeoPoint from parse_rest.connection import register from parse_rest.query import QueryResourceDoesNotExist from parse_rest.connection import ParseBatcher from parse_rest.core import ResourceRequestBadRequest, ParseError # App Variables register(parse['APPLICATION_ID'], parse['REST_API_KEY'], master_key=parse['MASTER_KEY']) # Database Structures plantKeys = ['piso', 'lado', 'linea', 'contador'] # Create Planta Class to Query class Plant(Object): piso = 1 lado = 'A' linea = 1 contador = 0 pass class Config(Object): pass
import requests import datetime import time import subprocess from requests.exceptions import RequestException from parse_rest.connection import register from parse_rest.datatypes import Object from parse_rest.datatypes import ACL from HeadCount import HeadCount # from xml.etree import ElementTree import config # Parse initialization register(config.APPLICATION_ID, config.REST_API_KEY, master_key=config.MASTER_KEY) ip = config.router['ip'] try: # Router login payload = config.router loginReq = requests.post('http://%s/cgi-bin/login' % ip, data=payload) # Router Wi-Fi devices request headers = { 'X-Requested-With': 'XMLHttpRequest', 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' } formdata = '<xmlrequest version="1.0.1"><command inst="cfgmgr-0"><key>begin_transaction</key><value>wireless-0</value></command><command inst="cfgmgr-0"><key>begin_transaction</key><value>wireless-1</value></command><query inst="wireless-0"><key>ap0_sta_list</key><value/></query><query inst="wireless-0"><key>ap1_sta_list</key><value/></query><query inst="wireless-0"><key>ap2_sta_list</key><value/></query><query inst="wireless-0"><key>ap3_sta_list</key><value/></query><query inst="wireless-1"><key>ap0_sta_list</key><value/></query><query inst="wireless-1"><key>ap1_sta_list</key><value/></query><query inst="wireless-1"><key>ap2_sta_list</key><value/></query><query inst="wireless-1"><key>ap3_sta_list</key><value/></query><command inst="cfgmgr-0"><key>commit</key><value>wireless-0</value></command><command inst="cfgmgr-0"><key>commit</key><value>wireless-1</value></command><command inst="cfgmgr-0"><key>end_transaction</key><value>wireless-0</value></command><command inst="cfgmgr-0"><key>end_transaction</key><value>wireless-1</value></command></xmlrequest>'
from flask import Flask, jsonify, request, redirect, url_for, session from flask.ext.cors import CORS from flask_oauthlib.client import OAuth, OAuthException import json from nutritionix import Nutritionix from werkzeug import secure_filename import cloudsight from parse_rest.connection import register, SessionToken from parse_rest.datatypes import Object from parse_rest.user import User register('O6H2V7pJzoOWntRT9hFqpxxHHdJTCLtA7xmnhHZ5', 'olPs7M45S8mx7RpdSOSbAqfZbfBKjLzDzqISSivP', master_key='ZSpZtkfRzOziXOOJEy9kGjaTDVaju64YQcbLeBRH') auth = cloudsight.SimpleAuth('qAd-COIpRxvKVaNUKrJMMQ') api = cloudsight.API(auth) nix = Nutritionix(app_id="76986486", api_key="28882f3d105c4c9e3222a05eeafd049a") UPLOAD_FOLDER = 'tmp' ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg']) FACEBOOK_APP_ID = os.environ['FACEBOOK_APP_ID'] FACEBOOK_APP_SECRET = os.environ['FACEBOOK_APP_SECRET'] app = Flask(__name__) app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
import socket, sys,logging,traceback,re,urllib import threading import thread import copy import math from SimpleXMLRPCServer import SimpleXMLRPCServer from SimpleXMLRPCServer import SimpleXMLRPCRequestHandler from parse_rest.connection import register from parse_rest.datatypes import Object,GeoPoint from parse_rest.query import Queryset from parse_rest.query import QueryResourceDoesNotExist from struct import * sys.excepthook = lambda *args: None register(sipLocatorConfig.PARSE_APPLICATION_ID, sipLocatorConfig.PARSE_REST_API_KEY) systemErrors = { 1: 'Method not supported', 2: 'Duplicate callID', 4: 'No such callID', 5: 'No such message', 6: 'Too many calls.', 7: 'Too many messages.', 8: 'No callID supplied', 10: 'No geoLocation supplied', 13: 'GeoLocation search not enabled', 15: 'Insufficient privileges', 16: 'Invalid callID value', 17: 'Call reservation failure', 18: 'Duplicate numeric ID',
from parse_rest.connection import register from itsdangerous import (TimedJSONWebSignatureSerializer as Serializer, BadSignature, SignatureExpired) from passlib.apps import custom_app_context as pwd_context import twilio from twilio.rest import TwilioRestClient import boto import analytics app = Flask(__name__) app.config.from_object("config") app.config["DEBUG"] = True register(app.config["PARSE_APP_ID"], app.config["PARSE_RESTAPI_KEY"]) auth = HTTPBasicAuth() @app.errorhandler(400) def bad_request(error): return make_response(jsonify({"error": error.description}), 400) @app.errorhandler(401) def unauthorized_401(error): return make_response(jsonify({"error": error.description}), 401) @app.errorhandler(404) def not_found(error): return make_response(jsonify({"error": error.description}), 404)
# !!!!Need to install ParsePy first # https://github.com/dgrtwo/ParsePy import datetime import time import parse_rest from parse_rest.connection import register from parse_rest.datatypes import Object # Keys for YList app. register("PRlCTmsvTNBeypIrP63NBkJBGxG8e84yzqX7FEdj", "I9h1MW4N3Ntq4bpNjcTZCWLa3ay7xlLO0VMnVWLE") # ORM for YList object. class YList(Object): pass # Sample Data comments=[{ "creator": "*****@*****.**", "up": 0, "down": 0, "message": "1 reply message","postedAt": time.strftime('%Y-%m-%dT%H:%M:%S.%f%Z') }] # Sample code to populate data. item = YList( topic="Topic", \ up=0, \ down=0, \ message="message", \ creator="*****@*****.**", \ postedAt=parse_rest.datatypes.Date(datetime.datetime.now()), \ comments=comments ) # Save to Parse server.
''' Script for faking runners for CrowdCheer ''' # register with parse from parse_rest.connection import register, ParseBatcher from parse_rest.user import User from parse_rest.datatypes import Object, GeoPoint batcher = ParseBatcher() import datetime from time import sleep import random import json, httplib, os, requests from settings_local import * register(APPLICATION_ID, REST_API_KEY, master_key=MASTER_KEY) API_ROOT = os.environ.get('PARSE_API_ROOT') #RunnerLocations class class RunnerLocations(Object): pass def nowVersion(self): rl = RunnerLocations() rl.location = self.location rl.time = datetime.datetime.now() rl.user = self.user rl.distance = self.distance rl.duration = self.duration rl.speed = self.speed rl.save()