问:
Flash AS3 FLVPlayback Component always has black bars above and below video even with exact scaling
I have written a very basic flash player based around the FLVPlayback component in the toolkit, which is then placed in the page by SWFObject. For some reason there always appear to be black bars above and below the video even if the scaling mode is set to EXACT_FIT. This does not make sense to me as the preview image is set to the same x,y position and height & width as the video, but it fits exactly and does not have black bars.

Is there something simple I am missing? I apologise for the large amount of code but I am not sure how must you need to see.

I am using SWFObject to inject the player with the following code:

```<code><script type="text/javascript">
var flashvars = {
   playerSkinURL: 'SkinUnderPlayStopSeekFullVol.swf',
   videoURL: 'video.flv',
   previewImageURL: 'video-preview.jpg',
   scaleMode: 'exact',
   autoBegin: false,
   playerColour: '#cccccc',
   playerAutoHide: false,
   playerAlpha: 0.85
};
var params = {
 allowfullscreen: true,
 quality: 'best',
 wmode: 'window'
};
swfobject.embedSWF("video.swf", "video", "479", "310", "9.0.0","/video/expressInstall.swf", flashvars, params);
</script>

<div id="video"></div>
</code>```

My action script is all on frame 1:

```<code>stop();

/**
 * Embedding this player is simple with the following flashvars API
 * playerSkinURL   = the url to the skin to use eg. SkinUnderPlayStopSeekMuteVol.swf
 * videoURL        = the url to the video FLV file
 * previewImageURL = the url of the image to use for the preview image (43px less than total height)
 * scaleMode       = scale mode of the player
 *        - exact (default) = fit to player dimensions exactly
 *        - no              = use FLV original dimensions
 *                     - aspect    = scale the video whilst maintaining aspect ratio
 * autoBegin       = automatically start playing the video as soon as it is ready (true or false) default = false
 * playerColour    = the colour of the bezel default = 0x47ABCB
 * playerAlpha     = the alpha transparency of the bezel default = 0.85
 * playerAutoHide  = whether to hide the bezel when the mouse is not over it (boolean true or false)
 */
import fl.video.VideoEvent;
import fl.video.VideoScaleMode;
import fl.video.LayoutEvent;
var flashVars;
var imageLoader:Loader;

var playerSkin:String = 'SkinUnderPlayStopSeekMuteVol.swf';
var videoURL:String = '';
var previewImage:String = '';
var previewImageLoader:Loader = new Loader();
var scaleMode:String = 'exact';
var autoBegin:Boolean = false;
var playerColour:uint = 0xCCCCCC;
var playerAlpha:Number = 0.85;
var playerAutoHide:Boolean = false;

/**
 * Action functions
 */
function populateLocalVars() {
 flashVars = root.loaderInfo.parameters;
 if(null != flashVars['playerSkinURL']) {
  playerSkin = flashVars['playerSkinURL'];
 }
 if(null != flashVars['videoURL']) {
  videoURL = flashVars['videoURL'];
 }
 if(null != flashVars['previewImageURL']) {
  previewImage = flashVars['previewImageURL'];
 }
 if(null != flashVars['scaleMode'] &&
    ('no' == flashVars['scaleMode'] || 'aspect' == flashVars['scaleMode'] || 'exact' == flashVars['scaleMode'])) {
  scaleMode = flashVars['scaleMode'];
 }
 if(null != flashVars['autoBegin']) {
  if('true' == flashVars['autoBegin']) {
   autoBegin = true;
  } else {
   autoBegin = false;
  }
 }
 if(null != flashVars['playerColour']) {
  if('#' == flashVars['playerColour'].substring(0, 1)) {
   playerColour = uint('0x' + flashVars['playerColour'].substring(1, flashVars['playerColour'].length));
  } else if('x' == flashVars['playerColour'].substring(1, 2)) {
   playerColour = uint(flashVars['playerColour']);
  }
 }
 if(null != flashVars['playerAlpha']) {
  playerAlpha = Number(flashVars['playerAlpha']);
 }
 if(null != flashVars['playerAutoHide']) {
  if('true' == flashVars['playerAutoHide']) {
   playerAutoHide = true;
  } else {
   playerAutoHide = false;
  }
 }
}
function initPlayer() {
 populateLocalVars();

 setScaleMode();
 setPlayerColour();
 setPlayerAlpha();
 setPlayerAutoHide();

 setPlayerSkin();
 loadPreview();
 resizePlayer();

 loadMovieIntoPlayer();

 // this must come after the video is loaded!
 setPlayerAutoBegin();
}

/**
 * Set FLVPlayBack component parameters
 */
function setScaleMode() {
 if('no' == scaleMode) {
  player.scaleMode = VideoScaleMode.NO_SCALE;
 } else if('aspect' == scaleMode) {
  player.scaleMode = VideoScaleMode.MAINTAIN_ASPECT_RATIO;
 } else if('exact' == scaleMode) {
  player.scaleMode = VideoScaleMode.EXACT_FIT;
 }
}
function setPlayerAutoBegin() {
 player.autoPlay = Boolean(autoBegin);
}
function setPlayerColour() {
 player.skinBackgroundColor = uint(playerColour);
}
function setPlayerAlpha() {
 player.skinBackgroundAlpha = Number(playerAlpha);
}
function setPlayerAutoHide() {
 player.skinAutoHide = Boolean(playerAutoHide);
}
function setPlayerSkin() {
 player.skin = playerSkin;
}
function loadMovieIntoPlayer() {
 player.load(videoURL);
}

/**
 * Operate on video
 */
function playMovie() {
    player.play();
 hidePreview();
}
function resetPlayHead() {
 player.seek(0);
}
function stopMovie() {
 player.stop();
}

/**
 * Preview image related
 */
function loadPreview() {
 previewImageLoader.load(new URLRequest(previewImage));
 showPreview();
}
function hidePreview() {
 preview.visible = false;
}
function showPreview() {
 preview.visible = true;
}

/**
 * Cause player to fit the defined area of the object html tag
 */
function resizePlayer() {
 player.width = stage.stageWidth;
 player.height = stage.stageHeight - 43;

 // now if the preview image has been loaded when can set it to the same
 // width and height as the player
 previewImageLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, previewImageLoadedEventHandler);
}
function resizePreview() {
 preview.width = player.width;
 preview.height = player.height;

 preview.x = player.x;
 preview.y = player.y;
}

/**
 * Event handling functions
 */
function loaderCompleteEventHandler(event:Event) {
 stage.addEventListener(Event.RESIZE, stageSizeEventHandler);
 stage.dispatchEvent(new Event(Event.RESIZE));
}
function beginPlayingEventHandler(event:Event):void {
 hidePreview();
}
function finishPlayingEventHandler(event:Event):void {
 resetPlayHead();
 showPreview();
}
function previewClickedEventHandler(event:Event):void {
 playMovie();
}
function previewImageLoadedEventHandler(event:Event):void {
 preview.addChild(previewImageLoader);
 resizePreview();
}
function stageSizeEventHandler(event:Event):void {
 if (stage.stageHeight > 0 && stage.stageWidth > 0) {
  stage.removeEventListener(Event.RESIZE, stageSizeEventHandler);
  initPlayer();
 }
}
function playerHasBeenResizedEventHandler(event:Event):void {
 resizePreview();
}

/**
 * Event bindings
 */
this.loaderInfo.addEventListener(Event.COMPLETE, loaderCompleteEventHandler);
player.addEventListener(VideoEvent.PLAYING_STATE_ENTERED, beginPlayingEventHandler);
player.addEventListener(VideoEvent.COMPLETE, finishPlayingEventHandler);
player.addEventListener(LayoutEvent.LAYOUT, playerHasBeenResizedEventHandler);
preview.addEventListener(MouseEvent.CLICK, previewClickedEventHandler);
</code>```

答:
wmode="transparent" might help.

also you can apply a mask to your flash app to hide the bars, but imho if the problem doesn't exist in a standalone FP - it's caused by insertion into HTML/js and so this should be fixed.

scale: "noScale" is useful too (but you'll have to resize your player or html container)

Body:
I have written a very basic flash player based around the FLVPlayback component in the toolkit, which is then placed in the page by SWFObject. For some reason there always appear to be black bars above and below the video even if the scaling mode is set to EXACT_FIT. This does not make sense to me as the preview image is set to the same x,y position and height & width as the video, but it fits exactly and does not have black bars.

Is there something simple I am missing? I apologise for the large amount of code but I am not sure how must you need to see.

I am using SWFObject to inject the player with the following code:

My action script is all on frame 1:

stop();

/**
 * Embedding this player is simple with the following flashvars API
 * playerSkinURL   = the url to the skin to use eg. SkinUnderPlayStopSeekMuteVol.swf
 * videoURL        = the url to the video FLV file
 * previewImageURL = the url of the image to use for the preview image (43px less than total height)
 * scaleMode       = scale mode of the player
 *        - exact (default) = fit to player dimensions exactly
 *        - no              = use FLV original dimensions
 *                     - aspect    = scale the video whilst maintaining aspect ratio
 * autoBegin       = automatically start playing the video as soon as it is ready (true or false) default = false
 * playerColour    = the colour of the bezel default = 0x47ABCB
 * playerAlpha     = the alpha transparency of the bezel default = 0.85
 * playerAutoHide  = whether to hide the bezel when the mouse is not over it (boolean true or false)
 */
import fl.video.VideoEvent;
import fl.video.VideoScaleMode;
import fl.video.LayoutEvent;
var flashVars;
var imageLoader:Loader;

var playerSkin:String = 'SkinUnderPlayStopSeekMuteVol.swf';
var videoURL:String = '';
var previewImage:String = '';
var previewImageLoader:Loader = new Loader();
var scaleMode:String = 'exact';
var autoBegin:Boolean = false;
var playerColour:uint = 0xCCCCCC;
var playerAlpha:Number = 0.85;
var playerAutoHide:Boolean = false;

/**
 * Action functions
 */
function populateLocalVars() {
 flashVars = root.loaderInfo.parameters;
 if(null != flashVars['playerSkinURL']) {
  playerSkin = flashVars['playerSkinURL'];
 }
 if(null != flashVars['videoURL']) {
  videoURL = flashVars['videoURL'];
 }
 if(null != flashVars['previewImageURL']) {
  previewImage = flashVars['previewImageURL'];
 }
 if(null != flashVars['scaleMode'] &&
    ('no' == flashVars['scaleMode'] || 'aspect' == flashVars['scaleMode'] || 'exact' == flashVars['scaleMode'])) {
  scaleMode = flashVars['scaleMode'];
 }
 if(null != flashVars['autoBegin']) {
  if('true' == flashVars['autoBegin']) {
   autoBegin = true;
  } else {
   autoBegin = false;
  }
 }
 if(null != flashVars['playerColour']) {
  if('#' == flashVars['playerColour'].substring(0, 1)) {
   playerColour = uint('0x' + flashVars['playerColour'].substring(1, flashVars['playerColour'].length));
  } else if('x' == flashVars['playerColour'].substring(1, 2)) {
   playerColour = uint(flashVars['playerColour']);
  }
 }
 if(null != flashVars['playerAlpha']) {
  playerAlpha = Number(flashVars['playerAlpha']);
 }
 if(null != flashVars['playerAutoHide']) {
  if('true' == flashVars['playerAutoHide']) {
   playerAutoHide = true;
  } else {
   playerAutoHide = false;
  }
 }
}
function initPlayer() {
 populateLocalVars();

 setScaleMode();
 setPlayerColour();
 setPlayerAlpha();
 setPlayerAutoHide();

 setPlayerSkin();
 loadPreview();
 resizePlayer();

 loadMovieIntoPlayer();

 // this must come after the video is loaded!
 setPlayerAutoBegin();
}

/**
 * Set FLVPlayBack component parameters
 */
function setScaleMode() {
 if('no' == scaleMode) {
  player.scaleMode = VideoScaleMode.NO_SCALE;
 } else if('aspect' == scaleMode) {
  player.scaleMode = VideoScaleMode.MAINTAIN_ASPECT_RATIO;
 } else if('exact' == scaleMode) {
  player.scaleMode = VideoScaleMode.EXACT_FIT;
 }
}
function setPlayerAutoBegin() {
 player.autoPlay = Boolean(autoBegin);
}
function setPlayerColour() {
 player.skinBackgroundColor = uint(playerColour);
}
function setPlayerAlpha() {
 player.skinBackgroundAlpha = Number(playerAlpha);
}
function setPlayerAutoHide() {
 player.skinAutoHide = Boolean(playerAutoHide);
}
function setPlayerSkin() {
 player.skin = playerSkin;
}
function loadMovieIntoPlayer() {
 player.load(videoURL);
}

/**
 * Operate on video
 */
function playMovie() {
    player.play();
 hidePreview();
}
function resetPlayHead() {
 player.seek(0);
}
function stopMovie() {
 player.stop();
}

/**
 * Preview image related
 */
function loadPreview() {
 previewImageLoader.load(new URLRequest(previewImage));
 showPreview();
}
function hidePreview() {
 preview.visible = false;
}
function showPreview() {
 preview.visible = true;
}

/**
 * Cause player to fit the defined area of the object html tag
 */
function resizePlayer() {
 player.width = stage.stageWidth;
 player.height = stage.stageHeight - 43;

 // now if the preview image has been loaded when can set it to the same
 // width and height as the player
 previewImageLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, previewImageLoadedEventHandler);
}
function resizePreview() {
 preview.width = player.width;
 preview.height = player.height;

 preview.x = player.x;
 preview.y = player.y;
}

/**
 * Event handling functions
 */
function loaderCompleteEventHandler(event:Event) {
 stage.addEventListener(Event.RESIZE, stageSizeEventHandler);
 stage.dispatchEvent(new Event(Event.RESIZE));
}
function beginPlayingEventHandler(event:Event):void {
 hidePreview();
}
function finishPlayingEventHandler(event:Event):void {
 resetPlayHead();
 showPreview();
}
function previewClickedEventHandler(event:Event):void {
 playMovie();
}
function previewImageLoadedEventHandler(event:Event):void {
 preview.addChild(previewImageLoader);
 resizePreview();
}
function stageSizeEventHandler(event:Event):void {
 if (stage.stageHeight > 0 && stage.stageWidth > 0) {
  stage.removeEventListener(Event.RESIZE, stageSizeEventHandler);
  initPlayer();
 }
}
function playerHasBeenResizedEventHandler(event:Event):void {
 resizePreview();
}

/**
 * Event bindings
 */
this.loaderInfo.addEventListener(Event.COMPLETE, loaderCompleteEventHandler);
player.addEventListener(VideoEvent.PLAYING_STATE_ENTERED, beginPlayingEventHandler);
player.addEventListener(VideoEvent.COMPLETE, finishPlayingEventHandler);
player.addEventListener(LayoutEvent.LAYOUT, playerHasBeenResizedEventHandler);
preview.addEventListener(MouseEvent.CLICK, previewClickedEventHandler);


来源: stackexchange

问:
Pip not installing in Ubuntu
I gave the command on terminal of Ubuntu 16.04 LTS as-

```<code> $ sudo apt install python-pip
</code>```

It is giving the error as:

```<code>> Reading package lists... Done Building dependency tree        Reading
> state information... Done You might want to run 'apt-get -f install'
> to correct these: The following packages have unmet dependencies:
> bcmwl-kernel-source:i386 : Depends: dkms:i386
>                             Depends: linux-libc-dev:i386 but it is not going to be installed
>                             Depends: libc6-dev:i386 but it is not going to be installed
>                             Depends: linux-headers-generic:i386 but it is not going to be installed or
>                                      linux-headers:i386  dkms : Depends: module-init-tools but it is not going to be installed
> python-pip : Depends: python-pip-whl (= 8.1.1-2ubuntu0.4) but it is
> not going to be installed
>               Recommends: python-all-dev (>= 2.6) but it is not going to be installed
>               Recommends: python-setuptools but it is not going to be installed
>               Recommends: python-wheel but it is not going to be installed E: Unmet dependencies. Try 'apt-get -f install' with no
> packages (or specify a solution).
</code>```

How can I install pip? Please see to the errors above.

答:
run

```<code>sudo apt -f install
</code>```

Then retry the command, if it still doesn't work, I think you need to install/upgrade some packages in errors

ContentLicense: CC BY-SA 3.0

Title: Pip not installing in Ubuntu

Body:
I gave the command on terminal of Ubuntu 16.04 LTS as-

 $ sudo apt install python-pip

It is giving the error as:

> Reading package lists... Done Building dependency tree        Reading
> state information... Done You might want to run 'apt-get -f install'
> to correct these: The following packages have unmet dependencies:
> bcmwl-kernel-source:i386 : Depends: dkms:i386
>                             Depends: linux-libc-dev:i386 but it is not going to be installed
>                             Depends: libc6-dev:i386 but it is not going to be installed
>                             Depends: linux-headers-generic:i386 but it is not going to be installed or
>                                      linux-headers:i386  dkms : Depends: module-init-tools but it is not going to be installed
> python-pip : Depends: python-pip-whl (= 8.1.1-2ubuntu0.4) but it is
> not going to be installed
>               Recommends: python-all-dev (>= 2.6) but it is not going to be installed
>               Recommends: python-setuptools but it is not going to be installed
>               Recommends: python-wheel but it is not going to be installed E: Unmet dependencies. Try 'apt-get -f install' with no
> packages (or specify a solution).

How can I install pip? Please see to the errors above.

Body:
run

sudo apt -f install

Then retry the command, if it still doesn't work, I think you need to install/upgrade some packages in errors


问:
Need solution to avoid repeated scanning in huge table
I have a event table which has 40 columns and fill up to 2 billion records. In that event table i would like to query for a combination event i.e Event A with Event B. Sometimes I may want to find more combination like Event A with B and C. It may goes to 5 or 6 combination.

I don't want to scan that table for every event in combination i.e Scanning for event A and scanning for event B. And I need a generic approach for more combination scanning as well.

Note: That 2 billion records is partitioned based on event date and data is been equally split.

Eg:

Need to find id's which has event A,B,C and need to find id's which has only A,B.

This number of combination is dynamic. I don't want to scan that table for each event and finally intersect the result.

答:
There may be some mileage in using a sql server equivalent of the mysql group_concat function.
For example

```<code>drop table t
create table t (id int, dt date, event varchar(1))
insert into t values
(1,'2017-01-01','a'),(1,'2017-01-01','b'),(1,'2017-01-01','c'),(1,'2017-01-02','c'),(1,'2017-01-03','d'),
(2,'2017-02-01','a'),(2,'2017-02-01','b')

select id,
        stuff(
    (
    select cast(',' as varchar(max)) + t1.event
    from t as t1
    WHERE t1.id  = t.id
    order by t1.id
    for xml path('')
    ), 1, 1, '') AS groupconcat
from t
group by t.id

Results in

id          groupconcat
----------- -----------
1           a,b,c,c,d
2           a,b
</code>```

If you then add a patindex

```<code>select * from
(
select id,
        stuff(
    (
    select cast(',' as varchar(max)) + t1.event
    from t as t1
    WHERE t1.id  = t.id
    order by t1.id
    for xml path('')
    ), 1, 1, '') AS groupconcat
from t
group by t.id
) s
where patindex('a,b,c%',groupconcat) > 0
</code>```

you get this

```<code>id          groupconcat
----------- ------------
1           a,b,c,c,d
</code>```

Body:
There may be some mileage in using a sql server equivalent of the mysql group_concat function.
For example

drop table t
create table t (id int, dt date, event varchar(1))
insert into t values
(1,'2017-01-01','a'),(1,'2017-01-01','b'),(1,'2017-01-01','c'),(1,'2017-01-02','c'),(1,'2017-01-03','d'),
(2,'2017-02-01','a'),(2,'2017-02-01','b')

select id,
        stuff(
    (
    select cast(',' as varchar(max)) + t1.event
    from t as t1
    WHERE t1.id  = t.id
    order by t1.id
    for xml path('')
    ), 1, 1, '') AS groupconcat
from t
group by t.id

Results in

id          groupconcat
----------- -----------
1           a,b,c,c,d
2           a,b

If you then add a patindex

select * from
(
select id,
        stuff(
    (
    select cast(',' as varchar(max)) + t1.event
    from t as t1
    WHERE t1.id  = t.id
    order by t1.id
    for xml path('')
    ), 1, 1, '') AS groupconcat
from t
group by t.id
) s
where patindex('a,b,c%',groupconcat) > 0

you get this

id          groupconcat
----------- ------------
1           a,b,c,c,d


问:
How can I remove spaces in view?
I use laravel 5.3

My case is like this :

My code in view :

```<code><div class="alert alert-warning" role="alert">
    "
    @if(isset($country))
        {{ $country }}
    @endif
    @if(isset($city))
        @if(isset($country))
            -
        @endif
        {{ $city }}
    @endif
    "
</div>
</code>```

The result like this :

" England - London "

I want the result like this :

"England - London"

How can I do it?

答:
```<code><div class="alert alert-warning" role="alert">
    <span>"</span>
    @if(isset($country))
        {{ $country }}
    @endif
    @if(isset($city))
        @if(isset($country))
            -
        @endif
        {{ $city }}
    @endif
    <span>"</span>
</div>
</code>```

Title: How can I remove spaces in view?

Body:
I use laravel 5.3

My case is like this :

My code in view :

    "
    @if(isset($country))
        {{ $country }}
    @endif
    @if(isset($city))
        @if(isset($country))
            -
        @endif
        {{ $city }}
    @endif
    "

The result like this :

" England - London "

I want the result like this :

"England - London"

How can I do it?


问:
How is a random number generated at runtime?
Since computers cannot pick random numbers(can they?) how is this random number actually generated. For example in C# we say,

```<code>Random.Next()
</code>```

What happens inside?

答:
The Random class is a pseudo-random number generator.

It is basically an extremely long but deterministic repeating sequence. The "randomness" comes from starting at different positions. Specifying where to start is done by choosing a seed for the random number generator and can for example be done by using the system time or by getting a random seed from another random source. The default Random constructor uses the system time as a seed.

The actual algorithm used to generate the sequence of numbers is documented in MSDN:

The current implementation of the Random class is based on Donald E. Knuth's subtractive random number generator algorithm. For more information, see D. E. Knuth. "The Art of Computer Programming, volume 2: Seminumerical Algorithms". Addison-Wesley, Reading, MA, second edition, 1981.

ContentLicense: CC BY-SA 2.5

Body:
Since computers cannot pick random numbers(can they?) how is this random number actually generated. For example in C# we say,

Random.Next()

What happens inside?


问:
symfony paginator + filter form
I'm new to Symfony, I got a page in where I have a list of articles, and I created a form above it that allow me to filter the results of my query :

The form works fine, but when I click on the 2nd page of my paginator table, the form reset, so my filter is reset too. What I want is that we can filter results and be able to paginate the table, with the same filter, and that the form keep his data.

Here's my code right now :

Controller :

```<code>public function listeAction(Request $request, $page) {
        if ($page < 1 && strlen($page) != 0) {
            throw new NotFoundHttpException('Page "' . $page . '" inexistante.');
        } else if (strlen($page) == 0) {
            $page = 1;
        }

        $nbPerPage = 5;

        $form = $this->createForm(ArticleRechercheType::class);
        $form->setData(array('rds' => true));

        //if we use filters
        if ($request->isMethod('POST') && $form->handleRequest($request)->isValid()) {
            $data = $form->getData();
            $form = $this->createForm(ArticleRechercheType::class, $data);
            if ($data['famille'] != null) {
                $data['famille'] = $data['famille']->getId();
            }
            $listArticles = $this->getDoctrine()
                    ->getManager()
                    ->getRepository('GRBackOfficeBundle:Article')
                    ->getFilteredArticles($page, $nbPerPage, $data);
        } else {
            $data = $form->getData();
            $form = $this->createForm(ArticleRechercheType::class, $data);

            $listArticles = $this->getDoctrine()
                    ->getManager()
                    ->getRepository('GRBackOfficeBundle:Article')
                    ->getArticles($page, $nbPerPage);
        }

        $nbPages = ceil(count($listArticles) / $nbPerPage);

        if ($nbPages != 0 && $page > $nbPages) {
            throw new NotFoundHttpException('Page "' . $page . '" inexistante.');
        }

        if ($nbPages == 0) {
            $nbPages = 1;
        }

        return $this->render('GRBackOfficeBundle:Article:liste_articles.html.twig', array(
                    'form' => $form->createView(),
                    'listArticles' => $listArticles,
                    'nbPages' => $nbPages,
                    'page' => $page
        ));
    }
</code>```

Form :

```<code>class ArticleRechercheType extends AbstractType {

    public function buildForm(FormBuilderInterface $builder, array $options) {
        $builder->add('famille', EntityType::class, array(
                    'class' => 'GRBackOfficeBundle:Famille',
                    'choice_label' => 'nom',
                    'required' => false
                ))
                ->add('rds', CheckboxType::class, array('required' => false))
                ->add('recherche', TextType::class, array('required' => false))
                ->add('Rechercher', SubmitType::class);
    }

    public function configureOptions(OptionsResolver $resolver) {
        $resolver->setDefaults(array(
            'translation_domain' => false
        ));
    }

}
</code>```

View :

```<code>{% extends "GRBackOfficeBundle::layout.html.twig" %}

{% block title %}
    Liste des articles
{% endblock %}

{% block gr_bo_body %}
    <h2>Liste des articles</h2>

    <div class="row">
        <div class="well row">
            {{ form_start(form) }}

            {{ form_errors(form) }}

            <div class="form-group col-md-2">
                {{ form_label(form.famille, "Famille d'article", {'label_attr': {'class': 'control-label'}}) }}

                {{ form_errors(form.famille) }}

                {{ form_widget(form.famille, {'attr': {'class': 'form-control'}}) }}
            </div>

            <div class="form-group col-md-4">
                {{ form_widget(form.rds, {'attr': {'class': ''}}) }}
                {{ form_label(form.rds, "Montrer les articles en rupture de stock", {'label_attr': {'class': 'control-label'}}) }}
                {{ form_errors(form.rds) }}

            </div>

            <div class="form-group col-md-3">
                {{ form_label(form.recherche, "Recherche", {'label_attr': {'class': 'control-label'}}) }}

                {{ form_errors(form.recherche) }}

                {{ form_widget(form.recherche, {'attr': {'class': 'form-control'}}) }}
            </div>
            <div class="form-group col-md-3" style="text-align: center">
                {{ form_widget(form.Rechercher, {'attr': {'class': 'btn btn-primary'}}) }}
            </div>
            {{ form_rest(form) }}

            {{ form_end(form) }}
        </div>

        <div class="well row">
            <table class="table table-bordered table-striped" id="listeArticles" style="width: 100%" cellspacing="0">
                <thead>
                    <tr>
                        <th>Référence client</th>
                        <th>Référence interne</th>
                        <th>Famille</th>
                        <th>Libellé</th>
                        <th>Alerte</th>
                        <th>Stock</th>
                    </tr>
                </thead>
                <tbody id="bodyListeArticles">
                    {% for article in listArticles %}
                        <tr>
                            <td><a href="{{ path('gr_bo_modif_article', {'article_id': article.id}) }}">{{ article.RefArticle }}</a></td>
                            <td>{{ article.RefLogistique }}</td>
                            <td>{{ article.famille.nom }}</td>
                            <td>{{ article.libelle }}</td>
                            <td>{{ article.StockAlerte }}</td>
                            <td>{{ article.StockActuel }}</td>
                        </tr>
                    {% endfor %}
                </tbody>
            </table>
            {% if nbPages > 1 %}
                <ul class="pagination">
                    {% for p in range(1, nbPages) %}
                        <li {% if p == page %} class="active"{% endif %}>
                            <a href="{{path('gr_bo_liste_articles', {'page' : p}) }}">{{ p }}</a>
                        </li>
                    {% endfor %}
                </ul>
            {% endif %}
        </div>

    </div>

{% endblock %}
</code>```

If anyone have an idea of how I can do that, that will be appreciated

答: You can use a bundle (like the knp paginator bundle for exemple), or put your args in session. But the bundle will make it simple as it does everything for you, you just have to pass your datas</p>

Title: symfony paginator + filter form

Body:
I'm new to Symfony, I got a page in where I have a list of articles, and I created a form above it that allow me to filter the results of my query :

The form works fine, but when I click on the 2nd page of my paginator table, the form reset, so my filter is reset too. What I want is that we can filter results and be able to paginate the table, with the same filter, and that the form keep his data.

Here's my code right now :

Controller :

public function listeAction(Request $request, $page) {
        if ($page < 1 && strlen($page) != 0) {
            throw new NotFoundHttpException('Page "' . $page . '" inexistante.');
        } else if (strlen($page) == 0) {
            $page = 1;
        }

        $nbPerPage = 5;

        $form = $this->createForm(ArticleRechercheType::class);
        $form->setData(array('rds' => true));

        //if we use filters
        if ($request->isMethod('POST') && $form->handleRequest($request)->isValid()) {
            $data = $form->getData();
            $form = $this->createForm(ArticleRechercheType::class, $data);
            if ($data['famille'] != null) {
                $data['famille'] = $data['famille']->getId();
            }
            $listArticles = $this->getDoctrine()
                    ->getManager()
                    ->getRepository('GRBackOfficeBundle:Article')
                    ->getFilteredArticles($page, $nbPerPage, $data);
        } else {
            $data = $form->getData();
            $form = $this->createForm(ArticleRechercheType::class, $data);

            $listArticles = $this->getDoctrine()
                    ->getManager()
                    ->getRepository('GRBackOfficeBundle:Article')
                    ->getArticles($page, $nbPerPage);
        }

        $nbPages = ceil(count($listArticles) / $nbPerPage);

        if ($nbPages != 0 && $page > $nbPages) {
            throw new NotFoundHttpException('Page "' . $page . '" inexistante.');
        }

        if ($nbPages == 0) {
            $nbPages = 1;
        }

        return $this->render('GRBackOfficeBundle:Article:liste_articles.html.twig', array(
                    'form' => $form->createView(),
                    'listArticles' => $listArticles,
                    'nbPages' => $nbPages,
                    'page' => $page
        ));
    }

Form :

class ArticleRechercheType extends AbstractType {

    public function buildForm(FormBuilderInterface $builder, array $options) {
        $builder->add('famille', EntityType::class, array(
                    'class' => 'GRBackOfficeBundle:Famille',
                    'choice_label' => 'nom',
                    'required' => false
                ))
                ->add('rds', CheckboxType::class, array('required' => false))
                ->add('recherche', TextType::class, array('required' => false))
                ->add('Rechercher', SubmitType::class);
    }

    public function configureOptions(OptionsResolver $resolver) {
        $resolver->setDefaults(array(
            'translation_domain' => false
        ));
    }

}

View :

{% extends "GRBackOfficeBundle::layout.html.twig" %}

{% block title %}
    Liste des articles
{% endblock %}

{% block gr_bo_body %}

Liste des articles

            {{ form_start(form) }}

            {{ form_errors(form) }}

                {{ form_label(form.famille, "Famille d'article", {'label_attr': {'class': 'control-label'}}) }}

                {{ form_errors(form.famille) }}

                {{ form_widget(form.famille, {'attr': {'class': 'form-control'}}) }}

                {{ form_widget(form.rds, {'attr': {'class': ''}}) }}
                {{ form_label(form.rds, "Montrer les articles en rupture de stock", {'label_attr': {'class': 'control-label'}}) }}
                {{ form_errors(form.rds) }}

                {{ form_label(form.recherche, "Recherche", {'label_attr': {'class': 'control-label'}}) }}

                {{ form_errors(form.recherche) }}

                {{ form_widget(form.recherche, {'attr': {'class': 'form-control'}}) }}

                {{ form_widget(form.Rechercher, {'attr': {'class': 'btn btn-primary'}}) }}

            {{ form_rest(form) }}

            {{ form_end(form) }}

                        Référence client
                        Référence interne
                        Famille
                        Libellé
                        Alerte
                        Stock

                    {% for article in listArticles %}

                            {{ article.RefArticle }}
                            {{ article.RefLogistique }}
                            {{ article.famille.nom }}
                            {{ article.libelle }}
                            {{ article.StockAlerte }}
                            {{ article.StockActuel }}

                    {% endfor %}

            {% if nbPages > 1 %}

                    {% for p in range(1, nbPages) %}

                            {{ p }}

                    {% endfor %}

            {% endif %}

{% endblock %}

If anyone have an idea of how I can do that, that will be appreciated


问:
Can't put value into map
I just learn golang, and want to build an struct like this.

```<code>{end:false map["h":{false "h" map["e":{true "e" map[]}]}
           "s":{false "s" map["h":{false "h" map["e":{true "e" map[]}]}]}
]}
</code>```

Follow is the code I write:

```<code>package main

import "fmt"
type node struct {
    end      bool
    char     string
    children map[int32]node
}

func addKeyword(root *node, key string) {
    current := root
    for _, v := range key {
        mm := current.children
        if nil == mm || len(mm) == 0 {
            mm = make(map[int32]node)
            current.children = mm
        }
        child, ok := mm[v]
        if !ok {
            child = node{false, string(v), nil}
            mm[v] = child
        }
        current = &child
    }
    current.end = true
}

func main() {
    root := new(node)
    addKeyword(root, "he")
    addKeyword(root, "she")
    fmt.Println(root)
}
</code>```

I get result is:

```<code>{end:false map["h":{false "h" map[]}
           "s":{false "s" map[]}
]}
</code>```

I don't know why second level struct not append to root object.

答:
The problem is related to the type of children map. You are using node values in this map. As a result, you get new values every time you access a key and the changes are not reflected into the original 'parent' node.

The fault lies with this line:

```<code>child, ok := mm[v]
</code>```

child is a new variable that is equal to the value of node mm[v]. The changes you make happen to this value while the node value in mm remains unchanged.

To fix this problem, you can use *node for values in children:

```<code>type node struct {
    end      bool
    char     string
    children map[int32]*node
}
</code>```

And fix the code accordingly:

```<code>// ...
mm := current.children
if nil == mm {
    mm = make(map[int32]*node)
    current.children = mm
}
child, ok := mm[v]
if !ok {
    child = &node{false, string(v), nil}
    mm[v] = child
}
current = child
// ...
</code>```

Working example: https://play.golang.org/p/XcmPY4Nx-O

Title: Can't put value into map

Body:
I just learn golang, and want to build an struct like this.

{end:false map["h":{false "h" map["e":{true "e" map[]}]}
           "s":{false "s" map["h":{false "h" map["e":{true "e" map[]}]}]}
]}

Follow is the code I write:

package main

import "fmt"
type node struct {
    end      bool
    char     string
    children map[int32]node
}

func addKeyword(root *node, key string) {
    current := root
    for _, v := range key {
        mm := current.children
        if nil == mm || len(mm) == 0 {
            mm = make(map[int32]node)
            current.children = mm
        }
        child, ok := mm[v]
        if !ok {
            child = node{false, string(v), nil}
            mm[v] = child
        }
        current = &child
    }
    current.end = true
}

func main() {
    root := new(node)
    addKeyword(root, "he")
    addKeyword(root, "she")
    fmt.Println(root)
}

I get result is:

{end:false map["h":{false "h" map[]}
           "s":{false "s" map[]}
]}

I don't know why second level struct not append to root object.

Body:
The problem is related to the type of children map. You are using node values in this map. As a result, you get new values every time you access a key and the changes are not reflected into the original 'parent' node.

The fault lies with this line:

child, ok := mm[v]

child is a new variable that is equal to the value of node mm[v]. The changes you make happen to this value while the node value in mm remains unchanged.

To fix this problem, you can use *node for values in children:

type node struct {
    end      bool
    char     string
    children map[int32]*node
}

And fix the code accordingly:

// ...
mm := current.children
if nil == mm {
    mm = make(map[int32]*node)
    current.children = mm
}
child, ok := mm[v]
if !ok {
    child = &node{false, string(v), nil}
    mm[v] = child
}
current = child
// ...

Working example: https://play.golang.org/p/XcmPY4Nx-O


问:
Include git commit hash as string into Rust program
I host a Rust project in git repository and I want to make it print the version on some command. How can I include the version into the program? I thought that the build script could set environment variables which can be used while compiling the project itself, but it does not work:

build.rs:

```<code>use std::env;

fn get_git_hash() -> Option<String> {
    use std::process::Command;

    let branch = Command::new("git")
                         .arg("rev-parse")
                         .arg("--abbrev-ref")
                         .arg("HEAD")
                         .output();
    if let Ok(branch_output) = branch {
        let branch_string = String::from_utf8_lossy(&branch_output.stdout);
        let commit = Command::new("git")
                             .arg("rev-parse")
                             .arg("--verify")
                             .arg("HEAD")
                             .output();
        if let Ok(commit_output) = commit {
            let commit_string = String::from_utf8_lossy(&commit_output.stdout);

            return Some(format!("{}, {}",
                        branch_string.lines().next().unwrap_or(""),
                        commit_string.lines().next().unwrap_or("")))
        } else {
            panic!("Can not get git commit: {}", commit_output.unwrap_err());
        }
    } else {
        panic!("Can not get git branch: {}", branch.unwrap_err());
    }
    None
}

fn main() {
    if let Some(git) = get_git_hash() {
        env::set_var("GIT_HASH", git);
    }
}
</code>```

src/main.rs:

```<code>pub const GIT_HASH: &'static str = env!("GIT_HASH");

fm main() {
    println!("Git hash: {}", GIT_HASH);
}
</code>```

The error message:

error: environment variable `GIT_HASH` not defined
  --> src/main.rs:10:25
   |
10 | pub const GIT_HASH: &'static str = env!("GIT_HASH");
   |
                                        ^^^^^^^^^^^^^^^^
```

Is there a way to pass such data at compile time? How can I communicate between the build script and the source code if not with environment variables? I can only think about writing data to some file, but I think this is overkill for this case.

答:
Since Rust 1.19 (cargo 0.20.0), thanks to https://github.com/rust-lang/cargo/pull/3929, you can now define a compile-time environment variable (env!(…)) for rustc and rustdoc via:

```<code>println!("cargo:rustc-env=KEY=value");
</code>```

So OP's program can be written as:

```<code>// build.rs
use std::process::Command;
fn main() {
    // note: add error checking yourself.
    let output = Command::new("git").args(&["rev-parse", "HEAD"]).output().unwrap();
    let git_hash = String::from_utf8(output.stdout).unwrap();
    println!("cargo:rustc-env=GIT_HASH={}", git_hash);
}
</code>```

```<code>// main.rs
fn main() {
    println!("{}", env!("GIT_HASH"));
    // output something like:
    // 7480b50f3c75eeed88323ec6a718d7baac76290d
}
</code>```

Note that you still cannot use this if you still want to support 1.18 or below.

Body:
I host a Rust project in git repository and I want to make it print the version on some command. How can I include the version into the program? I thought that the build script could set environment variables which can be used while compiling the project itself, but it does not work:

build.rs:

use std::env;

fn get_git_hash() -> Option<String> {
    use std::process::Command;

    let branch = Command::new("git")
                         .arg("rev-parse")
                         .arg("--abbrev-ref")
                         .arg("HEAD")
                         .output();
    if let Ok(branch_output) = branch {
        let branch_string = String::from_utf8_lossy(&branch_output.stdout);
        let commit = Command::new("git")
                             .arg("rev-parse")
                             .arg("--verify")
                             .arg("HEAD")
                             .output();
        if let Ok(commit_output) = commit {
            let commit_string = String::from_utf8_lossy(&commit_output.stdout);

            return Some(format!("{}, {}",
                        branch_string.lines().next().unwrap_or(""),
                        commit_string.lines().next().unwrap_or("")))
        } else {
            panic!("Can not get git commit: {}", commit_output.unwrap_err());
        }
    } else {
        panic!("Can not get git branch: {}", branch.unwrap_err());
    }
    None
}

fn main() {
    if let Some(git) = get_git_hash() {
        env::set_var("GIT_HASH", git);
    }
}

src/main.rs:

pub const GIT_HASH: &'static str = env!("GIT_HASH");

fm main() {
    println!("Git hash: {}", GIT_HASH);
}

The error message:

error: environment variable `GIT_HASH` not defined
  --> src/main.rs:10:25
   |
10 | pub const GIT_HASH: &'static str = env!("GIT_HASH");
   |
                                        ^^^^^^^^^^^^^^^^

Is there a way to pass such data at compile time? How can I communicate between the build script and the source code if not with environment variables? I can only think about writing data to some file, but I think this is overkill for this case.

Body:
Since Rust 1.19 (cargo 0.20.0), thanks to https://github.com/rust-lang/cargo/pull/3929, you can now define a compile-time environment variable (env!(…)) for rustc and rustdoc via:

println!("cargo:rustc-env=KEY=value");

So OP's program can be written as:

// build.rs
use std::process::Command;
fn main() {
    // note: add error checking yourself.
    let output = Command::new("git").args(&["rev-parse", "HEAD"]).output().unwrap();
    let git_hash = String::from_utf8(output.stdout).unwrap();
    println!("cargo:rustc-env=GIT_HASH={}", git_hash);
}

// main.rs
fn main() {
    println!("{}", env!("GIT_HASH"));
    // output something like:
    // 7480b50f3c75eeed88323ec6a718d7baac76290d
}

Note that you still cannot use this if you still want to support 1.18 or below.


问:
Button position in a linear layout
i'm trying to create button programmatically on a linear layout and i want to have "columns" of buttons but it seems the linear layout automatically put buttons under each other and i can't find a way to make my button position to the top again

```<code>protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_branch);

    LinearLayout linear = (LinearLayout) findViewById(R.id.content);
    for(int i =0; i <10; i++) {
        Button btn = new Button(this);
        btn.setText("Branch1");

        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(330,200);
        layoutParams.setMargins(rowNb*330+5, 3, 0, 0); // left, top, right, bottom
        btn.setLayoutParams(layoutParams);
        linear.addView(btn);
        btnNb++;
        if(btnNb>5)
        {
            rowNb = 1;
        }
    }

}
</code>```

here's what i got

Can someone help me out to find a way to make my 2nd columns like the first ? I already tried a btn.SetY or a btn.setGravity

答:
Try GridLayout instead of LinearLayout
https://developer.android.com/reference/android/widget/GridLayout.html</p>

Title: Button position in a linear layout

Body:
i'm trying to create button programmatically on a linear layout and i want to have "columns" of buttons but it seems the linear layout automatically put buttons under each other and i can't find a way to make my button position to the top again

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_branch);

    LinearLayout linear = (LinearLayout) findViewById(R.id.content);
    for(int i =0; i <10; i++) {
        Button btn = new Button(this);
        btn.setText("Branch1");

        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(330,200);
        layoutParams.setMargins(rowNb*330+5, 3, 0, 0); // left, top, right, bottom
        btn.setLayoutParams(layoutParams);
        linear.addView(btn);
        btnNb++;
        if(btnNb>5)
        {
            rowNb = 1;
        }
    }

}

here's what i got

Can someone help me out to find a way to make my 2nd columns like the first ? I already tried a btn.SetY or a btn.setGravity


问:
C# Databind question
OK, So Im fairly new to Web apps, been doing Windows app for a while in VB but Im switching to C# for web apps. Ok so I have a textbox and I have a SQLDataSource called SQLDataSource1. How in the world do I bind the source to the textbox so when it loads it will populate it?

Can someone give me some examples?

Ive tried the following,

```<code>Label1.Text = SqlDataSource1.SelectParameters.ToString();
</code>```

But I get something other than the value of the SQLDataSource. I get this:  System.Web.UI.WebControls.SqlDataSource

Thanks

答:
I found an answer here on Forum.ASP.Net

Here is what has been said by Samu Zhang (Microsoft Online Community Support) :

It is hard to bind textbox to sqldatasource. We usually bind data controls such as FormView and GridView to sqldatasource and put one TextBox control in their Template . And you can invoke FindControl method of FormView to retrieve the textbox.

See my sample.

```<code>protected void Button1_Click(object sender, EventArgs e)
{
    TextBox box = FormView1.FindControl("TextBox1") as TextBox;

}

<form id="form1" runat="server">
<div>
    <asp:FormView ID="FormView1" runat="server" DataKeyNames="countryid" DataSourceID="SqlDataSource1">

        <ItemTemplate>
            countryid:
            <asp:Label ID="countryidLabel" runat="server" Text='<%# Eval("countryid") %>'></asp:Label><br />
            countryname:
            <asp:TextBox ID="TextBox1" runat="server" Text='<%# Eval("countryname") %>'></asp:TextBox><br />
        </ItemTemplate>
    </asp:FormView>
     </div>
    <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString2 %>"
        SelectCommand="SELECT * FROM [country]"></asp:SqlDataSource>
    <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="retrieve value" />
</form>
</code>```

Title: C# Databind question

Body:
OK, So Im fairly new to Web apps, been doing Windows app for a while in VB but Im switching to C# for web apps. Ok so I have a textbox and I have a SQLDataSource called SQLDataSource1. How in the world do I bind the source to the textbox so when it loads it will populate it?

Can someone give me some examples?

Ive tried the following,

Label1.Text = SqlDataSource1.SelectParameters.ToString();

But I get something other than the value of the SQLDataSource. I get this:  System.Web.UI.WebControls.SqlDataSource

Thanks

Body:
I found an answer here on Forum.ASP.Net

Here is what has been said by Samu Zhang (Microsoft Online Community Support) :

It is hard to bind textbox to sqldatasource. We usually bind data controls such as FormView and GridView to sqldatasource and put one TextBox control in their Template . And you can invoke FindControl method of FormView to retrieve the textbox.

See my sample.

protected void Button1_Click(object sender, EventArgs e)
{
    TextBox box = FormView1.FindControl("TextBox1") as TextBox;

}

<form id="form1" runat="server">
<div>
    <asp:FormView ID="FormView1" runat="server" DataKeyNames="countryid" DataSourceID="SqlDataSource1">

        <ItemTemplate>
            countryid:
            <asp:Label ID="countryidLabel" runat="server" Text='<%# Eval("countryid") %>'></asp:Label><br />
            countryname:
            <asp:TextBox ID="TextBox1" runat="server" Text='<%# Eval("countryname") %>'></asp:TextBox><br />
        </ItemTemplate>
    </asp:FormView>
     </div>
    <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString2 %>"
        SelectCommand="SELECT * FROM [country]"></asp:SqlDataSource>
    <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="retrieve value" />
</form>


问:
Prolog - infinite loop
I want to check if element is in the middle of list.
I search middle element and next I check if is a member of list, but I get infinite loop.

My predicates:

```<code>remove_first([_,H1|T], [H1|T]).

remove_last([_],[]).
remove_last([H|T], [H|T2]) :- remove_last(T, T2).

remove_first_and_last([X],[X]).
remove_first_and_last(In, Out) :-
    remove_first(In, Out1),
    remove_last(Out1, Out).

middle([X], [X]).
middle(In, X) :-
    remove_first_and_last(In, Out),
    middle(Out, X).

member(X, [X|_]).
member(X, [_|T]) :- member(X, T).

is_middle(X, In) :-
    middle(In, Out),
    member(X, Out), !.
</code>```

And when I call is_middle(1,[2,1,3]) then I get true.
But when I call is_middle(1,[2,2,3]) then I don't get a result. Interpreter don't interrupt the processing.

答:
```<code>is_middle(Item,List) :-
    append(Left,[Item|Right],List),
    length(Left,X),
    length(Right,X).
</code>```

Complex solutions are bad solutions, my friend.

```<code>?- is_middle(X,[1,2,3,4,5]).
X = 3 ;
false.
</code>```

Fully reversible predicate:

```<code>?- is_middle(3,L).
L = [3] ;
L = [_G13, 3, _G19] ;
L = [_G13, _G19, 3, _G25, _G28] ;
</code>```

Title: Prolog - infinite loop

Body:
I want to check if element is in the middle of list.
I search middle element and next I check if is a member of list, but I get infinite loop.

My predicates:

remove_first([_,H1|T], [H1|T]).

remove_last([_],[]).
remove_last([H|T], [H|T2]) :- remove_last(T, T2).

remove_first_and_last([X],[X]).
remove_first_and_last(In, Out) :-
    remove_first(In, Out1),
    remove_last(Out1, Out).

middle([X], [X]).
middle(In, X) :-
    remove_first_and_last(In, Out),
    middle(Out, X).

member(X, [X|_]).
member(X, [_|T]) :- member(X, T).

is_middle(X, In) :-
    middle(In, Out),
    member(X, Out), !.

And when I call is_middle(1,[2,1,3]) then I get true.
But when I call is_middle(1,[2,2,3]) then I don't get a result. Interpreter don't interrupt the processing.

Body:
is_middle(Item,List) :-
    append(Left,[Item|Right],List),
    length(Left,X),
    length(Right,X).

Complex solutions are bad solutions, my friend.

?- is_middle(X,[1,2,3,4,5]).
X = 3 ;
false.

Fully reversible predicate:

?- is_middle(3,L).
L = [3] ;
L = [_G13, 3, _G19] ;
L = [_G13, _G19, 3, _G25, _G28] ;


问:
Adding fragments to activity
First of all, I read everything here. https://developer.android.com/guide/components/fragments.html

I have one activity and I want to divide the screen horizontally and add 2 fragments. I know how to add fragments on XML but I don't want that. I want to add them on Java.

So the problem is FragmentManager doesnt work unless my activity extends Fragment. Should I do that on the activity or should I add fragment transaction methods on one of the fragments?

If I extend my activity to Fragment, does it also become a fragment?

If I put the fragmentmanager and fragmenttransaction on one of the fragments how can I make the connection with activity?

this is the activity which I want my fragments displayed on

```<code>import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class ConversionActivity extends AppCompatActivity {

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

        NumpadFragment fragment = new NumpadFragment();
        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.add(R.id.numpad_layout,fragment);
        fragmentTransaction.commit();

    }
}
</code>```

and this is one of the fragments

```<code>import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class NumpadFragment extends Fragment {
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_numpad,container,false);
    }
}
</code>```

答:
Some suggestions:

Use fragmentTransaction.replace (unless you need your fragments to be added to stack)

As containter for your fragment, use FrameLayout

Don't create new fragment by "new" operator. Add newInstance() method instead and create new fragment instance by calling that methrod. Also, implement interaction between your fragment and activity. Tip: use Android Studio wizard to add fragment to your project. Android Studio will generate skeleton with all needed methods already included

You definitely need to use getSupportFragmentManager (because your fragment is android.support.v4.app.Fragment)

DEBUG! - if you say "my app is crashing", it's useless. Post your logcat/exception/whatever to show crash reason.

Title: Adding fragments to activity

Body:
First of all, I read everything here. https://developer.android.com/guide/components/fragments.html

I have one activity and I want to divide the screen horizontally and add 2 fragments. I know how to add fragments on XML but I don't want that. I want to add them on Java.

So the problem is FragmentManager doesnt work unless my activity extends Fragment. Should I do that on the activity or should I add fragment transaction methods on one of the fragments?

If I extend my activity to Fragment, does it also become a fragment?

If I put the fragmentmanager and fragmenttransaction on one of the fragments how can I make the connection with activity?

this is the activity which I want my fragments displayed on

import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class ConversionActivity extends AppCompatActivity {

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

        NumpadFragment fragment = new NumpadFragment();
        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.add(R.id.numpad_layout,fragment);
        fragmentTransaction.commit();

    }
}

and this is one of the fragments

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class NumpadFragment extends Fragment {
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_numpad,container,false);
    }
}


问:
How to know/change current directory in Python shell?
I am using Python 3.2 on Windows 7.  When I open the Python shell, how can I know what the current directory is? How can I change it to another directory (where my modules are)?</p>

答:
The easiest way to change the current working directory in python is using the 'os' package. Below there is an example for windows computer:</p>

```<code># Import the os package
import os

# Confirm the current working directory
os.getcwd()

# Use '\\' while changing the directory
os.chdir("C:\\user\\foldername")
</code>```

ContentLicense: CC BY-SA 4.0

Body:
The easiest way to change the current working directory in python is using the 'os' package. Below there is an example for windows computer:

# Import the os package
import os

# Confirm the current working directory
os.getcwd()

# Use '\\' while changing the directory
os.chdir("C:\\user\\foldername")


问:
MySql PDO - Referring two colowns and displaying the id as result
I have been checking for more than an hour but i cant get the result, my question is, by checking two columns it must display the other columns value as result using PDO.

```<code>$sql ="SELECT column3 FROM tablename WHERE column1 = :request AND column2= :recived";
$conn = $conn->prepare($sql);
$fetch = $conn->execute(array(':request'=> $value1,':recived'=>$value2));
$fetch = $fetch->fetchColumn();
</code>```

please help me with this. Thanks in advance

答:
This is what you looking for :</p>

```<code><?php

$sql ="SELECT column3 FROM tablename WHERE column1 = :request AND column2= :recived";
$stmt = $conn->prepare($sql);
$stmt->execute(array(':request'=> $value1,':recived'=>$value2));
$fetch = $stmt->fetchColumn();
?>
</code>```

Body:
I have been checking for more than an hour but i cant get the result, my question is, by checking two columns it must display the other columns value as result using PDO.

$sql ="SELECT column3 FROM tablename WHERE column1 = :request AND column2= :recived";
$conn = $conn->prepare($sql);
$fetch = $conn->execute(array(':request'=> $value1,':recived'=>$value2));
$fetch = $fetch->fetchColumn();

please help me with this. Thanks in advance

Body:
This is what you looking for :

<?php

$sql ="SELECT column3 FROM tablename WHERE column1 = :request AND column2= :recived";
$stmt = $conn->prepare($sql);
$stmt->execute(array(':request'=> $value1,':recived'=>$value2));
$fetch = $stmt->fetchColumn();
?>


问:
Find text string in jQuery and make it bold
What I want to do is use jQuery to find a piece of text within a paragraph and add some CSS to make it bold. I can't seem to figure out why this won't work:

```<code>$(window).load(function() {
// ADD BOLD ELEMENTS
$('#about_theresidency:contains("cross genre")').css({'font-weight':'bold'});
});
</code>```

The text in "about_theresidency" is dynamically pulled in, hence me executing it after the window has loaded.

答:
Needed a more secure method, that could escape. Here is a vanilla solution

var str = 'The world is big world red. the world is also small'
var words = ['world', 'is']
var reg = RegExp(words.join('|'), 'gi')
var p = document.createElement('p')
p.innerText = str
p.innerHTML = p.innerHTML.replace(reg, '$&')

document.body.appendChild(p)
console.log(p.outerHTML)```

Body:
What I want to do is use jQuery to find a piece of text within a paragraph and add some CSS to make it bold. I can't seem to figure out why this won't work:

$(window).load(function() {
// ADD BOLD ELEMENTS
$('#about_theresidency:contains("cross genre")').css({'font-weight':'bold'});
});

The text in "about_theresidency" is dynamically pulled in, hence me executing it after the window has loaded.

Body:
Needed a more secure method, that could escape. Here is a vanilla solution

var str = 'The world is big <b onclick="alert(false)">world</b> red. the world is also small'
var words = ['world', 'is']
var reg = RegExp(words.join('|'), 'gi')
var p = document.createElement('p')
p.innerText = str
p.innerHTML = p.innerHTML.replace(reg, '<u>$&</u>')

document.body.appendChild(p)
console.log(p.outerHTML)


问:
KendoUI Grid how to disable only some filters operators
I need to disable only some filter (e.g. isnotnull or isnull) globally on all my grids, without redefine all operators that I want to preserve. How can I do that?</p>

答:
You can globaly set to undefined the filter you want to hide, like this:</p>

```<code>kendo.ui.FilterMenu.fn.options.operators.number.isnotnull = undefined;
kendo.ui.FilterMenu.fn.options.operators.string.isnotnull = undefined;
kendo.ui.FilterMenu.fn.options.operators.date.isnotnull = undefined;
kendo.ui.FilterMenu.fn.options.operators.enums.isnotnull = undefined;
</code>```

Body:
You can globaly set to undefined the filter you want to hide, like this:

kendo.ui.FilterMenu.fn.options.operators.number.isnotnull = undefined;
kendo.ui.FilterMenu.fn.options.operators.string.isnotnull = undefined;
kendo.ui.FilterMenu.fn.options.operators.date.isnotnull = undefined;
kendo.ui.FilterMenu.fn.options.operators.enums.isnotnull = undefined;


问:
Inserting a million small records into Extensible Storage Engine (JetBlue) - quickly
I'm hoping Laurion Burchall reads this :-)

I need to insert a million tiny records as quickly as possible.

Right now I'm in a very tight loop where, for every record, I

```<code>a) start a transaction  (JetBeginTransaction)
b) prepare an update (JetPrepareUpdate)
c) add the row (JetSetColumns)
d) commit the transaction (JetCommitTransaction)
</code>```

Right now, during this process, I'm in a tight loop on one processor.  The target machine has multiple CPUs, great disks, and lots of free RAM.

I'm wondering how to get better performance.

As far as transactions go, I did some experiments and had troubles where errors came back if I put too much data in one transaction.  I'd like to better understand what's going on there - do I have a bug, or is the size of a transaction capped, if capped can I enlarge the cap? I'm only investigating this because I'm guessing that a transaction give ESE the ability to do more caching in RAM, minimzing disk flushes? - this is just a guess?

In general how do I make use of multiple processors/lots of RAM/and nice disks?  do I open the database twice and go from there? I'm not quite sure what happens with respect to thread safety and transactions.  If I have two handles to the DB, each in a transaction,  will a write on one handle be available for the second immediately, before the commit, or will I need to commit first?

any tips are appreciated

```<code>    here are the constraints

a) I've got a million records that need to be written into the DB as fast as possible
b) to fully generate the record for insertion there are two searches that need to occur within the same table (seeking keys)
c) This is a rebuild/regeneration of the DB - it either worked, or it didnt.
   If it didnt there is no going back, a fresh rebuild/regeneration is
   needed.  I cannot restart mid process and without all the data none of
   the data is valuable.  READ: having one big transaction is fine if it
   improves perf.  I'd like ESE to cache, in ram, if that helps perf.
</code>```

thanks!

答:
For single-threaded performance the most important thing to look at is your transaction model.

If you have tried putting more data in one transaction and it failed you probably got a JET_errOutOfVersionStore. Esent has to track undo information for all operations performed in a transaction (to enable rollback) and that information is stored in the version store. The default size of the version store is quite small. You can increase it with the JET_paramMaxVerPages system parameter. A value of 1024 (64MB of version store) will enable quite large transactions. I suggest doing 100-1000 insertions per transaction.

When you call JetCommitTransaction Esent will flush the log to disk, generating a synchronous I/O. To avoid that pass JET_bitCommitLazyFlush to JetCommitTransaction. Your transactions will still be atomic but not durable in the case of a crash (things will be fine if you exit normally). It looks like that should be find for your use.

If you are inserting records in ascending order then you might be able to get away with a single-threaded application. If you can change your implementation to do sequential inserts you should -- they are a lot faster. For random inserts multiple threads can be useful. To use multiple threads you just need to create new sessions (JetBeginSession) and have them open the database (JetOpenDatabase). Esent uses snapshot isloation (http://en.wikipedia.org/wiki/Snapshot_isolation) so cannot see modifications made by other sessions which aren't committed or commit after your transaction begins. This is different than read-committed where you can see changes once another session commits. You might need to think about how to divide up the work to deal with this.

Body:
I'm hoping Laurion Burchall reads this :-)

I need to insert a million tiny records as quickly as possible.

Right now I'm in a very tight loop where, for every record, I

a) start a transaction  (JetBeginTransaction)
b) prepare an update (JetPrepareUpdate)
c) add the row (JetSetColumns)
d) commit the transaction (JetCommitTransaction)

Right now, during this process, I'm in a tight loop on one processor.  The target machine has multiple CPUs, great disks, and lots of free RAM.

I'm wondering how to get better performance.

As far as transactions go, I did some experiments and had troubles where errors came back if I put too much data in one transaction.  I'd like to better understand what's going on there - do I have a bug, or is the size of a transaction capped, if capped can I enlarge the cap? I'm only investigating this because I'm guessing that a transaction give ESE the ability to do more caching in RAM, minimzing disk flushes? - this is just a guess?

In general how do I make use of multiple processors/lots of RAM/and nice disks?  do I open the database twice and go from there? I'm not quite sure what happens with respect to thread safety and transactions.  If I have two handles to the DB, each in a transaction,  will a write on one handle be available for the second immediately, before the commit, or will I need to commit first?

any tips are appreciated

    here are the constraints

a) I've got a million records that need to be written into the DB as fast as possible
b) to fully generate the record for insertion there are two searches that need to occur within the same table (seeking keys)
c) This is a rebuild/regeneration of the DB - it either worked, or it didnt.
   If it didnt there is no going back, a fresh rebuild/regeneration is
   needed.  I cannot restart mid process and without all the data none of
   the data is valuable.  READ: having one big transaction is fine if it
   improves perf.  I'd like ESE to cache, in ram, if that helps perf.

thanks!


问:
Can I get node --inspect to open Chrome automatically
In the new versions of node, node-inspector is built in and can be fired using the command node --inspect index.js. However, this always provides a command line with the address you have to plug into the address bar. I know this may not be the most "secure" but is there a way to eliminate that copy and paste step?

答:
While this doesn't specifically answer the question, it makes the question less relevant - once connected you don't need to reconnect.

I tried all the suggestions here and other posts e.g. but I found the debug-in-a-tab would never reconnect once supervisor watch had generated a new GUID - the address in the tab is out of date.

However I found a new link in Chrome (58) standard Developer Pane which opens a new "headless" window which does reconnect magically no matter how the app is rebuilt / restarted.

Under Threads > Main, you should see "Node instance available. Connect".

I find the new-window less usable as I'd prefer a tab, but the auto-reconnect is so reliable I'll live with that!

The only downside I've found is when it does reconnect it clears all breakpoints.

UPDATE:
I’ve found it’s possible to workaround the problem of the breakpoints vanishing on reload, if you open several debug windows using the “Connect” link under Chrome Debug > Sources > Threads > Main. Most of them will be blank and won’t even have any sources listed in them, but the one that’s properly connected will eventually retain its bookmarks. I don’t know why this hack works — I discovered it by mistake.

Also this Hackernoon article discusses the problem, and the tool NIM is recommended as a solution, and general improvement to managing the inspector (also suggested in the answer by Adrian Moisa).

Update (08/2017)

It seems Chrome v60 has changed the DevTools for Node, moving the link I described to a small green box icon in the top left nav-bar of the JS dev tools.

However now my breakpoint hack no longer works as you can no longer open multiple windows. Sadly they've not fixed the disappearing breakpoints issue either. So now I'm back to closing it and reopening it every time... This is extra annoying as it doesn't even remember its window position (I like to move it to differentiate it from the front-end JS debug window which I use simultaneously being full-stack...), nor the fact I've close all those source file tabs already (I'll stop ranting now).


问:
PayPal IPN returns INVALID on live and VERIFIED on sandbox
I have been trying to implement the paypal IPN system in our company website. When I test my script in the IPN sandbox tool, it is validated and everything goes well, however when I move it live, the IPN  returned as INVALID but the payment has been completed well.
When I check the IPN history in my account, I can see this IPN message with the HTTP Response 200:

mc_gross=0.01&invoice=40&protection_eligibility=Ineligible&item_number1=&payer_id=mypayerId&tax=0.00&payment_date=08:06:52 Sep 03, 2013 PDT&payment_status=Completed&charset=windows-1252&mc_shipping=0.00&mc_handling=0.00&first_name=myName&mc_fee=0.01&notify_version=3.7&custom=18528&payer_status=verified&business=bussiness_mail&num_cart_items=1&mc_handling1=0.00&verify_sign=AJ.HL1f2A9aoBiFQCLn.3J-QkKQGAF.RVW8er5rbGJ6SsQFWBbStuRtD&payer_email=myMail&mc_shipping1=0.00&tax1=0.00&txn_id=61052338B4613440H&payment_type=instant&last_name=MySurname&item_name1=Paquete Lite&receiver_email=mybussiness_mail&payment_fee=&quantity1=1&receiver_id=SVRXVCZYE2AYC&txn_type=cart&mc_gross_1=0.01&mc_currency=EUR&residence_country=ES&transaction_subject=18528&payment_gross=&ipn_track_id=38c492cbe6257

Paypal live credentials are OK.

URL is OK (https://www.paypal.com/cgi-bin/webscr)

My IPNHandler is a Java Servlet. The doPost Action is:

```<code> @Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // Java JSP
    log.error("IPN doPost " + new Date().getHours() + ":" + new Date().getMinutes() + ":" + new Date().getSeconds());

    // read post from PayPal system and add 'cmd'
    Enumeration en = request.getParameterNames();
    String str = "cmd=_notify-validate";
    while (en.hasMoreElements()) {
        String paramName = (String) en.nextElement();
        String paramValue = request.getParameter(paramName);
        paramValue = new String(paramValue.getBytes("iso-8859-1"), "utf-8");
        str = str + "&" + paramName + "=" + URLEncoder.encode(paramValue);
    }

    boolean isSandbox = "true".equals(PropertiesManager.getProperty("signbox", "PaypalSandbox"));
    // post back to PayPal system to validate
    // NOTE: change http: to https: in the following URL to verify using SSL (for increased security).
    // using HTTPS requires either Java 1.4 or greater, or Java Secure Socket Extension (JSSE)
    // and configured for older versions.
    String url = null;
    if (isSandbox){
        url = "https://www.sandbox.paypal.com/cgi-bin/webscr";
    }else{
        url = "https://www.paypal.com/cgi-bin/webscr";
    }
    log.error("La url de a la que redirigimos a Paypal es " + url);
    URL u = new URL(url);
    URLConnection uc = u.openConnection();
    uc.setDoOutput(true);
    uc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    PrintWriter pw = new PrintWriter(uc.getOutputStream());
    pw.println(str);
    pw.close();

    BufferedReader in = new BufferedReader(
            new InputStreamReader(uc.getInputStream()));
    String res = in.readLine();
    in.close();
    log.error("Tras abrir la conexión, res es = " + res);

    // assign posted variables to local variables
    String idUser = request.getParameter("custom");
    String idCompra = request.getParameter("invoice");
    String paymentStatus = request.getParameter("payment_status");
    String paymentAmount = request.getParameter("mc_gross");
    String fee = request.getParameter("mc_fee");
    String paymentCurrency = request.getParameter("mc_currency");
    String txnId = request.getParameter("txn_id");
    String receiptId = request.getParameter("receipt_id");
    String receiverEmail = request.getParameter("receiver_email");
    String payerEmail = request.getParameter("payer_email");
    String paymentType = request.getParameter("payment_type");
    String txnType = request.getParameter("txn_type");

    if (!"instant".equals(paymentType) || !"cart".equals(txnType)) {
        log.debug("NO ES UN CART CHECKOUT. Detalles:");
        log.debug("idCompra=" + idCompra);
        log.debug("status=" + paymentStatus);
        log.debug("amount=" + paymentAmount);
        log.debug("currency=" + paymentCurrency);
        log.debug("transactionId=" + txnId);
        log.debug("receiptId=" + receiptId);
        log.debug("receiverEmail=" + receiverEmail);
        log.debug("payerEmail=" + payerEmail);
        log.debug("paymentType=" + paymentType);
        log.debug("txnType=" + txnType);

        return;
    }

    **//HERE THE RESPONSE IS INVALID IN LIVE MODE**
    if (res != null && res.equals("VERIFIED")) { //res = "VERIFIED" res = "INVALID"
        // more code not important for this issue....
</code>```

Any idea? As I said, payments are completed but the IPN is sended INVALID.

答:
To receive IPN message data from PayPal, your listener must follow this request-response flow:

1.Your listener listens for the HTTPS POST IPN messages that PayPal sends with each event.

2.After receiving the IPN message from PayPal, your listener returns an empty HTTP 200 response to PayPal. Otherwise, PayPal resends the IPN message.

3.Your listener sends the complete message back to PayPal using HTTPS POST.

Prefix the returned message with the cmd=_notify-validate variable, but do not change the message fields, the order of the fields, or the character encoding from the original message.

Send response messages back to PayPal:

https://ipnpb.sandbox.paypal.com/cgi-bin/webscr (for Sandbox IPNs)

https:/ipnpb.paypal.com/cgi-bin/webscr (for live IPNs)

for more info see also:
https://developer.paypal.com/docs/classic/ipn/integration-guide/IPNImplementation/#specs

Body:
I have been trying to implement the paypal IPN system in our company website. When I test my script in the IPN sandbox tool, it is validated and everything goes well, however when I move it live, the IPN  returned as INVALID but the payment has been completed well.
When I check the IPN history in my account, I can see this IPN message with the HTTP Response 200:

mc_gross=0.01&invoice=40&protection_eligibility=Ineligible&item_number1=&payer_id=mypayerId&tax=0.00&payment_date=08:06:52 Sep 03, 2013 PDT&payment_status=Completed&charset=windows-1252&mc_shipping=0.00&mc_handling=0.00&first_name=myName&mc_fee=0.01&notify_version=3.7&custom=18528&payer_status=verified&business=bussiness_mail&num_cart_items=1&mc_handling1=0.00&verify_sign=AJ.HL1f2A9aoBiFQCLn.3J-QkKQGAF.RVW8er5rbGJ6SsQFWBbStuRtD&payer_email=myMail&mc_shipping1=0.00&tax1=0.00&txn_id=61052338B4613440H&payment_type=instant&last_name=MySurname&item_name1=Paquete Lite&receiver_email=mybussiness_mail&payment_fee=&quantity1=1&receiver_id=SVRXVCZYE2AYC&txn_type=cart&mc_gross_1=0.01&mc_currency=EUR&residence_country=ES&transaction_subject=18528&payment_gross=&ipn_track_id=38c492cbe6257

Paypal live credentials are OK.

URL is OK (https://www.paypal.com/cgi-bin/webscr)

My IPNHandler is a Java Servlet. The doPost Action is:

 @Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // Java JSP
    log.error("IPN doPost " + new Date().getHours() + ":" + new Date().getMinutes() + ":" + new Date().getSeconds());

    // read post from PayPal system and add 'cmd'
    Enumeration en = request.getParameterNames();
    String str = "cmd=_notify-validate";
    while (en.hasMoreElements()) {
        String paramName = (String) en.nextElement();
        String paramValue = request.getParameter(paramName);
        paramValue = new String(paramValue.getBytes("iso-8859-1"), "utf-8");
        str = str + "&" + paramName + "=" + URLEncoder.encode(paramValue);
    }

    boolean isSandbox = "true".equals(PropertiesManager.getProperty("signbox", "PaypalSandbox"));
    // post back to PayPal system to validate
    // NOTE: change http: to https: in the following URL to verify using SSL (for increased security).
    // using HTTPS requires either Java 1.4 or greater, or Java Secure Socket Extension (JSSE)
    // and configured for older versions.
    String url = null;
    if (isSandbox){
        url = "https://www.sandbox.paypal.com/cgi-bin/webscr";
    }else{
        url = "https://www.paypal.com/cgi-bin/webscr";
    }
    log.error("La url de a la que redirigimos a Paypal es " + url);
    URL u = new URL(url);
    URLConnection uc = u.openConnection();
    uc.setDoOutput(true);
    uc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    PrintWriter pw = new PrintWriter(uc.getOutputStream());
    pw.println(str);
    pw.close();

    BufferedReader in = new BufferedReader(
            new InputStreamReader(uc.getInputStream()));
    String res = in.readLine();
    in.close();
    log.error("Tras abrir la conexión, res es = " + res);

    // assign posted variables to local variables
    String idUser = request.getParameter("custom");
    String idCompra = request.getParameter("invoice");
    String paymentStatus = request.getParameter("payment_status");
    String paymentAmount = request.getParameter("mc_gross");
    String fee = request.getParameter("mc_fee");
    String paymentCurrency = request.getParameter("mc_currency");
    String txnId = request.getParameter("txn_id");
    String receiptId = request.getParameter("receipt_id");
    String receiverEmail = request.getParameter("receiver_email");
    String payerEmail = request.getParameter("payer_email");
    String paymentType = request.getParameter("payment_type");
    String txnType = request.getParameter("txn_type");

    if (!"instant".equals(paymentType) || !"cart".equals(txnType)) {
        log.debug("NO ES UN CART CHECKOUT. Detalles:");
        log.debug("idCompra=" + idCompra);
        log.debug("status=" + paymentStatus);
        log.debug("amount=" + paymentAmount);
        log.debug("currency=" + paymentCurrency);
        log.debug("transactionId=" + txnId);
        log.debug("receiptId=" + receiptId);
        log.debug("receiverEmail=" + receiverEmail);
        log.debug("payerEmail=" + payerEmail);
        log.debug("paymentType=" + paymentType);
        log.debug("txnType=" + txnType);

        return;
    }

    **//HERE THE RESPONSE IS INVALID IN LIVE MODE**
    if (res != null && res.equals("VERIFIED")) { //res = "VERIFIED" res = "INVALID"
        // more code not important for this issue....

Any idea? As I said, payments are completed but the IPN is sended INVALID.


问:
Laravel getQueryString() without &
I'm trying to output a variable containing part of a URL into Javascript on my page. When I do this, it changes any & into &, which breaks the URL.

I've tried using str_replace, html_entity_decode, htmlspecialchars_decode but the result was always same & instead of &.

How i can get it with & instead of & ?

This is my controller:

```<code>//here we catch the query
public function index(Request $request)
    {
        $input   = $request->getQueryString();

        return view('lots.browse')->withInput($input);
    }

// here we filter the ajax request
public function indexData(LotFilters $filters)
    {
       $lots  = Lot::filter($filters);

        return Datatables::eloquent($lots)->make(true);
    }
</code>```

This is my view:

```<code><!-- Datatables -->
    <script type="text/javascript">
        $(document).ready(function(){
            $('#table').DataTable({
                searching: false,
                processing: true,
                serverSide: true,
                ajax: '{{  url("/data") . "?" .  html_entity_decode($input) }}',
                columns: [
                    { data: 'date', name: 'date' },
                    { data: 'bid', name: 'bid' },
                    { data: 'auction_name', name: 'auction_name' },
                    { data: 'pics_urls', name: 'pics_urls' },
                    { data: 'company', name: 'company' },
                    { data: 'model_name_en', name: 'model_name_en' },
                    { data: 'model_type_en', name: 'model_type_en' },
                    { data: 'grade_en', name: 'grade_en' },
                    { data: 'mileage_en', name: 'mileage_en' },
                    { data: 'model_year_en', name: 'model_year_en' },
                    { data: 'color_en', name: 'color_en' },
                    { data: 'displacement', name: 'displacement' },
                    { data: 'transmission_en', name: 'transmission_en' },
                    { data: 'scores_en', name: 'scores_en' },
                    { data: 'start_price_en', name: 'start_price_en' },
                    { data: 'result_en', name: 'result_en' }
                ]
            });
        });
    </script>
</code>```

And this is the result:

答:
in stead of blade {{ $input }} just used <?php echo $input ?> and link renders with out changing & in to & . So this is just problem of blade.php , i don't know why it is like that, but i finally managed to solve my problem.

So this is my script:

```<code><script type="text/javascript">
        $(document).ready(function(){
            $('#table').DataTable({
                searching: false,
                processing: true,
                serverSide: true,
                ajax: "<?php echo '/data?' .  $input ?>",
                columns: [
                    { data: 'date', name: 'date'},
                    { data: 'bid', name: 'bid' },
                    { data: 'auction_name', name: 'auction_name' },
                    { data: 'pics_urls', name: 'pics_urls' },
                    { data: 'company', name: 'company' },
                    { data: 'model_name_en', name: 'model_name_en' },
                    { data: 'model_type_en', name: 'model_type_en' },
                    { data: 'grade_en', name: 'grade_en' },
                    { data: 'mileage_en', name: 'mileage_en' },
                    { data: 'model_year_en', name: 'model_year_en' },
                    { data: 'color_en', name: 'color_en' },
                    { data: 'displacement', name: 'displacement' },
                    { data: 'transmission_en', name: 'transmission_en' },
                    { data: 'scores_en', name: 'scores_en' },
                    { data: 'start_price_en', name: 'start_price_en' },
                    { data: 'result_en', name: 'result_en' }
                ]
            });
        });
    </script>
</code>```

And my controller:

```<code>public function index(Request $request)
    {
        $input   = $request->getQueryString();

        return view('lots.browse')->withInput($input);
    }
</code>```

And the result :

Title: Laravel getQueryString() without &

Body:
I'm trying to output a variable containing part of a URL into Javascript on my page. When I do this, it changes any & into &, which breaks the URL.

I've tried using str_replace, html_entity_decode, htmlspecialchars_decode but the result was always same & instead of &.

How i can get it with & instead of & ?

This is my controller:

//here we catch the query
public function index(Request $request)
    {
        $input   = $request->getQueryString();

        return view('lots.browse')->withInput($input);
    }

// here we filter the ajax request
public function indexData(LotFilters $filters)
    {
       $lots  = Lot::filter($filters);

        return Datatables::eloquent($lots)->make(true);
    }

This is my view:

And this is the result:

Body:
in stead of blade {{ $input }} just used <?php echo $input ?> and link renders with out changing & in to &amp; . So this is just problem of blade.php , i don't know why it is like that, but i finally managed to solve my problem.

So this is my script:

<script type="text/javascript">
        $(document).ready(function(){
            $('#table').DataTable({
                searching: false,
                processing: true,
                serverSide: true,
                ajax: "<?php echo '/data?' .  $input ?>",
                columns: [
                    { data: 'date', name: 'date'},
                    { data: 'bid', name: 'bid' },
                    { data: 'auction_name', name: 'auction_name' },
                    { data: 'pics_urls', name: 'pics_urls' },
                    { data: 'company', name: 'company' },
                    { data: 'model_name_en', name: 'model_name_en' },
                    { data: 'model_type_en', name: 'model_type_en' },
                    { data: 'grade_en', name: 'grade_en' },
                    { data: 'mileage_en', name: 'mileage_en' },
                    { data: 'model_year_en', name: 'model_year_en' },
                    { data: 'color_en', name: 'color_en' },
                    { data: 'displacement', name: 'displacement' },
                    { data: 'transmission_en', name: 'transmission_en' },
                    { data: 'scores_en', name: 'scores_en' },
                    { data: 'start_price_en', name: 'start_price_en' },
                    { data: 'result_en', name: 'result_en' }
                ]
            });
        });
    </script>

And my controller:

public function index(Request $request)
    {
        $input   = $request->getQueryString();

        return view('lots.browse')->withInput($input);
    }

And the result :


问:
Passing method to lodash with vue gives 'Expected a function'
I am trying to pass a Vue function to the lodash throttle method. Shouldn't I just be able to do something like this?

When I am trying to do this I am getting the following error:

Error in callback for watcher "query": "TypeError: Expected a function"

Watcher

```<code>watch: {
    query() {
        throttle(this.autocomplete(), 400);
    }
}
</code>```

Methods

```<code>methods: {
    autocomplete() {}
}
</code>```

Even though I am passing a function reference I am still getting an error message. If I wrap it with a anonymous function it won't fire:

```<code>throttle(() => { this.autocomplete(); }, 400);
</code>```

I just checked and the autocomplete function does actually seem to fire regardless of the error that it is not a function in my example at the top.

What is going wrong here?

Edit:

Jsfiddle: http://jsfiddle.net/yMv7y/2780/

答:
Working approach:

var demo = new Vue({
  el: '#demo',
  data: {
    query: ''
  },
  watch: {
    query: function() {
      this.autocomplete()
    }
  },
  methods: {
    autocomplete: _.throttle(function() {
      console.log('test');
    }, 50)
  }
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="http://vuejs.org/js/vue.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>

<div id="demo" v-cloak>
    <input type="text" v-model="query">
</div></code>```

As @Bill Criswell commented,

This is creating a throttled function every time query changes. You
  want to constantly call the same throttled function like the answer
  below.

Body:
I am trying to pass a Vue function to the lodash throttle method. Shouldn't I just be able to do something like this?

When I am trying to do this I am getting the following error:

Error in callback for watcher "query": "TypeError: Expected a function"

Watcher

watch: {
    query() {
        throttle(this.autocomplete(), 400);
    }
}

Methods

methods: {
    autocomplete() {}
}

Even though I am passing a function reference I am still getting an error message. If I wrap it with a anonymous function it won't fire:

throttle(() => { this.autocomplete(); }, 400);

I just checked and the autocomplete function does actually seem to fire regardless of the error that it is not a function in my example at the top.

What is going wrong here?

Edit:

Jsfiddle: http://jsfiddle.net/yMv7y/2780/

Body:
Working approach:

var demo = new Vue({
  el: '#demo',
  data: {
    query: ''
  },
  watch: {
    query: function() {
      this.autocomplete()
    }
  },
  methods: {
    autocomplete: _.throttle(function() {
      console.log('test');
    }, 50)
  }
})

<script src="http://vuejs.org/js/vue.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>

<div id="demo" v-cloak>
    <input type="text" v-model="query">
</div>

As @Bill Criswell commented,

This is creating a throttled function every time query changes. You
  want to constantly call the same throttled function like the answer
  below.


问:
css first child not wokring
I have the following html

.resources .resource:first-child {
  border-top: 1px solid #D9B310;
}

.resources .resource {
  border-bottom: 1px solid #D9B310;
  padding: 10px 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="resources">
  <h2 class="text-center">Ресурси</h1>

    <div class="resource">
      <h4>Минерали <span class="resource-quantity">3700</span></h3>
    </div>

    <div class="resource">
      <h4>Газ <span class="resource-quantity">500</span></h3>
    </div>
</div></code>```

the selector without the first-child works fine. But the first-child selector it's not wrking in my case. Can someone tell me why ?

答:
Use :first-of-type because it's second child of it's parent.

.resources .resource:first-of-type {
  border-top: 1px solid #D9B310;
}

.resources .resource {
  border-bottom: 1px solid #D9B310;
  padding: 10px 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="resources">
  <h2 class="text-center">Ресурси</h2>

    <div class="resource">
      <h4>Минерали <span class="resource-quantity">3700</span></h4>
    </div>

    <div class="resource">
      <h4>Газ <span class="resource-quantity">500</span></h4>
    </div>
</div></code>```

Title: css first child not wokring

Body:
I have the following html

.resources .resource:first-child {
  border-top: 1px solid #D9B310;
}

.resources .resource {
  border-bottom: 1px solid #D9B310;
  padding: 10px 0;
}

Ресурси

Минерали 3700

Газ 500

the selector without the first-child works fine. But the first-child selector it's not wrking in my case. Can someone tell me why ?

Body:
Use :first-of-type because it's second child of it's parent.

.resources .resource:first-of-type {
  border-top: 1px solid #D9B310;
}

.resources .resource {
  border-bottom: 1px solid #D9B310;
  padding: 10px 0;
}

<div class="resources">
  <h2 class="text-center">Ресурси</h2>

    <div class="resource">
      <h4>Минерали <span class="resource-quantity">3700</span></h4>
    </div>

    <div class="resource">
      <h4>Газ <span class="resource-quantity">500</span></h4>
    </div>
</div>