问:
WordPress, minify static text from a function
I have a php function in my function.php file like this:

```<code>function sample() {
    echo '$('#some-button').magnificPopup({
              items: {
                  src: 'path-to-image-1.jpg'
              },
          type: 'image'
         });';
}
add_action('wp_footer', 'sample');
</code>```

When the string is printed in the HTML code is exactly the same (rightly). Can I, just for this portion of code, minimize by eliminating all spaces and word wrap?

The result I want is this:

```<code>$('#some-button').magnificPopup({items:{src:'path-to-image-1.jpg'},type:'image'});
</code>```

答:
Sure you can. Just replace all space/newlines with nothing and you are good to go. Keep in mind(!) tho, that that following code replaces ALL speak unwanted and needed ones. But for your given input it works fine.</p>

```<code>$str = "$('#some-button').magnificPopup({
              items: {
                  src: 'path-to-image-1.jpg'
              },
          type: 'image'
         });";

print preg_replace('~\s~m', '', $str); // prints $('#some-button').magnificPopup({items:{src:'path-to-image-1.jpg'},type:'image'});
</code>```

Body:
I have a php function in my function.php file like this:

function sample() {
    echo '$('#some-button').magnificPopup({
              items: {
                  src: 'path-to-image-1.jpg'
              },
          type: 'image'
         });';
}
add_action('wp_footer', 'sample');

When the string is printed in the HTML code is exactly the same (rightly). Can I, just for this portion of code, minimize by eliminating all spaces and word wrap?

The result I want is this:

$('#some-button').magnificPopup({items:{src:'path-to-image-1.jpg'},type:'image'});

Body:
Sure you can. Just replace all space/newlines with nothing and you are good to go. Keep in mind(!) tho, that that following code replaces ALL speak unwanted and needed ones. But for your given input it works fine.

$str = "$('#some-button').magnificPopup({
              items: {
                  src: 'path-to-image-1.jpg'
              },
          type: 'image'
         });";

print preg_replace('~\s~m', '', $str); // prints $('#some-button').magnificPopup({items:{src:'path-to-image-1.jpg'},type:'image'});


来源: stackexchange

问:
Javascript Alert Window Redirects to Another Webpage
```<code>    <?php

session_start();

include_once "connect.php";

$fullName = $_POST['fullname'];
$userName = $_POST['username'];
$emailAdd = $_POST['email'];
$passWord = $_POST['password'];
$query =  mysql_query("SELECT * FROM users where USERNAME = '$username' ");
$result = mysql_fetch_array($query);

  if($fullName == "")
  {

?>
    <script>
      alert("Full Name is required!");
      window.location.href = "registeruser.php";
    </script>
<?php
  }

    else
    {
      if ($userName == "")
      {
?>
        <script>
          alert("Invalid username!");
          window.location.href = "registeruser.php";
        </script>
 <?php
      }

        else
        {
          if($userName == $result['USERNAME'])
          {
?>
            <script>
              alert("Username already exists!");
              window.location.href = "registeruser.php";
            </script>
<?php
          }

            else
            {
              if ($emailAdd == $result['EMAIL'])
              {
?>
                <script>
                  alert("Email address is required!");
                  window.location.href = "registeruser.php";
                </script>
<?php
              }

                else
                {
                  if ($passWord == "")
                  {
?>
                    <script>
                      alert("Username is required!");
                      window.location.href = "registeruser.php";
                    </script>
 <?php
                  }

                    else
                    {
                      if($_POST['password']==$_POST['confirmpass'])
                      {
                        mysql_query("INSERT INTO users (FULLNAME, USERNAME, EMAIL, PASSWORD)
                        VALUES ('$fullName', '$userName', '$emailAdd', '$passWord')" );
                        mysql_close();
?>
                        <script>
                          alert("Registered Successfully!");
                          window.location.href = "index.php";
                        </script>
<?php
                      }

                        else
                        {
?>
                          <script>
                            alert("Password and Confirm Password do not match");
                            window.location.href = "registeruser.php";
                          </script>
<?php
                        }
                    }
                }
            }
        }
    }

?>
</code>```

It works fine. But the problem is: the alert window shows to another web page and NOT within the webpage It is okay but it looks awful to direct the user to another web page without having contents there. If you could help me please on how to fix this and make the javascript alert window display on the same web page only. Actually, I have tried some solutions like this..

```<code>if($fullName == "")
{
  echo '<script>';
  echo 'alert("Full Name is required!")';
  echo 'window.location.href = "registeruser.php"';
  echo '</script>';
}
</code>```

答:
You need, as others said, to move your logic to the end of HTML. Second, you would need to implement this logic at the page you are looking to load, not the one that redirects. It's a 2 step logic. E.g.:

You would need to implement window.location at your current script.

Then, right before  tag of the page you want the user to be redirected:

```<code><?php
if($fullName == "")
{
  echo '<script>';
  echo 'alert("Full Name is required!")';
  echo '</script>';
}
?>
</body>
</code>```

So, doing it, after the page loaded, it will alert correctly.

ContentLicense: CC BY-SA 3.0

Body:
    <?php

session_start();

include_once "connect.php";

$fullName = $_POST['fullname'];
$userName = $_POST['username'];
$emailAdd = $_POST['email'];
$passWord = $_POST['password'];
$query =  mysql_query("SELECT * FROM users where USERNAME = '$username' ");
$result = mysql_fetch_array($query);

  if($fullName == "")
  {

?>

<?php
  }

    else
    {
      if ($userName == "")
      {
?>

 <?php
      }

        else
        {
          if($userName == $result['USERNAME'])
          {
?>

<?php
          }

            else
            {
              if ($emailAdd == $result['EMAIL'])
              {
?>

<?php
              }

                else
                {
                  if ($passWord == "")
                  {
?>

 <?php
                  }

                    else
                    {
                      if($_POST['password']==$_POST['confirmpass'])
                      {
                        mysql_query("INSERT INTO users (FULLNAME, USERNAME, EMAIL, PASSWORD)
                        VALUES ('$fullName', '$userName', '$emailAdd', '$passWord')" );
                        mysql_close();
?>

<?php
                      }

                        else
                        {
?>

<?php
                        }
                    }
                }
            }
        }
    }

?>

It works fine. But the problem is: the alert window shows to another web page and NOT within the webpage It is okay but it looks awful to direct the user to another web page without having contents there. If you could help me please on how to fix this and make the javascript alert window display on the same web page only. Actually, I have tried some solutions like this..

if($fullName == "")
{
  echo '';
}

Body:
You need, as others said, to move your logic to the end of HTML. Second, you would need to implement this logic at the page you are looking to load, not the one that redirects. It's a 2 step logic. E.g.:

You would need to implement window.location at your current script.

Then, right before  tag of the page you want the user to be redirected:

<?php
if($fullName == "")
{
  echo '<script>';
  echo 'alert("Full Name is required!")';
  echo '</script>';
}
?>
</body>

So, doing it, after the page loaded, it will alert correctly.


问:
using jQuery to bind a deeply rooted child element of an iFrame
I am trying to bind a click event to a deeply rooted child element of an iFrame and am not having any luck.  I managed to target the iFrame via the .on('load') event and have that.  I then traversed the DOM of the iFrame in the variable I set and found what I was looking for 9 children deep.  What is the best way to be able to bind to this as using the .find method comes back with a length of 0 meaning it is not finding it.

Here is the inheritance:

```<code>iFrame(root)
aspnetForm(form)
s4-workspace(div)
s4-bodyContainer(div)
contentRow(div)
contentBox(div)
DeltaPlaceHolderMain(div)
DialogTable(table)
cells(3)
ct100_PlaceHolderMain_btnOK(input) <---button I want to bind to it's click event.
</code>```

So basically its got a form and a bunch of divs as parents and then a table and its directly inside one of the cells of the table(index position 3).

This is on SharePoint 2013 online and is the AttachFile modal dialog.  I am attempting to bind to the click event of the OK button so I can do stuff once they click the button instead of having to wait for the result of the file upload which can be lengthy depending on the file size and internet speed.  I want to pop up a loading screen once they hit the button so they aren't just sitting there wondering what is going on because nothing is displayed after its clicked.

Any help would be appreciated. Here is what I have tried with no luck:

```<code> SP.UI.ModalDialog.showModalDialog(options); //pops up the Attach File modal

 $('.ms-dlgFrame').on('load', function () { //waits for iFrame to load
      var iBody = $('.ms-dlgFrame').contents().find("body"); //returns the iFrame object correctly
      var iContent = iBody.find('#ct100_PlaceHolderMain_btnOK'); //does NOT find this--length is 0
      console.log(iBody);
      console.log(iContent);
  });
</code>```

UPDATE:
 Ok so I realized the button id is ctl like control not ct1...but it still doesnt work. I actually am grabbing the aspnetForm with iContent = iBody[0].children.perforM and am attempting to target the form's submit event which is what the OK button is...however I cant get that to work either with

```<code>iContent.submit(function() {
// do stuff
})
</code>```

It just doesn't work. I also can grab the submit button itself by doing iContent = iBody[0].children.aspnetForm.ctl00$PlaceHolderMain$btnOK

However once again attempting to attach to the submit or click event doesn't work.

I'm at a loss here...I have the form and am targeting the submit event because when I console log it it says "form id="aspnetForm" onsubmit="blah blah""
Why isn't this working no matter what I am doing even when I have the right DOM element??

UPDATE 2:

Cannot get this working...

I bind to the iframe and find the aspnetForm and then have tried attaching to the submit and  onsubmit event, the ctl00_PlaceHolderMain_btnOK click event, etc.  These work but once the item submits I get a "Permission denied" even though it is coming from the same SharePoint site and should have the same domain.  It appears the button click happens and then the file uploads and the event doesn't try and fire until AFTER the modal closes, which I assume is being denied because there is no modal there.  When I put the call inside the .bind event, it fires again but then the length of the iFrame is 0 at that point meaning its no longer there.  I've even put it outside the bind call in an interval once it checks to see that frame has been loaded by use of a hasLoaded variable I set to true once the bind even fires, but then I get permission denied once the OK button is pressed with the only child element iContent has at this point being "error": "permission denied"

I know there HAS to be a way to do this and it's very frustrating Microsoft would leave this crappy functionality with no way of attaching a loading screen or even activation their OWN loading modal.  I can either activate the modal once the attach file modal pops up or once it closes but not in relation to when the 'OK' button is clicked to actually upload the file.  I know I can wait for the result to come back but that defeats the purpose because at that point the file is already uploaded.  I need a way to display a loading page in between the OK button(id: ctl00_PlaceHolderMain_btnOK) and the result coming back(ie, it appears when the OK button gets clicked and disappears once the dialogresult from the modal returns).  Any suggestions?  Nothing I have tried has worked so far. Using jQuery---either I get a permission denied error or the iFrame length is 0---its almost like the element doesn't allow event handlers on it.

答:
Finally found the solution!

$('.ms-dlgFrame').on('load', function() {
    $(this).contents.find('#ctl00_PlaceHolderMain_btnOk').on('click', function() {
        alert('clicked!');
    });
});

Body:
I am trying to bind a click event to a deeply rooted child element of an iFrame and am not having any luck.  I managed to target the iFrame via the .on('load') event and have that.  I then traversed the DOM of the iFrame in the variable I set and found what I was looking for 9 children deep.  What is the best way to be able to bind to this as using the .find method comes back with a length of 0 meaning it is not finding it.

Here is the inheritance:

iFrame(root)
aspnetForm(form)
s4-workspace(div)
s4-bodyContainer(div)
contentRow(div)
contentBox(div)
DeltaPlaceHolderMain(div)
DialogTable(table)
cells(3)
ct100_PlaceHolderMain_btnOK(input) <---button I want to bind to it's click event.

So basically its got a form and a bunch of divs as parents and then a table and its directly inside one of the cells of the table(index position 3).

This is on SharePoint 2013 online and is the AttachFile modal dialog.  I am attempting to bind to the click event of the OK button so I can do stuff once they click the button instead of having to wait for the result of the file upload which can be lengthy depending on the file size and internet speed.  I want to pop up a loading screen once they hit the button so they aren't just sitting there wondering what is going on because nothing is displayed after its clicked.

Any help would be appreciated. Here is what I have tried with no luck:

 SP.UI.ModalDialog.showModalDialog(options); //pops up the Attach File modal

 $('.ms-dlgFrame').on('load', function () { //waits for iFrame to load
      var iBody = $('.ms-dlgFrame').contents().find("body"); //returns the iFrame object correctly
      var iContent = iBody.find('#ct100_PlaceHolderMain_btnOK'); //does NOT find this--length is 0
      console.log(iBody);
      console.log(iContent);
  });

UPDATE:
 Ok so I realized the button id is ctl like control not ct1...but it still doesnt work. I actually am grabbing the aspnetForm with iContent = iBody[0].children.perforM and am attempting to target the form's submit event which is what the OK button is...however I cant get that to work either with

iContent.submit(function() {
// do stuff
})

It just doesn't work. I also can grab the submit button itself by doing iContent = iBody[0].children.aspnetForm.ctl00$PlaceHolderMain$btnOK

However once again attempting to attach to the submit or click event doesn't work.

I'm at a loss here...I have the form and am targeting the submit event because when I console log it it says "form id="aspnetForm" onsubmit="blah blah""
Why isn't this working no matter what I am doing even when I have the right DOM element??

UPDATE 2:

Cannot get this working...

I bind to the iframe and find the aspnetForm and then have tried attaching to the submit and  onsubmit event, the ctl00_PlaceHolderMain_btnOK click event, etc.  These work but once the item submits I get a "Permission denied" even though it is coming from the same SharePoint site and should have the same domain.  It appears the button click happens and then the file uploads and the event doesn't try and fire until AFTER the modal closes, which I assume is being denied because there is no modal there.  When I put the call inside the .bind event, it fires again but then the length of the iFrame is 0 at that point meaning its no longer there.  I've even put it outside the bind call in an interval once it checks to see that frame has been loaded by use of a hasLoaded variable I set to true once the bind even fires, but then I get permission denied once the OK button is pressed with the only child element iContent has at this point being "error": "permission denied"

I know there HAS to be a way to do this and it's very frustrating Microsoft would leave this crappy functionality with no way of attaching a loading screen or even activation their OWN loading modal.  I can either activate the modal once the attach file modal pops up or once it closes but not in relation to when the 'OK' button is clicked to actually upload the file.  I know I can wait for the result to come back but that defeats the purpose because at that point the file is already uploaded.  I need a way to display a loading page in between the OK button(id: ctl00_PlaceHolderMain_btnOK) and the result coming back(ie, it appears when the OK button gets clicked and disappears once the dialogresult from the modal returns).  Any suggestions?  Nothing I have tried has worked so far. Using jQuery---either I get a permission denied error or the iFrame length is 0---its almost like the element doesn't allow event handlers on it.


问:
How can I create a string from a single character?
I have a single char value, and I need to cast/convert it to a std::string. How can I do this?

I know how to go the opposite way, to retrieve a char from a std::string object: you just need to index the string at the appropriate location. For example: str[0] will retrieve the first character in the string.

But how do I go the other way? I want something like:

```<code>char c = 34;
std::string s(c);
</code>```

…but this doesn't work (the string is always empty).

答:
You still can use the string constructor taking two iterators:

```<code>char c = 'x';
std::string(&c, &c + 1);
</code>```

Update:

Good question James and GMan. Just searched freely downloadable "The New C Standard" by Derek M. Jones for "pointer past" and my first hit was:

If the expression P points to an
element of an array object and the
expression Q points to the last
element of the same array object, the
pointer expression Q+1 compares
greater than P... even though Q+1 does
not point to an element of the array
object...

On segmented architectures
incrementing a pointer past the end of
a segment causes the address to wrap
segmented architecture around to the
beginning of that segment (usually
address zero). If an array is
allocated within such a segment,
either the implementation must ensure
that there is room after the array for
there to be a one past the end
address, or it uses some other
implementation technique to handle
this case (e.g., if the segment used
is part of a pointer’s representation,
a special one past the end segment
value might be assigned)...

The C relational operator model enables
pointers to objects to be treated in
the same way as indexes into array
objects. Relational comparisons
between indexes into two different
array objects (that are not both
subobjects of a larger object) rarely
have any meaning and the standard does
not define such support for pointers.
Some applications do need to make use
of information on the relative
locations of different objects in
storage. However, this usage was not
considered to be of sufficient general
utility for the Committee to specify a
model defining the behavior...

Most implementations perform no checks
prior to any operation on values
having pointer type. Most processors
use the same instructions for
performing relational comparisons
involving pointer types as they use
for arithmetic types. For processors
that use a segmented memory
architecture, a pointer value is often
represented using two components, a
segment number and an offset within
that segment. A consequence of this
representation is that there are many
benefits in allocating storage for
objects such that it fits within a
single segment (i.e., storage for an
object does not span a segment
boundary). One benefit is an
optimization involving the generated
machine code for some of the
relational operators, which only needs
to check the segment offset component.
This can lead to the situation where
p >= q is false but p > q is true,
when p and q point to different objects.

ContentLicense: CC BY-SA 4.0

Body:
I have a single char value, and I need to cast/convert it to a std::string. How can I do this?

I know how to go the opposite way, to retrieve a char from a std::string object: you just need to index the string at the appropriate location. For example: str[0] will retrieve the first character in the string.

But how do I go the other way? I want something like:

char c = 34;
std::string s(c);

…but this doesn't work (the string is always empty).

Body:
You still can use the string constructor taking two iterators:

char c = 'x';
std::string(&c, &c + 1);

Update:

Good question James and GMan. Just searched freely downloadable "The New C Standard" by Derek M. Jones for "pointer past" and my first hit was:

If the expression P points to an
element of an array object and the
expression Q points to the last
element of the same array object, the
pointer expression Q+1 compares
greater than P... even though Q+1 does
not point to an element of the array
object...

On segmented architectures
incrementing a pointer past the end of
a segment causes the address to wrap
segmented architecture around to the
beginning of that segment (usually
address zero). If an array is
allocated within such a segment,
either the implementation must ensure
that there is room after the array for
there to be a one past the end
address, or it uses some other
implementation technique to handle
this case (e.g., if the segment used
is part of a pointer’s representation,
a special one past the end segment
value might be assigned)...

The C relational operator model enables
pointers to objects to be treated in
the same way as indexes into array
objects. Relational comparisons
between indexes into two different
array objects (that are not both
subobjects of a larger object) rarely
have any meaning and the standard does
not define such support for pointers.
Some applications do need to make use
of information on the relative
locations of different objects in
storage. However, this usage was not
considered to be of sufficient general
utility for the Committee to specify a
model defining the behavior...

Most implementations perform no checks
prior to any operation on values
having pointer type. Most processors
use the same instructions for
performing relational comparisons
involving pointer types as they use
for arithmetic types. For processors
that use a segmented memory
architecture, a pointer value is often
represented using two components, a
segment number and an offset within
that segment. A consequence of this
representation is that there are many
benefits in allocating storage for
objects such that it fits within a
single segment (i.e., storage for an
object does not span a segment
boundary). One benefit is an
optimization involving the generated
machine code for some of the
relational operators, which only needs
to check the segment offset component.
This can lead to the situation where
p >= q is false but p > q is true,
when p and q point to different objects.

ContentLicense: CC BY-SA 2.5


问:
Wordpress Woocommerce - Change pay button url in my account
I need to edit the URL for the Pay button in My Account.

The button currently sends the user to /checkout/order-pay/28077/ I need this to remove the /order-pay/ as this page doesn't show the various custom fields that I added to the normal purchase path.

I've looked through the template files but can't find the correct one.

答:
It's set in the Checkout endpoints section under the dashboard menu WooCommerce Settings/Checkout/Checkout Options.  Scroll down the page to the Pay endpoint and you'll see the default value of order-pay

Alternative is to use this filter if you want to remove it completely.

```<code>add_filter( 'woocommerce_my_account_my_orders_actions', 'modify_woocommerce_my_account_my_orders_actions', 10, 2 );

function modify_woocommerce_my_account_my_orders_actions( $actions, $order ) {

    if( isset( $actions['pay']['url'] ) ) {
        $actions['pay']['url'] = str_ireplace( 'order-pay/', '', $actions['pay']['url'] );
    }

    return $actions;
}
</code>```

Body:
It's set in the Checkout endpoints section under the dashboard menu WooCommerce Settings/Checkout/Checkout Options.  Scroll down the page to the Pay endpoint and you'll see the default value of order-pay

Alternative is to use this filter if you want to remove it completely.

add_filter( 'woocommerce_my_account_my_orders_actions', 'modify_woocommerce_my_account_my_orders_actions', 10, 2 );

function modify_woocommerce_my_account_my_orders_actions( $actions, $order ) {

    if( isset( $actions['pay']['url'] ) ) {
        $actions['pay']['url'] = str_ireplace( 'order-pay/', '', $actions['pay']['url'] );
    }

    return $actions;
}


问:
Adding a Vue.js v-bind:style attribute to an element that is dynamically created after page load
First of all, to understand my problems and choices: I am translating an existing JS project into a Vue.js framework.

I am struggeling with a problem that is easy to solve in jQuery but is breaking my head in Vue.js

In my code I have to generate canvasses after the whole page is loaded and then add them to a canvas container div. I need to make a change to the CSS of all of these canvasses when I click a button. The canvasses are as of now added using document.createElement('canvas').

The Vue way would be to add a v-bind:style attribute to the canvas and change it by setting a variable in data() the vue JS code, something like this: <canvas v-bind:style="{width: customWidth}></canvas>" and <button v-on:click="customWidth++">+</button>.

What I understand so far is that if I add the v-bind:style attribute whilst generating a canvas in the following way: canvas.setAttribute('v-bind:style', '{width: customWidth}'), Vue.js will not be aware of it's existance, since it was generated after loading up the page.

I am looking for a suggestion on how to solve my problem.

So, just to illustrate, this:

```<code><div id="canvas-container"><div>
<button v-on:click="customWidth++">+</button>
<button v-on:click="customWidth--">-</button>
</code>```

should become this:

```<code><div id="canvas-container">
   <canvas v-bind:style="{width: customWidth}"></canvas>
   <canvas v-bind:style="{width: customWidth}"></canvas>
   <canvas v-bind:style="{width: customWidth}"></canvas>
   <canvas v-bind:style="{width: customWidth}"></canvas>
   <canvas v-bind:style="{width: customWidth}"></canvas>
<div>
<button v-on:click="customWidth++">+</button>
<button v-on:click="customWidth--">-</button>
</code>```

With this in the Vue JS code:

```<code>data(){
   return{
      customWidth: 100
   }
}
</code>```

And be responsive to the button

答:
vue'ify the whole thing and using a v-for to create the canvases would be ideal but if that is a problem, just use pure JS

```<code>document.querySelector('#canvas-container canvas')
</code>```

and add the style that way.

Body:
First of all, to understand my problems and choices: I am translating an existing JS project into a Vue.js framework.

I am struggeling with a problem that is easy to solve in jQuery but is breaking my head in Vue.js

In my code I have to generate canvasses after the whole page is loaded and then add them to a canvas container div. I need to make a change to the CSS of all of these canvasses when I click a button. The canvasses are as of now added using document.createElement('canvas').

The Vue way would be to add a v-bind:style attribute to the canvas and change it by setting a variable in data() the vue JS code, something like this: <canvas v-bind:style="{width: customWidth}></canvas>" and <button v-on:click="customWidth++">+</button>.

What I understand so far is that if I add the v-bind:style attribute whilst generating a canvas in the following way: canvas.setAttribute('v-bind:style', '{width: customWidth}'), Vue.js will not be aware of it's existance, since it was generated after loading up the page.

I am looking for a suggestion on how to solve my problem.

So, just to illustrate, this:

<button v-on:click="customWidth++">+</button>
<button v-on:click="customWidth--">-</button>

should become this:

   <canvas v-bind:style="{width: customWidth}"></canvas>
   <canvas v-bind:style="{width: customWidth}"></canvas>
   <canvas v-bind:style="{width: customWidth}"></canvas>
   <canvas v-bind:style="{width: customWidth}"></canvas>
   <canvas v-bind:style="{width: customWidth}"></canvas>

<button v-on:click="customWidth++">+</button>
<button v-on:click="customWidth--">-</button>

With this in the Vue JS code:

data(){
   return{
      customWidth: 100
   }
}

And be responsive to the button

Body:
vue'ify the whole thing and using a v-for to create the canvases would be ideal but if that is a problem, just use pure JS

document.querySelector('#canvas-container canvas')

and add the style that way.


问:
How can I do vectorization for this matlab "for loop"?
I have some matlab code as follow, constructing KNN similarity weight matrix.

```<code>[D,I] = pdist2(X, X, 'squaredeuclidean', 'Smallest', k+1);
D = D < threshold;
W = zeros(n, n);
for i=1:size(I,2)
    W(I(:,i), i) = D(:,i);
    W(i, I(:,i)) = D(:,i)';
end
</code>```

I want to vectorize the for loop. I have tried

```<code>W(I) = D;
</code>```

but failed to get the correct value.

I add test case here:

```<code>n = 5;

D = [
 1     1     1     1     1
 0     1     1     1     1
 0     0     0     0     0
];

I = [
 1     2     3     4     5
 5     4     5     2     3
 3     1     1     1     1
];
</code>```

答:
There are some undefined variables that makes it hard to check what it is doing, but this should do the same as your for loop:

```<code>D,I] = pdist2(X, X, 'squaredeuclidean', 'Smallest', k+1);
D = D < threshold;
W = zeros(n);

% set the diagonal values
W(sub2ind(size(X), I(1, :), I(1, :))) = D(1,:);
% set the other values
W(sub2ind(size(W), I(2, :), 1:size(I, 2))) = D(2, :);
W(sub2ind(size(W), 1:size(I, 2), I(2, :))) = D(2, :).';
</code>```

I splited the directions, it works now with your test case.

Body:
I have some matlab code as follow, constructing KNN similarity weight matrix.

[D,I] = pdist2(X, X, 'squaredeuclidean', 'Smallest', k+1);
D = D < threshold;
W = zeros(n, n);
for i=1:size(I,2)
    W(I(:,i), i) = D(:,i);
    W(i, I(:,i)) = D(:,i)';
end

I want to vectorize the for loop. I have tried

W(I) = D;

but failed to get the correct value.

I add test case here:

n = 5;

D = [
 1     1     1     1     1
 0     1     1     1     1
 0     0     0     0     0
];

I = [
 1     2     3     4     5
 5     4     5     2     3
 3     1     1     1     1
];

Body:
There are some undefined variables that makes it hard to check what it is doing, but this should do the same as your for loop:

D,I] = pdist2(X, X, 'squaredeuclidean', 'Smallest', k+1);
D = D < threshold;
W = zeros(n);

% set the diagonal values
W(sub2ind(size(X), I(1, :), I(1, :))) = D(1,:);
% set the other values
W(sub2ind(size(W), I(2, :), 1:size(I, 2))) = D(2, :);
W(sub2ind(size(W), 1:size(I, 2), I(2, :))) = D(2, :).';

I splited the directions, it works now with your test case.


问:
Vuelidate warning in Karma/Chai Testing
Not that big a deal, but it makes my testing a little ugly. I'm using Vuelidate to handle my data validating, and even though there's no errors in the console for the rendered component I'm testing, my Karma testing is full of these:

```<code>ERROR LOG: '[Vue warn]: Property or method "$v" is not defined on the
instance but referenced during render Make sure to declare reactive
data properties in the data option. (found in <Root>).'
</code>```

Everything still runs, I'd just like to clean up the error.

答:
Add this intro your test file:</p>

```<code>import Vuelidate from 'vuelidate'
Vue.use(Vuelidate)
</code>```

Title: Vuelidate warning in Karma/Chai Testing

Body:
Not that big a deal, but it makes my testing a little ugly. I'm using Vuelidate to handle my data validating, and even though there's no errors in the console for the rendered component I'm testing, my Karma testing is full of these:

ERROR LOG: '[Vue warn]: Property or method "$v" is not defined on the
instance but referenced during render Make sure to declare reactive
data properties in the data option. (found in <Root>).'

Everything still runs, I'd just like to clean up the error.

Body:
Add this intro your test file:

import Vuelidate from 'vuelidate'
Vue.use(Vuelidate)


问:
SharePoint Lists vs Database Tables performance

We are looking to store transactional data in SharePoint lists. The lists will easily grow to 100,000+ items.

How would the query performance be compared with queries on a database table with these columns?

Queries:
Select by Id
Select Where ColumnValue = X
Group By OrderId
Group By Date

The SP List will be 6 columns wide: Id, Date, OrderId (Lookup), Quanity, ItemName, Title

答:
I also agree with the guys above
However - a lot of the performance problems discussed in blogs are due to the fact that the SharePoint Object Model is not used correctly.

You can checkout my blog series about SharePoint List Performance at dynaTrace Blog.
This series looks into the SharePoint Object Model to highlight what is actually going on between the SharePoint Servers and the Content Database

OwnerDisplayName: Andreas Grabner


问:
C# XPath help - Expression not working
Here is an example XML doc that matches the one I am getting info from:

```<code><?xml version="1.0" standalone="yes"?>
<Products xmlns="http://tempuri.org/Products.xsd">
  <Movies>
    <Title>Title1</Title>
    <Language>English</Language>
  </Movies>
  <Movies>
    <Title>Title2</Title>
    <Language>English</Language>
  </Movies>
  <Movies>
    <Title>Title3</Title>
    <Language>French</Language>
  </Movies>
  <Books>
    <Title>BTitle1</Title>
    <Genre>Suspense</Genre>
  </Books>
  <Books>
    <Title>BTitle2</Title>
    <Genre>Suspense</Genre>
  </Books>
  <Books>
    <Title>BTitle3</Title>
    <Genre>SciFi</Genre>
  </Books>
  <Books>
    <Title>BTitle4</Title>
    <Genre>SciFi</Genre>
  </Books>
</Products>
</code>```

Here is my code to get all books with the genre of Suspense:

```<code>//Get state list using XPath
XPathDocument xDoc = new XPathDocument(xmlPath); //Path to my file
XPathNavigator xNav = xDoc.CreateNavigator();
string booksQuery = "Books[Genre = \"Suspense\"]";
XPathNodeIterator xIter = xNav.Select(booksQuery);

while (xIter.MoveNext())
{
    //do stuff with xIter.Current
}
</code>```

I have tried several queries including Products/Books[Genre = \"Suspense\"], Products/Books, ./Books, and Books. My xIter always has zero items.

I'm new to XPath, so I'm sure it's a really simple error, but maybe not. I know I can get a DataSet with the tables [Movies] and [Books] out of this XML file using myDataSet.ReadXml(myXmlPathString); so the XML file is not corrupt. If that helps any.

So, my question ... what am I doing wrong?

答:
```<code>XPathDocument xDoc = new XPathDocument(xmlPath); //Path to my file
XPathNavigator xNav = xDoc.CreateNavigator();
XmlNamespaceManager mngr = new XmlNamespaceManager(xNav.NameTable);
mngr.AddNamespace("p", "http://tempuri.org/Products.xsd");
string booksQuery = "//p:Books[p:Genre = \"Suspense\"]";
XPathNodeIterator xIter = xNav.Select(booksQuery,mngr);
</code>```

Title: C# XPath help - Expression not working

Body:
Here is an example XML doc that matches the one I am getting info from:

<?xml version="1.0" standalone="yes"?>
<Products xmlns="http://tempuri.org/Products.xsd">
  <Movies>
    <Title>Title1</Title>
    <Language>English</Language>
  </Movies>
  <Movies>
    <Title>Title2</Title>
    <Language>English</Language>
  </Movies>
  <Movies>
    <Title>Title3</Title>
    <Language>French</Language>
  </Movies>
  <Books>
    <Title>BTitle1</Title>
    <Genre>Suspense</Genre>
  </Books>
  <Books>
    <Title>BTitle2</Title>
    <Genre>Suspense</Genre>
  </Books>
  <Books>
    <Title>BTitle3</Title>
    <Genre>SciFi</Genre>
  </Books>
  <Books>
    <Title>BTitle4</Title>
    <Genre>SciFi</Genre>
  </Books>
</Products>

Here is my code to get all books with the genre of Suspense:

//Get state list using XPath
XPathDocument xDoc = new XPathDocument(xmlPath); //Path to my file
XPathNavigator xNav = xDoc.CreateNavigator();
string booksQuery = "Books[Genre = \"Suspense\"]";
XPathNodeIterator xIter = xNav.Select(booksQuery);

while (xIter.MoveNext())
{
    //do stuff with xIter.Current
}

I have tried several queries including Products/Books[Genre = \"Suspense\"], Products/Books, ./Books, and Books. My xIter always has zero items.

I'm new to XPath, so I'm sure it's a really simple error, but maybe not. I know I can get a DataSet with the tables [Movies] and [Books] out of this XML file using myDataSet.ReadXml(myXmlPathString); so the XML file is not corrupt. If that helps any.

So, my question ... what am I doing wrong?


问:
3D TABS with imrovments of width and height
I have a 3D Tab on my website which I got from codepen (codepen.io/vavik96/pen/QjPVRL).

I increased the width (800px)  and height (550px).

No matter how much I tried I couldn't set a right size to it.

It should be screen web page sized to meet my needs.

Somebody help me.

Here my work.

.perspective {
  -webkit-perspective: 76em;
  perspective: 76em;
  -webkit-perspective-origin: 50% 50px;
  perspective-origin: 50% 50px;
  width: 494px;
  margin: 0 auto;
  font-family: 'Roboto', sans-serif;
  font-weight: 100;
  color: #fff;
  text-align: center;
}

input { display: none; }

.tab {
  position: absolute;
  width: 80px;
  height: 70px;
  background: pink;
  right: 0;
  line-height: 70px;
  font-weight: 300;
}

.tab:nth-child(1) {
  top: -80px;
  left:84px;
  background: #06D6A0;
}

.tab:nth-child(2) {
  top: -80px;
  left: 174px;
  background: #1B9AAA;
}

.tab:nth-child(3) {
  top: -80px;
  left: 262px;
  background: #EF476F;
}

.tab:nth-child(4) {
  top: -80px;
  left: 352px;
  background: red;
}

.cube {
  position: relative;
  width: 300px;
  height: 200px;
  -webkit-transform-origin: 0 100px;
  -ms-transform-origin: 0 100px;
  transform-origin: 100px 100px;
  -webkit-transform-style: preserve-3d;
  transform-style: preserve-3d;
  -webkit-transition: -webkit-transform 0.5s ease-in;
  transition: transform 0.5s ease-in;
}

.tab-content {
  width: 800px;
  height: 550px;
  position: absolute;
}

.tab-content h1 {
  font-size: 25px;
  margin: 75px 0 10px;
  font-weight: 300;
}

.tab-content p { font-size: 12px; }

.tab-content:nth-child(1) {
  -webkit-transform: translateZ(100px);
  transform: translateZ(700px);
  background:  #06D6A0;
}

.tab-content:nth-child(2) {
  -webkit-transform: rotateX(-270deg) translateY(-100px);
  transform: rotateY(270deg) translateX(-100px);
  -webkit-transform-origin: top left;
  -ms-transform-origin: top left;
  transform-origin: top left;
  background: #EF476F;
}

.tab-content:nth-child(3) {
  -webkit-transform: rotateX(90deg) translateY(200px);
    transform: rotateY(90deg) translateX(100px);
  -webkit-transform-origin: bottom center;
  -ms-transform-origin: bottom center;
  transform-origin: bottom right;
  background: red;
}

.tab-content:nth-child(4) {
  -webkit-transform: translateZ(100px);
  transform: translateZ(-100px);
  background: #1B9AAA;
}

#tab-one:checked ~ .cube {
  -webkit-transform: rotateY(90deg);
  transform: rotateY(-90deg);
}

#tab-two:checked ~ .cube {
  -webkit-transform: rotateX(0deg);
  transform: rotateX(0deg);
}

#tab-three:checked ~ .cube {
  -webkit-transform: rotateX(-90deg);
  transform: rotateY(-180deg);
}

#tab-four:checked ~ .cube {
  -webkit-transform: rotateX(90deg);
  transform: rotateY(-270deg);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><br>
<br>
<br>
<br>
<br>
<div class="perspective">
  <label class="tab" for="tab-two">Tab 2</label>
  <label class="tab" for="tab-one">Tab 1</label>
  <label class="tab" for="tab-three">Tab 3</label>
  <label class="tab" for="tab-four">Tab 4</label>
  <input type="radio" name="tabs" id="tab-one">
  <input type="radio" name="tabs" id="tab-two">
  <input type="radio" name="tabs" id="tab-three">
  <input type="radio" name="tabs" id="tab-four">
  <div class="cube">
    <div class="tab-content">
      <h1>Tab 1</h1>
      <p>THIS IS AWESOME</p>
    </div>
    <div class="tab-content">
      <h1>Tab 2</h1>
      <p>THIS IS COOL</p>
    </div>
    <div class="tab-content">
      <h1>Tab 3</h1>
      <p>THIS IS SWEET</p>
    </div>
    <div class="tab-content">
      <h1>Tab 4</h1>
      <p>THIS IS Good JOB</p>
    </div>
  </div>
</div></code>```

答:
```<code>width: 100% !important;
</code>```

please add your code to your question next time you ask someone to help you.

Body:
I have a 3D Tab on my website which I got from codepen (codepen.io/vavik96/pen/QjPVRL).

I increased the width (800px)  and height (550px).

No matter how much I tried I couldn't set a right size to it.

It should be screen web page sized to meet my needs.

Somebody help me.

Here my work.

.perspective {
  -webkit-perspective: 76em;
  perspective: 76em;
  -webkit-perspective-origin: 50% 50px;
  perspective-origin: 50% 50px;
  width: 494px;
  margin: 0 auto;
  font-family: 'Roboto', sans-serif;
  font-weight: 100;
  color: #fff;
  text-align: center;
}

input { display: none; }

.tab {
  position: absolute;
  width: 80px;
  height: 70px;
  background: pink;
  right: 0;
  line-height: 70px;
  font-weight: 300;
}

.tab:nth-child(1) {
  top: -80px;
  left:84px;
  background: #06D6A0;
}

.tab:nth-child(2) {
  top: -80px;
  left: 174px;
  background: #1B9AAA;
}

.tab:nth-child(3) {
  top: -80px;
  left: 262px;
  background: #EF476F;
}

.tab:nth-child(4) {
  top: -80px;
  left: 352px;
  background: red;
}

.cube {
  position: relative;
  width: 300px;
  height: 200px;
  -webkit-transform-origin: 0 100px;
  -ms-transform-origin: 0 100px;
  transform-origin: 100px 100px;
  -webkit-transform-style: preserve-3d;
  transform-style: preserve-3d;
  -webkit-transition: -webkit-transform 0.5s ease-in;
  transition: transform 0.5s ease-in;
}

.tab-content {
  width: 800px;
  height: 550px;
  position: absolute;
}

.tab-content h1 {
  font-size: 25px;
  margin: 75px 0 10px;
  font-weight: 300;
}

.tab-content p { font-size: 12px; }

.tab-content:nth-child(1) {
  -webkit-transform: translateZ(100px);
  transform: translateZ(700px);
  background:  #06D6A0;
}

.tab-content:nth-child(2) {
  -webkit-transform: rotateX(-270deg) translateY(-100px);
  transform: rotateY(270deg) translateX(-100px);
  -webkit-transform-origin: top left;
  -ms-transform-origin: top left;
  transform-origin: top left;
  background: #EF476F;
}

.tab-content:nth-child(3) {
  -webkit-transform: rotateX(90deg) translateY(200px);
    transform: rotateY(90deg) translateX(100px);
  -webkit-transform-origin: bottom center;
  -ms-transform-origin: bottom center;
  transform-origin: bottom right;
  background: red;
}

.tab-content:nth-child(4) {
  -webkit-transform: translateZ(100px);
  transform: translateZ(-100px);
  background: #1B9AAA;
}

#tab-one:checked ~ .cube {
  -webkit-transform: rotateY(90deg);
  transform: rotateY(-90deg);
}

#tab-two:checked ~ .cube {
  -webkit-transform: rotateX(0deg);
  transform: rotateX(0deg);
}

#tab-three:checked ~ .cube {
  -webkit-transform: rotateX(-90deg);
  transform: rotateY(-180deg);
}

#tab-four:checked ~ .cube {
  -webkit-transform: rotateX(90deg);
  transform: rotateY(-270deg);
}

  Tab 2
  Tab 1
  Tab 3
  Tab 4
  <input type="radio" name="tabs" id="tab-one">
  <input type="radio" name="tabs" id="tab-two">
  <input type="radio" name="tabs" id="tab-three">
  <input type="radio" name="tabs" id="tab-four">

Tab 1

THIS IS AWESOME

Tab 2

THIS IS COOL

Tab 3

THIS IS SWEET

Tab 4

THIS IS Good JOB

Body:
width: 100% !important;

please add your code to your question next time you ask someone to help you.


问:
Remembering loop variables after loop has ended in python
```<code>def john():
    for i in range(5):
        if i == 3:
            break
    print(i)

john()
</code>```

The function above prints 3 when called upon, whis is this so? Are loop variables still remembered after the loop has ended / break'ed'?

答:
See For-loop variable scope

Previous proposals to make for-loop variables local to
  the loop have stumbled on the problem of existing code
  that relies on the loop variable keeping its value
  after exiting the loop, and it seems that this is
  regarded as a desirable feature.

If the sequence is empty, the variable does not get assigned to at all by the loop:

```<code>>>> for x in []:
        pass

>>> print(x)
Traceback (most recent call last):
  File "<pyshell#66>", line 1, in <module>
    print(x)
NameError: name 'x' is not defined
</code>```

Body:
def john():
    for i in range(5):
        if i == 3:
            break
    print(i)

john()

The function above prints 3 when called upon, whis is this so? Are loop variables still remembered after the loop has ended / break'ed'?

Body:
See For-loop variable scope

Previous proposals to make for-loop variables local to
  the loop have stumbled on the problem of existing code
  that relies on the loop variable keeping its value
  after exiting the loop, and it seems that this is
  regarded as a desirable feature.

If the sequence is empty, the variable does not get assigned to at all by the loop:

>>> for x in []:
        pass

>>> print(x)
Traceback (most recent call last):
  File "<pyshell#66>", line 1, in <module>
    print(x)
NameError: name 'x' is not defined


问:
R - tryCatch - use last iteration index to restart the for loop
I already read documentations and several other question about tryCatch(), however, I am not able to figure out the solution to my class of problem.

The task to solve is:
1)There is a for loop that goes from row 1 to nrow of the dataframe.
2)Execute some instruction
3)In the case of error that would stop the program, instead restart the loop cycle from the current iteration.

Example

```<code>for (i in 1:50000) {
...execute instructions...
}
</code>```

What I am looking for is a solution that in the case of error at the iteration 30250, it restart the loop such that

```<code>for (i in 30250:50000) {
...execute instructions...
}
</code>```

The practical example I am working on is the following:

```<code>library(RDSTK)
library(jsonlite)
DF <- (id = seq(1:400000), lat = rep(38.929840, 400000), long = rep( -77.062343, 400000)
for (i in 1 : nrow(DF) {
    location <- NULL
    bo <- 0
    while (bo != 10) {  #re-try the instruction max 10 times per row
        location <- NULL
        location <- try(location <-  #try to gather the data from internet
                coordinates2politics(DF$lat[i], DF$long[i]))
        if (class(location) == "try-error") {  #if not able to gather the data
            Sys.sleep(runif(1,2,7))  #wait a random time before query again
            print("reconntecting...")
            bo <- bo+1
            print(bo)
        } else    #if there is NO error
            break   #stop trying on this individual
    }
    location <- lapply(location, jsonlite::fromJSON)
    location <- data.frame(location[[1]]$politics)
    DF$start_country[i] <- location$name[1]
    DF$start_region[i] <- location$name[2]
    Sys.sleep(runif(1,2,7))  #sleep random seconds before starting the new row
}
</code>```

N.B.: the try() is part of the "...execute instruction..."

What I am looking for is a tryCatch that when a critical error that stops the program happen, it instead restart the for loop from the current index "i".

This program would allow me to automatically iterate over 400000 rows and restart where it interrupted in the case of errors. This means that the program would be able to work totally independently by human.

I hope my question is clear, thank you very much.

答:
This is better addressed using while rather than for:

```<code>i <- 1
while(i < 10000){
  tryCatch(doStuff()) -> doStuffResults
  if(class(doStuffResults) != "try-catch") i <- i + 1
{
</code>```

Beware though if some cases will always fail doStuff: the loop will never terminate!

If the program will produce a fatal error and need a human restart, then the first line i <- 1 may be replaced (as long as you don't use i elsewhere in your code) with

```<code>if(!exists("i")) i <- 1
</code>```

so that the value from the loop will persist and not be reset to one.

Body:
I already read documentations and several other question about tryCatch(), however, I am not able to figure out the solution to my class of problem.

The task to solve is:
1)There is a for loop that goes from row 1 to nrow of the dataframe.
2)Execute some instruction
3)In the case of error that would stop the program, instead restart the loop cycle from the current iteration.

Example

for (i in 1:50000) {
...execute instructions...
}

What I am looking for is a solution that in the case of error at the iteration 30250, it restart the loop such that

for (i in 30250:50000) {
...execute instructions...
}

The practical example I am working on is the following:

library(RDSTK)
library(jsonlite)
DF <- (id = seq(1:400000), lat = rep(38.929840, 400000), long = rep( -77.062343, 400000)
for (i in 1 : nrow(DF) {
    location <- NULL
    bo <- 0
    while (bo != 10) {  #re-try the instruction max 10 times per row
        location <- NULL
        location <- try(location <-  #try to gather the data from internet
                coordinates2politics(DF$lat[i], DF$long[i]))
        if (class(location) == "try-error") {  #if not able to gather the data
            Sys.sleep(runif(1,2,7))  #wait a random time before query again
            print("reconntecting...")
            bo <- bo+1
            print(bo)
        } else    #if there is NO error
            break   #stop trying on this individual
    }
    location <- lapply(location, jsonlite::fromJSON)
    location <- data.frame(location[[1]]$politics)
    DF$start_country[i] <- location$name[1]
    DF$start_region[i] <- location$name[2]
    Sys.sleep(runif(1,2,7))  #sleep random seconds before starting the new row
}

N.B.: the try() is part of the "...execute instruction..."

What I am looking for is a tryCatch that when a critical error that stops the program happen, it instead restart the for loop from the current index "i".

This program would allow me to automatically iterate over 400000 rows and restart where it interrupted in the case of errors. This means that the program would be able to work totally independently by human.

I hope my question is clear, thank you very much.

Body:
This is better addressed using while rather than for:

i <- 1
while(i < 10000){
  tryCatch(doStuff()) -> doStuffResults
  if(class(doStuffResults) != "try-catch") i <- i + 1
{

Beware though if some cases will always fail doStuff: the loop will never terminate!

If the program will produce a fatal error and need a human restart, then the first line i <- 1 may be replaced (as long as you don't use i elsewhere in your code) with

if(!exists("i")) i <- 1

so that the value from the loop will persist and not be reset to one.


问:
Draw custom arc views and detect user click for each arc
I am creating custom arc views, which is like rainbow views. I can draw arc views but I am unable to create separate click events for each view. How to set separate click events for each arc view?. Thanks in advance.

Here is the code:

ArcView.java

```<code>public class ArcView extends View implements View.OnTouchListener{

    Paint paint;

    int radius, x, y;
    int color;

    public ArcView(Context context) {
        super(context);
        init();
    }

    public ArcView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public ArcView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }

    public ArcView(Context context, int radius, int x, int y, int color) {
        super(context);

        this.radius = radius;
        this.x = x;
        this.y = y;
        this.color = color;
        init();
    }

    private void init(){
        paint = new Paint();
        paint.setColor(color);
        paint.setStrokeWidth(10);
        paint.setStyle(Paint.Style.STROKE);
        setOnTouchListener(this);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        paint.setStyle(Paint.Style.FILL);
        canvas.drawCircle(x, y, radius, paint);
    }

    @Override
    public boolean onTouch(View view, MotionEvent event) {
        return false;
    }
}
</code>```

MainActivity.java

```<code>public class MainActivity extends AppCompatActivity {
    RelativeLayout arcButton;

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

        arcButton = (RelativeLayout) findViewById(R.id.arcButton);
        arcButton1 = (RelativeLayout) findViewById(R.id.arcButton1);
        arcButton2 = (RelativeLayout) findViewById(R.id.arcButton2);

        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        int width=dm.widthPixels;
        int height=dm.heightPixels;

        int arcRadius1 = (int)(width/1.5);
        int arcRadius2 = arcRadius1+(int)(width/3.5);
        int arcRadius3 = arcRadius2+(int)(width/3.5);

        int xCoor = width / 2;
        int yCoor = height;

        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(width, height);

        arcButton.setLayoutParams(params);
        View arcView1=new ArcView(this, arcRadius3, xCoor, yCoor, Color.RED);
        View arcView2=new ArcView(this, arcRadius2, xCoor, yCoor, Color.BLACK);
        View arcView3=new ArcView(this, arcRadius1, xCoor, yCoor, Color.BLUE);
        arcButton.addView(arcView1);
        arcButton1.addView(arcView2);
        arcButton2.addView(arcView3);

    }
}
</code>```

Output:

How can I create seperate click event for each arc button?

答:
A bit of a workaround, but it works. Put this inside ArcView:

```<code>@Override
public boolean performClick() {
    return super.performClick();
}

@Override
public boolean onTouch(View view, MotionEvent event) {
    view.performClick();
    if (isPointInCircle((int) event.getX(), (int) event.getY())) {
        // do what you want to do and get rid of the next two lines
        String color = (((ArcView) view).color == Color.RED) ? "RED" : (((ArcView) view).color == Color.BLACK) ? "BLACK" : "BLUE";
        Toast.makeText(context, color, Toast.LENGTH_SHORT).show();
        return true;
    }
    return false;
}

private boolean isPointInCircle(int clickX, int clickY) {
    return (clickX - x) * (clickX - x) + (clickY - y) * (clickY - y) <= radius * radius;
}
</code>```

Note that for the Toast to work, you need to make context global, but most likely you will want to get rid of the Toast anyway.

Body:
I am creating custom arc views, which is like rainbow views. I can draw arc views but I am unable to create separate click events for each view. How to set separate click events for each arc view?. Thanks in advance.

Here is the code:

ArcView.java

public class ArcView extends View implements View.OnTouchListener{

    Paint paint;

    int radius, x, y;
    int color;

    public ArcView(Context context) {
        super(context);
        init();
    }

    public ArcView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public ArcView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }

    public ArcView(Context context, int radius, int x, int y, int color) {
        super(context);

        this.radius = radius;
        this.x = x;
        this.y = y;
        this.color = color;
        init();
    }

    private void init(){
        paint = new Paint();
        paint.setColor(color);
        paint.setStrokeWidth(10);
        paint.setStyle(Paint.Style.STROKE);
        setOnTouchListener(this);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        paint.setStyle(Paint.Style.FILL);
        canvas.drawCircle(x, y, radius, paint);
    }

    @Override
    public boolean onTouch(View view, MotionEvent event) {
        return false;
    }
}

MainActivity.java

public class MainActivity extends AppCompatActivity {
    RelativeLayout arcButton;

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

        arcButton = (RelativeLayout) findViewById(R.id.arcButton);
        arcButton1 = (RelativeLayout) findViewById(R.id.arcButton1);
        arcButton2 = (RelativeLayout) findViewById(R.id.arcButton2);

        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        int width=dm.widthPixels;
        int height=dm.heightPixels;

        int arcRadius1 = (int)(width/1.5);
        int arcRadius2 = arcRadius1+(int)(width/3.5);
        int arcRadius3 = arcRadius2+(int)(width/3.5);

        int xCoor = width / 2;
        int yCoor = height;

        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(width, height);

        arcButton.setLayoutParams(params);
        View arcView1=new ArcView(this, arcRadius3, xCoor, yCoor, Color.RED);
        View arcView2=new ArcView(this, arcRadius2, xCoor, yCoor, Color.BLACK);
        View arcView3=new ArcView(this, arcRadius1, xCoor, yCoor, Color.BLUE);
        arcButton.addView(arcView1);
        arcButton1.addView(arcView2);
        arcButton2.addView(arcView3);

    }
}

Output:

How can I create seperate click event for each arc button?

Body:
A bit of a workaround, but it works. Put this inside ArcView:

@Override
public boolean performClick() {
    return super.performClick();
}

@Override
public boolean onTouch(View view, MotionEvent event) {
    view.performClick();
    if (isPointInCircle((int) event.getX(), (int) event.getY())) {
        // do what you want to do and get rid of the next two lines
        String color = (((ArcView) view).color == Color.RED) ? "RED" : (((ArcView) view).color == Color.BLACK) ? "BLACK" : "BLUE";
        Toast.makeText(context, color, Toast.LENGTH_SHORT).show();
        return true;
    }
    return false;
}

private boolean isPointInCircle(int clickX, int clickY) {
    return (clickX - x) * (clickX - x) + (clickY - y) * (clickY - y) <= radius * radius;
}

Note that for the Toast to work, you need to make context global, but most likely you will want to get rid of the Toast anyway.


问:
search in a text field which contains json
My Application is in RoR and DB is in MYSQL. I have  a User Table. It contains a field name. Its type is text.
It contains the value like {"first_name"=> 'Allen', "last_name"=> 'PAul'} and some other information.

I am able to store the same in DB by using store: accessors: [], coder: JSON.

Now, I want to retrive all records whose first_name == 'Allen'. So how to achieve this in rails

答:
Problem is the actual textual representation that is used to represent the json...

Using

```<code>ActiveRecord::Base.connection.execute("SELECT * FROM users")
</code>```

you can see how the LIKE clause should be structured to find the actual textual representation in the database. Afterwards you can use

```<code>User.find_by_sql("SELECT * FROM users WHERE name LIKE ...")
</code>```

to do the actual query

Body:
Problem is the actual textual representation that is used to represent the json...

Using

ActiveRecord::Base.connection.execute("SELECT * FROM users")

you can see how the LIKE clause should be structured to find the actual textual representation in the database. Afterwards you can use

User.find_by_sql("SELECT * FROM users WHERE name LIKE ...")

to do the actual query


问:
Tensorflow: what are "input_mean" and "input_std" in label_image.py in tensorflow example
I am using Windows 7.
I have train a mobilenet using the official retraining example.

https://github.com/tensorflow/tensorflow/tree/master/tensorflow/examples/image_retraining

I have run command like this:

```<code>python ../tensorflow-master/tensorflow/examples/image_retraining/retrain.py --image_dir test/ --learning_rate=0.0001 --testing_percentage=20 --validation_percentage=20 --train_batch_size=32 --validation_batch_size=-1 --flip_left_right True --random_scale=30 --random_brightness=30 --eval_step_interval=100 --how_many_training_steps=2000 --architecture mobilenet_0.25_128
</code>```

And I get the trained graph and label files "output_graph.pb" and "output_labels.txt".

Now, I want to perform classification using the above generated graph, so I used the label_image.py provided in tensorflow github.

https://github.com/tensorflow/tensorflow/tree/master/tensorflow/examples/label_image

```<code>from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import argparse
import sys

import numpy as np
import tensorflow as tf

def load_graph(model_file):
  graph = tf.Graph()
  graph_def = tf.GraphDef()

  with open(model_file, "rb") as f:
    graph_def.ParseFromString(f.read())
  with graph.as_default():
    tf.import_graph_def(graph_def)

  return graph

def read_tensor_from_image_file(file_name, input_height=299, input_width=299,
                input_mean=0, input_std=255):
  input_name = "file_reader"
  output_name = "normalized"
  file_reader = tf.read_file(file_name, input_name)
  if file_name.endswith(".png"):
    image_reader = tf.image.decode_png(file_reader, channels = 3,
                                       name='png_reader')
  elif file_name.endswith(".gif"):
    image_reader = tf.squeeze(tf.image.decode_gif(file_reader,
                                                  name='gif_reader'))
  elif file_name.endswith(".bmp"):
    image_reader = tf.image.decode_bmp(file_reader, name='bmp_reader')
  else:
    image_reader = tf.image.decode_jpeg(file_reader, channels = 3,
                                        name='jpeg_reader')
  float_caster = tf.cast(image_reader, tf.float32)
  dims_expander = tf.expand_dims(float_caster, 0);
  resized = tf.image.resize_bilinear(dims_expander, [input_height, input_width])
  normalized = tf.divide(tf.subtract(resized, [input_mean]), [input_std])
  sess = tf.Session()
  result = sess.run(normalized)

  return result

def load_labels(label_file):
  label = []
  proto_as_ascii_lines = tf.gfile.GFile(label_file).readlines()
  for l in proto_as_ascii_lines:
    label.append(l.rstrip())
  return label

if __name__ == "__main__":
  file_name = "tensorflow/examples/label_image/data/grace_hopper.jpg"
  model_file = \
    "tensorflow/examples/label_image/data/inception_v3_2016_08_28_frozen.pb"
  label_file = "tensorflow/examples/label_image/data/imagenet_slim_labels.txt"
  input_height = 299
  input_width = 299
  input_mean = 0
  input_std = 255
  input_layer = "input"
  output_layer = "InceptionV3/Predictions/Reshape_1"

  parser = argparse.ArgumentParser()
  parser.add_argument("--image", help="image to be processed")
  parser.add_argument("--graph", help="graph/model to be executed")
  parser.add_argument("--labels", help="name of file containing labels")
  parser.add_argument("--input_height", type=int, help="input height")
  parser.add_argument("--input_width", type=int, help="input width")
  parser.add_argument("--input_mean", type=int, help="input mean")
  parser.add_argument("--input_std", type=int, help="input std")
  parser.add_argument("--input_layer", help="name of input layer")
  parser.add_argument("--output_layer", help="name of output layer")
  args = parser.parse_args()

  if args.graph:
    model_file = args.graph
  if args.image:
    file_name = args.image
  if args.labels:
    label_file = args.labels
  if args.input_height:
    input_height = args.input_height
  if args.input_width:
    input_width = args.input_width
  if args.input_mean:
    input_mean = args.input_mean
  if args.input_std:
    input_std = args.input_std
  if args.input_layer:
    input_layer = args.input_layer
  if args.output_layer:
    output_layer = args.output_layer

  graph = load_graph(model_file)
  t = read_tensor_from_image_file(file_name,
                                  input_height=input_height,
                                  input_width=input_width,
                                  input_mean=input_mean,
                                  input_std=input_std)

  input_name = "import/" + input_layer
  output_name = "import/" + output_layer
  input_operation = graph.get_operation_by_name(input_name);
  output_operation = graph.get_operation_by_name(output_name);

  with tf.Session(graph=graph) as sess:
    results = sess.run(output_operation.outputs[0],
                      {input_operation.outputs[0]: t})
  results = np.squeeze(results)

  top_k = results.argsort()[-5:][::-1]
  labels = load_labels(label_file)
  for i in top_k:
    print(labels[i], results[i])
</code>```

And I run the following command:

```<code>python ../tensorflow-master/tensorflow/examples/label_image/label_image.py --graph=output_graph.pb --labels=output_labels.txt --image=test.jpg --input_layer=input --output_layer=final_result --input_mean=128 --input_std=128 --input_width=128 --input_height=128
</code>```

And the image "test.jpg" can be classified.

However, when I use different values for "input_mean" and "input_std", the result changes.

What are "input_mean" and "input_std" used for? And how can I get correct values for these 2 parameters?

答:
These two variables, are used to normalize the dataset, as we observe improvement in the result of doing so.

The input_mean, is the mean per channel of the dataset, and the input_std is the standard deviation associated. As you control which dataset you pass in your Network, you should be able to calculate the mean and the std.

Normalization means 2 things:

Putting the data on the same scale (Scaling)

Balancing the data around a point (Centering (around 0 in our case))

As to why we do that, you could read about it in this Crossvalidated answer : https://stats.stackexchange.com/a/220970

"Subtracting the dataset mean serves to "center" the data.
  Additionally, you ideally would like to divide by the sttdev of that
  feature or pixel as well if you want to normalize each feature value
  to a z-score.

The reason we do both of those things is because in the process of
  training our network, we're going to be multiplying (weights) and
  adding to (biases) these initial inputs in order to cause activations
  that we then backpropogate with the gradients to train the model.

We'd like in this process for each feature to have a similar range so
  that our gradients don't go out of control (and that we only need one
  global learning rate multiplier). "

EDIT : giving an example
Imagine your image is a really simple image of 3 pixels :

```<code>img = [[[1,2,3],[4,5,6],[7,8,9]]]
</code>```

You can easily compute the mean per channel

```<code>mean = [4,5,6]
</code>```

And as easily the std per channel too:

```<code>std = [2.45,2.45,2.45]
</code>```

As tensorflow will do an element-wise subtraction, and then an element-wise division, you will normalize individually each channel of your image.

In the code, it seems that they add a dimensions to be compliant with the tf.image functions. As the first dimension is the batch one, you should prepend your arrays with a 0. ([0,4,5,6])

Body:
I am using Windows 7.
I have train a mobilenet using the official retraining example.

https://github.com/tensorflow/tensorflow/tree/master/tensorflow/examples/image_retraining

I have run command like this:

python ../tensorflow-master/tensorflow/examples/image_retraining/retrain.py --image_dir test/ --learning_rate=0.0001 --testing_percentage=20 --validation_percentage=20 --train_batch_size=32 --validation_batch_size=-1 --flip_left_right True --random_scale=30 --random_brightness=30 --eval_step_interval=100 --how_many_training_steps=2000 --architecture mobilenet_0.25_128

And I get the trained graph and label files "output_graph.pb" and "output_labels.txt".

Now, I want to perform classification using the above generated graph, so I used the label_image.py provided in tensorflow github.

https://github.com/tensorflow/tensorflow/tree/master/tensorflow/examples/label_image

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import argparse
import sys

import numpy as np
import tensorflow as tf

def load_graph(model_file):
  graph = tf.Graph()
  graph_def = tf.GraphDef()

  with open(model_file, "rb") as f:
    graph_def.ParseFromString(f.read())
  with graph.as_default():
    tf.import_graph_def(graph_def)

  return graph

def read_tensor_from_image_file(file_name, input_height=299, input_width=299,
                input_mean=0, input_std=255):
  input_name = "file_reader"
  output_name = "normalized"
  file_reader = tf.read_file(file_name, input_name)
  if file_name.endswith(".png"):
    image_reader = tf.image.decode_png(file_reader, channels = 3,
                                       name='png_reader')
  elif file_name.endswith(".gif"):
    image_reader = tf.squeeze(tf.image.decode_gif(file_reader,
                                                  name='gif_reader'))
  elif file_name.endswith(".bmp"):
    image_reader = tf.image.decode_bmp(file_reader, name='bmp_reader')
  else:
    image_reader = tf.image.decode_jpeg(file_reader, channels = 3,
                                        name='jpeg_reader')
  float_caster = tf.cast(image_reader, tf.float32)
  dims_expander = tf.expand_dims(float_caster, 0);
  resized = tf.image.resize_bilinear(dims_expander, [input_height, input_width])
  normalized = tf.divide(tf.subtract(resized, [input_mean]), [input_std])
  sess = tf.Session()
  result = sess.run(normalized)

  return result

def load_labels(label_file):
  label = []
  proto_as_ascii_lines = tf.gfile.GFile(label_file).readlines()
  for l in proto_as_ascii_lines:
    label.append(l.rstrip())
  return label

if __name__ == "__main__":
  file_name = "tensorflow/examples/label_image/data/grace_hopper.jpg"
  model_file = \
    "tensorflow/examples/label_image/data/inception_v3_2016_08_28_frozen.pb"
  label_file = "tensorflow/examples/label_image/data/imagenet_slim_labels.txt"
  input_height = 299
  input_width = 299
  input_mean = 0
  input_std = 255
  input_layer = "input"
  output_layer = "InceptionV3/Predictions/Reshape_1"

  parser = argparse.ArgumentParser()
  parser.add_argument("--image", help="image to be processed")
  parser.add_argument("--graph", help="graph/model to be executed")
  parser.add_argument("--labels", help="name of file containing labels")
  parser.add_argument("--input_height", type=int, help="input height")
  parser.add_argument("--input_width", type=int, help="input width")
  parser.add_argument("--input_mean", type=int, help="input mean")
  parser.add_argument("--input_std", type=int, help="input std")
  parser.add_argument("--input_layer", help="name of input layer")
  parser.add_argument("--output_layer", help="name of output layer")
  args = parser.parse_args()

  if args.graph:
    model_file = args.graph
  if args.image:
    file_name = args.image
  if args.labels:
    label_file = args.labels
  if args.input_height:
    input_height = args.input_height
  if args.input_width:
    input_width = args.input_width
  if args.input_mean:
    input_mean = args.input_mean
  if args.input_std:
    input_std = args.input_std
  if args.input_layer:
    input_layer = args.input_layer
  if args.output_layer:
    output_layer = args.output_layer

  graph = load_graph(model_file)
  t = read_tensor_from_image_file(file_name,
                                  input_height=input_height,
                                  input_width=input_width,
                                  input_mean=input_mean,
                                  input_std=input_std)

  input_name = "import/" + input_layer
  output_name = "import/" + output_layer
  input_operation = graph.get_operation_by_name(input_name);
  output_operation = graph.get_operation_by_name(output_name);

  with tf.Session(graph=graph) as sess:
    results = sess.run(output_operation.outputs[0],
                      {input_operation.outputs[0]: t})
  results = np.squeeze(results)

  top_k = results.argsort()[-5:][::-1]
  labels = load_labels(label_file)
  for i in top_k:
    print(labels[i], results[i])

And I run the following command:

python ../tensorflow-master/tensorflow/examples/label_image/label_image.py --graph=output_graph.pb --labels=output_labels.txt --image=test.jpg --input_layer=input --output_layer=final_result --input_mean=128 --input_std=128 --input_width=128 --input_height=128

And the image "test.jpg" can be classified.

However, when I use different values for "input_mean" and "input_std", the result changes.

What are "input_mean" and "input_std" used for? And how can I get correct values for these 2 parameters?

Body:
These two variables, are used to normalize the dataset, as we observe improvement in the result of doing so.

The input_mean, is the mean per channel of the dataset, and the input_std is the standard deviation associated. As you control which dataset you pass in your Network, you should be able to calculate the mean and the std.

Normalization means 2 things:

Putting the data on the same scale (Scaling)

Balancing the data around a point (Centering (around 0 in our case))

As to why we do that, you could read about it in this Crossvalidated answer : https://stats.stackexchange.com/a/220970

"Subtracting the dataset mean serves to "center" the data.
  Additionally, you ideally would like to divide by the sttdev of that
  feature or pixel as well if you want to normalize each feature value
  to a z-score.

The reason we do both of those things is because in the process of
  training our network, we're going to be multiplying (weights) and
  adding to (biases) these initial inputs in order to cause activations
  that we then backpropogate with the gradients to train the model.

We'd like in this process for each feature to have a similar range so
  that our gradients don't go out of control (and that we only need one
  global learning rate multiplier). "

EDIT : giving an example
Imagine your image is a really simple image of 3 pixels :

img = [[[1,2,3],[4,5,6],[7,8,9]]]

You can easily compute the mean per channel

mean = [4,5,6]

And as easily the std per channel too:

std = [2.45,2.45,2.45]

As tensorflow will do an element-wise subtraction, and then an element-wise division, you will normalize individually each channel of your image.

In the code, it seems that they add a dimensions to be compliant with the tf.image functions. As the first dimension is the batch one, you should prepend your arrays with a 0. ([0,4,5,6])


问:
make Content_tag to print two elements in same line(Rails)
```<code>content_tag(:p, "link : ") + content_tag(:p, link_to("abc","www.abc.com"))
</code>```

This prints

```<code>link:
abc
</code>```

But I want it to print

```<code>link: abc
</code>```

答:
Just use display: inline-block on the element. This is not a Rails issue but a CSS quirk. p is a block element, as in it takes the whole width of the parent unless its inline.

.two p { display: inline-block; }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="one"><p>Hello</p><p>World</p></div>
<div class="two"><p>Hello</p><p>World</p></div></code>```

Body:
content_tag(:p, "link : ") + content_tag(:p, link_to("abc","www.abc.com"))

This prints

link:
abc

But I want it to print

link: abc

Body:
Just use display: inline-block on the element. This is not a Rails issue but a CSS quirk. p is a block element, as in it takes the whole width of the parent unless its inline.

.two p { display: inline-block; }

<div class="one"><p>Hello</p><p>World</p></div>
<div class="two"><p>Hello</p><p>World</p></div>


问:
Saving data to .mat file in MATLAB
I'm new to MATLAB, and I can't manage to make my function work in order to save my data into a .mat file.

The input:

A structure, with 5 fields:

data: 3D matrix of 19x1000x143

labels: 1x143 matrix with 1 or -1 in it

subject_number: an integer

sampling_rate: an integer, 500 Hz

channel_names: 1x19 matrix with text in it

name: a string for the name of the file

clean: a matrix 1x143 with 1 or 0 in it.

The idea is to save only the clean data, marked as 1 in the clean matrix.

```<code> If clean(i) is equal to 1:
      save data(:,:,i) and labels(:,i)
</code>```

This is the code I've tried to implement in the saving.m file:

```<code>function saving(EEG_struct, clean, name)

subject_number = EEG_struct.subject_number;
fs = EEG_struct.sampling_rate;
chan_names = EEG_struct.channel_names;
nb_epoch = size(EEG_struct.data, 3);

for j=1:nb_epoch
    if clean(j) == 1
        % Keep the epoch and label
        data = cat(3, data, EEG_struct.data(:,:,j));
        labels = cat(2, labels, EEG_struct.labels(:,j));
    end
end

save(name, data, labels, subject_number, fs, chan_names)
</code>```

As you can see, I would like to save the data as a structure with the same shape as the EEG_struct input.
Moreover, I would like to use a parfor instead of a for, but it raised me an error I didn't quite get:

```<code>An UndefinedFunction error was thrown on the workers for 'data'.  This might be because the file containing 'data' is not accessible on the workers.  Use addAttachedFiles(pool, files) to specify the required files to be attached.  See the documentation for 'parallel.Pool/addAttachedFiles' for more details. Caused by: Undefined function or variable 'data'.
</code>```

Thanks for the help !

答:
You can use your clean variable as a logical index and parse out your data and labels at once.  So there is no need for a loop.

Also the save command needs the "names" of the vars to save not the variables themselves.  So I just put ' ' around each one.

```<code>function saving(EEG_struct, clean, name)

subject_number = EEG_struct.subject_number;
fs = EEG_struct.sampling_rate;
chan_names = EEG_struct.channel_names;
nb_epoch = size(EEG_struct.data, 3);

%No need for a loop at all
data  = EEG_struct.data(:,:,logical(clean));
labels = EEG_struct.labels(logical(clean));  %This is a 1xN so I removed the extra colon operator
save(name, 'data', 'labels', 'subject_number', 'fs', 'chan_names');
</code>```

EDIT:
Per you comment if you want to just leave everything in the structure.  I gave you 2 options for how to save it.

```<code>function saving(EEG_struct, clean, name)
%Crop out ~clead data
EEG_struct.data  = EEG_struct.data(:,:,logical(clean));
EEG_struct.labels = EEG_struct.labels(logical(clean));  %This is a 1xN so I removed the extra colon operator
% Option 1
save(name, 'EEG_struct');
% Option2
save(name, '-struct', 'EEG_struct');
</code>```

Option 1 will directly save the struct to the MAT file.  So if you were to load the data back like this:

```<code>test = load(name);

test =
        EEG_struct: [1x1 struct]
</code>```

You would get your structure placed inside another structure ... which might not be ideal or require an extra line to de-nest it.  On the other hand just loading the MAT file with no outputs  load(name)  would put EEG_struct  into your current workspace.  But if in a function then it sort of springs into existence without every being declared which makes code a bit harder to follow.

Option 2  uses the '-struct' option which breaks out each field automatically into separate vars in the MAT file.  So loading like this:

EEG_struct = load(name);

Will put all the fields back together again.  To me at least this looks cleaner when done within a function but is probably just my preference

So comment out which ever you prefer.  Also, not I did not include clean in the save.  You could either append it to the MAT or add it to your structure.

Title: Saving data to .mat file in MATLAB

Body:
I'm new to MATLAB, and I can't manage to make my function work in order to save my data into a .mat file.

The input:

A structure, with 5 fields:

data: 3D matrix of 19x1000x143

labels: 1x143 matrix with 1 or -1 in it

subject_number: an integer

sampling_rate: an integer, 500 Hz

channel_names: 1x19 matrix with text in it

name: a string for the name of the file

clean: a matrix 1x143 with 1 or 0 in it.

The idea is to save only the clean data, marked as 1 in the clean matrix.

 If clean(i) is equal to 1:
      save data(:,:,i) and labels(:,i)

This is the code I've tried to implement in the saving.m file:

function saving(EEG_struct, clean, name)

subject_number = EEG_struct.subject_number;
fs = EEG_struct.sampling_rate;
chan_names = EEG_struct.channel_names;
nb_epoch = size(EEG_struct.data, 3);

for j=1:nb_epoch
    if clean(j) == 1
        % Keep the epoch and label
        data = cat(3, data, EEG_struct.data(:,:,j));
        labels = cat(2, labels, EEG_struct.labels(:,j));
    end
end

save(name, data, labels, subject_number, fs, chan_names)

As you can see, I would like to save the data as a structure with the same shape as the EEG_struct input.
Moreover, I would like to use a parfor instead of a for, but it raised me an error I didn't quite get:

An UndefinedFunction error was thrown on the workers for 'data'.  This might be because the file containing 'data' is not accessible on the workers.  Use addAttachedFiles(pool, files) to specify the required files to be attached.  See the documentation for 'parallel.Pool/addAttachedFiles' for more details. Caused by: Undefined function or variable 'data'.

Thanks for the help !

Body:
You can use your clean variable as a logical index and parse out your data and labels at once.  So there is no need for a loop.

Also the save command needs the "names" of the vars to save not the variables themselves.  So I just put ' ' around each one.

function saving(EEG_struct, clean, name)

subject_number = EEG_struct.subject_number;
fs = EEG_struct.sampling_rate;
chan_names = EEG_struct.channel_names;
nb_epoch = size(EEG_struct.data, 3);

%No need for a loop at all
data  = EEG_struct.data(:,:,logical(clean));
labels = EEG_struct.labels(logical(clean));  %This is a 1xN so I removed the extra colon operator
save(name, 'data', 'labels', 'subject_number', 'fs', 'chan_names');

EDIT:
Per you comment if you want to just leave everything in the structure.  I gave you 2 options for how to save it.

function saving(EEG_struct, clean, name)
%Crop out ~clead data
EEG_struct.data  = EEG_struct.data(:,:,logical(clean));
EEG_struct.labels = EEG_struct.labels(logical(clean));  %This is a 1xN so I removed the extra colon operator
% Option 1
save(name, 'EEG_struct');
% Option2
save(name, '-struct', 'EEG_struct');

Option 1 will directly save the struct to the MAT file.  So if you were to load the data back like this:

test = load(name);

test =
        EEG_struct: [1x1 struct]

You would get your structure placed inside another structure ... which might not be ideal or require an extra line to de-nest it.  On the other hand just loading the MAT file with no outputs  load(name)  would put EEG_struct  into your current workspace.  But if in a function then it sort of springs into existence without every being declared which makes code a bit harder to follow.

Option 2  uses the '-struct' option which breaks out each field automatically into separate vars in the MAT file.  So loading like this:

EEG_struct = load(name);

Will put all the fields back together again.  To me at least this looks cleaner when done within a function but is probably just my preference

So comment out which ever you prefer.  Also, not I did not include clean in the save.  You could either append it to the MAT or add it to your structure.


答:
As Jon said you are missing a namespace.

You can do this in C# as follows

```<code>//Get state list using XPath
XPathDocument xDoc = new XPathDocument(xmlPath); //Path to my file
XPathNavigator xNav = xDoc.CreateNavigator();
XmlNamespaceManager xmlns = new XmlNamespaceManager(xNav.NameTable);
xmlns.AddNamespace("p", "http://tempuri.org/Products.xsd");
string booksQuery = "//p:Books[p:Genre = 'Suspense']";
XPathNodeIterator xIter = xNav.Select(booksQuery, xmlns);

while (xIter.MoveNext())
{
    //do stuff with xIter.Current
}
</code>```

Title: C# XPath help - Expression not working

Body:
As Jon said you are missing a namespace.

You can do this in C# as follows

//Get state list using XPath
XPathDocument xDoc = new XPathDocument(xmlPath); //Path to my file
XPathNavigator xNav = xDoc.CreateNavigator();
XmlNamespaceManager xmlns = new XmlNamespaceManager(xNav.NameTable);
xmlns.AddNamespace("p", "http://tempuri.org/Products.xsd");
string booksQuery = "//p:Books[p:Genre = 'Suspense']";
XPathNodeIterator xIter = xNav.Select(booksQuery, xmlns);

while (xIter.MoveNext())
{
    //do stuff with xIter.Current
}


问:
Duplicate entry IInAppBillingService
Recently I implemented app billing to my android app
https://developer.android.com/google/play/billing/billing_integrate.html#billing-service

Then I implemented "stickerpipe" and then I got this error
Error:Execution failed for task :app:transformClassesWithJarMergingForRelease.> com.android.build.api.transform.TransformException: java.util.zip.ZipException: duplicate entry: com/android/vending/billing/IInAppBillingService$Stub$Proxy.class

Should I remove IInAppBillingService.aidl the one that I added manually ??

I tried this exclude group: 'com.android.vending.billing' but no change.

Can someone help me ?

答:
Error:Execution failed for task :app:transformClassesWithJarMergingForRelease.> com.android.build.api.transform.TransformException: java.util.zip.ZipException: duplicate entry: com/android/vending/billing/IInAppBillingService$Stub$Proxy.class

this Error is because Duplicate Entry of IInAppBillingService class that is added by you in main package.
Check carefully if you have added it at another palace from where compiler is detecting.

```<code>Hint:  if you added this File manually and added in gradle dependencies also  like in my case.
than try to remove this from one place.
</code>```

Hope any will gate helpfull.

Title: Duplicate entry IInAppBillingService

Body:
Error:Execution failed for task :app:transformClassesWithJarMergingForRelease.> com.android.build.api.transform.TransformException: java.util.zip.ZipException: duplicate entry: com/android/vending/billing/IInAppBillingService$Stub$Proxy.class

this Error is because Duplicate Entry of IInAppBillingService class that is added by you in main package.
Check carefully if you have added it at another palace from where compiler is detecting.

Hint:  if you added this File manually and added in gradle dependencies also  like in my case.
than try to remove this from one place.

Hope any will gate helpfull.


问:
Strip signatures and replies from emails
I'm currently working on a system that allows users to reply to notification emails that are sent out (sigh).

I need to strip out the replies and signatures, so that I'm left with the actual content of the reply, without all the noise.

Does anyone have any suggestions about the best way to do this?

答:
There's a really nice PHP library dedicated to the email parsing

http://williamdurand.fr/EmailReplyParser/

https://github.com/willdurand/EmailReplyParser


问:
Convert Json keys into Columns in Spark
I have written a code which reads the data and picks the second element from the tuple. The second element happens to be a JSON.
Code to get the JSON:

```<code>import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.conf.Configuration;
import    com.amazon.traffic.emailautomation.cafe.purchasefilter.util.CodecAwareManifestFileSystem;
import com.amazon.traffic.emailautomation.cafe.purchasefilter.util.CodecAwareManifestInputFormat;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import amazon.emr.utils.manifest.input.ManifestItemFileSystem;
import amazon.emr.utils.manifest.input.ManifestInputFormat;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat ;
import scala.Tuple2;

val configuration = new Configuration(sc.hadoopConfiguration);
ManifestItemFileSystem.setImplementation(configuration);
ManifestInputFormat.setInputFormatImpl(configuration, classOf[TextInputFormat]);
val linesRdd1 = sc.newAPIHadoopFile("location", classOf[ManifestInputFormat[LongWritable,Text]], classOf[LongWritable], classOf[Text], configuration).map(tuple2 =>  tuple2._2.toString());
</code>```

Below is an example:

```<code>{"data":   {"marketplaceId":7,"customerId":123,"eventTime":1471206800000,"asin":"4567","type":"OWN","region":"NA"},"uploadedDate":1471338703958}
</code>```

Now, i want to create a data frame which has the json keys like marketplaceId, customerId etc as columns and the rows having its value. I am not sure how to proceed with this? Can someone help me with pointer which can help me achieve the same?

答:
You can create a scala object for marshalling/unmarshalling JSON using this link
https://coderwall.com/p/o--apg/easy-json-un-marshalling-in-scala-with-jackson

And then use that object for reading JSON data using case class in scala:

```<code>import org.apache.spark.{SparkConf, SparkContext}

object stackover {
  case class Data(
                   marketplaceId: Double,
                   customerId: Double,
                   eventTime: Double,
                   asin: String,
                   `type`: String,
                   region: String
                 )
  case class R00tJsonObject(
                            data: Data,
                            uploadedDate: Double
                           )

  def main(args: Array[String]): Unit = {
    val conf = new SparkConf(true)
    conf.setAppName("example");
    conf.setMaster("local[*]")

    val sc = new SparkContext(conf)
    val data = sc.textFile("test1.json")
    val parsed = data.map(row => JsonUtil.readValue[R00tJsonObject](row))

    parsed.map(rec => (rec.data, rec.uploadedDate, rec.data.customerId,
rec.data.marketplaceId)).collect.foreach(println)
 }
 }
</code>```

Output:

```<code>(Data(7.0,123.0,1.4712068E12,4567,OWN,NA),1.471338703958E12,123.0,7.0)
</code>```

Title: Convert Json keys into Columns in Spark

Body:
I have written a code which reads the data and picks the second element from the tuple. The second element happens to be a JSON.
Code to get the JSON:

import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.conf.Configuration;
import    com.amazon.traffic.emailautomation.cafe.purchasefilter.util.CodecAwareManifestFileSystem;
import com.amazon.traffic.emailautomation.cafe.purchasefilter.util.CodecAwareManifestInputFormat;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import amazon.emr.utils.manifest.input.ManifestItemFileSystem;
import amazon.emr.utils.manifest.input.ManifestInputFormat;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat ;
import scala.Tuple2;

val configuration = new Configuration(sc.hadoopConfiguration);
ManifestItemFileSystem.setImplementation(configuration);
ManifestInputFormat.setInputFormatImpl(configuration, classOf[TextInputFormat]);
val linesRdd1 = sc.newAPIHadoopFile("location", classOf[ManifestInputFormat[LongWritable,Text]], classOf[LongWritable], classOf[Text], configuration).map(tuple2 =>  tuple2._2.toString());

Below is an example:

{"data":   {"marketplaceId":7,"customerId":123,"eventTime":1471206800000,"asin":"4567","type":"OWN","region":"NA"},"uploadedDate":1471338703958}

Now, i want to create a data frame which has the json keys like marketplaceId, customerId etc as columns and the rows having its value. I am not sure how to proceed with this? Can someone help me with pointer which can help me achieve the same?

Body:
You can create a scala object for marshalling/unmarshalling JSON using this link
https://coderwall.com/p/o--apg/easy-json-un-marshalling-in-scala-with-jackson

And then use that object for reading JSON data using case class in scala:

import org.apache.spark.{SparkConf, SparkContext}

object stackover {
  case class Data(
                   marketplaceId: Double,
                   customerId: Double,
                   eventTime: Double,
                   asin: String,
                   `type`: String,
                   region: String
                 )
  case class R00tJsonObject(
                            data: Data,
                            uploadedDate: Double
                           )

  def main(args: Array[String]): Unit = {
    val conf = new SparkConf(true)
    conf.setAppName("example");
    conf.setMaster("local[*]")

    val sc = new SparkContext(conf)
    val data = sc.textFile("test1.json")
    val parsed = data.map(row => JsonUtil.readValue[R00tJsonObject](row))

    parsed.map(rec => (rec.data, rec.uploadedDate, rec.data.customerId,
rec.data.marketplaceId)).collect.foreach(println)
 }
 }

Output:

(Data(7.0,123.0,1.4712068E12,4567,OWN,NA),1.471338703958E12,123.0,7.0)


问:
multiple displayed after search
I implement code that search recycler view but when i write more than one words that belongs to same cardview i get that card displayed multiple time. I need to be displayed only one time and if they match most of my words they need to be displayed first on list.

Search part

```<code>if (charString.contains(",")) {
  String searchChar[] = charString.split(",");
  for (int i = 0; i < searchChar.length; i++) {

    if (androidVersion.getApi().toLowerCase().contains(searchChar[i]) || androidVersion
        .getName()
        .toLowerCase().contains(searchChar[i]) || androidVersion.getVer().toLowerCase()
        .contains(searchChar[i])) {

      filteredList.add(androidVersion);
    }
  }
} else {
  if (androidVersion.getApi().toLowerCase().contains(charString) || androidVersion.getName()
      .toLowerCase().contains(charString) || androidVersion.getVer().toLowerCase()
      .contains(charString)) {

    filteredList.add(androidVersion);
  }
}
</code>```

example

答:
What do you do? Make it look up.

searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query)
            {return  false; }

```<code>        @Override
        public boolean onQueryTextChange(String newText) {

            newText = newText.toLowerCase();

            final ArrayList<DictObjectModel> filteredList = new ArrayList<DictObjectModel>();

            for (int i = 0; i < wordcombimelist.size(); i++) {

                final String text = wordcombimelist.get(i).toLowerCase();
                if (text.contains(newText)) {

                    filteredList.add(new DictObjectModel(wordcombimelist.get(i),meancombimelist.get(i)));
                }
            }
            adapter = new CustomAdapter(filteredList);
            recyclerView.setAdapter(adapter);

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

Title: multiple displayed after search

Body:
I implement code that search recycler view but when i write more than one words that belongs to same cardview i get that card displayed multiple time. I need to be displayed only one time and if they match most of my words they need to be displayed first on list.

Search part

if (charString.contains(",")) {
  String searchChar[] = charString.split(",");
  for (int i = 0; i < searchChar.length; i++) {

    if (androidVersion.getApi().toLowerCase().contains(searchChar[i]) || androidVersion
        .getName()
        .toLowerCase().contains(searchChar[i]) || androidVersion.getVer().toLowerCase()
        .contains(searchChar[i])) {

      filteredList.add(androidVersion);
    }
  }
} else {
  if (androidVersion.getApi().toLowerCase().contains(charString) || androidVersion.getName()
      .toLowerCase().contains(charString) || androidVersion.getVer().toLowerCase()
      .contains(charString)) {

    filteredList.add(androidVersion);
  }
}

example

Body:
What do you do? Make it look up.

searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query)
            {return  false; }

        @Override
        public boolean onQueryTextChange(String newText) {

            newText = newText.toLowerCase();

            final ArrayList<DictObjectModel> filteredList = new ArrayList<DictObjectModel>();

            for (int i = 0; i < wordcombimelist.size(); i++) {

                final String text = wordcombimelist.get(i).toLowerCase();
                if (text.contains(newText)) {

                    filteredList.add(new DictObjectModel(wordcombimelist.get(i),meancombimelist.get(i)));
                }
            }
            adapter = new CustomAdapter(filteredList);
            recyclerView.setAdapter(adapter);

            return true;
        }
    });