Q:

Angular 2 - Setting selected value on dropdown list

I have run into an issue in pre-selecting values on a dropdown list in Angular 2.
I set an array of colours in the component which I bind successfully to the dropdown list. The issue I'm experiencing is with pre-selecting a value on page init.
The line [selected]="car.color.id == x.id" should be selecting the value which has been set on the car model this.car.color = new Colour(-1,''); however this only works when  I set the car colour id to the last item in the list (in this case black) this.car.color = new Colour(4,'');
I am using the latest version of Angular (rc3) and have experienced the same issues in rc1 and rc2.
Here is a plunker showing the issue.
https://plnkr.co/edit/yIVEeLK7PUY4VQFrR48g?p=preview
Another odd aspect is that when looking at the meta data Angular has set the selected value to true.

But the dropdown still appears empty.

It appears to be a seperate issue from these related questions.
Angular 2 Set begin value of select
Binding select element to object in Angular 2
How to use select/option/NgFor on an array of objects in Angular2
Regards
Steve
Component template

        Colour

            <select [(ngModel)]="car.colour"">
                <option *ngFor="let x of colours" [value]="x.id" [selected]="car.color.id == x.id">{{x.name}}</option>
            </select>

Component
import { Component, OnInit } from '@angular/core';
import {AbstractControl,FORM_DIRECTIVES } from '@angular/common';

@Component({
    selector:'dropdown',
    templateUrl:'app/components/dropdown/dropdown.component.html',
    directives:[FORM_DIRECTIVES]
})
export class DropdownComponent implements OnInit
{
    car:Car = new Car();
    colours = Array<Colour>();

    ngOnInit(): void {

        this.colours = Array<Colour>();
        this.colours.push(new Colour(-1, 'Please select'));
        this.colours.push(new Colour(1, 'Green'));
        this.colours.push(new Colour(2, 'Pink'));
        this.colours.push(new Colour(3, 'Orange'));
        this.colours.push(new Colour(4, 'Black'));

        this.car = new Car();
        this.car.color = new Colour(-1,'');
    }
}

export class Car
{
    color:Colour;
}

export class Colour
{
    constructor(id:number, name:string) {
        this.id=id;
        this.name=name;
    }

    id:number;
    name:string;
}

A:

Setting car.colour to the value you want to have initially selected usually works.
When car.colour is set, you can remove [selected]="car.color.id == x.id".
If the value is not a string [ngValue]="..." must be used. [value]="..." only supports strings.

A:

Angular 2 simple dropdown selected value
It may help someone as I need to only show selected value, don't need to declare something in component and etc.
If your status is coming from the database then you can show selected value this way.

    Status
    <select class="form-control" name="status" [(ngModel)]="category.status">
       <option [value]="1" [selected]="category.status ==1">Active</option>
       <option [value]="0" [selected]="category.status ==0">In Active</option>
    </select>

A:

Thanks for the tip Günter, it got me moving in the right direction. There was a mis-matched spelling of 'color' in my solution which was causing issues and I needed to use 'ngValue' not 'value' in the template html.
Here is the complete solution using objects for the ngModel and select list options and avoiding use of the [selected] attribute.
I have updated the Plunker to show the full working solution.
https://plnkr.co/edit/yIVEeLK7PUY4VQFrR48g?p=preview
Component template

        Colour

            <select [(ngModel)]="car.colour">
                <option *ngFor="let x of colours" [ngValue]="x" >{{x.name}}</option>
            </select>

Component
import { Component, OnInit } from '@angular/core';
import {AbstractControl,FORM_DIRECTIVES } from '@angular/common';

@Component({
    selector:'dropdown',
    templateUrl:'app/components/dropdown/dropdown.component.html',
    directives:[FORM_DIRECTIVES]
})
export class DropdownComponent implements OnInit
{
    car:Car;
    colours: Array<Colour>;

    ngOnInit(): void {

        this.colours = Array<Colour>();
        this.colours.push(new Colour(-1, 'Please select'));
        this.colours.push(new Colour(1, 'Green'));
        this.colours.push(new Colour(2, 'Pink'));

        this.car = new Car();
        this.car.colour = this.colours[1];
    }
}

export class Car
{
    colour:Colour;
}

export class Colour
{
    constructor(id:number, name:string) {
        this.id=id;
        this.name=name;
    }

    id:number;
    name:string;
}


Q:

how to make xmonad use two mod keys

I find lots of examples on how to set the mod key in xmonad, but how do I add a second mod key?

A:

You can use xmodmap to add a second key to e.g. Mod1, so that pressing either would work with modMask = mod1Mask.

A:

You can just or the keys together... watch:
$ ghci
> :m + XMonad
> :t (.|.)
(.|.) :: (Data.Bits.Bits a) => a -> a -> a
> :t mod1Mask
mod1Mask :: KeyMask
> :t mod2Mask
mod2Mask :: KeyMask
> :t mod1Mask .|. mod2Mask
mod1Mask .|. mod2Mask :: KeyMask

So as you can see you OR two key masks together to get the result that you desire. That's all it takes so you just use it like the last line there.
myAwesomeModMask = mod1Mask .|. mod3Mask
-- or whatever you want it to be

And that is all that there is to it.
Edit: Ah wait, you want two different keys to independently act as the Mod key. That is currently impossible I think as the code currently stands. Solution: check out the source and edit it yourself and then cabal install it again; it would be a small change.


Q:

Parameters after opening bracket

I am doing my first steps in Vapor, the web framework for Swift.
The first piece of code that called my attention was this:
app.get("welcome") { request in
    return "Hello"
}

I don't understand the syntax here. I mean, I'm calling app.get() method, but I'm also defining some kind of function where request is a parameter. I know that this will result in a get method accessible by a /welcome URL and will return "Hello". What is not clear for me is how this piece of code works and how the compiler interprets it.

A:

This is called trailing closure syntax.
I give a nice rundown of the various syntactic sugars of closures in this answer.
The expanded version of this code would be:
app.get("welcome", { (request: Request) throws -> ResponseRepresentable in
    return "Hello"
})


Q:

Menu strip access from other Windows form

I want to deactivate my menu strip or my sub menu strip from form2 or form3
The problem is that the menu strip is private. I cannot access it from the other form where I can change the value. How can I do that?

A:

Don't try to access a private control of a form from the outside and don't make your menu public - it's not the right solution to your problem. If you make your controls public, you allow other components to access those controls without a chance to intervene - outside callers can make changes to the form's state without the form being aware of it. This may work in very small programs but it leads to code that's impossible to maintain as it grows because the various UI elements start depending on each other: as you change one, you'll have to update the code in other components to keep things building without errors. It's very hard to do this without breaking functionality.
If you need to affect one form from another, the correct way to do it is to acquire a temporary reference to the target form (preferably just an interface) and then to tell the target form to deactivate its own menu.
This keeps the menu a private component (as it should be) but still gives you the ability to tell the target form to update the status of the menu.
For example:
// Form1.Designer.cs
partial class Form1
{
    private System.Windows.Forms.ContextMenuStrip contextMenuStrip1;

    // ...
}

// Form with menu
public partial class Form1 : Form
{
    public void UpdateMenuStatus ( bool bEnable )
    {
        // update menu status here
    }
}

// Form that wants to update the menu on Form1
public partial class Form2 : Form
{
    private void SomeFunc ()
    {
        Form1 form1 = GetForm1Reference ();

        form1.UpdateMenuStatus ( true );
    }
}

The function GetForm1Reference () should look up the requested Form1 reference in a global list/map that you maintain - this way you don't hardcode a particular instance of your form within other forms - you want to keep these different forms as separate from each other as possible so that changing one doesn't force you to change the others.


Q:

immutable.js get keys from map/hash

I want to retrieve keys() from the following Immutable Map:
var map = Immutable.fromJS({"firstKey": null, "secondKey": null });
console.log(JSON.stringify(map.keys()));

I would expect the output:
["firstKey", "secondKey"]

However this outputs:
{"_type":0,"_stack":{"node":{"ownerID":{},"entries":[["firstKey",null],["secondKey",null]]},"index":0}}

How to do it properly?
JSFiddle link: https://jsfiddle.net/o04btr3j/57/

A:

Although this question got answered a while ago, here is a little update:
ES6 Solution:
const [ ...keys ] = map.keys();

Pre ES6 Solution:
var keys = map.keySeq().toArray();

A:

This is how ImmutableJS object looks like.
If you want to get:
["firstKey", "secondKey"]

You need to do:
console.log(map.keySeq().toArray())

A:

Possibly just answering my own question that lead me here, but I found mapKeys() which will gives you access to keys in a regular loop. It seems a bit more "the right way". (The docs are so vague, who knows!)
eg:
Map({ a: 1, b: 2 }).mapKeys((key, value) => console.log(key, value))
// a 1
// b 2


Q:

appendChild is not responding after class change - VANILLA Javascript

I found answers alluding to this question but most of them seemed to be based on jQuery.  As an exercise I am building a image slider app in jQuery and then Javascript.  I want to understand what jQuery is doing under the hood, and be able to make the decision to use it or not based on the project.
My problem is this: when I click the next button, I want the gallery to slide to the left, and prevImg will be removed, currentImg will become next and so forth.  I will then add a li element with the appropriate class nextImg and the image.
Everything is working fine, but the line of code nextImg.appendChild(next_ImgPath) is not appending an image.
function slideAnimSetting(direction) {
    counterAction();

    if (direction == 1) {
        establishImgPaths();

        for (var i = 0; i < innerListEl.length; i++) {
            leftPosition = innerListEl[i].offsetLeft;
            topPosition = innerListEl[i].offsetTop;
            Tween.to(innerListEl[i], 1, {left: leftPosition-700});
        };  // end for

        prevImg.removeAttribute('class');
        currentImg.className = 'prevImg';
        nextImg.className = 'currentImg';

        listEle = document.createElement('li');
        listEle.className = 'nextImg';

        for (var i = 0; i < innerUlEl.length; i++) {
            innerUlEl[i].appendChild(listEle);
        }; //end for

        nextImg = document.getElementsByClassName('next-img');
        nextImg = nextImg[0];
        nextImg.appendChild(next_ImgPath);

        setImageStyles();
    }
}; // end slideAnimSetting

The console.log is telling me that nextImg is undefined.

A:

You gave it a className of nextImg, but you're searching for next-img.


Q:

Using std::string Datatype in std::vector's Constructor

This isn't so much a specific question about RapidXML convention as it is a question about using a std::vector's constructor.
In all examples that I have found of others using RapidXML, everyone always reads data into a vector of char's using the std::vector's constructor like so:
vector<char> buffer((istreambuf_iterator<char>(theFile)), istreambuf_iterator<char>());

There must be a reason for this because when I try to change it to a vector of std::string's I get a screen full of errors with this being the first error:
error: invalid conversion from ‘void*’ to ‘std::istreambuf_iterator<std::basic_string<char> >::streambuf_type* {aka std::basic_streambuf<std::basic_string<char>, std::char_traits<std::basic_string<char> > >*}’

Is there a way to use std::string and if not why?

A:

What are you trying to do?
Do you want the contents of the file in a single string? If so, then
string buffer((istreambuf_iterator<char>(theFile)), istreambuf_iterator<char>());

should do it.
On the other hand, if you want a vector of strings, with each string containing a single line from the file, you'll have to write a loop like this (untested code):
vector <string> lines;
for (string aLine; std::getline(theFile, aLine) ; )
    lines.push_back(aLine);


Q:

Zend Framework PDF multiline problems

I have a problem, with Zend_PDF multiline, my problem is that I can't  write the entire text to my pdf.My text looks like this: http://pastebin.com/f6413f664
But when I open my .pdf file, the text looks like this: http://screencast.com/t/1CBjvRodeZQd
And here is my code:
    public function pdfAction()
{
    $this->_helper->layout->disableLayout();
    $this->_helper->viewRenderer->setNoRender();

    $theID = ($this->_getParam('id') !== NULL) ? (int)$this->_getParam('id') : false;

    ($theID === false) ? $this->_redirect('/home') : false;

    //Information
    $info = $this->artists->artistInfo($theID);

    // Create new PDF
    $pdf = new Zend_Pdf();
    $pdf->properties['Title'] = "TITLE";
    $pdf->properties['Author'] = "AUTHOR";

    // Add new page to the document
    $page = $pdf->newPage(Zend_Pdf_Page::SIZE_A4);
    $pdf->pages[] = $page;

    // Set font
    $page->setFont(Zend_Pdf_Font::fontWithName(Zend_Pdf_Font::FONT_HELVETICA), 8);

    // Draw text
     foreach (explode("
", $info[0]['biography']) as $i => $line) {
       $page->drawText($line, 0, 820 - $i * 10, 'UTF-8');
     }

    $this->getResponse()->setHeader('Content-type', 'application/x-pdf', true);
    $this->getResponse()->setHeader('Content-disposition', 'attachment; filename=my-file.pdf', true);
    $this->getResponse()->setBody($pdf->render());
}

What I want to do, is for every
 to have a break(
\n) and to display the entire text.
Any solutions guys?

A:

Instead of this:
 // Draw text
 foreach (explode("
", $info[0]['biography']) as $i => $line) {
   $page->drawText($line, 0, 820 - $i * 10, 'UTF-8');
 }

Give this a try(didn't try it):
// Draw text
$charsPerLine = 50;
$heightPerLine = 10;

$text = str_replace('
','',$info[0]['biography']);
$lines = array();

foreach (explode("
", $text) as $line) {
    $lines = array_merge(
                    $lines,
                    explode(
                            "\n",
                            wordwrap($line, $charsPerLine, "\n")
                    )
    );
}

foreach ( $lines as $i=>$line ) {
    $page->drawText($line, 0, 820 - $i * $heightPerLine, 'UTF-8');
}

You obviously need to play with those 2 "constants" to get the best results.
Hope it helps.


Q:

Find the joint pdf given an event (uniform distribution)

A point $\bar{X}=(X,Y,Z)$ is uniformly randomly selected from a unit ball. Find the joint pdf of $\bar{X}$ given the distance from $\bar{X}$ to the origin is greater than $\frac{1}{2}$ and $\bar{X}>0$ (positive orthoant).

I try to solve this problem in the following:

$f_{XYZ}(x,y,z)=\frac{3}{4\pi}$. (uniformly distributed)
$P[A] = P[r>\frac{1}{2},\bar{X}>0]=(\frac{4}{3}\pi\times1^3-\frac{4}{3}\pi\times r^3)\times \frac{3}{4\pi}\times \frac{1}{8}=\frac{1}{8}(1-r^3)$
$f_{XYZ}(x,y,z | A)$

How should I do the last step?  Should I find the pdf of the event $A$?
This is the tricky part to me.

A:

Yes; with the proviso that $(x,y,z)$ is in the unit sphere; $f(x,y,z)=0 \text{ elsewhere}$
No.  The region of $A$ is the unit sphere minus the inner sphere of radius $\tfrac 1 2$. Consider then: what is the area of this region?  (Hint: its a constant, not a function of $r$).
$f(x,y,z\mid A) = \dfrac{f(x,y,z) \;\mathbf 1_{(x,y,z)\in A}}{\mathsf P(A)}$


Q:

do boost::asio async write need a mutex?

I'm trying to understand the boost::asio but have some problems with it. In this example, please correct me if I'm wrong.

The message is given by reference to the write() method and by value to do_write(). So I think this is ok, even though the do_write is done by io_service.post, the boost::bind is binding the message by value.
But why is there no mutex for the write_msgs_ queue, since std::deque might move around or copy its elements, if needed and io_service::run has it's own thread, it is not ensured the data is consistent.
Is it not better to do it by pointer. If the messages are to long they have always to be copied by value. But with new and delete they will be created before and deleted after sending. Then I would do the send like so

code
boost::asio::async_write(socket_,
      boost::asio::buffer(*write_msgs_.front().data(),
        write_msgs_.front().length()),
      boost::bind(&chat_client::handle_write, this,
        boost::asio::placeholders::error));

A:

1) Is correct and the reason why 2) works.
You don't need a mutex here because the synchronization between the main and the client handler thread is done via the io_service::post method. post doesn't actually execute anything but adds a callback(the bound method) to the callback handlers which are the threads which execute io_service::run and such std::deque is only accessed by the one thread that runs io_service::run.
3) This is a question of thread-safety, exception-safety and ownership.
Concerning thread-safety you need to be 100% sure that after you called write only one thread will access the string pointed to by your pointer.
Ownership and exception safety is the more interesting point here. If you'd want to only store plain pointers in your deque you have an exception-safety problem as in case of a thrown exception your strings wouldn't be deleted anymore. To circumvent this problem you'd need something like a smart-pointer(e.g.: std::unique_ptr), which would require C++11 move-semantics or a shared_ptr which would add additional overhead for ref-counting. The cleanest solution is to use C++11 move semantics in combination with plain strings. You could just move the buffer to the write function and further into the handler with the added benefits of no copying and exception safety.
Another point before talking about performance and copying is that you should measure if this is really a problem and that you are not bottlenecked by something different like network-I/O.


Q:

HOW TO Return value array on function php mysql

Hy I have code below,
I wanna return value array with function :
    <?php

include "config/koneksi.php";

//script1
$fetch1 = mysqli_query($conn, "SELECT * FROM orders_temp");

$array = array();
while($row = mysqli_fetch_assoc($fetch1)){
    $array[] = $row[id_orders_temp];
}
echo "script1: ";
print_r($array);

echo "<br>";

//script2
function cart(){
    $array1= array();

    $fetch2 = mysqli_query($conn,"SELECT * FROM orders_temp");

    while ($r=mysqli_fetch_assoc($fetch2)) {
        $array1[] = $r[id_orders_temp];
    }
    return $array1;
}

$cart1 = cart();
echo "script2 : ";
print_r($cart1);

?>

and the result :
script1: Array ( [0] => 150 [1] => 151 )
script2 : Array ( )

there's no problem if I print_r array without function, but
when I used function as above, I got blank array( ).
How can I get array value with function ?

A:

The variable $conn is not defined within the function, so you need to either pass it to the function or reference the globally available $conn.
Pass in $conn
include "config/koneksi.php";

function cart($conn) {
    $identifiers = array();

    $result = mysqli_query($conn, 'SELECT id_orders_temp FROM orders_temp');

    while ($row = mysqli_fetch_assoc($result)) {
        $identifiers[] = $row['id_orders_temp'];
    }

    return $identifiers;
}

$cart = cart($conn);

var_dump($cart);

Reference global $conn
Ideally, you should limit global state (and accessing it), so I would not recommend this.
include "config/koneksi.php";

function cart() {
    global $conn;

    $identifiers = array();

    $result = mysqli_query($conn, 'SELECT id_orders_temp FROM orders_temp');

    while ($row = mysqli_fetch_assoc($result)) {
        $identifiers[] = $row['id_orders_temp'];
    }

    return $identifiers;
}

$cart = cart();

var_dump($cart);

Note I have renamed variables within cart() and optimized the SQL query to select only those columns actually required.


Q:

How can i configure L3 switch and DHCP server?

I'm stuck with configuring L3 sw + L2 sw + dhcp server. My scheme is:

I can't take ip addresses to computers in different VLAN's.
I have two dhcp pools:

Configuration on L3 switch:
ip routing
spanning-tree mode pvst
interface FastEthernet0/1
switchport trunk allowed vlan 10
switchport trunk encapsulation dot1q
switchport mode trunk

interface FastEthernet0/2
switchport trunk allowed vlan 20
switchport trunk encapsulation dot1q
switchport mode trunk

interface FastEthernet0/3
switchport access vlan 30
switchport mode access

interface Vlan1
no ip address
shutdown

interface Vlan10
mac-address 00d0.ba4b.a601
ip address 192.168.10.1 255.255.255.0
ip helper-address 192.168.1.1

interface Vlan20
mac-address 00d0.ba4b.a602
ip address 192.168.20.1 255.255.255.0
ip helper-address 192.168.1.1

interface Vlan30
mac-address 00d0.ba4b.a603
ip address 192.168.30.1 255.255.255.0

L2 switches with almost similar conf, just different vlan's:
spanning-tree mode pvst

interface FastEthernet0/1
 switchport access vlan 10
 switchport mode access

interface FastEthernet0/2
 switchport access vlan 10
 switchport mode access

DHCP server:
static ip: 192.168.1.1
gateway: 192.168.30.1

So, what i did wrong? What should i do for properly work ?
2:07:
I've changed VLAN1 and up this interface, plus set another dhcp ip,so now on my L3:
interface Vlan1
 ip address 1.1.1.1 255.255.255.0
 ip helper-address 1.1.1.5
!
interface Vlan10
 mac-address 00d0.ba4b.a601
 ip address 192.168.10.1 255.255.255.0
 ip helper-address 1.1.1.5
!
interface Vlan20
 mac-address 00d0.ba4b.a602
 ip address 192.168.20.1 255.255.255.0
 ip helper-address 1.1.1.5
!
interface Vlan30
 mac-address 00d0.ba4b.a603
 ip address 192.168.30.1 255.255.255.0
 ip helper-address 1.1.1.5
!

DHCP server:
IP: 1.1.1.5
Gateway: 1.1.1.1

But it still doesn't work. And i don;t know how to don't set mac-address,i think it was by packet tracker automatically.
Should i up VLAN1's svi on L2 switches?

A:

Your DHCP server address is not in the network where it is connected. It will never use an address in a different network for its gateway. The gateway is, by definition, in the same network as the host, and it is used by the host to get to addresses not in its network.
You either need to change the DHCP server's address, or you need to change the network to match the DHCP server's network.
Also, there is no reason to specifically set the MAC address on any VLAN.
Since you have the DHCP server connected to VLAN 30 on F0/3, you can change the DHCP servers address to 192.168.30.2 with a gateway of 192.168.30.1. Then just change the helper addresses to 192.168.30.2.


Q:

System service is not available to activities before onCreate()

I'm new to android development and I'm here to seek for help.
I've coded a wallet program and when i press the debit button , it stopped working and crashes.
Is it because of the final Context context declaration ?
My logcat error starts from here
: java.lang.IllegalStateException: System services not available to Activities before onCreate()

Main class activity :
private double total; //total amount
    EditText et;
    private double cinput; //credit input
    private double dinput; //debit input
    Button CreditButton;
    Button DebitButton;
    final Context context = this;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    //loadAmt();
    cinput = 0;
    dinput = 0;
    CreditButton = (Button) findViewById(R.id.CreditButton);
    DebitButton = (Button) findViewById(R.id.DebitButton);
    CreditButton.setOnClickListener(new ButtonActionListener());
    DebitButton.setOnClickListener(new ButtonActionListener());
    et = (EditText) findViewById(R.id.AmountText);
    et.setText(String.valueOf(total));
}

public void loadAmt() {

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

public class ButtonActionListener extends MainActivity implements View.OnClickListener {
    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.DebitButton) {
            try {
                // get prompts.xml view
                LayoutInflater li = LayoutInflater.from(context);
                View promptsView = li.inflate(R.layout.prompts, null);

                AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
                        context);

                // set prompts.xml to alertdialog builder
                alertDialogBuilder.setView(promptsView);

                final EditText userInput = (EditText) promptsView
                        .findViewById(R.id.editTextDialogUserInput);

                // set dialog message
                alertDialogBuilder
                        .setCancelable(false)
                        .setPositiveButton("OK",
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int id) {
                                        // get user input and set it to result
                                        // edit text
                                        String inputString = userInput.getText().toString();
                                        dinput = Double.parseDouble(inputString);
                                        total = total + dinput;
                                        et.setText(String.valueOf(total));

                                    }
                                })
                        .setNegativeButton("Cancel",
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int id) {
                                        dialog.cancel();
                                    }
                                });

                // create alert dialog
                AlertDialog alertDialog = alertDialogBuilder.create();

                // show it
                alertDialog.show();
            } catch (InputMismatchException e) {
                Toast.makeText(getApplicationContext(), "Only Numbers Are Allowed", Toast.LENGTH_SHORT).show();
            }
        } else if (v.getId() == R.id.CreditButton) {
            try {
                // get prompts.xml view
                LayoutInflater li = LayoutInflater.from(context);
                View promptsView = li.inflate(R.layout.prompts, null);

                AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
                        context);

                // set prompts.xml to alertdialog builder
                alertDialogBuilder.setView(promptsView);

                final EditText userInput = (EditText) promptsView
                        .findViewById(R.id.editTextDialogUserInput);

                // set dialog message
                alertDialogBuilder
                        .setCancelable(false)
                        .setPositiveButton("OK",
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int id) {
                                        // get user input and set it to result
                                        // edit text
                                        String inputString = userInput.getText().toString();
                                        cinput = Double.parseDouble(inputString);
                                        total = total - cinput;
                                        et.setText(String.valueOf(total));

                                    }
                                })
                        .setNegativeButton("Cancel",
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int id) {
                                        dialog.cancel();
                                    }
                                });

                // create alert dialog
                AlertDialog alertDialog = alertDialogBuilder.create();

                // show it
                alertDialog.show();
            } catch (InputMismatchException e) {
                Toast.makeText(getApplicationContext(), "Only Numbers Are Allowed", Toast.LENGTH_SHORT).show();
            }
        }

        //save(total);

    public void save(double tamt) {

        SharedPreferences spamount = getSharedPreferences("TotalAmount", MODE_PRIVATE);
        SharedPreferences.Editor editor = spamount.edit();
        editor.putString("LastAmount", String.valueOf(tamt));
        editor.apply();

    }
}
}

A:

You will only get the context of your activity in the Activity lifecycle methods. So you should initialize it inside the onCreate method.
private Context context;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    context = this;
}


Q:

Any way to push Javascript from NodeJS server to client for updates?

In Scala's Liftweb there are some classes which allow for Javascript to be pushed to the browser via comet/ajax after the page has loaded. Some documentation here.
The usage could be for example when someone submits a form to the server, the form would submit via AJAX and then some Javascript can be sent from the server to the client to show some error message. Well this is just for example, there are better ways to do form validation.
Is there any way to push Javascript from the NodeJS server to the client to do updates? Any standard way to do this? Why I want to do this is that its nicer to have all client and server code located in one server file.
Also as a secondary question, can I access the page data from the server side? It would be nice to be able to query a page element from the server side or query some page data from the server side.

A:

You can build this functionality into socket.io, either by predefining functions based on dynamic objects that are sent bi-directionally, or by building a system which will parse and run javascript from both sides.  Depending on what you are trying to do it might take a while to get that working for you securely (not just throwing everything in eval());
http://socket.io/
Alternatively there is a library built on node.js that has this functionality built in.  I have not personally used it so I can't attest to the reliability or security of the system, but it should be a good place to start.
http://www.nowjs.com/
https://github.com/Flotype/now
Hope this helps!


Q:

What is a parameter signature in PHP?

The PHP official documentation while explaining about extends under classes and objects section, it says:
"When overriding methods, the parameter signature should remain the same or PHP
will generate an E_STRICT level error. This does not apply to the constructor
which allows overriding with different parameters."

So I want to know, what a parameter signature is?
The example inside the documentation is the following:
<?php
class ExtendClass extends SimpleClass
{
    // Redefine the parent method
    function displayVar()
    {
        echo "Extending class\n";
        parent::displayVar();
    }
}

$extended = new ExtendClass();
$extended->displayVar();
?>

Official online link

A:

The parameter signature is simply the definition of parameters in the definition (signature) of a method. What is meant with the quoted text is, to use the same number (and type, which is not applicable in PHP) of parameter when overriding a method of a parent class.
A signature of a function/method is also referred to as a head. It contains the name and the parameters. The actual code of the function is called body.
function foo($arg1, $arg2) // signature
{
    // body
}

So for example if you have a method foo($arg1, $arg2) in a parent class, you can't override it in a extended class by defining a method foo($arg).


Q:

Database Connection Pooling (w/ Java)

I would like to know your thoughts on whether this type of methodology could be practically implemented. I am very knew to database pooling, so forgive me for any misunderstandings. I have multiple classes calling a dbData class (which connects to a database and has helper functions, like frequently uses gets and updates and etc). I need to keep all the get and update functions in dbData class, but keep a pool of active connections I can re-use. Which means I will instantiate the dbData class multiple times, each time checking whether an appropriate connection exists, if not, create a new one and put it into the pool.
My question is this how and where you would store this pool. I could perhaps accomplish this if dbData would not be instantiated more than once and keeps one persistent pool object. But in my case, I have multiple dbData instances which should all connect to a single pool. I thought about serializing the pool object, but this seems ridiculous. Is this possible (what is shown in the pic)? It seems I am having trouble with the object-oriented part of this design.
The applications uses multithreading with Class1 and Class2.
I would not like to use any external libraries if possible.

A:

If it is a standalone app, then I would create a seperate service with a static collection that keeps the connection and does all the handling of those. Then the dbData class can call the static method to get a connection. The service then itself takes care of creating new connections if required. If your dbData instances are running in parallel you have to think about synchronized access (if required).


Q:

Creating new array with unique key while mapping through given array

I am struggling with an array that i need to convert into a new array with unique keys. I have an array called 'mondayAvailability' which looks like this:
[
 {
   id: 1,
   from_time: '09:00',
   to_time: '10:00'
 },
 {
   id: 2,
   from_time: '16:00',
   to_time: '17:30'
 },
]

I need to extract 30-minute time slots based on the values of 'from_time' and 'to_time' of each item in the array, and create a new array called 'mondayTimeLabels', which will store these slots. Each time slot will be an object containing a unique key so the new array looks like this:
[
 {
   key: '1',
   slotTime: 09:00 AM,
   disabled: false
 },
 {
   key: '2',
   slotTime: 09:30 AM,
   disabled: false
 },
 {
   key: '3',
   slotTime: 10:00 AM,
   disabled: false
 },
 {
   key: '4',
   slotTime: 04:00 PM,
   disabled: false
 },
 {
   key: '5',
   slotTime: 04:30 PM,
   disabled: false
 },
 {
   key: '6',
   slotTime: 05:00 PM,
   disabled: false
 },
 {
   key: '7',
   slotTime: 05:30 PM,
   disabled: false
 },
]

I could achieve most of what i desire with the code below. However the problem with the code below is that it doesn't return unique keys when the original array length > 1. So how could i change my code to ensure that the new array mondayTimeLabels will end up with items with a unique key? Thanks in advance.
let mondayTimeLabels = [];
let startTime;
let endTime;
let arrayLength;
let slotTime;

mondayAvailability.map(item => {
  startTime = moment(item.from_time.substring(0,5), 'hh:mm')
  endTime = moment(item.to_time.substring(0,5), 'hh:mm')
  arrayLength = endTime.diff(startTime, 'minutes') / 30;
  slotTime = startTime;

  for (let x = 0; x <= arrayLength; x++) {
    slotTime.add(x === 0 ? 0 : interval)
    mondayTimeLabels.push({
      key: x,
      slotTime: slotTime.format('hh:mm A'),
      disabled: false
    })
  }
})

A:

You could just keep a counter for the keys outside of the loop, something like:

let mondayAvailability = [{
    id: 1,
    from_time: "09:00",
    to_time: "10:00",
  },
  {
    id: 2,
    from_time: "16:00",
    to_time: "17:30",
  },
];
let mondayTimeLabels = [];
let startTime;
let endTime;
let arrayLength;
let slotTime;
let key = 1;

mondayAvailability.map((item) => {
  startTime = moment(item.from_time.substring(0, 5), "hh:mm");
  endTime = moment(item.to_time.substring(0, 5), "hh:mm");
  arrayLength = endTime.diff(startTime, "minutes") / 30;
  slotTime = startTime;

  for (let x = 0; x <= arrayLength; x++) {
    slotTime.add(x === 0 ? 0 : 30, "minutes");
    mondayTimeLabels.push({
      key: String(key),
      slotTime: slotTime.format("hh:mm A"),
      disabled: false,
    });
    key++;
  }
});
console.log(mondayTimeLabels);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>


Q:

How to specify initial position of browser when viewing SVG file or embedded SVG code

I have an SVG file with a network diagram (rectangle with arrows connecting the rectangles). It is much larger that the browser's viewport. The logical starting point when reading the diagram is at a rectangle near the center of the diagram. I would like the initial view to be centered on this particular rectangle so the user doesn't have to hunt it down.
I am aware of the HTML anchor tag that allows you to open a webpage at a particular location. It is my understanding the  tag within the SVG file does not work the same way. Is there another way of controlling the initial position of the browser to start at an element of an SVG file? I don't mind having to embed the SVG code within an html file if there is a solution that would require that.

A:

The solution that seems to work with Google Chrome, Firefox and Android WebView is to use window.scroll(x,y) in JavaScript. For example:
<?xml version="1.0"?>
<svg xmlns="http://www.w3.org/2000/svg" width="5000" height="5000">

    <rect id="rect1" x="3000" y="3000" width="200" height="100" style="fill:rgb(0,0,255);stroke-width:3;stroke:rgb(0,0,0)"/>

    <script type="text/javascript">
        var rect1 = document.getElementById("rect1");
        var x = 3100 - window.innerWidth/2;
        var y = 3050 - window.innerHeight/2;
        window.scroll(x,y);
    </script>
</svg>


Q:

Using ImageMagick++ to modify image contrast/brightness

I'm trying to apply contrast and brightness to a bitmap in memory and I'm completely lost. Currently I'm trying to use Magick++ to do it, but if one of the other APIs would work better I'm all ears. I managed to find Magick::Image::sigmoidalContrast() for applying the contrast, but I can't figure out how to get it to work. I'm creating an image, passing it the buffer pointer, then calling that function, but it doesn't seem like it's changing anything so my first though was that it's making a copy and modifying that. Even so, I have no idea how to get the data out of the Magick::Image object.
Here's what I got so far.
Magick::Image image(fBitmapData->mGetTextureWidth(), fBitmapData->mGetTextureHeight(), "RGBA", MagickCore::CharPixel, pixels);
image.sigmoidalContrast(1, 20.0);

The documentation is useless and after searching I could only find hints that the first parameter is actually a boolean, even though it takes a size_t, that specifies whether to add or subtract the contrast, and the second value is something I have no idea what to pass so I'm just using 20.0 to test.
So does anyone know if this will work for contrast, and if not, then how do you apply contrast? And likewise I still have no idea how to apply brightness either and can't find any functions that look like they would work.

A:

Figured it out; The function for contrast I was using was correct, and for brightness I ended up using image.modulate(brightness, 100.0, 100.0);. To get the data out of the image object you can grab the pixels of the entire image by doing
const MagickCore::PixelPacket * magickPixels = image.getConstPixels(0, 0, image.columns(), image.rows());

And then copy the magickPixels data back into the original pixels that were passed into the image constructor. An important thing to note is that the member MagickCore::PixelPacket::opacity is not what you would think it would be. If the pixel is completely transparent you'd think the value would be 0, right? Well for some reason ImageMagick is doing it opposite. So for full transparency the value would be 255. This means you need to do 255 - opacity to get the correct value.
Also be careful of the MAGICKCORE_QUANTUM_DEPTH that ImageMagick was compiled with, as this will change the values drastically. For my code MAGICKCORE_QUANTUM_DEPTH just happened to be defined as 16 so all of the values were a range of 0 to 65535, which I just fixed by doing realValue = magickValue >> 8 when copying the data back over since the texture data is unsigned char values.
Just for clarification on how to use these functions, since the documentation is horrible and completely wrong, the first parameter to signmoidalContrast() is actually a boolean, even though the type is a size_t, that specifies whether to increase the contrast (true) or reduce it (false), and the second is a range from 0.00001 to 20.0. I say 0.00001 because 0.0 is an invalid value so it just needs to be some decimal that is close to but not exactly 0.0.
For modulate() the documentation says that each value should be specified as 1.0 for no change, which is completely wrong. The values are actually a percentage so for no change you would specify 100.0.
I hope that helps someone because it took me all damn day to figure this stuff out.


Q:

Writing numbers to a file with an array then printing them sorted

I am working with reading/writing files using arrays. This is for a college Java 2 assignment, I feel like I should know this but I'm drawing a blank.
What I need to do is sort the numbers in the file in ascending order.
First, the program checks if a certain file exits within the src file here:
        File file = new File("src/chapter12/randomfile.dat"); //File path

    if(file.exists())
    {   //If the file exists, print out each element on the file.
        Scanner input = new Scanner(file);
        while(input.hasNextLine())
        {
            System.out.println(input.nextLine());
        }
            input.close();
    }

^^ This part works out perfectly for searching for the file, then if it is found printing out the lines it contains.
Then, if the file is not found we create it and write 100 random numbers to it here, from 0-100:
else
    {   //If the file isn't found, create it and write 100 random numbers to it.
        try(PrintWriter output = new PrintWriter(file))
        {
            for(int i = 0; i < size; i++)
            {
                randomArray[i] += random.nextInt(101);
                output.print(randomArray[i] + " ");
            }
        }

I have tried inputting Array.sort(randomArray) in two places:
                randomArray[i] += random.nextInt(101);
                output.print(randomArray[i] + " ");
                Arrays.sort(randomArray);

and here
Scanner input = new Scanner(file);
        Arrays.sort(randomArray);
        while(input.hasNextLine())
        {
            System.out.println(input.nextLine());
        }
            input.close();

The first location is in the loop, where it would sort it before the end of each iteration.
The second one is before I do the check for the file, because the first time the program runs, the file doesn't exist so the array is empty. However since the file is created after the first run, logically it would sort the already full array before reading the file, but it made no sense because it would sort the array, but since the file is created, it can't sort the file.
Currently I am trying to search a way to possibly sort the file before printing out what was read, however my assignment states "You can use the array class to sort the file." This is where I draw a blank, any suggestions?
Here is a full snippet of code if needed:
package chapter12;

import java.io.*;           //Allows us to use File Writer.
import java.util.Arrays;    //Allows us to sort the array.
import java.util.Random;    //Allows us to get random numbers.
import java.util.Scanner;   //Allows us to read the file.
public class Excercise1215
{
    public static void main(String[] args) throws FileNotFoundException
    {
        int size = 100;
        int[] randomArray = new int[size];
        Random random = new Random();

    File file = new File("src/chapter12/randomfile.dat"); //File path

    if(file.exists())
    {   //If the file exists, print out each element on the file.
        Scanner input = new Scanner(file);
        Arrays.sort(randomArray);
        while(input.hasNextLine())
        {
            System.out.println(input.nextLine());
        }
            input.close();
    }
    else
    {   //If the file isn't found, create it and write 100 random numbers to it.
        try(PrintWriter output = new PrintWriter(file))
        {
            for(int i = 0; i < size; i++)
            {
                randomArray[i] += random.nextInt(101);
                output.print(randomArray[i] + " ");
                Arrays.sort(randomArray);
            }
        }
        //Exception handling
        catch(FileNotFoundException ex)
        {
            System.out.println("File was not found.");
        }
        catch(Exception ex)
        {
            System.out.println("Something went wrong.");
        }
    }
}

}

A:

Before writing to the file if it doesn't exist, you should sort your array before writing it. Do this using two for loops like this:
for(int i = 0; i < size; i++) {
    randomArray[i] += random.nextInt(101); //Populate the array
}
Arrays.sort(randomArray); // Sort the array
for(int i = 0; i < size; i++) {
    output.print(randomArray[i] + " "); // Write the array to the file
}

If the file does exist you should read the values into your array, sort the array, then print the array. Here is a sample:
if(file.exists())
{   //If the file exists, print out each element on the file.
    Scanner input = new Scanner(file);
    int count = 0;
    while(input.hasNextInt())
    {
        randomArray[count++] = input.nextInt();
    }
    input.close();
    Arrays.sort(randomArray);

    for(int i = 0; i < size; i++) {
        System.out.println(randomArray[i]);
    }
}


Q:

Extracting value from XMLType Column

I was learning XMLType applications when I came accross the below problem. It's returning NULL insteade of the CD Title.  I am not sure why it's behaving in this way.
DROP TABLE  Xml_tab;
 /
 CREATE TABLE Xml_tab ( xmlval xmltype);
 /
INSERT INTO Xml_tab
VALUES(XMLTYPE.CREATEXML(
  '<CATALOG><CD><TITLE>Empire Burlesque</TITLE><ARTIST>Bob Dylan</ARTIST><COUNTRY>USA</COUNTRY><COMPANY>Columbia</COMPANY><PRICE>10.90</PRICE><YEAR>1985</YEAR></CD><CD><TITLE>Hide your heart</TITLE><ARTIST>Bonnie Tyler</ARTIST><COUNTRY>UK</COUNTRY><COMPANY>CBS Records</COMPANY><PRICE>9.90</PRICE><YEAR>1988</YEAR></CD><CD><TITLE>Greatest Hits</TITLE><ARTIST>Dolly Parton</ARTIST><COUNTRY>USA</COUNTRY><COMPANY>RCA</COMPANY><PRICE>9.90</PRICE><YEAR>1982</YEAR></CD><CD><TITLE>Still got the blues</TITLE><ARTIST>Gary Moore</ARTIST><COUNTRY>UK</COUNTRY><COMPANY>Virgin records</COMPANY><PRICE>10.20</PRICE><YEAR>1990</YEAR></CD><CD><TITLE>Eros</TITLE><ARTIST>Eros Ramazzotti</ARTIST><COUNTRY>EU</COUNTRY><COMPANY>BMG</COMPANY><PRICE>9.90</PRICE><YEAR>1997</YEAR></CD><CD><TITLE>One night only</TITLE><ARTIST>Bee Gees</ARTIST><COUNTRY>UK</COUNTRY><COMPANY>Polydor</COMPANY><PRICE>10.90</PRICE><YEAR>1998</YEAR></CD><CD><TITLE>Sylvias Mother</TITLE><ARTIST>Dr.Hook</ARTIST><COUNTRY>UK</COUNTRY><COMPANY>CBS</COMPANY><PRICE>8.10</PRICE><YEAR>1973</YEAR></CD><CD><TITLE>Maggie May</TITLE><ARTIST>Rod Stewart</ARTIST><COUNTRY>UK</COUNTRY><COMPANY>Pickwick</COMPANY><PRICE>8.50</PRICE><YEAR>1990</YEAR></CD><CD><TITLE>Romanza</TITLE><ARTIST>Andrea Bocelli</ARTIST><COUNTRY>EU</COUNTRY><COMPANY>Polydor</COMPANY><PRICE>10.80</PRICE><YEAR>1996</YEAR></CD><CD><TITLE>When a man loves a woman</TITLE><ARTIST>Percy Sledge</ARTIST><COUNTRY>USA</COUNTRY><COMPANY>Atlantic</COMPANY><PRICE>8.70</PRICE><YEAR>1987</YEAR></CD><CD><TITLE>Black angel</TITLE><ARTIST>Savage Rose</ARTIST><COUNTRY>EU</COUNTRY><COMPANY>Mega</COMPANY><PRICE>10.90</PRICE><YEAR>1995</YEAR></CD><CD><TITLE>1999 Grammy Nominees</TITLE><ARTIST>Many</ARTIST><COUNTRY>USA</COUNTRY><COMPANY>Grammy</COMPANY><PRICE>10.20</PRICE><YEAR>1999</YEAR></CD><CD><TITLE>For the good times</TITLE><ARTIST>Kenny Rogers</ARTIST><COUNTRY>UK</COUNTRY><COMPANY>Mucik Master</COMPANY><PRICE>8.70</PRICE><YEAR>1995</YEAR></CD><CD><TITLE>Big Willie style</TITLE><ARTIST>Will Smith</ARTIST><COUNTRY>USA</COUNTRY><COMPANY>Columbia</COMPANY><PRICE>9.90</PRICE><YEAR>1997</YEAR></CD><CD><TITLE>Tupelo Honey</TITLE><ARTIST>Van Morrison</ARTIST><COUNTRY>UK</COUNTRY><COMPANY>Polydor</COMPANY><PRICE>8.20</PRICE><YEAR>1971</YEAR></CD><CD><TITLE>Soulsville</TITLE><ARTIST>Jorn Hoel</ARTIST><COUNTRY>Norway</COUNTRY><COMPANY>WEA</COMPANY><PRICE>7.90</PRICE><YEAR>1996</YEAR></CD><CD><TITLE>The very best of</TITLE><ARTIST>Cat Stevens</ARTIST><COUNTRY>UK</COUNTRY><COMPANY>Island</COMPANY><PRICE>8.90</PRICE><YEAR>1990</YEAR></CD><CD><TITLE>Stop</TITLE><ARTIST>Sam Brown</ARTIST><COUNTRY>UK</COUNTRY><COMPANY>A and M</COMPANY><PRICE>8.90</PRICE><YEAR>1988</YEAR></CD><CD><TITLE>Bridge of Spies</TITLE><ARTIST>T''Pau</ARTIST><COUNTRY>UK</COUNTRY><COMPANY>Siren</COMPANY><PRICE>7.90</PRICE><YEAR>1987</YEAR></CD><CD><TITLE>Private Dancer</TITLE><ARTIST>Tina Turner</ARTIST><COUNTRY>UK</COUNTRY><COMPANY>Capitol</COMPANY><PRICE>8.90</PRICE><YEAR>1983</YEAR></CD><CD><TITLE>Midt om natten</TITLE><ARTIST>Kim Larsen</ARTIST><COUNTRY>EU</COUNTRY><COMPANY>Medley</COMPANY><PRICE>7.80</PRICE><YEAR>1983</YEAR></CD><CD><TITLE>Pavarotti Gala Concert</TITLE><ARTIST>Luciano Pavarotti</ARTIST><COUNTRY>UK</COUNTRY><COMPANY>DECCA</COMPANY><PRICE>9.90</PRICE><YEAR>1991</YEAR></CD><CD><TITLE>The dock of the bay</TITLE><ARTIST>Otis Redding</ARTIST><COUNTRY>USA</COUNTRY><COMPANY>Atlantic</COMPANY><PRICE>7.90</PRICE><YEAR>1987</YEAR></CD><CD><TITLE>Picture book</TITLE><ARTIST>Simply Red</ARTIST><COUNTRY>EU</COUNTRY><COMPANY>Elektra</COMPANY><PRICE>7.20</PRICE><YEAR>1985</YEAR></CD><CD><TITLE>Red</TITLE><ARTIST>The Communards</ARTIST><COUNTRY>UK</COUNTRY><COMPANY>London</COMPANY><PRICE>7.80</PRICE><YEAR>1987</YEAR></CD><CD><TITLE>Unchain my heart</TITLE><ARTIST>Joe Cocker</ARTIST><COUNTRY>USA</COUNTRY><COMPANY>EMI</COMPANY><PRICE>8.20</PRICE><YEAR>1987</YEAR></CD></CATALOG>'));
  /
  COMMIT;

 SELECT P.xmlval.extract('//CATALOG/CD/TITLE/text()').GETSTRINGVAL AS CD

FROM   Xml_tab P;

Any explanation is very welcome.

A:

It's a little bit confusing but you can get cd titles like this:
SELECT extract(value(b),'//TITLE/text()').getstringval() AS CD
FROM   xml_tab x,
       TABLE(XMLSEQUENCE(extract(xmlval,'//CATALOG/CD'))) b

You sort of convert the xml into a table first and then get the values with the EXTRACT function.


Q:

Como enviar caracteres especiais pelo CMD para um arquivo?

Quero enviar o caractere > para um arquivo via CMD mas não estou conseguindo.
O exemplo a seguir ilustra a minha dificuldade:
echo casa > cidade > Estado  >Arquivo.txt

No exemplo acima deveria escrever no arquivo a frase "casa > cidade > Estado", mas não estou conseguindo escrever o  caractere > ( só escreve casa no Arquivo.txt).
Tem algum comando no CMD para escrever esse tipo de caractere em um arquivo ?

A:

Use o caractere de escape ^:
echo casa ^> cidade ^> Estado > Arquivo.txt


Q:

Solr-Highlight: unexpected results

I try to use the highlighting function of SOLR 4.4. After some trying it finally works, but not as I expected:
Generell setting: I have a text and a title field. Both are indexed and searched, but the highlighting is only needed in the title field.

1st try: title field of a doc was set as string => no highlighting-results even though the field was stored
2nd try: changed the field to text_ws (only WhiteSpace-Tokenizer). I was not quite sure whether or not I had to index the title field, so I did it. => HL working but only for direct matches (q=Apple didn't HL Apple-Pie in the title - q=Apple-Pie did)
3rd try: added ngram to the title field. Now the q:apple gives a hit, but highlights the complete Apple-pie, not only the query term.

Now for the question: is that the expected behaviour or is there a way to only highlight the query term

EDIT: snippets for..
.. solrconfig.xml
<requestHandler name="/query" class="solr.SearchHandler">
    <lst name="defaults">
        <str name="echoParams">explicit</str>
        <str name="wt">json</str>
        <str name="indent">true</str>
        <str name="df">text</str>
        <str name="defType">edismax</str>
        <str name="qf">title, text</str>
        <str name="hl">true</str>
        <str name="hl.fl">title</str>
        <str name="hl.simple.pre"><b class="text-success"></str>
        <str name="hl.simple.post"></b></str>
    </lst>
</requestHandler>

.. schema.xml
<fieldType name="text" class="solr.TextField" positionIncrementGap="100">
    <analyzer type="index">
        <charFilter class="solr.HTMLStripCharFilterFactory" />
        <tokenizer class="solr.WhitespaceTokenizerFactory" />
        <filter class="solr.WordDelimiterFilterFactory" stemEnglishPossessive="0" generateWordParts="1" generateNumberParts="1" catenateWords="1" catenateNumbers="1" catenateAll="0" splitOnCaseChange="0" preserveOriginal="1" />
        <filter class="solr.StopFilterFactory" ignoreCase="true" words="stopwords.txt" enablePositionIncrements="true" />
        <filter class="solr.LowerCaseFilterFactory" />
        <filter class="solr.SnowballPorterFilterFactory" language="German" />
        <filter class="solr.RemoveDuplicatesTokenFilterFactory" />
    </analyzer>
    <analyzer type="query">
        <tokenizer class="solr.WhitespaceTokenizerFactory" />
        <filter class="solr.WordDelimiterFilterFactory" generateWordParts="1" generateNumberParts="1" catenateWords="1" catenateNumbers="1" catenateAll="0" splitOnCaseChange="0" preserveOriginal="1" />
        <filter class="solr.StopFilterFactory" ignoreCase="true" words="stopwords.txt" enablePositionIncrements="true" />
        <filter class="solr.LowerCaseFilterFactory" />
        <filter class="solr.SnowballPorterFilterFactory" language="German" />
        <filter class="solr.RemoveDuplicatesTokenFilterFactory" />
    </analyzer>
</fieldType>

<fieldType name="text_ngrammed" class="solr.TextField" positionIncrementGap="100">
    <analyzer type="index">
        <charFilter class="solr.HTMLStripCharFilterFactory" />
        <tokenizer class="solr.WhitespaceTokenizerFactory" />
        <filter class="solr.StopFilterFactory" ignoreCase="true" words="stopwords.txt" enablePositionIncrements="true" />
        <filter class="solr.LowerCaseFilterFactory" />
        <filter class="solr.NGramFilterFactory" minGramSize="3" maxGramSize="10" />
        <filter class="solr.RemoveDuplicatesTokenFilterFactory" />

        <!--        <filter class="solr.SnowballPorterFilterFactory" language="English" protected="protwords.txt"/> -->
    </analyzer>
    <analyzer type="query">
        <tokenizer class="solr.WhitespaceTokenizerFactory" />
        <filter class="solr.LowerCaseFilterFactory" />
    </analyzer>
</fieldType>

 <fields>
    <!-- IDs -->
    <field name="id" type="string" indexed="true" stored="true" required="true" />
    <!-- Content -->
    <field name="title" type="text_ngrammed" indexed="true" stored="true" termVectors="true" termPositions="true" termOffsets="true" />
    <field name="text" type="text" indexed="true" stored="false" multiValued="true" />
</fields>

A:

I changed the tokenizer from WhiteSpaceTokenizerFactory to NGramTokenizerFactory and removed the NGramFilterFactory -> now it's (almost) working as expected


Q:

What does Stephen Hawking mean by 'an infinite universe'?

In the recent $100m search for extra terrestrial life project project, Stephen Hawking is quoted in the following way:

"We believe that life arose spontaneously on Earth," Hawking said at Monday's news conference, "So in an infinite universe, there must be other occurrences of life."

My understanding is that scientists believe that the universe isn't infinite - there there is a finite number of stars, it's continuously expanding but has a finite size at a given time.
What's Stephen Hawking refering to here?

A:

Due to the finite speed of light, and the finite age of the Universe, only a portion of it is observable. When people talk about "the size of the Universe", "the number of stars in the Universe", etc., they usually refer to the observable Universe, i.e. the sphere in which we are centered, and which has a radius given by the distance light has been able to travel in the 13.8 billion years since the Big Bang. Note that since the Universe is expanding, this radius is more than 13.8 billion light-years. In fact it's 46.3 billion light-years.
Observations indicate that, on large scales (i.e. above roughly half a billion light-years), the Universe is homogeneous (the same everywhere) and isotropic (the same in all directions). Assuming that this is indeed true is known as the cosmological principle. If the rest of the Universe follows this principle, then there are three possible overall "versions" of universes that we can live in. We call these versions "flat", "closed", and "open". Whereas a globally closed universe would have a finite extent, globally flat or open universes must be infinitely large.
The observable Universe is, within measuring uncertainties but too a very high precision, flat (e.g. Planck Collaboration et al. 2016). Hence, we might think that the whole Universe is, in fact, infinite. But sort of like standing in a large forest with limited visibility doesn't tell you whether the forest is just larger than you can see, or if it's infinitely large, we can't with our current theories and observations know whether the Universe is finite or infinite.


Q:

Windows Phone VB "NavigationService is not declared"

Im creating a very simple Windows Phone 8.1 app in Visual Studio Express. I have added a Hyperlink control, then from that I have double click to go to the relevant VB page.
As instructed by the many tutorials out there I have added the code for the button - which should navigate it to the second page I have created.
Private Sub hyperlinkButton_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
    NavigationService.Navigate(New Uri("/SecondPage.xaml", UriKind.Relative))
End Sub

However VB keeps on giving me the error "NavigationService is not declared"
Searching the error message has given me very little joy so far.

A:

In Windows Phone 8.1, code for navigation to another page are declared as,
this.Frame.Navigate(typeof(SecondPage));


Q:

Java: Use an Array over a Linked list

I am relatively new to Java. And I am a Student in the second semester.
The following has been my last task, and I have already presented it. Everything was fine, and the task that was neccessary for me to accomplish has been completely fulfilled.
The task over the semester was making a little game (My choice was guess a number game), and the tasks were simply build upon eachother. (e.g. use at least 5 functions, at least 3 classes, show all four examples of OOP and make a Computer Player)
So having that said I do not mean for people to solve these task because as you will see they have been completed.
Just one additional thing gives me trouble.
I use a Linked list to store the guessed numbers and recall them when needed.
So finally my question is:
How would I go about switching the Linked list with an Array?
Here the code:
Here the Run Class:
package fourfive;
public class Run {
/*
The Game Initializing class!
>>>> "game.getNumPlayers()" //can be uncommented if you want to play
if left commented, you can watch the bots fight to the death.
------------------------------------------------------
game.setBotPlayers //Same as getNumPlayers - defines how many (Bot) players you want to add
------------------------------------------------------
 game.setTopNum() // defines the maximum range of numbers
 which you want to guess. Starting from 0!
 -----------------------------------------------------
*/
public static void main(String[] args){
    Game game = new Game(0);
    //game.getNumPlayers();
    game.setBotPlayers(100);
    game.setTopNum(2000);
    game.start();
 }
}

Game Class:
package fourfive;

import java.util.Random;
import java.util.Scanner;

public class Game {
/*
Some Variables being defined here.
 */
private static Scanner input = new Scanner(System.in);
private int MAX_Tries;
private int TOP_Num;
private int numPlayers;
private int numBots;
private boolean gameWinner = false;
private Random rand = new Random();
private int num;
private Participants[] players; //inheritance 1
private Participants currentPlayer; //polymorphism 1

public Game(int numPlayers) {
    this(numPlayers, 10);
}

public Game(int numPlayers, int maxTries) {
    this(numPlayers, maxTries, 1000);
}

public Game(int numPlayers, int maxTries, int topNum) {
    MAX_Tries = maxTries;
    TOP_Num = topNum;
    this.numPlayers = numPlayers;
    resetPlayers();
    resetTheNumber();
}

/*
Inheritance Example 1
The following is a piece of inheritance. Whereas an array of Players whenever of the type
"Participants". Which is then resolved into the type "Human" and that is being inherited from
"Participants". And whenever Bots or Human players are joined, they will be joined within
the same array
 */
public void resetPlayers() {
    players = new Human[numPlayers + numBots];
    for (int i = 0; i < numPlayers; i++) {
        players[i] = new Human(i + 1);
    }
    for (int i = numPlayers; i < (numBots + numPlayers); i++) {
        players[i] = new Computer(i + 1, TOP_Num);
    }
}

public void setNumPlayers(int numPlayers) {
    this.numPlayers = numBots;
    resetPlayers();
}

public void setBotPlayers(int numBots) {
    this.numBots = numBots;
    resetPlayers();
}

public int getMaxTries() {
    return MAX_Tries;
}

public void setMaxTries(int maxTries) {
    this.MAX_Tries = maxTries;
}

public int getTopNum() {
    return TOP_Num;
}

public void setTopNum(int topNum) {
    this.TOP_Num = topNum;
    resetTheNumber();
    resetPlayers();
}

private void resetTheNumber() {
    num = rand.nextInt(TOP_Num);
}

public void start() {
    resetPlayers();
    System.out.println("Welcome to the Guess a Number Game!\n");
    System.out.println("Guess a number between 0 and " + (TOP_Num - 1) + "!");
    currentPlayer = players[0];
    System.out.println("The num " + num);
    /*
    Polymorphism example.
    Any object that can pore than one IS-A test is considered to be Polymorphic.
    In this case we are setting up a condition in which any given player has
    the ability to win, which is depicted from the "isCorrect()" Method.
     */
    while (!gameWinner && currentPlayer.getNumTries() < MAX_Tries) {
        for (int i = 0; i < players.length; i++) {
            //currentPlayer = players[i];
            players[i].guess();
            if (isCorrect()) {
                gameWinner = true;
                printWinner();
                break;
            } else
                printWrong();
        }
        if (!gameWinner) {
            printTriesLeft();
        }
    }
    if (!gameWinner)
        printLoser();
}

public boolean isCorrect() {
    return currentPlayer.getLastGuess() == num;
}

public void printWinner() {
    if (currentPlayer instanceof Computer)
        System.out.println("Sorry! The Bot " + currentPlayer.getPlayerNum() + " got the better of you, and guessed the number: [" + num + "] and won! Perhaps try again!");
    else
        System.out.println("GG Player " + currentPlayer.getPlayerNum() + "you guessed the Number [" + num + "] right in just " + currentPlayer.getNumTries() + " tries!");
}

public void printLoser() {
    System.out.println("Too Sad! You didn't guess within " + MAX_Tries + " tries! Try again!");
}

public void printWrong() {
    String word = "too high";
    if ((Integer.compare(currentPlayer.getLastGuess(), num)) == -1)
        word = "too low";
    System.out.println("Nope! " + word + "!");
}

public void printTriesLeft() {
    System.out.println(MAX_Tries - currentPlayer.getLastGuess() + " tries left!");
}

public void getNumPlayers() {
    System.out.print("Enter number of Persons playing => ");
    while (!input.hasNextInt()) {
        input.nextLine();
        System.out.println("Invalid input! It must be a number!");
        System.out.print("Enter the number of Players => ");
    }
    numPlayers = input.nextInt();
    System.out.print("Enter number of Bots! =>");
    while (!input.hasNextInt()) {
        input.nextLine();
        System.out.println("Invalid input! It must be a number!");
        System.out.print("Enter number of Bots! =>");
    }
    numBots = input.nextInt();
    resetPlayers();
}
}

Participants class:
package fourfive;
import java.util.LinkedList;

public abstract class Participants extends Run {
protected int numTries;
protected int playerNum;
protected LinkedList<Integer> guesses;
abstract void guess();
public int getLastGuess(){
    return guesses.peek();
}
public int getPlayerNum(){
    return playerNum;
}
public int getNumTries(){
    return guesses.size();
}
}

Now the Human class: (basically the human player)
package fourfive;
import java.util.LinkedList;
import java.util.Scanner;
public class Human extends Participants {
protected static Scanner input = new Scanner(System.in);
public Human(int playerNum) {
    numTries = 0;
    this.playerNum = playerNum;
    guesses = new LinkedList<Integer>();
}
public void guess(){
    System.out.print("Player " + playerNum + "guess =>");
    while(!input.hasNextInt()){
        input.nextLine();
        System.out.println("Invalid input!");
        System.out.print("Player " + playerNum + "guess =>");
    }
    guesses.push(input.nextInt());
}
}

And Last the Computer class:
package fourfive;
import java.util.Random;

public class Computer extends Human {
protected static Random rand = new Random();
protected int maxGuess;

Computer(int playerNum) {
    super(playerNum);
    maxGuess = 1000;
}
Computer(int playerNum, int topNum){
    super(playerNum);
    maxGuess = topNum;
}

@Override
public void guess() {
    int guess = rand.nextInt(maxGuess);
    System.out.println("Bot " + playerNum + " turn *" + guess + "*");
    guesses.push(guess);
}

public int getMaxGuess() {
    return maxGuess;
}

public void setMaxGuess(int num) {
    maxGuess = num;
}

}

A:

You would initialize the Array with a fixed size, e.g. 4 and resize if needed. For this, you need an extra attribute to store the fill level of the array.
int[] guesses = new int[4];
int guessFilling = 0;
[...]
@Override
public void guess() {
    int guess = rand.nextInt(maxGuess);
    System.out.println("Bot " + playerNum + " turn *" + guess + "*");
    if (guessFilling == guesses.length) {
        resizeGuesses();
    }
    guesses[guessFilling++] = guess;
}

private void resizeGuesses() {
    int[] newGuesses = new int[guesses.length > 0 ? 2 * guesses.length : 1];
    System.arraycopy(guesses, 0, newGuesses, 0, guesses.length);
    guesses = newGuesses;
}


Q:

Capturing group in java Regular Expression

I was working around java regular expression, but according to some examples I found for groups like below are being confused. So could anybody illustrate about the regular expression which are given by,
(?<!\d) and (?!\d)

I understood:
\d for digit
? for one or zero
! for not

What would be the about above groups mean? Please help!
Thanks in advance.

A:

The expressions (?<!\d) and (?!\d) are a "negative look behind" and a "negative look ahead". They are negative, zero-width assertions, not capturing groups.
The expression (?<!\d) asserts that the previous character is not a digit.
The expression (?!\d) asserts that the next character is not a digit.
Although they look like groups, that is just that the syntax that uses brackets.
Incidentally, they could be expressed as positive look arounds (?<=^|\D) and (?=\D|$)


Q:

Dynamically select catalog for Tomcat mysql connection pool in a Spring application

I need to create a connection pool from a spring application running in a tomcat server.
This application has many catalogs, the main catalog (its is static) called 'db' has just one table with all existing catalog names and a boolean flag for the "active" one.
When the application starts I need to choose from the main catalogs the active one, then I have to select it as default catalog.
How can I accomplish this?
Until now I used a custom class DataSourceSelector extends DriverManagerDataSource but now I need to improve the db connection using a pool, then I thought about a tomcat dbcp pool.

A:

@Configuration
public class DataAccessConfiguration {

    @Bean(destroyMethod = "close")
    public javax.sql.DataSource dataSource() {
        org.apache.tomcat.jdbc.pool.DataSource ds = new org.apache.tomcat.jdbc.pool.DataSource();
        ds.setDriverClassName("com.mysql.jdbc.Driver");
        ds.setUrl("jdbc:mysql://localhost/db");
        ds.setUsername("javauser");
        ds.setPassword("");
        ds.setInitialSize(5);
        ds.setMaxActive(10);
        ds.setMaxIdle(5);
        ds.setMinIdle(2);
        ds.get
        return ds;
    }

}


Q:

Matlab: Partly assign numbers into a symbolic matrix

I have a matrix with two different symbolic vector variables: S and K
I need to assign numbers to S but not to K. I don't know how to use for subs function in this way. Any suggestions? For example:
syms s1 s2 k1 k2 % symbols S and K vector
j1=s1*s2+s1*k1;
j2=k2*s1+k2*k1*s2*s1;
js=[j1, j2];
vars=[s1 s2];
M=jacobian(jcb,vars); % calculate the jacobian here, and the result
% should be a function of s1, s2, k1, k2

I need to assign for example s1=2 and s1=3 ans get a matrix which is function of k1 and k2. My real equations have more than 30 variables (s1 .. s30) and about 40 parameters (k1,... k40)
Thanks

A:

You can use subs to perform multiple substitutions at once as follows:
subs(M, vars, [2, 3])

Which is equivalent to:
subs(M, [s1 s2], [2, 3])


Q:

How can I solve system of linear equations in SymPy?

Sorry, I am pretty new to sympy and python in general.
I want to solve the following underdetermined linear system of equations:
x + y + z = 1
x + y + 2z = 3

A:

SymPy recently got a new Linear system solver: linsolve in sympy.solvers.solveset, you can use that as follows:
In [38]: from sympy import *

In [39]: from sympy.solvers.solveset import linsolve

In [40]: x, y, z = symbols('x, y, z')

List of Equations Form:
In [41]: linsolve([x + y + z - 1, x + y + 2*z - 3 ], (x, y, z))
Out[41]: {(-y - 1, y, 2)}

Augmented Matrix Form:
In [59]: linsolve(Matrix(([1, 1, 1, 1], [1, 1, 2, 3])), (x, y, z))
Out[59]: {(-y - 1, y, 2)}

A*x = b Form
In [59]: M = Matrix(((1, 1, 1, 1), (1, 1, 2, 3)))

In [60]: system = A, b = M[:, :-1], M[:, -1]

In [61]: linsolve(system, x, y, z)
Out[61]: {(-y - 1, y, 2)}

Note: Order of solution corresponds the order of given symbols.

A:

In addition to the great answers given by @AMiT Kumar and @Scott, SymPy 1.0 has added even further functionalities. For the underdetermined linear system of equations, I tried below and get it to work without going deeper into sympy.solvers.solveset. That being said, do go there if curiosity leads you.
from sympy import *
x, y, z = symbols('x, y, z')
eq1 = x + y + z
eq2 = x + y + 2*z
solve([eq1-1, eq2-3], (x, y,z))

That gives me {z: 2, x: -y - 1}.
Again, great package, SymPy developers!

A:

import sympy as sp
x, y, z = sp.symbols('x, y, z')
eq1 = sp.Eq(x + y + z, 1)             # x + y + z  = 1
eq2 = sp.Eq(x + y + 2 * z, 3)         # x + y + 2z = 3
ans = sp.solve((eq1, eq2), (x, y, z))

this is similar to @PaulDong answer with some minor changes

its a good practice getting used to not using import * (numpy has many similar functions)
defining equations with sp.Eq() results in cleaner code later on


Q:

Python struct string to bin

I´m learning Python.
Seeing the module struct, I found a doubt:
Is it possible to convert a "string" to "bin" without giving the length.
For the case (with chars length)
F = open("data.bin", "wb")

import struct
data = struct.pack("24s",b"This is an unknown string")
print(data)

F.write(data)

F.close()

I´m trying to do the same but with unknown length.
Thanks a lot!

A:

If you have the string, use len to determine the length of the string.
i.e
data = struct.pack("{0}s".format(len(unknown_string)), unknown_string)


Q:

I have trouble understanding the code for socket programming in python

I'm a beginner in the field of sockets and lately trying ti create a terminal chat app with that.I still have trouble understanding setblocking and select functions
"This is the code i have taken from a website i'm reading from and in the code if there is nothing in data, how does it mean that the socket has been disconnected and please also do explain what affect the setblocking in the server or the client does.I have read somewhere that setblocking allows to move on if the data has been fully not recieved,i'm not quite satisfied with the explaination.Please explain in simple words "
import select
import socket
import sys
import Queue

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setblocking(0)
server_address = ('localhost', 10000)
server.bind(server_address)
server.listen(5)
inputs = [ server ]

outputs = [ ]
message_queues = {}

while inputs:

 readable, writable, exceptional = select.select(inputs, outputs, inputs)

for s in readable:

 if s is server:

connection, client_address = s.accept()

connection.setblocking(0)
            inputs.append(connection)

 message_queues[connection] = Queue.Queue()

 else:
            data = s.recv(1024)
            if data:
                message_queues[s].put(data)
                if s not in outputs:
                    outputs.append(s)
            else:
                if s in outputs:
                    outputs.remove(s)
                inputs.remove(s)
                s.close()

A:

if there is nothing in data, how does it mean that the socket has been disconnected

The POSIX specification of recv() says:

Upon successful completion, recv() shall return the length of the message in bytes. If no messages are available to be
received and the peer has performed an orderly shutdown, recv() shall return 0. …

In the Python interface, return value 0 corresponds to a returned buffer of length 0, i. e. nothing in data.

what affect the setblocking in the server or the client does.

The setblocking(0) sets the socket to non-blocking, i. e. if e. g. the accept() or recv() cannot be completed immediately, the operation fails rather than blocks until complete. In the given code, this can hardly happen, since the operations are not tried before they are possible (due to the use of select()). However, the example is bad in that it includes output in the select() arguments, resulting in a busy loop since output is writable most of the time.


Q:

T-axis scale of a solved ODE

When I was calculating the following netwerk:

Where given was: R=5,L=1,C=4,V_C(t)=10,I_T(0)=-2,V_in(t)=20.
So the ODE that we get was:
$$
\begin{cases}
20\text{V}'_{C}(t)+\text{V}_{C}(t)+4\text{V}''_{C}(t)=20\\
\text{V}_{C}(0)=10\\
4\text{V}'_{C}(0)=-2
\end{cases}
$$
Solving this ODE, gives me:
$$\text{V}_{C}(t)=20-\frac{40\cosh\left[t\sqrt{6}\right]+17\sqrt{6}\sinh\left[t\sqrt{6}\right]}{4e^{\frac{5t}{2}}}\space\space\space\text{V}$$

QUESTION:
If I plot my found solution, than on the t-axis we get a line, but in which scale? Is it seconds, minutes? or what

A:

The t-axis is in seconds, assuming your argument is in seconds. If you do the unit analysis, you will find that the units you get are seconds, because seconds are the base SI unit of time.
For example:
The SI base of a farad: \$ s^4 * A^2 * m^{-2} * kg^{-1} \$
The SI base of an ohm: \$ kg * m^2 * s^{-3} * A^{-2} \$
Therefore, 1 ohm multiplied by 1 farad is 1 second.
The expression itself has implicit units, and if you wrote all the units out within the expression, you could use whatever time units you wish, you would simply have to evaluate with two different time units within the expression.


Q:

How to learn what `gparted`, `partitionmanager`... libcalls or `fdisk`, `parted`... commands are wrapping?

Querying partitionmananger --help does not document any verbose mode. Even gparted --help is not implemented. I wish I could use any --verbose mode without more esoteric thingy like using ltrace, because unless checking their sources one can not know if they resort only on libparted or some operations are performed using system commands, hence not being traced.
I don't know nesting strace on ltrace or vice-versa... I guess that would be a lot of standard output?
How to learn what gparted, partitionmanager... libcalls or fdisk, parted... commands are wrapping? I want to learn to use parted and fdisk in order not to need to rely on GUI interfaces such as gparted or partitionmanager, as I currently more or less know how to use the lvm suite of operations but not the more arcane fdisk and parted, but I guess it should help a lot watching actual examples of parted, fdisk and libparted being invoked by the user use of, for instance, gparted.

A:

If I understand your question correctly (and I might not), then I think that you wish to determine which libraries are being used by a particular application.  In this case ldd is your friend.
ldd /path/to/binary
gparted is actually a script (well it is on my Debian Wheezy box), and to determine the executables which are being called, simply cat /usr/sbin/gparted and read the script. When you find the exectuable files you are interested in, you can run ldd to determine which libraries are being linked to.
If you want a more verbose answer for a particular application, you can always download the source code if the software is open source, and have a look there. Usually you will find a file called INSTALL ( you can get from package developer's website or in most GNU/Linux distributions you may find it also in /usr/share/doc/) which tell you which libraries the software depends on before you can compile it.


Q:

How to generate wordclouds next to each other in Python

I have the following code that generates t figures with wordclouds:
    for t in range(n_components):
        plt.figure()
        plt.imshow(WordCloud().fit_words(lda_top_words[t]))
        plt.axis("off")
        plt.title("Topic #" + str(t))
        plt.show()

How can I change this to generate one figure with multiple plots in the same figure?

A:

I managed to solve my problem using subplots and the following code:
def display_wordcloud(top_words, title, n_components):
    plt.figure()
    j = np.ceil(n_components/4)
    for t in range(n_components):
        i=t+1
        plt.subplot(j, 4, i).set_title("Topic #" + str(t))
        plt.plot()
        plt.imshow(WordCloud().fit_words(top_words[t]))
        plt.axis("off")
    fig.suptitle(title)
    plt.show()

Here n_components are the number of plots I want to see and also the number of different topics in my topic model.
Top_words are the top Words from each topic in my topic model
And tile is the title i want for my figure
This code display 4 plots in each row.


Q:

Button_to in Ruby on Rails bad route

I'm trying to use the button_to rails helper. I wrote the following code:
<%= button_to 'Edit Item', edit_item_path(@item), :class => 'mark-button' %>
and got the following error message
No route matches "/items/1/edit"
But when I refresh the page it goes to the appropriate action. The URL of the page i get is localhost:3000/items/1/edit which is the correct URL. If I switch the button_to command to link_to the page loaded with no errors. Meaning this code:
<%= link_to 'Edit Item', edit_item_path(@item), :class => 'mark-button' %>
loads fine. Maybe there is some feature of button_to I'm not aware of, but I am at a lost.

A:

I think you might be misusing button_to. I've always thought that if you're linking to the edit action, you should be using link_to. Buttons seem to be for actions that need to post/put data such as updating a form or deleting a record.
Update:
By default, button_to uses POST instead of GET. Hence it working when you just visit the URL (ie GET).


Q:

Reading very large fixed(ish) width format txt files from SQL Server Export into R data.tables or likewise

I'm trying to read in (and eventually merge/link/manipulate) a series of large (~300M) and very large (~4G) fixed width files for eventual regressions, visualizations, etc., and am hitting some snags.
First, the format of the files themselves is odd - I'm guessing something SQL-y.  The file format is referenced here:
https://msdn.microsoft.com/en-us/library/ms191479.aspx
.  It's fixed width, but the last column seems to (sometimes?) cut off with an \r\n before the full fixed width is experienced for that column.  For reading it in I've tried laf_open_fwf and data.table::fread, but they both seem to get confused.  A sample file and the associated non-XML format descriptor is here. I can't even get the thing to read in properly with that goofy last column.  Here's a sample of the file:
1           1           7           7           ER
2           2           9           8           OI
3           54016       1988006     1953409     OI
4           54017       1988014     1953415     ER
5           54017       1988014     1953415     OB

(but note that the CR/LF are invisible here, and it's their odd placement that is the issue.  See the above link to the .txt file or png file (which I can't link, low rep) of a notepad++ view of the data to demonstrate the problem with the field.)
Second, file size is an issue.  I know I have a lot of table manipulation to do, so I'm tempted to look at data.table... but I also believe data.table stores the entire object in RAM, and that's going to be problematic.  LaF or ffdf or sqlite seem like options, though I'm new to them, and would need to cope with this file format issue first.
Some questions get at this general idea, suggesting LaF, ffbase or data.table are below...
Reading big data with fixed width
Quickly reading very large tables as dataframes in R
Speed up import of fixed width format table in R
... but none seems to (1) deal with this odd fixed-width-ish format or (2) move data eventually into data.tables, which seems like I'd like to try first.  I thought about trying to open and rewrite them as well-formatted CSVs so data.table could handle them (my goofy hack through data.frames and back to csv feels ridiculous and unscalable, below).  And the CSV export demonstates how confused the file gets, since the laf reader is strictly going by field length instead of adjusting based on where the /r/n is...
Currently I'm trying something like the below for starters.  Help, if possible?
require("data.table", "LaF", "ffbase")
searchbasis.laf = laf_open_fwf("SEARCHBASIS.txt",
                               column_widths = c(12, 12, 12, 12, 10),
                               column_names = c("SearchBasisID", "SearchID", "PersonID", "StopID", "Basis"),
                               column_types = rep("string",5),
                               trim = T)
# ^ The laf_open_fwf quietly "fails" because the last column doesn't always
# have 10 chars, but sometimes ends short with /r/n after the element.
searchbasis.dt = as.data.table(as.data.frame(laf_to_ffdf(searchbasis.laf)))
write.csv(searchbasis.dt, file="SEARCHBASIS.csv")
# ^ To take a look at the file.  Confirms that the read from laf, transfer
# to data.table is failing because of the last column issue.

A:

For this particular file:
form <- read.table("SEARCHBASIS_format.txt", as.is = TRUE, skip = 2)
x <- read.table("SEARCHBASIS.txt", col.names = form$V7, as.is = TRUE)

If you sometimes have strings including spaces you'll almost certainly need to process the file externally first.
If you're planning to read really large files I'd suggest (presuming you have awk on your path):
x <- setNames(data.table::fread("awk '{$1=$1}1' SEARCHBASIS.txt"), form$V7)

If you want to use fixed widths you could use:
x <- setNames(fread("gawk 'BEGIN {OFS = \"\t\"; FIELDWIDTHS = \"12 12 12 12 12\"} {for (i = 1; i<= NF; i++) {gsub(/ +$/, \"\", $i);}}1' SEARCHBASIS.txt"), form$V7)

You can also pull the widths from the format file:
x <- setNames(fread(paste0("gawk 'BEGIN {OFS = \"\t\"; FIELDWIDTHS = \"", paste(form$V4, collapse = " "), "\"} {for (i = 1; i<= NF; i++) {gsub(/ +$/, \"\", $i);}}1' SEARCHBASIS.txt")), form$V7)

Note $1=$1 forces awk to reevaluate the fields and the 1 at the end is effectively shorthand for print. I've also assumed you want to strip trailing spaces from each field.
On Windows you'll need to use single quotes in R and replace the single quotes within the command with " and the nested double quotes with "". So the last one above becomes:
x <- setNames(fread(paste0('gawk \"BEGIN {OFS = ""\t""; FIELDWIDTHS = ""', paste(form$V4, collapse = " "), '""} {for (i = 1; i<= NF; i++) {gsub(/ +$/, """", $i);}}1" SEARCHBASIS.txt')), form$V7)

For a cross-platform solution, you'll need to put your awk script in an external file:
stripSpace.awk
BEGIN {OFS="\t"} {for (i = 1; i<= NF; i++) {gsub(/ +$/, "", $i);}}1

R code
x <- setNames(fread(paste0('gawk -v FIELDWIDTHS="', paste(form$V4, collapse = " "), '" -f stripSpace.awk SEARCHBASIS.txt')), form$V7)

Tested on Scientific Linux 6 and Windows 8.1


Q:

JavaFX vs Java Swing usage in Industry

Why the developers refused to start new projects using super easy JavaFX package? Why they continue their projects with traditional Java Swing package? What will be the future of JavaFX? Will it be discontinued? I heard Java Swing is discontinued and no more future enhancements will be made. As a Beginner what should I learn.

A:

JavaFX is more recent and can be considered as the successor of Swing.
There is many very useful features added in JavaFX. See here some key features : https://docs.oracle.com/javase/8/javafx/get-started-tutorial/jfx-overview.htm#A1131418
I can list the main features for me:

Styles can be set by CSS (something similar to)
Bindings: easy way to
bind a ui-value, like width of text of input, to a field in class.
Changing the value of the field updates the ui without boilerplate
Animations/Transitions: easy way to make an animation, like a ui
components which blinks or moves
3D: easy way to manipulate model to
make animated 3D view

For making a new application from scratch, i think you should consider using JavaFX, Swing is outdated.

A:

Java AWT hasn't been discontinued, so it's unlikely that Java Swing will be discontinued.
If companies have existing Java Swing projects, it's usually not worthwhile financially to convert them to JavaFX.  There's also the problem that there are not many good Java Swing experts, and if you're lucky enough as a company to have a Java Swing expert that's also a User Experience (UX) expert, you don't want to rock the boat.
Companies (and Java teachers) that rely on  JApplets and Applets to deliver their UX have bigger problems with browser support than companies using Java Swing. There are companies still using Java 6 because of legacy requirements or client requirements.  For those companies, JavaFX isn't an option.
There are still more Java Swing experts on Stack Overflow than JavaFX experts available to answer questions.


Q:

UITableViewCell - Custom cell margins

I have built a UITableView which contains custom cells which are fed from a dynamic array.
My array code is here -
 feedData *feedData1 = [[feedData alloc] initWithFeedTitle:@"Fishing Article" FeedGroup:@"articleP" FeedImage:@"blah" FeedDate:@"1/11/13" FeedDesc:@"Check out this swimming article..."  FeedDestination:@"articlesSub" ];
 feedData *feedData2 = [[feedData alloc] initWithFeedTitle:@"Runnung Article" FeedGroup:@"articleP" FeedImage:@"blah" FeedDate:@"4/11/13" FeedDesc:@"Check out this marvellous article..."  FeedDestination:@"articlesSub" ];
 feedData *feedData3 = [[feedData alloc] initWithFeedTitle:@"Runnung Article" FeedGroup:@"articleP" FeedImage:@"" FeedDate:@"4/11/13" FeedDesc:@"Check out this marvellous article..."  FeedDestination:@"articlesSub" ];

 self.HpFeedArray = [NSArray arrayWithObjects:feedData1, feedData2, feedData3,  nil];

I want a margin above each cell - the only way I could figure how to do this was to split the cells up into sections, apply a section header and show one row in each section - my current code is like this -
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.HpFeedArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 10.; // you can have your own choice, of course
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *headerView = [[UIView alloc] init];
    headerView.backgroundColor = [UIColor clearColor];
    return headerView;
}

I then applied the relevant data to the relevant cells as follows -
-(UITableViewCell *)tableView:(UITableView *)tableView
    cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

static NSString *CellIdentifier =@"CellFeed";
feedData *f = [self.HpFeedArray objectAtIndex:indexPath.row];
tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
UITableViewCell *cell;

cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

CellHp_RecArticleWithImage *CellArticle = (CellHp_RecArticleWithImage *)cell;

    CellArticle.selectionStyle = UITableViewCellSelectionStyleNone;
    CellArticle.artTitle.text = f.FeedTitle;
    CellArticle.artImg.text = f.FeedDesc;
    CellArticle.artDate.text = f.FeedDate;
    CellArticle.textLabel.backgroundColor=[UIColor clearColor];

  return CellArticle;

The above displays the cells spaced apart - but displays the same data 3 times over!  Can anyone help me get my head around what im doing wrong!?
Cheers
Paul

A:

The problem is in this line
feedData *f = [self.HpFeedArray objectAtIndex:indexPath.row];

since you splitted your tableView with a row for each section if you use row for the index you will get always 0 since there is only one row. so the solution is
feedData *f = [self.HpFeedArray objectAtIndex:indexPath.section];


Q:

json structure difference after edits

I have json string that I have to edit and then transform back to json. But unfortunately I can't really restore the json structure.
The structure of the original json string ($json):
"[{"Language":{"0":"EN"},"Text":{"0":"xxx"},"ContentType":{"0":"PlainText"}},
{"Language":{"0":"DE"},"Text":{"0":"xxx"},"ContentType":{"0":"PlainText"}},
{"Language":{"0":"FR"},"Text":{"0":"xxx"},"ContentType":{"0":"PlainText"}}]"

The structure I get after my edits ($newJson):
"{"0":{"Language":{"0":"EN"},"Text":{"0":"yyy"},"ContentType":{"0":"PlainText"}},
"1":{"Language":{"0":"DE"},"Text":{"0":"yyy"},"ContentType":{"0":"PlainText"}},
"2":{"Language":{"0":"FR"},"Text":{"0":"yyy"},"ContentType":{"0":"PlainText"}}}"

Here is what I do with my edits:
$jsonArray = object_to_array(json_decode($json));
$editedJsonArray = someLoopStuff($jsonArray);
$newJson = json_encode(array_to_object(($editedJsonArray)));

function object_to_array($obj) {
    if(is_object($obj)) $obj = (array) $obj;
    if(is_array($obj)) {
        $new = array();
        foreach($obj as $key => $val) {
            $new[$key] = $this->object_to_array($val);
        }
    }
    else $new = $obj;
    return $new;
}

function array_to_object($a) {
    if (is_array($a) ) {
        foreach($a as $k => $v) {
            $a[$k] = $this->array_to_object($v);
        }
        return (object) $a;
    }
    return $a;
}

Do you have an idea how I could get the same structure as the original json?

A:

Use arrays instead of objects. Pass true to json_decode() as second argument and then do your stuff on arrays.
$jsonArray = json_decode($json, true);

Then just make your operation in loop on $jsonArray and simply use json_encode() without any additional work.

To achieve exactly same output as you have on input you need to cast subarrays on objects:
$jsonArray = json_decode('[{"Language":{"0":"EN"},"Text":{"0":"xxx"},"ContentType":{"0":"PlainText"}},{"Language":{"0":"DE"},"Text":{"0":"xxx"},"ContentType":{"0":"PlainText"}},{"Language":{"0":"FR"},"Text":{"0":"xxx"},"ContentType":{"0":"PlainText"}}]', true);

foreach ($jsonArray as &$item) {
    foreach ($item as &$val) {
        $val = (object) $val;
    }
    unset($val);
}
unset($item);

var_dump(json_encode($jsonArray));

Output:
string(226) "[{"Language":{"0":"EN"},"Text":{"0":"xxx"},"ContentType":{"0":"PlainText"}},{"Language":{"0":"DE"},"Text":{"0":"xxx"},"ContentType":{"0":"PlainText"}},{"Language":{"0":"FR"},"Text":{"0":"xxx"},"ContentType":{"0":"PlainText"}}]"


Q:

Space between Bootstrap 3 buttons

If I put several Bootstrap 3 buttons in a row:
    <button class="btn btn-default">Button 1</button>
    <button class="btn btn-default">Button 2</button>
    <button class="btn btn-default">Button 3</button>

there is a small space between them. Where does it come from and how to remove it without using float? According to the Firebug and Chrome Inspector the buttons haven't any margin applied to them.

A:

The newline between the buttons actually causes the space. Observe:

<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet"/>

<button class="btn btn-default">Button 1</button><button class="btn btn-default">Button 2</button><button class="btn btn-default">Button 3</button>

There is a button-group rule you can use if you want the buttons visually grouped: http://getbootstrap.com/components/#btn-groups

<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet"/>
<div class="btn-group" role="group" aria-label="...">
  <button type="button" class="btn btn-default">Left</button>
  <button type="button" class="btn btn-default">Middle</button>
  <button type="button" class="btn btn-default">Right</button>
</div>

A:

I believe you style your buttons display:inline-block; or inline. By default they create spaces if you have newline character.
So to remove it, put those markups next to each other without newline char.
It would get messy, but will get what you want without having a style float
So do it like this :
<button class="btn btn-default">Button 1</button><button class="btn btn-default">Button 2</button><button class="btn btn-default">Button 3</button>


Q:

How did Gandalf get his second staff back after it was destroyed by the Witch King of Angmar?

In the Return of the King film, Gandalf's staff is destroyed by the Witch-king:

During the battle of the Black Gate he uses his sword, Glamdring.
But at the end of the film, when the hobbits are leaving Middle-earth, he has it back:

But where did he get it from?
I'm looking for answers ONLY from the films!

A:

While not explicitly answered, there's no reason to believe that he couldn't have simply gotten a new one.
It's clear that he originally got his white staff from somewhere; in the book, it explicitly comes from Lothlórien:

'Thus it was that I came to Caras Galadhon and found you but lately gone. I tarried there in the ageless time of that land where days bring healing not decay. Healing I found, and I was clothed in white.
The Two Towers Book III Chapter 5: "The White Rider"

Though this isn't stated in the films, the visual design of the staff certainly implies it.
Recall also that, in the film, the final scene explicitly takes place about three years after the destruction of the Ring:

Frodo: Thirteen months to the day since Gandalf sent us on our long journey we find ourselves looking upon a familiar sight. We were home.
[...]
Frodo: It's been four years to the day since Weathertop, Sam.
Return of the King (2003)

It doesn't seem like a stretch to imagine Gandalf returning to Lórien to get a new staff sometime in those intervening years.


Q:

invalid input syntax for integer pgsql

I have just started with postgresql. I have a json object in table. There is a numeric value in the json object in which i want to add a number and assign it to other integer. This is how I am doing
declare
 total_votes integer;
....
select result into poll_result from polls where id = 1;
total_votes =  (select poll_result::json#>'{total_votes}'::integer + 1);

But this is showing
ERROR:  invalid input syntax for integer: "{total_votes}"
LINE 1: SELECT (select poll_result::json#>'{total_votes}'::integer +...

poll_result has the data like
{
    "yes": 1,
    "no": 0,
    "total_votes": 1
}

and when I try to print total_votes using
RAISE NOTICE '%',poll_result::json#>'{total_votes};

It prints 1.
even I have tried
total_votes =  (select (poll_result::json#>'{total_votes}')::integer + 1);

But the error
ERROR:  cannot cast type json to integer
LINE 1: ...ELECT (select (poll_result::json#>'{total_votes}')::integer ...

A:

The operator #> gives a json, while #>> gives a text and you need the second one:
select (poll_result::json #>> '{total_votes}')::integer + 1

or
select (poll_result::json ->> 'total_votes')::integer + 1

See JSON Functions and Operators.