Beat_Slayer 17 Posting Pro in Training

Had time to finnally optimize it using itertools now.

from itertools import combinations
import time

list1 = range(10, 30)
int1 = 60

print 'List:', ', '.join([str(i) for i in list1])

list1 = list(set(list1))
list1 = [item for item in list1 if (item + min(list1)) <= int1]

print 'Clean List:', ', '.join([str(i) for i in list1])

subsets_list = []

def min_list(x, mlist):
    m, rest = divmod(x, max(mlist))
    if rest:
        return m + 1
    else:
        return m

def max_list(x, mlist):
    m, rest = divmod(x, min(mlist))
    if not rest:
        return m - 1
    else:
        return m

def subsets(nlist, wanted, min_list_size, max_list_size):
    for s in range(min_list_size, max_list_size + 1):
        rlist = [item for item in nlist if item >= (wanted / len(nlist))]
        for item in combinations(rlist, s):
            subsets_list.append(item)

t1 = time.clock()
subsets(list1, int1, min_list(int1, list1), max_list(int1, list1))
t2 = time.clock()

print 'Subsets took %0.3f ms to calculate %s subsets' % ((t2 - t1) * 1000.0, len(subsets_list))

valid_sums = [item for item in subsets_list if sum(item) == int1]

print '%s is the sum of %s subsets' % (int1, len(valid_sums))
for sums in valid_sums:
    print '%s is the sum of %s' % (int1, ', '.join([str(i) for i in sums]))

Cheers and Happy coding

Beat_Slayer 17 Posting Pro in Training

You should have all working with the ips you give, i believe it's firewall problem.

If you notice this forum has lots of sub-foruns, and evey one has a different category.

Python is a computer programmming language.

Maybe here, or here will be better to find your answer.

Cheers and Happy coding

Beat_Slayer 17 Posting Pro in Training

For that function you use pyhton 3.x, or you do:

from __future__ import print_function

def main():
    f = open('lines.txt')
    for line in f:
        print(line, end = '')

if __name__ == "__main__": main()

Cheers and Happy coding

Beat_Slayer 17 Posting Pro in Training

And your code is?

Cheers and Happy coding

Beat_Slayer 17 Posting Pro in Training

It relys on a bad configuration for sure.

If the printer is connected to the router on a valid network configuration, then it is on the same network as the computers, since that it should be a firewall problem.

It can also be a NAT problem.

Wich are the IPs? of the computer, router and printer?

Cheers and Happy printing :)

Beat_Slayer 17 Posting Pro in Training

It relys on a bad configuration for sure.

If the printer is connected to the router on a valid network configuration, then it is on the same network as the computers, since that it should be a firewall problem.

It can also be a NAT problem.

Wich are the IPs? of the computer, router and printer?

Cheers and Happy printing :)

Beat_Slayer 17 Posting Pro in Training

Had a litle time to look at it and,

list1 = range(10, 20)
int1 = 60

print 'List:', ', '.join([str(i) for i in list1])

list1 = list(set(list1))
list1 = [item for item in list1 if (item + min(list1)) <= int1]

print 'Clean List:', ', '.join([str(i) for i in list1])

subsets_list = []
valid_sums = []

def subsets(nlist, wanted, max_list_size):
    for iteration in range(len(nlist)):
        ilist = nlist[:]
        ilist.pop(iteration)
        if ilist not in subsets_list:
            subsets_list.append(ilist)
            if len(ilist) <= max_list_size:
                if sum(ilist) == wanted and ilist not in valid_sums:
                    valid_sums.append(ilist)
                elif len(ilist) >= 3:
                    subsets(ilist, wanted, max_list_size)
            elif len(ilist) >= 3:
                subsets(ilist, wanted, max_list_size)

max_list_possible = lambda((x, mlist)): x / min(mlist)

subsets(list1, int1, max_list_possible((int1, list1)))

print '%s is the sum of %s subsets from the %s subsets calculated' % (int1, len(valid_sums), len(subsets_list))
for sums in valid_sums:
    print '%s is the sum of %s' % (int1, ', '.join([str(i) for i in sums]))

Cheers and Happy coding

Beat_Slayer 17 Posting Pro in Training

I believe with a GetCellValue(self, row, col) in a nice loop.

ncols = 7
row = 3
row = [self.GetCellValue(row, col) for col in range(ncols)]

Cheers and Happy coding

Beat_Slayer 17 Posting Pro in Training

Well, it bothers me to build menus for every shell application that needs one.

So, I've written a module to handle that, like in the good old turbo pascal times. :)

Here it is, the module comments are pretty explainatory, I think, and the sample usage if run as script should enlighten the concept.

Use it, give comments, improvements, have fun...

Cheers and Happy coding

Beat_Slayer 17 Posting Pro in Training

Your router may be cofigured to only allow connections through ethernet cable and not wireless connections to the settings.

Apart that, this is the python forum, for python related questions.

Cheers and Happy coding.

Beat_Slayer 17 Posting Pro in Training

format
This parameter can be used instead of the fmt24hr and displaySeconds parameters, respectively; it provides a shorthand way to specify the time format you want. Accepted values are 'HHMMSS', 'HHMM', '24HHMMSS', and '24HHMM'. If the format is specified, the other two arguments will be ignored.
fmt24hr
If True, control will display time in 24 hour time format; if False, it will use 12 hour AM/PM format. SetValue() will adjust values accordingly for the control, based on the format specified. (This value is ignored if the format parameter is specified.)

You can do

self.EndingHour = masked.TimeCtrl(panel, -1, name='24 hour control', format = '24HHMM')

or

self.EndingHour = masked.TimeCtrl(panel, -1, name='24 hour control', fmt24hr = True)

Cheers and Happy coding

Beat_Slayer 17 Posting Pro in Training

Some code???


Cheers and Happy coding

Beat_Slayer 17 Posting Pro in Training

You should start a thread and ask for help there, not on a old closed thread.

Anyway, you should read this.

Cheers and Happy coding

Beat_Slayer 17 Posting Pro in Training

OFF-TOPIC

nod = lambda(x): len(str(x))

print nod(125125)

Cheers and Happy coding

Beat_Slayer 17 Posting Pro in Training

You don't have questions, nowone cared about this, so just let it sink, till someone finds it attractive.


Cheers and Happy coding

Beat_Slayer 17 Posting Pro in Training

It does it now, but I'm not a regex expert, maybe they can make other way.

I can only see as searching with regex, catching the longest, then search for that group with the regex and ask the start.

words = ['cataaaaac', 'pooooloo']

for word in words:
    longest = 0
    letterlist = set(word)
    for char in letterlist:
        seq = sorted(re.findall('%s+' % char, word))[-1:]
        sequence = ''.join(seq)
        lenght = len(sequence)
        if lenght > longest:
            longest = lenght
            letters = sequence
    m = re.search(letters, word)
    print 'Word:', word
    print 'Most:', letters[0], 'with', len(letters), 'starting at index', m.start()

Cheers and Happy coding

Beat_Slayer 17 Posting Pro in Training
import re

words = ['cataaaaac', 'poolooo']

for word in words:
    longest = 0
    letterlist = set(word)
    for char in letterlist:
        for item in re.findall('%s+' % char, word):
            lenght = len(item)
            if lenght > longest:
                longest = lenght
                sequence = item
    print 'Word:', word
    print 'Most:', sequence[0], 'with', len(sequence), 'starting at index', word.index(sequence)

Cheers and Happy coding

Beat_Slayer 17 Posting Pro in Training

Thanks snippsat, I'll look at it. :)

I was using a small list during the build it did'nt shouwed up, back to the drawing table. lol

Cheers and Happy coding

Beat_Slayer 17 Posting Pro in Training

It does the work, but it's not regex.

words = ['cataaaaac', 'poolooo']

for word in words:
    rep = ''
    count = 0
    i = 0
    most = ''
    great = 0
    index = 0
    start = 0
    for char in word:
        if char == rep:
            count += 1
            if count > great:
                most = rep
                great = count
                index = start
        else:
            start = i
            rep = char
            count = 1
        i += 1
    print 'Word:', word
    print 'Most:', most, 'with', great, 'starting at index', index

Cheers and Happy coding

Beat_Slayer 17 Posting Pro in Training

Still not totally finished, since I want to optimize it, but... It does the job.

list1 = [1, 5, 3, 9, 4, 2, 7, 8]

list1 = range(10, 75)

int1 = 60

print 'List:', ', '.join([str(i) for i in list1])

list1 = list(set(list1))
list1 = [item for item in list1 if item <= int1 and (item + min(list1)) <= int1]

print 'Clean List:', ', '.join([str(i) for i in list1])

list2 = list1[:]
pre_valid_sums = []
for x in list1:
    list2 = list1[:]
    list2.remove(x)
    for rotation in range(len(list2)):
        r = list2.pop(0)
        list2.append(r)
        list3 = list2[:]
        for redution in range(len(list2) - 1):
            list3.pop()
            for iteration in range(len(list3) - 1):
                list4 = list3[:]
                list4.pop(iteration)
                if (x + sum(list4)) == int1:
                    pre_valid_sums.append(sorted([x] + list4))
valid_sums = []
for sums in pre_valid_sums:
    if sums not in valid_sums:
        valid_sums.append(sums)
for sums in valid_sums:
    print '%s is the sum of %s' % (int1, ', '.join([str(i) for i in sums]))

Cheers and Happy coding

Beat_Slayer 17 Posting Pro in Training

As NOT wizards, we don't guess code solutions.


Cheers and Happy coding

Beat_Slayer 17 Posting Pro in Training
import time
import subprocess

ip = '127.0.0.1'

def ping(ip):
    pinging = subprocess.Popen('ping -w 200 -n 1 ' + ip, stdout=subprocess.PIPE,
                                creationflags=0x08000000)
    time.sleep(1) # wait 1 sec before reading ping results
    if "0% loss" in pinging.stdout.read():
        return True
    
while 1:
    if ping(ip):
        subprocess.Popen('cmd', creationflags=0x08000000)
        time.sleep(300)
    else:
        time.sleep(300)

Cheers and Happy coding

Beat_Slayer 17 Posting Pro in Training
list1 = [1, 5, 3, 9, 4]
int1 = 8

found = None
for x in list1:
    for y in list1:
        if (x + y) == int1:
            print int1, 'is the sum of', x, 'and', y
            found = True
if not found:
    print int1, 'is not the sum of any of the numbers in the list'

Cheers and Happy coding

EDIT: Returning to the drawing table :)

Beat_Slayer 17 Posting Pro in Training

Like this mate.

import time
import subprocess

ip = '127.0.0.1'

def ping(ip):
    pinging = subprocess.Popen('ping -w 200 -n 1 ' + ip, stdout=subprocess.PIPE)
    if "0% loss" in pinging.stdout.read():
        return True

while 1:
    if ping(ip):
        subprocess.Popen('cmd')
        time.sleep(0.3)
    else:
        time.sleep(0.3)

Be aware, if you run it like this it will open a shell every 300 milisecs.

Cheers and Happy coding

s0ur commented: Really nice guy! :-) +0
Beat_Slayer 17 Posting Pro in Training

I think it's simple as this:

list1 = [1, 5, 3, 9, 4]
int1 = 8

list2 = [item + item for item in list1]

if int1 in list2:
    print int1, 'is the sum of', int1/2
else:
    print int1, 'is not the sum of any of the numbers in the list'

or

list1 = [1, 5, 3, 9, 4]
int1 = 8

for item in list1:
    if item + item == int1:
        print int1, 'is the sum of', item
        break
else:
    print int1, 'is not the sum of any of the numbers in the list'

Cheers and Happy coding

Beat_Slayer 17 Posting Pro in Training

Popen.terminate()¶

Stop the child. On Posix OSs the method sends SIGTERM to the child. On Windows the Win32 API function TerminateProcess() is called to stop the child.

New in version 2.6.

Popen.kill()¶

Kills the child. On Posix OSs the function sends SIGKILL to the child. On Windows kill() is an alias for terminate().

Source

If you paste the code it will be more easy to help.

Cheers and Happy coding

Beat_Slayer 17 Posting Pro in Training

Why is he adding portability adding json???

Json is more dedicated to data interchange, pickle it's here used to store data to the file, not to send serialized data over network or to databases.

As the address book increases in datasize, I believe cPickle will make you feel the difference.

Cheers and Happy coding

Edit:

One reason to use cPickle???

import cPickle as pickle
import json
import time

def time_it(func):
    def wrapper(*arg):
        t1 = time.time()
        res = func(*arg)
        t2 = time.time()
        print '%s took %0.3f ms' % (func.func_name, (t2 - t1) * 1000.0)
        return res
    return wrapper

list1 = [1, 2, 3, 'string1', 'string2', 'string3',
         [23, 35, 46], {'somewhere': 1, 'elsewhere': 4}]

print list1

@time_it
def test_pickle():
    for run in range(100000):
        pickle.dumps(list1)

@time_it
def test_json():
    for run in range(100000):
        json.dumps(list1)

test_pickle()
test_json()

It's really fast.

Cheers and Happy coding

Beat_Slayer 17 Posting Pro in Training

I'll get you a start point.

try:
    import cPickle as pickle
except:
    import pickle


class address_book():

    def __init__(self):
        try:
            self.__db = open('addressbook.db', 'rb')
            self.__entries = pickle.load(self.__db)
            self.__db.close()
        except:
            self.__db = open('addressbook.db', 'wb')
            self.__entries = {}
            self.__db.close()

    def __update(self):
        self.__db = open('addressbook.db', 'wb')
        pickle.dump(self.__entries, self.__db, -1)
        self.__db.close()

    def add_entry(self, (name, number, email)):
        self.__entries[name] = {}
        self.__entries[name]['Telephone'] = number
        self.__entries[name]['E-mail'] = email
        self.__update()

    def show_data(self):
        for k, v in self.__entries.iteritems():
            print 'Name:', k
            for subk, subv in v.iteritems():
                print '%s: %s' % (subk, subv)
            print
        

app = address_book()

userdata = ('Paul', '00316123456789', 'something@somewhere.com')

app.add_entry(userdata)

app.show_data()

Implement the rest,

Cheers and Happy coding

Beat_Slayer 17 Posting Pro in Training

Functions to add, remove and view entries to the address book, values stored in a pickled dictionary.

I'm eager to help, but I want to see some code effort from you.

Cheers and Happy coding

Beat_Slayer 17 Posting Pro in Training

How about all the clients read from the 'channel' they are associated, and post to the 'channel' socket.

The server has only receive message, and associate to the proper channel.

Cheers and Happy coding.

Beat_Slayer 17 Posting Pro in Training

And like this?

for item in pl[section]:
    if item.find('dashboard-tile') != -1:
        print "Dashboard" # dont need other values because there are none
        print '\t'.join((item['tile-data']['file-label'], item['tile-data']['file-data']['_CFURLString'], item['tile-data']['dashboard-tile'], section, plist_path))
    else:
        print '\t'.join((item['tile-data']['file-label'], item['tile-data']['file-data']['_CFURLString'], section, plist_path))

If you post your present code, I can do some clean up.

Cheers and Happy coding

Beat_Slayer 17 Posting Pro in Training

Yeah, I've no OS X experience.

Why don't you paste here the full plist? It would get easier.

For the correction, maybe:

for item in pl[section]:
    try:
      	if item.find('dashboard-tile') != -1:
       	    print "Dashboard" # dont need other values because there are none
        else:
            print '\t'.join((item['tile-data']['file-label'], item['tile-data']['file-data']['_CFURLString'], section, plist_path))

EDIT: Look what I've just found. plistlib — Generate and parse Mac OS X .plist files


Cheers and Happy coding

Beat_Slayer 17 Posting Pro in Training

Work it, and post when you get stuck.

from random import choice

first_list = []
second_list = []

for item in open('sampleconnection.txt').readlines():
    first, second = item.split('\t')
    first_list.append(first)
    second_list.append(second.strip('\n'))

for i in range(len(first_list)):
    choices_list = range(len(first_list) - 1)
    choices_list.remove(i)
    print first_list[i], second_list[choice(choices_list)]

Cheers and Happy coding

Beat_Slayer 17 Posting Pro in Training

Litle help...

for item in pl[section]:
    if item.has_key('dashboard-tile'):
        try:
            print '\t'.join((item['tile-data']['file-label'], item['tile-data']['file-data']['_CFURLString'], item['tile-data']['dashboard-tile'], section, plist_path))

Cheers and Happy coding

Beat_Slayer 17 Posting Pro in Training

And like this?

import nltk
import os
import smtplib
import time

from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email import encoders

from nltk.corpus import gutenberg
from random import choice


triggerSentence = raw_input("Please enter the trigger sentence: ")#get input str

lastLongestStr = ""
listOfSents = gutenberg.sents('austen-emma.txt') #all sentences of gutenberg are assigned -list of list format-
listOfWords = gutenberg.words('austen-emma.txt')# all words in gutenberg books -list format-

class gmail():
    
    def __init__(self):
        self.recipient = "xxxxxxx@hotmail.com"
        self.gmail_user = "asdassdsaadssd"
        self.gmail_pwd = "asdasdasasdasasd"
        self.subject = "assadasdasasdass"

    def create_mail(self, message):
        self.themail = MIMEMultipart()
        self.themail['Subject'] = self.subject
        self.themail['From'] = self.gmail_user
        self.themail['To'] = self.recipient
        self.themail.attach(MIMEText(message)) 
	
    def send_mail():
        smtpserver = smtplib.SMTP("smtp.gmail.com",587)
        smtpserver.ehlo()
        smtpserver.starttls()
        smtpserver.login(self.gmail_user, self.gmail_pwd)
        print "Connection established."
        smtpserver.sendmail(self.gmail_user, self.recipient, self.themail.as_string())
        print "Your mail has been sent."
        smtpserver.close()


while triggerSentence:

    longestLength = 0
    longestString = ""
    longestLen2 = 0
    longestStr2 = ""
    #run the loop so long as there is a trigger sentence

    sets = []
    split_str = triggerSentence.split()#split the sentence into words
        
    #code to find the longest word in the trigger sentence input
    for piece in split_str:
        if len(piece) > longestLength:
            longestString = piece
            longestLength = len(piece)

    if longestString == lastLongestStr:
       longestString = sorted(split_str, key=len)[-2]
       print longestString + " second longest!"

       if longestString == lastLongestStr:
          longestString = sorted(split_str, key=len)[-3]
          print longestString + " third longest!"
    
    print longestString + " is now the longest"
    print "\n"

    #code to get the sentences containing the longest word, then selecting
    #random one of these sentences that are longer than 40 characters

    for sentence1 in listOfSents: …
Beat_Slayer 17 Posting Pro in Training

Your code is very messy, very distorted, but if you copy your line 18 to line 25 it will work.

Anyway I recommend some clean up.

Cheers and Happy coding

Beat_Slayer 17 Posting Pro in Training

Yes, it follows the same principle of multi partition calls to slice and split an string.

I always use similar methods, and decided to make one liners of my current versions for easying the things out.

Cheers and Happy coding

Beat_Slayer 17 Posting Pro in Training

Look here.

Text slice and split made easy.

Cheers and Happy coding

Beat_Slayer 17 Posting Pro in Training

Two litle functions to help on text slice and spliting.

The code comments say it all.

# Slicer takes as arguments a tuple containing the string before,
# the string after and the string to truncate. It returns the string
# between the two given strings
Slicer = lambda((b, a, t)): t.partition(b)[2].partition(a)[0]
# Spliter takes as arguments a tuple containing the string before,
# the string after and the string to truncate. It returns a tuple
# containing the string before, the string between and the string
# after the given strings
Spliter = lambda((b, a, t)): ((t.partition(b)[0]),) + t.partition(b)[2].partition(a)[0::2]

Cheers and Happy coding

Beat_Slayer 17 Posting Pro in Training

It's pretty to say, but...

What types will be the sound files, what you define by instruments(midi, real) and a lot more...

Cheers and Happy coding

Beat_Slayer 17 Posting Pro in Training

What you want Tcll, the conversion of the case?

How are you reading the values?

Cheers and Happy coding

Beat_Slayer 17 Posting Pro in Training

Sorry for all the consecutive posts.

I was bored so...

import urllib

sock = urllib.urlopen('http://www.columbia.edu/')
htmlSource = sock.read()
sock.close()

before_html, tag_before, rest_html = str(htmlSource).partition('<!-- BEGIN COLUMBIA NEWS -->')
news, tag_after, after_html = rest_html.partition('<!-- END COLUMBIA NEWS -->')

news = news.split('\r')

stripwhite = lambda x: x.strip()

news = [stripwhite(item.strip('\n')) for item in news if stripwhite(item.strip('\n')) and stripwhite(item.strip('\n')) != '<br /><br />']

for line in news:
    news_title, tag_before, rest_html = str(line).partition('<a href=')
    link, tag_after, after_html = rest_html.partition('>')
    print 'News:', news_title
    print 'Link:', link

Cheers and Happy coding

Beat_Slayer 17 Posting Pro in Training

Some help.

import urllib

sock = urllib.urlopen('http://www.columbia.edu/')
htmlSource = sock.read()
sock.close()

before_html, tag_before, rest_html = str(htmlSource).partition('<!-- BEGIN COLUMBIA NEWS -->')
news, tag_after, after_html = rest_html.partition('<!-- END COLUMBIA NEWS -->')

for line in news.split('\r'):
    print line.strip()

Cheers and Happy coding

Beat_Slayer 17 Posting Pro in Training

Similar task

Try something and we'll help you.

Cheers and Happy coding

Beat_Slayer 17 Posting Pro in Training

Line 1 of your convert.py says 'on win32'?

I guess that's not valid python code, and thats why the import is failing.

Cheers and Happy coding

Beat_Slayer 17 Posting Pro in Training

I don't get it????

Whats the question? You create a picture image object RGB 600 by 600, but you write no data to it.

And you do something with a ImageDraw object but I can't see what also.

Cheers and Happy coding

Beat_Slayer 17 Posting Pro in Training

What happens when you run this?

What's the console output?

Sugestions??
Put dnaml on the path and run the script from the OutputFiles folder to avoid all those nasty paths.

Cheers and Happy coding

Beat_Slayer 17 Posting Pro in Training

Because dictionaries have hashable values as keys. And so the keys are ordered by their hash.

Cheers and Happy coding

Beat_Slayer 17 Posting Pro in Training

You must use the 'SetCellValue(self, row, col, s)' attrivute of the grid.

Make a loop, read row, iterate trough items, and insert the data on the cells.

Cheers and Happy coding

Beat_Slayer 17 Posting Pro in Training

Try with the datetime module instead.


Cheers and Hapy coding