问:
How to execute nested Javascript function
I am troubleshooting a slider problem at the moment, however, I don't know javascript that well, I have isolated the .js file that is responsible for the slider functioning, there is a destroy function that I would like to fire off, the code looks like this

```<code>(function ($) {

$.pixelentity = $.pixelentity || {version: '1.0.0'};

$.pixelentity.peBackgroundSlider = {
    conf: {
        api: false,
        wait: false
    },
    paused: false
};

function PeBackgroundSlider(target, conf) {

    ...

    function destroy() {
        prevColor = currentColor = currentBW = jwindow = jthis = undefined;
        target.data("peBackgroundSlider", null);
        target = undefined;
    }
}
</code>```

How would I fire off the destroy function in this scenario?

答:
You can't as it is right now.

To call it you must "export" it as follows:

```<code>function PeBackgroundSlider(target, conf) {

...

function destroy() {
    prevColor = currentColor = currentBW = jwindow = jthis = undefined;
    target.data("peBackgroundSlider", null);
    target = undefined;
  }

  return { "destroy": destroy };
}
</code>```

From the caller:

```<code>var ret = PeBackgroundSlider();
</code>```

Now you can do:

```<code>ret.destroy();
</code>```

Or, more concise:

```<code>  return destroy;
</code>```

And:

```<code>innerDestroy = PeBackgroundSlider();
</code>```

And finally:

```<code>innerDestroy();
</code>```

Body:
I am troubleshooting a slider problem at the moment, however, I don't know javascript that well, I have isolated the .js file that is responsible for the slider functioning, there is a destroy function that I would like to fire off, the code looks like this

(function ($) {

$.pixelentity = $.pixelentity || {version: '1.0.0'};

$.pixelentity.peBackgroundSlider = {
    conf: {
        api: false,
        wait: false
    },
    paused: false
};

function PeBackgroundSlider(target, conf) {

    ...

    function destroy() {
        prevColor = currentColor = currentBW = jwindow = jthis = undefined;
        target.data("peBackgroundSlider", null);
        target = undefined;
    }
}

How would I fire off the destroy function in this scenario?

Body:
You can't as it is right now.

To call it you must "export" it as follows:

function PeBackgroundSlider(target, conf) {

...

function destroy() {
    prevColor = currentColor = currentBW = jwindow = jthis = undefined;
    target.data("peBackgroundSlider", null);
    target = undefined;
  }

  return { "destroy": destroy };
}

From the caller:

var ret = PeBackgroundSlider();

Now you can do:

ret.destroy();

Or, more concise:

  return destroy;

And:

innerDestroy = PeBackgroundSlider();

And finally:

innerDestroy();


来源: stackexchange

问:
MongoDB + PHP : Get subarray inside a document
I have the following structure and data:

```<code>game{
    alias: "GAME01",
    players[
        {
            name: Nick,
            city: London
        },
        {
            name: Chris,
            city: London
        },
        {
            name: Emmy,
            city: Paris
        }
    ]
}
</code>```

and I need to get an array just with the players from London. Something like:

```<code>[[name: Nick, city: London], [name: Chris, city: London]]
</code>```

How can I get it? Any ideas?

All I've tryed returns me the entire game, or an empty object.

mongoDB version: 3.4.4 / mongoDB driver version 1.6.14

Thanks!

What I've tryed:

Try 1:

```<code>$game = $mongo->game->find(
    array("alias" => "GAME01", "players.city" => "London"),
    array('_id' => false, "players" => array('$elementMatch' =>
    array("players.city" => "London")))
);
</code>```

Returns:

```<code>object(MongoCursor)#10 (0) {}
</code>```

Try 2:

```<code>$game = $mongo->game->find(
    array("alias" => "GAME01",
    array("players" => array('$elementMatch' => array("city" => "London"))))
);
</code>```

Returns:

```<code>object(MongoCursor)#10 (0) {}
</code>```

Try 3:

```<code>$ops = array(
    array('$match' => array("alias" => "GAME01")),
    array('$project' => array("game.players" => 1)),
    array('$unwind' => '$players'),
    array('$match' => array("players.city" => "London")),
    array('$group' => array(
        '_id' => '$_id',
        'players' => array(
            '$push' => '$players'))
    )
);

$game = $mongo->game->aggregate($ops);
</code>```

Returns:

```<code>array(2) {
    ["result"] => array(0) {}
    ["ok"] => float(1)
}
</code>```

答:
Thanks! I finally found this solution:</p>

```<code>$ops = array(
    array('$match' => array(
        "alias" => "GAME01",
        )
    ),
    array('$project' => array(
        "players" => 1
        )
    ),
    array('$unwind' => '$players'),
    array('$match' => array(
            "athletes.city" => "London"
            )
        ),
    array('$group' => array(
            '_id' => '$_id',
            'players' => array(
            '$push' => '$players'
            )
        )
    )
);

$game = $mongo->game->aggregate($ops);
$players = $game["result"][0]["players"];
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have the following structure and data:

game{
    alias: "GAME01",
    players[
        {
            name: Nick,
            city: London
        },
        {
            name: Chris,
            city: London
        },
        {
            name: Emmy,
            city: Paris
        }
    ]
}

and I need to get an array just with the players from London. Something like:

[[name: Nick, city: London], [name: Chris, city: London]]

How can I get it? Any ideas?

All I've tryed returns me the entire game, or an empty object.

mongoDB version: 3.4.4 / mongoDB driver version 1.6.14

Thanks!

What I've tryed:

Try 1:

$game = $mongo->game->find(
    array("alias" => "GAME01", "players.city" => "London"),
    array('_id' => false, "players" => array('$elementMatch' =>
    array("players.city" => "London")))
);

Returns:

object(MongoCursor)#10 (0) {}

Try 2:

$game = $mongo->game->find(
    array("alias" => "GAME01",
    array("players" => array('$elementMatch' => array("city" => "London"))))
);

Returns:

object(MongoCursor)#10 (0) {}

Try 3:

$ops = array(
    array('$match' => array("alias" => "GAME01")),
    array('$project' => array("game.players" => 1)),
    array('$unwind' => '$players'),
    array('$match' => array("players.city" => "London")),
    array('$group' => array(
        '_id' => '$_id',
        'players' => array(
            '$push' => '$players'))
    )
);

$game = $mongo->game->aggregate($ops);

Returns:

array(2) {
    ["result"] => array(0) {}
    ["ok"] => float(1)
}

Body:
Thanks! I finally found this solution:

$ops = array(
    array('$match' => array(
        "alias" => "GAME01",
        )
    ),
    array('$project' => array(
        "players" => 1
        )
    ),
    array('$unwind' => '$players'),
    array('$match' => array(
            "athletes.city" => "London"
            )
        ),
    array('$group' => array(
            '_id' => '$_id',
            'players' => array(
            '$push' => '$players'
            )
        )
    )
);

$game = $mongo->game->aggregate($ops);
$players = $game["result"][0]["players"];


问:
Why can I only view Storyboard's source and not Interface Builder?
I was using Xcode and making changes to my storyboard... no problem.  Now, I get the source code for the storyboard but not the storyboard images!

When I right click on the storyboard file, I don't see "Interface Builder - IOS Storyboard" as an option.

Anyone have this happen to them?

答: Click this icon in the top right of the Xcode window</p>


问:
What are the correct jar files for Jzy3d API?
Can someone tell me which .jar files to download to get the newest Jzy3d version? I have looked at their website but I don't know which files to download.</p>

答:
The easiest way is to use maven to build Jzy3d charts. Install maven if you don't have it.

Add a maven pom.xml file at the root of your project, similar to this one. Running the following command will import dependencies and build the project

```<code>mvn clean test install
</code>```

If you want to retrieve jar manually (discouraged), you can get jzy3d builds here. You will also have to download jzy3d dependencies (jogl, jply, jmathio, jdt-core, miglayout, opencsv, etc) as listed in jzy3d-api pom file.

Body:
The easiest way is to use maven to build Jzy3d charts. Install maven if you don't have it.

Add a maven pom.xml file at the root of your project, similar to this one. Running the following command will import dependencies and build the project

mvn clean test install

If you want to retrieve jar manually (discouraged), you can get jzy3d builds here. You will also have to download jzy3d dependencies (jogl, jply, jmathio, jdt-core, miglayout, opencsv, etc) as listed in jzy3d-api pom file.


问:
AmCharts : Uncaught TypeError: Cannot read property 'mouseX' of undefined
I am using AmCharts for stock related events. I am having following weird error in my console window.

```<code>Uncaught TypeError: Cannot read property 'mouseX' of undefined
    at b.followCursor (amcharts.js:271)
    at b.showBalloonReal (amcharts.js:130)
    at amcharts.js:130
</code>```

My code is as follows:
-I use this function to fill data in dividendEventData variable.

function getCompanyEventChartData() {
        var jqhx = $.ajax({
            type: "GET",
            data: { 'marketID': '@Model.MarketID', 'companyID': '@Model.CompanyID' },
            url: "@Url.CompanyChartEvent()"
        })
        .done(function (data) {
            for (var i = 0; i < data.length; i++) {
                if (data[i][1] == "31") {
                    var e0 = {
                        date: new Date(data[i][0]),
                        type: "sign",
                        backgroundColor: "#85CDE6",
                        graph: closeGraph,
                        text: "D",
                        description: "temporary",
                        url: "https://www.google.com/",
                        urlTarget: "_blank"
                    };
                    dividendEventData.push(e0);
                }
            }
        });```
</div>
</div>
</p>

<p>The dividendEventData is in this format.</p>

```[["Sunday, 18, Dec, 2016",31],["Thursday, 24, Dec, 2015",31],["Thursday, 11, Dec, 2014",31],["Thursday, 19, Dec, 2013",31],["Saturday, 22, Dec, 2012",31],["Saturday, 24, Dec, 2011",31],["Tuesday, 22, Feb, 2011",31],["Tuesday, 19, Jan, 2010",31],["Saturday, 29, Nov, 2008",31],["Wednesday, 20, Feb, 2008",31],["Tuesday, 27, Feb, 2007",31],["Monday, 28, Mar, 2005",31]]
```

<p>I am then adding dividendEventData to my chart like this.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>simpleDataSet.stockEvents = dividendEventData;
                setTimeout(function () {
                    $("#chartcurtain").hide();
                    chart.validateData();
                }, 1000);</code>```

My chart looks like this.
Chart Image

My chart works fine one time and display the description. But after next reload it does not show description when I hover my mouse over the events icon and it gives the error I mentioned earlier in console. I've deleted my cookies and have verified that the data returned from ajax call is same alway. I've followed this stackoverflow thread but still the same error.

答:
When you first initialize the chart, it expects data/config as JavaScript objects and arrays. It then proceeds to convert simple JS objects into instances of appropriate classes.

In case of Stock Events, it converts stockEvents array of objects into array of StockEvent instances.

This is why your chart works the first time.

Now, when you are adding events to an already initialized chart, you're basically adding a basic object to stockEvents array. Now, when you do so, you end up with an array of mixed StockEvent instances and basic objects.

This time the objects are not converted into StockEvent instances, hence the anomaly.

What you need to do is to instantiate a new event as StockEvent and push that instance into stockEvents instead.

Something like this:

```<code>var e0 = new AmCharts.StockEvent();
e0.date = new Date(data[i][0]);
e0.type = "sign";
e0.backgroundColor = "#85CDE6";
e0.graph = closeGraph;
e0.text = "D";
e0.description = "temporary";
e0.url = "https://www.google.com/";
e0.urlTarget = "_blank";
dividendEventData.push(e0);
</code>```

That should take care of it.

Here's a working example:

var chart = AmCharts.makeChart("chartdiv", {
  "type": "stock",
  "theme": "light",

  "categoryAxesSettings": {
    "minPeriod": "mm"
  },

  "dataSets": [
    {
      "fieldMappings": [
        {
          "fromField": "value",
          "toField": "value"
        }
      ],
      "dataProvider": generateChartData(),
      "categoryField": "date"
    }
  ],

  "panels": [
    {
      "stockGraphs": [
        {
          "valueField": "value",
          "type": "smoothedLine"
        }
      ]
    }
  ],

  "chartCursorSettings": {
    "valueBalloonsEnabled": true
  }
});

function generateChartData() {
  var chartData = [];
  var firstDate = new Date(2012, 0, 1);
  firstDate.setDate(firstDate.getDate() - 1000);
  firstDate.setHours(0, 0, 0, 0);

  for (var i = 0; i < 1000; i++) {
    var newDate = new Date(firstDate);
    newDate.setHours(0, i, 0, 0);

    var a = Math.round(Math.random() * (40 + i)) + 100 + i;

    chartData.push({
      date: newDate,
      value: a
    });
  }
  return chartData;
}

function test() {
  var dividendEventData = [];
  for (var i = 0; i < 5; i++) {
    var r = Math.floor(Math.random() * 1000);
    var e0 = new AmCharts.StockEvent();
    e0.date = new Date(chart.dataSets[0].dataProvider[r].date);
    e0.type = "sign";
    e0.backgroundColor = "#85CDE6";
    e0.graph = chart.panels[0].stockGraphs[0];
    e0.text = "D";
    e0.description = "temporary";
    e0.url = "https://www.google.com/";
    e0.urlTarget = "_blank";
    dividendEventData.push(e0);
  }
  chart.dataSets[0].stockEvents = dividendEventData;
  chart.validateData();
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#chartdiv {
 width: 100%;
 height: 200px;
}</code>```

<input type="button" value="add event" onclick="test();" />```

And here's the CodePen version of the same:
https://codepen.io/team/amcharts/pen/c37ef299206c6ab5a09c15b0f665e6f0?editors=0010

Body:
I am using AmCharts for stock related events. I am having following weird error in my console window.

Uncaught TypeError: Cannot read property 'mouseX' of undefined
    at b.followCursor (amcharts.js:271)
    at b.showBalloonReal (amcharts.js:130)
    at amcharts.js:130

My code is as follows:
-I use this function to fill data in dividendEventData variable.

function getCompanyEventChartData() {
        var jqhx = $.ajax({
            type: "GET",
            data: { 'marketID': '@Model.MarketID', 'companyID': '@Model.CompanyID' },
            url: "@Url.CompanyChartEvent()"
        })
        .done(function (data) {
            for (var i = 0; i < data.length; i++) {
                if (data[i][1] == "31") {
                    var e0 = {
                        date: new Date(data[i][0]),
                        type: "sign",
                        backgroundColor: "#85CDE6",
                        graph: closeGraph,
                        text: "D",
                        description: "temporary",
                        url: "https://www.google.com/",
                        urlTarget: "_blank"
                    };
                    dividendEventData.push(e0);
                }
            }
        });

The dividendEventData is in this format.

[["Sunday, 18, Dec, 2016",31],["Thursday, 24, Dec, 2015",31],["Thursday, 11, Dec, 2014",31],["Thursday, 19, Dec, 2013",31],["Saturday, 22, Dec, 2012",31],["Saturday, 24, Dec, 2011",31],["Tuesday, 22, Feb, 2011",31],["Tuesday, 19, Jan, 2010",31],["Saturday, 29, Nov, 2008",31],["Wednesday, 20, Feb, 2008",31],["Tuesday, 27, Feb, 2007",31],["Monday, 28, Mar, 2005",31]]

I am then adding dividendEventData to my chart like this.

simpleDataSet.stockEvents = dividendEventData;
                setTimeout(function () {
                    $("#chartcurtain").hide();
                    chart.validateData();
                }, 1000);

My chart looks like this.
Chart Image

My chart works fine one time and display the description. But after next reload it does not show description when I hover my mouse over the events icon and it gives the error I mentioned earlier in console. I've deleted my cookies and have verified that the data returned from ajax call is same alway. I've followed this stackoverflow thread but still the same error.

Body:
When you first initialize the chart, it expects data/config as JavaScript objects and arrays. It then proceeds to convert simple JS objects into instances of appropriate classes.

In case of Stock Events, it converts stockEvents array of objects into array of StockEvent instances.

This is why your chart works the first time.

Now, when you are adding events to an already initialized chart, you're basically adding a basic object to stockEvents array. Now, when you do so, you end up with an array of mixed StockEvent instances and basic objects.

This time the objects are not converted into StockEvent instances, hence the anomaly.

What you need to do is to instantiate a new event as StockEvent and push that instance into stockEvents instead.

Something like this:

var e0 = new AmCharts.StockEvent();
e0.date = new Date(data[i][0]);
e0.type = "sign";
e0.backgroundColor = "#85CDE6";
e0.graph = closeGraph;
e0.text = "D";
e0.description = "temporary";
e0.url = "https://www.google.com/";
e0.urlTarget = "_blank";
dividendEventData.push(e0);

That should take care of it.

Here's a working example:

var chart = AmCharts.makeChart("chartdiv", {
  "type": "stock",
  "theme": "light",

  "categoryAxesSettings": {
    "minPeriod": "mm"
  },

  "dataSets": [
    {
      "fieldMappings": [
        {
          "fromField": "value",
          "toField": "value"
        }
      ],
      "dataProvider": generateChartData(),
      "categoryField": "date"
    }
  ],

  "panels": [
    {
      "stockGraphs": [
        {
          "valueField": "value",
          "type": "smoothedLine"
        }
      ]
    }
  ],

  "chartCursorSettings": {
    "valueBalloonsEnabled": true
  }
});

function generateChartData() {
  var chartData = [];
  var firstDate = new Date(2012, 0, 1);
  firstDate.setDate(firstDate.getDate() - 1000);
  firstDate.setHours(0, 0, 0, 0);

  for (var i = 0; i < 1000; i++) {
    var newDate = new Date(firstDate);
    newDate.setHours(0, i, 0, 0);

    var a = Math.round(Math.random() * (40 + i)) + 100 + i;

    chartData.push({
      date: newDate,
      value: a
    });
  }
  return chartData;
}

function test() {
  var dividendEventData = [];
  for (var i = 0; i < 5; i++) {
    var r = Math.floor(Math.random() * 1000);
    var e0 = new AmCharts.StockEvent();
    e0.date = new Date(chart.dataSets[0].dataProvider[r].date);
    e0.type = "sign";
    e0.backgroundColor = "#85CDE6";
    e0.graph = chart.panels[0].stockGraphs[0];
    e0.text = "D";
    e0.description = "temporary";
    e0.url = "https://www.google.com/";
    e0.urlTarget = "_blank";
    dividendEventData.push(e0);
  }
  chart.dataSets[0].stockEvents = dividendEventData;
  chart.validateData();
}

#chartdiv {
 width: 100%;
 height: 200px;
}

<script src="//www.amcharts.com/lib/3/amcharts.js"></script>
<script src="//www.amcharts.com/lib/3/serial.js"></script>
<script src="//www.amcharts.com/lib/3/themes/light.js"></script>
<script src="//www.amcharts.com/lib/3/amstock.js"></script>
<div id="chartdiv"></div>
<input type="button" value="add event" onclick="test();" />

And here's the CodePen version of the same:
https://codepen.io/team/amcharts/pen/c37ef299206c6ab5a09c15b0f665e6f0?editors=0010


问:
audio streaming extention with no save option? (joomla 1.0)
I need to publish a audio file that I want to make available to

```<code>* listen and
* not to download
</code>```

any idea how to do it? Is there any free joomla extention plugin for that?

Something where user cannot save the audo using any webbrowser plugin like DownloadHelper etc.

答: The easiest way I can think of is to use the JoomlaWorks extension AllVideos. It has support for audio files and very easy to set up and use.</p>

ContentLicense: CC BY-SA 2.5

Body:
I need to publish a audio file that I want to make available to

* listen and
* not to download

any idea how to do it? Is there any free joomla extention plugin for that?

Something where user cannot save the audo using any webbrowser plugin like DownloadHelper etc.


问:
Can't start jHipster microservice gateway out of box
So I've built a jHipster microservices gateway out of the box. I have jHipster 4.5.2. I have done nothing to it beyond answering the setup questions (you can see my answers below). I assigned it to run on localhost:8082. I also have installed Tomcat 8.5.15, which works; when I turn it on I see the server page at localhost:8080.

I have tried to run the gateway by doing the following:

```<code>/Users/jimstewart/apache-maven-3.3.9/bin/mvn -Pprod package
java -jar target/data-gateway-0.0.1-SNAPSHOT.war
</code>```

When it tries to start up I get the following warning early on:

```<code>Could not locate PropertySource: I/O error on GET request for "http://localhost:8761/config/DataGateway/dev/master": Connection refused; nested exception is java.net.ConnectExc
</code>```

But the Tomcat server is running: when I go to localhost:8080 the page is there.

There is a ton of boilerplate, hundreds of lines, so I won't copy them all. But in the following errors keep repeating

```<code>2017-06-03 22:48:58.671 ERROR 1271 --- [           main] c.n.d.s.t.d.RedirectingEurekaHttpClient  : Request execution error

2017-06-03 22:48:58.674  WARN 1271 --- [           main]
c.n.d.s.t.d.RetryableEurekaHttpClient    : Request execution failed with
message: java.net.ConnectException: Connection refused

2017-06-03 22:48:58.675 ERROR 1271 --- [           main]
com.netflix.discovery.DiscoveryClient    :
DiscoveryClient_DATAGATEWAY/DataGateway:5ee0c99cb98fec0674d7db2672260892 - was
unable to refresh its cache! status = Cannot execute request on any known server

2017-06-03 22:49:17.689  WARN 1271 --- [nfoReplicator-0]
c.n.d.s.t.d.RetryableEurekaHttpClient    : Request execution failed with message: java.net.ConnectException: Connection refused
</code>```

Eventually it just shuts down without starting.

I've also tried to start it by running it from NetBeans. When I have Tomcat turned on, it quits because "Failed to start Tomcat: port 8080 is already in use." So, fine, start it with Tomcat turned off so it can turn it on itself. Then it won't start because "connection refused."

How can I get my app to start?

I answered the setup questions the following way:

```<code>What kind of application? Gateway application
What is the base name? DataGateway
Would you like to install other generators? No
Which port do you want to run it on? 8082
What is your default package name? com.kidslearntocode.datagateway
Do you want to use the jHipster registry? Yes
What kind of authentication? JWT
What type of database? SQL
What production database? mySQL
What development database? mySQL
Maven or Gradle? Maven
Which other technologies? None
Which framework? [beta] Angular 4
LibSass? Yes
Internationalization? No
Other languages? None
</code>```

答:
The error is indicated here:

Could not locate PropertySource: I/O error on GET request for "http://localhost:8761/config/DataGateway/dev/master": Connection refused; nested exception is java.net.ConnectExc

It means you didn't start the JHipster Registry.
For that, you have 2 solutions:

1) with Docker, simply launch: docker-compose -f src/main/docker/jhipster-registry.yml up -d

2) clone the project https://github.com/jhipster/jhipster-registry, then yarn install and start the registry: ./mvwn

Then, try to log into the JHipster Registry at http://localhost:8761

More information at https://jhipster.github.io/api-gateway/

PS: I don't understand very well how you use Tomcat here, as your Gateway already uses embedded Undertow, so you don't need another server.

Body:
So I've built a jHipster microservices gateway out of the box. I have jHipster 4.5.2. I have done nothing to it beyond answering the setup questions (you can see my answers below). I assigned it to run on localhost:8082. I also have installed Tomcat 8.5.15, which works; when I turn it on I see the server page at localhost:8080.

I have tried to run the gateway by doing the following:

/Users/jimstewart/apache-maven-3.3.9/bin/mvn -Pprod package
java -jar target/data-gateway-0.0.1-SNAPSHOT.war

When it tries to start up I get the following warning early on:

Could not locate PropertySource: I/O error on GET request for "http://localhost:8761/config/DataGateway/dev/master": Connection refused; nested exception is java.net.ConnectExc

But the Tomcat server is running: when I go to localhost:8080 the page is there.

There is a ton of boilerplate, hundreds of lines, so I won't copy them all. But in the following errors keep repeating

2017-06-03 22:48:58.671 ERROR 1271 --- [           main] c.n.d.s.t.d.RedirectingEurekaHttpClient  : Request execution error

2017-06-03 22:48:58.674  WARN 1271 --- [           main]
c.n.d.s.t.d.RetryableEurekaHttpClient    : Request execution failed with
message: java.net.ConnectException: Connection refused

2017-06-03 22:48:58.675 ERROR 1271 --- [           main]
com.netflix.discovery.DiscoveryClient    :
DiscoveryClient_DATAGATEWAY/DataGateway:5ee0c99cb98fec0674d7db2672260892 - was
unable to refresh its cache! status = Cannot execute request on any known server

2017-06-03 22:49:17.689  WARN 1271 --- [nfoReplicator-0]
c.n.d.s.t.d.RetryableEurekaHttpClient    : Request execution failed with message: java.net.ConnectException: Connection refused

Eventually it just shuts down without starting.

I've also tried to start it by running it from NetBeans. When I have Tomcat turned on, it quits because "Failed to start Tomcat: port 8080 is already in use." So, fine, start it with Tomcat turned off so it can turn it on itself. Then it won't start because "connection refused."

How can I get my app to start?

I answered the setup questions the following way:

What kind of application? Gateway application
What is the base name? DataGateway
Would you like to install other generators? No
Which port do you want to run it on? 8082
What is your default package name? com.kidslearntocode.datagateway
Do you want to use the jHipster registry? Yes
What kind of authentication? JWT
What type of database? SQL
What production database? mySQL
What development database? mySQL
Maven or Gradle? Maven
Which other technologies? None
Which framework? [beta] Angular 4
LibSass? Yes
Internationalization? No
Other languages? None


问:
Raspberry Pi remote update of entire OS or NodeJS
I am new to raspberry pi.
I want to develop small program using Raspberry Pi.
What are the options I have for remote update of Raspberry Pi which I will be giving to my users.

For example I am in New York and my user is in Atlanta and Chicago.
Once i give the raspberry pi with added NodeJS and node program to them.
How can i update it remotely if i want to modify the program or update the OS itself, in case they have any issues considering the fact they have no technical knowledge ?

Is there anyway to control that entire Pi remotely ?

I know the SSH options but that will be on the same network right ?

Some expert help would be great.

答: Just a suggestion. You can use git and webhooks. It's a breeze and a convenient way to maintain version history too. You should also look into continuous integration.</p>


问:
Repeater with HiddenField
I have the following HiddenField within a Repeater labeled "AdminGetAllRPT":

```<code> <asp:Repeater ID="AdminGetAllRPT" runat="server" OnLoad="AdminGetAllRPT_Load">
    <HeaderTemplate>
        <table id="AdminGetAllTBL">
            <tr>
                <td></td>
                <td>Username</td>
                <td>Email Address</td>
                <td>First Name</td>
                <td>Last Name</td>
                <td>Active?</td>
            </tr>
    </HeaderTemplate>
    <ItemTemplate>
       <tr>
           <td>
               <asp:LinkButton ID="AdminEditLnk" runat="server" OnClick="AdminEdit_OnClick">Edit
               <asp:HiddenField ID="editAdminEmail" runat="server" Value='<%# Eval("emailAddress") %>' />
               </asp:LinkButton>
           </td>
           <td><%# Eval("userName") %></td>
           <td><%# Eval("emailAddress") %></td>
           <td><%# Eval("firstName") %></td>
           <td><%# Eval("lastName") %></td>
           <td><%# Eval("isActive") %></td>
       </tr>
    </ItemTemplate>
    <AlternatingItemTemplate>
        <tr class="alternateTemplate">
           <td>
               <asp:LinkButton ID="AdminEditLnk" runat="server" OnClick="AdminEdit_OnClick">Edit
               <asp:HiddenField ID="editAdminEmail" runat="server" Value='<%# Eval("emailAddress") %>' />
               </asp:LinkButton>
           </td>
           <td><%# Eval("userName") %></td>
           <td><%# Eval("emailAddress") %></td>
           <td><%# Eval("firstName") %></td>
           <td><%# Eval("lastName") %></td>
           <td><%# Eval("isActive") %></td>
       </tr>
    </AlternatingItemTemplate>
    <FooterTemplate>
            <tr>
                <td colspan="2"><a href="#">Add Administrator</a></td>
            </tr>
        </table>
    </FooterTemplate>
</asp:Repeater>
</code>```

I have a linkbutton that fires this code:

```<code>protected void AdminEdit_OnClick(object sender, EventArgs e)
{
    HiddenField hf = (HiddenField)AdminGetAllRPT.FindControl("editAdminEmail");
</code>```

but the hf is coming up null. What am I doing wrong?

答:
Change AdminGetAllRPT.FindControl...

to

e.Item.FindControl...

Edit: Thanks for the votedown on a correct answer.

But yes e.Item.FindControl is what you want because what you're trying to do is not an event on the button, it's an event on the ItemCommand of the repeater.

```<code><asp:Repeater OnItemCommand="MyButtonCommandEvent" ID="AdminGetAllRPT" runat="server" OnLoad="AdminGetAllRPT_Load">
</code>```

Then in the code-behind you can setup the event

```<code>void MyButtonCommandEvent(Object src, RepeaterCommandEventArgs e) {
   //My event that is raised for each button pressed in the RepeaterItem
   var poo = e.Item.FindControl("myhiddenfieldid") as HiddenField;
}
</code>```

Done...

To iterate over all RepeaterItems, you can have a button outside of the repeater (or maybe in the footer or something, this is not a repeater ItemCommand)

```<code>foreach(var item in AdminGetAllRPT.Items)
{
    if (item.ItemType == RepeaterItemType.Item || item.ItemType == RepeaterItemType.AlternatingItem)
    {
        var hiddenField = item.FindControl("hiddenFieldid") as HiddenField;
        //Do Stuff
    }
}
</code>```

Title: Repeater with HiddenField

Body:
I have the following HiddenField within a Repeater labeled "AdminGetAllRPT":

 <asp:Repeater ID="AdminGetAllRPT" runat="server" OnLoad="AdminGetAllRPT_Load">
    <HeaderTemplate>

                Username
                Email Address
                First Name
                Last Name
                Active?

    </HeaderTemplate>
    <ItemTemplate>

               <asp:LinkButton ID="AdminEditLnk" runat="server" OnClick="AdminEdit_OnClick">Edit
               <asp:HiddenField ID="editAdminEmail" runat="server" Value='<%# Eval("emailAddress") %>' />
               </asp:LinkButton>

           <%# Eval("userName") %>
           <%# Eval("emailAddress") %>
           <%# Eval("firstName") %>
           <%# Eval("lastName") %>
           <%# Eval("isActive") %>

    </ItemTemplate>
    <AlternatingItemTemplate>

               <asp:LinkButton ID="AdminEditLnk" runat="server" OnClick="AdminEdit_OnClick">Edit
               <asp:HiddenField ID="editAdminEmail" runat="server" Value='<%# Eval("emailAddress") %>' />
               </asp:LinkButton>

           <%# Eval("userName") %>
           <%# Eval("emailAddress") %>
           <%# Eval("firstName") %>
           <%# Eval("lastName") %>
           <%# Eval("isActive") %>

    </AlternatingItemTemplate>
    <FooterTemplate>

                Add Administrator

    </FooterTemplate>
</asp:Repeater>

I have a linkbutton that fires this code:

protected void AdminEdit_OnClick(object sender, EventArgs e)
{
    HiddenField hf = (HiddenField)AdminGetAllRPT.FindControl("editAdminEmail");

but the hf is coming up null. What am I doing wrong?

Body:
Change AdminGetAllRPT.FindControl...

to

e.Item.FindControl...

Edit: Thanks for the votedown on a correct answer.

But yes e.Item.FindControl is what you want because what you're trying to do is not an event on the button, it's an event on the ItemCommand of the repeater.

<asp:Repeater OnItemCommand="MyButtonCommandEvent" ID="AdminGetAllRPT" runat="server" OnLoad="AdminGetAllRPT_Load">

Then in the code-behind you can setup the event

void MyButtonCommandEvent(Object src, RepeaterCommandEventArgs e) {
   //My event that is raised for each button pressed in the RepeaterItem
   var poo = e.Item.FindControl("myhiddenfieldid") as HiddenField;
}

Done...

To iterate over all RepeaterItems, you can have a button outside of the repeater (or maybe in the footer or something, this is not a repeater ItemCommand)

foreach(var item in AdminGetAllRPT.Items)
{
    if (item.ItemType == RepeaterItemType.Item || item.ItemType == RepeaterItemType.AlternatingItem)
    {
        var hiddenField = item.FindControl("hiddenFieldid") as HiddenField;
        //Do Stuff
    }
}


问:
Pass external parameter to Custom View
I just get going on drawing, canvas, basic animations but have stumbled upon this annoying issue:

I have a CustomView

```<code>public class CustomView extends View{
   //

   //Edited code ****************************
   bool dir;    // true -- right-to-left, false -- left-to-right

   public void setDirection(bool b)
       this.bool = b

   // ****************************************

   public CustomView(Context context) {
     super(context);
     ...
   }
   public CustomView(Context context, AttributeSet attrs) {
      super(context, attrs)
    ...
   }
   ...

   //stuff for animation
   protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
   ...
  }
  ...
</code>```

and inside I have created a little animation, basically something flying from right to left over and over again.

Now, let's say I wanted to have 2 of these views in my layout. But on the second one, stuff should fly from  left to right.

Is it possible to somehow pass this "parameter" to the Custom view? or do I really have to create the exact same class and change a plus sign to a minus sign and make it thereby a new class. This would mean animations created by extending view are not tunable at all.

If the latter is the case, then is there a better way to have tunable animations?

答:
Is it possible to somehow pass this "parameter" to the Custom view?

Step #1: Add a field to your custom view to hold your animation

Step #2: Add a setter method to populate the field

Step #3: Call that setter method from something (activity, fragment, etc.) to tell it what animation to use

Title: Pass external parameter to Custom View

Body:
I just get going on drawing, canvas, basic animations but have stumbled upon this annoying issue:

I have a CustomView

public class CustomView extends View{
   //

   //Edited code ****************************
   bool dir;    // true -- right-to-left, false -- left-to-right

   public void setDirection(bool b)
       this.bool = b

   // ****************************************

   public CustomView(Context context) {
     super(context);
     ...
   }
   public CustomView(Context context, AttributeSet attrs) {
      super(context, attrs)
    ...
   }
   ...

   //stuff for animation
   protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
   ...
  }
  ...

and inside I have created a little animation, basically something flying from right to left over and over again.

Now, let's say I wanted to have 2 of these views in my layout. But on the second one, stuff should fly from  left to right.

Is it possible to somehow pass this "parameter" to the Custom view? or do I really have to create the exact same class and change a plus sign to a minus sign and make it thereby a new class. This would mean animations created by extending view are not tunable at all.

If the latter is the case, then is there a better way to have tunable animations?


问:
Where is my DI error?
I try to make a filtered list of guidelines that are retrieved as a JSON object. However after running the code i get a DI error. Totally don't know where the error might arise? Does anybody have an idea?

The error:

error_handler.js:54 EXCEPTION: Uncaught (in promise): Error: DI Error
  Error: DI Error
      at NoProviderError.ZoneAwareError (http://localhost:8080/polyfills.bundle.js:3423:33)
      at NoProviderError.BaseError [as constructor] (http://localhost:8080/vendor.bundle.js:27156:16)
      at NoProviderError.AbstractProviderError [as constructor] (http://localhost:8080/vendor.bundle.js:55463:16)
      at new NoProviderError (http://localhost:8080/vendor.bundle.js:55525:16)
      at ReflectiveInjector_.throwOrNull (http://localhost:8080/vendor.bundle.js:74856:19)
      at ReflectiveInjector.getByKeyDefault (http://localhost:8080/vendor.bundle.js:74895:25)
      at ReflectiveInjector.getByKey (http://localhost:8080/vendor.bundle.js:74827:25)
      at ReflectiveInjector.get (http://localhost:8080/vendor.bundle.js:74696:21)
      at AppModuleInjector.NgModuleInjector.get (http://localhost:8080/vendor.bundle.js:56399:52)
      at CompiledTemplate.proxyViewClass.AppView.injectorGet (http://localhost:8080/vendor.bundle.js:75631:45)
      at CompiledTemplate.proxyViewClass.DebugAppView.injectorGet (http://localhost:8080/vendor.bundle.js:76059:49)
      at ElementInjector.get (http://localhost:8080/vendor.bundle.js:75135:27)
      at ReflectiveInjector_.getByKeyDefault (http://localhost:8080/vendor.bundle.js:74892:24)
      at ReflectiveInjector.getByKey (http://localhost:8080/vendor.bundle.js:74827:25)
      at ReflectiveInjector.get (http://localhost:8080/vendor.bundle.js:74696:21

)

Here is an excerpt of the code:

```<code>import { Component, OnInit, ElementRef, Injectable } from '@angular/core';
import { FormControl, FormArray, FormGroup, FormBuilder, Validators } from '@angular/forms';
import { Recommendation, Question, PreReq, Topic } from '../recommendations/recommendation';

import { RecommendationService } from '../recommendations/recommendation.service';

@Component({
  selector: 'app-inputform',
  templateUrl: './inputform.component.html',
  styleUrls: ['./inputform.component.css']
})

export class InputformComponent implements OnInit{
  inputform: FormGroup;
  Recommendations: Recommendation[];
  Guidelines: string[] = [];
  Topics: string [] = [];
  Questions: string [] = [];
  public query = '';
  public filteredList = [];
  public elementRef;
  selectedIdx: number;

  constructor(private fb: FormBuilder, myElement: ElementRef, private RecommendationService: RecommendationService) {
    this.elementRef = myElement;
    this.selectedIdx = -1;
    this.createForm();
  }

  ngOnInit() {
  this.RecommendationService
        .getRecommendations()
        .then((Recommendations: Recommendation[]) => {
        this.Recommendations = Recommendations.map((Recommendation) => {
          let checker = 0;
          console.log(Recommendation.guideline);
          for (let i = 0; i < this.Guidelines.length; i++) {
            if (Recommendation.guideline == this.Guidelines[i]) {
               checker = 1;
            }
          }
          if (checker == 0) {
            this.Guidelines.push(Recommendation.guideline);
          }
          checker = 0;

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

and this is the module definition:

```<code>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { ReactiveFormsModule } from '@angular/forms';  // <-- #1 import module voor reactieve forms
import { AppComponent } from './app.component';
import { RecommendationDetailsComponent } from './recommendations/recommendation-details/recommendation-details.component';
import { RecommendationListComponent } from './recommendations/recommendation-list/recommendation-list.component';
import { RecommendationSearchComponent } from './recommendations/recommendation-details/recommendation-search';
import { AppRoutingModule } from './app-routing.module';
import { GuidelinepageComponent } from './guidelinepage/guidelinepage.component';
import { InputformComponent } from './inputform/inputform.component';

@NgModule({
  declarations: [
    AppComponent,
    RecommendationDetailsComponent,
    RecommendationListComponent,
    RecommendationSearchComponent,
    GuidelinepageComponent,
    InputformComponent,
  ],
  imports: [
    AppRoutingModule,
    BrowserModule,
    FormsModule,
    HttpModule,
    ReactiveFormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

答:
Looks like you're not providing your RecommendationService

try modifying the providers section in your module code to:

```<code>providers: [ RecommendationService ],
</code>```

Title: Where is my DI error?

Body:
I try to make a filtered list of guidelines that are retrieved as a JSON object. However after running the code i get a DI error. Totally don't know where the error might arise? Does anybody have an idea?

The error:

error_handler.js:54 EXCEPTION: Uncaught (in promise): Error: DI Error
  Error: DI Error
      at NoProviderError.ZoneAwareError (http://localhost:8080/polyfills.bundle.js:3423:33)
      at NoProviderError.BaseError [as constructor] (http://localhost:8080/vendor.bundle.js:27156:16)
      at NoProviderError.AbstractProviderError [as constructor] (http://localhost:8080/vendor.bundle.js:55463:16)
      at new NoProviderError (http://localhost:8080/vendor.bundle.js:55525:16)
      at ReflectiveInjector_.throwOrNull (http://localhost:8080/vendor.bundle.js:74856:19)
      at ReflectiveInjector.getByKeyDefault (http://localhost:8080/vendor.bundle.js:74895:25)
      at ReflectiveInjector.getByKey (http://localhost:8080/vendor.bundle.js:74827:25)
      at ReflectiveInjector.get (http://localhost:8080/vendor.bundle.js:74696:21)
      at AppModuleInjector.NgModuleInjector.get (http://localhost:8080/vendor.bundle.js:56399:52)
      at CompiledTemplate.proxyViewClass.AppView.injectorGet (http://localhost:8080/vendor.bundle.js:75631:45)
      at CompiledTemplate.proxyViewClass.DebugAppView.injectorGet (http://localhost:8080/vendor.bundle.js:76059:49)
      at ElementInjector.get (http://localhost:8080/vendor.bundle.js:75135:27)
      at ReflectiveInjector_.getByKeyDefault (http://localhost:8080/vendor.bundle.js:74892:24)
      at ReflectiveInjector.getByKey (http://localhost:8080/vendor.bundle.js:74827:25)
      at ReflectiveInjector.get (http://localhost:8080/vendor.bundle.js:74696:21

)

Here is an excerpt of the code:

import { Component, OnInit, ElementRef, Injectable } from '@angular/core';
import { FormControl, FormArray, FormGroup, FormBuilder, Validators } from '@angular/forms';
import { Recommendation, Question, PreReq, Topic } from '../recommendations/recommendation';

import { RecommendationService } from '../recommendations/recommendation.service';

@Component({
  selector: 'app-inputform',
  templateUrl: './inputform.component.html',
  styleUrls: ['./inputform.component.css']
})

export class InputformComponent implements OnInit{
  inputform: FormGroup;
  Recommendations: Recommendation[];
  Guidelines: string[] = [];
  Topics: string [] = [];
  Questions: string [] = [];
  public query = '';
  public filteredList = [];
  public elementRef;
  selectedIdx: number;

  constructor(private fb: FormBuilder, myElement: ElementRef, private RecommendationService: RecommendationService) {
    this.elementRef = myElement;
    this.selectedIdx = -1;
    this.createForm();
  }

  ngOnInit() {
  this.RecommendationService
        .getRecommendations()
        .then((Recommendations: Recommendation[]) => {
        this.Recommendations = Recommendations.map((Recommendation) => {
          let checker = 0;
          console.log(Recommendation.guideline);
          for (let i = 0; i < this.Guidelines.length; i++) {
            if (Recommendation.guideline == this.Guidelines[i]) {
               checker = 1;
            }
          }
          if (checker == 0) {
            this.Guidelines.push(Recommendation.guideline);
          }
          checker = 0;

          return Recommendation;
        });
      });

and this is the module definition:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { ReactiveFormsModule } from '@angular/forms';  // <-- #1 import module voor reactieve forms
import { AppComponent } from './app.component';
import { RecommendationDetailsComponent } from './recommendations/recommendation-details/recommendation-details.component';
import { RecommendationListComponent } from './recommendations/recommendation-list/recommendation-list.component';
import { RecommendationSearchComponent } from './recommendations/recommendation-details/recommendation-search';
import { AppRoutingModule } from './app-routing.module';
import { GuidelinepageComponent } from './guidelinepage/guidelinepage.component';
import { InputformComponent } from './inputform/inputform.component';

@NgModule({
  declarations: [
    AppComponent,
    RecommendationDetailsComponent,
    RecommendationListComponent,
    RecommendationSearchComponent,
    GuidelinepageComponent,
    InputformComponent,
  ],
  imports: [
    AppRoutingModule,
    BrowserModule,
    FormsModule,
    HttpModule,
    ReactiveFormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Body:
Looks like you're not providing your RecommendationService

try modifying the providers section in your module code to:

providers: [ RecommendationService ],


问:
Cannot print api response on console
For some reason, when I try to print the response using print statement for the response body, the system does not print. please help.

In the following API post, I am using Java, rest-assured, TestNG on Eclipse Neon 3. Using @DataProvider annotation, I am passing multiple params in Post request to see the response of the call. Any help would be truly appreciated.

```<code>package com.auto.restassured;

import io.restassured.RestAssured;
import static io.restassured.RestAssured.basic;
import static io.restassured.RestAssured.given;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import io.restassured.response.Response;
import org.apache.log4j.Logger;
import org.apache.log4j.BasicConfigurator;

public class FilePostToVirusTotal {

static String baseURL = "https://www.virustotal.com/vtapi/v2/file/report";
Response myResponse;

@DataProvider(name = "md5hashes")
public String[][] createMd5Hashes() {

    return new String[][]  {

        {"md51", "c1105fb75bc00b5e487f7b26a5be7088"},
        {"md52", "213f3287c81d09b095334c9f3151cff8"},
        {"md53", "b00c2c458b4cf1eb172e354f54f0fe12"},
        {"md54", "32ac9b6b6b7cdbfce179acc5edae98c3"},
        {"md55", "510b0b81b85c025d538ed4bad78dc64f"},

    };

}

@Test(dataProvider = "md5hashes")
public void md5JsonTest(String apikey, String resource)
{

    //Catch API response
    myResponse = given().param("text", resource).param("text", "34b937e6e2d28ee6f93a70392d958de8ac4a8dd842e08bbca9bcb0d22f9b9960").when().post(baseURL);
    //Print Response
    System.out.println(myResponse.getBody().asString());

}
</code>```

}

答: You can use built-in log methods e.g. given().log().all() for request and then().log().all() for response

Title: Cannot print api response on console

Body:
For some reason, when I try to print the response using print statement for the response body, the system does not print. please help.

In the following API post, I am using Java, rest-assured, TestNG on Eclipse Neon 3. Using @DataProvider annotation, I am passing multiple params in Post request to see the response of the call. Any help would be truly appreciated.

package com.auto.restassured;

import io.restassured.RestAssured;
import static io.restassured.RestAssured.basic;
import static io.restassured.RestAssured.given;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import io.restassured.response.Response;
import org.apache.log4j.Logger;
import org.apache.log4j.BasicConfigurator;

public class FilePostToVirusTotal {

static String baseURL = "https://www.virustotal.com/vtapi/v2/file/report";
Response myResponse;

@DataProvider(name = "md5hashes")
public String[][] createMd5Hashes() {

    return new String[][]  {

        {"md51", "c1105fb75bc00b5e487f7b26a5be7088"},
        {"md52", "213f3287c81d09b095334c9f3151cff8"},
        {"md53", "b00c2c458b4cf1eb172e354f54f0fe12"},
        {"md54", "32ac9b6b6b7cdbfce179acc5edae98c3"},
        {"md55", "510b0b81b85c025d538ed4bad78dc64f"},

    };

}

@Test(dataProvider = "md5hashes")
public void md5JsonTest(String apikey, String resource)
{

    //Catch API response
    myResponse = given().param("text", resource).param("text", "34b937e6e2d28ee6f93a70392d958de8ac4a8dd842e08bbca9bcb0d22f9b9960").when().post(baseURL);
    //Print Response
    System.out.println(myResponse.getBody().asString());

}

}


问:
Pycharm Unexpected Result Output
I'm a beginner at Pycharm. I'm using Flask web framework to develop a basic web application. I have written a simple code to display "Hello" on my browser, which it did. Strangely, when I add something to 'Hello', such as 'Hello my name is Yusef' and re-run the program; it won't show any changes, it still appears with message 'Hello' on my browser. Any idea, what I'm missing?

Below is my code:

```<code>from flask import Flask

app = Flask(__name__)

@app.route('/')
def hello():
    return "hello world"

if __name__ == "__main__":
    app.run()
</code>```

答:
You need to clear the browser cache, this isn't a Pycharm issue, just clear your browser cache and you should be fine.
Open in incognito mode to avoid such issues.</p>

Title: Pycharm Unexpected Result Output

Body:
I'm a beginner at Pycharm. I'm using Flask web framework to develop a basic web application. I have written a simple code to display "Hello" on my browser, which it did. Strangely, when I add something to 'Hello', such as 'Hello my name is Yusef' and re-run the program; it won't show any changes, it still appears with message 'Hello' on my browser. Any idea, what I'm missing?

Below is my code:

from flask import Flask

app = Flask(__name__)

@app.route('/')
def hello():
    return "hello world"

if __name__ == "__main__":
    app.run()


问:
Load more hide previous content
I have this code using jquery, as I do when to display 4 new content it hid the previous 4 and when it reaches the end back to the beginning. Like a carousel.

Currently when you click on load more it keeps all the contents ready, current and previous.

```<code><html>
<head>

<style>

div {
    display:none;
    padding: 10px;
    border-width: 0 1px 1px 0;
    border-style: solid;
    border-color: #fff;
    box-shadow: 0 1px 1px #ccc;
    margin-bottom: 5px;
    background-color: #f1f1f1;
}

</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>

<body>

<div>Content</div>
<div>Content 1</div>
<div>Content 2</div>
<div>Content 3</div>
<div>Content 4</div>

<div>Content 5</div>
<div>Content 6</div>
<div>Content 7</div>
<div>Content 8</div>
<div>Content 9</div>
<div>Content 10</div>

<a href="#" id="loadMore">Load More</a>

<script>
$(function () {
    $("div").slice(0, 4).show();
    $("#loadMore").on('click', function (e) {
        e.preventDefault();
        $("div:hidden").slice(0, 4).slideDown();
        if ($("div:hidden").length == 0) {
            $("#load").fadeOut('slow');
        }
        $('html,body').animate({
            scrollTop: $(this).offset().top
        }, 1500);
    });
});

</script>
</body>
</htmL>
</code>```

答:
what you'll have to do is at every div content section you'll have to have a button in that div container that will trigger a special event.

you should go about this with something like:

```<code>  <div id="view1"> <h1>what ever your content is.<h1>
                  <p> then lets put a button below this
           It could be housed in a paragraph, div or table container
           how ever you want</p>
           <p align="center"> <button id="hide1">Next </button> </p>

   </div>
</code>```

your java would look like this for each button view:

```<code>     <script>

      $(document).ready(function(){
        $("#hide1").click(function(){
          $("#view1").hide();
          $("#view3").hide(); */ and list all the div you want to keep hidden
          $("#view4").hide();
       $("#view5").hide();
        $("#view6").hide()
          $("#view2").show();
         });

            });

            </script>
</code>```

then you'll need a script section to define your page, so it will execute on page load

```<code>      <script>
          $(document).ready(function(){

      $("#view2").hide();
         $("#view3").hide();
        $("#view4").hide();
       $("#view5").hide();
        $("#view6").hide();

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

of course you can combine the sets and put the page load code and your buttons click functions in the same document ready function to make the code run faster, but I decided to separate the two so I could be explain it better.

Title: Load more hide previous content

Body:
I have this code using jquery, as I do when to display 4 new content it hid the previous 4 and when it reaches the end back to the beginning. Like a carousel.

Currently when you click on load more it keeps all the contents ready, current and previous.

Content

Content 1

Content 2

Content 3

Content 4

Content 5

Content 6

Content 7

Content 8

Content 9

Content 10

Load More

Body:
what you'll have to do is at every div content section you'll have to have a button in that div container that will trigger a special event.

you should go about this with something like:

  <div id="view1"> <h1>what ever your content is.<h1>
                  <p> then lets put a button below this
           It could be housed in a paragraph, div or table container
           how ever you want</p>
           <p align="center"> <button id="hide1">Next </button> </p>

   </div>

your java would look like this for each button view:

     <script>

      $(document).ready(function(){
        $("#hide1").click(function(){
          $("#view1").hide();
          $("#view3").hide(); */ and list all the div you want to keep hidden
          $("#view4").hide();
       $("#view5").hide();
        $("#view6").hide()
          $("#view2").show();
         });

            });

            </script>

then you'll need a script section to define your page, so it will execute on page load

      <script>
          $(document).ready(function(){

      $("#view2").hide();
         $("#view3").hide();
        $("#view4").hide();
       $("#view5").hide();
        $("#view6").hide();

      });
       </script>

of course you can combine the sets and put the page load code and your buttons click functions in the same document ready function to make the code run faster, but I decided to separate the two so I could be explain it better.


问:
mysql: indexes in a delete query
I've asked a suggestion on indexes and select queries here
mysql: multiple indexes advice

Now I'd like to focus on a slightly different issue: I also have to delete lots of rows at the same time (in case you ask, my db supports a map creation tool, so you have lots of inserts and deletes, and re-inserts etc. as many as the user adds and removes map elements).
Are indexes used in deletes also? I imagined that I could copy table1 onto a new table2 excluding all the elements not being deleted (so I use a select), drop the old table1, and then copy table2 in table1, this way table1 ends up with only the rows it needs. Of course if a delete operation uses indexes the same way a select does this is useless. I stress that very large tables might reach millions of rows.
What is the best approach?

edit: this is the show create table

| map   | CREATE TABLE map (

  px decimal(7,3) NOT NULL,

  py decimal(7,3) NOT NULL,

  pz decimal(7,3) NOT NULL,

  rx decimal(7,3) NOT NULL,

  ry decimal(7,3) NOT NULL,

  rz decimal(7,3) NOT NULL,

  sx decimal(7,3) NOT NULL,

  sy decimal(7,3) NOT NULL,

  sz decimal(7,3) NOT NULL,

  a tinyint(1) NOT NULL,

  b tinyint(1) NOT NULL,

  c tinyint(1) NOT NULL,

  d tinyint(1) NOT NULL,

  e tinyint(1) NOT NULL,

  f tinyint(1) NOT NULL,

  g tinyint(1) NOT NULL,

  h tinyint(1) NOT NULL,

  i tinyint(1) NOT NULL,

  j tinyint(1) NOT NULL,

  k tinyint(1) NOT NULL,

  l tinyint(1) NOT NULL,

  m text,

  KEY a (a),

  KEY b (b),

  KEY c (c),

  KEY d (d)

) ENGINE=InnoDB DEFAULT CHARSET=latin1 |

答:
There are multiple techniques for dealing with a million rows being "updated".

If it is an complete replacement, build a new table, then swap (RENAME TABLE).

If the "update" needs to INSERT or UPDATE...  That is, some rows are new, some need minor modifications, then look at INSERT ... ON DUPLICATE KEY UPDATE ...

If you need some combination of the two, plus DELETEing some of the rows, it gets messier, but it can probably be done in a very few SQL statements, no looping.  CREATE and populate (LOAD DATA?) the change set; perform a multi-table DELETE; perform a INSERT ... SELECT .. LEFT JOIN .. to copy in "new" rows; do IODKU or multi-table UPDATE do do the UPDATEs.  I discuss some of that here.

I don't fully grok what you need to do.  Which of these techniques sounds close?  Can you rephrase your requirements closer to what I propose?  Perhaps then I can be more specific.  It would probably be useful to include SHOW CREATE TABLE and point out the column(s) that play a role in deciding what to insert/delete/update.

And, yes, INDEXes are useful for DELETEs and UPDATEs.

Title: mysql: indexes in a delete query


问:
Why language change required app to restart in Objective C
I am new in iOS and I am facing problem in language conversion

For English I am using code like this

```<code> [[NSUserDefaults standardUserDefaults] setObject:[NSArray arrayWithObjects:@"en", nil] forKey:@"AppleLanguages"];
            [[NSUserDefaults standardUserDefaults]synchronize];

            //to set the selected language at runtime (dynamically)
            NSLog(@"Language set=Malay");
            [NSBundle setLanguage:@"en"];
            MenuScreen *menu=[[MenuScreen alloc] initWithNibName:@"MenuScreen" bundle:nil];
            [self.navigationController pushViewController:menu animated:YES];
</code>```

For Thai Language I used code like this

```<code>[[NSUserDefaults standardUserDefaults] setObject:[NSArray arrayWithObjects:@"th-TH", nil] forKey:@"AppleLanguages"];
            [[NSUserDefaults standardUserDefaults]synchronize];

            //to set the selected language at runtime (dynamically)
            NSLog(@"Language set=Malay");
            [NSBundle setLanguage:@"th-TH"];
            MenuScreen *menu=[[MenuScreen alloc] initWithNibName:@"MenuScreen" bundle:nil];
            [self.navigationController pushViewController:menu animated:YES];
</code>```

But every time it required to restart app. Is there is any solution for this or any thing I am doing wrong.
Thanks in Advance!

答:
Muju I created sample project and I worked getting solution for your question.I got the solution perfectly.

In my below sample I want to change "Welcome to Thailand" to "ยินดีต้อนรับสู่ประเทศไทย".I use localization concept for this.

Before going to steps, I want you to see my storyboard designing

Please follow the below steps.

STEP 1:Click Project->info->Localization->Click +

Now it shows the drop down list of Language.From that we should select Thai

STEP 2:Once we choose or select the Language from drop down list,it shows the below window and we need to click Finish button

Now it looks like below

STEP 3:Create the String File for the localization and set the name.

above I set String file name as LocalizationThai

STEP 4:Click the LocalizationThai.strings also click the File Inspector.Click the Localization inside the File Inspector.Now it shows the below pop up box.

STEP 5:Click Localize.Once you Localize,it shows below like this

STEP 6:Click 3 Checkboxes

Now in bundle we have 3 files under LocalizationThai.strings

STEP 7:Write your required changing text in string files.

i.In LocalizationThai.strings(Thai) file I write below text

ii.In LocalizationThai.strings(English) file I write below text

iii.In LocalizationThai.strings(Base) file I write below text

STEP 8:Create the Header File for the multiple Languages.

STEP 9 : set the Header name(I set header name as LocalizationHeader) and define Languages in the Header file like below

LocalizationHeader.h

```<code>#ifndef LocalizationHeader_h
#define LocalizationHeader_h

#define ENGLISH 0
#define THAI 1

#endif /* LocalizationHeader_h */
</code>```

STEP 10:Implement the below coding part

Localization.h

```<code>#import <Foundation/Foundation.h>
#import "LocalizationHeader.h"
@interface Localization : NSObject
+(Localization *)sharedInstance;
+(NSString*) strSelectLanguage:(int)curLang;
+(NSString*) languageSelectedStringForKey:(NSString*) key;
@end
</code>```

Localization.m

```<code>#import "Localization.h"
int currentLanguage,selectedrow;
@implementation Localization

+(Localization *)sharedInstance
{
    static Localization *sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[Localization alloc] init];
    });
    return sharedInstance;
}

+(NSString*) strSelectLanguage:(int)curLang{
    if(curLang==THAI){
        [[NSUserDefaults standardUserDefaults] setObject:[NSArray arrayWithObjects:@"th", nil]forKey:@"AppleLanguages"];
    }
    else{
        [[NSUserDefaults standardUserDefaults] setObject:[NSArray arrayWithObjects:@"en", nil]forKey:@"AppleLanguages"];
    }
    [[NSUserDefaults standardUserDefaults] synchronize];
    currentLanguage=curLang;
    NSString *strLangSelect = [[[NSUserDefaults standardUserDefaults]objectForKey:@"AppleLanguages"] objectAtIndex:0];
    return strLangSelect;
}

+(NSString*) languageSelectedStringForKey:(NSString*) key
{
    NSString *path;
    NSString *strSelectedLanguage = [[[NSUserDefaults standardUserDefaults]objectForKey:@"AppleLanguages"] objectAtIndex:0];
    //When we check with iPhone,iPad device it shows "en-US".So we need to change it to "en"
    if([strSelectedLanguage hasPrefix:@"en-"])
        strSelectedLanguage = [strSelectedLanguage stringByReplacingOccurrencesOfString:@"en-US" withString:@"en"];
    if([strSelectedLanguage isEqualToString:[NSString stringWithFormat: @"en"]]){
        currentLanguage=ENGLISH;
        selectedrow=ENGLISH;
        path = [[NSBundle mainBundle] pathForResource:@"en" ofType:@"lproj"];
    }
    else{
        currentLanguage=THAI;
        selectedrow=THAI;
        path = [[NSBundle mainBundle] pathForResource:@"th" ofType:@"lproj"];
    }
    NSBundle* languageBundle = [NSBundle bundleWithPath:path];
    NSString* str=[languageBundle localizedStringForKey:key value:@"" table:@"LocalizationThai"];
    return str;
}
@end
</code>```

ViewController.h

```<code>#import <UIKit/UIKit.h>
#import "Localization.h"
@interface ViewController : UIViewController{
    Localization *localization;

}
@property (strong, nonatomic) IBOutlet UILabel *lblWelcome;
- (IBAction)actionChangeLanToThai:(id)sender;
- (IBAction)actionChangeLangToEng:(id)sender;
@end
</code>```

ViewController.m

```<code>#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
@synthesize lblWelcome;

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    localization = [Localization sharedInstance];
    lblWelcome.text = [Localization languageSelectedStringForKey:@"Welcome to Thailand"];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)actionChangeLanToThai:(id)sender {
    [Localization strSelectLanguage:THAI];
    lblWelcome.text = [Localization languageSelectedStringForKey:@"Welcome to Thailand"];

}

- (IBAction)actionChangeLangToEng:(id)sender {
    [Localization strSelectLanguage:ENGLISH];
    lblWelcome.text = [Localization languageSelectedStringForKey:@"Welcome to Thailand"];
}
@end
</code>```

When I run the app first

Then When I change the Language from English to Thai

Again when I change it to English

You have to follow the same steps for XIB

Below is for XIB

I create the ViewController with XIB.ViewController name is RootViewController

Now see the designing part

AppDelegate.h

```<code>#import <UIKit/UIKit.h>
#import "RootViewController.h"
@interface AppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@property (strong,nonatomic) RootViewController *viewController;
@end
</code>```

AppDelegate.m

```<code>- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.viewController = [[RootViewController alloc] initWithNibName:@"RootViewController" bundle:nil];
    UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:self.viewController];
    self.window.rootViewController = navController;
    [navController setNavigationBarHidden:YES];
    [self.window makeKeyAndVisible];
    return YES;
  }
</code>```

RootViewController.h

```<code> #import <UIKit/UIKit.h>
 #import "Localization.h"
 @interface RootViewController : UIViewController{
    Localization *localization;
 }
 @property (strong, nonatomic) IBOutlet UILabel *lblWelcomeThaiLang;
 - (IBAction)actionChangeLangToThai:(id)sender;
 - (IBAction)actionChangeLangToEng:(id)sender;
 @end
</code>```

RootViewController.m

```<code> #import "RootViewController.h"
 @interface RootViewController ()
 @end
 @implementation RootViewController
 @synthesize lblWelcomeThaiLang;
 - (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
 }
 - (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
 }
 - (IBAction)actionChangeLangToThai:(id)sender {
    [Localization strSelectLanguage:THAI];
    lblWelcomeThaiLang.text = [Localization languageSelectedStringForKey:@"Welcome to Thailand"];
 }
 - (IBAction)actionChangeLangToEng:(id)sender {
    [Localization strSelectLanguage:ENGLISH];
    lblWelcomeThaiLang.text = [Localization languageSelectedStringForKey:@"Welcome to Thailand"];
 }
 @end
</code>```

Now see the result

Body:
I am new in iOS and I am facing problem in language conversion

For English I am using code like this

 [[NSUserDefaults standardUserDefaults] setObject:[NSArray arrayWithObjects:@"en", nil] forKey:@"AppleLanguages"];
            [[NSUserDefaults standardUserDefaults]synchronize];

            //to set the selected language at runtime (dynamically)
            NSLog(@"Language set=Malay");
            [NSBundle setLanguage:@"en"];
            MenuScreen *menu=[[MenuScreen alloc] initWithNibName:@"MenuScreen" bundle:nil];
            [self.navigationController pushViewController:menu animated:YES];

For Thai Language I used code like this

[[NSUserDefaults standardUserDefaults] setObject:[NSArray arrayWithObjects:@"th-TH", nil] forKey:@"AppleLanguages"];
            [[NSUserDefaults standardUserDefaults]synchronize];

            //to set the selected language at runtime (dynamically)
            NSLog(@"Language set=Malay");
            [NSBundle setLanguage:@"th-TH"];
            MenuScreen *menu=[[MenuScreen alloc] initWithNibName:@"MenuScreen" bundle:nil];
            [self.navigationController pushViewController:menu animated:YES];

But every time it required to restart app. Is there is any solution for this or any thing I am doing wrong.
Thanks in Advance!

Body:
Muju I created sample project and I worked getting solution for your question.I got the solution perfectly.

In my below sample I want to change "Welcome to Thailand" to "ยินดีต้อนรับสู่ประเทศไทย".I use localization concept for this.

Before going to steps, I want you to see my storyboard designing

Please follow the below steps.

STEP 1:Click Project->info->Localization->Click +

Now it shows the drop down list of Language.From that we should select Thai

STEP 2:Once we choose or select the Language from drop down list,it shows the below window and we need to click Finish button

Now it looks like below

STEP 3:Create the String File for the localization and set the name.

above I set String file name as LocalizationThai

STEP 4:Click the LocalizationThai.strings also click the File Inspector.Click the Localization inside the File Inspector.Now it shows the below pop up box.

STEP 5:Click Localize.Once you Localize,it shows below like this

STEP 6:Click 3 Checkboxes

Now in bundle we have 3 files under LocalizationThai.strings

STEP 7:Write your required changing text in string files.

i.In LocalizationThai.strings(Thai) file I write below text

ii.In LocalizationThai.strings(English) file I write below text

iii.In LocalizationThai.strings(Base) file I write below text

STEP 8:Create the Header File for the multiple Languages.

STEP 9 : set the Header name(I set header name as LocalizationHeader) and define Languages in the Header file like below

LocalizationHeader.h

#ifndef LocalizationHeader_h
#define LocalizationHeader_h

#define ENGLISH 0
#define THAI 1

#endif /* LocalizationHeader_h */

STEP 10:Implement the below coding part

Localization.h

#import <Foundation/Foundation.h>
#import "LocalizationHeader.h"
@interface Localization : NSObject
+(Localization *)sharedInstance;
+(NSString*) strSelectLanguage:(int)curLang;
+(NSString*) languageSelectedStringForKey:(NSString*) key;
@end

Localization.m

#import "Localization.h"
int currentLanguage,selectedrow;
@implementation Localization

+(Localization *)sharedInstance
{
    static Localization *sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[Localization alloc] init];
    });
    return sharedInstance;
}

+(NSString*) strSelectLanguage:(int)curLang{
    if(curLang==THAI){
        [[NSUserDefaults standardUserDefaults] setObject:[NSArray arrayWithObjects:@"th", nil]forKey:@"AppleLanguages"];
    }
    else{
        [[NSUserDefaults standardUserDefaults] setObject:[NSArray arrayWithObjects:@"en", nil]forKey:@"AppleLanguages"];
    }
    [[NSUserDefaults standardUserDefaults] synchronize];
    currentLanguage=curLang;
    NSString *strLangSelect = [[[NSUserDefaults standardUserDefaults]objectForKey:@"AppleLanguages"] objectAtIndex:0];
    return strLangSelect;
}

+(NSString*) languageSelectedStringForKey:(NSString*) key
{
    NSString *path;
    NSString *strSelectedLanguage = [[[NSUserDefaults standardUserDefaults]objectForKey:@"AppleLanguages"] objectAtIndex:0];
    //When we check with iPhone,iPad device it shows "en-US".So we need to change it to "en"
    if([strSelectedLanguage hasPrefix:@"en-"])
        strSelectedLanguage = [strSelectedLanguage stringByReplacingOccurrencesOfString:@"en-US" withString:@"en"];
    if([strSelectedLanguage isEqualToString:[NSString stringWithFormat: @"en"]]){
        currentLanguage=ENGLISH;
        selectedrow=ENGLISH;
        path = [[NSBundle mainBundle] pathForResource:@"en" ofType:@"lproj"];
    }
    else{
        currentLanguage=THAI;
        selectedrow=THAI;
        path = [[NSBundle mainBundle] pathForResource:@"th" ofType:@"lproj"];
    }
    NSBundle* languageBundle = [NSBundle bundleWithPath:path];
    NSString* str=[languageBundle localizedStringForKey:key value:@"" table:@"LocalizationThai"];
    return str;
}
@end

ViewController.h

#import <UIKit/UIKit.h>
#import "Localization.h"
@interface ViewController : UIViewController{
    Localization *localization;

}
@property (strong, nonatomic) IBOutlet UILabel *lblWelcome;
- (IBAction)actionChangeLanToThai:(id)sender;
- (IBAction)actionChangeLangToEng:(id)sender;
@end

ViewController.m

#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
@synthesize lblWelcome;

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    localization = [Localization sharedInstance];
    lblWelcome.text = [Localization languageSelectedStringForKey:@"Welcome to Thailand"];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)actionChangeLanToThai:(id)sender {
    [Localization strSelectLanguage:THAI];
    lblWelcome.text = [Localization languageSelectedStringForKey:@"Welcome to Thailand"];

}

- (IBAction)actionChangeLangToEng:(id)sender {
    [Localization strSelectLanguage:ENGLISH];
    lblWelcome.text = [Localization languageSelectedStringForKey:@"Welcome to Thailand"];
}
@end

When I run the app first

Then When I change the Language from English to Thai

Again when I change it to English

You have to follow the same steps for XIB

Below is for XIB

I create the ViewController with XIB.ViewController name is RootViewController

Now see the designing part

AppDelegate.h

#import <UIKit/UIKit.h>
#import "RootViewController.h"
@interface AppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@property (strong,nonatomic) RootViewController *viewController;
@end

AppDelegate.m

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.viewController = [[RootViewController alloc] initWithNibName:@"RootViewController" bundle:nil];
    UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:self.viewController];
    self.window.rootViewController = navController;
    [navController setNavigationBarHidden:YES];
    [self.window makeKeyAndVisible];
    return YES;
  }

RootViewController.h

 #import <UIKit/UIKit.h>
 #import "Localization.h"
 @interface RootViewController : UIViewController{
    Localization *localization;
 }
 @property (strong, nonatomic) IBOutlet UILabel *lblWelcomeThaiLang;
 - (IBAction)actionChangeLangToThai:(id)sender;
 - (IBAction)actionChangeLangToEng:(id)sender;
 @end

RootViewController.m

 #import "RootViewController.h"
 @interface RootViewController ()
 @end
 @implementation RootViewController
 @synthesize lblWelcomeThaiLang;
 - (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
 }
 - (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
 }
 - (IBAction)actionChangeLangToThai:(id)sender {
    [Localization strSelectLanguage:THAI];
    lblWelcomeThaiLang.text = [Localization languageSelectedStringForKey:@"Welcome to Thailand"];
 }
 - (IBAction)actionChangeLangToEng:(id)sender {
    [Localization strSelectLanguage:ENGLISH];
    lblWelcomeThaiLang.text = [Localization languageSelectedStringForKey:@"Welcome to Thailand"];
 }
 @end

Now see the result


问:
JQuery panel hiding
I'm having trouble getting a simple panel hide script to work. It works for MLAWebsite's panel, but when I click the MLAJournal button nothing happens? I've tried everything I can think of and looked at it for quite a bit now and can't seem to figure it out.

Relevant JQuery and HTML:

$(document).ready(function(){
    //var currentStep = 0;

    $("#MLAJournalpanel").hide();
    $("#MLAWebsitepanel").hide();

    $("btnMLAJournal").click(function(){
        $("#MLAWebsitepanel").hide();
        $("#MLAJournalpanel").show();

        //currentStep = 1;
    });

    $("#btnMLAWebsite").click(function(){
        $("#MLAJournalpanel").hide();
        $("#MLAWebsitepanel").show();

        //currentStep = 2;
    });

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
   <head>
    <base target="_top">
     <link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons1.css">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
        <script src="Code.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>

     <style>
     .branding-below {
        bottom: 56px;
        top: 0;
     }

     .branding-text {
        left: 7px;
        position: relative;
        top: 3px;
     }

     .col-contain {
        overflow: hidden;
     }

     .col-one {
        float: left;
        width: 50%;
     }

     .logo {
        vertical-align: middle;
     }

     .radio-spacer {
        height: 20px;
     }

     .width-100 {
        width: 100%;
     }
     </style>

   </head>

   <body>
     <div class="sidebar branding-below">
            <input id="btnMLAJournal" type="button" value="MLA Journal"></input>
            <input id="btnMLAWebsite" type="button" value="MLA Website"></input>

            <div id="MLAJournalpanel" class="panel">
                <div class="panel-body">
                    <h2>MLA Journal</h2>
                </div>
            </div>

            <div id="MLAWebsitepanel" class="panel">
                <div class="panel-body">
                    <h1>dadadda</h1>
                    <p>surprise!"</p>
                </div>
            </div>

        </div>
   </body>
</html></code>```

答:
You're missing a # there.

```<code>$("#btnMLAJournal").click(function(){
    $("#MLAWebsitepanel").hide();
    $("#MLAJournalpanel").show();

    //currentStep = 1;
});
</code>```

Title: JQuery panel hiding

Body:
I'm having trouble getting a simple panel hide script to work. It works for MLAWebsite's panel, but when I click the MLAJournal button nothing happens? I've tried everything I can think of and looked at it for quite a bit now and can't seem to figure it out.

Relevant JQuery and HTML:

$(document).ready(function(){
    //var currentStep = 0;

    $("#MLAJournalpanel").hide();
    $("#MLAWebsitepanel").hide();

    $("btnMLAJournal").click(function(){
        $("#MLAWebsitepanel").hide();
        $("#MLAJournalpanel").show();

        //currentStep = 1;
    });

    $("#btnMLAWebsite").click(function(){
        $("#MLAJournalpanel").hide();
        $("#MLAWebsitepanel").show();

        //currentStep = 2;
    });

});

<!DOCTYPE html>

    <base target="_top">
     <link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons1.css">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

            <input id="btnMLAJournal" type="button" value="MLA Journal"></input>
            <input id="btnMLAWebsite" type="button" value="MLA Website"></input>

MLA Journal

dadadda

surprise!"

Body:
You're missing a # there.

$("#btnMLAJournal").click(function(){
    $("#MLAWebsitepanel").hide();
    $("#MLAJournalpanel").show();

    //currentStep = 1;
});


问:
Angular 4 http post request to google captcha api fails
I'm trying to verify my captcha response by using angular 4's http library and google's siteverify api.
For some reason in the console it's printing:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://www.google.com/recaptcha/api/siteverify. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

And

ERROR Object { _body: error, status: 0, ok: false, statusText: "", headers: Object, type: 3, url: null }

When i check my network tab it seems successfull:

Here's my code:

```<code>import { Injectable } from '@angular/core';
import { Http, URLSearchParams, Headers } from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()
export class CaptchaService {
  captchaUrl = 'https://www.google.com/recaptcha/api/siteverify';
  secretKey = 'SECRETKEY';

  constructor(private http: Http) { }

  verifyCaptcha = function(captchaResponse) {
    let headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');
    let body = new URLSearchParams;
    body.set('secret', this.secretKey);
    body.set('response', captchaResponse);
    return this.http.post(this.captchaUrl, body, { headers: headers })
    .map((response) => response.json())
    .subscribe((data) => console.log(data));
  }
}
</code>```

I'm sorry if this is a nooby question, but i'm new to angular.

Thanks

答: Ok turns out it was just google missing the cors headers.... I was able to fix this problem by having my own api send the request to google and then return it to me.</p>

Body:
I'm trying to verify my captcha response by using angular 4's http library and google's siteverify api.
For some reason in the console it's printing:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://www.google.com/recaptcha/api/siteverify. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

And

ERROR Object { _body: error, status: 0, ok: false, statusText: "", headers: Object, type: 3, url: null }

When i check my network tab it seems successfull:

Here's my code:

import { Injectable } from '@angular/core';
import { Http, URLSearchParams, Headers } from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()
export class CaptchaService {
  captchaUrl = 'https://www.google.com/recaptcha/api/siteverify';
  secretKey = 'SECRETKEY';

  constructor(private http: Http) { }

  verifyCaptcha = function(captchaResponse) {
    let headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');
    let body = new URLSearchParams;
    body.set('secret', this.secretKey);
    body.set('response', captchaResponse);
    return this.http.post(this.captchaUrl, body, { headers: headers })
    .map((response) => response.json())
    .subscribe((data) => console.log(data));
  }
}

I'm sorry if this is a nooby question, but i'm new to angular.

Thanks


问:
How to make a div not fill the height of its parent?
There are several questions about how to make a child div the height of its parent.

I have this behaviour by default and would like to have the inverse: so that the child does not fill the height of its parent (cross-axis):

#root {
  display: flex;
  flex-direction: row;
  height: 50px;
  width: 200px;
  background: blue;
}

.el {
  background: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="root">
  <div class="el">hello</div>
  <div class="el">world</div>
</div></code>```

What should I do (to the parent? to the child?) so that the height of hello and world is tight with the text?

答:
Use align-items with a value other than stretch

#root {
  display: flex;
  flex-direction: row;
  height: 50px;
  width: 200px;
  background: blue;
  align-items: flex-start;
}

.el {
  background: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="root">
  <div class="el">hello</div>
  <div class="el">world</div>
</div></code>```

Body:
There are several questions about how to make a child div the height of its parent.

I have this behaviour by default and would like to have the inverse: so that the child does not fill the height of its parent (cross-axis):

#root {
  display: flex;
  flex-direction: row;
  height: 50px;
  width: 200px;
  background: blue;
}

.el {
  background: red;
}

hello

world

What should I do (to the parent? to the child?) so that the height of hello and world is tight with the text?

Body:
Use align-items with a value other than stretch

#root {
  display: flex;
  flex-direction: row;
  height: 50px;
  width: 200px;
  background: blue;
  align-items: flex-start;
}

.el {
  background: red;
}

<div id="root">
  <div class="el">hello</div>
  <div class="el">world</div>
</div>


问:
Django Like button ajax
I'm been trying to create like button with ajax. In my model strain i have a field call user_like = models.ManyToManyField(settings.AUTH_USER_MODEL,
                                       related_name='strains_liked',
                                       blank=True)

This is my views.py

```<code>@login_required
@require_POST
def strain_like(request):
    strain_id = request.POST.get('id')
    action = request.POST.get('action')
    if strain_id and action:
        try:
            strain = Strain.objects.get(id=strain_id)
            if action == 'like':
                strain.user_like.add(request.user)
            else:
                strain.user_like.remove(request.user)
            return JsonResponse({'status': 'ok'})
        except:
            pass
    return JsonResponse({'status': 'ok'})
</code>```

this is urls.py

```<code>url(r'^like/$', views.strain_like, name='like')
</code>```

and this is my templates

```<code>{% block content %}
{{ strain.name }}

    {% with total_likes=strain.user_like.count user_like=strain.user_like.all %}
       <span class="count">
           <span class="total">{{ total_likes }}</span> like
       </span>
        <a href="#" data-id="{{ strain.id }}" data-action="{% if request.user in user_like %}un{% endif %}like" class="like">
        {% if request.user not in user_like %}
            Like
        {% else %}
            Unlike
        {% endif %}
        </a>
    {% endwith %}
{% endblock %}
<script>
var csrftoken = $.cookie('csrftoken');
function csrfSafeMethod(method) {
    // these HTTP methods do not require CSRF protection
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
    beforeSend: function(xhr, settings) {
        if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
            xhr.setRequestHeader("X-CSRFToken", csrftoken);
        }
    }
});
    $(document).ready(function () {
$('a.like').click(function(e){
            e.preventDefault();
            $.post('{% url "strains:like" %}',
             {
                 id: $(this).data('id'),
                 action: $(this).data('action')
             },
             function(data){
                if (data['status'] == 'ok')
                {
                    var previous_action = $('a.like').data('action');
                    $('a.like').data('action', previous_action == 'like' ? 'unlike' : 'like');
                    $('a.like').text(previous_action == 'like' ? 'unlike' : 'like');

                    var previous_likes = parseInt($('span.count .total').text());
                    $('span.count .total').text(previous_action == 'like' ? previous_likes + 1 : previous_likes - 1);
                }
            }
            );
     });
    })
</script>
</code>```

when I click to like or unlike I have this error in developer tools

IMG with error

答: Your url for this action is r'^like/$'. But you send a request for /strains/like, that is not matched.</p>

Title: Django Like button ajax

Body:
I'm been trying to create like button with ajax. In my model strain i have a field call user_like = models.ManyToManyField(settings.AUTH_USER_MODEL,
                                       related_name='strains_liked',
                                       blank=True)

This is my views.py

@login_required
@require_POST
def strain_like(request):
    strain_id = request.POST.get('id')
    action = request.POST.get('action')
    if strain_id and action:
        try:
            strain = Strain.objects.get(id=strain_id)
            if action == 'like':
                strain.user_like.add(request.user)
            else:
                strain.user_like.remove(request.user)
            return JsonResponse({'status': 'ok'})
        except:
            pass
    return JsonResponse({'status': 'ok'})

this is urls.py

url(r'^like/$', views.strain_like, name='like')

and this is my templates

{% block content %}
{{ strain.name }}

    {% with total_likes=strain.user_like.count user_like=strain.user_like.all %}

           {{ total_likes }} like

        {% if request.user not in user_like %}
            Like
        {% else %}
            Unlike
        {% endif %}

    {% endwith %}
{% endblock %}

when I click to like or unlike I have this error in developer tools

IMG with error


问:
Debugging monit
I find debugging monit to be a major pain. Monit's shell environment basically has nothing in it (no paths or other environment variables). Also, there are no log file that I can find.

The problem is, if the start or stop command in the monit script fails, it is difficult to discern what is wrong with it. Often times it is not as simple as just running the command on the shell because the shell environment is different from the monit shell environment.

What are some techniques that people use to debug monit configurations?

For example, I would be happy to have a monit shell, to test my scripts in, or a log file to see what went wrong.

答:
You can start Monit in verbose/debug mode by adding MONIT_OPTS="-v" to /etc/default/monit (don't forget to restart; /etc/init.d/monit restart).

You can then capture the output using tail -f /var/log/monit.log

```<code>[CEST Jun  4 21:10:42] info     : Starting Monit 5.17.1 daemon with http interface at [*]:2812
[CEST Jun  4 21:10:42] info     : Starting Monit HTTP server at [*]:2812
[CEST Jun  4 21:10:42] info     : Monit HTTP server started
[CEST Jun  4 21:10:42] info     : 'ocean' Monit 5.17.1 started
[CEST Jun  4 21:10:42] debug    : Sending Monit instance changed notification to monit@example.io
[CEST Jun  4 21:10:42] debug    : Trying to send mail via smtp.sendgrid.net:587
[CEST Jun  4 21:10:43] debug    : Processing postponed events queue
[CEST Jun  4 21:10:43] debug    : 'rootfs' succeeded getting filesystem statistics for '/'
[CEST Jun  4 21:10:43] debug    : 'rootfs' filesytem flags has not changed
[CEST Jun  4 21:10:43] debug    : 'rootfs' inode usage test succeeded [current inode usage=8.5%]
[CEST Jun  4 21:10:43] debug    : 'rootfs' space usage test succeeded [current space usage=59.6%]
[CEST Jun  4 21:10:43] debug    : 'ws.example.com' succeeded testing protocol [WEBSOCKET] at [ws.example.com]:80/faye [TCP/IP] [response time 114.070 ms]
[CEST Jun  4 21:10:43] debug    : 'ws.example.com' connection succeeded to [ws.example.com]:80/faye [TCP/IP]
</code>```

Title: Debugging monit

Body:
You can start Monit in verbose/debug mode by adding MONIT_OPTS="-v" to /etc/default/monit (don't forget to restart; /etc/init.d/monit restart).

You can then capture the output using tail -f /var/log/monit.log

[CEST Jun  4 21:10:42] info     : Starting Monit 5.17.1 daemon with http interface at [*]:2812
[CEST Jun  4 21:10:42] info     : Starting Monit HTTP server at [*]:2812
[CEST Jun  4 21:10:42] info     : Monit HTTP server started
[CEST Jun  4 21:10:42] info     : 'ocean' Monit 5.17.1 started
[CEST Jun  4 21:10:42] debug    : Sending Monit instance changed notification to monit@example.io
[CEST Jun  4 21:10:42] debug    : Trying to send mail via smtp.sendgrid.net:587
[CEST Jun  4 21:10:43] debug    : Processing postponed events queue
[CEST Jun  4 21:10:43] debug    : 'rootfs' succeeded getting filesystem statistics for '/'
[CEST Jun  4 21:10:43] debug    : 'rootfs' filesytem flags has not changed
[CEST Jun  4 21:10:43] debug    : 'rootfs' inode usage test succeeded [current inode usage=8.5%]
[CEST Jun  4 21:10:43] debug    : 'rootfs' space usage test succeeded [current space usage=59.6%]
[CEST Jun  4 21:10:43] debug    : 'ws.example.com' succeeded testing protocol [WEBSOCKET] at [ws.example.com]:80/faye [TCP/IP] [response time 114.070 ms]
[CEST Jun  4 21:10:43] debug    : 'ws.example.com' connection succeeded to [ws.example.com]:80/faye [TCP/IP]


问:
How to get past this duplicate symbol error (Vungle, CodePush)?
How do I get past this error?</p>

```<code>duplicate symbol _zipOpen4 in:
    /Users/a/app/app-client/ios/Pods/VungleSDK-iOS/VungleSDK.embeddedframework/VungleSDK.framework/VungleSDK(vungle_zip.o)
    /Users/a/Library/Developer/Xcode/DerivedData/AppClient-hirdjpuiiuosayehatqakfrifyvs/Build/Products/Debug-iphoneos/libCodePush.a(zip.o)
ld: 1 duplicate symbol for architecture arm64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
</code>```

答:
The duplicate symbol is fairly generic and co-relates to many things. In this case

There could be three reasons. Vungle and CodePush might be using same constant names. Or Vungle may internally be using CodePush or vice-versa.

Try to include only one in them and see if it works. Chances are that you might be using both libraries in same interface/implementation if so try splitting code into multiple files.

Body:
How do I get past this error?

duplicate symbol _zipOpen4 in:
    /Users/a/app/app-client/ios/Pods/VungleSDK-iOS/VungleSDK.embeddedframework/VungleSDK.framework/VungleSDK(vungle_zip.o)
    /Users/a/Library/Developer/Xcode/DerivedData/AppClient-hirdjpuiiuosayehatqakfrifyvs/Build/Products/Debug-iphoneos/libCodePush.a(zip.o)
ld: 1 duplicate symbol for architecture arm64
clang: error: linker command failed with exit code 1 (use -v to see invocation)


问:
compare two folders for non identical files with SymmetricDifference?
I am comparing two folders for non identical files with symmetric difference and write the length and directory name into a text file...But it is writing like

```<code>5506       D:\Trial\codegenpath\ramcovm247_portal_765\EDKPLAjaxCodeGen.log
5857       D:\Trial\codegenpath\ramcovm247_portal_765\EDKService.log
3741       D:\Trial\codegenpath\ramcovm247_portal_765\EDKTypes.log
10644      D:\Trial\zippedpath\ramcovm247_portal_765\EDKPLAjaxCodeGen.log
11714      D:\Trial\zippedpath\ramcovm247_portal_765\EDKService.log
7482       D:\Trial\zippedpath\ramcovm247_portal_765\EDKTypes.log
</code>```

but i need to write one after other like this

```<code>5506       D:\Trial\codegenpath\ramcovm247_portal_765\EDKPLAjaxCodeGen.log
10644      D:\Trial\zippedpath\ramcovm247_portal_765\EDKPLAjaxCodeGen.log
5857       D:\Trial\codegenpath\ramcovm247_portal_765\EDKService.log
11714      D:\Trial\zippedpath\ramcovm247_portal_765\EDKService.log
3741       D:\Trial\codegenpath\ramcovm247_portal_765\EDKTypes.log
7482       D:\Trial\zippedpath\ramcovm247_portal_765\EDKTypes.log
</code>```

Here is my code

```<code> var queryList1Only2 = (from file in list1 select file).Except(list2, myFileCompare1);
 var queryList1Only22 = (from file in list2 select file).Except(list1, myFileCompare1);
 var difference = queryList1Only2.ToHashSet();
 difference.SymmetricExceptWith(queryList1Only22);
 foreach (var v in difference )
       {
             dest.WriteLine(v.Length + "       " + v.FullName);

       }
</code>```

and

```<code>public class FileCompareLength : System.Collections.Generic.IEqualityComparer<System.IO.FileInfo>
        {
            public FileCompareLength() { }
            public bool Equals(System.IO.FileInfo f1, System.IO.FileInfo f2)
            {
                return (f1.Length == f2.Length);
            }
            public int GetHashCode(System.IO.FileInfo fi)
            {
                string s = String.Format("{0}", fi.Length);
                return s.GetHashCode();
            }
        }
</code>```

Any suggestion??

Body:
I am comparing two folders for non identical files with symmetric difference and write the length and directory name into a text file...But it is writing like

5506       D:\Trial\codegenpath\ramcovm247_portal_765\EDKPLAjaxCodeGen.log
5857       D:\Trial\codegenpath\ramcovm247_portal_765\EDKService.log
3741       D:\Trial\codegenpath\ramcovm247_portal_765\EDKTypes.log
10644      D:\Trial\zippedpath\ramcovm247_portal_765\EDKPLAjaxCodeGen.log
11714      D:\Trial\zippedpath\ramcovm247_portal_765\EDKService.log
7482       D:\Trial\zippedpath\ramcovm247_portal_765\EDKTypes.log

but i need to write one after other like this

5506       D:\Trial\codegenpath\ramcovm247_portal_765\EDKPLAjaxCodeGen.log
10644      D:\Trial\zippedpath\ramcovm247_portal_765\EDKPLAjaxCodeGen.log
5857       D:\Trial\codegenpath\ramcovm247_portal_765\EDKService.log
11714      D:\Trial\zippedpath\ramcovm247_portal_765\EDKService.log
3741       D:\Trial\codegenpath\ramcovm247_portal_765\EDKTypes.log
7482       D:\Trial\zippedpath\ramcovm247_portal_765\EDKTypes.log

Here is my code

 var queryList1Only2 = (from file in list1 select file).Except(list2, myFileCompare1);
 var queryList1Only22 = (from file in list2 select file).Except(list1, myFileCompare1);
 var difference = queryList1Only2.ToHashSet();
 difference.SymmetricExceptWith(queryList1Only22);
 foreach (var v in difference )
       {
             dest.WriteLine(v.Length + "       " + v.FullName);

       }

and

public class FileCompareLength : System.Collections.Generic.IEqualityComparer<System.IO.FileInfo>
        {
            public FileCompareLength() { }
            public bool Equals(System.IO.FileInfo f1, System.IO.FileInfo f2)
            {
                return (f1.Length == f2.Length);
            }
            public int GetHashCode(System.IO.FileInfo fi)
            {
                string s = String.Format("{0}", fi.Length);
                return s.GetHashCode();
            }
        }

Any suggestion??

Body: Try this http://msdn.microsoft.com/en-us/library/bb546137.aspx