问:
Display 2 tables in 1 view
I want to display 2 tables in 1 view

like this:

```<code>{{ $match->title }}
{{ $distance->distance }}
</code>```

but I can't get it to work.

This is my controller:

```<code>public function bikeGamesMatch(Request $request){
    $matches = BikeGame::find($request->id);
    $distances = Distance::find($request->id);
    dd($matches);
    return view('bike_games.match', compact("matches","distances"));
}
</code>```

why does the $distances return to null when I dd(): it?

this is my view:

```<code><th scope="col" class="text-center"><strong>Game Title:</strong>
             @foreach($matches as $match)
             {{ $match->title }}
             @endforeach
              </th>
                <th scope="col" class="text-center"><strong>Target: Distance</strong>
              @foreach($distances as $distance)
             {{ $distance->distance }} {{ $distance->unit }}
             @endforeach
</th>
</code>```

If I do this the view gives me 404

```<code>$matches = BikeGame::find($request->id)->firstOrFail();
$distances = Distance::find($request->id)->firstOrFail();
</code>```

What am I doing wrong here?

答:
In view before using foreach try to check

```<code>isset($matches) && count(matches) >0
</code>```

if this condition is true then use foreach.

Title: Display 2 tables in 1 view

Body:
I want to display 2 tables in 1 view

like this:

{{ $match->title }}
{{ $distance->distance }}

but I can't get it to work.

This is my controller:

public function bikeGamesMatch(Request $request){
    $matches = BikeGame::find($request->id);
    $distances = Distance::find($request->id);
    dd($matches);
    return view('bike_games.match', compact("matches","distances"));
}

why does the $distances return to null when I dd(): it?

this is my view:

Game Title:
             @foreach($matches as $match)
             {{ $match->title }}
             @endforeach

                Target: Distance
              @foreach($distances as $distance)
             {{ $distance->distance }} {{ $distance->unit }}
             @endforeach

If I do this the view gives me 404

$matches = BikeGame::find($request->id)->firstOrFail();
$distances = Distance::find($request->id)->firstOrFail();

What am I doing wrong here?

Body:
In view before using foreach try to check

isset($matches) && count(matches) >0

if this condition is true then use foreach.


来源: stackexchange

问:
Why does Thread.Sleep(0) fix my problems, and how to avoid it?
I'm working on a client server application.  At certain times, on certain machines, when there's more than 5 clients requesting data, it seems to reach a deadlock.  If I step in to debug the problem, then the program appears to be processing.  Simply setting a break point where I know the program is executing, and causing it to hit the breakpoint a few times causes it to finish. If I insert Thread.Sleep(0) at certain points in the code, mostly around some cpu intensive loops, it seems to pretty much totally resolve the problem.  The one problem that I have now is that if I call Thread.Sleep(0) too much, it can slow down the code.  If I don't call it enough, the code seems to be in deadlock.  Although I can verify that it isn't in deadlock because if I step into the code, it causes the problem to disappear, simply because I'm pausing a thread.

Is there a good way to track down exactly what is causing this.  It seems that it only happens on my laptop which is running Vista, but not on my desktop which is running Windows XP.  However, it's impossible to debug, because simply stepping into the code causes the problem to go away.  I've read comments that calling Thread.Sleep(0) is a bad practice, and shouldn't be necessary, and I don't like putting witchcraft type code into my applications that I don't understand why it has to be there.  Any pointers would be greatly appreciated.

[EDIT]
I can also verify that the code is still running when it is "deadlocked" because if I leave it long enough, it will finish, only the amount of time it takes is many orders of magnitude higher.  I mean like it's actually at least 100 times slower when it's in this "deadlocked" mode.  The CPU is pegged at 80-95%, so it is working, altough what it is doing is beyond me, because it's taking forever to complete the task.

[More Info]
Just because everybody here is insistent that it's a deadlock, I removed all the code that did any locking. There was only a couple lines of code that did any locking whatsoever. The threads work completely independantly for the most part, so it wasn't much work to remove the locking completely.  Still the problem persists.  There is no more synclocks in my code, no more mutex's no more stuff that I see see that would cause a deadlock, but the problem is still there.  And it's not deadlocked.  It runs, albeit very slowly, even though it's eating up all the processor resources.

答:
Unless hardware forces you to, you should never use sleep().

Try thinking about the problem in a different way. Consider what data needs to be shared between threads and think about ways to send the data (IE, copy it) to the interested parties instead of sharing access.. If you do this right, you may not actually need any mutexes...

Remember, local variables exist on different stacks, but statics within functions are essentially globals (and of course, you need to look closely at your globals).

OwnerDisplayName: Kibbee

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Kibbee

OwnerDisplayName: dicroce


问:
Reuse define statement from .h file in C# code
I have C++ project (VS2005) which includes header file with version number in #define directive. Now I need to include exactly the same number in twin C# project. What is the best way to do it?

I'm thinking about including this file as a resource, then parse it at a runtime with regex to recover version number, but maybe there's a better way, what do you think?

I cannot move version outside .h file, also build system depends on it and the C# project is one which should be adapted.

答:
I would consider using a .tt file to process the .h and turn it into a .cs file. Its very easy and the source files will then be part of your C# solution (meaning they will be refreshed as the .h file changes), can be clicked on to open in the editor, etc.

If you've only got 1 #define it might be a little overkill, but if you have a file full of them (eg a mfc resource.h file perhaps) then this solution becomes a big win.

eg: create a file, DefineConverter.tt and add it to your project, change the marked line to refer to your .h file, and you'll get a new class in your project full of static const entries. (note the input file is relative to your project file, set hostspecific=false if you want absolute paths).

```<code><#@ template language="C#v3.5" hostspecific="True" debug="True" #>
<#@ output extension="cs" #>
<#@ assembly name="System.Core.dll" #>
<#@ import namespace="System" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ import namespace="System.IO" #>

<#
string input_file = this.Host.ResolvePath("resource.h");             <---- change this
StreamReader defines = new StreamReader(input_file);
#>
//------------------------------------------------------------------------------
//     This code was generated by template for T4
//     Generated at <#=DateTime.Now#>
//------------------------------------------------------------------------------

namespace Constants
{
    public class <#=System.IO.Path.GetFileNameWithoutExtension(input_file)#>
    {
<#
    // constants definitions

    while (defines.Peek() >= 0)
    {
        string def = defines.ReadLine();
        string[] parts;
        if (def.Length > 3 && def.StartsWith("#define"))
        {
            parts = def.Split(null as char[], StringSplitOptions.RemoveEmptyEntries);
            try {
                Int32 numval = Convert.ToInt32(parts[2]);
                #>
        public static const int <#=parts[1]#> = <#=parts[2]#>;
<#
            }
            catch (FormatException e) {
            #>
        public static const string <#=parts[1]#> = "<#=parts[2]#>";
<#
            }
        }
    } #>
    }
}
</code>```

OwnerDisplayName: tomash

Body:
I would consider using a .tt file to process the .h and turn it into a .cs file. Its very easy and the source files will then be part of your C# solution (meaning they will be refreshed as the .h file changes), can be clicked on to open in the editor, etc.

If you've only got 1 #define it might be a little overkill, but if you have a file full of them (eg a mfc resource.h file perhaps) then this solution becomes a big win.

eg: create a file, DefineConverter.tt and add it to your project, change the marked line to refer to your .h file, and you'll get a new class in your project full of static const entries. (note the input file is relative to your project file, set hostspecific=false if you want absolute paths).

<#@ template language="C#v3.5" hostspecific="True" debug="True" #>
<#@ output extension="cs" #>
<#@ assembly name="System.Core.dll" #>
<#@ import namespace="System" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ import namespace="System.IO" #>

<#
string input_file = this.Host.ResolvePath("resource.h");             <---- change this
StreamReader defines = new StreamReader(input_file);
#>
//------------------------------------------------------------------------------
//     This code was generated by template for T4
//     Generated at <#=DateTime.Now#>
//------------------------------------------------------------------------------

namespace Constants
{
    public class <#=System.IO.Path.GetFileNameWithoutExtension(input_file)#>
    {
<#
    // constants definitions

    while (defines.Peek() >= 0)
    {
        string def = defines.ReadLine();
        string[] parts;
        if (def.Length > 3 && def.StartsWith("#define"))
        {
            parts = def.Split(null as char[], StringSplitOptions.RemoveEmptyEntries);
            try {
                Int32 numval = Convert.ToInt32(parts[2]);
                #>
        public static const int <#=parts[1]#> = <#=parts[2]#>;
<#
            }
            catch (FormatException e) {
            #>
        public static const string <#=parts[1]#> = "<#=parts[2]#>";
<#
            }
        }
    } #>
    }
}

ContentLicense: CC BY-SA 3.0


问:
How to replace one parameter in Vuejs router
We have a multi-level multi-tenant application, where the hostname identifies the 'supplier' account, but the customer account is actually part of the URL.

For instance, we have routes set up as follows:

```<code>/:locale/app/:customer_id/invoices
</code>```

At the top of the page, we have a drop down with all customer ID's the user has access to.  The idea basically is that when a user changes the customer, the route changes from  /nl/app/4/invoices to /nl/app/5/invoicesfor instance.  So basically what I want to do is tell VueJs router to take the current route, and just change one parameter value in that route.

As you can imagine: the same goes for the :locale parameter where we basically have a language switch on top.

I know you can use $router.push in combination with a named route, and pass the current params in, replacing the params I want to update, but that would mean I'd have to name every route, and I'd need to know what the routes name is when I do an update.

Isn't there a way to just ask VueJS Router to "give me the current route", and update one parameter?

I've searched a lot on SO as well as through other resources, but so far did not get a good result...

答:
You do not really need named routes or manual path creation for this functionality. Router's push and replace methods support partial patches. You can build a simple reusable function to achieve this:

```<code>// This function expects router instance and params object to change
function updatePathParams($router, newParams) {

  // Retrieve current params
  const currentParams = $router.currentRoute.params;

  // Create new params object
  const mergedParams = { ...currentParams, newParams };

  // When router is not supplied path or name,
  // it simply tries to update current route with new params or query
  // Almost everything is optional.
  $router.push({ params: mergedParams });
}
</code>```

In your component, you can use it like:

```<code>onClickHandler() {
  updatePathParams(this.$router, { locale: 'en-us' });

  // Sometime later
  updatePathParams(this.$router, { customer_id: 123 });
}
</code>```

Also, here I merged the params object with existing values to illustrate the idea. In reality, you don't need to pass all the params. If you wish to change just one param say, customer_id, then simply do: $router.push({ params: { customer_id: 1234 } }). Vue-Router is smart enough to retain the same route and keep other params (locale here) unchanged.

ContentLicense: CC BY-SA 4.0

Body:
We have a multi-level multi-tenant application, where the hostname identifies the 'supplier' account, but the customer account is actually part of the URL.

For instance, we have routes set up as follows:

/:locale/app/:customer_id/invoices

At the top of the page, we have a drop down with all customer ID's the user has access to.  The idea basically is that when a user changes the customer, the route changes from  /nl/app/4/invoices to /nl/app/5/invoicesfor instance.  So basically what I want to do is tell VueJs router to take the current route, and just change one parameter value in that route.

As you can imagine: the same goes for the :locale parameter where we basically have a language switch on top.

I know you can use $router.push in combination with a named route, and pass the current params in, replacing the params I want to update, but that would mean I'd have to name every route, and I'd need to know what the routes name is when I do an update.

Isn't there a way to just ask VueJS Router to "give me the current route", and update one parameter?

I've searched a lot on SO as well as through other resources, but so far did not get a good result...

Body:
You do not really need named routes or manual path creation for this functionality. Router's push and replace methods support partial patches. You can build a simple reusable function to achieve this:

// This function expects router instance and params object to change
function updatePathParams($router, newParams) {

  // Retrieve current params
  const currentParams = $router.currentRoute.params;

  // Create new params object
  const mergedParams = { ...currentParams, newParams };

  // When router is not supplied path or name,
  // it simply tries to update current route with new params or query
  // Almost everything is optional.
  $router.push({ params: mergedParams });
}

In your component, you can use it like:

onClickHandler() {
  updatePathParams(this.$router, { locale: 'en-us' });

  // Sometime later
  updatePathParams(this.$router, { customer_id: 123 });
}

Also, here I merged the params object with existing values to illustrate the idea. In reality, you don't need to pass all the params. If you wish to change just one param say, customer_id, then simply do: $router.push({ params: { customer_id: 1234 } }). Vue-Router is smart enough to retain the same route and keep other params (locale here) unchanged.


问:
How do i set the state from one API call and use the data for URL in next API call?
I need the data from API call 1 to add to the URL of API call 2. The data from API 2 will go into the URL for API 3. I am setting the state on each Axios request and it is not working. Returning undefined</p>

```<code>componentDidMount() {
  // Get the IP adress of user
  axios
    .get('https://api.ipify.org?format=json')
    .then(res => {
      this.setState({
        ip: res.data.ip
      });
      console.log(`IP : ${this.state.ip}`);
    })
    .catch(err => console.log(err));

  // GET the coordinates of a location based on IP adress
  axios
    .get(
      'https://geo.ipify.org/api/v1?apiKey=YOUR_API_KEY&ipAddress=24.8.227.87'
    )
    .then(res => {
      this.setState({
        latitude: res.data.location.lat,
        longitude: res.data.location.lng
      });
      console.log(
        `Latitude: ${this.state.latitude}. Longitude: ${this.state.longitude}`
      );
    })
    .catch(err => console.log(err));

  // Make the API call on page load
  axios({
      method: 'get',
      url: `https://developers.zomato.com/api/v2.1/geocode?lat=39.6924553&lon=-105.0256318`,
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        Accept: 'application/json',
        'user-key': 'USER_KEY'
      }
    })
    .then(res => {
      const restaurantsNearMe = res.data.nearby_restaurants;

      this.setState({
        restaurants: restaurantsNearMe
      });

      // Pick out a random retaurant from what the API returns
      var randomRestaurant =
        restaurantsNearMe[
          Math.floor(Math.random() * restaurantsNearMe.length)
        ];

      // Select only the data that you want
      var finalResult = {
        name: randomRestaurant.restaurant.name,
        id: randomRestaurant.restaurant.id,
        rating: randomRestaurant.restaurant.user_rating.aggregate_rating,
        ratingColor: randomRestaurant.restaurant.user_rating.rating_color,
        address: randomRestaurant.restaurant.location.address,
        delivery: randomRestaurant.restaurant.is_delivering_now,
        typeOfFood: randomRestaurant.restaurant.cuisines
      };

      this.setState({
        restaurant: finalResult
      });
      console.log(this.state.restaurant);
    })
    .catch(err => console.log(err));
}
</code>```

答:
I dont know how do you call API's but, try something like this:

In componentDidMount you can do this:

async componentDidMount(){
  const resApiOne = await callFirstApi();
  this.setState({resApiOne});
  const resApiTwo = await callSecondApi(resApiOne);
  this.setState({resApiTwo});
}
```

Body:
I need the data from API call 1 to add to the URL of API call 2. The data from API 2 will go into the URL for API 3. I am setting the state on each Axios request and it is not working. Returning undefined

componentDidMount() {
  // Get the IP adress of user
  axios
    .get('https://api.ipify.org?format=json')
    .then(res => {
      this.setState({
        ip: res.data.ip
      });
      console.log(`IP : ${this.state.ip}`);
    })
    .catch(err => console.log(err));

  // GET the coordinates of a location based on IP adress
  axios
    .get(
      'https://geo.ipify.org/api/v1?apiKey=YOUR_API_KEY&ipAddress=24.8.227.87'
    )
    .then(res => {
      this.setState({
        latitude: res.data.location.lat,
        longitude: res.data.location.lng
      });
      console.log(
        `Latitude: ${this.state.latitude}. Longitude: ${this.state.longitude}`
      );
    })
    .catch(err => console.log(err));

  // Make the API call on page load
  axios({
      method: 'get',
      url: `https://developers.zomato.com/api/v2.1/geocode?lat=39.6924553&lon=-105.0256318`,
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        Accept: 'application/json',
        'user-key': 'USER_KEY'
      }
    })
    .then(res => {
      const restaurantsNearMe = res.data.nearby_restaurants;

      this.setState({
        restaurants: restaurantsNearMe
      });

      // Pick out a random retaurant from what the API returns
      var randomRestaurant =
        restaurantsNearMe[
          Math.floor(Math.random() * restaurantsNearMe.length)
        ];

      // Select only the data that you want
      var finalResult = {
        name: randomRestaurant.restaurant.name,
        id: randomRestaurant.restaurant.id,
        rating: randomRestaurant.restaurant.user_rating.aggregate_rating,
        ratingColor: randomRestaurant.restaurant.user_rating.rating_color,
        address: randomRestaurant.restaurant.location.address,
        delivery: randomRestaurant.restaurant.is_delivering_now,
        typeOfFood: randomRestaurant.restaurant.cuisines
      };

      this.setState({
        restaurant: finalResult
      });
      console.log(this.state.restaurant);
    })
    .catch(err => console.log(err));
}


问:
How to get the table name from the function argument in postgres so that the table name is used to create a table in the function
I am creating a function in Postgres for creating a table, the table name has to be given by the user at the time of the function call

```<code>CREATE OR REPLACE FUNCTION mnth(
tablename text
)
RETURNS void as $$
BEGIN
CREATE TABLE monthly.||tablename||
(
row_id text,
left_row text,
right_row text,
left_plus text
);
END;
$$ LANGUAGE plpgsql;
</code>```

During the function call, the name given by the user will be the name of the table that will be created in the function.

答:
You may use EXECUTE format

```<code>CREATE OR REPLACE FUNCTION mnth(
tablename text
)
RETURNS void as $$
BEGIN
EXECUTE format (
'CREATE TABLE %I.%I
(
 row_id text,
 left_row text,
 right_row text,
 left_plus text
)' , 'monthly',tablename );
END;
$$ LANGUAGE plpgsql;
</code>```

Body:
I am creating a function in Postgres for creating a table, the table name has to be given by the user at the time of the function call

CREATE OR REPLACE FUNCTION mnth(
tablename text
)
RETURNS void as $$
BEGIN
CREATE TABLE monthly.||tablename||
(
row_id text,
left_row text,
right_row text,
left_plus text
);
END;
$$ LANGUAGE plpgsql;

During the function call, the name given by the user will be the name of the table that will be created in the function.

Body:
You may use EXECUTE format

CREATE OR REPLACE FUNCTION mnth(
tablename text
)
RETURNS void as $$
BEGIN
EXECUTE format (
'CREATE TABLE %I.%I
(
 row_id text,
 left_row text,
 right_row text,
 left_plus text
)' , 'monthly',tablename );
END;
$$ LANGUAGE plpgsql;


问:
How do I create a Vim function-list inside quick-fix window?
Is there a way to put all functions defined in the current buffer to the quick-fix list? Imagine Tlist (from taglist plugin) opened in quick-fix window.

答:
Create an expression that returns the list that you want. Eg:

```<code>let cmd='exctags -x '.bufname('%')." | awk '{print $4\"|\"$3\"|\",$1}'"
</code>```

Feed it to cexpr or cgetexpr

```<code>cexpr system(cmd)
</code>```

Body:
Create an expression that returns the list that you want. Eg:

let cmd='exctags -x '.bufname('%')." | awk '{print $4\"|\"$3\"|\",$1}'"

Feed it to cexpr or cgetexpr

cexpr system(cmd)


问:
SQL help to make a particular select statement for a table
```<code>CREATE TABLE person (
  id INTEGER PRIMARY KEY,
  first_name TEXT,
  last_name TEXT,
  age INTEGER
);

INSERT INTO person VALUES (0, 'Pat', 'Johnson', 25);
INSERT INTO person VALUES (1, 'John', 'Wells', 28);
</code>```

So I have a table called person and I am trying to query all people younger than Pat Johnson, but I do not want to query it by hard coding.

```<code>SELECT first_name, last_name FROM person WHERE age < 25;
</code>```

^^^ this is an example of what I do not want to do.

答:
You can try using a subquery</p>

```<code>SELECT first_name, last_name FROM person
WHERE age<(select age from person where first_name='Pat' and last_name='Johnson')
</code>```

Body:
CREATE TABLE person (
  id INTEGER PRIMARY KEY,
  first_name TEXT,
  last_name TEXT,
  age INTEGER
);

INSERT INTO person VALUES (0, 'Pat', 'Johnson', 25);
INSERT INTO person VALUES (1, 'John', 'Wells', 28);

So I have a table called person and I am trying to query all people younger than Pat Johnson, but I do not want to query it by hard coding.

SELECT first_name, last_name FROM person WHERE age < 25;

^^^ this is an example of what I do not want to do.

Body:
You can try using a subquery

SELECT first_name, last_name FROM person
WHERE age<(select age from person where first_name='Pat' and last_name='Johnson')


问:
How to write Test with diffrence module ? i got initializer is inaccessible due to 'internal' protection level
I have Module A and Module B .  My test class written in A . and imported B as @testable import B.
Everything is ok till i got this warning

'Models.SetLanguage.Response' initializer is inaccessible due to 'internal' protection level

The struct of Models , SetLanguage ,Response each defined as public

I hade no idea why i cant access B public module struct from module A test class.

```<code>public struct  Models {

   public struct SetLanguage {
    /// Data struct sent to Interactor
    public struct Request {
      let language: Language
    }
    /// Data struct sent to Presenter
    public struct Response {
      let result: Result<Language>
    }
    /// Data struct sent to ViewController
    public struct ViewModel {
      let content: Content<Language>
    }
  }
</code>```

答:
Just use open instead of public

Code:

```<code>open struct  Models {
   open struct SetLanguage {
    public struct Request {
      let language: Language
    }
    open struct Response {
      let result: Result<Language>
    }
    open struct ViewModel {
      let content: Content<Language>
    }
  }
</code>```

Body:
I have Module A and Module B .  My test class written in A . and imported B as @testable import B.
Everything is ok till i got this warning

'Models.SetLanguage.Response' initializer is inaccessible due to 'internal' protection level

The struct of Models , SetLanguage ,Response each defined as public

I hade no idea why i cant access B public module struct from module A test class.

public struct  Models {

   public struct SetLanguage {
    /// Data struct sent to Interactor
    public struct Request {
      let language: Language
    }
    /// Data struct sent to Presenter
    public struct Response {
      let result: Result<Language>
    }
    /// Data struct sent to ViewController
    public struct ViewModel {
      let content: Content<Language>
    }
  }

Body:
Just use open instead of public

Code:

open struct  Models {
   open struct SetLanguage {
    public struct Request {
      let language: Language
    }
    open struct Response {
      let result: Result<Language>
    }
    open struct ViewModel {
      let content: Content<Language>
    }
  }


问:
What will be regular expression of domain URL of "www.google.com"?
What will be the regex for RegularExpressionValidator in asp.net for domain name like "www.google.com"?

Valid Cases:

www.google.com

www.youwebsite.com

Invalid Cases:

http://www.google.com

https://www.google.com

google.com

www.google

Currently I used (?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9][a-z0-9-]{0,61}[a-z0-9] but it fails for invalid case number 3 and 4.

答:
Assuming that we would have valid ULRs as listed, we can start with a simple expression such as:

```<code>^www\..+\.com
</code>```

Demo 1

Then, we can add additional boundaries, if desired. For instance, we could add char class and end anchor, such as:

```<code>^www\..+\.com$
^www\.[A-Za-z_]+\.com$
</code>```

Demo 2

If necessary, we would continue adding more constraints and test:

```<code>using System;
using System.Text.RegularExpressions;

public class Example
{
    public static void Main()
    {
        string pattern = @"^www\.[A-Za-z_]+\.com";
        string input = @"www.google.com
www.youwebsite.com

http://www.google.com
https://www.google.com
google.com
www.google";
        RegexOptions options = RegexOptions.Multiline;

        foreach (Match m in Regex.Matches(input, pattern, options))
        {
            Console.WriteLine("'{0}' found at index {1}.", m.Value, m.Index);
        }
    }
}
</code>```

RegEx Circuit

jex.im visualizes regular expressions:

Body:
Assuming that we would have valid ULRs as listed, we can start with a simple expression such as:

^www\..+\.com

Demo 1

Then, we can add additional boundaries, if desired. For instance, we could add char class and end anchor, such as:

^www\..+\.com$
^www\.[A-Za-z_]+\.com$

Demo 2

If necessary, we would continue adding more constraints and test:

using System;
using System.Text.RegularExpressions;

public class Example
{
    public static void Main()
    {
        string pattern = @"^www\.[A-Za-z_]+\.com";
        string input = @"www.google.com
www.youwebsite.com

http://www.google.com
https://www.google.com
google.com
www.google";
        RegexOptions options = RegexOptions.Multiline;

        foreach (Match m in Regex.Matches(input, pattern, options))
        {
            Console.WriteLine("'{0}' found at index {1}.", m.Value, m.Index);
        }
    }
}

RegEx Circuit

jex.im visualizes regular expressions:


问:
drv <- dbDriver("Oracle") works fine in Command-line R but not working on RStudio Server
as suggested by the title, I'm trying to setup connections to Oracle DBs through R using the library ROracle on a Unix Machine.
using R in command line I have 0 problems, but when trying the same exact instruction in RStudio Server i'm stuc with the following error.

drv <- dbDriver("Oracle")
  Error in .oci.Driver(.oci.drv(), interruptible = interruptible, unicode_as_utf8 = unicode_as_utf8,  :
    Error while trying to retrieve text for error ORA-01804

these are the output of libPaths():
in RStudio Server

```<code>.libPaths()
[1] "/home/rs_violac/R/x86_64-redhat-linux-gnu-library/3.5"
[2] "/usr/lib64/R/library"
[3] "/usr/share/R/library"
</code>```

in R (command line)

```<code>> .libPaths()
[1] "/usr/lib64/R/library" "/usr/share/R/library"
</code>```

I have set the following path:

and set the LD to the share oracle.conf file as suggested in other stackoverflow answear

```<code>echo "/oracle/app/oracle/product/12.2.0/client/lib" | sudo tee /etc/ld.so.conf.d/oracle.conf
</code>```

Any idea or suggestion how to resolve?

EDIT: I've tryed setting those enviornments variable in RStudio console but no resolution

```<code>Sys.setenv("OCI_INC"="/oracle/app/oracle/product/12.2.0/client")
Sys.setenv("OCI_LIB"="/oracle/app/oracle/product/12.2.0/client/lib")
Sys.setenv("OCI_LIB64"="/oracle/app/oracle/product/12.2.0/client/lib")
Sys.setenv("TNS_ADMIN"="/oracle/app/oracle/product/12.2.0/client/network/admin")
Sys.setenv("LD_LIBRARY_PATH"="/usr/lib64/R/lib::/lib:/usr/lib/jvm/jre/lib/amd64/server:/usr/lib/jvm/jre/lib/amd64:/usr/lib/jvm/java/lib/amd64:/usr/java/packages/lib/amd64:/lib:/usr/lib:/oracle/app/oracle/product/12.2.0/client/lib")
Sys.setenv("ORACLE_HOME"="/oracle/app/oracle/product/12.2.0/client")
Sys.setenv("NLS_LANG"="en_US.UTF-8")
Sys.setenv("ORACLE_BASE"="/oracle/app/oracle")
Sys.setenv("LC_ALL"="en_US.UTF-8")
</code>```

Now the error is:

Error in .oci.Driver(.oci.drv(), interruptible = interruptible,
  unicode_as_utf8 = unicode_as_utf8,  :    ORA-12715: invalid character
  set specified

the error change is triggered by the setting of ORACLE_HOME env

答:
The rstudio user needs to have ORACLE_HOME and ORACLE_HOSTNAME set in its environment on the server where the rstudio-server runs. You can use a config file .Renviron, with something like the following for example using BASH shell:</p>

```<code>ORACLE_HOME=<your Oracle home>
ORACLE_HOSTNAME=<your host name>
export ORACLE_HOME ORACLE_HOSTNAME
</code>```

Body:
as suggested by the title, I'm trying to setup connections to Oracle DBs through R using the library ROracle on a Unix Machine.
using R in command line I have 0 problems, but when trying the same exact instruction in RStudio Server i'm stuc with the following error.

drv <- dbDriver("Oracle")
  Error in .oci.Driver(.oci.drv(), interruptible = interruptible, unicode_as_utf8 = unicode_as_utf8,  :
    Error while trying to retrieve text for error ORA-01804

these are the output of libPaths():
in RStudio Server

.libPaths()
[1] "/home/rs_violac/R/x86_64-redhat-linux-gnu-library/3.5"
[2] "/usr/lib64/R/library"
[3] "/usr/share/R/library"

in R (command line)

> .libPaths()
[1] "/usr/lib64/R/library" "/usr/share/R/library"

I have set the following path:

and set the LD to the share oracle.conf file as suggested in other stackoverflow answear

echo "/oracle/app/oracle/product/12.2.0/client/lib" | sudo tee /etc/ld.so.conf.d/oracle.conf

Any idea or suggestion how to resolve?

EDIT: I've tryed setting those enviornments variable in RStudio console but no resolution

Sys.setenv("OCI_INC"="/oracle/app/oracle/product/12.2.0/client")
Sys.setenv("OCI_LIB"="/oracle/app/oracle/product/12.2.0/client/lib")
Sys.setenv("OCI_LIB64"="/oracle/app/oracle/product/12.2.0/client/lib")
Sys.setenv("TNS_ADMIN"="/oracle/app/oracle/product/12.2.0/client/network/admin")
Sys.setenv("LD_LIBRARY_PATH"="/usr/lib64/R/lib::/lib:/usr/lib/jvm/jre/lib/amd64/server:/usr/lib/jvm/jre/lib/amd64:/usr/lib/jvm/java/lib/amd64:/usr/java/packages/lib/amd64:/lib:/usr/lib:/oracle/app/oracle/product/12.2.0/client/lib")
Sys.setenv("ORACLE_HOME"="/oracle/app/oracle/product/12.2.0/client")
Sys.setenv("NLS_LANG"="en_US.UTF-8")
Sys.setenv("ORACLE_BASE"="/oracle/app/oracle")
Sys.setenv("LC_ALL"="en_US.UTF-8")

Now the error is:

Error in .oci.Driver(.oci.drv(), interruptible = interruptible,
  unicode_as_utf8 = unicode_as_utf8,  :    ORA-12715: invalid character
  set specified

the error change is triggered by the setting of ORACLE_HOME env

Body:
The rstudio user needs to have ORACLE_HOME and ORACLE_HOSTNAME set in its environment on the server where the rstudio-server runs. You can use a config file .Renviron, with something like the following for example using BASH shell:

ORACLE_HOME=<your Oracle home>
ORACLE_HOSTNAME=<your host name>
export ORACLE_HOME ORACLE_HOSTNAME


问:
How to run multiple Python versions on Windows
I had two versions of Python installed on my machine (versions 2.6 and 2.5). I want to run 2.6 for one project and 2.5 for another.

How can I specify which I want to use?

I am working on Windows XP SP2.

答:
I strongly recommend the pyenv-win project.

Thanks to kirankotari's work, now we have a Windows version of pyenv.


问:
How can I get '/path/to/certfile' of a public website for requests?
I am using requests to get HTML of a webpage. However, I am running into certificate verification problems. On running the code I get the following error:

SSL: CERTIFICATE_VERIFY_FAILED

Going through other questions I found two solutions. The one that works is by disabling verification through verify=False in the function call. However, this is not a safe option.

The other one is to use verify='/path/to/certfile'

I am not sure how to get the path to certfile. Through settings in Chromer browser I was taken to a "keychain access" app on mac with various certificates. I exported the certificate "DST Root CA X3" to my working directory and provided the path of that file as '/path/to/certfile' value. But that gives me the following error:

requests.exceptions.SSLError:
  HTTPSConnectionPool(host='rajyasabha.nic.in', port=443): Max retries
  exceeded with url: /rsnew/member_site/MemlistElDate.aspx (Caused by
  SSLError(SSLError(0, 'unknown error (_ssl.c:3622)'),))

python :

```<code>import requests
url='https://rajyasabha.nic.in/rsnew/member_site/MemlistElDate.aspx'
page=requests.get(url)
</code>```

Is there a different way to get the path to certfile?

答:
The problem with that site is that the server is not configured correctly to return the intermediate certificate in the certificate chain during TLS handshake. You can check this using the following command:

```<code>openssl s_client -connect rajyasabha.nic.in:443
</code>```

If you scroll down you will see that only depth 0 (the leaf certificate) is sent by the server. This is generally not a problem for web browsers as they cache intermediate certificates, but it is an issue for requests as it does not know about it.

The root certificates (DST Root CA X3 in this case) almost always exist in your operating systems's CA repository. So the certificate we need is this one:

```<code>depth=1 C = US, O = Let's Encrypt, CN = Let's Encrypt Authority X3
</code>```

So your best bet is to download the Let's Encrypt Authority X3 intermediate certificate from the following URL and set that as your verify path:

https://letsencrypt.org/certificates/

Clarification: You should include both intermediate and the root certificates in your .pem file, so it should look like:

```<code>-----BEGIN CERTIFICATE-----
MIIFjTCCA3WgAwIBAgIRANOxciY0IzLc9AUoUSrsnGowDQYJKoZIhvcNAQELBQAw
...
rUCGwbCUDI0mxadJ3Bz4WxR6fyNpBK2yAinWEsikxqEt
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
MIIFazCCA1OgAwIBAgIRAIIQz7DSQONZRGPgu2OCiwAwDQYJKoZIhvcNAQELBQAw
...
emyPxgcYxn/eR44/KJ4EBs+lVDR3veyJm+kXQ99b21/+jh5Xos1AnX5iItreGCc=
-----END CERTIFICATE-----
</code>```

Body:
I am using requests to get HTML of a webpage. However, I am running into certificate verification problems. On running the code I get the following error:

SSL: CERTIFICATE_VERIFY_FAILED

Going through other questions I found two solutions. The one that works is by disabling verification through verify=False in the function call. However, this is not a safe option.

The other one is to use verify='/path/to/certfile'

I am not sure how to get the path to certfile. Through settings in Chromer browser I was taken to a "keychain access" app on mac with various certificates. I exported the certificate "DST Root CA X3" to my working directory and provided the path of that file as '/path/to/certfile' value. But that gives me the following error:

requests.exceptions.SSLError:
  HTTPSConnectionPool(host='rajyasabha.nic.in', port=443): Max retries
  exceeded with url: /rsnew/member_site/MemlistElDate.aspx (Caused by
  SSLError(SSLError(0, 'unknown error (_ssl.c:3622)'),))

python :

import requests
url='https://rajyasabha.nic.in/rsnew/member_site/MemlistElDate.aspx'
page=requests.get(url)

Is there a different way to get the path to certfile?

Body:
The problem with that site is that the server is not configured correctly to return the intermediate certificate in the certificate chain during TLS handshake. You can check this using the following command:

openssl s_client -connect rajyasabha.nic.in:443

If you scroll down you will see that only depth 0 (the leaf certificate) is sent by the server. This is generally not a problem for web browsers as they cache intermediate certificates, but it is an issue for requests as it does not know about it.

The root certificates (DST Root CA X3 in this case) almost always exist in your operating systems's CA repository. So the certificate we need is this one:

depth=1 C = US, O = Let's Encrypt, CN = Let's Encrypt Authority X3

So your best bet is to download the Let's Encrypt Authority X3 intermediate certificate from the following URL and set that as your verify path:

https://letsencrypt.org/certificates/

Clarification: You should include both intermediate and the root certificates in your .pem file, so it should look like:

-----BEGIN CERTIFICATE-----
MIIFjTCCA3WgAwIBAgIRANOxciY0IzLc9AUoUSrsnGowDQYJKoZIhvcNAQELBQAw
...
rUCGwbCUDI0mxadJ3Bz4WxR6fyNpBK2yAinWEsikxqEt
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
MIIFazCCA1OgAwIBAgIRAIIQz7DSQONZRGPgu2OCiwAwDQYJKoZIhvcNAQELBQAw
...
emyPxgcYxn/eR44/KJ4EBs+lVDR3veyJm+kXQ99b21/+jh5Xos1AnX5iItreGCc=
-----END CERTIFICATE-----


问:
What's wrong with this DB2 SQL Query?
```<code>SELECT
    getOrgName(BC.ManageOrgID),
    COUNT(CASE WHEN (EXISTS (SELECT FO.OBJECTNO FROM FLOW_OBJECT FO WHERE FO.ObjectNo=CR.SerialNo) AND NVL(CR.FinallyResult,'') IN ('01','02','03','04','05')) THEN BC.ManageOrgID ELSE NULL END)
FROM
    BUSINESS_CONTRACT BC,
    CLASSIFY_RECORD CR
WHERE
 CR.ObjectType='BusinessContract'
AND CR.ObjectNo=BC.SerialNo
GROUP BY BC.ManageOrgID, CR.SerialNo, CR.FinallyResult
</code>```

The error message I receive is:

11:01:32  [SELECT - 0 row(s), 0.000 secs]  [Error Code: -112, SQL State: 42607]  DB2 SQL Error: SQLCODE=-112, SQLSTATE=42607, SQLERRMC=SYSIBM.COUNT, DRIVER=3.57.82
  ... 1 statement(s) executed, 0 row(s) affected, exec/fetch time: 0.000/0.000 sec  [0 successful, 0 warnings, 1 errors]

答:
"The operand of the column function name (in your case, count) includes a column function, a scalar fullselect, or a subquery." DB2 doesn't allow this.  See the documentation on SQL112 for more.

I'm not really sure how to fix your query but perhaps you can try the HAVING clause after GROUP BY.

Title: What's wrong with this DB2 SQL Query?

Body:
SELECT
    getOrgName(BC.ManageOrgID),
    COUNT(CASE WHEN (EXISTS (SELECT FO.OBJECTNO FROM FLOW_OBJECT FO WHERE FO.ObjectNo=CR.SerialNo) AND NVL(CR.FinallyResult,'') IN ('01','02','03','04','05')) THEN BC.ManageOrgID ELSE NULL END)
FROM
    BUSINESS_CONTRACT BC,
    CLASSIFY_RECORD CR
WHERE
 CR.ObjectType='BusinessContract'
AND CR.ObjectNo=BC.SerialNo
GROUP BY BC.ManageOrgID, CR.SerialNo, CR.FinallyResult

The error message I receive is:

11:01:32  [SELECT - 0 row(s), 0.000 secs]  [Error Code: -112, SQL State: 42607]  DB2 SQL Error: SQLCODE=-112, SQLSTATE=42607, SQLERRMC=SYSIBM.COUNT, DRIVER=3.57.82
  ... 1 statement(s) executed, 0 row(s) affected, exec/fetch time: 0.000/0.000 sec  [0 successful, 0 warnings, 1 errors]


问:
Node - was compiled against a different Node.js version using NODE_MODULE_VERSION 51
I am running a node application on terminal. Have recently upgraded to node v8.5.0, but am getting this error:

```<code>Error: The module '/tidee/tidee-au/packages/tidee-au-server/node_modules/bcrypt/lib/binding/bcrypt_lib.node'
was compiled against a different Node.js version using
NODE_MODULE_VERSION 51. This version of Node.js requires
NODE_MODULE_VERSION 57. Please try re-compiling or re-installing
the module (for instance, using `npm rebuild` or `npm install`).
    at Object.Module._extensions..node (module.js:653:18)
    at Module.load (module.js:545:32)
    at tryModuleLoad (module.js:508:12)
    at Function.Module._load (module.js:500:3)
    at Module.require (module.js:568:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (/tidee/tidee-au/packages/tidee-au-server/node_modules/bcrypt/bcrypt.js:6:16)
    at Module._compile (module.js:624:30)
    at Module._extensions..js (module.js:635:10)
    at Object.require.extensions.(anonymous function) [as .js] (/tidee/tidee-au/packages/tidee-au-server/node_modules/babel-register/lib/node.js:152:7)
    at Module.load (module.js:545:32)
    at tryModuleLoad (module.js:508:12)
    at Function.Module._load (module.js:500:3)
    at Module.require (module.js:568:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (/tidee/tidee-au/packages/tidee-au-server/server/helpers/encryptPass.js:1:16)
</code>```

Any idea how to solve this?

答:
I had a similar problem with robotjs. There were some deprecated code that required node v11, but I had already compiled electron code on v12. So I got basically the same error.
Nothing here worked as I was basically trying to rebuild electron and my other dependencies into node v11 from v12.

Here is what I did (part of this is based on chitzui's answer, credit where credit is due):

Back up package.json

completely delete the node_modules folder

completely delete package_lock.json

delete package.json (will reinit later)

Close any open editors and other cmd windows that are in the project's directory.

run npm init to reinit package, then missing data with old backed up package.json

run npm i

fixed

Body:
I am running a node application on terminal. Have recently upgraded to node v8.5.0, but am getting this error:

Error: The module '/tidee/tidee-au/packages/tidee-au-server/node_modules/bcrypt/lib/binding/bcrypt_lib.node'
was compiled against a different Node.js version using
NODE_MODULE_VERSION 51. This version of Node.js requires
NODE_MODULE_VERSION 57. Please try re-compiling or re-installing
the module (for instance, using `npm rebuild` or `npm install`).
    at Object.Module._extensions..node (module.js:653:18)
    at Module.load (module.js:545:32)
    at tryModuleLoad (module.js:508:12)
    at Function.Module._load (module.js:500:3)
    at Module.require (module.js:568:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (/tidee/tidee-au/packages/tidee-au-server/node_modules/bcrypt/bcrypt.js:6:16)
    at Module._compile (module.js:624:30)
    at Module._extensions..js (module.js:635:10)
    at Object.require.extensions.(anonymous function) [as .js] (/tidee/tidee-au/packages/tidee-au-server/node_modules/babel-register/lib/node.js:152:7)
    at Module.load (module.js:545:32)
    at tryModuleLoad (module.js:508:12)
    at Function.Module._load (module.js:500:3)
    at Module.require (module.js:568:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (/tidee/tidee-au/packages/tidee-au-server/server/helpers/encryptPass.js:1:16)

Any idea how to solve this?


问:
Detect language from string in PHP
In PHP, is there a way to detect the language of a string? Suppose the string is in UTF-8 format.</p>

答:
You could implement a module of Apache Tika with Java, insert the results into a txt file, a DB, etc and then read from the file, db, whatever with php.
If you don't have that much content, you could use Google's API, although keep in mind your calls will be limited, and you can only send a restricted number of characters to the API. At the time of writing I'd finished testing version 1 (which turned out to be not so accurate) and the labs version 2 (i ditched after i read that there's a 100,000 chars cap per day) of the API.</p>

Title: Detect language from string in PHP


问:
Spring Security Configuration - HttpSecurity vs WebSecurity
I just need to understand something in Spring Security Configuration. Using the example below...

```<code>@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .httpBasic()
            .and()
            .authorizeRequests().antMatchers("/secret/**").authenticated()
            .and()
            .authorizeRequests().antMatchers("/**").permitAll();
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/resources/**");
    }

}
</code>```

What is the purpose of configure(WebSecurity web) method?

Can't I just add /resources/** in the configure(HttpSecurity http) method in this line .authorizeRequests().antMatchers("/**", "/resources/**").permitAll();
Shouldn't it work the same i.e. permitting all requests to /resources/** without any authentication?

答:
configure(HttpSecurity) : It allows configuring web based security for specific http requests. It is used for configuration of web based security at a resource level, based on a selection match.

configure (WebSecurity) : Allows adding RequestMatcher instances that Spring Security should ignore.

Body:
I just need to understand something in Spring Security Configuration. Using the example below...

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .httpBasic()
            .and()
            .authorizeRequests().antMatchers("/secret/**").authenticated()
            .and()
            .authorizeRequests().antMatchers("/**").permitAll();
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/resources/**");
    }

}

What is the purpose of configure(WebSecurity web) method?

Can't I just add /resources/** in the configure(HttpSecurity http) method in this line .authorizeRequests().antMatchers("/**", "/resources/**").permitAll();
Shouldn't it work the same i.e. permitting all requests to /resources/** without any authentication?


问:
How to find all multi-directional relations between two nodes?
I'm trying to find all relations between node a and node b, and the relations could be multi-directions. For example,
a <- c -> b or a -> d -> b where c and d are nodes.

I've tried MATCH (a:PERSON {name: 'WD'})-[r*..3]-(b:PERSON{name: 'EK'}) RETURN r, a, b, but I got two isolated nodes, because the relation between a and b is: a <- c -> b.

Any help would be appreciated.

答:
You can return the path if you need all the relationships and nodes in between.

Following query will
You can modify your query to return full paths instead of just nodes a and b as following:

```<code>MATCH paths=(a:PERSON {name: 'WD'})-[r*..3]-(b:PERSON{name: 'EK'})
RETURN paths
</code>```

This will return paths of length up to 3, change it as you need.

Body:
You can return the path if you need all the relationships and nodes in between.

Following query will
You can modify your query to return full paths instead of just nodes a and b as following:

MATCH paths=(a:PERSON {name: 'WD'})-[r*..3]-(b:PERSON{name: 'EK'})
RETURN paths

This will return paths of length up to 3, change it as you need.


问:
Secondary command buffer for rendering in vulkan
Is it possible to make the rendering happen in the secondary command buffers? For example, there are 3 primary buffers and they call secondary buffers, which in turn render? I want to make a simple Manager that allows you to add and remove new objects on the screen.</p>

答: Yes. And when using secondary command buffers and the VK_SUBPASS_CONTENTS_SECONDARY_COMMAND_BUFFERS flag for your renderpass (see VkSubpassContents) you actually have to put all rendering commands into secondary command buffers that are called from within the primary command buffer using vkCmdExecuteCommands.


答:
When you use HttpSecurity and try to permitAll() requests. Your requests will be allowed to be accessed from the Spring Security Filter Chain. This is costly as there will be requests other requests which would also come into this filter chain which needs to be allowed or disallowed based on Authentication/Authorization.

```<code>HttpSecurity.authorizeRequests().antMatchers("/**", "/resources/**").permitAll();
</code>```

But when you use, any requests to resources will completely by pass the Spring Security Filter Chain all together. It is safe because you don't need any Authentication/Authorization to be in place to see an image or read a javascript file.

```<code>WebSecurity.ignoring().antMatchers("/resources/**");
</code>```

Title: Spring Security Configuration - HttpSecurity vs WebSecurity

Body:
When you use HttpSecurity and try to permitAll() requests. Your requests will be allowed to be accessed from the Spring Security Filter Chain. This is costly as there will be requests other requests which would also come into this filter chain which needs to be allowed or disallowed based on Authentication/Authorization.

HttpSecurity.authorizeRequests().antMatchers("/**", "/resources/**").permitAll();

But when you use, any requests to resources will completely by pass the Spring Security Filter Chain all together. It is safe because you don't need any Authentication/Authorization to be in place to see an image or read a javascript file.

WebSecurity.ignoring().antMatchers("/resources/**");


问:
Convert a specific string date
I have a date string like 28052019145051+05 (DDMMYYYYHHmmss) not a Unix timestamp. How can i convert it to date using date-fns? I have tried parse() but i'm getting Invalid date error.

答:
You can do this like below :</p>

```<code>var date = new Date(unix_timestamp*1000);

var hours = date.getHours();

var minutes = "0" + date.getMinutes();

var seconds = "0" + date.getSeconds();

var formattedTime = hours + ':' + minutes.substr(-2) + ':' + seconds.substr(-2);
</code>```

Title: Convert a specific string date

Body:
You can do this like below :

var date = new Date(unix_timestamp*1000);

var hours = date.getHours();

var minutes = "0" + date.getMinutes();

var seconds = "0" + date.getSeconds();

var formattedTime = hours + ':' + minutes.substr(-2) + ':' + seconds.substr(-2);


问:
How can I be getting multiple unwanted event blocks from the same onFormSubmit Trigger?
I created a one question form this morning because I wanted to look at the event block for myself.  However, the process took an unexpected turn for me. My description follows:

I'm logging the onFormSubmit event with the following code:

```<code>function testFormSubmission(e) {
  var lock=LockService.getUserLock();
  try{
      if(lock.tryLock(30000)) {
      var ss=SpreadsheetApp.getActive();
      var sh=ss.getSheetByName('LogSheet');
      var tA=[Utilities.formatDate(new Date(), Session.getScriptTimeZone(),"d/M/yyyy HH:mm:ss")];
      tA=tA.concat(e.values);
      tA.splice(tA.length-1,1,e.triggerUid,e.range.rowStart,e.range.columnEnd,JSON.stringify(e.values));
      sh.appendRow(tA);
      lock.releaseLock();
    }
  }
  catch (e){throw("Couldn\'t get lock for 30 seconds");return;};
}
</code>```

I have two images of my spreadsheet below:

There's actually only two columns in e.values one is the date and one is the answer to the question which is either "green" or "blue".  The blank columns come from the fact that I started with three questions and collecting emails but decided to remove two of them for simplicity, since I'm generating the submissions myself.

Anyway the responses that don't have either Green or Blue in columnC just shouldn't be there.  Column J is simply JSON.stringify(e.values) and it seems to suggest that e has incorrect values in it...I think? Yes/No

Here's an image of the Spreadsheet. (some of it)

This is the Form Responses 1 Sheet:

This is the LogSheet:

So my question is simply where are the unwanted appended lines in the Log Sheet  coming from?

I updated my title question because I don't think I'm getting multiple submissions otherwise I'd expect to have multiple lines in Form Responses 1 sheet.

For your information columnH in LogSheet is rowStart so it's easy to figure out what row in Form Response 1 correlates.

答:
I think your code proved that some triggers are spurious and unwanted and as such Google should not be generating them. I submitted a feedback item to Google on a similar issue.

In my unwanted triggers, I was only getting the e.range.getRow() to determine which row changed, then going to the row to do the required computation. In my case the row contained correct info for all spurious triggers (probably because the first one correctly recorded the data in the spreadsheet).

Your code is a great backstop to prevent it, but I have way too many forms and triggers to cover. Putting this code in all those places would be a pain. Let's hope google solves this issue soon and we don't see any more spurious triggers occurring.

Body:
I created a one question form this morning because I wanted to look at the event block for myself.  However, the process took an unexpected turn for me. My description follows:

I'm logging the onFormSubmit event with the following code:

function testFormSubmission(e) {
  var lock=LockService.getUserLock();
  try{
      if(lock.tryLock(30000)) {
      var ss=SpreadsheetApp.getActive();
      var sh=ss.getSheetByName('LogSheet');
      var tA=[Utilities.formatDate(new Date(), Session.getScriptTimeZone(),"d/M/yyyy HH:mm:ss")];
      tA=tA.concat(e.values);
      tA.splice(tA.length-1,1,e.triggerUid,e.range.rowStart,e.range.columnEnd,JSON.stringify(e.values));
      sh.appendRow(tA);
      lock.releaseLock();
    }
  }
  catch (e){throw("Couldn\'t get lock for 30 seconds");return;};
}

I have two images of my spreadsheet below:

There's actually only two columns in e.values one is the date and one is the answer to the question which is either "green" or "blue".  The blank columns come from the fact that I started with three questions and collecting emails but decided to remove two of them for simplicity, since I'm generating the submissions myself.

Anyway the responses that don't have either Green or Blue in columnC just shouldn't be there.  Column J is simply JSON.stringify(e.values) and it seems to suggest that e has incorrect values in it...I think? Yes/No

Here's an image of the Spreadsheet. (some of it)

This is the Form Responses 1 Sheet:

This is the LogSheet:

So my question is simply where are the unwanted appended lines in the Log Sheet  coming from?

I updated my title question because I don't think I'm getting multiple submissions otherwise I'd expect to have multiple lines in Form Responses 1 sheet.

For your information columnH in LogSheet is rowStart so it's easy to figure out what row in Form Response 1 correlates.


问:
How to initialise an instance of `ApolloClient` in nodejs?
I have below code written in nodejs10.

```<code>const ApolloClient = require('apollo-boost');

const client = new ApolloClient({
  uri: 'http://localhost:8000/graphql'
});

</code>```

The error I got when running this program is:

```<code>const client = ApolloClient({
               ^

TypeError: ApolloClient is not a function
</code>```

Below is the dependencies:

```<code>"apollo-boost": "^0.3.1",
    "apollo-cache-inmemory": "^1.6.0",
    "apollo-client": "^2.6.0",
    "apollo-link-http": "^1.5.14",
    "apollo-server": "^2.5.0",
    "apollo-server-express": "^2.5.1",
</code>```

I followed the user guide to setup a apollo client to take to me server. But it failed at very beginning stage. I wonder what wrong with my code. Is there anything I missed?

答:
In order to initialize Apollo Client, you must specify link & cache properties on the config object. You can override this by using the default import.</p>

```<code>const apollo = require('apollo-boost');
const ApolloClient = apollo.default;

const client = new ApolloClient({
  uri: 'http://localhost:8000/graphql'
});
</code>```

Body:
I have below code written in nodejs10.

const ApolloClient = require('apollo-boost');

const client = new ApolloClient({
  uri: 'http://localhost:8000/graphql'
});

The error I got when running this program is:

const client = ApolloClient({
               ^

TypeError: ApolloClient is not a function

Below is the dependencies:

"apollo-boost": "^0.3.1",
    "apollo-cache-inmemory": "^1.6.0",
    "apollo-client": "^2.6.0",
    "apollo-link-http": "^1.5.14",
    "apollo-server": "^2.5.0",
    "apollo-server-express": "^2.5.1",

I followed the user guide to setup a apollo client to take to me server. But it failed at very beginning stage. I wonder what wrong with my code. Is there anything I missed?

Body:
In order to initialize Apollo Client, you must specify link & cache properties on the config object. You can override this by using the default import.

const apollo = require('apollo-boost');
const ApolloClient = apollo.default;

const client = new ApolloClient({
  uri: 'http://localhost:8000/graphql'
});


问:
Read a string from shared preferences in flutter
I have saved two strings using shared preferences. I want to retrieve the strings individually and display it as texts.

Write:

```<code>_nameSaver() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setString('name', nameController.text);
    prefs.setString('school', schoolController.text);
  }

RaisedButton(onPressed: () => _nameSaver(),);
</code>```

Read:

```<code>  _nameRetriever() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    final name = prefs.getString('name') ?? '';
    final school = prefs.getString('school') ?? '';

    print(name);
    print(school);
  }
</code>```

I should extract out the name and school from the shared preference and display it on the list tile respectively. Title for name and subtitle for school. However i am unsure on how to extract it this way using a method await.

```<code>ListTile(title: Text("")
         subtitle: Text(""),),
</code>```

答:
Can Read value from pref. as -

```<code>getPref('name');
</code>```

Using this method-

```<code> getPref(String key) async {
        SharedPreferences prefs = await SharedPreferences.getInstance();
        String auth = prefs.getString(key);
     }
</code>```

Worked for me.

Body:
I have saved two strings using shared preferences. I want to retrieve the strings individually and display it as texts.

Write:

_nameSaver() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setString('name', nameController.text);
    prefs.setString('school', schoolController.text);
  }

RaisedButton(onPressed: () => _nameSaver(),);

Read:

  _nameRetriever() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    final name = prefs.getString('name') ?? '';
    final school = prefs.getString('school') ?? '';

    print(name);
    print(school);
  }

I should extract out the name and school from the shared preference and display it on the list tile respectively. Title for name and subtitle for school. However i am unsure on how to extract it this way using a method await.

ListTile(title: Text("")
         subtitle: Text(""),),

Body:
Can Read value from pref. as -

getPref('name');

Using this method-

 getPref(String key) async {
        SharedPreferences prefs = await SharedPreferences.getInstance();
        String auth = prefs.getString(key);
     }

Worked for me.


问:
Change color of caption text in toctree
Is there a way to change the color of captions on a sphinx webpage? I'm using the :caption: directive with toctree, but the caption comes out almost the same color as the sidebar. For reference here is the link to the page with the hard to see captions and here is my index file:

```<code>Contents
============

.. toctree::
   :caption: User Documentation
   :maxdepth: 2

   overview
   installation
   tutorial

.. toctree::
   :maxdepth: 2
   :caption: Developer Documentation

   dev/conventions
   dev/enviroment
   dev/docs
   dev/site
   doc/modules

* :ref:`genindex`
* :ref:`modindex`

.. toctree::
   :maxdepth: 2
   :caption: Support

   trouble/faq
   trouble/issuetracker
   trouble/contact
</code>```

答:
@aflp91 will indeed change caption text in the side bar, but also the caption text in the toctree as well.

If you want the caption color to change in side bar - and side bar only - you should add this

.wy-menu > .caption > span.caption-text {
  color: #ffffff;
}
```

Title: Change color of caption text in toctree

Body:
Is there a way to change the color of captions on a sphinx webpage? I'm using the :caption: directive with toctree, but the caption comes out almost the same color as the sidebar. For reference here is the link to the page with the hard to see captions and here is my index file:

Contents
============

.. toctree::
   :caption: User Documentation
   :maxdepth: 2

   overview
   installation
   tutorial

.. toctree::
   :maxdepth: 2
   :caption: Developer Documentation

   dev/conventions
   dev/enviroment
   dev/docs
   dev/site
   doc/modules

* :ref:`genindex`
* :ref:`modindex`

.. toctree::
   :maxdepth: 2
   :caption: Support

   trouble/faq
   trouble/issuetracker
   trouble/contact


问:
How do I make the program do something when an object is destroyed?
I have plane(as in air plane) objects in my program, they get destroyed when bullets hit them but they also get destroyed after 5 seconds, when they exit the screen.

I also have a health script that resets the whole thing when it goes down to 0, and I want to remove a point every time the object is destroyed, but only when off screen. So I keep the scripts separate.

I use this in the ships spawn script to destroy them after 5 seconds, simple enough.

```<code>Destroy(spawnedPlane, 5f);
</code>```

It would be perfect if I could just have some code that does "Destroy this object after X seconds AND add this to this value". Because as I understand it, "destroy" only accepts 2 parameters and nothing else.

Surely it is possible but I am at a loss. Still very new to this. Sorry if this is very unclear but I barely know what I'm doing myself.

答:
You can use events to cleanly achieve what you are after. Below is an example of an event you might find useful. Other objects can listen to the event and once it is triggered, they will be notified.

```<code>[Serializable]
public class PlaneEvent : UnityEvent<Plane> { }
</code>```

Once you have defined your event, you can then add it as a field in your Plane. Once your plane has been destroyed, you can fire the event and it will in turn notify anyone who is listening!

```<code>public class Plane : MonoBehaviour {

    public PlaneEvent OnDestroyed;

    public void Destroy () {
        Destroy(gameObject);
        OnDestroyed.Invoke(this);
        OnDestroyed.RemoveAllListeners();
    }

}
</code>```

Now in our score class, we add a method that will be called once the OnDestroyed plane event is triggered.

```<code>public class Score : MonoBehaviour {

    public void AddPointsFor (Plane plane) {
        Debug.Log("A Plane was destroyed!");
        //Tick a counter, add points, do whatever you want!
    }

}
</code>```

Once we have these pieces, it is trivial to make them work together. We take the plane and we add the score as a listener to the OnDestroyed event. Then once the plane is destroyed, the event is fired and score is told to add points.

```<code>public class Game : MonoBehaviour {

    [SerializeField]
    private Score _score;
    [SerializeField]
    private Plane _plane;

    public void Start () {
        // When you are destroyed let me know so I can add some points.
        _plane.OnDestroyed.AddListener(_score.AddPointsFor);
        _plane.Destroy();
    }
}
</code>```

Another big advantage in using events is your plane has no idea that a score even exists, it will let anyone who cares know that it has been destroyed. In the same way this event could also be used to trigger particle effects, animations and sound effects when the plane is destroyed and all you need to do is add more listeners.

Body:
I have plane(as in air plane) objects in my program, they get destroyed when bullets hit them but they also get destroyed after 5 seconds, when they exit the screen.

I also have a health script that resets the whole thing when it goes down to 0, and I want to remove a point every time the object is destroyed, but only when off screen. So I keep the scripts separate.

I use this in the ships spawn script to destroy them after 5 seconds, simple enough.

Destroy(spawnedPlane, 5f);

It would be perfect if I could just have some code that does "Destroy this object after X seconds AND add this to this value". Because as I understand it, "destroy" only accepts 2 parameters and nothing else.

Surely it is possible but I am at a loss. Still very new to this. Sorry if this is very unclear but I barely know what I'm doing myself.

Body:
You can use events to cleanly achieve what you are after. Below is an example of an event you might find useful. Other objects can listen to the event and once it is triggered, they will be notified.

[Serializable]
public class PlaneEvent : UnityEvent<Plane> { }

Once you have defined your event, you can then add it as a field in your Plane. Once your plane has been destroyed, you can fire the event and it will in turn notify anyone who is listening!

public class Plane : MonoBehaviour {

    public PlaneEvent OnDestroyed;

    public void Destroy () {
        Destroy(gameObject);
        OnDestroyed.Invoke(this);
        OnDestroyed.RemoveAllListeners();
    }

}

Now in our score class, we add a method that will be called once the OnDestroyed plane event is triggered.

public class Score : MonoBehaviour {

    public void AddPointsFor (Plane plane) {
        Debug.Log("A Plane was destroyed!");
        //Tick a counter, add points, do whatever you want!
    }

}

Once we have these pieces, it is trivial to make them work together. We take the plane and we add the score as a listener to the OnDestroyed event. Then once the plane is destroyed, the event is fired and score is told to add points.

public class Game : MonoBehaviour {

    [SerializeField]
    private Score _score;
    [SerializeField]
    private Plane _plane;

    public void Start () {
        // When you are destroyed let me know so I can add some points.
        _plane.OnDestroyed.AddListener(_score.AddPointsFor);
        _plane.Destroy();
    }
}

Another big advantage in using events is your plane has no idea that a score even exists, it will let anyone who cares know that it has been destroyed. In the same way this event could also be used to trigger particle effects, animations and sound effects when the plane is destroyed and all you need to do is add more listeners.


问:
How to close application using hardware back button
The hardware back button does not closes the application in Ionic 4 either with cordova or capacitor.

This feature was working in Ionic 3 but now in Ionic 4 it only navigates back.

Is there a way out to close the application using hardware back button.

答:
In the app.component.ts, you need below code, when you press your mobile hardware back button

```<code>initializeApp() {
        this.platform.ready().then(() => {
          this.statusBar.backgroundColorByHexString("#efa300");
          this.splashScreen.hide();
          this.platform.backButton.subscribe(() => {
            this.routerOutlets.forEach((outlet: IonRouterOutlet) => {
              if (this.router.url === '/home') {  //mention your router url(when to exit your app)
                if (new Date().getTime() - this.lastTimeBackPress < this.timePeriodToExit) {
                  navigator['app'].exitApp();
                }
              }
            });
          })
        });
      }
</code>```

Body:
In the app.component.ts, you need below code, when you press your mobile hardware back button

initializeApp() {
        this.platform.ready().then(() => {
          this.statusBar.backgroundColorByHexString("#efa300");
          this.splashScreen.hide();
          this.platform.backButton.subscribe(() => {
            this.routerOutlets.forEach((outlet: IonRouterOutlet) => {
              if (this.router.url === '/home') {  //mention your router url(when to exit your app)
                if (new Date().getTime() - this.lastTimeBackPress < this.timePeriodToExit) {
                  navigator['app'].exitApp();
                }
              }
            });
          })
        });
      }


问:
I need to add the items from list A to list B, only when the item already exists in list B
I need to add all the items in list A in to list B, if and only if the items already exist in list B, even if there are multiple items that are same in list A. How can I do this? Right now, it stops after the first of the same words. Say for example, List A is [the, a, sure, book, is, the, best], and list B is [the, rock], I need to add the two "the"s in list A to list B, to make a total of three "the"s in list B

It's for a beginner's class in python. I've tried different formats of the for loop, but it doesn't seem to work. There is a for loop before this, that creates the list B, I think it maybe because of the back to back for loops.

```<code>for word in list_a:
    if word[0].isupper() == True:
        list_b.append(word)

list_b = [word.lower() for word in list_b]

for word in list_a:
    if word in list_b:
        list_b.append(word)

list_b = [word.capitalize() for word in list_b]
</code>```

The second for loop is the one giving me trouble. I have pasted the larger code which I am trying to work with. So my main objective is to first separate the words that are capitalized in list A in to list B.

Then lowercase list B, so I can find the same words in list A that are not capitalized, and then add those to list B as well. Then capitalize all of list B again to print the count.

I know that there is an easier way to do this, where I can just make the original string lowercase and then work from there. However, in this case I need to keep track of the words that were originally capitalized, because when I print the words with their total counts, the words that were originally capitalized, need to print in their capitalized form rather than the lowercase form.

Therefore, the expected outcome I am looking for is list B as [the, rock, the, the].

答:
```<code>a = ['the', 'a', 'sure', 'book', 'is', 'the', 'best']
b = ['the', 'rock']

b = b + [text for text in a if text in b]
</code>```

Body:
I need to add all the items in list A in to list B, if and only if the items already exist in list B, even if there are multiple items that are same in list A. How can I do this? Right now, it stops after the first of the same words. Say for example, List A is [the, a, sure, book, is, the, best], and list B is [the, rock], I need to add the two "the"s in list A to list B, to make a total of three "the"s in list B

It's for a beginner's class in python. I've tried different formats of the for loop, but it doesn't seem to work. There is a for loop before this, that creates the list B, I think it maybe because of the back to back for loops.

for word in list_a:
    if word[0].isupper() == True:
        list_b.append(word)

list_b = [word.lower() for word in list_b]

for word in list_a:
    if word in list_b:
        list_b.append(word)

list_b = [word.capitalize() for word in list_b]

The second for loop is the one giving me trouble. I have pasted the larger code which I am trying to work with. So my main objective is to first separate the words that are capitalized in list A in to list B.

Then lowercase list B, so I can find the same words in list A that are not capitalized, and then add those to list B as well. Then capitalize all of list B again to print the count.

I know that there is an easier way to do this, where I can just make the original string lowercase and then work from there. However, in this case I need to keep track of the words that were originally capitalized, because when I print the words with their total counts, the words that were originally capitalized, need to print in their capitalized form rather than the lowercase form.

Therefore, the expected outcome I am looking for is list B as [the, rock, the, the].


问:
The endpoint reference (EPR) for the Operation not found when invoking proxy service in WSO2 ESB
I'm using wso2 esb 5.0. I created the proxy service for invoke soap endpoint. Below mentioned the proxy service code.

```<code><?xml version="1.0" encoding="UTF-8"?>
<proxy xmlns="http://ws.apache.org/ns/synapse"
       name="LicenseRenewalSystem"
       startOnLoad="true"
       statistics="disable"
       trace="disable"
       transports="http,https">
   <target>
      <inSequence>
         <log/>
         <property expression="get-property('transport','VehicleNo')"
                   name="vehicleNo"
                   scope="default"
                   type="STRING"/>
         <log>
            <property expression="get-property('default','vehicleNo')" name="VehicleNo"/>
         </log>
         <payloadFactory media-type="xml">
            <format>
               <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
                                 xmlns:wsa="http://www.w3.org/2005/08/addressing"
                                 xmlns:sam="http://sample.esb.org">
                  <soapenv:Header/>
                  <soapenv:Body>
                     <sam:getPolicyID>
                        <sam:vehicleNumber>$1</sam:vehicleNumber>
                     </sam:getPolicyID>
                  </soapenv:Body>
               </soapenv:Envelope>
            </format>
            <args>
               <arg evaluator="xml" expression="get-property('default','vehicleNo')"/>
            </args>
         </payloadFactory>
         <log level="full"/>
         <property name="ContentType" scope="axis2" type="STRING" value="text/xml"/>
         <property name="messageType" scope="axis2" value="text/xml"/>
         <call>
            <endpoint>
               <address format="soap12"
                        uri="http://172.17.0.1:9763/services/EmissionTestService?wsdl2"/>
            </endpoint>
         </call>
         <log level="full"/>
      </inSequence>
   </target>
   <description/>
</proxy>
</code>```

I used header value (VehicleNo) to pass the proxy service.
But I invoke this proxy using postmen, below error is occurred.

```<code>The endpoint reference (EPR) for the Operation not found is http://172.17.0.1:9763/services/EmissionTestService and the WSA Action = null. If this EPR was previously reachable, please contact the server administrator.
</code>```

Can anyone help me to slove this issue.

答:
This kind errors comes up when the related WSDL file for the proxy is not found. Please make sure that the Endpoint that you are calling is available in the ESB instance.

Please refer to the guide for more info. https://wso2.com/library/176/

Also a similar kind of question is answered here. The endpoint reference (EPR) for the Operation not found is

Body:
I'm using wso2 esb 5.0. I created the proxy service for invoke soap endpoint. Below mentioned the proxy service code.

<?xml version="1.0" encoding="UTF-8"?>
<proxy xmlns="http://ws.apache.org/ns/synapse"
       name="LicenseRenewalSystem"
       startOnLoad="true"
       statistics="disable"
       trace="disable"
       transports="http,https">
   <target>
      <inSequence>
         <log/>
         <property expression="get-property('transport','VehicleNo')"
                   name="vehicleNo"
                   scope="default"
                   type="STRING"/>
         <log>
            <property expression="get-property('default','vehicleNo')" name="VehicleNo"/>
         </log>
         <payloadFactory media-type="xml">
            <format>
               <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
                                 xmlns:wsa="http://www.w3.org/2005/08/addressing"
                                 xmlns:sam="http://sample.esb.org">
                  <soapenv:Header/>
                  <soapenv:Body>
                     <sam:getPolicyID>
                        <sam:vehicleNumber>$1</sam:vehicleNumber>
                     </sam:getPolicyID>
                  </soapenv:Body>
               </soapenv:Envelope>
            </format>
            <args>
               <arg evaluator="xml" expression="get-property('default','vehicleNo')"/>
            </args>
         </payloadFactory>
         <log level="full"/>
         <property name="ContentType" scope="axis2" type="STRING" value="text/xml"/>
         <property name="messageType" scope="axis2" value="text/xml"/>
         <call>
            <endpoint>
               <address format="soap12"
                        uri="http://172.17.0.1:9763/services/EmissionTestService?wsdl2"/>
            </endpoint>
         </call>
         <log level="full"/>
      </inSequence>
   </target>
   <description/>
</proxy>

I used header value (VehicleNo) to pass the proxy service.
But I invoke this proxy using postmen, below error is occurred.

The endpoint reference (EPR) for the Operation not found is http://172.17.0.1:9763/services/EmissionTestService and the WSA Action = null. If this EPR was previously reachable, please contact the server administrator.

Can anyone help me to slove this issue.


问:
How to ignore duplicate keys while parsing json using gson?
I am getting a a duplicate key exception while parsing JSON response containing timestamps as keys using GSON. It gives the following error:

com.google.gson.JsonSyntaxException: duplicate key: 1463048935
          at com.google.gson.internal.bind.MapTypeAdapterFactory$Adapter.read(MapTypeAdapterFactory.java:186)
          at com.google.gson.internal.bind.MapTypeAdapterFactory$Adapter.read(MapTypeAdapterFactory.java:141)

How do I make it ignore the duplicate entries, and just parse it to a map with any one from the duplicate entries?

答:
Hackerman solution, tested and working using GSON v2.8.5, but use at your own risk! Whenever you update GSON to a new version, make sure to check whether this is still working!

Basically, you can use the fact that the generic ObjectTypeAdapter ignores duplicates as seen here:

Looks like MapTypeAdapterFactory checks for duplicate

```<code>  V replaced = map.put(key, value);
  if (replaced != null) {
    throw new JsonSyntaxException("duplicate key: " + key);
  }
</code>```

however ObjectTypeAdapter does not

```<code>case BEGIN_OBJECT:
  Map<String, Object> map = new LinkedTreeMap<String, Object>();
  in.beginObject();
  while (in.hasNext()) {
    map.put(in.nextName(), read(in));
  }
  in.endObject();
  return map;
</code>```

What you can do now is trying to deserialize using fromJson as usual, but catch the "duplicate key" exception, deserialize as a generic Object, which will ignore duplicates, serialize it again, which will result in a JSON string without duplicate keys, and finally deserialize using the correct type it's actually meant to be.

Here is a Kotlin code example:

```<code>fun <T> String.deserialize(gson: Gson, typeToken: TypeToken<T>): T {
    val type = typeToken.type
    return try {
        gson.fromJson<T>(this, type)
    } catch (e: JsonSyntaxException) {
        if (e.message?.contains("duplicate key") == true) {
            gson.toJson(deserialize(gson, object : TypeToken<Any>() {})).deserialize(gson, typeToken)
        } else {
            throw e
        }
    }
}
</code>```

Obviously, this adds (potentially heavy) overhead by requiring 2 deserializations and an additional serialization, but currently I don't see any other way to do this. If Google decides to add an option for a built-in way to ignore duplicates, as suggested here, better switch to that.

Body:
Hackerman solution, tested and working using GSON v2.8.5, but use at your own risk! Whenever you update GSON to a new version, make sure to check whether this is still working!

Basically, you can use the fact that the generic ObjectTypeAdapter ignores duplicates as seen here:

Looks like MapTypeAdapterFactory checks for duplicate

  V replaced = map.put(key, value);
  if (replaced != null) {
    throw new JsonSyntaxException("duplicate key: " + key);
  }

however ObjectTypeAdapter does not

case BEGIN_OBJECT:
  Map<String, Object> map = new LinkedTreeMap<String, Object>();
  in.beginObject();
  while (in.hasNext()) {
    map.put(in.nextName(), read(in));
  }
  in.endObject();
  return map;

What you can do now is trying to deserialize using fromJson as usual, but catch the "duplicate key" exception, deserialize as a generic Object, which will ignore duplicates, serialize it again, which will result in a JSON string without duplicate keys, and finally deserialize using the correct type it's actually meant to be.

Here is a Kotlin code example:

fun <T> String.deserialize(gson: Gson, typeToken: TypeToken<T>): T {
    val type = typeToken.type
    return try {
        gson.fromJson<T>(this, type)
    } catch (e: JsonSyntaxException) {
        if (e.message?.contains("duplicate key") == true) {
            gson.toJson(deserialize(gson, object : TypeToken<Any>() {})).deserialize(gson, typeToken)
        } else {
            throw e
        }
    }
}

Obviously, this adds (potentially heavy) overhead by requiring 2 deserializations and an additional serialization, but currently I don't see any other way to do this. If Google decides to add an option for a built-in way to ignore duplicates, as suggested here, better switch to that.


问:
how to configure network to enable discovery service
I am trying to set up a fabric network in multiple machines using aws.
The problem I am having is that I am trying to enable discovery service using node sdk. It works  when I am in localhost using docker, but doesn't work if I have a distributed network in multiple machines because it tries to endorse to localhost instead of the assigned ips.

I don't have the option asLocalhost set to true so I don't know why it tries to do it anyways.

答:
In the SDK must be set the Discovery options accordingly with your network configuration.

Below you can find the link to the official NodeJS Fabric SDK:

https://fabric-sdk-node.github.io/release-1.4/module-fabric-network.Gateway.html#~DiscoveryOptions

Here also a tutorial on Discovery Service:

https://fabric-sdk-node.github.io/release-1.4/tutorial-discovery.html


问:
Flask - how to hook into all @login_required decorated views
In my Flask applicaiton I have around 30 views which are decorated with the @login_required decorator.
My goal is: I want to call a python method - lets call it "refreshSession()" - every time a view which is @login_required decorated is called.
Is there a way to hook into this decorator? I don't want to write the line "refreshSession()" 30 times.

答:
As far as i know, there's no way to hook directly into @login_required decorator.

Maybe you should try to call refreshSession on your Flask-Login user_loader function?

More information: https://flask-login.readthedocs.io/en/latest/#flask_login.LoginManager.user_loader

Something like this:

```<code>from flask_login import LoginManager

login_manager = LoginManager()

@login_manager.user_loader
def load_user(user_id):
    refreshSession()
    # Fetch user from database
    user = User.get_by_id(user_id)
    return user
</code>```

Alternatively you could create your own login_required decorator, and then call refreshSession() inside it.

login_required decorator source: https://github.com/maxcountryman/flask-login/blob/3e521a326696cafbfbebfbb80a2fbffed68e6cf3/flask_login/utils.py#L231

Body:
As far as i know, there's no way to hook directly into @login_required decorator.

Maybe you should try to call refreshSession on your Flask-Login user_loader function?

More information: https://flask-login.readthedocs.io/en/latest/#flask_login.LoginManager.user_loader

Something like this:

from flask_login import LoginManager

login_manager = LoginManager()

@login_manager.user_loader
def load_user(user_id):
    refreshSession()
    # Fetch user from database
    user = User.get_by_id(user_id)
    return user

Alternatively you could create your own login_required decorator, and then call refreshSession() inside it.

login_required decorator source: https://github.com/maxcountryman/flask-login/blob/3e521a326696cafbfbebfbb80a2fbffed68e6cf3/flask_login/utils.py#L231


问:
pandoc lua filter to replace tex macro
I am trying to write a pandoc lua filter to replace the \ce{} command from the latex package mhchem.

This is what I tried with the example of \ce{NO3-}, but it doesn't work and renders a blank in the rtf output file:

return {
  {
    Str = function (elem)
      if elem.text == "\\ce%{%NO3-%}%" then
        return {pandoc.Str "NO3"}
      else
        return elem
      end
    end,
  }
}
```

<p>My pandoc command is:</p>

<pre class="lang-sh prettyprint-override"><code>pandoc -s myfile.tex --lua-filter myfilter.lua -o myfile.rtf
</code>```

答: You only need to escape special characters before them rather than before and after and you also need to escape -, but don't need to escape {}, so "\\ce%{%NO3-%}%" should probably be "\\ce{NO3%-}". You can see the list of "magic characters" that need escaping in the Patterns chapter.

Title: pandoc lua filter to replace tex macro

Body:
I am trying to write a pandoc lua filter to replace the \ce{} command from the latex package mhchem.

This is what I tried with the example of \ce{NO3-}, but it doesn't work and renders a blank in the rtf output file:

return {
  {
    Str = function (elem)
      if elem.text == "\\ce%{%NO3-%}%" then
        return {pandoc.Str "NO3"}
      else
        return elem
      end
    end,
  }
}

My pandoc command is:

pandoc -s myfile.tex --lua-filter myfilter.lua -o myfile.rtf


问:
How to search for a specific dynamic pattern of a field's in mongodb.?
I need to search mongodb collection for a specific pattern field. I tried using {$exists:true}; However, this gives results only if you provide exact field.

I tried using {$exists:true} for my field. But this does not give results if you give some pattern.

```<code>{
"field1":"value1",
"field2":"value2",
"field3":object
{/arjun1/pat1: 1,
/arjun2/pat2: 3,
/arjun3/pat3: 5
}
"field4":"value4",
}
</code>```

From some field, I get the keys pat3 & field3. From this I would need to find out if the value /arjun3/pat3 exists in the document.
If I use {"field3./arjun3/pat3":{$exists:true}}, this would give me results. But the problem is I get only field3 and pat3 and I need to use some pattern matching like field3.*.pat3 and then use $expr or $exists; which I'm not exactly sure how to. Please help.

答:
you could try something of this kind</p>

```<code>db.arjun.find(
    {"field3" : {
        "$elemMatch" : { $and: [
            {"arjun3.pat3" : {$exists:true}},
            {"arjun3.pat3" : 5}
        ]
        }}}
);
</code>```

Body:
I need to search mongodb collection for a specific pattern field. I tried using {$exists:true}; However, this gives results only if you provide exact field.

I tried using {$exists:true} for my field. But this does not give results if you give some pattern.

{
"field1":"value1",
"field2":"value2",
"field3":object
{/arjun1/pat1: 1,
/arjun2/pat2: 3,
/arjun3/pat3: 5
}
"field4":"value4",
}

From some field, I get the keys pat3 & field3. From this I would need to find out if the value /arjun3/pat3 exists in the document.
If I use {"field3./arjun3/pat3":{$exists:true}}, this would give me results. But the problem is I get only field3 and pat3 and I need to use some pattern matching like field3.*.pat3 and then use $expr or $exists; which I'm not exactly sure how to. Please help.

Body:
you could try something of this kind

db.arjun.find(
    {"field3" : {
        "$elemMatch" : { $and: [
            {"arjun3.pat3" : {$exists:true}},
            {"arjun3.pat3" : 5}
        ]
        }}}
);


问:
ValueError: Input contains NaN, infinity or a value too large for dtype('float64') after using df.drop command
I understand that the error is because I have NaN values in my csv, but I have the command df.dropna in many places in my code, so I don't understand why it is interpreting the code as still having NaN values.

Now it is making me write more because of my long code, you can just ignore this, it is gibberish, please refer to the above sentence for my question, I greatly appreciate your help for helping me solve it, thanks!

```<code>import numpy as np
import pandas as pd
import pickle
from collections import Counter
from sklearn import svm, model_selection as cross_validation, neighbors
from sklearn.ensemble import RandomForestClassifier, VotingClassifier

def process_data_for_lables(ticker):
    hm_days = 7
    df = pd.read_csv('sp500_joined_closes.csv', index_col=0)
    df.dropna(inplace=True)
    tickers = df.columns.values.tolist()
    df.fillna(0)

    for i in range (1,hm_days+1):
        df['{}_{}d'.format(ticker, i)] = (df[ticker].shift(-i)-df[ticker])/ df[ticker]

    df.fillna(0)
    return tickers, df
#process_data_for_lables('XOM')

def buy_sell_hold(*args):
    cols = [c for c in args]
    requirement = 0.02
    for col in cols:
        if col > requirement:
            return 1
        if col < -requirement:
            return-1
    return 0

def extract_featuresets(ticker):
    tickers, df = process_data_for_lables(ticker)
    df.dropna(inplace=True)
    df['{}_target'.format(ticker)] = list(map(buy_sell_hold,
                                              df['{}_1d'.format(ticker)],
                                              df['{}_2d'.format(ticker)],
                                              df['{}_3d'.format(ticker)],
                                              df['{}_4d'.format(ticker)],
                                              df['{}_5d'.format(ticker)],
                                              df['{}_6d'.format(ticker)],
                                              df['{}_7d'.format(ticker)]))

    vals = df['{}_target'.format(ticker)].values.tolist()
    str_vals = [str(i) for i in vals]
    print('Data spread:', Counter(str_vals))
    df.fillna(0)

    df = df.replace([np.inf, -np.inf], np.nan)
    df.dropna(inplace=True)

    df_vals = df[[ticker for ticker in tickers]].pct_change()
    df_vals = df_vals.replace([np.inf, -np.inf], 0)
    df_vals.fillna(0)

    X = df_vals.values
    y = df['{}_target'.format(ticker)].values
    np.nan_to_num(X)
    return X, y, df
#extract_featuresets('XOM')

def do_ml(ticker):

    X, y, df = extract_featuresets(ticker)
    X_train, X_test, y_train, y_test = cross_validation.train_test_split(X,
                                                                    y,
                                                                    test_size = 0.25)
    clf = neighbors.KNeighborsClassifier()
    clf.fit(X_train, y_train)
    confidence = clf.score(X_test, y_test)
    predictions = clf.predict(X_test)
    print('Predicted spread:', Counter(predictions))

    return confidence

do_ml('BAC')
</code>```

ValueError: Input contains NaN, infinity or a value too large for
  dtype('float64').

答:
There's a couple of places where the NaNs might be propagated. You could try:</p>

```<code>df_vals = df_vals.fillna(0)
...
X = np.nan_to_num(X)
</code>```

Body:
I understand that the error is because I have NaN values in my csv, but I have the command df.dropna in many places in my code, so I don't understand why it is interpreting the code as still having NaN values.

Now it is making me write more because of my long code, you can just ignore this, it is gibberish, please refer to the above sentence for my question, I greatly appreciate your help for helping me solve it, thanks!

import numpy as np
import pandas as pd
import pickle
from collections import Counter
from sklearn import svm, model_selection as cross_validation, neighbors
from sklearn.ensemble import RandomForestClassifier, VotingClassifier

def process_data_for_lables(ticker):
    hm_days = 7
    df = pd.read_csv('sp500_joined_closes.csv', index_col=0)
    df.dropna(inplace=True)
    tickers = df.columns.values.tolist()
    df.fillna(0)

    for i in range (1,hm_days+1):
        df['{}_{}d'.format(ticker, i)] = (df[ticker].shift(-i)-df[ticker])/ df[ticker]

    df.fillna(0)
    return tickers, df
#process_data_for_lables('XOM')

def buy_sell_hold(*args):
    cols = [c for c in args]
    requirement = 0.02
    for col in cols:
        if col > requirement:
            return 1
        if col < -requirement:
            return-1
    return 0

def extract_featuresets(ticker):
    tickers, df = process_data_for_lables(ticker)
    df.dropna(inplace=True)
    df['{}_target'.format(ticker)] = list(map(buy_sell_hold,
                                              df['{}_1d'.format(ticker)],
                                              df['{}_2d'.format(ticker)],
                                              df['{}_3d'.format(ticker)],
                                              df['{}_4d'.format(ticker)],
                                              df['{}_5d'.format(ticker)],
                                              df['{}_6d'.format(ticker)],
                                              df['{}_7d'.format(ticker)]))

    vals = df['{}_target'.format(ticker)].values.tolist()
    str_vals = [str(i) for i in vals]
    print('Data spread:', Counter(str_vals))
    df.fillna(0)

    df = df.replace([np.inf, -np.inf], np.nan)
    df.dropna(inplace=True)

    df_vals = df[[ticker for ticker in tickers]].pct_change()
    df_vals = df_vals.replace([np.inf, -np.inf], 0)
    df_vals.fillna(0)

    X = df_vals.values
    y = df['{}_target'.format(ticker)].values
    np.nan_to_num(X)
    return X, y, df
#extract_featuresets('XOM')

def do_ml(ticker):

    X, y, df = extract_featuresets(ticker)
    X_train, X_test, y_train, y_test = cross_validation.train_test_split(X,
                                                                    y,
                                                                    test_size = 0.25)
    clf = neighbors.KNeighborsClassifier()
    clf.fit(X_train, y_train)
    confidence = clf.score(X_test, y_test)
    predictions = clf.predict(X_test)
    print('Predicted spread:', Counter(predictions))

    return confidence

do_ml('BAC')

ValueError: Input contains NaN, infinity or a value too large for
  dtype('float64').

Body:
There's a couple of places where the NaNs might be propagated. You could try:

df_vals = df_vals.fillna(0)
...
X = np.nan_to_num(X)


问:
SQL help to make a particular select statement for a table
```<code>CREATE TABLE person (
  id INTEGER PRIMARY KEY,
  first_name TEXT,
  last_name TEXT,
  age INTEGER
);

INSERT INTO person VALUES (0, 'Pat', 'Johnson', 25);
INSERT INTO person VALUES (1, 'John', 'Wells', 28);
</code>```

So I have a table called person and I am trying to query all people younger than Pat Johnson, but I do not want to query it by hard coding.

```<code>SELECT first_name, last_name FROM person WHERE age < 25;
</code>```

^^^ this is an example of what I do not want to do.

答:
We can try an anti-join approach:</p>

```<code>SELECT t1.first_name, t1.last_name
FROM yourTable t1
LEFT JOIN yourTable t2
    ON t1.age > t2.age AND
       t2.first_name = 'Pat' AND
       t2.last_name = 'Johnson'
WHERE
    t2.first_name IS NULL;
</code>```

Body:
CREATE TABLE person (
  id INTEGER PRIMARY KEY,
  first_name TEXT,
  last_name TEXT,
  age INTEGER
);

INSERT INTO person VALUES (0, 'Pat', 'Johnson', 25);
INSERT INTO person VALUES (1, 'John', 'Wells', 28);

So I have a table called person and I am trying to query all people younger than Pat Johnson, but I do not want to query it by hard coding.

SELECT first_name, last_name FROM person WHERE age < 25;

^^^ this is an example of what I do not want to do.

Body:
We can try an anti-join approach:

SELECT t1.first_name, t1.last_name
FROM yourTable t1
LEFT JOIN yourTable t2
    ON t1.age > t2.age AND
       t2.first_name = 'Pat' AND
       t2.last_name = 'Johnson'
WHERE
    t2.first_name IS NULL;


问:
pointer & array conflict
let

```<code>int*p ,b = 5;
p = &b;
</code>```

denotes a ONE DIMENSIONAL array, then what is the output given by following statement

```<code>printf("%d",p);
</code>```

is it an address? if it is an address then tell me which element it belongs,please explain clearly

答:
The p pointer does not denote a one-dimensional array. It is simply a pointer to an integer. It may point to the first element of an array, like when you do int* p = new int[6], but that's something entirely different; in that case you allocate space for a new array of six integers and you store the address of the first one (or, the beginning of the array) in p.

If you print p it will print the memory address it stores. If p "denotes an array" (emphasis on quotes) then you will print the address of the first element of the array.

Title: pointer & array conflict

Body:
let

int*p ,b = 5;
p = &b;

denotes a ONE DIMENSIONAL array, then what is the output given by following statement

printf("%d",p);

is it an address? if it is an address then tell me which element it belongs,please explain clearly