问:
HTML5 Camera access - controlling the resolution
I am using normal form input to access the camera on client phones like this:

```<code><input type="file" name="video" accept="video/*" capture></input>
</code>```

My question is: Can I control what quality/resolution the final video will be recorded in so I can reduce the size of the video being posted with the form?

Best regards
Jakob

答:
No, HTML Media Capture does not give you a way to do what you are looking for.

There is a new spec called getUserMedia.

Some documentation: Here

Here is a real demo of using the api. You would have to expand it to stream the video back to the server using sockets or webrtc or something. Go to it on a phone or something with a camera.

Below is a very raw example. Do not run the snippet here. I do that for formatting.

// Put event listeners into place
window.addEventListener("DOMContentLoaded", function() {
  // Grab elements, create settings, etc.
  var canvas = document.getElementById('canvas');
  var context = canvas.getContext('2d');
  var video = document.getElementById('video');
  var mediaConfig = {
    audio: false,
    video: {
      facingMode: {
        //"user"
        //The video source is facing toward the user; this includes, for example,
        //the front-facing camera on a //smartphone.

        //"environment"
        //The video source is facing away from the user, thereby viewing their environment.
        //This is the back //camera on a smartphone.

        exact: "environment"
      },
      width: {
        min: 1920,
        ideal: 1920,
        max: 2900
      },
      height: {
        min: 1080,
        ideal: 1080,
        max: 2900
      }

    }
  };
  var errBack = function(e) {
    console.log('An error has occurred!', e)
  };

  // Put video listeners into place
  if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
    navigator.mediaDevices.getUserMedia(mediaConfig).then(function(stream) {
      video.src = window.URL.createObjectURL(stream);
      video.play();
    }).catch(this.errBack);
  }
  //Older browser support
  else if (navigator.getUserMedia) { // Standard
    navigator.getUserMedia(mediaConfig, function(stream) {
      video.src = stream;
      video.play();
    }, errBack);
  } else if (navigator.webkitGetUserMedia) { // WebKit-prefixed
    navigator.webkitGetUserMedia(mediaConfig, function(stream) {
      video.src = window.webkitURL.createObjectURL(stream);
      video.play();
    }, errBack);
  } else if (navigator.mozGetUserMedia) { // Mozilla-prefixed
    navigator.mozGetUserMedia(mediaConfig, function(stream) {
      video.src = window.URL.createObjectURL(stream);
      video.play();
    }, errBack);
  }

  // Trigger photo take
  document.getElementById('snap').addEventListener('click', function() {
    context.drawImage(video, 0, 0, 640, 480);
  });
}, false);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><video id="video" width="640" height="480" autoplay></video>
<button id="snap" class="sexyButton">Take Photo</button>
<canvas id="canvas" width="640" height="480"></canvas></code>```

Body:
I am using normal form input to access the camera on client phones like this:

<input type="file" name="video" accept="video/*" capture></input>

My question is: Can I control what quality/resolution the final video will be recorded in so I can reduce the size of the video being posted with the form?

Best regards
Jakob

Body:
No, HTML Media Capture does not give you a way to do what you are looking for.

There is a new spec called getUserMedia.

Some documentation: Here

Here is a real demo of using the api. You would have to expand it to stream the video back to the server using sockets or webrtc or something. Go to it on a phone or something with a camera.

Below is a very raw example. Do not run the snippet here. I do that for formatting.

// Put event listeners into place
window.addEventListener("DOMContentLoaded", function() {
  // Grab elements, create settings, etc.
  var canvas = document.getElementById('canvas');
  var context = canvas.getContext('2d');
  var video = document.getElementById('video');
  var mediaConfig = {
    audio: false,
    video: {
      facingMode: {
        //"user"
        //The video source is facing toward the user; this includes, for example,
        //the front-facing camera on a //smartphone.

        //"environment"
        //The video source is facing away from the user, thereby viewing their environment.
        //This is the back //camera on a smartphone.

        exact: "environment"
      },
      width: {
        min: 1920,
        ideal: 1920,
        max: 2900
      },
      height: {
        min: 1080,
        ideal: 1080,
        max: 2900
      }

    }
  };
  var errBack = function(e) {
    console.log('An error has occurred!', e)
  };

  // Put video listeners into place
  if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
    navigator.mediaDevices.getUserMedia(mediaConfig).then(function(stream) {
      video.src = window.URL.createObjectURL(stream);
      video.play();
    }).catch(this.errBack);
  }
  //Older browser support
  else if (navigator.getUserMedia) { // Standard
    navigator.getUserMedia(mediaConfig, function(stream) {
      video.src = stream;
      video.play();
    }, errBack);
  } else if (navigator.webkitGetUserMedia) { // WebKit-prefixed
    navigator.webkitGetUserMedia(mediaConfig, function(stream) {
      video.src = window.webkitURL.createObjectURL(stream);
      video.play();
    }, errBack);
  } else if (navigator.mozGetUserMedia) { // Mozilla-prefixed
    navigator.mozGetUserMedia(mediaConfig, function(stream) {
      video.src = window.URL.createObjectURL(stream);
      video.play();
    }, errBack);
  }

  // Trigger photo take
  document.getElementById('snap').addEventListener('click', function() {
    context.drawImage(video, 0, 0, 640, 480);
  });
}, false);

<video id="video" width="640" height="480" autoplay></video>
<button id="snap" class="sexyButton">Take Photo</button>
<canvas id="canvas" width="640" height="480"></canvas>


来源: stackexchange

问:
Choosing a simple web application framework
I'm evaluating web application frameworks for a hobby project I'm starting, and am beginning to go crazy trying to decide among the vast number of frameworks available to choose. The framework language isn't helping me filter out frameworks as I have varying levels of experience with Java, Python, Ruby and C#, and don't mind frameworks in any of these languages. </p>

<p>I'm looking for help in narrowing the choice down to a few that I can then investigate in more detail. </p>

答:
The usual suspects are django and rails, of course. They are not "small" by any definition.

I recommend webpy, it is simple, small and stays out of the way. I think reddit ran on it for a while as it is the brain child of Aaron Swartz.

OwnerDisplayName: nagul

ContentLicense: CC BY-SA 2.5

Body:
I'm evaluating web application frameworks for a hobby project I'm starting, and am beginning to go crazy trying to decide among the vast number of frameworks available to choose. The framework language isn't helping me filter out frameworks as I have varying levels of experience with Java, Python, Ruby and C#, and don't mind frameworks in any of these languages.

I'm looking for help in narrowing the choice down to a few that I can then investigate in more detail.

LastEditorDisplayName: Marko Dumic

OwnerDisplayName: rz

LastEditorDisplayName: rz


问:
Load data from table using PHP & AJAX
I'm trying to retrieve data from table using PHP and AJAX, at the moment I'm able to display the result of my query in json format, what I want to do is select an specific data from that array, for example I get this array:

{data: [{IdProduct: "1", Name: "Name here..........",…}]}

For example I want to select only Name, I tried doing this:

```<code>function LoadProductos() {

$.ajax({
    url: '../../class/loadProd.php',
    method: 'POST',
    success: function (data) {
      var aRC = JSON.parse(data);

      for (var i = 0; i < aRC.length; i++) {
        console.log(aRC[i].Name);
      }
    }

  });
}
</code>```

But this doesn't shows anything, how can I do this? This is my PHP code:

```<code>while($row = mysqli_fetch_array($registros)) {

    $table.='{
        "IdProduct":"'.$row['IdProduct'].'",
        "Name":"'.$row['Name'].'",
        "Description":"'.$row['Description'].'",
        "ImagePath":"'.$row['ImagePath'].'"
    },';

    $table = substr($table, 0, strlen($table) -1);

    echo '{"data":['.$table.']}';
}
</code>```

答:
There are couple of things you need to change in your code, such as:

That's not how you should create a json string. Create an empty array before the while() loop and append the row details to this array in each iteration of the loop. And after coming out of the loop, simply apply json_encode() function to the resultant array to get the final json string.

```<code>$table = array();
while($row = mysqli_fetch_array($registros)) {
    $table[]= array(
        'IdProduct' => $row['IdProduct'],
        'Name' => $row['Name'],
        'Description' => $row['Description'],
        'ImagePath' => $row['ImagePath']
    );
}
echo json_encode($table);
</code>```

Since you're expecting a json string from server, add this setting dataType:'json' to your AJAX request. dataType is the type of data you're expecting back from the server. And in the success() callback function, simply loop through the json result to get the relevant data.

```<code>function LoadProductos() {
    $.ajax({
        url: '../../class/loadProd.php',
        method: 'POST',
        dataType: 'json',
        success: function (data) {
            for (var i = 0; i < data.length; i++) {
                alert(data[i].Name);
            }
        }
    });
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Load data from table using PHP & AJAX

Body:
I'm trying to retrieve data from table using PHP and AJAX, at the moment I'm able to display the result of my query in json format, what I want to do is select an specific data from that array, for example I get this array:

{data: [{IdProduct: "1", Name: "Name here..........",…}]}

For example I want to select only Name, I tried doing this:

function LoadProductos() {

$.ajax({
    url: '../../class/loadProd.php',
    method: 'POST',
    success: function (data) {
      var aRC = JSON.parse(data);

      for (var i = 0; i < aRC.length; i++) {
        console.log(aRC[i].Name);
      }
    }

  });
}

But this doesn't shows anything, how can I do this? This is my PHP code:

while($row = mysqli_fetch_array($registros)) {

    $table.='{
        "IdProduct":"'.$row['IdProduct'].'",
        "Name":"'.$row['Name'].'",
        "Description":"'.$row['Description'].'",
        "ImagePath":"'.$row['ImagePath'].'"
    },';

    $table = substr($table, 0, strlen($table) -1);

    echo '{"data":['.$table.']}';
}

Body:
There are couple of things you need to change in your code, such as:

That's not how you should create a json string. Create an empty array before the while() loop and append the row details to this array in each iteration of the loop. And after coming out of the loop, simply apply json_encode() function to the resultant array to get the final json string.

$table = array();
while($row = mysqli_fetch_array($registros)) {
    $table[]= array(
        'IdProduct' => $row['IdProduct'],
        'Name' => $row['Name'],
        'Description' => $row['Description'],
        'ImagePath' => $row['ImagePath']
    );
}
echo json_encode($table);

Since you're expecting a json string from server, add this setting dataType:'json' to your AJAX request. dataType is the type of data you're expecting back from the server. And in the success() callback function, simply loop through the json result to get the relevant data.

function LoadProductos() {
    $.ajax({
        url: '../../class/loadProd.php',
        method: 'POST',
        dataType: 'json',
        success: function (data) {
            for (var i = 0; i < data.length; i++) {
                alert(data[i].Name);
            }
        }
    });
}


问:
Merging two unevenly spaced timeseries in Python
I have two unevenly spaced timeseries:

```<code>      time    X1
1234567000 96.32
1234567005 96.01
1234567009 96.05

      time    X2
1234567001 23.88
1234567005 23.96
</code>```

I would like to merge them:

```<code>      time    X1    X2
1234567000 96.32   nan
1234567001   nan 23.88
1234567005 96.01 23.96
1234567009 96.05   nan
</code>```

How can I do so in Python? I'm open to using packages, e.g. pandas.

time is integer (It isn't a UNIX timestamp). X1 and X2 are float.

答:
If you want to use pandas, you first format your inputs as pandas dataframes like follows :

```<code>import pandas as pd

s1 = pd.DataFrame({
    'time':[1234567000,1234567005,1234567009],
    'X1':[96.32,96.01,96.05]
},columns=['time','X1'])  # to keep columns order

s2 = pd.DataFrame({
    'time':[1234567001,1234567005],
    'X2':[23.88,23.96]
},columns=['time','X2'])  # to keep columns order
</code>```

and then simply merge them with this one line:

```<code>df = pd.merge(s1,s2,how='outer')
</code>```

if you want the time values to be sorted use this instead:

```<code>df = pd.merge(s1,s2,how='outer').sort_values(by='time')
</code>```

Body:
I have two unevenly spaced timeseries:

      time    X1
1234567000 96.32
1234567005 96.01
1234567009 96.05

      time    X2
1234567001 23.88
1234567005 23.96

I would like to merge them:

      time    X1    X2
1234567000 96.32   nan
1234567001   nan 23.88
1234567005 96.01 23.96
1234567009 96.05   nan

How can I do so in Python? I'm open to using packages, e.g. pandas.

time is integer (It isn't a UNIX timestamp). X1 and X2 are float.

Body:
If you want to use pandas, you first format your inputs as pandas dataframes like follows :

import pandas as pd

s1 = pd.DataFrame({
    'time':[1234567000,1234567005,1234567009],
    'X1':[96.32,96.01,96.05]
},columns=['time','X1'])  # to keep columns order

s2 = pd.DataFrame({
    'time':[1234567001,1234567005],
    'X2':[23.88,23.96]
},columns=['time','X2'])  # to keep columns order

and then simply merge them with this one line:

df = pd.merge(s1,s2,how='outer')

if you want the time values to be sorted use this instead:

df = pd.merge(s1,s2,how='outer').sort_values(by='time')


问:
executing scripts on Google App Engine localhost
is there an easy way to execute scripts on Google App Engine localhost?
For instance i have few scripts to generate pilot data, it's quite painful to copy-and-paste them to the interactive console all the time.

Currently, i'm using a simple bash script to do this, but i'm not sure this is the best solution.

curl --data-urlencode "code=`cat src/gen_pilot_data.py`" http://localhost:8079/_ah/admin/interactive/execute

thanks,
 V

答:
There is nothing special to do in order to execute script on AppEngine, but if you want to use AppEngine APIs you have to boot AppEngine before. I don't know the builtin one-line way, but you can take look how various projects do this:

https://bitbucket.org/wkornewald/djangoappengine/src/4f5d7a223084/boot.py

http://code.google.com/p/nose-gae/source/browse/trunk/nosegae.py?r=54

You can also try to import your script in console:

```<code>import gen_pilot_data
</code>```

Body:
There is nothing special to do in order to execute script on AppEngine, but if you want to use AppEngine APIs you have to boot AppEngine before. I don't know the builtin one-line way, but you can take look how various projects do this:

https://bitbucket.org/wkornewald/djangoappengine/src/4f5d7a223084/boot.py

http://code.google.com/p/nose-gae/source/browse/trunk/nosegae.py?r=54

You can also try to import your script in console:

import gen_pilot_data


问:
Get the first n/2 of n words in a column in a pandas data frame
I would like to get the first n/2 of n words in a column in a pandas data frame.
Each row can have a different number of words, but every row has an even number of words.
This column contains the name of an item, but every name is duplicated.
For example, One became One One and One Two became One Two One Two.

I thought the following would work.

count the number of words

split the column on spaces

get the first n/2 words in this split

But it doesn't work (I only casually use Python and pandas).
Here is an MWE.

```<code>import pandas as pd
df = pd.DataFrame(['One One', 'One Two One Two'])
df[1] = df[0].str.count('\w+')
df[2] = df[0].str.split()
df[3] = df[0].get(df[2])
</code>```

P.S. Please let me know if you have a good reference on pandas for the R user.

答:
```<code>df = pd.DataFrame(['One One', 'One Two One Two'])

def proc(s):
    l = s.split()
    return ' '.join(l[:len(l) // 2])

df[1] = [proc(s) for s in df[0].values.tolist()]

                 0        1
0          One One      One
1  One Two One Two  One Two
</code>```

Body:
I would like to get the first n/2 of n words in a column in a pandas data frame.
Each row can have a different number of words, but every row has an even number of words.
This column contains the name of an item, but every name is duplicated.
For example, One became One One and One Two became One Two One Two.

I thought the following would work.

count the number of words

split the column on spaces

get the first n/2 words in this split

But it doesn't work (I only casually use Python and pandas).
Here is an MWE.

import pandas as pd
df = pd.DataFrame(['One One', 'One Two One Two'])
df[1] = df[0].str.count('\w+')
df[2] = df[0].str.split()
df[3] = df[0].get(df[2])

P.S. Please let me know if you have a good reference on pandas for the R user.


问:
Is there a way to call SSDT DacServices without a connectionstring
I have a Source DacPac and a Target DacPac. With powershell I would like to compare both and generate a upgrade script. This per se is simple for all cases with DacServices as long as there is a valid Connection String. However, for my CD pipeline, I do not know the eventual connection string nor do I wish to know. And all I want is for the script to generate the SQL.

I tried this out with sqlpackage.exe by sending args as follows

$args = @(
                    "/a:Script",
                    "/sf:$PathToDacpacSource",
                    "/tf:$PathToDacpacTarget",
                    "/op:$outputFile",
                    "/tdn:$TargetDatabaseName"
                )

and this works fine. so far I had managed by adding just a dependency to DacServices via [Microsoft.SqlServer.DacFx.x64], but this inability to generate scripts without a connection string has forced me to add the dependency on SQLPackage.exe via [Microsoft.Data.Tools.Msbuild] too

The constructors for DacServices all require a ConnectionString

Has anyone else encountered a similar situation and any solutions?

or Do you exclusively use SQLPackage at the deployment side to overcome this issue?

答:
There is a static version of GenerateDeployScript that does not need a connection string as you don't call the constructor for a static method, it isn't very clear in the msdn documentation but the "S" which looks like it is floating means it is static :)

https://msdn.microsoft.com/en-us/library/microsoft.sqlserver.dac.dacservices.generatedeployscript(v=sql.120).aspx#M:Microsoft.SqlServer.Dac.DacServices.GenerateDeployScript%28Microsoft.SqlServer.Dac.DacPackage,Microsoft.SqlServer.Dac.DacPackage,System.String,Microsoft.SqlServer.Dac.DacDeployOptions%29

` public static string GenerateDeployScript( DacPackage sourcePackage, DacPackage targetPackage, string targetDatabaseName, DacDeployOptions options = null )


问:
How can I perform a server to server file transfer
I would like to copy a site which is currently being hosted live on an easyspace web domain to another domain that is hosted by the web company Parallels. I wondered if there was a way of doing this without fist taking the site down and copying the files back to the local server, then re-uploading them again.

If anyone has any advice on this, I would be most grateful!

Regards,

Robert Y

答: It is necessary to check if fxp protocol (that is a protocol that supports file transfer between servers) is supported by both servers: but usually is disabled for security reasons. If it is active (make a question to your host admin) than you can use a fxp software as FlashFXP, SmartFTP or FTP Rush (Freeware) or similar sw.</p>


问:
Using divs on an image slider
I have code below for an image slider that stops when you hover on the image. I was wondering if there's anyway to do this but instead of using image tags using just use a div tag so I can create custom shapes to have on the slider with CSS. Can anyone point me in the right direction, when I try replacing the images with divs it stops working. Any thoughts?

#scroller {
  position: absolute;
  left: 33%;
  top: 14%;
}

#scroller .innerScrollArea {
  overflow: hidden;
  position: absolute;
  top: 10%;
  bottom: 0;
  left: 0;
  right: 0;
}

#scroller ul {
  padding: 0;
  top: 10%;
  position: relative;
}

#scroller li {
  padding: 0;
  top: 7%;
  list-style-type: none;
  position: absolute;
}

.test {
width:100px;
height:200px;
background-color:pink;}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>  <!-- SCROLLING IMAGE GALLERY-->

  <div id="scroller" style="width: 536px; height: 263px; margin: 0 auto;">
    <div class="innerScrollArea">
      <ul>
        <li><img src="http://i1055.photobucket.com/albums/s511/Josh_Tilton/website/angels_landing_zpsn5dpgsui.jpg" width="536" height="263" /></li>
        <li><img src="http://i1055.photobucket.com/albums/s511/Josh_Tilton/website/big_cottonwood_zpszx8qyyik.jpg" width="536" height="263" /></li>
      </ul>
    </div>
  </div>

  <!-- JS SCROLLING IMAGES CODE-->

  <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
  <script type="text/javascript">
    $(function(){
        var scroller = $('#scroller div.innerScrollArea');
        var scrollerContent = scroller.children('ul');
        scrollerContent.children().clone().appendTo(scrollerContent);
        var curX = 0;
        scrollerContent.children().each(function(){
            var $this = $(this);
            $this.css('left', curX);
            curX += $this.outerWidth(true);
        });
        var fullW = curX / 2;
        var viewportW = scroller.width();

        // Scrolling speed management
        var controller = {curSpeed:0, fullSpeed:2};
        var $controller = $(controller);
        var tweenToNewSpeed = function(newSpeed, duration)
        {
            if (duration === undefined)
                duration = 600;
            $controller.stop(true).animate({curSpeed:newSpeed}, duration);
        };

        // Pause on hover
        scroller.hover(function(){
            tweenToNewSpeed(0);
        }, function(){
            tweenToNewSpeed(controller.fullSpeed);
        });

        // Scrolling management; start the automatical scrolling
        var doScroll = function()
        {
            var curX = scroller.scrollLeft();
            var newX = curX + controller.curSpeed;
            if (newX > fullW*2 - viewportW)
                newX -= fullW;
            scroller.scrollLeft(newX);
        };
        setInterval(doScroll, 40);
        tweenToNewSpeed(controller.fullSpeed);
    });
  </script>
</body>

</html></code>```

答:
You could wrap the image like so.

In your Script:

```<code>  <ul>
    <li><div class='slidingIMG'><img src="http://i1055.photobucket.com/albums/s511/Josh_Tilton/website/angels_landing_zpsn5dpgsui.jpg" width="536" height="263" /><div></li>
    <li><div class='slidingIMG'><img src="http://i1055.photobucket.com/albums/s511/Josh_Tilton/website/big_cottonwood_zpszx8qyyik.jpg" width="536" height="263" /><div></li>
  </ul>
</code>```

and in your Stylesheet. (The 10px is only to show an extremum to your current)

```<code>.slidingIMG img{

    height:10px;
}
</code>```

Title: Using divs on an image slider

Body:
You could wrap the image like so.

In your Script:

  <ul>
    <li><div class='slidingIMG'><img src="http://i1055.photobucket.com/albums/s511/Josh_Tilton/website/angels_landing_zpsn5dpgsui.jpg" width="536" height="263" /><div></li>
    <li><div class='slidingIMG'><img src="http://i1055.photobucket.com/albums/s511/Josh_Tilton/website/big_cottonwood_zpszx8qyyik.jpg" width="536" height="263" /><div></li>
  </ul>

and in your Stylesheet. (The 10px is only to show an extremum to your current)

.slidingIMG img{

    height:10px;
}


问:
difference between &ptr.member and &(ptr.member)
I'm writing a c program and I'm not too certain about how to write data to the particular members of a struct. I'm using a struct pointer that gets allocated memory using realloc() and accessing that data similar to an array. The array is dynamically resized each time an element is added.

My question is when writing data to an array index what is the correct way to do this?

```<code>struct s{...some data members...}
struct s *s_array = NULL;

//allocate memory at some point using realloc()

printf("enter some data: ");
scanf("%d", &s[index].data_member);
</code>```

OR

```<code>scanf("%d", &(s[index].data_member));
</code>```

答:
The array index operator [] and the member access operator . both have higher precedence than the address-of operator &.

So &s[index].data_member is valid to get the address of a member of an array element.  The parenthesis in &(s[index].data_member) are redundant and not needed.

Body:
I'm writing a c program and I'm not too certain about how to write data to the particular members of a struct. I'm using a struct pointer that gets allocated memory using realloc() and accessing that data similar to an array. The array is dynamically resized each time an element is added.

My question is when writing data to an array index what is the correct way to do this?

struct s{...some data members...}
struct s *s_array = NULL;

//allocate memory at some point using realloc()

printf("enter some data: ");
scanf("%d", &s[index].data_member);

OR

scanf("%d", &(s[index].data_member));


问:
How to show a "are u sure YES OR NOT" dialog when user press a button?
first of all, i have to tell you that i have searched here and on google and i can't find a easy way to do it (im newbie on this), then i need your help please

i have this button, that removes a friend from the remote database:

```<code>removeButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                con.deletePermission(settings.getString("login",""),bundle.getString("email"));
                finish();
                Toast.makeText(getApplicationContext(), getString(R.string.friendsuccessfullyremoved), Toast.LENGTH_LONG).show();
            }
        });
</code>```

i just want to show a simple "Are you sure? YES or NOT" dialog with two buttons (YES AND NOT) and when the user press YES, it have to be called this code:

```<code>con.deletePermission(settings.getString("login",""),bundle.getString("email"));
                    finish();
                    Toast.makeText(getApplicationContext(), getString(R.string.friendsuccessfullyremoved), Toast.LENGTH_LONG).show();
</code>```

exist's a easy way to do it?

thanks

EDIT: i try to do it with this: http://developer.android.com/guide/topics/ui/dialogs.html  but it doesn't works, nothing happens when i press the button, no dialog appear

my new code:

```<code>bundle = this.getIntent().getExtras();//get the intent & bundle passed by X
        builder = new AlertDialog.Builder(this);
        removeButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                /*
                con.deletePermission(settings.getString("login",""),bundle.getString("email"));
                finish();
                Toast.makeText(getApplicationContext(), getString(R.string.friendsuccessfullyremoved), Toast.LENGTH_LONG).show();
                */
                builder.setMessage("Are you sure?")
                       .setCancelable(false)
                       .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                           public void onClick(DialogInterface dialog, int id) {
                                con.deletePermission(settings.getString("login",""),bundle.getString("email"));
                                finish();
                                Toast.makeText(getApplicationContext(), getString(R.string.friendsuccessfullyremoved), Toast.LENGTH_LONG).show();
                           }
                       })
                       .setNegativeButton("No", new DialogInterface.OnClickListener() {
                           public void onClick(DialogInterface dialog, int id) {
                                dialog.cancel();
                           }
                       });
                AlertDialog alert = builder.create();
            }
        });
</code>```

答:
yeah it's missing

```<code> AlertDialog alert = builder.create();
 alert.show();
</code>```

This is assuming you want to show the alert dialogue as soon as the button has been pressed.

Body:
first of all, i have to tell you that i have searched here and on google and i can't find a easy way to do it (im newbie on this), then i need your help please

i have this button, that removes a friend from the remote database:

removeButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                con.deletePermission(settings.getString("login",""),bundle.getString("email"));
                finish();
                Toast.makeText(getApplicationContext(), getString(R.string.friendsuccessfullyremoved), Toast.LENGTH_LONG).show();
            }
        });

i just want to show a simple "Are you sure? YES or NOT" dialog with two buttons (YES AND NOT) and when the user press YES, it have to be called this code:

con.deletePermission(settings.getString("login",""),bundle.getString("email"));
                    finish();
                    Toast.makeText(getApplicationContext(), getString(R.string.friendsuccessfullyremoved), Toast.LENGTH_LONG).show();

exist's a easy way to do it?

thanks

EDIT: i try to do it with this: http://developer.android.com/guide/topics/ui/dialogs.html  but it doesn't works, nothing happens when i press the button, no dialog appear

my new code:

bundle = this.getIntent().getExtras();//get the intent & bundle passed by X
        builder = new AlertDialog.Builder(this);
        removeButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                /*
                con.deletePermission(settings.getString("login",""),bundle.getString("email"));
                finish();
                Toast.makeText(getApplicationContext(), getString(R.string.friendsuccessfullyremoved), Toast.LENGTH_LONG).show();
                */
                builder.setMessage("Are you sure?")
                       .setCancelable(false)
                       .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                           public void onClick(DialogInterface dialog, int id) {
                                con.deletePermission(settings.getString("login",""),bundle.getString("email"));
                                finish();
                                Toast.makeText(getApplicationContext(), getString(R.string.friendsuccessfullyremoved), Toast.LENGTH_LONG).show();
                           }
                       })
                       .setNegativeButton("No", new DialogInterface.OnClickListener() {
                           public void onClick(DialogInterface dialog, int id) {
                                dialog.cancel();
                           }
                       });
                AlertDialog alert = builder.create();
            }
        });

Body:
yeah it's missing

 AlertDialog alert = builder.create();
 alert.show();

This is assuming you want to show the alert dialogue as soon as the button has been pressed.


问:
Plone: filtered view of Unauthorized exceptions
In my Plone site, Unauthorized exceptions are quite common; most of the time they mean, "Please log in, because the requested content is not available for anonymous users".  Normally, those exceptions are ignored for the error log (/prefs_error_log_form).

However, sometimes such exceptions are supposed not to be raised, and there is some problem which causes a malfunction. Is it possible to get a filtered list of Unauthorized exceptions, e.g. filtered by a certain path?

答: If you install something like iw.rejectanonymous, you should be able to log all Unauthorized exceptions and only get authenticated users trying to access something they shouldn't.</p>


问:
Output specific strings from a file in RedHat Linux 7 - Regex possibly
First time asking a questions so my apologies if I skipped over some of the basics before posting this question.

Basically my questions is fairly simple....I have a file that gets written to very often and the first string/column always has the word "CLEAR" or "CRITICAL", sometimes "WARNING", but I want to ignore those entries.

Around the 17th column there is a specific32bit alpha-numeric # that accompanies each entry. I'm trying to find a way to, without modifying the original file....write out just the 1st column and the 32bit alpha-numeric # into a new file for starters. Unfortunately the 32bit # is not always in column 17 or else I could do this on my own.

Here is a glance of a portion of the log file that I'm referring to. Please don't bash me to hard on my ignorance if my question is not detailed enough or has already been answered before.

CLEAR ; lnx20162.csxt.csx.com ; Database Instance ; actd ; Dec 14,
  2012 4:46:31 PM EST ; D0C53D1FB19075C2E0405C0A6FF002BF ; Metric Alert
  ; Response:State ; The database status is OPEN.

CRITICAL ; lnx20016.csxt.csx.com ; Database Instance ; GISP_GISP2 ;
  Dec 14, 2012 4:39:54 PM EST ; D0C53D32C0E53F85E0405C0A6FF002C9 ;
  Metric Alert ; alertLog:genericErrStack ; ORA-error stack (4,031)
  logged in
  /oramisc01/oracle/diag/rdbms/gisp/GISP2/trace/alert_GISP2.log.

CRITICAL ; lnx20016.csxt.csx.com ; Database Instance ; GISP_GISP2 ;
  Dec 14, 2012 4:40:00 PM EST ; D0C53D32C1093F85E0405C0A6FF002C9 ;
  Metric Alert ; alertLog:genericErrStack ; ORA-error stack (04031,
  04031) logged in
  /oramisc01/oracle/diag/rdbms/gisp/GISP2/trace/alert_GISP2.log.

CRITICAL ; lnx20016.csxt.csx.com ; Database Instance ; GISP_GISP2 ;
  Dec 14, 2012 4:39:55 PM EST ; D0C53D32C0EB3F85E0405C0A6FF002C9 ;
  Metric Alert ; alertLog:genericErrStack ; ORA-error stack (04031,
  04031, 04031, 04031, 04031) logged in
  /oramisc01/oracle/diag/rdbms/gisp/GISP2/trace/alert_GISP2.log.

答:
```<code>grep -E -o "EST ;.{0,33}" file1| cut -d ";" -f2 > outputfile
</code>```

you need to find a consistent "hook" which is "EST ;"

if you want this done all the time say on the minute, make a script and put in on crontab

Body:
grep -E -o "EST ;.{0,33}" file1| cut -d ";" -f2 > outputfile

you need to find a consistent "hook" which is "EST ;"

if you want this done all the time say on the minute, make a script and put in on crontab


问:
Swift - UISlider doesn't change its value
I programmatically created an UISlider and I created an action that runs evertime I change the slider value. The actions print out the slider.value. The problem is that the value printed out is always 0. Even if I move the slider.
This is the code:</p>

```<code>import UIKit

class EditVC: UIViewController {

var slider : UISlider {
    let frame = CGRect(x: 10, y: 85, width: editView.frame.width - 30, height: 20)
    let slider = UISlider(frame: frame)
    slider.minimumValue = 0
    slider.maximumValue = 10
    slider.isContinuous = true
    slider.addTarget(self, action: #selector(valueChangedFunc), for: .valueChanged)

    return slider

    }

@objc func valueChangedFunc() {
    print(slider.value)
}

override func viewDidLoad() {
    super.viewDidLoad()

    view.addSubview(slider)
}
}
</code>```

答:
I moved some code and removed the @objc in your function.</p>

```<code> import UIKit

class EditVC: UIViewController {

func addSlider() -> UISlider {
        let frame = CGRect(x: 10, y: 85, width: editView.frame.width - 30, height: 20)
        let slider = UISlider(frame: frame)
        slider.minimumValue = 0
        slider.maximumValue = 10
        slider.isContinuous = true
        slider.addTarget(self, action: #selector(valueChangedFunc), for: .valueChanged)

    return slider

    }

func valueChangedFunc() {
    print(slider.value)
}

override func viewDidLoad() {
    super.viewDidLoad()

    view.addSubview(addSlider())
}
}
</code>```

Body:
I programmatically created an UISlider and I created an action that runs evertime I change the slider value. The actions print out the slider.value. The problem is that the value printed out is always 0. Even if I move the slider.
This is the code:

import UIKit

class EditVC: UIViewController {

var slider : UISlider {
    let frame = CGRect(x: 10, y: 85, width: editView.frame.width - 30, height: 20)
    let slider = UISlider(frame: frame)
    slider.minimumValue = 0
    slider.maximumValue = 10
    slider.isContinuous = true
    slider.addTarget(self, action: #selector(valueChangedFunc), for: .valueChanged)

    return slider

    }

@objc func valueChangedFunc() {
    print(slider.value)
}

override func viewDidLoad() {
    super.viewDidLoad()

    view.addSubview(slider)
}
}

Body:
I moved some code and removed the @objc in your function.

 import UIKit

class EditVC: UIViewController {

func addSlider() -> UISlider {
        let frame = CGRect(x: 10, y: 85, width: editView.frame.width - 30, height: 20)
        let slider = UISlider(frame: frame)
        slider.minimumValue = 0
        slider.maximumValue = 10
        slider.isContinuous = true
        slider.addTarget(self, action: #selector(valueChangedFunc), for: .valueChanged)

    return slider

    }

func valueChangedFunc() {
    print(slider.value)
}

override func viewDidLoad() {
    super.viewDidLoad()

    view.addSubview(addSlider())
}
}


问:
Add attribute to i18n strings in React Native
I've already known how to generate i18n string through react-native-i18n. For example,

// en.js  source
{
  "hello": "Hello, {{name}}."
}

// use
I18n.t("hello", { name: "John" })
```

<p>and it shows <code>Hello, John.</code>.</p>

<p>I've also known how to generate attributed string:</p>

```<Text>
  This is a <Text style={{fontWeight: 'bold'}}>bold<Text> word.
<Text>
```

<p>and it shows <code>This is a</code><strong><code>bold</code></strong><code>word</code>.</p>

<p>The problem is, how can I add attributes to a i18n template string? Any library for this?</p>

```// en.js  source
{
  "hello": "Hello, {{guest}}. I'm {{host}}."
}

// use
I18n.t("hello", { guest: "John", host: "Sam" })
```

Expected: Hello,John. I'm Sam.

What I got: Hello, John. I'm Sam.

答:
You can use react-i18next it supports react content inside its translation component:

<Trans i18nKey="userMessagesUnread" count={count}>
    Hello {{name}}, you have {{count}} unread message. <Link to="/msgs">Go to messages</Link>.
</Trans>
```
<p>In the dictionary,</p>
<pre class="lang-json prettyprint-override"><code>"userMessagesUnread": "Hello <1>{{name}}</1>, you have {{count}} unread message. <5>Go to message</5>.",
"userMessagesUnread_plural": "Hello <1>{{name}}</1>, you have {{count}} unread messages.  <5>Go to messages</5>.",
</code>```

Learn more https://react.i18next.com/latest/trans-component#using-with-react-components

Body:
I've already known how to generate i18n string through react-native-i18n. For example,

// en.js  source
{
  "hello": "Hello, {{name}}."
}

// use
I18n.t("hello", { name: "John" })

and it shows Hello, John..

I've also known how to generate attributed string:

<Text>
  This is a <Text style={{fontWeight: 'bold'}}>bold<Text> word.
<Text>

and it shows This is aboldword.

The problem is, how can I add attributes to a i18n template string? Any library for this?

// en.js  source
{
  "hello": "Hello, {{guest}}. I'm {{host}}."
}

// use
I18n.t("hello", { guest: "John", host: "Sam" })

Expected: Hello,John. I'm Sam.

What I got: Hello, John. I'm Sam.

Body:
You can use react-i18next it supports react content inside its translation component:

<Trans i18nKey="userMessagesUnread" count={count}>
    Hello <strong title={t('nameTitle')}>{{name}}</strong>, you have {{count}} unread message. <Link to="/msgs">Go to messages</Link>.
</Trans>

In the dictionary,

"userMessagesUnread": "Hello <1>{{name}}</1>, you have {{count}} unread message. <5>Go to message</5>.",
"userMessagesUnread_plural": "Hello <1>{{name}}</1>, you have {{count}} unread messages.  <5>Go to messages</5>.",

Learn more https://react.i18next.com/latest/trans-component#using-with-react-components

ContentLicense: CC BY-SA 4.0


问:
Pare Cloud Code getHours() changes all variables
I'm writing a node.js function using Parse Open Source's cloud code. Yet for some reason changing the hours on one variable changes other ones?!</p>

```<code>var beforeTime = item.get("date")
var afterTime = item.get("date")
console.log("before " + beforeTime.getHours())
console.log("after " + afterTime.getHours())
original.log("original " + item.get("date").getHours())

/*
All off these print out the same (i.e. 15)
*/

beforeTime.setHours(beforeTime.getHours() - request.params.hours)

console.log("before " + beforeTime.getHours())
console.log("after " + afterTime.getHours())
original.log("original " + item.get("date").getHours())

/*
All off these ALSO print out the same (i.e. 14) !!!???
*/
</code>```

答:
beforeTime and afterTime are both getting set to instances of the same object.

Try var afterTime = new Date(item.get("date").toString());

Body:
I'm writing a node.js function using Parse Open Source's cloud code. Yet for some reason changing the hours on one variable changes other ones?!

var beforeTime = item.get("date")
var afterTime = item.get("date")
console.log("before " + beforeTime.getHours())
console.log("after " + afterTime.getHours())
original.log("original " + item.get("date").getHours())

/*
All off these print out the same (i.e. 15)
*/

beforeTime.setHours(beforeTime.getHours() - request.params.hours)

console.log("before " + beforeTime.getHours())
console.log("after " + afterTime.getHours())
original.log("original " + item.get("date").getHours())

/*
All off these ALSO print out the same (i.e. 14) !!!???
*/


问:
No such method applying pointcut in Spring AOP to batch job
I'm learning Spring AOP, and decided to use it for some performance monitoring on a batch job. I want to monitor the execution times of a jdbctemplate object's .update() method within a Spring Batch ItemWriter's write() method.

The relevant parts of my pom.xml:

```<code>  <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjweaver</artifactId>
        <version>1.5.4</version>
    </dependency>
    <dependency>
        <groupId>cglib</groupId>
        <artifactId>cglib-nodep</artifactId>
        <version>3.2.5</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aspects</artifactId>
        <version>3.1.2.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aop</artifactId>
        <version>4.3.9.RELEASE</version>
    </dependency>
</code>```

My spring configuration XML file:

```<code><aop:config>
    <aop:pointcut id="writerMethods" expression="execution(* my.package.name.writers.IvrWriter.write())"/>
    <aop:advisor advice-ref="performanceMonitor" pointcut-ref="writerMethods" order="2"/>
</aop:config>
</code>```

However, I'm receiving a NoSuchMethodError that I'm having some trouble understanding how to debug:

```<code>Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.aop.support.DefaultBeanFactoryPointcutAdvisor#0': Initialization of bean failed; nested exception is java.lang.NoSuchMethodError: org.springframework.beans.factory.config.ConfigurableBeanFactory.getSingletonMutex()Ljava/lang/Object;
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:527)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    at org.springframework.aop.framework.autoproxy.BeanFactoryAdvisorRetrievalHelper.findAdvisorBeans(BeanFactoryAdvisorRetrievalHelper.java:92)
    at org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator.findCandidateAdvisors(AbstractAdvisorAutoProxyCreator.java:102)
    at org.springframework.aop.aspectj.autoproxy.AspectJAwareAdvisorAutoProxyCreator.shouldSkip(AspectJAwareAdvisorAutoProxyCreator.java:103)
    at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.postProcessBeforeInstantiation(AbstractAutoProxyCreator.java:248)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsBeforeInstantiation(AbstractAutowireCapableBeanFactory.java:880)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.resolveBeforeInstantiation(AbstractAutowireCapableBeanFactory.java:852)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:446)
    ... 15 more
Caused by: java.lang.NoSuchMethodError: org.springframework.beans.factory.config.ConfigurableBeanFactory.getSingletonMutex()Ljava/lang/Object;
    at org.springframework.aop.support.AbstractBeanFactoryPointcutAdvisor.resetAdviceMonitor(AbstractBeanFactoryPointcutAdvisor.java:81)
    at org.springframework.aop.support.AbstractBeanFactoryPointcutAdvisor.setBeanFactory(AbstractBeanFactoryPointcutAdvisor.java:76)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeAwareMethods(AbstractAutowireCapableBeanFactory.java:1475)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1443)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
    ... 27 more
</code>```

I'm not even sure whether or not this is a dependency issue with Spring AOP, a syntax error in terms of how I am writing the pointcut expression, or something else. I have followed a tutorial accessedenter link description here here on how to write pointcut expressions. Can anyone direct me in the right direction?

答:
from exception stacktrace:

NoSuchMethodError:
  org.springframework.beans.factory.config.ConfigurableBeanFactory.getSingletonMutex()Ljava/lang/Object;

you should update in your pom.xml version for  for spring aop afticat to version : 4.3.9.RELEASE . You use two different version for spting artifacts spring-aspects with 3.1.2.RELEASE and spring-aop with 4.3.9.RELEASE they are not compatible

```<code>    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aspects</artifactId>
        <version>4.3.9.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aop</artifactId>
        <version>4.3.9.RELEASE</version>
    </dependency>
</code>```

better use properties variable in pom.xml

```<code><properties>
     <spring.version>4.3.4.RELEASE</spring.version>
</properties>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>${spring.version}</version>
        </dependency>
</code>```

Body:
I'm learning Spring AOP, and decided to use it for some performance monitoring on a batch job. I want to monitor the execution times of a jdbctemplate object's .update() method within a Spring Batch ItemWriter's write() method.

The relevant parts of my pom.xml:

  <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjweaver</artifactId>
        <version>1.5.4</version>
    </dependency>
    <dependency>
        <groupId>cglib</groupId>
        <artifactId>cglib-nodep</artifactId>
        <version>3.2.5</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aspects</artifactId>
        <version>3.1.2.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aop</artifactId>
        <version>4.3.9.RELEASE</version>
    </dependency>

My spring configuration XML file:

<aop:config>
    <aop:pointcut id="writerMethods" expression="execution(* my.package.name.writers.IvrWriter.write())"/>
    <aop:advisor advice-ref="performanceMonitor" pointcut-ref="writerMethods" order="2"/>
</aop:config>

However, I'm receiving a NoSuchMethodError that I'm having some trouble understanding how to debug:

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.aop.support.DefaultBeanFactoryPointcutAdvisor#0': Initialization of bean failed; nested exception is java.lang.NoSuchMethodError: org.springframework.beans.factory.config.ConfigurableBeanFactory.getSingletonMutex()Ljava/lang/Object;
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:527)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    at org.springframework.aop.framework.autoproxy.BeanFactoryAdvisorRetrievalHelper.findAdvisorBeans(BeanFactoryAdvisorRetrievalHelper.java:92)
    at org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator.findCandidateAdvisors(AbstractAdvisorAutoProxyCreator.java:102)
    at org.springframework.aop.aspectj.autoproxy.AspectJAwareAdvisorAutoProxyCreator.shouldSkip(AspectJAwareAdvisorAutoProxyCreator.java:103)
    at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.postProcessBeforeInstantiation(AbstractAutoProxyCreator.java:248)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsBeforeInstantiation(AbstractAutowireCapableBeanFactory.java:880)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.resolveBeforeInstantiation(AbstractAutowireCapableBeanFactory.java:852)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:446)
    ... 15 more
Caused by: java.lang.NoSuchMethodError: org.springframework.beans.factory.config.ConfigurableBeanFactory.getSingletonMutex()Ljava/lang/Object;
    at org.springframework.aop.support.AbstractBeanFactoryPointcutAdvisor.resetAdviceMonitor(AbstractBeanFactoryPointcutAdvisor.java:81)
    at org.springframework.aop.support.AbstractBeanFactoryPointcutAdvisor.setBeanFactory(AbstractBeanFactoryPointcutAdvisor.java:76)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeAwareMethods(AbstractAutowireCapableBeanFactory.java:1475)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1443)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
    ... 27 more

I'm not even sure whether or not this is a dependency issue with Spring AOP, a syntax error in terms of how I am writing the pointcut expression, or something else. I have followed a tutorial accessedenter link description here here on how to write pointcut expressions. Can anyone direct me in the right direction?

Body:
from exception stacktrace:

NoSuchMethodError:
  org.springframework.beans.factory.config.ConfigurableBeanFactory.getSingletonMutex()Ljava/lang/Object;

you should update in your pom.xml version for  for spring aop afticat to version : 4.3.9.RELEASE . You use two different version for spting artifacts spring-aspects with 3.1.2.RELEASE and spring-aop with 4.3.9.RELEASE they are not compatible

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aspects</artifactId>
        <version>4.3.9.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aop</artifactId>
        <version>4.3.9.RELEASE</version>
    </dependency>

better use properties variable in pom.xml

<properties>
     <spring.version>4.3.4.RELEASE</spring.version>
</properties>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>${spring.version}</version>
        </dependency>


问:
How to merge 2 data sets using 2 common columns in each in R
I'm trying to merge two data frames based on 2 columns in each. I want to merge the Territory column and IDMate column from Data Frame 2 to Data Frame 1 based on matching ID and Year columns.

Data Frame 1:

```<code>        ID Year
     1  1 1998
     2  2 2001
     3  3 2005
     4  4 2008
</code>```

Data Frame 2:

```<code>       ID Year Territory  IDMate
    1  1 1998         A    22
    2  1 1999         B    24
    3  1 2000         C    25
    4  2 2001         D    26
    5  2 2002         E    27
    6  3 2005         F    28
    7  4 2008         G    29
</code>```

Goal is to get this:

```<code>       ID Year Territory  IDMate
    1  1 1998         A    22
    2  2 2001         D    26
    3  3 2005         F    28
    4  4 2008         G    29
</code>```

答:
common <- intersect(data.frame1$col, data.frame2$col)
data.frame2[common,]

Hopefully, this will get you what you want

Body:
I'm trying to merge two data frames based on 2 columns in each. I want to merge the Territory column and IDMate column from Data Frame 2 to Data Frame 1 based on matching ID and Year columns.

Data Frame 1:

        ID Year
     1  1 1998
     2  2 2001
     3  3 2005
     4  4 2008

Data Frame 2:

       ID Year Territory  IDMate
    1  1 1998         A    22
    2  1 1999         B    24
    3  1 2000         C    25
    4  2 2001         D    26
    5  2 2002         E    27
    6  3 2005         F    28
    7  4 2008         G    29

Goal is to get this:

       ID Year Territory  IDMate
    1  1 1998         A    22
    2  2 2001         D    26
    3  3 2005         F    28
    4  4 2008         G    29


问:
How to Get Mac Desktop size
How do I discover the size of the Desktop (or screen size) of the Mac?</p>

答:
For the screen size use -[NSScreen frame] on an instance received through e.g. +[NSScreen mainScreen] or -[NSWindow screen].

To get the visible part without the dock and menu bar, use -[NSScreen visibleFrame].

Keep in mind that the full desktop can stretch over multiple screens.

Title: How to Get Mac Desktop size


问:
How to use variables and OR cunjunctions in SQL statement in Python?
I have a list of Ids in a list named res that I want to use line by line as WHERE conditions on a SQL query before saving the results in an array :

```<code>                              ids
grupos
0       [160, 161, 365, 386, 471]
1                      [296, 306]
</code>```

Here is what I tried to insert it in a SQL query :

```<code>listado = [None]*len(res)
# We store the hashtags that describes the best the groups
# We iterate on the people of a group to construct the WHERE condition
print "res : ", res
for i in (0,len(res)):

conn = psycopg2.connect(**params)
cur = conn.cursor()

listado = [None]*len(res)
for i in (0,len(res)):
    print "res[i:p] : ", res.iloc[i]['ids']
    cur.execute("""SELECT COUNT(swipe.eclipse_id), subscriber_hashtag.hashtag_id  FROM subscriber_hashtag
    -- join para que las publicidades/eclipses que gusta un usarios estan vinculadas con las de la tabla de correspondencia con los hashtag
    INNER JOIN eclipse_hashtag ON eclipse_hashtag.hashtag_id = subscriber_hashtag.hashtag_id
    -- join para que los usarios  estan vinculados con los de la tabla de correspondencia con los hashtag
    LEFT OUTER JOIN swipe ON subscriber_hashtag.subscriber_id = swipe.subscriber_id
    -- recobremos los "me gusta"
    WHERE subscriber_hastag.subscriber_id in (%s)
    GROUP BY subscriber_hashtag.hashtag_id
        ORDER BY COUNT(swipe.eclipse_id) DESC;""",(res.iloc[i]['ids']))

    n = cur.fetchall()
    listado[i] = [{"count": elem[0], "eclipse_id": elem[1]} for elem in n]
</code>```

Data for a reproducible example

Providing the further data informations :

```<code>subscriber_id hashtag_id
160           345
160           347
161           345
160           334
161           347
306           325
296           362
306           324
296           326
161           322
160           322
</code>```

The output should, here, be like :

```<code>{0:[324,1],[325,1],[326,1],[362,1], 1 : [345,2],[347,2],[334,1]}
</code>```

Current error message

ERROR: An unexpected error occurred while tokenizing input
The following traceback may be corrupted or invalid
The error message is: ('EOF in multi-line string', (1, 50))

```<code>---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-44-f7c3c5b81303> in <module>()
     39         WHERE subscriber_hastag.subscriber_id in (%s)
     40         GROUP BY subscriber_hashtag.hashtag_id
---> 41             ORDER BY COUNT(swipe.eclipse_id) DESC;""",(res.iloc[i]['ids']))
     42
     43         n = cur.fetchall()
</code>```

TypeError: not all arguments converted during string formatting

答:
Have a look at tuples adaptation:

Python tuples are converted into a syntax suitable for the SQL IN operator and to represent a composite type:

Pass ids as a tuple query argument, so your argument to execute is a 1-tuple of tuple of ids, and drop the manual parentheses around %s. At the moment your (res.iloc[i]['ids']) is nothing but a sequence expression in redundant parentheses, so execute() uses it as the argument sequence, which causes your TypeError exception; your argument sequence has more arguments than the query has placeholders.

Try (tuple(res.iloc[i]['ids']),) instead. Note the comma, it is a very common error to omit it. All in all:

```<code>cur.execute("""SELECT COUNT(swipe.eclipse_id),
subscriber_hashtag.hashtag_id
FROM subscriber_hashtag
INNER JOIN eclipse_hashtag ON eclipse_hashtag.hashtag_id = subscriber_hashtag.hashtag_id
LEFT OUTER JOIN swipe ON subscriber_hashtag.subscriber_id = swipe.subscriber_id
WHERE subscriber_hashtag.subscriber_id in %s
GROUP BY subscriber_hashtag.hashtag_id
    ORDER BY COUNT(swipe.eclipse_id) DESC;""",
(tuple(res.iloc[i]['ids']),))
</code>```

Your for-loop is a bit strange, since you iterate over a 2-tuple (0, len(res)).  Perhaps you meant range(len(res)). You could also just iterate over the Pandas Series:

```<code>for i, ids in enumerate(res['ids']):
    ...
    cur.execute(..., (tuple(ids),))
</code>```

Body:
I have a list of Ids in a list named res that I want to use line by line as WHERE conditions on a SQL query before saving the results in an array :

                              ids
grupos
0       [160, 161, 365, 386, 471]
1                      [296, 306]

Here is what I tried to insert it in a SQL query :

listado = [None]*len(res)
# We store the hashtags that describes the best the groups
# We iterate on the people of a group to construct the WHERE condition
print "res : ", res
for i in (0,len(res)):

conn = psycopg2.connect(**params)
cur = conn.cursor()

listado = [None]*len(res)
for i in (0,len(res)):
    print "res[i:p] : ", res.iloc[i]['ids']
    cur.execute("""SELECT COUNT(swipe.eclipse_id), subscriber_hashtag.hashtag_id  FROM subscriber_hashtag
    -- join para que las publicidades/eclipses que gusta un usarios estan vinculadas con las de la tabla de correspondencia con los hashtag
    INNER JOIN eclipse_hashtag ON eclipse_hashtag.hashtag_id = subscriber_hashtag.hashtag_id
    -- join para que los usarios  estan vinculados con los de la tabla de correspondencia con los hashtag
    LEFT OUTER JOIN swipe ON subscriber_hashtag.subscriber_id = swipe.subscriber_id
    -- recobremos los "me gusta"
    WHERE subscriber_hastag.subscriber_id in (%s)
    GROUP BY subscriber_hashtag.hashtag_id
        ORDER BY COUNT(swipe.eclipse_id) DESC;""",(res.iloc[i]['ids']))

    n = cur.fetchall()
    listado[i] = [{"count": elem[0], "eclipse_id": elem[1]} for elem in n]

Data for a reproducible example

Providing the further data informations :

subscriber_id hashtag_id
160           345
160           347
161           345
160           334
161           347
306           325
296           362
306           324
296           326
161           322
160           322

The output should, here, be like :

{0:[324,1],[325,1],[326,1],[362,1], 1 : [345,2],[347,2],[334,1]}

Current error message

ERROR: An unexpected error occurred while tokenizing input
The following traceback may be corrupted or invalid
The error message is: ('EOF in multi-line string', (1, 50))

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-44-f7c3c5b81303> in <module>()
     39         WHERE subscriber_hastag.subscriber_id in (%s)
     40         GROUP BY subscriber_hashtag.hashtag_id
---> 41             ORDER BY COUNT(swipe.eclipse_id) DESC;""",(res.iloc[i]['ids']))
     42
     43         n = cur.fetchall()

TypeError: not all arguments converted during string formatting

Body:
Have a look at tuples adaptation:

Python tuples are converted into a syntax suitable for the SQL IN operator and to represent a composite type:

Pass ids as a tuple query argument, so your argument to execute is a 1-tuple of tuple of ids, and drop the manual parentheses around %s. At the moment your (res.iloc[i]['ids']) is nothing but a sequence expression in redundant parentheses, so execute() uses it as the argument sequence, which causes your TypeError exception; your argument sequence has more arguments than the query has placeholders.

Try (tuple(res.iloc[i]['ids']),) instead. Note the comma, it is a very common error to omit it. All in all:

cur.execute("""SELECT COUNT(swipe.eclipse_id),
subscriber_hashtag.hashtag_id
FROM subscriber_hashtag
INNER JOIN eclipse_hashtag ON eclipse_hashtag.hashtag_id = subscriber_hashtag.hashtag_id
LEFT OUTER JOIN swipe ON subscriber_hashtag.subscriber_id = swipe.subscriber_id
WHERE subscriber_hashtag.subscriber_id in %s
GROUP BY subscriber_hashtag.hashtag_id
    ORDER BY COUNT(swipe.eclipse_id) DESC;""",
(tuple(res.iloc[i]['ids']),))

Your for-loop is a bit strange, since you iterate over a 2-tuple (0, len(res)).  Perhaps you meant range(len(res)). You could also just iterate over the Pandas Series:

for i, ids in enumerate(res['ids']):
    ...
    cur.execute(..., (tuple(ids),))


问:
MVC, Browser return error: Website redirected you too many times When I browse a file on a specific restricted folder by web.config file
I want restrict access of anonymous users to Music folder (in the root of my website). Then I put this code in web.config file in the Music folder:

```<code><?xml version="1.0"?>
<configuration>
    <system.web>
        <authorization>
            <deny users="?" />
        </authorization>
    </system.web>
</configuration>
</code>```

I tested this one too:

```<code><allow users="*" />
<deny users="?" />
</code>```

Also the web.config file of the website has the bellow config:

```<code><authentication mode="Forms">
      <forms loginUrl="~/account/login" timeout="2880" />
</authentication>

<modules runAllManagedModulesForAllRequests="false">
      <remove name="FormsAuthenticationModule" />
      <add name="FormsAuthenticationModule" type="System.Web.Security.FormsAuthenticationModule" />

      <remove name="UrlAuthorization" />
      <add name="UrlAuthorization" type="System.Web.Security.UrlAuthorizationModule" />
</modules>

<rule name="Redirect to https" enabled="true" stopProcessing="true">
      <match url=".*" />
      <conditions>
        <add input="{HTTPS}" pattern="off" />
      </conditions>
      <action type="Redirect" url="https://{HTTP_HOST}/{R:0}" appendQueryString="false" redirectType="Permanent" />
</rule>

<location path="~/Music">
    <system.webServer>
      <handlers accessPolicy="Read" />
    </system.webServer>
</location>
</code>```

And this code is part of the startup.cs:

```<code>var loginPath= new UrlHelper(HttpContext.Current.Request.RequestContext).Action(MVC.Account.Login());

appBuilder.UseCookieAuthentication(new CookieAuthenticationOptions
{
    AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
    LoginPath = new PathString(loginPath),
    // Other Codes
}
</code>```

Now, when i browse to example.com/music/1.mp3 it return me to /account/login but when i login it show me the following error from the browser:

WebsiteName redirected you too many times.

net::ERR_TOO_MANY_REDIRECTS

Also if i change the authentication mode to none, it show me a prompt like it (that i wont it!):

Note1: I cleared the browser cookies but no success.

What is the reason of the redirect loop?

How should do this work as safe without redirect loop?

Update:

My project has a Return to Url mechanism in the login page. So when i browse /Music/1.mp3 it redirect me to /account/login?ReturnUrl=/Music/1.mp3and after login base this mechanism it redirect me to /Music/1.mp3 automatically. I think in this step I have not enough access permission to open /Music/1.mp3 again! And it redirect me to login page again and this loop continue until i get ERR_T_OOMANY_REDIRECTS error.

答:
Even if you set "authenticate mode" to none, as your web.config has a required login <deny users="?" />, then the request will send a login request to the browser, then it will ask you by the browser login form.

What is the reason of the redirect loop?

This error may occur for a lot of reasons. The most common is that login is redirecting to a folder that user cannot access even once it is logged-in.

For instance, Your music folder web.config is denying a logged user. Then it will redirect from the folder to the login, then login will authenticate, then it will send the user back to the folder. Once the folder is denying all users, then it will send back to login again, and bingo, here is your loop.

you must make sure that you're not denying logged-in users.

How should do this work as safe without redirect loop?

After redirect from login the server will deliver the .mp3 file required.

Please note that when using MVC you must be sure that the folders that you have in your project not always match the path that user type in URL. For MVC Core application those contents must be on wwwroot folder.

Body:
I want restrict access of anonymous users to Music folder (in the root of my website). Then I put this code in web.config file in the Music folder:

<?xml version="1.0"?>
<configuration>
    <system.web>
        <authorization>
            <deny users="?" />
        </authorization>
    </system.web>
</configuration>

I tested this one too:

<allow users="*" />
<deny users="?" />

Also the web.config file of the website has the bellow config:

<authentication mode="Forms">
      <forms loginUrl="~/account/login" timeout="2880" />
</authentication>

<modules runAllManagedModulesForAllRequests="false">
      <remove name="FormsAuthenticationModule" />
      <add name="FormsAuthenticationModule" type="System.Web.Security.FormsAuthenticationModule" />

      <remove name="UrlAuthorization" />
      <add name="UrlAuthorization" type="System.Web.Security.UrlAuthorizationModule" />
</modules>

<rule name="Redirect to https" enabled="true" stopProcessing="true">
      <match url=".*" />
      <conditions>
        <add input="{HTTPS}" pattern="off" />
      </conditions>
      <action type="Redirect" url="https://{HTTP_HOST}/{R:0}" appendQueryString="false" redirectType="Permanent" />
</rule>

<location path="~/Music">
    <system.webServer>
      <handlers accessPolicy="Read" />
    </system.webServer>
</location>

And this code is part of the startup.cs:

var loginPath= new UrlHelper(HttpContext.Current.Request.RequestContext).Action(MVC.Account.Login());

appBuilder.UseCookieAuthentication(new CookieAuthenticationOptions
{
    AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
    LoginPath = new PathString(loginPath),
    // Other Codes
}

Now, when i browse to example.com/music/1.mp3 it return me to /account/login but when i login it show me the following error from the browser:

WebsiteName redirected you too many times.

net::ERR_TOO_MANY_REDIRECTS

Also if i change the authentication mode to none, it show me a prompt like it (that i wont it!):

Note1: I cleared the browser cookies but no success.

What is the reason of the redirect loop?

How should do this work as safe without redirect loop?

Update:

My project has a Return to Url mechanism in the login page. So when i browse /Music/1.mp3 it redirect me to /account/login?ReturnUrl=/Music/1.mp3and after login base this mechanism it redirect me to /Music/1.mp3 automatically. I think in this step I have not enough access permission to open /Music/1.mp3 again! And it redirect me to login page again and this loop continue until i get ERR_T_OOMANY_REDIRECTS error.


问:
CSS Animation on multiple properties
I would like to animate an element's bottom position and opacity simultaneously using CSS keyframes.

My element opacity is animating but the bottom position does not.

```<code>.custom-fade-down{
-webkit-animation: 23s ease 0s normal forwards 1 custom-down;
-moz-animation: 23s ease 0s normal forwards 1 custom-down;
    animation: 23s ease 0s normal forwards 1 custom-down;
}

@keyframes custom-down {
    from {
        opacity: 0;
        bottom: 10px;
    }

    to {
        opacity: 1;
        bottom: 1px;
    }
}
</code>```

答:
Your solution is close. Add a position: relative; to the .custom-fade-down class so the bottom prop takes effect.

$('div').addClass('custom-fade-down');```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.custom-fade-down {
  width: 100px;
  height: 100px;
  bottom: -100px;
  background-color: black;
  -webkit-animation: 23s ease 0s normal forwards 1 custom-down;
  -moz-animation: 23s ease 0s normal forwards 1 custom-down;
  animation: 23s ease 0s normal forwards 1 custom-down;
}

@keyframes custom-down {
  from {
    opacity: 0;
    bottom: -100px;
  }
  to {
    opacity: 1;
    bottom: 0px;
  }
}</code>```

```

Title: CSS Animation on multiple properties

Body:
I would like to animate an element's bottom position and opacity simultaneously using CSS keyframes.

My element opacity is animating but the bottom position does not.

.custom-fade-down{
-webkit-animation: 23s ease 0s normal forwards 1 custom-down;
-moz-animation: 23s ease 0s normal forwards 1 custom-down;
    animation: 23s ease 0s normal forwards 1 custom-down;
}

@keyframes custom-down {
    from {
        opacity: 0;
        bottom: 10px;
    }

    to {
        opacity: 1;
        bottom: 1px;
    }
}

Body:
Your solution is close. Add a position: relative; to the .custom-fade-down class so the bottom prop takes effect.

$('div').addClass('custom-fade-down');

.custom-fade-down {
  width: 100px;
  height: 100px;
  bottom: -100px;
  background-color: black;
  -webkit-animation: 23s ease 0s normal forwards 1 custom-down;
  -moz-animation: 23s ease 0s normal forwards 1 custom-down;
  animation: 23s ease 0s normal forwards 1 custom-down;
}

@keyframes custom-down {
  from {
    opacity: 0;
    bottom: -100px;
  }
  to {
    opacity: 1;
    bottom: 0px;
  }
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="position: relative;"></div>


问:
Python sort a sublist by object attribute
I know how to sort by an attribute from this question where the top answer suggests doing:

```<code>someList.sort(key=lambda x: x.someAttr, reverse=True)
</code>```

and I have seen suggestions for sorting a sublist which suggest to do something like:

```<code>someList[i:j] = sorted(somelist[i:j])
</code>```

but how can I sort a sublist by an attribute? I tried:

```<code>someList[i:j].sort(key=lambda x: x.someAttr, reverse=True)
</code>```

but this did not work. Any suggestions?

答:
The reason your last method didn't work is because you're trying to sort the sublist in-place. When you do:

```<code>L[1:-1].sort(...)
</code>```

You're basically creating a copy of the sublist L[1:-1]. But because you sorted the copy in place, no reference was ever made to copy, and the new sorted list was lost and later garbage collected.

Instead, you need to reassign the new sorted value of the sublist, to the old sublist. eg:

```<code>>>> l = [1, 3, 2, 4, 5]
>>> l[1:-1].sort() # Reference to sorted sublist is never saved
>>> l # List unchanged
[1, 3, 2, 4, 5]
>>> l[1:-1] = sorted(l[1:-1]) # Reassign the sorted sublist to the old one
>>> l # List is modfied
[1, 2, 3, 4, 5]
</code>```

Here's an example pertaining more to your specific case:

```<code>>>> class UserId:
...     def __init__(self, id_number):
...         self.id_number = id_number
...     def __repr__(self):
...         return 'UserId(id_number={})'.format(self.id_number)
...
>>> user_ids = [UserId(1), UserId(3), UserId(4), UserId(2), UserId(5)]
>>> user_ids[1:-1] = sorted(user_ids[1:-1], key=lambda u: u.id_number, reverse=True)
>>> user_ids
[UserId(id_number=1), UserId(id_number=4), UserId(id_number=3), UserId(id_number=2), UserId(id_number=5)]
</code>```

Body:
I know how to sort by an attribute from this question where the top answer suggests doing:

someList.sort(key=lambda x: x.someAttr, reverse=True)

and I have seen suggestions for sorting a sublist which suggest to do something like:

someList[i:j] = sorted(somelist[i:j])

but how can I sort a sublist by an attribute? I tried:

someList[i:j].sort(key=lambda x: x.someAttr, reverse=True)

but this did not work. Any suggestions?

Body:
The reason your last method didn't work is because you're trying to sort the sublist in-place. When you do:

L[1:-1].sort(...)

You're basically creating a copy of the sublist L[1:-1]. But because you sorted the copy in place, no reference was ever made to copy, and the new sorted list was lost and later garbage collected.

Instead, you need to reassign the new sorted value of the sublist, to the old sublist. eg:

>>> l = [1, 3, 2, 4, 5]
>>> l[1:-1].sort() # Reference to sorted sublist is never saved
>>> l # List unchanged
[1, 3, 2, 4, 5]
>>> l[1:-1] = sorted(l[1:-1]) # Reassign the sorted sublist to the old one
>>> l # List is modfied
[1, 2, 3, 4, 5]

Here's an example pertaining more to your specific case:

>>> class UserId:
...     def __init__(self, id_number):
...         self.id_number = id_number
...     def __repr__(self):
...         return 'UserId(id_number={})'.format(self.id_number)
...
>>> user_ids = [UserId(1), UserId(3), UserId(4), UserId(2), UserId(5)]
>>> user_ids[1:-1] = sorted(user_ids[1:-1], key=lambda u: u.id_number, reverse=True)
>>> user_ids
[UserId(id_number=1), UserId(id_number=4), UserId(id_number=3), UserId(id_number=2), UserId(id_number=5)]


问:
JQuery UI sortables display sort order
I cannot find in the JQUI documentation how to display the sort order.  What I want to do is display the sort order i.e. 1,2,3, 4, etc as a visual reference for a user.  The sort order obviously updates on a sort, just not sure how to find/get the sort order  - Oh I'm not sorting
's

答:
You can do it youself, just recalculate order on each stop event of sortable element: </p>

```<code>...
 stop: function (event, ui) {
                setOrder();
            },
...
function setOrder() {
 $("#liContainerId").each(function (index,li) {
  // set display order here
});
}
</code>```

Title: JQuery UI sortables display sort order

Body:
You can do it youself, just recalculate order on each stop event of sortable element:

...
 stop: function (event, ui) {
                setOrder();
            },
...
function setOrder() {
 $("#liContainerId").each(function (index,li) {
  // set display order here
});
}


答:
You can use left_join from dplyr:

```<code>library(dplyr)
res <- left_join(df1, df2, by = c("ID", "Year"))

#  ID Year Territory IDMate
#   1 1998         A     22
#   2 2001         D     26
#   3 2005         F     28
#   4 2008         G     29
</code>```

Title: How to merge 2 data sets using 2 common columns in each in R

Body:
You can use left_join from dplyr:

library(dplyr)
res <- left_join(df1, df2, by = c("ID", "Year"))

#  ID Year Territory IDMate
#   1 1998         A     22
#   2 2001         D     26
#   3 2005         F     28
#   4 2008         G     29


问:
How can I orchestrate state change in my React Native page?
I wish to have a number (say 10) different 'pages' on a React Native screen.
The use case is a workflow or flowchart. Each page can send you to multiple different places.

I want the final thing to be flexible enough that I don't want to simply write the 10 or so .js pages and link them together.

My cunning plan was to put a state object in the 'state' thing that React provides, I am now stumped as to how to update this object.

This is my current code. renderif is a bit of magic that hides the following layout if it is passed false

The current behaviour is it shows 'page one' only. when I press the button I see a blank screen.

What basic javascript errors am I making? and how have I over complexified this for myself :)

```<code>import React, {Component} from "react";
import {StyleSheet, Text, View, ScrollView, Image, Button} from "react-native";
import {Font, AppLoading, WebBrowser} from "expo";
import {Actions} from "react-native-router-flux";
import styles from "./Styles";
import renderif from "./RenderIf";

class pageToShow {
  constructor() {
    this.GoToPageOne();
  }
  GoToPageOne() {
    this.pageOne = true;
    this.pageTwo = false;
    return this;
  }
  GoToPageTwo() {
    this.pageOne = false;
    this.pageTwo = true;
    return this;
  }
}
export default class FlipBook extends Component {
  constructor(props) {
    super(props);
    this.state = {show: new pageToShow()};
  }
  render() {
    return (
      <View>
        {renderif(this.state.show.pageOne)(
          <ScrollView style={styles.background}>

            <Text style={styles.header}>
              <Text>{"Page one"}</Text>
            </Text>
            <Text style={styles.normal}>
              This is page one
            </Text>
            <Button
              title="This is a button to two"
              onPress={() => this.setState({show: this.state.show.GoToPageTwo})}
            />
          </ScrollView>
        )}
        {renderif(this.state.show.pageTwo)(
          <ScrollView style={styles.background}>
            <Text style={styles.header}>
              <Text>{"Page two"}</Text>
            </Text>
            <Text style={styles.normal}>
              This is page two
            </Text>
            <Button
              title="This is a button to one"
              onPress={() => this.setState({show: this.state.show.GoToPageOne})}
            />
          </ScrollView>
        )}
      </View>
    );
  }
}
</code>```

答:
Hmm i think you're making this way more complicated than it should be. For one you can use a navigation library to navigate between the pages, but if you want everything to be handled by state you could do something like this. *Also you could use 'case' to handle conditional rendering too:</p>

```<code>export default class FlipBook extends Component {
  constructor(props) {
    super(props);
    this.state = {show: 'pageOne' };
  }
  render() {
    return (
      <View>
        {this.state.show === 'pageOne' ? (
          <ScrollView style={styles.background}>
            <Text style={styles.header}>
              <Text>{"Page one"}</Text>
            </Text>
            <Text style={styles.normal}>
              This is page one
            </Text>
            <Button
              title="This is a button to two"
              onPress={() => this.setState({show: 'pageTwo' })}
            />
          </ScrollView>
        ) : null}
        {this.state.show === 'pageTwo' ? (
          <ScrollView style={styles.background}>
            <Text style={styles.header}>
              <Text>{"Page two"}</Text>
            </Text>
            <Text style={styles.normal}>
              This is page two
            </Text>
            <Button
              title="This is a button to one"
              onPress={() => this.setState({show: 'pageOne' })}
            />
          </ScrollView>
        ) : null}
      </View>
    );
  }
}
</code>```

Body:
I wish to have a number (say 10) different 'pages' on a React Native screen.
The use case is a workflow or flowchart. Each page can send you to multiple different places.

I want the final thing to be flexible enough that I don't want to simply write the 10 or so .js pages and link them together.

My cunning plan was to put a state object in the 'state' thing that React provides, I am now stumped as to how to update this object.

This is my current code. renderif is a bit of magic that hides the following layout if it is passed false

The current behaviour is it shows 'page one' only. when I press the button I see a blank screen.

What basic javascript errors am I making? and how have I over complexified this for myself :)

import React, {Component} from "react";
import {StyleSheet, Text, View, ScrollView, Image, Button} from "react-native";
import {Font, AppLoading, WebBrowser} from "expo";
import {Actions} from "react-native-router-flux";
import styles from "./Styles";
import renderif from "./RenderIf";

class pageToShow {
  constructor() {
    this.GoToPageOne();
  }
  GoToPageOne() {
    this.pageOne = true;
    this.pageTwo = false;
    return this;
  }
  GoToPageTwo() {
    this.pageOne = false;
    this.pageTwo = true;
    return this;
  }
}
export default class FlipBook extends Component {
  constructor(props) {
    super(props);
    this.state = {show: new pageToShow()};
  }
  render() {
    return (
      <View>
        {renderif(this.state.show.pageOne)(
          <ScrollView style={styles.background}>

            <Text style={styles.header}>
              <Text>{"Page one"}</Text>
            </Text>
            <Text style={styles.normal}>
              This is page one
            </Text>
            <Button
              title="This is a button to two"
              onPress={() => this.setState({show: this.state.show.GoToPageTwo})}
            />
          </ScrollView>
        )}
        {renderif(this.state.show.pageTwo)(
          <ScrollView style={styles.background}>
            <Text style={styles.header}>
              <Text>{"Page two"}</Text>
            </Text>
            <Text style={styles.normal}>
              This is page two
            </Text>
            <Button
              title="This is a button to one"
              onPress={() => this.setState({show: this.state.show.GoToPageOne})}
            />
          </ScrollView>
        )}
      </View>
    );
  }
}

Body:
Hmm i think you're making this way more complicated than it should be. For one you can use a navigation library to navigate between the pages, but if you want everything to be handled by state you could do something like this. *Also you could use 'case' to handle conditional rendering too:

export default class FlipBook extends Component {
  constructor(props) {
    super(props);
    this.state = {show: 'pageOne' };
  }
  render() {
    return (
      <View>
        {this.state.show === 'pageOne' ? (
          <ScrollView style={styles.background}>
            <Text style={styles.header}>
              <Text>{"Page one"}</Text>
            </Text>
            <Text style={styles.normal}>
              This is page one
            </Text>
            <Button
              title="This is a button to two"
              onPress={() => this.setState({show: 'pageTwo' })}
            />
          </ScrollView>
        ) : null}
        {this.state.show === 'pageTwo' ? (
          <ScrollView style={styles.background}>
            <Text style={styles.header}>
              <Text>{"Page two"}</Text>
            </Text>
            <Text style={styles.normal}>
              This is page two
            </Text>
            <Button
              title="This is a button to one"
              onPress={() => this.setState({show: 'pageOne' })}
            />
          </ScrollView>
        ) : null}
      </View>
    );
  }
}


问:
How to handle exceptions in async void methods with NUnit
I have some tests that run through the workflow of my WPF program. I do the normal MVVM approach which is binding buttons on the view to commands on the view model, which then handles the event. The way my tests test my workflow is then by directly executing the commands on the view model. This roughly translates to look something like:

```<code>[Test]
public void Test()
{
    var vm = new ViewModel();
    vm.AcceptCommand.Execute();
    Assert.IsTrue(stuff);
}
</code>```

All of this works well, except for the fact that the code in the viewmodel that handles the command ends up being an async void method since this just becomes an event handler. If an exception gets thrown here, nunit does not show a failing test because it doesn't "see" this exception in the background thread.

My question is: is there a way to get NUnit to handle these background exceptions?

答:
If it's possible then refactor your method into 2 methods. First one should return Task and it's the one that is testable. The other should call and await first method.
This hint is taken from Concurrency in C# Cookbook by Stephen Cleary. This is the preferred method. This book also mentions AsyncContext class from AsyncEx library which allows to test async void methods.

```<code>AsyncContext.Run(() =>
 {
     // put your code here
 })
</code>```

Quote from the same book: The AsyncContext type will wait until all asynchronous operations complete (including async void methods) and will propagate exceptions that they raise.

Take a look here for similar discussion: Await a Async Void method call for unit testing

Body:
I have some tests that run through the workflow of my WPF program. I do the normal MVVM approach which is binding buttons on the view to commands on the view model, which then handles the event. The way my tests test my workflow is then by directly executing the commands on the view model. This roughly translates to look something like:

[Test]
public void Test()
{
    var vm = new ViewModel();
    vm.AcceptCommand.Execute();
    Assert.IsTrue(stuff);
}

All of this works well, except for the fact that the code in the viewmodel that handles the command ends up being an async void method since this just becomes an event handler. If an exception gets thrown here, nunit does not show a failing test because it doesn't "see" this exception in the background thread.

My question is: is there a way to get NUnit to handle these background exceptions?

Body:
If it's possible then refactor your method into 2 methods. First one should return Task and it's the one that is testable. The other should call and await first method.
This hint is taken from Concurrency in C# Cookbook by Stephen Cleary. This is the preferred method. This book also mentions AsyncContext class from AsyncEx library which allows to test async void methods.

AsyncContext.Run(() =>
 {
     // put your code here
 })

Quote from the same book: The AsyncContext type will wait until all asynchronous operations complete (including async void methods) and will propagate exceptions that they raise.

Take a look here for similar discussion: Await a Async Void method call for unit testing


问:
Package not found on virtualenv - No module named "mypack"
Hi !

I've tried to use a package I've created (named mypackage) on my main program (named collector). mypackage is defined with the setup.py below:

```<code>name = "mypackage"
[...]
packages = find_packages(),
include_package_data = True,
exclude_package_data = { '': ['README.md'] }
[...]
entry_points = {
    'console_scripts': [
        'my-package=mypack.mypack:main'
    ]
},
</code>```

I want to use a little program present this package, which will normally be called as below on collector:

```<code>from mypack.common.prog import mylittleprogram
</code>```

I've tried to install mypackage on a virtualenv, and then (re)installed my main program. Then I executed it, and there is the error I have:

```<code>Traceback (most recent call last):
from project.common.collector import collectArt
File "/root/project/lib/python3.5/site-packages/collector-0.1-py3.5.egg/project/common/collector.py", line 7, in <module>
ImportError: No module named 'mypack'
</code>```

Also, when the virtualenv is activated, I've just tried to launch the entry-point named my-package:

```<code>Traceback (most recent call last):
File "/root/project/bin/my-package", line 11, in <module>
load_entry_point('mypackage==0.1.1', 'console_scripts', 'my-package')()
File "/root/project/lib/python3.5/site-packages/pkg_resources/__init__.py", line 560, in load_entry_point
return get_distribution(dist).load_entry_point(group, name)
File "/root/project/lib/python3.5/site-packages/pkg_resources/__init__.py", line 2648, in load_entry_point
return ep.load()
File "/root/project/lib/python3.5/site-packages/pkg_resources/__init__.py", line 2302, in load
return self.resolve()
File "/root/project/lib/python3.5/site-packages/pkg_resources/__init__.py", line 2308, in resolve
module = __import__(self.module_name, fromlist=['__name__'], level=0)
ImportError: No module named 'mypack'
</code>```

Note 1: I precise that I have the __init__.py on each folder of my package.

Note 2: the virtualenv folders are on the same folder as my main program.

How do I use mylittleprogram present on mypackage on my collector main program with virtualenv ? Did I made something wrong ?

Thank you :)

答:
There is the issue, I had to install my package via the following command:

```<code>python setup.py develop
</code>```

And then the package is recognized. This command has to be executed when the virtualenv is activated, and be executed on the directory of the package.

Hope this will help someone in the future !

Body:
Hi !

I've tried to use a package I've created (named mypackage) on my main program (named collector). mypackage is defined with the setup.py below:

name = "mypackage"
[...]
packages = find_packages(),
include_package_data = True,
exclude_package_data = { '': ['README.md'] }
[...]
entry_points = {
    'console_scripts': [
        'my-package=mypack.mypack:main'
    ]
},

I want to use a little program present this package, which will normally be called as below on collector:

from mypack.common.prog import mylittleprogram

I've tried to install mypackage on a virtualenv, and then (re)installed my main program. Then I executed it, and there is the error I have:

Traceback (most recent call last):
from project.common.collector import collectArt
File "/root/project/lib/python3.5/site-packages/collector-0.1-py3.5.egg/project/common/collector.py", line 7, in <module>
ImportError: No module named 'mypack'

Also, when the virtualenv is activated, I've just tried to launch the entry-point named my-package:

Traceback (most recent call last):
File "/root/project/bin/my-package", line 11, in <module>
load_entry_point('mypackage==0.1.1', 'console_scripts', 'my-package')()
File "/root/project/lib/python3.5/site-packages/pkg_resources/__init__.py", line 560, in load_entry_point
return get_distribution(dist).load_entry_point(group, name)
File "/root/project/lib/python3.5/site-packages/pkg_resources/__init__.py", line 2648, in load_entry_point
return ep.load()
File "/root/project/lib/python3.5/site-packages/pkg_resources/__init__.py", line 2302, in load
return self.resolve()
File "/root/project/lib/python3.5/site-packages/pkg_resources/__init__.py", line 2308, in resolve
module = __import__(self.module_name, fromlist=['__name__'], level=0)
ImportError: No module named 'mypack'

Note 1: I precise that I have the __init__.py on each folder of my package.

Note 2: the virtualenv folders are on the same folder as my main program.

How do I use mylittleprogram present on mypackage on my collector main program with virtualenv ? Did I made something wrong ?

Thank you :)

Body:
There is the issue, I had to install my package via the following command:

python setup.py develop

And then the package is recognized. This command has to be executed when the virtualenv is activated, and be executed on the directory of the package.

Hope this will help someone in the future !


问:
How do I fix this parameter error when running game using unity game engine?
Hi everyone this is my first Q.

I get this error on the console tab when I run the game.

```<code>Parameter 'speed' does not exist.
</code>```

UnityEngine.Animator:SetFloat(String, Single)
PlayerMovement:FixedUpdate() (at Assets/Scripts/PlayerMovement.cs:30)

Could anyone please help me find the root of the problem please?

Thanks =)

Here is my code

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerMovement : MonoBehaviour {

    private Animator playerAnimator;
    private float moveHorizontal;
    private float moveVertical;
    private Vector3 movement;

    // Use this for initialization
    void Start () {
        playerAnimator = GetComponent<Animator>();
    }

    // Update is called once per frame
    void Update () {
        moveHorizontal = Input.GetAxisRaw ("Horizontal");
        moveVertical = Input.GetAxisRaw ("Vertical");

        movement = new Vector3 (moveHorizontal, 0.0f, moveVertical);
    }

    void FixedUpdate () {
        if (movement != Vector3.zero) {
            playerAnimator.SetFloat ("speed", 3f);
        } else {
            playerAnimator.SetFloat ("speed", 0f);
        }
    }

}
```

答:
Noob mistake!  "speed" should be capitalized. I should have "Speed", but have typed "speed".

Just incase anyone else has this problem...

Body:
Hi everyone this is my first Q.

I get this error on the console tab when I run the game.

Parameter 'speed' does not exist.

UnityEngine.Animator:SetFloat(String, Single)
PlayerMovement:FixedUpdate() (at Assets/Scripts/PlayerMovement.cs:30)

Could anyone please help me find the root of the problem please?

Thanks =)

Here is my code

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerMovement : MonoBehaviour {

    private Animator playerAnimator;
    private float moveHorizontal;
    private float moveVertical;
    private Vector3 movement;

    // Use this for initialization
    void Start () {
        playerAnimator = GetComponent<Animator>();
    }

    // Update is called once per frame
    void Update () {
        moveHorizontal = Input.GetAxisRaw ("Horizontal");
        moveVertical = Input.GetAxisRaw ("Vertical");

        movement = new Vector3 (moveHorizontal, 0.0f, moveVertical);
    }

    void FixedUpdate () {
        if (movement != Vector3.zero) {
            playerAnimator.SetFloat ("speed", 3f);
        } else {
            playerAnimator.SetFloat ("speed", 0f);
        }
    }

}