问:
Condition in controller laravel
I have this code in my Laravel controller

```<code>public function index($id=false) {
    //get resto by name
    $resto_nom = DB::table('restos as r')
        ->JOIN('produit as p', 'p.r_id', '=', 'r.r_id')
        ->JOIN('categorie as c', 'c.ca_id', '=', 'p.ca_id')
        ->WHERE('r.r_nom', $id)
        ->WHERE('p.po_etat', 1)
        ->get();

    foreach ($resto_nom as $r):
        $r_nom = $r->r_nom;
        $r_description = $r->r_description;
        $r_specialite = $r->r_specialite;
        $meta = $r_nom.', '.$r_specialite.", restaurant NosRepas, repas";
        $description = $r_nom.' - '.$r_specialite.'. '.$r_description;
    endforeach;

    if($id != $r_nom){
        return view('frontend.pages.resto', compact('meta', 'description', 'resto_nom'));
    }else{
        return view('frontend.pages.resto', compact('meta', 'description', 'resto_nom'));
    }
}
</code>```

I have error after Undefined variable: r_nom
My goal is displaying if the value found is correct so view display and so incorrect it returns 404 not found.

答:
You have to set the variable before foreach, otherwise it will be available only inside the loop. Try this:

```<code>$r_nom = null;
foreach ($resto_nom as $r):
    $r_nom = $r->r_nom;
    $r_description = $r->r_description;
    $r_specialite = $r->r_specialite;

    $meta = $r_nom.', '.$r_specialite.", restaurant NosRepas, repas";
    $description = $r_nom.' - '.$r_specialite.'. '.$r_description;
endforeach;
</code>```

Title: Condition in controller laravel

Body:
I have this code in my Laravel controller

public function index($id=false) {
    //get resto by name
    $resto_nom = DB::table('restos as r')
        ->JOIN('produit as p', 'p.r_id', '=', 'r.r_id')
        ->JOIN('categorie as c', 'c.ca_id', '=', 'p.ca_id')
        ->WHERE('r.r_nom', $id)
        ->WHERE('p.po_etat', 1)
        ->get();

    foreach ($resto_nom as $r):
        $r_nom = $r->r_nom;
        $r_description = $r->r_description;
        $r_specialite = $r->r_specialite;
        $meta = $r_nom.', '.$r_specialite.", restaurant NosRepas, repas";
        $description = $r_nom.' - '.$r_specialite.'. '.$r_description;
    endforeach;

    if($id != $r_nom){
        return view('frontend.pages.resto', compact('meta', 'description', 'resto_nom'));
    }else{
        return view('frontend.pages.resto', compact('meta', 'description', 'resto_nom'));
    }
}

I have error after Undefined variable: r_nom
My goal is displaying if the value found is correct so view display and so incorrect it returns 404 not found.

Body:
You have to set the variable before foreach, otherwise it will be available only inside the loop. Try this:

$r_nom = null;
foreach ($resto_nom as $r):
    $r_nom = $r->r_nom;
    $r_description = $r->r_description;
    $r_specialite = $r->r_specialite;

    $meta = $r_nom.', '.$r_specialite.", restaurant NosRepas, repas";
    $description = $r_nom.' - '.$r_specialite.'. '.$r_description;
endforeach;


来源: stackexchange

问:
How can I count the number of seconds a window is open?
I'm trying to write a script where I need a timer to count the number of seconds a popup is open. I'm new to programming but I assume you use javascript for it?</p>

答:
When it comes the calculating a certain time frame, I always use the date object, storing a new date in a variable once the popup is open and subtracting that value to the current date. Here's an example:

```<code>// Execute this when the popup opens
var popup_opened = (new Date()).getTime();

// And this way you can get the time (in seconds) that the popup has been opened
var current_time = (new Date()).getTime();
var time_spent_opened = (current_time - popup_opened)/100;
</code>```

You can also retrieve the time the popup has been open multiple times using a function:

```<code>function getPopupTime() {
    var current_time = (new Date()).getTime();
    return (current_time - popup_opened)/100;
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
When it comes the calculating a certain time frame, I always use the date object, storing a new date in a variable once the popup is open and subtracting that value to the current date. Here's an example:

// Execute this when the popup opens
var popup_opened = (new Date()).getTime();

// And this way you can get the time (in seconds) that the popup has been opened
var current_time = (new Date()).getTime();
var time_spent_opened = (current_time - popup_opened)/100;

You can also retrieve the time the popup has been open multiple times using a function:

function getPopupTime() {
    var current_time = (new Date()).getTime();
    return (current_time - popup_opened)/100;
}


问:
npm modules versioning on popper.js sample: why 1.13.0 is not a release?
npm view popper.js versions returns  this list of versions

[...
  '1.12.8',
  '1.12.9',
  '1.13.0-next',
  '1.13.0' ]

But the current popper.js version is 1.12.9 :
https://www.npmjs.com/package/popper.js

Could somebody help me to understand what is a 1.13.0  ? Is it a prerelease ? Hidden version?

P.S. I'm trying to find the way how to get a last prerelease version of bootstrap with the npm, I understand that I should write a script around npm view popper.js versions but there is a sample of output that I can't interpretate.

答: IMO you should ask your question about Popper.js here : https://github.com/FezVrasta/popper.js</p>

ContentLicense: CC BY-SA 3.0


问:
Mutate a nummrec variable dependent of it´s quantity
I have this column in my data frame.

str(a)

```<code> $ : int [1:2] 2 2
 $ : int [1:2] 0 3
 $ : int [1:2] 0 0
 $ : int [1:2] 0 0
 $ : int [1:2] 10 9
</code>```

dput (a)

```<code>list(c(2L, 2L), c(0L, 3L), c(0L, 0L), c(0L, 0L), 10:9)
</code>```

As you can see, every row consists two numbers. I want to create a new variable out of these in a new column.

The conditions are as follows:

If the first of the two numbers is greater than the second one -> -1

If the second number is greater than the first one -> +1

If both numbers are equal -> 0

So the result should look as follows:

```<code>      a (old variable) b (new variable)
1.    2 2              0
2.    0 3              1
3.    0 0              0
4.    0 0              0
5.   10 9             -1
</code>```

I tried the following code but I got an error.

```<code>a %>% mutate(b = ifelese(sapply(a,'[[',1) == sapply(a,'[[',2), 0, ifelese(sapply(a,'[[',1) > sapply(a,'[[',2), -1, felese(sapply(a,'[[',1) < sapply(a,'[[',2), 1, NA))))

    Error in UseMethod("mutate_") : no applicable method for 'mutate_' applied to an object of class "list"
</code>```

Much appreciated!

答:
How about this:</p>

```<code>sapply(a, function(x) sign(diff(x)))
#[1]  0  1  0  0 -1
</code>```

Body:
I have this column in my data frame.

str(a)

 $ : int [1:2] 2 2
 $ : int [1:2] 0 3
 $ : int [1:2] 0 0
 $ : int [1:2] 0 0
 $ : int [1:2] 10 9

dput (a)

list(c(2L, 2L), c(0L, 3L), c(0L, 0L), c(0L, 0L), 10:9)

As you can see, every row consists two numbers. I want to create a new variable out of these in a new column.

The conditions are as follows:

If the first of the two numbers is greater than the second one -> -1

If the second number is greater than the first one -> +1

If both numbers are equal -> 0

So the result should look as follows:

      a (old variable) b (new variable)
1.    2 2              0
2.    0 3              1
3.    0 0              0
4.    0 0              0
5.   10 9             -1

I tried the following code but I got an error.

a %>% mutate(b = ifelese(sapply(a,'[[',1) == sapply(a,'[[',2), 0, ifelese(sapply(a,'[[',1) > sapply(a,'[[',2), -1, felese(sapply(a,'[[',1) < sapply(a,'[[',2), 1, NA))))

    Error in UseMethod("mutate_") : no applicable method for 'mutate_' applied to an object of class "list"

Much appreciated!

Body:
How about this:

sapply(a, function(x) sign(diff(x)))
#[1]  0  1  0  0 -1


问:
Alter a MySQL column to be AUTO_INCREMENT
I’m trying to modify a table to make its primary key column AUTO_INCREMENT after the fact.  I have tried the following SQL, but got a syntax error notification.

ALTER TABLE document
ALTER COLUMN document_id AUTO_INCREMENT
```

<p>Am I doing something wrong or is this not possible?</p>

```
+--------------------+
| VERSION()          |
+--------------------+
| 5.0.75-0ubuntu10.2 |
+--------------------+
```

答:
As you are redefining the column again, you have to specify the datatype again and add auto_increment to it as it's a part of datatype.</p>

```<code>ALTER TABLE `document` MODIFY COLUMN `document_id` INT AUTO_INCREMENT;
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I’m trying to modify a table to make its primary key column AUTO_INCREMENT after the fact.  I have tried the following SQL, but got a syntax error notification.

ALTER TABLE document
ALTER COLUMN document_id AUTO_INCREMENT

Am I doing something wrong or is this not possible?

+--------------------+
| VERSION()          |
+--------------------+
| 5.0.75-0ubuntu10.2 |
+--------------------+

Body:
As you are redefining the column again, you have to specify the datatype again and add auto_increment to it as it's a part of datatype.

ALTER TABLE `document` MODIFY COLUMN `document_id` INT AUTO_INCREMENT;


问:
undefined references when using fftw3.3.6 with threads and float enabled
I installed fftw3.3.6 on my Ubuntu 16.04 to test the performance of using this library with thread and float enabled.

Step 1 :

Installed the library with thread and float and SIMD instructions enabled:`

```<code>sudo ./configure --enable-float --enable-generic-simd128 --enable-generic-simd256 --enable-threads
make
make install
</code>```

Step 2 :

I wrote this code (basing on the manual and tutorial) to compute an fft of 1024 points using 4 threads (complex to complex):

```<code>#include <stdio.h>
#include <stdlib.h>
#include <fftw3.h>

#include "input.h"

#define         NUMBER_OF_ELEMENTS              1024
#define         NUM_THREADS                     4

void Load_inputs(fftwf_complex* data)
{
   int i;

   for(i=0;i<NUMBER_OF_ELEMENTS;i++)
   {
      data[i][0] = input_data[2 * i];
      data[i][1] = input_data[2 * i + 1];
   }
}

int main()
{
   fftwf_complex array[NUMBER_OF_ELEMENTS];
   fftwf_plan p;
   int i;

   fftwf_init_threads();
   fftwf_plan_with_nthreads(NUM_THREADS);
   p = fftwf_plan_dft(1,NUMBER_OF_ELEMENTS,array,array,FFTW_FORWARD,FFTW_EXHAUSTIVE);
   Load_inputs(array); //function to load input data from input.h file to array[]
   fftwf_execute(p);
   FILE* res = NULL;
   res = fopen("result.txt", "w");
   for ( i = 0; i <1024; i++ )
   {
       fprintf(res,"RE = %f \t IM  = %f\n",array[i][0], array[i][1] );
   }
   fclose(res);
   fftwf_destroy_plan(p);
   fftwf_cleanup_threads();
}
</code>```

And then, I compiled this program with this makefile.

```<code>CC=gcc
CFLAGS=-g3 -c -Wall -O0 -mavx -mfma -ffast-math

SOURCES=$ test.c
OBJECTS=$(SOURCES:.c=.o)

EXECUTABLE=test

all: $(TASKMAP) $(SOURCES) $(EXECUTABLE)

$(EXECUTABLE): $(OBJECTS)
     $(CC) $(OBJECTS) -o $@ -L -lfftw3f_threads -lfftw3f

.c.o:
     $(CC) $(CFLAGS) $< -lm -o $@

clean:
     rm -fr $(OBJECTS) $(EXECUTABLE)
</code>```

Compilation errors :

After compilation I've got these errors:

```<code>gcc test.o -o test -L -lfftw3f_threads -lfftw3f
//usr/local/lib/libfftw3f.a(mapflags.o): In function `fftwf_mapflags':
mapflags.c:(.text+0x346): undefined reference to `__log_finite'
Makefile:13: recipe for target 'test' failed
//usr/local/lib/libfftw3f.a(trig.o): In function `cexpl_sincos':
trig.c:(.text+0x2c1): undefined reference to `sincos'
//usr/local/lib/libfftw3f.a(trig.o): In function `fftwf_mktriggen':
trig.c:(.text+0x50b): undefined reference to `sincos'
trig.c:(.text+0x653): undefined reference to `sincos'
test.o: In function `main':
/home/anouar/workspace/Thread_example//test.c:27: undefined reference to `fftwf_init_threads'
/home/anouar/workspace/Thread_example//test.c:28: undefined reference to `fftwf_plan_with_nthreads'
/home/anouar/workspace/Thread_example//test.c:40: undefined reference to `fftwf_cleanup_threads'
 collect2: error: ld returned 1 exit status
 make: *** [test] Error 1
</code>```

Is there something missing, or something wrong that I have did during installation and compilation?

答:
Read the fine manual.  From the sincos() man page:

Link with -lm.

Using -lm in the compile phase of your program is useless:

```<code>.c.o:
     $(CC) $(CFLAGS) $< -lm -o $@
</code>```

-lm needs to be in the link stage:

```<code>$(EXECUTABLE): $(OBJECTS)
     $(CC) $(OBJECTS) -o $@ -L -lfftw3f_threads -lfftw3f -lm
</code>```

Body:
I installed fftw3.3.6 on my Ubuntu 16.04 to test the performance of using this library with thread and float enabled.

Step 1 :

Installed the library with thread and float and SIMD instructions enabled:`

sudo ./configure --enable-float --enable-generic-simd128 --enable-generic-simd256 --enable-threads
make
make install

Step 2 :

I wrote this code (basing on the manual and tutorial) to compute an fft of 1024 points using 4 threads (complex to complex):

#include <stdio.h>
#include <stdlib.h>
#include <fftw3.h>

#include "input.h"

#define         NUMBER_OF_ELEMENTS              1024
#define         NUM_THREADS                     4

void Load_inputs(fftwf_complex* data)
{
   int i;

   for(i=0;i<NUMBER_OF_ELEMENTS;i++)
   {
      data[i][0] = input_data[2 * i];
      data[i][1] = input_data[2 * i + 1];
   }
}

int main()
{
   fftwf_complex array[NUMBER_OF_ELEMENTS];
   fftwf_plan p;
   int i;

   fftwf_init_threads();
   fftwf_plan_with_nthreads(NUM_THREADS);
   p = fftwf_plan_dft(1,NUMBER_OF_ELEMENTS,array,array,FFTW_FORWARD,FFTW_EXHAUSTIVE);
   Load_inputs(array); //function to load input data from input.h file to array[]
   fftwf_execute(p);
   FILE* res = NULL;
   res = fopen("result.txt", "w");
   for ( i = 0; i <1024; i++ )
   {
       fprintf(res,"RE = %f \t IM  = %f\n",array[i][0], array[i][1] );
   }
   fclose(res);
   fftwf_destroy_plan(p);
   fftwf_cleanup_threads();
}

And then, I compiled this program with this makefile.

CC=gcc
CFLAGS=-g3 -c -Wall -O0 -mavx -mfma -ffast-math

SOURCES=$ test.c
OBJECTS=$(SOURCES:.c=.o)

EXECUTABLE=test

all: $(TASKMAP) $(SOURCES) $(EXECUTABLE)

$(EXECUTABLE): $(OBJECTS)
     $(CC) $(OBJECTS) -o $@ -L -lfftw3f_threads -lfftw3f

.c.o:
     $(CC) $(CFLAGS) $< -lm -o $@

clean:
     rm -fr $(OBJECTS) $(EXECUTABLE)

Compilation errors :

After compilation I've got these errors:

gcc test.o -o test -L -lfftw3f_threads -lfftw3f
//usr/local/lib/libfftw3f.a(mapflags.o): In function `fftwf_mapflags':
mapflags.c:(.text+0x346): undefined reference to `__log_finite'
Makefile:13: recipe for target 'test' failed
//usr/local/lib/libfftw3f.a(trig.o): In function `cexpl_sincos':
trig.c:(.text+0x2c1): undefined reference to `sincos'
//usr/local/lib/libfftw3f.a(trig.o): In function `fftwf_mktriggen':
trig.c:(.text+0x50b): undefined reference to `sincos'
trig.c:(.text+0x653): undefined reference to `sincos'
test.o: In function `main':
/home/anouar/workspace/Thread_example//test.c:27: undefined reference to `fftwf_init_threads'
/home/anouar/workspace/Thread_example//test.c:28: undefined reference to `fftwf_plan_with_nthreads'
/home/anouar/workspace/Thread_example//test.c:40: undefined reference to `fftwf_cleanup_threads'
 collect2: error: ld returned 1 exit status
 make: *** [test] Error 1

Is there something missing, or something wrong that I have did during installation and compilation?

Body:
Read the fine manual.  From the sincos() man page:

Link with -lm.

Using -lm in the compile phase of your program is useless:

.c.o:
     $(CC) $(CFLAGS) $< -lm -o $@

-lm needs to be in the link stage:

$(EXECUTABLE): $(OBJECTS)
     $(CC) $(OBJECTS) -o $@ -L -lfftw3f_threads -lfftw3f -lm


问:
Required Validation on bootstrap date-timepicker
I have developed  ASP.Net MVC 5  application. In that I am working on client side validation for bootstrap datetime-picker.

I am facing a problem with required validation. Validation is working fine on submit button  but when I , select datetime validation error message should be removed automatically and when I remove the datetime or clear textbox ,it should be display validation error message.

This is model

```<code>[Required(ErrorMessage = "Please select from date")]
public DateTime FromDate { get; set; }
</code>```

This is View

```<code><div class="input-append date form_datetime" id="datepickerConsFrom">
                @Html.TextBoxFor(m => m.FromDate, new { @readonly = "readonly", @class = "pull-left FromDate group", @placeholder = "From", ID = "startdtCons", Style = "width:49%" })
 <span class="add-on fromDate " id="spanFromDate" style="cursor: default"><i class="fa fa-calendar"></i></span>
 </div>
 @Html.ValidationMessageFor(m => m.FromDate, "", new { @class = "error" })
</code>```

Please suggest any  inputs on this..

Thanks

答:
When using clientside Validator with Bootstrap-datetimepicker, you should revalidate the datetime field.

Simply add below code in script

```<code>$("#startdtCons").on("change", function (evt, params) {
            $(evt.target).valid();
        });
</code>```

its works for me.

Body:
I have developed  ASP.Net MVC 5  application. In that I am working on client side validation for bootstrap datetime-picker.

I am facing a problem with required validation. Validation is working fine on submit button  but when I , select datetime validation error message should be removed automatically and when I remove the datetime or clear textbox ,it should be display validation error message.

This is model

[Required(ErrorMessage = "Please select from date")]
public DateTime FromDate { get; set; }

This is View

                @Html.TextBoxFor(m => m.FromDate, new { @readonly = "readonly", @class = "pull-left FromDate group", @placeholder = "From", ID = "startdtCons", Style = "width:49%" })

 @Html.ValidationMessageFor(m => m.FromDate, "", new { @class = "error" })

Please suggest any  inputs on this..

Thanks

Body:
When using clientside Validator with Bootstrap-datetimepicker, you should revalidate the datetime field.

Simply add below code in script

$("#startdtCons").on("change", function (evt, params) {
            $(evt.target).valid();
        });

its works for me.


问:
How to implement 3 stacks with one array?
Sometimes, I come across the following interview question: How to implement 3 stacks with one array ? Of course, any static allocation is not a solution.</p>

答:
For simplicity if not very efficient memory usage, you could[*] divide the array up into list nodes, add them all to a list of free nodes, and then implement your stacks as linked lists, taking nodes from the free list as required. There's nothing special about the number 3 in this approach, though.

[*] in a low-level language where memory can be used to store pointers, or if the stack elements are of a type such as int that can represent an index into the array.


问:
IOExpectation use
```<code>import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class OpenTest {

    public static void main(String args[]){

        int ln = 0;

        try {

            BufferedReader in = new BufferedReader (new
            FileReader("test.txt"));

                String line = null;

                while ((line = in.readLine()) != null) {

                ln ++;

                System.out.println("Line " + ln + " : " + line);
            }
        }catch (IOExpectation e){
         e.printStackTrace();

        }
    }
}
</code>```

Here is the error it's giving me:

```<code>--------------------Configuration: <Default>--------------------
C:\Users\Kirsty\Documents\Javadocs\Java Kirsty\Quiz Project\OpenTest.java:23: error: cannot find symbol
        }catch (IOExpectation e){
                ^
  symbol:   class IOExpectation
  location: class OpenTest
1 error
</code>```

How can I solve it?

答: Change the word IOExpectation for IOException because as @melpomene says, they are different words.

Title: IOExpectation use

Body:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class OpenTest {

    public static void main(String args[]){

        int ln = 0;

        try {

            BufferedReader in = new BufferedReader (new
            FileReader("test.txt"));

                String line = null;

                while ((line = in.readLine()) != null) {

                ln ++;

                System.out.println("Line " + ln + " : " + line);
            }
        }catch (IOExpectation e){
         e.printStackTrace();

        }
    }
}

Here is the error it's giving me:

--------------------Configuration: <Default>--------------------
C:\Users\Kirsty\Documents\Javadocs\Java Kirsty\Quiz Project\OpenTest.java:23: error: cannot find symbol
        }catch (IOExpectation e){
                ^
  symbol:   class IOExpectation
  location: class OpenTest
1 error

How can I solve it?


问:
In Django, How do you write the url pattern for '/' and other root-based urls
I'm new to django, and one of the things that I'm still learning is url_patterns. I set up a pages app to handle the root path (http://www.mysite.com) as well as some static pages such as the about page. I figured out how to set up the url pattern for the root path, but I can't get the site to direct the path '/about' to the pages "about" view.

Here is my main urls.py

```<code> from django.conf.urls import patterns, include, url
 from django.conf import settings
 urlpatterns = patterns('',
     url(r'^polls/', include('polls.urls')),
     url(r'^$', 'pages.views.root'),
     url(r'^/', include('pages.urls')),
  )
</code>```

here is my pages urls.py

```<code> from django.conf.urls import patterns, include, url
 urlpatterns = patterns('pages.views',
      url(r'^about', 'about'),
 )
</code>```

Here is my pages views.py

```<code> # Create your views here.
 from django.shortcuts import render_to_response
 from django.template import RequestContext
 from django.http import HttpResponse, HttpResponseRedirect
 from django.core.urlresolvers import reverse

 def root(request):
    return render_to_response('pages/root.html',context_instance=RequestContext(request))
 def about(request):
    return render_to_response('pages/about.html',context_instance=RequestContext(request))
</code>```

If I change the main urls.py file to have r'^a/', include('pages.urls') then the path '/a/about' directs to the about action.. so I think it has to be an issue in the way i'm writing the url pattern in this file. But, I can't figure out how to change it. Can anyone help?

答:
Note that from Django version 2.0 the URL pattern has changed to use  django.urls.path() Check Example here: link

```<code>from django.urls import path

from . import views

urlpatterns = [
    # ex: /polls/
    path('', views.index, name='index'),
    # ex: /polls/5/
    path('<int:question_id>/', views.detail, name='detail'),
    # ex: /polls/5/results/
    path('<int:question_id>/results/', views.results, name='results'),
    # ex: /polls/5/vote/
    path('<int:question_id>/vote/', views.vote, name='vote'),
]
</code>```

Body:
I'm new to django, and one of the things that I'm still learning is url_patterns. I set up a pages app to handle the root path (http://www.mysite.com) as well as some static pages such as the about page. I figured out how to set up the url pattern for the root path, but I can't get the site to direct the path '/about' to the pages "about" view.

Here is my main urls.py

 from django.conf.urls import patterns, include, url
 from django.conf import settings
 urlpatterns = patterns('',
     url(r'^polls/', include('polls.urls')),
     url(r'^$', 'pages.views.root'),
     url(r'^/', include('pages.urls')),
  )

here is my pages urls.py

 from django.conf.urls import patterns, include, url
 urlpatterns = patterns('pages.views',
      url(r'^about', 'about'),
 )

Here is my pages views.py

 # Create your views here.
 from django.shortcuts import render_to_response
 from django.template import RequestContext
 from django.http import HttpResponse, HttpResponseRedirect
 from django.core.urlresolvers import reverse

 def root(request):
    return render_to_response('pages/root.html',context_instance=RequestContext(request))
 def about(request):
    return render_to_response('pages/about.html',context_instance=RequestContext(request))

If I change the main urls.py file to have r'^a/', include('pages.urls') then the path '/a/about' directs to the about action.. so I think it has to be an issue in the way i'm writing the url pattern in this file. But, I can't figure out how to change it. Can anyone help?

Body:
Note that from Django version 2.0 the URL pattern has changed to use  django.urls.path() Check Example here: link

from django.urls import path

from . import views

urlpatterns = [
    # ex: /polls/
    path('', views.index, name='index'),
    # ex: /polls/5/
    path('<int:question_id>/', views.detail, name='detail'),
    # ex: /polls/5/results/
    path('<int:question_id>/results/', views.results, name='results'),
    # ex: /polls/5/vote/
    path('<int:question_id>/vote/', views.vote, name='vote'),
]


问:
RestAssured - JsonPath filter a matching Object's properties from an array of objects, given a filter criteria
I am writing an integration test to my microservice using rest assured. I have a Json payload like this which is returned from it.

```<code>{
   "sessionQuestions":[
      {
         "id":1272,
         "sessionId":1146,
         "questionId":"1002",
      },
      {
         "id":1273,
         "sessionId":1146,
         "questionId":"1004",
      }
   ]
}
</code>```

I need to find the id of a sessionquestion given the questionId value. Then I need to compare them in my assertion. I am having hard time fetching the id off of a sessionQuestion given the questionId value. I am using JsonPath to get this thing done. And here's my Json path expression.

```<code>new JsonPath(response).get("$.sessionQuestions[?(@.questionId=='1002')].id");
</code>```

This throws an error.

```<code>java.lang.IllegalArgumentException: Invalid JSON expression:
Script1.groovy: 1: expecting EOF, found '[' @ line 1, column 45.
   nRootObject.$.sessionQuestions[?(@.quest
                                 ^

1 error

   at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
</code>```

I tried the same Json path expression in this online evaluator, which works fine. I am using json-path-2.9.0.jar

What I am doing wrong here? Any help is really appreciated.

答:
Which version of JsonPath do you use? I use this.

And the code which works for your case is:

```<code>JsonPath.parse(response).read("$.sessionQuestions[?(@.questionId=='1002')].id").toString();
</code>```

And try with this JSON:

```<code>{
   "sessionQuestions":[
      {
         "id":1272,
         "sessionId":1146,
         "questionId":"1002"
      },
      {
         "id":1273,
         "sessionId":1146,
         "questionId":"1004"
      }
   ]
}
</code>```

Edit: If you are using this dependancy (json-path-2.9.0), you have to do it like this:

```<code>from(response).getList("sessionQuestions.findAll { it.questionId=='1002' }.id").toString();
</code>```

and you have to import from like this:

```<code>import static com.jayway.restassured.path.json.JsonPath.from;
</code>```

Body:
I am writing an integration test to my microservice using rest assured. I have a Json payload like this which is returned from it.

{
   "sessionQuestions":[
      {
         "id":1272,
         "sessionId":1146,
         "questionId":"1002",
      },
      {
         "id":1273,
         "sessionId":1146,
         "questionId":"1004",
      }
   ]
}

I need to find the id of a sessionquestion given the questionId value. Then I need to compare them in my assertion. I am having hard time fetching the id off of a sessionQuestion given the questionId value. I am using JsonPath to get this thing done. And here's my Json path expression.

new JsonPath(response).get("$.sessionQuestions[?(@.questionId=='1002')].id");

This throws an error.

java.lang.IllegalArgumentException: Invalid JSON expression:
Script1.groovy: 1: expecting EOF, found '[' @ line 1, column 45.
   nRootObject.$.sessionQuestions[?(@.quest
                                 ^

1 error

   at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)

I tried the same Json path expression in this online evaluator, which works fine. I am using json-path-2.9.0.jar

What I am doing wrong here? Any help is really appreciated.

Body:
Which version of JsonPath do you use? I use this.

And the code which works for your case is:

JsonPath.parse(response).read("$.sessionQuestions[?(@.questionId=='1002')].id").toString();

And try with this JSON:

{
   "sessionQuestions":[
      {
         "id":1272,
         "sessionId":1146,
         "questionId":"1002"
      },
      {
         "id":1273,
         "sessionId":1146,
         "questionId":"1004"
      }
   ]
}

Edit: If you are using this dependancy (json-path-2.9.0), you have to do it like this:

from(response).getList("sessionQuestions.findAll { it.questionId=='1002' }.id").toString();

and you have to import from like this:

import static com.jayway.restassured.path.json.JsonPath.from;


问:
Get all wp_users sort by metakey
I am trying to get users list sort by metakey. I mean i have set meta key user_last_login. some users doesnot have this meta key. some users have it.

I want to get both users in single query but if metakey exists those will come first and remaining should come last.

Here is my query

```<code>$meta_query_args = array(
            'relation' => 'OR', // Optional, defaults to "AND"
            array(
            'key'     => 'user_last_login',
            'compare' => 'Not Exists'
            ),
            array(
            'key'     => 'user_last_login',
            'compare' => 'Exists'
            )
        );
        $meta_query = new WP_Meta_Query( $meta_query_args );

            $args = array(
                'offset' => $paged ? ($paged - 1) * $number : 0,
                'number' => $number,
                'fields' => 'all',
                'orderby'=>'user_last_login',
                'exclude' => array(get_current_user_id()),

                'meta_query'  =>$meta_query
            );

            $users = get_users( $args );
</code>```

Please help.

答:
A meta_key argument is required when you wan to order by meta_value. Here is the modified code,

```<code>$query_args = array(
    'relation' => 'OR',
    array(
        'key'     => 'user_last_login',
        'compare' => 'NOT EXISTS'
    ),
    array(
        'key'     => 'user_last_login',
        'compare' => 'EXISTS'
    )
);

$meta_query = new WP_Meta_Query($query_args);

$args = array(
    'offset' => $paged ? ($paged - 1) * $number : 0,
    'number' => $number,
    'fields' => 'all',
    'meta_key' => 'user_last_login',
    'orderby' => 'meta_value',
    'order' => 'ASC',
    'exclude' => array(get_current_user_id()),
    'meta_query' => $meta_query
);

$users = get_users( $args );
</code>```

Hope this one helps.

Title: Get all wp_users sort by metakey

Body:
I am trying to get users list sort by metakey. I mean i have set meta key user_last_login. some users doesnot have this meta key. some users have it.

I want to get both users in single query but if metakey exists those will come first and remaining should come last.

Here is my query

$meta_query_args = array(
            'relation' => 'OR', // Optional, defaults to "AND"
            array(
            'key'     => 'user_last_login',
            'compare' => 'Not Exists'
            ),
            array(
            'key'     => 'user_last_login',
            'compare' => 'Exists'
            )
        );
        $meta_query = new WP_Meta_Query( $meta_query_args );

            $args = array(
                'offset' => $paged ? ($paged - 1) * $number : 0,
                'number' => $number,
                'fields' => 'all',
                'orderby'=>'user_last_login',
                'exclude' => array(get_current_user_id()),

                'meta_query'  =>$meta_query
            );

            $users = get_users( $args );

Please help.

Body:
A meta_key argument is required when you wan to order by meta_value. Here is the modified code,

$query_args = array(
    'relation' => 'OR',
    array(
        'key'     => 'user_last_login',
        'compare' => 'NOT EXISTS'
    ),
    array(
        'key'     => 'user_last_login',
        'compare' => 'EXISTS'
    )
);

$meta_query = new WP_Meta_Query($query_args);

$args = array(
    'offset' => $paged ? ($paged - 1) * $number : 0,
    'number' => $number,
    'fields' => 'all',
    'meta_key' => 'user_last_login',
    'orderby' => 'meta_value',
    'order' => 'ASC',
    'exclude' => array(get_current_user_id()),
    'meta_query' => $meta_query
);

$users = get_users( $args );

Hope this one helps.


问:
I think stopPropagation() is breaking my mouse events - how can I fix?
I am trying to detect clicks anywhere on the document only after my start session button has been clicked. The start session button adds a .waiting class to the body.

I have used stopPropagation(), but I think this is breaking some mouseover/mouseout functionality that adds a hover state class to child elements.

The issue is that once the both the session button and document has been clicked, mouseover/mouseout functionality still happens despite removal of the .waiting class.

What is the solution to fix my code please? Or, is stopPropagation() a bad idea for my use case given this article.

There is a snippet below - just click the button, hover over the squares and then click. The problem is the squares still have red outline on hover.

$("#start-session").on("click", function(e) {
  $("body").addClass("waiting");

  $("body.waiting").children().mouseover(function(e) {
    e.stopPropagation();

    $(".el-hover").removeClass("el-hover");
    $(e.target).addClass("el-hover");
  }).mouseout(function(e) {
    $(e.target).removeClass("el-hover");
  });

  e.stopPropagation();
})

$(document).on("click", function(e) {

  if ($("body").hasClass("waiting")) {

    e.preventDefault()

    alert("Document was clicked");
    $("body").removeClass("waiting")
  }
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#container {
  width: 200px;
  background: stealblue;
  display: flex;
  flex-wrap: nowrap;
  justify-content: space-evenly;
  margin: 50px;
}

.zone {
  background: #eee;
  border: 1px solid #ccc;
  padding: 15px;
}

.el-hover {
  outline: 1px solid red;
}</code>```

<button id="start-session">Start session</button>

```

答:
Solution

To quote @CBroe from the comments:

$("body.waiting").children().mouseover(...) applies the handler to all elements found at the time - the handler does not magically get removed, once body loses that class again. You’re trying to work against that by stopping propagation, but I think you’d be better off applying the handler only if that class is currently present to begin with. Using event delegation you could achieve that kind of “dynamism” - but for that you would have to go one level up here, so that you can use body in the selector - something like $(document).on('mouseover', 'body.waiting *', function(...) {})

Updated snippet

$("#start-session").on("click", function(e) {
  $("body").addClass("waiting");

  $(document).on({
    mouseenter: function() {
      $(this).css({
        "outline": "1px solid red"
      })
    },
    mouseleave: function() {
      $(this).css({
        "outline": "0"
      })
    }
  }, 'body.waiting *');

  e.stopPropagation();
})

$(document).on("click", function(e) {

  if ($("body").hasClass("waiting")) {

    e.preventDefault()

    alert("Document was clicked");
    $("body").removeClass("waiting")
  }
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#container {
  width: 200px;
  background: stealblue;
  display: flex;
  flex-wrap: nowrap;
  justify-content: space-evenly;
  margin: 50px;
}

.zone {
  background: #eee;
  border: 1px solid #ccc;
  padding: 15px;
}

.el-hover {
  outline: 1px solid red;
}</code>```

<button id="start-session">Start session</button>

```

Body:
I am trying to detect clicks anywhere on the document only after my start session button has been clicked. The start session button adds a .waiting class to the body.

I have used stopPropagation(), but I think this is breaking some mouseover/mouseout functionality that adds a hover state class to child elements.

The issue is that once the both the session button and document has been clicked, mouseover/mouseout functionality still happens despite removal of the .waiting class.

What is the solution to fix my code please? Or, is stopPropagation() a bad idea for my use case given this article.

There is a snippet below - just click the button, hover over the squares and then click. The problem is the squares still have red outline on hover.

$("#start-session").on("click", function(e) {
  $("body").addClass("waiting");

  $("body.waiting").children().mouseover(function(e) {
    e.stopPropagation();

    $(".el-hover").removeClass("el-hover");
    $(e.target).addClass("el-hover");
  }).mouseout(function(e) {
    $(e.target).removeClass("el-hover");
  });

  e.stopPropagation();
})

$(document).on("click", function(e) {

  if ($("body").hasClass("waiting")) {

    e.preventDefault()

    alert("Document was clicked");
    $("body").removeClass("waiting")
  }
})

#container {
  width: 200px;
  background: stealblue;
  display: flex;
  flex-wrap: nowrap;
  justify-content: space-evenly;
  margin: 50px;
}

.zone {
  background: #eee;
  border: 1px solid #ccc;
  padding: 15px;
}

.el-hover {
  outline: 1px solid red;
}

<button id="start-session">Start session</button>

Body:
Solution

To quote @CBroe from the comments:

$("body.waiting").children().mouseover(...) applies the handler to all elements found at the time - the handler does not magically get removed, once body loses that class again. You’re trying to work against that by stopping propagation, but I think you’d be better off applying the handler only if that class is currently present to begin with. Using event delegation you could achieve that kind of “dynamism” - but for that you would have to go one level up here, so that you can use body in the selector - something like $(document).on('mouseover', 'body.waiting *', function(...) {})

Updated snippet

$("#start-session").on("click", function(e) {
  $("body").addClass("waiting");

  $(document).on({
    mouseenter: function() {
      $(this).css({
        "outline": "1px solid red"
      })
    },
    mouseleave: function() {
      $(this).css({
        "outline": "0"
      })
    }
  }, 'body.waiting *');

  e.stopPropagation();
})

$(document).on("click", function(e) {

  if ($("body").hasClass("waiting")) {

    e.preventDefault()

    alert("Document was clicked");
    $("body").removeClass("waiting")
  }
})

#container {
  width: 200px;
  background: stealblue;
  display: flex;
  flex-wrap: nowrap;
  justify-content: space-evenly;
  margin: 50px;
}

.zone {
  background: #eee;
  border: 1px solid #ccc;
  padding: 15px;
}

.el-hover {
  outline: 1px solid red;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button id="start-session">Start session</button>

<div id="container">
  <div class="zone"></div>
  <div class="zone"></div>
  <div class="zone"></div>
</div>


问:
What is the right way to ensure the correct version of a gem is required using bundler?
If I understand correctly puting

```<code>require 'rubygems'
require 'bundler/setup'
</code>```

at the top of my ruby source file will ensure that subsequent requires will load the versions of the gems specified in the Gemfile located in the same directory, thus allowing me to develop multiple projects which use different versions of the same gem - is this correct? How is this different from using Bundler.setup()?

答:
When you require 'bundler/setup' it loads this file which calls Bundler.setup for you. This means there's no need for you to include that in your own code.

RubyGems is loaded implicitly by Ruby, unless you're using a really old version, so require 'rubygems' isn't needed.

Body:
If I understand correctly puting

require 'rubygems'
require 'bundler/setup'

at the top of my ruby source file will ensure that subsequent requires will load the versions of the gems specified in the Gemfile located in the same directory, thus allowing me to develop multiple projects which use different versions of the same gem - is this correct? How is this different from using Bundler.setup()?


问:
Efficient implementation of a Z-Buffer
I am currently implementing my own renderer using the Z-Buffer algorithm. Once I have done the necessary calculations (read: My Z-Buffer is filled with the correct values) I use SDL to colour in the necessary pixels. I'm using an HWSurface for this.

My question is, how can I render this as fast as possible? With this I mean the drawing itself, I can do optimisations in my structure, my algorithm, I will do that later on, but I want to be sure that the drawing itself is as fast as possible.

Because I have my own implementation of a ZBuffer (and there will be other algorithms later on) I can not use OpenGL, so are there any alternatives?

Now I'm just going over all my points in the z-buffer and I draw all the pixels that have to be drawn, one by one (and because it's z-buffering I have to do this, right?) and I call a DrawPixel method. Concerning SDL I lock my surface before going over the z-buffer, draw all the pixels and unlock it afterwards, this can't go faster as far as I know.

Any suggestions?

答:
Software implementations are incredibly slow- that is, WARP renders Crysis on an i7 hexacore at a tenth the FPS that an 8800GT does. You won't find any competitive performance in a software-implemented Z-buffer.

A Z-buffer is not a particularly complex algorithm and it's pretty unlikely that you'll find one implementation that's more efficient than another. Z-buffering isn't something you do during rasterization- it's something that you do during pixel rendering. If the depth of the new pixel is further away than the currently written value, don't render the pixel any further, e.g., don't compute it's colour etc. You don't draw the z-buffer or anything like that. It's not like a sort where you might pick the most efficient sort for your algorithm- it's more like a matrix multiplication, they're pretty much all the same.

Title: Efficient implementation of a Z-Buffer


问:
ReactBootstrap popover dismiss on click outside
ReactBootstrap provides a popover control. I would like this to be dismissed on clicking outside the popover in a similar way to how modals work (it just dismisses by default clicking out of the box).

Is there a way to do this using ReactBootstrap or do I need to custom code something?

JSfiddle of a popover: http://jsfiddle.net/226cwe4e/

```<code>React.createClass({
    render: function() {
        return <ReactBootstrap.OverlayTrigger trigger="click" placement="bottom" overlay={<ReactBootstrap.Popover title="Popover bottom"><strong>Holy guacamole!</strong> Check this info.</ReactBootstrap.Popover>}>
        <ReactBootstrap.Button bsStyle="default">Holy guacamole!</ReactBootstrap.Button>
      </ReactBootstrap.OverlayTrigger>;
    }
});
</code>```

答:
No you don't need any custom code. Just include rootClose prop and this will do for you. Its in the react bootstrap official documentation https://react-bootstrap.netlify.com/components/overlays/#overlays-api

```<code><OverlayTrigger trigger='click' rootClose>
  ....
</OverlayTrigger>
</code>```

Body:
ReactBootstrap provides a popover control. I would like this to be dismissed on clicking outside the popover in a similar way to how modals work (it just dismisses by default clicking out of the box).

Is there a way to do this using ReactBootstrap or do I need to custom code something?

JSfiddle of a popover: http://jsfiddle.net/226cwe4e/

React.createClass({
    render: function() {
        return <ReactBootstrap.OverlayTrigger trigger="click" placement="bottom" overlay={<ReactBootstrap.Popover title="Popover bottom">Holy guacamole! Check this info.</ReactBootstrap.Popover>}>
        <ReactBootstrap.Button bsStyle="default">Holy guacamole!</ReactBootstrap.Button>
      </ReactBootstrap.OverlayTrigger>;
    }
});

Body:
No you don't need any custom code. Just include rootClose prop and this will do for you. Its in the react bootstrap official documentation https://react-bootstrap.netlify.com/components/overlays/#overlays-api

<OverlayTrigger trigger='click' rootClose>
  ....
</OverlayTrigger>


问:
iOS 11 SearchDisplayController shows black status bar
I know SearchDisplayController is deprecated, but Storyboard still supports it, and it is an easy way to present tableViewController on top of your view controller. I have been using it, and I would still prefer to use that. And in iOS 11, when I run my app, the status bar of the SearchDisplayController. after the search bar is focused, is pitch BLACK. Does anyone know how to solve this bug? Also if you realize, the margins of the searcher is off. I am using the default iOS 11 searchbar. Below is attached screenshot:

答:
Have you tried to set the extendedLayoutIncludesOpaqueBars property to true?</p>

```<code>searchDisplayController.extendedLayoutIncludesOpaqueBars = true
</code>```

Body:
Have you tried to set the extendedLayoutIncludesOpaqueBars property to true?

searchDisplayController.extendedLayoutIncludesOpaqueBars = true


问:
Validate types in PactNet
I am testing micro services and I'm using PactNet to create and validate pacts. I am finding that the tests are too brittle, as the verifier is checking for exact values and not verifying the types.

For example, I am testing against the GitHub API and the test works. If a new Repo is added, the public_repos value increases by one and the test fails.

Is anyone using this to check the types instead of the concrete values?

Here is the verification code:

```<code>[Test]
public void VerifyPact()
{

    // Arrange.
    var pactVerifier = new PactVerifier(() => { }, () => { });
    pactVerifier.ProviderState("There is call with the name 'karlgjertsen'");

    // Act.
    using (var client = new HttpClient { BaseAddress = new Uri("https://api.github.com/users/karlgjertsen") })
    {

        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident / 6.0)");

        // Assert.
        pactVerifier
            .ServiceProvider("GitHub API", client)
            .HonoursPactWith("Pact Test")
            .PactUri(@"C:\Pact\pacts\pact_test-git_api.json")
            .Verify();

    }

}
</code>```

And here's the PACT file.

```<code>{
  "provider": {
    "name": "GitHub API"
  },
  "consumer": {
    "name": "PACT Test"
  },
  "interactions": [
    {
      "description": "A GET request for user deatils for 'karlgjertsen'",
      "provider_state": "There is call with the name 'karlgjertsen'",
      "request": {
        "method": "get",
        "path": "/users/karlgjertsen",
        "headers": {
          "Accept": "application/json"
        }
      },
      "response": {
        "status": 200,
        "headers": {
          "Content-Type": "application/json; charset=utf-8"
        },
        "body": {
          "login": "karlgjertsen",
          "id": 4457667,
          "avatar_url": "https://avatars.githubusercontent.com/u/4457667?v=3",
          "gravatar_id": "",
          "url": "https://api.github.com/users/karlgjertsen",
          "html_url": "https://github.com/karlgjertsen",
          "followers_url": "https://api.github.com/users/karlgjertsen/followers",
          "following_url": "https://api.github.com/users/karlgjertsen/following{/other_user}",
          "gists_url": "https://api.github.com/users/karlgjertsen/gists{/gist_id}",
          "starred_url": "https://api.github.com/users/karlgjertsen/starred{/owner}{/repo}",
          "subscriptions_url": "https://api.github.com/users/karlgjertsen/subscriptions",
          "organizations_url": "https://api.github.com/users/karlgjertsen/orgs",
          "repos_url": "https://api.github.com/users/karlgjertsen/repos",
          "events_url": "https://api.github.com/users/karlgjertsen/events{/privacy}",
          "received_events_url": "https://api.github.com/users/karlgjertsen/received_events",
          "type": "User",
          "site_admin": false,
          "name": "Karl Gjertsen",
          "company": "infiniforms.io",
          "blog": "http://www.karlgjertsen.com",
          "location": "UK",
          "email": null,
          "hireable": null,
          "bio": null,
          "public_repos": 1,
          "public_gists": 0,
          "followers": 0,
          "following": 0,
          "created_at": "2013-05-17T14:05:30Z",
          "updated_at": "2016-03-07T19:39:58Z"
        }
      }
    }
  ],
  "metadata": {
    "pactSpecificationVersion": "1.1.0"
  }
}
</code>```

答:
PactNet v2 already supports type and regex matching:

Type matching for whole body:

```<code>// IMockProviderService
.WillRespondWith(new ProviderServiceResponse
{
    Body = Match.Type(new { Id = 123, FirstName = "John" })
});
</code>```

or for a property:

```<code>.WillRespondWith(new ProviderServiceResponse
{
    Body = new { Id = 123, FirstName = Match.Type("John") }
});
</code>```

Regex matching:

```<code>.WillRespondWith(new ProviderServiceResponse
{
    Body = new { FirstName = Match.Regex("Jan", @"\A\w+\z") }
});
</code>```

There's also Match.MinType for arrays.

Title: Validate types in PactNet

Body:
I am testing micro services and I'm using PactNet to create and validate pacts. I am finding that the tests are too brittle, as the verifier is checking for exact values and not verifying the types.

For example, I am testing against the GitHub API and the test works. If a new Repo is added, the public_repos value increases by one and the test fails.

Is anyone using this to check the types instead of the concrete values?

Here is the verification code:

[Test]
public void VerifyPact()
{

    // Arrange.
    var pactVerifier = new PactVerifier(() => { }, () => { });
    pactVerifier.ProviderState("There is call with the name 'karlgjertsen'");

    // Act.
    using (var client = new HttpClient { BaseAddress = new Uri("https://api.github.com/users/karlgjertsen") })
    {

        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident / 6.0)");

        // Assert.
        pactVerifier
            .ServiceProvider("GitHub API", client)
            .HonoursPactWith("Pact Test")
            .PactUri(@"C:\Pact\pacts\pact_test-git_api.json")
            .Verify();

    }

}

And here's the PACT file.

{
  "provider": {
    "name": "GitHub API"
  },
  "consumer": {
    "name": "PACT Test"
  },
  "interactions": [
    {
      "description": "A GET request for user deatils for 'karlgjertsen'",
      "provider_state": "There is call with the name 'karlgjertsen'",
      "request": {
        "method": "get",
        "path": "/users/karlgjertsen",
        "headers": {
          "Accept": "application/json"
        }
      },
      "response": {
        "status": 200,
        "headers": {
          "Content-Type": "application/json; charset=utf-8"
        },
        "body": {
          "login": "karlgjertsen",
          "id": 4457667,
          "avatar_url": "https://avatars.githubusercontent.com/u/4457667?v=3",
          "gravatar_id": "",
          "url": "https://api.github.com/users/karlgjertsen",
          "html_url": "https://github.com/karlgjertsen",
          "followers_url": "https://api.github.com/users/karlgjertsen/followers",
          "following_url": "https://api.github.com/users/karlgjertsen/following{/other_user}",
          "gists_url": "https://api.github.com/users/karlgjertsen/gists{/gist_id}",
          "starred_url": "https://api.github.com/users/karlgjertsen/starred{/owner}{/repo}",
          "subscriptions_url": "https://api.github.com/users/karlgjertsen/subscriptions",
          "organizations_url": "https://api.github.com/users/karlgjertsen/orgs",
          "repos_url": "https://api.github.com/users/karlgjertsen/repos",
          "events_url": "https://api.github.com/users/karlgjertsen/events{/privacy}",
          "received_events_url": "https://api.github.com/users/karlgjertsen/received_events",
          "type": "User",
          "site_admin": false,
          "name": "Karl Gjertsen",
          "company": "infiniforms.io",
          "blog": "http://www.karlgjertsen.com",
          "location": "UK",
          "email": null,
          "hireable": null,
          "bio": null,
          "public_repos": 1,
          "public_gists": 0,
          "followers": 0,
          "following": 0,
          "created_at": "2013-05-17T14:05:30Z",
          "updated_at": "2016-03-07T19:39:58Z"
        }
      }
    }
  ],
  "metadata": {
    "pactSpecificationVersion": "1.1.0"
  }
}

Body:
PactNet v2 already supports type and regex matching:

Type matching for whole body:

// IMockProviderService
.WillRespondWith(new ProviderServiceResponse
{
    Body = Match.Type(new { Id = 123, FirstName = "John" })
});

or for a property:

.WillRespondWith(new ProviderServiceResponse
{
    Body = new { Id = 123, FirstName = Match.Type("John") }
});

Regex matching:

.WillRespondWith(new ProviderServiceResponse
{
    Body = new { FirstName = Match.Regex("Jan", @"\A\w+\z") }
});

There's also Match.MinType for arrays.


问:
Hadoop 2.6.1 Warning: WARN util.NativeCodeLoader
I'm running hadoop 2.6.1 on OS X 10.10.5.
I'm getting this warning:

WARN util.NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable

I've read that this problem can be caused by running a 32bit native library libhadoop.so.1.0.0 with a 64 bit version of hadoop.  I've checked my version of libhadoop.so.1.0.0 and it is 64 bit.

```<code>$ find ~/hadoop-2.6.1/ -name libhadoop.so.1.0.0 -ls
136889669     1576 -rwxr-xr-x    1 davidlaxer       staff              806303 Sep 16 14:18 /Users/davidlaxer/hadoop-2.6.1//lib/native/libhadoop.so.1.0.0

$ file /Users/davidlaxer/hadoop-2.6.1//lib/native/libhadoop.so.1.0.0
    /Users/davidlaxer/hadoop-2.6.1//lib/native/libhadoop.so.1.0.0: ELF 64-bit LSB shared object, x86-64, version 1 (SYSV), dynamically linked, not stripped

$ env | grep HADOOP
HADOOP_HOME=/Users/davidlaxer/hadoop-2.6.1
HADOOP_COMMON_LIB_NATIVE_DIR=/Users/davidlaxer/hadoop-2.6.1/lib/native
HADOOP_INSTALL=/Users/davidlaxer/hadoop-2.6.1
HADOOP_CONF_DIR=/Users/davidlaxer/hadoop-2.6.1/etc/hadoop
HADOOP_OPTS=-Djava.library.path=/Users/davidlaxer/hadoop-2.6.1/lib

$ hadoop version
Hadoop 2.6.1
Subversion https://git-wip-us.apache.org/repos/asf/hadoop.git -r b4d876d837b830405ccdb6af94742f99d49f9c04
Compiled by jenkins on 2015-09-16T21:07Z
Compiled with protoc 2.5.0
From source with checksum ba9a9397365e3ec2f1b3691b52627f
This command was run using /Users/davidlaxer/hadoop-2.6.1/share/hadoop/common/hadoop-common-2.6.1.jar

$ java -version
java version "1.8.0_05"
Java(TM) SE Runtime Environment (build 1.8.0_05-b13)
Java HotSpot(TM) 64-Bit Server VM (build 25.5-b02, mixed mode)

$ hadoop checknative -a
15/09/26 11:01:28 WARN util.NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
Native library checking:
hadoop:  false
zlib:    false
snappy:  false
lz4:     false
bzip2:   false
openssl: false
15/09/26 11:01:29 INFO util.ExitUtil: Exiting with status 1

$ sudo port list zlib
Password:
zlib                           @1.2.8          archivers/zlib
$ sudo port list snappy
snappy                         @1.1.1          archivers/snappy
$ sudo port list lz4
lz4                            @r130           archivers/lz4
$ sudo port list bzip2
bzip2                          @1.0.6          archivers/bzip2
$ sudo port list openssl
openssl                        @1.0.2d         devel/openssl

$env | grep CLASS

CLASSPATH=/users/davidlaxer/trunk/core/src/test/java/:/Users/davidlaxer/hadoop-2.6.1-src/hadoop-dist/target/hadoop-dist-2.6.1.jar:/Users/davidlaxer/clojure/target:/Users/davidlaxer/hadoop-2.6.1/lib/native:
</code>```

˚Any ideas?

答:
I had same problem. Fortunately the problem has been solved.
You can see the solution below.

A few times displaying the warning does not let you upload a file to HDFS.
So when there is no warning, there is no such problem.

Open  the hadoop-env.sh  and  go to the end of the file and try to add the following lines

```<code>export HADOOP_HOME_WARN_SUPPRESS=1
export HADOOP_ROOT_LOGGER="WARN,DRFA"
</code>```

Body:
I'm running hadoop 2.6.1 on OS X 10.10.5.
I'm getting this warning:

WARN util.NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable

I've read that this problem can be caused by running a 32bit native library libhadoop.so.1.0.0 with a 64 bit version of hadoop.  I've checked my version of libhadoop.so.1.0.0 and it is 64 bit.

$ find ~/hadoop-2.6.1/ -name libhadoop.so.1.0.0 -ls
136889669     1576 -rwxr-xr-x    1 davidlaxer       staff              806303 Sep 16 14:18 /Users/davidlaxer/hadoop-2.6.1//lib/native/libhadoop.so.1.0.0

$ file /Users/davidlaxer/hadoop-2.6.1//lib/native/libhadoop.so.1.0.0
    /Users/davidlaxer/hadoop-2.6.1//lib/native/libhadoop.so.1.0.0: ELF 64-bit LSB shared object, x86-64, version 1 (SYSV), dynamically linked, not stripped

$ env | grep HADOOP
HADOOP_HOME=/Users/davidlaxer/hadoop-2.6.1
HADOOP_COMMON_LIB_NATIVE_DIR=/Users/davidlaxer/hadoop-2.6.1/lib/native
HADOOP_INSTALL=/Users/davidlaxer/hadoop-2.6.1
HADOOP_CONF_DIR=/Users/davidlaxer/hadoop-2.6.1/etc/hadoop
HADOOP_OPTS=-Djava.library.path=/Users/davidlaxer/hadoop-2.6.1/lib

$ hadoop version
Hadoop 2.6.1
Subversion https://git-wip-us.apache.org/repos/asf/hadoop.git -r b4d876d837b830405ccdb6af94742f99d49f9c04
Compiled by jenkins on 2015-09-16T21:07Z
Compiled with protoc 2.5.0
From source with checksum ba9a9397365e3ec2f1b3691b52627f
This command was run using /Users/davidlaxer/hadoop-2.6.1/share/hadoop/common/hadoop-common-2.6.1.jar

$ java -version
java version "1.8.0_05"
Java(TM) SE Runtime Environment (build 1.8.0_05-b13)
Java HotSpot(TM) 64-Bit Server VM (build 25.5-b02, mixed mode)

$ hadoop checknative -a
15/09/26 11:01:28 WARN util.NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
Native library checking:
hadoop:  false
zlib:    false
snappy:  false
lz4:     false
bzip2:   false
openssl: false
15/09/26 11:01:29 INFO util.ExitUtil: Exiting with status 1

$ sudo port list zlib
Password:
zlib                           @1.2.8          archivers/zlib
$ sudo port list snappy
snappy                         @1.1.1          archivers/snappy
$ sudo port list lz4
lz4                            @r130           archivers/lz4
$ sudo port list bzip2
bzip2                          @1.0.6          archivers/bzip2
$ sudo port list openssl
openssl                        @1.0.2d         devel/openssl

$env | grep CLASS

CLASSPATH=/users/davidlaxer/trunk/core/src/test/java/:/Users/davidlaxer/hadoop-2.6.1-src/hadoop-dist/target/hadoop-dist-2.6.1.jar:/Users/davidlaxer/clojure/target:/Users/davidlaxer/hadoop-2.6.1/lib/native:

˚Any ideas?

Body:
I had same problem. Fortunately the problem has been solved.
You can see the solution below.

A few times displaying the warning does not let you upload a file to HDFS.
So when there is no warning, there is no such problem.

Open  the hadoop-env.sh  and  go to the end of the file and try to add the following lines

export HADOOP_HOME_WARN_SUPPRESS=1
export HADOOP_ROOT_LOGGER="WARN,DRFA"


问:
Why can't my Java/SalesForce app create JAXBContext due to a security restriction?
I was on one Java/Salesforce tutorial but I couldn't get it to work as is because SoapBindingStub seems to be obsolete code based upon depreciated libraries.  So I tried to mesh the code with code from JAX-WS Quick Start, but this didn't quite work either.  No matter what I did, ultimately the sample console application would suffer exceptions, complaining "Web Service Exception creating salesface port.: Unable to create JAXBContext due to the security restriction on class javax.xml.ws.WebServiceException".

I gave up (for the moment) trying to mash the two codes, and instead am now just working on abstracting the JAX-WS Quickstart.java so I can understand wow it works and reuse its methods in other applications.

No matter how I slice and dice the code, it always gets stuck at the same location with essentially that same error.

Here is the current code for method which is persistantly failing:

```<code>private void initPort()
{
    try
    {
        URL wsdlLocation = this.getClass().getClassLoader().getResource("META-INF/enterprise.wsdl");
        if (wsdlLocation == null)
        {
            WebServiceException webServiceException = new WebServiceException("enterprise.wsdl not found!");
            ExceptionToolkit.display("Web Service Exception can't find enterprise.wsdl", webServiceException);
            throw webServiceException;
        }
        else {System.out.println("\nFOUND enterprise.wsdl!!!\n\n");}

        QName qName = new QName("urn:enterprise.soap.sforce.com", "SforceService");
        SforceService sforceService = new SforceService( wsdlLocation, qName );
        System.out.println("\nsforceService INITIALIZED. About to get Soap.\n\n");
        Soap soap = (sforceService).getSoap();
        System.out.println("\nWe have soap.\n\n");
        setPort (soap);
    }
    catch (WebServiceException webServiceException)
    {
        ExceptionToolkit.display("Web Service Exception creating salesface port", webServiceException);
        return;
    }
}
</code>```

Here is the error, including output immediately before and after:

```<code>Running main loop

FOUND enterprise.wsdl!!!

sforceService INITIALIZED. About to get Soap.

Web Service Exception creating salesface port: Unable to create JAXBContext due to the security restriction
on class javax.xml.ws.WebServiceException
javax.xml.ws.WebServiceException: Unable to create JAXBContext due to the security restriction
    at com.sun.xml.ws.model.AbstractSEIModelImpl.createJAXBContext(AbstractSEIModelImpl.java:131)
    at com.sun.xml.ws.model.AbstractSEIModelImpl.postProcess(AbstractSEIModelImpl.java:63)
    at com.sun.xml.ws.model.RuntimeModeler.buildRuntimeModel(RuntimeModeler.java:224)
    at com.sun.xml.ws.client.WSServiceDelegate.addSEI(WSServiceDelegate.java:588)
    at com.sun.xml.ws.client.WSServiceDelegate.getPort(WSServiceDelegate.java:291)
    at com.sun.xml.ws.client.WSServiceDelegate.getPort(WSServiceDelegate.java:274)
    at com.sun.xml.ws.client.WSServiceDelegate.getPort(WSServiceDelegate.java:267)
    at javax.xml.ws.Service.getPort(Unknown Source)
    at com.sforce.soap.enterprise.SforceService.getSoap(SforceService.java:53)
    at hu.flux.salesforce.LoginToolkit.initPort(LoginToolkit.java:78)
    at hu.flux.salesforce.LoginToolkit.doLogin(LoginToolkit.java:122)
    at hu.flux.salesforce.LoginToolkit.<init>(LoginToolkit.java:49)
    at hu.flux.salesforce.samples.Quickstart.mainLoop(Quickstart.java:55)
    at hu.flux.salesforce.samples.Quickstart.<init>(Quickstart.java:28)
    at hu.flux.salesforce.samples.Quickstart.main(Quickstart.java:21)
Caused by: java.security.PrivilegedActionException: com.sun.xml.bind.v2.runtime.IllegalAnnotationsException: 2 counts of IllegalAnnotationExceptions
java.lang.StackTraceElement does not have a no-arg default constructor.
    this problem is related to the following location:
        at java.lang.StackTraceElement
        at public java.lang.StackTraceElement[] java.lang.Throwable.getStackTrace()
        at java.lang.Throwable
        at java.lang.Exception
        at com.sforce.ws.ConnectionException
        at com.sforce.ws.SoapFaultException
        at com.sforce.soap.enterprise.fault.ApiFault
        at public javax.xml.bind.JAXBElement com.sforce.soap.enterprise.fault.ObjectFactory.createFault(com.sforce.soap.enterprise.fault.ApiFault)
        at com.sforce.soap.enterprise.fault.ObjectFactory
com.sforce.ws.types.Time does not have a no-arg default constructor.
    this problem is related to the following location:
        at com.sforce.ws.types.Time
        at public com.sforce.ws.types.Time com.sforce.soap.enterprise.sobject.BusinessHours.getFridayEndTime()
        at com.sforce.soap.enterprise.sobject.BusinessHours
        at public com.sforce.soap.enterprise.sobject.BusinessHours com.sforce.soap.enterprise.sobject.ObjectFactory.createBusinessHours()
        at com.sforce.soap.enterprise.sobject.ObjectFactory

    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.xml.ws.model.AbstractSEIModelImpl.createJAXBContext(AbstractSEIModelImpl.java:124)
    ... 14 more
Caused by: com.sun.xml.bind.v2.runtime.IllegalAnnotationsException: 2 counts of IllegalAnnotationExceptions
java.lang.StackTraceElement does not have a no-arg default constructor.
    this problem is related to the following location:
        at java.lang.StackTraceElement
        at public java.lang.StackTraceElement[] java.lang.Throwable.getStackTrace()
        at java.lang.Throwable
        at java.lang.Exception
        at com.sforce.ws.ConnectionException
        at com.sforce.ws.SoapFaultException
        at com.sforce.soap.enterprise.fault.ApiFault
        at public javax.xml.bind.JAXBElement com.sforce.soap.enterprise.fault.ObjectFactory.createFault(com.sforce.soap.enterprise.fault.ApiFault)
        at com.sforce.soap.enterprise.fault.ObjectFactory
com.sforce.ws.types.Time does not have a no-arg default constructor.
    this problem is related to the following location:
        at com.sforce.ws.types.Time
        at public com.sforce.ws.types.Time com.sforce.soap.enterprise.sobject.BusinessHours.getFridayEndTime()
        at com.sforce.soap.enterprise.sobject.BusinessHours
        at public com.sforce.soap.enterprise.sobject.BusinessHours com.sforce.soap.enterprise.sobject.ObjectFactory.createBusinessHours()
        at com.sforce.soap.enterprise.sobject.ObjectFactory

    at com.sun.xml.bind.v2.runtime.IllegalAnnotationsException$Builder.check(IllegalAnnotationsException.java:66)
    at com.sun.xml.bind.v2.runtime.JAXBContextImpl.getTypeInfoSet(JAXBContextImpl.java:422)
    at com.sun.xml.bind.v2.runtime.JAXBContextImpl.<init>(JAXBContextImpl.java:270)
    at com.sun.xml.bind.v2.ContextFactory.createContext(ContextFactory.java:103)
    at com.sun.xml.bind.api.JAXBRIContext.newInstance(JAXBRIContext.java:89)
    at com.sun.xml.ws.model.AbstractSEIModelImpl$1.run(AbstractSEIModelImpl.java:126)
    at com.sun.xml.ws.model.AbstractSEIModelImpl$1.run(AbstractSEIModelImpl.java:125)
    ... 16 more

1. Login
2. Get Accounts
3. Update Accounts
4. Get Server Timestamp
5. Exit
Enter a menu option:
</code>```

The last line (chronologically) on the stack which refers to my own code is:

```<code>at hu.flux.salesforce.LoginToolkit.initPort(LoginToolkit.java:78)
</code>```

System.out.println statements in the source confirms that this is what the execution terminates.  This line specifically states:

```<code>Soap soap = (sforceService).getSoap();
</code>```

Does anyone know how or why this could transcend a security restriction ultimately leaving java unable to create the JAXBContext?

答:
It looks like you are trying to make a web service that has a subclass of java.lang.Exception or StackTraceElement in its contract. You can't do that. The only way to handle exceptions is to use faults.

Have you made all this work outside salesforce?

Note that your code goes to trouble to manually initialize a JAXB context, but you're not communicating that into the JAX-WS calls, so that stack is making a new JAXB context and getting into trouble trying. Did you remember to pass it into the binding provider, as in ...

```<code> try {
        jc = JAXBContext.newInstance("com.salesforce.sei");
        bindingProvider.setOutboundHeaders(Headers.create((JAXBRIContext) jc, sh));
    } catch (JAXBException e) {
        System.out.println("Error creating JAXBContext instance " + e.getMessage());
        return false;
    }
</code>```

Body:
I was on one Java/Salesforce tutorial but I couldn't get it to work as is because SoapBindingStub seems to be obsolete code based upon depreciated libraries.  So I tried to mesh the code with code from JAX-WS Quick Start, but this didn't quite work either.  No matter what I did, ultimately the sample console application would suffer exceptions, complaining "Web Service Exception creating salesface port.: Unable to create JAXBContext due to the security restriction on class javax.xml.ws.WebServiceException".

I gave up (for the moment) trying to mash the two codes, and instead am now just working on abstracting the JAX-WS Quickstart.java so I can understand wow it works and reuse its methods in other applications.

No matter how I slice and dice the code, it always gets stuck at the same location with essentially that same error.

Here is the current code for method which is persistantly failing:

private void initPort()
{
    try
    {
        URL wsdlLocation = this.getClass().getClassLoader().getResource("META-INF/enterprise.wsdl");
        if (wsdlLocation == null)
        {
            WebServiceException webServiceException = new WebServiceException("enterprise.wsdl not found!");
            ExceptionToolkit.display("Web Service Exception can't find enterprise.wsdl", webServiceException);
            throw webServiceException;
        }
        else {System.out.println("\nFOUND enterprise.wsdl!!!\n\n");}

        QName qName = new QName("urn:enterprise.soap.sforce.com", "SforceService");
        SforceService sforceService = new SforceService( wsdlLocation, qName );
        System.out.println("\nsforceService INITIALIZED. About to get Soap.\n\n");
        Soap soap = (sforceService).getSoap();
        System.out.println("\nWe have soap.\n\n");
        setPort (soap);
    }
    catch (WebServiceException webServiceException)
    {
        ExceptionToolkit.display("Web Service Exception creating salesface port", webServiceException);
        return;
    }
}

Here is the error, including output immediately before and after:

Running main loop

FOUND enterprise.wsdl!!!

sforceService INITIALIZED. About to get Soap.

Web Service Exception creating salesface port: Unable to create JAXBContext due to the security restriction
on class javax.xml.ws.WebServiceException
javax.xml.ws.WebServiceException: Unable to create JAXBContext due to the security restriction
    at com.sun.xml.ws.model.AbstractSEIModelImpl.createJAXBContext(AbstractSEIModelImpl.java:131)
    at com.sun.xml.ws.model.AbstractSEIModelImpl.postProcess(AbstractSEIModelImpl.java:63)
    at com.sun.xml.ws.model.RuntimeModeler.buildRuntimeModel(RuntimeModeler.java:224)
    at com.sun.xml.ws.client.WSServiceDelegate.addSEI(WSServiceDelegate.java:588)
    at com.sun.xml.ws.client.WSServiceDelegate.getPort(WSServiceDelegate.java:291)
    at com.sun.xml.ws.client.WSServiceDelegate.getPort(WSServiceDelegate.java:274)
    at com.sun.xml.ws.client.WSServiceDelegate.getPort(WSServiceDelegate.java:267)
    at javax.xml.ws.Service.getPort(Unknown Source)
    at com.sforce.soap.enterprise.SforceService.getSoap(SforceService.java:53)
    at hu.flux.salesforce.LoginToolkit.initPort(LoginToolkit.java:78)
    at hu.flux.salesforce.LoginToolkit.doLogin(LoginToolkit.java:122)
    at hu.flux.salesforce.LoginToolkit.<init>(LoginToolkit.java:49)
    at hu.flux.salesforce.samples.Quickstart.mainLoop(Quickstart.java:55)
    at hu.flux.salesforce.samples.Quickstart.<init>(Quickstart.java:28)
    at hu.flux.salesforce.samples.Quickstart.main(Quickstart.java:21)
Caused by: java.security.PrivilegedActionException: com.sun.xml.bind.v2.runtime.IllegalAnnotationsException: 2 counts of IllegalAnnotationExceptions
java.lang.StackTraceElement does not have a no-arg default constructor.
    this problem is related to the following location:
        at java.lang.StackTraceElement
        at public java.lang.StackTraceElement[] java.lang.Throwable.getStackTrace()
        at java.lang.Throwable
        at java.lang.Exception
        at com.sforce.ws.ConnectionException
        at com.sforce.ws.SoapFaultException
        at com.sforce.soap.enterprise.fault.ApiFault
        at public javax.xml.bind.JAXBElement com.sforce.soap.enterprise.fault.ObjectFactory.createFault(com.sforce.soap.enterprise.fault.ApiFault)
        at com.sforce.soap.enterprise.fault.ObjectFactory
com.sforce.ws.types.Time does not have a no-arg default constructor.
    this problem is related to the following location:
        at com.sforce.ws.types.Time
        at public com.sforce.ws.types.Time com.sforce.soap.enterprise.sobject.BusinessHours.getFridayEndTime()
        at com.sforce.soap.enterprise.sobject.BusinessHours
        at public com.sforce.soap.enterprise.sobject.BusinessHours com.sforce.soap.enterprise.sobject.ObjectFactory.createBusinessHours()
        at com.sforce.soap.enterprise.sobject.ObjectFactory

    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.xml.ws.model.AbstractSEIModelImpl.createJAXBContext(AbstractSEIModelImpl.java:124)
    ... 14 more
Caused by: com.sun.xml.bind.v2.runtime.IllegalAnnotationsException: 2 counts of IllegalAnnotationExceptions
java.lang.StackTraceElement does not have a no-arg default constructor.
    this problem is related to the following location:
        at java.lang.StackTraceElement
        at public java.lang.StackTraceElement[] java.lang.Throwable.getStackTrace()
        at java.lang.Throwable
        at java.lang.Exception
        at com.sforce.ws.ConnectionException
        at com.sforce.ws.SoapFaultException
        at com.sforce.soap.enterprise.fault.ApiFault
        at public javax.xml.bind.JAXBElement com.sforce.soap.enterprise.fault.ObjectFactory.createFault(com.sforce.soap.enterprise.fault.ApiFault)
        at com.sforce.soap.enterprise.fault.ObjectFactory
com.sforce.ws.types.Time does not have a no-arg default constructor.
    this problem is related to the following location:
        at com.sforce.ws.types.Time
        at public com.sforce.ws.types.Time com.sforce.soap.enterprise.sobject.BusinessHours.getFridayEndTime()
        at com.sforce.soap.enterprise.sobject.BusinessHours
        at public com.sforce.soap.enterprise.sobject.BusinessHours com.sforce.soap.enterprise.sobject.ObjectFactory.createBusinessHours()
        at com.sforce.soap.enterprise.sobject.ObjectFactory

    at com.sun.xml.bind.v2.runtime.IllegalAnnotationsException$Builder.check(IllegalAnnotationsException.java:66)
    at com.sun.xml.bind.v2.runtime.JAXBContextImpl.getTypeInfoSet(JAXBContextImpl.java:422)
    at com.sun.xml.bind.v2.runtime.JAXBContextImpl.<init>(JAXBContextImpl.java:270)
    at com.sun.xml.bind.v2.ContextFactory.createContext(ContextFactory.java:103)
    at com.sun.xml.bind.api.JAXBRIContext.newInstance(JAXBRIContext.java:89)
    at com.sun.xml.ws.model.AbstractSEIModelImpl$1.run(AbstractSEIModelImpl.java:126)
    at com.sun.xml.ws.model.AbstractSEIModelImpl$1.run(AbstractSEIModelImpl.java:125)
    ... 16 more

1. Login
2. Get Accounts
3. Update Accounts
4. Get Server Timestamp
5. Exit
Enter a menu option:

The last line (chronologically) on the stack which refers to my own code is:

at hu.flux.salesforce.LoginToolkit.initPort(LoginToolkit.java:78)

System.out.println statements in the source confirms that this is what the execution terminates.  This line specifically states:

Soap soap = (sforceService).getSoap();

Does anyone know how or why this could transcend a security restriction ultimately leaving java unable to create the JAXBContext?

Body:
It looks like you are trying to make a web service that has a subclass of java.lang.Exception or StackTraceElement in its contract. You can't do that. The only way to handle exceptions is to use faults.

Have you made all this work outside salesforce?

Note that your code goes to trouble to manually initialize a JAXB context, but you're not communicating that into the JAX-WS calls, so that stack is making a new JAXB context and getting into trouble trying. Did you remember to pass it into the binding provider, as in ...

 try {
        jc = JAXBContext.newInstance("com.salesforce.sei");
        bindingProvider.setOutboundHeaders(Headers.create((JAXBRIContext) jc, sh));
    } catch (JAXBException e) {
        System.out.println("Error creating JAXBContext instance " + e.getMessage());
        return false;
    }


问:
Can't use migrations in EF Core: "42P07: relation "AspNetRoles" already exists"
I have strange issue which I can't find solution for.

The stack is: NET Core 2, EF, PostgreSQL.
I use .NET Core Identity with User : IdentityUser to extend base user model with additional fields.

After I create first migration, drop whole database and try to dotnet ef database update I always get an error: 42P07: relation "AspNetRoles" already exists

Even with this error, the database and tables are created but it makes migrations useless as it does not save applied migrations so I can't update DB with following changes...

fail: Microsoft.EntityFrameworkCore.Database.Command[200102]
        Failed executing DbCommand (0ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
        CREATE TABLE "AspNetRoles" (
            "Id" text NOT NULL,
            "ConcurrencyStamp" text NULL,
            "Name" varchar(256) NULL,
            "NormalizedName" varchar(256) NULL,
            CONSTRAINT "PK_AspNetRoles" PRIMARY KEY ("Id")
        ); Npgsql.PostgresException (0x80004005): 42P07: relation "AspNetRoles" already exists    at
  Npgsql.NpgsqlConnector.d__148.MoveNext()
  --- End of stack trace from previous location where exception was thrown ---    at
  System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()    at
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task)    at System.Runtime.CompilerServices.TaskAwaiter1.GetResult()
  at System.Runtime.CompilerServices.ValueTaskAwaiter1.GetResult()

  at Npgsql.NpgsqlConnector.d__147.MoveNext()

答:
The reason was pretty simple.
I was calling EnsureCreated in Startup.cs which was getting conflict with migrations as working different way.
Thankfully EF Core owners made it clear for me on GitHub.

So to summarize - if you want to use Migrations, you can't use EnsureCreated.


问:
Dynamic binding variables to existing dom elements
I have a component that presents dynamically loaded SVG. Svg is being loaded to variable svgSelector. Component template is simple:

```<code><div #selectorContainer [innerHTML]="svgSelector | safeHtml"></div>
</code>```

Until now everything is ok - SVG displays correctly. Now I want to bind attributes for some of the elements to variable. Eg. insinde SVG I have:

```<code><path fill="#00ff00" d="m1319.0166 570.7281l17.700806 0l0 26.771667l-17.700806 0z" fill-rule="evenodd"></path>
</code>```

I would like to bind value of the fill attribute to variable. How do I do it?

I get the reference to my selectorContainer and I have it available:

```<code>@ViewChild('selectorContainer') selectorContainer: ElementRef;
ngAfterViewInit() {
    this.selectorContainer.nativeElement.querySelector('svg') // <-- my SVG DOM element

}
</code>```

What next? Is there a way I dynamically bind variable to any of this dynamically created DOM elements?

答:
Have you tried surrounding with square brackets []? i.e.

```<code><path [fill]="varName" ... ></path>
</code>```

Or using {{}}? i.e.

```<code><path fill={{varName}} ... ></path>
</code>```

Body:
I have a component that presents dynamically loaded SVG. Svg is being loaded to variable svgSelector. Component template is simple:

Until now everything is ok - SVG displays correctly. Now I want to bind attributes for some of the elements to variable. Eg. insinde SVG I have:

<path fill="#00ff00" d="m1319.0166 570.7281l17.700806 0l0 26.771667l-17.700806 0z" fill-rule="evenodd"></path>

I would like to bind value of the fill attribute to variable. How do I do it?

I get the reference to my selectorContainer and I have it available:

@ViewChild('selectorContainer') selectorContainer: ElementRef;
ngAfterViewInit() {
    this.selectorContainer.nativeElement.querySelector('svg') // <-- my SVG DOM element

}

What next? Is there a way I dynamically bind variable to any of this dynamically created DOM elements?

Body:
Have you tried surrounding with square brackets []? i.e.

<path [fill]="varName" ... ></path>

Or using {{}}? i.e.

<path fill={{varName}} ... ></path>


问:
MySQL limit syntax with Query performance
I want to know how it is affected in query performance to use limit syntax
There are 180000 rows. So I would select data using limit syntax.
So I want to know the relationship between limit syntax and query performance.</p>

答:
The easiest way to quickly gauge the impact of any SQL commands is using EXPLAIN and checking the number of rows etc.. Starting with EXPLAINing the query is usually a good route. Just put 'EXPLAIN ' before your query to find out how expensive it is.

Sending large data sets might not be the problem -- it 's the sorting

In my experience it's the usage of ORDER BY which is extremely slow. Frequently LIMIT and ORDER BY are used together for obvious reasons, and it's the sorting that's the slow part, rather than LIMIT itself.

LIMIT does avoid returning large data sets which might otherwise be discarded, but usually in practice the database is on the same local network or even the same server. Network performance & large datasets usually aren't the limiting factor. Instead, it's the cost of sorting the data before returning it which is highest. You can get the most benefit by optimising for those sorts, eg by creating indexes matching your queries.


问:
User Control not giving the real width and height
I have add a user control and resize it to 300 x 300 in the control designer.
I declared it in the top so that I can use it through out my entire code but it gives me the wrong width of the control but when I declare it in the event itself I get the right width.

Ex:

```<code>Public Class UserControl1

Dim A As Integer = Me.Width

Private Sub UserControl1_Click(sender As Object, e As EventArgs) Handles Me.Click

    Dim B As Integer = Me.Width

    MsgBox("A = " & A & " " & "and" & "  " & "B = " & B)

End Sub
</code>```

End Class

I named the Variables A and B but A gives me 150 and B gives me 300

A = 150 and B = 300

Can anyone please explain this to me??? Thanks

答: The reason the values are different is because A is set to the width when the object is first constructed, before any properties like Width have been modified by any consuming code. B is set when the control is clicked, after the control has been fully loaded.

Body:
I have add a user control and resize it to 300 x 300 in the control designer.
I declared it in the top so that I can use it through out my entire code but it gives me the wrong width of the control but when I declare it in the event itself I get the right width.

Ex:

Public Class UserControl1

Dim A As Integer = Me.Width

Private Sub UserControl1_Click(sender As Object, e As EventArgs) Handles Me.Click

    Dim B As Integer = Me.Width

    MsgBox("A = " & A & " " & "and" & "  " & "B = " & B)

End Sub

End Class

I named the Variables A and B but A gives me 150 and B gives me 300

A = 150 and B = 300

Can anyone please explain this to me??? Thanks


问:
Secure method for software distribution
I work at a software development company, and one of our tasks is to distribute our software to our customers before deployment. We have a lot of software components that at built separately, so we end up with 5 or more packages - usually more, and some times up to several hundred files because we also need to distribute data sets from time to time. We would like to find a way to distribute these packages to the customers as easy as possible. Currently we are using Box which is OK, but uploading and downloading several hundred packages takes a while, so we would like a method that will automatically place the files at the customers site.

Ideally we would like to end up with a file structure on our build environment, where we could place folders like:

Customer1

Customer2

Customer3

etc.

and putting files into those folders would automatically end up at that particular customer. It could probably be done by Dropbox, but we cannot install that at the customers sites.

We expect to build something with that functionality ourselves, but are there any frameworks or anything so we don't have to start from scratch? It's important that the files actually end up at the customers sites, and not on a shared drive somewhere in the cloud, since some of the customers have really slow internet connection. We are running on Windows.

答: You can link your startup page with web based verification process. If the software is installed in particular MAC ID, then verify it first at your web portal, and create one file or a value in db to ensure it is verified. From the 2nd time the startup page will check for the verification key in db or the verification file. If it is available then it will open the software otherwise it should redirect the software to registration page.</p>

Title: Secure method for software distribution


问:
return data which value is not empty or exists in mongodb
i am a beginner in python and mongodb. My database is like this

```<code>{ '_id' : 1,
  'identity' : {
          'first_name' : 'John',
          'last_name' : 'Doe',
          'phone' : '+440823XXX'
         }
   'status' : 'active'
}
</code>```

I want to return data which phone is empty or doesn't exists in db. I tried

```<code>db.collection.find({"identity" : { "phone" : { "$exists": "true", "$ne": "null" }  }})
</code>```

But it returned <pymongo.cursor.Cursor at 0x7f5da40e8e80>

How the sintax for getting the query which the value is not empty?

答:
Please try this code :

```<code>db.collection.find({"identity.phone" { $exists: "true", $ne: "null" } })
</code>```

It will return a cursor, so

```<code>cur = db.collection.find({"identity.phone" { $exists: "true", $ne: "null" } })
</code>```

and you got the data in cur. just loop through it.

```<code>for doc in cur:
...
</code>```

For further reference check here

Body:
i am a beginner in python and mongodb. My database is like this

{ '_id' : 1,
  'identity' : {
          'first_name' : 'John',
          'last_name' : 'Doe',
          'phone' : '+440823XXX'
         }
   'status' : 'active'
}

I want to return data which phone is empty or doesn't exists in db. I tried

db.collection.find({"identity" : { "phone" : { "$exists": "true", "$ne": "null" }  }})

But it returned <pymongo.cursor.Cursor at 0x7f5da40e8e80>

How the sintax for getting the query which the value is not empty?

Body:
Please try this code :

db.collection.find({"identity.phone" { $exists: "true", $ne: "null" } })

It will return a cursor, so

cur = db.collection.find({"identity.phone" { $exists: "true", $ne: "null" } })

and you got the data in cur. just loop through it.

for doc in cur:
...

For further reference check here


问:
How can I get the equivalent non-utf8 chars from a utf8 string?
ruby 1.8.6, rails 2.3.8

Im doing some evals to write some methods to a class, and its working out nice(first time playing w/ metaprogramming :p), except that some strings that need to go into the methods(as code, and not strings) have accented characters and etc...

for example, I need to get "restricao" from the string "restrição", how can I do that, please?

答:
Check Unidecode gem!</p>

```<code>"restrição".to_ascii #=> "restricao"
</code>```

Body:
Check Unidecode gem!

"restrição".to_ascii #=> "restricao"


问:
In Javafx when a window is opened how can i set it so that the user isnt able to open the same window again?

I tried a lot but just couldn't find any solution. At the moment the opened window(popup window) is always on top but the user can still access the main window. That's how it should be, but it shouldn't be possible to open the same popup window again.
</p>

```<code>    Stage stage = new Stage();
    stage.setTitle(panelTitle);
    stage.setScene(new Scene(root));
    stage.initModality(Modality.WINDOW_MODAL);
    stage.setAlwaysOnTop(true);
    stage.showAndWait();
</code>```

<p>
Thank you in advance!
</p>

答:
As LazerBanana said, I would disable the button that opens the window, and I would enable it when you close it.</p>

```<code>Stage stage = new Stage();
button.setDisable(true);
stage.setTitle(panelTitle);
stage.setScene(new Scene(root));
stage.initModality(Modality.WINDOW_MODAL);
stage.setAlwaysOnTop(true);
stage.showAndWait();
// your logic here
button.setDisable(false);
</code>```

Body:
I tried a lot but just couldn't find any solution. At the moment the opened window(popup window) is always on top but the user can still access the main window. That's how it should be, but it shouldn't be possible to open the same popup window again.

    Stage stage = new Stage();
    stage.setTitle(panelTitle);
    stage.setScene(new Scene(root));
    stage.initModality(Modality.WINDOW_MODAL);
    stage.setAlwaysOnTop(true);
    stage.showAndWait();

Thank you in advance!

Body:
As LazerBanana said, I would disable the button that opens the window, and I would enable it when you close it.

Stage stage = new Stage();
button.setDisable(true);
stage.setTitle(panelTitle);
stage.setScene(new Scene(root));
stage.initModality(Modality.WINDOW_MODAL);
stage.setAlwaysOnTop(true);
stage.showAndWait();
// your logic here
button.setDisable(false);


问:
Using xpath containing whitespace
```<code>List <WebElement> tableSituacao = driver.findElements(By.xpath("//*[@id=\"tabela\"]/tbody/tr/td[5][contains(text(),"+situacao+")]"));
</code>```

<p>how to use normalize-space in my case? "situacao" has white spaces </p>

答:
Use below code :

```<code>//*[@id=\"tabela\"]/tbody/tr/td[5][normalize-space()='"+situacao+"')]
</code>```

Note : This will work if you have left of right spaces in string like _example_ (consider _ as space). but if you tend to consider space middle of and string like example example then its a complete string it remove space before first example text and after last example text.

Title: Using xpath containing whitespace

Body:
List <WebElement> tableSituacao = driver.findElements(By.xpath("//*[@id=\"tabela\"]/tbody/tr/td[5][contains(text(),"+situacao+")]"));

how to use normalize-space in my case? "situacao" has white spaces

Body:
Use below code :

//*[@id=\"tabela\"]/tbody/tr/td[5][normalize-space()='"+situacao+"')]

Note : This will work if you have left of right spaces in string like _example_ (consider _ as space). but if you tend to consider space middle of and string like example example then its a complete string it remove space before first example text and after last example text.


问:
Is it possible to delete running container automatically after 1 day?
I have created my own linux container and its in running state. I want to delete the running container after one day automatically.

Is there anyway to delete the container automatically?

If it's possible, Where do I have to add script/code in my Dockerfile?

答:
I had this requirement earlier and I used sleep 86400 in script file like

service apache2 start && sleep 86400 in bash script ,
which runs for 1day.

Else you can go through this thread which explained

stop and delete docker container if its running


问:
Logstash multiline codec ignore last event / line
Logstash multiline codec ignore my last event (line) until send next package of logs.

My logstash.conf:

```<code>input {
    }
    http {
        port => "5001"
        codec => multiline {
            pattern => "^\[%{TIMESTAMP_ISO8601}\]"
            negate => true
            what => previous
            auto_flush_interval => 15
        }
    }
}

filter{
    grok {
        match => { "message" => "(?m)\[%{TIMESTAMP_ISO8601:timestamp}\]\s\<%{LOGLEVEL:log-level}\>\s\[%{WORD:component}\]\s%{GREEDYDATA:log-message}"
    }
}

output {
    elasticsearch {
        hosts => "elasticsearch:9200"
        index => "%{+YYYY-MM-dd}"
    }
}
</code>```

Moreover solution with auto_flush_interval don't work.

For example:

input using Postman:

[2017-07-11 22:32:12.345]  [KCU] Component initializing
  Exception in thread "main" java.lang.NullPointerException
          at com.example.myproject.Book.getTitle(Book.java:16)
  [2017-07-11 22:32:16.345]  [KCU] Return with status 1

output - only one event (should be two):

[2017-07-11 22:32:12.345]  [KCU] Component initializing
  Exception in thread "main" java.lang.NullPointerException
          at com.example.myproject.Book.getTitle(Book.java:16)

I need this last line.

Question:
Am I doing something wrong or there are problems with multiline codec? - How to fix this?

答:
I'm afraid you're using the multiline codec wrong. Let's take a look at your configuration:

```<code>codec => multiline {
            pattern => "^\[%{TIMESTAMP_ISO8601}\]"
            negate => true
            what => previous
        }
</code>```

It says if a logline does not (negate => true) start with a ISO timestamp (pattern) append it to the previous log line (what => previous).

But the logline you're missing starts with a ISO timestamp:

[2017-07-11 22:32:16.345] [KCU] Return with status 1

So it will not be appended to the previous log lines but instead create a new document in Elasticsearch.

Body:
Logstash multiline codec ignore my last event (line) until send next package of logs.

My logstash.conf:

input {
    }
    http {
        port => "5001"
        codec => multiline {
            pattern => "^\[%{TIMESTAMP_ISO8601}\]"
            negate => true
            what => previous
            auto_flush_interval => 15
        }
    }
}

filter{
    grok {
        match => { "message" => "(?m)\[%{TIMESTAMP_ISO8601:timestamp}\]\s\<%{LOGLEVEL:log-level}\>\s\[%{WORD:component}\]\s%{GREEDYDATA:log-message}"
    }
}

output {
    elasticsearch {
        hosts => "elasticsearch:9200"
        index => "%{+YYYY-MM-dd}"
    }
}

Moreover solution with auto_flush_interval don't work.

For example:

input using Postman:

[2017-07-11 22:32:12.345]  [KCU] Component initializing
  Exception in thread "main" java.lang.NullPointerException
          at com.example.myproject.Book.getTitle(Book.java:16)
  [2017-07-11 22:32:16.345]  [KCU] Return with status 1

output - only one event (should be two):

[2017-07-11 22:32:12.345]  [KCU] Component initializing
  Exception in thread "main" java.lang.NullPointerException
          at com.example.myproject.Book.getTitle(Book.java:16)

I need this last line.

Question:
Am I doing something wrong or there are problems with multiline codec? - How to fix this?

Body:
I'm afraid you're using the multiline codec wrong. Let's take a look at your configuration:

codec => multiline {
            pattern => "^\[%{TIMESTAMP_ISO8601}\]"
            negate => true
            what => previous
        }

It says if a logline does not (negate => true) start with a ISO timestamp (pattern) append it to the previous log line (what => previous).

But the logline you're missing starts with a ISO timestamp:

[2017-07-11 22:32:16.345] [KCU] Return with status 1

So it will not be appended to the previous log lines but instead create a new document in Elasticsearch.


问:
Is bounce rate a (Google) search engine factor?
I believe someone (perhaps a competitor) is trying to manipulate the bouncing rate of one of my sites. So I'm trying to figure out if this has any impact on search engine ranking, and take appropriate action.

I have read mixed opinions about this, but couldn't find a definitive Yes or No anywhere.

Edit: If the answer is yes, I hope Google considers repeated bounces (coming from the same user) as an additional variable in their bouncing rate calculation algorithm. Otherwise, anyone could set a bot to bounce every x minutes.

答: Bounce rate is important for SEO, the lower the better. Is that guy just going to your site and close it and then repeat ? If yes than usually Google can identify behavior which is unnatural. Also either he has to sit all day and do this, or your site needs to have a really low visitor count for him to be able to affect you.</p>


问:
Google Chrome redirecting localhost to https
When I debug a Visual Studio project using Chrome the browser tries to redirect to the https equivalent of my web address. I do not have SSL enabled in the web project and the start URL is the http URL.  When I debug using FireFox or IE I do not have this problem.

I did re-install Chrome which fixed the problem for a day.  Without downloading any addons the problem happened again the next day.

What is making Chrome redirect localhost to https?

Network Inspect Shows:
Request URL:data:text/html,chromewebdata
Request Headers
Provisional headers are shown
User-Agent:Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.143 Safari/537.36

No preview and no response data in those tabs.

答:
None of these worked for me. It started happening after a chrome update (Version 63.0.3239.84, linux) with a local URL. Would always redirect to https no matter what. Lost some hours and a lot of patience on this

What did worked after all was just changing the domain.

For what is worth, the domain was .app. Perhaps it got something to do? And just changed it to .test and chrome stopped redirecting it