问:
Not able to access the value in one method in other
I would like to insert the value here as to send the JSON to backend but unable to get it.

```<code>var generateSearchObject = function() {
    var searchObj = {
        "fileName": change, // Here the fileName should be "Change Data"
        "tabType": text.toUpperCase(),
        "offset": offValue,
    };
    return searchObj;
};
var renderCrumbs = function(breadCrumbs, state, node) {
    var change = "Change Data";
}
</code>```

Please help!

答:
First of all renderCrumbs: function(breadCrumbs, state, node) { ... } makes no sense, because you're using Object property notation with no Object to be found. If it is contained within an Object which is not visible in the code snippet then all is fine, but keep in mind that you must reference the object to call the function in the following code snippet, e.g. obj.renderCrumbs().

Secondly, and problematically, you may be tempted to use change as a global. Don't do this, globals are bad. Read more here. Further information is available elsewhere with a little googling.

The best solution that I can see is to change the functionality of renderCrumbs to

```<code>function renderCrumbs(breadCrumbs, state, node) {
    return 'Change Data';
}
</code>```

and then you can do

```<code>var generateSearchObject = function() {
   var searchObj = {
       "fileName": renderCrumbs(),
       "tabType": text.toUpperCase(),
       "offset": offValue,
   };
   return searchObj;
};
</code>```

Body:
I would like to insert the value here as to send the JSON to backend but unable to get it.

var generateSearchObject = function() {
    var searchObj = {
        "fileName": change, // Here the fileName should be "Change Data"
        "tabType": text.toUpperCase(),
        "offset": offValue,
    };
    return searchObj;
};
var renderCrumbs = function(breadCrumbs, state, node) {
    var change = "Change Data";
}

Please help!

Body:
First of all renderCrumbs: function(breadCrumbs, state, node) { ... } makes no sense, because you're using Object property notation with no Object to be found. If it is contained within an Object which is not visible in the code snippet then all is fine, but keep in mind that you must reference the object to call the function in the following code snippet, e.g. obj.renderCrumbs().

Secondly, and problematically, you may be tempted to use change as a global. Don't do this, globals are bad. Read more here. Further information is available elsewhere with a little googling.

The best solution that I can see is to change the functionality of renderCrumbs to

function renderCrumbs(breadCrumbs, state, node) {
    return 'Change Data';
}

and then you can do

var generateSearchObject = function() {
   var searchObj = {
       "fileName": renderCrumbs(),
       "tabType": text.toUpperCase(),
       "offset": offValue,
   };
   return searchObj;
};


来源: stackexchange

问:
Restarting the animation once all divs are clicked?
I am trying to get the script to run again after all the gifs have been clicked and changed to the png's. Once all the gifs are clicked I have to refresh the browser in order for the game to start again. I would preferably like to have the creation of a newDiv happen when one of the divs is clicked. So that way a new one appears when one is clicked, and is constantly adding the newDiv. Any ideas on how to do that would help.

HTML:

```<code><!DOCTYPE html>
<html>

<head>

<title>Shoo Fly</title>

<style>

div.a {
width: 200px;
height:200px;
position:absolute;
background-image: url("fly.gif");
   }

html {
  background: url("fly-background.png");
  background-size: cover;
  background-repeat: no-repeat;
  margin: 0;
  padding:0;
  background-color: #50BBAD;
  zoom: 80%;
  }

 </style>

 <script src="jquery-3.1.1.js"></script>
 <script src="please-work.js"></script>

 </head>

 <body>

 <div class="animatedDivs"></div>

</body>

</html>
</code>```

Javascript:

```<code>$(document).ready(function () {
newDiv();
newDiv();
newDiv();
newDiv();
newDiv(); //5
newDiv();
newDiv();
newDiv();
newDiv();
newDiv(); //10
});

function newDiv() {
var $div = $("<div class='a'>");
$(".animatedDivs").append($div);
animateDiv();

$div.click(function(){
    $div.css('background-image','url(splatter-1.png)');
    $div.css('zIndex' , '-1');
    $div.css({'position': 'absolute'});
    //$(this).data('clicked', true);
    var offset = $div.position();
    $div.stop();
    $div.position({left:(offset.left), right: (offset.right)});
});

function animateDiv() {
    var newq = makeNewPosition();
    var oldq = $div.offset();
    var speed = calcSpeed([oldq.top, oldq.left], newq);

    $div.animate({
        top: newq[0],
        left: newq[1]
    }, speed, function () {
        animateDiv();
    });

};

}

function makeNewPosition() {

// Get viewport dimensions (remove the dimension of the div)
var h = $(window).height() - 50;
var w = $(window).width() - 50;

var nh = Math.floor(Math.random() * h);
var nw = Math.floor(Math.random() * w);

return [nh, nw];

}

function calcSpeed(prev, next) {

var x = Math.abs(prev[1] - next[1]);
var y = Math.abs(prev[0] - next[0]);

var greatest = x > y ? x : y;

var speedModifier = .1;

var speed = Math.ceil(greatest / speedModifier);

return speed;

}
</code>```

答:
A bonus
 to skip a couple lines and get a new param.

```<code>var init = function(x){
    for(i=0;i<x;i++){
       newDiv();
    };

// Onload initialisation
init(10);                 // OKAY! div amount as argument??
                          //       So possibly a incrental or random amount?
                          //
                          //       Thanks SO!
</code>```

ACCEPTED ANSWER

I named your function, to be able to call it again from somewhere else in the code.

Then I added a loop to check if all images have been clicked...

On each click event.

I also changed your images sources... But it is just for my demo.

Here is the whole code working in this CodePen:

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

  // Named the init fonction
  var init = function(){
    newDiv();
    newDiv();
    newDiv();
    newDiv();
    newDiv(); //5
    newDiv();
    newDiv();
    newDiv();
    newDiv();
    newDiv(); //10
  };

  // Onload initialisation
  init();

  function newDiv() {
    var $div = $("<div class='a'>");
    $(".animatedDivs").append($div);
    animateDiv();

    $div.click(function(){
      console.log("Image clicked");

      $div.css('background-image','url(https://media.licdn.com/mpr/mpr/shrink_200_200/AAEAAQAAAAAAAATsAAAAJDM0N2NjNzkxLWEyOGYtNDE5MS05OGQxLTRkMzFkMDA3ZmZjNw.png)');
      $div.css('zIndex' , '-1');
      $div.css({'position': 'absolute'});
      //$(this).data('clicked', true);
      var offset = $div.position();
      $div.stop();
      $div.position({left:(offset.left), right: (offset.right)});

      // ===================================
      // Check if all images are clicked.
      var allClicked=true;
      $(".a").each(function(){
        if( $(this).css("z-index")!="-1" ){
          allClicked=false;
        }
      });
      console.log( allClicked );      // Is true when all images are clicked.

      if(allClicked){
        console.log("restarting!");
        $(".a").remove();

        // Re-init the game
        init();
      }
      // ===================================

    });

    function animateDiv() {
      var newq = makeNewPosition();
      var oldq = $div.offset();
      var speed = calcSpeed([oldq.top, oldq.left], newq);

      $div.animate({
        top: newq[0],
        left: newq[1]
      }, speed, function () {
        animateDiv();
      });
    };
  }

  function makeNewPosition() {

    // Get viewport dimensions (remove the dimension of the div)
    var h = $(window).height() - 50;
    var w = $(window).width() - 50;

    var nh = Math.floor(Math.random() * h);
    var nw = Math.floor(Math.random() * w);

    return [nh, nw];

  }

  function calcSpeed(prev, next) {

    var x = Math.abs(prev[1] - next[1]);
    var y = Math.abs(prev[0] - next[0]);

    var greatest = x > y ? x : y;

    var speedModifier = .1;

    var speed = Math.ceil(greatest / speedModifier);

    return speed;

  }

});
</code>```

EDIT

To keep the "splats" there and load some new moving divs, only two lines have to be changed:

In CSS :

```<code>div.a {
</code>```

becomes:

```<code>div.a, div.splatted {
</code>```

And in JS :

```<code>$(".a").remove();
</code>```

becomes:

```<code>$(".a").removeClass("a").addClass("splatted");
</code>```

See this CodePen v2.

ContentLicense: CC BY-SA 3.0

Body:
I am trying to get the script to run again after all the gifs have been clicked and changed to the png's. Once all the gifs are clicked I have to refresh the browser in order for the game to start again. I would preferably like to have the creation of a newDiv happen when one of the divs is clicked. So that way a new one appears when one is clicked, and is constantly adding the newDiv. Any ideas on how to do that would help.

HTML:

<!DOCTYPE html>

<title>Shoo Fly</title>

Javascript:

$(document).ready(function () {
newDiv();
newDiv();
newDiv();
newDiv();
newDiv(); //5
newDiv();
newDiv();
newDiv();
newDiv();
newDiv(); //10
});

function newDiv() {
var $div = $("
");
$(".animatedDivs").append($div);
animateDiv();

$div.click(function(){
    $div.css('background-image','url(splatter-1.png)');
    $div.css('zIndex' , '-1');
    $div.css({'position': 'absolute'});
    //$(this).data('clicked', true);
    var offset = $div.position();
    $div.stop();
    $div.position({left:(offset.left), right: (offset.right)});
});

function animateDiv() {
    var newq = makeNewPosition();
    var oldq = $div.offset();
    var speed = calcSpeed([oldq.top, oldq.left], newq);

    $div.animate({
        top: newq[0],
        left: newq[1]
    }, speed, function () {
        animateDiv();
    });

};

}

function makeNewPosition() {

// Get viewport dimensions (remove the dimension of the div)
var h = $(window).height() - 50;
var w = $(window).width() - 50;

var nh = Math.floor(Math.random() * h);
var nw = Math.floor(Math.random() * w);

return [nh, nw];

}

function calcSpeed(prev, next) {

var x = Math.abs(prev[1] - next[1]);
var y = Math.abs(prev[0] - next[0]);

var greatest = x > y ? x : y;

var speedModifier = .1;

var speed = Math.ceil(greatest / speedModifier);

return speed;

}

Body:
A bonus
 to skip a couple lines and get a new param.

var init = function(x){
    for(i=0;i<x;i++){
       newDiv();
    };

// Onload initialisation
init(10);                 // OKAY! div amount as argument??
                          //       So possibly a incrental or random amount?
                          //
                          //       Thanks SO!

ACCEPTED ANSWER

I named your function, to be able to call it again from somewhere else in the code.

Then I added a loop to check if all images have been clicked...

On each click event.

I also changed your images sources... But it is just for my demo.

Here is the whole code working in this CodePen:

$(document).ready(function () {

  // Named the init fonction
  var init = function(){
    newDiv();
    newDiv();
    newDiv();
    newDiv();
    newDiv(); //5
    newDiv();
    newDiv();
    newDiv();
    newDiv();
    newDiv(); //10
  };

  // Onload initialisation
  init();

  function newDiv() {
    var $div = $("<div class='a'>");
    $(".animatedDivs").append($div);
    animateDiv();

    $div.click(function(){
      console.log("Image clicked");

      $div.css('background-image','url(https://media.licdn.com/mpr/mpr/shrink_200_200/AAEAAQAAAAAAAATsAAAAJDM0N2NjNzkxLWEyOGYtNDE5MS05OGQxLTRkMzFkMDA3ZmZjNw.png)');
      $div.css('zIndex' , '-1');
      $div.css({'position': 'absolute'});
      //$(this).data('clicked', true);
      var offset = $div.position();
      $div.stop();
      $div.position({left:(offset.left), right: (offset.right)});

      // ===================================
      // Check if all images are clicked.
      var allClicked=true;
      $(".a").each(function(){
        if( $(this).css("z-index")!="-1" ){
          allClicked=false;
        }
      });
      console.log( allClicked );      // Is true when all images are clicked.

      if(allClicked){
        console.log("restarting!");
        $(".a").remove();

        // Re-init the game
        init();
      }
      // ===================================

    });

    function animateDiv() {
      var newq = makeNewPosition();
      var oldq = $div.offset();
      var speed = calcSpeed([oldq.top, oldq.left], newq);

      $div.animate({
        top: newq[0],
        left: newq[1]
      }, speed, function () {
        animateDiv();
      });
    };
  }

  function makeNewPosition() {

    // Get viewport dimensions (remove the dimension of the div)
    var h = $(window).height() - 50;
    var w = $(window).width() - 50;

    var nh = Math.floor(Math.random() * h);
    var nw = Math.floor(Math.random() * w);

    return [nh, nw];

  }

  function calcSpeed(prev, next) {

    var x = Math.abs(prev[1] - next[1]);
    var y = Math.abs(prev[0] - next[0]);

    var greatest = x > y ? x : y;

    var speedModifier = .1;

    var speed = Math.ceil(greatest / speedModifier);

    return speed;

  }

});

EDIT

To keep the "splats" there and load some new moving divs, only two lines have to be changed:

In CSS :

div.a {

becomes:

div.a, div.splatted {

And in JS :

$(".a").remove();

becomes:

$(".a").removeClass("a").addClass("splatted");

See this CodePen v2.


问:
AVCaptureDevice is always null on simulator
I am trying to capture live microphone audio data.

I took the following from the apple example for AVCaptureSession.

```<code>AVCaptureSession *captureSession = [[AVCaptureSession alloc] init];

AVCaptureDevice *audioCaptureDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeAudio];

NSError *error = nil;
AVCaptureDeviceInput *audioInput = [AVCaptureDeviceInput deviceInputWithDevice:audioCaptureDevice error:&error];

if (audioInput) {
    [captureSession addInput:audioInput];
}
else {
    // Handle the failure.
    NSLog(@"ERROR");
}
</code>```

audioCaptureDevice and audioInput are both null.

答: The simulator cannot take the Mac microphone as a source. You need to use a real device to test that.</p>

Body:
I am trying to capture live microphone audio data.

I took the following from the apple example for AVCaptureSession.

AVCaptureSession *captureSession = [[AVCaptureSession alloc] init];

AVCaptureDevice *audioCaptureDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeAudio];

NSError *error = nil;
AVCaptureDeviceInput *audioInput = [AVCaptureDeviceInput deviceInputWithDevice:audioCaptureDevice error:&error];

if (audioInput) {
    [captureSession addInput:audioInput];
}
else {
    // Handle the failure.
    NSLog(@"ERROR");
}

audioCaptureDevice and audioInput are both null.


答:
Yes, it should be. Because simulator doesn't have any microphone. You should always test any audio, video, rendering related task on a real device.

Take a look about Limitations of Testing in iOS Simulator

Hardware Limitations While most of the functionality of iOS devices
can be simulated in iOS Simulator, there are some hardware features
that must be tested directly on a device. The hardware features that
cannot be simulated are:

Accelerometer

Gyroscope

Camera

Proximity

Sensor Microphone Input

Title: AVCaptureDevice is always null on simulator


问:
symfony2 method undefined in EntityRepository
i want create a request from my EntityRepository so this is my code:

```<code><?php

namespace zhr\myprojectBundle\Entity;

use Doctrine\ORM\EntityRepository;

/**
 * myprojectdbEntityRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class myprojectdbEntityRepository extends EntityRepository
{
    public function getAll()
    {
        $qb = $this->createQueryBuilder('s');

        $query = $qb;

        $result = $qb->getQuery()->execute();

    }
}
</code>```

i want use it in my controller file so this is my code:

public function searchusersAction(Request $request)
    {

```<code>    $em = $this->getDoctrine()->getManager();
    $repository = $em->getRepository('myprojectBundle:User');

    $utilisateur = $repository->getAll();

   var_dump($utilisateur); die();

    //return $this->render('mypageBundle:Admin:adminindex.html.twig', array('sheet'=>$utilisateur));

}
</code>```

i get a error:

Undefined method 'getAll'. The method name must start with either findBy or findOneBy!

??? normaly all methode in repository file must be defined in my controller file no ?

thanks first guys

答:
You have to use getResult() to return a result as follow:

```<code>public function getAll()
{
    return $this->createQueryBuilder('s')->getQuery()->getResult();
}
</code>```

But you really don't need this kind of function since EntityRepository class already has findAll() function to get all rows from an entity:

```<code>$em = $this->getDoctrine()->getManager();
$rows = $em->getRepository('myprojectBundle:User')->findAll();
</code>```

I suggest you to check documentation for QueryBuilder and EntityRepository api.

Body:
i want create a request from my EntityRepository so this is my code:

<?php

namespace zhr\myprojectBundle\Entity;

use Doctrine\ORM\EntityRepository;

/**
 * myprojectdbEntityRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class myprojectdbEntityRepository extends EntityRepository
{
    public function getAll()
    {
        $qb = $this->createQueryBuilder('s');

        $query = $qb;

        $result = $qb->getQuery()->execute();

    }
}

i want use it in my controller file so this is my code:

public function searchusersAction(Request $request)
    {

    $em = $this->getDoctrine()->getManager();
    $repository = $em->getRepository('myprojectBundle:User');

    $utilisateur = $repository->getAll();

   var_dump($utilisateur); die();

    //return $this->render('mypageBundle:Admin:adminindex.html.twig', array('sheet'=>$utilisateur));

}

i get a error:

Undefined method 'getAll'. The method name must start with either findBy or findOneBy!

??? normaly all methode in repository file must be defined in my controller file no ?

thanks first guys

Body:
You have to use getResult() to return a result as follow:

public function getAll()
{
    return $this->createQueryBuilder('s')->getQuery()->getResult();
}

But you really don't need this kind of function since EntityRepository class already has findAll() function to get all rows from an entity:

$em = $this->getDoctrine()->getManager();
$rows = $em->getRepository('myprojectBundle:User')->findAll();

I suggest you to check documentation for QueryBuilder and EntityRepository api.


问:
Using auto layout to orientate stack views vertically in portrait and horizontally in landscape
What is the best way to get a vertical stackview in portrait to align horizontally in landscape. I have tried code and auto layout solutions and they have not worked. Is there any simple way to do this in storyboard?</p>

答:
Swift 3.0

```<code>override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
    coordinator.animate(alongsideTransition: { (context) -> Void in

        let orientation = UIApplication.shared.statusBarOrientation

        if orientation.isPortrait {
            self.stackView.axis = .horizontal
        } else {
            self.stackView.axis = .vertical
        }

    }, completion: nil)
}
</code>```

Body:
Swift 3.0

override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
    coordinator.animate(alongsideTransition: { (context) -> Void in

        let orientation = UIApplication.shared.statusBarOrientation

        if orientation.isPortrait {
            self.stackView.axis = .horizontal
        } else {
            self.stackView.axis = .vertical
        }

    }, completion: nil)
}


问:
Placing spans on opposite sides of div, without using float
I have some spans inside of a div. I would like one span, which contains some string, on the left side and one span which contains some font awesome icons on the right side. However I cannot use floats as these elements are heavily nested and that causes issues. Note also the width is finite and sometimes if the string is long enough it can word break.</p>

```<code><div>
<span>Some Long Text Here</span>
<span><i class="fa fa-bars"></i></span>
</div>
</code>```

答:
If it is an option use flexbox :

div {
  line-height: 20px;
  padding: 15px;
  color: white;
  background: purple;
  /*Code flex*/
  display: flex;
}

span:first-child {
  flex:1 1 auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css" rel="stylesheet" />
<div>
  <span>Some Long Text Here</span>
  <span><i class="fa fa-bars"></i></span>
</div><br>
<div>
  <span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quo quibusdam, iusto laboriosam ipsam quas impedit voluptatem fugiat rerum quis, minima velit nam accusantium beatae voluptas commodi eligendi molestiae dolorum reiciendis!</span>
  <span><i class="fa fa-home"></i></span>
</div></code>```

Body:
I have some spans inside of a div. I would like one span, which contains some string, on the left side and one span which contains some font awesome icons on the right side. However I cannot use floats as these elements are heavily nested and that causes issues. Note also the width is finite and sometimes if the string is long enough it can word break.

Some Long Text Here

Body:
If it is an option use flexbox :

div {
  line-height: 20px;
  padding: 15px;
  color: white;
  background: purple;
  /*Code flex*/
  display: flex;
}

span:first-child {
  flex:1 1 auto;
}

<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css" rel="stylesheet" />
<div>
  <span>Some Long Text Here</span>
  <span><i class="fa fa-bars"></i></span>
</div><br>
<div>
  <span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quo quibusdam, iusto laboriosam ipsam quas impedit voluptatem fugiat rerum quis, minima velit nam accusantium beatae voluptas commodi eligendi molestiae dolorum reiciendis!</span>
  <span><i class="fa fa-home"></i></span>
</div>


问:
Custom scheme URIs are not allowed for 'Web' client type - Google with Firebase
I am trying to implement google sign in using firebase in to my iOS app. I follow this tutorial.
    https://firebase.google.com/docs/auth/ios/google-signin
I have setup the iOS app in firebase and use the google clientID and reversedClientID from the dowloaded GoogleService-Info.plist.

FYI: I have a custom sign-in button instead of the google sign in button. Anyway when i click the sign in button, google following error display in a webview.

I know my problem is the same as which described in this question.

Google 400 Error: invalid request Custom scheme URIs are not allowed for 'Web' client type

But, in my case, I have created the app in Firebase still I get the error. Any idea please...

答:
The first step is to check if you have already the OAuth 2.0 ID for iOS. To do this please open the Credentials page in the API Console. I hope you will find iOS client for your application under OAuth 2.0 client IDs section. If not, please follow this Guide
The second step is to replace the Web Client ID with in iOS Client ID from OAuth 2.0 client IDs section. To do this, you should open the GoogleService-Info.plist and modify following keys: CLIENT_ID with [value].apps.googleusercontent.com and REVERSED_CLIENT_ID with com.googleusercontent.apps.[value].


问:
Methods Not Found Symfony
i have the following code

```<code><?php

namespace AppBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use AppBundle\Entity\Todo;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;

class ToDoController extends Controller
{
    /**
     * @Route("/todo", name="todo_list")
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function listAction()
    {
        $todos = $this->getDoctrine()->getRepository('AppBundle:Todo')->findAll();
        return $this->render('todo/index.html.twig', array(
            'todos' => $todos
        ));
    }

    /**
     * @Route("/todo/create", name="todo_create")
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function createAction(Request $request)
    {
        $todo = new Todo();

        $form = $this->createFormBuilder($todo)
            ->add('name', TextType::class, array('attr' => array('class' => 'form-control', 'style' => 'margin-bottom:15px')))
            ->add('category', TextType::class, array('attr' => array('class' => 'form-control', 'style' => 'margin-bottom:15px')))
            ->add('description', TextareaType::class, array('attr' => array('class' => 'form-control', 'style' => 'margin-bottom:15px')))

            ;

            $form->handleRequest($request);

            if ($form->isSubmitted() && $form->isValid()) {
                die('Submitted');
            }

        return $this->render('todo/create.html.twig', array(
            'form' => $form->createView()
        ));
    }

    /**
     * @Route("todo/edit/{id}", name="todo_edit")
     * @param $id
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function editAction($id, Request $request)
    {
        return $this->render('todo/edit.html.twig');
    }

    /**
     * @Route("/todo/details/{id}", name="todo_details")
     */
    public function detailsAction($id)
    {
        return $this->render('todo/details.html.twig');
    }
}
</code>```

The problem is that the mehods like handleRequest() isSubmitted() isValid() createView() etc.. are not found. I don't have any idea why ? Can anyone help me ? Thanks in advance.

答:
What you do is

```<code>$form = $this->createFormBuilder($todo)
// ...
;

$form->handleRequest($request);
// ...
</code>```

which is incorrect,
you need to do

```<code>$form = $this->createFormBuilder($todo)
// ...
->getForm()
;
// ...
</code>```

Your methods are not found becausecreateFormBuilder() will return a FormBuilder object, the methods handleRequest() and the others are on the object Form

Edit

To remove your ide's warning about method definition being not found. you can do the following:

```<code>use Symfony\Component\Form\Form;

// ...

/** @var Form $form */
$form = $this->createFormBuilder($todo)
// ...
</code>```

Note that it's 100% cosmetic, and the warnins will have no impact on code execution.

I don't know why your ide don't find the methods swhen the builder has > 1 fields. I can 100% reproduce this buggy behavior, but your code will work.

In order to fix those warnings you may consider using form classes

Edit 2

If you are using the Symfony Plugin for phpStorm there is a similar issue on their github

Title: Methods Not Found Symfony

Body:
i have the following code

<?php

namespace AppBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use AppBundle\Entity\Todo;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;

class ToDoController extends Controller
{
    /**
     * @Route("/todo", name="todo_list")
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function listAction()
    {
        $todos = $this->getDoctrine()->getRepository('AppBundle:Todo')->findAll();
        return $this->render('todo/index.html.twig', array(
            'todos' => $todos
        ));
    }

    /**
     * @Route("/todo/create", name="todo_create")
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function createAction(Request $request)
    {
        $todo = new Todo();

        $form = $this->createFormBuilder($todo)
            ->add('name', TextType::class, array('attr' => array('class' => 'form-control', 'style' => 'margin-bottom:15px')))
            ->add('category', TextType::class, array('attr' => array('class' => 'form-control', 'style' => 'margin-bottom:15px')))
            ->add('description', TextareaType::class, array('attr' => array('class' => 'form-control', 'style' => 'margin-bottom:15px')))

            ;

            $form->handleRequest($request);

            if ($form->isSubmitted() && $form->isValid()) {
                die('Submitted');
            }

        return $this->render('todo/create.html.twig', array(
            'form' => $form->createView()
        ));
    }

    /**
     * @Route("todo/edit/{id}", name="todo_edit")
     * @param $id
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function editAction($id, Request $request)
    {
        return $this->render('todo/edit.html.twig');
    }

    /**
     * @Route("/todo/details/{id}", name="todo_details")
     */
    public function detailsAction($id)
    {
        return $this->render('todo/details.html.twig');
    }
}

The problem is that the mehods like handleRequest() isSubmitted() isValid() createView() etc.. are not found. I don't have any idea why ? Can anyone help me ? Thanks in advance.

Body:
What you do is

$form = $this->createFormBuilder($todo)
// ...
;

$form->handleRequest($request);
// ...

which is incorrect,
you need to do

$form = $this->createFormBuilder($todo)
// ...
->getForm()
;
// ...

Your methods are not found becausecreateFormBuilder() will return a FormBuilder object, the methods handleRequest() and the others are on the object Form

Edit

To remove your ide's warning about method definition being not found. you can do the following:

use Symfony\Component\Form\Form;

// ...

/** @var Form $form */
$form = $this->createFormBuilder($todo)
// ...

Note that it's 100% cosmetic, and the warnins will have no impact on code execution.

I don't know why your ide don't find the methods swhen the builder has > 1 fields. I can 100% reproduce this buggy behavior, but your code will work.

In order to fix those warnings you may consider using form classes

Edit 2

If you are using the Symfony Plugin for phpStorm there is a similar issue on their github


问:
How to properly handle a JWT refresh?
I have an android app. It connects with a REST API developed with Jersey. My REST End points are secured with Tokens. Below is how I generate them.

```<code>Algorithm algorithm = Algorithm.HMAC256(secret);
String token = JWT.create()
    .withClaim("userName","myusername)
    .withExpiresAt(expirationDate)
    .sign(algorithm);
</code>```

Below is how I validate the token

```<code>public boolean validateTokenHMAC256(String token, String secret) throws UnsupportedEncodingException, JWTVerificationException
    {
        Algorithm algorithm = Algorithm.HMAC256(secret);

        JWTVerifier verifier = JWT.require(algorithm)
                .build(); //Reusable verifier instance
            DecodedJWT jwt = verifier.verify(token);

            Claim usernameClaim = jwt.getClaim("username");
            String username = usernameClaim.asString();
            System.out.println(username);

        return true;
    }
</code>```

In my REST API I have a filter and that filter checks every request to see whether the token is as it is. Below is the code.

```<code>@Secured
@Provider
@Priority(Priorities.AUTHENTICATION)
public class AuthenticationFilter implements ContainerRequestFilter{

    //private static String authorizationSecret = "ZXW24xGr9Dqf9sq5Dp8ZAn5nSnuZwux2QxdvcH3wQGqYteJ5yMTw5T8DBUJPbySR";

    public AuthenticationFilter()
    {
        System.out.println("test printing");
    }

    @Override
    public void filter(ContainerRequestContext crc) throws IOException
    {
        String headerString = crc.getHeaderString("Bearer");
        System.out.println("bluh: "+headerString);
        System.out.println("test printing");

        try
        {
            boolean validateToken = validateToken(headerString, AuthKey.authorizationSecret);
            System.out.println("valid");
        }
        catch(Exception e)
        {
            System.out.println("invalid");
            crc.abortWith(
                Response.status(Response.Status.UNAUTHORIZED).build());
        }

    }

    private boolean validateToken(String strToken, String secret) throws UnsupportedEncodingException, JWTVerificationException
    {
        Token token = new Token();
        return token.validateTokenHMAC256(strToken,secret);
    }

}
</code>```

The above code will be called when the user login to the application. However the token will be expired in 60 minutes. I know that after the token is expired either I have to take the user back to sign in screen or refresh the token. I went through the advices in here and here

But I do not understand the following.

How can I figure out whether the token has to be renewed? I thought I should do that after it is expired, but seems that is not the case. If I ask it to refresh in now<exp it will refresh in every request.

How can I assign and send this token back to the user? Currently when the user login on, he will get the token and he will save it in a variable. For the refreshed token to work, do I have to call the login method again (So the token will be sent to the user) or JWT it self will handle the case?

How do I actually refersh using java-jwt ?

答:
How can I figure out whether the token has to be renewed? I thought I should do that after it is expired, but seems that is not the case. If I ask it to refresh in now

You need to refresh the token before it is expired. Decide your policy:

issue a fresh token in every request

issue a fresh token when the current one is close to expire. e.g. 10 min

let client app request a new token when it needs it using a "refresh service" of your api. For example

```<code>@GET
@Path("/jwt/refresh")
@Produces(MediaType.TEXT_HTML)
public String refresh(){
    //Build a returns a fresh JWT to client
}
</code>```

How can I assign and send this token back to the user?

If you issue a fresh token during a request, you can return it in a special header that client will read during processing of the response. If you publish a "refresh" service as described above, then the client will call it independently when the current JWT is close to expire

Redirect to login method is not a good alternative because you will lose the current request

How do I actually refresh using java-jwt

Just issue a new token

Title: How to properly handle a JWT refresh?

Body:
I have an android app. It connects with a REST API developed with Jersey. My REST End points are secured with Tokens. Below is how I generate them.

Algorithm algorithm = Algorithm.HMAC256(secret);
String token = JWT.create()
    .withClaim("userName","myusername)
    .withExpiresAt(expirationDate)
    .sign(algorithm);

Below is how I validate the token

public boolean validateTokenHMAC256(String token, String secret) throws UnsupportedEncodingException, JWTVerificationException
    {
        Algorithm algorithm = Algorithm.HMAC256(secret);

        JWTVerifier verifier = JWT.require(algorithm)
                .build(); //Reusable verifier instance
            DecodedJWT jwt = verifier.verify(token);

            Claim usernameClaim = jwt.getClaim("username");
            String username = usernameClaim.asString();
            System.out.println(username);

        return true;
    }

In my REST API I have a filter and that filter checks every request to see whether the token is as it is. Below is the code.

@Secured
@Provider
@Priority(Priorities.AUTHENTICATION)
public class AuthenticationFilter implements ContainerRequestFilter{

    //private static String authorizationSecret = "ZXW24xGr9Dqf9sq5Dp8ZAn5nSnuZwux2QxdvcH3wQGqYteJ5yMTw5T8DBUJPbySR";

    public AuthenticationFilter()
    {
        System.out.println("test printing");
    }

    @Override
    public void filter(ContainerRequestContext crc) throws IOException
    {
        String headerString = crc.getHeaderString("Bearer");
        System.out.println("bluh: "+headerString);
        System.out.println("test printing");

        try
        {
            boolean validateToken = validateToken(headerString, AuthKey.authorizationSecret);
            System.out.println("valid");
        }
        catch(Exception e)
        {
            System.out.println("invalid");
            crc.abortWith(
                Response.status(Response.Status.UNAUTHORIZED).build());
        }

    }

    private boolean validateToken(String strToken, String secret) throws UnsupportedEncodingException, JWTVerificationException
    {
        Token token = new Token();
        return token.validateTokenHMAC256(strToken,secret);
    }

}

The above code will be called when the user login to the application. However the token will be expired in 60 minutes. I know that after the token is expired either I have to take the user back to sign in screen or refresh the token. I went through the advices in here and here

But I do not understand the following.

How can I figure out whether the token has to be renewed? I thought I should do that after it is expired, but seems that is not the case. If I ask it to refresh in now<exp it will refresh in every request.

How can I assign and send this token back to the user? Currently when the user login on, he will get the token and he will save it in a variable. For the refreshed token to work, do I have to call the login method again (So the token will be sent to the user) or JWT it self will handle the case?

How do I actually refersh using java-jwt ?

Body:
How can I figure out whether the token has to be renewed? I thought I should do that after it is expired, but seems that is not the case. If I ask it to refresh in now

You need to refresh the token before it is expired. Decide your policy:

issue a fresh token in every request

issue a fresh token when the current one is close to expire. e.g. 10 min

let client app request a new token when it needs it using a "refresh service" of your api. For example

@GET
@Path("/jwt/refresh")
@Produces(MediaType.TEXT_HTML)
public String refresh(){
    //Build a returns a fresh JWT to client
}

How can I assign and send this token back to the user?

If you issue a fresh token during a request, you can return it in a special header that client will read during processing of the response. If you publish a "refresh" service as described above, then the client will call it independently when the current JWT is close to expire

Redirect to login method is not a good alternative because you will lose the current request

How do I actually refresh using java-jwt

Just issue a new token


问:
Check number input field only have 8 digits and starts with number 2
I have an input field which already force a user to enter 8 digits, but i want to force him to enter the digits starts with 2 as give him an alert when enter the first number wrong, if he wrote 2 then let him enter the rest of number.
here is my code :

HTML

```<code><input type="number" maxlength="8"  class="form-control myInput" name="myInput" id="myInput" placeholder="myInput" pattern="\d{8}" required>
</div>
</code>```

JQuery

```<code>$(".myInput").unbind('keyup change input paste').bind('keyup change input paste',function(e){
    var $this = $(this) ,val = $this.val(),valLength = val.length, maxCount = $this.attr('maxlength');
    if(valLength>maxCount){
        $this.val($this.val().substring(0,maxCount));
    }
});
</code>```

Please help.

答:
here is my solution

Jquery

```<code>$("#myInput").on('keypress', function(){
            var numbers = $(this).val().trim();
            if(numbers[1]){
              if(numbers[0] != '2' || numbers.length > 8){
                $(this).val('');
                $('.error').html("Error the input has to start with number 2 and has to be lesser than 8 numbers");
              }else{
                $('.error').html("Good");
              }
            }
          });
</code>```

html

```<code><input type="number" maxlength="8" id="myInput" required>
<div class='error'>

</div>
</code>```

This is just an example feel free to adjust anything, i removed some tags and stuff but you can re add them this is just to show you how to do

So the script checks if 2numbers have been entered if yes it checks if the first one is 2 if not it shows err message and reset input value else it writes good

Here is the fiddle

https://jsfiddle.net/qh7gwecc/3/

Body:
I have an input field which already force a user to enter 8 digits, but i want to force him to enter the digits starts with 2 as give him an alert when enter the first number wrong, if he wrote 2 then let him enter the rest of number.
here is my code :

HTML

<input type="number" maxlength="8"  class="form-control myInput" name="myInput" id="myInput" placeholder="myInput" pattern="\d{8}" required>

JQuery

$(".myInput").unbind('keyup change input paste').bind('keyup change input paste',function(e){
    var $this = $(this) ,val = $this.val(),valLength = val.length, maxCount = $this.attr('maxlength');
    if(valLength>maxCount){
        $this.val($this.val().substring(0,maxCount));
    }
});

Please help.

Body:
here is my solution

Jquery

$("#myInput").on('keypress', function(){
            var numbers = $(this).val().trim();
            if(numbers[1]){
              if(numbers[0] != '2' || numbers.length > 8){
                $(this).val('');
                $('.error').html("Error the input has to start with number 2 and has to be lesser than 8 numbers");
              }else{
                $('.error').html("Good");
              }
            }
          });

html

<input type="number" maxlength="8" id="myInput" required>
<div class='error'>

</div>

This is just an example feel free to adjust anything, i removed some tags and stuff but you can re add them this is just to show you how to do

So the script checks if 2numbers have been entered if yes it checks if the first one is 2 if not it shows err message and reset input value else it writes good

Here is the fiddle

https://jsfiddle.net/qh7gwecc/3/


问:
How can I record that sound going out of my speakers (not what's coming into the mic)?
I'm trying to record the sound my computer produces (without using a microphone)

I've found these two commands that work to record my microphone output into files:

```<code># creates mp3
arecord -f cd > my_file.mp3

# creates ogg
arecord -f cd -t raw | oggenc - -r -o out.ogg
</code>```

However I am not sure how to record the audio coming out of my speakers directly.

I should note that I have figured out how to do this using PulseAudio and Audacity - there's a good tutorial here however it broke my microphone input and also I would like to be able to do it from the command line.

答:
Revisiting this 5 months later, I finally figured it out.

From the answer here:

sudo apt-get install pulseaudio-utils lame mpg123

pacmd list-sinks | grep -e 'name:' -e 'index' -e 'Speakers', find the string in between <> brackets - for me it's alsa_output.pci-0000_00_1b.0.analog-stereo

start playing some audio

parec -d alsa_output.pci-0000_00_1b.0.analog-stereo.monitor | lame -r -V0 - out.mp3

control + c to stop

Now for the tricky part, the file for some reason cannot be listened to with aplay - it just sounds like static. Listen to it with mpg123 instead.

Body:
I'm trying to record the sound my computer produces (without using a microphone)

I've found these two commands that work to record my microphone output into files:

# creates mp3
arecord -f cd > my_file.mp3

# creates ogg
arecord -f cd -t raw | oggenc - -r -o out.ogg

However I am not sure how to record the audio coming out of my speakers directly.

I should note that I have figured out how to do this using PulseAudio and Audacity - there's a good tutorial here however it broke my microphone input and also I would like to be able to do it from the command line.


问:
How to rotate an image clockwise or counterclockwise, whichever is shorter?
I'm making a web page that includes a clock with an arrow in the center.  When the user clicks on an hour, the arrow rotates to point to what he/she has clicked.

I'm using a jQuery image rotate plugin (jQueryRotate) to rotate the arrow.

Here is the current code to compute the number of degrees to rotate:

```<code>var numTiles = $("ul li").size(); // Number of tiles is however many are listed in the UL, which is 12
var sel = 0; // Default hour selection
var rot = 0; // Default rotation is at the top (0 degrees)
var gap = 360 / numTiles; // Degrees between each tile

function rotateArrow(num) {
  rot = num * gap;
  $("#arrow").rotateAnimation(rot);
  sel = num;
}
</code>```

When the user clicks one of the hours, it passes num as a value of 1 through 12.

It works fine, but the problem is that if the arrow is pointing to 1 o'clock, and the user clicks 11 o'clock, the arrow rotates clockwise 300 degrees, when it would make more sense to rotate 60 degrees counterclockwise.

So, how can I write an equation to take the current hour (num) and the hour clicked (sel), and output a value as a positive or negative number, which equals the number of degrees to rotate that is most efficient, rather than just rotate only in one direction?

Any advice is appreciated.  Let me know if you have any questions.  Thanks!

答:
Basically the closest rotation will always be less than 180 degrees, so if your angle is greater than 180, just subtract 360 from it to get the negative angle. Taking your own example, if you end up with 300 degrees, subtract 360 to get -60 degrees.

So to add to your current line of code:

```<code>rot = num * gap;
</code>```

all you need is:

```<code>if (rot > 180)
  rot -= 360;
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'm making a web page that includes a clock with an arrow in the center.  When the user clicks on an hour, the arrow rotates to point to what he/she has clicked.

I'm using a jQuery image rotate plugin (jQueryRotate) to rotate the arrow.

Here is the current code to compute the number of degrees to rotate:

var numTiles = $("ul li").size(); // Number of tiles is however many are listed in the UL, which is 12
var sel = 0; // Default hour selection
var rot = 0; // Default rotation is at the top (0 degrees)
var gap = 360 / numTiles; // Degrees between each tile

function rotateArrow(num) {
  rot = num * gap;
  $("#arrow").rotateAnimation(rot);
  sel = num;
}

When the user clicks one of the hours, it passes num as a value of 1 through 12.

It works fine, but the problem is that if the arrow is pointing to 1 o'clock, and the user clicks 11 o'clock, the arrow rotates clockwise 300 degrees, when it would make more sense to rotate 60 degrees counterclockwise.

So, how can I write an equation to take the current hour (num) and the hour clicked (sel), and output a value as a positive or negative number, which equals the number of degrees to rotate that is most efficient, rather than just rotate only in one direction?

Any advice is appreciated.  Let me know if you have any questions.  Thanks!

Body:
Basically the closest rotation will always be less than 180 degrees, so if your angle is greater than 180, just subtract 360 from it to get the negative angle. Taking your own example, if you end up with 300 degrees, subtract 360 to get -60 degrees.

So to add to your current line of code:

rot = num * gap;

all you need is:

if (rot > 180)
  rot -= 360;


问:
Is there a more efficient and elegant way to filter pandas index by date?
I often use DatetimeIndex.date, especially in groupby methods. However, DatetimeIndex.date is slow when compared to DatetimeIndex.year/month/day. From what I understand, it is because the .date attribute works with a lambda function over the index and returns a datetime ordered index, while index.year/month/day just returns integer indices. I have made a small example function that performs a bit better and would speed up some of my code (at least for finding the values in a groupby), but I feel that there must be a better way:

```<code>In [217]: index = pd.date_range('2011-01-01', periods=100000, freq='h')

In [218]: data = np.random.rand(len(index))

In [219]: df = pd.DataFrame({'data':data},index)

In [220]: def func(df):
 ...:     groupby = df.groupby([df.index.year, df.index.month, df.index.day]).mean()
 ...:     index = pd.date_range(df.index[0], periods = len(groupby), freq='D')
 ...:     groupby.index = index
 ...:     return groupby
 ...:

In [221]: df.groupby(df.index.date).mean().equals(func(df))
Out[221]: True

In [222]: df.groupby(df.index.date).mean().index.equals(func(df).index)
Out[222]: True

In [223]: %timeit df.groupby(df.index.date).mean()
1 loop, best of 3: 1.32 s per loop

In [224]: %timeit func(df)
10 loops, best of 3: 89.2 ms per loop
</code>```

Does the pandas/index have a similar functionality that I am not finding?

答:
You can even improve it a little bit:

```<code>In [69]: %timeit func(df)
10 loops, best of 3: 84.3 ms per loop

In [70]: %timeit df.groupby(pd.TimeGrouper('1D')).mean()
100 loops, best of 3: 6 ms per loop

In [84]: %timeit df.groupby(pd.Grouper(level=0, freq='1D')).mean()
100 loops, best of 3: 6.48 ms per loop

In [71]: (func(df) == df.groupby(pd.TimeGrouper('1D')).mean()).all()
Out[71]:
data    True
dtype: bool
</code>```

another solution - using DataFrame.resample() method:

```<code>In [73]: (df.resample('1D').mean() == func(df)).all()
Out[73]:
data    True
dtype: bool

In [74]: %timeit df.resample('1D').mean()
100 loops, best of 3: 6.63 ms per loop
</code>```

UPDATE: grouping by the string:

```<code>In [75]: %timeit df.groupby(df.index.strftime('%Y%m%d')).mean()
1 loop, best of 3: 2.6 s per loop

In [76]: %timeit df.groupby(df.index.date).mean()
1 loop, best of 3: 1.07 s per loop
</code>```

Body:
I often use DatetimeIndex.date, especially in groupby methods. However, DatetimeIndex.date is slow when compared to DatetimeIndex.year/month/day. From what I understand, it is because the .date attribute works with a lambda function over the index and returns a datetime ordered index, while index.year/month/day just returns integer indices. I have made a small example function that performs a bit better and would speed up some of my code (at least for finding the values in a groupby), but I feel that there must be a better way:

In [217]: index = pd.date_range('2011-01-01', periods=100000, freq='h')

In [218]: data = np.random.rand(len(index))

In [219]: df = pd.DataFrame({'data':data},index)

In [220]: def func(df):
 ...:     groupby = df.groupby([df.index.year, df.index.month, df.index.day]).mean()
 ...:     index = pd.date_range(df.index[0], periods = len(groupby), freq='D')
 ...:     groupby.index = index
 ...:     return groupby
 ...:

In [221]: df.groupby(df.index.date).mean().equals(func(df))
Out[221]: True

In [222]: df.groupby(df.index.date).mean().index.equals(func(df).index)
Out[222]: True

In [223]: %timeit df.groupby(df.index.date).mean()
1 loop, best of 3: 1.32 s per loop

In [224]: %timeit func(df)
10 loops, best of 3: 89.2 ms per loop

Does the pandas/index have a similar functionality that I am not finding?

Body:
You can even improve it a little bit:

In [69]: %timeit func(df)
10 loops, best of 3: 84.3 ms per loop

In [70]: %timeit df.groupby(pd.TimeGrouper('1D')).mean()
100 loops, best of 3: 6 ms per loop

In [84]: %timeit df.groupby(pd.Grouper(level=0, freq='1D')).mean()
100 loops, best of 3: 6.48 ms per loop

In [71]: (func(df) == df.groupby(pd.TimeGrouper('1D')).mean()).all()
Out[71]:
data    True
dtype: bool

another solution - using DataFrame.resample() method:

In [73]: (df.resample('1D').mean() == func(df)).all()
Out[73]:
data    True
dtype: bool

In [74]: %timeit df.resample('1D').mean()
100 loops, best of 3: 6.63 ms per loop

UPDATE: grouping by the string:

In [75]: %timeit df.groupby(df.index.strftime('%Y%m%d')).mean()
1 loop, best of 3: 2.6 s per loop

In [76]: %timeit df.groupby(df.index.date).mean()
1 loop, best of 3: 1.07 s per loop


问:
Funnel chart with bars
Is it possible to make the rectangle cut at the end of the right (As below image):

Tried to use the css skew but its cutting both ends, I need only right like funnel.

答:
Use clipping with polygon.  My polygons go from upper left, to upper right, to lower right, to lower left.  I used the css calc function in order to make the offset relative to the end.  I did a 40px slant, but if you want more a slant, simply change that number.

body {
  background:black;
}

.slant {
  height:100px;
  background:blue;
  -webkit-clip-path: polygon(0 0, 100% 0, calc(100% - 40px) 100%, 0 100%);
  clip-path: polygon(0 0, 100% 0, calc(100% - 40px) 100%, 0 100%);
}

.slant.outside {
  width:200px;
  background:#1384dd;
}

.slant.inside {
  width:100px;
  background:#addafd;
}

.slant.insideInside {
  width:60px;
  background:white;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="slant outside">
  <div class="slant inside">
    <div class="slant insideInside"></div>
  </div>
</div></code>```

Title: Funnel chart with bars

Body:
Use clipping with polygon.  My polygons go from upper left, to upper right, to lower right, to lower left.  I used the css calc function in order to make the offset relative to the end.  I did a 40px slant, but if you want more a slant, simply change that number.

body {
  background:black;
}

.slant {
  height:100px;
  background:blue;
  -webkit-clip-path: polygon(0 0, 100% 0, calc(100% - 40px) 100%, 0 100%);
  clip-path: polygon(0 0, 100% 0, calc(100% - 40px) 100%, 0 100%);
}

.slant.outside {
  width:200px;
  background:#1384dd;
}

.slant.inside {
  width:100px;
  background:#addafd;
}

.slant.insideInside {
  width:60px;
  background:white;
}

<div class="slant outside">
  <div class="slant inside">
    <div class="slant insideInside"></div>
  </div>
</div>


问:
How do I change the size of a chart symbol in a javafx scatter chart?
I can change the symbol shape, colour, padding, radius but I can't seem to find a CSS item that will change the size of the symbol.

I had thought that if I recreated the symbol with smaller SVG path, that might be a way to do it, but it appears that my smaller shape just gets scaled up anyway.

I need smaller symbols but so far have not found a way to scale them.

答:
This is how I created a rectangle in SVG path then changed the size in css.</p>

```<code>.chart-symbol{
    -fx-shape: "M 20.0 20.0  v24.0 h 10.0  v-24   Z";
    -fx-padding: 7px 7px 7px 7px;
}
</code>```

Body:
This is how I created a rectangle in SVG path then changed the size in css.

.chart-symbol{
    -fx-shape: "M 20.0 20.0  v24.0 h 10.0  v-24   Z";
    -fx-padding: 7px 7px 7px 7px;
}


问:
why public_key_verify_signature() returns error if signature buffer is defined in file scope? (linux kernel crypto)
I'm using linux kernel 4.8.0.26, and writing a simple module verifying digital signature.

If the buffer given to struct public_key_signature as the signature bytes is defined in the file scope - public_key_verify_signature() returns -EINVAL.

If the buffer is defined inside the function - public_key_verify_signature() succeeds.

The code below returns error. to make it work - just move signature_bytes declaration inside rsa_verify():

```<code>/*
*  rsa-verify.c - simple kernel module using crypto api to verify digital signature.
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <crypto/public_key.h>

MODULE_LICENSE("GPL");

//public key in der format
u8 public_key_bytes[] = { 0x30,0x82,0x01,0x0a,0x02,0x82,0x01,0x01,0x00,0xe4,0xde,0x7c,0x12,0x6d,0xaa,0x6b,0xe9,0xb6,0x17,0x58,0x81,0x4e,0xad,0xfb,0x0e,0x21,0x39,0x4b,0x09,0x57,0xdd,0xa0,0xe1,0xfb,0x53,0x4b,0xc3,0xc3,0x0c,0x33,0xa7,0x37,0xfb,0xa8,0x47,0x26,0x2f,0xea,0x70,0x7c,0xbf,0x91,0x52,0xd8,0x2d,0x3a,0xd7,0xd9,0xba,0xa0,0x87,0x6d,0x8d,0x0c,0x7a,0xfe,0x7b,0x6c,0x7c,0x3d,0x57,0x73,0xb8,0xd1,0x55,0x2c,0x1e,0xc5,0x81,0xad,0x1a,0x59,0x71,0x12,0xa3,0x0b,0xee,0xe2,0x7b,0xf8,0x0c,0x8f,0xbf,0x68,0xbf,0x50,0x11,0x8b,0xa7,0xd7,0x00,0xb6,0xdc,0x65,0x4f,0xe3,0x75,0xdd,0xcc,0xa4,0x55,0x0c,0x70,0x27,0x23,0x9b,0x8d,0x1e,0x7d,0x66,0x33,0x06,0xad,0x62,0x37,0x1b,0xd4,0x68,0x50,0xcf,0x26,0x9d,0x60,0x6e,0xc0,0x3c,0xc7,0x15,0xcb,0x76,0x07,0x8a,0xc4,0xd3,0x84,0xf6,0xad,0x51,0xe0,0x63,0x31,0x55,0x4b,0x4a,0x96,0x4d,0x43,0xb7,0xd6,0x57,0xd6,0x6b,0x66,0x5c,0x60,0x35,0xf9,0x32,0x8d,0xe9,0x49,0x5c,0x3d,0x0f,0x77,0xfb,0x87,0x95,0xc2,0x57,0x8a,0xa2,0x9d,0xbe,0x42,0xc2,0x95,0x74,0x80,0xb1,0x10,0xd4,0x6c,0x37,0xb6,0xc5,0xed,0x73,0x2b,0xdd,0x44,0x87,0xf9,0xed,0x14,0xec,0x58,0x46,0x86,0xa4,0x0d,0x38,0x0f,0xcb,0x61,0xf9,0x39,0xf5,0x06,0xe6,0x20,0x0a,0x02,0xed,0x01,0xc7,0x77,0x9e,0x4e,0xaa,0x45,0xcf,0xc9,0xb2,0xa6,0xd1,0xf0,0x2c,0x6e,0x33,0xbb,0x49,0x18,0x7a,0x0a,0x55,0x06,0x7b,0xd8,0x6f,0x08,0xd6,0xc7,0xfd,0x41,0x2b,0x37,0x77,0x40,0x1e,0x63,0xf8,0x27,0x58,0x23,0x02,0x03,0x01,0x00,0x01 };

//SHA-256 digest for the data "asaf"
u8 digest[] = { 0x6f,0x82,0xd3,0x9a,0x2c,0x53,0xaf,0xa5,0x00,0xd4,0x6e,0x0e,0xfb,0xe1,0xa8,0xd5,0x6c,0xc4,0x69,0x4d,0xde,0x94,0x66,0xde,0xb2,0xb7,0x76,0x30,0xd1,0xf7,0x53,0x57 };

//given signature of data "asaf" using a private key
u8 signature_bytes[] = { 0xb7,0xa8,0x48,0x1c,0x31,0x80,0xab,0xa3,0x16,0x23,0xc8,0xb8,0x2b,0xf6,0x99,0x5b,0x90,0x64,0xe1,0x4f,0xda,0xe4,0xfc,0x4c,0xa4,0xbe,0x58,0x9c,0xec,0xef,0x9c,0x92,0x56,0x05,0x3e,0xa3,0xcc,0x00,0xd3,0x7e,0xa3,0xab,0x09,0xd7,0xc9,0x3f,0x2b,0x28,0x4f,0x14,0x57,0x2a,0x24,0x56,0x07,0x55,0xc1,0xbe,0xf8,0xbe,0x41,0x8d,0xa3,0xa4,0x79,0xdd,0x27,0x3e,0xc6,0x32,0xe1,0x80,0xe3,0x40,0x27,0x48,0x9f,0xe8,0xb6,0x87,0xee,0x4e,0x8a,0x82,0x6c,0x6c,0x32,0x50,0x7a,0x28,0x63,0xbc,0xb2,0xd4,0x59,0x50,0x66,0x07,0xb9,0x93,0x27,0x1b,0x45,0x35,0x00,0x15,0xe2,0x6e,0x7d,0xf8,0xb6,0x75,0x9b,0x3a,0xb8,0xc5,0xe5,0x1d,0xda,0x4c,0xdc,0x01,0xb2,0x69,0x7f,0x87,0x08,0x6e,0x11,0xb7,0xcd,0x1f,0x9f,0xaa,0xb4,0xe4,0x13,0x4e,0x67,0x1f,0x60,0x9c,0x30,0x7d,0xec,0xf1,0xf4,0x0d,0x72,0x62,0x39,0x51,0x82,0x9f,0x5f,0x25,0x1f,0x4a,0xff,0x73,0x88,0xf1,0x8e,0x2d,0x6e,0xec,0xa9,0x2a,0xea,0xca,0x49,0x39,0x6d,0x00,0xeb,0xb8,0x25,0x2b,0x02,0x06,0xcf,0xf3,0xa7,0xe2,0x14,0xcd,0xd6,0x5c,0xfa,0xd0,0x87,0x6b,0x29,0xc5,0xc4,0xe0,0x97,0x76,0x6b,0xd8,0x7c,0x49,0x63,0x2e,0xc9,0x96,0xf6,0xb2,0x3b,0x2d,0x35,0x77,0x3c,0x33,0x09,0x39,0xa6,0xff,0xb2,0x98,0x27,0x61,0x32,0x5b,0x30,0x30,0xd5,0xee,0xa0,0xcb,0x0a,0xb1,0xc7,0x6d,0x7b,0xf5,0x1a,0x12,0x25,0xe1,0xf0,0x78,0x4f,0xd9,0x54,0x32,0xb7,0x3b,0x6f,0xf3,0x33,0x9e,0xa8,0x58,0x7c,0xa3 };

int rsa_verify(void)
{
    // u8 signature_bytes[]... if it was here - it would work

    struct public_key rsa_pub_key = {
        .key = public_key_bytes,
        .keylen = (u32)(sizeof(public_key_bytes)),
        .pkey_algo = "rsa",
        .id_type = "X509"
    };

    struct public_key_signature sig = {
        .s = signature_bytes,
        .s_size = (u32)(sizeof(signature_bytes)),
        .digest = digest,
        .digest_size = (u8)(sizeof(digest)),
        .pkey_algo = "rsa",
        .hash_algo = "sha256"
    };

    int error = public_key_verify_signature(&rsa_pub_key, &sig);
    if (error) {
        pr_info("error verifying. error %d\n", error);
        return -1;
    }

    pr_info("verified successfuly!!!\n");
    return 0;
}

int init_module(void)
{
    printk(KERN_INFO "Hello rsa-verify\n");
    return rsa_verify();
}

void cleanup_module(void)
{
    printk(KERN_INFO "Goodbye rsa-verify\n");
}
</code>```

Makefile:

```<code>obj-m += rsa-verify.o

all:
    make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules EXTRA_CFLAGS="$(EXTRA_CFLAGS)"

clean:
    make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean
</code>```

(gcc version 6.1.1)

答:
The reason is that when you follow the code, you can see the following calls:

```<code>public_key_verify_signature();               // will call:
sg_init_one(&sig_sg, sig->s, sig->s_size);   // will call:
sg_set_buf(sg, buf, buflen);
</code>```

sg_set_buf code is:

```<code>#ifdef CONFIG_DEBUG_SG
    BUG_ON(!virt_addr_valid(buf));
#endif
    sg_set_page(sg, virt_to_page(buf), buflen, offset_in_page(buf));
</code>```

and virt_to_page won't work, because elf sections are loaded to pages allocated with vmalloc.

Body:
I'm using linux kernel 4.8.0.26, and writing a simple module verifying digital signature.

If the buffer given to struct public_key_signature as the signature bytes is defined in the file scope - public_key_verify_signature() returns -EINVAL.

If the buffer is defined inside the function - public_key_verify_signature() succeeds.

The code below returns error. to make it work - just move signature_bytes declaration inside rsa_verify():

/*
*  rsa-verify.c - simple kernel module using crypto api to verify digital signature.
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <crypto/public_key.h>

MODULE_LICENSE("GPL");

//public key in der format
u8 public_key_bytes[] = { 0x30,0x82,0x01,0x0a,0x02,0x82,0x01,0x01,0x00,0xe4,0xde,0x7c,0x12,0x6d,0xaa,0x6b,0xe9,0xb6,0x17,0x58,0x81,0x4e,0xad,0xfb,0x0e,0x21,0x39,0x4b,0x09,0x57,0xdd,0xa0,0xe1,0xfb,0x53,0x4b,0xc3,0xc3,0x0c,0x33,0xa7,0x37,0xfb,0xa8,0x47,0x26,0x2f,0xea,0x70,0x7c,0xbf,0x91,0x52,0xd8,0x2d,0x3a,0xd7,0xd9,0xba,0xa0,0x87,0x6d,0x8d,0x0c,0x7a,0xfe,0x7b,0x6c,0x7c,0x3d,0x57,0x73,0xb8,0xd1,0x55,0x2c,0x1e,0xc5,0x81,0xad,0x1a,0x59,0x71,0x12,0xa3,0x0b,0xee,0xe2,0x7b,0xf8,0x0c,0x8f,0xbf,0x68,0xbf,0x50,0x11,0x8b,0xa7,0xd7,0x00,0xb6,0xdc,0x65,0x4f,0xe3,0x75,0xdd,0xcc,0xa4,0x55,0x0c,0x70,0x27,0x23,0x9b,0x8d,0x1e,0x7d,0x66,0x33,0x06,0xad,0x62,0x37,0x1b,0xd4,0x68,0x50,0xcf,0x26,0x9d,0x60,0x6e,0xc0,0x3c,0xc7,0x15,0xcb,0x76,0x07,0x8a,0xc4,0xd3,0x84,0xf6,0xad,0x51,0xe0,0x63,0x31,0x55,0x4b,0x4a,0x96,0x4d,0x43,0xb7,0xd6,0x57,0xd6,0x6b,0x66,0x5c,0x60,0x35,0xf9,0x32,0x8d,0xe9,0x49,0x5c,0x3d,0x0f,0x77,0xfb,0x87,0x95,0xc2,0x57,0x8a,0xa2,0x9d,0xbe,0x42,0xc2,0x95,0x74,0x80,0xb1,0x10,0xd4,0x6c,0x37,0xb6,0xc5,0xed,0x73,0x2b,0xdd,0x44,0x87,0xf9,0xed,0x14,0xec,0x58,0x46,0x86,0xa4,0x0d,0x38,0x0f,0xcb,0x61,0xf9,0x39,0xf5,0x06,0xe6,0x20,0x0a,0x02,0xed,0x01,0xc7,0x77,0x9e,0x4e,0xaa,0x45,0xcf,0xc9,0xb2,0xa6,0xd1,0xf0,0x2c,0x6e,0x33,0xbb,0x49,0x18,0x7a,0x0a,0x55,0x06,0x7b,0xd8,0x6f,0x08,0xd6,0xc7,0xfd,0x41,0x2b,0x37,0x77,0x40,0x1e,0x63,0xf8,0x27,0x58,0x23,0x02,0x03,0x01,0x00,0x01 };

//SHA-256 digest for the data "asaf"
u8 digest[] = { 0x6f,0x82,0xd3,0x9a,0x2c,0x53,0xaf,0xa5,0x00,0xd4,0x6e,0x0e,0xfb,0xe1,0xa8,0xd5,0x6c,0xc4,0x69,0x4d,0xde,0x94,0x66,0xde,0xb2,0xb7,0x76,0x30,0xd1,0xf7,0x53,0x57 };

//given signature of data "asaf" using a private key
u8 signature_bytes[] = { 0xb7,0xa8,0x48,0x1c,0x31,0x80,0xab,0xa3,0x16,0x23,0xc8,0xb8,0x2b,0xf6,0x99,0x5b,0x90,0x64,0xe1,0x4f,0xda,0xe4,0xfc,0x4c,0xa4,0xbe,0x58,0x9c,0xec,0xef,0x9c,0x92,0x56,0x05,0x3e,0xa3,0xcc,0x00,0xd3,0x7e,0xa3,0xab,0x09,0xd7,0xc9,0x3f,0x2b,0x28,0x4f,0x14,0x57,0x2a,0x24,0x56,0x07,0x55,0xc1,0xbe,0xf8,0xbe,0x41,0x8d,0xa3,0xa4,0x79,0xdd,0x27,0x3e,0xc6,0x32,0xe1,0x80,0xe3,0x40,0x27,0x48,0x9f,0xe8,0xb6,0x87,0xee,0x4e,0x8a,0x82,0x6c,0x6c,0x32,0x50,0x7a,0x28,0x63,0xbc,0xb2,0xd4,0x59,0x50,0x66,0x07,0xb9,0x93,0x27,0x1b,0x45,0x35,0x00,0x15,0xe2,0x6e,0x7d,0xf8,0xb6,0x75,0x9b,0x3a,0xb8,0xc5,0xe5,0x1d,0xda,0x4c,0xdc,0x01,0xb2,0x69,0x7f,0x87,0x08,0x6e,0x11,0xb7,0xcd,0x1f,0x9f,0xaa,0xb4,0xe4,0x13,0x4e,0x67,0x1f,0x60,0x9c,0x30,0x7d,0xec,0xf1,0xf4,0x0d,0x72,0x62,0x39,0x51,0x82,0x9f,0x5f,0x25,0x1f,0x4a,0xff,0x73,0x88,0xf1,0x8e,0x2d,0x6e,0xec,0xa9,0x2a,0xea,0xca,0x49,0x39,0x6d,0x00,0xeb,0xb8,0x25,0x2b,0x02,0x06,0xcf,0xf3,0xa7,0xe2,0x14,0xcd,0xd6,0x5c,0xfa,0xd0,0x87,0x6b,0x29,0xc5,0xc4,0xe0,0x97,0x76,0x6b,0xd8,0x7c,0x49,0x63,0x2e,0xc9,0x96,0xf6,0xb2,0x3b,0x2d,0x35,0x77,0x3c,0x33,0x09,0x39,0xa6,0xff,0xb2,0x98,0x27,0x61,0x32,0x5b,0x30,0x30,0xd5,0xee,0xa0,0xcb,0x0a,0xb1,0xc7,0x6d,0x7b,0xf5,0x1a,0x12,0x25,0xe1,0xf0,0x78,0x4f,0xd9,0x54,0x32,0xb7,0x3b,0x6f,0xf3,0x33,0x9e,0xa8,0x58,0x7c,0xa3 };

int rsa_verify(void)
{
    // u8 signature_bytes[]... if it was here - it would work

    struct public_key rsa_pub_key = {
        .key = public_key_bytes,
        .keylen = (u32)(sizeof(public_key_bytes)),
        .pkey_algo = "rsa",
        .id_type = "X509"
    };

    struct public_key_signature sig = {
        .s = signature_bytes,
        .s_size = (u32)(sizeof(signature_bytes)),
        .digest = digest,
        .digest_size = (u8)(sizeof(digest)),
        .pkey_algo = "rsa",
        .hash_algo = "sha256"
    };

    int error = public_key_verify_signature(&rsa_pub_key, &sig);
    if (error) {
        pr_info("error verifying. error %d\n", error);
        return -1;
    }

    pr_info("verified successfuly!!!\n");
    return 0;
}

int init_module(void)
{
    printk(KERN_INFO "Hello rsa-verify\n");
    return rsa_verify();
}

void cleanup_module(void)
{
    printk(KERN_INFO "Goodbye rsa-verify\n");
}

Makefile:

obj-m += rsa-verify.o

all:
    make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules EXTRA_CFLAGS="$(EXTRA_CFLAGS)"

clean:
    make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean

(gcc version 6.1.1)

Body:
The reason is that when you follow the code, you can see the following calls:

public_key_verify_signature();               // will call:
sg_init_one(&sig_sg, sig->s, sig->s_size);   // will call:
sg_set_buf(sg, buf, buflen);

sg_set_buf code is:

#ifdef CONFIG_DEBUG_SG
    BUG_ON(!virt_addr_valid(buf));
#endif
    sg_set_page(sg, virt_to_page(buf), buflen, offset_in_page(buf));

and virt_to_page won't work, because elf sections are loaded to pages allocated with vmalloc.

ContentLicense: CC BY-SA 4.0


问:
Android studio firebase banner ads id not working with intertial ads ids
I have use banner ads in my app and want to add interstitial ads too with same firebase ad mob project. How can I do it? I have use banner id with the interstitial ads id but when I do it, it doesn't display it. Help me to get out of this. Add interstitial ads in fire-base ad mob projects which already banner ads id have in that project.    </p>

```<code>  mAdView = (AdView) findViewById(R.id.adView);
    AdRequest adRequest = new AdRequest.Builder().build();
    mAdView.loadAd(adRequest);

    mInterstitialAd = new InterstitialAd(this);
    mInterstitialAd.setAdUnitId(" ca-app-pub-6314200474000962/6862626336");
    requestNewInterstitial();
    mInterstitialAd.setAdListener(new AdListener() {
        @Override
        public void onAdClosed() {
            requestNewInterstitial();
        }
    });

    requestNewInterstitial();
</code>```

答: You need to explicitly call mInterstitialAd.show() at whatever natural breakpoint in your app you intend on showing the interstitial.

Body:
I have use banner ads in my app and want to add interstitial ads too with same firebase ad mob project. How can I do it? I have use banner id with the interstitial ads id but when I do it, it doesn't display it. Help me to get out of this. Add interstitial ads in fire-base ad mob projects which already banner ads id have in that project.

  mAdView = (AdView) findViewById(R.id.adView);
    AdRequest adRequest = new AdRequest.Builder().build();
    mAdView.loadAd(adRequest);

    mInterstitialAd = new InterstitialAd(this);
    mInterstitialAd.setAdUnitId(" ca-app-pub-6314200474000962/6862626336");
    requestNewInterstitial();
    mInterstitialAd.setAdListener(new AdListener() {
        @Override
        public void onAdClosed() {
            requestNewInterstitial();
        }
    });

    requestNewInterstitial();


问:
How to access twitter moment API
I can embed one twitter moment into my website, I am curious, if Twitter offers any public moment api (similar to their search api) so I can automatically get their their top 4 twitter moments each day

//This is i used their oembed to get one moment, if I know the id

twttr.widgets.createMoment(
  '650667182356082688',
  document.getElementById('widget-content-twitter'),
  {
    limit: 1
  }
);
```

答: There are no public API endpoints for Moments at this time.</p>

Title: How to access twitter moment API


问:
Convert the values in a column into row names in an existing data frame
I would like to convert the values in a column of an existing data frame into row names. Is is possible to do this without exporting the data frame and then reimporting it with a row.names =  call?

For example I would like to convert:

```<code> > samp
     names Var.1 Var.2 Var.3
 1     A     1     5     0
 2     B     2     4     1
 3     C     3     3     2
 4     D     4     2     3
 5     E     5     1     4
</code>```

Into:

```<code>> samp.with.rownames
     Var.1 Var.2 Var.3
A     1     5     0
B     2     4     1
C     3     3     2
D     4     2     3
E     5     1     4
</code>```

答:
As of 2016 you can also use the tidyverse.

```<code>library(tidyverse)
samp %>% remove_rownames %>% column_to_rownames(var="names")
</code>```

Body:
I would like to convert the values in a column of an existing data frame into row names. Is is possible to do this without exporting the data frame and then reimporting it with a row.names =  call?

For example I would like to convert:

 > samp
     names Var.1 Var.2 Var.3
 1     A     1     5     0
 2     B     2     4     1
 3     C     3     3     2
 4     D     4     2     3
 5     E     5     1     4

Into:

> samp.with.rownames
     Var.1 Var.2 Var.3
A     1     5     0
B     2     4     1
C     3     3     2
D     4     2     3
E     5     1     4

Body:
As of 2016 you can also use the tidyverse.

library(tidyverse)
samp %>% remove_rownames %>% column_to_rownames(var="names")


问:
Producing random float from negative to positive range?
I am trying to produce a random float within the range -50.0 and 50.0 inclusively, using rand(). I've looked everywhere for an answer but it deals with ints and % operator.</p>

答:
Honestly, all present answers don't explain that there is a change in distribution in their solutions(I am assuming that rand() follows the uniform distribution! correct me if I am wrong please). Use a library please, and my recommendation is using the new facilities in C++0x:

```<code>#include <random>
#include <functional>

int main()
{
    std::mt19937 generator;
    std::uniform_real_distribution<float> uniform_distribution(-50.0, 50.0);
    auto my_rand = std::bind(uniform_distribution, generator);
}
</code>```

If you can't, Boost is a perfect choice. That way, you can use my_rand() just like good ol' rand():

```<code>std::vector<float> random_numbers(1000);
std::generate(random_numbers.begin(), random_numbers.end(), my_rand);
</code>```

Body:
Honestly, all present answers don't explain that there is a change in distribution in their solutions(I am assuming that rand() follows the uniform distribution! correct me if I am wrong please). Use a library please, and my recommendation is using the new facilities in C++0x:

#include <random>
#include <functional>

int main()
{
    std::mt19937 generator;
    std::uniform_real_distribution<float> uniform_distribution(-50.0, 50.0);
    auto my_rand = std::bind(uniform_distribution, generator);
}

If you can't, Boost is a perfect choice. That way, you can use my_rand() just like good ol' rand():

std::vector<float> random_numbers(1000);
std::generate(random_numbers.begin(), random_numbers.end(), my_rand);


问:
how to refresh JSESSIONID cookie after login
A product I work on got a tough security audit by a potential customer and they are upset that Tomcat sets a JSESSIONID cookie before authentication has happened.  That is, Tomcat sets this cookie when our stateless Login Page loads, but before login.

They suggest either of the following:

issue a new JSESSIONID cookie after login

prevent a JSESSIONID cookie from being set in the first place on the Login Page (i.e., before authentication has happened)

I have been poring through everything JSESSIONID-related on this site and can find no easy answer.  I'm just hoping for some ideas.  My best solutions for each are:

right after login, clone the Session (minus the id) by copying all the attributes, invalidating the old session, creating a new one, copying the values, associating it with the request, and hoping that works.

create a servlet Filter at the very end of the chain that strips out the JSESSIONID cookie before the Login Page is initially loaded.  And then hope the login request works out without a JSESSIONID set.

I've got to get some sleep, but will be attempting these in the morning.  It would be awesome to get some feedback or better suggestions from people much smarter than myself -- like you!

Regardless, I'll post my results here because it seems like a lot of other people have been wanting to do something similar.

答: If you are using Tomcat and want to apply this globally to all your servlets which use Tomcat's authentication mechanism, you can write a Valve to force this behavior, as shown in this sample code.</p>


问:
Piping the json body only with requirejs
So I started using requestjs which I am happy with, but I wonder if there is some way to pipe in a fashion, like you would do with promises:

```<code>function foo(url) {
  return request({ "url": url, "json": true })
}
let result = foo("https://jsonplaceholder.typicode.com/posts/1")
result.pipe(process.stdout)
result.on('data', console.log)
</code>```

with pipe I can't access the object itself, so I can't only stream the body

and on doesn't respect my specification to parse the response to json

So I can't use any of those to only access the json I receive. Of course I can use JSON.parse, but I'm looking for some easier way to operate on the response (similar to promises) and I feel like I'm missing the big picture.

答:
Is there a reason you need to use streams?  You can always wrap request in a promise.

This is very high level but hopefully this can get you on the right path.

```<code>function makeRequest(params) {
  return Promise((resolve, reject) => {
    request(params, (err, response) => {
      if (err) {
        return reject(err);
      }
      return resolve(response);
    };
  });
}

const params = {
  url: 'foo.com',
  method: 'GET',
  json: true,
};

makeRequest(params)
  .then(response => {
    if (response.statusCode === 200) {
      return Promise.resolve(response.body);
    } else if (response.statucCode === 404) {
      const err = {
        message: 'Not Found',
        code: 404,
      };
      return Promise.reject(err);
    }
  })
  .then(body => // do something fun with data)
  .catch(err => // handle error);
</code>```

Body:
So I started using requestjs which I am happy with, but I wonder if there is some way to pipe in a fashion, like you would do with promises:

function foo(url) {
  return request({ "url": url, "json": true })
}
let result = foo("https://jsonplaceholder.typicode.com/posts/1")
result.pipe(process.stdout)
result.on('data', console.log)

with pipe I can't access the object itself, so I can't only stream the body

and on doesn't respect my specification to parse the response to json

So I can't use any of those to only access the json I receive. Of course I can use JSON.parse, but I'm looking for some easier way to operate on the response (similar to promises) and I feel like I'm missing the big picture.

Body:
Is there a reason you need to use streams?  You can always wrap request in a promise.

This is very high level but hopefully this can get you on the right path.

function makeRequest(params) {
  return Promise((resolve, reject) => {
    request(params, (err, response) => {
      if (err) {
        return reject(err);
      }
      return resolve(response);
    };
  });
}

const params = {
  url: 'foo.com',
  method: 'GET',
  json: true,
};

makeRequest(params)
  .then(response => {
    if (response.statusCode === 200) {
      return Promise.resolve(response.body);
    } else if (response.statucCode === 404) {
      const err = {
        message: 'Not Found',
        code: 404,
      };
      return Promise.reject(err);
    }
  })
  .then(body => // do something fun with data)
  .catch(err => // handle error);


问:
Numpy argmax - random tie breaking
In numpy.argmax function, tie breaking between multiple max elements is so that the first element is returned.
Is there a functionality for randomizing tie breaking so that all maximum numbers have equal chance of being selected?

Below is an example directly from numpy.argmax documentation.

```<code>>>> b = np.arange(6)
>>> b[1] = 5
>>> b
array([0, 5, 2, 3, 4, 5])
>>> np.argmax(b) # Only the first occurrence is returned.
1
</code>```

I am looking for ways so that 1st and 5th elements in the list are returned with equal probability.

Thank you!

答:
In the case of a multi-dimensional array, choice won't work.

An alternative is

```<code>def randargmax(b,**kw):
  """ a random tie-breaking argmax"""
  return np.argmax(np.random.random(b.shape) * (b==b.max()), **kw)
</code>```

If for some reason generating random floats is slower than some other method, random.random can be replaced with that other method.

Title: Numpy argmax - random tie breaking

Body:
In numpy.argmax function, tie breaking between multiple max elements is so that the first element is returned.
Is there a functionality for randomizing tie breaking so that all maximum numbers have equal chance of being selected?

Below is an example directly from numpy.argmax documentation.

>>> b = np.arange(6)
>>> b[1] = 5
>>> b
array([0, 5, 2, 3, 4, 5])
>>> np.argmax(b) # Only the first occurrence is returned.
1

I am looking for ways so that 1st and 5th elements in the list are returned with equal probability.

Thank you!

Body:
In the case of a multi-dimensional array, choice won't work.

An alternative is

def randargmax(b,**kw):
  """ a random tie-breaking argmax"""
  return np.argmax(np.random.random(b.shape) * (b==b.max()), **kw)

If for some reason generating random floats is slower than some other method, random.random can be replaced with that other method.


问:
Removing Ant logging prefix when running via Gradle
Is it possible to remove the logging prefix added for Ant when importing its tasks into Gradle?

Here is the example from the official documentation:

build.gradle

```<code>ant.importBuild 'build.xml'
</code>```

build.xml

```<code><project>
    <target name="hello">
        <echo>Hello, from Ant</echo>
    </target>
</project>
</code>```

Output of gradle hello:

```<code>> gradle hello
:hello
[ant:echo] Hello, from Ant

BUILD SUCCESSFUL

Total time: 1 secs
</code>```

Instead of this, would it be possible to have the following?

```<code>> gradle hello
:hello
Hello, from Ant

BUILD SUCCESSFUL

Total time: 1 secs
</code>```

Ideally, the solution would also fix problems with other Ant messages such as [ant:input].

答:
I would recommend creating your own custom gradle logger where you can control what is logged to the console.

Check this out for more information: https://docs.gradle.org/current/userguide/logging.html#sec:changing_what_gradle_logs

Body:
Is it possible to remove the logging prefix added for Ant when importing its tasks into Gradle?

Here is the example from the official documentation:

build.gradle

ant.importBuild 'build.xml'

build.xml

<project>
    <target name="hello">
        <echo>Hello, from Ant</echo>
    </target>
</project>

Output of gradle hello:

> gradle hello
:hello
[ant:echo] Hello, from Ant

BUILD SUCCESSFUL

Total time: 1 secs

Instead of this, would it be possible to have the following?

> gradle hello
:hello
Hello, from Ant

BUILD SUCCESSFUL

Total time: 1 secs

Ideally, the solution would also fix problems with other Ant messages such as [ant:input].


问:
builtins.TypeError: __init__() missing 2 required positional arguments: 'height' and 'radius'
I am getting an error that says I am missing 2 required positional arguments: 'height' and 'radius.' I feel like I have tried everything but I know I am missing something small. Any help?
Thanks

```<code># import math
import math

class SodaCan :
    # Constructs sodaCan with a given height and radius
    # @param height = given height and radius = given radius
    def __init__(self, height, radius):
        self._height = height
        self._radius = radius

    # Constructs the volume with the given height and radius
    def volume(self):
        self._volume = (pi * (self._radius ** 2) * self._height)

    # Constructs the Surface Area with the given height and radius
    def surfaceArea(self):
        self._surfaceArea = (2 * pi * self._radius * self._height) + (2 * pi   * (self._radius)**2)

    # Return the volume
    def getVolume(self):
        return self._volume

    # Return the Surface Area
    def getSurfaceArea(self):
        return self._surfaceArea
</code>```

I am not sure what I am doing wrong here. Below there is the test program for my code.

```<code>##
# This program test the sodaCan.py
##

# import math so the program can read pi
import math

# from the file folder, ipmort the code from program 'sodaCan'
from sodaCan import SodaCan

mySodaCan = SodaCan()
mySodaCan.height(10)
mySodaCan.radius(4)

print(mySodaCan.getVolume())
print(mySodaCan.getSurfaceArea())
</code>```

答:
When you define the initializer like this:

```<code>class SodaCan:

    def __init__(self, height, radius):
        ...
</code>```

You are saying that height and radius are required.  They must be specified in order to create a soda can instance.

```<code>mySodaCan = SodaCan(height=10, radius=4)
</code>```

If you want them to be optional, you may specify default values for those arguments when you define the __init__ method.  Then when you create an instance, the arguments will take the default values if omitted when creating an instance.

Body:
I am getting an error that says I am missing 2 required positional arguments: 'height' and 'radius.' I feel like I have tried everything but I know I am missing something small. Any help?
Thanks

# import math
import math

class SodaCan :
    # Constructs sodaCan with a given height and radius
    # @param height = given height and radius = given radius
    def __init__(self, height, radius):
        self._height = height
        self._radius = radius

    # Constructs the volume with the given height and radius
    def volume(self):
        self._volume = (pi * (self._radius ** 2) * self._height)

    # Constructs the Surface Area with the given height and radius
    def surfaceArea(self):
        self._surfaceArea = (2 * pi * self._radius * self._height) + (2 * pi   * (self._radius)**2)

    # Return the volume
    def getVolume(self):
        return self._volume

    # Return the Surface Area
    def getSurfaceArea(self):
        return self._surfaceArea

I am not sure what I am doing wrong here. Below there is the test program for my code.

##
# This program test the sodaCan.py
##

# import math so the program can read pi
import math

# from the file folder, ipmort the code from program 'sodaCan'
from sodaCan import SodaCan

mySodaCan = SodaCan()
mySodaCan.height(10)
mySodaCan.radius(4)

print(mySodaCan.getVolume())
print(mySodaCan.getSurfaceArea())

Body:
When you define the initializer like this:

class SodaCan:

    def __init__(self, height, radius):
        ...

You are saying that height and radius are required.  They must be specified in order to create a soda can instance.

mySodaCan = SodaCan(height=10, radius=4)

If you want them to be optional, you may specify default values for those arguments when you define the __init__ method.  Then when you create an instance, the arguments will take the default values if omitted when creating an instance.


问:
PHP MySQL Group BY Having issue
Suppose I have a table like:

```<code>ID|Word |Reference
1 |Dog  |1
1 |Fish |2
1 |Sheep|3
2 |Dog  |4
2 |Fish |5
3 |Sheep|6
4 |Dog  |7
</code>```

I want to select all ID's that have the word Dog AND Sheep. So the result should be ID's: 1 and 2. I tried using this query:

```<code>SELECT ID FROM `Table` WHERE Word='Dog' OR Word='Fish' GROUP BY ID Having Word='Dog AND Word='Fish'
</code>```

However, this AND in the Having clause makes me get 0 results. So, am I doing something wrong or is there another way to achieve wat I want based on MySQL query only (to optimize speed, since it has to search through many rows with the same setup as in the example above)

Basically the problem is the AND statement over multiple rows with the same ID.

UPDATE:

I need to get the reference for the ID's that where found. E.g. when the ID 1 and 2 are returned I need to know that ID 1 has reference 1 and 2. ID 2 has reference 3 and 4. Currently, I'm using this query:

```<code>SELECT ID FROM `Test` WHERE Word in ('Dog', 'Fish') GROUP BY ID HAVING  count(DISTINCT Word) = 2;
</code>```

Thanks

答:
You need to join the table on itself. This way you can pick up where the id's are the same for instances where dog and sheep overlap.
Try this:</p>

```<code>declare @t table (id int ,  Word varchar(10) )
insert into @t (ID, Word) values (1, 'Dog'),
(1 ,'Fish'),
(1 ,'Sheep'),
(2 ,'Dog'),
(2 ,'Sheep'),
(3 ,'Sheep'),
(4 ,'Dog')

select t.ID
from @t as t
join @t as t1 on t1.id = t.id
where t.word = 'Dog' and t1.word = 'Sheep'
</code>```

Title: PHP MySQL Group BY Having issue

Body:
Suppose I have a table like:

ID|Word |Reference
1 |Dog  |1
1 |Fish |2
1 |Sheep|3
2 |Dog  |4
2 |Fish |5
3 |Sheep|6
4 |Dog  |7

I want to select all ID's that have the word Dog AND Sheep. So the result should be ID's: 1 and 2. I tried using this query:

SELECT ID FROM `Table` WHERE Word='Dog' OR Word='Fish' GROUP BY ID Having Word='Dog AND Word='Fish'

However, this AND in the Having clause makes me get 0 results. So, am I doing something wrong or is there another way to achieve wat I want based on MySQL query only (to optimize speed, since it has to search through many rows with the same setup as in the example above)

Basically the problem is the AND statement over multiple rows with the same ID.

UPDATE:

I need to get the reference for the ID's that where found. E.g. when the ID 1 and 2 are returned I need to know that ID 1 has reference 1 and 2. ID 2 has reference 3 and 4. Currently, I'm using this query:

SELECT ID FROM `Test` WHERE Word in ('Dog', 'Fish') GROUP BY ID HAVING  count(DISTINCT Word) = 2;

Thanks

Body:
You need to join the table on itself. This way you can pick up where the id's are the same for instances where dog and sheep overlap.
Try this:

declare @t table (id int ,  Word varchar(10) )
insert into @t (ID, Word) values (1, 'Dog'),
(1 ,'Fish'),
(1 ,'Sheep'),
(2 ,'Dog'),
(2 ,'Sheep'),
(3 ,'Sheep'),
(4 ,'Dog')

select t.ID
from @t as t
join @t as t1 on t1.id = t.id
where t.word = 'Dog' and t1.word = 'Sheep'


问:
Unable to get property '0' of undefined or null reference
I am getting the following error which shows up in IE/Edge only.

```<code>Unable to get propety '0' of undefined or null reference
</code>```

I am using RxJs observables in the following manner:

```<code>getVersions(): void {
  this.databaseService.getProductVersions().subscribe(
    (versions) => this.processVersions(versions),
    (error) => console.error(error)
  );
}
</code>```

and in Chrome/Firefox this works without errors. productVersions looks like this:

```<code>getProductVersions(): Observable<any[]> {
    let options = this.header();
    let url: string = this.baseUrl + 'admin/version/searchall';
    return this.http.get(url, options).map(
        response => response.json(),
        error => console.log(error)
    );
}
</code>```

Am I using the Observable incorrectly. Should I be unsubscribing? (My api call is finite so from what I've read unsubscribing is not necessary).

答: I thought I had ruled out the 3rd party library I was using. But I found that it was happening there. So it was not my code causing the issue. Thanks @Martin and @Jakub for your help. I am at least now using the map/catch methods correctly thanks to you.</p>

Body:
I am getting the following error which shows up in IE/Edge only.

Unable to get propety '0' of undefined or null reference

I am using RxJs observables in the following manner:

getVersions(): void {
  this.databaseService.getProductVersions().subscribe(
    (versions) => this.processVersions(versions),
    (error) => console.error(error)
  );
}

and in Chrome/Firefox this works without errors. productVersions looks like this:

getProductVersions(): Observable<any[]> {
    let options = this.header();
    let url: string = this.baseUrl + 'admin/version/searchall';
    return this.http.get(url, options).map(
        response => response.json(),
        error => console.log(error)
    );
}

Am I using the Observable incorrectly. Should I be unsubscribing? (My api call is finite so from what I've read unsubscribing is not necessary).


答:
You need the pass the height and radius when you initialize the class. Arguments in the init class mean that they have to be passed when you initialize the class. Something like this would work:</p>

```<code>height = 40
radius = 10
a = SodaCan(height, radius)
</code>```

Title: builtins.TypeError: __init__() missing 2 required positional arguments: 'height' and 'radius'

Body:
You need the pass the height and radius when you initialize the class. Arguments in the init class mean that they have to be passed when you initialize the class. Something like this would work:

height = 40
radius = 10
a = SodaCan(height, radius)


问:
Reformatting SubjectDN Data Using Python
I have a bunch of python code set up that retrieves the subjectDN from a list of certificates based on some search criteria.  All information for each certificate is done on a line by line basis.  The format is as follows:

C="ISO code", ST="province", L="locality", O="org name", OU="org unit", CN="name of certificate"

An example of one of my files would be:

C=US, ST=California, L=Oakland, O=Acme Ltd., OU=Web Services, CN=www.acme.com

C=US, ST=California, L=Oakland, O=Acme Ltd., OU=Web Services, CN=portal.acme.com

C=US, ST=California, L=Oakland, O=Acme Ltd., OU=Web Services, CN=sardine.acme.com

I would like to transform this into a working CSV file which normally would seem pretty easy but some of these rows contain additional data:

businessCategory=Private Organization, juridictionCountry=US, C=US, ST=California, L=Oakland, O=Acme Ltd., OU=Web Services, CN=www.acme.com

This additional data throws all of the columns out of line.

I want to do two things with this data.

I want to have only the fields from the first example show up in the CSV file for each column; so C, ST, L, O, OU and CN (omitting the weird fields found in various certificates).

I want to omit the "C=" or "ST=" from each value.

I have tried using the CSV module but I can only get this data formatted exactly the same as it is now.  I have also tried using the re module within python to rewrite some of the lines but I'm very confused on the expressions with re.

The idea that I had was to read each line in the output file that I have and then include a for loop for each line to seek out the fields I need and rewrite them.  Something like:

```<code>def rewrite()
    common_name = #here is where I would do a re command
    if #CN= x, is found (where x is the data I want):
        ofile.write("www.acme.com")
    organization = #here is where I would do a re command
    if #O= x, is found (where x is the data I want):
        ofile.write("Acme Ltd.")
--snip--
    ofile.write("\n")
</code>```

Essentially I would run this function for each line in the input file to an output file.  Something like:

```<code>with open(...) as f:
    for line in f:
        rewrite()
</code>```

Is this a good way to do this or is there an easier way?  Can someone help me with the regular expression to do this?

答:
Well, if you can be sure about the order  of the entries, you could extract the data with a regular expression and form a pandas dataframe out of it afterwards:

```<code>import re, pandas as pd

string = """
C=US, ST=California, L=Oakland, O=Acme Ltd., OU=Web Services, CN=www.acme.com

C=US, ST=California, L=Oakland, O=Acme Ltd., OU=Web Services, CN=portal.acme.com

C=US, ST=California, L=Oakland, O=Acme Ltd., OU=Web Services, CN=sardine.acme.com

businessCategory=Private Organization, juridictionCountry=US, C=US, ST=California, L=Oakland, O=Acme Ltd., OU=Web Services, CN=www.acme.com
"""

rx = re.compile(r'[A-Z]{1,2}=([^\n\r,]+)')

data = [(rx.findall(line)) for line in string.split("\n") if line]
df = pd.DataFrame.from_records(data, columns = ['CountryName', 'StateOrProvinceName', 'Locality', 'Organization', 'OrganizationalUnit', 'CommonName'])
print(df)
</code>```

... which would yield:

```<code>  CountryName StateOrProvinceName Locality Organization OrganizationalUnit  \
0          US          California  Oakland    Acme Ltd.       Web Services
1          US          California  Oakland    Acme Ltd.       Web Services
2          US          California  Oakland    Acme Ltd.       Web Services
3          US          California  Oakland    Acme Ltd.       Web Services

         CommonName
0      www.acme.com
1   portal.acme.com
2  sardine.acme.com
3      www.acme.com
</code>```

Body:
I have a bunch of python code set up that retrieves the subjectDN from a list of certificates based on some search criteria.  All information for each certificate is done on a line by line basis.  The format is as follows:

C="ISO code", ST="province", L="locality", O="org name", OU="org unit", CN="name of certificate"

An example of one of my files would be:

C=US, ST=California, L=Oakland, O=Acme Ltd., OU=Web Services, CN=www.acme.com

C=US, ST=California, L=Oakland, O=Acme Ltd., OU=Web Services, CN=portal.acme.com

C=US, ST=California, L=Oakland, O=Acme Ltd., OU=Web Services, CN=sardine.acme.com

I would like to transform this into a working CSV file which normally would seem pretty easy but some of these rows contain additional data:

businessCategory=Private Organization, juridictionCountry=US, C=US, ST=California, L=Oakland, O=Acme Ltd., OU=Web Services, CN=www.acme.com

This additional data throws all of the columns out of line.

I want to do two things with this data.

I want to have only the fields from the first example show up in the CSV file for each column; so C, ST, L, O, OU and CN (omitting the weird fields found in various certificates).

I want to omit the "C=" or "ST=" from each value.

I have tried using the CSV module but I can only get this data formatted exactly the same as it is now.  I have also tried using the re module within python to rewrite some of the lines but I'm very confused on the expressions with re.

The idea that I had was to read each line in the output file that I have and then include a for loop for each line to seek out the fields I need and rewrite them.  Something like:

def rewrite()
    common_name = #here is where I would do a re command
    if #CN= x, is found (where x is the data I want):
        ofile.write("www.acme.com")
    organization = #here is where I would do a re command
    if #O= x, is found (where x is the data I want):
        ofile.write("Acme Ltd.")
--snip--
    ofile.write("\n")

Essentially I would run this function for each line in the input file to an output file.  Something like:

with open(...) as f:
    for line in f:
        rewrite()

Is this a good way to do this or is there an easier way?  Can someone help me with the regular expression to do this?

Body:
Well, if you can be sure about the order  of the entries, you could extract the data with a regular expression and form a pandas dataframe out of it afterwards:

import re, pandas as pd

string = """
C=US, ST=California, L=Oakland, O=Acme Ltd., OU=Web Services, CN=www.acme.com

C=US, ST=California, L=Oakland, O=Acme Ltd., OU=Web Services, CN=portal.acme.com

C=US, ST=California, L=Oakland, O=Acme Ltd., OU=Web Services, CN=sardine.acme.com

businessCategory=Private Organization, juridictionCountry=US, C=US, ST=California, L=Oakland, O=Acme Ltd., OU=Web Services, CN=www.acme.com
"""

rx = re.compile(r'[A-Z]{1,2}=([^\n\r,]+)')

data = [(rx.findall(line)) for line in string.split("\n") if line]
df = pd.DataFrame.from_records(data, columns = ['CountryName', 'StateOrProvinceName', 'Locality', 'Organization', 'OrganizationalUnit', 'CommonName'])
print(df)

... which would yield:

  CountryName StateOrProvinceName Locality Organization OrganizationalUnit  \
0          US          California  Oakland    Acme Ltd.       Web Services
1          US          California  Oakland    Acme Ltd.       Web Services
2          US          California  Oakland    Acme Ltd.       Web Services
3          US          California  Oakland    Acme Ltd.       Web Services

         CommonName
0      www.acme.com
1   portal.acme.com
2  sardine.acme.com
3      www.acme.com


问:
CSS webpage alignment with middle fullscreen and ratio
I would like to try to do the following for a webpage:

The goal is to have a black line splitting the fullscreen and height 80% of screen height. At the top, a small picture(p1) and at the bottom, two pictures on each side of the line.

The display would be responsive and switch when in portrait mode. I tried to made a clear schema attached.

I'm really a beginner in CSS and not sure to understand correctly viewport and if they are compatible with all browsers.

答:
You can play around in Bootply, which is playground for Bootstrap. I think you're looking for something like this: http://www.bootply.com/ArGmZ2yvMH

I did not deal with the height aspect, though.

```<code><div class="container">
<div class="row">
  <div class="col-xs-12 col-md-6 col-md-offset-3"></div>
  </div>
<div class="row">
  <div class="col-xs-6 col-md-3 col-md-offset-3"></div>
  <div class="col-xs-6 col-md-3"></div>
  </div>
</div>
</code>```

Body:
You can play around in Bootply, which is playground for Bootstrap. I think you're looking for something like this: http://www.bootply.com/ArGmZ2yvMH

I did not deal with the height aspect, though.

<div class="container">
<div class="row">
  <div class="col-xs-12 col-md-6 col-md-offset-3"></div>
  </div>
<div class="row">
  <div class="col-xs-6 col-md-3 col-md-offset-3"></div>
  <div class="col-xs-6 col-md-3"></div>
  </div>
</div>