Wednesday, May 27, 2020

How to filter a list of dictionaries in python

# This is a list of dictionaries in python
list_of_dictionaries = [{'id':2, "name":"python"}, {'id':1, "name":"import"}, {'id':3, "name":"bye!"}]

# This is the list, filtered by the 'name' key
# returns a list that contains one element -- the dictionary with id == 1
filteredlist = list(filter(lambda d: d['name'] in ['import'], list_of_dictionaries))


# This is the list, filtered by the 'name' key
# returns a list that contains two dictionaries
filteredlist = list(filter(lambda d: d['name'] in ['import','python'], list_of_dictionaries))


# understanding the filter function
# https://docs.python.org/3/library/functions.html#filter

# understanding what lambda means
# https://docs.python.org/3/tutorial/controlflow.html#lambda-expressions

Tuesday, May 19, 2020

How to sort a list of dictionaries in python


# This is a list of dictionaries in python
list_of_dictionaries = [{'id':2, "name":"python"}, {'id':1, "name":"import"}]

# This is the list, sorted by the key "name"
sortedlist = sorted(list_of_dictionaries, key=lambda k: k['name'])

# This is the list, reverse sorted by the key "name"
sortedlist = sorted(list_of_dictionaries, key=lambda k: k['name'], reverse=True)

#shortcut to learn more about the sorted function
# https://docs.python.org/3/howto/sorting.html

#understanding what lambda means
# https://docs.python.org/3/tutorial/controlflow.html#lambda-expressions



Thursday, August 11, 2016

How to get VueJS, Rubaxa Sortable, and flask to work together

One of the problems I recently had integrating flask, sortable, and vuejs was that everytime I removed a object from the vuejs store, the sortable list would reset itself, sorting based on the data-id rather than the order of sortable. In the end, I added a function to Vue's watch and compiled events to sort sortable.
Vue.directive('sortable', {
    bind: function(){
        var vm = this.vm;
        var el = this.el;
        window.sortable = Sortable.create(el, {
            store: {
                get: function(sortable) {
                    const order = "{{ sort_order }}";
                    vm.sortOrder = order
                    return order ? order.split('|') : [];
                },

                set: function(sortable) {
                    const order = sortable.toArray();
                    vm.sortOrder = order.join('|')
                    $.ajax({
                        type: "POST",
                        url: '/sortorder',
                        data: {
                            'ordertype': 'todo_order',
                            'order': order.join('|')
                        }
                    })
                }
            },

            group: "todo_sort_order",
        });

    },
});

var vm =  new Vue({
    el:'#app',
    data:{
        todos: {{json_todo_list |safe}},
        sortOrder: [],
        orderedTodos:[]
    },
    methods: {

        deleteTodo: function(todo){
            _id = todo.id
            $("#" + _id)[0].reset();
            this.todos.$remove(todo);

            $.ajax({
                type: "POST",
                url: '/present/delete',
                data: {'id':_id},
                success: function(data) {
                }
            });
        },
    },
    watch: {
        'todos':function(val, oldVal){
            sortable.sort(this.sortOrder.split('|'));
        },
    },
    compiled: function(){
        sortable.sort(this.sortOrder.split('|'));
    }
})

Friday, July 29, 2016

How to get jeditable and autosizeInput width to use the correct css styling

In a previous post, I showed how to get the jquery libraries jeditable and jquery.autosize.input (autosizeInput) to work together.

 jeditable - https://github.com/tuupola/jquery_jeditable
autosizeInput - https://github.com/MartinF/jQuery.Autosize.Input

After implementation, i decided to change the font used in my css from a serif to a monospaced font type and discovered that autosizeInput was incorrectly calculating the width size based on the serif font size. Looking at the code, I discovered that my custom autosizeInput type creates a input element but that element is not attached to the DOM. In other words, the input element does not inherit the styling from css.

To fix this, i added a line that attaches the created input element to the DOM:

$.editable.addInputType('autosize', {
    element : function(settings, original) {
        /* Create an input. Mask it using autosizeInput plugin. Settings  */
        /* for mask can be passed with Jeditable settings hash.          */

        var input = $('<input />');
        input.appendTo('body');

        input.autosizeInput();
        if (settings.width  != 'none') { input.width(settings.width);  }
        if (settings.height != 'none') { input.height(settings.height); }
        $(this).append(input);
        return(input);
    }
});

Thursday, July 28, 2016

How to get rubaxa Sortable and jeditable to work together

One of the problems I was having was how to get the rubaxa sortable library and jeditable library to work together.  In the end, searching on google only lead to disappointment as the existing answers only referenced a different sortable library (jquery-ui). 

Here's how I got rubaxa sortable and jeditable to work together.



    disableSortable = function(settings, self) {
        sortable.option('disabled', true);
    };

    enableSortable = function(settings, self) {
        sortable.option('disabled', false);
    };

     $(document).ready(function()
     {$('.edit').each(function()
        {$(this).editable('/present/edit',
            {
                event: 'dblclick',
                onblur: 'submit',
                onedit : disableSortable,
                onsubmit: enableSortable,
                onrevert: enableSortable

            });
        });
     });

Tuesday, July 26, 2016

how to get jeditable to work with autosizeInput

I've been writing a flask todo program (jaychou.pythonanywhere.com) and have had to deal alot with jquery lately. This has been my first experience really diving into javascript and jquery so it's been a good learning experience.

One of the things i wanted was to have editable autosizing fields. Using the jeditable library, i was able to edit text and using the autosizeInput library, i was able to autosize the input tags. The problem was there was no good examples of how to integrate the two. So, here it is below.

How to get Jeditable to work with autosizeInput for input html tags


jeditable: https://github.com/tuupola/jquery_jeditable
autosizeInput: https://github.com/MartinF/jQuery.Autosize.Input


//jeditable
    $.editable.addInputType('autosize', {
        element : function(settings, original) {
            /* Create an input. Mask it using autosizeInput plugin. Settings  */
            /* for mask can be passed with Jeditable settings hash.          */

            var input = $('<input />').autosizeInput();
            if (settings.width  != 'none') { input.width(settings.width);  }
            if (settings.height != 'none') { input.height(settings.height); }
            $(this).append(input);
            return(input);
        }
    });

     $(document).ready(function()
     {$('.edit').each(function()
        {$(this).editable('/present/edit',
            {
                type: 'autosize',
                event: 'dblclick',
                onblur: 'submit',
                width: $(this).width()+30+'px',
            });
        });
     });

Wednesday, March 23, 2016

How to convert an H:MM:SS time string to seconds in Python

hhmmss2seconds
In [1]:
def get_sec(s):
    l = s.split(':')
    return int(l[0]) * 3600 + int(l[1]) * 60 + int(l[2])

print get_sec('2:15:30')
print get_sec('0:10:00')
print get_sec('0:00:30')
8130
600
30