
暂无个人介绍
在不同的端口上运行microservice-2。使用Python标准或第三方库将请求从microservice-1发送到microservice-2,然后将请求发送到microservice-1。 下面是使用Python3标准库的例子:
m1.py:
from flask import Flask, jsonify
import urllib
import json
app = Flask(name)
@app.route('/reverse_random/string:string', methods=['GET'])
def reverse(string):
content = urllib.request.urlopen('http://127.0.0.1:5001').read().decode('utf-8')
print('response from m2: ', content)
string = string[::-1]
return jsonify({'message': string, 'random' :
json.loads(content)['message']})
if name == 'main':
app.run(debug = True)
m2.py:
import random
from flask import Flask, jsonify
app = Flask(name)
@app.route('/', methods=['GET'])
def myRandom():
r1 = random.uniform(0, 10)
return jsonify({'message': r1 })
if name == 'main':
app.run(debug=True, port=5001) # running m2 on a different port than default 5000
运行m1: python3 m1.py
在新的位置运行m2: python3 m2
发送请求m1: curl http://127.0.1:50 000/reverse_random/vivek
结果: { "message": "keviv",
"random": 4.138115905045612 }
观察m1和m2的日志,确保调用了m2。
使用pd.concat来将它们分组通过添加相同标签,if-else是区分是否有多个列的必要条件,如果没有if-else语句,sum(axis=1)会抛出错误: new_df=pd.concat([df[col].sum(axis=1).rename(col) if len(df[col].shape)==2 else df[col] for col in df.columns.unique()],axis=1) print(new_df)
在你的代码中,计算z的时候除了0,试试下面的:
plt3d = plt.figure().gca(projection='3d')
xx, zz = np.meshgrid(range(10), range(10))
yy = 2
plt3d.plot_surface(xx, yy, zz)
plt.show()
希望有帮助
def login():
official = {'dan': ['snow', 1],
'bob': ['golf', 2],
'bill': ['dogs', 3]
}
username=input("Enter your user name: ")
if username in official:
print("You are user number: ",official[username][1])
attempts=0
while attempts<3:
password=input("Enter your password: ")
if password == official[username][0]:
print("Log in successfull")
print("Hello",username)
login()
else:
print("Incorrect password")
attempts+=1
print("Attempts left: ",3-attempts)
if attempts==3:
print("Too many attempts!")
login()
print("Unknown User")
login()
先查看支持下载的版本:
pip install forexconnect==0
然后,安装相应版本:
pip install forexconnect==versionnumber
使用正则表达式
import re
result=[]
maze1 =['','* * ',' G','D',' ***']
for counter, value in enumerate(maze1):
m=re.search('([a-zA-Z]+)',value)
if m :
result.append((counter, m.start()))
这是Reader的代码: class Reader(object):
def __init__(self, stream):
if isinstance(stream, str):
self.name = "<unicode string>"
self.check_printable(stream)
self.buffer = stream+'\0'
elif isinstance(stream, bytes):
self.name = "<byte string>"
self.raw_buffer = stream
self.determine_encoding()
else:
self.stream = stream
self.name = getattr(stream, 'name', "<file>")
self.eof = False
self.raw_buffer = None
self.determine_encoding()
函数本身会检验数据类型然后做不同的处理。
尝试创建一个最小的示例,您会发现它是valoare = input()。 看起来像是你不小心从extrema =复制粘贴过来的?它对于一般的值是不需要的。如果需要,可以使用valoare = None,或者完全省略它。
偏函数(在函数编程和数学上下文中)就是所说的:没有为所有可能的参数定义函数。在编程环境中,我们通常将“未定义”解释为几种情况之一,包括未定义的行为、异常或不终止。 局部函数的一个例子是整数除法,如果除数为0,则不定义该除法(在Haskell中,它将抛出一个错误)。在上面的代码片段中,new_function是偏函数。该代码在Python中只会导致一个错误,但是如果它按照您的预期工作,那么它将是一个total(而不是partial)函数。 您很可能认为这是一个部分应用的函数。
你可以使用np.lexsort():
import numpy as np
a = np.asarray([[9, 2, 3],
[4, 5, 6],
[7, 0, 5],
[7, 1, 6]])
a[np.lexsort((-a[:, 1], a[:, 0]))]lexsort
def execute():
return """
this is imam
this akarsh
this is abhi
"""
一个方法是使用DataFrame.merge:
df1 = df[0].merge(df[1], on=['Cat1','Cat2'], suffixes=('_0','_1'))
print (df1)
Cat1 Cat2 Cat3_0 Prc_0 Cat3_1 Prc_1
0 11 0 5 100 5 90
1 55 1 8 100 5 95
print (df1.filter(like='Prc').sum())
Prc_0 200
Prc_1 185
dtype: int64
另一种方法是:
s1 = df[0].set_index(['Cat1','Cat2'])['Prc']
s2 = df[1].set_index(['Cat1','Cat2'])['Prc']
print (s1[s1.index.isin(s2.index)].sum())
200
print (s2[s2.index.isin(s1.index)].sum())
185
您可以存储对列表本身的引用,并对其调用clear(),而不是存储列表的名称。
Result1={"d11":"1","d12":"2"}
Result2 =["l11","l22"]
def length(name):
print(str(name) + " having length is : "+ str(len(name)))
def GlobalClear():
overallList = [Result1, Result2]
for key in overallList:
key.clear()
print("Prev Length")
length(Result1)
length(Result2)
GlobalClear()
print("Final Length")
length(Result1)
length(Result2)
在使用.title()方法之前,需要将22(在dict中是一个int类型)转换成一个字符串。
person={'fname':'harry','lname':'max','age':22,'city':'ktm'}
for value in person.values():
print(str(value).title(), end=" ")
使用: df = pd.DataFrame(np.array(L).reshape(-1, 5)).rename(columns = lambda x: f'Heading {x + 1}')
print (df)
Heading 1 Heading 2 Heading 3
0 a1 b1 c1
1 a2 b2 c2
2 a3 b3 c3
对新的列名和聚合函数使用GroupBy.agg和元组:
df = (op1.groupby(['subject_id','date'])['val'] .agg([('val_max', 'max'),('val_min', 'min')]) .reset_index())
print (df)
subject_id date val_max val_min
0 1 1/1/2017 11 5
1 1 1/2/2017 10 5
2 1 1/3/2017 16 11
3 2 1/4/2017 26 21
4 2 1/5/2017 8 5
在pandas 0.25+可以使用named aggregation:
df = (op1.groupby(['subject_id','date']) .agg(val_min=pd.NamedAgg(column='val', aggfunc='min'), val_max=pd.NamedAgg(column='val', aggfunc='max')) .reset_index())
遍历元素并继续添加到另一个列表中,除非您找到一个元素“-”并且其旁边的索引也为“-”。
l = ['5', '-', '8', '2', '-', '3', '-', '-', '1', '-', '2']
final = []
for i in range(len(l)-1): # Iterate to the last second element
... if l[i] == '-' and l[i]==l[i+1]:
... continue
... final.append(l[i])
... final
['5', '-', '8', '2', '-', '3', '-', '1', '-']
尝试将axis参数设置为none(默认为0)
np.concatenate((a, b), axis=None)
declare -a pids
launch_first_program &
pids+=($!)
launch_second_program &
pids+=($!)
wait "${pids[@]}"
continue_with_our_day
使用后台启动进程后&,变量$!将包含子代的PID。我们可以将其收集到一个数组变量中,然后使用wait阻塞来完成所有列出的过程。
cat command.list | xargs -L 1 python3 my_script.py 这将-L 1一次向脚本传递一行()。