问:
wordpress, mulitsite missing wp_options table
I have one strange request here, one of my client's WordPress multi-site environment site needs to migrate to another server and change domain name but when I checked the database the main wp-options table does not exist there.

And am I not able to do migration of this setup getting blank page

Can anyone suggest on this?

答:
It is not possible. I just deleted this table and the site stopped working. It shows the error: Error establishing a database connection

It doesn't have to be called wp_options though. The prefix could be different. So it could be something_options. The prefix is defined in the wp_config.php file.

If you are viewing the tables in phpMyAdmin you can enter _options in the text field for filtering the tables. This should find it.

If you mean that it doesn't exist on the new server only, then the database might not have been imported correctly. See if it exists on the old server.


来源: stackexchange

问:
PanTo() for google maps api without jQuery or PHP
I am not a developer, stuck in this panTo(). All I want is to run this function with if-else statement without loading new google map and without jQuery.

```<code><body>
    <div id="map"></div>
    <div>
        <ul>
            <li><a href="#" id="abc" onclick="main(1)">A</a></li>
            <li><a href="#" id="def" onclick="main(2)">B</a></li>
            <li><a href="#" id="ghi" onclick="main(3)">C</a></li>
            <li><a href="#" id="jkl" onclick="main(4)">D</a></li>
        </ul>
</body>
</div>

 <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBFX2v5z34vYKl0We4nHV4KFV1j6uVsltg&callback=main"></script>
</code>```

and function is:

```<code>function main(number) {
var map;
var map= {
    center:new google.maps.LatLng(33.72939,73.09315),
    zoom:10,
    };

if (number==1) {
    map.setCenter(51.508742,-0.120850);
}else if (number==2) {
    map.setCenter(33.72939,73.09315);
}else if (number==3) {
    map.setCenter(33.939445,73.34587);
}else{
    alert("Sorry! No Place found with name ")
}
var map1= new google.maps.Map(document.getElementById("map"),map);
}
</code>```

答:
Should be map.setCenter( latLngObject ); not map.setCenter( "lat", "lng" );

// don't complicate using else/if-s. Simplify your code!

var locations = { // name : [lat, lng]
  "1" : [51.508742, -0.120850],
  "2" : [33.72939, 73.09315],
  "3" : [33.939445, 73.34587]
};

// Define map Object
var map = new google.maps.Map(document.getElementById("map"), {
  // common map options here
  zoom: 16,
});

function main( name ){

  if(!(name in locations)) return alert("Sorry! No Place found with name: "+ name);
  // Create a new LatLng Object
  var latLng = new google.maps.LatLng( locations[name][0], locations[name][1] );
  map.setCenter( latLng );
}

// Init map using location name "2"
main("2");```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#map{height:200px;}
li {display: inline-block;} li a{cursor: pointer;}</code>```

A

B

C

D

```

notice also that I removed the &callback after the google maps URI

ContentLicense: CC BY-SA 3.0

Body:
I am not a developer, stuck in this panTo(). All I want is to run this function with if-else statement without loading new google map and without jQuery.

A

B

C

D

and function is:

function main(number) {
var map;
var map= {
    center:new google.maps.LatLng(33.72939,73.09315),
    zoom:10,
    };

if (number==1) {
    map.setCenter(51.508742,-0.120850);
}else if (number==2) {
    map.setCenter(33.72939,73.09315);
}else if (number==3) {
    map.setCenter(33.939445,73.34587);
}else{
    alert("Sorry! No Place found with name ")
}
var map1= new google.maps.Map(document.getElementById("map"),map);
}

Body:
Should be map.setCenter( latLngObject ); not map.setCenter( "lat", "lng" );

// don't complicate using else/if-s. Simplify your code!

var locations = { // name : [lat, lng]
  "1" : [51.508742, -0.120850],
  "2" : [33.72939, 73.09315],
  "3" : [33.939445, 73.34587]
};

// Define map Object
var map = new google.maps.Map(document.getElementById("map"), {
  // common map options here
  zoom: 16,
});

function main( name ){

  if(!(name in locations)) return alert("Sorry! No Place found with name: "+ name);
  // Create a new LatLng Object
  var latLng = new google.maps.LatLng( locations[name][0], locations[name][1] );
  map.setCenter( latLng );
}

// Init map using location name "2"
main("2");

#map{height:200px;}
li {display: inline-block;} li a{cursor: pointer;}

<ul>
  <li><a id="abc" onclick="main(1)">A</a></li>
  <li><a id="def" onclick="main(2)">B</a></li>
  <li><a id="ghi" onclick="main(3)">C</a></li>
  <li><a id="jkl" onclick="main(4)">D</a></li>
</ul>

<div id="map"></div>

<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBFX2v5z34vYKl0We4nHV4KFV1j6uVsltg"></script>

notice also that I removed the &callback after the google maps URI


问:
java access redis throw java.util.NoSuchElementException: Unable to validate object
when I used the java code to operated redis was OK.But  after project run  a few hours when I access redis again project   was throw The following  Exception .

java.util.NoSuchElementException: Unable to validate object
    at org.apache.commons.pool2.impl.GenericObjectPool.borrowObject(GenericObjectPool.java:506)
    at org.apache.commons.pool2.impl.GenericObjectPool.borrowObject(GenericObjectPool.java:363)
    at redis.clients.util.Pool.getResource(Pool.java:49)
    at redis.clients.jedis.JedisPool.getResource(JedisPool.java:99)

java code:

Jedis jedis = jedisPool.getResource();

I used a redis-cli.exe clinet to access redis is ok.  What should I do? Thanks.

答:
I met this problem today, too, I tried to find some solutions, but at last, I just relaunched the redis-server, the problem was solved.

PS: my redis version is 3.2.6


问:
Append cookies and sending to next request using cookie manager in jmeter
I am doing load test for my application. For login i am getting set-cookie in response headers. Is it possible to append all cookies using cookie manager and sending it in request header for another request</p>

答:
Just add cookie manager to you thread group.

Jmeter will automatically transfer the cookies to the further request correspondingly


问:
Determine if table exists in SQL Server CE?
I know this is similar to this question, but I'm using SQL Server CE 3.5 with a WinForms project in C#.  How can I determine whether a table exists?  I know the IF keyword is not supported, though EXISTS is.  Does information_schema exist in CE where I can query against it?  Thanks.

答:
Yes, it does exist:</p>

```<code>SELECT *
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME = 'TableName'
</code>```

OwnerDisplayName: mitzoe

ContentLicense: CC BY-SA 2.5

Body:
Yes, it does exist:

SELECT *
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME = 'TableName'

OwnerDisplayName: Mehrdad Afshari


问:
How to pass arguments to an included file?
I'm trying to make the whole  section its own include file. One drawback is the title and description and keyword will be the same; I can't figure out how to pass arguments to the include file.

So here is the code:

index.php

```<code><?php include("header.php?header=aaaaaaaaaaaaaaaaaaaaa"); ?>

<body>
.....
..
.
</code>```

header.php

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<link rel="shortcut icon" href="favicon.ico">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="Keywords" content=" <?php $_GET["header"]?> " >
<meta name="Description" content=" <?php $_GET["header"]?> " >
<title> <?php $_GET["header"]?> </title>
<link rel="stylesheet" type="text/css" href="reset.css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
</head>
</code>```

Obviously this doesn't work; how can I pass arguments to an included file?

答:
If you include a file it is just like inserting that code into the parent file. You could simply do this:

```<code><?php
$parameter = "Hello World";
include("header.php");
?>
</code>```

and then in the header.php

```<code><?php
$parameter = isset($parameter) ? $parameter : "Default Text";
// Use accordingly
?>
</code>```

I used the isset() method to verify that it has a value already and is instantiated.

Body:
I'm trying to make the whole  section its own include file. One drawback is the title and description and keyword will be the same; I can't figure out how to pass arguments to the include file.

So here is the code:

index.php

<?php include("header.php?header=aaaaaaaaaaaaaaaaaaaaa"); ?>

.....
..
.

header.php

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<link rel="shortcut icon" href="favicon.ico">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="Keywords" content=" <?php $_GET["header"]?> " >
<meta name="Description" content=" <?php $_GET["header"]?> " >
<title> <?php $_GET["header"]?> </title>
<link rel="stylesheet" type="text/css" href="reset.css" />

Obviously this doesn't work; how can I pass arguments to an included file?

Body:
If you include a file it is just like inserting that code into the parent file. You could simply do this:

<?php
$parameter = "Hello World";
include("header.php");
?>

and then in the header.php

<?php
$parameter = isset($parameter) ? $parameter : "Default Text";
// Use accordingly
?>

I used the isset() method to verify that it has a value already and is instantiated.


问:
Use PHP to submit HTTP POST request containing image
So I've seen many examples of uploading an image via PHP using move_uploaded_file, but from the way that sounds, that would be a PHP script that resides on the server. In my case, I'm not trying to handle an uploaded file. I'm trying to submit a POST request and actually have the binary content of the file inserted with the HTTP POST request.

For example, my PHP script should be able to submit a form and include an image in its HTTP POST data, but I can't seem to figure this out or find valid examples specifically for doing this.

To further clarify, I am using CURL within PHP to submit this multipart/form-data.

Here's an example of what I have now:

```<code>function GetPostData($filename) {
    if(!$filename) {
        echo "The image doesn't exist ".$filename;
    } else {
        $data = [
            'device_timestamp' => time(),
            'photo' => '@'.$filename
        ];
        return $data;
    }
}
function SendRequest($url, $post, $data, $userAgent, $cookies) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 'https://i.example.com/api/v1/'.$url);
    curl_setopt($ch, CURLOPT_USERAGENT, $userAgent);
    curl_setopt($ch, CURLOPT_PROXY, 'http://192.168.1.21:8080');
    curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

    if($post) {
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    }

    if($cookies) {
        curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookies.txt');
    } else {
        curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookies.txt');
    }

    $response = curl_exec($ch);
    $http = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    return [
        'code' => $http,
        'response' => $response,
    ];
}
</code>```

.

```<code> $data = GetPostData($filename);
        $post = SendRequest('media/upload/', true, $data, $agent, true);
</code>```

But when I submit the image via the PHP script, this is what it looks like when I inspect the network traffic.

```<code>Content-Type: multipart/form-data; boundary=------------------------eee3f953c516cc55
Connection: close

--------------------------eee3f953c516cc55
Content-Disposition: form-data; name="device_timestamp"

1491023582
--------------------------eee3f953c516cc55
Content-Disposition: form-data; name="photo"

@/home/user/Desktop/square.jpeg
--------------------------eee3f953c516cc55--
</code>```

Isn't the POST data supposed to contain the binary output of the image? How would the server save the image otherwise if just the path of the file is submitted in the form and not the actual image?

In other words, just like you would go to the terminal and type cat image.jpg, that's what I need PHP to submit in its form.

答:
You have required to use in  then you can easly uploded image

ex:-

```<code><form action="" method="post" enctype="multipart/form-data">
</form>
</code>```

PHP Code Required

```<code> <?php
    if(isset($_POST['submit']))
            {
            $filename=$_FILES['Yourfilename']['name'];
            $filetempname=$_FILES['Yourfilename']['tmp_name'];
            $fname=md5($_SERVER['REMOTE_ADDR'].rand()).$filename;
            $filepath1="uploads/folder name/".$fname;
            move_uploaded_file($filetempname,$filepath1);
    ?>
</code>```

Body:
So I've seen many examples of uploading an image via PHP using move_uploaded_file, but from the way that sounds, that would be a PHP script that resides on the server. In my case, I'm not trying to handle an uploaded file. I'm trying to submit a POST request and actually have the binary content of the file inserted with the HTTP POST request.

For example, my PHP script should be able to submit a form and include an image in its HTTP POST data, but I can't seem to figure this out or find valid examples specifically for doing this.

To further clarify, I am using CURL within PHP to submit this multipart/form-data.

Here's an example of what I have now:

function GetPostData($filename) {
    if(!$filename) {
        echo "The image doesn't exist ".$filename;
    } else {
        $data = [
            'device_timestamp' => time(),
            'photo' => '@'.$filename
        ];
        return $data;
    }
}
function SendRequest($url, $post, $data, $userAgent, $cookies) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 'https://i.example.com/api/v1/'.$url);
    curl_setopt($ch, CURLOPT_USERAGENT, $userAgent);
    curl_setopt($ch, CURLOPT_PROXY, 'http://192.168.1.21:8080');
    curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

    if($post) {
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    }

    if($cookies) {
        curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookies.txt');
    } else {
        curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookies.txt');
    }

    $response = curl_exec($ch);
    $http = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    return [
        'code' => $http,
        'response' => $response,
    ];
}

.

 $data = GetPostData($filename);
        $post = SendRequest('media/upload/', true, $data, $agent, true);

But when I submit the image via the PHP script, this is what it looks like when I inspect the network traffic.

Content-Type: multipart/form-data; boundary=------------------------eee3f953c516cc55
Connection: close

--------------------------eee3f953c516cc55
Content-Disposition: form-data; name="device_timestamp"

1491023582
--------------------------eee3f953c516cc55
Content-Disposition: form-data; name="photo"

@/home/user/Desktop/square.jpeg
--------------------------eee3f953c516cc55--

Isn't the POST data supposed to contain the binary output of the image? How would the server save the image otherwise if just the path of the file is submitted in the form and not the actual image?

In other words, just like you would go to the terminal and type cat image.jpg, that's what I need PHP to submit in its form.

Body:
You have required to use in  then you can easly uploded image

ex:-

<form action="" method="post" enctype="multipart/form-data">
</form>

PHP Code Required

 <?php
    if(isset($_POST['submit']))
            {
            $filename=$_FILES['Yourfilename']['name'];
            $filetempname=$_FILES['Yourfilename']['tmp_name'];
            $fname=md5($_SERVER['REMOTE_ADDR'].rand()).$filename;
            $filepath1="uploads/folder name/".$fname;
            move_uploaded_file($filetempname,$filepath1);
    ?>


问:
Table content held within a div will not print over several pages
I have some tabular content that is held within a div thus..

```<code><div class="someDiv">
   <table>
       <tr>...</tr>
       ....
       ....
       <tr>...</tr>
   </table>
</div>
</code>```

When I print using a print stylesheet with all items set to float:none !important; and height:auto !important; the table will only print one page worth of information as opposed to about 10 or so.

Has anyone come across this before?

答:
Could it be as simple as CSS syntax?

I see in this old article (where I first heard of this) they have a space between the exclamation point and the word important.

I also see a space here (section 3.1 is about important).

Does your CSS code have that space?

Body:
I have some tabular content that is held within a div thus..

...

       ....
       ....

...

When I print using a print stylesheet with all items set to float:none !important; and height:auto !important; the table will only print one page worth of information as opposed to about 10 or so.

Has anyone come across this before?


问:
Passing map distance to ngModel in Ionic 2
This is part of the code:

```<code>calculateAndDisplayRoute(directionsService, directionsDisplay) {

  if((this.origin.query !== '') && (this.destination.query !== '')) {

    directionsService.route({
      origin: this.origin.query,
      destination: this.destination.query,
      travelMode: 'DRIVING'
    }, function(response, status) {
      if (status === 'OK') {
        directionsDisplay.setDirections(response);
        var total = 0;
        var route = directionsDisplay.getDirections().routes[0];

        for (var i = 0; i < route.legs.length; i++) {
          total += route.legs[i].distance.value;
        }

        total = total / 1000;

        this.distance = total << PROBLEM

      } else {
        window.alert('Directions request failed due to ' + status);
      }

  });

  } else {
    return;
}
</code>```

This gets the route and distance in km (var total) between the two places. The problem is that I can't use the variable outside this callback. I want to bind it to a ngModel for further manual change / use.

I know that I need to use ngZone in order to update the model but I can't pass zone to the callback, some help ?^^

```<code><ion-input type="number" (keyup)="onKey($event)" [(ngModel)]="distance"></ion-input>
</code>```

答:
Problem is not ngZone at all. It is the fact that you are using a regular function which changes this value. So this.distance within function(response,status) is different.
Try:

```<code>(response, status)=> {
      if (status === 'OK') {
        directionsDisplay.setDirections(response);
        var total = 0;
        var route = directionsDisplay.getDirections().routes[0];

        for (var i = 0; i < route.legs.length; i++) {
          total += route.legs[i].distance.value;
        }

        total = total / 1000;

        this.distance = total << PROBLEM

      } else {
        window.alert('Directions request failed due to ' + status);
      }

  }
</code>```

Arrow Functions Reference

Body:
This is part of the code:

calculateAndDisplayRoute(directionsService, directionsDisplay) {

  if((this.origin.query !== '') && (this.destination.query !== '')) {

    directionsService.route({
      origin: this.origin.query,
      destination: this.destination.query,
      travelMode: 'DRIVING'
    }, function(response, status) {
      if (status === 'OK') {
        directionsDisplay.setDirections(response);
        var total = 0;
        var route = directionsDisplay.getDirections().routes[0];

        for (var i = 0; i < route.legs.length; i++) {
          total += route.legs[i].distance.value;
        }

        total = total / 1000;

        this.distance = total << PROBLEM

      } else {
        window.alert('Directions request failed due to ' + status);
      }

  });

  } else {
    return;
}

This gets the route and distance in km (var total) between the two places. The problem is that I can't use the variable outside this callback. I want to bind it to a ngModel for further manual change / use.

I know that I need to use ngZone in order to update the model but I can't pass zone to the callback, some help ?^^

<ion-input type="number" (keyup)="onKey($event)" [(ngModel)]="distance"></ion-input>

Body:
Problem is not ngZone at all. It is the fact that you are using a regular function which changes this value. So this.distance within function(response,status) is different.
Try:

(response, status)=> {
      if (status === 'OK') {
        directionsDisplay.setDirections(response);
        var total = 0;
        var route = directionsDisplay.getDirections().routes[0];

        for (var i = 0; i < route.legs.length; i++) {
          total += route.legs[i].distance.value;
        }

        total = total / 1000;

        this.distance = total << PROBLEM

      } else {
        window.alert('Directions request failed due to ' + status);
      }

  }

Arrow Functions Reference


问:
String replace not working in function
string input= "hello, how are you tod&#97y"
i knw the encode is not in proper format thats why i am using a function to replace improper "tod&#97y" to "today".

f1(input);
but at time of comparing

```<code>if  (input.Contains("today") == true)
{
    lbldisplay.Text = str1;
}
</code>```

it returing false,i have debugged the program.it is working correctly till replace s1.Replace("&#97","a");(shown "hello, how are you today") but at return statement return s1; it is returning original value i.e "hello, how are you tod&#97y".

```<code>public string f1(string s1)
{
    s1 = s1.Replace("&#97", "a");
    return s1;
}
</code>```

please help.thank you.

答:
Most likely what is happening is that you're not assigning the return value back to your variable when you call it.  The parameter is not declared ref so this will have no effect:

```<code>f1(input);
</code>```

You would need to use this:

```<code>input = f1(input);
</code>```

Title: String replace not working in function

Body:
string input= "hello, how are you tod&#97y"
i knw the encode is not in proper format thats why i am using a function to replace improper "tod&#97y" to "today".

f1(input);
but at time of comparing

if  (input.Contains("today") == true)
{
    lbldisplay.Text = str1;
}

it returing false,i have debugged the program.it is working correctly till replace s1.Replace("&#97","a");(shown "hello, how are you today") but at return statement return s1; it is returning original value i.e "hello, how are you tod&#97y".

public string f1(string s1)
{
    s1 = s1.Replace("&#97", "a");
    return s1;
}

please help.thank you.

Body:
Most likely what is happening is that you're not assigning the return value back to your variable when you call it.  The parameter is not declared ref so this will have no effect:

f1(input);

You would need to use this:

input = f1(input);


问:
How to concatenate numpy arrays into a specific shape?
I need to assign an array of mnist image values to the following variable...

```<code>x = tf.get_variable("input_image", shape=[10,784], dtype=tf.float32)
</code>```

The problem is I need to sift the through the mnist data set and extract 10 images of the number 2 and assign it to x.

This is my approach at sifting through the data set and extracting the number 2...

```<code>while mnist.test.next_batch(FLAGS.batch_size):
    sample_image, sample_label = mnist.test.next_batch(10)
    # get number 2
    itemindex = np.where(sample_label == 1)

    if itemindex[1][0] == 1:
        # append image to numpy
        np.append(labels_of_2, sample_image)
    # if the numpy array has 10 images then we stop
    if labels_of_2.size == 10:
        break

# assign to variable
sess.run(tf.assign(x, labels_of_2))
</code>```

The problem is I believe my logic is flawed. I need an array with shape [10, 784] to satisfy the variable x and clearly the following line is not the way to do it...

```<code>np.append(labels_of_2, sample_image)
</code>```

There must be an easy way to accomplish what I want but I cannot figure it out.

答:
Forget np.append; collect the images in a list

```<code>alist = []
while mnist.test.next_batch(FLAGS.batch_size):
    sample_image, sample_label = mnist.test.next_batch(10)
    # get number 2
    itemindex = np.where(sample_label == 1)

    if itemindex[1][0] == 1:
        alist.append(sample_image)
    # if the list has 10 images then we stop
    if len(alist) == 10:
        break

    labels_of_2 = np.array(alist)
</code>```

Assuming the arrays in alist all have the same size, e.g. (784,), then the array function will produce a new array with shape (10, 784).  If the images are (1,784) you could use np.concatenate(alist, axis=0) instead.

List append is faster and easier to use.

Body:
I need to assign an array of mnist image values to the following variable...

x = tf.get_variable("input_image", shape=[10,784], dtype=tf.float32)

The problem is I need to sift the through the mnist data set and extract 10 images of the number 2 and assign it to x.

This is my approach at sifting through the data set and extracting the number 2...

while mnist.test.next_batch(FLAGS.batch_size):
    sample_image, sample_label = mnist.test.next_batch(10)
    # get number 2
    itemindex = np.where(sample_label == 1)

    if itemindex[1][0] == 1:
        # append image to numpy
        np.append(labels_of_2, sample_image)
    # if the numpy array has 10 images then we stop
    if labels_of_2.size == 10:
        break

# assign to variable
sess.run(tf.assign(x, labels_of_2))

The problem is I believe my logic is flawed. I need an array with shape [10, 784] to satisfy the variable x and clearly the following line is not the way to do it...

np.append(labels_of_2, sample_image)

There must be an easy way to accomplish what I want but I cannot figure it out.

Body:
Forget np.append; collect the images in a list

alist = []
while mnist.test.next_batch(FLAGS.batch_size):
    sample_image, sample_label = mnist.test.next_batch(10)
    # get number 2
    itemindex = np.where(sample_label == 1)

    if itemindex[1][0] == 1:
        alist.append(sample_image)
    # if the list has 10 images then we stop
    if len(alist) == 10:
        break

    labels_of_2 = np.array(alist)

Assuming the arrays in alist all have the same size, e.g. (784,), then the array function will produce a new array with shape (10, 784).  If the images are (1,784) you could use np.concatenate(alist, axis=0) instead.

List append is faster and easier to use.


问:
Recursive Synchronization vs Recursive Reentrant Lock
I know  thread is allowed to acquire a monitor owned by itself i.e. In Java, synchronized locks are reentrant as shown in example below.

My query is if i use java.util.concurrent.locks.ReentrantLock API it will produce the same result or not, Can we have dead lock in synchronized but never in java.util.concurrent.locks.ReentrantLock

e.g.

```<code>  final Object[] objects = new Object[10]

    public synchronized Object setAndReturnPrevious(int index, Object val) {
        lock.lock();//If i use this will it be same as above synchronization
        set(index, val);
        lock.unlock()//;
    }

    public synchronized void set(int index, Object val) {
        lock.lock();//
        objects[index] = val;
        lock.unlock();//
    }
</code>```

答:
If you look at the Java doc (here) and the point is very clear (emphasis mine):

A reentrant mutual exclusion Lock with the same basic behavior and
  semantics as the implicit monitor lock accessed using synchronized
  methods and statements, but with extended capabilities. A
  ReentrantLock is owned by the thread last successfully locking, but
  not yet unlocking it. A thread invoking lock will return, successfully
  acquiring the lock, when the lock is not owned by another thread. The
  method will return immediately if the current thread already owns the
  lock.

The main point is that they both behave with the same concept, but ReentrantLock lock provides additional methods to lock()/unlock()/etc.. methods which you can use them explicitly in different code blocks (methods).

Body:
I know  thread is allowed to acquire a monitor owned by itself i.e. In Java, synchronized locks are reentrant as shown in example below.

My query is if i use java.util.concurrent.locks.ReentrantLock API it will produce the same result or not, Can we have dead lock in synchronized but never in java.util.concurrent.locks.ReentrantLock

e.g.

  final Object[] objects = new Object[10]

    public synchronized Object setAndReturnPrevious(int index, Object val) {
        lock.lock();//If i use this will it be same as above synchronization
        set(index, val);
        lock.unlock()//;
    }

    public synchronized void set(int index, Object val) {
        lock.lock();//
        objects[index] = val;
        lock.unlock();//
    }


问:
Monitor Coldfusion on linux with monit?
We are trying to use monit to monitor services on our Ubuntu machine. I have successfully setup a host url check to make sure that coldfusion can render web pages and it there is an error to restart coldfusion.

I was wondering if there is a way to get more stats into monit by monitoring the coldfusion process. I have been unable to find out if coldfusion creates a pid file.

Does Coldfusion 9 or Jrun create a pid file for monit to use? Is there another way to monitor coldfusion with monit?

答:
ColdFusion can output real-time performance metrics such as:

Page hits per second

Database accesses per second

Number of queued requests

Number of running requests

Number of timed out requests

Average queue time

Average request time

Average database transaction time

Bytes incoming per second

Bytes outgoing per second

You can learn more about the output of this logging here: http://help.adobe.com/en_US/ColdFusion/9.0/Admin/WSc3ff6d0ea77859461172e0811cbf3638e6-7fe0.html#WS9F365555-357A-4a15-AC72-449EF611E342

I would be interested to learn how you set this up once complete. I'll have the same task in a few weeks.

Thanks!

ContentLicense: CC BY-SA 4.0

Title: Monitor Coldfusion on linux with monit?


问:
Is there an easy way to export 1 module and 1 form from 1 Excel file to dozens of other Excel files?
The title pretty much says it all.  I'm trying to find a way to export 1 Module (named Module1) and one Form (named UserForm1).  I know the object names are very creative.  Is there a way to export these 2 objects from one Excel template, to dozens of other Excel templates that have no code, but need the same code I have in this one file?

I looked at the link below and followed the instructions.

http://www.rondebruin.nl/win/s9/win002.htm

With the 2 noted references added in, I start to step through the code, and get to this line:

```<code>For Each cmpComponent In wkbSource.VBProject.VBComponents
</code>```

Here I get an error that says 'Run-time error 1004 Method VBProject of object Workbook failed'.

One more thing, I commented out a few lines around:

```<code>'If wkbSource.VBProject.Protection = 1 Then'
</code>```

I don't really care about that part.  Any idea how I can make this work?

TIA.

答:
The easiest way should be to use VBE's export and import functions.

In the VB Editor, select the module or form you want to export.

Right-click and select "Export file ...". This function is also available from the File menu in the ribbon.

Save the module as a file with the BAS extension. For the form the extension will be FRM.

Use the "Import file ..." function to import the BAS or FRM files into other documents.

Body:
The title pretty much says it all.  I'm trying to find a way to export 1 Module (named Module1) and one Form (named UserForm1).  I know the object names are very creative.  Is there a way to export these 2 objects from one Excel template, to dozens of other Excel templates that have no code, but need the same code I have in this one file?

I looked at the link below and followed the instructions.

http://www.rondebruin.nl/win/s9/win002.htm

With the 2 noted references added in, I start to step through the code, and get to this line:

For Each cmpComponent In wkbSource.VBProject.VBComponents

Here I get an error that says 'Run-time error 1004 Method VBProject of object Workbook failed'.

One more thing, I commented out a few lines around:

'If wkbSource.VBProject.Protection = 1 Then'

I don't really care about that part.  Any idea how I can make this work?

TIA.


问:
Use Javascript to create dynamic input id
I want to use javascript to create <input/> tags with a dynamic id (name attribute will be the same) depending on the order in which they appear.

I have the first <input/> tag in plain html and a div that should append a new <input/> with an incremented id when clicked:

```<code><input type="text" name="1" id="1" />
<div class="add_new" onClick="add_new_input()">+</div>
</code>```

Now, the javascript needs to count the amount of <input/>s currently being displayed (count) and use that amount to generate a dynamic id (count+1).

Therefore if the
<.. is clicked twice, the output should be as follows:

```<code><input type="text" name="1" id="1" />
<input type="text" name="2" id="2" />
<input type="text" name="3" id="3" />
</code>```

If I append the new <input/> tag in my form using jquery's append(), would this add to the previously appended <input/>s? Or would I need to append one <input/>, then two, then three, etc?

Also, how can I use javascript to count the amount of <input/>s currently being displayed?

答:
```<code>var index = 1;

function add_fields() {

    index++;
    var objTo = document.getElementById('room_fileds')
    var divtest = document.createElement("tr");
    divtest.innerHTML = ("<tr><td class='slno'>" + index + "</td><td><input type='text'></td><td><button class='remove_button' onclick='myfn()'>remove</button></td></tr>");
    objTo.appendChild(divtest);
     $(".slno").each(function(index, element) {
            $(element).text(index + 1);

       });

}

function myfn() {
        $(".remove_button").parents('tr').first().remove();
        $(".slno").each(function(index, element) {
            $(element).text(index + 1);

        });
}
</code>```

Body:
I want to use javascript to create <input/> tags with a dynamic id (name attribute will be the same) depending on the order in which they appear.

I have the first <input/> tag in plain html and a div that should append a new <input/> with an incremented id when clicked:

<input type="text" name="1" id="1" />

+

Now, the javascript needs to count the amount of <input/>s currently being displayed (count) and use that amount to generate a dynamic id (count+1).

Therefore if the
<.. is clicked twice, the output should be as follows:

<input type="text" name="1" id="1" />
<input type="text" name="2" id="2" />
<input type="text" name="3" id="3" />

If I append the new <input/> tag in my form using jquery's append(), would this add to the previously appended <input/>s? Or would I need to append one <input/>, then two, then three, etc?

Also, how can I use javascript to count the amount of <input/>s currently being displayed?


问:
Run jQuery Counter with value from MySQL
I have jQuery counter which move numbers from one fixed number to other fixed number. But I want to create the Counter which end at number which come from MySQL database.

Counter Function Code:

Now It starts value from 99950 and end value is 100000 but I want to change end value. It should be the value which I fetch from mysql.

```<code><script type="text/javascript">

(function($) {
    $.fn.countTo = function(options) {
        // merge the default plugin settings with the custom options
        options = $.extend({}, $.fn.countTo.defaults, options || {});

        // how many times to update the value, and how much to increment the value on each update
        var loops = Math.ceil(options.speed / options.refreshInterval),
            increment = (options.to - options.from) / loops;

        return $(this).each(function() {
            var _this = this,
                loopCount = 0,
                value = options.from,
                interval = setInterval(updateTimer, options.refreshInterval);

            function updateTimer() {
                value += increment;
                loopCount++;
                $(_this).html(value.toFixed(options.decimals));

                if (typeof(options.onUpdate) == 'function') {
                    options.onUpdate.call(_this, value);
                }

                if (loopCount >= loops) {
                    clearInterval(interval);
                    value = options.to;

                    if (typeof(options.onComplete) == 'function') {
                        options.onComplete.call(_this, value);
                    }
                }
            }
        });
    };

    $.fn.countTo.defaults = {
        from: 0,  // the number the element should start at
        to: 100,  // the number the element should end at
        speed: 1000,  // how long it should take to count between the target numbers
        refreshInterval: 100,  // how often the element should be updated
        decimals: 0,  // the number of decimal places to show
        onUpdate: null,  // callback method for every time the element is updated,
        onComplete: null,  // callback method for when the element finishes updating
    };
})(jQuery);

jQuery(function($) {
        $('.timer').countTo({
            from: 99950,
            to: 100000,
            speed: 2000,
            refreshInterval: 50,
            onComplete: function(value) {
                console.debug(this);
            }
        });
    });

</script>
</code>```

HTML Code:

```<code><h2><span class="timer" style="color:#F44336;font-weight:700; font-size:20px;"></span></h2>
</code>```

答:
jQuery code:

```<code>$.ajax({
    type: "POST",
    dataType: "json",
    url: 'endpoint to php script',
    success: function(data) {
        $('.timer').countTo({
            from: data.startFrom,
            to: data.endOn,
            speed: 2000,
            refreshInterval: 50,
            onComplete: function(value) {
                console.debug(this);
            }
        });
    },
    error: function(error) {
        console.log(error);
    }
});
</code>```

PHP code:

```<code><?php
//I assume you know how connect to your database and get data
header("Content-Type: application/json", true);

$result = array(
        'startFrom' => 1000,
        'endOn' => 9000
    );

echo json_encode($result);
</code>```

I thnik it's clear and explain this code is not needed

Body:
I have jQuery counter which move numbers from one fixed number to other fixed number. But I want to create the Counter which end at number which come from MySQL database.

Counter Function Code:

Now It starts value from 99950 and end value is 100000 but I want to change end value. It should be the value which I fetch from mysql.

HTML Code:

Body:
jQuery code:

$.ajax({
    type: "POST",
    dataType: "json",
    url: 'endpoint to php script',
    success: function(data) {
        $('.timer').countTo({
            from: data.startFrom,
            to: data.endOn,
            speed: 2000,
            refreshInterval: 50,
            onComplete: function(value) {
                console.debug(this);
            }
        });
    },
    error: function(error) {
        console.log(error);
    }
});

PHP code:

<?php
//I assume you know how connect to your database and get data
header("Content-Type: application/json", true);

$result = array(
        'startFrom' => 1000,
        'endOn' => 9000
    );

echo json_encode($result);

I thnik it's clear and explain this code is not needed


问:
Cannot see "font" resource type in Android studio
I was going through the new Android O features, and one of the new thing is now app can add fonts directly into res folder. As per the android documentation for working with fonts, one of the 1st step is to create a new resource type named "font" using Right-click the res folder and go to New > Android resource directory.

But I could not see "font" option available for resource type in the drop down in android studio.

Below is the image attached.

I am not able to see "font" option in the drop down, and hence I am unable to create font android resource directory.

My Android studio details:

Android Studio 2.3
Build #AI-162.3764568, built on February 24, 2017
JRE: 1.8.0_112-release-b06 x86_64
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o

答:
Step 1: create new folder name it 'assets' under app/src/main manually.

Step 2: create 'fonts' name folder inside assets folder.

Step 3: put your .ttf files under fonts folder.

then check your studio project structure.


问:
How to assign a package to a variable in Go?
First of all, the word "variable" might be wrong in the question but I assume the detailed question explains why I'm using the word "variable".

I have two packages with different names but the exact same function(s).

Depending on the input of the user I want to use the function of a package. But instead of switching over the packages I would like to assign the package to a new function with a generic name, how to do this? And if it's not possible, why?

```<code>// foo/bar.go

package foo

func Test() {
    fmt.Println("hola from bar")
}
</code>```

```<code>// baz/bar.go

package baz

func Test() {
    fmt.Println("hola from baz")
}
</code>```

```<code>// main.go

package main

import (
    "foo"
    "baz"
)

func main() {

    thePackage := flag.String("package", "foo", "a package")

    if thePackage == "foo" {
        howToSetThis := foo // How to do this?
    } else {
        howToSetThis := baz // How to do this?
    }

    howToSetThis.Test() // execs Println from one of the two bar.go files

}
</code>```

In JavaScript I would do something like (simplified):

```<code>function foo(){
  console.log("hola from foo")
}

function baz(){
  console.log("hola from baz")
}

if(somethingInput == "foo"){
  var howToSetThis = foo;
} else {
  var howToSetThis = baz;
}

howToSetThis();
</code>```

答:
You could define a interface in a package that requires the functions you want to have in those two packages .

```<code>package intfc

type Intfc interface {
    Test()
}
</code>```

And then two structs in different packages which implements that interface

```<code>package foo

import "fmt"

type Foo struct {

}

func (f Foo) Test() {
    fmt.Println("hola from foo")
}
</code>```

and

```<code>package baz

import "fmt"

type Baz struct {

}

func (f Baz) Test() {
    fmt.Println("hola from baz")
}
</code>```

And then in main do something like this:

```<code>package main

import (
    "foo"
    "baz"
    "intfc"
    "flag"
)

func main() {

    var howToSetThis intfc.Intfc

    thePackage := flag.String("package", "foo", "a package")

    if *thePackage == "foo" {
        howToSetThis = foo.Foo{}
    } else {
        howToSetThis = baz.Baz{}
    }

    howToSetThis.Test() // execs Println from one of the two bar.go files

}
</code>```

Body:
First of all, the word "variable" might be wrong in the question but I assume the detailed question explains why I'm using the word "variable".

I have two packages with different names but the exact same function(s).

Depending on the input of the user I want to use the function of a package. But instead of switching over the packages I would like to assign the package to a new function with a generic name, how to do this? And if it's not possible, why?

// foo/bar.go

package foo

func Test() {
    fmt.Println("hola from bar")
}

// baz/bar.go

package baz

func Test() {
    fmt.Println("hola from baz")
}

// main.go

package main

import (
    "foo"
    "baz"
)

func main() {

    thePackage := flag.String("package", "foo", "a package")

    if thePackage == "foo" {
        howToSetThis := foo // How to do this?
    } else {
        howToSetThis := baz // How to do this?
    }

    howToSetThis.Test() // execs Println from one of the two bar.go files

}

In JavaScript I would do something like (simplified):

function foo(){
  console.log("hola from foo")
}

function baz(){
  console.log("hola from baz")
}

if(somethingInput == "foo"){
  var howToSetThis = foo;
} else {
  var howToSetThis = baz;
}

howToSetThis();

Body:
You could define a interface in a package that requires the functions you want to have in those two packages .

package intfc

type Intfc interface {
    Test()
}

And then two structs in different packages which implements that interface

package foo

import "fmt"

type Foo struct {

}

func (f Foo) Test() {
    fmt.Println("hola from foo")
}

and

package baz

import "fmt"

type Baz struct {

}

func (f Baz) Test() {
    fmt.Println("hola from baz")
}

And then in main do something like this:

package main

import (
    "foo"
    "baz"
    "intfc"
    "flag"
)

func main() {

    var howToSetThis intfc.Intfc

    thePackage := flag.String("package", "foo", "a package")

    if *thePackage == "foo" {
        howToSetThis = foo.Foo{}
    } else {
        howToSetThis = baz.Baz{}
    }

    howToSetThis.Test() // execs Println from one of the two bar.go files

}


问:
SQL Server: set NULL value to today's value
I have a column EntryDate in a SQL Server database.

How can I set a NULL value to fill it with today's date (server time) if value was not provided in a query?

答:
Disallow Nulls on the column and set a default on the column of getdate()

```<code>/*Deal with any existing NULLs*/
UPDATE YourTable SET EntryDate=GETDATE() WHERE EntryDate IS NULL

/*Disallow NULLs*/
ALTER TABLE YourTable ALTER COLUMN EntryDate DATE NOT NULL

/*Add default constraint*/
ALTER TABLE YourTable ADD CONSTRAINT
    DF_YourTable_EntryDate DEFAULT GETDATE() FOR EntryDate
</code>```

Body:
Disallow Nulls on the column and set a default on the column of getdate()

/*Deal with any existing NULLs*/
UPDATE YourTable SET EntryDate=GETDATE() WHERE EntryDate IS NULL

/*Disallow NULLs*/
ALTER TABLE YourTable ALTER COLUMN EntryDate DATE NOT NULL

/*Add default constraint*/
ALTER TABLE YourTable ADD CONSTRAINT
    DF_YourTable_EntryDate DEFAULT GETDATE() FOR EntryDate


问:
root node slash vs root node name
Why would the slash cause a file io error (cannot open xml file) vs if I specifically use name in match it works? Aren't they synonymous?

snippet of code below:

```<code>  <xsl:template match="/"> <!-- In question, different results / vs root -->
    <xsl:apply-templates select="greeting"/>
  </xsl:template>
</code>```

Sample xslt

```<code><?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  version="1.0">

  <xsl:output method="html"/>

  <xsl:template match="/"> <!-- In question, different results / vs root -->
    <xsl:apply-templates select="greeting"/>
  </xsl:template>

  <xsl:template match="greeting">
    <html>
      <body>
        <h1>
          <xsl:value-of select="."/>
        </h1>
      </body>
    </html>
  </xsl:template>
</xsl:stylesheet>
</code>```

Sample xml

```<code><?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet type="text/xsl" href="helloworld.xslt"?>
<root>
  <greeting>
    Hello, World!
  </greeting>
  <greeting>
    Hello, World Too!
  </greeting>
</root>
</code>```

答:
When you use / you are at the document level.

The only element that exists on the document level is the <root> element. But you are using the select attribute to say, specifically apply templates to the element named greetings, but this does not exist on the document level, it exists in your <root> element.

You have three options.

Change it to <xsl:template match="/root">

Remove the select <xsl:apply-templates />

Change your select to <xsl:apply-templates select="root/greeting"/>

Title: root node slash vs root node name

Body:
Why would the slash cause a file io error (cannot open xml file) vs if I specifically use name in match it works? Aren't they synonymous?

snippet of code below:

  <xsl:template match="/">
    <xsl:apply-templates select="greeting"/>
  </xsl:template>

Sample xslt

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  version="1.0">

  <xsl:output method="html"/>

  <xsl:template match="/">
    <xsl:apply-templates select="greeting"/>
  </xsl:template>

  <xsl:template match="greeting">

          <xsl:value-of select="."/>

  </xsl:template>
</xsl:stylesheet>

Sample xml

<?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet type="text/xsl" href="helloworld.xslt"?>
<root>
  <greeting>
    Hello, World!
  </greeting>
  <greeting>
    Hello, World Too!
  </greeting>
</root>


问:
`CI` return wrong value
I have no idea why my CI return wrong value from phpMyAdmin
Model :

```<code>    <?php

class Post extends CI_Model
{
function __construct()
{
    parent::__construct();

}
function getallpost()
{
    return $this->db->get('post');

}

}
?>
</code>```

And

Controller :

```<code>    <?php

defined('BASEPATH') OR exit('No direct script access allowed');

class Postc extends CI_Controller {
    function index()
    {
    $this->load->model('post');
    $posts=$this->post->getallpost();
    echo '```';
    print_r($posts);

    }
}
?>
```

enter image description here

答:
Change your Model Code

```<code><?php
    class Post extends CI_Model
    {
        function __construct()
        {
            parent::__construct();
        }
        function getallpost()
        {
            $query = $this->db->get('post');
            if($query->num_rows() > 0)
            {
                return $query->result();
            }else{
                return false;
            }
        }
    }
</code>```

Title: `CI` return wrong value

Body:
I have no idea why my CI return wrong value from phpMyAdmin
Model :

    <?php

class Post extends CI_Model
{
function __construct()
{
    parent::__construct();

}
function getallpost()
{
    return $this->db->get('post');

}

}
?>

And

Controller :

    <?php

defined('BASEPATH') OR exit('No direct script access allowed');

class Postc extends CI_Controller {
    function index()
    {
    $this->load->model('post');
    $posts=$this->post->getallpost();
    echo '
';
    print_r($posts);

    }
}
?>

enter image description here

Body:
Change your Model Code

<?php
    class Post extends CI_Model
    {
        function __construct()
        {
            parent::__construct();
        }
        function getallpost()
        {
            $query = $this->db->get('post');
            if($query->num_rows() > 0)
            {
                return $query->result();
            }else{
                return false;
            }
        }
    }


问:
fake p12 and mobileprovision for phonegap
I use phonegap for making an iOS application. I want a fake certificate  file for building my ios app.
I find a fake p12 file but when I build the app, it shows the following error:

Error - Certificate doesn't match profile: The default keychain
  doesn't have an identity matching

答: I don't think fake things work for making any certificate for iphone or mac os, you have to register your system csr file to developer account and then you have to permit to get register in your key chain, thats way certificate works. Else you cant test your app in legal way, and i dont know about some hacking thing about it or else..</p>


问:
Rx Java Android : How to convert this callback block to Observer
I'm trying to upload a file via Amazon's S3 Android SDK. I've used RX Java a bit but I'm not sure how to convert this method to a method that returns an Observable because I want to chain the result of this method to another Observable call. It confuses me I suppose because of the fact that this does not return right away and can't return until either OnError or OnState changes. How do I handle these situations in an RX way?

```<code>public void uploadFile(TransferObserver transferObserver){

    transferObserver.setTransferListener(new TransferListener() {
        @Override
        public void onStateChanged(int id, TransferState state) {

        }

        @Override
        public void onProgressChanged(int id, long bytesCurrent, long bytesTotal) {

        }

        @Override
        public void onError(int id, Exception ex) {

        }
  });

}
</code>```

If someone could answer with RX Java 2 and lambdas that would be great because I just keep coming up short on this one

答:
@Yosriz I could not get your code to compile , but you did help me quite a bit so based on your answer here is what I now have:</p>

```<code>return Observable.fromEmitter(new Action1<AsyncEmitter<Integer>>() {
            @Override
            public void call(AsyncEmitter<Integer> emitter) {

                transObs.setTransferListener(new TransferListener() {
                    @Override
                    public void onStateChanged(int id, TransferState state) {
                        if (state == TransferState.COMPLETED)
                            emitter.onCompleted();
                    }

                    @Override
                    public void onProgressChanged(int id, long bytesCurrent, long bytesTotal) {

                    }

                    @Override
                    public void onError(int id, Exception ex) {
                        emitter.onError(ex);
                    }
                });

                emitter.setCancellation(new AsyncEmitter.Cancellable() {
                    @Override
                    public void cancel() throws Exception {

                        transObs.cleanTransferListener();
                    }
                });
            }
        }, AsyncEmitter.BackpressureMode.DROP);
</code>```

Body:
I'm trying to upload a file via Amazon's S3 Android SDK. I've used RX Java a bit but I'm not sure how to convert this method to a method that returns an Observable because I want to chain the result of this method to another Observable call. It confuses me I suppose because of the fact that this does not return right away and can't return until either OnError or OnState changes. How do I handle these situations in an RX way?

public void uploadFile(TransferObserver transferObserver){

    transferObserver.setTransferListener(new TransferListener() {
        @Override
        public void onStateChanged(int id, TransferState state) {

        }

        @Override
        public void onProgressChanged(int id, long bytesCurrent, long bytesTotal) {

        }

        @Override
        public void onError(int id, Exception ex) {

        }
  });

}

If someone could answer with RX Java 2 and lambdas that would be great because I just keep coming up short on this one

Body:
@Yosriz I could not get your code to compile , but you did help me quite a bit so based on your answer here is what I now have:

return Observable.fromEmitter(new Action1<AsyncEmitter<Integer>>() {
            @Override
            public void call(AsyncEmitter<Integer> emitter) {

                transObs.setTransferListener(new TransferListener() {
                    @Override
                    public void onStateChanged(int id, TransferState state) {
                        if (state == TransferState.COMPLETED)
                            emitter.onCompleted();
                    }

                    @Override
                    public void onProgressChanged(int id, long bytesCurrent, long bytesTotal) {

                    }

                    @Override
                    public void onError(int id, Exception ex) {
                        emitter.onError(ex);
                    }
                });

                emitter.setCancellation(new AsyncEmitter.Cancellable() {
                    @Override
                    public void cancel() throws Exception {

                        transObs.cleanTransferListener();
                    }
                });
            }
        }, AsyncEmitter.BackpressureMode.DROP);


问:
Java - C-Like Fork?
Is it possible to do  a "C like" fork in java, using an new independent jvm process ?

How?

答:
This answer is probably a little late but:

http://akuma.kohsuke.org/

seems to be exactly what your looking for

OwnerDisplayName: sakana

Title: Java - C-Like Fork?

LastEditorDisplayName: Marko


问:
Fatal error: Cannot redeclare <method>
I'm getting the following error:

Fatal error: Cannot redeclare ControllerSaleOrder::saveValue() in /home/xxxxxxxxxx/public_html/vqmod/vqcache/vq2-system_storage_modification_admin_controller_sale_order.php on line 2617

Here's the code:

```<code>public function saveValue() {
  $json = array();
  if ($this->request->server['REQUEST_METHOD'] == 'POST') {
    $post = $this->request->post;
    $this->load->model('sale/order');
    $json['msg'] = $this->model_sale_order->saveNewValue($post);
  }
  $this->response->addHeader('Content-Type: application/json');
  $this->response->setOutput(json_encode($json));
}

public function install() {
  if ($this->request->server['REQUEST_METHOD'] == 'POST') {
    $this->load->model('sale/order');
    $json['success'] = $this->model_sale_order->install();
  }
  $this->response->addHeader('Content-Type: application/json');
  $this->response->setOutput(json_encode($json));
}
</code>```

答: in vq2-system_storage_modification_admin_controller_sale_order.php there are two methods named saveValue(). Rename one</p>

Title: Fatal error: Cannot redeclare <method>

Body:
I'm getting the following error:

Fatal error: Cannot redeclare ControllerSaleOrder::saveValue() in /home/xxxxxxxxxx/public_html/vqmod/vqcache/vq2-system_storage_modification_admin_controller_sale_order.php on line 2617

Here's the code:

public function saveValue() {
  $json = array();
  if ($this->request->server['REQUEST_METHOD'] == 'POST') {
    $post = $this->request->post;
    $this->load->model('sale/order');
    $json['msg'] = $this->model_sale_order->saveNewValue($post);
  }
  $this->response->addHeader('Content-Type: application/json');
  $this->response->setOutput(json_encode($json));
}

public function install() {
  if ($this->request->server['REQUEST_METHOD'] == 'POST') {
    $this->load->model('sale/order');
    $json['success'] = $this->model_sale_order->install();
  }
  $this->response->addHeader('Content-Type: application/json');
  $this->response->setOutput(json_encode($json));
}


问:
Error sending email via SMTP in C#, Does this still work in 2017?
Having researched the issue extensively especially applying recommendations from similar issues on stackoverflow, the below code still returns error ""System.Net.Mail.SmtpException: Syntax error, command unrecognized. The server response was: connection rejected at....""

```<code>        try
        {
            var mail = new MailMessage();
            mail.From = new MailAddress("demo77377@gmail.com");
            mail.To.Add(new MailAddress("xxxxxxx@gmail.com"));
            mail.Subject = "TEST";
            mail.Body = "This is a test mail from C# program";

            using (var smtp = new SmtpClient())
            {
                smtp.Credentials = new System.Net.NetworkCredential("demo77377@gmail.com", "AABBCCDDEE1!","gmail.com");
                smtp.Host = "smtp.gmail.com";
                smtp.Port = 587;
                smtp.EnableSsl = true;
                smtp.UseDefaultCredentials = false;
                smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
                smtp.Timeout = 10000;
                //
                smtp.Send(mail);
                Console.WriteLine("Message sent successfully");
                Console.ReadLine();
            }

        }
        catch (Exception e)
</code>```

I have done everything possible

On Client> I have alternated smtp properties (permutation) etc

On Server> I have made gmail account less secure, I have disabled captcha etc

I observed that similar issues on stackoverflow were mostly dated over 3years ago and thus, is it possible that gmail no longer supports this SMTP method via C#, likewise has it been deprecated in favor of gmail API

Also, please find provided in code, original password supplied for the gmail account, in order to confirm if this issue is general or isolated to this gmail account

Thanks

答: Finally got it working after switching from my hotel's wireless network to office network...type of network connection has a role to play in sending email via SMTP in C#</p>

Body:
Having researched the issue extensively especially applying recommendations from similar issues on stackoverflow, the below code still returns error ""System.Net.Mail.SmtpException: Syntax error, command unrecognized. The server response was: connection rejected at....""

        try
        {
            var mail = new MailMessage();
            mail.From = new MailAddress("demo77377@gmail.com");
            mail.To.Add(new MailAddress("xxxxxxx@gmail.com"));
            mail.Subject = "TEST";
            mail.Body = "This is a test mail from C# program";

            using (var smtp = new SmtpClient())
            {
                smtp.Credentials = new System.Net.NetworkCredential("demo77377@gmail.com", "AABBCCDDEE1!","gmail.com");
                smtp.Host = "smtp.gmail.com";
                smtp.Port = 587;
                smtp.EnableSsl = true;
                smtp.UseDefaultCredentials = false;
                smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
                smtp.Timeout = 10000;
                //
                smtp.Send(mail);
                Console.WriteLine("Message sent successfully");
                Console.ReadLine();
            }

        }
        catch (Exception e)

I have done everything possible

On Client> I have alternated smtp properties (permutation) etc

On Server> I have made gmail account less secure, I have disabled captcha etc

I observed that similar issues on stackoverflow were mostly dated over 3years ago and thus, is it possible that gmail no longer supports this SMTP method via C#, likewise has it been deprecated in favor of gmail API

Also, please find provided in code, original password supplied for the gmail account, in order to confirm if this issue is general or isolated to this gmail account

Thanks


问:
Laravel Auto-Link library
I'm looking for a travel auto-link detection.

I'm trying to make a social media website and when my users post URLs I need it so like shows instead of just normal text.

答: Try Autologin for Laravel by dwightwatson, which provides you to generate URLs that will provide automatic login to your application and then redirect to the appropriate location

Title: Laravel Auto-Link library


问:
Split vector intro more vectors with constrains
Im working on a mealplan and I need some advice on how to split the Daily intake into several meals.

I have a vector where each element represents # of grams of different foods that a person should eat in order to meet his/her Daily intake of protein, carbs, fat, fiber..etc.

The vector looks as such:

```<code>intake <-  Salmon                 Chicken                   Pesto                  Butter
         162.573720               96.262731               48.415283                4.560707
            Yoghurt                Couscous              Boiled Egg                   Apple
         190.233090              518.741711              198.049714                0.000000
            Avocado                Broccoli              Grapefruit Quark / Kesella Natural
           0.000000              350.000000                0.000000              217.450103
            Oatmeal
          67.820707
</code>```

This has lenght 13.
I also have a matrix X with all the nutritional facts about each food type, it looks like this:

```<code>        Salmon Chicken   Pesto Butter Yoghurt Couscous Boiled Egg  Apple Avocado Broccoli Grapefruit
protein   0.18   0.231 0.12740  0.004  0.0342   0.0379     0.1225 0.0000  0.0194   0.0350      0.007
fat       0.12   0.010 0.53850  0.820  0.0300   0.0016     0.0973 0.0005  0.1960   0.0027      0.001
carbs     0.00   0.000 0.04080  0.005  0.0484   0.2182     0.0040 0.1058  0.0170   0.0312      0.070
fibre     0.00   0.000 0.00218  0.000  0.0000   0.0140     0.0000 0.0232  0.0475   0.0310      0.019
Greens    0.00   0.000 0.00000  0.000  0.0000   0.0000     0.0000 0.0000  1.0000   1.0000      0.000
        Quark / Kesella Natural Oatmeal
protein                   0.127   0.133
fat                       0.001   0.070
carbs                     0.036   0.576
fibre                     0.000   0.100
Greens                    0.000   0.000
</code>```

Lastly, I have (0/1)- vectors  that indicate if the food source is considered a "breakfast" or not. The same goes for "lunch", "dinner" and "snack".

I want to split the vector "intake" into meals that one eats throughout the day. My first idea was to simply take the dot product of intake*breakfast to get all the Foods that are considered breakfast and just eat them. This method does not give very reasonable answers since It may give way to much food to eat for breakfast and almost nothing left for the rest of the meals.

So lets say someone eats 5 meals a day;

I want to split the intake vector into 5 separate vectors, with the Foods that are considered breakfast to go in the new breakfast-vector.
Also, I want to be able to adjust how much of every food that goes in each vector: such as

Default (Breakfast 50% Protein or lower, 10% Fat or higher, 40% Carbohydrates or lower, Evening Snack 70% Protein or lower, 25% Fat or higher, 5% Carbohydrates or lower).

So that I can adjust so that one eats a lot of protein for breakfast and a lot of carbs Before they work out.

答:
When you say 50% protein, I'm not sure how you want us to quantify. How do you weight nutritional protein values against non protein foods? 50% or less protein means how much chicken relative to broccoli? I don't know much about nutrition.

Also, I had to retype up all your data so here this is for people who try to tackle this/when I come back after some clarification. Use dput() on your datasets and copy and paste the output in an edit to make your work easier for us to use.

```<code>Foods <- c("Salmon", "Chicken","Pesto","Butter","Yoghurt","Couscous","Boiled Egg","Apple","Avocado","Broccoli","Grapefruit","Quark / Kesella Natural","Oatmeal")

intake <- c(162.573720, 96.262731, 48.415283, 4.560707, 190.233090, 518.741711, 198.049714, 0.00000, 0.0000, 350.00000, 0.00000, 217.450103, 67.820707)
names(intake) <- Foods
intake

nutrition <- data.frame(protein = c(0.18, 0.231, 0.12740, 0.004, 0.0342, 0.0379, 0.1225, 0.0000, 0.0194, 0.0350, 0.007, 0.127, 0.133), fat = c(0.12, 0.010, 0.53850, 0.820, 0.0300, 0.0016, 0.0973, 0.0005, 0.1960, 0.0027, 0.001, 0.001, 0.070), carbs = c(0.00,0.000, 0.04080, 0.005, 0.0484, 0.2182, 0.0040, 0.1058, 0.0170, 0.0312, 0.070, 0.036, 0.576), fibre = c(0, 0, 0.0218, 0, 0, 0.0140, 0, 0.0232, 0.0475, 0.0310, 0.019, 0.0, 0.1), greens = c(0,0,0,0,0,0,0,0,1,1,0,0,0), row.names = Foods)
nutrition

# constraints
#Breakfast
#protein*.5 # maximum
#fat*.1 # minimum
#carbs*.4 # maximum

#Evening Snack
#protein*.7 # maximum
#fat*.25 # minimum
#carbs*.5 #maximum

Breakfast <- c(0,1,0,0,1,0,1,1,1,0,1,1,1)
Lunch <- c(1,1,1,1,0,1,0,0,0,1,1,1,1)
Dinner <- c(1,1,0,0,0,1,0,0,1,0,0,1,0)
meals <- cbind(Breakfast, Lunch, Dinner)

# even split amongst meals
apply(meals, 2, function(x)
  intake[which(x == 1)] / rowSums(split(cbind(intake, nutrition, meals), x)$`1`[,colnames(meals)]))
</code>```

Now the hard part you say is how to do a non-even split based on nutrition/meal food relative portions.
Whats the grams to serving ratio so we know how much protein the person gets? Seems like we need that to make intake work with the nutrition information.

Body:
Im working on a mealplan and I need some advice on how to split the Daily intake into several meals.

I have a vector where each element represents # of grams of different foods that a person should eat in order to meet his/her Daily intake of protein, carbs, fat, fiber..etc.

The vector looks as such:

intake <-  Salmon                 Chicken                   Pesto                  Butter
         162.573720               96.262731               48.415283                4.560707
            Yoghurt                Couscous              Boiled Egg                   Apple
         190.233090              518.741711              198.049714                0.000000
            Avocado                Broccoli              Grapefruit Quark / Kesella Natural
           0.000000              350.000000                0.000000              217.450103
            Oatmeal
          67.820707

This has lenght 13.
I also have a matrix X with all the nutritional facts about each food type, it looks like this:

        Salmon Chicken   Pesto Butter Yoghurt Couscous Boiled Egg  Apple Avocado Broccoli Grapefruit
protein   0.18   0.231 0.12740  0.004  0.0342   0.0379     0.1225 0.0000  0.0194   0.0350      0.007
fat       0.12   0.010 0.53850  0.820  0.0300   0.0016     0.0973 0.0005  0.1960   0.0027      0.001
carbs     0.00   0.000 0.04080  0.005  0.0484   0.2182     0.0040 0.1058  0.0170   0.0312      0.070
fibre     0.00   0.000 0.00218  0.000  0.0000   0.0140     0.0000 0.0232  0.0475   0.0310      0.019
Greens    0.00   0.000 0.00000  0.000  0.0000   0.0000     0.0000 0.0000  1.0000   1.0000      0.000
        Quark / Kesella Natural Oatmeal
protein                   0.127   0.133
fat                       0.001   0.070
carbs                     0.036   0.576
fibre                     0.000   0.100
Greens                    0.000   0.000

Lastly, I have (0/1)- vectors  that indicate if the food source is considered a "breakfast" or not. The same goes for "lunch", "dinner" and "snack".

I want to split the vector "intake" into meals that one eats throughout the day. My first idea was to simply take the dot product of intake*breakfast to get all the Foods that are considered breakfast and just eat them. This method does not give very reasonable answers since It may give way to much food to eat for breakfast and almost nothing left for the rest of the meals.

So lets say someone eats 5 meals a day;

I want to split the intake vector into 5 separate vectors, with the Foods that are considered breakfast to go in the new breakfast-vector.
Also, I want to be able to adjust how much of every food that goes in each vector: such as

Default (Breakfast 50% Protein or lower, 10% Fat or higher, 40% Carbohydrates or lower, Evening Snack 70% Protein or lower, 25% Fat or higher, 5% Carbohydrates or lower).

So that I can adjust so that one eats a lot of protein for breakfast and a lot of carbs Before they work out.

Body:
When you say 50% protein, I'm not sure how you want us to quantify. How do you weight nutritional protein values against non protein foods? 50% or less protein means how much chicken relative to broccoli? I don't know much about nutrition.

Also, I had to retype up all your data so here this is for people who try to tackle this/when I come back after some clarification. Use dput() on your datasets and copy and paste the output in an edit to make your work easier for us to use.

Foods <- c("Salmon", "Chicken","Pesto","Butter","Yoghurt","Couscous","Boiled Egg","Apple","Avocado","Broccoli","Grapefruit","Quark / Kesella Natural","Oatmeal")

intake <- c(162.573720, 96.262731, 48.415283, 4.560707, 190.233090, 518.741711, 198.049714, 0.00000, 0.0000, 350.00000, 0.00000, 217.450103, 67.820707)
names(intake) <- Foods
intake

nutrition <- data.frame(protein = c(0.18, 0.231, 0.12740, 0.004, 0.0342, 0.0379, 0.1225, 0.0000, 0.0194, 0.0350, 0.007, 0.127, 0.133), fat = c(0.12, 0.010, 0.53850, 0.820, 0.0300, 0.0016, 0.0973, 0.0005, 0.1960, 0.0027, 0.001, 0.001, 0.070), carbs = c(0.00,0.000, 0.04080, 0.005, 0.0484, 0.2182, 0.0040, 0.1058, 0.0170, 0.0312, 0.070, 0.036, 0.576), fibre = c(0, 0, 0.0218, 0, 0, 0.0140, 0, 0.0232, 0.0475, 0.0310, 0.019, 0.0, 0.1), greens = c(0,0,0,0,0,0,0,0,1,1,0,0,0), row.names = Foods)
nutrition

# constraints
#Breakfast
#protein*.5 # maximum
#fat*.1 # minimum
#carbs*.4 # maximum

#Evening Snack
#protein*.7 # maximum
#fat*.25 # minimum
#carbs*.5 #maximum

Breakfast <- c(0,1,0,0,1,0,1,1,1,0,1,1,1)
Lunch <- c(1,1,1,1,0,1,0,0,0,1,1,1,1)
Dinner <- c(1,1,0,0,0,1,0,0,1,0,0,1,0)
meals <- cbind(Breakfast, Lunch, Dinner)

# even split amongst meals
apply(meals, 2, function(x)
  intake[which(x == 1)] / rowSums(split(cbind(intake, nutrition, meals), x)$`1`[,colnames(meals)]))

Now the hard part you say is how to do a non-even split based on nutrition/meal food relative portions.
Whats the grams to serving ratio so we know how much protein the person gets? Seems like we need that to make intake work with the nutrition information.


问:
Simple breadcrum logo in jsx of react binding
```<code>{breadcrumbs.map((obj,i) =>
    <p> {i} > 1 ? "<span className="seperator">|</span>" : <span className="bold">{obj}</span> </p>
)}
</code>```

I want to make breadcrumbs from an array but failed using above code. breadcrumbs is just an array ['books','javascript'] and my expected output will be

Books -> javascript and so on, it should be working if I have more than 2 item in the array.

答:
You can call a function to render the conditional components like

class App extends React.Component {
  conditionalRender(i, len) {
   if (i < len -1)
   return ->

  }
  render() {

    var breadcrumbs = ['books','javascript', 'something'];

    return (

{breadcrumbs.map((obj,i) =>
               {obj} {this.conditionalRender(i, breadcrumbs.length)}
          )}

    )
  }
 }
 ReactDOM.render(<App/>, document.getElementById('app'))```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div></code>```

Body:
{breadcrumbs.map((obj,i) =>

 {i} > 1 ? "|" : {obj}

)}

I want to make breadcrumbs from an array but failed using above code. breadcrumbs is just an array ['books','javascript'] and my expected output will be

Books -> javascript and so on, it should be working if I have more than 2 item in the array.

Body:
You can call a function to render the conditional components like

class App extends React.Component {
  conditionalRender(i, len) {
   if (i < len -1)
   return <span className="seperator">-></span>

  }
  render() {

    var breadcrumbs = ['books','javascript', 'something'];

    return (
         <div>{breadcrumbs.map((obj,i) =>
              <span><span className="bold"> {obj} </span>{this.conditionalRender(i, breadcrumbs.length)} </span>
          )}</div>
    )
  }
 }
 ReactDOM.render(<App/>, document.getElementById('app'))

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>


问:
Any Mysql guru who knows how to handle a custom group calculation scenario in 1 query?
I hope any sense can be made from my explanation. I was able to create the query, however my query only works for Items related to Containers, AND only if no more than one Items are related. I really hope anybody can be of any assistance!

Consider the following objects:

Container

Person

Item

I have one table where instances of all objects are stored. The table uses a self-referencing parent-child construction so it is db-technically possible to put a Container 'inside' a Person (just mentioning, this is not happening).

Object_Instances

objectid

parentid

typeid

typespecification (same as containerid, personid or itemid => one of three is filled)

containerid

personid

itemid

I have two tables which can be used to link persons/items to containers:

Container_Person

containerid

personid

amount

required (boolean)

Container_Item

containerid

itemid

amount

required (boolean)

(there are also a person/*item* table)

Now for an instance of a container I would like to calculate a number between 0 and 1 which is based on the related Container_Person and Container_Item specification in the following way:

if NO Container_Person/Container_Item are related to the Container => result = 1

if there are related records they should be taken into account in the following manner:

if the Container DOES NOT contain (has a child record of) ALL of the related persons/items which are required => result 0

otherwise:

result = average based on:

(# child records vs amount in Container_xxx relation)

if there are more than 1 person or item related to the container then the 'weight' for the (#records vs amount) value should be the ratio between the related Container_xxx.amount values for that Container.

Here is my current 'solution':

This query only works for one related item to a container. It doesn't take persons into account in any way... If more than one item are related to the container then the query returns multiple records.

So my actual question is: How can I group/sum(calculate to 0 - 1 decimal) the results of the following query based on the _Person / _Item related amount/required specification?

```<code>SELECT
    Container.name,
    Item.name,
    (ifnull(Sum(Object_Instance.amount),0) / Container_Item.amount) as value
FROM
    Container
    Inner Join Object_Instances as Containers
        ON Containers.typeid = 'container'
        AND Container.containerid = Containers.typespecification
    Left Outer Join Container_Item ON Container_Item.containerid = Container.containerid
    Left Outer Join Item ON Item.itemid = Container_Item.itemid
    Left Outer Join Object_Instance as ContainerItems
        ON Item.itemid = ContainerItems.typespecification
        AND ContainerItems.typeid = 'item'
        AND ContainerItems.parentid = Containers.objectid
WHERE Containers.objectid = 1
GROUP BY
    Container.name,
    Container_Item.amount,
    Item.name,
    Container.containerid
</code>```

答:
When doing complex joins and grouping I will often have to resort to this type of query:

Create grouped (or unique) list

In a new query take the grouped list and then join in a ungrouped list that provides additional details that are needed.

Body:
I hope any sense can be made from my explanation. I was able to create the query, however my query only works for Items related to Containers, AND only if no more than one Items are related. I really hope anybody can be of any assistance!

Consider the following objects:

Container

Person

Item

I have one table where instances of all objects are stored. The table uses a self-referencing parent-child construction so it is db-technically possible to put a Container 'inside' a Person (just mentioning, this is not happening).

Object_Instances

objectid

parentid

typeid

typespecification (same as containerid, personid or itemid => one of three is filled)

containerid

personid

itemid

I have two tables which can be used to link persons/items to containers:

Container_Person

containerid

personid

amount

required (boolean)

Container_Item

containerid

itemid

amount

required (boolean)

(there are also a person/*item* table)

Now for an instance of a container I would like to calculate a number between 0 and 1 which is based on the related Container_Person and Container_Item specification in the following way:

if NO Container_Person/Container_Item are related to the Container => result = 1

if there are related records they should be taken into account in the following manner:

if the Container DOES NOT contain (has a child record of) ALL of the related persons/items which are required => result 0

otherwise:

result = average based on:

(# child records vs amount in Container_xxx relation)

if there are more than 1 person or item related to the container then the 'weight' for the (#records vs amount) value should be the ratio between the related Container_xxx.amount values for that Container.

Here is my current 'solution':

This query only works for one related item to a container. It doesn't take persons into account in any way... If more than one item are related to the container then the query returns multiple records.

So my actual question is: How can I group/sum(calculate to 0 - 1 decimal) the results of the following query based on the _Person / _Item related amount/required specification?

SELECT
    Container.name,
    Item.name,
    (ifnull(Sum(Object_Instance.amount),0) / Container_Item.amount) as value
FROM
    Container
    Inner Join Object_Instances as Containers
        ON Containers.typeid = 'container'
        AND Container.containerid = Containers.typespecification
    Left Outer Join Container_Item ON Container_Item.containerid = Container.containerid
    Left Outer Join Item ON Item.itemid = Container_Item.itemid
    Left Outer Join Object_Instance as ContainerItems
        ON Item.itemid = ContainerItems.typespecification
        AND ContainerItems.typeid = 'item'
        AND ContainerItems.parentid = Containers.objectid
WHERE Containers.objectid = 1
GROUP BY
    Container.name,
    Container_Item.amount,
    Item.name,
    Container.containerid


问:
Trying to use SASS in Nativescript Angular App
I have created a nativescript angular app using "tns create my-app --template ng" in the nativescript cli, then installed the android platform with "tns platform add android".  The application then runs perfectly on the android emulator using "tns run android".

To enable the use of SASS for styling, I followed the instructions here "https://docs.nativescript.org/ui/theme".  This includes installing the SASS plugin and creating the basic scss files in the app directory.  Now, when I try to run my app I get the following error:

"First call of getPlatformData without providing projectData."

I have repeated the process a number of times but the result remains the same. Any ideas?  (Using nativescript v2.5)

答:
This error is related to changes in the NativeScript CLI versions 2.5.x that break the SASS plugin with LiveSync. I've updated the plugin tonight so that it will work with both NativeScript 2.4.x and with the upcoming NativeScript 3.0.

In NativeScript 2.5, the plugin should transpile SCSS to CSS, but LiveSync will not work correctly.

So for now, either downgrade your CLI to 2.4.2 OR try-out the new RC release for 3.0.0-rc. With either of these CLI versions installed, the SASS plugin should work again (with LiveSync).

Try the latest version of the plugin in your project by doing this:

```<code>   $ tns plugin remove nativescript-dev-sass
   $ npm install nativescript-dev-sass@rc --save-dev
</code>```

Hopefully this works better. Sorry for the trouble.

(NOTE: The plugin will drop the RC tag once {N} 3.0.0 officially ships)

UPDATE

The changes to this plugin for {N} 2.5+ are now official and available simply by installing the latest version (no need for RC tag). If you're using {N} 2.4.2 or lower, it's still best to use the older version of this plugin. To install the older version:

```<code>$ npm install nativescript-dev-sass@0.4.2 --save-dev
</code>```

Body:
This error is related to changes in the NativeScript CLI versions 2.5.x that break the SASS plugin with LiveSync. I've updated the plugin tonight so that it will work with both NativeScript 2.4.x and with the upcoming NativeScript 3.0.

In NativeScript 2.5, the plugin should transpile SCSS to CSS, but LiveSync will not work correctly.

So for now, either downgrade your CLI to 2.4.2 OR try-out the new RC release for 3.0.0-rc. With either of these CLI versions installed, the SASS plugin should work again (with LiveSync).

Try the latest version of the plugin in your project by doing this:

   $ tns plugin remove nativescript-dev-sass
   $ npm install nativescript-dev-sass@rc --save-dev

Hopefully this works better. Sorry for the trouble.

(NOTE: The plugin will drop the RC tag once {N} 3.0.0 officially ships)

UPDATE

The changes to this plugin for {N} 2.5+ are now official and available simply by installing the latest version (no need for RC tag). If you're using {N} 2.4.2 or lower, it's still best to use the older version of this plugin. To install the older version:

$ npm install nativescript-dev-sass@0.4.2 --save-dev


问:
Pure Data chord selection based on input MIDI note scale causes crash
I'm working on a patch in Pure Data which uses an 8 number scale to decide which chords can be played. E.g. if a chord uses a note that is not in the scale, re-roll. Obviously this isn't the most musical soultion as we usually expect accidentals and such, but here we are looking at a primitive method for procedural music. Here is the problem patch:

CreateChords patch

As soon as I attempt to use a new scale, pure data freezes and requires an immediate restart.

Any suggestions would be greatly appreciated.

Thanks,

Liam

答: Ah, yea, I suspected a stack overflow as the cause of the crash. It's easy to make that mistake with so many wires so close together, as it's hard to see what all has been connected or mis-connected. Accomplishing this idea using only vanilla objects is quite a bit more challenging, now that you mention it. Here's something that could possibly work.


问:
module getters not updating in vue component
I'an not using getters.js file seperately, instead getters are written in js->assets->store->modules->user.js file

This is my user.js

```<code>const state = {
    count : '',
    list:[]
};

const mutations = {
    COUNT: (state, data) => {
        state.count = data
    },
    LIST : (state, data) => {
        state.list = data
    }
};

const getters = {
  userCount:(state) => state.list.length
};

const actions = {
    getList: ({commit,state}) => {
        axios.get('/api/user/list')
        .then((response) => {
            commit('LIST', response.data);
        })
    }
};

export default {
  namespaced: true,
  state,
  getters,
  actions,
  mutations
}
</code>```

This is my user vue component-user.vue

```<code><template>
    <div class="col-lg-3 col-xs-6">
        <div class="small-box bg-yellow">
            <div class="inner">
                    <h3>{{ usercount }}</h3>
                    <p>User Registrations</p>
            </div>
            <div class="icon">
                <i class="ion ion-person-add"></i>
            </div>
            <a href="#" class="small-box-footer">View <i class="fa fa-arrow-circle-right"></i></a>
        </div>
    </div>
</template>
<script>
export default{
    computed: {
        usercount() {
          return this.$store.getters['user/userCount'];
        }
    },
    mounted(){
        this.$store.dispatch('user/getList');
    }
}
</script>
</code>```

In user.js,
    alert(state.list.length)
 gives the correct count in the alert box.

But in user.vue,
    alert(this.$store.getters['user/userCount'])
gives 'undefined'

答:
In the Api controller, I'am using paginate() instead of get().vue dev tools helped me to find out this...

```<code>getList: ({commit,state}) => {
    axios.get('/api/user/list')
    .then((response) => {
        commit('LIST', response.data);
    })
}
</code>```

changed response.data to response.data.data

Body:
I'an not using getters.js file seperately, instead getters are written in js->assets->store->modules->user.js file

This is my user.js

const state = {
    count : '',
    list:[]
};

const mutations = {
    COUNT: (state, data) => {
        state.count = data
    },
    LIST : (state, data) => {
        state.list = data
    }
};

const getters = {
  userCount:(state) => state.list.length
};

const actions = {
    getList: ({commit,state}) => {
        axios.get('/api/user/list')
        .then((response) => {
            commit('LIST', response.data);
        })
    }
};

export default {
  namespaced: true,
  state,
  getters,
  actions,
  mutations
}

This is my user vue component-user.vue

<template>

{{ usercount }}

User Registrations

            View

</template>

In user.js,
    alert(state.list.length)
 gives the correct count in the alert box.

But in user.vue,
    alert(this.$store.getters['user/userCount'])
gives 'undefined'

Body:
In the Api controller, I'am using paginate() instead of get().vue dev tools helped me to find out this...

getList: ({commit,state}) => {
    axios.get('/api/user/list')
    .then((response) => {
        commit('LIST', response.data);
    })
}

changed response.data to response.data.data


问:
SQL Server Agent Job cannot access datafile
I have a an SSIS solution that runs fine in BIDS.  However, once I try to deploy it to the server and execute through SQL Server Agent, it fails with:

```<code>Cannot access datafile...
</code>```

Details:

server:  localhost that I built
sysadmin:  my local domain account is the sysadmin using Windows Authentication
filepath:  my local C:\Users\me\Downloads

I have tried mapping my login to a credential and using that credential as a proxy, but it still fails.

Can someone help with a step-by-step solution as to how to make sure the SQL Server Agent account has access to write and read files on my local file directory?

答:
look that：

What is the service account for SQL Server Agent? Is has privilege to access operation sytem?

Body:
I have a an SSIS solution that runs fine in BIDS.  However, once I try to deploy it to the server and execute through SQL Server Agent, it fails with:

Cannot access datafile...

Details:

server:  localhost that I built
sysadmin:  my local domain account is the sysadmin using Windows Authentication
filepath:  my local C:\Users\me\Downloads

I have tried mapping my login to a credential and using that credential as a proxy, but it still fails.

Can someone help with a step-by-step solution as to how to make sure the SQL Server Agent account has access to write and read files on my local file directory?