chriswelborn 63

@sa_2, on line 282 you mixed single quotes with double quotes. The syntax highlighting shows it right here:

cout<<'  \t\t¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥\n\n\n";

Next time start a new question, so more people can help you.

ddanbe commented: Nice +15

chriswelborn 63

It's been a while since I messed with VB, but I can't find anything that sticks out as far as the overflow situation. It's hard to read anything the way you're building those queries. I'm pretty sure that they're prone to SQL injection anyway. Have you looked at prepared statements? So the user can't just enter 2016-22-13'); DROP TABLE Employee_Information; into txtDateOfHire?

Can you print some kind of stack trace, showing exactly where the error takes place?

chriswelborn 63

I think it would help if you weren't shadowing the cosa name in your for loop. Classes should use CamelCase, to distinguish them from function names and other stuff. Instantiating a class is like calling a function, so if you are instantiating a Cosa, and not trying to call a Cosa instance (like in the loop), it should work. print(repr(cosa)) should tell you which you are dealing with.

chriswelborn 63

Put the form on your page with an id (let's say 'contactForm') and css set to 'display: none', so it's easily accessible with javascript but initially hidden. Make your "show form" button/link/whatever with an onclick event (there are multiple ways to do this):

<a href='#contactForm' onclick='javascript: show_form();'>
    E-mail me.
</a>

Here is one way to implement show_form(). There are lots though. If you are already using some framework, they probably have a cross-browser way of doing this (such as jQuery's $('#contactForm').toggle() and $('#contactForm').css({'display': 'block'})):

function show_form() {
    var frm = document.getElementById('contactForm');
    frm.style.display = 'block';
}

Your cancel button will also need to be handled, so that clicking the button hides the form.

var cancelbtn = document.getElementById('cancel');
cancelbtn.onclick = function () {
    var frm = document.getElementById('contactForm');
    frm.style.display = 'none';
}

Here is an ugly jsfiddle displaying the behavior. I would suggest studying up on JavaScript if you're not already in the process.

tobyITguy commented: helpful. +3

chriswelborn 63

What is the content and type of cfg.project["samples"][0]["files"]["bam"]? A Tuple/List/Set/Dict? Maybe stepping through a debugger, or even a simple debug-print would help you see what you are getting, or why you're not getting what you think you should.

testdata = cfg.project['samples'][0]['files']
print('Actual files content:')
print('{!r}'.format(testdata))

print('Actual bam content:')
print('{!r}'.format(testdata['bam']))

Also, there are a lot of lists being concatenated here, I guess to build up command-line arguments. Command line args are fickle at times, and could possibly be broken by the concatenation (or concatenating in a certain order). I'm reaching here, but it's possible.

chriswelborn 63

This question is difficult to understand. I don't think the wall of output text helps. Maybe you could word it differently, or provide a little pseudo-code to help us understand what exactly you are trying to do?

What are the comparisons? A file?

What does "takes that to [metadata][phenotype][embryo]" mean? (what does "takes that to" mean in python?)

"samples -> files -> bam which is the input"..input to what?

A lot have people have viewed your question, but I think the wording is making it hard to help.

chriswelborn 63

What is the actual problem? Is there a traceback when you run it? You say:

while p is less than the length of the list...

..which is basically describing what your code does. Can you give me a more general explanation? Like "I want to shift the ordinance of every character in a string."? I see some patterns here that can be shortened:

This:

n = 0
number = []
while n<8:
    random_number = chr(random.randint(33, 126))
    print(random_number)
    n = n + 1
    characters = ord(random_number)
    number.append(characters)

Could be written much cleaner as (untested):

# A list of 8 random character ordinances (numbers)
numbers = [random.randint(33, 126) for _ in range(8)]

Which is also easy to work with when building strings or whatever:

# That same list converted to characters
actualchars = [chr(n) for n in numbers]

# That character list as a string.
actualstring = ''.join(actualchars)

# All in one go (using a generator)
randomstring = ''.join((chr(random.randint(33, 126)) for _ in range(8)))

It's a much shorter version of this for-loop:

numbers = []
for _ in range(8):
    numbers.append(random.randint(33, 126))

This way you don't have to do so much bookkeeping. Also, there is no reason to go from int -> chr -> ord (line #15 and #21), because ord(chr(47)) == 47. Python is good at list comprehensions and generators, so there is no reason to build a simple list like this with a while loop (for more complicated processing, maybe, but for-loops are possibly even better).

chriswelborn 63

I can only find python-based "watermark" plugins at the moment. You may have to make one. The PIL or pillow libraries can help you work with images. Outside of GIMP, I see the StegHide application recommended for this.

chriswelborn 63

Small typo in that example, the font name. Should be 'Times New Roman'

chriswelborn 63

I see that your __init__ method is misspelled, but you're gonna want an instance to work with. You have a calculating class, but no object. Instantiate the class:

mycalc = calculating()

...then use the method (mycalc.addition). Also, its good practice in python for classes to start with a capital letter. So calculating should be called Calculating instead.

chriswelborn 63

enumerate() is great for grabbing an index and item at the same time, and f.tell() can tell you the current position in the file:

for i, line in enumerate(file):
    print('{lineno} ({pos}): {line}'.format(
        lineno=i + 1, 
        pos=file.tell(), 
        line=line))

chriswelborn 63

just type it out. Put a blank line before the code, make sure all of the code lines are indented with 4 spaces.

# I did not use the </>Code button.
print('Hello World.')

You can also use the tilde character (`) to do "inline code" such as this: int c = 5; ...for when you don't need a whole block.

chriswelborn 63

Indention level matters in Python. I see you assign s in main(), but the code following that is actually outside of main() because of it's indention level. In other words, this:

#main function
def main(self):

    s = Set([0, 1, 2, 3, 4])
print
"The elements in the set are : ",

# Ask the user to enter the element to be added
n = input('Enter the element to add to the set: ')

#calling method to add the element
valid = s.addElement(n)
# ... All code for main() below this too..

Needs to be this:

#main function
def main(self):
    s = Set([0, 1, 2, 3, 4])
    print "The elements in the set are : ",

    # Ask the user to enter the element to be added
    n = input('Enter the element to add to the set: ')

    #calling method to add the element
    valid = s.addElement(n)
    # ... All code for main() below this too..

So you were accessing s before main() was even called (during definition on file load). Also notice how I put the print statement all on one line. This will print a blank line:

print
"Hello",

This will print "Hello " (a space is added because of the ,):

print "Hello",

When you separate the lines like that, "Hello", is not part of the print statement. It is evaluated and the result is thrown away. print statements should be on the same line, or if you really have to break them up you can do something ...

chriswelborn 63

Sounds like homework. If you post what you have tried so far I'm sure you would receive the help you are looking for.

chriswelborn 63

@vegaseat, from the Python doc page for multiprocessing:

It runs on both Unix and Windows.

It's stdlib stuff so I assumed it was cross-platform, but to be honest I've never tested it on Windows.

I see on the doc page that there are some differences with spawn and fork in the multiprocessing API itself. Windows has spawn and fork, but uses spawn by default. Unix only has fork pre Python 3.4, and it uses fork by default. Support for spawn was added in 3.4. I see no differences in the Process API, which by the way is compatible with the Thread API (awesome).

chriswelborn 63

I would refer to the API documentation for DataResult<fmd>. I'm sure there are methods to help you retrieve the images it captures. I'm not sure which SDK you are using, and the DigitalPersona documentation (which I think you may be using) requires that you purchase support.

DigitalPersona does have a SerializeXml method, which is database-friendly and allows you to recreate the images for verification after saving them.

chriswelborn 63

You could also do this with a Process.

import functools
import multiprocessing
def background(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        p = multiprocessing.Process(target=func, args=args, kwargs=kwargs)
        p.start()
    return wrapper

Also, I wanted to point something out for new people that may be reading this. I think it's a good practice to use the functools.wraps decorator when making things like this.

Example:

def decoratorwithout(f):
    def wrapper():
        return f()
    return wrapper

def decoratorwith(f):
    @functools.wraps(f)
    def wrapper():
        return f()
    return wrapper

@decoratorwithout
def myfuncwithout():
    """ You can't see this with help() or other tools. """
    return None

@decoratorwith
def myfuncwith():
    """ This is correct documentation. """
    return None

Checking the docs:

help(myfuncwith)

Help on function myfuncwith in module __main__:

myfuncwith()
    This is correct documentation.

And the function without functools.wraps:

help(myfuncwithout)

Help on function wrapper in module __main__:

wrapper()

functools.wraps sets the __doc__ and other things to help avoid confusion when wrapping functions.

print(myfuncwithout.__name__)
wrapper

print(myfuncwith.__name__)
myfuncwith

chriswelborn 63

@snippsat, you're right about that JavaScript bit. I don't know what I was thinking. I guess if you were trying to do some validation on the client side, besides what the inputs already check, you might need it.

chriswelborn 63

You could look at making a cgi script, but I don't recommend it. You should look into HTML/JavaScript and AJAX/Forms, and make a Python backend like Flask, Django, or Bottle.

Basically you have a Python app running server-side, that accepts a GET or POST request. A GET request would look like:

http://yoursite.com/?userinput="blah blah"

You need some JavaScript to get the value from your input box. You put the value in some POST data ({userinput: $('#userbox').val()}), or a GET request, send it off from the browser and from there your server app handles it. You'll have to look at the differences between GET and POST. They each have their pros and cons.

In django the view could be as simple as:

def view_helloworld(request):
    userinput = request.REQUEST.get('userinput', None)
    if userinput:
        return HttpResponse('User said: {}'.format(userinput))
    else:
        return HttpResponse('No data!', status=500)

Of course I haven't even mentioned the templating systems available, error handling, or anything else that comes with some of Python's awesome web frameworks.

I use jQuery for AJAX because it simplifies the cross-browser problems. Django has CSRF protection, so you also have to grab the value from the csrftoken cookie and send it along with the data.

I am simplifying things. There is actually a lot more to it. Too much for me to put in a daniweb comment. Look at the things I mentioned, and if you get stuck come back with what you have tried. We will be glad to help you.

chriswelborn 63

This is an old post, but I didn't see any translation tables in here. So here you go, a less secure encryption method for low-risk data:

rot13 = str.maketrans(
    'ABCDEFGHIJKLMabcdefghijklmNOPQRSTUVWXYZnopqrstuvwxyz',
    'NOPQRSTUVWXYZnopqrstuvwxyzABCDEFGHIJKLMabcdefghijklm')
encrypted = 'This is encrypted'.translate(rot13)
print(encrypted)
decrypted = encrypted.translate(rot13)
print(decrypted)

You can make the translation tables almost anything you want. I used rot13 as an example. I wouldn't recommend something like this for high-risk data.

chriswelborn 63

Line 28:

if(overnightCheck >= 0 && overnightCheck <= 1)
      {
         if(overnightCheck == 1)
            overnightPrice = 5.00;
      }

That wrapper to make sure overnightCheck is 1 or 0 is pointless. Because you are checking it again just below, and then doing nothing for the false case. What happens if a user enters 2,3, or 5 in this:

if (overnightCheck == 1) {
    overnightPrice = 5.00;
}

Nothing. So, they have to enter 1 for the price to be set. The extra guard is redundant.

chriswelborn 63

If libraries aren't allowed, you could make your own Counter.

words = ['this', 'this', 'that', 'that', 'that', 'and']
wordcount = {}
for word in words:
    existing = wordcount.get(word, 0)
    wordcount[word] = existing + 1

wordcountlist = []
for word, count in wordcount.items():
    wordcountlist.extend((word, count))

print(repr(wordcountlist))
# ['this', 2, 'that', 3, 'and', 1]

Of course, there are libraries that would simplify this too..

from collections import defaultdict
wordcount = defaultdict(int)
for word in words:
    wordcount[word] += 1

Anyway, I think there are some good answers here no matter what the constraints are on the problem. Plenty to choose from. :)

chriswelborn 63

There is also collections.Counter.

from collections import Counter
wordcount = Counter(['this', 'this', 'that', 'that', 'that', 'and'])
print(repr(wordcount))
# Reveals:
# {'this': 3, 'that': 2, 'and': 1}

Not only is it easy, but I'm pretty sure it performs better (coded in C).
If you really wanted it in list format you could do this to it:

wordcountlist = []
for word, count in wordcount.items():
    wordcountlist.extend((word, count))

Or you could combine the two:

words = ['this', 'this', 'that', 'that', 'that', 'and']
wordcountlist = []
for word, count in Counter(words).items():
    wordcountlist.extend((word, count))

The order may be off, because of the Counter converting to dict. Honestly, if you are going to be retrieving the counts in the future, a dict may be better anyway. Retrieving the count would just be: wordcount['this'] or wordcount[myword]. ..instead of having to construct your own for-loop to retrieve/parse the counts.

chriswelborn 63

Ok, thanks Dani and pritaeas.

chriswelborn 63

You have an event loop up at the top (while done==False:) that runs until the user has quit. Because of the indention, your event loop runs until completion and only then draws what you wanted it to. Your indention signifies a 'code block'.Everything in that code block will run until the code block is exited. Right now only a portion of your code is inside of the event loop. The rest of it (the important part) is outside of the code block, and doesn't run until the event loop completes. By indenting all of your logic and draw-events to the same level as the while block I was able to make your game run.

Example:

done = False
while not done:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            print('User has exited!')
            done = True

    print('We are inside of the event loop, press CTRL + C!')

print('We are outside of the event loop.')
print('Now is not a good time to start drawing stuff.')

chriswelborn 63

'Tutorials' and 'Snippets' came later right? So 'Unanswered' used to be exactly what I am talking about. 'Unanswered' does exactly what it's supposed to do and shows all unanswered posts, so with the new additions maybe it's time for a new kind of 'Unanswered'?

chriswelborn 63 ...

I think Snippets and Tutorials should be excluded from 'Unanswered', or a new section should be created called 'Open Questions' that doesn't include snippets and tutorials. Most of the snippets/tutorials don't receive an answer for a long time and they cloud the view when looking for a quick question to answer/solve.

..just my two cents. :)

chriswelborn 63

I like this. I modified it so the function name would be included with frame.f_code.co_name.

chriswelborn 63

There is a possibility that the python executable is not in /usr/bin on other people's systems. It could be in /usr/local/bin, /home/otheruser/.local/bin, or anywhere else. Without the env, you are telling it exactly which executable to use.

env will use the system's $PATH to determine where python is. There is also a possibility the env executable isn't really in /usr/bin, but that's a slim chance.

Long story short, if you are writing for only yourself and your machine, you can use whatever you want. I think it's a good practice to use #!/usr/bin/env python if you are distributing your scripts.

chriswelborn 63

when you write a view function, it must have a request parameter (try writing one without it). This is because Django automatically passes the HttpRequest() to your view so you can use it. You don't have to use it, I have plenty of views that do absolutely nothing with the request (not on my part anyway). Django is instantiating the HttpRequest(), not you.

It lets you do things like this (not tested):

def my_search_view(request):

    # Retrieve GET/POST argument from http request
    GET_arg1 = request.REQUEST.get('search_query', None)

    # Validate arguments
    if GET_arg1 is None:
        # No argument found, tell the user
        response = HttpResponse("No search argument given!")
    else:    
        # Use the argument we found to do something.
        response = HttpResponse("You are searching for: " + GET_arg1)

    return response

The request has alot of useful information in it like request.POST, request.GET, request.REQUEST (GET and POST combined), request.META (useful info about the request). I think Django needs to use the request itself anyway, so passing it to you is just a convenience. Just one of the many "magic" things Django does for you. I hope this helps.