How do you query using an "IN" WHERE clause with Zend_Db_Adapter_Mysqli::fetchAll()?

I'm having a strange problem with Zend_Db_Adapter_Mysqli. I need to query multiple items by ID from my database, so I have the following SQL,

SELECT * FROM mytable WHERE id IN (1,2,3)

This query works fine.

I then try and do this programatically with Zend_Db_Adapter_Mysqli,

$sql = 'SELECT * FROM mytable WHERE id IN (?)';
$ids = array(1,2,3);
$result = $adapter->fetchAll($sql, implode(',', $ids));

The problem is for the above PHP I only get back 1 result instead of the expected 3. I've tried just passing the $ids instead of using implode(), but I just get an error.

What am I doing wrong?


jQuery - Don't hide div if I click inside it

I'm trying to keep the current div visible if I click inside it. I want to hide the div only if I click anywhere on the page but the current div.

I already tried e.stopPropagation(); but that breaks other click handlers I have inside the function.

jsFiddle

var filterContainer = $(".js-filter-container");
var pageDocument = $(document);

$(document).on('click', '.js-show-filter', function(e) {
    e.preventDefault();

    var currentFilter = $(this).next(filterContainer);
    currentFilter.toggle().css("z-index", 99);
    filterContainer.not(currentFilter).hide();

    pageDocument.click(function(){
        filterContainer.hide();
    });

    return false;
});


Combining messages from multiple devices

Is there a recommended way in the Azure ecosystem to join the JSON messages sent by two or more separate devices at approximately the same time in order to run them through, for example, an Azure ML webservice.

The goal of this would be running a real time analysis with data coming from multiple devices.

Thank you

Edit :
Perhaps I should have phrased my question better, but I am currently using Azure Stream Analytics in order to capture the data sent from a device to Azure ML, which works fine (from docs.microsoft.com/en-us/azure/iot-hub/…). Now I want to do the same thing but with multiple devices that each send part of the information that Azure ML needs.


Error with Weblogic 10.x while deploying

I am receiving an error while I try to connect my local environment to a Test DB. Deployment of the ear file fails.

Here's the exception stack trace.

####<Sep 5, 2013 5:22:22 PM IST> <Info> <Deployer> <H1-DDM67BS> <AdminServer> <[ACTIVE] ExecuteThread: '0' for queue: 'weblogic.kernel.Default (self-tuning)'> <<WLS Kernel>> <> <> <1378381942855> <BEA-149060> <Module nemo of application NeMo successfully transitioned from STATE_PREPARED to STATE_ADMIN on server AdminServer.>
####<Sep 5, 2013 5:22:24 PM IST> <Warning> <JMSPool> <H1-DDM67BS> <AdminServer> <[ACTIVE] ExecuteThread: '1' for queue: 'weblogic.kernel.Default (self-tuning)'> <<anonymous>> <> <> <1378381944212> <BEA-169808> <There was an error while making the initial connection to the JMS resource named jms/statisticsFactory from the EJB "JMSWriter" inside application "NeMo". The server will attempt the connection again later. The error was javax.jms.JMSException: [JMSPool:169803]JNDI lookup of the JMS connection factory jms/statisticsFactory failed: javax.naming.NameNotFoundException: While trying to lookup 'jms.statisticsFactory' didn't find subcontext 'jms'. Resolved ''; remaining name 'jms/statisticsFactory'>
####<Sep 5, 2013 5:22:26 PM IST> <Info> <Kodo> <H1-DDM67BS> <AdminServer> <[ACTIVE] ExecuteThread: '0' for queue: 'weblogic.kernel.Default (self-tuning)'> <<anonymous>> <BEA1-00003CA049AA50DAD185> <> <1378381946428> <BEA-2004002> <Starting BEA Kodo 4.1.3.1>
####<Sep 5, 2013 5:22:26 PM IST> <Info> <Kodo JDBC> <H1-DDM67BS> <AdminServer> <[ACTIVE] ExecuteThread: '0' for queue: 'weblogic.kernel.Default (self-tuning)'> <<anonymous>> <BEA1-00003CA049AA50DAD185> <> <1378381946474> <BEA-2002382> <[JDBC] Using dictionary class "com.bmw.nemo.business.util.MyOracleDictionary".>
####<Sep 5, 2013 5:22:26 PM IST> <Info> <Kodo JDBC> <H1-DDM67BS> <AdminServer> <[ACTIVE] ExecuteThread: '0' for queue: 'weblogic.kernel.Default (self-tuning)'> <<anonymous>> <BEA1-00003CA049AA50DAD185> <> <1378381946584> <BEA-2002360> <[JDBC] OpenJPA is now connecting to the database in order to figure out what JDBC driver you are using, as OpenJPA must alter its behavior for this database depending on the driver vendor. To avoid this connection, set the DriverVendor value in your org.apache.openjpa.jdbc.DBDictionary configuration property to one of the following values: oracle, oracle92 (for the 9.2 driver), datadirect, datadirect61 (for driver versions <= 3.1), other For example: org.apache.openjpa.jdbc.DBDictionary: oracle(DriverVendor=oracle92)>
####<Sep 5, 2013 5:22:28 PM IST> <Warning> <Kodo> <H1-DDM67BS> <AdminServer> <[ACTIVE] ExecuteThread: '0' for queue: 'weblogic.kernel.Default (self-tuning)'> <<anonymous>> <BEA1-00003CA049AA50DAD185> <> <1378381948783> <BEA-2000012> <[MetaData] Found duplicate query "XXXX.ProjektByWerkJoin" in "class XXXX.ProjektBE". Ignoring.>
####<Sep 5, 2013 5:22:59 PM IST> <Info> <EJB> <H1-DDM67BS> <AdminServer> <[ACTIVE] ExecuteThread: '0' for queue: 'weblogic.kernel.Default (self-tuning)'> <<anonymous>> <BEA1-00003CA049AA50DAD185> <> <1378381979251> <BEA-010051> <EJB Exception occurred during invocation from home: weblogic.ejb.container.internal.StatelessEJBHomeImpl@239c1e7 threw exception: <1.0.0.1.1 nonfatal general error> org.apache.openjpa.persistence.PersistenceException: The transaction is no longer active - status: 'Marked rollback. [Reason=weblogic.transaction.internal.TimedOutException: Transaction timed out after 32 seconds
BEA1-00003CA049AA50DAD185]'. No further JDBC access is allowed within this transaction.
<1.0.0.1.1 nonfatal general error> org.apache.openjpa.persistence.PersistenceException: The transaction is no longer active - status: 'Marked rollback. [Reason=weblogic.transaction.internal.TimedOutException: Transaction timed out after 32 seconds
BEA1-00003CA049AA50DAD185]'. No further JDBC access is allowed within this transaction.
    at org.apache.openjpa.jdbc.sql.DBDictionary.narrow(DBDictionary.java:3849)
    at org.apache.openjpa.jdbc.sql.DBDictionary.newStoreException(DBDictionary.java:3813)
    at org.apache.openjpa.jdbc.sql.SQLExceptions.getStore(SQLExceptions.java:102)
    at org.apache.openjpa.jdbc.sql.SQLExceptions.getStore(SQLExceptions.java:88)
    at org.apache.openjpa.jdbc.sql.SQLExceptions.getStore(SQLExceptions.java:64)
    at org.apache.openjpa.jdbc.kernel.SelectResultObjectProvider.handleCheckedException(SelectResultObjectProvider.java:155)
    at org.apache.openjpa.lib.rop.EagerResultList.<init>(EagerResultList.java:40)
    at org.apache.openjpa.kernel.QueryImpl.toResult(QueryImpl.java:1219)
    at org.apache.openjpa.kernel.QueryImpl.execute(QueryImpl.java:987)
    at org.apache.openjpa.kernel.QueryImpl.execute(QueryImpl.java:796)
    at org.apache.openjpa.kernel.QueryImpl.execute(QueryImpl.java:766)
    at kodo.kernel.KodoQuery.execute(KodoQuery.java:43)
    at org.apache.openjpa.kernel.QueryImpl.execute(QueryImpl.java:762)
    at kodo.kernel.KodoQuery.execute(KodoQuery.java:39)
    at org.apache.openjpa.kernel.DelegatingQuery.execute(DelegatingQuery.java:517)
    at org.apache.openjpa.persistence.QueryImpl.execute(QueryImpl.java:230)
    at org.apache.openjpa.persistence.QueryImpl.getResultList(QueryImpl.java:269)

===============

I have tried all sorts of setting on JTA by increasing the timeouts etc on weblogic console, didn't work.

I have dumped the whole data on my local oracle DB and then connected it works perfectly but it's a tedious job again and again to take the dump from remote DB and dump it on my local DB.

I am not sure why it's not working when I connect to remote DB but locally it works with the same weblogic settings.

Please share your opinions.

-Vishal Nadikudi


Generate C# from H2O Model

I know you can generate Java POJOs from H2O models built in Python or R, but is there a way to build C# dlls or something similar that can run in a .NET environment? I have seen references to this but nothing concrete.


Add a parameter to all ajax calls with method POST made with jQuery

Answer is simular to Adding a general parameter to all ajax calls made with jQuery, but I need to add additional param only for ajax calls with method post:

$.ajax({
  url: url,
  type: "POST",
  data: data,
  success: success,
  dataType: dataType
});

May I achieve this without adding param into all ajax calls directly (editing inplace), i.e. via setup param via some sort of common config?


Get keyboard's superview in ios

I am trying to move keyboard with the uiviewcontroller when the user is trying to go back using edge swipe and keyboard is there on the controller.
So one solution I found is to animate keyboard's superview along with  edge swipe using this function:

animateAlongsideTransitionInView:animation:completion

But for this I need to get superview of the keyboard. So I was adding one dummy inputAccesoryView to it and then using it to get superview. But I do not want to use this method as this seems very brittle. Is there anyway to get reference to directly keyboard or its superview without using inputAccesoryView.
Any help will be appreciated as I am stuck badly on this. Have searched a lot but everywhere it is written to use this inputAccessory method.


JQuery ajax call returns json data - good. How do we grab each piece of data so query can act on it?

Doing an ajax call to a page to grab 5 pieces of data.  3 images as filenames, 2 statuses as numbers 1/0.  End game is to use this data to instruct jquery to change out 3 divs with the images as a result of the ajax call.  So am trying to get a grip on these items to hand them off to a function that will swap out these divs.  Issue thus far is grabbing the data pieces into a format whereby I can manipulate them.  Values to vars....

Return data seems fine.  Formatted correctly.  Actual return example:

[
{"optiontext" : "spin1", "optionvalue" : "brown_anna.jpg"},
{"optiontext" : "spin2", "optionvalue" : "crada_amberly.jpg"},
{"optiontext" : "spin3", "optionvalue" : "ginda_marlins.jpg"},
{"optiontext" : "SID", "optionvalue" : "1"},
{"optiontext" : "HOT", "optionvalue" : "1"}
]

Called by - and just outputting them as a list - How does one obtain this data in distinct pieces  as vars for a future query image swap?

dataType:"json",
    success: function (data) {
        var winns="<ul>";
        $.each(data, function(i,n){
        winns+="<li>"+n["optionvalue"]+"</li>";
        });
        winns+="</ul>";
        $('#message').append(winns);
        }

Any help greatly appreciated - its been days......  Does not have to be JSON data either.  At this point will try anything to get this charity project done.


Can system notes be accessed via web services?

I am developing a Net Suite application based on web services (SuiteTalk). I have learned about the concept of System Notes, which are a journal of changes on all types of objects. Yet, I see no way to access the list of system notes (say last N notes) via web services. Are you aware if this is possible and how? If not, what would be an alternative solution?


Thrift serialization for kafka messages - single topic per struct

I'm planning of using kafka as a persistent log for event sourcing and I'm currently investigating different serialization options.  My focus is currently on using thrift for the serialization and deserialization of messages that I will be storing in kafka.

When using thrift so serialize messages for kafka, the simplest approach appears to be to have a single thrift struct per kafka topic.

Question: Is this a good pattern to follow in practice?  If not, can you please list the disadvantages of following this approach?

Note: If you think this question doesn't meet stackoverflow standards, please help me improve it!


Canvas.captureStream() causes update layer tree to consume a lot of time

The moment we use canvas.captureStream() the performance of the system is reduced with low fps. In the performance tab I can see majority of the time being consumed  by update layer tree. Can someone explain the link between captureStream and update layer tree?


Internet Explorer 7,8 Font Face with Turkish Chars

I am trying to use Open Sans (Turkish version)

I am pretty sure i applied correct syntax. however Turkish character looks different in IE 7,8

IE 9

IE8 and IE7

@font-face {
font-family: 'open_sansregular';
src: url('Fonts/OpenSans-Regular-webfont.eot');
src: url('Fonts/OpenSans-Regular-webfont.eot?#iefix') format('embedded-opentype'),
     url('Fonts/OpenSans-Regular-webfont.woff') format('woff'),
     url('Fonts/OpenSans-Regular-webfont.ttf') format('truetype'),
     url('Fonts/OpenSans-Regular-webfont.svg#open_sansregular') format('svg');
font-weight: normal;
font-style: normal;

}

@font-face {
    font-family: 'open_sanssemibold';
    src: url('Fonts/OpenSans-Semibold-webfont.eot');
    src: url('Fonts/OpenSans-Semibold-webfont.eot?#iefix') format('embedded-opentype'),
         url('Fonts/OpenSans-Semibold-webfont.woff') format('woff'),
         url('Fonts/OpenSans-Semibold-webfont.ttf') format('truetype'),
         url('Fonts/OpenSans-Semibold-webfont.svg#open_sanssemibold') format('svg');
    font-weight: normal;
    font-style: normal;

}

EDIT
This is strange I uploaded example here and it works perfectly. Problem still exist on localhost

I am using VS 2013 and IIS Express 8.0


Is a DBMS (MySQL, SQL Server….) interpreted or compiled?

I mean, in the terms of the SQL queries, Are they compiled or interpreted in a low level?. How it works internally, It is a SQL statement interpreted or compiled?.


Uncaught ReferenceError: height is not defined - Backbone.js

First of all, I am completely new to Backbone.js and I am using this example to learn.

I am trying to get values from a text input and create models from the input. The template should be loaded and the attribute height from each model should be displayed on the same HTML.

I am able to create models and add them to a collection since I see n {length: 105, models: Array[105], _byId: Object} in console.log(Sections). However, (I'm guessing) when I try to load the template, it is giving me the error: 'Uncaught ReferenceError: height is not defined'. I am thinking if I am getting the attributes incorrectly.

Any help would be appreciated! Thank you in advance.

Here is the template:

<script type="text/template" id="section-template">
    <div class="view">
       <label><%- height %></label>
       <label><%- color %></label>
       <a class="destroy"></a>
    </div>
</script>

Model:

var Section = Backbone.Model.extend({
    defaults: function(){
        return {
            height: 200,
            color: ''
        };
    }
});

Model Collection:

var SectionList = Backbone.Collection.extend({
    model: Section,
    localStorage: new Backbone.LocalStorage("sections-backbone")
});
var Sections = new SectionList;

Model View & event action:

var SectionView = Backbone.View.extend({
    tagName:  "li",
    template: _.template($("#section-template").html()),
    initialize: function() {
    },
    render: function() {
        this.$el.html(this.template(this.model.toJSON()));
        return this;
    }
});

Make Application:

var AppView = Backbone.View.extend({
    el: $("#sectionboard"),
    events: {
        "keypress #new-height":  "createOnEnter"
    },
    initialize: function() {
        this.input = this.$("#new-height");
        this.main = $("#main");
        Sections.fetch();
    },
        createOnEnter: function(e) {
         if (e.keyCode != 13) return;
         if (!this.input.val()) return;
         Sections.create({height: this.input.val(), color: '#FFFFFF'});
         this.input.val("");

         console.log(Sections);

         var view = new SectionView({model: Sections});
         this.$("#section-list").append(view.render().el);

      }
});
var App = new AppView;


Java How to access JSON inner child array

I have a JSON that has a similar structure to the one below (end of post). I'm trying to read it from a file and then extract some information. I'd like to get the "times" child and do something with it. I've tried using json.simple and some of the jackson stuff but I keep getting casting/type errors. I'm pretty stuck :/

First I read in the file and it seems to be correctly captured:

JSONParser parser = new JSONParser();
JSONObject data = (JSONObject) parser.parse(new FileReader("test.json"));

I then tried following this: Java JSONObject get children
but get errors org.json.simple.JSONArray cannot be cast to org.json.simple.JSONObject

What I want (think is what I want?) to do is something along the lines create a JSON of the times, and then from there I can make a list of the times/do various operations with them. Or maybe the best approach is to use an ObjectMapper and map it to a matching object?

{
    "id": "ca1b57be-6c38-4976-9050-f9a95a05a38d",
    "name": "some name",
    "results": [
        {
            "name": "https://st-dev.aexp.com/smart-test/v1/test/test",
            "tests": {
                "name": "Body matches string",
                "status": "pass",
                "Response time is less than 200ms": true
            },
            "testPassFailCounts": {
                "Body matches string": {
                    "pass": 100,
                    "fail": 0
                },
                "Response time is less than 200ms": {
                    "pass": 100,
                    "fail": 0
                }
            },
            "times": [
                "48",
                "25",
                "25",
                "28",
                "24",
                "24",
                "35",
                "29",
                "41",
                "28",
                "28",
                "24",
                "31",
                "28",
                "25",
                "27",
                "23",
                "28",
                "44",
                "29",
                "25",
                "23",
                "44",
                "28",
                "22"
            ]
        }
    ]
}

Thanks much for any help!


Trying to compile simple c++ program in make

I am having trouble with make. I installed all of the features that come with cygwin. When I type in make command it says:

make:***No targets specified and no
  makefile found. Stop.

This is really annoying as it's a very simple program.
My make file (Makefile):

# This is a sample file.

all: lab1

lab1: lab1.o
 g++ -Wall lab1.o -o lab1

lab1.o: lab1.cpp
 g++ -Wall -c lab1.cpp -o lab1.o

my program (lab1.cpp):

// This is a sample file written.

#include <iostream>

using namespace std;

int main() {
  cout << "Welcome to CS-240!" << endl;
  return 0;
  }


iOS: in Swift3, in my collectionView, when I scroll downstair, the collectionView comes automatically at the top. How to stop it?

I would like my collectionView to stop in the cell. The problem is that when I scroll downstair, if I release it, it comes automatically at the first position...

I tried with collection.alwaysBounceVertical = true without success...

Here is my code:

override func viewDidLoad() {
        super.viewDidLoad()

        let layout = OrganiserLayout()
        let frameCollection = CGRect(x: self.view.frame.origin.x, y: self.view.frame.origin.y, width: self.view.frame.width, height: self.view.frame.height + 1000)

        let collection = UICollectionView(frame: frameCollection, collectionViewLayout: layout)
        collection.delegate = self
        collection.dataSource = self
        collection.backgroundColor = UIColor.white
        collection.register(OrganiserCollectionViewCell.self, forCellWithReuseIdentifier: "cell")
        self.view.addSubview(collection)
        collection.alwaysBounceVertical = true
        collection.alwaysBounceHorizontal = true
        collection.bounces = true
        collection.isPagingEnabled = false
        collection.isScrollEnabled = true
}
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 15
    }

        func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
            switch section {
            case 0:
                return 40
        }
    }

class OrganiserLayout:UICollectionViewLayout {

    let cellWidth:CGFloat = 100
    var attrDict = Dictionary<IndexPath,UICollectionViewLayoutAttributes>()
    var contentSize = CGSize.zero

    override var collectionViewContentSize : CGSize {
        return self.contentSize
    }

    override func prepare() {
        // Generate the attributes for each cell based on the size of the collection view and our chosen cell width
        if let cv = collectionView {
            let collectionViewHeight = cv.frame.height
            let numberOfSections = cv.numberOfSections
            self.contentSize = cv.frame.size
            self.contentSize.width = cellWidth*CGFloat(numberOfSections)
            for section in 0...numberOfSections-1 {
                let numberOfItemsInSection = cv.numberOfItems(inSection: section)
                let itemHeight = collectionViewHeight/CGFloat(numberOfItemsInSection)
                let itemXPos = cellWidth*CGFloat(section)
                for item in 0...numberOfItemsInSection-1 {
                    let indexPath = IndexPath(item: item, section: section)
                    let itemYPos = itemHeight*CGFloat(item)
                    let attr = UICollectionViewLayoutAttributes(forCellWith: indexPath)
                    attr.frame = CGRect(x: itemXPos, y: itemYPos, width: cellWidth, height: itemHeight)
                    attrDict[indexPath] = attr
                }
            }
        }
    }

    override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        // Here we return the layout attributes for cells in the current rectangle
        var attributesInRect = [UICollectionViewLayoutAttributes]()
        for cellAttributes in attrDict.values {
            if rect.intersects(cellAttributes.frame) {
                attributesInRect.append(cellAttributes)
            }
        }
        return attributesInRect
    }

    override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
        // Here we return one attribute object for the specified indexPath
        return attrDict[indexPath]!
    }

}

class OrganiserCollectionViewCell:UICollectionViewCell {

    var label:UILabel!
    var seperator:UIView!

    override init(frame: CGRect) {
        super.init(frame: frame)

        label = UILabel()
        label.translatesAutoresizingMaskIntoConstraints = false
        self.addSubview(label)

        seperator = UIView()
        seperator.backgroundColor = UIColor.black
        seperator.translatesAutoresizingMaskIntoConstraints = false
        self.addSubview(seperator)

        let views:[String:UIView] = [
            "label":label,
            "sep":seperator
        ]

        let cons = [
            "V:|-20-[label]",
            "V:[sep(1)]|",
            "H:|[label]|",
            "H:|[sep]|"
        ]

        for con in cons {
            self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: con, options: [], metrics: nil, views: views))
        }
    }

I need that because I need the user stops on the cell, and click on it. With that problem, he cannot click on the cells that are downstairs.

Thanks in advance.


What's the best way to show multiple checkboxes for multiple records in ASP.NET

The situation is as follows:

I have a database with many RSS Categories, that in turn have many RSS Feeds. I want to display them in the following fashion:

RSS Category 1
 [ ] Rss Feed 1
 [ ] Rss Feed 2
 [ ] Rss Feed 3

RSS Category 2
 [ ] Rss Feed 1
 [ ] Rss Feed 2
 [ ] Rss Feed 3

Where [ ] represents a checkbox.

So each RSS Feed is pulled out of the database depending on the id of the parent RSS category. I cannot use CheckBoxList as each checkbox must be contained inside an unordered list list item. I need the markup to be semantically correct and cant use the Control Adapters.

I initially imagined two nested repeaters, the outside one databound to a list of RSS Categories from the database which displays the Category header and contains a hidden control with the Category ID, then an inner Repeater with the RSS Feeds for that category.

How do I access the Category id from the hidden field control in the parent repeater so I can look up the correct RSS Feeds?


Is it possible to specify a database and schema within a linqtosql query?

I am using linqtosql to query a database directly (not as am ORM).

I have the following code which works:

var events =
    from e in Events
    select e.EventID;

What I would like to do is expand it to join to a second table within a different database / schema on the same SQL instance. For example:

var events =
    from e in Events
    join p in database2.dbo.People on p.PersonID equals e.PersonID
    select e.EventID;

How would I go about specifying the database / schema within the linq query?


Play sound file when image is clicked

I am not a native HTML programmer, so please don't jump all over me about this simple question.

I have an image that, I am displaying using the following code:

 <img name="track1" src="images/track1.png" width="180" height="180" border="0" id="track1" alt="" />

I want a sound file to be played when that image is clicked. I can make the image a button, but that is messing up the layout of the page for some reason.

I am okay with using any player, but the only thing is that I do not want to display an intrusive player. I just want the user to press the image and hear the music. If he presses another image, the current music needs to stop playing, and a different sound must be played.

Please help! Thanks!


Should I use java.text.MessageFormat for localised messages without placeholders?

We are localising the user-interface text for a web application that runs on Java 5, and have a dilemma about how we output messages that are defined in properties files - the kind used by java.util.Properties.

Some messages include a placeholder that will be filled using java.text.MessageFormat. For example:

search.summary = Your search for {0} found {1} items.

MessageFormat is annoying, because a single quote is a special character, despite being common in English text. You have to type two for a literal single quote:

warning.item = This item''s {0} is not valid.

However, three-quarters of the application's 1000 or so messages do not include a placeholder. This means that we can output them directly, avoiding MessageFormat, and leave the single quotes alone:

help.url = The web page's URL

Question: should we use MessageFormat for all messages, for consistent syntax, or avoid MessageFormat where we can, so most messages do not need escaping?

There are clearly pros and cons either way.

Note that the API documentation for MessageFormat acknowledges the problem and suggests a non-solution:

The rules for using quotes within
  message format patterns unfortunately
  have shown to be somewhat confusing.
  In particular, it isn't always obvious
  to localizers whether single quotes
  need to be doubled or not. Make sure
  to inform localizers about the rules,
  and tell them (for example, by using
  comments in resource bundle source
  files) which strings will be processed
  by MessageFormat.


Turn off error bars in Seaborn Bar Plot

I'm using GridSpec in matplotlib to create a page that has 9 subplots.  One of the subplots is a Seaborn bar plot created with the following code:

import seaborn as sns
sns.barplot(x=df['Time'], y=df['Volume_Count'], ax=ax7)

Is there a way to turn off the vertical error bars of the bar plot?  If not, is it possible to reduce the horizontal width of the bars?

Thanks!


Designing URIs for RESTful Web Services

http://www.filesspecialtours.com/ER.png

To get "agrupaciones" I do:

GET /agrupaciones/

To get "asociados" I do:

GET /agrupaciones/asociados/

How to do to obtains the result of cross two resources?

agrupaciones., asociados.

Any common method for to do it?


Swift push notification received but not popped up

I've added to my app the remote notification feature, I can receive push notifications, but when I receive it, there is no automatic popup displayed.

here it my AppDelegate code:

func application( application: UIApplication,
                  didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
    print("Notification received: \(userInfo)")
    GCMService.sharedInstance().appDidReceiveMessage(userInfo);
    // Handle the received message
    NSNotificationCenter.defaultCenter().postNotificationName(messageKey, object: nil,userInfo: userInfo)

my app is correctly connected to GCM Server, and I receive the following logs while receiving a notification:

Notification received: [collapse_key: do_not_collapse, from: 22334444232]

on the server side, I'm sending a basic Payload such as:

{{"aps":{"alert":"Hello world!","badge":0, "sound": "default"}, "to":"MY_TOKEN_KEY", }

any idea why my app is not treating automatically the notification received ?

EDIT1:

I also tried to change the message payload to match Google's GCM tutorial for IOS:

https://gcm-http.googleapis.com/gcm/send
Content-Type:application/json
Authorization:key=AIzaSyZ-1u...0GBYzPu7Udno5aA

{
  "to" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
  "notification" : {
    "body" : "Hello world",
"title" : "alert data"
}

}

but still just getting didReceiveRemoteNotification function called with the following logs:

Notification received : [aps: {
alert =     {
    body = "Hello world";
    title = "alert data";
};

}, gcm.message_id: 0:1470516999022408%f1xxxxxx....]


datatable fnfilterclear return cannot read property

I'm right now working with jquery datatable + fnfilter by toggle button .

my datatable :

     <table class="table table-bordered table-dataTable display nowrap"  id="mytable" cellspacing="0" width="100%">
            <thead>
            <tr>
                <th>First Name</th>
                <th>Last Name</th>
                <th>Employee Id</th>
                <th>Contact Number</th>
                <th>Status</th>
                <th>Action</th>

            </tr>
            </thead>
            <tfoot>
            <tr>
                <th>First Name</th>
                <th>Last Name</th>
                <th>Employee Id</th>
                <th>Contact Number</th>
                <th class="status">Status</th>
                <th>Action</th>
            </tr>
            </tfoot>
        </table>

my toggle button :

             <div class="btn-group" data-toggle="buttons">
                <label class="btn btn-primary custom-button-width active btn-filter" data-id="all">

                    <input type="radio"  id="option1"  autocomplete="off" checked  >ALL
                </label>
                <label class="btn btn-primary custom-button-width btn-filter" data-id="new">
                    <input type="radio"  id="option2"  autocomplete="off"  >NEW
                </label>
                <label class="btn btn-primary custom-button-width btn-filter" data-id="rejected">
                    <input type="radio"  id="option3"  autocomplete="off"  >REJECTED
                </label>
                <label class="btn btn-primary custom-button-width btn-filter" data-id="approved">
                    <input type="radio"  id="option4"  autocomplete="off"  >APPROVED
                </label>
            </div>

my init file :

    $(document).ready(function ()
{
var oTable = $('#mytable').dataTable({

    "bProcessing": true,
    "serverSide": false,
    "sAjaxSource": base_url ,
    "bJQueryUI": false,
    "pageLength": 2,
    "bLengthChange": false,
    "bFilter": true,
    "bInfo": false,
    "bAutoWidth": false,
    "sPaginationType": "full_numbers",
    "iDisplayStart ": 20,
    "fnInitComplete": function () {
        //oTable.fnAdjustColumnSizing();
    },
    'fnServerData': function (sSource, aoData, fnCallback) {
        $.ajax
        ({
            'dataType': 'json',
            'type': 'GET',
            'url': sSource,
            'data': aoData,
            'success': fnCallback
        });
    },
    "columns": [
        { "data": "fname", 'bSearchable': true  },
        { "data": "lname",'bSearchable': true  },
        { "data": "employee_id" , 'bSearchable': false },
        { "data": "contactno", "bSearchable": true},
        { "data": "status"  , 'bSearchable': true },
        { "data": "action", 'bSearchable': false },
    ]
});

$('.btn-filter').on('click',function () {
     var mydata = $(this).attr("data-id");
    var oTable = $('#mytable').dataTable();

    var tfoot = $('tfoot .status');

   oTable.fnFilter(mydata,tfoot.index());

    if(mydata == "rejected" && "new") {
        $('.approved').hide();
    }

    if(mydata == "all" ) {
        oTable.fnFilterClear();
        $('.approved').hide();
    }

    if(mydata == "approved") {
        $('.approved').show();
    }

} )});

it will return an error when i select "ALL"

Uncaught TypeError: Cannot read property 'oPreviousSearch' of null
    at n.fn.init.jQuery.fn.dataTableExt.oApi.fnFilterClear (fnFilterClear.js:41)

How to fix it?

thank you


How should I configure the Oracle HTTP server to handle PL/SQL page requests?

I am wanting to build an Oracle OFM development environment on Windows 7 (64-bit) to migrate over an existing java/struts and PL/SQL application from OAS10G.  So far I have installed the Oracle Database product (), Java 7, and WebLogic Server (10.3.6 = wls1036_generic).

Have I installed everything I need as far as OFM is concerned?  I can't see how to configure the oracle http server to handle PL/SQL page requests.  I spotted on post that said this can be done through the Oracle Fusion Middleware Control - which should be found at my-domain:7001/em, but that tool doesn't seem to be found.  I only seem to have the WebLogic Server Console (my-domain:7001/console) which has lots of tabs and options but I don't see anything that lets me configure the ohs (Oracle Http Server).  Does the Oracle Http Server (ohs) even get installed as part of the WebLogic installation?

Thanks for any help.  Oracle product installations confuse me.


Cannot exclude pk and model from serializer in django 1.8

I'm trying to get rid of pk and model from the output json object as part of Django serialization. I tried the below code in views.py, but it threw the below error

TypeError: serialize() takes 2 positional arguments but 3 were given.

To solve this, I used @staticmethod as well, but no much use.

Here is the views.py

def get_stats(request):
    if request.method == "POST":
        srch_dropV = request.POST['srch_dropAJ']
    else:
        srch_dropV = ''
    if(srch_dropV == 'Lock'):
        stud = LockBased.objects.all()
    response_data = {}
    response_data['result'] = 'Success'
    serializer = NewSerializer()
    response_data['message'] = serializer.serialize('json', stud)
    return HttpResponse(JsonResponse(response_data), content_type="application/json")

from django.core.serializers.json import Serializer, DjangoJSONEncoder
import json

class NewSerializer(Serializer):
    def end_serialization(self):
        cleaned_objects = []

        for obj in self.objects:
            del obj['pk']
            del obj['model']
            cleaned_objects.append(obj)

        json.dump(cleaned_objects, self.stream, cls=DjangoJSONEncoder, **self.options)

Please help me to identify the issue and fix it.

I'm using Django 1.8 and Python 3.4.


Namespace problem in Struts2 when using Apache Tiles

I have a simple problem when I come to Struts2. I use tiles plugin in my Struts2 project. As all of us know, tiles are used for making templates. We can give namespace for our package in struts.xml, the configuration file :

<package name="demo" namespace="/menu" extends="default">

and I gave namespace attribute to one of my link

<s:url action="hello" namespace="menu" />

All of these worked out well, still I could see my pages, but this time, when I add the above namespace to package definition in struts.xml and s:url, I lost my tiles definition. I lost my tiles template, styles(css) and settings. But without using this namespace, I can access my pages with tiles.

Please help me, where did i go wrong? Thanks in advance.


How can I create 1 route with 2 differents user's access in ASP.NET MVC?

How can I do this: I have on page named "Schedule" and it can be accessed through 2 differente ways:

URL 1- www.bla.com/Admin/Schedule
URL 2- www.bla.com/Schedule

"URL 1" will be accessed by users with Admin previlegies and this View will show some Admin stuff, and users must be LoggedOn.

In the otherhand, "URL 2" will be accessed by users NOT LoggedOn and it will NOT show the admin stuff.

But, they are the same page, just with some differences depending on user's access.

I already have AdminController and I intend to put this "Schedule" View as part of this controller. As result, I know if I type "URL 1" it will work. But, if I type "URL 2"? Will I have to create a "ScheduleController" just to handle this?

I wonder if there is a way to resolve this by Global.asax, configuring the routing... I don't know...

Thanks!!!


fwrite and hiding symbols

I have an application that is used to edit .txt files. It opens the selected file, writes to a file and closes the file. Each file that has to be edited has special characters
e.g. [, ', =, _, ;.`
 that do not have to be edited so they will not be displayed on the web page when file is opened. Between those special characters text exists thats the part that will be edited.What i want to achieve is when the file is opened the special charterer will be hidden and the letters in the file only be displayed and here is the twist what i am trying to achieve is when the file is saved the special charterers will be still in the file with the edited text in there original place. Everything in the file looks like this

['text'] = ['some_,more_text']

Currently i am playing around with explode(); function and str_replace() function
but so far i am only able to remove the special charterers and when the file is saved the characters do not save with the text they are removed.

Is there some function or a method that i massed that can achieve the results i am aiming for any replays are greatly appreciated

I am still going over the php manual but cant find anything close to what i need appart from explode() and str_replace().

here is my code i use this to open my file:

$fileHandle = fopen($relPath, 'r') or die("Failed to open file $relPath go and make me a sandwich! ");

echo '<form action="updatefile.php" method="post">';

while(!feof($fileHandle))
    {
    $line = fgets($fileHandle);
    $lineArr = explode('=', $line);

    if (count($lineArr) !=2){

       continue;
    }
    $part1 = trim($lineArr[0]);
    $part2 = trim($lineArr[1]);

    //$simbols = array("$", "[", "]", "'", ";");

  //echo "<pre>$part1 $part2</pre>";

           echo '<pre><input type="text" name="content_prt1[]" size="50" value="' .str_replace($simbols, "",$part1).'"> <input type="text" name="content_prt2[]" size="50" value="' .str_replace($simbols, "",$part2).'"></pre>';
    }
    echo '<input type="submit" value="Submit" name="submit1">';
    echo '<form />';

  fclose($fileHandle) or die ("Error closing file!");

this is the one that writes to file :

if(isset($_POST['submit1'])){
    ini_set('auto_detect_line_endings', TRUE);

    $file = "test_file_1.php";

    if(is_file($file))
    {
        $handle = fopen($file, "w") or die ("Error opening file! {$file}");
    }
    else
    {
        die($file . ' Dose Not Exist!');
    }

    $content_prt1 = $_POST['content_prt1'];
    $content_prt2 = $_POST['content_prt2'];

    $data = '';

    foreach ($content_prt1 as $key => $value) {
        $data .= $value . " = ". $content_prt2[$key]. PHP_EOL;
    }

    //$file_contents = $_POST["content_prt1" . "content_prt1"];

    fwrite($handle, $data) or die ("Error writing to file {$file}!");
    fclose($handle) or die("Error closing file!");

     header( 'Location:../index.php' ) ;

}


data mining: subset based on maximum criteria of several observations

Consider the example data

Zip_Code <- c(1,1,1,2,2,2,3,3,3,3,4,4)
Political_pref <- c('A','A','B','A','B','B','A','A','B','B','A','A')
income <- c(60,120,100,90,80,60,100,90,200,200,90,110)
df1 <- data.frame(Zip_Code, Political_pref, income)

I want to group_by each $Zip_code and obtain the maximum $income based on each $Political_pref factor.

The desired output is a df which has 8obs of 3 variables. That contains, 2 obs for each $Zip_code (an A and B for each) which had the greatest income

I am playing with dplyr, but happy for a solution using any package (possibly with data.table)

library(dplyr)
df2 <- df1 %>%
  group_by(Zip_Code) %>%
  filter(....)


hadoop log4j not working

My jobs are running successfully with Hadoop 2.6.0 but the logger is not working at all

I always see

log4j:WARN No appenders could be found for logger (org.apache.hadoop.mapreduce.v2.app.MRAppMaster).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.

yarn-site.xml has the directory with the log4j.properties file listed. I also tried passing it manually via -Dlog4j.configuration option.

the file is here: http://www.pastebin.ca/2966941


JAX-RS Struts2 REST API

Why would one like to integrate JAX-RS(Jersey) using Rest API to Struts2? Struts2 is itself a mvc framework, so why would anyone want to integrate these both? If combined, how will the resulting framework be(I wanted to know if REST API just control the controller part of MVC).


hibernate not able to reconnect to the mysql DB

In my spring-hibernate application, we are using org.apache.tomcat.jdbc.pool.DataSource for connection pooling. When we start the server, we are able to see the connection to the DB is established and after the mysql service is stopped the server starts throwing error saying that the connection is lost. When the mysql service is started again, should we have to restart the server to reestablish the connections to the DB? Cuz even after providing autoReconnect=true parameter, the application is not able to establish connection to the DB.


Rest api for yii

I am trying implement REST api in yii by official example, and now I got lot of errors instead of response http://www.taxitaxi.kz/dispatcher/index.php/api/drivers.

Can someone clearify me what is the issue?


Do I need to make any special flask-sslify settings for HTTP Strict Transport?

I am using Flask as my web/app server. I am attempting to SSLify my Flask app to have the best security for HSTS. From some other Stackoverflow comments, I see it is probably best to set SSLify(app, permanent=True) to give 301 response. Do I need to set an age limit, or make any other non-default setting? I am assuming my response header is set with SSLify, or do I need to add the Strict-Transport-Security: max-age, etc to the response header, or does SSLify do this for my Flask App.

Ref:

https://github.com/kennethreitz/flask-sslify/blob/main/README.rst


tkinter frame display basics

I am trying to create an application (well my very first) in Python/tkinter which ultimatively should run on a Raspberry Pi with a a small touchscreen display (480x320px) attached to it. The screen is divided into a mainframe and a frame which (later on) will contain 6 function keys (buttons)

So I started with below code, hoping/expecting that somehow I will get the main application window divided into two frames, one being grey, one being black ... but all I see (on my PC) is the MainApp window in correct size, not resizeable, with correct title (so far so good!) and a yellow background ... it seems the frames I defined inside MainApp are not displayed, even thoough there are Labels inside, they are sticky, they have a weight (and I can't remember what else I tried and where else I searched)

What am I overlooking here please?

#!/usr/bin/python3
import tkinter as tk
#
# main application
#
class MainApp(tk.Frame):
    def __init__(self, parent):
        tk.Frame.__init__(self, parent)
        self.parent = parent
        self.parent.title("My first GUI")
        self.parent.geometry("480x320")
        self.parent.resizable(width=False, height=False)
        self.parent.config(bg="yellow")

        mainframe = tk.Frame(self, bg="grey", width=480, height=280 )
        mainframe.grid(column=0, row=0, sticky="WENS")
        tk.Label(mainframe, text="co-cooo").grid(column=0, row=0, sticky="WENS")

        fkeyframe = tk.Frame(self, bg="black", width=480, height=40)
        fkeyframe.grid(column=0, row=1, sticky="WENS")
        tk.Label(fkeyframe, text="fo-fooo").grid(column=0, row=0, sticky="WENS")

        self.rowconfigure(0, weight=1, minsize=280)
        self.rowconfigure(1, weight=1, minsize=40)
#
# define root element and start application
#
def main():
    root = tk.Tk()
    app = MainApp(root)
    root.mainloop()

#
# start if called from command line
#
if __name__ == '__main__':
    main()

#      0,0   MainApp (yellow)          480,0
#       +---------------------------------+
#       |   mainframe (grey, h=280)       |
#       |+-------------------------------+|
#       ||                               ||
#       ||                               ||
#       ||                               ||
#       |+-------------------------------+|
#       |   fkeyframe  (black, h=40)      |
#       |+-------------------------------+|
#       ||+----+----+----+----+----+----+||
#       ||| Bt | Bt | Bt | Bt | Bt | Bt |||
#       ||+----+----+----+----+----+----+||
#       |+-------------------------------+|
#       +---------------------------------+
#    320,0                             320,480


Is it possible to attach to a remote gdb target with vscode?

I'm trying to setup the configuration to attach to a remote C/C++ gdb target running gdbserver with visual studio code.  Is this currently supported?  If so, how do I get around these limitations:

The address and port options indicate that they aren't supported for C/C++.

I can force code to use the special remote enabled version of gdb, but its trying to run the target application locally and not connecting to the target gdbserver platform.

Will PowerPC remote targets be supported assuming I can solve #1 and #2?


how to insert and replace a list of words in another list or a string in python

I am trying to replace a string with the word [NOUN] on it. I'm clueless!

Here's my code below - which returns lots of errors - the variable story is a string and listOfNouns is a list - so I try and convert the string into a list by splitting it.:

def replacement(story, listOfNouns):
    length = len(story1)
    story1 = story.split()
    for c in range(0,len(story1)):
        if c in listOfNouns:
             story1[c]= 'NOUN'
             story = ''.join(story)
    return story

Here's the error message that I get below when I call the above function with

replacement("Let's play marbles", ['marbles']):

Traceback (most recent call last):
  File "<pyshell#189>", line 1, in <module>
    replacement("Let's play marbels", ['marbels'])
  File "C:/ProblemSet4/exam.py", line 3, in replacement
    length = len(story1)
UnboundLocalError: local variable 'story1' referenced before assignment

How can I replace the new story1 list with another element from another list?

How do I modify the tuples and return the new string - which is supposed to say:

Let's play [NOUN]???

Can anyone please help out? I'm lost and i've been trying this for hours using all the knowledge I have in Python/Java to figure this crap out!


Ruby Sinatra app not storing session variable correctly

I am following a guide on learning Ruby and Sinatra which had me write the following code for a card game (based off of Play Your Cards Right).

Here is the code

enable :sessions

get '/' do
    session[:deck] = []
    suits = %w[ Hearts Diamonds Clubs Spades ]
    values = %w[ Ace 2 3 4 5 6 7 8 9 10 Jack Queen King ]
    suits.each do |suit|
        values.each do |value|
            session[:deck] << "#{value} of #{suit}"
        end
    end
    session[:deck].shuffle!
    session[:guesses] = -1
    redirect to('/play')
end

get '/:guess' do

    card = session[:deck].pop
    value = case card[0]
        when "J" then 11
        when "Q" then 12
        when "K" then 13
        else card.to_i
    end

    if (params[:guess] == 'higher' and value < session[:value]) or (params[:guess] == 'lower' and value > session[:value])
        "Game Over! The card was the #{card} (value #{value}), and you had #{session[:value]}. You managed to make #{session[:guesses]} correct guess#{'opensearch' unless session[:guesses] == 1}. <a href='/'>Play Again</a>"
    else
        session[:guesses] += 1
        session[:value] = value
        "The card is the #{card} (value of #{value}). Do you think the next card will be <a href='/higher'>Higher</a> or <a href='/lower'>Lower</a>?"
    end
end

The game seems to play ok some of the time, however, for some reason, the session variable value seems to be overwritten with a new value before the IF statement executes.

I have no clue what could be wrong with the above code and why the value session variable is changing to a new value randomly when it shouldn't.

Please take a look at my code (or try to run it yourself) and tell me what could be wrong.

My config.ru file:

require 'rubygems'
require 'sinatra'

set :environment, ENV['RACK_ENV'].to_sym
disable :run, :reload

require './play_your_cards_right.rb'

run Sinatra::Application


It's possible to share a cookie between 'some' subdomains?

I've been reading some posts about web performance, one of the points is to

serve static content from a cookie-free domain, my question is:

Can I share cookies between, let's say example.com and www.example.com, while excluding static1.example.com, static2.example.com, etc?

Or do I need to set a different top level domain?

I know (or I think) that I could set the domain of the cookie to '.example.com', but

correct me if I'm wrong this shares the cookies across all sub-domains.


Set font face and size in Scala TextArea

An old thread (2009) mentioned the following:

val area = new TextArea {
   font = new Font("Arial", 0, 8)
}

However that code has no effect on current version of scala.swing  . I also tried

area.peer.setFont(new Font("Arial", 0,8).

That also had no effect. So what is the correct way?


android tcp client file receive

I am trying to send a file (png to be specific) over sockets from python server to android client. I know that my python server is sending the data, I just can't figure out how to receive the data on the android side. Here is what the code looks like to receive the file.

    String path = Environment.getExternalStorageDirectory().toString() +"/tmp/test.png";
        try {
            socket = new Socket("192.168.1.129", 29877);

             is = socket.getInputStream();
             out = new FileOutputStream(path);
            byte[] temp = new byte[1024];
            for(int c = is.read(temp,0,1024); c > 0; c = is.read(temp,0,1024)){
                out.write(temp,0,c);
                Log.d("debug tag", out.toString());
            }
            Log.d("debug tag", temp.toString());

            Bitmap myBitmap = BitmapFactory.decodeByteArray(temp, 0, temp.length);
            imageView.setImageBitmap(myBitmap);

Thanks for any advice.


Duplicate commit on GitHub - Using SmartGit

I use SmartGit o control my repo. When I commited and pushed my project, I had a problem and closed the SmartGit, after that I realized that the operation didn´t finish, then, I did it again, but the first commit was sent. Now I have a duplicate commit on GitHub and cannot do the pull request.

Could you pls help me with this issue.

Pls, keep in mind that I using SmartGi, so, no command line here! =)

Thanks!

Pls, don´t care about the portuguese. I´m from Brazil! =)


How to automate open office online apps

I need to automate excel online functionality that is being used by a web app. How can I automate excel online (open office app integrated with my web app)?  I'm using selenium for my web app..


Tomcat 6.0 does not allow generic ArrayList to be used for useBean

In a jsp file I have this declaration:

<jsp:useBean scope="request" id="products" class="java.util.ArrayList<sgt.supermarket.entity.Product>"/>

This declaration works fine with GlassFish 2.1, however, when I switch to Tomcat 6.0, exceptions is thrown:

The value for the useBean class attribute java.util.ArrayList is invalid.

Is there any library missed for Tomcat that makes it behave different from Glass Fish 2.1?


R: aggregate several colums at once

I am new to R and this is the first time I use stackoverflow so excuse me if I ask for something obvious or my question is not clear enough.

I am working with the following data set

dim(storm)
[1] 883602     39

    names(storm)
   [1] "STATE__"    "BGN_DATE"   "BGN_TIME"   "TIME_ZONE"  "COUNTY"
   [6] "COUNTYNAME" "STATE"      "EVTYPE"     "BGN_RANGE"  "BGN_AZI"
   [11] "BGN_LOCATI" "END_DATE"   "END_TIME"   "COUNTY_END" "COUNTYENDN"
   [16] "END_RANGE"  "END_AZI"    "END_LOCATI" "LENGTH"     "WIDTH"
   [21] "F"          "MAG"        "FATALITIES" "INJURIES"   "PROPDMG"
   [26] "PROPDMGEXP" "CROPDMG"    "CROPDMGEXP" "WFO"        "STATEOFFIC"
   [31] "ZONENAMES"  "LATITUDE"   "LONGITUDE"  "LATITUDE_E" "LONGITUDE_"
   [36] "REMARKS"    "REFNUM"     "PROPTOTAL"  "CROPTOTAL"

I am interested to use EVTYPE (a factor variable) to aggregate 4 other numerical variables (PROPTOTAL, CROPTOTAL, FATALITIES, INJURIES)

The factor variable as 950 levels:

length(unique(storm$EVTYPE))
[1] 950

class(storm$EVTYPE)
[1] "factor"

So I would expect an aggregated data frame with 950 observations and 5 variables when I run the following command:

    storm_tidy<-
aggregate(cbind(PROPTOTAL,CROPTOTAL,FATALITIES,INJURIES)~EVTYPE,FUN=sum,data=storm)

However I get only 155 rows

dim(storm_tidy)
[1] 155   5

I am using the aggregate with several columns following the help page of the function (use cbind):

Formulas, one ~ one, one ~ many, many ~ one, and many ~ many:

aggregate(weight ~ feed, data = chickwts, mean)
aggregate(breaks ~ wool + tension, data = warpbreaks, mean)
**aggregate(cbind(Ozone, Temp) ~ Month, data = airquality, mean)**
aggregate(cbind(ncases, ncontrols) ~ alcgp + tobgp, data = esoph, sum)

I am loosing information at some point:

sum(storm$PROPTOTAL)
[1] 424769204805

sum(storm_tidy$PROPTOTAL)
[1] 228366211339

However, if I aggregate column by column it seems to work fine:

storm_tidy <- aggregate(PROPTOTAL~EVTYPE,FUN = sum, data = storm)
dim(storm_tidy)
[1] 950   2

sum(storm_tidy$PROPTOTAL)
[1] 424769204805

What am I missing? What am I doing wrong?

Thanks.


how do i import postgresql database from a local folder or host directory

I have a .sql file on both my local computer and another one FTP to my host..
There is not tool in phppgdmin to import the file.
What is the easiest to import the data?

i have dedicated hosting, and puTTy terminal.


Which String Converter and When And Why?

I know the title might look little vague but I couldn't come up with something better. So my question is that in my company they are paying close attention to String conversion functions.
And so far I've been dealing with CStr(), Convert.ToString() and ToString() and I need to understand what the difference is between these functions.

They said they were preferring the CStr() and Convert.ToString() and I would like to know why they decided to go with these two?

Is it because ToString() depends on the object?


Getting unknown property: frontend\modules\printinvoice\models\Prodfin::productcode

I'm trying to print an invoice in yii2. There are two tables which I'm touching two tables. One is prodfin - where the totalamount is stored and prodsummary where the products and quantities are stored. Now I want to pass these to my view and print to pdf using mpdf. I am using prodfin as primary model and get prodsummary data attached to it. My main obstacle now is to pass prodsummary details i.e. - productcode, productname, quantity,rate, amount in place row by row. I'm attaching a sample with this.

What I'm trying to achieve -

My Controller Action

public function actionPrintinvoice($id) {
        $model = $this->findModel($id);
        $searchModel  = new ProdfinSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
        $data         = Prodfin::findOne($id);
        $dataProvider = new ActiveDataProvider([
            'query' => Prodsummary::find()->select(['productcode','productname','qty','rate','amount'])->where(['prfinid' => $id]),
            'pagination' => [
            'pageSize' => 20,
                ],
        ]);
        $posts = $dataProvider->getModels();
        $content = $this->renderPartial('_printInvoice', [
            'model' => $model,
            'dataProvider' => $dataProvider,
            'searchModel'  => $searchModel,
            'data'=> $data,

            ]);
        $pdf = new Pdf([
            'mode'=> Pdf::MODE_UTF8,
            'format'=> Pdf::FORMAT_A4,
            'destination'=> Pdf::DEST_BROWSER,
            //'destination' => Pdf::DEST_DOWNLOAD,
            'cssFile' => '@vendor/kartik-v/yii2-mpdf/assets/kv-mpdf-bootstrap.min.css',
            // any css to be embedded if required
            'cssInline' => '.kv-heading-1{font-size:18px}',
             // set mPDF properties on the fly
            'options' => ['title' => 'Print Invoice'],
             // call mPDF methods on the fly
            'methods' => [
                'SetHeader'=>['Private and Confidential'],
                'SetFooter'=>['This Payslip is computer generated.'],
            ],
            'content' => $content,

        ]);
        return $pdf->render();
        //return $this->render('_printSalarystatement', ['s_period' => $s_period]);

    }

My view.php (partialview)

<?php

use yii\helpers\Html;
use yii\widgets\DetailView;

/* @var $this yii\web\View */
/* @var $model frontend\modules\printinvoice\models\Prodfin */

$this->title = $model->prfinslno;
$this->params['breadcrumbs'][] = ['label' => 'Prodfins', 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="ps-details">
    <div style="width:38%; float:left;border:1px solid black;">
            <h3 style="margin-bottom:0;margin-bottom:0;margin-top:2;margin-left:2;"><strong><p class="text-left">M/S. My Company</p></strong></h3>
            <h5 style="margin-bottom:0;margin-top:0;margin-left:2;"><p class="text-left">My details</p></h5>
            <h5 style="margin-bottom:0;margin-top:0;margin-left:2;"><p class="text-left">My Address</p></h5>
    </div>
        <div style="width:61.25%; float:right;border:1px solid black;">
            <table style="width:100%">
            <tr>
                <td>PAN No.</td>
                <td>AGZPD/2365A</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
            </tr>
            <tr>
                <td>Invoice No.</td>
                <td><?php echo $model['invoiceno'];?></td>
                <td>Date : </td>
                <td><?php echo $model['date'];?></td>
            </tr>
            <tr>
                <td>Challan No.</td>
                <td><?php echo $model['challanno'];?></td>
                <td>Date : </td>
                <td><?php echo $model['date'];?></td>
            </tr>
            <tr>
                <td>Order No.</td>
                <td><?php echo $model['orderno'];?></td>
                <td>Date : </td>
                <td><?php echo $model['date'];?></td>
            </tr>
        </table>
        </div>
</div>
<div class="orient-details">
    <div style="width:100%; float:center;border:1px solid black;">
            <h3 style="margin-bottom:0;margin-top:2;margin-left:2;"><strong><p class="text-center">My Company</p></strong></h3>
            <h5 style="margin-bottom:0;margin-top:0;margin-left:2;"><p class="text-center">A Division of My Company</p></h5>
            <h5 style="margin-bottom:0;margin-top:0;margin-left:2;"><p class="text-center">My Address</p></h5>
    </div>
</div>
<div class="product-details">
    <?= DetailView::widget([
    'model' => $model,
    'attributes' => [
        //'id',
        'productcode',
        'productname',
        'qty',
        'rate',
        'amount:ntext'
        //'ativo',
    ],
]) ?>
</div>
<div class="prodfin-view">

    <!-- <h1><?= Html::encode($this->title) ?></h1> -->

<!-- <strong>Using display: inline-block; </strong><br>
    <table style="border:1px solid black;border-collapse:collapse;width:100%" class="inlineTable">
        <tr>
            <td style="border-right: 1px solid";><font face="Calibri";size="72">M/S P.S. Enterprise</font></td>
            <td>This One will contain the Invoice details</td>
        </tr>
    </table> -->
    <?= DetailView::widget([
        'model' => $model,
        'attributes' => [
            'prfinslno',
            'invoiceno',
            'challanno',
            'orderno',
            'amount',
            'date',
        ],
    ]) ?>

</div>

Please let me know how to set the gridview with the details in the middle in picture.

Model Prodfin -

<?php

namespace frontend\modules\printinvoice\models;

use Yii;

/**
 * This is the model class for table "prodfin".
 *
 * @property string $prfinslno
 * @property string $invoiceno
 * @property string $challanno
 * @property string $orderno
 * @property string $amount
 * @property string $date
 */
class Prodfin extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'prodfin';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['date'], 'safe'],
            [['invoiceno', 'challanno', 'orderno', 'amount'], 'string', 'max' => 40],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'prfinslno' => 'Prfinslno',
            'invoiceno' => 'Invoiceno',
            'challanno' => 'Challanno',
            'orderno' => 'Orderno',
            'amount' => 'Amount',
            'date' => 'Date',
        ];
    }
}

Model Prodsummary

<?php

namespace frontend\modules\printinvoice\models;

use Yii;

/**
 * This is the model class for table "prodsummary".
 *
 * @property string $prid
 * @property string $productiondate
 * @property string $invoiceno
 * @property string $challanno
 * @property string $orderno
 * @property string $productcode
 * @property string $productname
 * @property string $unit
 * @property string $qty
 * @property string $rate
 * @property string $amount
 */
class Prodsummary extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'prodsummary';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['productiondate'], 'safe'],
            [['invoiceno', 'challanno', 'orderno'], 'string', 'max' => 40],
            [['productcode', 'amount'], 'string', 'max' => 15],
            [['productname'], 'string', 'max' => 80],
            [['unit', 'qty', 'rate'], 'string', 'max' => 10],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'prid' => 'Prid',
            'productiondate' => 'Productiondate',
            'invoiceno' => 'Invoiceno',
            'challanno' => 'Challanno',
            'orderno' => 'Orderno',
            'productcode' => 'Productcode',
            'productname' => 'Productname',
            'unit' => 'Unit',
            'qty' => 'Qty',
            'rate' => 'Rate',
            'amount' => 'Amount',
        ];
    }
}


ImageMap polygon coordinates shifting to the right in Google Chrome

I have the image below on my website. For the colored states, the image map coordinates are working as expected. I need to add IL state to my map. I've been trying all sorts of poly coordinates but it seems not to be working. I took a screenshot of what the outline looks like when I click it. I've tried in Chrome and FF. Any ideas would be greatly appreciated. Thanks!!

<p><img src="/assets/map.jpg" alt="" border="0" usemap="#StateMap" /></p>
<map name="StateMap">
    <area shape="poly" coords="98,116,124,120,123,132,142,135,136,186,88,178" href="/utah" alt="" />
    <area shape="poly" coords="88,179,79,188,71,232,106,252,127,254,135,186" href="/arizona" alt="" />
    <area shape="poly" coords="347,131,368,129,372,140,376,181,369,205,358,205,333,166" href="/illinois" alt="" />
</map>

EDIT: Here's the CSS. I took it from Chrome's developer window

CSS inline style (I took it out above without realizing that it might matter):

style="padding: 5px; border: 1px solid rgb(221, 221, 221); float: none; margin: 0px;"

CSS:

img{
    height: auto;
    max-width: 100%;
    vertical-align: middle;
}
.span8{
    font-size: 16px;
}
body{
    font-family: 'lato';
    line-height: 1.5;
}


how to use blade Html:: class inside Html:: class in laravel 5.1

I am trying to display an image instead of word "back" to go to previous page how do i do that ?

 {!! Html::linkRoute('authors', Html::image(images/back.png)) !!}


EER diagram in mysql workbench

I'm sorry about my 'nuewbie' question!

I must make EER diagram of my database but I have an question about it because it is not so clear for me. When I connect my database to MySQL Workbench it puts lines only on tables between two tables.. those with FK on them. Now do I need manualy to put the other lines where I don't have FK's because I connect two tables with third middle one?

Also is this EER diagram is logical (conceptual) database or this is physical database? What exactly is logical database? I mean I think I know what is logical database. This is blueprint of the database. But how to describe tables?


C# How Do I Load an image into a code-behind generated table?

I'm using asp.net/c# to create a PDF file that will be downloaded. It's all done in the code behind by creating a series of HTMLTables that load into a div-created HTMLGenericControl.  This div is then converted into a string and passed into the function that generates the PDF file.  Below is a code sample:

//This dataset contains the student's name, age and grade, want it for all sections
List<studentExportPersonal> lsep = sp.getExportPersonal(exportStudents);

//Page Header containg Grade, Student Name, and Age
HtmlGenericControl div = new HtmlGenericControl("div");

foreach (studentExportPersonal sep in lsep)
{
    foreach (string sec in secs)
    {
        HtmlTable identityTable = new HtmlTable();
        div.Controls.Add(identityTable);

        identityTable.Width = "100%";
        identityTable.Border = 0;
        identityTable.Style.Add("margin-bottom", "20px");

        HtmlTableRow identityTR = new HtmlTableRow();
        identityTable.Rows.Add(identityTR);

        HtmlTableCell tdGrade = new HtmlTableCell();
        identityTR.Cells.Add(tdGrade);
        tdGrade.Style.Add("font-size", "30px");
        tdGrade.Align = "center";
        tdGrade.RowSpan = 2;
        tdGrade.InnerText = sep.si.studentGrade;

        HtmlTableCell tdStudentName = new HtmlTableCell();
        identityTR.Cells.Add(tdStudentName);
        tdStudentName.Style.Add("font-size", "30px");
        tdStudentName.Align = "center";
        tdStudentName.InnerText = sep.si.studentName;

        HtmlTableCell tdStudentAge = new HtmlTableCell();
        identityTR.Cells.Add(tdStudentAge);
        tdStudentAge.Style.Add("font-size", "30px");
        tdStudentAge.Align = "center";
        tdStudentAge.RowSpan = 2;
        tdStudentAge.InnerText = sep.si.studentAge + " Years Old";

        HtmlTableRow identityTR1 = new HtmlTableRow();
        identityTable.Rows.Add(identityTR1);

        HtmlTableCell tdPic = new HtmlTableCell();
        identityTR1.Cells.Add(tdPic);

        Bitmap studPic;

        if (HttpContext.Current.Request.IsLocal)
            studPic = (Bitmap)System.Drawing.Image.FromFile(@"C:\studentPics\" + sep.si.studentPicID, true);
        else
            studPic = (Bitmap)System.Drawing.Image.FromFile(@"E:\Website\Cascade\studentPics\" + sep.si.studentPicID, true);
    }
}

export dmc = new export();

var sb = new StringBuilder();
div.RenderControl(new HtmlTextWriter(new StringWriter(sb)));
string s = sb.ToString();

dmc.exportPDF("Student Profiles", "Portrait", s);

At the bottom of the foreach loop you can see that I'm creating a bitmap variable, my question is, how do I load it into the HTMLTableCell variable?


Number of contiguous subarrays in which element of array is max

Given an array of 'n' integers, i need to find for each element of the array, the number of continuous subarrays that have that element as its max element.

Elements can repeat.

Is there a way to do it in less than O(n^2).

O(nlogn) or O(n)?

Example-
If array is {1,2,3}. Then-
For '1': 1 Such subarray {1}.
For '2': 2 Such subarrays {2},{1,2}
For '3': 3 Such subarrays {3},{2,3},{1,2,3}


Is there a way of adding exclusions to Eclipse's "Sort all members"?

In general I like the "Sort all members" feature in Eclipse and have it turned on for the Save Actions.

However, occasionally I'd like to stop it for individual sections, e.g. enumerations. Is there a way of doing this?

Am aware of the "Ignore fields and enum constants" option but not keen on using this as in generally like my fields in alphabetical order. Also know I can undo the change after the first save and then save it again - but don't want to have to remember to do this every time.


stagewebview calling local javascript

friends.

I'm currently developing a flex mobile project. I currently need to load local javascript using stagewebview. Like:

var str:String = '<head>'+
                 '<script src="myLocalJs.js"/>'+
                 '</head><body>...</body>';
webView:StageWebView = new StageWebView();
webView.loadString(str);

Is there any way to load local javascript using StageWebView? I'm not expecting an answer like 'There is a project called StageWebViewBridge' since it does't have all the features I need.
THX!!


Type juggling in function declarations

I'm just playing around here, my code:

<?php

function test(string $str, array $arr = array()) {
    echo $str;
}
test('something');

Which results in:

Catchable fatal error: Argument 1 passed to test() must be an instance of string, string given

I'm curious why I can precede $arr with array without any problems, but I cannot precede $str with string?


Deployd comparison and swift with alamofire

I am trying to query data from my Deployd API with alamofire. How is it possible to do a comparison in a request. I have something like:

let parameters = ["number": ["gt": 3]]
 Manager.sharedInstance.request(.GET, "http://localhost:2403/collections", parameters: parameters).responseJSON { (request, response, result) -> Void in
            print(result.isSuccess)
            print(result.data)
        }

But the result is empty. In my dashboard i have a number column with the values: 1,2,3 and 4. So the response should return me the rows with the number 4.

Any ideas?
Thank


Using Jquery, toggle a replaceWith command to switch between an input

I have a problem I cannot seem to solve.

I have a php and sql function that creates and populates a select drop-down. I need to be able to toggle this with a simple text input. I can use replaceWith() to get from the select drop-down to the text input but I cannot work out how to switch back to the original select drop-down.

 $('.plus').click(function() {
                            var id = $(this).closest('li').find('select').attr('id');
                            $(this).closest('li').find('select').replaceWith('<input class="new_input" type="text" id="' + id + '" />');

                              });

So when .plus is clicked I need it to toggle between the select and input items. I am creating the new input in jquery as I need to dynamically assign the input's id. Any help is greatly appreciated!


Phonegap fixed header and footer

We are developing Phonegap mobile app having fixed header and footer. But if any form elements focus the whole page become scrollable and header and footer losses its position fixed. In Android it is working fine but in iOS we face this problems.

Update :-

Viewport Meta

<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, height=device-height, width=device-width ,target-densityDpi=device-dpi"/>

Application Header

<div data-role="header" id ="Top_content" data-position="fixed" data-tap-toggle="false" data-hide-during-focus="">
    <div id="jqm-homeheader" class="jqm-homeheader" align="center">
        <img src="images/logo.png" align="center">
    </div><!-- Logo closes-->
    <div data-theme="c" data-add-back-btn="true" >
        <div id="search-box1">
            <form action="" onsubmit="custom_search();">
                <input type="search" name="search-product" id="search-product" value="" placeholder="Search" style="width:90%;" data-theme="s" />
            </form>
        </div> <!-- Search Box-->
    </div>
</div>


Make a widget show up has a normal App

How to make a widget show up has a normal App?


r - merge and melt list to data frame

Situation & data

I have a data frame of employees df_employees:

df_employees <- structure(list(empNo = c(1001, 1002, 1003)), .Names = "empNo", row.names = c(NA,
  -3L), class = "data.frame")

> df_employees
  empNo
1  1001
2  1002
3  1003

and a list of skills l_skills

l_skills <- list(c("skill1", "skill2", "skill3"), c("skill1", "skill2"),
             "skill1")

> l_skills
[[1]]
[1] "skill1" "skill2" "skill3"

[[2]]
[1] "skill1" "skill2"

[[3]]
[1] "skill1"

Question

How do I merge and melt the data to give me a resulting dataframe df_result

> df_result
  empNo skills
1  1001 skill1
2  1001 skill2
3  1001 skill3
4  1002 skill1
5  1002 skill2
6  1003 skill1

Attempts

I thought I could use a similar approach to this cSplit function, but I get an error when trying to install cSplit

> install.packages("cSplit")
Installing package into ‘C:/Users/<username>/Documents/R/win-library/3.1’
(as ‘lib’ is unspecified)
Warning in install.packages :
  package ‘cSplit’ is not available (for R version 3.1.2)


compare columns from multiple files with bash command

I have several files, namely a.txt, b.txt, c.txt, d.txt, in the same format (3 columns, separated with tab). Let's take the first 3 lines of a.txt and b.txt for example:

$head -3 a.txt
id_1 59 4
id_4 89 43
id_5 8 90

$head -3 b.txt
id_1 9 4
id_4 39 43
id_5 81 9

c.txt and d.txt are similar to that.

I want to check if the first columns from them are all the same. Is there any easy way in shell to do this?


Python3+Django1.10+mysqlclient1.3.9: cannot save emoji characters

I got the error below in django when saving a field with emoji character in the admin panel.

OperationalError at /admin/core/message/add/
     (1366, "Incorrect string value: '\xF0\x9F\x98\x9E \xF0...' for column 'name' at row 1")

I'm sure the database is ready for utf8mb4, because I can write/read these emoji character in phpmyadmin.

More, the saved emoji character displayed correctly in phpmyadmin but displays ??? in django output.

And in my another django project, the emoji plays well, till I just cannot find the difference between the two environment.

So what can be the problem when I save the same thing using python?

The problem is under django framework, so I want a solution that make django work.


How render calendar events side by side

I don't want to use jQuery, and I'm familiar with fullCalendar but want something that can be used directly in an Angular 2 environment. FullCalendar is great but still depends on jQuery. Obviously it can be done but I can't wrap my head around how to achieve it.

What I want is that, given an array of events with start and end time values, if two or more events overlap in time the rendering of these events in the day view should squeeze them side-ways so that they don't overlap or hide each other.

The content of an event is created server side and controlled by me, thus I can set it up in whatever way is most useful. But say I have starttime, endtime and title params.

Google, Apple and FullCalendar all handle it in their calendar solutions for week and day views but how?


Swift / CloudKit: After record changed, upload triggers "Service Record Changed"

I'm trying to add a CKReference to a record in cloud kit, but the attempt keeps triggering "Service Record Changed". From the console messages my println's have shown (console messages and code below), I'm uploading said record with 0 references, then when I attach the reference I'm seeing an attempt to upload the record with 1 reference. Then I'm getting the error.

As I understand it, "Service Record Changed" shouldn't be triggered because the values in the Reference List have changed (the record has an entire extra field). Even though I'm in development mode, I manually created key-value field for the Reference List, because the first record upload doesn't include the field when the reference list is empty (uploading an empty array causes another error).

I'll include code in order of relevance (you'll be able to see most of the println's) after the console messages. The whole project is on github and I can link to it or include more code if needed.

Relevant Console:

name was set
uploading TestCrewParticipant
with 0 references
if let projects
upload succeeded: TestCrewParticipant
attaching reference
adding TestVoyage:_d147aa657fbf2adda0c82bf30d0e29a9 from guard
references #: Optional(1)
uploading TestCrewParticipant
with 1 references
if let projects
success: 1
uploading TestCrewParticipant
with 1 references
if let projects
success: 1
local storage tested: TestCrewParticipant
u!error for TestCrewParticipant
CKError: <CKError 0x7fcbd05fa960: "Server Record Changed" (14/2004); server message = "record to insert already exists"; uuid = 96377029-341E-487C-85C3-E18ADE1119DF; container ID = "iCloud.com.lingotech.cloudVoyageDataModel">
u!error for TestCrewParticipant
CKError: <CKError 0x7fcbd05afb80: "Server Record Changed" (14/2004); server message = "record to insert already exists"; uuid = 3EEDE4EC-4BC1-4F18-9612-4E2C8A36C68F; container ID = "iCloud.com.lingotech.cloudVoyageDataModel">
passing the guard

Code from CrewParticipant:

/**
 * This array stores a conforming instance's CKReferences used as database
 * relationships. Instance is owned by each record that is referenced in the
 * array (supports multiple ownership)
 */
var references: [CKReference] { return associatedProjects ?? [CKReference]() }

// MARK: - Functions

/**
 * This method is used to store new ownership relationship in references array,
 * and to ensure that cloud data model reflects such changes. If necessary, ensures
 * that owned instance has only a single reference in its list of references.
 */
mutating func attachReference(reference: CKReference, database: CKDatabase) {
print("attaching reference")
    guard associatedProjects != nil else {
print("adding \(reference.recordID.recordName) from guard")
        associatedProjects = [reference]
        uploadToCloud(database)
        return
    }
print("associatedProjects: \(associatedProjects?.count)")
    if !associatedProjects!.contains(reference) {
print("adding \(reference.recordID.recordName) regularly")
        associatedProjects!.append(reference)
        uploadToCloud(database)
    }
}

/**
 * An identifier used to store and recover conforming instances record.
 */
var recordID: CKRecordID { return CKRecordID(recordName: identifier) }

/**
 * This computed property generates a conforming instance's CKRecord (a key-value
 * cloud database entry). Any values that conforming instance needs stored should be
 * added to the record before returning from getter, and conversely should recover
 * in the setter.
 */
var record: CKRecord {
    get {
        let record = CKRecord(recordType: CrewParticipant.REC_TYPE, recordID: recordID)

        if let id = cloudIdentity { record[CrewParticipant.TOKEN] = id }

// There are several other records that are dealt with successfully here.

print("if let projects")
        // Referable properties
        if let projects = associatedProjects {
print("success: \(projects.count)")
            record[CrewParticipant.REFERENCES] = projects
        }

        return record
    }

    set { matchFromRecord(newValue) }
}

generic code (which works for several other classes) where upload occurs:

/**
 * This method uploads any instance that conforms to recordable up to the cloud. Does not check any
 * redundancies or for any constraints before (over)writing.
 */
func uploadRecordable<T: Recordable>
    (instanceConformingToRecordable: T, database: CKDatabase, completionHandler: (() -> ())? = nil) {
print("uploading \(instanceConformingToRecordable.recordID.recordName)")
if let referable = instanceConformingToRecordable as? Referable { print("with \(referable.references.count) references") }
    database.saveRecord(instanceConformingToRecordable.record) { record, error in
        guard error == nil else {
print("u!error for \(instanceConformingToRecordable.recordID.recordName)")
            self.tempHandler = { self.uploadRecordable(instanceConformingToRecordable,
                                                       database: database,
                                                       completionHandler: completionHandler) }
            CloudErrorHandling.handleError(error!, errorMethodSelector: #selector(self.runTempHandler))
            return
        }
print("upload succeeded: \(record!.recordID.recordName)")
        if let handler = completionHandler { handler() }
    }
}

/**
 * This method comprehensiviley handles any cloud errors that could occur while in operation.
 *
 * error: NSError, not optional to force check for nil / check for success before calling method.
 *
 * errorMethodSelector: Selector that points to the func calling method in case a retry attempt is
 * warranted. If left nil, no retries will be attempted, regardless of error type.
 */
static func handleError(error: NSError, errorMethodSelector: Selector? = nil) {

    if let code: CKErrorCode = CKErrorCode(rawValue: error.code) {
        switch code {

        // This case requires a message to USER (with USER action to resolve), and retry attempt.
        case .NotAuthenticated:
            dealWithAuthenticationError(error, errorMethodSelector: errorMethodSelector)

        // These cases require retry attempts, but without error messages or USER actions.
        case .NetworkUnavailable, .NetworkFailure, .ServiceUnavailable, .RequestRateLimited, .ZoneBusy, .ResultsTruncated:
            guard errorMethodSelector != nil else { print("Error Retry CANCELED: no selector"); return }
            retryAfterError(error, selector: errorMethodSelector!)

        // These cases require no message to USER or retry attempts.
        default:
            print("CKError: \(error)")
        }
    }
}


AWS ECS get placement constraint after task creation

I am trying to create a CI build step that will stop and re-run my tasks when my docker containers changed.

The definition itself would be pointing at latest tag in ECR, and so all i need is to stop-task and then run-task.

Two of the parameters in the API as well as the UI are PlacementConstraints and PlacementStrategy.

Is there any way to get these from the API AFTER the task has been started? e.g. get them for a running task. describe-tasks doesn't seem to return this information.


Using ClassLoader when loading .jar resources

I just don't understand why using the ClassLoader causes these two cases to act differently. Can someone explain how/why the ClassLoader changes the search such that it requires a full path into the jar?

package com.example;
import java.io.InputStream;

public class SomeClass {
  private static InputStream stm;
  static {
    for (final String s : new String[] { "file.png", "com/example/file.png", "/com/example/file.png" }) {
      // case 1 - w/o classLoader
      stm = SomeClass.class.getResourceAsStream(s);
      System.out.println("w/o          : " + (stm == null ? "FAILED to load" : "loaded") + " " + s);

      // case 2 - w/ classLoader
      stm = SomeClass.class.getClassLoader().getResourceAsStream(s);
      System.out.println("w/classloader: " + (stm == null ? "FAILED to load" : "loaded") + " " + s);
    }
  }

  public static void main(final String args[]) {}
}

Produces:

w/o          : loaded file.png
w/classloader: FAILED to load file.png
w/o          : FAILED to load com/example/file.png
w/classloader: loaded com/example/file.png
w/o          : loaded /com/example/file.png
w/classloader: FAILED to load /com/example/file.png


Redirect System.in on JTextField and make it wait for user's input

I need to create a GUI for an application.
I redirected the System.out stream on a JTextArea, but I can't redirect the System.in stream on a separate JTextField.

This throws an exception or stop the execution.
In the original app, I asked user's input with:

String reading = new Scanner(System.in).nextLine();

I need to use System.setIn(InputStream).

If I run normally my GUI version, the input was taken from Eclipse console.
I need to recreate that thing in a new "Console" rappresented by a JTextField.

How I can do this without changing the original code? (Sorry for my english!)


DataTables problems PHP

I'm trying to use DataTables server side with the following codes:

Here is the Javascript:

<script>

        $(document).ready( function () {

            $('#table').DataTable({
                "serverSide": true,
                "processing": true,
                "ajax": "{{ $url }}",

                "aoColumns": [
                    { "data": null },
                    { "data": "name" },
                    { "data": "playercount" },
                    { "data": "warswon" },
                    { "data": "warslost" },
                    { "data": "warstied" },
                    { "data": "level"},
                    { "data": "exp"},
                    { "data": "location"},
                    { "data": "warwinpercent"}
                ],

                "fnRowCallback": function( nRow, aData, iDisplayIndex ) {
                    $('td:eq(1)', nRow).html('<a href="/clans/' + aData[1] + '">' +
                            aData[3] + '</a>');
                    return nRow;
                },

                "fnRowCallback": function( nRow, aData, iDisplayIndex ) {
                    var index = iDisplayIndex + 1;
                    $('td:eq(0)', nRow).html(index);
                    return nRow;
                }
            });

            $('#table').dataTable().columnFilter({
                sPlaceHolder: "head:before",
                aoColumns: [null, { type: "text" }, null, null, null, null, null, null, { type: "text" }, null]
            });

        } );
    </script>

And my PHP code for server processing is available here: http://pastebin.com/Wpn9u64U

You can see my live example at: http://clashdata.tk/clans/

The problems are:

It is only showing me 10 records.

Pagination doesn't working.

Search filtering doesn't working.

Order by doesn't work.

What is going on and how come these aren't working as they should?

I've been searching around but can't find anything. Someone said to set serverSide to false but the whole point of this is to use serverSide so I don't have to mass load data on page load.

Here is the serverCode in the post:

<?php

namespace App\Helpers\DataTables;

use PDO;
use PDOException;

ini_set('display_startup_errors',1);
ini_set('display_errors',1);
error_reporting(-1);

class DataTables {

    private $_db;

    public function __construct() {

        try {
            $host               = 'localhost';
            $database           = 'zzzzzzzzzzzz';
            $user               = 'xxxxxxxxxxxx';
            $passwd             = 'yyyyyyyyyyyyy';

            $this->_db = new PDO('mysql:host='.$host.';dbname='.$database, $user, $passwd, array(PDO::ATTR_PERSISTENT => true, PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'"));
        } catch (PDOException $e) {
            error_log("Failed to connect to database: ".$e->getMessage());
        }

    }

    public function utf8ize($d) {
        if (is_array($d)) {
            foreach ($d as $k => $v) {
                $d[$k] = $this->utf8ize($v);
            }
        } else if (is_string ($d)) {
            return utf8_encode($d);
        }
        return $d;
    }

    public function get($table, $index_column, $columns) {

        // Paging
        $sLimit = "";
        if ( isset( $_GET['iDisplayStart'] ) && $_GET['iDisplayLength'] != '-1' ) {
            $sLimit = "LIMIT ".intval( $_GET['iDisplayStart'] ).", ".intval( $_GET['iDisplayLength'] );
        }

        // Ordering
        $sOrder = "";
        if ( isset( $_GET['iSortCol_0'] ) ) {
            $sOrder = "ORDER BY  ";
            for ( $i=0 ; $i<intval( $_GET['iSortingCols'] ) ; $i++ ) {
                if ( $_GET[ 'bSortable_'.intval($_GET['iSortCol_'.$i]) ] == "true" ) {
                    $sortDir = (strcasecmp($_GET['sSortDir_'.$i], 'ASC') == 0) ? 'ASC' : 'DESC';
                    $sOrder .= "`".$columns[ intval( $_GET['iSortCol_'.$i] ) ]."` ". $sortDir .", ";
                }
            }

            $sOrder = substr_replace( $sOrder, "", -2 );
            if ( $sOrder == "ORDER BY" ) {
                $sOrder = "";
            }
        }

        /*
         * Filtering
         * NOTE this does not match the built-in DataTables filtering which does it
         * word by word on any field. It's possible to do here, but concerned about efficiency
         * on very large tables, and MySQL's regex functionality is very limited
         */
        $sWhere = "";
        if ( isset($_GET['sSearch']) && $_GET['sSearch'] != "" ) {
            $sWhere = "WHERE (";
            for ( $i=0 ; $i<count($columns) ; $i++ ) {
                if ( isset($_GET['bSearchable_'.$i]) && $_GET['bSearchable_'.$i] == "true" ) {
                    $sWhere .= "`".$columns[$i]."` LIKE :search OR ";
                }
            }
            $sWhere = substr_replace( $sWhere, "", -3 );
            $sWhere .= ')';
        }

        // Individual column filtering
        for ( $i=0 ; $i<count($columns) ; $i++ ) {
            if ( isset($_GET['bSearchable_'.$i]) && $_GET['bSearchable_'.$i] == "true" && $_GET['sSearch_'.$i] != '' ) {
                if ( $sWhere == "" ) {
                    $sWhere = "WHERE ";
                }
                else {
                    $sWhere .= " AND ";
                }
                $sWhere .= "`".$columns[$i]."` LIKE :search".$i." ";
            }
        }

        // SQL queries get data to display

        $stmt = $this->_db->prepare('SET @rownum = 0');
        $stmt->execute();

        $sQuery = "SELECT SQL_CALC_FOUND_ROWS `".str_replace(" , ", " ", implode("`, `", $columns))."`, @rownum := @rownum+1 AS rank FROM `".$table."` ".$sWhere." ".$sOrder." ".$sLimit;
        $statement = $this->_db->prepare($sQuery);

        // Bind parameters
        if ( isset($_GET['sSearch']) && $_GET['sSearch'] != "" ) {
            $statement->bindValue(':search', '%'.$_GET['sSearch'].'%', PDO::PARAM_STR);
        }
        for ( $i=0 ; $i<count($columns) ; $i++ ) {
            if ( isset($_GET['bSearchable_'.$i]) && $_GET['bSearchable_'.$i] == "true" && $_GET['sSearch_'.$i] != '' ) {
                $statement->bindValue(':search'.$i, '%'.$_GET['sSearch_'.$i].'%', PDO::PARAM_STR);
            }
        }

        $statement->execute();
        $rResult = $statement->fetchAll();

        $iFilteredTotal = current($this->_db->query('SELECT FOUND_ROWS()')->fetch());

        // Get total number of rows in table
        $sQuery = "SELECT COUNT(`".$index_column."`) FROM `".$table."`";
        $iTotal = current($this->_db->query($sQuery)->fetch());

        // Output
        $output = array(
            "draw" => 1,
            "recordsTotal" => $iTotal,
            "recordsFiltered" => $iFilteredTotal,
            "data" => array()
        );

        // Return array of values
        foreach($rResult as $aRow) {
            $row = array();
            for ( $i = 0; $i < count($columns); $i++ ) {
                if ( $columns[$i] == "version" ) {
                    // Special output formatting for 'version' column
                    $row[] = ($aRow[ $columns[$i] ]=="0") ? '-' : $aRow[ $columns[$i] ];
                }
                else if ( $columns[$i] != ' ' ) {
                    $row[] = $aRow[ $columns[$i] ];
                }
            }
            $output['data'][] = $row;
        }

        echo json_encode($this->utf8ize($output));
    }

}

header('Pragma: no-cache');
header('Cache-Control: no-store, no-cache, must-revalidate');

// Create instance of TableData class
$tableData = new DataTables();
$tableData->get('clans', 'id', array('id', 'clanid', 'name'));

?>

UPDATE

I've just noticed that the link the console is fetching new data on when paginating displays the correct data but that data isn't getting put onto the table.


how do i plot time on x-axis in canvas js chart?

i have a values in date time format. I want to show the time on x-axis instead of date.

{"dateTime":"2016-03-16
  07:09:41","value":"41.0"},{"dateTime":"2016-03-16
  07:09:43","value":"43.0"},{"dateTime":"2016-03-16
  07:09:45","value":"45.0"},{"dateTime":"2016-03-16
  07:09:47","value":"47.0"},{"dateTime":"2016-03-16
  07:09:49","value":"49.0"},{"dateTime":"2016-03-16
  07:09:51","value":"51.0"},{"dateTime":"2016-03-16
  07:09:53","value":"53.0"},{"dateTime":"2016-03-16
  07:09:55","value":"55.0"},{"dateTime":"2016-03-16
  07:09:57","value":"57.0"},{"dateTime":"2016-03-16
  07:09:59","value":"59.0"},{"dateTime":"2016-03-16
  07:10:01","value":"1.0"},{"dateTime":"2016-03-16
  07:10:03","value":"3.0"},{"dateTime":"2016-03-16
  07:10:05","value":"5.0"},{"dateTime":"2016-03-16
  07:10:07","value":"7.0"},{"dateTime":"2016-03-16
  07:10:09","value":"9.0"},{"dateTime":"2016-03-16
  07:10:11","value":"11.0"},{"dateTime":"2016-03-16
  07:10:13","value":"13.0"},{"dateTime":"2016-03-16
  07:10:15","value":"15.0"},{"dateTime":"2016-03-16
  07:10:17","value":"17.0"},{"dateTime":"2016-03-16
  07:10:19","value":"19.0"},{"dateTime":"2016-03-16
  07:10:21","value":"21.0"},{"dateTime":"2016-03-16
  07:10:23","value":"23.0"},{"dateTime":"2016-03-16
  07:10:25","value":"25.0"},{"dateTime":"2016-03-16
  07:10:27","value":"27.0"},{"dateTime":"2016-03-16
  07:10:29","value":"29.0"},{"dateTime":"2016-03-16
  07:10:31","value":"31.0"},{"dateTime":"2016-03-16
  07:10:33","value":"33.0"},{"dateTime":"2016-03-16
  07:10:35","value":"35.0"},{"dateTime":"2016-03-16
  07:10:37","value":"37.0"},{"dateTime":"2016-03-16
  07:10:39","value":"39.0"},{"dateTime":"2016-03-16
  07:10:41","value":"41.0"},{"dateTime":"2016-03-16
  07:10:43","value":"43.0"},{"dateTime":"2016-03-16
  07:10:45","value":"45.0"},{"dateTime":"2016-03-16
  07:10:47","value":"47.0"},{"dateTime":"2016-03-16
  07:10:49","value":"49.0"},{"dateTime":"2016-03-16
  07:10:51","value":"51.0"},{"dateTime":"2016-03-16
  07:10:53","value":"53.0"},{"dateTime":"2016-03-16
  07:10:55","value":"55.0"},{"dateTime":"2016-03-16
  07:10:57","value":"57.0"},{"dateTime":"2016-03-16
  07:10:59","value":"59.0"},{"dateTime":"2016-03-16
  07:11:01","value":"1.0"},{"dateTime":"2016-03-16
  07:11:03","value":"3.0"},{"dateTime":"2016-03-16
  07:11:05","value":"5.0"},{"dateTime":"2016-03-16
  07:11:07","value":"7.0"},{"dateTime":"2016-03-16
  07:11:09","value":"9.0"},{"dateTime":"2016-03-16
  07:11:11","value":"11.0"},{"dateTime":"2016-03-16
  07:11:13","value":"13.0"},{"dateTime":"2016-03-16
  07:11:15","value":"15.0"},{"dateTime":"2016-03-16
  07:11:17","value":"17.0"},{"dateTime":"2016-03-16
  07:11:19","value":"19.0"},{"dateTime":"2016-03-16
  07:11:21","value":"21.0"},{"dateTime":"2016-03-16
  07:11:23","value":"23.0"},{"dateTime":"2016-03-16
  07:11:25","value":"25.0"},{"dateTime":"2016-03-16
  07:11:27","value":"27.0"},{"dateTime":"2016-03-16
  07:11:29","value":"29.0"},{"dateTime":"2016-03-16
  07:11:31","value":"31.0"},{"dateTime":"2016-03-16
  07:11:33","value":"33.0"},{"dateTime":"2016-03-16
  07:11:35","value":"35.0"},{"dateTime":"2016-03-16
  07:11:37","value":"37.0"},{"dateTime":"2016-03-16
  07:11:39","value":"39.0"}

Currently i am using canvas js chart.

 <script src="/public/javascript/canvasjs.min.js" type="text/javascript"></script>

<script type="text/javascript">
window.onload = function () {
    var chart = new CanvasJS.Chart("chartContainer",
    {
        title: {
            text: "Date Time Formatting"
        },
        axisX:{
            valueFormatString: "hh:mm:ss" ,
            labelAngle: -50
        },
        axisY: {
          valueFormatString: "#,###"
      },

      data: [
      {
        type: "area",
        color: "rgba(0,75,141,0.7)",
        dataPoints: [

        { x: new Date(07,11,35), y: 0},
        { x: new Date(07,11,29), y: 20 },
        { x: new Date(07,10,53), y: 30 },
        { x: new Date(07,10,31), y: 10}

        ]
    }

    ]
});

chart.render();
}
</script>

<div id="chartContainer" style="height: 300px; width: 100%;">
</div>

its shows only 12.00:00. Please help how can i show the time on x-axis


Is there a way to support HTML5 video tag on non HTML5 compliant browsers?

I am working on HTML5 these days and facing problem in HTML5 video tag. Please help me with suitable answers. Thanks in advance.


Processing and examine user URLs in django

I'm building a website where users are posting content and URLs, very much alike the facebook wall/news feed.

I was thinking that I could take the URL from the user and open it from the server in the django backend and examine the content (just like facebook does).

I thought that there should be a django-opengraph app which helps me to open a URL and check the meta-tags to determine what kind of content etc. But it seems that Open Graph is an invention of Facebook?

My question is how I can open a URL using django and fetch content (video, audio, images, texts) and by determine what kind of content i can embed it properly into my site? Any apps?

And also, I'm intersted in the security aspect of open URLs from the server sent by a user.

Thanks!