问:
what is the es6 fat arrow equivalent to a es5 function declaration
With ES5 I can declare either a function declaration or expression, depending on what I need.

```<code>function es5FunctionDeclaration() {
  return 'I am an es5 function declaration';
}

var es5FunctionExpression = function() {
  return 'I am an es5 function expression';
}
</code>```

With the ES6 fat arrow, it is common to create a function expression like this...

```<code>const es6FunctionExpression = () => {
  return 'I am an es6 function expression';
}
</code>```

But I haven't find a way to do a function declaration with a fat arrow, perhaps it is not possible.

```<code>// es6FunctionDeclarationWithFatArrow ??
</code>```

答:
To declare functions in ES6 you can do it via:

```<code>const functionName = () => {};
</code>```

Or you can do it via the function keyword:

```<code>function functionName() {}
</code>```

And, if you're creating ES6 classes you don't create functions but methods:

```<code>class MyClass {
  constructor() {}
  method1() {}
  method2() {}
}
</code>```

Body:
With ES5 I can declare either a function declaration or expression, depending on what I need.

function es5FunctionDeclaration() {
  return 'I am an es5 function declaration';
}

var es5FunctionExpression = function() {
  return 'I am an es5 function expression';
}

With the ES6 fat arrow, it is common to create a function expression like this...

const es6FunctionExpression = () => {
  return 'I am an es6 function expression';
}

But I haven't find a way to do a function declaration with a fat arrow, perhaps it is not possible.

// es6FunctionDeclarationWithFatArrow ??

Body:
To declare functions in ES6 you can do it via:

const functionName = () => {};

Or you can do it via the function keyword:

function functionName() {}

And, if you're creating ES6 classes you don't create functions but methods:

class MyClass {
  constructor() {}
  method1() {}
  method2() {}
}


来源: stackexchange

问:
Redirect to user dashboard after successful login
I'm trying to redirect to my user-dash.html page after the user is successfully logged in.

I've already tried using res.redirect() and got an error about not setting headers after they've been sent to the client.

public.index.js:

```<code>// when the login from is submitted:

    $("#loginForm").submit(function(e) {
        e.preventDefault();
        let username = $("#GET-username").val();
        let password = $("#GET-password").val();
        let userInfo = {username, password};
        let settings = {
            url:"/auth/login",
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(userInfo),
            success: function(data) {
                console.log('successfully logged in');
                localStorage.setItem("authToken", data.authToken);
                localStorage.setItem("currentUser", username);
                user = username;
                console.log(data);
                },
            error: function(err) {
                console.log(err);
            }
        };
        $.ajax(settings);
    })
</code>```

auth/router.js:

```<code>// The user provides a username and password to login
router.post('/login', localAuth, (req, res) => {
  const authToken = createAuthToken(req.user.serialize());
  res.json({authToken});
});

const jwtAuth = passport.authenticate('jwt', {session: false});
</code>```

right now, when submit is clicked, the user is successfully logged in but nothing happens i.e. the user isn't redirected to their dashboard.

答:
You can use:

window.location.href = '/dashboard'

if you're using React, you can use :

this.props.history.push('/dashboard')

Add it inside function assigned to the success attribute

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to redirect to my user-dash.html page after the user is successfully logged in.

I've already tried using res.redirect() and got an error about not setting headers after they've been sent to the client.

public.index.js:

// when the login from is submitted:

    $("#loginForm").submit(function(e) {
        e.preventDefault();
        let username = $("#GET-username").val();
        let password = $("#GET-password").val();
        let userInfo = {username, password};
        let settings = {
            url:"/auth/login",
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(userInfo),
            success: function(data) {
                console.log('successfully logged in');
                localStorage.setItem("authToken", data.authToken);
                localStorage.setItem("currentUser", username);
                user = username;
                console.log(data);
                },
            error: function(err) {
                console.log(err);
            }
        };
        $.ajax(settings);
    })

auth/router.js:

// The user provides a username and password to login
router.post('/login', localAuth, (req, res) => {
  const authToken = createAuthToken(req.user.serialize());
  res.json({authToken});
});

const jwtAuth = passport.authenticate('jwt', {session: false});

right now, when submit is clicked, the user is successfully logged in but nothing happens i.e. the user isn't redirected to their dashboard.


问:
VBA, Outlook, Seeing 'People's Calendars
I am tring to programmatically (with VBA) to access calendars others share with me. They are listed in my Outlook under 'People's Calendars.' I have searched the Web for this and all the suggestions have done little more than confuse me. How can I get a listing of all the calendars shared to me, and then one calendar in specific, from among the 'People's Calendars'? </p>

答:
I think this gets closer. It came from Sue Mosher's outstanding Microsoft Outlook 2007 Programming: Jumpstart for Power Users and Administrators. I hope she doesn't mind.</p>

```<code>Sub ShowOtherUserCalFolders()
    Dim objOL As Outlook.Application
    Dim objNS As Outlook.NameSpace
    Dim objExpCal As Outlook.Explorer
    Dim objNavMod As Outlook.CalendarModule
    Dim objNavGroup As Outlook.NavigationGroup
    Dim objNavFolder As Outlook.NavigationFolder
    Dim objFolder As Outlook.Folder
    Dim colExpl As Outlook.Explorers
    Dim objExpl As Outlook.Explorer
    Set objOL = Application
    Set objNS = objOL.Session
    Set colExpl = objOL.Explorers
    Set objExpCal = _
      objNS.GetDefaultFolder(olFolderCalendar).GetExplorer
    Set objNavMod = objExpCal.NavigationPane.Modules. _
      GetNavigationModule(olModuleCalendar)
    Set objNavGroup = objNavMod.NavigationGroups. _
      GetDefaultNavigationGroup(olPeopleFoldersGroup)
    For Each objNavFolder In objNavGroup.NavigationFolders
        Set objFolder = objNavFolder.Folder
        Set objExpl = _
          colExpl.Add(objFolder, olFolderDisplayNormal)
        objExpl.Activate
        objExpl.WindowState = olMaximized
        objExpl.WindowState = olMinimized
    Next
    Set objOL = Nothing
    Set objNS = Nothing
    Set objNavMod = Nothing
    Set objNavGroup = Nothing
    Set objNavFolder = Nothing
    Set objFolder = Nothing
    Set colExpl = Nothing
    Set objExpl = Nothing
End Sub
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I think this gets closer. It came from Sue Mosher's outstanding Microsoft Outlook 2007 Programming: Jumpstart for Power Users and Administrators. I hope she doesn't mind.

Sub ShowOtherUserCalFolders()
    Dim objOL As Outlook.Application
    Dim objNS As Outlook.NameSpace
    Dim objExpCal As Outlook.Explorer
    Dim objNavMod As Outlook.CalendarModule
    Dim objNavGroup As Outlook.NavigationGroup
    Dim objNavFolder As Outlook.NavigationFolder
    Dim objFolder As Outlook.Folder
    Dim colExpl As Outlook.Explorers
    Dim objExpl As Outlook.Explorer
    Set objOL = Application
    Set objNS = objOL.Session
    Set colExpl = objOL.Explorers
    Set objExpCal = _
      objNS.GetDefaultFolder(olFolderCalendar).GetExplorer
    Set objNavMod = objExpCal.NavigationPane.Modules. _
      GetNavigationModule(olModuleCalendar)
    Set objNavGroup = objNavMod.NavigationGroups. _
      GetDefaultNavigationGroup(olPeopleFoldersGroup)
    For Each objNavFolder In objNavGroup.NavigationFolders
        Set objFolder = objNavFolder.Folder
        Set objExpl = _
          colExpl.Add(objFolder, olFolderDisplayNormal)
        objExpl.Activate
        objExpl.WindowState = olMaximized
        objExpl.WindowState = olMinimized
    Next
    Set objOL = Nothing
    Set objNS = Nothing
    Set objNavMod = Nothing
    Set objNavGroup = Nothing
    Set objNavFolder = Nothing
    Set objFolder = Nothing
    Set colExpl = Nothing
    Set objExpl = Nothing
End Sub


问:
What is the order that foreach in PHP should respect when iterating over an array?
I know that PHP array is not an array, it is actually an ordered hashmap, but it still does not make sense to me why if I run this code:

```<code><?php

$teste = [];
$teste[2] = 'Test 2';
$teste[1] = 'Test 1';
$teste[3] = 'Test 3';

foreach ($teste as $t) {
    echo $t;
}
</code>```

It prints the following:

```<code>Test 2
Test 1
Test 3
</code>```

The result does not make sense to me, shouldn't it be ordered like:

```<code>Test 1
Test 2
Test 3
</code>```

答:
All arrays in PHP are actually ordered maps. Thus, the order in which key-value pairs are encountered in the map will depend primarily on the order in which they were added to the map. Arrays with a 0..n-1 index sequence in strict increasing order are simply a special case. You can test this by doing the following:

$my_arr = array();
$my_arr[3] = 'd';
$my_arr[1] = 'b';
$my_arr[2] = 'c';
$my_arr[0] = 'a';

// #1
echo json_encode($my_arr, JSON_PRETTY_PRINT) . "\n";

// #2
ksort($my_arr);
echo json_encode($my_arr, JSON_PRETTY_PRINT);
```

<p>Output for #1:</p>

```{
    "3": "d",
    "1": "b",
    "2": "c",
    "0": "a"
}
```

<p>Output for #2:</p>

```[
    "a",
    "b",
    "c",
    "d"
]
```

Note that the only difference between the two versions of $my_arr is the order of the keys. Out of order, the array is encoded as an object, but in order the array is encoded as a simple array.

Please review the linked section of the documentation for more information about PHP's arrays. This is already a well-documented feature of the language. If you desire a strict increasing sort order for your keys, use ksort() as shown in the example above.

Body:
I know that PHP array is not an array, it is actually an ordered hashmap, but it still does not make sense to me why if I run this code:

<?php

$teste = [];
$teste[2] = 'Test 2';
$teste[1] = 'Test 1';
$teste[3] = 'Test 3';

foreach ($teste as $t) {
    echo $t;
}

It prints the following:

Test 2
Test 1
Test 3

The result does not make sense to me, shouldn't it be ordered like:

Test 1
Test 2
Test 3

Body:
All arrays in PHP are actually ordered maps. Thus, the order in which key-value pairs are encountered in the map will depend primarily on the order in which they were added to the map. Arrays with a 0..n-1 index sequence in strict increasing order are simply a special case. You can test this by doing the following:

$my_arr = array();
$my_arr[3] = 'd';
$my_arr[1] = 'b';
$my_arr[2] = 'c';
$my_arr[0] = 'a';

// #1
echo json_encode($my_arr, JSON_PRETTY_PRINT) . "\n";

// #2
ksort($my_arr);
echo json_encode($my_arr, JSON_PRETTY_PRINT);

Output for #1:

{
    "3": "d",
    "1": "b",
    "2": "c",
    "0": "a"
}

Output for #2:

[
    "a",
    "b",
    "c",
    "d"
]

Note that the only difference between the two versions of $my_arr is the order of the keys. Out of order, the array is encoded as an object, but in order the array is encoded as a simple array.

Please review the linked section of the documentation for more information about PHP's arrays. This is already a well-documented feature of the language. If you desire a strict increasing sort order for your keys, use ksort() as shown in the example above.


Title: Adding and printing very small numbers in R

Body:
I'm running a for loop in R to see whether adding up halves of the previous half eventually reaches 1 (.5 + .25 + .125 + .0625 +  .03125,...) using the code below:

temp = 0
for(i in 2^seq(1, 60, by = 1))  {
  temp = temp + 1/i
  print(sprintf("%.40f", temp))
  flush.console()
  }

but, past the 54th iteration, it does reach one, but it's apparently not adding things any more (even increasing the %.40f parameter):

result.52 "0.9999999999999997779553950749686919152737"
result.53 "0.9999999999999998889776975374843459576368"
result.54 "1.0000000000000000000000000000000000000000"
result.55 "1.0000000000000000000000000000000000000000"
result.56 "1.0000000000000000000000000000000000000000"
result.57 "1.0000000000000000000000000000000000000000"
result.58 "1.0000000000000000000000000000000000000000"
result.59 "1.0000000000000000000000000000000000000000"

How can I print all digits? I guess that's got to do with deeper knowledge of R's math standards

Body:
Package Rmpfr can get more digits of precision. In the example below I will use 100 digits of precision.

library(Rmpfr)

d <- 100
zero <- mpfr(0, precBits = d)
one <- mpfr(1, precBits = d)
powers <- mpfr(2^(1:60), precBits = d)

result <- vector("list", length = length(powers))
temp2 <- zero
for(i in seq_along(powers)) {
  temp2 = temp2 + one/powers[i]
  iszero <- mpfrIs0(one/powers[i])
  result[[i]] <- list(Exp = i, InvIsZero = iszero, Sum = temp2)
}

In the question the OP says that

past the 54th iteration, it does reach one, but it's apparently not
  adding things any more (even increasing the %.40f parameter).

Apparently this has to do with sprintf, not with the results.

With the print.mpfr method:

for(i in 52:60){
  print(result[[i]][[3]], digits = 60)
  flush.console()
}
#1 'mpfr' number of precision  100   bits
#[1] 0.9999999999999997779553950749686919152736663818359375
#1 'mpfr' number of precision  100   bits
#[1] 0.99999999999999988897769753748434595763683319091796875
#1 'mpfr' number of precision  100   bits
#[1] 0.999999999999999944488848768742172978818416595458984375
#1 'mpfr' number of precision  100   bits
#[1] 0.9999999999999999722444243843710864894092082977294921875
#1 'mpfr' number of precision  100   bits
#[1] 0.99999999999999998612221219218554324470460414886474609375
#1 'mpfr' number of precision  100   bits
#[1] 0.999999999999999993061106096092771622352302074432373046875
#1 'mpfr' number of precision  100   bits
#[1] 0.9999999999999999965305530480463858111761510372161865234375
#1 'mpfr' number of precision  100   bits
#[1] 0.99999999999999999826527652402319290558807551860809326171875
#1 'mpfr' number of precision  100   bits
#[1] 0.999999999999999999132638262011596452794037759304046630859375

With sprintf:

for(i in 52:60){
  print(sprintf("%d - %.60f", i, result[[i]][[3]]))
  flush.console()
}
#[1] "52 - 0.999999999999999777955395074968691915273666381835937500000000"
#[1] "53 - 0.999999999999999888977697537484345957636833190917968750000000"
#[1] "54 - 1.000000000000000000000000000000000000000000000000000000000000"
#[1] "55 - 1.000000000000000000000000000000000000000000000000000000000000"
#[1] "56 - 1.000000000000000000000000000000000000000000000000000000000000"
#[1] "57 - 1.000000000000000000000000000000000000000000000000000000000000"
#[1] "58 - 1.000000000000000000000000000000000000000000000000000000000000"
#[1] "59 - 1.000000000000000000000000000000000000000000000000000000000000"
#[1] "60 - 1.000000000000000000000000000000000000000000000000000000000000"


问:
jquery templating - import a file?
I'm working with backbone.js, but as far as I've seen, it doesn't care what templating system you use. Currently I'm trying out mustache.js, but I'm open to other ones. I'm a little annoyed though with the way I have to put a template into a string:

```<code>var context = {
    name: this.model.get('name'),
    email: this.model.get('email')
}

var template = "<form>Name<input name='name' type='text' value='{{name}}' />Email<input name='email' type='text' value='{{email}}' /></form>";

var html = Mustache.to_html(template, context);
    $(this.el).html(html);
    $('#app').html(this.el);
</code>```

I'd like if I could load it from a different file or something somehow. I want to be able to have template files in order to simplify things. For example, if I put it all in a string, I can't have breaks (well I can have html breaks, but that's not the point). After the line starts to get very long, it becomes unmanageable.

Tips?

答:
Updated (4/11/14):

As answered by OP below:

Unfortunately, the jQuery team has moved the templating functionality out of jQuery Core. The code is still available as a library here: github.com/BorisMoore/jquery-tmpl and here: github.com/borismoore/jsrender

Original Answer:

I just used this a couple of hours ago:
http://api.jquery.com/category/plugins/templates/

It's an official jQuery plugin(i.e. the devs endorse it).

This is the function you need to use for loading templates from things other than strings: http://api.jquery.com/template/

Here's the code to have a template in HTML:

```<code><script id="titleTemplate" type="text/x-jquery-tmpl">
  <li>${Name}</li>
</script>
___________

// Compile the inline template as a named template
$( "#titleTemplate" ).template( "summaryTemplate" );

function renderList() {
  // Render the movies data using the named template: "summaryTemplate"
  $.tmpl( "summaryTemplate", movies ).appendTo( "#moviesList" );
}
</code>```

It's in a

Title: jquery templating - import a file?

Body:
I'm working with backbone.js, but as far as I've seen, it doesn't care what templating system you use. Currently I'm trying out mustache.js, but I'm open to other ones. I'm a little annoyed though with the way I have to put a template into a string:

var context = {
    name: this.model.get('name'),
    email: this.model.get('email')
}

var template = "<form>Name<input name='name' type='text' value='{{name}}' />Email<input name='email' type='text' value='{{email}}' /></form>";

var html = Mustache.to_html(template, context);
    $(this.el).html(html);
    $('#app').html(this.el);

I'd like if I could load it from a different file or something somehow. I want to be able to have template files in order to simplify things. For example, if I put it all in a string, I can't have breaks (well I can have html breaks, but that's not the point). After the line starts to get very long, it becomes unmanageable.

Tips?

Body:
Updated (4/11/14):

As answered by OP below:

Unfortunately, the jQuery team has moved the templating functionality out of jQuery Core. The code is still available as a library here: github.com/BorisMoore/jquery-tmpl and here: github.com/borismoore/jsrender

Original Answer:

I just used this a couple of hours ago:
http://api.jquery.com/category/plugins/templates/

It's an official jQuery plugin(i.e. the devs endorse it).

This is the function you need to use for loading templates from things other than strings: http://api.jquery.com/template/

Here's the code to have a template in HTML:

<script id="titleTemplate" type="text/x-jquery-tmpl">
  <li>${Name}</li>
</script>
___________

// Compile the inline template as a named template
$( "#titleTemplate" ).template( "summaryTemplate" );

function renderList() {
  // Render the movies data using the named template: "summaryTemplate"
  $.tmpl( "summaryTemplate", movies ).appendTo( "#moviesList" );
}

It's in a <script> tag, because that's not visible by default.

Note the type="text/x-jquery-tmpl". If you omit that, it will try to parse it as JavaScript(and fail horribly).

Also note that "loading from a different file" is essentially the same as "reading a file" and then "loading from a string".


问:
devise/omniauth - The action 'facebook' could not be found
I'm trying to implement facebook authentication in my app following this guide

I've followed all the steps but get the following error after hitting  login.

```<code>Unknown action

The action 'facebook' could not be found for Devise::OmniauthCallbacksController
</code>```

I've created the file omniauth_callbacks_controller in controllers/users. It has a facebook method defined. Any idea how I should debug?

Adding my routes file  -

```<code>Myapp::Application.routes.draw do
  get "static_pages/home"

  get "static_pages/help"

  get "static_pages/about"

  devise_for :users do
    resources :posts

  end

  root :to => 'static_pages#home'

  devise_for :users, controllers: {omniauth_callbacks: "omniauth_callbacks"}
end
</code>```

答:
I am assuming that your users will be able to login and logout, edit profile, register with facebook or register with email and also you may add Confirmable to devise if you want. You should have extra columns in users table. Something like adding extra fields into your user model first.

rails g migration AddFieledsToUser provider:string uid:string image:string

then run rails db:migrate

Check your users table ensure you have these 3 columns above

Also I am assuming that you you have correctly configured initializers/devise.rb like so: config.omniauth :facebook, 'APP_ID', 'APP_SECRET_KEY', scope: 'email', info_fields: 'email, name' after you've properly created the facebook app. Also assuming you have properly created and configured your omniauth_callbacks_controller.rb based on the gems gem 'omniauth', '~> 1.6' and gem 'omniauth-facebook', '~> 4.0' in your gem file successfully. Just make sure you have all these steps done.

In your routes.rb you can add this:

```<code>devise_for :users,
         path: '',
         path_names: {
           sign_in: 'login',
           sign_out: 'logout',
           edit: 'profile',
           sign_up: 'registration'
         },
         controllers: {
           omniauth_callbacks: 'omniauth_callbacks',
         }
</code>```

I think this is the part you have missed. You can also name the routes whatever you want. Just saying.

Body:
I'm trying to implement facebook authentication in my app following this guide

I've followed all the steps but get the following error after hitting  login.

Unknown action

The action 'facebook' could not be found for Devise::OmniauthCallbacksController

I've created the file omniauth_callbacks_controller in controllers/users. It has a facebook method defined. Any idea how I should debug?

Adding my routes file  -

Myapp::Application.routes.draw do
  get "static_pages/home"

  get "static_pages/help"

  get "static_pages/about"

  devise_for :users do
    resources :posts

  end

  root :to => 'static_pages#home'

  devise_for :users, controllers: {omniauth_callbacks: "omniauth_callbacks"}
end

Body:
I am assuming that your users will be able to login and logout, edit profile, register with facebook or register with email and also you may add Confirmable to devise if you want. You should have extra columns in users table. Something like adding extra fields into your user model first.

rails g migration AddFieledsToUser provider:string uid:string image:string

then run rails db:migrate

Check your users table ensure you have these 3 columns above

Also I am assuming that you you have correctly configured initializers/devise.rb like so: config.omniauth :facebook, 'APP_ID', 'APP_SECRET_KEY', scope: 'email', info_fields: 'email, name' after you've properly created the facebook app. Also assuming you have properly created and configured your omniauth_callbacks_controller.rb based on the gems gem 'omniauth', '~> 1.6' and gem 'omniauth-facebook', '~> 4.0' in your gem file successfully. Just make sure you have all these steps done.

In your routes.rb you can add this:

devise_for :users,
         path: '',
         path_names: {
           sign_in: 'login',
           sign_out: 'logout',
           edit: 'profile',
           sign_up: 'registration'
         },
         controllers: {
           omniauth_callbacks: 'omniauth_callbacks',
         }

I think this is the part you have missed. You can also name the routes whatever you want. Just saying.


问:
How to fix org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: u
I am trying to get the User object which has, besides username and password, a boolean variable that states if it has been deleted or not. The boolean var is called delete. In my database all the user entities are false.

I tried the ClassicalSyntax but it gave another error.

public User loginUser(String username, String password) {
        TypedQuery<User> query = em.createQuery("Select u from User u " + "where u.username LIKE "
                + "?1 AND u.password LIKE " + "?2 AND u.delete =:delete", User.class);
        query.setParameter(1, username);
        query.setParameter(2, password);
        query.setParameter("delete", false);
        User foundUser = query.getSingleResult();
        return foundUser;

    }
```

<p>It works with the other two u definitions u.username and u.password , but when I add u.delete it gives me this error. I expect it to return the object. </p>

<pre class="lang-java prettyprint-override"><code>SEVERE: Servlet.service() for servlet [Jersey Web Application] in context with path [/webproject] threw exception [java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: u near line 1, column 101 [Select u from com.ikubinfo.project.model.User u where u.username LIKE ?1 AND u.password LIKE ?2 AND u.delete =:delete]] with root cause
org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: u near line 1, column 101 [Select u from com.ikubinfo.project.model.User u where u.username LIKE ?1 AND u.password LIKE ?2 AND u.delete =:delete]
    at org.hibernate.hql.internal.ast.QuerySyntaxException.convert(QuerySyntaxException.java:91)
    at org.hibernate.hql.internal.ast.ErrorCounter.throwQueryException(ErrorCounter.java:109)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.parse(QueryTranslatorImpl.java:304)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:203)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:158)
    at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:126)
    at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:88)
    at org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:167)
    at org.hibernate.internal.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:301)
    at org.hibernate.internal.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:236)
    at org.hibernate.internal.SessionImpl.createQuery(SessionImpl.java:1800)
    at org.hibernate.jpa.spi.AbstractEntityManagerImpl.createQuery(AbstractEntityManagerImpl.java:342)
    at com.ikubinfo.project.repository.UserRepository.loginUser(UserRepository.java:34)
    at com.ikubinfo.project.controller.UserResource.deleteUser(UserResource.java:71)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.glassfish.jersey.server.model.internal.ResourceMethodInvocationHandlerFactory.lambda$static$0(ResourceMethodInvocationHandlerFactory.java:52)
    at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher$1.run(AbstractJavaResourceMethodDispatcher.java:124)
    at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.invoke(AbstractJavaResourceMethodDispatcher.java:167)
    at org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$ResponseOutInvoker.doDispatch(JavaResourceMethodDispatcherProvider.java:176)
    at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.dispatch(AbstractJavaResourceMethodDispatcher.java:79)
    at org.glassfish.jersey.server.model.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:469)
    at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:391)
    at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:80)
    at org.glassfish.jersey.server.ServerRuntime$1.run(ServerRuntime.java:253)
    at org.glassfish.jersey.internal.Errors$1.call(Errors.java:248)
    at org.glassfish.jersey.internal.Errors$1.call(Errors.java:244)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:292)
</code>```

答: delete cannot be used as property name, Please try to rename it?

Body:
I am trying to get the User object which has, besides username and password, a boolean variable that states if it has been deleted or not. The boolean var is called delete. In my database all the user entities are false.

I tried the ClassicalSyntax but it gave another error.

public User loginUser(String username, String password) {
        TypedQuery<User> query = em.createQuery("Select u from User u " + "where u.username LIKE "
                + "?1 AND u.password LIKE " + "?2 AND u.delete =:delete", User.class);
        query.setParameter(1, username);
        query.setParameter(2, password);
        query.setParameter("delete", false);
        User foundUser = query.getSingleResult();
        return foundUser;

    }

It works with the other two u definitions u.username and u.password , but when I add u.delete it gives me this error. I expect it to return the object.

SEVERE: Servlet.service() for servlet [Jersey Web Application] in context with path [/webproject] threw exception [java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: u near line 1, column 101 [Select u from com.ikubinfo.project.model.User u where u.username LIKE ?1 AND u.password LIKE ?2 AND u.delete =:delete]] with root cause
org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: u near line 1, column 101 [Select u from com.ikubinfo.project.model.User u where u.username LIKE ?1 AND u.password LIKE ?2 AND u.delete =:delete]
    at org.hibernate.hql.internal.ast.QuerySyntaxException.convert(QuerySyntaxException.java:91)
    at org.hibernate.hql.internal.ast.ErrorCounter.throwQueryException(ErrorCounter.java:109)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.parse(QueryTranslatorImpl.java:304)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:203)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:158)
    at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:126)
    at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:88)
    at org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:167)
    at org.hibernate.internal.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:301)
    at org.hibernate.internal.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:236)
    at org.hibernate.internal.SessionImpl.createQuery(SessionImpl.java:1800)
    at org.hibernate.jpa.spi.AbstractEntityManagerImpl.createQuery(AbstractEntityManagerImpl.java:342)
    at com.ikubinfo.project.repository.UserRepository.loginUser(UserRepository.java:34)
    at com.ikubinfo.project.controller.UserResource.deleteUser(UserResource.java:71)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.glassfish.jersey.server.model.internal.ResourceMethodInvocationHandlerFactory.lambda$static$0(ResourceMethodInvocationHandlerFactory.java:52)
    at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher$1.run(AbstractJavaResourceMethodDispatcher.java:124)
    at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.invoke(AbstractJavaResourceMethodDispatcher.java:167)
    at org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$ResponseOutInvoker.doDispatch(JavaResourceMethodDispatcherProvider.java:176)
    at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.dispatch(AbstractJavaResourceMethodDispatcher.java:79)
    at org.glassfish.jersey.server.model.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:469)
    at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:391)
    at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:80)
    at org.glassfish.jersey.server.ServerRuntime$1.run(ServerRuntime.java:253)
    at org.glassfish.jersey.internal.Errors$1.call(Errors.java:248)
    at org.glassfish.jersey.internal.Errors$1.call(Errors.java:244)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:292)


问:
Cancelling a Socket.xxxxAsync call
After calling Socket.Shutdown, Socket.Close and Socket.Disconnect, it appears that Socket.ReceiveAsync does not abort. Attempts to reuse the SocketAsycEventArgs object used in the ReceiveAsync call (suggested in the documentation as best practice) result in the error:

An asynchronous socket operation is already in progress using this SocketAsyncEventArgs instance

What do I have to do to get ReceiveAsync to release its grip on this SocketAsyncEventArgs instance?

Edit:I have worked around this by flagging a pending receive and not doing any cleanup until the receive comes in (i.e Completed is dispatched). Doesn't feel too good though. Can't it just be aborted, like the WebRequest API?

答:
There does not appear to be a way to abort the asynchronous receive.

When the socket is closed, this forces the receive to complete, and the SocketError property of the SocketAsyncEventArgs parameter to your callback method will have a value of SocketError.OperationAborted.  When this condition is encountered, you can return the SocketAsyncEventArgs object to the reusable pool.

This is demonstrated in the example shown here.  Specifically, look at the ProcessReceive() method, which calls the CloseClientSocket() method when e.BytesTransferred == 0 or e.SocketError != SocketError.Success.  The CloseClientSocket() method is where the SocketAsyncEventArgs object is returned to the pool.

OwnerDisplayName: spender

ContentLicense: CC BY-SA 2.5

Title: Cancelling a Socket.xxxxAsync call

LastEditorDisplayName: spender

OwnerDisplayName: Matt Davis


问:
QShortCut and QSpinBox conflict
I'm writing an application were i use my own shortcut. It looks like this:

```<code>myShortcut= new QShortcut(Qt::SHIFT + Qt::Key_B,this);
connect(myShortcut, SIGNAL(activated()), this, SLOT(setCameraBack()));
</code>```

I defined it in the constructor of main widget and it works fine until i click one of the spinbox buttons which are also located on the main widget. After that my shortcut stop working and it doesn't work until i click push button or check box. When i do that everything is fine again. I'd like to add that after i click spinbox it seems to be "active" (because the cursor is still "blinking" on it) until i click one of the other buttons. Do you have any idea what is wrong? Is it some kind process or event problem? Thanks for all answers
~Marwroc

答: Have you tried MySpinBox -> setFocusPolicy (Qt::NoFocus) ?

Title: QShortCut and QSpinBox conflict

Body:
I'm writing an application were i use my own shortcut. It looks like this:

myShortcut= new QShortcut(Qt::SHIFT + Qt::Key_B,this);
connect(myShortcut, SIGNAL(activated()), this, SLOT(setCameraBack()));

I defined it in the constructor of main widget and it works fine until i click one of the spinbox buttons which are also located on the main widget. After that my shortcut stop working and it doesn't work until i click push button or check box. When i do that everything is fine again. I'd like to add that after i click spinbox it seems to be "active" (because the cursor is still "blinking" on it) until i click one of the other buttons. Do you have any idea what is wrong? Is it some kind process or event problem? Thanks for all answers
~Marwroc


问:
ASP.NET Core OAuth with basic auth for TokenEndpoint
I'm trying to use ASP.Net Core 2.2 with OAuth authentication. To use OAuth I use the AddOAuth method in the public void ConfigureServices(IServiceCollection services)in Startup.cs:

services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = "Provider";
})
.AddCookie()
.AddOAuth("Provider", options =>
{
    options.ClientId = Configuration["Provider:ClientId"];
    options.ClientSecret = Configuration["Provider:ClientSecret"];
    options.CallbackPath = new PathString("/callback");

    options.AuthorizationEndpoint = "https://api.provider.net/auth/code";
    options.TokenEndpoint = "https://api.provider.net/auth/token";
});
```

The problem is, that when the middleware tries to get an authorization code by using the TokenEndpoint, I receive a HTTP 401 because the provider expects a basic authentication header at this endpoint.

My question is, how can I tell the middleware to add a basic auth header to the TokenEndpoint request?

答:
@Kirk Larkin Thanks for posting the link, this helped me alot to came up with a solution!

I  created a DelegateHandler which adds a basic authentication header if the request is send to the TokenEndpoint:

```<code>public class AuthorizingHandler : DelegatingHandler
{
    private readonly OAuthOptions _options;
    public AuthorizingHandler(HttpMessageHandler inner, OAuthOptions options)
        : base(inner)
    {
        _options = options;
    }

    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        if(request.RequestUri == new Uri(_options.TokenEndpoint))
        {
            string credentials = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(_options.ClientId + ":" + _options.ClientSecret));

            request.Headers.Add("Authorization", $"Basic {credentials}");
        }
        return base.SendAsync(request, cancellationToken);
    }
}
</code>```

This DelegateHandler is used in the ConfigureService method:

```<code>public void ConfigureServices(IServiceCollection services)
{
    // ...

    services.AddAuthentication(options =>
    {
        options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        options.DefaultChallengeScheme = "Provider";
    })
    .AddCookie()
    .AddOAuth("Provider", options =>
    {
        options.ClientId = Configuration["Provider:ClientId"];
        options.ClientSecret = Configuration["Provider:ClientSecret"];
        options.CallbackPath = new PathString("/callback");

        options.AuthorizationEndpoint = "https://api.provider.net/auth/code";
        options.TokenEndpoint = "https://api.provider.net/auth/token";

        var innerHandler = new HttpClientHandler();
        options.BackchannelHttpHandler = new AuthorizingHandler(innerHandler, options);

        //...
    });

    // ...
}
</code>```

Body:
I'm trying to use ASP.Net Core 2.2 with OAuth authentication. To use OAuth I use the AddOAuth method in the public void ConfigureServices(IServiceCollection services)in Startup.cs:

services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = "Provider";
})
.AddCookie()
.AddOAuth("Provider", options =>
{
    options.ClientId = Configuration["Provider:ClientId"];
    options.ClientSecret = Configuration["Provider:ClientSecret"];
    options.CallbackPath = new PathString("/callback");

    options.AuthorizationEndpoint = "https://api.provider.net/auth/code";
    options.TokenEndpoint = "https://api.provider.net/auth/token";
});

The problem is, that when the middleware tries to get an authorization code by using the TokenEndpoint, I receive a HTTP 401 because the provider expects a basic authentication header at this endpoint.

My question is, how can I tell the middleware to add a basic auth header to the TokenEndpoint request?

Body:
@Kirk Larkin Thanks for posting the link, this helped me alot to came up with a solution!

I  created a DelegateHandler which adds a basic authentication header if the request is send to the TokenEndpoint:

public class AuthorizingHandler : DelegatingHandler
{
    private readonly OAuthOptions _options;
    public AuthorizingHandler(HttpMessageHandler inner, OAuthOptions options)
        : base(inner)
    {
        _options = options;
    }

    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        if(request.RequestUri == new Uri(_options.TokenEndpoint))
        {
            string credentials = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(_options.ClientId + ":" + _options.ClientSecret));

            request.Headers.Add("Authorization", $"Basic {credentials}");
        }
        return base.SendAsync(request, cancellationToken);
    }
}

This DelegateHandler is used in the ConfigureService method:

public void ConfigureServices(IServiceCollection services)
{
    // ...

    services.AddAuthentication(options =>
    {
        options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        options.DefaultChallengeScheme = "Provider";
    })
    .AddCookie()
    .AddOAuth("Provider", options =>
    {
        options.ClientId = Configuration["Provider:ClientId"];
        options.ClientSecret = Configuration["Provider:ClientSecret"];
        options.CallbackPath = new PathString("/callback");

        options.AuthorizationEndpoint = "https://api.provider.net/auth/code";
        options.TokenEndpoint = "https://api.provider.net/auth/token";

        var innerHandler = new HttpClientHandler();
        options.BackchannelHttpHandler = new AuthorizingHandler(innerHandler, options);

        //...
    });

    // ...
}


问:
How to check for change in array while change is via javascript
I want to know if there is a simple, clean way to listen for an array change in an array in Javascript.

I was attempting to use jQuery's change function but soon realized that it only works when the change is made in the HTML. I need to check if a change is made in Javascript, not HTML.

答:
Yes, object.watch (it's non-standard though). Here's my
  implementation that works in every current major browser.

Listening for variable changes in JavaScript


问:
First HTTPS request takes much more time than the rest
I'm making a python app that needs to make fast HTTP API calls.
I use the python requests package to make API calls on HTTPS.
I noticed that first request always takes much more time than the rest.
This is not due to establishing the HTTP connection because requests.get() establishes a new connection on every call (checked requests with logs).

I investigated my network with Wireshark and although I found that the first request takes more time than the others, the difference is not big.

I also noticed that even if I make the first call to host1 and all the rest to host2, the request to host1 takes much more time than all subsequent requests. That assures me that the issue is not connected to establishing some kind of connection with the host.

I checked with the ping command and didn't find such a difference between the first and subsequent ping requests.

Is it something to do with the OS, requests initial set up on the first request or something else?

My python code:

```<code>import requests
import time
import logging

logging.basicConfig(level=logging.DEBUG)

url = "https://bittrex.com/api/v1.1/public/getorderbook?market=BTC-LTC&type=both"

for i in range(10):
    start = time.time()

    requests.get(url)

    end = time.time()

    print('Time: {}. index: {}'.format(end - start, i))
</code>```

Output:

```<code>DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): bittrex.com
DEBUG:urllib3.connectionpool:https://bittrex.com:443 "GET /api/v1.1/public/getorderbook?market=BTC-LTC&type=both HTTP/1.1" 200 46568
Time: 0.8292889595031738. index: 0
DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): bittrex.com
DEBUG:urllib3.connectionpool:https://bittrex.com:443 "GET /api/v1.1/public/getorderbook?market=BTC-LTC&type=both HTTP/1.1" 200 46568
Time: 0.14321112632751465. index: 1
DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): bittrex.com
DEBUG:urllib3.connectionpool:https://bittrex.com:443 "GET /api/v1.1/public/getorderbook?market=BTC-LTC&type=both HTTP/1.1" 200 46568
Time: 0.10214948654174805. index: 2
DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): bittrex.com
DEBUG:urllib3.connectionpool:https://bittrex.com:443 "GET /api/v1.1/public/getorderbook?market=BTC-LTC&type=both HTTP/1.1" 200 46568
Time: 0.10616683959960938. index: 3
DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): bittrex.com
DEBUG:urllib3.connectionpool:https://bittrex.com:443 "GET /api/v1.1/public/getorderbook?market=BTC-LTC&type=both HTTP/1.1" 200 46568
Time: 0.1061558723449707. index: 4
DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): bittrex.com
DEBUG:urllib3.connectionpool:https://bittrex.com:443 "GET /api/v1.1/public/getorderbook?market=BTC-LTC&type=both HTTP/1.1" 200 46568
Time: 0.09714269638061523. index: 5
DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): bittrex.com
DEBUG:urllib3.connectionpool:https://bittrex.com:443 "GET /api/v1.1/public/getorderbook?market=BTC-LTC&type=both HTTP/1.1" 200 46568
Time: 0.0861358642578125. index: 6
DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): bittrex.com
DEBUG:urllib3.connectionpool:https://bittrex.com:443 "GET /api/v1.1/public/getorderbook?market=BTC-LTC&type=both HTTP/1.1" 200 46568
Time: 0.08713865280151367. index: 7
DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): bittrex.com
DEBUG:urllib3.connectionpool:https://bittrex.com:443 "GET /api/v1.1/public/getorderbook?market=BTC-LTC&type=both HTTP/1.1" 200 46568
Time: 0.09714365005493164. index: 8
DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): bittrex.com
DEBUG:urllib3.connectionpool:https://bittrex.com:443 "GET /api/v1.1/public/getorderbook?market=BTC-LTC&type=both HTTP/1.1" 200 46568
Time: 0.09714889526367188. index: 9
</code>```

答:
I have the same problem too. The first request takes 5s, and others is fast.
I tried to update requests and python, problem still exist. Then I check server's load and network connections, nothing wrong.
I tried this code:

```<code>logging.basicConfig()
logging.getLogger().setLevel(logging.DEBUG)
requests_log = logging.getLogger("requests.packages.urllib3")
requests_log.setLevel(logging.DEBUG)
requests_log.propagate = True
</code>```

It shows that the first DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1) last for 5s.

I also tried use session instead of get, no improvement.

At last I add the domain to /etc/hosts, the problem was solved.

So I think the key is DNS.

Body:
I'm making a python app that needs to make fast HTTP API calls.
I use the python requests package to make API calls on HTTPS.
I noticed that first request always takes much more time than the rest.
This is not due to establishing the HTTP connection because requests.get() establishes a new connection on every call (checked requests with logs).

I investigated my network with Wireshark and although I found that the first request takes more time than the others, the difference is not big.

I also noticed that even if I make the first call to host1 and all the rest to host2, the request to host1 takes much more time than all subsequent requests. That assures me that the issue is not connected to establishing some kind of connection with the host.

I checked with the ping command and didn't find such a difference between the first and subsequent ping requests.

Is it something to do with the OS, requests initial set up on the first request or something else?

My python code:

import requests
import time
import logging

logging.basicConfig(level=logging.DEBUG)

url = "https://bittrex.com/api/v1.1/public/getorderbook?market=BTC-LTC&type=both"

for i in range(10):
    start = time.time()

    requests.get(url)

    end = time.time()

    print('Time: {}. index: {}'.format(end - start, i))

Output:

DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): bittrex.com
DEBUG:urllib3.connectionpool:https://bittrex.com:443 "GET /api/v1.1/public/getorderbook?market=BTC-LTC&type=both HTTP/1.1" 200 46568
Time: 0.8292889595031738. index: 0
DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): bittrex.com
DEBUG:urllib3.connectionpool:https://bittrex.com:443 "GET /api/v1.1/public/getorderbook?market=BTC-LTC&type=both HTTP/1.1" 200 46568
Time: 0.14321112632751465. index: 1
DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): bittrex.com
DEBUG:urllib3.connectionpool:https://bittrex.com:443 "GET /api/v1.1/public/getorderbook?market=BTC-LTC&type=both HTTP/1.1" 200 46568
Time: 0.10214948654174805. index: 2
DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): bittrex.com
DEBUG:urllib3.connectionpool:https://bittrex.com:443 "GET /api/v1.1/public/getorderbook?market=BTC-LTC&type=both HTTP/1.1" 200 46568
Time: 0.10616683959960938. index: 3
DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): bittrex.com
DEBUG:urllib3.connectionpool:https://bittrex.com:443 "GET /api/v1.1/public/getorderbook?market=BTC-LTC&type=both HTTP/1.1" 200 46568
Time: 0.1061558723449707. index: 4
DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): bittrex.com
DEBUG:urllib3.connectionpool:https://bittrex.com:443 "GET /api/v1.1/public/getorderbook?market=BTC-LTC&type=both HTTP/1.1" 200 46568
Time: 0.09714269638061523. index: 5
DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): bittrex.com
DEBUG:urllib3.connectionpool:https://bittrex.com:443 "GET /api/v1.1/public/getorderbook?market=BTC-LTC&type=both HTTP/1.1" 200 46568
Time: 0.0861358642578125. index: 6
DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): bittrex.com
DEBUG:urllib3.connectionpool:https://bittrex.com:443 "GET /api/v1.1/public/getorderbook?market=BTC-LTC&type=both HTTP/1.1" 200 46568
Time: 0.08713865280151367. index: 7
DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): bittrex.com
DEBUG:urllib3.connectionpool:https://bittrex.com:443 "GET /api/v1.1/public/getorderbook?market=BTC-LTC&type=both HTTP/1.1" 200 46568
Time: 0.09714365005493164. index: 8
DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): bittrex.com
DEBUG:urllib3.connectionpool:https://bittrex.com:443 "GET /api/v1.1/public/getorderbook?market=BTC-LTC&type=both HTTP/1.1" 200 46568
Time: 0.09714889526367188. index: 9

Body:
I have the same problem too. The first request takes 5s, and others is fast.
I tried to update requests and python, problem still exist. Then I check server's load and network connections, nothing wrong.
I tried this code:

logging.basicConfig()
logging.getLogger().setLevel(logging.DEBUG)
requests_log = logging.getLogger("requests.packages.urllib3")
requests_log.setLevel(logging.DEBUG)
requests_log.propagate = True

It shows that the first DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1) last for 5s.

I also tried use session instead of get, no improvement.

At last I add the domain to /etc/hosts, the problem was solved.

So I think the key is DNS.


问:
QMake not matching regex for distro detection
I have a C++ project using QMake.  I'm trying to set some compiler options based on a simple test of which Linux distro is running, but the test does not pass.  My qmake file contains:

```<code>OSDISTRO = $$(cat /proc/version)
contains(OSDISTRO, "Ubuntu"): {
  message(Found ubuntu)
}
</code>```

I tested the regex from the command line and it works!

```<code>cat /proc/version | pcregrep "Ubuntu"
Linux version 4.18.0-20-generic (buildd@lcy01-amd64-020) (gcc version 7.3.0 (Ubuntu 7.3.0-16ubuntu3)) #21~18.04.1-Ubuntu SMP Wed May 8 08:43:37 UTC 2019
</code>```

Is there something special about the regex syntax in qmake?  Any reason why this isn't working?

答:
For the RegEx:

This works for me:

```<code>OSDISTRO = $$system(cat /proc/version)
contains(OSDISTRO, .*Ubuntu.*){
  message("Found Ubuntu")
}
</code>```

Note:
The match is case sensitive.

You can use .*[uU]buntu.* for example to match ubuntu and Ubuntu.

Explanation why your solution does not work:

The QMake function contains works with lists of values.

So, the execution of you solution will be like this:

1) First instruction OSDISTRO = $$(cat /proc/version):

QMake will execute $$system(cat /proc/version).

Then the result is splitted (by space as separator) to list of values. OSDISTRO will contain this list.

Assuming that the result is as yours. The result of the first instruction is like this:
OSDISTRO = "Linux" "version" "4.18.0-20-generic"....

2) Second instruction contains(OSDISTRO, "Ubuntu") : message(Found ubuntu):

QMake will search if the variable OSDISTRO contains the value Ubuntu and display the message Found ubuntu if success.

Here in your case, QMake will never find Ubuntu, cause the value which contains it is like this (Ubuntu 7.3.0-16ubuntu3) and QMake search only the value Ubuntu.

Hope it helps you.

Body:
I have a C++ project using QMake.  I'm trying to set some compiler options based on a simple test of which Linux distro is running, but the test does not pass.  My qmake file contains:

OSDISTRO = $$(cat /proc/version)
contains(OSDISTRO, "Ubuntu"): {
  message(Found ubuntu)
}

I tested the regex from the command line and it works!

cat /proc/version | pcregrep "Ubuntu"
Linux version 4.18.0-20-generic (buildd@lcy01-amd64-020) (gcc version 7.3.0 (Ubuntu 7.3.0-16ubuntu3)) #21~18.04.1-Ubuntu SMP Wed May 8 08:43:37 UTC 2019

Is there something special about the regex syntax in qmake?  Any reason why this isn't working?

Body:
For the RegEx:

This works for me:

OSDISTRO = $$system(cat /proc/version)
contains(OSDISTRO, .*Ubuntu.*){
  message("Found Ubuntu")
}

Note:
The match is case sensitive.

You can use .*[uU]buntu.* for example to match ubuntu and Ubuntu.

Explanation why your solution does not work:

The QMake function contains works with lists of values.

So, the execution of you solution will be like this:

1) First instruction OSDISTRO = $$(cat /proc/version):

QMake will execute $$system(cat /proc/version).

Then the result is splitted (by space as separator) to list of values. OSDISTRO will contain this list.

Assuming that the result is as yours. The result of the first instruction is like this:
OSDISTRO = "Linux" "version" "4.18.0-20-generic"....

2) Second instruction contains(OSDISTRO, "Ubuntu") : message(Found ubuntu):

QMake will search if the variable OSDISTRO contains the value Ubuntu and display the message Found ubuntu if success.

Here in your case, QMake will never find Ubuntu, cause the value which contains it is like this (Ubuntu 7.3.0-16ubuntu3) and QMake search only the value Ubuntu.

Hope it helps you.


问:
Proxy a node/react application in an apache server
Using forever to forever run the node server on the virtual machine, I am unable to get the app to run without explicitly adding the port in the url like so: URL.com:8080
If I don't use the port in the URL, I do load up the file structure of the application.

Steps to reproduce: I have a create-react-app application.On the virtual server I run 'npm run build' to make sure I have a build to serve. I then run forever start on the root of the application.

The code below should give all the necessary details. I can provide more if you need.

I have spent so much time tweaking the .conf file to try different configurations but I can't seem to get it. I am using it and successfully hosting two static html sites but not this node application.

Package.json:

```<code>...
"main":"server/index.js",
"proxy":"http://localhost:8080"
...
</code>```

Apache url.conf:

```<code><VirtualHost *:80>
    ServerName URL.com
    ServerAlias URL.com:8080/
    DocumentRoot /var/www/nameOfApp/
<Directory />
    Options -Indexes +FollowSymLinks
    AllowOverride All
</Directory>
<Directory /var/www/nameOfApp/public>
    Options +Indexes +FollowSymLinks +MultiViews
    AllowOverride All
</Directory>
</VirtualHost>
</code>```

Node server file using express:

```<code>app.use(express.static(`${__dirname}/../build`));
</code>```

I've also made sure I have the modules enabled to allow for proxying. So I think essentially, what I need is to request this site and not need the :8080 at the end.

答:
Apache and NodeJS are 2 different and separate application.
You interact with them by sending request to the port that they are listening to. In your case here,

Apache is listening at port 80

Your NodeJS application is listening at port 8080

So all request to port 80 will be handled by Apache, and since you do not has an index.html, Apache will default to just list out the files and directory (Options Indexes). Up until this point, your node application do not know anything about your request.

So what you need to do is define some endpoint, say url.com/node, and tell Apache to forward all request of this endpoint to port 8080 and let your node application to do the job.

How to do this?

http://httpd.apache.org/docs/2.2/mod/mod_proxy.html#proxypass

Best practices when running Node.js with port 80 (Ubuntu / Linode)

Node.js + Nginx - What now?

Hope this points you to the right direction.

Body:
Using forever to forever run the node server on the virtual machine, I am unable to get the app to run without explicitly adding the port in the url like so: URL.com:8080
If I don't use the port in the URL, I do load up the file structure of the application.

Steps to reproduce: I have a create-react-app application.On the virtual server I run 'npm run build' to make sure I have a build to serve. I then run forever start on the root of the application.

The code below should give all the necessary details. I can provide more if you need.

I have spent so much time tweaking the .conf file to try different configurations but I can't seem to get it. I am using it and successfully hosting two static html sites but not this node application.

Package.json:

...
"main":"server/index.js",
"proxy":"http://localhost:8080"
...

Apache url.conf:

<VirtualHost *:80>
    ServerName URL.com
    ServerAlias URL.com:8080/
    DocumentRoot /var/www/nameOfApp/
<Directory />
    Options -Indexes +FollowSymLinks
    AllowOverride All
</Directory>
<Directory /var/www/nameOfApp/public>
    Options +Indexes +FollowSymLinks +MultiViews
    AllowOverride All
</Directory>
</VirtualHost>

Node server file using express:

app.use(express.static(`${__dirname}/../build`));

I've also made sure I have the modules enabled to allow for proxying. So I think essentially, what I need is to request this site and not need the :8080 at the end.


答:
Another option is to escape it in the entity class:
@Column(name = "\"delete\"")

Title: How to fix org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: u


问:
c# Array of delegate references
When referencing other classes we use delegates. During unit testing we override these values.

I have a class which references over 20 other classes, so I thought I'd create an array of delegates. If I create a static array of these delegates (see code below) it stores the values of the delegates, not the reference to the delegate.

As a result the unit tests can't update the values. To work around this I've created the array of delegates when I want to use them but I'd like the code below to work.

```<code>private static Func<int, bool> firstMethod = ExternalClass1.Method;
private static Func<int, bool> secondMethod = ExternalClass2.Method;
private static Func<int, bool> thirdMethod = ExternalClass3.Method;

private static Func<int, bool>[] handlers = { first, second, third };

public bool Test(int value)
{
    foreach (var handler in handlers)
    {
        if (handler.Invoke(value) == true)
        {
             return true;
        }
    }

    return false;
}
</code>```

答:
Instead of creating this handlers array, you can do something like this:

```<code>private static IEnumerable<Func<int,bool>> GetHandlers()
{
    yield return firstMethod;
    yield return secondMethod;
    yield return thirdMethod;
}
</code>```

Now you have a way to get the actual field references so they can be replaced for unit tests, but also have a way to iterate over all of the handlers.  That said, an array of delegates that can be replaced is basically an interface or set of abstract methods that can be overridden.  It might be cleaner and easier to maintain if you implement polymorphism using the language features designed to provide it.  For the convenience of swapping out behavior using delegates during your unit tests, you can use mocking frameworks like Moq to mock an interface without having to write specific test classes.

-Dan

Title: c# Array of delegate references

Body:
When referencing other classes we use delegates. During unit testing we override these values.

I have a class which references over 20 other classes, so I thought I'd create an array of delegates. If I create a static array of these delegates (see code below) it stores the values of the delegates, not the reference to the delegate.

As a result the unit tests can't update the values. To work around this I've created the array of delegates when I want to use them but I'd like the code below to work.

private static Func<int, bool> firstMethod = ExternalClass1.Method;
private static Func<int, bool> secondMethod = ExternalClass2.Method;
private static Func<int, bool> thirdMethod = ExternalClass3.Method;

private static Func<int, bool>[] handlers = { first, second, third };

public bool Test(int value)
{
    foreach (var handler in handlers)
    {
        if (handler.Invoke(value) == true)
        {
             return true;
        }
    }

    return false;
}

Body:
Instead of creating this handlers array, you can do something like this:

private static IEnumerable<Func<int,bool>> GetHandlers()
{
    yield return firstMethod;
    yield return secondMethod;
    yield return thirdMethod;
}

Now you have a way to get the actual field references so they can be replaced for unit tests, but also have a way to iterate over all of the handlers.  That said, an array of delegates that can be replaced is basically an interface or set of abstract methods that can be overridden.  It might be cleaner and easier to maintain if you implement polymorphism using the language features designed to provide it.  For the convenience of swapping out behavior using delegates during your unit tests, you can use mocking frameworks like Moq to mock an interface without having to write specific test classes.

-Dan


问:
Python regex match certain floating point numbers
I'm trying to match: 0 or more numbers followed by a dot followed by ( (0 or more numbers) but not (if followed by a d,D, or _))

Some examples and what should match/not:

match:

```<code>['1.0','1.','0.1','.1','1.2345']
</code>```

not match:

```<code>['1d2','1.2d3','1._dp','1.0_dp','1.123165d0','1.132_dp','1D5','1.2356D6']
</code>```

Currently i have:

```<code>"([0-9]*\.)([0-9]*(?!(d|D|_)))"
</code>```

Which correctly matches everything in the match list. But for those in the things it should not match it incorrectly matches on:

```<code>['1.2d3','1.0_dp','1.123165d0','1.132_dp','1.2356D6']
</code>```

and correctly does not match on:

```<code>['1d2','1._dp','1D5']
</code>```

So it appears i have problem with the ([0-9]*(?!(d|D|_)) part which is trying to not match if there is a d|D|_ after the dot (with zero or more numbers in-between). Any suggestions?

答:
Instead of using a negative lookahead, you might use a negated character class to match any character that is not in the character class.

If you only want to match word characters without the dD_ or a whitespace char you could use [^\W_Dd\s].

You might also remove the \W and \s to match all except dD_

```<code>^[0-9]*\.[^\W_Dd\s]*$
</code>```

Explanation

^ Start of string

[0-9]*\. Match 0+ times a digit 0-9 followed by a dot

[^\W_Dd\s]* Negated character class, match 0+ times a word character without _ D d or whitespace char

$ End of string

Regex demo

If you don't want to use anchors to assert the start and the end of the string you could also use lookarounds to assert what is on the left and right is not a non whitspace char:

```<code>(?<!\S)[0-9]*\.[^\W_Dd\s]*(?!\S)
</code>```

Regex demo

Body:
I'm trying to match: 0 or more numbers followed by a dot followed by ( (0 or more numbers) but not (if followed by a d,D, or _))

Some examples and what should match/not:

match:

['1.0','1.','0.1','.1','1.2345']

not match:

['1d2','1.2d3','1._dp','1.0_dp','1.123165d0','1.132_dp','1D5','1.2356D6']

Currently i have:

"([0-9]*\.)([0-9]*(?!(d|D|_)))"

Which correctly matches everything in the match list. But for those in the things it should not match it incorrectly matches on:

['1.2d3','1.0_dp','1.123165d0','1.132_dp','1.2356D6']

and correctly does not match on:

['1d2','1._dp','1D5']

So it appears i have problem with the ([0-9]*(?!(d|D|_)) part which is trying to not match if there is a d|D|_ after the dot (with zero or more numbers in-between). Any suggestions?

Body:
Instead of using a negative lookahead, you might use a negated character class to match any character that is not in the character class.

If you only want to match word characters without the dD_ or a whitespace char you could use [^\W_Dd\s].

You might also remove the \W and \s to match all except dD_

^[0-9]*\.[^\W_Dd\s]*$

Explanation

^ Start of string

[0-9]*\. Match 0+ times a digit 0-9 followed by a dot

[^\W_Dd\s]* Negated character class, match 0+ times a word character without _ D d or whitespace char

$ End of string

Regex demo

If you don't want to use anchors to assert the start and the end of the string you could also use lookarounds to assert what is on the left and right is not a non whitspace char:

(?<!\S)[0-9]*\.[^\W_Dd\s]*(?!\S)

Regex demo


问:
Navigation Component - Problem with Livedata lifecycle
I'm beginning with navigation components and I'm facing some problem with a livedata observer.

For example:
I have this livedata, who manage auth response from server.

```<code>viewModel.authenticate.observe(this, Observer {
        manageAuthResponse(it)
        })
</code>```

Everything works fine, and I go to Fragment B.
But when I'm in Fragment B, and I try to go back to Fragment A (who contains that livedata), the Observer fires again with the previous result (SUCCESS).

How can I prevent this?

When I go back, I want to refresh this result and prevent livedata observer to be fired.

答:
Wrap your LiveData object in a ConsumableValue like this

```<code>class ConsumableValue<T>(private val data: T) {

    private var consumed = false

    fun consume(block: ConsumableValue<T>.(T) -> Unit) {
        if (!consumed) {
            consumed = true
            block(data)
        }
    }
}
</code>```

then in viewmodel

```<code>val authenticate = MutableLiveData<Consumable<AuthenticationObject>>()
</code>```

and in your fragment

```<code>viewModel.authenticate.observe(this, Observer { consumable ->
        consumable.consume {
            manageAuthResponse(it)
        }
    })
</code>```

Body:
I'm beginning with navigation components and I'm facing some problem with a livedata observer.

For example:
I have this livedata, who manage auth response from server.

viewModel.authenticate.observe(this, Observer {
        manageAuthResponse(it)
        })

Everything works fine, and I go to Fragment B.
But when I'm in Fragment B, and I try to go back to Fragment A (who contains that livedata), the Observer fires again with the previous result (SUCCESS).

How can I prevent this?

When I go back, I want to refresh this result and prevent livedata observer to be fired.

Body:
Wrap your LiveData object in a ConsumableValue like this

class ConsumableValue<T>(private val data: T) {

    private var consumed = false

    fun consume(block: ConsumableValue<T>.(T) -> Unit) {
        if (!consumed) {
            consumed = true
            block(data)
        }
    }
}

then in viewmodel

val authenticate = MutableLiveData<Consumable<AuthenticationObject>>()

and in your fragment

viewModel.authenticate.observe(this, Observer { consumable ->
        consumable.consume {
            manageAuthResponse(it)
        }
    })


问:
bookdown-demo Can Build pdf and epub, but have error with gitbook creation
I am trying to create the HTML output in gitbook format for the demo Bookdown files. When I go to build I receive the following error:

I am using RStudio Version 1.1.463, r Version 3.5.3, and MiKTeX Version 2.9

I have no problems creating the pdf or epub versions of the demo book

My Workspace is on a separate logical drive, D:\R-Work\bookdown-demo-master, as I don't want any of my work saved in the mapped network documents folder.

My r library files are located in \\DRIFTWOODDC\Student\steven.taylor\My Documents\R\win-library\3.5

My _output.yml file has not been changed from the originally downloaded version:

```<code>bookdown::gitbook:
  css: style.css
  config:
    toc:
      before: |
        <li><a href="./">A Minimal Book Example</a></li>
      after: |
        <li><a href="https://github.com/rstudio/bookdown" target="blank">Published with bookdown</a></li>
    edit: https://github.com/rstudio/bookdown-demo/edit/master/%s
    download: ["pdf", "epub"]
bookdown::pdf_book:
  includes:
    in_header: preamble.tex
  latex_engine: xelatex
  citation_package: natbib
  keep_tex: yes
bookdown::epub_book: default
</code>```

I am expecting RStudio to create the html files for the gitbook output, but none are created and I receive the following error:

```<code>==> rmarkdown::render_site(output_format = 'bookdown::gitbook', encoding = 'UTF-8')

Error in system.file(..., package = "bookdown", mustWork = TRUE) :
  no file found
Calls: <Anonymous> ... do.call -> <Anonymous> -> bookdown_file -> system.file
Execution halted

Exited with status 1.
</code>```

I have the same symptoms and issues if I try to create the bookdown-crc template files in gitbook format. I can create the pdf and epub, but not the html output.

答:
I performed the following actions to troubleshoot:

Uninstall and Reinstall R and R Studio both to new logical drive instead of default location.

Changed the R_USER_LIBS environment variable to where I wanted the library files to be installed on the new logical drive. I installed all extra libraries via to command line instead of letting the libraries auto-install when they were missing during the build process.

It seems that there is an issue using networked drives for the R Libraries. By default on my Windows work computer the R Libraries were put into the "My Documents" folder.

Second successful method was to install RPortable and RStudioPortable on a USB Drive and use the portable version to generate the bookdown::gitbook.

Body:
I am trying to create the HTML output in gitbook format for the demo Bookdown files. When I go to build I receive the following error:

I am using RStudio Version 1.1.463, r Version 3.5.3, and MiKTeX Version 2.9

I have no problems creating the pdf or epub versions of the demo book

My Workspace is on a separate logical drive, D:\R-Work\bookdown-demo-master, as I don't want any of my work saved in the mapped network documents folder.

My r library files are located in \\DRIFTWOODDC\Student\steven.taylor\My Documents\R\win-library\3.5

My _output.yml file has not been changed from the originally downloaded version:

bookdown::gitbook:
  css: style.css
  config:
    toc:
      before: |

A Minimal Book Example

      after: |

Published with bookdown

    edit: https://github.com/rstudio/bookdown-demo/edit/master/%s
    download: ["pdf", "epub"]
bookdown::pdf_book:
  includes:
    in_header: preamble.tex
  latex_engine: xelatex
  citation_package: natbib
  keep_tex: yes
bookdown::epub_book: default

I am expecting RStudio to create the html files for the gitbook output, but none are created and I receive the following error:

==> rmarkdown::render_site(output_format = 'bookdown::gitbook', encoding = 'UTF-8')

Error in system.file(..., package = "bookdown", mustWork = TRUE) :
  no file found
Calls: <Anonymous> ... do.call -> <Anonymous> -> bookdown_file -> system.file
Execution halted

Exited with status 1.

I have the same symptoms and issues if I try to create the bookdown-crc template files in gitbook format. I can create the pdf and epub, but not the html output.


问:
importing js file into ts file
I've already read several posts concerning this. My approach was working yesterday but today it is failing. I'm importing a js file into a ts file. allowJs is set to true in tsconfig.json.

Getting the following error:

```<code>ERROR in src/app/core/input-parser.service.ts(5,26): error TS2497: Module '".../dashboard/shared/models/ecn-info"' resolves to a non-module entity and cannot be imported using this construct.
</code>```

input-parser.service.ts:

```<code>import * as EcnInfo from '../../../../shared/models/ecn-info';
</code>```

ecn-info.js:

```<code>class EcnInfo {
  constructor(name, structure, status) {
    this.name = name;
    this.structure = structure;
    this.status = status;
  }
}

module.exports = EcnInfo;
</code>```

答:
Use an export default in your ecn-info.js file:

```<code>export default class EcnInfo {
    constructor(name, structure, status) {
        this.name = name;
        this.structure = structure;
        this.status = status;
    }
}
</code>```

Disable noImplicitAny in your tsconfig.json:

```<code>{
  "compilerOptions": {
    "noImplicitAny": false
    ...
  }
}
</code>```

Import like this:

```<code>import EcnInfo from '../../../../shared/models/ecn-info';
</code>```

Update

Here is an approach without using default export:

Use an export in your ecn-info.js file:

```<code>export class EcnInfo {
    constructor(name, structure, status) {
        this.name = name;
        this.structure = structure;
        this.status = status;
    }
}
</code>```

Disable noImplicitAny in your tsconfig.json:

```<code>{
  "compilerOptions": {
    "noImplicitAny": false
    ...
  }
}
</code>```

Import like this:

```<code>import {EcnInfo} from '../../../../shared/models/ecn-info';
</code>```

Title: importing js file into ts file

Body:
I've already read several posts concerning this. My approach was working yesterday but today it is failing. I'm importing a js file into a ts file. allowJs is set to true in tsconfig.json.

Getting the following error:

ERROR in src/app/core/input-parser.service.ts(5,26): error TS2497: Module '".../dashboard/shared/models/ecn-info"' resolves to a non-module entity and cannot be imported using this construct.

input-parser.service.ts:

import * as EcnInfo from '../../../../shared/models/ecn-info';

ecn-info.js:

class EcnInfo {
  constructor(name, structure, status) {
    this.name = name;
    this.structure = structure;
    this.status = status;
  }
}

module.exports = EcnInfo;

Body:
Use an export default in your ecn-info.js file:

export default class EcnInfo {
    constructor(name, structure, status) {
        this.name = name;
        this.structure = structure;
        this.status = status;
    }
}

Disable noImplicitAny in your tsconfig.json:

{
  "compilerOptions": {
    "noImplicitAny": false
    ...
  }
}

Import like this:

import EcnInfo from '../../../../shared/models/ecn-info';

Update

Here is an approach without using default export:

Use an export in your ecn-info.js file:

export class EcnInfo {
    constructor(name, structure, status) {
        this.name = name;
        this.structure = structure;
        this.status = status;
    }
}

Disable noImplicitAny in your tsconfig.json:

{
  "compilerOptions": {
    "noImplicitAny": false
    ...
  }
}

Import like this:

import {EcnInfo} from '../../../../shared/models/ecn-info';


问:
Count number of children recursively in Javascript/Typescript/ES6
I'm looking for a recursive method that would give me the count of all items with children.

I am currently just looking three levels deep and incrementing a counter when I find that an item has children.

However I want to be able to recursively check until no children are present in the array.

```<code>[
    {
        id: 2,
        name: 'parent',
        children: [
            {
                id: 12,
                name: 'firstChild',
                children: [
                    {
                        id: 22,
                        name: 'firstGrandChild',
                        children: [
                            {
                                id: 32,
                                name: 'GreatGrandChild',
                                children: []
                            }
                        ]
                    }
                ]
            },
            {
                id: 3,
                name: 'secondRowFirstChild',
                children: [
                    {
                        id: 13,
                        name: 'secondRowGrandChild',
                        children: []
                    }
                ]
            },
            {
                id: 4,
                name: 'thirdRowFirstChild',
                children: [
                    {
                        id: 14,
                        name: 'thirdRowGrandChild',
                        children: []
                    }
                ]
            }
        ]
    }
]

// Here is the procedural code that I want to convert

getExpandableRowCount(items: TableRow[]): number {
    let count = 0

    items.map(item => {
        if (item.children && item.children.length) {
            count++;
            item.children.map(subItem => {
                if (subItem.children && subItem.children.length) {
                    count++;
                    subItem.children.map(subSubItem => {
                        if (subSubItem.children && subSubItem.children.length) {
                            count++;
                        }
                    })
                }
            })
        }
    });

  return count;
}
</code>```

I expect the count to be 5.

答:
You can use Array.reduce(), and if an item has children with a length greater than 0, add 1, call count on them, and add to the total:

const count = arr => arr.reduce((r, { children = [] }) =>
  children.length ? r + 1 + count(children) : r
, 0)

const data = [{"id":2,"name":"parent","children":[{"id":12,"name":"firstChild","children":[{"id":22,"name":"firstGrandChild","children":[{"id":32,"name":"GreatGrandChild","children":[]}]}]},{"id":3,"name":"secondRowFirstChild","children":[{"id":13,"name":"secondRowGrandChild","children":[]}]},{"id":4,"name":"thirdRowFirstChild","children":[{"id":14,"name":"thirdRowGrandChild","children":[]}]}]}]

const result = count(data)

console.log(result)```

Body:
I'm looking for a recursive method that would give me the count of all items with children.

I am currently just looking three levels deep and incrementing a counter when I find that an item has children.

However I want to be able to recursively check until no children are present in the array.

[
    {
        id: 2,
        name: 'parent',
        children: [
            {
                id: 12,
                name: 'firstChild',
                children: [
                    {
                        id: 22,
                        name: 'firstGrandChild',
                        children: [
                            {
                                id: 32,
                                name: 'GreatGrandChild',
                                children: []
                            }
                        ]
                    }
                ]
            },
            {
                id: 3,
                name: 'secondRowFirstChild',
                children: [
                    {
                        id: 13,
                        name: 'secondRowGrandChild',
                        children: []
                    }
                ]
            },
            {
                id: 4,
                name: 'thirdRowFirstChild',
                children: [
                    {
                        id: 14,
                        name: 'thirdRowGrandChild',
                        children: []
                    }
                ]
            }
        ]
    }
]

// Here is the procedural code that I want to convert

getExpandableRowCount(items: TableRow[]): number {
    let count = 0

    items.map(item => {
        if (item.children && item.children.length) {
            count++;
            item.children.map(subItem => {
                if (subItem.children && subItem.children.length) {
                    count++;
                    subItem.children.map(subSubItem => {
                        if (subSubItem.children && subSubItem.children.length) {
                            count++;
                        }
                    })
                }
            })
        }
    });

  return count;
}

I expect the count to be 5.


问:
Is it possible to obtain a human-readable record of all transactions on a SQL Server database?
For example, a log that shows when which value was changed from what to what in which table, row and field?</p>

答:
Apart from investigating a particular issue, its NOT recommended to use Transaction log for this purpose. There are many issues one in particular is reading from it when there are concurrent transactions which can cause access violation errors.

http://www.sqlservercentral.com/blogs/hugo/archive/2009/01/17/it-s-minus-twenty-five-outside-and-i-m-writing-about-transaction-log-files.aspx

As others have pointed out, roll out your own or use Change Data Capture (CDC) or Change Tracking (CT) if you are using SQL Server 2008 & above.


问:
How do I define plugin in Kotlin?
I am currently rewriting my small minecraft plugin project from java to kotlin, and I would like to use the BukkitScheduler. For that I need to define plugin, which I have no clue how to do in Kotlin.

My question is, how to 'translate' my java code to kotlin?

Note: I am still a beginner in kotlin, and I learn as i move forward with my project. I have also posted this on the spigot forums, but since most of the people there work with java, I believe I'm going to receive an answer faster here.

Thanks!

private Main plugin;

    public ClassName(Main plugin){
        this.plugin = plugin;
        }
```

答:
There is a pretty helpful wiki post on Spigot about how to set up your workspace that you can find here.

Besides that things should work pretty much the same as a normal plugin in Java. Here's how creating your plugin would work:

```<code>class Main : JavaPlugin() {
    override fun onEnable() {

    }
}
</code>```

and then in ClassName you'd have the following:

```<code>class ClassName(private val plugin: Main) {

}
</code>```

The above code is equivalent to the following code snippets:

```<code>public class Main extends JavaPlugin {
    @Override
    public void onEnable() {
        ClassName className = new ClassName();
    }
}
</code>```

and

```<code>public class ClassName {
    private Main plugin;
    public ClassName(Main plugin) {
        this.plugin = plugin;
    }
}
</code>```

Just a heads up, if you write something in Java and want to see how to do it in Kotlin, IntelliJ will convert it for you. All you need to do is right click on the file and at the bottom there will be "Convert Java File to Kotlin File".

Title: How do I define plugin in Kotlin?

Body:
There is a pretty helpful wiki post on Spigot about how to set up your workspace that you can find here.

Besides that things should work pretty much the same as a normal plugin in Java. Here's how creating your plugin would work:

class Main : JavaPlugin() {
    override fun onEnable() {

    }
}

and then in ClassName you'd have the following:

class ClassName(private val plugin: Main) {

}

The above code is equivalent to the following code snippets:

public class Main extends JavaPlugin {
    @Override
    public void onEnable() {
        ClassName className = new ClassName();
    }
}

and

public class ClassName {
    private Main plugin;
    public ClassName(Main plugin) {
        this.plugin = plugin;
    }
}

Just a heads up, if you write something in Java and want to see how to do it in Kotlin, IntelliJ will convert it for you. All you need to do is right click on the file and at the bottom there will be "Convert Java File to Kotlin File".


问:
Invalid block tag: 'endblock' django
I am getting this error (Invalid block tag: 'endblock') pointing to the line number 12. I have no idea why, because my blocks seems okay to me.</p>
```<code>1{% extends 'base.html' %} <!-- tells that you use the base for most of the look -->
3
4       {% block jumbotron}
5           <div class="jumbotron">
6             <div class="container">
7               <h1>Connect your world</h1>
8               <p>This is a template .</p>
9               <p><a class="btn btn-primary btn-lg" href="#" role="button">Learn more »</a></p>
10            </div>
11          </div>
12      {% endblock %}
</code>```

答:
I would use the template tags like below:</p>

```<code>{% block jumbotron %}

    <div></div>

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

Title: Invalid block tag: 'endblock' django

Body:
I am getting this error (Invalid block tag: 'endblock') pointing to the line number 12. I have no idea why, because my blocks seems okay to me.

1{% extends 'base.html' %}
3
4       {% block jumbotron}
5

6

7
Connect your world

8
This is a template .

9
Learn more »

10

11

12      {% endblock %}

Body:
I would use the template tags like below:

{% block jumbotron %}

    <div></div>

{% endblock jumbotron %}


问:
Can't access variable (array) from another function (defined in global scope)
I'd like to use a variable (array) from another function. I already defined it in global scope, but it doesn't work..

Here is my code for better understanding:

```<code>var globalData = '';
var data = '';

$.getJSON('https://...' + data[x].id + '.json', function(data) {

    globalData = data;
    data = globalData.name;

    console.log(data); // works just fine

    if (condition === 1) {
        function2(); // calls this function
    } else {
        function3();
    }
});

function function2() {
    console.log(data); // just an empty line
    console.log(globalData); // UPDATE: works just fine
}
</code>```

答: You are using the same variable name for two different things. You have a variable named data in your global scope and the getJSON callback function parameter also has a parameter called data which hides the data global variable. Also, inside that callback, you are modifying the data variable. If you intend to modify the data passed as parameter, this is not a good practice.

Body:
I'd like to use a variable (array) from another function. I already defined it in global scope, but it doesn't work..

Here is my code for better understanding:

var globalData = '';
var data = '';

$.getJSON('https://...' + data[x].id + '.json', function(data) {

    globalData = data;
    data = globalData.name;

    console.log(data); // works just fine

    if (condition === 1) {
        function2(); // calls this function
    } else {
        function3();
    }
});

function function2() {
    console.log(data); // just an empty line
    console.log(globalData); // UPDATE: works just fine
}


问:
Stackdriver advanced filter query without wildcards
I have logs being sent in JSON format to Stackdriver, each which contains an entry like:

name: pipeline.<application>.process

where <application> is a variable length string that represents various components in our system.

I would like a query to get all such logs, however, don't know how to do so given that stackdriver doesn't support wildcards or regex.

Ideally, something like a pipeline.*.process would be great, but I can't figure it out from the docs. Equally, <application> takes >40 forms, and so I don't want to create a custom metric for every one.

答:
Filtering for

```<code>jsonPayload.name: "pipeline."
jsonPayload.name: ".process"
</code>```

should give you the results you want

If you're interested in building a metric you can create a single log based metric that extracts the  portion of the name value: https://cloud.google.com/logging/docs/logs-based-metrics/labels

Body:
Filtering for

jsonPayload.name: "pipeline."
jsonPayload.name: ".process"

should give you the results you want

If you're interested in building a metric you can create a single log based metric that extracts the  portion of the name value: https://cloud.google.com/logging/docs/logs-based-metrics/labels


问:
VideoView: Fullscreen on doubleTap
Basically, what I want to do in my application is displaying a video.

The best tool to achieve this goal seem to be a VideoView.

So I used this code:

```<code><VideoView android:id="@+id/videoview" android:layout_width="50dip" android:layout_height="50dip"></VideoView>
</code>```

and in my Activity:

```<code> VideoView videoHolder = (VideoView)findViewById(R.id.videoview);
 videoHolder.setMediaController(new MediaController(this));
 videoHolder.setVideoURI(Uri.parse("android.resource://com.blabla.blabla/" + R.raw.blabla));
 videoHolder.requestFocus();
 videoHolder.start();
</code>```

and that do the trick.

Unfortunately, I was expecting having a preview (thumbnail) of the video in my layout by default

So , I removed the videoHolder.start(); command, but I can only get a blackscreen. The video start when tapping on an invisible zone...

First question

Is that possible to display a preview of the video in the VideoView before starting it?

Second question

I wuld like to display the video on Fullscreen when double tapping the webview, How can I achieve this?

Thank a lot for any help / link / suggestion

答:
Yes, you can get video thumbnails using ThumbnailUtils:

```<code>Bitmap thumb = ThumbnailUtils.createVideoThumbnail(path,
    MediaStore.Images.Thumbnails.MINI_KIND);
</code>```

I haven't really seen apps toggle into fullscreen before. I'm actually not sure if it can be done (especially for a VideoView). However, you might have some luck with one of these methods:

Holding the VideoView in a FrameLayout and then changing its layout parameters.

Overlaying the VideoView via Window#addContentView.

Hiding (via Visibility.GONE) your other views and allowing the VideoView to expand its layout area.

Title: VideoView: Fullscreen on doubleTap

Body:
Basically, what I want to do in my application is displaying a video.

The best tool to achieve this goal seem to be a VideoView.

So I used this code:

<VideoView android:id="@+id/videoview" android:layout_width="50dip" android:layout_height="50dip"></VideoView>

and in my Activity:

 VideoView videoHolder = (VideoView)findViewById(R.id.videoview);
 videoHolder.setMediaController(new MediaController(this));
 videoHolder.setVideoURI(Uri.parse("android.resource://com.blabla.blabla/" + R.raw.blabla));
 videoHolder.requestFocus();
 videoHolder.start();

and that do the trick.

Unfortunately, I was expecting having a preview (thumbnail) of the video in my layout by default

So , I removed the videoHolder.start(); command, but I can only get a blackscreen. The video start when tapping on an invisible zone...

First question

Is that possible to display a preview of the video in the VideoView before starting it?

Second question

I wuld like to display the video on Fullscreen when double tapping the webview, How can I achieve this?

Thank a lot for any help / link / suggestion

Body:
Yes, you can get video thumbnails using ThumbnailUtils:

Bitmap thumb = ThumbnailUtils.createVideoThumbnail(path,
    MediaStore.Images.Thumbnails.MINI_KIND);

I haven't really seen apps toggle into fullscreen before. I'm actually not sure if it can be done (especially for a VideoView). However, you might have some luck with one of these methods:

Holding the VideoView in a FrameLayout and then changing its layout parameters.

Overlaying the VideoView via Window#addContentView.

Hiding (via Visibility.GONE) your other views and allowing the VideoView to expand its layout area.


问:
How to add RateYo to Django project
I plan on using the RateYo jQuery plugin within my Django project but there are a variety of parts I plan on changing and therefore I would like to have all the files directly within my project (unless I can easily modify RateYo options with CDNjs imports)

The official RateYo website shows a variety of methods of implementation but with a Django project structure, I'm not quite sure how to adapt the installation guide.

I have the following project architecture:

```<code>PWEB
 |--> exchange
 |      |--> __pycache__
 |      |--> migrations
 |      |--> static
 |      |      |--> exchange
 |      |      |      |--> assets
 |      |      |      |      |--> css
 |      |      |      |      |     |--> *.css
 |      |      |      |      |--> fonts
 |      |      |      |      |--> js
 |      |      |      |      |     |--> ..., jquery.min.js, jquery2.min.js, ...
 |      |      |      |      |--> sass
 |      |      |      |--> images
 |      |--> templates
 |      |      |--> exchange
 |      |      |      |--> *.html
 |      |--> *.py
 |--> PWEB
 |      |--> __pycache__
 |      |--> *.py
 |--> manage.py
 |--> *.*
</code>```

As you can see, I already have a jquery.min.js file in my project (even a second one). Should I add the file within the RateYo zip archive as jquery3.min.js and watch out what file I use since I'll have 3?

I'm a little lost of where all the files should go to not break what I already have.

The files contained in the RateYo.zip are
index.html,
jquery.min.js,
jquery.rateyo.css,
jquery.rateyo.js,
jquery.rateyo.less,
jquery.rateyo.min.css,
jquery.rateyo.min.css.map,
jquery.rateyo.min.js,
jquery.rateyo.min.js.map

答:
It appears the best solution for this installation would be to place all of these files in your JS folder (if you don't have one, make one) and then reference those files in your HTML file or whatever "index" file you have (as well as any other page where you use jQuery plus the plugin.

https://hannahdnallen.wordpress.com/2014/02/20/steps-to-installing-a-jquery-plugin/

Title: How to add RateYo to Django project

Body:
I plan on using the RateYo jQuery plugin within my Django project but there are a variety of parts I plan on changing and therefore I would like to have all the files directly within my project (unless I can easily modify RateYo options with CDNjs imports)

The official RateYo website shows a variety of methods of implementation but with a Django project structure, I'm not quite sure how to adapt the installation guide.

I have the following project architecture:

PWEB
 |--> exchange
 |      |--> __pycache__
 |      |--> migrations
 |      |--> static
 |      |      |--> exchange
 |      |      |      |--> assets
 |      |      |      |      |--> css
 |      |      |      |      |     |--> *.css
 |      |      |      |      |--> fonts
 |      |      |      |      |--> js
 |      |      |      |      |     |--> ..., jquery.min.js, jquery2.min.js, ...
 |      |      |      |      |--> sass
 |      |      |      |--> images
 |      |--> templates
 |      |      |--> exchange
 |      |      |      |--> *.html
 |      |--> *.py
 |--> PWEB
 |      |--> __pycache__
 |      |--> *.py
 |--> manage.py
 |--> *.*

As you can see, I already have a jquery.min.js file in my project (even a second one). Should I add the file within the RateYo zip archive as jquery3.min.js and watch out what file I use since I'll have 3?

I'm a little lost of where all the files should go to not break what I already have.

The files contained in the RateYo.zip are
index.html,
jquery.min.js,
jquery.rateyo.css,
jquery.rateyo.js,
jquery.rateyo.less,
jquery.rateyo.min.css,
jquery.rateyo.min.css.map,
jquery.rateyo.min.js,
jquery.rateyo.min.js.map