Пример #1
0
def extractor_save(base_path, folder, outputs):
    nb_written = 0
    name_to_path = {}
    wrote_endpoints = False

    for name, contents in outputs:
        if '.proto' in name:
            if folder:
                path = base_path / 'protos' / folder / name
            else:
                path = base_path / name

            makedirs(path.parent, exist_ok=True)
            with open(path, 'w') as fd:
                fd.write(contents)

            if name not in name_to_path:
                nb_written += 1
            name_to_path[name] = str(path)

        elif name.endswith('.sample'):
            endpoint = contents

            name = name.replace('.sample', '.proto')
            endpoint['proto_path'] = name_to_path[name]
            endpoint['proto_msg'] = name.replace('.proto', '')

            wrote_endpoints = True
            if folder:
                insert_endpoint(base_path / 'endpoints', {'request': endpoint})
            else:
                insert_endpoint(base_path, {'request': endpoint})

    return nb_written, wrote_endpoints
Пример #2
0
def findRestaurantsByName(restaurants, name):
    tempRestaurants = list()
    name = name.replace(' ', '').lower()
    for restaurant in restaurants:
        if(editDistance(restaurant['name'].replace(' ', '').lower(), name) < 4):
            tempRestaurants.append(restaurant)
    return tempRestaurants
Пример #3
0
def pay_url(payment, name, out_order_id, total_price):
    name = name.replace('=', '_')  #防止k,v冲突
    try:
        if payment == '支付宝当面付':
            # return jsonify({'qr_code':'455555555454deffffffff'})
            r = AlipayF2F().create_order(name, out_order_id, total_price)
        elif payment == '虎皮椒微信':
            r = Hupi().Pay(trade_order_id=out_order_id,
                           total_fee=total_price,
                           title=name)
        elif payment == '虎皮椒支付宝':
            r = Hupi(payment='alipay').Pay(trade_order_id=out_order_id,
                                           total_fee=total_price,
                                           title=name)
        elif payment in ['码支付微信', '码支付支付宝', '码支付QQ']:
            if payment == '码支付微信':
                payname = 'wechat'
            elif payment == '码支付支付宝':
                payname = 'alipay'
            else:
                payname = 'qqpay'
            r = CodePay(payment=payname).create_order(payment, out_order_id,
                                                      total_price)
        elif payment in ['PAYJS支付宝', 'PAYJS微信']:
            r = Payjs().create_order(name, out_order_id, total_price)
        elif payment in ['V免签支付宝', 'V免签微信']:
            # 参数错误情况下,会失效
            if payment == 'V免签微信':
                r = VMQ().create_order(name, out_order_id, total_price)
            else:
                r = VMQ(payment='alipay').create_order(name, out_order_id,
                                                       total_price)
        elif payment in ['微信官方接口']:
            r = Wechat().create_order(name, out_order_id, total_price)
        elif payment in ['QQ钱包']:
            r = QQpay().create_order(name, out_order_id, total_price)
        elif payment in ['易支付']:
            r = Epay().create_order(name, out_order_id, total_price)
        elif payment in ['Mugglepay']:
            r = Mugglepay().create_order(name, out_order_id, total_price)
        elif payment in ['YunGouOS']:  # 统一接口
            r = YunGou(payment='unity').create_order(name, out_order_id,
                                                     total_price)
        elif payment in ['YunGouOS_WXPAY']:  # 微信接口
            r = YunGou().create_order_wxpay(name, out_order_id, total_price)
        else:
            return None
        return r
    except Exception as e:
        log(e)
        return False
Пример #4
0
def pay_url(payment, name, out_order_id, total_price):
    name = name.replace('=', '_')  # 防止k,v冲突
    try:
        if payment == '支付宝当面付':
            # return jsonify({'qr_code':'455555555454deffffffff'})
            r = AlipayF2F().create_order(name, out_order_id, total_price)
        elif payment == '虎皮椒微信':
            r = Hupi().Pay(trade_order_id=out_order_id,
                           total_fee=total_price,
                           title=name)
        elif payment == '虎皮椒支付宝':
            r = Hupi(payment='alipay').Pay(trade_order_id=out_order_id,
                                           total_fee=total_price,
                                           title=name)
        elif payment == '迅虎微信':
            r = Xunhu(payment='wechat').Pay(trade_order_id=out_order_id,
                                            total_fee=total_price,
                                            title=name)
        elif payment in ['码支付微信', '码支付支付宝', '码支付QQ']:
            if payment == '码支付微信':
                payname = 'wechat'
            elif payment == '码支付支付宝':
                payname = 'alipay'
            else:
                payname = 'qqpay'
            r = CodePay(payment=payname).create_order(payment, out_order_id,
                                                      total_price)
        elif payment in ['PAYJS支付宝', 'PAYJS微信']:
            if payment == 'PAYJS支付':
                payname = 'alipay'
            else:
                payname = 'wechat'
            r = Payjs(payment=payname).create_order(name, out_order_id,
                                                    total_price)
        elif payment in ['V免签支付宝', 'V免签微信']:
            # 参数错误情况下,会失效
            if payment == 'V免签微信':
                r = VMQ().create_order(name, out_order_id, total_price)
            else:
                r = VMQ(payment='alipay').create_order(name, out_order_id,
                                                       total_price)
        elif payment in ['微信官方接口']:
            r = Wechat().create_order(name, out_order_id, total_price)
        elif payment in ['QQ钱包']:
            r = QQpay().create_order(name, out_order_id, total_price)
        elif payment in ['易支付支付宝', '易支付QQ', '易支付微信']:
            if payment == '易支付支付宝':
                payname = 'alipay'
            elif payment == '易支付微信':
                payname = 'wechat'
            else:
                payname = 'qqpay'
            r = Epay(payment=payname).create_order(name, out_order_id,
                                                   total_price)
        elif payment in ['Mugglepay']:
            r = Mugglepay().create_order(name, out_order_id, total_price)
        elif payment in ['YunGouOS']:  # 统一接口
            r = YunGou(payment='unity').create_order(name, out_order_id,
                                                     total_price)
        elif payment in ['YunGouOS_WXPAY']:  # 微信接口
            r = YunGou().create_order_wxpay(name, out_order_id, total_price)
        elif payment in ['Stripe支付宝', 'Stripe微信']:  # 微信接口
            if payment == 'Stripe微信':
                r = Stripe(payment='wechat').create_order(
                    name, out_order_id, total_price)
            else:
                r = Stripe(payment='alipay').create_order(
                    name, out_order_id,
                    total_price)  # 导入cource_id和clinent_key[]合并
            if r:
                with db.auto_commit_db():
                    TempOrder.query.filter_by(
                        out_order_id=out_order_id).update(
                            {'contact_txt': r['signs']})
                r.pop('signs')
        elif payment in ['云免签微信', '云免签支付宝']:
            if payment == '云免签微信':
                r = Ymq(payment='wechat').create_order(name, out_order_id,
                                                       total_price)
            else:
                r = Ymq(payment='alipay').create_order(name, out_order_id,
                                                       total_price)
        else:
            return None
        return r
    except Exception as e:
        log(e)
        return False
Пример #5
0
 def get_package_directories(self):
     from os.path import sep
     name = self.get_project_name()
     return [item.replace('.', sep) for item in get_package_namespace(name)] + [name.replace('.', sep)]
Пример #6
0
 def get_package_directories(self):
     from os.path import sep
     name = self.get_project_name()
     return [
         item.replace('.', sep) for item in get_package_namespace(name)
     ] + [name.replace('.', sep)]
Пример #7
0
path = "data2.xlsx"

# workbook object is created
wb_obj = openpyxl.load_workbook(path)

sheet_obj = wb_obj.active

max_col = sheet_obj.max_column
max_row = sheet_obj.max_row

# Will print a particular row value
for i in range(2, max_row + 1):
    print("-----------------------")
    cell_obj = sheet_obj.cell(row=i, column=2)
    name = cell_obj.value
    name.replace("\'", "\\'")
    print("Name = {name}".format(name=name))
    cell_obj = sheet_obj.cell(row=i, column=3)
    print("Image = {name}".format(name=cell_obj.value))
    img = cell_obj.value
    cell_obj = sheet_obj.cell(row=i, column=4)
    res = str(cell_obj.value)
    if '-' in res:
        res = removecharater(res)
    if res[0] == '$':
        res = res[1:len(res)]
    print("Price = {name}".format(name=res))
    price = res
    cell_obj = sheet_obj.cell(row=i, column=5)
    print("Rating = {name}".format(name=cell_obj.value))
    rating = cell_obj.value
Пример #8
0
# Create a list of the number of times a muscle group was targetted
muscle_group_count = [
    muscle_group.count(muscle) for muscle in unique_muscle_group
]

# Create a list of the number of times an exercise was performed
exercise_name_count = [
    exercise_name.count(exercise) for exercise in unique_exercise_name
]

# Remove the year from dates in unique_dates list
unique_dates = [date.lstrip('2020-') for date in unique_dates]

# Remove extraneous notation from exercise names
unique_exercise_name = [
    name.replace('(Pulley)', '') for name in unique_exercise_name
]

# Create a list of lists containing the volumes lifted on dates
volumes_for_workout = []
volumes_for_workout.append(volumes[0:18])  # 18
volumes_for_workout.append(volumes[18:45])  # 27
volumes_for_workout.append(volumes[45:65])  # 20
volumes_for_workout.append(volumes[65:92])  # 27
volumes_for_workout.append(volumes[92:120])  # 28
volumes_for_workout.append(volumes[120:140])  # 20
volumes_for_workout.append(volumes[140:166])  # 26
volumes_for_workout.append(volumes[166:193])  # 27
volumes_for_workout.append(volumes[193:212])  # 19
volumes_for_workout.append(volumes[212:239])  # 27
volumes_for_workout.append(volumes[239:267])  # 28
Пример #9
0
    def Run(self):
        import json

        reqs = Requests()
        reqs.GetToken()

        error = False
        addedItems = 0
        replacedItems = 0
        isReplaced = False

        try:
            import requests, datetime
            print(" \033[32mStarting\033[0m spells parser")
            print("--------------------------")

            self.lastItemID = self.rangeStart

            params = dict(namespace="static-eu", access_token=reqs.token)

            self.processStarted = True
            while self.lastItemID < self.rangeEnd - 1 and not error:
                try:
                    #REQUEST AND PARSE ITEMS
                    for itemID in range(self.lastItemID, self.rangeEnd):

                        self.lastItemID = itemID
                        url = self.baseUrl % (itemID)

                        reqs.MakeRequest(url, params)
                        req_status_code = reqs.GetRequestStatusCode()

                        data = reqs.GetData()

                        if data != "Downstream Error":
                            data = json.loads(data)

                            if req_status_code == 200:
                                if 'name' not in data:
                                    print(data)
                                    self.PrintError("E",
                                                    "No 'name' field in data")
                                    print("--------------------------")
                                    error = True
                                    break

                                for localeIndex in range(len(
                                        self.localesList)):
                                    locale = self.localesList[localeIndex]
                                    nameDict = data["name"]

                                    if locale not in nameDict:
                                        self.eachLangcheck[
                                            localeIndex] = self.NOT_FOUND
                                    else:
                                        name = nameDict[locale]
                                        name = name.replace('"', '\\"')
                                        name = name.replace('\r\n', '')
                                        name = name.replace('\n', '')

                                        luaString = '  {%i,"%s"},\n' % (itemID,
                                                                        name)

                                        result = self.FindInFile(
                                            localeIndex, itemID)
                                        exists = result[1]

                                        if not exists:
                                            self.files[
                                                localeIndex].InsertInLine(
                                                    result[0] + 1, luaString)
                                            self.files[localeIndex].lines += 1
                                            addedItems += 1
                                            self.eachLangcheck[
                                                localeIndex] = self.ADDED
                                        else:
                                            current_name = self.GetNameFromLine(
                                                localeIndex, result[0])
                                            new_name = '"%s"' % (name)
                                            if current_name != new_name:
                                                isReplaced = True
                                                self.ReplaceNameFromLine(
                                                    localeIndex, result[0],
                                                    luaString)
                                                replacedItems += 1
                                                self.eachLangcheck[
                                                    localeIndex] = self.REPLACED
                                            else:
                                                isReplaced = False
                                                self.eachLangcheck[
                                                    localeIndex] = self.UNTOUCHED

                                self.PrintItem(itemID)
                            else:
                                if req_status_code == 404:
                                    if 'detail' not in data:
                                        self.PrintError(
                                            "E", "404 Error: No reason found")
                                        error = True
                                        break
                                    else:
                                        for localeIndex in range(
                                                len(self.localesList)):
                                            result = self.FindInFile(
                                                localeIndex, itemID)
                                            exists = result[1]
                                            if exists:
                                                self.files[
                                                    localeIndex].DeleteLine(
                                                        result[0] + 1)
                                                self.eachLangcheck[
                                                    localeIndex] = self.REMOVED
                                            else:
                                                self.eachLangcheck[
                                                    localeIndex] = self.NOT_FOUND
                                        self.PrintItem(itemID)

                                elif req_status_code == 504:
                                    self.PrintError(
                                        "E", "504 Error: Gateway timeout")
                                    error = True
                                    break
                                else:
                                    self.PrintError(
                                        "E", "%i Error: Unknown error code" %
                                        (req_status_code))  #504
                                    error = True
                                    break
                        else:
                            print(" %s - \033[33m#%i\033[0m - %s" %
                                  (time, itemID, "Downstream Error"))

                        if itemID % 50 == 0:
                            print(" New indexes saved:")
                            self.SaveIndexes()
                            self.lastSavedID = itemID
                except KeyboardInterrupt:
                    error = True
                    raise
                except requests.exceptions.ConnectionError:
                    error = True
                    raise
                except IOError:
                    error = True
                    raise
                except ValueError:
                    error = True
                    raise
                except:
                    print("--------------------------")
                    self.PrintError("E", "Unknown Error")
                    error = True
                    raise

            if not error:
                self.lastItemID += 1

            if self.lastItemID >= self.rangeEnd - 1:
                self.Continue = False
                print("--------------------------")

        except KeyboardInterrupt:
            print("--------------------------")
            if self.processStarted:
                self.PrintError("W", "Process interrupted by the user")
            else:
                self.PrintError(
                    "W", "Process interrupted by the user before starting")
            self.Continue = False
        except requests.exceptions.ConnectionError:
            print("--------------------------")
            self.PrintError(
                "E", "There was a problem with the Internet connection.")
        except IOError:
            print("--------------------------")
            self.PrintError("E", "There was a problem with the file access.")
        except ValueError:
            print("--------------------------")
            self.PrintError("E",
                            "No JSON object could be decoded // ValueError")
        except:
            print("--------------------------")
            self.PrintError("E", "Unknown Error")
            raise
        finally:
            print(" New indexes saved:")
            self.SaveIndexes()
            print("--------------------------")
            print(" Stats:")
            print("\tSpells parsed: \033[36m%i\033[0m" %
                  (self.lastItemID - self.rangeStart))
            print("\tNew spells added: \033[36m%i\033[0m" % (addedItems))
            print("\tReplaced spells: \033[36m%i\033[0m" % (replacedItems))
            print("--------------------------")
            print(" \033[32mProcess Finished\033[0m")
            print("--------------------------")
            self.utils.PlaySound(2000, 250, 1)
Пример #10
0
	def Run(self):
		import requests, json, datetime
		
		self.error = False
		
		try:
			print " \033[32mStarting\033[0m item parser"
			print "--------------------------"

			self.lastItemID = self.rangeStart
			
			params = dict(
				locale=self.currLocale,
				apikey=self.apiKey
			)
			
			self.file.GetNumberOfLines()

			self.RemoveExtraLua()
			self.file.GetNumberOfLines()
			
			self.processStarted = True
			while self.lastItemID < self.rangeEnd-1 and not self.error:
				try:
					#REQUEST AND PARSE ITEMS
					for itemID in xrange(self.lastItemID, self.rangeEnd):
					
						self.lastItemID = itemID
						url = self.baseUrl % (itemID)
						
						resp = requests.get(url=url, params=params)
						data = json.loads(resp.text)
						
						now = datetime.datetime.now()
						time = now.strftime('%H:%M:%S')
						
						if resp.status_code == 200:
							if 'name' not in data:
								print data
								self.PrintError("E", "No 'name' field in data")
								print "--------------------------"
								self.error = True
								break
							
							name = data["name"]
							name = name.replace('"', '\\"')
							
							luaString = '  {%i,"%s"},\n' % (itemID, name)
							luaString = luaString.encode('utf-8')
							
							exists = False
							result = self.FindInFile(itemID, 1, self.file.lines)
							if not result[1]:
								self.file.InsertInLine(result[0], luaString)
								self.file.lines += 1
								exists = True
							
							if len(name) > self.strLen+3:
								name = name[:self.strLen] + "..."
							
							if exists:
								print (" %s - \033[31m#%i\033[0m - [%s]" % (time, itemID, name)).encode('utf-8')
							else:
								print (" %s - \033[32m#%i\033[0m - [%s]" % (time, itemID, name)).encode('utf-8')
						else:
							if resp.status_code == 404:
								if 'reason' not in data:
									self.PrintError("E", "404 Error: No reason found")
									self.error = True
									break
								else:
									print " %s - \033[33m#%i\033[0m - /!\ %s" % (time, itemID, data["reason"].encode('utf-8'))
							else:
								self.PrintError("E", "%i Error: Unknown error code" % (resp.status_code))
								self.error = True
								break
				except KeyboardInterrupt:
					self.error = True
					raise
				except:
					self.PrintError("E", "Unknown Error")
					self.error = True
					raise
			
			if not self.error:
				self.lastItemID += 1
			
			print " \033[32mFinished\033[0m parsing \033[36m%s\033[0m" % (self.currLocale)
			print "--------------------------"
			self.utils.PlaySound(2000, 250, 1)
		except KeyboardInterrupt:
			print "--------------------------"
			if self.processStarted:
				self.PrintError("W", "Process interrupted by the user")
			else:
				self.PrintError("W", "Process interrupted by the user before starting")
		except:
			self.PrintError("E", "Unknown Error")
			raise
		finally:
			self.RestoreExtraLua()
			print " New indexes saved:"
			self.SaveIndexes()
			print "--------------------------"
			self.rangeStart = self.lastItemID