mardi 28 juin 2016

How can I define global options with sub-parsers in python argparse?


I'm trying to figure out how to add global option in a sub-parser scenario with pythons arparse library.

Right now my code looks like this:

def parseArgs(self):
    parent_parser = argparse.ArgumentParser(add_help=False)
    parent_parser.add_argument('--debug', default=False, required=False,
        action='store_true', dest="debug", help='debug flag')

    main_parser = argparse.ArgumentParser()
    main_parser.add_argument('--debug', default=False, required=False,
        action='store_true', dest="debug", help='debug flag')

    service_subparsers = main_parser.add_subparsers(title="category",
        dest="category")
    agent_parser = service_subparsers.add_parser("agent",
        help="agent commands", parents=[parent_parser])
    return main_parser.parse_args()

This works for the command line ./test --help and the --debug option is listed as global:

usage: test [-h] [--debug] {agent} ...

optional arguments:
  -h, --help  show this help message and exit
  --debug     debug flag

category:
  {agent}
    agent     agent commands

However when I trigger the agent sub-parser with the command line ./test agent --help the --debug option is now no longer listed as a global option but as an option for the sub-parser. Also it must now specified as ./test agent --debug and ./test --debug agent no longer works:

usage: test agent [-h] [--debug]

optional arguments:
  -h, --help  show this help message and exit
  --debug     debug flag

What I'd like to be able to do is define --debug is global so that it can always be specified for all sub-parsers and appropriately listed as such in the help output.


typo3 7.6.X backend extension using jquery and bootstrap and boostrap.js


in my custom extension for typo3 which is ported from 6.2.9 to 7.4.9 I want to use jquery and bootstrap.js

But if I use both one of them is not working well.

in my layoutfile I define this:

<f:be.container>

    <script src="{f:uri.resource(path:'js/jquery-2.1.4.min.js')}" type="text/javascript"></script>
   <script src="{f:uri.resource(path:'js/bootstrap.js')}" type="text/javascript"></script>
    <script src="{f:uri.resource(path:'js/jquery.tablesorter.min.js')}" type="text/javascript"></script>
    <!-- Chart JS -->
    <script src="{f:uri.resource(path:'js/Chart.min.js')}" type="text/javascript"></script>
    <link href="{f:uri.resource(path:'css/resultrepository.css')}" rel="stylesheet" type="text/css"/>
    <!-- Bootstrap -->
    <link href="{f:uri.resource(path:'css/bootstrap.min.css')}" rel="stylesheet">

    <!-- Globales JavaScript für das Result Repository Modul -->
    <script src="{f:uri.resource(path:'js/rereGlobal.js')}" type="text/javascript"></script>

    <!-- JS for Noteverwaltung.html -->
    <script src="{f:uri.resource(path:'js/noteverwaltung.js')}" type="text/javascript"></script>

    <!-- FontAwesome -->
    <link href="{f:uri.resource(path:'css/font-awesome.min.css')}" rel="stylesheet">

In this case what could be the problem? Former when I used it in typo3 6.2.9 it worked fine with the code above. Just in 7.4.9 only jquery or bootstrap.js is working.


Django REST Framework DateTimeField format showing Python Time


Given some model

class Loan(models.Model):
    time_of_loan = models.DateTimeField()
    username = models.CharField()

I have attempted to use the ModelSerializer from Django's REST Framework to serialize the Loan.

class LoanSerializer(serializers.ModelSerializer):
    time_of_loan = serializers.DateTimeField(
    format=None, input_formats=['%Y-%m-%d %H:%M:%S',])
    class Meta:
        model = `Loan`
        fields = ['time_of_loan', 'username']

On using the serializer.data to get the JSON format, when I save the first time, the first time the model is saved, the JSON is well-behaved.

{
  'time_of_loan': '2016-06-20 00:00:00+08:00', 
  username: 'doe'
}

However, when I attempt to update the model, it "misbehaves" and it appears in a python datetime format.

{
  'time_of_loan': datetime.datetime(2016, 6, 20, 7, 55, tzinfo=<UTC>), 
  'username': 'doe'
}

What change do I need to do so that, whenever the model gets serialized, it remains as the first format that I want?

FIRST EDIT

Can you show what you're doing to update the object

The question asked was what I did to update the model. I actually am using this as an audit log and so it took from an actual Django Form. In forms.py:

id = forms.cleaned_data.get('id')
username = forms.cleaned_data.get('username')
loan = Loan.objects.filter(id=id) #Queryset with count() = 1

loan.update(username=username)
loan_obj = loan[0]
serializer = LoanSerializer(loan_obj)
print(serializer.data)

event.stopPropogation is not a function


This is my first SO question and I'm afraid it may be a dumb one but I've spent many hours trying to figure this out and I have failed.

I am using DataTables plugin and trying to create a table with collapsible rows. The rows will have "select" buttons, each with their own .on("click") functions. When a child row is clicked, both its click function and its parent row's function execute. I am pretty sure this is because the event is bubbling up the DOM elements (child row(s) to parent row), and I am trying to use event.stopPropogation() inside the click function, but no matter what I try, I get the error message: "event.stopPropogation() is not a function"

Here is my basic table setup:

function _table(targetDiv) {

  var keyTable = d3.select("#juice").append("table")
    .attr("id", "keyTable");

  var keyHead = keyTable.append("thead");
  var columnNames = [null, "CPC", "Description"];

  keyHead.append("tr")
    .selectAll('td')
    .data(columnNames).enter()
        .append('th')
        .html(function(d) { console.log(d); return d; });

  $(document).ready(function() {
    table = $('#keyTable').DataTable({
        "ajax": "testing.txt",
        "columns":[     
            {
                 //some stuff
            }
        ]
    });

And in my event listener (I believe that's what this is called), I have tried it several ways but none of these work:

        $('#keyTable tbody')
        .on("click", 'tr', function(event){

             //add children and whatnot
             event.stopPropogation();
        }

Always I get the same error: Uncaught TypeError: event.stopPropogation is not a function

Let me know if I need to include more info or any of the code that I left out.


Unable to send mails


I have an HTML form, and linked with jQuery and PHP. The jQuery check whether the fields or empty or not, if they are not empty, it should send the data to the PHP file. But its not working.

$(document).ready(function() {
  $("#submit").click(function() {
    var name = $("#name").val();
    var message = $("#message").val();

    $("#returnmessage").empty(); // To empty previous error/success message.
    // Checking for blank fields.
    if (name == '') {
      alert(" Please Fill your name");
    } else if (message == '') {
      alert("Please Fill message");
    } else {
      $.post("xxx.php", { // To php file.
        name: name,
        message: message
      }, function(data) {
        $("#returnmessage").append(data);
        if (data == "We will contact you soon.") {
          $("#form")[0].reset(); // To reset form fields on success.
        }
      });
    }
  });
});
<form name="form" method="post" action="">
  <h4>FEED-BACK FORM</h4>
  <p id="returnmessage"></p>
  <label>Name:  </label>
  <input type="text" id="name" /><br>
  <label>Message:  </label>
  <input type="text" id="message" /><br>
  <input type="button" id="submit" value="Submit"/>
</form>

THE PHP CODE IS:

if(!isset($_POST['submit']))
       {
    //Need to submit the form.
    exit;
       }
$name = $_POST['name'];
$message = $_POST['message'];

$email_body ="Dear sir,n".
"Name: $namen". 
"Message:    $messagen";

//Email sending to
$email_from = 'xxx@xxx.xxx';
$email_subject = "my-form";
$to = "xxx@xxxx";
$headers = "From: $email_from rn";

//Send the email!
mail($to,$email_subject,$email_body,$headers);

Looking for a super explanation /tkinter direction (getting max recursion depth without super)


So I'm trying to use my "controller" to call my "view." But if I don't use super, I get an infinite recursion when buildTK tries to build iiBar. Using Super everything is fine. I'd just like to understand why that is.

import inputhandler as iH
import buildtk as tA
import scanhandler as aS

class ControlHandler:
    def __init__(self):
        #self.view = tA.buildTK() #does not work

        self.view = super(tA.buildTK) #works
        self.smodel = aS.aScan()
        self.imodel = iH.InputHandler() 

The buildTK class:

import tkinter as tt
import controlhandler as cH

class buildTK(tt.Frame):
    def __init__(self, master = None):
        self.frame = tt.Frame(master, bg="tan")
        self.frame.grid()

        self.ibar = iiBar(self.frame)

...
class iiBar:
    def __init__(self, master):
        print(repr(self)) #prints forever
        self.mbar = tt.Frame(master, relief = 'raised', bg="blue")
        self.mbar.grid(column=0, row=0) #Show File Bar
        self.tryFile() 
        self.tryTool()
        self.tryH()

EDIT: those try methods have no effect when commented out, but the basic code is:

    def tryTool(self):
        # Create  tools menu
        self.toolsbutton = tt.Menubutton(self.mbar, text = 'Tools', )
        self.toolsbutton.grid(row=0, column=2)

        self.toolsmenu = tt.Menu(self.toolsbutton, tearoff=0)
        self.toolsbutton['menu'] = self.toolsmenu

        # Populate tools menu
        self.toolsmenu.add('command', label = 'tools', command = root.destroy)

And out of curiosity, is there a best-practice for going about what I'm trying to do? Eventually I'd like a "build handler" to instantiate the form (either tkinter, html, xml) - in which case the controller would instantiate the build handler which would determine what to build.


How to read a csv django http response


In a view, I create a Django HttpResponse object composed entirely of a csv using a simply csv writer: response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="foobar.csv"' writer = csv.writer(response) table_headers = ['Foo', 'Bar'] writer.writerow(table_headers) bunch_of_rows = [['foo', 'bar'], ['foo2', 'bar2']] for row in bunch_of_rows: writer.writerow(row) return response In a unit test, I want to test some aspects of this csv, so I need to read it. I'm trying to do so like so: response = views.myview(args) reader = csv.reader(response.content) headers = next(reader) row_count = 1 + sum(1 for row in reader) self.assertEqual(row_count, 3) # header + 1 row for each attempt self.assertIn('Foo', headers) But the test fails with the following on the headers = next(reader) line: nose.proxy.Error: iterator should return strings, not int (did you open the file in text mode?) I see in the HttpResponse source that response.content is spitting the string back out as a byte-string, but I'm not sure the correct way to deal with that to let csv.reader read the file correctly. I thought I would be able to just replace response.content with response (since you write to the object itself, not it's content), but that just resulted in a slight variation in the error: _csv.Error: iterator should return strings, not bytes (did you open the file in text mode?) Which seems closer but obviously still wrong. Reading the csv docs, I assume I am failing to open the file correctly. How do I "open" this file-like object so that csv.reader can parse it?