Пример #1
0
    def get(self):
        Guser = users.get_current_user()
        if Guser:
            findRequest = Profile.query(
                Profile.strReference == Guser.user_id())
            thisProfileList = findRequest.fetch()

            if len(thisProfileList) > 0:
                thisProfile = thisProfileList[0]
            else:
                thisProfile = Profile()

            findRequest = BankAccount.query(
                BankAccount.strReference == Guser.user_id())
            thisBankAccountList = findRequest.fetch()
            if len(thisBankAccountList) > 0:
                thisBankAccount = thisBankAccountList[0]
            else:
                thisBankAccount = BankAccount()

                thisBankAccount.writeReference(strinput=Guser.user_id())
                thisBankAccount.put()

            template = template_env.get_template(
                "templates/admin/wallet/wallet.html")
            context = {
                'thisProfile': thisProfile,
                'thisBankAccount': thisBankAccount
            }
            self.response.write(template.render(context))
Пример #2
0
    def get(self):
        Guser = users.get_current_user()
        if Guser:

            findRequest = Promotions.query(Promotions.strReference == Guser.user_id())
            thisPromotionsList = findRequest.fetch()

            if len(thisPromotionsList) > 0:
                thisPromotions = thisPromotionsList[0]
            else:
                thisPromotions = Promotions()
                thisPromotions.writeReference(strinput=Guser.user_id())
                thisPromotions.put()

            findRequest = Profile.query(Profile.strReference == Guser.user_id())
            thisProfileList = findRequest.fetch()

            if len(thisProfileList) > 0:
                thisProfile = thisProfileList[0]
            else:
                thisProfile = Profile()
                thisProfile.writeReference(strinput=Guser.user_id())
                thisProfile.put()

            if thisProfile.strWallet > thisPromotions.strAutoDownLine:
                thisProfile.strWallet = thisProfile.strWallet - thisPromotions.strAutoDownLine
                thisProfile.put()
                thisPromotions.strEnableAutoDownLine = True
                thisPromotions.strTotalPromos = thisPromotions.strTotalPromos +  thisPromotions.strAutoDownLine
                thisPromotions.put()
                self.response.write("Auto Down-Line Enabled")
            else:
                self.response.write("Failed to enable Auto Down-Line - Insufficient Funds")
Пример #3
0
    def get(self):
        Guser = users.get_current_user()
        if Guser:


            findRequest = Promotions.query(Promotions.strReference == Guser.user_id())
            thisPromotionsList = findRequest.fetch()

            if len(thisPromotionsList) > 0:
                thisPromotions = thisPromotionsList[0]
            else:
                thisPromotions = Promotions()
                thisPromotions.writeReference(strinput=Guser.user_id())
                thisPromotions.put()

            findRequest = Profile.query(Profile.strReference == Guser.user_id())
            thisProfileList = findRequest.fetch()

            if len(thisProfileList) > 0:
                thisProfile = thisProfileList[0]
            else:
                thisProfile = Profile()
                thisProfile.writeReference(strinput=Guser.user_id())
                thisProfile.put()

            if thisProfile.strWallet > thisPromotions.strSocialMediaPromo:
                thisProfile.strWallet = thisProfile.strWallet - thisPromotions.strSocialMediaPromo
                thisProfile.put()
                thisPromotions.strEnableSocialMediaPromo = True
                thisPromotions.strTotalPromos = thisPromotions.strTotalPromos + thisPromotions.strSocialMediaPromo
                thisPromotions.put()
                self.response.write("Social Media Promos Enabled")
            else:
                self.response.write("Failure enabling Social Media Promos - Insufficient Funds")
Пример #4
0
    def get(self):
        Guser = users.get_current_user()
        if Guser:
            findRequests = Promotions.query(Promotions.strReference == Guser.user_id())
            thisPromotionsList = findRequests.fetch()

            if len(thisPromotionsList) > 0:
                thisPromotions = thisPromotionsList[0]
            else:
                thisPromotions = Promotions()
                thisPromotions.writeReference(strinput=Guser.user_id())
                thisPromotions.put()

            findRequests = Profile.query(Profile.strReference == Guser.user_id())
            thisProfileList = findRequests.fetch()

            if len(thisProfileList) > 0:
                thisProfile = thisProfileList[0]
            else:
                thisProfile = Profile()
                thisProfile.writeReference(strinput=Guser.user_id())
                thisProfile.put()


            if thisProfile.strWallet > thisPromotions.strPriorityListing:
                thisProfile.strWallet = thisProfile.strWallet - thisPromotions.strPriorityListing
                thisProfile.put()
                thisPromotions.strEnablePriorityListing = True
                thisPromotions.strTotalPromos = thisPromotions.strTotalPromos +  thisPromotions.strPriorityListing
                thisPromotions.put()
                self.response.write("Priority Listing Enabled")
            else:
                self.response.write("Failed to enable Priority Listing- Insufficient funds")
Пример #5
0
    def post(self):
        Guser = users.get_current_user()
        if Guser:
            findRequest = Profile.query(
                Profile.strReference == Guser.user_id())
            thisProfileList = findRequest.fetch()

            if len(thisProfileList) > 0:
                thisProfile = thisProfileList[0]
            else:
                thisProfile = Profile()
                thisProfile.writeReference(strinput=Guser.user_id())

            vstrPayPalEmail = self.request.get('vstrPayPalEmail')

            infoUpdated = False

            if not (vstrPayPalEmail == None):
                thisProfile.writePayPalEmail(strinput=vstrPayPalEmail)
                thisProfile.put()
                infoUpdated = True

            vstrAccountHolder = self.request.get('vstrAccountHolder')
            vstrBankName = self.request.get('vstrBankName')
            vstrBranchCode = self.request.get('vstrBranchCode')
            vstrAccountNumber = self.request.get('vstrAccountNumber')
            vstrAccountType = self.request.get('vstrAccountType')

            if ((not (vstrAccountHolder == None))
                    and (not (vstrAccountNumber == None))):
                findRequest = BankAccount.query(
                    BankAccount.strReference == Guser.user_id())
                thisBankAccountList = findRequest.fetch()
                if len(thisBankAccountList) > 0:
                    thisBankAccount = thisBankAccountList[0]
                else:
                    thisBankAccount = BankAccount()
                    thisBankAccount.writeReference(strinput=Guser.user_id())

                thisBankAccount.writeAccountHolder(strinput=vstrAccountHolder)
                thisBankAccount.writeBankName(strinput=vstrBankName)
                thisBankAccount.writeBranchCode(strinput=vstrBranchCode)
                thisBankAccount.writeAccountType(strinput=vstrAccountType)

                thisBankAccount.put()
                infoUpdated = True

            if infoUpdated:
                self.response.write(
                    "Account Linking Information is successfully updated")
            else:
                self.response.write(
                    "Account Linking Information not updated we will not be able to process your withdrawals successfully"
                )
Пример #6
0
 def _plans_tablescan(self, node):
     tbl = node.get('table')[1]
     profile = Profile.build(node, None)
     for server in [s for s in self._servers if tbl in s.tables]:
         authorized = self._servers.authorize(profile, server.id)
         if authorized:
             yield self.makeplan(node, [], server, authorized)
Пример #7
0
    async def on_reaction_add(self, reaction, user):
        global gamechannel
        global valid  # game status
        global winnerPoints
        global color

        # Win Validation
        if reaction.message.channel == gamechannel != None and valid and reaction.message.content == startmsg + react + f' {color}' + '.' and str(
                reaction
        ) == emojis[
                color] and user != self.user:  # checks if the reaction is from a valid minigame session and if it's the right emoji
            playersinfo = shelve.open('players.info', 'c',
                                      writeback=True)  # db open

            # finishing the actual open game
            await gamechannel.send(winmsg1 + user.name + winmsg2)
            valid = False

            # checks if the player profile already exists
            try:
                data = playersinfo[f'{user.id}']
                del data

            except:
                playersinfo[f'{user.id}'] = Profile(user.id)

            # point computation
            playersinfo[f'{user.id}'].addPoint(winnerPoints)
            playersinfo.close()  # db close
            del color
Пример #8
0
 def _plans_default(self, node, servers=None):
     for inputplans in product(*map(self.get_plans, node.inputs)):
         profile = Profile.build(node, inputplans)
         for server in servers or self._servers:
             authorized = self._servers.authorize(profile, server.id)
             if authorized:
                 yield self.makeplan(node, inputplans, server, authorized)
Пример #9
0
    def get(self):
        Guser = users.get_current_user()
        if Guser:
            URL = self.request.uri
            URLlist = URL.split("/")
            vstrReference = URLlist[len(URLlist) - 1]

            findRequest = Profile.query(Profile.strReference == vstrReference)
            thisProfileList = findRequest.fetch()
            if len(thisProfileList) > 0:
                thisProfile = thisProfileList[0]

                findRequest = Settings.query(
                    Settings.strReference == vstrReference)
                thisSettingsList = findRequest.fetch()
                if len(thisSettingsList) > 0:
                    thisSettings = thisSettingsList[0]
                else:
                    thisSettings = Settings()

                template = template_env.get_template(
                    'templates/admin/admin/thisProfile.html')
                context = {
                    'thisProfile': thisProfile,
                    'thisSettings': thisSettings
                }
                self.response.write(template.render(context))
Пример #10
0
    def get(self):
        Guser = users.get_current_user()
        vstrLogoutURL = users.create_logout_url(dest_url="/")
        vstrLoginURL = users.create_login_url(dest_url="/")

        if Guser:
            vstrUsername = Guser.nickname()
            findRequest = Profile.query(
                Profile.strReference == Guser.user_id())
            thisProfileList = findRequest.fetch()

            if len(thisProfileList) > 0:
                thisProfile = thisProfileList[0]
                template = template_env.get_template(
                    'templates/dynamic/navigation/sidebar.html')
                context = {
                    'vstrUsername': thisProfile.strProfileName,
                    'vstrLogoutURL': vstrLogoutURL,
                    'strActivated': thisProfile.strProfileActivated
                }
                self.response.write(template.render(context))

            else:
                template = template_env.get_template(
                    'templates/dynamic/navigation/sidebar.html')
                context = {
                    'vstrUsername': vstrUsername,
                    'vstrLogoutURL': vstrLogoutURL
                }
                self.response.write(template.render(context))
        else:
            template = template_env.get_template(
                'templates/dynamic/navigation/sidebar.html')
            context = {'vstrLoginURL': vstrLoginURL}
            self.response.write(template.render(context))
Пример #11
0
    def post(self):
        Guser = users.get_current_user()
        if Guser:
            vstrActivationCode = self.request.get('vstrActivationCode')
            findRequest = Profile.query(
                Profile.strReference == Guser.user_id())
            thisProfileList = findRequest.fetch()
            if len(thisProfileList) > 0:
                thisProfile = thisProfileList[0]

                if thisProfile.strProfileActivated == False:
                    if thisProfile.ConfirmCode == vstrActivationCode:
                        thisProfile.strProfileActivated = True
                        thisProfile.put()
                        self.response.write(
                            "Your Profile was Successfully Activated thank you"
                        )
                    else:
                        self.response.write(
                            "Your Profile Activation Code do not match")
                else:
                    self.response.write("Your Profile is already Activated")
            else:
                self.response.write(
                    "You do not have a profile yet please send an activation request"
                )
Пример #12
0
 def _plans_default(self, node, servers=None):
     for inputplans in product(*map(self.get_plans, node.inputs)):
         profile = Profile.build(node, inputplans)
         for server in servers or self._servers:
             authorized = self._servers.authorize(profile, server.id)
             if authorized:
                 yield self.makeplan(node, inputplans, server, authorized)
Пример #13
0
 def _plans_tablescan(self, node):
     tbl = node.get('table')[1]
     profile = Profile.build(node, None)
     for server in [s for s in self._servers if tbl in s.tables]:
         authorized = self._servers.authorize(profile, server.id)
         if authorized:
             yield self.makeplan(node, [], server, authorized)
Пример #14
0
    def get(self):

        thisDay = datetime.datetime.today()
        thisDay = thisDay.date()
        findRequest = Profile.query(Profile.strScheduleWithdrawal == thisDay)
        thisProfileList = findRequest.fetch()

        for thisProfile in thisProfileList:

            if thisProfile.strWithdraw >= 100:
                thisPayments = TodaysPayments()
                thisPayments.writeAmountToPay(
                    strinput=str(thisProfile.strWithdraw))
                thisPayments.writeReference(strinput=thisProfile.strReference)
                if thisProfile.strWithDrawMethod == "PayPal":
                    thisPayments.writePayMethod(
                        strinput=thisProfile.strWithDrawMethod)
                    thisPayments.writePayPalEmail(
                        strinput=thisProfile.strPayPalEmail)

                    try:
                        thisPayments.put()
                    except:
                        pass
                    thisProfile.strWithdraw = 0

                    thisProfile.put()

                else:
                    findRequest = BankAccount.query(
                        BankAccount.strReference == thisProfile.strReference)
                    thisBankAccountList = findRequest.fetch()
                    if len(thisBankAccountList) > 0:
                        thisBankAccount = thisBankAccountList[0]
                    else:
                        thisBankAccount = BankAccount()
                        thisBankAccount.writeReference(
                            strinput=thisProfile.strReference)
                        thisBankAccount.put()
                    try:
                        thisPayments.writeBankName(
                            strinput=thisBankAccount.strBankName)
                        thisPayments.writeAccountHolder(
                            strinput=thisBankAccount.strAccountHolder)
                        thisPayments.writeAccountNumber(
                            strinput=thisBankAccount.strAccountNumber)
                        thisPayments.writeAccountType(
                            strinput=thisBankAccount.strAccountType)
                        thisPayments.writeBranchCode(
                            strinput=thisBankAccount.strBranchCode)
                        thisPayments.put()

                    except:
                        pass

                    thisProfile.strWithdraw = 0
                    thisProfile.strScheduleWithdrawal = None
                    thisProfile.put()
Пример #15
0
    def test_provider_id(self):
        # Arrange
        name = "random name"
        provider_id = "random_provider_id"
        profile = Profile(name, provider_id, 1)

        # Act & Assert
        self.assertEqual(profile.name, name)
        self.assertEqual(profile.provider_id, provider_id)
Пример #16
0
    def get(self):
        Guser = users.get_current_user()
        if Guser:
            findRequest = Profile.query()
            thisProfilesList = findRequest.fetch()

            template = template_env.get_template(
                'templates/admin/admin/profiles.html')
            context = {'thisProfilesList': thisProfilesList}
            self.response.write(template.render(context))
Пример #17
0
def read_input(file):
	try:
		with open(file) as f:
			data = json.load(f)
			profiles = [Profile(**profile) for profile in data["profiles"]]
		return profiles
	except ValueError:
		sys.exit('Json decode error! Please check file format')
	except FileNotFoundError:
		sys.exit('File not found! Please enter correct file path')	
Пример #18
0
    def get(self):
        Guser = users.get_current_user()
        template = template_env.get_template('templates/register.html')
        if Guser:
            findRequest = Profile.query(
                Profile.strReference == Guser.user_id())
            thisProfileList = findRequest.fetch()
            if len(thisProfileList) > 0:
                thisProfile = thisProfileList[0]
            else:
                thisProfile = Profile()

            if thisProfile.strProfileActivated:
                context = {'ProfileIsActive': "ProfileIsActive"}
            else:
                context = {}
            self.response.write(template.render(context))
        else:
            context = {}
            self.response.write(template.render(context))
Пример #19
0
def getJsonTest():
    geniFile = open('./geni.json','r')
    contents = geniFile.read()
    jsoncontents = json.loads(contents)
    p = Profile(jsoncontents['focus']['id'], 'publicUrl',
            'firstName' + ' ' + 'lastName', [], jsoncontents['focus']['gender'])
    contents = jsoncontents['nodes']
    for node in contents:
        if node.startswith('profile') and jsoncontents['focus']['id'] != contents[node]['id']:
            p.addRelation(contents[node]['first_name'] + ' ' + contents[node]['last_name'],
                      contents[node]['gender'], contents[node]['id'])
    data = {}
    data['id'] = p.id
    data['name'] = p.name
    data['gender'] = p.gender
    data['geniLink'] = p.geniLink
    relations = []
    for node in p.relations:
        relations.append({'id':node.id,'name':node.name,'gender':node.gender})
    data['relations'] = relations
    return jsonify(data)
Пример #20
0
    def post(self):
        Guser = users.get_current_user()
        if Guser:

            vstrCampaignID = self.request.get('vstrCampaignID')

            findRequest = Campaigns.query(
                Campaigns.strCampaignID == vstrCampaignID)
            thisCampaignList = findRequest.fetch()

            if len(thisCampaignList) > 0:
                thisCampaign = thisCampaignList[0]
            else:
                thisCampaign = Campaigns()

            if not (thisCampaign.strPromoted):
                findRequest = Constant.query(
                    Constant.strReference == Guser.user_id())
                thisConstantList = findRequest.fetch()
                if len(thisConstantList) > 0:
                    thisConstant = thisConstantList[0]
                else:
                    thisConstant = Constant()

                thisConstant.writeReference(strinput=Guser.user_id())
                thisConstant.put()

                findRequest = Profile.query(
                    Profile.strReference == Guser.user_id())
                thisProfileList = findRequest.fetch()
                if len(thisProfileList) > 0:
                    thisProfile = thisProfileList[0]
                else:
                    thisProfile = Profile()

                thisProfile.writeReference(strinput=Guser.user_id())

                if (thisProfile.strWallet > thisConstant.strPromotionCost):
                    thisProfile.strWallet = thisProfile.strWallet - thisConstant.strPromotionCost
                    thisCampaign.strPromoted = True
                    thisProfile.put()
                    thisCampaign.put()
                    self.response.write("Campaign Successfully Promoted")
                else:
                    self.response.write(
                        "Campaign cannot be promoted insufficient funds")
            else:
                self.response.write("Campaign Already Promoted")
Пример #21
0
def load_default_profile():
    global decoders
    default_profile = Profile(default_profile_name, profiles_dirs)
    if default_profile.rhasspy.get('preload_profile', False):
        try:
            # Load speech to text decoder
            decoder = maybe_load_decoder(default_profile)
            decoders[default_profile.name] = decoder
        except Exception as e:
            logging.error('Failed to pre-load profile')

    if default_profile.rhasspy.get('listen_on_start', False):
        # Start listening for wake word
        listen_for_wake(default_profile)
Пример #22
0
def main():
    profile1 = Profile("joe", "M", "F", 72, list(range(50, 90)), 5, 20,
                       list(range(18, 50)), 5, "Jewish", 5, "D", 5, "I", "E",
                       5, "N", "Y", 5, "M", "M", 5, "C", 5)
    profile2 = Profile("Jane", "F", "M", 68, list(range(40, 100)), 5, 19,
                       list(range(18, 24)), 5, "Buddhist", 5, "I", 9, "E", "E",
                       5, "Y", "Y", 5, "N", "N", 5, "D", 5)
    profile3 = Profile("Mary", "F", "M", 62, list(range(73, 77)), 2, 18,
                       list(range(18, 21)), 5, "Christian", 1, "R", 10, "E",
                       "E", 7, "N", "N", 5, "N", "M", 2, "D", 4)
    profile4 = Profile("Jackie", "F", "M", 65, list(range(67, 80)), 5, 42,
                       list(range(18, 30)), 5, "Muslim", 5, "R", 5, "I", "I",
                       5, "N", "N", 5, "N", "N", 5, "C", 5)

    profileList = [profile2, profile1, profile4, profile3]
    print(profile1.find_opposite(profileList))

    print()

    print(profile1.find_hated(profileList))

    print()

    print(profile1.find_friend_zone(profileList))
Пример #23
0
    def get(self):
        Guser = users.get_current_user()
        if Guser:

            findRequest = Profile.query(
                Profile.strReference == Guser.user_id())
            thisProfileList = findRequest.fetch()

            if len(thisProfileList) > 0:
                thisProfile = thisProfileList[0]

                if thisProfile.strWithdraw > 0:
                    thisProfile.strWallet = thisProfile.strWallet + thisProfile.strWithdraw
                    thisProfile.strWithdraw = 0
                    thisProfile.strScheduleWithdrawal = None
                    thisProfile.put()
                    self.response.write("Withdrawal Succesfully Cancelled")
                else:
                    self.response.write(
                        "Theres no Scheduled withdrawals to Cancell")
            else:

                self.response.write(
                    "Theres no Scheduled withdrawals to Cancell")
Пример #24
0
def update_database(data):
    print('updating db')
    # start upload text
    if int(data['rows_saved']) > 0:
        if 'saved' in data:
            saved = data['saved']
            if 'addresses' in saved:
                for addresses in saved['addresses']:
                    address = Address()
                    where = {'id': addresses['id']}
                    data = {'address_id': addresses['address_id']}
                    address.put(where=where, data=data)

            if 'colors' in saved:
                for colors in saved['colors']:
                    color = Colored()
                    where = {'id': colors['id']}
                    data = {'color_id': colors['color_id']}
                    color.put(where=where, data=data)
                    
            if 'cards' in saved:
                for cards in saved['cards']:
                    card = Card()
                    where = {'id': cards['id']}
                    data = {'card_id': cards['card_id']}
                    card.put(where=where, data=data)
            if 'credits' in saved:
                for credit in saved['credits']:
                    credits = Credit()
                    where = {'id': credit['id']}
                    data = {'credit_id': credit['credit_id']}
                    credits.put(where=where, data=data)
            if 'companies' in saved:
                for companies in saved['companies']:
                    company = Company()
                    where = {'id': companies['id']}
                    data = {'company_id': companies['company_id']}
                    company.put(where=where, data=data)

            if 'custids' in saved:
                for custids in saved['custids']:
                    custid = Custid()
                    where = {'id': custids['id']}
                    data = {'cust_id': custids['cust_id']}
                    custid.put(where=where, data=data)

            if 'deliveries' in saved:
                for deliveries in saved['deliveries']:
                    delivery = Delivery()
                    where = {'id': deliveries['id']}
                    data = {'delivery_id': deliveries['delivery_id']}
                    delivery.put(where=where, data=data)

            if 'discounts' in saved:
                for discounts in saved['discounts']:
                    discount = Discount()
                    where = {'id': discounts['id']}
                    data = {'discount_id': discounts['discount_id']}
                    discount.put(where=where, data=data)

            if 'inventories' in saved:
                for inventories in saved['inventories']:
                    inventory = Inventory()
                    where = {'id': inventories['id']}
                    data = {'inventory_id': inventories['inventory_id']}
                    inventory.put(where=where, data=data)

            if 'inventory_items' in saved:
                for inventory_items in saved['inventory_items']:
                    inventory_item = InventoryItem()
                    where = {'id': inventory_items['id']}
                    data = {'item_id': inventory_items['item_id']}
                    inventory_item.put(where=where, data=data)

            if 'invoices' in saved:
                for invoices in saved['invoices']:

                    invoice = Invoice()
                    where = {'id': invoices['id']}
                    data = {'invoice_id': invoices['invoice_id']}
                    invoice.put(where=where, data=data)

            if 'invoice_items' in saved:
                for invoice_items in saved['invoice_items']:

                    invoice_item = InvoiceItem()
                    where = {'id': invoice_items['id']}
                    data = {'invoice_items_id': invoice_items['invoice_items_id']}
                    invoice_item.put(where=where, data=data)

            if 'memos' in saved:
                for memos in saved['memos']:
                    memo = Memo()
                    where = {'id': memos['id']}
                    data = {'memo_id': memos['memo_id']}
                    memo.put(where=where, data=data)
            if 'printers' in saved:
                for printers in saved['printers']:
                    printer = Printer()
                    where = {'id': printers['id']}
                    data = {'printer_id': printers['printer_id']}
                    printer.put(where=where, data=data)
                    
            if 'profiles' in saved:
                for profiles in saved['profiles']:
                    profile = Profile()
                    where = {'id': profiles['id']}
                    data = {'p_id': profiles['p_id']}
                    profile.put(where=where, data=data)
                    
            if 'reward_transactions' in saved:
                for reward_transactions in saved['reward_transactions']:
                    reward_transaction = RewardTransaction()
                    where = {'id': reward_transactions['id']}
                    data = {'reward_id': reward_transactions['reward_id']}
                    reward_transaction.put(where=where, data=data)

            if 'rewards' in saved:
                for rewards in saved['rewards']:
                    reward = Reward()
                    where = {'id': rewards['id']}
                    data = {'reward_id': rewards['reward_id']}
                    reward.put(where=where, data=data)

            if 'schedules' in saved:
                for schedules in saved['schedules']:
                    schedule = Schedule()
                    where = {'id': schedules['id']}
                    data = {'schedule_id': schedules['schedule_id']}
                    schedule.put(where=where, data=data)

            if 'taxes' in saved:
                for taxes in saved['taxes']:
                    tax = Tax()
                    where = {'id': taxes['id']}
                    data = {'tax_id': taxes['tax_id']}
                    tax.put(where=where, data=data)

            if 'transactions' in saved:
                for transactions in saved['transactions']:
                    transaction = Transaction()
                    where = {'id': transactions['id']}
                    data = {'trans_id': transactions['trans_id']}
                    transaction.put(where=where, data=data)

            if 'users' in saved:
                for users in saved['users']:
                    user = User()
                    where = {'id': users['id']}
                    data = {'user_id': users['user_id']}
                    user.put(where=where, data=data)

            if 'zipcodes' in saved:
                for zipcodes in saved['zipcodes']:
                    zipcode = Zipcode()
                    where = {'id': zipcodes['id']}
                    data = {'zipcode_id': zipcodes['zipcode_id']}
                    zipcode.put(where=where, data=data)
Пример #25
0
def sync_from_server(data):
    # print('sync from server')
    # start upload text
    # print(data)
    # print(data['rows_to_create'])
    if int(data['rows_to_create']) > 0:
        updates = data['updates']
        if 'addresses' in updates:
            for addresses in updates['addresses']:
                address = Address()
                address.address_id = addresses['id']
                address.user_id = addresses['user_id']
                address.name = addresses['name']
                address.street = addresses['street']
                address.suite = addresses['suite']
                address.city = addresses['city']
                address.state = addresses['state']
                address.zipcode = addresses['zipcode']
                address.primary_address = addresses['primary_address']
                address.concierge_name = addresses['concierge_name']
                address.concierge_number = addresses['concierge_number']
                address.status = addresses['status']
                address.deleted_at = addresses['deleted_at']
                address.created_at = addresses['created_at']
                address.updated_at = addresses['updated_at']
                # check to see if color_id already exists and update

                count_address = address.where({'address_id': address.address_id})
                if len(count_address) > 0 or address.deleted_at:
                    for data in count_address:
                        address.id = data['id']
                        if address.deleted_at:
                            address.delete()
                        else:
                            address.update_special()
                else:
                    address.add_special()
            address.close_connection()
 
        if 'cards' in updates:
            for cards in updates['cards']:
                card = Card()
                card.card_id = cards['id']
                card.company_id = cards['company_id']
                card.user_id = cards['user_id']
                card.profile_id = cards['profile_id']
                card.payment_id = cards['payment_id']
                card.root_payment_id = cards['root_payment_id']
                card.street = cards['street']
                card.suite = cards['suite']
                card.city = cards['city']
                card.state = cards['state']
                card.zipcode = cards['zipcode']
                card.exp_month = cards['exp_month']
                card.exp_year = cards['exp_year']
                card.status = cards['status']
                card.deleted_at = cards['deleted_at']
                card.created_at = cards['created_at']
                card.updated_at = cards['updated_at']
                # check to see if color_id already exists and update

                count_card = card.where({'card_id': card.card_id})
                if len(count_card) > 0 or card.deleted_at:
                    for data in count_card:
                        card.id = data['id']
                        if card.deleted_at:
                            card.delete()
                        else:
                            card.update_special()
                else:
                    card.add_special()
            card.close_connection()
        
        if 'colors' in updates:
            for colors in updates['colors']:
                color = Colored()
                color.color_id = colors['id']
                color.company_id = colors['company_id']
                color.color = colors['color']
                color.name = colors['name']
                color.ordered = colors['ordered']
                color.status = colors['status']
                color.deleted_at = colors['deleted_at']
                color.created_at = colors['created_at']
                color.updated_at = colors['updated_at']
                # check to see if color_id already exists and update

                count_color = color.where({'color_id': color.color_id})
                if len(count_color) > 0 or color.deleted_at:
                    for data in count_color:
                        color.id = data['id']
                        if color.deleted_at:
                            color.delete()
                        else:
                            color.update_special()
                else:
                    color.add_special()
            color.close_connection()

        if 'companies' in updates:
            for companies in updates['companies']:
                company = Company()
                company.company_id = companies['id']
                company.name = companies['name']
                company.street = companies['street']
                company.city = companies['city']
                company.state = companies['state']
                company.zip = companies['zip']
                company.email = companies['email']
                company.phone = companies['phone']
                company.store_hours = companies['store_hours']
                company.turn_around = companies['turn_around']
                company.api_token = companies['api_token']
                company.payment_gateway_id = companies['payment_gateway_id']
                company.payment_api_login = companies['payment_api_login']
                company.deleted_at = companies['deleted_at']
                company.created_at = companies['created_at']
                company.updated_at = companies['updated_at']
                company.server_at = now
                count_company = company.where({'company_id': company.company_id})
                if len(count_company) > 0 or company.deleted_at:
                    for data in count_company:
                        company.id = data['id']
                        if company.deleted_at:
                            company.delete()
                        else:
                            company.update_special()
                else:
                    company.add_special()
            company.close_connection()
            
        if 'credits' in updates:
            for credits in updates['credits']:
                credit = Credit()
                credit.credit_id = credits['id']
                credit.employee_id = credits['employee_id']
                credit.customer_id = credits['customer_id']
                credit.amount = credits['amount']
                credit.reason = credits['reason']
                credit.status = credits['status']
                credit.deleted_at = credits['deleted_at']
                credit.created_at = credits['created_at']
                credit.updated_at = credits['updated_at']
                # check to see already exists and update

                count_credit = credit.where({'credit_id': credit.credit_id})
                if len(count_credit) > 0 or credit.deleted_at:
                    for data in count_credit:
                        credit.id = data['id']
                        if credit.deleted_at:
                            credit.delete()
                        else:
                            credit.update_special()
                else:
                    credit.add_special()
            credit.close_connection()
        if 'custids' in updates:
            for custids in updates['custids']:
                custid = Custid()
                custid.cust_id = custids['id']
                custid.customer_id = custids['customer_id']
                custid.company_id = custids['company_id']
                custid.mark = custids['mark']
                custid.status = custids['status']
                custid.deleted_at = custids['deleted_at']
                custid.created_at = custids['created_at']
                custid.updated_at = custids['updated_at']
                count_custid = custid.where({'cust_id': custids['id']})
                if len(count_custid) > 0 or custid.deleted_at:
                    for data in count_custid:
                        custid.id = data['id']
                        if custid.deleted_at:
                            custid.delete()
                        else:
                            custid.update_special()
                else:
                    custid.add_special()
            custid.close_connection()

        if 'deliveries' in updates:
            for deliveries in updates['deliveries']:
                delivery = Delivery()
                delivery.delivery_id = deliveries['id']
                delivery.company_id = deliveries['company_id']
                delivery.route_name = deliveries['route_name']
                delivery.day = deliveries['day']
                delivery.delivery_limit = deliveries['limit']
                delivery.start_time = deliveries['start_time']
                delivery.end_time = deliveries['end_time']
                delivery.zipcode = deliveries['zipcode']
                delivery.blackout = deliveries['blackout']
                delivery.status = deliveries['status']
                delivery.deleted_at = deliveries['deleted_at']
                delivery.created_at = deliveries['created_at']
                delivery.updated_at = deliveries['updated_at']
                count_delivery = delivery.where({'delivery_id': delivery.delivery_id})
                if len(count_delivery) > 0 or delivery.deleted_at:
                    for data in count_delivery:
                        delivery.id = data['id']
                        if delivery.deleted_at:
                            delivery.delete()
                        else:
                            delivery.update_special()
                else:
                    delivery.add_special()
            delivery.close_connection()

        if 'discounts' in updates:
            for discounts in updates['discounts']:
                discount = Discount()
                discount.discount_id = discounts['id']
                discount.company_id = discounts['company_id']
                discount.inventory_id = discounts['inventory_id']
                discount.inventory_item_id = discounts['inventory_item_id']
                discount.name = discounts['name']
                discount.type = discounts['type']
                discount.discount = discounts['discount']
                discount.rate = discounts['rate']
                discount.end_time = discounts['end_time']
                discount.start_date = discounts['start_date']
                discount.end_date = discounts['end_date']
                discount.status = discounts['status']
                discount.deleted_at = discounts['deleted_at']
                discount.created_at = discounts['created_at']
                discount.updated_at = discounts['updated_at']
                count_discount = discount.where({'discount_id': discount.discount_id})
                if len(count_discount) > 0 or discount.deleted_at:
                    for data in count_discount:
                        discount.id = data['id']
                        if discount.deleted_at:
                            discount.delete()
                        else:
                            discount.update_special()
                else:
                    discount.add_special()
            discount.close_connection()

        if 'inventories' in updates:
            for inventories in updates['inventories']:
                inventory = Inventory()
                inventory.inventory_id = inventories['id']
                inventory.company_id = inventories['company_id']
                inventory.name = inventories['name']
                inventory.description = inventories['description']
                inventory.ordered = inventories['ordered']
                inventory.laundry = inventories['laundry']
                inventory.status = inventories['status']
                inventory.deleted_at = inventories['deleted_at']
                inventory.create_at = inventories['created_at']
                inventory.updated_at = inventories['updated_at']
                count_inventory = inventory.where({'inventory_id': inventory.inventory_id})
                if len(count_inventory) > 0 or inventory.deleted_at:
                    for data in count_inventory:
                        inventory.id = data['id']
                        if inventory.deleted_at:
                            inventory.delete()
                        else:
                            inventory.update_special()
                else:
                    inventory.add_special()
            inventory.close_connection()

        if 'inventory_items' in updates:
            for inventory_items in updates['inventory_items']:
                inventory_item = InventoryItem()
                inventory_item.item_id = inventory_items['id']
                inventory_item.inventory_id = inventory_items['inventory_id']
                inventory_item.company_id = inventory_items['company_id']
                inventory_item.name = inventory_items['name']
                inventory_item.description = inventory_items['description']
                inventory_item.tags = inventory_items['tags']
                inventory_item.quantity = inventory_items['quantity']
                inventory_item.ordered = inventory_items['ordered']
                inventory_item.price = inventory_items['price']
                inventory_item.image = inventory_items['image']
                inventory_item.status = inventory_items['status']
                inventory_item.deleted_at = inventory_items['deleted_at']
                inventory_item.created_at = inventory_items['created_at']
                inventory_item.updated_at = inventory_items['updated_at']
                count_inventory_item = inventory_item.where({'item_id': inventory_item.item_id})
                if len(count_inventory_item) > 0 or inventory_item.deleted_at:
                    for data in count_inventory_item:
                        inventory_item.id = data['id']
                        if inventory_item.deleted_at:
                            inventory_item.delete()
                        else:
                            inventory_item.update_special()
                else:
                    inventory_item.add_special()
            inventory_item.close_connection()

        # if 'invoice_items' in updates:
        #     for invoice_items in updates['invoice_items']:
        #         invoice_item = InvoiceItem()
        #         invoice_item.invoice_items_id = invoice_items['id']
        #         invoice_item.invoice_id = invoice_items['invoice_id']
        #         invoice_item.item_id = invoice_items['item_id']
        #         invoice_item.inventory_id = invoice_items['inventory_id']
        #         invoice_item.company_id = invoice_items['company_id']
        #         invoice_item.customer_id = invoice_items['customer_id']
        #         invoice_item.quantity = invoice_items['quantity']
        #         invoice_item.color = invoice_items['color']
        #         invoice_item.memo = invoice_items['memo']
        #         invoice_item.pretax = invoice_items['pretax']
        #         invoice_item.tax = invoice_items['tax']
        #         invoice_item.total = invoice_items['total']
        #         invoice_item.status = invoice_items['status']
        #         invoice_item.deleted_at = invoice_items['deleted_at']
        #         invoice_item.created_at = invoice_items['created_at']
        #         invoice_item.updated_at = invoice_items['updated_at']
        #         count_invoice_item = invoice_item.where({'invoice_items_id': invoice_item.invoice_items_id})
        #         if len(count_invoice_item) > 0 or invoice_item.deleted_at:
        #             for data in count_invoice_item:
        #                 invoice_item.id = data['id']
        #                 if invoice_item.deleted_at:
        #                     invoice_item.delete()
        #                 else:
        #                     invoice_item.update_special()
        #         else:
        #             invoice_item.add_special()
        #     invoice_item.close_connection()
        #
        # if 'invoices' in updates:
        #
        #     for invoices in updates['invoices']:
        #         invoice = Invoice()
        #         invoice.invoice_id = invoices['id']
        #         invoice.company_id = invoices['company_id']
        #         invoice.customer_id = invoices['customer_id']
        #         invoice.quantity = invoices['quantity']
        #         invoice.pretax = invoices['pretax']
        #         invoice.tax = invoices['tax']
        #         invoice.reward_id = invoices['reward_id']
        #         invoice.discount_id = invoices['discount_id']
        #         invoice.total = invoices['total']
        #         invoice.rack = invoices['rack']
        #         invoice.rack_date = invoices['rack_date']
        #         invoice.due_date = invoices['due_date']
        #         invoice.memo = invoices['memo']
        #         invoice.transaction_id = invoices['transaction_id']
        #         invoice.schedule_id = invoices['schedule_id']
        #         invoice.status = invoices['status']
        #         invoice.deleted_at = invoices['deleted_at']
        #         invoice.created_at = invoices['created_at']
        #         invoice.updated_at = invoices['updated_at']
        #
        #         # extra loop through invoice items to delete or check for data
        #         if 'invoice_items' in invoices:
        #
        #             iitems = invoices['invoice_items']
        #             if len(iitems) > 0:
        #                 for iitem in iitems:
        #                     invoice_item = InvoiceItem()
        #                     invoice_item.invoice_items_id = iitem['id']
        #                     invoice_item.invoice_id = iitem['invoice_id']
        #                     invoice_item.item_id = iitem['item_id']
        #                     invoice_item.inventory_id = iitem['inventory_id']
        #                     invoice_item.company_id = iitem['company_id']
        #                     invoice_item.customer_id = iitem['customer_id']
        #                     invoice_item.quantity = iitem['quantity']
        #                     invoice_item.color = iitem['color']
        #                     invoice_item.memo = iitem['memo']
        #                     invoice_item.pretax = iitem['pretax']
        #                     invoice_item.tax = iitem['tax']
        #                     invoice_item.total = iitem['total']
        #                     invoice_item.status = iitem['status']
        #                     invoice_item.deleted_at = iitem['deleted_at']
        #                     invoice_item.created_at = iitem['created_at']
        #                     invoice_item.updated_at = iitem['updated_at']
        #                     count_invoice_item = invoice_item.where({'invoice_items_id': invoice_item.invoice_items_id})
        #                     if len(count_invoice_item) > 0 or invoice_item.deleted_at:
        #                         for data in count_invoice_item:
        #                             invoice_item.id = data['id']
        #                             if invoice_item.deleted_at:
        #                                 invoice_item.delete()
        #                             else:
        #                                 invoice_item.update_special()
        #
        #         count_invoice = invoice.where({'invoice_id': invoice.invoice_id})
        #         if len(count_invoice) > 0 or invoice.deleted_at:
        #             for data in count_invoice:
        #                 invoice.id = data['id']
        #                 if invoice.deleted_at:
        #                     invoice.delete()
        #                 else:
        #                     invoice.update_special()
        #         else:
        #             invoice.add_special()
        #     invoice.close_connection()

        if 'memos' in updates:
            for memos in updates['memos']:
                memo = Memo()
                memo.memo_id = memos['id']
                memo.company_id = memos['company_id']
                memo.memo = memos['memo']
                memo.ordered = memos['ordered']
                memo.status = memos['status']
                memo.deleted_at = memos['deleted_at']
                memo.created_at = memos['created_at']
                memo.updated_at = memos['updated_at']
                count_memo = memo.where({'memo_id': memo.memo_id})
                if len(count_memo) > 0 or memo.deleted_at:
                    for data in count_memo:
                        memo.id = data['id']
                        if memo.deleted_at:
                            memo.delete()
                        else:
                            memo.update_special()
                else:
                    memo.add_special()
            memo.close_connection()

        # if 'printers' in updates:
        #     for printers in updates['printers']:
        #         printer = Printer()
        #         printer.printer_id = printers['id']
        #         printer.company_id = printers['company_id']
        #         printer.name = printers['name']
        #         printer.model = printers['model']
        #         printer.nick_name = printers['nick_name']
        #         printer.type = printers['type']
        #         printer.vendor_id = printers['vendor_id']
        #         printer.product_id = printers['product_id']
        #         printer.status = printers['status']
        #         printer.deleted_at = printers['deleted_at']
        #         printer.created_at = printers['created_at']
        #         printer.updated_at = printers['updated_at']
        #         count_printer = printer.where({'printer_id': printer.printer_id})
        #         if len(count_printer) > 0 or printer.deleted_at:
        #             for data in count_printer:
        #                 printer.id = data['id']
        #                 if printer.deleted_at:
        #                     printer.delete()
        #                 else:
        #                     printer.update_special()
        #         else:
        #             printer.add_special()
        #     printer.close_connection()

        if 'profiles' in updates:
            for profiles in updates['profiles']:
                profile = Profile()
                profile.p_id = profiles['id']
                profile.company_id = profiles['company_id']
                profile.user_id = profiles['user_id']
                profile.profile_id = profiles['profile_id']
                profile.status = profiles['status']
                profile.deleted_at = profiles['deleted_at']
                profile.created_at = profiles['created_at']
                profile.updated_at = profiles['updated_at']
                count_profile = profile.where({'p_id': profile.p_id})
                if len(count_profile) > 0 or profile.deleted_at:
                    for data in count_profile:
                        profile.id = data['id']
                        if profile.deleted_at:
                            profile.delete()
                        else:
                            profile.update_special()
                else:
                    profile.add_special()
            profile.close_connection()


        if 'reward_transactions' in updates:
            for reward_transactions in updates['reward_transactions']:
                reward_transaction = RewardTransaction()
                reward_transaction.reward_id = reward_transactions['reward_id']
                reward_transaction.transaction_id = reward_transactions['transaction_id']
                reward_transaction.customer_id = reward_transactions['customer_id']
                reward_transaction.employee_id = reward_transactions['employee_id']
                reward_transaction.company_id = reward_transactions['company_id']
                reward_transaction.type = reward_transactions['type']
                reward_transaction.points = reward_transactions['points']
                reward_transaction.credited = reward_transactions['credited']
                reward_transaction.reduced = reward_transactions['reduced']
                reward_transaction.running_total = reward_transactions['running_total']
                reward_transaction.reason = reward_transactions['reason']
                reward_transaction.name = reward_transactions['name']
                reward_transaction.status = reward_transactions['status']
                reward_transaction.deleted_at = reward_transactions['deleted_at']
                reward_transaction.created_at = reward_transactions['created_at']
                reward_transaction.updated_at = reward_transactions['updated_at']
                count_reward_transaction = reward_transaction.where({'reward_id': reward_transaction.reward_id})
                if len(count_reward_transaction) > 0 or reward_transaction.deleted_at:
                    for data in count_reward_transaction:
                        reward_transaction.id = data['id']
                        if reward_transaction.deleted_at:
                            reward_transaction.delete()
                        else:
                            reward_transaction.update_special()
                else:
                    reward_transaction.add_special()
            reward_transaction.close_connection()

        if 'rewards' in updates:
            for rewards in updates['rewards']:
                reward = Reward()
                reward.reward_id = rewards['id']
                reward.company_id = rewards['company_id']
                reward.name = rewards['name']
                reward.points = rewards['points']
                reward.discount = rewards['discount']
                reward.status = rewards['status']
                reward.deleted_at = rewards['deleted_at']
                reward.created_at = rewards['created_at']
                reward.updated_at = rewards['updated_at']
                count_reward = reward.where({'reward_id': reward.reward_id})
                if len(count_reward) > 0 or reward.deleted_at:
                    for data in count_reward:
                        reward.id = data['id']
                        if reward.deleted_at:
                            reward.delete()
                        else:
                            reward.update_special()
                else:
                    reward.add_special()
            reward.close_connection()

        if 'schedules' in updates:
            for schedules in updates['schedules']:
                schedule = Schedule()
                schedule.schedule_id = schedules['id']
                schedule.company_id = schedules['company_id']
                schedule.customer_id = schedules['customer_id']
                schedule.card_id = schedules['card_id']
                schedule.pickup_delivery_id = schedules['pickup_delivery_id']
                schedule.pickup_address = schedules['pickup_address']
                schedule.pickup_date = schedules['pickup_date']
                schedule.dropoff_delivery_id = schedules['dropoff_delivery_id']
                schedule.dropoff_address = schedules['dropoff_address']
                schedule.dropoff_date = schedules['dropoff_date']
                schedule.special_instructions = schedules['special_instructions']
                schedule.type = schedules['type']
                schedule.token = schedules['token']
                schedule.status = schedules['status']
                schedule.deleted_at = schedules['deleted_at']
                schedule.created_at = schedules['created_at']
                schedule.updated_at = schedules['updated_at']
                count_schedule = schedule.where({'schedule_id': schedule.schedule_id})
                if len(count_schedule) > 0 or schedule.deleted_at:
                    for data in count_schedule:
                        schedule.id = data['id']
                        if schedule.deleted_at:
                            schedule.delete()
                        else:
                            schedule.update_special()
                else:
                    schedule.add_special()
            schedule.close_connection()

        if 'taxes' in updates:
            for taxes in updates['taxes']:
                tax = Tax()
                tax.tax_id = taxes['id']
                tax.company_id = taxes['company_id']
                tax.rate = taxes['rate']
                tax.status = taxes['status']
                tax.deleted_at = taxes['deleted_at']
                tax.created_at = taxes['created_at']
                tax.updated_at = taxes['updated_at']
                count_tax = tax.where({'tax_id': tax.tax_id})
                if len(count_tax) > 0 or tax.deleted_at:
                    for data in count_tax:
                        tax.id = data['id']
                        if tax.deleted_at:
                            tax.delete()
                        else:
                            tax.update_special()
                else:
                    tax.add_special()
            tax.close_connection()

        if 'transactions' in updates:
            for transactions in updates['transactions']:
                transaction = Transaction()
                transaction.trans_id = transactions['id']
                transaction.company_id = transactions['company_id']
                transaction.customer_id = transactions['customer_id']
                transaction.schedule_id = transactions['schedule_id']
                transaction.pretax = transactions['pretax']
                transaction.tax = transactions['tax']
                transaction.aftertax = transactions['aftertax']
                transaction.credit = transactions['credit']
                transaction.discount = transactions['discount']
                transaction.total = transactions['total']
                transaction.invoices = transactions['invoices'] if transactions['invoices'] else None
                transaction.account_paid = transactions['account_paid']
                transaction.account_paid_on = transactions['account_paid_on']
                transaction.type = transactions['type']
                transaction.last_four = transactions['last_four']
                transaction.tendered = transactions['tendered']
                transaction.transaction_id = transactions['transaction_id']
                transaction.status = transactions['status']
                transaction.deleted_at = transactions['deleted_at']
                transaction.created_at = transactions['created_at']
                transaction.updated_at = transactions['updated_at']
                count_transaction = transaction.where({'trans_id': transaction.trans_id})
                if len(count_transaction) > 0 or transaction.deleted_at:
                    for data in count_transaction:
                        transaction.id = data['id']
                        if transaction.deleted_at:
                            transaction.delete()
                        else:
                            transaction.update_special()
                else:
                    transaction.add_special()
            transaction.close_connection()

        if 'users' in updates:
            for users in updates['users']:
                user = User()
                user.user_id = users['id']
                user.company_id = users['company_id']
                user.username = users['username']
                user.first_name = users['first_name']
                user.last_name = users['last_name']
                user.street = users['street']
                user.suite = users['suite']
                user.city = users['city']
                user.state = users['state']
                user.zipcode = users['zipcode']
                user.email = users['email']
                user.phone = users['phone']
                user.intercom = users['intercom']
                user.concierge_name = users['concierge_name']
                user.concierge_number = users['concierge_number']
                user.special_instructions = users['special_instructions']
                user.shirt_old = users['shirt_old']
                user.shirt = users['shirt']
                user.delivery = users['delivery']
                user.profile_id = users['profile_id']
                user.payment_status = users['payment_status']
                user.payment_id = users['payment_id']
                user.token = users['token']
                user.api_token = users['api_token']
                user.reward_status = users['reward_status']
                user.reward_points = users['reward_points']
                user.account = users['account']
                user.account_total = users['account_total']
                user.credits = users['credits']
                user.starch = users['starch']
                user.important_memo = users['important_memo']
                user.invoice_memo = users['invoice_memo']
                user.role_id = users['role_id']
                user.deleted_at = users['deleted_at']
                user.created_at = users['created_at']
                user.updated_at = users['updated_at']
                count_user = user.where({'user_id': user.user_id})
                if len(count_user) > 0 or user.deleted_at:
                    for data in count_user:
                        user.id = data['id']
                        if user.deleted_at:
                            user.delete()
                        else:
                            user.update_special()
                else:
                    user.add_special()
            user.close_connection()

        if 'zipcodes' in updates:
            for zipcodes in updates['zipcodes']:
                zipcode = Zipcode()
                zipcode.zipcode_id = zipcodes['id']
                zipcode.company_id = zipcodes['company_id']
                zipcode.delivery_id = zipcodes['delivery_id']
                zipcode.zipcode = zipcodes['zipcode']
                zipcode.status = zipcodes['status']
                zipcode.deleted_at = zipcodes['deleted_at']
                zipcode.created_at = zipcodes['created_at']
                zipcode.updated_at = zipcodes['updated_at']
                # check to see if color_id already exists and update
        
                count_zipcode = zipcode.where({'zipcode_id': zipcode.zipcode_id})
                if len(count_zipcode) > 0 or zipcode.deleted_at:
                    for data in count_zipcode:
                        zipcode.id = data['id']
                        if zipcode.deleted_at:
                            zipcode.delete()
                        else:
                            zipcode.update_special()
                else:
                    zipcode.add_special()
            zipcode.close_connection()
Пример #26
0
    def get(self):
        Guser = users.get_current_user()
        if Guser:
            vstrFirstName = self.request.get('vstrFirstName')
            vstrSurname = self.request.get('vstrSurname')
            vstrCellNumber = self.request.get('vstrCellNumber')
            vstrEmail = self.request.get('vstrEmail')

            findRequest = Profile.query(
                Profile.strReference == Guser.user_id())
            thisProfileList = findRequest.fetch()

            if len(thisProfileList) > 0:
                thisProfile = thisProfileList[0]
            else:
                thisProfile = Profile()

            try:
                thisProfile.writeReference(strinput=Guser.user_id())
                thisProfile.writeFullNames(strinput=vstrFirstName)
                thisProfile.writeSurname(strinput=vstrSurname)
                thisProfile.writeCell(strinput=vstrCellNumber)
                thisProfile.writeEmail(strinput=vstrEmail)
                thisProfile.CreateConfirmCode()
                if thisProfile.sendActivationCode() == True:
                    thisProfile.put()
                    self.response.write(
                        "A Comfirmation Email has been sent please follow the instructions on the email to fully activate your account"
                    )
                else:
                    self.response.write(
                        "Send Mail Function causing a general Error please check your email address"
                    )
            except:
                self.response.write(
                    "There was an error sending a confirmation email please try again"
                )
Пример #27
0
    def predict(self, F, datainfo, timeinfo):
        print('\nFile: {} Class: {} Function: {} State: {}'.format(
            'architectures.py', 'OriginalEnsemble', 'predict', 'Start'))

        info = extract(datainfo, timeinfo)
        self._info.update(info)
        print_time_info(self._info)

        test_data = get_data(F, self._info)
        print('test_data.shape: {}'.format(test_data.shape))

        transformed_test_data = self._transform(test_data, DataType.TEST)
        train_data = self._transform(self._train_data, DataType.TRAIN)

        train_labels = self._train_labels
        print('transformed_test_data.shape: {}'.format(
            transformed_test_data.shape))
        print('train_data.shape: {}'.format(train_data.shape))

        size = len(train_data) if len(transformed_test_data) > len(
            train_data) else len(transformed_test_data)
        train_weights = correct_covariate_shift(
            train_data, self._test_sampler.sample(transformed_test_data, size),
            self._random_state, self._correction_threshold,
            self._correction_n_splits) if self._should_correct else None

        fixed_hyperparameters, search_space = Profile.parse_profile(
            self._profile)
        if self._best_hyperparameters is None:
            tuner = HyperparametersTuner(fixed_hyperparameters, search_space,
                                         self._max_evaluations)
            self._best_hyperparameters = tuner.get_best_hyperparameters(
                train_data, train_labels, self._validation_ratio,
                self._random_state)
            print('self._best_hyperparameters: {}'.format(
                self._best_hyperparameters))

        if has_sufficient_time(self._dataset_budget_threshold,
                               self._info) or len(self._classifiers) == 0:
            t_d, validation_data, t_l, validation_labels = train_test_split(
                train_data,
                train_labels,
                test_size=self._validation_ratio,
                random_state=self._random_state,
                shuffle=True,
                stratify=train_labels)
            new_classifier = LGBMClassifier()
            new_classifier.set_params(**self._best_hyperparameters)
            new_classifier.fit(train_data,
                               train_labels,
                               sample_weight=train_weights)

            new_predictions = new_classifier.predict_proba(validation_data)[:,
                                                                            1]
            new_weight = compute_weight(new_predictions, validation_labels,
                                        self._epsilon)

            self._ensemble_weights = np.array([])
            for i in range(len(self._classifiers)):
                currrent_classifier = self._classifiers[i]
                currrent_classifier_predictions = currrent_classifier.predict_proba(
                    validation_data)[:, 1]
                currrent_classifier_weight = compute_weight(
                    currrent_classifier_predictions, validation_labels,
                    self._epsilon)
                self._ensemble_weights = np.append(self._ensemble_weights,
                                                   currrent_classifier_weight)

            self._classifiers = np.append(self._classifiers, new_classifier)
            self._ensemble_weights = np.append(self._ensemble_weights,
                                               new_weight)
            print('self._ensemble_weights: {}'.format(self._ensemble_weights))

            if len(self._classifiers) > self._ensemble_size:
                i = remove_worst_classifier(self._classifiers, validation_data,
                                            validation_labels)
                print('Removed classifier: {}'.format(i))
                self._classifiers = np.delete(self._classifiers, i)
                self._ensemble_weights = np.delete(self._ensemble_weights, i)
        else:
            print('Time budget exceeded.')

        if len(self._classifiers) == 1:
            predictions = self._classifiers[0].predict_proba(
                transformed_test_data)[:, 1]
        else:
            predictions = np.zeros(len(transformed_test_data))
            for i in range(len(self._classifiers)):
                predictions = np.add(
                    predictions, self._ensemble_weights[i] *
                    self._classifiers[i].predict_proba(
                        transformed_test_data)[:, 1])
            predictions = np.divide(predictions,
                                    np.sum(self._ensemble_weights))
        self._iteration += 1
        print('predictions.shape: {}'.format(predictions.shape))
        print('File: {} Class: {} Function: {} State: {} \n'.format(
            'architectures.py', 'OriginalEnsemble', 'predict', 'End'))
        return predictions
Пример #28
0
    def predict(self, F, datainfo, timeinfo):
        print('\nFile: {} Class: {} Function: {} State: {}'.format(
            'architectures.py', 'OriginalEnsemble', 'predict', 'Start'))

        info = extract(datainfo, timeinfo)
        self._info.update(info)
        print_time_info(self._info)

        test_data = get_data(F, self._info)
        print('test_data.shape: {}'.format(test_data.shape))

        transformed_test_data = self._transform(test_data, DataType.TEST)
        train_data = self._transform(self._train_data, DataType.TRAIN)

        train_labels = self._train_labels
        print('transformed_test_data.shape: {}'.format(
            transformed_test_data.shape))
        print('train_data.shape: {}'.format(train_data.shape))

        size = len(train_data) if len(transformed_test_data) > len(
            train_data) else len(transformed_test_data)
        train_weights = correct_covariate_shift(
            train_data, self._test_sampler.sample(transformed_test_data, size),
            self._random_state, self._correction_threshold,
            self._correction_n_splits) if self._should_correct else None

        fixed_hyperparameters, search_space = Profile.parse_profile(
            self._profile)
        if self._best_hyperparameters is None:
            tuner = HyperparametersTuner(fixed_hyperparameters, search_space,
                                         self._max_evaluations)
            self._best_hyperparameters = tuner.get_best_hyperparameters(
                train_data, train_labels, self._validation_ratio,
                self._random_state)
            print('self._best_hyperparameters: {}'.format(
                self._best_hyperparameters))

        if has_sufficient_time(self._dataset_budget_threshold, self._info):
            t_d, validation_data, t_l, validation_labels = train_test_split(
                train_data,
                train_labels,
                test_size=self._validation_ratio,
                random_state=self._random_state,
                shuffle=True,
                stratify=train_labels)

            self._classifier = LGBMClassifier()
            self._classifier.set_params(**self._best_hyperparameters)
            self._classifier.fit(train_data,
                                 train_labels,
                                 sample_weight=train_weights)

        else:
            print('Time budget exceeded.')

        predictions = self._classifier.predict_proba(transformed_test_data)[:,
                                                                            1]
        self._iteration += 1
        print('predictions.shape: {}'.format(predictions.shape))
        print('File: {} Class: {} Function: {} State: {} \n'.format(
            'architectures.py', 'OriginalEnsemble', 'predict', 'End'))
        return predictions
Пример #29
0
    def get(self):
        Guser = users.get_current_user()
        if Guser:
            vstrapply_boost = self.request.get('vstrapply_boost')
            vstrCampaignID = self.request.get('vstrCampaignID')

            findRequest = Campaigns.query(
                Campaigns.strCampaignID == vstrCampaignID)
            thisCampaignList = findRequest.fetch()

            if len(thisCampaignList) > 0:
                thisCampaign = thisCampaignList[0]
            else:
                thisCampaign = Campaigns()

            if (thisCampaign.strBoost + int(vstrapply_boost)) <= 10:

                findRequest = Profile.query(
                    Profile.strReference == thisCampaign.strReference)
                thisProfileList = findRequest.fetch()
                if len(thisProfileList) > 0:
                    thisProfile = thisProfileList[0]
                else:
                    thisProfile = Profile()

                if thisProfile.strWallet > int(vstrapply_boost):
                    thisCampaign.setBoostLevel(strinput=vstrapply_boost)
                    thisProfile.strWallet = thisProfile.strWallet - int(
                        vstrapply_boost)
                    thisProfile.put()
                    self.response.write("Boost Level Successfully Adjusted")
                else:
                    self.response.write(
                        "Boost Level not Adjusted insufficient funds")

            elif thisCampaign.strBoost < 10:
                vstrapply_boost = 10 - thisCampaign.strBoost
                findRequest = Profile.query(
                    Profile.strReference == thisCampaign.strReference)
                thisProfileList = findRequest.fetch()
                if len(thisProfileList) > 0:
                    thisProfile = thisProfileList[0]
                else:
                    thisProfile = Profile()

                if thisProfile.strWallet > vstrapply_boost:
                    vstrapply_boost = str(vstrapply_boost)
                    thisCampaign.setBoostLevel(strinput=vstrapply_boost)
                    thisProfile.strWallet = thisProfile.strWallet - int(
                        vstrapply_boost)
                    thisProfile.put()
                    self.response.write("Boost Level Successfully Adjusted")
                else:
                    self.response.write(
                        "Boost Level not Adjusted insufficient funds")

            else:
                self.response.write("Campaign fully boosted")

            thisCampaign.put()
Пример #30
0
    def get(self):
        Guser = users.get_current_user()
        if Guser:
            vstrWithDrawalAmount = self.request.get('vstrWithDrawalAmount')
            vstrWithdrawalMethod = self.request.get('vstrWithdrawalMethod')
            vstrWithDrawalAmount = int(vstrWithDrawalAmount)

            findRequest = Profile.query(
                Profile.strReference == Guser.user_id())
            thisProfileList = findRequest.fetch()

            if len(thisProfileList) > 0:
                thisProfile = thisProfileList[0]
            else:
                thisProfile = Profile()

            thisProfile.writeReference(strinput=Guser.user_id())

            if (thisProfile.strWallet >
                    vstrWithDrawalAmount) and (vstrWithDrawalAmount > 100):
                thisProfile.strWallet = thisProfile.strWallet - vstrWithDrawalAmount
                thisProfile.strWithdraw = thisProfile.strWithdraw + vstrWithDrawalAmount
                Today = datetime.datetime.now()
                Today = Today.date()

                thisMonth = Today.month
                thisYear = Today.year

                if thisMonth < 12:
                    thisMonth = thisMonth + 1
                else:
                    thisMonth = 1
                    thisYear = thisYear + 1

                thisDay = Today.day

                Today = datetime.date(year=thisYear,
                                      month=thisMonth,
                                      day=thisDay)

                thisProfile.strScheduleWithdrawal = Today
                thisProfile.strWithDrawMethod = vstrWithdrawalMethod
                thisProfile.put()

                self.response.write("Withdrawal Successfully scheduled")
            else:
                self.response.write(
                    "Cannot Schedule a withdrawal either because your withdrawal is less than $ 100.00 or your Balance is less than $ 100.00"
                )
Пример #31
0
    def get(self):
        Guser = users.get_current_user()
        if Guser:
            findRequest = MyAffiliates.query(MyAffiliates.strReference == Guser.user_id())
            thisMyAffiliatesList = findRequest.fetch()

            if len(thisMyAffiliatesList) > 0:
                thisMyAffiliates = thisMyAffiliatesList[0]
            else:
                thisMyAffiliates = MyAffiliates()
                thisMyAffiliates.writeReference(strinput=Guser.user_id())
                thisMyAffiliates.put()

            if thisMyAffiliates.strAvailable >= 50:
                findRequest = Profile.query(Profile.strReference == Guser.user_id())
                thisProfileList = findRequest.fetch()
                if len(thisProfileList) > 0:
                    thisProfile = thisProfileList[0]
                else:
                    thisProfile = Profile()
                    thisProfile.writeReference(strinput=Guser.user_id())
                    thisProfile.put()
                try:
                    thisProfile.strWallet = thisProfile.strWallet + thisMyAffiliates.strAvailable
                    thisMyAffiliates.strAvailable = 0
                    thisProfile.strTotalFundsReceived = thisProfile.strTotalFundsReceived + thisMyAffiliates.strAvailable
                    thisMyAffiliates.put()
                    thisProfile.put()
                    self.response.write("Succesfully Transferred all Affiliate Income into your Wallet")
                except:
                    self.response.write("Error Transferring your Affiliate funds into your Wallet")
            else:
                self.response.write("Error Transferring your Affiliate funds into your Wallet insufficient credit")
Пример #32
0
    def post(self):
        Guser = users.get_current_user()
        if Guser:
            vstrCampaignType = self.request.get('vstrCampaignType')
            vstrCampaignName = self.request.get('vstrCampaignName')
            vstrCampaignIntro = self.request.get('vstrCampaignIntro')
            vstrCampaignBody = self.request.get('vstrCampaignBody')
            vstrFundMe = self.request.get('vstrFundMe')

            findRequest = Constant.query(
                Constant.strReference == Guser.user_id())
            thisConstantList = findRequest.fetch()

            if len(thisConstantList) > 0:
                thisConstant = thisConstantList[0]
            else:
                thisConstant = Constant()

            findRequest = Campaigns.query(
                Campaigns.strReference == Guser.user_id())
            thisCampaignsList = findRequest.fetch()

            findRequest = Profile.query(
                Profile.strReference == Guser.user_id())
            thisProfileList = findRequest.fetch()

            if len(thisProfileList) > 0:
                thisProfile = thisProfileList[0]
            else:
                thisProfile = Profile()

            if (thisProfile.strWallet > thisConstant.strCampaignCost) or (
                    len(thisCampaignsList) <
                    thisConstant.strFreeCampaignAllowance):
                if len(thisCampaignsList
                       ) > thisConstant.strFreeCampaignAllowance:
                    thisProfile.strWallet = thisProfile.strWallet - thisConstant.strCampaignCost
                else:
                    pass
                try:
                    thisCampaign = Campaigns()
                    thisCampaign.writeReference(strinput=Guser.user_id())
                    thisCampaignID = str(Guser.user_id()) + str(
                        len(thisCampaignsList))

                    thisCampaign.writeCampaignID(strinput=thisCampaignID)
                    thisPublicURL = "/campaigns/public/" + thisCampaignID
                    thisPublicURL = thisConstant.strAppURL + thisPublicURL
                    thisCampaign.writeCampaignURL(strinput=thisPublicURL)
                    thisCampaign.writeCampaignName(strinput=vstrCampaignName)
                    if vstrCampaignType == "Personal":
                        thisCampaign.setBusinessCampaign(strinput=True)
                    else:
                        thisCampaign.setBusinessCampaign(strinput=False)

                    thisCampaign.writeCampaignIntro(strinput=vstrCampaignIntro)
                    thisCampaign.writeCampaignBody(strinput=vstrCampaignBody)
                    thisCampaign.writeFundMe(strinput=vstrFundMe)
                    # thisCampaign.setActive() Cannot set the campaign to active since this is a draft
                    StartDate = datetime.datetime.now()
                    StartDate = StartDate.date()
                    EndDate = datetime.date.today() + datetime.timedelta(+30)
                    thisCampaign.setStartDate(strinput=StartDate)
                    thisCampaign.setEndDate(strinput=EndDate)
                    thisInternalURL = "/campaigns/detail/" + thisCampaignID
                    thisCampaign.writeInternalURL(strinput=thisInternalURL)

                    thisCampaign.put()
                    self.response.write("Successfully created your Campaign")
                except:
                    self.response.write("Error Creating Campaign")
            else:
                self.response.write(
                    "Insufficient credit to create a new campaign")
Пример #33
0
def results():

    name = request.form['name']
    Gender = request.form['Gender']
    PGender = request.form['pGender']
    Height = request.form['Height']
    pHeight = request.form['pHeight']
    heightScale = request.form['heightScale']
    Age = request.form['Age']
    pAge = request.form['pAge']
    religion = request.form['Religion']
    religionScale = request.form['religionScale']
    politics = request.form['Politics']
    politicsScale = request.form['politicsScale']
    introExtrovert = request.form['IntroExtro']
    pIntroExtrovert = request.form['PIntroExtro']
    introExtrovertScale = 1  #request.form['IntroExtroScale']
    smoke = request.form['Smoker']
    pSmoke = request.form['Psmoker']
    smokeScale = request.form['smokeScale']
    messyNeat = request.form['MessyNeat']
    pMessyNeat = request.form['PMessyNeat']
    messyNeatScale = request.form['messyNeatScale']
    dogCat = request.form['DogCat']
    dogCatScale = request.form['dogCatScale']
    Robot = request.form['Robot']
    pic = request.form['pic']
    email = request.form['email']

    #List of all of the values
    userValues = [
        name, Gender, PGender, Height, pHeight, heightScale, Age, pAge,
        religion, religionScale, politics, politicsScale, introExtrovert,
        pIntroExtrovert, introExtrovertScale, smoke, pSmoke, smokeScale,
        messyNeat, pMessyNeat, messyNeatScale, dogCat, dogCatScale, Robot,
        email, pic
    ]

    #Convert values to proper form (turn to integer, list)
    for i in range(len(userValues)):
        #Integers
        if isinstance(userValues[i], int) or userValues[i].isdigit():
            userValues[i] = int(userValues[i])
        #List
        elif len(userValues[i]) > 0 and userValues[i][0] == "[":
            comma = userValues[i].index(",")
            num1 = ""
            num2 = ""
            for j in range(1, comma):
                num1 += userValues[i][j]
            for j in range(comma + 1, len(userValues[i]) - 1):
                num2 += userValues[i][j]
            num1 = int(num1)
            num2 = int(num2)
            userValues[i] = list(range(num1, num2 + 1))

    #Create profile
    profile0 = Profile(userValues[0], userValues[1], userValues[2],
                       userValues[3], userValues[4], userValues[5],
                       userValues[6], userValues[7], userValues[8],
                       userValues[9], userValues[10], userValues[11],
                       userValues[12], userValues[13], userValues[14],
                       userValues[15], userValues[16], userValues[17],
                       userValues[18], userValues[19], userValues[20],
                       userValues[21], userValues[22], userValues[23],
                       userValues[24], userValues[25])

    #Read the database list, append current profile
    with open('profileInformation.txt', 'rb') as input:
        data = pickle.load(input)
        if profile0 not in data:
            data.append(profile0)
    #Write list back to database
    with open('profileInformation.txt', 'wb') as output:
        pickle.dump(data, output, pickle.HIGHEST_PROTOCOL)

    #Read the database list
    with open('profileInformation.txt', 'rb') as input:
        profileList = pickle.load(input)

    #Junk profiles (for testing)
    # profile1 = Profile("joe","Male","Female",72,list(range(50,90)),5,20,list(range(18,50)),"Jewish",5,"Democrat",5,"Introvert","Extrovert",5,"No","Yes",5,"Messy","Messy",5,"Cat",5)
    # profile2 = Profile("Jane","Female","Male",68,list(range(40,100)),5,19,list(range(18,24)),"Buddhist",5,"Independent",9,"Extrovert","Extrovert",5,"Yes","Yes",5,"Neat","Neat",5,"Dog",5)
    # profile3 = Profile("Mary","Female","Male",62,list(range(73,77)),2,18,list(range(18,21)),"Christian",1,"Republican",10,"Extrovert","Extrovert",7,"No","No",5,"Neat","Messy",2,"Dog",4)
    # profile4 = Profile("Jackie","Female","Male",65,list(range(67,80)),5,42,list(range(18,30)),"Muslim",5,"Republican",5,"Introvert","Introvert",5,"No","No",5,"Neat","Neat",5,"Cat",5)

    # profileList = [profile1,profile2,profile3,profile4]

    newopposite = profile0.find_opposite(profileList)
    newhated = profile0.find_hated(profileList)
    newfriend = profile0.find_friend_zone(profileList)

    return render_template("results.html",
                           answers=(userValues, newopposite, newhated,
                                    newfriend))
Пример #34
0
    def get(self):
        Guser = users.get_current_user()
        if Guser:
            vstrSendFunding = self.request.get('vstrSendFunding')
            vstrCampaignID = self.request.get('vstrCampaignID')

            findRequest = Campaigns.query(
                Campaigns.strCampaignID == vstrCampaignID)
            thisCampaignList = findRequest.fetch()

            self.response.write("Send fund running...")

            if len(thisCampaignList) > 0:
                thisCampaign = thisCampaignList[0]
            else:
                thisCampaign = Campaigns()

            findRequest = Profile.query(
                Profile.strReference == Guser.user_id())
            thisProfileList = findRequest.fetch()

            if len(thisProfileList) > 0:
                thisProfile = thisProfileList[0]
            else:
                thisProfile = Profile()

            if thisProfile.strWallet > int(vstrSendFunding):
                thisProfile.strWallet = thisProfile.strWallet - int(
                    vstrSendFunding)
                thisProfile.strTotalFundsSent = thisProfile.strTotalFundsSent + int(
                    vstrSendFunding)
                thisProfile.put()
                thisCampaign.AddToReceivedFunds(strinput=vstrSendFunding)
                thisCampaign.put()

                try:
                    findRequest = Profile.query(
                        Profile.strReference == thisCampaign.strReference)
                    thisReceiveProfileList = findRequest.fetch()

                    if len(thisReceiveProfileList) > 0:
                        thisReceiveProfile = thisReceiveProfileList[0]
                    else:
                        thisReceiveProfile = Profile()

                    thisReceiveProfile.strTotalFundsReceived = thisReceiveProfile.strTotalFundsReceived + int(
                        vstrSendFunding)
                    thisReceiveProfile.put()

                    self.response.write("Succesfully Funded Campaign")
                except:
                    self.response.write("Error Funding Project")
            else:
                self.response.write(
                    "Error Funding Campaign Insufficient Funds")