Running the code below
import threading
import io
import Client
Proxies = None
Users = None
with open("proxies.txt") as x:
Proxies = x.readlines()
with open("ids.txt") as f:
Users = f.readlines()
c = 0
for udata in Users:
uid = udata.split(':')[0]
ok = udata.split(':')[1]
while True:
proxy = Proxies[c].strip('\n')
proxySplit = proxy.split(':')
c = Client.Client(proxySplit[0], proxySplit[1], uid, ok, 171147281)
if(c):
c += 1
break
I've got this exception:
Traceback (most recent call last):
File "Run.py", line 20, in <module>
proxy = str(Proxies[c]).strip('\n')
TypeError: object cannot be interpreted as an index
I can not found what's wrong with my code. Any help will be appreciated.
It seems that in line 22 c = Client.Client(proxySplit[0], proxySplit[1], uid, ok, 171147281) you make c an object, not an int anymore. And when it goes to line 20 again, c is used as an index, which is not allowed.
Related
Code:
import socket
import struct
from datetime import datetime
s = socket.socket(socket.PF_PACKET, socket.SOCK_RAW, 8)
dict = {}
file_txt = open("dos.txt", 'a')
file_txt.writelines("**********")
t1 = str(datetime.now())
file_txt.writelines(t1)
file_txt.writelines("**********")
file_txt.writelines("n")
print
"Detection Start ......."
D_val = 10
D_val1 = D_val + 10
while True:
pkt = s.recvfrom(2048)
ipheader = pkt[0][14:34]
ip_hdr = struct.unpack("!8sB3s4s4s", ipheader)
IP = socket.inet_ntoa(ip_hdr[3])
print
"Source IP", IP
if dict_has.key(IP):
dict[IP] = dict[IP] + 1
print
dict[IP]
if (dict[IP] > D_val) and (dict[IP] < D_val1):
line = "DDOS Detected "
file_txt.writelines(line)
file_txt.writelines(IP)
file_txt.writelines("n")
else:
dict[IP] = 1
When compiling i have facing a error
Error:
raceback (most recent call last):
File "/root/Desktop/Detect/./Detectddos.py", line 24, in
if dict_has.key(IP):
NameError: name 'dict_has' is not defined
it seems you have made a spelling mistake in the if statement
if dict_has.key(IP):
should be
if dict.has_key(IP):
refer https://www.geeksforgeeks.org/python-dictionary-has_key/ for more.
dict.has_key() has removed from Python 3.x
instead use
if IP in dict:
This program is supposed to emit sound based on a CSV file.
There is a frequency range in the dataset of 37-32677. In the beginning I didn't add this in and got this same error message. I tried adding in this range and I am still getting the same error.
import winsound
import csv
winsound.Beep(261,100)
def preload(filename):
file = open(filename)
data = csv.reader(file)
return data
def getNote(sensorVal):
return int(sensorVal * 75)
def setup():
cleanedData = {}
notes = []
data = preload("data1.csv")
for row in data(range(36,32677)):
print(row)
if row[1] != "trial number":
sensorVal = float(row[4])
channel = int(row[7])
if channel not in cleanedData:
cleanedData[channel] = []
cleanedData[channel].append({"sensorVal":sensorVal})
notes.append(getNote(sensorVal))
return cleanedData,notes
def play(notes,time):
for note in notes:
winsound.Beep(note,time)
data, notes = setup()
play(notes, 200)
Error message:
Traceback (most recent call last):
File "C:/Users/clair/PycharmProjects/winSound/main.py", line 32, in <module>
data, notes = setup()
File "C:/Users/clair/PycharmProjects/winSound/main.py", line 16, in setup
for row in data(range(36,32677)):
TypeError: '_csv.reader' object is not callable
Process finished with exit code 1
i'm getting NameError: for the following code...
d = [('1','as'),('2','sd')]
for i in d:
RD = ReleaseDeal(int(i[0]))
print(RD)
def ReleaseDeal(a):
RD = '''<ReleaseDeal><DealReleaseReference>R'''+ no +'''</DealReleaseReference><Deal><DealTerms><CommercialModelType>AsPerContract</CommercialModelType>
<Usage><UseType UserDefinedValue="GoogleMusicBasic">UserDefined</UseType> <UseType UserDefinedValue="SscSnmLocker">UserDefined</UseType>
<UseType UserDefinedValue="GoogleMusicSubscription">UserDefined</UseType></Usage><TerritoryCode>Worldwide</TerritoryCode><PriceInformation>
<PriceType Namespace="DPID:"">13</PriceType></PriceInformation><ValidityPeriod><StartDate>2018-10-04</StartDate></ValidityPeriod>
</DealTerms></Deal></ReleaseDeal>'''
return RD
i'm getting following errors...
Traceback (most recent call last):
File "example.py", line 3, in <module>
RD = ReleaseDeal(int(i[0]))
NameError: name 'ReleaseDeal' is not defined
please help me on this , Thanks in advance..
You got several errors:
Define something before you reference to it
The parameter does not apply to the used one in ReleaseDeal
Concatenation of int to string fails.
def ReleaseDeal(no): # this was a, is has to be no and string
RD = '''<ReleaseDeal><DealReleaseReference>R'''+ no +'''</DealReleaseReference><Deal><DealTerms><CommercialModelType>AsPerContract</CommercialModelType>
<Usage><UseType UserDefinedValue="GoogleMusicBasic">UserDefined</UseType> <UseType UserDefinedValue="SscSnmLocker">UserDefined</UseType>
<UseType UserDefinedValue="GoogleMusicSubscription">UserDefined</UseType></Usage><TerritoryCode>Worldwide</TerritoryCode><PriceInformation>
<PriceType Namespace="DPID:"">13</PriceType></PriceInformation><ValidityPeriod><StartDate>2018-10-04</StartDate></ValidityPeriod>
</DealTerms></Deal></ReleaseDeal>'''
return RD
d = [('1','as'),('2','sd')]
for i in d:
RD = ReleaseDeal(i[0])
print(RD)
Maybe type hints are useful for you ;-) https://docs.python.org/3/library/typing.html#typing.ClassVar Then you can say something like
ReleaseDeal(no: str) -> str:
So you want to get no of type string and return string.
lambda from getattr getting called with "connection" as a keyword argument? Am I misusing the code or is there a bug?
Code and traceback: https://github.com/bigcommerce/bigcommerce-api-python/issues/32
#!/usr/bin/env python2
import bigcommerce
import bigcommerce.api
BIG_URL = 'store-45eg5.mybigcommerce.com'
BIG_USER = 'henry'
BIG_KEY = '10f0f4f371f7953c4d7d7809b62463281f15c829'
api = bigcommerce.api.BigcommerceApi(host=BIG_URL, basic_auth=(BIG_USER, BIG_KEY))
def get_category_id(name):
get_request = api.Categories.get(name)
try:
cat_list = api.Categories.all(name=name)
if cat_list:
return cat_list[0]['id']
else:
return None
except:
return None
def create_category(name):
rp = api.Categories.create(name)
if rp.status == 201:
return rp.json()['id']
else:
return get_category_id(name)
create_category('anothertestingcat')
Gives this traceback:
Traceback (most recent call last):
File "./bigcommerceimporter.py", line 50, in
create_category('anothertestingcat')
File "./bigcommerceimporter.py", line 44, in create_category
rp = api.Categories.create(name)
File "/home/henry/big_test_zone/local/lib/python2.7/site-packages/bigcommerce/api.py", line 57, in
return lambda args, *kwargs: (getattr(self.resource_class, item))(args, connection=self.connection, *kwargs)
TypeError: create() got multiple values for keyword argument 'connection'
Line in api.py that the traceback refers to: https://github.com/bigcommerce/bigcommerce-api-python/blob/master/bigcommerce/api.py#L57
According to the examples, create should be used like this:
api.Categories.create(name = 'anothertestingcat')
Note: You should generate a new API KEY, since you published the current one in this question.
Ive the following function which is do POST request to provider , I need to add new param to post request to incress the timeout ( which is by default is 5 mints i want to incress it to 1 hour , i did changes but i keep getting errors
Exception in thread Thread-1:
Traceback (most recent call last):
File "/usr/lib64/python2.6/threading.py", line 532, in __bootstrap_inner
self.run()
File "/opt/lvptest/lvp_upload.py", line 226, in run
op = uploadMedia(mediaName, "PyUploader", env)
File "/opt/lvptest/lvp_upload.py", line 121, in uploadMedia
expires = math.ceil(time() + 3000) ["expires"]
TypeError: 'module' object is not callable
Here is my function
def uploadMedia(filepath, description, env):
global verbose
global config
orgId = config[env]["org_id"]
accessKey = config[env]["access_key"]
secret = config[env]["secret"]
expires = math.ceil(time() + 3000) ["expires"]
filename = os.path.basename(filepath)
baseUrl = "http://api.videoplatform.limelight.com/rest/organizations/%s/media" %(orgId)
signedUrl = lvp_auth_util.authenticate_request("POST", baseUrl, accessKey, secret, expires)
c = pycurl.Curl()
c.setopt(c.POST, 1)
c.setopt(c.HEADER, 0)
c.setopt(c.HTTPPOST, [('title', filename), ("description", description), (("media_file", (c.FORM_FILE, filepath)))])
if verbose:
c.setopt(c.VERBOSE, 1)
bodyOutput = StringIO()
headersOutput = StringIO()
c.setopt(c.WRITEFUNCTION, bodyOutput.write)
c.setopt(c.URL, signedUrl)
c.setopt(c.HEADERFUNCTION, headersOutput.write)
try:
c.perform()
c.close()
Any tips if im mistaken adding param "expires" ?
here is example how is my POST request looks like
POST /rest/organizations/9fafklsdf/media?access_key=sfdfsdfsdfsdfsdf89234 &expires=1400406364&signature=Mc9Qsd4sdgdfg0iEOFUaRC4iiAJBtP%2BMCot0sFKM8A$
Two errors:
You should do from time import time instead of just time. Because the time module has a time function inside it.
math.ceil returns a float and you are trying to use it as a dict after:
expires = math.ceil(time() + 3000) ["expires"]
This doesn't make sense. math.ceil(time() + 3000) will be equal to something like 1400406364 and you can't retrieve a data from it.
Removing the ["expires"] should solve the problem.
The time module is not callable, you need to call time method from it:
>>> import time
>>> import math
>>> math.ceil(time())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'module' object is not callable
>>> math.ceil(time.time())
1400657920.0
Then you need to get rid of ["expires"] after it, since it will return a float number not a dictionary.
I don't know why you are using cURL here, with requests your code is a lot simpler:
import time
import math
import urllib
import requests
url = 'http://api.videoplatform.limelight.com/rest/organizations/{}/media'
filename = 'foo/bar/zoo.txt'
params = {}
params['access_key'] = 'dfdfdeef'
params['expires'] = math.ceil(time.time()+3000)
url = '{}?{}'.format(url.format(org_id), urllib.urlquote(params))
payload = {}
payload['title'] = os.path.basename(filename)
payload['description'] = 'description'
file_data = {'media_file': open(filename, 'rb')}
result = requests.post(url, data=payload, files=file_data)
result.raise_for_status() # This will raise an exception if
# there is a problem with the request