Search Results

Search found 14486 results on 580 pages for 'python idle'.

Page 176/580 | < Previous Page | 172 173 174 175 176 177 178 179 180 181 182 183  | Next Page >

  • Threaded Python port scanner

    - by Amnite
    I am having issues with a port scanner I'm editing to use threads. This is the basics for the original code: for i in range(0, 2000): s = socket(AF_INET, SOCK_STREAM) result = s.connect_ex((TargetIP, i)) if(result == 0) : c = "Port %d: OPEN\n" % (i,) s.close() This takes approx 33 minutes to complete. So I thought I'd thread it to make it run a little faster. This is my first threading project so it's nothing too extreme, but I've ran the following code for about an hour and get no exceptions yet no output. Am I just doing the threading wrong or what? import threading from socket import * import time a = 0 b = 0 c = "" d = "" def ScanLow(): global a global c for i in range(0, 1000): s = socket(AF_INET, SOCK_STREAM) result = s.connect_ex((TargetIP, i)) if(result == 0) : c = "Port %d: OPEN\n" % (i,) s.close() a += 1 def ScanHigh(): global b global d for i in range(1001, 2000): s = socket(AF_INET, SOCK_STREAM) result = s.connect_ex((TargetIP, i)) if(result == 0) : d = "Port %d: OPEN\n" % (i,) s.close() b += 1 Target = raw_input("Enter Host To Scan:") TargetIP = gethostbyname(Target) print "Start Scan On Host ", TargetIP Start = time.time() threading.Thread(target = ScanLow).start() threading.Thread(target = ScanHigh).start() e = a + b while e < 2000: f = raw_input() End = time.time() - Start print c print d print End g = raw_input()

    Read the article

  • Python Attributes and Inheritance

    - by user368186
    Say I have the folowing code: class Class1(object): def __init__(self): self.my_attr = 1 self.my_other_attr = 2 class Class2(Class1): def __init__(self): super(Class1,self).__init__() Why does Class2 not inherit the attributes of Class1?

    Read the article

  • Python: Picking an element without replacement

    - by wpeters
    I would like to slice random letters from a string. Given s="howdy" I would like to pick elements from 's' without replacement but keep the index number. For example >>> random.sample(s,len(s)) ['w', 'h', 'o', 'd', 'y'] is close to what I want, but I would actually prefer something like [('w',2), ('h',0), ('o',1), ('d',3), ('y',4)] with letter-index pairs. This is important because the same letter appears in 's' more than once. ie) "letter" where 't' appears twice but I need to distinguish the first 't' from the 'second'. Ideally I actually only need to pick letters as I need them but scrambling and calculating all the letters in a list (as shown above) is ok.

    Read the article

  • python array.array with strings as data type

    - by Gladius
    Is there an object that acts like array.array, yet can handle strings (or character arrays) as its data type? It should be able to convert the string array to binary and back again, preferably with null terminated strings, however fixed length strings would be acceptable. >>> my_array = stringarray(['foo', 'bar']) >>> my_array.tostring() 'foo\0bar\0' >>> re_read = stringarray('foo\0bar\0') >>> re_read[:] ['foo', 'bar'] I will be using it with arrays that contain a couple million strings.

    Read the article

  • Waiting for thread to finish Python

    - by lunchtime
    Alright, here's my problem. I have a thread that creates another thread in a pool, applies async so I can work with the returned data, which is working GREAT. But I need the current thread to WAIT until the result is returned. Here is the simplified code, as the current script is over 300 lines. I'm sure i've included everything for you to make sense of what I'm attempting: from multiprocessing.pool import ThreadPool import threading pool = ThreadPool(processes=1) class MyStreamer(TwythonStreamer): #[...] def on_success(self, data): #### Everytime data comes in, this is called #[...] #<Pseudocode> if score >= limit if list exists: Do stuff elif list does not exist: #</Pseudocode> dic = [] dic.append([k1, v1]) did = dict(dic) async_result = pool.apply_async(self.list_step, args=(did)) return_val = async_result.get() slug = return_val[0] idd = return_val[1] #[...] def list_step(self, *args): ## CREATE LIST ## RETURN 2 VALUES class threadStream (threading.Thread): def __init__(self, auth): threading.Thread.__init__(self) self.auth = auth def run(self): stream = MyStreamer(auth = auth[0], *auth[0]) stream.statuses.filter(track=auth[1]) t = threadStream(auth=AuthMe) t.start() I receive the results as intended, which is great, but how do I make it so this thread t waits for the async_result to come in?? My problem is everytime new data comes in, it seems that the ## CREATE LIST function is called multiple times if similar data comes in quickly enough. So I'm ending up with many lists of the same name when I have code in place to ensure that a list will never be created if the name already exists. So to reiterate: How do I make this thread wait on the function to complete before accepting new data / continuing. I don't think time.sleep() works because on_success is called when data enters the stream. I don't think Thread.Join() will work either since I have to use a ThreadPool.apply_async to receive the data I need. Is there a hack I can make in the MyStreamer class somehow? I'm kind of at a loss here. Am I over complicating things and can this be simplified to do what I want?

    Read the article

  • Google App Engine: Difficulty with Users API (or maybe just a Python syntax problem)

    - by Rosarch
    I have a simple GAE app that includes a login/logout link. This app is running on the dev server at the moment. The base page handler gets the current user, and creates a login/logout url appropriately. It then puts this information into a _template_data dictionary, for convenience of subclasses. class BasePage(webapp.RequestHandler): _user = users.get_current_user() _login_logout_link = None if _user: _login_logout_link = users.create_logout_url('/') else: _login_logout_link = users.create_login_url('/') _template_data = {} _template_data['login_logout_link'] = _login_logout_link _template_data['user'] = _user def render(self, templateName, templateData): path = os.path.join(os.path.dirname(__file__), 'Static/Templates/%s.html' % templateName) self.response.out.write(template.render(path, templateData)) Here is one such subclass: class MainPage(BasePage): def get(self): self.render('start', self._template_data) The login/logout link is displayed fine, and going to the correct devserver login/logout page. However, it seems to have no effect - the server still seems to think the user is logged out. What am I doing wrong here?

    Read the article

  • Python script to remove lines from file containing words in array

    - by chromesub
    I have the following script which identifies lines in a file which I want to remove, based on an array but does not remove them. What should I change? sourcefile = "C:\\Python25\\PC_New.txt" filename2 = "C:\\Python25\\PC_reduced.txt" offending = ["Exception","Integer","RuntimeException"] def fixup( filename ): print "fixup ", filename fin = open( filename ) fout = open( filename2 , "w") for line in fin.readlines(): for item in offending: print "got one",line line = line.replace( item, "MUST DELETE" ) line=line.strip() fout.write(line) fin.close() fout.close() fixup(sourcefile)

    Read the article

  • python and regular expression with unicode

    - by bsn
    I need to delete some unicode symbols from the string '?????? ??????? ???????????? ??????????' I know they exist here for sure. I try: re.sub('([\u064B-\u0652\u06D4\u0670\u0674\u06D5-\u06ED]+)', '', '?????? ??????? ???????????? ??????????') but it doesn't work. String stays the same. ant suggestion what i do wrong?

    Read the article

  • Python: Trouble with YACC

    - by Rosarch
    I'm parsing sentences like: "CS 2310 or equivalent experience" The desired output: [[("CS", 2310)], ["equivalent experience"]] YACC tokenizer symbols: tokens = [ 'DEPT_CODE', 'COURSE_NUMBER', 'OR_CONJ', 'MISC_TEXT', ] t_DEPT_CODE = r'[A-Z]{2,}' t_COURSE_NUMBER = r'[0-9]{4}' t_OR_CONJ = r'or' t_ignore = ' \t' terms = {'DEPT_CODE': t_DEPT_CODE, 'COURSE_NUMBER': t_COURSE_NUMBER, 'OR_CONJ': t_OR_CONJ} for name, regex in terms.items(): terms[name] = "^%s$" % regex def t_MISC_TEXT(t): r'\S+' for name, regex in terms.items(): # print "trying to match %s with regex %s" % (t.value, regex) if re.match(regex, t.value): t.type = name return t return t (MISC_TEXT is meant to match anything not caught by the other terms.) Some relevant rules from the parser: precedence = ( ('left', 'MISC_TEXT'), ) def p_statement_course_data(p): 'statement : course_data' p[0] = p[1] def p_course_data(p): 'course_data : course' p[0] = p[1] def p_course(p): 'course : DEPT_CODE COURSE_NUMBER' p[0] = make_course(p[1], int(p[2])) def p_or_phrase(p): 'or_phrase : statement OR_CONJ statement' p[0] = [[p[1]], [p[3]]] def p_misc_text(p): '''text_aggregate : MISC_TEXT MISC_TEXT | MISC_TEXT text_aggregate | text_aggregate MISC_TEXT ''' p[0] = "%s %s" % (p[0], [1]) def p_text_aggregate_statement(p): 'statement : text_aggregate' p[0] = p[1] Unfortunately, this fails: # works as it should >>> token_list("CS 2110 or equivalent experience") [LexToken(DEPT_CODE,'CS',1,0), LexToken(COURSE_NUMBER,'2110',1,3), LexToken(OR_CONJ,'or',1,8), LexToken(MISC_TEXT,'equivalent',1,11), LexToken(MISC_TEXT,'experience',1,22)] # fails. bummer. >>> parser.parse("CS 2110 or equivalent experience") Syntax error in input: LexToken(MISC_TEXT,'equivalent',1,11) What am I doing wrong? I don't fully understand how to set precedence rules. Also, this is my error function: def p_error(p): print "Syntax error in input: %s" % p Is there a way to see which rule the parser was trying when it failed? Or some other way to make the parser print which rules its trying?

    Read the article

  • How to join the results of two tables in django python

    - by user1787524
    I have two models class Weather(model.model): region = models.ForeignKey(Region) district = models.ForeignKey(District) temp_max = models.IntegerField(blank=True, null=True, verbose_name='Max temperature (C)') temp_min = models.IntegerField(blank=True, null=True, verbose_name='Min temperature (C)') and class Plan(model.model): name = tinymce_models.HTMLField(blank=True, null=True) region = models.ForeignKey(Region) district = models.ForeignKey(District) Provided for every region and district have unique row. I want to combine the result so that i can get all the columns of both tables These two Models are not related to each other. ' I need to make the join like join weather w on w.region = A.region and w.distric = A.district so that result contains all the columns in everyobject like obj.temp_max etc

    Read the article

  • Python: Parsing a colon delimited file with various counts of fields

    - by Mark
    I'm trying to parse a a few files with the following format in 'clientname'.txt hostname:comp1 time: Fri Jan 28 20:00:02 GMT 2011 ip:xxx.xxx.xx.xx fs:good:45 memory:bad:78 swap:good:34 Mail:good Each section is delimited by a : but where lines 0,2,6 have 2 fields... lines 1,3-5 have 3 or more fields. (A big issue I've had trouble with is the time: line, since 20:00:02 is really a time and not 3 separate fields. I have several files like this that I need to parse. There are many more lines in some of these files with multiple fields. ... for i in clients: if os.path.isfile(rpt_path + i + rpt_ext): # if the rpt exists then do this rpt = rpt_path + i + rpt_ext l_count = 0 for line in open(rpt, "r"): s_line = line.rstrip() part = s_line.split(':') print part l_count = l_count + 1 else: # else break break First I'm checking if the file exists first, if it does then open the file and parse it (eventually) As of now I'm just printing the output (print part) to make sure it's parsing right. Honestly, the only trouble I'm having at this point is the time: field. How can I treat that line specifically different than all the others? The time field is ALWAYS the 2nd line in all of my report files.

    Read the article

  • Noob Python Question: List Confusion

    - by potatocubed
    I'm trying to transfer the contents of one list to another, but it's not working and I don't know why not. My code looks like this: list1 = [1, 2, 3, 4, 5, 6] list2 = [] for item in list1: list2.append(item) list1.remove(item) But if I run it my output looks like this: >>> list1 [2, 4, 6] >>> list2 [1, 3, 5] My question is threefold, I guess: Why is this happening, how do I make it work, and am I overlooking an incredibly simple solution like a 'move' statement or something?

    Read the article

  • How to reverse a dictionary that it has repeated values (python)

    - by Galois
    Hi guys! So, I have a dictionary with almost 100,000 (key, values) pairs and the majority of the keys map to the same values. For example imagine something like that: dict = {'a': 1, 'c': 2, 'b': 1, 'e': 2, 'd': 3, 'h': 1, 'j': 3} What I want to do, is to reverse the dictionary so that each value in dict is going to be a key at the reverse_dict and is going to map to a list of all the dict.keys that used to map to that value at the dict. So based on the example above I would get: reversed_dict = {1: ['a', 'b', 'h'], 2:['e', 'c'] , 3:['d', 'j']} I came up with a solution that is very expensive and I would really want to hear any ideas more efficient than mine. my expensive solution: reversed_dict = {} for value in dict.values(): reversed_dict[value] = [] for key in dict.keys(): if dict[key] == value: if key not in reversed_dict[value]: reversed_dict[value].append(key) Output >> reversed_dict = {1: ['a', 'b', 'h'], 2: ['c', 'e'], 3: ['d', 'j']} I would really appreciate to hear any ideas better and more efficient than than mine. Thanks!

    Read the article

  • How can i optimize this python code

    - by RandomVector
    def maxVote(nLabels): count = {} maxList = [] maxCount = 0 for nLabel in nLabels: if nLabel in count: count[nLabel] += 1 else: count[nLabel] = 1 #Check if the count is max if count[nLabel] > maxCount: maxCount = count[nLabel] maxList = [nLabel,] elif count[nLabel]==maxCount: maxList.append(nLabel) return random.choice(maxList) nLabels contains a list of integers. The above function returns the integer with highest frequency, if more than one have same frequency then a randomly selected integer from them is returned. E.g. maxVote([1,3,4,5,5,5,3,12,11]) is 5

    Read the article

  • Selecting dictionary items by key efficiently in Python

    - by user248237
    suppose I have a dictionary whose keys are strings. How can I efficiently make a new dictionary from that which contains only the keys present in some list? for example: # a dictionary mapping strings to stuff mydict = {'quux': ..., 'bar': ..., 'foo': ...} # list of keys to be selected from mydict keys_to_select = ['foo', 'bar', ...] The way I came up with is: filtered_mydict = [mydict[k] for k in mydict.keys() \ if k in keys_to_select] but I think this is highly inefficient because: (1) it requires enumerating the keys with keys(), (2) it requires looking up k in keys_to_select each time. at least one of these can be avoided, I would think. any ideas? I can use scipy/numpy too if needed.

    Read the article

  • "Slice" out one element from a python dictionary

    - by BCS
    I have a dictionary: D = { "foo" : "bar", "baz" : "bip" } and I want to create new dictionary that has a copy of one of it's elements k. So if k = "baz": R = { "baz" : "bip" } what I'v got now is: R = { k : D[k] } But in my case k is a complex expression and I've got a whole stack of these. Caching k in a temporary looks about as ugly as the original option. What I'm looking for is a better (cleaner) way to do this.

    Read the article

  • Second largest number in list python

    - by Manu Lakaster
    So I have to find THE SECOND LARGEST NUMBER IN A LIST. I am doing it through simple loops.My approach is I am going to divide a list into two parts and then find the largest number into two parts and then compare two nuumbers. I will choose the smaller number from two of them. I can not use ready functions or different approaches. Basically, this is my code....But it does not run correctly....Help me please to fix it because I spent a lot of time on it :( Thanks....P.S. Can we use indices to "divide" a list ??? #!/usr/local/bin/python2.7 alist=[-45,0,3,10,90,5,-2,4,18,45,100,1,-266,706] largest=alist[0] h=len(alist)/2 m=len(alist)-h print(alist) for i in alist: if alist[h]>largest: largest=alist[h] i=i+1 print(largest)

    Read the article

  • Python point lookup (coordinate binning?)

    - by Rince
    Greetings, I am trying to bin an array of points (x, y) into an array of boxes [(x0, y0), (x1, y0), (x0, y1), (x1, y1)] (tuples are the corner points) So far I have the following routine: def isInside(self, point, x0, x1, y0, y1): pr1 = getProduct(point, (x0, y0), (x1, y0)) if pr1 >= 0: pr2 = getProduct(point, (x1, y0), (x1, y1)) if pr2 >= 0: pr3 = getProduct(point, (x1, y1), (x0, y1)) if pr3 >= 0: pr4 = getProduct(point, (x0, y1), (x0, y0)) if pr4 >= 0: return True return False def getProduct(origin, pointA, pointB): product = (pointA[0] - origin[0])*(pointB[1] - origin[1]) - (pointB[0] - origin[0])*(pointA[1] - origin[1]) return product Is there any better way then point-by-point lookup? Maybe some not-obvious numpy routine? Thank you!

    Read the article

  • Python: Give a class its own `self` at instantiation time

    - by SuperDisk
    I've got a button class that you can instantiate like so: engine.createElement((0, 0), Button(code=print, args=("Stuff!",))) And when it is clicked it will print "Stuff!". However, I need the button to destroy itself whenever it is clicked. Something like this: engine.createElement((0, 0), Button(code=engine.killElement, args=(self,))) However, that would just kill the caller, because self refers to the caller at that moment. What I need to do is give the class its own 'self' in advance... I thought of just making the string 'self' refer to the self variable upon click, but what if I wanted to use the string 'self' in the arguments? What is the way to do this? Is my architecture all wrong or something? Thanks.

    Read the article

  • Using varible in re.match in python

    - by screwuphead
    I am trying to create an array of things to match in a description line. So I cant ignore them later on in my script. Below is a sample script that I have been working on, on the side. Basically I am trying to take a bunch of strings and match it against a bunch of other strings. AKA: asdf or asfs or wrtw in string = true continue with script if not print this. import re ignorelist = ['^test', '(.*)set'] def guess(a): for ignore in ignorelist: if re.match(ignore, a): return('LOSE!') else: return('WIN!') a = raw_input('Take a guess: ') print guess(a) Thanks

    Read the article

< Previous Page | 172 173 174 175 176 177 178 179 180 181 182 183  | Next Page >