问:
Change data and color of JavaFX chart dynamically
i have a little programm which connects with a Database for getting data and shows this in a StackedBarChart. Before i insert the data, i sort them for every day and customer. I have a ComboBox too, which lets the user choose the day.
So every time the day is changed, i clear the data of the chart and add new data. Then i want to change the color dynamically, because i don't know how many customers will be displayed. I know i have to do this after the Stage is shown.
At the start of the programm the first chart displayed thems to look right. The colors of the stacked bars and legend changed and don't repeat. But if i select another day the colors of the legend doesn't change and show alyways the same eight colors, which repeat of there are more then eight customers.
Here is a piece of my code:

```<code>public class BarChartSample extends Application
{
    StackPane chartPane;
    StackPane comboboxPane;
    BorderPane layout;
    Scene scene;
    StackedBarChart<String, Number> bc;
    ComboBox<String> combobox;
    ArrayList<Date> listDates;
    ArrayList<Customer> listCustomers;
    HashMap<String, ArrayList<XYChart.Series<String, Number>>> listData;
    ArrayList<Day> listDays;
    ObservableList<String> xCategories =
            FXCollections.<String> observableArrayList("6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19");
    StackedBarChart<String, Number> chart;

    @Override
    public void start(Stage stage) throws Exception
    {
        try
        {
                boolean dataExists = getDataSortedByDay();
                if (dataExists)
                {
                    stage.setTitle("Title");
                    ArrayList<String> weekdays = dateToWeekday(listDates);
                    CategoryAxis xAxis = new CategoryAxis();
                    NumberAxis yAxis = new NumberAxis();
                    xAxis.setLabel("Lieferstunde");
                    xAxis.setCategories(xCategories);
                    yAxis.setLabel("Anzahl Dokumente");
                    chart = new StackedBarChart<String, Number>(xAxis, yAxis);
                    chart.setAnimated(false);
                    chart.applyCss();
                    listData = new HashMap<String, ArrayList<XYChart.Series<String, Number>>>();
                    // create for every day a new chart and save to hashmap
                    for (Day day : listDays)
                    {
                        // create for every customer of a day a new series
                        ArrayList<XYChart.Series<String, Number>> listSeries = new ArrayList<XYChart.Series<String, Number>>();
                        for (Customer customer : day.getListCustomers())
                        {
                            XYChart.Series<String, Number> series = new XYChart.Series<String, Number>();
                            series.setName(customer.getName());
                            series.getData().add(new XYChart.Data<String, Number>(String.valueOf(customer.getHour()), customer.getNumDocs()));
                            listSeries.add(series);
                        }
                        listData.put(dateToWeekday(day.getDate()), listSeries);
                    }
                    chartPane = new StackPane();
                    chart.getData().addAll(listData.get(weekdays.get(0)));
                    chartPane.getChildren().add(chart);
                    comboboxPane = new StackPane();
                    comboboxPane.getChildren().add(createComboBoxMenu(weekdays));
                    layout = new BorderPane();
                    layout.setTop(comboboxPane);
                    layout.setCenter(chartPane);
                    scene = new Scene(layout, 1000, 800);
                    stage.setScene(scene);
                    stage.centerOnScreen();
                    stage.show();
                    chart.setTitle(weekdays.get(0));
                    changeColorsOfChart(chart);
                }
                else
                {
                    // no data found
                }
        }
        catch (ClassNotFoundException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        catch (SQLException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        catch (Exception e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
public ComboBox<String> createComboBoxMenu(ArrayList<String> weekdays)
    {
        ContextMenu contextMenu = new ContextMenu();
        for (String date : weekdays)
        {
            MenuItem menuItem = new MenuItem(date);
            contextMenu.getItems().add(menuItem);
        }
        combobox = new ComboBox<String>(FXCollections.<String> observableArrayList(weekdays));
        combobox.setContextMenu(contextMenu);
        combobox.valueProperty().addListener(new ChangeListener<String>()
        {
            @Override
            public void changed(ObservableValue<? extends String> ov, String oldValue, String newValue)
            {
                chart.getData().clear();
                chart.getData().addAll(listData.get(newValue));
                changeColorsOfChart(chart);
            }
        });
        return combobox;
    }

    public void changeColorsOfChart(StackedBarChart<String, Number> chart)
    {
        ArrayList<Color> listColors = new ArrayList<Color>();
        for (int i = 0; i < chart.getData().size(); i++)
        {
            Set<Node> seriesNodes = chart.lookupAll(".series" + i);
            String rgb = randomColorRgbFormat();
            while (listColors.contains(rgb))
            {
                rgb = randomColorRgbFormat();
            }
            for (Node n : seriesNodes)
            {
                n.setStyle("-fx-background-color: rgb(" + rgb + "); ");
            }
        }
    }

    public String randomColorRgbFormat()
    {
        Color color = new Color(Math.random(), Math.random(), Math.random(), 0);
        return String.format("%d, %d, %d, 1.0", (int) (color.getRed() * 255), (int) (color.getGreen() * 255),
                (int) (color.getBlue() * 255));
    }

    public static void main(String[] args)
    {
        launch(args);
    }
</code>```

I already looked up a lot of on stackoverflow and other websites and found jewelseas example. But i can't solve the problem when the data is always changing.
If you need further information to help me, please let me know!

答:
Thanks to Sedrick Jefferson. His link solved the problem.
This is my new code for changing the colors:</p>

```<code>public void changeColorsOfChart(StackedBarChart<String, Number> chart)
    {
        ArrayList<Color> listColors = new ArrayList<Color>();
        HashMap<String, String> colors = new HashMap<String, String>();
        for (XYChart.Series<String, Number> series : chart.getData())
        {
            String rgb = randomColorRgbFormat();
            while (listColors.contains(rgb))
            {
                rgb = randomColorRgbFormat();
            }
            for (XYChart.Data<String, Number> data : series.getData())
            {
                data.getNode().setStyle("-fx-bar-fill: rgb(" + rgb + ");");
            }
            colors.put(series.getName(), rgb);
        }
        for (Node n : chart.getChildrenUnmodifiable())
        {
            if (n instanceof Legend)
            {
                for (LegendItem items : ((Legend)n).getItems())
                {
                    String rgb = colors.get(items.getText());
                    items.getSymbol().setStyle("-fx-bar-fill: rgb(" + rgb + ");");
                }
            }
        }
    }
</code>```

Body:
i have a little programm which connects with a Database for getting data and shows this in a StackedBarChart. Before i insert the data, i sort them for every day and customer. I have a ComboBox too, which lets the user choose the day.
So every time the day is changed, i clear the data of the chart and add new data. Then i want to change the color dynamically, because i don't know how many customers will be displayed. I know i have to do this after the Stage is shown.
At the start of the programm the first chart displayed thems to look right. The colors of the stacked bars and legend changed and don't repeat. But if i select another day the colors of the legend doesn't change and show alyways the same eight colors, which repeat of there are more then eight customers.
Here is a piece of my code:

public class BarChartSample extends Application
{
    StackPane chartPane;
    StackPane comboboxPane;
    BorderPane layout;
    Scene scene;
    StackedBarChart<String, Number> bc;
    ComboBox<String> combobox;
    ArrayList<Date> listDates;
    ArrayList<Customer> listCustomers;
    HashMap<String, ArrayList<XYChart.Series<String, Number>>> listData;
    ArrayList<Day> listDays;
    ObservableList<String> xCategories =
            FXCollections.<String> observableArrayList("6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19");
    StackedBarChart<String, Number> chart;

    @Override
    public void start(Stage stage) throws Exception
    {
        try
        {
                boolean dataExists = getDataSortedByDay();
                if (dataExists)
                {
                    stage.setTitle("Title");
                    ArrayList<String> weekdays = dateToWeekday(listDates);
                    CategoryAxis xAxis = new CategoryAxis();
                    NumberAxis yAxis = new NumberAxis();
                    xAxis.setLabel("Lieferstunde");
                    xAxis.setCategories(xCategories);
                    yAxis.setLabel("Anzahl Dokumente");
                    chart = new StackedBarChart<String, Number>(xAxis, yAxis);
                    chart.setAnimated(false);
                    chart.applyCss();
                    listData = new HashMap<String, ArrayList<XYChart.Series<String, Number>>>();
                    // create for every day a new chart and save to hashmap
                    for (Day day : listDays)
                    {
                        // create for every customer of a day a new series
                        ArrayList<XYChart.Series<String, Number>> listSeries = new ArrayList<XYChart.Series<String, Number>>();
                        for (Customer customer : day.getListCustomers())
                        {
                            XYChart.Series<String, Number> series = new XYChart.Series<String, Number>();
                            series.setName(customer.getName());
                            series.getData().add(new XYChart.Data<String, Number>(String.valueOf(customer.getHour()), customer.getNumDocs()));
                            listSeries.add(series);
                        }
                        listData.put(dateToWeekday(day.getDate()), listSeries);
                    }
                    chartPane = new StackPane();
                    chart.getData().addAll(listData.get(weekdays.get(0)));
                    chartPane.getChildren().add(chart);
                    comboboxPane = new StackPane();
                    comboboxPane.getChildren().add(createComboBoxMenu(weekdays));
                    layout = new BorderPane();
                    layout.setTop(comboboxPane);
                    layout.setCenter(chartPane);
                    scene = new Scene(layout, 1000, 800);
                    stage.setScene(scene);
                    stage.centerOnScreen();
                    stage.show();
                    chart.setTitle(weekdays.get(0));
                    changeColorsOfChart(chart);
                }
                else
                {
                    // no data found
                }
        }
        catch (ClassNotFoundException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        catch (SQLException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        catch (Exception e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
public ComboBox<String> createComboBoxMenu(ArrayList<String> weekdays)
    {
        ContextMenu contextMenu = new ContextMenu();
        for (String date : weekdays)
        {
            MenuItem menuItem = new MenuItem(date);
            contextMenu.getItems().add(menuItem);
        }
        combobox = new ComboBox<String>(FXCollections.<String> observableArrayList(weekdays));
        combobox.setContextMenu(contextMenu);
        combobox.valueProperty().addListener(new ChangeListener<String>()
        {
            @Override
            public void changed(ObservableValue<? extends String> ov, String oldValue, String newValue)
            {
                chart.getData().clear();
                chart.getData().addAll(listData.get(newValue));
                changeColorsOfChart(chart);
            }
        });
        return combobox;
    }

    public void changeColorsOfChart(StackedBarChart<String, Number> chart)
    {
        ArrayList<Color> listColors = new ArrayList<Color>();
        for (int i = 0; i < chart.getData().size(); i++)
        {
            Set<Node> seriesNodes = chart.lookupAll(".series" + i);
            String rgb = randomColorRgbFormat();
            while (listColors.contains(rgb))
            {
                rgb = randomColorRgbFormat();
            }
            for (Node n : seriesNodes)
            {
                n.setStyle("-fx-background-color: rgb(" + rgb + "); ");
            }
        }
    }

    public String randomColorRgbFormat()
    {
        Color color = new Color(Math.random(), Math.random(), Math.random(), 0);
        return String.format("%d, %d, %d, 1.0", (int) (color.getRed() * 255), (int) (color.getGreen() * 255),
                (int) (color.getBlue() * 255));
    }

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

I already looked up a lot of on stackoverflow and other websites and found jewelseas example. But i can't solve the problem when the data is always changing.
If you need further information to help me, please let me know!

Body:
Thanks to Sedrick Jefferson. His link solved the problem.
This is my new code for changing the colors:

public void changeColorsOfChart(StackedBarChart<String, Number> chart)
    {
        ArrayList<Color> listColors = new ArrayList<Color>();
        HashMap<String, String> colors = new HashMap<String, String>();
        for (XYChart.Series<String, Number> series : chart.getData())
        {
            String rgb = randomColorRgbFormat();
            while (listColors.contains(rgb))
            {
                rgb = randomColorRgbFormat();
            }
            for (XYChart.Data<String, Number> data : series.getData())
            {
                data.getNode().setStyle("-fx-bar-fill: rgb(" + rgb + ");");
            }
            colors.put(series.getName(), rgb);
        }
        for (Node n : chart.getChildrenUnmodifiable())
        {
            if (n instanceof Legend)
            {
                for (LegendItem items : ((Legend)n).getItems())
                {
                    String rgb = colors.get(items.getText());
                    items.getSymbol().setStyle("-fx-bar-fill: rgb(" + rgb + ");");
                }
            }
        }
    }


来源: stackexchange

问:
Xcode 8.3 settings
I am new to Xcode and have two questions.

Main.storyboard: I want to see the whole iPhone, but now 2/3 of the screen is a white background. How to fit it to show only the whole device ?   link

I noticed that when I get an exception, there are some new windows opened in Xcode and I just can't get back to my previously opened stuff without manually closing these new windows and starting again which is pretty frustrating; how can I prevent it ?

Additional explanation: first problem
a) I set zoom and resize the window (upper image)
b) I click button in upper right corner (middle image)
c) Now I click this button once again to go back - but everything gets messed up and I need to manually resize it again  here

I just want my device to be fixed as it is in AndroidStudio for example.

答:
The solution for your first problem is like right click on the main.storyboard then you will see a menu of options where you can set the appropriate zoom level

Please provide some screenshots for the second problem.

ContentLicense: CC BY-SA 3.0

Title: Xcode 8.3 settings


问:
How does Two way binding works in Angular 2?
I am trying to use two way binding between two of my components (Parent and Child component) and trying to detect the changes caused by this in ngOnChanges of both of the components. I am able to trigger ngOnChanges of Child component (Test Component) by changing input/output property of Parent component (App Component). However, I am not able to trigger ngOnChanges of Parent component by changing two way bound property in Child component.

Working Plunker can be found here: https://plnkr.co/edit/AGh6EM9l9ENMufb9JWPW?p=preview

```<code>import { Component, OnInit, OnChange, Output, Input, EventEmitter } from '@angular/core';

@Component({
  selector: 'my-app',
  template: `<h1>Hello {{name}}</h1>
              <h3>Two Way Parent - {{twoWaySend}} </h3>

              <button (click) =  "oneWayButtonPressed()">Increase oneWay from Parent</button>
              <button (click) = "twoWayButtonPressed()">Increase TwoWay from Parent</button>
                <test-component [oneWayReceive] = 'oneWaySend'
              [(twoWayReceive)] = 'twoWaySend'></test-component>`
})
export class AppComponent implements OnChanges{
  name = 'Angular';
  oneWaySend = "You shall pass";
  twoWaySend = "You shall both ways";
  counter:int = 0;
  negativeCounter:int = 0;
  oneWayButtonPressed() {
    this.oneWaySend = `${this.oneWaySend} ${++this.counter}`;
  }
  twoWayButtonPressed() {
    this.twoWaySend = `${this.twoWaySend} ${--this.negativeCounter}`;
  }
  ngOnChanges() {
    console.log('ngOnchange Parent ' + this.twoWaySend);
  }
}

@Component({
  selector: 'test-component',
  template: `<h1>TestComponent {{name}}  {{oneWayReceive}}</h1>
            <h3>Two Way Child - {{twoWayReceive}}</h3>
            <button (click) = "twoWayButtonPressed()">Change Two Way from Child</button>`
})
export class TestComponent implements OnChange {
  @Input() oneWayReceive;
  @Input() twoWayReceive;
  @Output() twoWayReceiveChange: EventEmitter<string> = new EventEmitter<string>();
  name = 'Angular';
  negativeCounter = 0;
  ngOnChanges() {
    console.log(`OneWayReceive ${this.oneWayReceive}   TwoWayReceive ${this.twoWayReceive}`);
  }
  twoWayButtonPressed() {
    this.twoWayReceive = `${--this.negativeCounter}  ${this.twoWayReceive}`;
    this.twoWayReceiveChange.emit(this.twoWayReceive);
  }
}
</code>```

答:
Simply you can't

"I am not able to trigger ngOnChanges of Parent component by changing
  two way bound property in Child component"

you can detect that only from parent to child , if you want to pass changed value or event from child to parent you have to use @Outpput or  EventTrigger via Service

Body:
I am trying to use two way binding between two of my components (Parent and Child component) and trying to detect the changes caused by this in ngOnChanges of both of the components. I am able to trigger ngOnChanges of Child component (Test Component) by changing input/output property of Parent component (App Component). However, I am not able to trigger ngOnChanges of Parent component by changing two way bound property in Child component.

Working Plunker can be found here: https://plnkr.co/edit/AGh6EM9l9ENMufb9JWPW?p=preview

import { Component, OnInit, OnChange, Output, Input, EventEmitter } from '@angular/core';

@Component({
  selector: 'my-app',
  template: `
Hello {{name}}

Two Way Parent - {{twoWaySend}}

              <button (click) =  "oneWayButtonPressed()">Increase oneWay from Parent</button>
              <button (click) = "twoWayButtonPressed()">Increase TwoWay from Parent</button>
                <test-component [oneWayReceive] = 'oneWaySend'
              [(twoWayReceive)] = 'twoWaySend'></test-component>`
})
export class AppComponent implements OnChanges{
  name = 'Angular';
  oneWaySend = "You shall pass";
  twoWaySend = "You shall both ways";
  counter:int = 0;
  negativeCounter:int = 0;
  oneWayButtonPressed() {
    this.oneWaySend = `${this.oneWaySend} ${++this.counter}`;
  }
  twoWayButtonPressed() {
    this.twoWaySend = `${this.twoWaySend} ${--this.negativeCounter}`;
  }
  ngOnChanges() {
    console.log('ngOnchange Parent ' + this.twoWaySend);
  }
}

@Component({
  selector: 'test-component',
  template: `
TestComponent {{name}}  {{oneWayReceive}}

Two Way Child - {{twoWayReceive}}

            <button (click) = "twoWayButtonPressed()">Change Two Way from Child</button>`
})
export class TestComponent implements OnChange {
  @Input() oneWayReceive;
  @Input() twoWayReceive;
  @Output() twoWayReceiveChange: EventEmitter<string> = new EventEmitter<string>();
  name = 'Angular';
  negativeCounter = 0;
  ngOnChanges() {
    console.log(`OneWayReceive ${this.oneWayReceive}   TwoWayReceive ${this.twoWayReceive}`);
  }
  twoWayButtonPressed() {
    this.twoWayReceive = `${--this.negativeCounter}  ${this.twoWayReceive}`;
    this.twoWayReceiveChange.emit(this.twoWayReceive);
  }
}


问:
Toggling popover(); using ajax
How to toggle popover of the same element? im using ajax so im using this to refer to its specific identity, when ajax success it will toggle its own popover i took this code from w3schools and use it in mine.

HTML

```<code><input type = "text" id = "input_name" class="form-control" data-toggle="popover" title="Popover Header" data-content="Some content inside the popover">
</code>```

jQuery

```<code>$(document).on('keyup', '#input_name', function(){
    var myname = $(this).val();

    if(myname != ''){
        $.ajax({
            url:"sample.php",
            method: "POST",
            data:{myname:myname},
            dataType:"text",
            success:function(data){
                $("[data-toggle='popover']").popover();
            }
        });
    }
</code>```

I want to call its own popover.

答:
https://jsfiddle.net/ws5zojyc/3/

see above link it might help you

```<code>$(function() {
    $("#input_name").popover({
        content: "Enter a text here"
    });
});

$("#input_name").keyup(function(event) {
    var myname = $(this).val();
    // alert(myname);
    if (myname != '') {
        $.ajax({
            url: "/echo/js/?js=" + myname,
            method: "POST",
            data: {
                myname: myname
            },
            dataType: "text",
            success: function(data) {
                $('#input_name').data('bs.popover').tip().find(".popover-content").html(data)
            }
        });
    }
});
</code>```

you can use effect like hover , click etc.

Title: Toggling popover(); using ajax

Body:
How to toggle popover of the same element? im using ajax so im using this to refer to its specific identity, when ajax success it will toggle its own popover i took this code from w3schools and use it in mine.

HTML

<input type = "text" id = "input_name" class="form-control" data-toggle="popover" title="Popover Header" data-content="Some content inside the popover">

jQuery

$(document).on('keyup', '#input_name', function(){
    var myname = $(this).val();

    if(myname != ''){
        $.ajax({
            url:"sample.php",
            method: "POST",
            data:{myname:myname},
            dataType:"text",
            success:function(data){
                $("[data-toggle='popover']").popover();
            }
        });
    }

I want to call its own popover.

Body:
https://jsfiddle.net/ws5zojyc/3/

see above link it might help you

$(function() {
    $("#input_name").popover({
        content: "Enter a text here"
    });
});

$("#input_name").keyup(function(event) {
    var myname = $(this).val();
    // alert(myname);
    if (myname != '') {
        $.ajax({
            url: "/echo/js/?js=" + myname,
            method: "POST",
            data: {
                myname: myname
            },
            dataType: "text",
            success: function(data) {
                $('#input_name').data('bs.popover').tip().find(".popover-content").html(data)
            }
        });
    }
});

you can use effect like hover , click etc.


问:
mongodb connect fail in osx
I'm newer to mongode, I use shell to start mongodb service but failed and get following error. What should I do?

mongod log
enter image description here

mongo log

MongoDB shell version v3.4.4
connecting to: mongodb://127.0.0.1:27017
2017-05-07T07:59:40.141+1000 W NETWORK  [thread1] Failed to connect to 127.0.0.1:27017, in(checking socket for error after poll), reason: Connection refused
2017-05-07T07:59:40.142+1000 E QUERY    [thread1] Error: couldn't connect to server 127.0.0.1:27017, connection attempt failed :
connect@src/mongo/shell/mongo.js:237:13
@(connect):1:6
exception: connect failed

答:
Step 1: Please check whether you have C:\data\db. If you dont have it create it manually.

Step 2: in command line go to directory of mongodb such as c:\Program files\Mongodb\server\3.4\bin and type *mongod

Step 3: type Mongo

Hopefully its gonna work out for you.

Title: mongodb connect fail in osx


问:
Socket.io > calling client-side functions from server?
I am trying to execute functions on the client side from a node server using socket.io. The data is getting to the client side no problem but I am not able to execute functions on connect.

My server code (emit in a loop):

```<code>var io = require('socket.io')(server);
io.on('connection', function(client){
    setInterval(function(){
        client.emit('for_client', datatosend);
    }, 100);
});
</code>```

My client side code:

```<code>socket.on('for_client', function (data) {

    console.log(data);

    switch(true) {
        case (data == "reload"):
            console.log('DO reload');  //<<< not working
            break;

        case (data == "switch"):
            console.log('DO switch');  //<<< not working
            break;

        default:
            console.log(data);  //<<< this DOES work
    }

});
</code>```

And here is proof the data is coming through ;)

Any help is super appreciated.

答:
```<code>//comparison operator in the switch " "==> it get the data as string  below method worked for me just normal comparison
switch(true) {
    case data == reload:
        console.log('DO reload');  //will work just test
        break;

    case data == switch:
        console.log('DO switch');  ///working
        break;

    default:
        console.log(data);  //<<< this DOES work
}
</code>```

Body:
I am trying to execute functions on the client side from a node server using socket.io. The data is getting to the client side no problem but I am not able to execute functions on connect.

My server code (emit in a loop):

var io = require('socket.io')(server);
io.on('connection', function(client){
    setInterval(function(){
        client.emit('for_client', datatosend);
    }, 100);
});

My client side code:

socket.on('for_client', function (data) {

    console.log(data);

    switch(true) {
        case (data == "reload"):
            console.log('DO reload');  //<<< not working
            break;

        case (data == "switch"):
            console.log('DO switch');  //<<< not working
            break;

        default:
            console.log(data);  //<<< this DOES work
    }

});

And here is proof the data is coming through ;)

Any help is super appreciated.


问:
Maximum length of Intent putExtra method? (Force close)
I need some help with debugging my application. First of all: In emulator and on some other devices my app is running fine. On my device I got a force close (without a force close message).

The "crash" happens if the Activity of the app is changed.

Here is some code of the MainActivity class. It just reads html content from a web page over webview. And no, it is NOT possible to do this over HttpRequest because I was not able to simulate the post request.

```<code>public class MainActivity extends Activity {

    public final static String EXTRA_HTML = "com.example.com.test.HTML";

    private WebView mWebView;
    private ProgressDialog mDialog;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mWebView = (WebView) findViewById(R.id.webView1);
        CookieSyncManager.createInstance(this);
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.removeAllCookie();
        mWebView.setBackgroundColor(0);
        mWebView.setWebChromeClient(new WebChromeClient() {
            public boolean onConsoleMessage(ConsoleMessage cmsg) {
                if (cmsg.message().startsWith("MAGIC")) {
                    mDialog.cancel();
                    /*HashMap<String, String> message = new HashMap<String, String>();*/
                    String msg = cmsg.message().substring(5);
                    Intent intent = new Intent(MainActivity.this,
                        ReadDataActivity.class);
                    /*message.put("message", msg);*/
                    /*intent.putExtra(EXTRA_HTML, message);*/
                                    intent.putExtra(EXTRA_HTML, msg);
                    startActivity(intent);
                }
                return false;
            }
        });
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.getSettings().setPluginState(PluginState.OFF);
        mWebView.getSettings().setLoadsImagesAutomatically(false);
        mWebView.getSettings().setBlockNetworkImage(true);
        mWebView.getSettings().setAppCacheEnabled(true);
        mWebView.getSettings().setSavePassword(true);
        mWebView.getSettings()
                .setCacheMode(WebSettings.LOAD_NORMAL);
        mWebView.setWebViewClient(new WebViewClient() {

            public void onPageFinished(WebView view, String address) {
                if (address.indexOf("mySession") != -1) {
                    view.loadUrl("javascript:console.log('MAGIC'+document.getElementsByTagName('html')[0].innerHTML);");
                }
});

                mWebView.loadUrl("http://www.myurl.de");

}
</code>```

So, in the onConsoleMessage() method I just pass the html code to another Activity class which read, parse and display the content.

The problem is now that at this point when the ReadDataActivity class should be loaded the application just close and go back to the home screen without any message or user dialog.

Is it possible that the html code which is passed as a string to the ReadDataActivity is to big? I also try to add the html code as a string in a HashMap but the problem is the same.

Some ideas what I can do to debug the problem? Maybe I should try to create a Parcelable object?

In the emulator everything is working fine.

答:
The fixed size of 1MB is not only limited to intents. As Intents, Content Providers, Messenger, all system services like Telephone, Vibrator etc. utilize IPC infrastructure provider by Binder. Moreover the activity lifecycle callbacks also use this infrastructure.

1MB is the overall limit on all the binder transactions executed in the system at a particular moment.

In case there are lot of transactions happening when the intent is sent,it may fail even though extra data is not large.

http://codetheory.in/an-overview-of-android-binder-framework/

ContentLicense: CC BY-SA 4.0

Body:
I need some help with debugging my application. First of all: In emulator and on some other devices my app is running fine. On my device I got a force close (without a force close message).

The "crash" happens if the Activity of the app is changed.

Here is some code of the MainActivity class. It just reads html content from a web page over webview. And no, it is NOT possible to do this over HttpRequest because I was not able to simulate the post request.

public class MainActivity extends Activity {

    public final static String EXTRA_HTML = "com.example.com.test.HTML";

    private WebView mWebView;
    private ProgressDialog mDialog;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mWebView = (WebView) findViewById(R.id.webView1);
        CookieSyncManager.createInstance(this);
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.removeAllCookie();
        mWebView.setBackgroundColor(0);
        mWebView.setWebChromeClient(new WebChromeClient() {
            public boolean onConsoleMessage(ConsoleMessage cmsg) {
                if (cmsg.message().startsWith("MAGIC")) {
                    mDialog.cancel();
                    /*HashMap<String, String> message = new HashMap<String, String>();*/
                    String msg = cmsg.message().substring(5);
                    Intent intent = new Intent(MainActivity.this,
                        ReadDataActivity.class);
                    /*message.put("message", msg);*/
                    /*intent.putExtra(EXTRA_HTML, message);*/
                                    intent.putExtra(EXTRA_HTML, msg);
                    startActivity(intent);
                }
                return false;
            }
        });
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.getSettings().setPluginState(PluginState.OFF);
        mWebView.getSettings().setLoadsImagesAutomatically(false);
        mWebView.getSettings().setBlockNetworkImage(true);
        mWebView.getSettings().setAppCacheEnabled(true);
        mWebView.getSettings().setSavePassword(true);
        mWebView.getSettings()
                .setCacheMode(WebSettings.LOAD_NORMAL);
        mWebView.setWebViewClient(new WebViewClient() {

            public void onPageFinished(WebView view, String address) {
                if (address.indexOf("mySession") != -1) {
                    view.loadUrl("javascript:console.log('MAGIC'+document.getElementsByTagName('html')[0].innerHTML);");
                }
});

                mWebView.loadUrl("http://www.myurl.de");

}

So, in the onConsoleMessage() method I just pass the html code to another Activity class which read, parse and display the content.

The problem is now that at this point when the ReadDataActivity class should be loaded the application just close and go back to the home screen without any message or user dialog.

Is it possible that the html code which is passed as a string to the ReadDataActivity is to big? I also try to add the html code as a string in a HashMap but the problem is the same.

Some ideas what I can do to debug the problem? Maybe I should try to create a Parcelable object?

In the emulator everything is working fine.


问:
Advantages of IQueryable<T> over IList<T>
In C# DAL, What advantages will i derive if i return IQueryable than IList, Iam not using Entity Framework / N Hibernate, just plain old ADO.Net.. </p>

答:
You should return an IEnumerable instead of IList or IQueryable:

IQueryable makes the caller think they can use lazy evaluation and add filters, sorting, projection, etc.

IList allows the caller to add, remove, reverse, set values, and otherwise modify the returned collection.  This might not be a problem for you, but if you plan on sharing data between calls then you need to watch out for this

IEnumerable provides the caller an immutable collection which they know doesn't not support lazy evaluation.

ContentLicense: CC BY-SA 2.5


问:
Android Studio 2.3 - Cannot lock System Folders
I'm new to Android App Development and am using Android Studio 2.3 to learn it. I've been working on it for a week now but now I'm getting the following error:

port lock error

Currently I'm working on a project so I need this error to be resolved.
Please help.

答:
try this my friend

Go to folder where android-studio is installed. (e.g. C:\Program Files (x86)\Android\android-studio)

Now go one folder back. (i.e. C:\Program Files (x86)\Android)

Right click on the android-studio folder and click to Properties.

Once in the Properties window, go to the Security tab.

Click the Edit button

In the new window that opens up click the Users (your-username-or-your-group-name)

From the list below, check Allow in front of Full control.

Press OK, then again OK.
I hope it help you!

for more information follow this link


问:
Make Column value as key using JSON function in Postgres
I'm using Postgres database and have a table as below

```<code>Table Name: Test

id    firstname    lastname
 1     Sam          Crews
 2     John         Dave
</code>```

I'm trying to get result set back in below JSON format but with no luck

Expected:

```<code>[{"1": {"firstname": "Sam", "lastname": "Crews"}},
 {"2": {"firstname": "John", "lastname": "Dave"}}
]
</code>```

I tried using row_to_json, json_build_object functions but the output is bit different (as below).

Actual:

```<code>[{"id": "1", "firstname": "Sam", "lastname": "Crews"},
 {"id": "2", "firstname": "John", "lastname": "Dave"}
]
</code>```

Any pointers on how to achieve expected result would be greatly appreciated.

Thank you!

答:
row_to_json() will always use all column names to create the keys in the JSON document. If you only want two columns, you need to explicitly specify them.

You also want a nested JSON object, so you need to nest the methods to create one:

```<code>select json_agg(json_build_object(
                 id,
                 json_build_object('firstname', firstname, 'lastname', lastname))
                )
from the_table;
</code>```

Klin made me realize that with Postgres 9.6 you can simplify the creation of the firstname/lastname object:

```<code>select json_agg(json_build_object(id, to_jsonb(the_table) - 'id'))
from the_table;
</code>```

Body:
I'm using Postgres database and have a table as below

Table Name: Test

id    firstname    lastname
 1     Sam          Crews
 2     John         Dave

I'm trying to get result set back in below JSON format but with no luck

Expected:

[{"1": {"firstname": "Sam", "lastname": "Crews"}},
 {"2": {"firstname": "John", "lastname": "Dave"}}
]

I tried using row_to_json, json_build_object functions but the output is bit different (as below).

Actual:

[{"id": "1", "firstname": "Sam", "lastname": "Crews"},
 {"id": "2", "firstname": "John", "lastname": "Dave"}
]

Any pointers on how to achieve expected result would be greatly appreciated.

Thank you!

Body:
row_to_json() will always use all column names to create the keys in the JSON document. If you only want two columns, you need to explicitly specify them.

You also want a nested JSON object, so you need to nest the methods to create one:

select json_agg(json_build_object(
                 id,
                 json_build_object('firstname', firstname, 'lastname', lastname))
                )
from the_table;

Klin made me realize that with Postgres 9.6 you can simplify the creation of the firstname/lastname object:

select json_agg(json_build_object(id, to_jsonb(the_table) - 'id'))
from the_table;


问:
My VBS script is looking for file in wrong directory

The macro I had written was working fine until I happened to change the file path to a relative one.

Here is the actual macro:

```<code>Public Sub refreshXLS()
    Dim fso As Object
    Dim folder As Object
    Dim file As Object
    Path = ThisWorkbook.Path & "\requiredSource\TestData1.xlsm"
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set folder = fso.GetFolder(Path)

    With Application
        .DisplayAlerts = False
        .ScreenUpdating = False
        .EnableEvents = False
        .AskToUpdateLinks = False
    End With

    For Each file In folder.Files
        If Right(file.Name, 4) = "xlsx" Or Right(file.Name, 3) = "xls" Then
            Workbooks.Open Path & file.Name
            ActiveWorkbook.UpdateLink Name:=ActiveWorkbook.LinkSources
            ActiveWorkbook.Close True
         End If
    Next

        With Application
        .DisplayAlerts = False
        .ScreenUpdating = True
        .EnableEvents = True
        .AskToUpdateLinks = False
    End With
End Sub
</code>```

I updated it to:

```<code>Public Sub refreshXLS()

    Dim xlApp
    Dim xlBook
    Dim fso As Object
    Dim folder As Object
    Dim file As Object
    Set fso = CreateObject("Scripting.FileSystemObject")
    Dim fullpath
    fullpath = fso.GetAbsolutePathName(".")
    Set fso = Nothing
    Set xlApp = CreateObject("Excel.Application")
    Path = xlApp.Workbooks.Open(fullpath & "\TestData1.xlsm")
    Set folder = fso.GetFolder(Path)

    With Application
        .DisplayAlerts = False
        .ScreenUpdating = False
        .EnableEvents = False
        .AskToUpdateLinks = False
    End With

    For Each file In folder.Files
        If Right(file.Name, 4) = "xlsx" Or Right(file.Name, 3) = "xls" Then
            Workbooks.Open Path & file.Name
            ActiveWorkbook.UpdateLink Name:=ActiveWorkbook.LinkSources
            ActiveWorkbook.Close True
         End If
    Next

        With Application
        .DisplayAlerts = False
        .ScreenUpdating = True
        .EnableEvents = True
        .AskToUpdateLinks = False
    End With
End Sub
</code>```

I also tried to use:

```<code>Workbooks.Open FileName:= ThisWorkbook.Path & "\TestData1.xlms".
</code>```

This didn't help either.

答:
Your code fails to work because you changed the variable Path.

You put Path = xlApp.Workbooks.Open(fullpath & "\TestData1.xlsm") which means the Path is now a Workbook Object, not a String anymore.

I suggest you to start using Option Explicit as a habit. In VBE, Options --> tick Require Variable Declaration.

Body:
The macro I had written was working fine until I happened to change the file path to a relative one.

Here is the actual macro:

Public Sub refreshXLS()
    Dim fso As Object
    Dim folder As Object
    Dim file As Object
    Path = ThisWorkbook.Path & "\requiredSource\TestData1.xlsm"
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set folder = fso.GetFolder(Path)

    With Application
        .DisplayAlerts = False
        .ScreenUpdating = False
        .EnableEvents = False
        .AskToUpdateLinks = False
    End With

    For Each file In folder.Files
        If Right(file.Name, 4) = "xlsx" Or Right(file.Name, 3) = "xls" Then
            Workbooks.Open Path & file.Name
            ActiveWorkbook.UpdateLink Name:=ActiveWorkbook.LinkSources
            ActiveWorkbook.Close True
         End If
    Next

        With Application
        .DisplayAlerts = False
        .ScreenUpdating = True
        .EnableEvents = True
        .AskToUpdateLinks = False
    End With
End Sub

I updated it to:

Public Sub refreshXLS()

    Dim xlApp
    Dim xlBook
    Dim fso As Object
    Dim folder As Object
    Dim file As Object
    Set fso = CreateObject("Scripting.FileSystemObject")
    Dim fullpath
    fullpath = fso.GetAbsolutePathName(".")
    Set fso = Nothing
    Set xlApp = CreateObject("Excel.Application")
    Path = xlApp.Workbooks.Open(fullpath & "\TestData1.xlsm")
    Set folder = fso.GetFolder(Path)

    With Application
        .DisplayAlerts = False
        .ScreenUpdating = False
        .EnableEvents = False
        .AskToUpdateLinks = False
    End With

    For Each file In folder.Files
        If Right(file.Name, 4) = "xlsx" Or Right(file.Name, 3) = "xls" Then
            Workbooks.Open Path & file.Name
            ActiveWorkbook.UpdateLink Name:=ActiveWorkbook.LinkSources
            ActiveWorkbook.Close True
         End If
    Next

        With Application
        .DisplayAlerts = False
        .ScreenUpdating = True
        .EnableEvents = True
        .AskToUpdateLinks = False
    End With
End Sub

I also tried to use:

Workbooks.Open FileName:= ThisWorkbook.Path & "\TestData1.xlms".

This didn't help either.


问:
I have 2 js file but the second doesn't work
I have the first js file with all my things and also my buttons already created with a specified class.
In the second js file i wanted to do some events when that button with that class is clicked but it doesn't work. Any suggestions?

this is my call to the first js file

```<code><script src="js/tmdb/searchFilm.js"></script>
</code>```

then on the file I create this element:

```<code>var td = tr.insertCell();
   var btn = document.createElement("button");
   btn.setAttribute("type", "button");
   btn.setAttribute("id",ids[i]);
   btn.setAttribute("class","btnInfo");
   var t = document.createTextNode("More info");
   btn.appendChild(t);
</code>```

and everything is ok

but in the second  js file i have thi

```<code>  $(document).ready(function () {
      $('.btnInfo').click(function (event) {
          console.log("arrivato");
      });
  });
</code>```

but if i add the script as the first one it does not work, any suggestions?

zero output on the console

答:
Try renaming event in

```<code>$('.btnInfo').click(function (event) {
    console.log("arrivato");
});
</code>```

to something else, like e. That should fix it.

Body:
I have the first js file with all my things and also my buttons already created with a specified class.
In the second js file i wanted to do some events when that button with that class is clicked but it doesn't work. Any suggestions?

this is my call to the first js file

then on the file I create this element:

var td = tr.insertCell();
   var btn = document.createElement("button");
   btn.setAttribute("type", "button");
   btn.setAttribute("id",ids[i]);
   btn.setAttribute("class","btnInfo");
   var t = document.createTextNode("More info");
   btn.appendChild(t);

and everything is ok

but in the second  js file i have thi

  $(document).ready(function () {
      $('.btnInfo').click(function (event) {
          console.log("arrivato");
      });
  });

but if i add the script as the first one it does not work, any suggestions?

zero output on the console

Body:
Try renaming event in

$('.btnInfo').click(function (event) {
    console.log("arrivato");
});

to something else, like e. That should fix it.


问:
passing jquery var from view to controller in codeigniter
This is in script .ready() function which fetch existing files from database and putting in jquery var splitfiles. which is in array formate.

```<code>  var splitfiles = '<?php echo @$projectDetails->upload_file; ?>';
</code>```

this line gives array of attached file from view in controller

```<code> $arrayoffiles = json_encode($joinfiles);
</code>```

I want to get  this splitfiles var in controller and then merge with  $arrayoffiles after that store in database with other form data.

I tried with this solution to pass 'splitfiles' to controller by this bellow code but i am not getting in the controller

```<code> $(document).ready(function() {
    $.ajax({
    url: '<?php echo site_url("trusts/fundsRaisingModule"); ?>',
    type: 'GET',
    dataType: 'json',

    data: {
        splitfiles:splitfiles,
        // key : value pair. You can send as many pair as you want like this
    }

   });
 });
</code>```

In controller i am not getting the 'splitfiles'

```<code>    $files=$_REQUEST['splitfiles'];
</code>```

giving error :undefined index 'splitfiles'
so help me to pass jquery variable from view to controller in codeigniter
after that i will try to merge the two arrays
Thanks in advance.

答:
To achieve this use jquery ajax() and send the js variable to controller method and use it as you want.

Its syntax is:

```<code>$(document).ready(function(){
    $.ajax({
        url: 'controller_method',
        type: 'POST',
        data: {
            splitfiles  :splitfiles,
            // key : value pair. You can send as many pair as you want like this
        },
        success: function(response){    // response from process
            // do your stuff here
        }
    });
});
</code>```

controller_method

```<code>$splitfiles = $_REQUEST['splitfiles'];
// do your stuff here
</code>```

Note: Don't forget to add the jquery library in your code.

Body:
This is in script .ready() function which fetch existing files from database and putting in jquery var splitfiles. which is in array formate.

  var splitfiles = '<?php echo @$projectDetails->upload_file; ?>';

this line gives array of attached file from view in controller

 $arrayoffiles = json_encode($joinfiles);

I want to get  this splitfiles var in controller and then merge with  $arrayoffiles after that store in database with other form data.

I tried with this solution to pass 'splitfiles' to controller by this bellow code but i am not getting in the controller

 $(document).ready(function() {
    $.ajax({
    url: '<?php echo site_url("trusts/fundsRaisingModule"); ?>',
    type: 'GET',
    dataType: 'json',

    data: {
        splitfiles:splitfiles,
        // key : value pair. You can send as many pair as you want like this
    }

   });
 });

In controller i am not getting the 'splitfiles'

    $files=$_REQUEST['splitfiles'];

giving error :undefined index 'splitfiles'
so help me to pass jquery variable from view to controller in codeigniter
after that i will try to merge the two arrays
Thanks in advance.

Body:
To achieve this use jquery ajax() and send the js variable to controller method and use it as you want.

Its syntax is:

$(document).ready(function(){
    $.ajax({
        url: 'controller_method',
        type: 'POST',
        data: {
            splitfiles  :splitfiles,
            // key : value pair. You can send as many pair as you want like this
        },
        success: function(response){    // response from process
            // do your stuff here
        }
    });
});

controller_method

$splitfiles = $_REQUEST['splitfiles'];
// do your stuff here

Note: Don't forget to add the jquery library in your code.


问:
Laravel Conditional Clause When()
I am new to Laravel and have encountered a problem using when() function. To start this  I do have a form consisting of 3 input fields named: name, email, and password.

```<code><form method="post" action="/users">
    <?php echo csrf_field(); ?>
    <input type="text" name="name" placeholder="Name">
    <input type="email" name="email" placeholder="Email">
    <input type="password" name="password" placeholder="Password">
<input type="submit" value="Create">
</form>
</code>```

Also I have this code inside a controller file.

```<code>$role = $request->input('role');

        $first = User::when($role,function ($query) use ($role){
            return $query->where('username',$role);
        })->get();
</code>```

Based on Laravel documentation this shouldn't work as no elements named 'role' in the form that I submitted and $role variable must return false. But when I loop the $first variable, It has all the records inside of Users table. So I tried correcting and put

```<code>$role = $request->input('name');
</code>```

So it works perfectly when I put a name that is inside the User table. But when I type nothing at (input type='text' name='name') element and submit the form. It shows all the records inside of Users table again. I am really confused, I think it has something to do with the 'false' or 'empty' returned by the $request->input(). Please advise. Thanks.

答:
When $role is false, the closure is not executed, so you'll simply get this query:

```<code>User::get();
</code>```

This query will just return all users.

You need to use simple where() in this situation:

```<code>User::where('username', $role)->first();
</code>```

It will return an User object or null if $role is empty.

Title: Laravel Conditional Clause When()

Body:
I am new to Laravel and have encountered a problem using when() function. To start this  I do have a form consisting of 3 input fields named: name, email, and password.

<form method="post" action="/users">
    <?php echo csrf_field(); ?>
    <input type="text" name="name" placeholder="Name">
    <input type="email" name="email" placeholder="Email">
    <input type="password" name="password" placeholder="Password">
<input type="submit" value="Create">
</form>

Also I have this code inside a controller file.

$role = $request->input('role');

        $first = User::when($role,function ($query) use ($role){
            return $query->where('username',$role);
        })->get();

Based on Laravel documentation this shouldn't work as no elements named 'role' in the form that I submitted and $role variable must return false. But when I loop the $first variable, It has all the records inside of Users table. So I tried correcting and put

$role = $request->input('name');

So it works perfectly when I put a name that is inside the User table. But when I type nothing at (input type='text' name='name') element and submit the form. It shows all the records inside of Users table again. I am really confused, I think it has something to do with the 'false' or 'empty' returned by the $request->input(). Please advise. Thanks.

Body:
When $role is false, the closure is not executed, so you'll simply get this query:

User::get();

This query will just return all users.

You need to use simple where() in this situation:

User::where('username', $role)->first();

It will return an User object or null if $role is empty.


问:
Date not showing in div
I have View with div where I need to show date

I write this JavaScript code

$(document).ready(function() {
  var dateObj = new Date();
  var month = dateObj.getUTCMonth() + 1; //months from 1-12
  var day = dateObj.getUTCDate();
  var year = dateObj.getUTCFullYear();

  newdate = year + "/" + month + "/" + day;
  $("#id").append(newdate);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="date" style="width: 100%; height: 10%; background:#1d69b4 ">

</div></code>```

答:
Change

```<code>$("#id").append(newdate);
</code>```

To

```<code>$("#date").append(newdate);
</code>```

This is a selector for getting an element with ID as date

Title: Date not showing in div

Body:
Change

$("#id").append(newdate);

To

$("#date").append(newdate);

This is a selector for getting an element with ID as date


问:
CardView Strange Behaviour
I have a simple layout with CardView

```<code><android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/cv_tag"
android:layout_width="wrap_content"
android:layout_height="@dimen/tag_height"
android:layout_margin="4dp"
android:clickable="true"
app:cardCornerRadius="20dp"
app:cardElevation="2dp">

<FrameLayout
    android:id="@+id/fl_selection_indicator"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/tv_tag"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:padding="8dp"
        android:textAppearance="@style/PrimaryWhiteText.Tiny"
        tools:text="Hard"/>

</FrameLayout>

</android.support.v7.widget.CardView>
</code>```

And it's rendering not as I expect it to. It looks like system wraps this layout into FrameLayout with elevation and white background. Interesting thing is if I wrap this layout into FrameLayout by myself elevation goes away but white background is still there (Background of frame layout not CardView)

How to remove elevation and white background and why is it happening?

Thanks in advance!

答:
Original answer is here

My latout is for custom view and when I add setBackgroundColor(ContextCompat.getColor(context, android.R.color.transparent)); to its contructors elevation and white background have gone.

Title: CardView Strange Behaviour

Body:
I have a simple layout with CardView

<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/cv_tag"
android:layout_width="wrap_content"
android:layout_height="@dimen/tag_height"
android:layout_margin="4dp"
android:clickable="true"
app:cardCornerRadius="20dp"
app:cardElevation="2dp">

<FrameLayout
    android:id="@+id/fl_selection_indicator"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/tv_tag"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:padding="8dp"
        android:textAppearance="@style/PrimaryWhiteText.Tiny"
        tools:text="Hard"/>

</FrameLayout>

</android.support.v7.widget.CardView>

And it's rendering not as I expect it to. It looks like system wraps this layout into FrameLayout with elevation and white background. Interesting thing is if I wrap this layout into FrameLayout by myself elevation goes away but white background is still there (Background of frame layout not CardView)

How to remove elevation and white background and why is it happening?

Thanks in advance!


Title: Make Column value as key using JSON function in Postgres

Body:
with my_table(id, firstname, lastname) as (
values
(1, 'Sam', 'Crews'),
(2, 'John', 'Dave')
)

select jsonb_agg(obj)
from my_table,
jsonb_build_object(id, to_jsonb(my_table)- 'id') obj

                                              jsonb_agg
------------------------------------------------------------------------------------------------------
 [{"1": {"lastname": "Crews", "firstname": "Sam"}}, {"2": {"lastname": "Dave", "firstname": "John"}}]
(1 row)


问:
UISearchController makes the controller black
I am using UISearchController in iOS 8 with the following intializaiton in viewDidLoad of a view controller embedded in a tab controller

```<code> _searchController = [[UISearchController alloc] initWithSearchResultsController:nil];

    _searchBar = _searchController.searchBar;
    [_searchController.searchBar sizeToFit];
    _searchController.searchBar.delegate = self;
   _searchController.searchResultsUpdater = self;
    _searchController.dimsBackgroundDuringPresentation = NO;
    _searchController.hidesNavigationBarDuringPresentation  = NO;
    self.definesPresentationContext = NO;
    _shopsTable.tableHeaderView = _searchController.searchBar;
</code>```

I've implemented

- (void) updateSearchResultsForSearchController:(UISearchController *)searchController  and (void)filterContentForSearchText:(NSString *)searchText

and the search works, the tableview gets updated properly, etc.

But!

If I switch tabs while the searchcontroller is active (just tapping the search bar or with some text) to a different tab, and then go back to teh search tab, I get a blank screen with only the search bar, like this

In this case, I search for things that start with lar, which did return results and displayed them correcly. But if I switch tabs, and return to the search tab I get a blank screen like this. The only way the controller returns to its original state is if I do _searchController.active = NO. But if the user wants to keep that search active, I can't just deactivate it.

I am sure I am missing something, but since there isn't much to do in UISeachController, I can't figure out what is causing this..

答:
Write the below code in viewDidLoad mehtod.

self.definesPresentationContext = true

searchController.searchResultsUpdater = self

searchController.searchBar.delegate = self

searchController.dimsBackgroundDuringPresentation = false
searchController.definesPresentationContext = true

Body:
I am using UISearchController in iOS 8 with the following intializaiton in viewDidLoad of a view controller embedded in a tab controller

 _searchController = [[UISearchController alloc] initWithSearchResultsController:nil];

    _searchBar = _searchController.searchBar;
    [_searchController.searchBar sizeToFit];
    _searchController.searchBar.delegate = self;
   _searchController.searchResultsUpdater = self;
    _searchController.dimsBackgroundDuringPresentation = NO;
    _searchController.hidesNavigationBarDuringPresentation  = NO;
    self.definesPresentationContext = NO;
    _shopsTable.tableHeaderView = _searchController.searchBar;

I've implemented

- (void) updateSearchResultsForSearchController:(UISearchController *)searchController  and (void)filterContentForSearchText:(NSString *)searchText

and the search works, the tableview gets updated properly, etc.

But!

If I switch tabs while the searchcontroller is active (just tapping the search bar or with some text) to a different tab, and then go back to teh search tab, I get a blank screen with only the search bar, like this

In this case, I search for things that start with lar, which did return results and displayed them correcly. But if I switch tabs, and return to the search tab I get a blank screen like this. The only way the controller returns to its original state is if I do _searchController.active = NO. But if the user wants to keep that search active, I can't just deactivate it.

I am sure I am missing something, but since there isn't much to do in UISeachController, I can't figure out what is causing this..


问:
Can Masonry use as RTL (Right-To-Left) direction
Masonry worked fine with the text direction from LTR (Left-To-Right). Now I want to use masonry with the text direction RTL (Right-To-Left [Middle eastern languages such as Hebrew and Arabic are written predominantly right-to-left.] ).

Whenever I run masonry on the RTL (Right-To-Left)  text direction, the masonry plugin setups all its grid layout in the LTR (Left-To-Right) format.

I also go through from the masonry plugin's documentation but didn't find any setting related to RTL (Right-To-Left)  direction.

Any proposed solution?

答:
OriginLeft

Controls the horizontal flow of the layout. By default, item elements start positioning at the left, with originLeft: true. Set originLeft: false for right-to-left layouts.

```<code>originLeft: false
</code>```

Body:
OriginLeft

Controls the horizontal flow of the layout. By default, item elements start positioning at the left, with originLeft: true. Set originLeft: false for right-to-left layouts.

originLeft: false


问:
Warning: PhantomJS not found
I have installed nodejs 0.10.15 on debian 6. Using npm I have then installed:

```<code>sudo npm install grunt-cli -g
</code>```

I have also executed npm install in my local test directory (downloading the necessary dependencies to the node_modules directory) which contains the following package.json file:

```<code>{
  "name": "sample-name",
  "version": "1.4.0",
  "devDependencies": {
    "grunt": "~0.4.1",
    "grunt-contrib-qunit": ">0.0.0",
    "grunt-qunit-istanbul": ">0.0.0"
  }
}
</code>```

here is the output when installing phantomjs:

```<code>...
Writing location.js file
Done. Phantomjs binary available at /home/myuser/Test/node_modules/grunt-contrib-qunit/node_modules/grunt-lib-phantomjs/node_modules/phantomjs/lib/phantom/bin/phantomjs
Done. Phantomjs binary available at /home/myuser/Test/node_modules/grunt-qunit-istanbul/node_modules/grunt-lib-phantomjs-istanbul/node_modules/phantomjs/lib/phantom/bin/phantomjs
grunt@0.4.1 node_modules/grunt
├── which@1.0.5
...
</code>```

But when I run grunt test from the test dir I get:

```<code>Running PhantomJS...ERROR
>> In order for this task to work properly, PhantomJS must be installed locally
>> via NPM. If you're seeing this message, generally that means the NPM install
>> has failed. Please submit an issue providing as much detail as possible at:
>> https://github.com/gruntjs/grunt-lib-phantomjs/issues
Warning: PhantomJS not found. Use --force to continue.
</code>```

If I run the phantomjs script installed in the previous specified location nothing happens, I get exit code 127 though (indicating problem PATH :http://tldp.org/LDP/abs/html/exitcodes.html). If I cat the phantomjs bash script it looks like this:

```<code>#!/usr/bin/env node

var path = require('path')
var spawn = require('child_process').spawn

var binPath = require(path.join(__dirname, '..', 'lib', 'phantomjs')).path

var args = process.argv.slice(2)

// For Node 0.6 compatibility, pipe the streams manually, instead of using
// `{ stdio: 'inherit' }`.
var cp = spawn(binPath, args)
cp.stdout.pipe(process.stdout)
cp.stderr.pipe(process.stderr)
cp.on('exit', process.exit)

process.on('SIGTERM', function() {
  cp.kill('SIGTERM')
  process.exit(1)
})
</code>```

As I understand this means that phantomjs is executed inside node. If I start node enter the path var I get:

```<code>:~$ env node
> var path = require('path')
undefined
>
</code>```

(which I understand is default behavior: node.js displays "undefined" on the console)

Any suggestions to further debug this problem?

答:
Try running the following in your terminal:</p>

```<code>npm install phantomjs-prebuilt@2.1.14 --ignore-scripts
</code>```

Title: Warning: PhantomJS not found

Body:
I have installed nodejs 0.10.15 on debian 6. Using npm I have then installed:

sudo npm install grunt-cli -g

I have also executed npm install in my local test directory (downloading the necessary dependencies to the node_modules directory) which contains the following package.json file:

{
  "name": "sample-name",
  "version": "1.4.0",
  "devDependencies": {
    "grunt": "~0.4.1",
    "grunt-contrib-qunit": ">0.0.0",
    "grunt-qunit-istanbul": ">0.0.0"
  }
}

here is the output when installing phantomjs:

...
Writing location.js file
Done. Phantomjs binary available at /home/myuser/Test/node_modules/grunt-contrib-qunit/node_modules/grunt-lib-phantomjs/node_modules/phantomjs/lib/phantom/bin/phantomjs
Done. Phantomjs binary available at /home/myuser/Test/node_modules/grunt-qunit-istanbul/node_modules/grunt-lib-phantomjs-istanbul/node_modules/phantomjs/lib/phantom/bin/phantomjs
grunt@0.4.1 node_modules/grunt
├── which@1.0.5
...

But when I run grunt test from the test dir I get:

Running PhantomJS...ERROR
>> In order for this task to work properly, PhantomJS must be installed locally
>> via NPM. If you're seeing this message, generally that means the NPM install
>> has failed. Please submit an issue providing as much detail as possible at:
>> https://github.com/gruntjs/grunt-lib-phantomjs/issues
Warning: PhantomJS not found. Use --force to continue.

If I run the phantomjs script installed in the previous specified location nothing happens, I get exit code 127 though (indicating problem PATH :http://tldp.org/LDP/abs/html/exitcodes.html). If I cat the phantomjs bash script it looks like this:

#!/usr/bin/env node

var path = require('path')
var spawn = require('child_process').spawn

var binPath = require(path.join(__dirname, '..', 'lib', 'phantomjs')).path

var args = process.argv.slice(2)

// For Node 0.6 compatibility, pipe the streams manually, instead of using
// `{ stdio: 'inherit' }`.
var cp = spawn(binPath, args)
cp.stdout.pipe(process.stdout)
cp.stderr.pipe(process.stderr)
cp.on('exit', process.exit)

process.on('SIGTERM', function() {
  cp.kill('SIGTERM')
  process.exit(1)
})

As I understand this means that phantomjs is executed inside node. If I start node enter the path var I get:

:~$ env node
> var path = require('path')
undefined
>

(which I understand is default behavior: node.js displays "undefined" on the console)

Any suggestions to further debug this problem?

Body:
Try running the following in your terminal:

npm install phantomjs-prebuilt@2.1.14 --ignore-scripts


问:
Embed d3.js to a Jekyll Post
Exactly as this question, I want to embed this particular example on my blog.

I tried using  but bl.ocks.org isn't supporting it anymore. I tried with  using rawgit but this too didn't work. I tried using the method given here and it works! but for my example it doesn't.

I have inspected both of these sites (this one) and (this too), and found out that in my case the d3 script isn't appending any svg element in my custom div. ( Please look at this answer for the method I used )

Please suggest me how to proceed with this.

答:
I solved this by:

creating another folder in _includes in the main Jekyll
directory and placing my custom .js files in it.

Then change d3.select("body").selectAll("svg") to
d3.select("div#example").append("svg").

Finally it renders the custom .js files alright.

Title: Embed d3.js to a Jekyll Post


问:
How to use basic queues in laravel without a Job
I have worked with Queues in laravel which will Queue the Jobs. php artisan queue:work command will take jobs in queue and process it.

But, i want to use pure queue without a job, One process will push itnto queue and another process read from queue and process it.

Eg, in a login api request, i will push just email id to queue. There will be a background process running(not queue:work) which can read the queue enties(list of emails) and do some action with it.

So the i need a custom worker which can read from queue.

How to do this in laravel?

答:
Its not possible directly. https://github.com/laravel/framework/issues/17083

By design laravel doesnt allow this. You can however try to implement a custom solution.


问:
java - Injecting proxies via CDI
in my project I have some external Java interfaces (so I can't change them).
E.g.

```<code>public interface Abc
{
    void do123();
}
</code>```

in a bean I like to use this interface by injection.
E.g.

```<code>public class TestAbc
{
    @Inject
    private Abc abc;
}
</code>```

But I don't have a implementation of this interface or a producer method. Instead I'm looking for a way to inject a generic proxy for this interface.

I guess, that I need something like a cdi extension for doing things like this. Unfortunatelly I can't find any good how to for this.
In a optimal world I would expect to implement a method like this.

```<code>public Object produce( Class< ? > type )
{
    if(isMyType(type))
    {
        // I can produce this type
        return createProxy(type);
    }
    return null; // this method can't produce this type
}
</code>```

Does anyone have an idea how to do this?

Regards
Johannes

答:
So, finally I got it.
For my use case I needed an CDI extension which listens to the ProcessInjectionPoint and the AfterBeanDiscovery.
ProcessInjectionPoint collects all relevant interfaces for injection and AfterBeanDiscovery creates beans for this interfaces.

The check if an inject is relevant or not is done by an annotation with @RMI. @RMI is an own qualifier annotation. RMILifecyle is responsible for build or destroy the injected object.
Here some source code.

```<code>public class RMIInjectionExtension implements Extension
{
    private Set< Class< ? > > interfaces = Sets.newHashSet();

    void processInjectionPoint( @Observes final ProcessInjectionPoint< ?, ? > aProcessInjectionPoint )
    {
        // collecting all relevant interfaces
        if( aProcessInjectionPoint.getInjectionPoint().getQualifiers().stream()
            .anyMatch( RMI.class::isInstance ) )
        {
            interfaces.add( (Class< ? >)aProcessInjectionPoint.getInjectionPoint().getType() );
        }
    }

    void afterBeanDiscovery( @Observes final AfterBeanDiscovery aAfterBeanDiscovery,
        BeanManager aBeanManager )
    {
        // create beans for the interfaces
        // using DeltaSpike BeanBuilder
        interfaces.stream().map( a -> new BeanBuilder< Object >( aBeanManager ).beanClass( a )
            .qualifiers( (RMI)() -> RMI.class ).beanLifecycle( new RMILifecyle() ).create() )
            .forEach( aAfterBeanDiscovery::addBean );
    }
}
</code>```

This works quite well for me.

Title: java - Injecting proxies via CDI

Body:
in my project I have some external Java interfaces (so I can't change them).
E.g.

public interface Abc
{
    void do123();
}

in a bean I like to use this interface by injection.
E.g.

public class TestAbc
{
    @Inject
    private Abc abc;
}

But I don't have a implementation of this interface or a producer method. Instead I'm looking for a way to inject a generic proxy for this interface.

I guess, that I need something like a cdi extension for doing things like this. Unfortunatelly I can't find any good how to for this.
In a optimal world I would expect to implement a method like this.

public Object produce( Class< ? > type )
{
    if(isMyType(type))
    {
        // I can produce this type
        return createProxy(type);
    }
    return null; // this method can't produce this type
}

Does anyone have an idea how to do this?

Regards
Johannes

Body:
So, finally I got it.
For my use case I needed an CDI extension which listens to the ProcessInjectionPoint and the AfterBeanDiscovery.
ProcessInjectionPoint collects all relevant interfaces for injection and AfterBeanDiscovery creates beans for this interfaces.

The check if an inject is relevant or not is done by an annotation with @RMI. @RMI is an own qualifier annotation. RMILifecyle is responsible for build or destroy the injected object.
Here some source code.

public class RMIInjectionExtension implements Extension
{
    private Set< Class< ? > > interfaces = Sets.newHashSet();

    void processInjectionPoint( @Observes final ProcessInjectionPoint< ?, ? > aProcessInjectionPoint )
    {
        // collecting all relevant interfaces
        if( aProcessInjectionPoint.getInjectionPoint().getQualifiers().stream()
            .anyMatch( RMI.class::isInstance ) )
        {
            interfaces.add( (Class< ? >)aProcessInjectionPoint.getInjectionPoint().getType() );
        }
    }

    void afterBeanDiscovery( @Observes final AfterBeanDiscovery aAfterBeanDiscovery,
        BeanManager aBeanManager )
    {
        // create beans for the interfaces
        // using DeltaSpike BeanBuilder
        interfaces.stream().map( a -> new BeanBuilder< Object >( aBeanManager ).beanClass( a )
            .qualifiers( (RMI)() -> RMI.class ).beanLifecycle( new RMILifecyle() ).create() )
            .forEach( aAfterBeanDiscovery::addBean );
    }
}

This works quite well for me.


问:
When to request permission at runtime for Android Marshmallow 6.0?
I am testing my app on Marshmallow 6.0 and it's getting force closed for the android.permission.READ_EXTERNAL_STORAGE, even if it is defined in the Manifest already. Somewhere I have read that if I request permission at runtime then it would not force close your application. I have read this android document also, which is for requesting runtime permission.

So, I came to know that we can request a permission like below which is mentioned in the android document.

```<code>// Here, thisActivity is the current activity
if (ContextCompat.checkSelfPermission(thisActivity,
                Manifest.permission.READ_CONTACTS)
        != PackageManager.PERMISSION_GRANTED) {

    // Should we show an explanation?
    if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity,
            Manifest.permission.READ_CONTACTS)) {

        // Show an expanation to the user *asynchronously* -- don't block
        // this thread waiting for the user's response! After the user
        // sees the explanation, try again to request the permission.

    } else {

        // No explanation needed, we can request the permission.

        ActivityCompat.requestPermissions(thisActivity,
                new String[]{Manifest.permission.READ_CONTACTS},
                MY_PERMISSIONS_REQUEST_READ_CONTACTS);

        // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
        // app-defined int constant. The callback method gets the
        // result of the request.
    }
}
</code>```

The above code has a callback method onRequestPermissionsResult which gets the result.

```<code>@Override
public void onRequestPermissionsResult(int requestCode,
        String permissions[], int[] grantResults) {
    switch (requestCode) {

     }
}
</code>```

My question is where to exactly request the permission to user? Should we use the requesting permission at start of the app or should we do it as when the permission is required?

答:
https://material.io/guidelines/patterns/permissions.html
This link will give you different type of scenario where permissions can be asked. Choose accordingly to your needs.</p>

Body:
I am testing my app on Marshmallow 6.0 and it's getting force closed for the android.permission.READ_EXTERNAL_STORAGE, even if it is defined in the Manifest already. Somewhere I have read that if I request permission at runtime then it would not force close your application. I have read this android document also, which is for requesting runtime permission.

So, I came to know that we can request a permission like below which is mentioned in the android document.

// Here, thisActivity is the current activity
if (ContextCompat.checkSelfPermission(thisActivity,
                Manifest.permission.READ_CONTACTS)
        != PackageManager.PERMISSION_GRANTED) {

    // Should we show an explanation?
    if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity,
            Manifest.permission.READ_CONTACTS)) {

        // Show an expanation to the user *asynchronously* -- don't block
        // this thread waiting for the user's response! After the user
        // sees the explanation, try again to request the permission.

    } else {

        // No explanation needed, we can request the permission.

        ActivityCompat.requestPermissions(thisActivity,
                new String[]{Manifest.permission.READ_CONTACTS},
                MY_PERMISSIONS_REQUEST_READ_CONTACTS);

        // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
        // app-defined int constant. The callback method gets the
        // result of the request.
    }
}

The above code has a callback method onRequestPermissionsResult which gets the result.

@Override
public void onRequestPermissionsResult(int requestCode,
        String permissions[], int[] grantResults) {
    switch (requestCode) {

     }
}

My question is where to exactly request the permission to user? Should we use the requesting permission at start of the app or should we do it as when the permission is required?


答:
You where just pointing to the wrong id. It should have been #date:

```<code>$("#date").append(newdate);
</code>```

$(document).ready(function() {
  var dateObj = new Date();
  var month = dateObj.getUTCMonth() + 1; //months from 1-12
  var day = dateObj.getUTCDate();
  var year = dateObj.getUTCFullYear();

  newdate = year + "/" + month + "/" + day;
  $("#date").append(newdate);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="date" style="width: 100%; height: 10%;background:#1d69b4 ">
</div></code>```

Title: Date not showing in div

Body:
I have View with div where I need to show date

I write this JavaScript code

$(document).ready(function() {
  var dateObj = new Date();
  var month = dateObj.getUTCMonth() + 1; //months from 1-12
  var day = dateObj.getUTCDate();
  var year = dateObj.getUTCFullYear();

  newdate = year + "/" + month + "/" + day;
  $("#id").append(newdate);
});

Body:
You where just pointing to the wrong id. It should have been #date:

$("#date").append(newdate);

$(document).ready(function() {
  var dateObj = new Date();
  var month = dateObj.getUTCMonth() + 1; //months from 1-12
  var day = dateObj.getUTCDate();
  var year = dateObj.getUTCFullYear();

  newdate = year + "/" + month + "/" + day;
  $("#date").append(newdate);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="date" style="width: 100%; height: 10%;background:#1d69b4 ">
</div>


问:
3D Flip Animation on android.support.v4.Fragment
I am currently reading this tutorial:

http://developer.android.com/training/animation/cardflip.html

on flip Animations of Fragments. Unfortunately, the object-animator is only available for android.app.Fragment, and not the support Fragment.

I tried to reconstruct the .xml animations using scale and rotation animations.
But now the animations are just not executed,  and after the time that I've set in the animations .xml file passes, the other Fragment appears, instead of flipping.

Did I simply make a misstake in implementing the .xml animations?

Or is it not possible to do a 3D flip animation without object-animator?

Or is it not possible to do a 3D flip animation with the support
Fragment?

Here are my .xml animations:
flip_left_in.xml

```<code><set xmlns:android="http://schemas.android.com/apk/res/android" >

  <!-- Before rotating, immediately set the alpha to 0. -->
 <alpha
    android:valueFrom="1.0"
    android:valueTo="0.0"
    android:propertyName="alpha"
    android:duration="0" />

 <!-- Rotate. -->
 <rotate
    android:valueFrom="-180"
    android:valueTo="0"
    android:propertyName="rotationY"
    android:interpolator="@android:anim/accelerate_decelerate_interpolator"
    android:duration="800"/>

<!-- Half-way through the rotation (see startOffset), set the alpha to 1. -->
<alpha
    android:valueFrom="0.0"
    android:valueTo="1.0"
    android:startOffset="400"
    android:duration="1" />
</set>
</code>```

flip_left_out.xml

```<code> <set xmlns:android="http://schemas.android.com/apk/res/android" >

   <!-- Rotate. -->
   <rotate
    android:duration="800"
    android:interpolator="@android:anim/accelerate_decelerate_interpolator"
    android:propertyName="rotationY"
    android:valueFrom="0"
    android:valueTo="180" />

<!-- Half-way through the rotation (see startOffset), set the alpha to 0. -->
<alpha
    android:duration="1"
    android:propertyName="alpha"
    android:startOffset="400"
    android:valueFrom="1.0"
    android:valueTo="0.0" />

 </set>
</code>```

flip_right_in.xml

```<code><set xmlns:android="http://schemas.android.com/apk/res/android" >
<!-- Before rotating, immediately set the alpha to 0. -->
<alpha
    android:duration="0"
    android:propertyName="alpha"
    android:valueFrom="1.0"
    android:valueTo="0.0" />

<!-- Rotate. -->
<rotate
    android:duration="800"
    android:interpolator="@android:anim/accelerate_decelerate_interpolator"
    android:propertyName="rotationY"
    android:valueFrom="180"
    android:valueTo="0" />

<!-- Half-way through the rotation (see startOffset), set the alpha to 1. -->
<alpha
    android:duration="1"
    android:propertyName="alpha"
    android:startOffset="400"
    android:valueFrom="0.0"
    android:valueTo="1.0" />

  </set>
</code>```

flip_right_out.xml

```<code><set xmlns:android="http://schemas.android.com/apk/res/android" >
<!-- Rotate. -->
<rotate
    android:duration="800"
    android:interpolator="@android:anim/accelerate_decelerate_interpolator"
    android:propertyName="rotationY"
    android:valueFrom="0"
    android:valueTo="-180" />

<!-- Half-way through the rotation (see startOffset), set the alpha to 0. -->
<alpha
    android:duration="1"
    android:propertyName="alpha"
    android:startOffset="400"
    android:valueFrom="1.0"
    android:valueTo="0.0" />

 </set>
</code>```

And here is the code where they are executed:

```<code>FragmentTransaction trans = getActivity().getSupportFragmentManager().beginTransaction();

trans.setCustomAnimations(R.anim.flip_right_in, R.anim.flip_right_out,
                           R.anim.flip_left_in, R.anim.flip_left_out);
trans.addToBackStack(null);

trans.replace(R.id.content_frame, new MyFragment()).commit();
</code>```

答:
In case if you are not supporting below api<3

use the same code as given in: https://stuff.mit.edu/afs/sipb/project/android/docs/training/animation/cardflip.html

just tweaked the flipCard method to:

```<code>private void flipCard() {
if (mShowingBack) {
    mShowingBack = false;
    FragmentTransaction trans = getActivity().getFragmentManager().beginTransaction();
    trans.setCustomAnimations(R.animator.card_flip_right_in,
            R.animator.card_flip_right_out,
            R.animator.card_flip_left_in,
            R.animator.card_flip_left_out)
         .replace(R.id.memberCardContainer, new CardFrontFragment())
         .commit();
    return;
}

// Flip to the back.
mShowingBack = true;
FragmentTransaction trans = getActivity().getFragmentManager().beginTransaction();
trans.setCustomAnimations(R.animator.card_flip_right_in,
        R.animator.card_flip_right_out,
        R.animator.card_flip_left_in,
        R.animator.card_flip_left_out)
     .replace(R.id.memberCardContainer, new CardBackFragment())
     .commit();
}
</code>```

Body:
I am currently reading this tutorial:

http://developer.android.com/training/animation/cardflip.html

on flip Animations of Fragments. Unfortunately, the object-animator is only available for android.app.Fragment, and not the support Fragment.

I tried to reconstruct the .xml animations using scale and rotation animations.
But now the animations are just not executed,  and after the time that I've set in the animations .xml file passes, the other Fragment appears, instead of flipping.

Did I simply make a misstake in implementing the .xml animations?

Or is it not possible to do a 3D flip animation without object-animator?

Or is it not possible to do a 3D flip animation with the support
Fragment?

Here are my .xml animations:
flip_left_in.xml

<set xmlns:android="http://schemas.android.com/apk/res/android" >

 <alpha
    android:valueFrom="1.0"
    android:valueTo="0.0"
    android:propertyName="alpha"
    android:duration="0" />

 <rotate
    android:valueFrom="-180"
    android:valueTo="0"
    android:propertyName="rotationY"
    android:interpolator="@android:anim/accelerate_decelerate_interpolator"
    android:duration="800"/>

<alpha
    android:valueFrom="0.0"
    android:valueTo="1.0"
    android:startOffset="400"
    android:duration="1" />
</set>

flip_left_out.xml

 <set xmlns:android="http://schemas.android.com/apk/res/android" >

   <rotate
    android:duration="800"
    android:interpolator="@android:anim/accelerate_decelerate_interpolator"
    android:propertyName="rotationY"
    android:valueFrom="0"
    android:valueTo="180" />

<alpha
    android:duration="1"
    android:propertyName="alpha"
    android:startOffset="400"
    android:valueFrom="1.0"
    android:valueTo="0.0" />

 </set>

flip_right_in.xml

<set xmlns:android="http://schemas.android.com/apk/res/android" >

<alpha
    android:duration="0"
    android:propertyName="alpha"
    android:valueFrom="1.0"
    android:valueTo="0.0" />

<rotate
    android:duration="800"
    android:interpolator="@android:anim/accelerate_decelerate_interpolator"
    android:propertyName="rotationY"
    android:valueFrom="180"
    android:valueTo="0" />

<alpha
    android:duration="1"
    android:propertyName="alpha"
    android:startOffset="400"
    android:valueFrom="0.0"
    android:valueTo="1.0" />

  </set>

flip_right_out.xml

<set xmlns:android="http://schemas.android.com/apk/res/android" >

<rotate
    android:duration="800"
    android:interpolator="@android:anim/accelerate_decelerate_interpolator"
    android:propertyName="rotationY"
    android:valueFrom="0"
    android:valueTo="-180" />

<alpha
    android:duration="1"
    android:propertyName="alpha"
    android:startOffset="400"
    android:valueFrom="1.0"
    android:valueTo="0.0" />

 </set>

And here is the code where they are executed:

FragmentTransaction trans = getActivity().getSupportFragmentManager().beginTransaction();

trans.setCustomAnimations(R.anim.flip_right_in, R.anim.flip_right_out,
                           R.anim.flip_left_in, R.anim.flip_left_out);
trans.addToBackStack(null);

trans.replace(R.id.content_frame, new MyFragment()).commit();

Body:
In case if you are not supporting below api<3

use the same code as given in: https://stuff.mit.edu/afs/sipb/project/android/docs/training/animation/cardflip.html

just tweaked the flipCard method to:

private void flipCard() {
if (mShowingBack) {
    mShowingBack = false;
    FragmentTransaction trans = getActivity().getFragmentManager().beginTransaction();
    trans.setCustomAnimations(R.animator.card_flip_right_in,
            R.animator.card_flip_right_out,
            R.animator.card_flip_left_in,
            R.animator.card_flip_left_out)
         .replace(R.id.memberCardContainer, new CardFrontFragment())
         .commit();
    return;
}

// Flip to the back.
mShowingBack = true;
FragmentTransaction trans = getActivity().getFragmentManager().beginTransaction();
trans.setCustomAnimations(R.animator.card_flip_right_in,
        R.animator.card_flip_right_out,
        R.animator.card_flip_left_in,
        R.animator.card_flip_left_out)
     .replace(R.id.memberCardContainer, new CardBackFragment())
     .commit();
}


问:
Detecting forgotten SQLite transaction on Android using StrictMode?
Executing multiple SQL statements without putting them into one transaction is a severe bottleneck (see e.g. http://www.sqlite.org/faq.html#q19). I haven't thoroughly checked how SQLite is configured on Android, but anecdotally I perceived dramatical performance increase within my on app when using transactions in more places.

Is it possible to detect instances where one forgets to use transactions using StrictMode? If not, could that be considered for a future release of StrictMode? It might be somewhat tricky to detect, but two different strategies could be, 1) non-select statements outside transaction, or 2) multiple non-select statements outside transaction executed within a short period of time.

答:
Yeah, that sounds like a good thing to catch.  I could imagine an API like:

StrictMode.catchWritesOutsideTransactionsOn(SQLiteDatabase db);

We've been considering other SQLite hooks into StrictMode (mostly around selects missing indexes and such), but this is a good idea too!


问:
Downloading Android Data Binding Library

https://developer.android.com/topic/libraries/data-binding/index.html

I wonder how to download the library from the Support repository in the Android SDK manager. It seems that I only have to set dataBinding to true in build.gradle file in the app module. Using Android Studio 2.3

答:
You can add data binding in your project by adding the below code in your app level build.gradle file.

```<code>android {
    ....
    dataBinding {
        enabled = true;
    }
}
</code>```

You don't have to do anything more for data binding. You can also check this blog.

https://medium.com/@karmakar.avijit/android-data-binding-library-i-782d773de42c

Body:
You can add data binding in your project by adding the below code in your app level build.gradle file.

android {
    ....
    dataBinding {
        enabled = true;
    }
}

You don't have to do anything more for data binding. You can also check this blog.

https://medium.com/@karmakar.avijit/android-data-binding-library-i-782d773de42c


问:
Parse JSON Array and load into hive table
I have a Json Array like as below

```<code>[{"Name":"xxxx","Machine":"Machine1"},{"Name":"yyyy","Machine":"Machine2"},{"Name":"zzzz","Machine":"Machine3"}]
</code>```

I need to parse that data and load into a hive table like below

```<code>Name    Machine

xxxx    Machine1
yyyy    Machine2
zzzz    Machine3
</code>```

could someone please help?

答:
```<code>select  j.Name,j.Machine

from    jsonarray t
        lateral view explode(split(substr(t.json,2),'(?<=\\}),(?=\\{)')) e
        lateral view json_tuple(e.col,'Name','Machine') j as Name,Machine
;
</code>```

<hr>

```<code>+------+----------+
| name | machine  |
+------+----------+
| xxxx | Machine1 |
| yyyy | Machine2 |
| zzzz | Machine3 |
+------+----------+
</code>```

Body:
I have a Json Array like as below

[{"Name":"xxxx","Machine":"Machine1"},{"Name":"yyyy","Machine":"Machine2"},{"Name":"zzzz","Machine":"Machine3"}]

I need to parse that data and load into a hive table like below

Name    Machine

xxxx    Machine1
yyyy    Machine2
zzzz    Machine3

could someone please help?

Body:
select  j.Name,j.Machine

from    jsonarray t
        lateral view explode(split(substr(t.json,2),'(?<=\\}),(?=\\{)')) e
        lateral view json_tuple(e.col,'Name','Machine') j as Name,Machine
;

+------+----------+
| name | machine  |
+------+----------+
| xxxx | Machine1 |
| yyyy | Machine2 |
| zzzz | Machine3 |
+------+----------+


答:
If the $role variable is set then the mysql query will look like this

```<code>select * from `users` where `role_id` = 1
</code>```

If $role isn't set like false then the mysql query will look like this

```<code>select * from `users`
</code>```

You should edit your query for example with if and use different where()

Title: Laravel Conditional Clause When()

Body:
I am new to Laravel and have encountered a problem using when() function. To start this  I do have a form consisting of 3 input fields named: name, email, and password.

<form method="post" action="/users">
    <?php echo csrf_field(); ?>
    <input type="text" name="name" placeholder="Name">
    <input type="email" name="email" placeholder="Email">
    <input type="password" name="password" placeholder="Password">
<input type="submit" value="Create">
</form>

Also I have this code inside a controller file.

$role = $request->input('role');

        $first = User::when($role,function ($query) use ($role){
            return $query->where('username',$role);
        })->get();

Based on Laravel documentation this shouldn't work as no elements named 'role' in the form that I submitted and $role variable must return false. But when I loop the $first variable, It has all the records inside of Users table. So I tried correcting and put

$role = $request->input('name');

So it works perfectly when I put a name that is inside the User table. But when I type nothing at (input type='text' name='name') element and submit the form. It shows all the records inside of Users table again. I am really confused, I think it has something to do with the 'false' or 'empty' returned by the $request->input(). Please advise. Thanks.

Body:
If the $role variable is set then the mysql query will look like this

select * from `users` where `role_id` = 1

If $role isn't set like false then the mysql query will look like this

select * from `users`

You should edit your query for example with if and use different where()


问:
Trying to rename a database in Redshift cluster
I'm trying to rename a database in my Redshift cluster.

You cannot rename the database when you're connected to it so I've created a temporary database, reconnected with SQL Workbench to the temporary db and issued:

ALTER DATABASE olddb RENAME to newdb;

I get an error stating ERROR: database "olddb" is being accessed by other users [SQL State=55006]

I've checked who is connected and there appear to be some connections from user rdsdb to the database. I assume this is a service account that AWS Redshift use to perform maintenance tasks etc.

How can I rename the database when this superuser is connected?

Many thanks.

答: That's possible now -- I just renamed the database that was created during the initial cluster creation.</p>


问:
Is it possible to keep a connection with two different MQTT Brokers when using the Node-RED?
I have a server on the cloud that receives MQTT messages and I'm running the Node-RED on a Raspberry pi on my localhost...

With the Raspberry, I'm receiving data from different devices using the MQTT protocol. And until here, it works great! The problem is when I try to receive messages from the MQTT broker that's running locally (on the Raspberry) and then send these messages to other MQTT broker that's running on another server. Something like this image:

When I try to use two different brokers with the Node-RED, it automatically updates all other nodes to the last broker that I had configured. So, is it possible to open a connection with two different MQTT Brokers when I'm using the Node-RED?

答:
In the MQTT node edit dialog, the 'Server' field is a select box. It lists all of the broker configurations you have in your flow.

To add a connection to a different broker, select the 'Add new mqtt-broker...' option then click the button next to the select box.

That adds a new connection configuration rather than edit the one already being used by your existing nodes.


问:
How to create an iPhone app that interacts with my website?
What I want to do is to make an iPhone application for my website similar to the photofunia. The users will be able to select an effect from a list, and then upload their own photo. Then the result will be shown in the browser where the user can save the image and/or publish to website like facebook, etc.

What software can I use to do that? Phonegap, appcelerator, etc? Can some of these help?

Thanks.

答:
Of course I know there is no "easy" solution, but I'm almost sure there are other options for making iphone apps, instead of using Objective-C.
I only don't know the name of the tools.
Flash doesn't works. Adobe Air currently doesn't offer a way to access the camera roll on the ios.</p>