Esempio n. 1
0
def user_contactus(): #Setup and start smtp server on the instance
    (traffic, created) = TrafficModel.objects.get_or_create(created_at=str(datetime.datetime.utcnow()), service="cloud", endpoint="/public/user/contactus")
    if not created:
        traffic.interactions += 1 
        traffic.save()
        
    if fk.request.method == 'POST':
        if fk.request.data:
            data = json.loads(fk.request.data)
            try:
                email = data.get("email", "")
                message = data.get("message", "")
                msg = MIMEText("Dear user,\n You contacted us regarding the following matter:\n-------\n%s\n-------\nWe hope to reply shortly.\nBest regards,\n\nDDSM team."%message)
                msg['Subject'] = 'DDSM -- You contacted us!'
                msg['From'] = "*****@*****.**" # [email protected]
                msg['To'] = email
                msg['CC'] = "*****@*****.**"
                s = smtplib.SMTP('localhost')
                s.sendmail("*****@*****.**", email, msg.as_string())
                s.quit()
                return fk.Response('Message sent.', status.HTTP_200_OK)
            except:
                print str(traceback.print_exc())
                return fk.make_response("Could not send the email.", status.HTTP_503_SERVICE_UNAVAILABLE)
        else:
            return fk.make_response("Missing mandatory fields.", status.HTTP_400_BAD_REQUEST)
    else:
        return fk.make_response('Method not allowed.', status.HTTP_405_METHOD_NOT_ALLOWED)
Esempio n. 2
0
def club_pictures(rowkey):
    if not check_auth(request):
        abort(403)
    if request.method == 'POST':
        # check if the post request has the file part
        if 'file' not in request.files:
            return make_response('No file part', 400)
        file = request.files['file']
        # if user does not select file, browser also
        # submit a empty part without filename
        if file.filename == '':
            return make_response('No file part', 400)
        if not allowed_file(file.filename):
            return make_response('The filetype is not allowed')
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            filename = rowkey + "." + filename.rsplit('.', 1)[1]
            file.save(os.path.join(app.config['CLUB_PICTURE_UPLOAD_FOLDER'], filename))
            db_picture = db_session.query(UserFile).filter_by(owner=rowkey, file_type='ProfilePicture')
            if len(list(db_picture)) == 0:
                db_picture = UserFile()
                db_picture.file_type = 'ProfilePicture'
                db_picture.owner = rowkey
                db_session.add(db_picture)
                db_session.commit()
                return make_response("",200)
            db_picture.update({"file_name":filename})
            db_session.commit()
            return make_response("", 200)
    if request.method == 'GET':
        filename = db_session.query(UserFile).filter_by(file_type='ProfilePicture', owner=rowkey)[0].file_name
        return jsonify({"filename":  str.replace(app.config['CLUB_PICTURE_UPLOAD_FOLDER'], "static\\Sloach\\", "") + "/" + filename})
Esempio n. 3
0
def keysign():
    response = make_response("Whoops, no pubkey specified!")
    if ssl_client_verify in request.headers:
        if "pubkey" in request.form and request.headers[ssl_client_verify] == "NONE":
            pubkey = "SPKAC="
            spkac = request.form['pubkey']
            for char in removedchars:
                spkac = spkac.replace(char, "")
            pubkey += spkac

            certAttributes['CN'] = random.randint(0, 1000)
            if "CN" in request.form:
                certAttributes['CN'] = request.form['CN']

            for attribute in certAttributes:
                pubkey += "\n%s=%s" % (attribute, certAttributes[attribute])
            try:
                openssl = subprocess.check_output(opensslcmd,
                                                  input=pubkey.encode('utf-8'))
                response = make_response(openssl)
                response.headers['Content-Type'] = "application/x-x509-user-cert"
            except subprocess.CalledProcessError:
                response = jsonify({
                    "result": "OpenSSL command failed",
                    "command": opensslcmd,
                    "stdin": pubkey
                })
        else:
            return "You silly goose, you already have a certificate! You can't make another one"
    return response
Esempio n. 4
0
def public_user_picture(user_id):
    (traffic, created) = TrafficModel.objects.get_or_create(created_at=str(datetime.datetime.utcnow()), service="cloud", endpoint="/public/user/picture/<user_id>")
    if not created:
        traffic.interactions += 1 
        traffic.save()
        
    if fk.request.method == 'GET':
        user_model = UserModel.object.with_id(user_id)
        if user_model == None:
            return fk.redirect('http://0.0.0.0:5000/error-204/')
        else:
            profile_model = ProfileModel.object(user=user_model).first_or_404()
            if profile_model.picture['scope'] == 'remote':
                return fk.redirect(profile_model.picture['location'])
            elif profile_model.picture['scope'] == 'local':
                if profile_model.picture['location']:
                    picture = load_picture(profile_model)
                    print picture[1]
                    return fk.send_file(
                        picture[0],
                        mimetypes.guess_type(picture[1])[0],
                        as_attachment=True,
                        attachment_filename=profile_model.picture['location'],
                    )
                else:
                    print "Failed because of picture location not found."
                    return fk.make_response('Empty location. Nothing to pull from here!', status.HTTP_204_NO_CONTENT)
    else:
        return fk.make_response('Method not allowed.', status.HTTP_405_METHOD_NOT_ALLOWED)


# Picture upload
#    Update the picture field to: local and the name of the file.

#Picture get link to retrieve file
Esempio n. 5
0
def merge():
    try:
        if request.method == 'OPTIONS':
            return make_response(jsonify({"Allow":"POST"}), 200)

        if not request.json or not 'foreground_url' in request.json or not 'background_url' in request.json:
            abort(400)

        foreground_url = request.json['foreground_url']
        background_url = request.json['background_url']
        m = Merger(foreground_url, background_url)
        m.merge_images()
        response = {
            'output_image':{
                'name': m.get_output_image('name'),
                'url' : url_for('get_image', image_name = m.get_output_image('name'),_external=True),
                'base64' : m.get_output_image('base64')
            }
        }
        return jsonify(response), 201
    except Exception as e:
        err_msg = e.message
        if  err_msg == '':
            err_msg = 'Internal Error. Please Try Again'
        return make_response(jsonify({'error': e.message}), 202)
    def api_create(self):
        is_valid_form = True
        get_filter_args(self._filters)
        exclude_cols = self._filters.get_relation_cols()
        form = self.add_form.refresh()

        self._fill_form_exclude_cols(exclude_cols, form)
        if form.validate():
            item = self.datamodel.obj()
            form.populate_obj(item)
            self.pre_add(item)
            if self.datamodel.add(item):
                self.post_add(item)
                http_return_code = 200
            else:
                http_return_code = 500
        else:
            is_valid_form = False
        if is_valid_form:
            response = make_response(jsonify({'message': self.datamodel.message[0],
                                              'severity': self.datamodel.message[1]}), http_return_code)
        else:
            # TODO return dict with errors
            response = make_response(jsonify({'message': 'Invalid form',
                                              'severity': 'warning'}), 500)
        return response
    def api_update(self, pk):
        is_valid_form = True
        get_filter_args(self._filters)
        exclude_cols = self._filters.get_relation_cols()

        item = self.datamodel.get(pk, self._base_filters)
        if not item:
            abort(404)
        # convert pk to correct type, if pk is non string type.
        pk = self.datamodel.get_pk_value(item)

        form = self.edit_form.refresh(request.form)
        # fill the form with the suppressed cols, generated from exclude_cols
        self._fill_form_exclude_cols(exclude_cols, form)
        # trick to pass unique validation
        form._id = pk
        if form.validate():
            form.populate_obj(item)
            self.pre_update(item)
            if self.datamodel.edit(item):
                self.post_update(item)
                http_return_code = 200
            else:
                http_return_code = 500
        else:
            is_valid_form = False
        if is_valid_form:
            response = make_response(jsonify({'message': self.datamodel.message[0],
                                              'severity': self.datamodel.message[1]}), http_return_code)
        else:
            # TODO return dict with from errors validation
            response = make_response(jsonify({'message': 'Invalid form',
                                              'severity': 'warning'}), 500)
        return response
Esempio n. 8
0
def gdisconnect():
    # Only disconnect a connected user.
    credentials = login_session.get('credentials')
    if credentials is None:
        response = make_response(json.dumps('Current user not connected.'), 401)
        response.headers['Content-Type'] = 'application/json'
        return response
    parsed_json = json.loads(credentials)
    access_token = parsed_json['access_token']
    url = 'https://accounts.google.com/o/oauth2/revoke?token=%s' % access_token
    h = httplib2.Http()
    result = h.request(url, 'GET')[0]

    if result['status'] == '200':
        # Reset the user's sesson.
        del login_session['credentials']
        del login_session['gplus_id']
        del login_session['username']
        del login_session['email']
        del login_session['picture']

        return redirect('/login')
    else:
        # For whatever reason, the given token was invalid.
        response = make_response(json.dumps('Failed to revoke token for given user.', 400))
        response.headers['Content-Type'] = 'application/json'
        return response
Esempio n. 9
0
def unauthorize():
    # Unauthorize on POST.
    if request.method == 'POST':
        # Checks if user is connected prior to attempting a disconnect.
        access_token = login_session.get('access_token')
        if access_token is None:
            response = make_response(json.dumps('Current user not connected.'), 401)
            add_headers(response)
            return response

        url = 'https://accounts.google.com/o/oauth2/revoke?token=%s' % access_token
        h = httplib2.Http()
        result = h.request(url, 'GET')[0]

        if result['status'] == '200':
            # Resets the user's session.
            del login_session['access_token']
            del login_session['gplus_id']
            del login_session['username']
            del login_session['email']
            del login_session['picture']

            response = make_response(json.dumps('Successfully disconnected.'), 200)
            add_headers(response)
            return response

        else:
            # Alerts if unable to disconnect.
            response = make_response(json.dumps('Failed to revoke token for given user.', 400))
            add_headers(response)
            return response

    response = make_response()
    add_headers(response)
    return response
Esempio n. 10
0
def gcodeFileCommand(filename, target):
	if not target in [FileDestinations.LOCAL, FileDestinations.SDCARD]:
		return make_response("Unknown target: %s" % target, 404)

	if not _verifyFileExists(target, filename):
		return make_response("File not found on '%s': %s" % (target, filename), 404)

	# valid file commands, dict mapping command name to mandatory parameters
	valid_commands = {
		"select": []
	}

	command, data, response = util.getJsonCommandFromRequest(request, valid_commands)
	if response is not None:
		return response

	if command == "select":
		# selects/loads a file
		printAfterLoading = False
		if "print" in data.keys() and data["print"]:
			if not printer.isOperational():
				return make_response("Printer is not operational, cannot directly start printing", 409)
			printAfterLoading = True

		sd = False
		if target == FileDestinations.SDCARD:
			filenameToSelect = filename
			sd = True
		else:
			filenameToSelect = gcodeManager.getAbsolutePath(filename)
		printer.selectFile(filenameToSelect, sd, printAfterLoading)

	return NO_CONTENT
Esempio n. 11
0
def deleteGcodeFile(filename, target):
	if not target in [FileDestinations.LOCAL, FileDestinations.SDCARD]:
		return make_response("Unknown target: %s" % target, 404)

	if not _verifyFileExists(target, filename):
		return make_response("File not found on '%s': %s" % (target, filename), 404)

	sd = target == FileDestinations.SDCARD

	currentJob = printer.getCurrentJob()
	currentFilename = None
	currentSd = None
	if currentJob is not None and "filename" in currentJob.keys() and "sd" in currentJob.keys():
		currentFilename = currentJob["filename"]
		currentSd = currentJob["sd"]

	# prohibit deleting the file that is currently being printed
	if currentFilename == filename and currentSd == sd and (printer.isPrinting() or printer.isPaused()):
		make_response("Trying to delete file that is currently being printed: %s" % filename, 409)

	# deselect the file if it's currently selected
	if currentFilename is not None and filename == currentFilename:
		printer.unselectFile()

	# delete it
	if sd:
		printer.deleteSdFile(filename)
	else:
		gcodeManager.removeFile(filename)

	return NO_CONTENT
Esempio n. 12
0
    def front(self, request):
        loginfo = "[Ebatong Front] form: {}"
        logger.info(loginfo.format(request.values.to_dict()))
        try:
            if self.validate_signature(request):
                total_fee = Decimal(str(request.values['total_fee']))
                if request.values['trade_status'] == 'TRADE_FINISHED':
                    self.accept(request, total_fee)
                    msgstr = '/#!/account/funding/deposit?success=您成功充值了{}元!'
                    total_fee = float_quantize_by_two(
                        request.values['total_fee'])

                    return make_response(
                        redirect(msgstr.format(total_fee))
                    )
                else:
                    self.reject(request, total_fee)
                    msgstr = ('/#!/account/funding/deposit?error=抱歉!'
                              '您的充值操作遇到了问题,请联系客服!')
                    return make_response(redirect(msgstr))
        except Exception as e:
            logger.error('[Ebatong Front Error] Error: {}'.format(e),
                         exc_info=1)
            msgstr = '/#!/account/funding/deposit?error=抱歉!您的充值操作遇到了问题,请联系客服!'
            return make_response(redirect(msgstr))
        else:
            return make_response(redirect('/#!/account/funding/deposit'))
Esempio n. 13
0
    def front(self, request):
        loginfo = "[Yintong Front] form: {}"
        logger.info(loginfo.format(request.values.to_dict()))
        try:
            if self.validate_signature(request):
                money_order = Decimal(str(request.values['money_order']))
                if request.values['result_pay'] == 'SUCCESS':
                    self.accept(request, money_order)
                    msgstr = '/#!/account/funding/deposit?success=您成功充值了{}元!'
                    money_order = float_quantize_by_two(
                        request.values['money_order'])

                    return make_response(
                        redirect(msgstr.format(money_order))
                    )
                else:
                    self.reject(request, money_order)
                    msgstr = ('/#!/account/funding/deposit?error=抱歉!'
                              '您的充值操作遇到了问题,请联系客服!')
                    return make_response(redirect(msgstr))
        except Exception as e:
            logger.error('[Yintong Front Error] Error: {}'.format(e),
                         exc_info=1)
            msgstr = '/#!/account/funding/deposit?error=抱歉!您的充值操作遇到了问题,请联系客服!'
            return make_response(redirect(msgstr))
        else:
            return make_response(redirect('/#!/account/funding/deposit'))
Esempio n. 14
0
def gdisconnect():
    """
    Revoke user token and reset login_session
    """
    # Use AccessTokenCredentials for fix bug in Flask
    credentials = AccessTokenCredentials(login_session['credentials'], 'user-agent-value')
    if credentials is None:
        response = make_response(json.dumps("Current user not connected."), 401)
        response.headers['Content-Type'] = 'application/json'
        return response

    # Execute HTTP GET to revoke token
    access_token = credentials.access_token
    url = 'https://accounts.google.com/o/oauth2/revoke?token=%s' % access_token
    h = httplib2.Http()
    result = h.request(url, 'GET')[0]

    if result['status'] == '200':
        response = make_response(json.dumps('Successfully disconnected!'), 200)
        response.headers['Content-Type'] = 'application/json'
        return response
    else:
        response = make_response(json.dumps('Failed to revoke token for given user'), 400)
        response.headers['Content-Type'] = 'application/json'
        return response
Esempio n. 15
0
 def front(self, request):
     """
         充值 - 浏览器回调
         1. v_pstatus 参数等于20 - 通过 其他参数为失败
         2. 完成后跳转到用户中心界面
     """
     try:
         logger.info("[ChinaBank recv] values: {}".format(request.values))
         if self.validate_signature(request):
             if request.values['v_pstatus'] == '20':
                 self.accept(request, float(request.values['v_amount']))
                 msgstr = '/#!/account/funding/deposit?success=您成功充值了{}元'
                 return make_response(
                     redirect(msgstr.format(
                         float_quantize_by_two(request.values['v_amount']))
                     )
                 )
             else:
                 self.reject(request, float(request.values['v_amount']))
                 msgstr = ('/#!/account/funding/deposit?error=抱歉!'
                           '您的充值操作遇到了问题,请联系客服!')
                 return make_response(redirect(msgstr))
     except Exception as exception:
         loginfo = "[ChinaBank front Error] Request: {}, Error: {}"
         logger.error(loginfo.format(request, exception), exc_info=1)
         raise exception
     else:
         return make_response(redirect('/#!/account/funding/deposit'))
 def get(self, clientId, ansId):
     if ansId is None:
         ans = ClientResponse.query.all()
         message = {"results": (ClientResponse.serialize_list(ans))}
         return make_response(jsonify(message), 200)
     ans = ClientResponse.query.filter(ClientResponse.id==id).first()
     return make_response(json.dumps(ans.serialize()), 200)
Esempio n. 17
0
def get_ip():
     tag = "tag_Name_" + request.args.get('host')
     env = request.args.get('env')
     eip = request.args.get('eip').capitalize() if 'eip' in request.url else False
     inventory_file = ec2_inventory_path + env + "/ec2.py"

     if env not in envs:
        return make_response(json.dumps({'error': env + ' Environment not found'}),400)

     inv = Inventory(inventory_file)
     if len(inv.get_hosts(tag)) == 0:
        msg = "No Host match for {} in {}".format(request.args.get('host'), env)
        return make_response(json.dumps({'error': msg}),400) 

     if eip == False:
         #print "Checking IP of {} for Env: {}".format(tag,env)
         ipaddr = ','.join([ ip.name for ip in inv.get_hosts(tag)])
     else:
         #print "Checking EIP of {} for Env: {}".format(tag,env)
         data = ansible.runner.Runner(
                        module_name='debug', 
                        pattern=tag, 
                        inventory = inv, 
                        transport = 'local', 
                        module_args="var=hostvars['{{ inventory_hostname }}']['ec2_ip_address']"
         ).run()
         element = data['contacted'].keys()
         ipaddr = ','.join([ ''.join(data['contacted'][e]['var'].values()) for e in element])
         if len(ipaddr) == 0:
            msg = "No EIP Found for {} in {}".format(request.args.get('host'), env)
            return make_response(json.dumps({'error': msg}),400) 
 
     return  ipaddr
Esempio n. 18
0
    def post(self):
        args = parser.parse_args()
        dest = args['dest']
        # check if dest worker registered
        if args['action'] == 'purge':
            count = celery.control.purge()
            return jsonify({"msg": "{} tasks have been discarded".format(count)})

        registered = celery.control.inspect(dest).registered()
        if not registered:
            response = make_response(jsonify({
                "msg": "Invalid woker name appears."
            }), 400)
            return response

        if args['action'] == 'cancel_consumer':
            return celery.control.cancel_consumer(args['task'], reply=True, destination=args['dest'])
        elif args['action'] == 'pool_restart':
            return celery.control.broadcast('pool_restart', arguments={'reload': True}, reply=True)
        elif args['action'] == 'shutdown':
            celery.control.broadcast('shutdown', destination=args['dest'])
            return jsonify({
                "msg": "Shutdown messages have sent to {}".args['dest']
            })
        else:
            response = make_response(jsonify({
                "msg": "Invalid action."
            }), 400)
            return response
Esempio n. 19
0
def bad_request(error):
    """
    Bad Request response for a request. Takes an error message.
    """
    if isinstance(error, BadRequest):
        return make_response(jsonify({'code': 400, 'error': 'BadRequest'}), 400)
    return make_response(jsonify({'code': 400, 'error': error}), 400)
Esempio n. 20
0
def markers(methods=["GET", "POST"]):
    logging.debug('getting markers')
    if request.method == "GET":
        ne_lat = float(request.values['ne_lat'])
        ne_lng = float(request.values['ne_lng'])
        sw_lat = float(request.values['sw_lat'])
        sw_lng = float(request.values['sw_lng'])
        zoom = int(request.values['zoom'])
        start_date = datetime.date.fromtimestamp(int(request.values['start_date']))
        end_date = datetime.date.fromtimestamp(int(request.values['end_date']))
        fatal = request.values['show_fatal']
        severe = request.values['show_severe']
        light = request.values['show_light']
        inaccurate = request.values['show_inaccurate']
        min_zoom_level = 16
        if zoom < min_zoom_level:
            markers = []
        else:
            # query = Marker.all()

            # if 'start_time' in request.values:
            #     query = query.filter("created >=", request.values["start_time"])
            # if 'start_time' in request.values:
            #     query = query.filter("created <=", request.values["end_time"])
            print ""
            logging.debug('querying markers in bounding box')
            results = Marker.bounding_box_fetch(ne_lat, ne_lng, sw_lat, sw_lng,
                                                start_date, end_date,
                                                fatal, severe, light, inaccurate)
            logging.debug('serializing markers')
            markers = [marker.serialize() for marker in results.all()]

        if request.values.get('format') == 'csv':
            if not markers:
                raise Exception("No markers available.")

            output_file = StringIO()
            output = csv.DictWriter(output_file, markers[0].keys())
            output.writeheader()
            for marker in markers:
                row = {k: v.encode('utf8')
                       if type(v) is unicode else v
                       for k, v in marker.iteritems()}
                output.writerow(row)

            return make_response((output_file.getvalue(),
                200,
                {u'Content-Type': 'text/csv',
                 u'Content-Disposition': u'attachment; filename="data.csv"'}))

        else: # defaults to json
            return jsonify(markers=markers)

    else:
        data = json.loads(self.request.body)
        marker = Marker.parse(data)
        marker.user = self.user
        marker.update_location()
        marker.put()
        return make_response(json.dumps(marker.serialize(self.user)))
Esempio n. 21
0
 def get(self, name):
     args = parser.parse_args()
     # select worker
     if name == 'all':
         inspect = celery.control.inspect()
     else:
         inspect = celery.control.inspect([name])
     # test if worker registered
     if inspect.registered():
         # if not specify the task, return the stats of the worker
         if args['task']:
             if args['task'] == 'active':
                 return jsonify(inspect.active())
             elif args['task'] == 'scheduled':
                 return jsonify(inspect.scheduled())
             elif args['task'] == 'reserved':
                 return jsonify(inspect.reserved())
             else:
                 response = make_response(jsonify({
                     "msg": "Invalid task type."
                 }), 400)
         else:
             response = jsonify(inspect.stats())
     else:
         response = make_response(jsonify({
             "msg": "Invalid worker name."
         }), 400)
     return response
Esempio n. 22
0
 def delete(self, uuid):
     '''Handle delete by UUID.'''
     try:
         handle_delete(uuid)
         return make_response(200, { "success": True })
     except Exception, e:
         return make_response(400, { "success": False, "error": e.message })
def register():
    # The POST should include `email`
    email = request.form.get('email', None)[:32]

    # The POST should include `password`
    _password = request.form.get('password', None)[:32]

    # Validate the parameters POST'ed (intentionally not too strict)
    if not email or not _password:
        return make_response('Bad Request', 400)

    # Hash password
    password = CredentialStore.hash(_password)
    # Perform relevant sanitization/validation on your own code.
    # This demo omits them on purpose for simplicity.
    profile = {
        'id':       email,
        'email':    email,
        'name':     request.form.get('name', ''),
        'password': password,
        'imageUrl': '/images/default_img.png'
    }

    # Overwrite existing user
    store = CredentialStore(id=profile['id'], profile=profile)
    store.put()

    session['id'] = profile['id']

    # Not making a session for demo purpose/simplicity
    return make_response('Registered', 200)
def pwauth():
    # The POST should include `email`
    email = request.form.get('email', None)[:32]
    # The POST should include `password`
    password = request.form.get('password', None)[:32]

    if not email or not password:
        return make_response('Authentication failed', 401)

    # Obtain Datastore entry by email address
    store = CredentialStore.get_by_id(email)

    # If the store doesn't exist, fail.
    if store is None:
        return make_response('Authentication failed', 401)

    profile = store.profile

    # If the profile doesn't exist, fail.
    if profile is None:
        return make_response('Authentication failed', 401)

    # If the password doesn't match, fail.
    if CredentialStore.verify(password, profile['password']) is False:
        return make_response('Authentication failed', 401)

    session['id'] = email

    # Not making a session for demo purpose/simplicity
    return make_response('Authenticated', 200)
def gauth():
    # The POST should include `id_token`
    id_token = request.form.get('id_token', '')[:3072]

    # Verify the `id_token` using API Client Library
    idinfo = client.verify_id_token(id_token, CLIENT_ID)

    # Additional verification: See if `iss` matches Google issuer string
    if idinfo['iss'] not in ['accounts.google.com',
                             'https://accounts.google.com']:
        return make_response('Authentication failed', 401)

    id = idinfo['sub']

    # For now, we'll always store profile data after successfully
    # verifying the token and consider the user authenticated.
    store = CredentialStore.get_by_id(id)

    if store is None:
        store = CredentialStore(id=id)

    # Construct a profile object
    store.profile = {
        'id':        id,
        'imageUrl':  idinfo.get('picture', None),
        'name':      idinfo.get('name', None),
        'email':     idinfo.get('email', None)
    }
    store.put()

    session['id'] = id

    # Not making a session for demo purpose/simplicity
    return make_response('Authenticated', 200)
Esempio n. 26
0
def login():
    if request.method == "POST":
        user = request.form['username']
        pword = request.form['password']
        token = verify_user(user, pword)
        if "_$" in token:
            response = make_response(redirect(url_for('dashboard')))
            response.set_cookie("last_user", user)
            response.set_cookie("token", token)
            C.load_courses(user)
            return response

    user = request.cookies.get("last_user", "none")
    token = request.cookies.get("token", "none")
    auth = authenticate(user, token)
    if auth[:2] == "_$":
        response = make_response(redirect(url_for("dashboard")))
        response.set_cookie('token', auth)
        C.load_courses(user)
        return response
    else:
        if auth == "Timeout":
            return redirect(url_for("logout"))
        response = make_response(render_template("home.html"))
        response.set_cookie('token', "none")
        response.set_cookie('last_user', 'none')
        return response
Esempio n. 27
0
def plot_append():
    fig_name = request.headers.get('Figure-Name')
    if fig_name not in ploters:
        return make_response(jsonify({'status': 1, 'info': 'append not exist figure'}), 200)
    else:
        ploters[fig_name]['queue'].put([3, request.json])
        return make_response(jsonify({'status': 0}), 200)
Esempio n. 28
0
def gdisconnect():
# Only disconnect a connected user.
    access_token = login_session.get('credentials')
    if access_token is None:
        response = make_response(
            json.dumps('Current user not connected.'), 401)
        response.headers['Content-Type'] = 'application/json'
        print access_token
        return redirect(url_for('restaurantList'))
    url = 'https://accounts.google.com/o/oauth2/revoke?token=%s' % access_token
    h = httplib2.Http()
    result = h.request(url, 'GET')[0]
    if result['status'] == '200':
        # Reset the user's sesson.
        del login_session['credentials']
        del login_session['provider']
        del login_session['gplus_id']
        del login_session['username']
        del login_session['email']
        del login_session['image']
        del login_session['user_id']

        response = make_response(json.dumps('Successfully disconnected.'), 200)
        response.headers['Content-Type'] = 'application/json'
        return redirect(url_for('restaurantList'))
    else:
# For whatever reason, the given token was invalid.
        response = make_response(json.dumps('Failed to revoke token for given '
                                            'user. reason: '
                                            '{reason}'.format(reason=reason),
                                            400))
        response.headers['Content-Type'] = 'application/json'
        return redirect(url_for('restaurantList'))
Esempio n. 29
0
def google_logout():
    """Disconnect user's Google account"""
    # Only disconnect a connected user.
    access_token = login_session.get('access_token')
    if access_token is None:
        response = make_response(
            json.dumps('Current user not connected.'), 401)
        response.headers['Content-Type'] = 'application/json'
        return response
    url = 'https://accounts.google.com/o/oauth2/revoke?token=%s' % access_token
    h = httplib2.Http()
    result = h.request(url, 'GET')[0]
    if result['status'] == '200':
        # Reset the user's sesson.
        del login_session['access_token']
        del login_session['gplus_id']

        response = make_response(json.dumps('Successfully disconnected.'), 200)
        response.headers['Content-Type'] = 'application/json'
        return response
    else:
        # For whatever reason, the given token was invalid.
        response = make_response(
            json.dumps('Failed to revoke token for given user.', 400))
        response.headers['Content-Type'] = 'application/json'
        return response
Esempio n. 30
0
def login():
    user = get_user()
    if user:
        return make_response(json.dumps(user.serialize()))

    if request.json:
        facebook_data = request.json
        user_id = facebook_data["userID"]
        access_token = facebook_data["accessToken"]
        user_details = json.loads(urllib.urlopen("https://graph.facebook.com/me?access_token=" + access_token).read())
        # login successful
        if user_details["id"] == user_id:
            user = User.query.filter(User.email == user_details["email"]).scalar()
            if not user:
                user = User(
                    email = user_details["email"],
                    first_name = user_details["first_name"],
                    last_name = user_details["last_name"],
                    username = user_details["username"],
                    facebook_id = user_details["id"],
                    facebook_url = user_details["link"],
                    access_token = facebook_data["accessToken"]
                )
            else:
                user.access_token = facebook_data["accessToken"]

            db_session.add(user)
            set_user(user)
            return make_response(json.dumps(user.serialize()))
        else:
            raise Exception("Error in logging in.")
    else:
        raise Exception("No login data or user logged in.")
Esempio n. 31
0
def gconnect():
    # Validate state token
    if request.args.get('state') != login_session['state']:
        response = make_response(json.dumps('Invalid state parameter.'), 401)
        response.headers['Content-Type'] = 'application/json'
        return response
    # Obtain authorization code
    code = request.data

    try:
        # Upgrade the authorization code into a credentials object
        oauth_flow = flow_from_clientsecrets('client_secrets.json', scope='')
        oauth_flow.redirect_uri = 'postmessage'
        credentials = oauth_flow.step2_exchange(code)
    except FlowExchangeError:
        response = make_response(
            json.dumps('Failed to upgrade the authorization code.'), 401)
        response.headers['Content-Type'] = 'application/json'
        return response

    # Check that the access token is valid.
    access_token = credentials.access_token
    url = ('https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=%s'
           % access_token)
    h = httplib2.Http()
    result = json.loads(h.request(url, 'GET')[1])
    # If there was an error in the access token info, abort.
    if result.get('error') is not None:
        response = make_response(json.dumps(result.get('error')), 500)
        response.headers['Content-Type'] = 'application/json'
        return response

    # Verify that the access token is used for the intended user.
    gplus_id = credentials.id_token['sub']
    if result['user_id'] != gplus_id:
        response = make_response(
            json.dumps("Token's user ID doesn't match given user ID."), 401)
        response.headers['Content-Type'] = 'application/json'
        return response

    # Verify that the access token is valid for this app.
    if result['issued_to'] != CLIENT_ID:
        response = make_response(
            json.dumps("Token's client ID does not match app's."), 401)
        print("Token's client ID does not match app's.")
        response.headers['Content-Type'] = 'application/json'
        return response

    stored_access_token = login_session.get('access_token')
    stored_gplus_id = login_session.get('gplus_id')
    if stored_access_token is not None and gplus_id == stored_gplus_id:
        response = make_response(json.dumps('Current user is already connected.'),
                                 200)
        response.headers['Content-Type'] = 'application/json'
        return response

    # Store the access token in the session for later use.
    login_session['access_token'] = credentials.access_token
    login_session['gplus_id'] = gplus_id

    # Get user info
    userinfo_url = "https://www.googleapis.com/oauth2/v1/userinfo"
    params = {'access_token': credentials.access_token, 'alt': 'json'}
    answer = requests.get(userinfo_url, params=params)

    data = answer.json()

    login_session['username'] = data['name']
    login_session['picture'] = data['picture']
    login_session['email'] = data['email']
    # ADD PROVIDER TO LOGIN SESSION
    login_session['provider'] = 'google'

    # see if user exists, if it doesn't make a new one
    user_id = getUserID(data["email"])
    if not user_id:
        user_id = createUser(login_session)
    login_session['user_id'] = user_id

    output = ''
    output += '<h1>Welcome, '
    output += login_session['username']
    output += '!</h1>'
    output += '<img src="'
    output += login_session['picture']
    output += ' " style = "width: 300px; height: 300px;border-radius: 150px;-webkit-border-radius: 150px;-moz-border-radius: 150px;"> '
    flash("you are now logged in as %s" % login_session['username'])
    print( "done!")
    return output
Esempio n. 32
0
def search():
    search_text = request.form["q"]
    resp = make_response(usertweets.search_tweets(search_text))
    resp.status_code = 200
    resp.headers["Access-Control-ALlow-Origin"] = "*"    
    return resp
def tweet():
    if "command" in request.form \
      and request.form["command"] == "/tweet":
        trigger_id = request.form["trigger_id"]
        try:
            response = slack_web_client.views_open(
                trigger_id=trigger_id,
                view={
                    "type":
                    "modal",
                    "callback_id":
                    "modal-id-tweet",
                    "title": {
                        "type": "plain_text",
                        "text": "Tweet a message"
                    },
                    "submit": {
                        "type": "plain_text",
                        "text": "Submit"
                    },
                    "close": {
                        "type": "plain_text",
                        "text": "Cancel"
                    },
                    "blocks": [{
                        "type": "section",
                        "text": {
                            "type": "plain_text",
                            "text": "Use this form to tweet a status."
                        }
                    }, {
                        "type": "divider"
                    }, {
                        "type": "input",
                        "block_id": "b2-id",
                        "label": {
                            "type": "plain_text",
                            "text": "Message",
                        },
                        "element": {
                            "action_id": "a2-id",
                            "multiline": True,
                            "type": "plain_text_input",
                        }
                    }]
                })
            return make_response("", 200)
        except SlackApiError as e:
            code = e.response["error"]
            return make_response(f"Failed to open a modal due to {code}", 200)

    elif "payload" in request.form:
        payload = json.loads(request.form["payload"])
        # print(json.dumps(payload, indent=1))
        if payload["type"] == "block_actions" \
          and payload["view"]["callback_id"] == "modal-id":
            #   if payload["actions"]["type"] == "multi_channel_select":
            return 200

        if payload["type"] == "view_submission" \
          and payload["view"]["callback_id"] == "modal-id":
            submitted_data = payload["view"]["state"]["values"]
            print(
                submitted_data
            )  # {'b-id': {'a-id': {'type': 'plain_text_input', 'value': 'your input'}}}
            message = submitted_data['b2-id']['a2-id']['value']
            for i in submitted_data['b1-id']['a1-id']['selected_channels']:
                slack_web_client.chat_postMessage(channel=i, text=message)
            return make_response("", 200)

    return make_response("", 404)
Esempio n. 34
0
def hello():
    body, cookie = get()
    response = make_response(body.read())
    response.headers['Content-Type'] = 'image/png'
    response.set_cookie('Set-Cookie', cookie)
    return response
Esempio n. 35
0
def datagrid_css():
    return make_response(render_template('datagrid/css/datagrid.css'), 200,
                         {'Content-Type': 'text/css'})
Esempio n. 36
0
 def images(path):
     fullpath = os.path.join(app.root_path, 'images', path)
     resp = make_response(open(fullpath).read())
     resp.content_type = "image/jpeg"
     return resp
Esempio n. 37
0
def fbconnect():
    if request.args.get('state') != login_session['state']:
        response = make_response(json.dumps('Invalid state parameter.'), 401)
        response.headers['Content-Type'] = 'application/json'
        return response
    access_token = request.data
    print ("access token received %s " % access_token)


    app_id = json.loads(open('fb_client_secrets.json', 'r').read())[
        'web']['app_id']
    app_secret = json.loads(
        open('fb_client_secrets.json', 'r').read())['web']['app_secret']
    url = 'https://graph.facebook.com/oauth/access_token?grant_type=fb_exchange_token&client_id=%s&client_secret=%s&fb_exchange_token=%s' % (
        app_id, app_secret, access_token)
    h = httplib2.Http()
    result = h.request(url, 'GET')[1]


    # Use token to get user info from API
    userinfo_url = "https://graph.facebook.com/v2.8/me"
    '''
        Due to the formatting for the result from the server token exchange we have to
        split the token first on commas and select the first index which gives us the key : value
        for the server access token then we split it on colons to pull out the actual token value
        and replace the remaining quotes with nothing so that it can be used directly in the graph
        api calls
    '''
    token = result.split(',')[0].split(':')[1].replace('"', '')

    url = 'https://graph.facebook.com/v2.8/me?access_token=%s&fields=name,id,email' % token
    h = httplib2.Http()
    result = h.request(url, 'GET')[1]
    # print "url sent for API access:%s"% url
    # print "API JSON result: %s" % result
    data = json.loads(result)
    login_session['provider'] = 'facebook'
    login_session['username'] = data["name"]
    login_session['email'] = data["email"]
    login_session['facebook_id'] = data["id"]

    # The token must be stored in the login_session in order to properly logout
    login_session['access_token'] = token

    # Get user picture
    url = 'https://graph.facebook.com/v2.8/me/picture?access_token=%s&redirect=0&height=200&width=200' % token
    h = httplib2.Http()
    result = h.request(url, 'GET')[1]
    data = json.loads(result)

    login_session['picture'] = data["data"]["url"]

    # see if user exists
    user_id = getUserID(login_session['email'])
    if not user_id:
        user_id = createUser(login_session)
    login_session['user_id'] = user_id

    output = ''
    output += '<h1>Welcome, '
    output += login_session['username']

    output += '!</h1>'
    output += '<img src="'
    output += login_session['picture']
    output += ' " style = "width: 300px; height: 300px;border-radius: 150px;-webkit-border-radius: 150px;-moz-border-radius: 150px;"> '

    flash("Now logged in as %s" % login_session['username'])
    return output
Esempio n. 38
0
def pretty_json(arg):
    response = make_response(json.dumps(arg, sort_keys=True, indent=4))
    response.headers['Content-type'] = "application/json"
    return response
Esempio n. 39
0
def gconnect():
    # Validate state token
    if request.args.get('state') != login_session['state']:
        response = make_response(json.dumps('Invalid state parameter.'), 401)
        response.headers['Content-Type'] = 'application/json'
        return response
    # Obtain authorization code
    code = request.data

    try:
        # Upgrade the authorization code into a credentials object
        oauth_flow = flow_from_clientsecrets(
            '/var/www/CatalogApp/CatalogApp/client_secrets.json', scope='')
        oauth_flow.redirect_uri = 'postmessage'
        credentials = oauth_flow.step2_exchange(code)
    except FlowExchangeError:
        response = make_response(
            json.dumps('Failed to upgrade the authorization code.'), 401)
        response.headers['Content-Type'] = 'application/json'
        return response

    # Check that the access token is valid.
    access_token = credentials.access_token
    url = ('https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=%s' %
           access_token)
    h = httplib2.Http()
    result = json.loads(h.request(url, 'GET')[1])
    # If there was an error in the access token info, abort.
    if result.get('error') is not None:
        response = make_response(json.dumps(result.get('error')), 500)
        response.headers['Content-Type'] = 'application/json'
        return response

    # Verify that the access token is used for the intended user.
    gplus_id = credentials.id_token['sub']
    if result['user_id'] != gplus_id:
        response = make_response(
            json.dumps("Token's user ID doesn't match given user ID."), 401)
        response.headers['Content-Type'] = 'application/json'
        return response

    # Verify that the access token is valid for this app.
    if result['issued_to'] != CLIENT_ID:
        response = make_response(
            json.dumps("Token's client ID does not match app's."), 401)
        print "Token's client ID does not match app's."
        response.headers['Content-Type'] = 'application/json'
        return response

    stored_access_token = login_session.get('access_token')
    stored_gplus_id = login_session.get('gplus_id')
    if stored_access_token is not None and gplus_id == stored_gplus_id:
        response = make_response(
            json.dumps('Current user is already connected.'), 200)
        response.headers['Content-Type'] = 'application/json'
        return response

    # Store the access token in the session for later use.
    login_session['access_token'] = credentials.access_token
    login_session['gplus_id'] = gplus_id

    # Get user info
    userinfo_url = "https://www.googleapis.com/oauth2/v1/userinfo"
    params = {'access_token': credentials.access_token, 'alt': 'json'}
    answer = requests.get(userinfo_url, params=params)
    data = answer.json()
    login_session['provider'] = 'google'
    login_session['username'] = data['name']
    login_session['picture'] = data['picture']
    login_session['email'] = data['email']

    # Check if user already exists
    user_id = getUserID(login_session['email'])
    if not user_id:
        user_id = createUser()
    login_session['user_id'] = user_id
    flash("you are now logged in as %s" % login_session['username'])
    return redirect(url_for('index'))
Esempio n. 40
0
def other_page(page_name):
    response = make_response('<!DOCTYPE html>\
    <html><body><h1>My ECP testing site</h1>\
    <p>The page named %s does not exist.</p></body></html>'\
    % page_name, 404)
    return response
Esempio n. 41
0
def unPayItems():
    # optional argument
    year = request.args.get('year')
    is_handled = request.args.get('handled')
    is_progress = request.args.get('progress')
    name = request.args.get('name', "所有人")

    db_tuple = db_selection(year)
    db = db_tuple.db
    sale_c = db_tuple.sale_c
    unpay_sale_status = db_tuple.unpay_sale_status

    query = db.session().query(sale_c, unpay_sale_status)
    sale_c_joined = query.outerjoin(
        unpay_sale_status, sale_c.sc_code == unpay_sale_status.sc_code)

    handle_query = or_(unpay_sale_status.handled == 0,
                       unpay_sale_status.handled == None)

    #handle status
    # if handle == NONE mean not set in the unpay table
    # handle_query = or_(unpay_sale_status.handled == None)
    if is_progress: handle_query = unpay_sale_status.handled == 5
    if is_handled: handle_query = unpay_sale_status.handled == 10

    # this is just a placeholder, just execute the handle_query twice

    name_query = sale_c.sc_sponsor is not None
    if name != "所有人":
        name_query = sale_c.sc_sponsor == name

    result = []
    # except_companys = ["北京康瑞明科技有限公司", "太原重工股份有限公司","泰安航天特种车有限公司"]
    except_sponsorList = ['春桥科技']
    except_companys = []
    now = datetime.now().date()
    _90DaysAgo = now - timedelta(days=90)
    items = sale_c_joined.filter(
        and_(
            #没收全
            #sale_c.sc_reca_money+ sale_c.sc_recr_money < sale_c.sc_item_summoney,
            #收了不到百分80
            sale_c.sc_reca_money + sale_c.sc_recr_money <
            sale_c.sc_item_summoney * 0.97,
            name_query,
            # 出货超过百分99
            #  SaleC.sc_item_out >= 99,
            # 大于60天交货期
            sale_c.sc_appd_date < _90DaysAgo,
            handle_query,
            sale_c.sc_sponsor.notin_(except_sponsorList),
            sale_c.sc_receive_company.notin_(except_companys))).all()

    items2 = []
    unpay_d = {"handled": None, "id": None, "remark": None}
    for x in items:
        d = x[0].as_dict()
        d.update(x[1].as_dict()) if x[1] else d.update(unpay_d)

        rec_money = d["sc_rec_money"] = d["sc_reca_money"] + d["sc_recr_money"]
        sc_recr_money_prec = 0 if (
            rec_money == 0) else rec_money / (d["sc_item_summoney"])
        d["sc_recr_money_prec"] = sc_recr_money_prec
        d.pop("sc_reca_money")
        d.pop("sc_recr_money")

        items2.append(d)
    return make_response(jsonify(items2))
Esempio n. 42
0
def setTimelapseConfig():
    data = request.values
    if hasattr(request, "json") and request.json:
        data = request.json

    if "type" in data:
        config = {
            "type": data["type"],
            "postRoll": 0,
            "fps": 25,
            "options": {}
        }

        if "postRoll" in data:
            try:
                postRoll = int(data["postRoll"])
            except ValueError:
                return make_response(
                    "Invalid value for postRoll: %r" % data["postRoll"], 400)
            else:
                if postRoll >= 0:
                    config["postRoll"] = postRoll
                else:
                    return make_response(
                        "Invalid value for postRoll: %d" % postRoll, 400)

        if "fps" in data:
            try:
                fps = int(data["fps"])
            except ValueError:
                return make_response("Invalid value for fps: %r" % data["fps"],
                                     400)
            else:
                if fps > 0:
                    config["fps"] = fps
                else:
                    return make_response("Invalid value for fps: %d" % fps,
                                         400)

        if "interval" in data:
            try:
                interval = int(data["interval"])
            except ValueError:
                return make_response(
                    "Invalid value for interval: %r" % data["interval"], 400)
            else:
                if interval > 0:
                    config["options"]["interval"] = interval
                else:
                    return make_response(
                        "Invalid value for interval: %d" % interval, 400)

        if "capturePostRoll" in data:
            try:
                capturePostRoll = bool(data["capturePostRoll"])
            except ValueError:
                return make_response(
                    "Invalid value for capturePostRoll: %r" %
                    data["capturePostRoll"], 400)
            else:
                config["options"]["capturePostRoll"] = capturePostRoll

        if "retractionZHop" in data:
            try:
                retractionZHop = float(data["retractionZHop"])
            except ValueError:
                return make_response(
                    "Invalid value for retraction Z-Hop: %r" %
                    data["retractionZHop"], 400)
            else:
                if retractionZHop >= 0:
                    config["options"]["retractionZHop"] = retractionZHop
                else:
                    return make_response(
                        "Invalid value for retraction Z-Hop: %f" %
                        retractionZHop, 400)

        if "minDelay" in data:
            try:
                minDelay = float(data["minDelay"])
            except ValueError:
                return make_response(
                    "Invalid value for minimum delay: %r" % data["minDelay"],
                    400)
            else:
                if minDelay > 0:
                    config["options"]["minDelay"] = minDelay
                else:
                    return make_response(
                        "Invalid value for minimum delay: %f" % minDelay, 400)

        if admin_permission.can(
        ) and "save" in data and data["save"] in valid_boolean_trues:
            octoprint.timelapse.configure_timelapse(config, True)
        else:
            octoprint.timelapse.configure_timelapse(config)

    return getTimelapseData()
Esempio n. 43
0
def not_found(error):
    return make_response(jsonify({'error': 'Bad request'}), 400)
Esempio n. 44
0
def predict():
    #for HTML GUI rendering
    file = request.files['file']
    print(file.filename)
    if file.filename.split(".")[-1] != "png":
        return render_template('Wrong_file_type.html')

    npimg = np.fromfile(file, np.uint8)
    img = cv2.imdecode(npimg, 0)
    # f.save(os.path.join(app.config['UPLOAD_FOLDER'], secure_filename(f.filename)))
    # img = cv2.imread(os.path.join(app.config['UPLOAD_FOLDER'], secure_filename(f.filename)))
    # img = cv2.imdecode(img, 0)

    thresh, img_bin = cv2.threshold(img, 128, 255, cv2.THRESH_BINARY)
    img_bin = 255 - img_bin

    img_bin1 = 255 - img
    thresh1, img_bin1_otsu = cv2.threshold(img_bin1, 128, 255, cv2.THRESH_OTSU)

    img_bin2 = 255 - img
    thresh1, img_bin_otsu = cv2.threshold(img_bin2, 128, 255,
                                          cv2.THRESH_BINARY | cv2.THRESH_OTSU)

    kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (2, 2))

    vertical_kernel = cv2.getStructuringElement(
        cv2.MORPH_RECT, (1, np.array(img).shape[1] // 100))
    eroded_image = cv2.erode(img_bin_otsu, vertical_kernel, iterations=3)
    vertical_lines = cv2.dilate(eroded_image, vertical_kernel, iterations=3)

    hor_kernel = cv2.getStructuringElement(cv2.MORPH_RECT,
                                           (np.array(img).shape[1] // 100, 1))
    horizontal_lines = cv2.erode(img_bin, hor_kernel, iterations=5)
    horizontal_lines = cv2.dilate(horizontal_lines, hor_kernel, iterations=5)

    vertical_horizontal_lines = cv2.addWeighted(vertical_lines, 0.5,
                                                horizontal_lines, 0.5, 0.0)
    vertical_horizontal_lines = cv2.erode(~vertical_horizontal_lines,
                                          kernel,
                                          iterations=3)
    thresh, vertical_horizontal_lines = cv2.threshold(
        vertical_horizontal_lines, 128, 255,
        cv2.THRESH_BINARY | cv2.THRESH_OTSU)
    bitxor = cv2.bitwise_xor(img, vertical_horizontal_lines)
    bitnot = cv2.bitwise_not(bitxor)

    contours, hierarchy = cv2.findContours(vertical_horizontal_lines,
                                           cv2.RETR_TREE,
                                           cv2.CHAIN_APPROX_SIMPLE)

    boundingBoxes = [cv2.boundingRect(contour) for contour in contours]
    (contours, boundingBoxes) = zip(
        *sorted(zip(contours, boundingBoxes), key=lambda x: x[1][1]))

    boxes = []
    for contour in contours:
        x, y, w, h = cv2.boundingRect(contour)
        if (w < 1000 and h < 500):
            image = cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)
            boxes.append([x, y, w, h])

    rows = []
    columns = []
    heights = [boundingBoxes[i][3] for i in range(len(boundingBoxes))]
    mean = np.mean(heights)
    print(mean)
    columns.append(boxes[0])
    previous = boxes[0]
    for i in range(1, len(boxes)):
        if (boxes[i][1] <= previous[1] + mean / 2):
            columns.append(boxes[i])
            previous = boxes[i]
            if (i == len(boxes) - 1):
                rows.append(columns)
        else:
            rows.append(columns)
            columns = []
            previous = boxes[i]
            columns.append(boxes[i])
    # print("Rows")
    for row in rows:
        print(row)

    total_cells = 0
    for i in range(len(row)):
        if len(row[i]) > total_cells:
            total_cells = len(row[i])
    # print(total_cells)

    center = [
        int(rows[i][j][0] + rows[i][j][2] / 2) for j in range(len(rows[i]))
        if rows[0]
    ]
    # print(center)

    center = np.array(center)
    center.sort()
    # print(center)

    boxes_list = []
    for i in range(len(rows)):
        l = []
        for k in range(total_cells):
            l.append([])
        for j in range(len(rows[i])):
            diff = abs(center - (rows[i][j][0] + rows[i][j][2] / 4))
            minimum = min(diff)
            indexing = list(diff).index(minimum)
            l[indexing].append(rows[i][j])
        boxes_list.append(l)
    # for box in boxes_list:
    # print(box)

    dataframe_final = []
    for i in range(len(boxes_list)):
        for j in range(len(boxes_list[i])):
            s = ''
            if (len(boxes_list[i][j]) == 0):
                dataframe_final.append(' ')
            else:
                for k in range(len(boxes_list[i][j])):
                    y, x, w, h = boxes_list[i][j][k][0], boxes_list[i][j][k][
                        1], boxes_list[i][j][k][2], boxes_list[i][j][k][3]
                    roi = bitnot[x:x + h, y:y + w]
                    kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (2, 1))
                    border = cv2.copyMakeBorder(roi,
                                                2,
                                                2,
                                                2,
                                                2,
                                                cv2.BORDER_CONSTANT,
                                                value=[255, 255])
                    resizing = cv2.resize(border,
                                          None,
                                          fx=2,
                                          fy=2,
                                          interpolation=cv2.INTER_CUBIC)
                    dilation = cv2.dilate(resizing, kernel, iterations=1)
                    erosion = cv2.erode(dilation, kernel, iterations=2)
                    out = pytesseract.image_to_string(erosion)
                    if (len(out) == 0):
                        out = pytesseract.image_to_string(erosion)
                    s = s + " " + out
                dataframe_final.append(s)
    # print(dataframe_final)
    arr = np.array(dataframe_final)
    # print(arr)
    dataframe = pd.DataFrame(arr.reshape(len(rows), total_cells))
    data = dataframe.style.set_properties(align="left")
    # dataframe.to_csv("output.csv")
    # dataframe=pd.read_csv("output.csv")

    resp = make_response(dataframe.to_csv())
    resp.headers["Content-Disposition"] = "attachment; filename=table.csv"
    resp.headers["Content-Type"] = "text/csv"
    return resp
Esempio n. 45
0
def gconnect():
    """
    LOGIN BY CONNECT TO GOOGLE
    """
    if request.args.get('state') != login_session['state']:
        response = make_response(json.dumps('Invalid state parameter'), 401)
        response.headers['Content-Type'] = 'application'
        return response
    code = request.data
    try:
        oauth_flow = flow_from_clientsecrets('client_secrets.json', scope='')
        oauth_flow.redirect_uri = 'postmessage'
        credentials = oauth_flow.step2_exchange(code)
    except FlowExchangeError:
        response = make_response(json.dumps(
            'Failed to upgrade the authorization code.'), 401)
        response.headers['Content-Type'] = 'application/json'
        return response
    access_token = credentials.access_token
    url = (
        'https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=%s'
        % access_token)
    h = httplib2.Http()
    result = json.loads(h.request(url, 'POST')[1])
    error = result.get('error')

    if error is not None:
        response = make_response(json.dumps(error), 500)
        response.headers['Content-Type'] = 'application/json'

    # Verify that the access token is used for the intended user.
    gplus_id = credentials.id_token['sub']
    if result['user_id'] != gplus_id:
        response = make_response(
            json.dumps('Token user ID does not match given user ID.'), 401)
        response.headers['Content-Type'] = 'application/json'
        return response

    # Verify that the access token is valid for this app.
    if result['issued_to'] != CLIENT_ID:
        response = make_response(
            json.dumps("Token's client ID does not match app's."), 401)
        response.headers['Content-Type'] = 'application/json'
        return response

    # Check to see if user is already logged in
    stored_credentials = login_session.get('credentials')
    stored_gplus_id = login_session.get('plus_id')
    if stored_credentials is not None and gplus_id == stored_gplus_id:
        response = make_response(
            json.dumps('Current user is already connected.'), 200)
        response.headers['Content-Type'] = 'application/json'

    # If none of if statements above were true,
    # the user of the current session successfully connects the app with Google
    # Store new credentials and gplus id to the session for return users
    login_session['credentials'] = credentials.access_token
    login_session['gplus_id'] = gplus_id
    login_session['provider'] = 'google'

    # Then get user info by providing access token to Google API
    userinfo_url = 'https://www.googleapis.com/oauth2/v1/userinfo'
    params = {'access_token': access_token, 'alt': 'json'}
    answer = requests.get(userinfo_url, params=params)
    data = json.loads(answer.text)

    # Store the detail data
    login_session['username'] = data["name"]
    login_session['picture'] = data["picture"]
    login_session['email'] = data["email"]

    # Create a new User record if non-existed user
    user_id = getUserID(login_session['email'])
    if not user_id:
        user_id = createUser(login_session)
    login_session['user_id'] = user_id

    output = ''
    output += '<h1>Welcome, '
    output += login_session['username']
    output += '!</h1>'
    output += '<img src="'
    output += login_session['picture']
    output += ' " style = "width: 300px; height: 300px;border-radius: 150px;" \
    "-webkit-border-radius: 150px;-moz-border-radius: 150px;"> '
    flash("you are now logged in as %s" % login_session['username'])
    return output
Esempio n. 46
0
def not_found(error):
    return make_response(jsonify({'error': 'Not found'}), 404)
Esempio n. 47
0
def predict(get_map=False, and_confirm=None): 
    """ Predict where user is from """

    queries, found_words = interp_answers(request.json)
    grids = get_grids(queries)
     
    def negative(query):
        return query[0][0:4] == "NOT "

    def min_max_scaling(arr):
        return np.divide(arr - arr.min(), arr.max() - arr.min())

    def matrix_product(grids, queries):
        """ Multiply all distributions into a final one """ 

        product = np.ones(grids[0].shape) # Set up uniform distribution

        for grid, query in zip(grids, queries): 
            if negative(query):
                deviation_grid, _ = dev_from_null_hyp(grid)
                #deviation_grid = min_max_scaling(deviation_grid)
                deviation_grid = normalize(deviation_grid)
                product = np.multiply(product, not_in(deviation_grid)) 
                make_map(not_in(deviation_grid), filename=str(query))
            else:
                deviation_grid, _ = dev_from_null_hyp(grid)
                #deviation_grid = min_max_scaling(deviation_grid)
                deviation_grid = normalize(deviation_grid)

                product = np.multiply(product, deviation_grid) 
                make_map(deviation_grid, filename=str(query))

        return product

    product = matrix_product(grids, queries)    
    product = normalize(product)
    coordinate, second_maximum, third_maximum = grid_maximum(product) 

    region = translation[rg.get(coordinate)['admin1']]
    region2 = translation[rg.get(second_maximum)['admin1']]
    region3 = translation[rg.get(third_maximum)['admin1']]

    if get_map:
        product = min_max_scaling(product)
        filename_product = make_map(product)
    else:
        filename_product = None 

    #_, null_hyp_grid = dev_from_null_hyp(product)
    #filename_hypo = make_map(null_hyp_grid, log=True)

    predictions = [region, region2, region3]
    predictionCoordinates = [coordinate, second_maximum, third_maximum]

    if and_confirm:
        addDatapoints(place=predictions[and_confirm-1], 
                      longitude=predictionCoordinates[and_confirm-1][1], 
                      latitude=predictionCoordinates[and_confirm-1][0], 
                      found_words=found_words)
                     
        return make_response(jsonify( { 'confirmed': predictions[and_confirm-1], 
                                        'coordinate': predictionCoordinates[and_confirm-1] } ))
    else:
        return make_response(jsonify( { 'region': region, 'region2': region2, 'region3': region3, 
                                        'filename_product': filename_product } ))
Esempio n. 48
0
def unauthorized():
    return make_response(jsonify({'error': 'Unauthorized access'}), 403)
Esempio n. 49
0
def not_found(error):
    """
    RESTful 404 error
    """

    return make_response(jsonify({'error': 'Not found', 'code': 404})), 404
Esempio n. 50
0
def fbconnect():
    """
    LOGIN BY CONNECT TO FACEBOOK
    """
    if request.args.get('state') != login_session['state']:
        response = make_response(json.dumps('Invalid state parameter'), 401)
        response.headers['Content-Type'] = 'application'
        return response
    access_token = request.data

    # Exchange client token for long-lived server-side token
    app_id = json.loads(open(
        'fb_client_secrets.json', 'r').read())['web']['app_id']
    app_secret = json.loads(open(
        'fb_client_secrets.json', 'r').read())['web']['app_secret']
    url = 'https://graph.facebook.com/v2.8/oauth/" \
    "access_token?grant_type=fb_exchange_token" \
    "&client_id=%s&client_secret=%s&fb_exchange_token=%s' \
    % (app_id, app_secret, access_token)
    h = httplib2.Http()
    result = h.request(url, 'GET')[1]
    # Use token to get user info from API
    data = json.loads(result)
    token = 'access_token=' + data['access_token']

    url = 'https://graph.facebook.com/v2.8/me?%s&fields=name,id,email' \
        % token
    h = httplib2.Http()
    result = h.request(url, 'GET')[1]

    if "error" in result:
        response = make_response(json.dumps('Fail to request data'), 401)
        response.headers['Content-Type'] = 'application'
        return response

    data = json.loads(result)

    login_session['provider'] = 'facebook'
    login_session['username'] = data["name"]
    login_session['email'] = data["email"]
    login_session['facebook_id'] = data["id"]
    login_session['credentials'] = token

    # Retrieve user profile picture
    url = 'https://graph.facebook.com/v2.8/me/picture?%s&redirect=0" \
    "&height=200&width=200' % token
    h = httplib2.Http()
    result = h.request(url, 'GET')[1]
    data = json.loads(result)

    login_session['picture'] = data["data"]["url"]

    # Create a new User record if non-existed user
    user_id = getUserID(login_session['email'])
    if not user_id:
        user_id = createUser(login_session)

    login_session['user_id'] = user_id
    output = ''
    output += '<h1>Welcome, '
    output += login_session['username']
    output += '!</h1>'
    output += '<img src="'
    output += login_session['picture']
    output += ' " style = "width: 300px; height: 300px;border-radius: 150px;" \
    "-webkit-border-radius: 150px;-moz-border-radius: 150px;"> '
    flash("you are now logged in as %s" % login_session['username'])
    return output
Esempio n. 51
0
def basic_pages(**kwargs):
    return make_response(open('angular_flask/templates/index.html').read())
Esempio n. 52
0
def login():
    form = LoginForm()

    if form.validate_on_submit():
        username = form.username.data
        password = form.password.data

        user = requests.get(
            'http://10.100.5.195:8017/api/ADUser/AuthenticateUser?username='******'&password='******'@ubagroup.com', password,
                            'Default', 'Default')
                db.session.add(user)
                db.session.commit()
                login_user(user)
                # Une fois l'utilisateur connecté on vérifie si remember est actif
                if form.remember_me.data:
                    resp = make_response(redirect(url_for("main.home")))
                    # Envoyer les cookies au navigateur
                    remember_token = user.get_remember_token()
                    db.session.commit()
                    # Stocker les cookies dans des variables
                    resp.set_cookie('remember_token',
                                    encrypt_cookie(remember_token),
                                    max_age=60 * 2)
                    resp.set_cookie('user_id',
                                    encrypt_cookie(user.id),
                                    max_age=60 * 2)
                    return resp
                else:
                    resp1 = make_response(redirect(url_for("main.home")))
                    resp1.set_cookie('user_id',
                                     encrypt_cookie(user.id),
                                     max_age=60 * 2)
                    return resp1
            else:
                # Une fois l'utilisateur connecté on vérifie si remember est actif
                user = User.query.filter_by(username=username).first()
                if form.remember_me.data:
                    resp = make_response(redirect(url_for("main.home")))
                    # Envoyer les cookies au navigateur
                    remember_token = user.get_remember_token()
                    db.session.commit()
                    # Stocker les cookies dans des variables
                    resp.set_cookie('remember_token',
                                    encrypt_cookie(remember_token),
                                    max_age=60 * 60)
                    resp.set_cookie('user_id',
                                    encrypt_cookie(user.id),
                                    max_age=60 * 60)
                    return resp
                else:
                    resp1 = make_response(redirect(url_for("main.home")))
                    #db.session.commit()
                    resp1.set_cookie('user_id',
                                     encrypt_cookie(user.id),
                                     max_age=60 * 60)
                    return resp1
        else:
            flash("The username or password is not correct.")
            return render_template("login.html", form=form)
    return render_template("login.html", form=form)
Esempio n. 53
0
def logout():
    resp = make_response(redirect(url_for("index")))
    resp.set_cookie(key='username',  value='', expires=0)
    resp.set_cookie(key='sessionId',  value='', expires=0)
    return resp    
Esempio n. 54
0
def caption():
	filename = save_file(next(request.files.values()), app.config['UPLOAD_FOLDER'])
	captions = get_captions(os.path.join(app.config['UPLOAD_FOLDER'], filename))
	return make_response(jsonify({'captions': [{'caption': c, 'p': p} for c, p in captions]}), 200)
Esempio n. 55
0
def purchase_packages(cano_url):

    if request.method == 'GET':
        try:
            course_package = Pac_course.query.filter_by(
                cano_url=cano_url, is_active=True).first()
            if course_package:
                months = package_months(course_package.expire_month)
                comp_sub = Pac_compulsory_subjects.query.filter_by(
                    pac_course_id=course_package.id).all()
                opt_sub = Pac_optional_subjects.query.filter_by(
                    pac_course_id=course_package.id).all()
                total_comp_sub_price = 0
                if comp_sub:
                    for cps in comp_sub:
                        total_comp_sub_price = total_comp_sub_price + cps.price
                resp = make_response(
                    render_template('home/purchase-package.html',
                                    course_package=course_package,
                                    comp_sub=comp_sub,
                                    opt_sub=opt_sub,
                                    total_comp_sub_price=total_comp_sub_price,
                                    months=months))
                return resp
            else:
                return redirect(url_for('packages'))
        except Exception as e:
            app.logger.error(str(e))
            return abort(500)
    else:
        pcgd = request.form.get('pcgd')
        optional_subject = request.form.getlist('optional_subject')
        months = request.form.getlist('month')
        cano_url = request.form.get('cano')

        if session.get('subs_pac_id'):
            session.pop('subs_pac_id')

        if session.get('subs_optional_subjects'):
            session.pop('subs_optional_subjects')

        if session.get('subs_months'):
            session.pop('subs_months')

        if len(months) < 1:
            return redirect(url_for('purchase_packages', cano_url=cano_url))
        else:
            subscribe_course_package = []
            subs_month = []
            subs_opt_subjs = []

            for month in months:
                subs_month.append(month)

            for opt_sub in optional_subject:
                subs_opt_subjs.append(opt_sub)

            session['subs_pac_id'] = pcgd
            session[
                'subs_optional_subjects'] = subs_opt_subjs  #subscribe_course_package
            session['subs_months'] = subs_month
            return redirect(url_for('payment_process'))
Esempio n. 56
0
def latest_matchmaking():
    seasons = db.get_season_range(g.conn)
    if len(seasons) == 0:
        return flask.make_response('No seasons found', 404)
    players = db.get_players_in_last_round(g.conn)
    return matchmaking0(seasons, players, season_id=seasons[-1], latest=True)
Esempio n. 57
0
def query():
    try:
        structure_type = 'garnet'
        c_string = request.args.get("c_string")
        a_string = request.args.get("a_string")
        d_string = request.args.get("d_string")
        formula = ""

        c_composition = parse_composition(structure_type, c_string, "C")
        a_composition = parse_composition(structure_type, a_string, "A")
        d_composition = parse_composition(structure_type, d_string, "D")

        charge = -2.0 * 12

        for k in c_composition.keys():
            charge += 3 * k.oxi_state * c_composition.get_atomic_fraction(k)
        for k in a_composition.keys():
            charge += 2 * k.oxi_state * a_composition.get_atomic_fraction(k)
        for k in d_composition.keys():
            charge += 3 * k.oxi_state * d_composition.get_atomic_fraction(k)

        if len(c_composition) > 1:
            mix_site = "c"
        elif len(a_composition) > 1:
            mix_site = "a"
        elif len(d_composition) > 1:
            mix_site = "d"
        else:
            mix_site = None

        species = {"a": a_composition, "d": d_composition, "c": c_composition}

        if abs(charge) < 0.1:
            with tf.Session() as sess:

                oxide_table_path = os.path.join(
                    os.path.dirname(os.path.abspath(__file__)),
                    "data/garnet_oxi_table.json")
                model, scaler, graph = load_model_and_scaler(structure_type, mix_site) if mix_site \
                    else load_model_and_scaler(structure_type, "unmix")
                inputs = get_descriptor(structure_type, species)

                with graph.as_default():
                    form_e = get_form_e(inputs, model, scaler) * 20
                tot_e = get_tote(structure_type,
                                 form_e,
                                 species,
                                 oxides_table_path=oxide_table_path)
                if mix_site:
                    decompose_entries = get_decomposed_entries(
                        structure_type, species, oxide_table_path)
                    decomp, ehull = get_ehull(structure_type,
                                              tot_e,
                                              species,
                                              unmix_entries=decompose_entries)
                else:
                    decomp, ehull = get_ehull(structure_type, tot_e, species)
                formula = spe2form(structure_type, species)
                message = [
                    "<i>E<sub>f</sub></i> = %.3f eV/fu" % form_e,
                    "<i>E<sub>hull</sub></i> = %.0f meV/atom" % (ehull * 1000)
                ]
                if ehull > 0:
                    reaction = []
                    for k, v in decomp.items():
                        comp = k.composition
                        comp, f = comp.get_reduced_composition_and_factor()
                        reaction.append(
                            '%.3f <a href="https://www.materialsproject.org/materials/%s">%s</a>'
                            % (v * f / comp.num_atoms * 20, k.entry_id,
                               html_formula(comp.reduced_formula)))
                    message.append("Decomposition: " + " + ".join(reaction))

                message = "<br>".join(message)
        else:
            message = "Not charge neutral! Total charge = %.0f" % charge
    except Exception as ex:
        message = str(ex)

    return make_response(
        render_template('index.html',
                        c_string=c_string,
                        a_string=a_string,
                        d_string=d_string,
                        formula=html_formula(formula),
                        message=message))
Esempio n. 58
0
def make_json_response(data):
    response = make_response(data)
    response.headers['Content-Type'] = 'application/json'
    return response
Esempio n. 59
0
def index():
    return make_response(render_template('index.html'))
Esempio n. 60
0
def set_cookie():
    response = make_response('kasim')
    response.set_cookie('name', 'kasim', 100)
    return response