Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I want to copy one file to another. From the accepted answer of this thread, I have done:
def fcopy(src):
dst = os.path.splitext(src)[0] + "a.pot"
try:
shutil.copy(src, dst)
except:
print("Error in copying " + src)
sys.exit(0)
and using it as:
print(atoms)
for q in range(0, len(atoms), 2):
print(type(atoms[q]))
print(atoms[q], fcopy(atoms[q]))
This is quite a few check down inside the code, but I expect that does not matter as long as it finds atoms[q]. But the result I am getting is:
['Mn1.pot', 'Mn2.pot'] <= result of print(atoms)
<class 'str'> <= result of type(atoms)
Mn1.pot None <= result of print(atoms,fcopy(atoms)).
['Mn3.pot', 'Mn4.pot']
<class 'str'>
Mn3.pot None
['Mn5.pot', 'Mn6.pot']
<class 'str'>
Mn5.pot None
['Mn7.pot', 'Mn8.pot']
<class 'str'>
Mn7.pot None
Where I was expecting the print(atoms[q], fcopy(atoms[q])) to give me Mn1.pot Mn1a.pot
I am still a beginner in python, so it will be great if someone can show me what's going wrong here.
You are not getting an error -- if you did you would see the Error in copying message printed.
The part you need to know is that every Python function returns a value. If you do not tell Python what value to return, Python returns None.
So if you want the destination file to be returned to the caller, you have to do it yourself:
def fcopy(src):
dst = os.path.splitext(src)[0] + "a.pot"
try:
shutil.copy(src, dst)
return dst # this line should be added
except:
print("Error in copying " + src)
sys.exit(0)
Related
I know there are some answers on website on this issue, but trust me none of them are helping. Some have not working code claiming to be working.
I keep getting this error at runtime, NZEC, maybe because of spaces and all or type of input it takes but I have tried everything. Please help me, it been 5 hrs + already on this problem. I am sharing my basic code, please visit the problem if necessary and suggest me something.
import sys
def isprime(n):
if n==1:
return False
if n==2:
return True
l=n//2
for i in range(2,l+1):
if(n%i==0):
return False
return True
t=int(input())
if t<=10:
for q in range(t):
m=int(input("Lower Number"))
n=int(input("Higher number"))
if (m>=1 and m<=1000000000 and n>m and n<=1000000000 and n-m<=100000):
for i in range(m,n+1):
if isprime(i):
print(i)
else:
quit()
I went and checked submitted answer on codechef, and they were accepting answers which don't even give correct output on my local machine. I don't understand this submission thing, help is much appreciated.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I am trying to create a proxy checker in python3 and everything is working fine until than i didn't introduce multi-threading in it to make it fast now it is giving me error and i am not able to understand why it is so
import requests
import threading
#DECLARING ALL VARIABLES
proxy_api="https://api.proxyscrape.com/?request=getproxies&proxytype=http&timeout=50&country=all&ssl=all&anonymity=all"
raw_proxy = []
live_proxy = []
#Declaring ALL COUNTERS
proxy_Counter = 0
def main():
pass
def fetch_proxy():
global raw_proxy
res = requests.get(proxy_api)
raw_proxy = res.text.splitlines()
print(len(raw_proxy))
return raw_proxy
def check_proxy():
global raw_proxy
global live_proxy
global proxy_Counter
while proxy_Counter < len(raw_proxy):
try:
proxyDict = {
"https" : "https://"+raw_proxy[proxy_Counter],
"http" : "http://"+raw_proxy[proxy_Counter],
}
res = requests.get("http://httpbin.org/ip",proxies=proxyDict,timeout=3)
print(f"Proxy Live {raw_proxy[proxy_Counter]}")
live_proxy.append(raw_proxy[proxy_Counter])
proxy_Counter+=1
except Exception as e:
print(f"Dead Proxy {raw_proxy[proxy_Counter]}")
proxy_Counter+=1
print(len(live_proxy))
return live_proxy
fetch_proxy()
threads = []
for _ in range(10):
t = threading.Thread(target=check_proxy)
t.start()
threads.append(t)
for t in threads:
t.join()
You didn't provide any error or stacktrace but it looks like you're getting an IndexError, this is because your loop is incorrect. Imagine you got back 100 proxies, your current loop will go from 0 to 100, however, that is 101 entries and not 100; because 0 is the first index. A quick solution is to change this line so that it is one less (0-99 = 100 iterations):
while proxy_Counter < len(raw_proxy) - 1:
However, if your aim is to speed up the process of checking the proxies, your code will have the opposite effect because for each thread you create, you're checking each proxy again so now you have x10 the redundancy. It would be better to use a ThreadPoolExecutor and evenly distribute the proxies to your threads and set a maximum amount of threads so that you're not overloading the server.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
Having used pandas for a long time, this is the first time I got an error as shown in the title of this question and I'm stuck because I don't see any reason why the DataFrame would not have the groupby function "available." Already reinstalled pandas, even looked in the code that is being used (groupby is defined in the core modules).
This is what I'm doing, the error is shown below:
def _bin_by_answer(row):
collocated_answer = row['colname']
if collocated_answer <= -1:
return -1
elif collocated_answer >= 1:
return 1
else:
return 0
df = pd.read_pickle(somepath)
df['binned'] = df.apply(func=lambda row: _bin_by_answer(row), axis=1)
df_sampled = df.groupyby(by='binned', group_keys=False).apply(lambda grp: grp.sample(n=50))
Here is the error:
Traceback (most recent call last):
File "/Users/felix/IdeaProjects/cope/ann4class/exportfromaestoretomturk.py", line 858, in <module>
process_and_export_ps2_inductive()
File "/Users/felix/IdeaProjects/cope/ann4class/exportfromaestoretomturk.py", line 786, in process_and_export_ps2_inductive
df_sampled = df_results.groupyby(by=COL_ANSWER1_COLLOCATED_MAJORITY, group_keys=False).apply(
File "/Users/felix/anaconda3/envs/cope/lib/python3.7/site-packages/pandas/core/generic.py", line 5179, in __getattr__
return object.__getattribute__(self, name)
AttributeError: 'DataFrame' object has no attribute 'groupyby'
As suggested by ddoGas, the cause of this error was a typo. So, I guess the general answer would be: In case you're reading this question because you're running into a similar problem, double check that you wrote the function name correctly.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I'm unable to understand what triggers the below Error.
This is the error:
Exception in Tkinter callback
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/tkinter/__init__.py", line 1705, in __call__
return self.func(*args)
File line 26, in print_sel
dob.index(INSERT, cal.selection_get())
TypeError: index() takes 2 positional arguments but 3 were given
This is my code:
def calendar():
def print_sel():
dob.index(INSERT, cal.selection_get())
top = Toplevel(root)
top.title("Select Registration Date")
cal = Calendar(top, font="Arial 14", selectmode='day', locale='en_US',
cursor="hand1", year=2019, month=4, day=4)
cal.pack(fill="both", expand=True)
Button(top, text="ok", command=print_sel).pack()
dob=Entry(Registration_Frame,style='TEntry')
dob.grid(row=3,column=1,columnspan=2,sticky=NSEW)
Button(Registration_Frame, text='Select',command=calendar,width=5,style='TButton').grid(row=3,column=3)
You confused the .insert() method with index(); the latter only takes a single argument, and would move longer text within the entry box to show the character at the given index to be the left-most visible character.
Just replace .index() with .insert():
dob.insert(INSERT, cal.selection_get())
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
>>> compile("""
def some_function(x):
return x+2
some_function""",'compiled function','single')
Traceback (most recent call last):
File "<pyshell#3>", line 4, in <module>
some_function""",'compiled function','single')
File "compiled function", line 4
some_function
^
SyntaxError: unexpected EOF while parsing
If you want to compile a multi-statement string with compile, single should be exec. Also, after you compile the code, you have to execute it and capture the globals in order to access the created function:
def anonymous(code):
# To fix the indentation
fixed_code = '\n'.join(line[4:] for line in code.splitlines())
_globals = {}
exec(compile(fixed_code, '<string>', 'exec'), _globals)
if 'f' not in _globals:
raise ValueError('You must name your function "f"')
return _globals['f']
anonymous('''
def f(x):
return x + 2
''')(12)
Question is not very clear, but is this the example you want?
>>> c=compile('''\
... def some_function(x):
... return x+2
... print(some_function(5))
... ''','<string>','exec')
>>> exec(c)
7
>>> c=compile('7+2','<string>','eval')
>>> eval(c)
9