vendredi 11 septembre 2015

auto close modal dialog google sheets - google apps script

I have a google sheet that I am connecting to a sql server to allow some non-sql server folks a tool to view and make small edits to data in a table. I have the read and write set up for the server, but want to create a "loading..." modal while data is being refreshed to prevent any issues. I can get the modal to pop up but am trying to figure out how to auto-close the dialog as soon as the code is finished firing.

An example I have set up is:

function testpop () {
  var htmlOutput = HtmlService
    .createHtmlOutput('<p> This box will close when the data has finished loading.</p>')
    .setSandboxMode(HtmlService.SandboxMode.IFRAME)
    .setWidth(250)
    .setHeight(200);
  SpreadsheetApp.getUi().showModalDialog(htmlOutput, 'Loading...');
  sleep(1000);
//close the dialog
}

I know this can be called on a client side but need it to be handled in the gs so it fires when the code is done. Thanks.



via Chebli Mohamed

Highlight multiple items of ListView

This problem is not new. However, any of the solution is not working for me.

I have got a ListView with several TextView which is populated from data fetched from SQLite. User can LongPress on one item to select multiple items of ListView and further choose to delete them from database.

What I want to do next is to highlight those items which are selected by user after the first LongPress (including the first one).
Here is the snippet of my ListView.

    <ListView
        ...
        android:drawSelectorOnTop="false"
        android:listSelector="@android:color/darker_gray"
        android:choiceMode="multipleChoice"/>

This is highlighting the item of ListView but not the first one on which the user will do the LongPress. And only highlight one of the item on ListView, whenever user chooses another item the current one is resetted and the background of the new item is changed, and this continues.



via Chebli Mohamed

Implementation wice_grid for one-to-many association

Image has a one-to-many association with Category:

# Category model:
has_many :images
# Image model:
has_one :category
Images migration file:
t.references :category, index: true, foreign_key: true

I'm trying to implement a grid view using the wice_grid gem. This works but one line is failing. The following works in the index view:

g.column name: 'Category', attribute: 'category_id', auto_reload: true, html: {id: 'grid-cells'} do |image|
  image.category_id
end

But this displays the number/id of the category, while I want it to display its name. If I try image.category instead of image.category_id there's an error:

PG::UndefinedColumn: ERROR:  column categories.image_id does not exist
LINE 1: SELECT  "categories".* FROM "categories" WHERE "categories"."image_id...

How can I have it display the category name instead of the id of the category?

Controller method:

def index
  @images_grid = initialize_grid(Image,
  # include: :category  # Do I need this? Tried it with and without
  per_page: 40)
end



via Chebli Mohamed

How to properly format logs

Is there a proper way to logging?

I want my web application to log every received call, just as any regular web server would do.

Are there some brilliant approaches to logging out there? My goal, aside from tracking errors, is to be able at some point in the future to get valuable statistical information on the server activity.

JSON and XML are verbose, while space-delimited logs (as in nginx & apache) are tedious to parse.

Did I miss something great?



via Chebli Mohamed

In Vanilla JavaScript, how do I structure my app when having multiple Models/Views/Controllers?

I'm trying to get a practical grasp of MVC model implementation (not the conceptual understanding) in JavaScript.

As for the start, I thought it would be worth making an effort and try building a MVC app in plain JS. I've read dozens of articles and book chapters referring to MVC and its variations. Of course I googled lots of examples to see how it's done for real. The most understandable and with the proper meaning is in my opinion this one:

http://ift.tt/1FBZo6q

In the end, I was able to refactor my own app in the todomvc-vanillajs way.

However, there is one thing that still bothers me. All these apps and examples are very basic, so there is only one Model, View and Controller specified for the whole app.

What if I wanted to add more (equally complex) features to such app?

Should I add them one by one to my controller.js view.js and model.js files or whether should I stop developing spaghetti code and add new files instead, thus creating new models, controllers and views for each of the new feature individually?

It seems to me, that every feature should have its own view, controller and model, or at least, could have, depending on the subjective evaluation. But I'm not quite sure how such implementation should look at this situation in terms of code structure, namespacing etc.?

What if I want to imitate a scale by creating multiple views, models and controllers on every single functionality like e.g. handling an "add task to the list" or "delete the task" actions.

For the purpose of my dilemma, I've created my own MVC draft, which has two models, controllers and views. Whether such an approach would make sense? What happens when further developing my application, I quickly get to the point where I have dozens and more specific (coresponding) models, views and controllers.

Heres is the aforementioned fiddle.

;(function () {
    'use strict';
    /**
     * @file ./App.js
     */ 

    var App = {
        Model : {},
        Controller : {},
        View : {}
    };

    console.log('start');

    window.App = App;

})();
/* -------------Views-folder----------------------*/
    /* -------------separate-file-----------------------*/
(function () {
    'use strict';
    /**
     * @file Views/buildAdd.js
     */ 

    var buildAdd = {
        // render

        // event

            // pass the reference to event handler in Controller
    };

    App.View.buildAdd = buildAdd;

})(App);
    /* -------------separate-file-----------------------*/
(function () {
    'use strict';
    /**
     * @file Views/buildDelete.js
     */ 

    var buildDelete = {
        // render

        // event

            // pass the reference to event handler in Controller
    };

    App.View.buildDelete = buildDelete; 

})(App);
/* -------------Controllers-folder----------------------*/
    /* -------------separate-file-----------------------*/
(function () {
    'use strict';

    var addController = {
        // handle the event and decide what the Model has to do

        // handle the response from Model and tells the View how to update 
    };

    App.Controller.addController = addController;

})(App);
/* -------------separate-file-----------------------*/
(function () {
    'use strict';

    var deleteController = {
        // handle the event and decide what the Model has to do

        // handle the response from Model and tells the View how to update
    };

    App.Controller.deleteController = deleteController;

})(App);
    /* -------------Models-folder----------------------*/
    /* -------------separate-file-----------------------*/
(function () {
    'use strict';

    var addModel = {
        // send request

        // get response
    };

    App.Model.addModel = addModel;

})(App);
    /* -------------separate-file-----------------------*/
(function () {
    'use strict';

    var deleteModel = {
        // send request

        // get response
    };

    App.Model.deleteModel = deleteModel;

})(App);
    /* -------------separate-file-----------------------*/

Thus, I found this question very similar to mine, but the provided answers are not entirely satisfactory, at least to me.



via Chebli Mohamed

JS: css property and value in one variable

var trns1 = '"transition": "all 1s"';

Why doesnt that work?

$('#box').css({"transform": "translate(xy)", trns1 });

Shouldnt that be exactly the same like:

$('#box').css({"transform": "translate(xy)", "transition": "all 1s" });

?



via Chebli Mohamed

Not sure why this code was added?

The home page for this handmade furniture website had this code

$outputstrg = htmlentities("<url>"). "<br />". htmlentities("<loc>").$urltest .$town . htmlentities("</loc>") . "<br />" . htmlentities("</url>");

I removed it and it had no effect, any idea why it was there and what it was supposed to do?



via Chebli Mohamed

Hibernate relations and AngularJS

I have this relation between Travelers and Trips in Hibernate:

enter image description here

If I want to create a new trip for traveler 1, I visit the route /frontend/#/trip-creation/1 and here I have a form:

enter image description here

By accessing the $routeParams.id I can get the details for traveler 1 like firstName (= Marcel) , lastName and also traveler_id.

$scope.traveler = TravelerFactory.show({id: $routeParams.id});

That is an example for the Traveler object. It contains all the Trips a Traveler had made so far:

[{"traveler_id":1,"company_id":0,"account":false,"firstName":"Marcel","middleName":null,"lastName":"Schmitt","gender":null,"trips":[],"email":null}]

My question:

  1. How can I relate my traveler 1 with the new created trip

    [{"trip_id":2,"traveler":null,"currency":null,"rate":100,"description":"Flug","dateCreated":null}]

  2. Is this a proper way of mapping the realtions?

Thank you!

Additional information // backend: Java, Hibernate 4.11, SpringMVC // frontend: AngularJS 1.4.3



via Chebli Mohamed

Where are my ko.observable properties?

http://ift.tt/1NmkSdD

thing = {
            id: 3,
            bool: ko.observable(false),
            state: ko.observable('disabled')
        }

I'm in the middle of trying to debug something in a much larger app, and I'm trying to make a simple example of how my app is breaking, and I can't even get my basic objects properties to show up.

Where are my 2 ko.observable properites on each thing object in rows? When I try to use "row.state()" it isn't there, it doesn't exist, as you can see in the stringified "text" in the dom.

Thoughts please.



via Chebli Mohamed

Modifying Array Data

I have to constantly add data to my NSMutableArray to index 0.

  MyVariables.MutableChatUser.insertObject(MyVariables.username, atIndex: 0)

Problem: The code above works perfectly the first time around but then next time it runs it overwrites the previous data.

Goal: I want the array to push the previous value from index 0 to index 1 when inserting a new value at index 0. I dont want to stomp on any existing data in the array



via Chebli Mohamed

Upload modal will not close after filepath is sent

I'm attempting to upload a file, which it does, however the upload screen just stays open so I cannot view on half the screen. Anyone know a workaround? The code I use:

        var path = require('path');
         //the file to upload
        var fileToUpload = 'some path i put in',
          //this is variable that inserts the path to find file to upload
          absolutePath = path.resolve(__dirname, fileToUpload);
         //inserts the path
        $('input[type="file"]').sendKeys(absolutePath);

I've tried adding: $('#uploadButton').click(); however it throws errors.

This question is related to my previous questions here: Are you able to upload a file



via Chebli Mohamed

How to query a single value from a datatable using linq in vb.net

I'm trying to query a value from a datable in vb using a linq query but am getting several errors.

here's my code:

For Each cl In clients
Dim cn As DataTable
    cn = getClients() #datatable with two columns, client code (cln_idck) and client name (cln_name)
Dim clientname As String
clientname = From cntable In cn Where cntable.Item("cln_idck") = cl Select (cntable.Item("cln_name")).ToString()

#do something   
Next

I'm just trying to grab the client name and put it into the string variable clientname using the client code to search. The above code gives me an error.

"range variable name cannot match the name of a member of the "object" class"

Any ideas why this isn't working?

Thanks for the help!

Rafael

update:

client is a list(of string) that has the client codes

Dim clients As New List(Of String)
    clients.Add("Cln1")
    clients.Add("Cln2") #etc.



via Chebli Mohamed

How to set raw header using winHttp for user name?

I used to access my own small server using Qt, and I could set my raw header using Qt like this:

        QString concatenated = "admin:admin";
        newRequest.setRawHeader("Authorization", concatenated.toLocal8Bit());

But how could I do the same thing using winHttp? How could I add the username password as admin:admin in my winHttp header?



via Chebli Mohamed

I Need a way to execute a particular function when i press the forward key or the back key in javascript

I need a way to execute a particular function when I press the forward key or the back key in javascript. So that it may work when the forward button is pressed it may execute the function but it should work without taking the input in any type of text box.

I mean it should work on the whole page no matter where I am on the page but if I press the forward button the function should be executed.

I know how to do it by taking an input in a text box by matching the key codes but don't know how to make it work in someway else.



via Chebli Mohamed

How to add 3 months to a UTC time stamp in javascript centered at midnight 00 Hours?

I am trying to add 3 months to today's date in a javascript. This is my code:

    var now = new Date();
    now.setHours(0, 0, 0, 0);;
    now.setMinutes(0);

    var plus3mo = new Date();
    plus3mo.setMonth((now.getMonth() + 3));
    plus3mo.setHours(0, 0, 0, 0);
    plus3mo.setMinutes(0);

    var utc_timestamp_today = Date.UTC(now.getFullYear(), now.getMonth(), now.getDate(), 0, 0, 0, 0);
    var utc_timestamp_3moFromNow = Date.UTC(plus3mo.getFullYear(), plus3mo.getMonth(), plus3mo.getDate(), 0, 0, 0, 0);

I want to add exactly 3 months to today's date and have the hours. It is doing that, but the catch is I need the hours to be set to exactly 00 hours or 12am. I am getting weird results with the code I have.

Here are my results that I viewed while debugging and using this UTC time stamp converter site.

1441929600000  --> 09/10/2015 20:00:00     ("Today's Date")
1449792000000  --> 12/10/2015 19:00:00     ("3 Months From Now")

As you can see, I am adding 3 months, but the hours are centered at 8pm and 7pm. Why is this happening?



via Chebli Mohamed

How to deliberately fail a Sphinx build when autodoc fails an import

I have a CI (Jenkins) job which builds Sphinx documentation for my Python project:

#!/bin/bash
set -x
virtualenv $WORKSPACE
source $WORKSPACE/bin/activate
pip install 'sphinx>=1.3.1'
python setup.py build_sphinx

My project uses the Sphinx autodoc extension to extract docstrings from my modules by importing them, e.g. in "docs/api/foo.bar.rst":

.. automodule:: foo.bar
    :members:
    :undoc-members:
    :show-inheritance:

Now, if autodoc fails to import foo.bar, the Sphinx build shows the traceback in the logs and carries on building anyway, although it warns me that:

WARNING: toctree contains reference to document u'api/foo.bar' that doesn't have a title: no link will be generated

This results in missing documentation, so I'd like to make my Sphinx build step fail in this event. Is there a more elegant way of doing this than trying to grep the logs from build_sphinx?



via Chebli Mohamed

partial matching of strings in different two datasets to obtain a match with higher frequency

I have strings in two datasets and i would like to do a partial match. Here is the code that I have written

 df1 <- data.frame(A=c(.87,.11,.44,.45), B=c("I have a beard", "I slept for two hours", "I have had two courses","this is not true"))

 df2 <- data.frame(X=c(127,10,433,344,890,4),Y=c("have","beard","syllabus","true","three","maths"))

I want to do a pmatch and I am expecting output as follows

  A     B                            X      Y
.87   I have a beard               127      have
.11   I slept for two hours        NA       NA
.44   I have had two courses       127      have
.45   this is not true             344      true

I would like to a partial match with a left join on df1. I want to get the higher of the two matches(for example in "I have a beard" string "have" match has 127 and "beard" has 10 and i want to get the higher match. Any suggestions?



via Chebli Mohamed

Are Joomla 1.5.25 templates and extensions fully compatible backwards to Joomla 1.5.15

I have been tasked with upgrading the template of a Joomla 1.5 website to responsive using Bootstrap (a really tricky thing for me since I have only worked from Joomla 2.5 up to 3.4), so I created a base template on a Joomla 1.5.26 Stable local installation.

Client didn't wanted to share code, so I will have to give only the template file, that is the base template modified, but today they told me Joomla version they are using is 1.5.15 and they won't update it anymore since it was the last version that allowed myisam on mysql config. Template is not finished but they want to test it, so I can't find enough documentation since its very old to confirm template will work properly.

Also I am recoding old extensions to try to use Google Maps API, but I can't find almost any extensions left and I'm trying some but can't know if they can run on previous builds. I didn't even was programming or designing anything by the time these versions were released :( could someone enlighten me?

EDIT: So far version 1.5.15 requires myisam database config to run, so it needs a mySQL version lower than 5.5. With XAMPP 1.7.2 it seems to run fine, just delete all cookies from browser to be able to use phpmyadmin and other things. Clientside seems to work fine for now, but maybe Google Maps API will require a bit of patience.

Bootstrap running on these antique its a real challenge but it will be done, one way or another. Thinking of publishing a template just in case anyone wants to revive these old systems.



via Chebli Mohamed

sencha add list to panel,then add panel to my tabpanel.in controller

when i write code direct in my view .the list success display in my tabpanel's tab.look the view underneath

        {
            xtype: 'tabpanel',
            itemId: 'tabfirst',
            flex: 1,
            //activeItem: 1,
            tabBar: {
                layout: {
                    pack: 'center'
                }
            },
            items: [
                {
                    title: 'tab1',
                    xtype: 'list',
                    itemTpl: '{title}',
                    data: [
                        {title : 'title1'},
                        {title : 'title2'},
                        {title : 'title3'}
                    ]                        
                },
                {
                    title: 'tab2',
                    html: 'here second html2'
                }
            ]
        }

but it not success in my controller. there is nothing in my tab.

Ext.define('ylp2p.controller.addtab',{
extend: 'Ext.app.Controller',
launch: function(){
    var moneytab = Ext.ComponentQuery.query('.makemoney #tabfirst')[0];//--get my tabpanel
    var titlestor = Ext.create('ylp2p.store.loanlist');//---get my store
    titlestor.load({
        callback: function(records, operation, success){
            Ext.each(records, function(record){
                var loanname = record.get('loanname');
                var myPanel = Ext.create('Ext.Panel',{ 
                    //the code is same in my view but not work
                    title: loanname,
                    xtype: 'list',
                    itemTpl: '{title}',
                    data: [
                        {title : 'title1'},
                        {title : 'title2'},
                        {title : 'title3'}
                    ]
                });
                moneytab.add([myPanel]);
               //add above panel
            });
        }
    });
}
});

when i add only "title" and "html" in panel,it work. then i change it to list.it success in direct write in view. but it not work write it direct in controller.



via Chebli Mohamed

Animate objects in force layout in D3.js

I need to create a data visualisation which would look like a bunch of floating bubbles with text inside of the bubble.

I have a partially working example which uses mock data prepared here: JSfiddle

// helpers
var random = function(min, max) {
    if (max == null) {
        max = min;
        min = 0;
    }
    return min + Math.floor(Math.random() * (max - min + 1));
};

// mock data
var colors = [
    {
        fill: 'rgba(242,216,28,0.3)',
        stroke: 'rgba(242,216,28,1)'
    },
    {
        fill: 'rgba(207,203,196,0.3)',
        stroke: 'rgba(207,203,196,1)'
    },
    {
        fill: 'rgba(0,0,0,0.2)',
        stroke: 'rgba(100,100,100,1)'
    }
];
var data = [];
for(var j = 0; j <= 2; j++) {
    for(var i = 0; i <= 4; i++) {
        var text = 'text' + i;
        var category = 'category' + j;
        var r = random(50, 100);
        data.push({
            text: text,
            category: category,
            r: r,
            r_change_1: r + random(-20, 20),
            r_change_2:  r + random(-20, 20),
            fill: colors[j].fill,
            stroke: colors[j].stroke
        });
    }
}
// mock debug
//console.table(data);

// collision detection
// derived from http://ift.tt/1MgMORF
function collide(alpha) {
    var quadtree = d3.geom.quadtree(data);
    return function(d) {
        var r = d.r + 10,
            nx1 = d.x - r,
            nx2 = d.x + r,
            ny1 = d.y - r,
            ny2 = d.y + r;
        quadtree.visit(function(quad, x1, y1, x2, y2) {
            if (quad.point && (quad.point !== d)) {
                var x = d.x - quad.point.x,
                    y = d.y - quad.point.y,
                    l = Math.sqrt(x * x + y * y),
                    r = d.r * 2;
                if (l < r) {
                    l = (l - r) / l * alpha;
                    d.x -= x *= l;
                    d.y -= y *= l;
                    quad.point.x += x;
                    quad.point.y += y;
                }
            }
            return x1 > nx2 || x2 < nx1 || y1 > ny2 || y2 < ny1;
        });
    };
}

// initialize
var container = d3.select('.bubble-cloud');
var $container = $('.bubble-cloud');
var containerWidth = $container.width();
var containerHeight = $container.height();
var svgContainer = container
    .append('svg')
    .attr('width', containerWidth)
    .attr('height', containerHeight);

// prepare layout
var force = d3.layout
    .force()
    .size([containerWidth, containerHeight])
    .gravity(0)
    .charge(0)
;

// load data
force.nodes(data)
    .start()
;

// create item groups
var node = svgContainer.selectAll('.node')
    .data(data)
    .enter()
    .append('g')
    .attr('class', 'node')
    .call(force.drag);

// create circles
node.append('circle')
    .classed('circle', true)
    .attr('r', function (d) {
            return d.r;
        })
    .style('fill', function (d) {
            return d.fill;
        })
    .style('stroke', function (d) {
        return d.stroke;
    });

// create labels
node.append('text')
    .text(function(d) {
        return d.text
    })
    .classed('text', true)
    .style({
        'fill': '#ffffff',
        'text-anchor': 'middle',
        'font-size': '12px',
        'font-weight': 'bold',
        'font-family': 'Tahoma, Arial, sans-serif'
    })
;

node.append('text')
    .text(function(d) {
        return d.category
    })
    .classed('category', true)
    .style({
        'fill': '#ffffff',
        'font-family': 'Tahoma, Arial, sans-serif',
        'text-anchor': 'middle',
        'font-size': '9px'
    })
;

node.append('line')
    .classed('line', true)
    .attr('x1', 0)
    .attr('y1', 0)
    .attr('x2', 50)
    .attr('y2', 0)
    .attr('stroke-width', 1)
    .attr('stroke',  function (d) {
        return d.stroke;
    })
;

// put circle into movement
force.on('tick', function(){

    d3.selectAll('circle')
        .each(collide(.5))
        .attr('cx', function (d) {

            // boundaries
            if(d.x <= d.r) {
                d.x = d.r + 1;
            }
            if(d.x >= containerWidth - d.r) {
                d.x = containerWidth - d.r - 1;
            }
            return d.x;
        })
        .attr('cy', function (d) {

            // boundaries
            if(d.y <= d.r) {
                d.y = d.r + 1;
            }
            if(d.y >= containerHeight - d.r) {
                d.y = containerHeight - d.r - 1;
            }
            return d.y;
        });

    d3.selectAll('line')
        .attr('x1', function (d) {
            return d.x - d.r + 10;
        })
        .attr('y1', function (d) {
            return d.y;
        })
        .attr('x2', function (d) {
            return d.x + d.r - 10;
        })
        .attr('y2', function (d) {
            return d.y;
        });

    d3.selectAll('.text')
        .attr('x', function (d) {
            return d.x;
        })
        .attr('y', function (d) {
            return d.y - 10;
        });

    d3.selectAll('.category')
        .attr('x', function (d) {
            return d.x;
        })
        .attr('y', function (d) {
            return d.y + 20;
        });
});

// animate
var interval = setInterval(function(){

    // moving of the circles
    // ...

}, 5 * 1000);

However I am now facing problem with animation. I cannot figure out how can I animate nodes in force diagram. I tried to adjust values of the data object and then invoke .tick() method inside setInterval method, however it didn't help. I am utilizing D3 force layout.

My questions are:

  • How to make the bubbles "float" around the screen, i.e. how to animate them?

  • How to animate changes of circle radius?

Thank you for your ideas.



via Chebli Mohamed

Reverse Engineering hash/encryption function

I have 5 numeric codes. They vary in length (8-10 digits). For each numeric code I have a corresponding alpha-numeric code. The alpha numeric codes are always 8 digits in length.

Now the problem. I know that by some process each numeric code is converted into it's corresponding 8 digit alpha numeric code but I do not know the process used. At first I thought that the alpha-numeric codes may be randomly generated using a seed from the numeric code but that did not seem to work. Now I am thinking that some sort of hashing algorithm is being used to convert the numerics to the alpha-numerics

My question is

1) Can I brute force solve this

2) If yes then what algorithms should I look into that can covert a numeric code to an 8 digit alpha-numeric code

3) Is there some other way to solve this?

Notes: The alpha-numeric codes are not case sensitive. I do not mind if a brute force search returns a few false positives because I will be able to narrow them down myself.

Clarification: I think the first guy misunderstood something. I know the exact values of these numeric and alpha-numeric codes. I simply am not sharing them on the site. I'm not trying to randomly map codes to codes I'm trying to find an algorithm that map my specific codes to the outputs.



via Chebli Mohamed

Neural Networks: What does the input layer consist of?

EDIT2: I added a fourth possibility based on two of the answers below. If I can do so without being rude, may I suggest that any answers that contain modifications to one of the possibilities illustrate their points with the example I have below? After reading each of the answers below several times, I can't help but feel that the four of us in this conversation so far are having four parallel separate conversations, clouded by ambiguous phrasing and terminology. I think illustrating with the example below would go a long way towards unambiguously answering the question so we can upvote a correct and crystal-clear answer for future searchers. Thanks for all the help and time put in so far!

EDIT 3: removed Possibility 4. I will clean up all these edits and make the question presentable once a consensus is reached. Thanks for the help, this community is awesome!

What does the input layer consist of in Neural Networks? What does that layer do?

A similar question is here Neural Networks: Does the input layer consist of neurons? but the answers there did not clear up my confusion.

Like the poster in the question above, I'm confused by the many contradicting things the Internet has to say about the input layer of a basic feed-forward network.

I'll skip the links to contradicting tutorials and articles and list the three possibilities that I can see. Which one (if any) is the correct one?

  1. The input layer passes the data directly to the first hidden layer where the data is multiplied by the first hidden layer's weights.
  2. The input layer passes the data through the activation function before passing it on. The data is then multiplied by the first hidden layer's weights.
  3. The input layer has its own weights that multiply the incoming data. The input layer then passes the data through the activation function before passing it on. The data is then multiplied by the first hidden layer's weights.

Thanks!

EDIT1: Here is an image and an example for further clarity.

Also, I understand that there are many different "correct" implementations, but I am just starting, and am trying to get the basics down before I start working on my own implementations. An as-basic-and-standard-as-possible feed-forward ANN is what I'm looking for!



via Chebli Mohamed

wxPython how to put a text in TextCtrl with a button inserted by "Add" Button

I'm using wxPython to build some GUI... Indeed it isn't an easy program...
Many many user inputs and outputs to be generated...

One part of the program I put an "Add" button that will dynamically add a TextCtrl field and an "Open" button to open a file. After clicking in the "Open" the user can select a file, the file pathway is therefore showed in the TextCtrl field.

Indeed, using a simple example (one TextCtrl one button) I can handle it...
But in a dynamically way, putting several TextCtrl and several Buttons I don't know how to handle it...

In the following code (only a small part of all, some stuff should not be there), I put a "def OpenReadFile" as you can see there after "Open" button click, it will put the text in the last TextCtrl not in the corresponding field... Any ideas?

In another words... Imagine this: Add (the user can Add "n" samples)

"TEXT-1" 'BUTTON-1'
"TEXT-2" 'BUTTON-2'
"TEXT-3" 'BUTTON-3'

if the user click in button-3 for example it will put the text in Text-3 field (as expected)
if the user click in button-2, it will put the text in Text-3...

My code so far (Indeed I know where the mistake is, I just don't know what to d0) =[

self.addButton = wx.Button(self, label="Add Sample")
self.Bind(wx.EVT_BUTTON, self.OnAddWidget, self.addButton)
def OnAddWidget(self, event):
    self.samplenumber += 1
    self.sampleTextCtrl = wx.TextCtrl(self, wx.NewId(), "", size = (200,-1))
    self.buttonF = wx.Button(self, buttonId, label = "Select File") #Add Open File Button
    self.Bind(wx.EVT_BUTTON, self.OpenReadFile, self.buttonF) #Add click event
    self.fgs4.Add(self.buttonF, proportion = 1, flag = wx.CENTER, border = -1)
def OpenReadFile(self,event):
    dlg = wx.FileDialog(self, "Open File",
                os.getcwd(), style = wx.OPEN)

    if dlg.ShowModal() == wx.ID_OK:
        self.filename = dlg.GetPath()
        self.sampleTextCtrl.SetValue(self.filename)

I'm pretty sure that I do have to do some stuff in OpenReadFile =]

EDITED

I've put a dict before, got the button ID and the TextCtrl put it in the dict and done.

my_dict = {}
self.sampleTextCtrl = wx.TextCtrl(self, wx.NewId(), "", size = (200,-1))
value = self.sampleTextCtrl
buttonId = wx.NewId()
self.buttonF = wx.Button(self, buttonId, label = "Select File")

mydict[buttonId] = value

Done



via Chebli Mohamed

XAML Binding in Style Setter using the Binding Path from the target control

I had an interesting request from a client, there were a number challenges involved, the one that I thought would be the easiest, turned out to be the hardest.

The user needs to know that a value has been changed locally, but not yet persisted to the backend store. We solved this with a data trigger on a style declared within each control on the page.

What I would like to do is simplify the XAML using a single Style or a control template, here is a section of the XAML with some of the textboxes:

Edit - To be more specific, I would prefer a solution where the developer doesn't need to know the inner mechanics of how it works (what the field names for the xIsLocal flags are), but simply by the ViewModel implementing a specific interface, (like IDataErrorInfo) I can globally target control styles bound to the states described by the interface.

         <TextBox Text="{Binding ScaleName}" Margin="5,2,5,2" Grid.Row="1" Grid.Column="2">
            <TextBox.Style>
                <Style TargetType="{x:Type TextBox}">
                    <Style.Triggers>
                        <DataTrigger Binding="{Binding ScaleNameIsLocal}" Value="True">
                            <Setter Property="Background" Value="{StaticResource LocalValueBackgroundBrush}" />
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </TextBox.Style>
        </TextBox>
        <TextBox x:Name="nbScaleCap" Text="{Binding ScaleCap}" Grid.Row="3" Grid.Column="0" Margin="5,2,5,2">
            <TextBox.Style>
                <Style TargetType="{x:Type TextBox}">
                    <Style.Triggers>
                        <DataTrigger Binding="{Binding ScaleCapIsLocal}" Value="True">
                            <Setter Property="Background" Value="{StaticResource LocalValueBackgroundBrush}" />
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </TextBox.Style>
        </TextBox>
        <TextBox x:Name="nbTareTol" Text="{Binding TareTol}" Grid.Row="3" Grid.Column="1" Margin="5,2,5,2">
            <TextBox.Style>
                <Style TargetType="{x:Type TextBox}">
                    <Style.Triggers>
                        <DataTrigger Binding="{Binding TareTolIsLocal}" Value="True">
                            <Setter Property="Background" Value="{StaticResource LocalValueBackgroundBrush}" />
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </TextBox.Style>
        </TextBox>

Each property on the View Model has an xxxIsLocal reciprocal property, So the following partial model corresponds to the above example:

string ScaleName { get; set; }
bool ScaleNameIsLocal { get; set; }
string ScaleCap { get; set; }
bool ScaleCapIsLocal { get; set; }
string TareTol { get; set; }
bool TarTolIsLocal { get; set; }

I've played around with using an indexer to get the IsLocal value but struggled with INotifyPropertyChanged implementation, that aside, the bigger issue was how to make a single style with a binding that is based on the path of the content or text binding on the target control instead of the value of the binding result.

I was inspired by the IDataErrorInfo pattern and using the Validation.ErrorTemplate, it looks simple on the surface and such a simple repetitive pattern like this seems like something that WPF should be able to handle without too many issues.

I am not sure how often I will need this exact template, but it's a pattern that I'm sure I'd like to use again, where there is a potential for each property to have multiple states (not just Error) and to apply a different style using the state as a trigger.


I've edited this post because I haven't quite found what I wanted but thanks to Nikkita I am a step closer :)

By using a custom attached property, we can declare the binding to the flag field directly in the control and can now properly define the style triggers in a global style dictionary.

The ViewModel has not changed, but the XML from above is now simplifed:

    <Style TargetType="TextBox" BasedOn="{StaticResource {x:Type TextBox}}">
        <Style.Triggers>
            <Trigger Property="att:IsLocal.Value" Value="True">
                <Setter Property="Background" Value="{StaticResource LocalValueBackgroundBrush}" />
            </Trigger>
        </Style.Triggers>
    </Style>


<TextBox Text="{Binding ScaleName}" Margin="5,2,5,2" Grid.Row="1" Grid.Column="2" att:IsLocal.Value="{Binding ScaleNameIsLocal}"></TextBox>
<TextBox Text="{Binding ScaleCap}" Grid.Row="3" Grid.Column="0" Margin="5,2,5,2" att:IsLocal.Value="{Binding ScaleCapIsLocal}"></TextBox>
<TextBox Text="{Binding TareTol}" Grid.Row="3" Grid.Column="1" Margin="5,2,5,2" att:IsLocal.Value="{Binding TareTolIsLocal}"></TextBox>

My biggest issue with the current solution is that I would still need to edit a lot of existing XAML if I wanted to apply this (or another) interface pattern to existing apps. Even in the current form there are over 20 fields, so that's 20 opportunities to get the binding wrong, or to accidentally skip one.



via Chebli Mohamed

Configure qemu-1.4.2 on CentOS 6.2 with --enable-sdl

I want to install qemu-1.4.2 on my CentOS 6.2. I downloaded the source code, unpacked and ran ./configure --disable-vnc --enable-sdl. Then it prompted it cannot find sdl:

ERROR
ERROR: User requested feature sdl
ERROR: configure was not able to find it
ERROR

Then I installed SDL and SDL-devel packages and ran ./configure again. It still prompted it cannot find sdl. The screenshot showed that I have installed SDL packages, so why it still complains? Please help, I really need qemu to work on my project.

enter image description here



via Chebli Mohamed

Switching between 2 production VMs

At my job we are currently using a simple system to have backup VMs available.

We have 2 VMs, let's call them prod-1 and prod-2. They share the filesystem and home directory. There's a directory, let's call it /flags, and in there are directories for every VM, and there's an empty file called LIVE sitting in one of those directories, indicating which VM is live:

/flags/prod-1/LIVE
/flags/prod-2

The cron is live on both VMs, and we have a script called flagrun.pl that must be used to run all of the cron jobs. It checks to see if there's a file called LIVE in the directory for that VM, and if not it stops, if so it runs the cron job:

* * * * * /flags/flagrun.pl '/path/to/script.sh'

When there's an issue with prod-1, we move the LIVE file to /flags/prod-2, and all following cron jobs are executed on prod-2 instead.

My questions:

  1. Is there a better way to switch between 2 production VMs?
  2. Is there a better way to start running crons on the other VM? Should we write a script that detects when the LIVE file is moved and stop crond on the old VM and start it on the new VM?


via Chebli Mohamed

Using data.table package in R to sum over columns - getting GForce sum(gsum) error

here is a data.table:

Date     colA  colB  colC  .... month    year
01/23/15  2323  2323 2323        january  2015
.......

On this data.table Im trying to: 1) Sum all column values by month and then year 2) In the subset returned I want to exclude the Date column

I have set keys on the DT as follows:

setkey(DT, month, year)

Now Im running this command to achieve the operations listed in steps 1 & 2 above:

DT[ ,lapply(.SD, sum, na.rm=TRUE), by=.(month , year), .SDcols= 2:(length(colnames(DT))-2) ]

I got the above example from this SO post here.

When I run this..... I get the following error:

Error in gsum(`colA`, na.rm = TRUE) : 
  Type 'character' not supported by GForce sum (gsum). Either add the prefix base::sum(.) or turn off GForce optimization using options(datatable.optimize=1)

Im not sure what this means and how to debug it.......

Any assistance would be appreciated. Thanks



via Chebli Mohamed

JQuery Autocomplete function- Selected value doesn't get available in the spring bean class

I am working on replacing a large dropdown ( which makes a performance impact due t browser rendering) with a Jquery autocomplete input box. I can get the autocomplete functionality to work however the selected value doesn't get available in the java bean class. Here my code

<script>

var productionSourceListString =      document.getElementById("hiddenField").value;
var productionSourceListArray = productionSourceListString.split(',');
$(document).ready(function(){
$("#centerForm\\:production_source").autocomplete({ source :  productionSourceListArray, minLength: 3 });   
$( "#centerForm\\:production_source" ).on( "autocompletechange", function()  {$( "#centerForm\\:production_source" ).attr("value",this.value);} );

});
</script>
<h:inputText  id="production_source" style="width:80px; overflow:hidden"   value="#{recurringSplitBean.item.productionSource.description}">
</h:inputText>

<input type="hidden" id="hiddenField" value="#{productionSourceBean.productionSourceList}"/>

Spring Bean Class(To get the list of elements in dropdown and store them in a comma delimited string declared globally)

private String productionSourceList = ""; (GLOBAL)

public void getProductionSourceListAjax(AjaxBehaviorEvent event){

    List<String> localList = new ArrayList<String>();
    Iterator<ProductionSource> iterator = this.getLovItems().iterator();

    while(iterator.hasNext())
    {
        localList.add(iterator.next().getDescription());
    }

    productionSourceList = StringUtils.collectionToCommaDelimitedString(localList);     
}

When I try to access the value in RecurringSplitBean class

if(AppSupport.isEmpty(item.getProductionSource()) || AppSupport.isEmpty(item.getProductionSource().getProductionSourceId())){           
        JsfMessage.addError("production_source","error.value.required");
        return null;
    }

item.getProductionSource().getDescription() is null. However rather than selecting a value from the list provided by the Jquery dropdown if I type a value in the input box the value becomes available in the recurringsplitbean class. Any thoughts ? :)



via Chebli Mohamed

A proper way to implement item editors

For example we have some busines object we want to edit. Editing occures in separate dialog.
Dialog has a ViewModel containing as a property this BusinesObject.
Dialog contains some fields(TextBoxes, ComboBoxes e.t.c.).
What is the best way to implement editing of BusinesObject?

First approatch I have in mind: Create a clone of object. On accepting editings copy value of clone to original one. Is this ok for MVVM? So all my BusinessObject ViewModels have to be IClonable?



via Chebli Mohamed

Using scala play-json 2.4.x, how do I extract the name of a json object into a different object?

Given this json:

{
  "credentials": {
    "b79a2ba2-lolo-lolo-lolo-lololololol": {
      "description": "meaningful description",
      "displayName": "git (meaningful description)",
      "fullName": "credential-store/_/b79a2ba2-lolo-lolo-lolo-lololololol",
      "typeName": "SSH Username with private key"
    }
  },
  "description": "Credentials that should be available irrespective of domain specification to requirements matching.",
  "displayName": "Global credentials (unrestricted)",
  "fullDisplayName": "Credentials » Global credentials (unrestricted)",
  "fullName": "credential-store/_",
  "global": true,
  "urlName": "_"
}

and this scala destination class:

case class JenkinsCredentials(uuid: String, description: String)

How can I create a Reads[JenkinsCredentials] to extract that first object name uuid b79a2ba2-lolo-lolo-lolo-lololololol along with the description?

Following the documentation it'd be something along the lines of this:

implicit val credsReader: Reads[JenkinsCredentials] = (
  (JsPath).read[String] and
    (JsPath \ "description").read[String]
  )(JenkinsCredentials.apply _)

Used with (Json.parse(content) \\ "credentials").validate[Seq[JenkinsCredentials]

But the documentation doesn't discuss anything about extracting the names of the objects as a field used somewhere else...



via Chebli Mohamed

Select test cases in a test suite

Well i want to create a manager to be able to create a test suite with maybe 10 tests cases and be able to choose the tests cases to run, for example:

class Test extends \PHPUnit_Extensions_SeleniumTestCase
{
   constants...
   protected function setUp()
   {
        $this->setBrowser(self::BROWSER);
        $this->setBrowserUrl(self::URL);
   }
   public function testFirst()
   {
        code...
   }
   public function testSecond()
   {
        code...
   }
   public function testThird()
   {
        code...
   }
}

I want to be able to tell to phpunit to just run testSecond and testThird and will not execute testThird.

I have a idea to do this: Creating separated testSuites (classes) one for each test.

There is a better way to do this?

Thanks!



via Chebli Mohamed

Javascript object accessor weirdness

so I've been coming across a weird issue with javascript objects. Maybe it's just a lack of knowledge (relatively newer to JS), or part of the weird world of JS, but here it goes:

Whenever I try to check if an object has some property, ie:

var someObject = {};
var someArray = ['cat', 'cat', 'cat', 'dog', 'dog', 'dog', 'cow', 'horse'];
someArray.some(function(animal, index) {
    if (!someObject[animal]) {
        someObject[animal] = index;
    }
};

now if I'm not mistaken, the expected output of this should be as follows:

someObject = {
    'cat': 0,
    'dog': 3,
    'cow': 6,
    'horse': 7
}

however what I'm getting is:

someObject = {
    'cat': 1,
    'dog': 3,
    'cow': 6,
    'horse': 7
}

wat.

Also, the issue is resolved when I switch to using the following:

someArray.some(function(animal, index) {
     if (!someObject.hasOwnProperty(animal)) {
        someObject[animal] = index;
     }
  });

WAT. Not that it's much an issue since I've figured out the above solution, I'm just curious as to if I'm not understanding how the object[property] feature works? Thanks!



via Chebli Mohamed

Need help in SQL query - Urgent

I have a user database and i need help forming a query. Table = users fields = sign_in_count , last_sign_in_at

These are two queries which gives me following results :-

select *
from users
where last_sign_in_at >= '2015-08-01' and sign_in_count != ''

gives me 131000 rows.

select *
from users
where last_sign_in_at between '2015-05-01' and '2015-09-11' and
      sign_in_count <> ''

gives me 203000 rows.

so the difference of users in 72,000 users who have signed in at least once between 05/15 to 08/15.

I need to know the no of users from these 72k users who have logged in more than once.



via Chebli Mohamed

Using isset from a name of an input

I am not sure if I am going about this correctly. I have a set of checkbox inputs. If someone selects the last check box all_users_check, I want a new form to appear where I will be listing all of the users in a drop down (haven't added the drop down yet). I thought I could do this by using the name of the input, but I am mistaken apparently as I am getting this error..

Fatal error: Cannot use isset() on the result of an expression (you can use "null !== expression" instead)

How else could I structure what I am doing so that if someone checks that option the new form displays?

<form action="">
 <input type="checkbox" name="spectator_check" value=""> Spectators<br>
  <input type="checkbox" name="member_check" value="" checked> Team Members<br>
  <input type="checkbox" name="commissioner_check" value="" checked> Commissioner(s)<br>
  <input type="checkbox" name="all_users_check" value="" checked> Individual User<br>
</form>

<?php
    if(isset(['all_users_check'])) {

?>
<form action="">
  <input type="checkbox" name="spectator_check" value=""> Spectators<br>
  <input type="checkbox" name="member_check" value="" checked> Team Members<br>
  <input type="checkbox" name="commissioner_check" value="" checked> Commissioner(s)<br>
  <input type="checkbox" name="all_users_check" value="" checked> Individual User<br>
</form>

<?  
    }

?>



via Chebli Mohamed

Where are my ko.observable properties?

http://ift.tt/1NmkSdD

thing = {
            id: 3,
            bool: ko.observable(false),
            state: ko.observable('disabled')
        }

I'm in the middle of trying to debug something in a much larger app, and I'm trying to make a simple example of how my app is breaking, and I can't even get my basic objects properties to show up.

Where are my 2 ko.observable properites on each thing object in rows? When I try to use "row.state()" it isn't there, it doesn't exist, as you can see in the stringified "text" in the dom.

Thoughts please.



via Chebli Mohamed

Return by reference to change CodeIgniter database configs

I'm trying change the database config at execution time in CI. I've had a little progress,but here we use 3 database managers: ActiveRecord(native from CI),Lumine(a small and old ORM) and Doctrine. I'll try explain better.

In CI exists a database static config file,called database.php. In that file you put the configs,in a matrix format:

$db['config_group']['username']
$db['config_group']['password']

Well,I had to create a Class to generate and return that configuration. So I found a way that I could change it dinamically:

DatabaseClass

Then in the database.php I call it:

$database = DatabaseManager::initDatabase('address',"user","db");
$active_record = &$database->getActiveRecord();
$active_group  = &$database->getActiveGroup();
$db = &$database->exportConfigCI();

Fine! It makes and exports the config for me. Note that I call it with return by reference. Now,it's the time to change it. I have to make a change in the user of DB,according to the type of user logged. So I build a hook of type post_controller_constructor.

Hook to change DB config

The problem: The reference is lost in the middle of process. No matter how I try,I can't change the values of CI->db object(the object that holds the database attributes). By polymorphism(how I show in the hook) I can do that,but only to ActiveRecord. The others ORM's are based on database.php file. Here I need of return by reference,to change all dependencies linked at database config file.

What I'm missing? It's possible do what I want?



via Chebli Mohamed

I need drop down menu to close after # selection in mobile

In our mobile site we are using a hamburger drop-down menu to navigate to different sections on the mobile home page. Our problem is that the menu does not automatically close afterwards. The user has to click off afterwards to make the drop down hide.

HTML

<div id="menuSlideIn">
                <ul>
                    <li><a href="#item1">About</a></li>
                    <li><a href="#item2">Academics</a></li>
                    <li><a href="#item3">Cost</a></li>
                    <li><a href="#item4">Orientation</a></li>
                    <li><a href="#item5">Student Life</a></li>
                </ul>
            </div> 
<div id="about">
                    <a name="item1></a>
                    <div class="inner">
                        <asp:ContentPlaceHolder ID="ContentPlaceHolder11" runat="server"></asp:ContentPlaceHolder>
                        <div class="toTop black"><a href="#"></a></div>
                    </div>
                </div>

javascript

        $('#menuSlideIn').css("bottom", function () { return (-1 * $('#menuSlideIn').height()); });
        $("#menuSlideIn").toggle("slide");
        $('#menuHamburger').click(function () {
            $("#menuSlideIn").toggle("slide");
        });

css

#menuHamburger{
    float:left;
    padding: 8px 5px;
}
#searchImg {
    float:right;
    padding: 8px 5px;
}
.menuText{
    float:left;
    font-size:24px;
    color: #ffce00;
}
#menuSlideIn{
    height: auto;
    width: auto;
    background: #000;
    position:absolute;
    z-index: 100000;
}
#menuSlideIn li{
    padding: 5px 10px;
}
#menuSlideIn li a{
    color: #fff;
}



via Chebli Mohamed

How to deal with errors so they show up in the google play developer console?

i'm volunteering for an organization building an Android app. We are going to publish a BETA version on google play soon, and there is a section in the google play developer console interface called "Crashes and ANRs" that i'm hoping we can use for finding errors in the app

Now for the question: How can we write the exception handling code inside the app so that it works well together with this section in the google developer console? (Any other useful tips in this context is very welcome, we are looking to find errors using this interface)

For example, is it a good approach to use the Log.d(tag, msg, throwable) method? (Please note the throwable at the end). Can we benefit from a custom exception class or classes?

Kind Regards, Tord



via Chebli Mohamed

Robot framework: looping through kwargs

I have need to take a list of keyword arguments in robot and convert them to a string of the form key=value if the keyword is in a certain list and set key=value if not. In python, it looks like this:

keywords=#list of keywords

def convert(**kwargs):
    s = ''
    for k,v in kwargs.iteritems():
        if k in keywords:
            s = s + '-%s=%s ' % (k,v)
        else:
            s = s + '-set %s=%s ' % (k,v)
    return s

I know this could be simply written as a python keyword, but I'm trying to figure out if it's possible using Robot. I can iterate using :For ${arg} in ${kwargs}, but I'm not sure how it would work to retrieve the keys and values individually.



via Chebli Mohamed

I Need a way to execute a particular function when i press the forward key or the back key in javascript

I need a way to execute a particular function when I press the forward key or the back key in javascript. So that it may work when the forward button is pressed it may execute the function but it should work without taking the input in any type of text box.

I mean it should work on the whole page no matter where I am on the page but if I press the forward button the function should be executed.

I know how to do it by taking an input in a text box by matching the key codes but don't know how to make it work in someway else.



via Chebli Mohamed

Dynamic Thread Pool

I have a long running process that listens to events and do some intense processing.

Currently I use Executors.newFixedThreadPool(x) to throttle the number of jobs that runs concurrently, but depending of the time of the day, and other various factors, I would like to be able to dynamically increase or decrease the number of concurrent threads.

If I decrease the number of concurrent threads, I want the current running jobs to finish nicely.

Is there a Java library that let me control and dynamically increase or decrease the number of concurrent threads running in a Thread Pool ? (The class must implement ExecutorService).

Do I have to implement it myself ?



via Chebli Mohamed

Fair Reentrant Lock C++

I'm working on a program which suffer from starvation when one thread is doing more work than another. Critical section is protected by a reentrant QMutex, which is not fair.

In Java, you can specify a fairness parameter for a lock. Does C++,(or boost libraries) have any fair reentrant lock available? Preferably up to C++11.

I did some research before, there is shared_lock in boost, but I do not need a read/write lock. Just a lock which will guarantee that each thread has equal chances to enter the critical section.

Thank you very much.



via Chebli Mohamed

Difference between \z and \Z and \a and \A in Perl

Can you please tell me the difference between \z and \Z as well as \a and \A in Perl with a simple example ?



via Chebli Mohamed

how to retrieve LogCat data after use Log.d(); statement as we get logcat information earlier

I have just used Log.d(); statement to debug my app and for this I created a filter configuration. I got it working so that it shows the feedback.

But Now I deleted this Log.d(); from my app. But I can't access the Logcat Information as I got earlier. It's not an error. I just want to get my Logcat as I used before Log.d(); statement.

Would anyone tell me how !!!!



via Chebli Mohamed

Create Provider failed

I want to implement my API with:

private boolean setupGameAPI() {
    if (getServer().getPluginManager().getPlugin("GameAPI") != null) {
        System.out.println("GameAPI found");
        RegisteredServiceProvider<GameAPI> GameAPIProvider = getServer().getServicesManager().getRegistration(GameAPI.class);
        if (GameAPIProvider != null) {
            gameapi = GameAPIProvider.getProvider();
            System.out.println("GameAPIProvider found");
        } else {
            System.out.println("GameAPIProvider not found");
        }
        return (gameapi != null);
    } else {
        System.out.println("GameAPI not found");
    }
    return false;
}

The output is:

[16:55:07] [Server thread/INFO]: GameAPI found
[16:55:07] [Server thread/INFO]: GameAPIProvider not found

The question how can I do it so that GameAPIProvider is not null? Maybe I have to add something in my API.



via Chebli Mohamed

Is it possible to return relationships between two objects in SPARQL?

I am a beginner in SPARQL and I would like to know if it is possible to return relationships between two objects. For example I would like to write a SPARQL query which returns the relationship between Thierry Henry and Arsenal in dbpedia.



via Chebli Mohamed

NERDTree with AG.vim after "e" cursor goes to NERDTree - vim

I have NERDTree opened on the default left side, and some vim file on the right side. After I do search with Ag like :Ag! "echo" I get results in the quickfix window. I chose one of the results and by pressing "e" it opens it to the right side and close the quickfix window, but cursor goes to the left side where the NERDTree is located. Is there a way to jump to opened file right after I click "e" and not pressing "ctrl+w" and "l"?



via Chebli Mohamed

How to implement oneway RPC calls via ZeroMQ

In our distributed system there are native and .NET components, there is a broker that acts both as a network topology explorer and as a message router. Transport and serialization is provided by in-house developed component - it's ugly and buggy.

I'm looking for solutions that provide RPC or messaging and also serialization. I don't need AMQP broker, because it would require additional administration of exchanges and queues. Also I don't need persistence for messages in the system - every such message has value only in real-time.

I know that Thrift offers RPC and also serialization - it works for me only partially, because some communication in our system is based on the PUB/SUB pattern, and Thift isn't suitable for this.

Which ZMQ messaging pattern is suitable for oneway (async) calls? Some components in our system do oneway requests (this is not data distribution, so ZMQ PUB/SUB sockets are not suitable here, as I think). ZMQ REQ/REP sockets are not the option too. Maybe some other patterns?



via Chebli Mohamed

Update C# form RichTextBox content (in realtime) with the output of the batch file execution without waiting for the batch command execution to finish

Below is my C# code in the form.

    private void callInfraCommand(string cmd)
    {
        string os_name = GetOSFriendlyName();
        var m_command = new System.Diagnostics.Process();

        // set up output redirection
        m_command.StartInfo.RedirectStandardOutput = true;
        m_command.StartInfo.RedirectStandardError = true;
        m_command.StartInfo.CreateNoWindow = true;
        m_command.StartInfo.UseShellExecute = false;
        m_command.StartInfo.CreateNoWindow = true;
        m_command.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
        m_command.EnableRaisingEvents = true;

        // see below for output handler
        m_command.ErrorDataReceived += proc_DataReceived;
        m_command.OutputDataReceived += proc_DataReceived;

        if (os_name.Contains("Windows 7") || os_name.Contains("2008") || os_name.Contains("Windows 8") || os_name.Contains("2012"))
            m_command.StartInfo.FileName = @"C:\windows\system32\cmd.exe";
        else
            m_command.StartInfo.FileName = @"C:\WINNT\system32\cmd.exe";

        m_command.StartInfo.Arguments = cmd;
        m_command.Start();

        m_command.BeginErrorReadLine();
        m_command.BeginOutputReadLine();
        m_command.WaitForExit();
    }

    private void proc_DataReceived(object sender, DataReceivedEventArgs e)
    {
        // output will be in string e.Data
        if (e.Data != null)
            this.BeginInvoke(new Action(() => deploy_result_txt.Text += (Environment.NewLine + e.Data)));
    }

I am passing the windows batch file to callInfraComamnd and it's block of code is working fine. But, my batch file is taking more than 5 minutes to finish and during that time, my form is freezing and after the batch process completes it displaying all the output of the batch file in chunk.

Ideally, i would like to see the progress (intermediate output of the batch file) in the TextBox while the batch process is running in the background.

Can anyone please advise how can I resolve it (i am using .NET 4) ?



via Chebli Mohamed

Monodevelop 5.9 (GNU Debugger?)

I recently installed Monodevelop 5.9 under Linux Lite 2.6 (Ubuntu 14.04 variant), and can't seem to find the proper monodevelop-debugger-gbd package to install for C/C++ debugging.

The only one Synaptic is showing me is for version Monodevelop 4.0, and I can't seem to locate any information on the proper PPA to use for a compatible 5.9 debugger (Synaptic won't let me install the older debugger).

I really don't want to roll back to Monodevelop 4.0, and currently, I can't debug any C/C++ code, can anyone point me in the right direction?



via Chebli Mohamed

mardi 4 août 2015

How do i use void with methods in Java?

public String firstMethod() {
    System.out.println("Hello!");
    return 'Done!';
}

and

public void secondMethod() {
    System.out.println("Hello!");
    return 'Done!';
}

Please, don't tell me "Void returns a value". Where does it return, how, and why do i need to use this? How can it be benefit from using?

Export Function in Display Tag

I am working on one migration project(Struts --> Spring MVC) but without changing the UI parts. The place where I stuck is my table using Display Tag. I am using Display tag to show data in tabular format like below.

<display:table style="width:100%" name="sessionScope.list" id="listID" export="true" sort="list" pagesize="20" defaultorder="ascending">
    <display:column property="rowNumber" title="#"/>
    <display:column property="issuerName" title="Issuer Name" sortable="true" paramId="in" paramProperty="issuerName" />
    <display:column property="contractNumber" title="Contract Number" sortable="true"/>
    <display:column property="ip" title="IP" sortable="true"/>
    <display:column property="maturityDate" title="Maturity Date" sortable="true"/>
</display:table>

As we know marking export="true" gives us "Export options" with options like CSV, Excel, XML.

My problem is, the link that is generated on each options is like below

http://localhost:8080/myWebApp/WEB-INF/pages/myjsp.jsp?d-445967-e=1&6578706f7274=1

As you can notice, its like jsps path which is inside WEB-INF folder. That can not be accessed from outside. But in my old application this link appears as below.

http://server:port/myAppName/myJspName.jsp?d-445967-e=3&6578706f7274=1

Since this was an Struts application so folder struct was little different where we had JSPs outside

WEB-INF folder.

Same issue I am facing with pagination links.

Thanks

Hibernate JPA Joined Inheritance

I have a project with a part of the data structure made with @Inheritance(strategy = InheritanceType.JOINED). That part of the data structure looks something like this:

enter image description here

The design is based on the thoughts in this article. I'm using Hibernate with JPA2 interface as my datalayer. The structure above has resulted in the following pojo/dao classes (getters and setter omitted):

BaseItem:

@Entity
@Table( name = "base_item" )
@Inheritance(strategy = InheritanceType.JOINED)
public class BaseItemPojo {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private Long id;
}

PhysicalItem:

@Entity
@Table( name = "physical_item" )
public class PhysicalItemPojo extends BaseItemPojo{
}

SomeHardware:

@Entity
@Table( name = "some_hardware" )
public class SomeHardwarePojo extends PhysicalItemPojo{
}

SomeOtherHardware:

@Entity
@Table( name = "some_other_hardware" )
public class SomeOtherHardwarePojo extends PhysicalItemPojo{
}

Here is my issue:

One of my other tables has a reference to the base_item class, and it would make my life a lot easier, if that class loaded either the "some_hardware" or the "some_other_hardware" based on that base_item_id. Hence, I made navigation properties like this on that particular class:

@Entity
@Table( name = "some_navigation_class" )
public class SomeNavigationClassPojo{
    @ManyToOne(optional = false)
    @JoinColumn(name="base_item_id", insertable = false, updatable = false)
    private BaseItemPojo baseItem;

    @ManyToOne
    @JoinColumn(name="base_item_id", insertable = false, updatable = false)
    private PhysicalItemPojo physicalItem;

    @ManyToOne()
    @JoinColumn(name = "base_item_id", insertable = false, updatable = false)
    private SomeHardwarePojo someHardwarePojo;

    @ManyToOne()
    @JoinColumn(name = "base_item_id", insertable = false, updatable = false)
    private SomeOtherHardwarePojo someOtherHardwarePojo;
}

As you might have guessed, the above didn't work. If I try to access a "SomeNavigationClassPojo" that has a related "SomeHardwarePojo" attached to the entity, I get the following error:

java.lang.IllegalArgumentException: Can not set SomeOtherHardwarePojo field SomeNavigationClass.someOtherHardware to SomeHardwarePojo.

For reference, my goal is that if either someHardwarePojo or someOtherHardwarePojo doesn't exist in the database, they should just be set to null, and not tried to be mapped to respective other child of PhysicalItemPojo

Deployed JavaFX Application with embedded JRE not startable on some systems

The Application gets deployed via Java FX Packaging Tools and is bundled with the JRE (8u40, 32bit). The resulting Ant File was extended by us to run unit-tests and stuff like that. Since we want to support custom locations, we don´t use the generated FX-Installer. So the generated bundles/[appname] folder gets zipped and extracted on the target systems. Usually the application runs fine, but on some systems we experience a weird issue.

When the user tries to start the application via generated .exe file, the application does not start. Nothing happens, no runtime errors, no system errors, just nothing at all. The same happens, when I try to start the .jar directly. Unfortunatly the clients have no rights to use the terminal, so I can´t launch the application from there.

The system, where this behavior occurs is Windows 7. For debugging purposes I added a simple Swing frame before starting the application, but this one isn`t starting either. No log-files where created, so I guess the application does not start at all.

Does anyone know if there is any chance to find out, what is going wrong during the start of the application and/or the runtime enviroment?

LDAP Sub Query to fetch SamAccountName from CN

Currently I have this query as mentioned below which returns all users but each user has a parameter called manager which returns "CN=Peder Ellingsen,OU=Users,OU=NO,OU=Countries,DC=xds,DC=xxx,DC=com"

Need the samAccountName instead of the CN above ,need help with LDAP Subquery which can help me to get the SamAccountName directly by modifying the query mentioned below

Wanted to avoid double hits to ldap server just to get the SamAccountName.

(&(objectCategory=person)(objectClass=user)(memberof=cn=MyCompass_NO,OU=Groups,OU=Common,OU=Applications,DC=xds,DC=xxx,DC=com))

ModelAttribute Values are not populating values

I have a form as shown below

    <!DOCTYPE html>
<html>
<%@ taglib uri="http://ift.tt/QfKAz6" prefix="c" %>
<head>
    <meta charset="utf-8" />
    <title>Dealer Details</title>
    <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" />
    <link href="css/app.css" rel="stylesheet" />
    <script src="//code.jquery.com/jquery-2.0.3.min.js"></script>
    <script type="text/javascript">
        function onChange() {
            var value = ($("#jsonTextArea").text());
            alert(value);
            document.getElementById("jsonTextHidden").value = value;
        };
    </script>
</head>
<body class="body-bg">
    <form modelAttribute="jsonString" method="post" action="postHome">
        <div class="container">
            <div class="col-sm-8 col-sm-offset-2">
                <div class="row">
                    <div class="col-md-6 col-md-offset-3">
                        <div class="centerediv">
                            <div class="panel panel-default">
                                <div class="panel-heading">
                                    <h3 class="panel-title">Select Home</h3>
                                </div>
                                <div class="panel-body">
                                    <div class="form-group">
                                        <textarea rows="4" cols="40" name="jsonTextArea"></textarea>
                                    </div>
                                    <input class="btn btn-danger" type="button" value="Cancel">
                                    <input class="btn btn-success" type="submit" value="Ok" onclick="onChange();">
                                    <input type=hidden id="jsonTextHidden" name="jsonTextHiddenField" />
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </form>
</body>
</html>

I have a controller class as shown below.

@Controller
public class HomeController {

    @RequestMapping(value = "/home", method = RequestMethod.GET)
    public String callHomePage() {
        return "home";
    }

    @POST
    @Consumes({MediaType.APPLICATION_XML})
    @RequestMapping(value = "/postHome")
    public ModelAndView postHomeList(@ModelAttribute("jsonString") HomeRequest request, @Context HttpServletRequest servletReq, @Context HttpServletResponse servletRes) {
        ModelAndView mav = null;
        System.out.println(request.getHomeId());
        return mav;
    }

}

In this home.jsp a textarea field is there where I can enter some values ( json string ). After submission the value for request.getHomeId() is coming as null. Can any one help me to solve this issue?

How to format time from Android's TimePicker?

Hi I am currently using a TimePickerDialog to set the time and display it into a text view. However, I am having problems with the formating. This is my code

    TimePickerDialog.OnTimeSetListener time = new TimePickerDialog.OnTimeSetListener() {
    @Override
    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
        if ((hourOfDay >= 1) && (hourOfDay <= 11.59)) {
            hours = hourOfDay;
            am_pm = "AM";
        } else if (hourOfDay >= 12) {
            hours = hourOfDay - 12;
            am_pm = "PM";
        } else if (hourOfDay == 0) {
            hours = 12;
            am_pm = "AM";
        }

        tvScheduleTime.setText(hours + " : " + minute + " " + am_pm);

    }
};

This method works in retrieving AM and PM but the numbering is weird, like 6:08 AM becomes 6:8 AM. How can I make it so that it creates the text HH-MM AM/PM?

ParameterizedAssertionError in JUnit Theory

The following test throws a ParameterizedAssertionError. It seems that both parameters of the test method get the same argument, although they are of different types.

import java.lang.reflect.Field;
import java.util.ResourceBundle;

import org.junit.experimental.theories.DataPoint;
import org.junit.experimental.theories.DataPoints;
import org.junit.experimental.theories.Theories;
import org.junit.experimental.theories.Theory;
import org.junit.runner.RunWith;

@RunWith(Theories.class)
    public class ErrorIDsTest {

    @DataPoints
    public static Field[] errorIDs() {
        return ErrorIDs.class.getDeclaredFields();
    }

    @DataPoint
    public static ResourceBundle bundle = null;

    @Theory
    public void testThatFails(Field field, ResourceBundle bundle) throws Exception {
    }

    interface ErrorIDs {
      public final String Fehler = "ErrorIDs.Fehler";
    }
}

The exception is ParameterizedAssertionError

org.junit.experimental.theories.internal.ParameterizedAssertionError: testThatFails(errorIDs[0], errorIDs[0]) at org.junit.experimental.theories.Theories$TheoryAnchor.reportParameterizedError(Theories.java:183) at org.junit.experimental.theories.Theories$TheoryAnchor$1$1.evaluate(Theories.java:138) ...

I used an example from here ParameterizedAssertionError in Theory but facing exactly the same. It's fixed but I'm not using the same .jar. Is there any other fix to resolve this?

Firebase returning keys of child node in different orders on different devices/Android versions

I am getting a snapspot of the data from my Firebase database to retrieve a users list, but the order of the keys being returned is different depending on the Android version/ device being used.

For demonstrative purposes I have shortened the method, but it is essentially as follows:

public void getUsers(){

Firebase ref = new Firebase("http://ift.tt/1eQ0zaI");

    final Firebase userRef = ref.child("users");

    userRef.addListenerForSingleValueEvent(new ValueEventListener() {

        @Override
        public void onDataChange(DataSnapshot snapshot) {


           snapshot.toString();

                                                           }                                                           
                                                                  });
                           }

It is the data I get from calling toString() on the snapshot object (snapshot.toString()) that changes order.

I have tried it on 4 devices. The 2 running Lollipop (Nexus 7 5.1.1 & Galaxy s4 5.01) return the data in the same order. And the 2 two other devices (HTC Sensation 4.0.3 and Motorola G2 4.4.4) return the data in the same order (but a different order to devices with Lollipop).

There is no difference in the code used, and the data in the database was completely unchanged at the times when I retrieved the snapshots.

Here is the data order on the 4.4.4 and 4.0.3 devices:

DataSnapshot { key = users, value = { 114585619420240714499={userIDOfCUser=114585619420240714499, NameOfCUser=testName, EmailOfCUser=testerfireapp@gmail.com, friends={103902248954972338254={userIDOfFriend=103902248954972338254, NameOfFriend=testName2 }}}

Here is the data order on the 5.1.1 and 5.01 devices:

DataSnapshot { key = users, value = {114585619420240714499={NameOfCUser=testName, userIDOfCUser=114585619420240714499, friends={103902248954972338254={NameOfFriend=testName2 , userIDOfFriend=103902248954972338254}}, EmailOfCUser= testerfireapp@gmail.com}}}

Why is the data being delivered in different orders depending on the android version/device being used? is there another difference I am unaware of ?

Thanks in advance.

NullPointerException in JCodec with .mkv

I want to get all frames from video in jpg. For .mp4 file program works great but for .mkv i got NullPointerException I don't know why. I use JCodec

public static void Frames(File video, String destiny){
    boolean check = true;
    int i = 1;

    while (check == true) {
        try {
            BufferedImage frame = FrameGrab.getFrame(video, i);  //22
            ImageIO.write(frame, "jpg", new File(destiny+"/photo" + i + ".jpg"));
            System.out.println("Now: " + i);
        } catch (ArrayIndexOutOfBoundsException e) {
            check = false;
        }
        catch(JCodecException e){
            e.printStackTrace();
        }
        catch(IOException e){
            e.printStackTrace();
        }
        i++;
    }
}

.

Exception in thread "main" java.lang.NullPointerException
at org.jcodec.api.FrameGrab.<init>(FrameGrab.java:59)
at org.jcodec.api.FrameGrab.getFrame(FrameGrab.java:331)
at Pack.Main.Frames(Main.java:22)
at Pack.Main.main(Main.java:77)

Thanks

How to count number of custom objects in list which have same value for one of its attribute

I am programming in java. Say I have an custom object Item

class Item
{
     Integer id;
     BigDecimal itemNumber;
}

I have list of Items.

List<Item> items = new ArrayList<>();

Now, What is best way in java to know, list of Items contain some Items with same value for itemNumber.

How Can I extract the .dat file(contain image) using java API

HMEFContentsExtractor ext = new HMEFContentsExtractor(new File(winmailFilename));

   File dir = new File(directoryName);
   File rtf = new File(dir, "message.rtf");
   if(! dir.exists()) {
       throw new FileNotFoundException("Output directory " + dir.getName() + " not found");
   }
   HMEFMessage msg = new HMEFMessage(new FileInputStream(winmailFilename));
   msg.getAttachments();

Iterating over a hashmap struts 1.x

Sturts 1.x framework. I'm trying to iterate over a hash map. "blockIdCountMap" is the hashmap which is returned by a getter method in "EquipmentCharacteristicFormBean" bean.

Code in jsp page.

<logic:iterate name="EquipmentCharacteristicFormBean" id="blockIdCountMap" >
        <bean:write name="blockIdCountMap" property="key"/>
        <bean:write name="blockIdCountMap" property="value"/>
</logic:iterate>

ERROR:

Aug 4, 2015 5:18:43 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet login threw exception
javax.servlet.jsp.JspException: Cannot create iterator for this collection
    at org.apache.struts.taglib.logic.IterateTag.doStartTag(IterateTag.java:310)
    at org.apache.struts.taglib.nested.logic.NestedIterateTag.doStartTag(NestedIterateTag.java:123)
    at org.apache.jsp.website.equipment.equipmentCharacteristic_jsp._jspService(equipmentCharacteristic_jsp.java:224)
    at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:723)
    at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:388)
    at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313)
    at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:723)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:646)
    at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:436)
    at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:374)
    at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:302)
    at org.apache.struts.action.RequestProcessor.doForward(RequestProcessor.java:1056)
    at org.apache.struts.action.RequestProcessor.processForwardConfig(RequestProcessor.java:451)
    at org.apache.struts.action.RequestProcessor.processActionForward(RequestProcessor.java:401)
    at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:279)
    at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1420)
    at org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:520)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:643)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:723)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:646)
    at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:436)
    at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:374)
    at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:302)
    at org.apache.struts.action.RequestProcessor.doForward(RequestProcessor.java:1056)
    at org.apache.struts.action.RequestProcessor.processForwardConfig(RequestProcessor.java:451)
    at org.apache.struts.action.RequestProcessor.processActionForward(RequestProcessor.java:401)
    at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:279)
    at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1420)
    at org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:520)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:643)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:723)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at com.railsync.command.filter.RequestMonitorFilter.doFilter(RequestMonitorFilter.java:102)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at com.railsync.command.filter.GZIPFilter.doFilter(GZIPFilter.java:96)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:470)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:861)
    at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:620)
    at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
    at java.lang.Thread.run(Thread.java:655)

How can I animate my binary tree drawing in Java

I am really struggling with a a project that I am working on. The eventual outcome should be an animation that shows algorithms in AVLTrees. I have managed to display a tree using values input by a user. But I am worried that they I have done it may prevent me being able to animate it. Each time a node is added, the entire tree is re drawn (up to a depth of four at the moment), is there a way (I assume after a lot of "if" statements) do gradually animate the new line added, and then have the new node appear? I apologise in advance if this is the worst code ever seen on here, I"m very new to java and struggling a lot!

    package dissV12;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class AnimateNode implements ActionListener {

    NodePane nodePane = new NodePane();
    JButton jb1, jb2, jb3;  
    JTextField tf;

    public static void main(String[] args) {

        AnimateNode animate = new AnimateNode();

    }

    public AnimateNode() {

        JFrame frame = new JFrame("Version12");     
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout(new BorderLayout());

        JPanel jp1 = new JPanel();      

        tf = new JTextField(3);
        jb1 = new JButton("Search");
        jb2 = new JButton("Insert");
        jb3 = new JButton("Delete");
        jb1.addActionListener(this);
        jb2.addActionListener(this);
        jb3.addActionListener(this);
        frame.add(jp1, BorderLayout.SOUTH);
        jp1.add(tf);
        jp1.add(jb1);
        jp1.add(jb2);
        jp1.add(jb3);

        nodePane.setPreferredSize(new Dimension(1000, 600));
        frame.add(nodePane, BorderLayout.CENTER);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        String input = tf.getText();
        int numbInput = (int) ((Double.parseDouble(input)));

        if (e.getSource() == jb1) {

            tf.setText("");
        }

        if (e.getSource() == jb2) {
            nodePane.insert(numbInput);
            tf.setText("");

        }

        if (e.getSource() == jb3) {

            tf.setText("");

        }

    }

}

This next class is where the drawing takes place. So I assume this is where I put the timer??? Beyond that, I have no idea what I'm doing but feel I have read everything on the internet :/

import java.awt.FontMetrics;

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Line2D;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Random;

import javax.swing.JComponent;
import javax.swing.JPanel;
import javax.swing.Timer;


public class NodePane extends JPanel implements ActionListener {

    private Timer t;

    AVLTree12<Integer> tree;
    Node adding;

    public NodePane() {
        tree = new AVLTree12<Integer>();
        adding = null;
        t = new Timer(1000, this);
        t.start();
    }

    public void addingNode(Node n) {
        adding = n;
    }

    public void insert(int n) {
        tree.insert(n);
        tree.updateLevels();        
        Node nd = tree.getNodeSearch(n);
        System.out.println(nd);
        addingNode(nd);
        repaint();
    }

    public void delete(int n){
        if(tree.search(n)){

        }
    }

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2D = (Graphics2D) g.create();
        if (adding != null) {

            Queue<Node> queue = new LinkedList<Node>();
            queue.add(tree.root);

            while (!queue.isEmpty()) {
                Node node = queue.poll();
                int level = node.getLevel();
                if (level == 1) {
                    Point p = paintLevelOne(node, g2D);
                    paintNode(node, p, g2D);
                }

                if (level == 2) {
                    Node parent = node.getParent();
                    if (node.compareTo(parent) > 0) {
                        Point p = paintLevelTwo(node, 2, g2D);
                        paintLine(node, g2D);
                        paintNode(node, p, g2D);
                    }
                    if (node.compareTo(parent) < 0) {
                        Point p = paintLevelTwo(node, 1, g2D);
                        paintLine(node, g2D);
                        paintNode(node, p, g2D);
                    }
                }
                if (level == 3) {
                    Node parent = node.getParent();
                    Node gParent = parent.getParent();
                    if (node.compareTo(parent) < 0 && parent.compareTo(gParent) < 0) {
                        Point p = paintLevelThree(node, 1, g2D);
                        paintLine(node, g2D);
                        paintNode(node, p, g2D);

                    }
                    if (node.compareTo(parent) > 0 && parent.compareTo(gParent) < 0) {
                        Point p = paintLevelThree(node, 2, g2D);
                        paintLine(node, g2D);
                        paintNode(node, p, g2D);

                    }
                    if (node.compareTo(parent) < 0 && parent.compareTo(gParent) > 0) {
                        Point p = paintLevelThree(node, 3, g2D);
                        paintLine(node, g2D);
                        paintNode(node, p, g2D);

                    }
                    if (node.compareTo(parent) > 0 && parent.compareTo(gParent) > 0) {
                        Point p = paintLevelThree(node, 4, g2D);
                        paintLine(node, g2D);
                        paintNode(node, p, g2D);

                    }

                }
                if(level == 4){
                    Node parent = node.getParent();
                    Node gParent = parent.getParent();
                    Node gGParent = gParent.getParent();
                    if (node.compareTo(parent) < 0 && parent.compareTo(gParent) < 0 && gParent.compareTo(gGParent)<0) {
                        Point p = paintLevelFour(node, 1, g2D);
                        paintLine(node, g2D);
                        paintNode(node, p, g2D);

                    }
                    if (node.compareTo(parent) > 0 && parent.compareTo(gParent) < 0 && gParent.compareTo(gGParent)<0) {
                        Point p = paintLevelFour(node, 2, g2D);
                        paintLine(node, g2D);
                        paintNode(node, p, g2D);

                    }
                    if (node.compareTo(parent) < 0 && parent.compareTo(gParent) > 0 && gParent.compareTo(gGParent)<0) {
                        Point p = paintLevelFour(node, 3, g2D);
                        paintLine(node, g2D);
                        paintNode(node, p, g2D);

                    }
                    if (node.compareTo(parent) > 0 && parent.compareTo(gParent) > 0 && gParent.compareTo(gGParent)<0){
                        Point p = paintLevelFour(node, 4, g2D);
                        paintLine(node, g2D);
                        paintNode(node, p, g2D);

                    }
                    if (node.compareTo(parent) < 0 && parent.compareTo(gParent) < 0 && gParent.compareTo(gGParent)>0) {
                        Point p = paintLevelFour(node, 5, g2D);
                        paintLine(node, g2D);
                        paintNode(node, p, g2D);

                    }
                    if (node.compareTo(parent) > 0 && parent.compareTo(gParent) < 0 && gParent.compareTo(gGParent)>0) {
                        Point p = paintLevelFour(node, 6, g2D);
                        paintLine(node, g2D);
                        paintNode(node, p, g2D);

                    }
                    if (node.compareTo(parent) < 0 && parent.compareTo(gParent) > 0 && gParent.compareTo(gGParent)>0) {
                        Point p = paintLevelFour(node, 7, g2D);
                        paintLine(node, g2D);
                        paintNode(node, p, g2D);

                    }
                    if (node.compareTo(parent) > 0 && parent.compareTo(gParent) > 0 && gParent.compareTo(gGParent)>0){
                        Point p = paintLevelFour(node, 8, g2D);
                        paintLine(node, g2D);
                        paintNode(node, p, g2D);

                    }
                }
                Node left = node.getLeft();
                Node right = node.getRight();
                if (left != null) {
                    queue.add(left);
                }
                if (right != null) {
                    queue.add(right);
                }
            }
        }

    }

    public void paintNode(Node n, Point p, Graphics2D g2d) {

        if (n != null) {

            FontMetrics fm = g2d.getFontMetrics();
            int radius = (fm.getHeight()) * 2;

            Ellipse2D circ = new Ellipse2D.Float(p.x, p.y, radius, radius);
            g2d.draw(circ);
            String text = String.valueOf(n.getData());
            int xTextPos = p.x + ((radius - fm.stringWidth(text)) / 2);
            int yTextPos = p.y
                    + (((radius - fm.getHeight()) / 2) + fm.getAscent());

            g2d.drawString(text, xTextPos, yTextPos);
        }
    }

    public void paintLine(Node n, Graphics2D g2d) {
        FontMetrics fm = g2d.getFontMetrics();
        int radius = (fm.getHeight()) * 2;
        Node parent = n.getParent();
        Point p = parent.getLocation();
        int xPar = p.x + (radius/2);
        int yPar = p.y + radius;
        Point pP = new Point(xPar, yPar);

        Point pc = n.getLocation();
        int xC = pc.x+(radius/2);
        int yC = pc.y;
        Point pC = new Point(xC, yC);
        g2d.draw(new Line2D.Float(pP, pC));

    }

    public Point paintLevelOne(Node n, Graphics2D g2d) {
        FontMetrics fm = g2d.getFontMetrics();
        int radius = (fm.getHeight()) * 2;
        int x = (getWidth() / 2) - (radius / 2);
        int y = radius;
        Point p = new Point(x, y);
        n.setLocation(p);
        return p;
    }

    public Point paintLevelTwo(Node n, int l2, Graphics2D g2d) {
        FontMetrics fm = g2d.getFontMetrics();
        int radius = (fm.getHeight()) * 2;
        int x = (l2 * (getWidth() / 3)) - (radius / 2);
        int y = 3 * radius;
        Point p = new Point(x, y);
        n.setLocation(p);
        return p;
    }

    public Point paintLevelThree(Node n, int l3, Graphics g2d) {
        FontMetrics fm = g2d.getFontMetrics();
        int radius = (fm.getHeight()) * 2;
        int x = (l3 * (getWidth() / 5)) - (radius / 2);
        int y = 5 * radius;
        Point p = new Point(x, y);
        n.setLocation(p);
        return p;
    }

    public Point paintLevelFour(Node n, int l4, Graphics g2d){
        FontMetrics fm = g2d.getFontMetrics();
        int radius = (fm.getHeight()) * 2;
        int x = (l4 * (getWidth() / 9)) - (radius / 2);
        int y = 8 * radius;
        Point p = new Point(x, y);
        n.setLocation(p);
        return p;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        // TODO Auto-generated method stub

    }

}

I assume I won't need to show the Node Class and the Tree class.

If anyone can help I would cry much appreciate it :)