问:
How to correctly read the method signature of the .Any function in C#
I really enjoy using the aggregate functions that C# provides such as .Any(), but I struggle to understand what my options are just looking from the method signature:

Can someone help me better understand the meanings of (Func predicate)? I know that I normally use a lamda fucntion here. But, how that translates back into whatever Func is, I don't understand.

答:
```<code>(extension) bool IEnumerable<string>.Any<string>(Func<string, bool> predicate)(+ 1 overload)
Determines whether any element of a sequence satisfies a condition.

Exceptions:
  ArgumentNullException
</code>```

Means:

You can call this as an extension method.

On an IEnumerable<string>, that is something you can iterate on that gives you string. string is type that holds text.

The name of the method is Any

It has a type argument, which is set to string. You probably can call this on a IEnumerable<T> where T is something other than string.

It takes a Func<string, bool> predicate, that is a delegate to a function that takes a string as input parameter and returns a bool.

There is another overload of the method, which takes different arguments.

The method documentation says it "Determines whether any element of a sequence satisfies a condition." We can presume it goes over the IEnumerable<string> calls the Func<string, bool> passing the string from the IEnumerable<string> passing each value, and returns whether or not it got true for any one of them.

The method is documented to throw an ArgumentNullException, presumubly if you pass a null.

If we look online for it, we find in the official documentation Enumerable.Any. There we can see the other overload and also some examples.

Here is one:

```<code>Pet[] pets =
        { new Pet { Name="Barley", Age=8, Vaccinated=true },
          new Pet { Name="Boots", Age=4, Vaccinated=false },
          new Pet { Name="Whiskers", Age=1, Vaccinated=false } };

    // Determine whether any pets over age 1 are also unvaccinated.
    bool unvaccinated =
        pets.Any(p => p.Age > 1 && p.Vaccinated == false);
</code>```

We see an array of Pet, and we call Any on it. Thus, in this case the type argument is Pet instead of string, given that an array of Pet is a thing over which you can iterate and it gives you elements of type Pet... I'm saying that an array of Pet is an IEnumerable<Pet>... and thus we are calling Any<Pet>.

We observe that the parameter is a lambda expression: p => p.Age > 1 && p.Vaccinated == false

This lambda represents an anonymous function that takes an argument p. Since we know that we are using Any<Pet>, and we know that Any<Pet> wants a delegate to a function that takes a Pet and returns bool, we know that p is a Pet.

The anonymous function takes the Pet p compares the property Age with 1 and the property Vaccinated with false, and return true if Age is greater than 1 and Vaccinated is false.

Looking at the values in the array, we can see that the second item (the one of Name "Boots") has Age greater than 1 and Vaccinated is false. Thus, the anonymous function should return true for that Pet.

And given that Any return true if the predicate (the anonymous funciton) was true for any of the elements, we expect Any to return true in this case. The description of the example and expected output in the official documentation confirms this.

If we still have the doubt, we can, of course, try running the code: code on SharpLab. The expected output is "There are unvaccinated animals over age one.".

If you want to go one step deeper, you can search the reference implementation of Enumerable.Any.

If you know where to look, you can get the .NET Core source for Enumerable.Any, Not guaranteed to stay there, refectoring could put it somewhere else.

You may also be interested in the documentation about extension methods.

See also What is Func, how and when is it used.

Body:
(extension) bool IEnumerable<string>.Any<string>(Func<string, bool> predicate)(+ 1 overload)
Determines whether any element of a sequence satisfies a condition.

Exceptions:
  ArgumentNullException

Means:

You can call this as an extension method.

On an IEnumerable<string>, that is something you can iterate on that gives you string. string is type that holds text.

The name of the method is Any

It has a type argument, which is set to string. You probably can call this on a IEnumerable<T> where T is something other than string.

It takes a Func<string, bool> predicate, that is a delegate to a function that takes a string as input parameter and returns a bool.

There is another overload of the method, which takes different arguments.

The method documentation says it "Determines whether any element of a sequence satisfies a condition." We can presume it goes over the IEnumerable<string> calls the Func<string, bool> passing the string from the IEnumerable<string> passing each value, and returns whether or not it got true for any one of them.

The method is documented to throw an ArgumentNullException, presumubly if you pass a null.

If we look online for it, we find in the official documentation Enumerable.Any. There we can see the other overload and also some examples.

Here is one:

Pet[] pets =
        { new Pet { Name="Barley", Age=8, Vaccinated=true },
          new Pet { Name="Boots", Age=4, Vaccinated=false },
          new Pet { Name="Whiskers", Age=1, Vaccinated=false } };

    // Determine whether any pets over age 1 are also unvaccinated.
    bool unvaccinated =
        pets.Any(p => p.Age > 1 && p.Vaccinated == false);

We see an array of Pet, and we call Any on it. Thus, in this case the type argument is Pet instead of string, given that an array of Pet is a thing over which you can iterate and it gives you elements of type Pet... I'm saying that an array of Pet is an IEnumerable<Pet>... and thus we are calling Any<Pet>.

We observe that the parameter is a lambda expression: p => p.Age > 1 && p.Vaccinated == false

This lambda represents an anonymous function that takes an argument p. Since we know that we are using Any<Pet>, and we know that Any<Pet> wants a delegate to a function that takes a Pet and returns bool, we know that p is a Pet.

The anonymous function takes the Pet p compares the property Age with 1 and the property Vaccinated with false, and return true if Age is greater than 1 and Vaccinated is false.

Looking at the values in the array, we can see that the second item (the one of Name "Boots") has Age greater than 1 and Vaccinated is false. Thus, the anonymous function should return true for that Pet.

And given that Any return true if the predicate (the anonymous funciton) was true for any of the elements, we expect Any to return true in this case. The description of the example and expected output in the official documentation confirms this.

If we still have the doubt, we can, of course, try running the code: <a href="https://sharplab.io/#v2:EYLgxg9gTgpgtADwGwBYA0AXEUCuA7AHwAEAmARgFgAoIgBgAIiyA6AGQEs8BHAbmutL0ACjAzUA3tXrTGAZkZkGAOQCGAWxj1x9AOaie9AM776AXykyi8zhnoBBPVt0njGA+aoy59YBAgAbegA1FTAwThUMGAATJz03IxMPDwESBQB2CQtpJiRGFHoAWRVOAAoASmytKq87PABPAFEEWQq+TxkPLyqrBTyiArqmloqqyQ6vaQB6KfoAYVhIzRU8ehUoKBV6+ggAM2FRQ2YamREMAG0AXXoAB0P6AF4Tyac8GAB3A9ttVQ0HgCIAELrfwwer/ND2PQPAAckJCYQiUWiDwwuE0pjQzxe9DenzOTl+MABgL8GEMEKhxPQwVC4TwSxRuxU/mMZixExxXjxX0J6mJ/wA6gALdiGADWMCgFMhDmJZHhdKRMQezNZGLM7WxM3oABFRFK1JxNO9haIzVA1g1bvcIAA3KVrRxkNawNasiD0fB2pUM5HHTleXwBL14H2Iv0xR7Yrx3cnMIalG6PAB8twTjjTLoAZNn0wj6YzHg96GrjOUtYHLGQAJylGMyf4AFQtmnEtFMofDheRVvYahZhh2DstKkcEDezAhDek3t9RYA/PR/usYP96CBl6vcRBbCtwRWqskgA==" rel="nofollow noreferrer">code on SharpLab. The expected output is "There are unvaccinated animals over age one.".

If you want to go one step deeper, you can search the reference implementation of Enumerable.Any.

If you know where to look, you can get the .NET Core source for Enumerable.Any, Not guaranteed to stay there, refectoring could put it somewhere else.

You may also be interested in the documentation about extension methods.

See also What is Func, how and when is it used.


来源: stackexchange

答:
But, how that translates back into whatever Func is?

Well, first we need to know what Func is.

Let's see how Func is declared:

```<code>public delegate TResult Func<in T,out TResult>(T arg);
</code>```

We can see that Func is a delegate. If you don't know what a delegate is, there are wonder pages out there that tell you about them: 1, 2, 3.

How is related to the lambda expression you pass in?

The declaration says that Func is a delegate that takes a parameter of type T, and returns a TResult. From the signature of Any, we can see that T is string while TResult is bool in this particular case.

This means that you can convert a lambda expression, (or a method group,) that takes a string as a parameter and returns bool to an instance of Func<string, bool>.

Let's say you call Any like this:

```<code>something.Any(x => x.Length > 10)
</code>```

From the parameter type, the compiler infers that the lambda expression must take a string, so the type of x must be string. And the lambda expression must also return a bool, which it does, so we're good! The lambda expression is converted to an instance of Func<string, bool>.

ContentLicense: CC BY-SA 4.0

Title: How to correctly read the method signature of the .Any function in C#

Body:
I really enjoy using the aggregate functions that C# provides such as .Any(), but I struggle to understand what my options are just looking from the method signature:

Can someone help me better understand the meanings of (Func predicate)? I know that I normally use a lamda fucntion here. But, how that translates back into whatever Func is, I don't understand.

Body:
But, how that translates back into whatever Func is?

Well, first we need to know what Func is.

Let's see how Func is declared:

public delegate TResult Func<in T,out TResult>(T arg);

We can see that Func is a delegate. If you don't know what a delegate is, there are wonder pages out there that tell you about them: 1, 2, 3.

How is related to the lambda expression you pass in?

The declaration says that Func is a delegate that takes a parameter of type T, and returns a TResult. From the signature of Any, we can see that T is string while TResult is bool in this particular case.

This means that you can convert a lambda expression, (or a method group,) that takes a string as a parameter and returns bool to an instance of Func<string, bool>.

Let's say you call Any like this:

something.Any(x => x.Length > 10)

From the parameter type, the compiler infers that the lambda expression must take a string, so the type of x must be string. And the lambda expression must also return a bool, which it does, so we're good! The lambda expression is converted to an instance of Func<string, bool>.


问:
Building Full Page Web Apps
Im trying to build a full screen web application I really like what MobileMe has done where the whole screen is taken up so it resembles a native desktop application.

I'm looking for tutorials on the topic of designing web apps. I cant seem to find anything on the interwebs.

These are the sorts of things im trying to design:
www.mobileme.com
http://280slides.com/Editor/
https://gomockingbird.com/mockingbird/

BUT - Its not a very complex app, so I don't really want to use any sort of js framework. All I want to create is the html / css and minimal javascript. Unless there is a framework thats small and nimble, I'm open to suggestions

答: I recommend looking at the tutorial 100% Height Layout using CSS which goes into detail in at least how the full height will work. From there you can decide how to layout horizontally.</p>

ContentLicense: CC BY-SA 3.0

Title: Building Full Page Web Apps


问:
Count live online players
I have a playable client and I want to echo/show my online users on my index page. In my database I have the table settings and in that 2 rows
setting and value. e.g. players.online and value 0 as standard counting up to every number how much players there are online. But, it's not counting. The counter stays on 0.</p>

```<code>function onlineusers(){
    $link = mysqli_connect("xxx", "xxx", "xxx" "`xxx");
    mysqli_query($link, "SELECT value FROM settings WHERE value = 'players.online'");
    $i = 0;
    while($b = mysqli_fetch_array($link)){
        if(onlineusers($b['players.online'])){
            $i++;
        }
    }
    return $i;
}
</code>```

答:
You can count the number of rows in DB and return it.</p>

```<code>function onlineusers(){
    $link = mysqli_connect("xxx", "xxx", "xxx" "`xxx");
    $result = mysqli_query($link, "SELECT count(*) as total FROM settings WHERE value = 'players.online'");

    $data=mysql_fetch_assoc($result);
    return $data['total'];
}
</code>```

Title: Count live online players

Body:
I have a playable client and I want to echo/show my online users on my index page. In my database I have the table settings and in that 2 rows
setting and value. e.g. players.online and value 0 as standard counting up to every number how much players there are online. But, it's not counting. The counter stays on 0.

function onlineusers(){
    $link = mysqli_connect("xxx", "xxx", "xxx" "`xxx");
    mysqli_query($link, "SELECT value FROM settings WHERE value = 'players.online'");
    $i = 0;
    while($b = mysqli_fetch_array($link)){
        if(onlineusers($b['players.online'])){
            $i++;
        }
    }
    return $i;
}

Body:
You can count the number of rows in DB and return it.

function onlineusers(){
    $link = mysqli_connect("xxx", "xxx", "xxx" "`xxx");
    $result = mysqli_query($link, "SELECT count(*) as total FROM settings WHERE value = 'players.online'");

    $data=mysql_fetch_assoc($result);
    return $data['total'];
}


问:
SQL - Comparing sql ddl programmatically
We are automating the process of creating/modifying tables on our database. We keep our ddls in github repo. Our objective is to drop and create the table again if the definition has changed. Otherwise, no change.

Lets say we have a table named table1

Steps:

```<code>1. Query database to get ddl for table1.
2. Get ddl from github repo, check if there is any difference between github & ddl from database server.
3. If there is a difference, drop and create again
4. Else, no change.
</code>```

For comparing, doing string comparison is very naive ( change in space(s) doesn't mean change in schema).

Is there any API for comparison? I am specifically looking for python APIs. Standard diff utility doesn't do a good job of comparing 2 sql files. It will create a diff if the order the fields are different but the overall ddl may be same.

答: Consider running both versions through a SQL parser (e.g., https://pypi.org/project/sqlparse/ -- no endorsement is implied, there may be other alternatives) and comparing elements of the two parse trees.</p>

Body:
We are automating the process of creating/modifying tables on our database. We keep our ddls in github repo. Our objective is to drop and create the table again if the definition has changed. Otherwise, no change.

Lets say we have a table named table1

Steps:

1. Query database to get ddl for table1.
2. Get ddl from github repo, check if there is any difference between github & ddl from database server.
3. If there is a difference, drop and create again
4. Else, no change.

For comparing, doing string comparison is very naive ( change in space(s) doesn't mean change in schema).

Is there any API for comparison? I am specifically looking for python APIs. Standard diff utility doesn't do a good job of comparing 2 sql files. It will create a diff if the order the fields are different but the overall ddl may be same.


问:
JavaScript alert not showing up in the browser page but at the right hand side of screen
Visual Studio Code must have had an update. I wasn't able to find anything on their website but I wasn't seeing my alert I created like it used to appear on the browser page and then I noticed that the alert is at the bottom right hand of the screen outside of the browser page but inside the Visual Studio Code. Is there any way to make this show up in the browser preview using extension for Live Server?See attached screen shot - scroll to the bottom right to see the alert.</p>

答: This looks like a VSCode runtime and VSCode alerts look just like that. If you run it in an actual browser it will give you a browser alert as you are used to.</p>


问:
Is there a function in ms-access sql-query with which one can extract a certain string?
I was wondering if there is a function in MS-Access SQL-Query with which one can extract a given string of each cell of a column (similar to substring() but with a string as criteria).

For example, I would like to extract the keywords SUN and FUN from the following column (named Lyrics)

Lyrics

```<code>AeSUN9SL
Pla4FUNP
L2wqSUNop
ASUNfdNNK
7dssFUN9SL
</code>```

so that I am only left with:
Lyrics

```<code>SUN
FUN
SUN
SUN
FUN
</code>```

in the column. Since the length as well as the number of "unused" characters before and after the string keyword differ,  I could not use left() and right().

Is there another way to solve this problem?

答:
You can use case and like:

```<code>select (case when lyrics like '%SUN%' then 'SUN'
             when lyrics like '%FUN%' then 'FUN'
        end)
</code>```

In MS Access (which was not the original tag):

```<code>select iif(lyrics like '*SUN*', 'SUN'
           iif(lyrics like '*FUN*', 'FUN', NULL)
          )
</code>```

You can also include this in an UPDATE:

```<code>update t
    set lyrics = iif(lyrics like '*SUN*', 'SUN'
                     iif(lyrics like '*FUN*', 'FUN', NULL)
                    ) ;
</code>```

Body:
I was wondering if there is a function in MS-Access SQL-Query with which one can extract a given string of each cell of a column (similar to substring() but with a string as criteria).

For example, I would like to extract the keywords SUN and FUN from the following column (named Lyrics)

Lyrics

AeSUN9SL
Pla4FUNP
L2wqSUNop
ASUNfdNNK
7dssFUN9SL

so that I am only left with:
Lyrics

SUN
FUN
SUN
SUN
FUN

in the column. Since the length as well as the number of "unused" characters before and after the string keyword differ,  I could not use left() and right().

Is there another way to solve this problem?

Body:
You can use case and like:

select (case when lyrics like '%SUN%' then 'SUN'
             when lyrics like '%FUN%' then 'FUN'
        end)

In MS Access (which was not the original tag):

select iif(lyrics like '*SUN*', 'SUN'
           iif(lyrics like '*FUN*', 'FUN', NULL)
          )

You can also include this in an UPDATE:

update t
    set lyrics = iif(lyrics like '*SUN*', 'SUN'
                     iif(lyrics like '*FUN*', 'FUN', NULL)
                    ) ;


问:
Xcode 4 Supported Device Orientations
I recently upgraded to Xcode 4. Previously in Xcode 3 to set the allowed device orientations you had to edit the shouldAutorotateToInterfaceOrientation: method in the application delegate. But now in Xcode 4 I see there is an option in Targets -> Summary where you can select different orientations.

Which alternative will rule over the other?

Cheers,

Peter

答: The "target summary" is just short hand for the data in the Info.plist file and so this has been available before. Nothing new here.</p>

Title: Xcode 4 Supported Device Orientations


问:
allowdoubleescaping = "true" in IIS Express Config Not Working
I get HTTP Error 404.11 - Not Found
The request filtering module is configured to deny a request that contains a double escape sequence.
Error when I send a request to a .razor page in Blazor, The link is dynamically built and sent to users email:

```<code>string confirmationLink = $"{HttpContext.Request.Scheme}://{Request.Host}/account/confirmemail/{System.Web.HttpUtility.UrlEncode(user.Id)}/{System.Web.HttpUtility.UrlEncode(confirmationToken)}";
</code>```

I modified the IIS Express config files in five places:

web.config in "C:\Windows\System32\inetsrv"

applicationhost.config in
"C:\Program Files\IIS Express\AppServer"

applicationhost.config in "C:\Program Files\IIS Express\config\templates\PersonalWebServer"

applicationhost.config in "C:\Program Files (x86)\IISExpress\AppServer"

applicationhost.config in "C:\Program Files(x86)\IIS Express\config\templates\PersonalWebServer"

In all cases I modified the

```<code><requestFiltering allowDoubleEscaping="true">
</code>```

tag in "web.server" "security" section. But I still get the error. Is there any solution to this?

答:
This worked for me...

To find the applicationhost.config file for IISExpress I looked for the IIS Express icon in the system tray (lower right corner of Windows 10).

I right-clicked on the IIS Express icon and clicked "Show All Applications".

From the list of Running Applications I clicked on the Site Name whose config file I wanted to modify.

Once the site name was clicked the word Config: appeared below.

I clicked on the path to the right of Config: This opened the applicationhost.config file in Visual Studio.

There I clicked Ctrl-F and searched for <requestFiltering> which I changed to <requestFiltering allowDoubleEscaping="true">

Body:
I get HTTP Error 404.11 - Not Found
The request filtering module is configured to deny a request that contains a double escape sequence.
Error when I send a request to a .razor page in Blazor, The link is dynamically built and sent to users email:

string confirmationLink = $"{HttpContext.Request.Scheme}://{Request.Host}/account/confirmemail/{System.Web.HttpUtility.UrlEncode(user.Id)}/{System.Web.HttpUtility.UrlEncode(confirmationToken)}";

I modified the IIS Express config files in five places:

web.config in "C:\Windows\System32\inetsrv"

applicationhost.config in
"C:\Program Files\IIS Express\AppServer"

applicationhost.config in "C:\Program Files\IIS Express\config\templates\PersonalWebServer"

applicationhost.config in "C:\Program Files (x86)\IISExpress\AppServer"

applicationhost.config in "C:\Program Files(x86)\IIS Express\config\templates\PersonalWebServer"

In all cases I modified the

<requestFiltering allowDoubleEscaping="true">

tag in "web.server" "security" section. But I still get the error. Is there any solution to this?


问:
Fire trigger for every inserted row using SqlBulkCopy
I am using SqlBulkCopy class to insert 50k rows at a time in table tbl_records
I have set a After Insert trigger on this table and using following code

```<code>SqlBulkCopy SqlBc1 = new SqlBulkCopy(strConnString, SqlBulkCopyOptions.FireTriggers);

// Set DataReader For SqlBulkCopy

sqlComm = new SqlCommand(strQuery, sqlTemCon);
sqlComm.CommandTimeout = 3600000;
sqlComm.CommandType = System.Data.CommandType.Text;
SqlDataReader dReader = sqlComm.ExecuteReader();
SqlBc1.WriteToServer(dReader);
</code>```

But after execution of prog. It fire trigger for only First  row out of 50k inserted

I wanna it should fire for every row. How can i do this??

答:
In case another person come across this problem and looking for a solution, here I will post my findings as well.

IMPORTANT: usr has already given the answer, but I will explain it a little bit.

First, this is what Microsoft documentation says about bulk insert,

If FIRE_TRIGGERS is not specified, no insert triggers execute.

FIRE_TRIGGERS Specifies that any insert triggers defined on the
  destination table execute during the bulk-import operation. If
  triggers are defined for INSERT operations on the target table, they
  are fired for every completed batch.

FIRE_TRIGGERS is a argument use with BULK INSERT T-SQL statement.

And if you are trying to use bulk insert with SqlBulkCopyclass (.Net Framework/Core) you have to use SqlBulkCopyOptions Enum (docs).

You can use the SqlBulkCopyOptions enumeration when you construct a
  SqlBulkCopy instance to change how the WriteToServer methods for that
  instance behave.

Here is a sample,

```<code>var options = SqlBulkCopyOptions.CheckConstraints | SqlBulkCopyOptions.FireTriggers | SqlBulkCopyOptions.KeepIdentity;
var bulkCopy = new SqlBulkCopy(connectionString, options);
</code>```

OK. Now triggers will run with bulk insert, But why for only one record. Read what Microsoft said about FIRE_TRIGGER argument again.

If triggers are defined for INSERT operations on the target table,
  they are fired for every completed batch.

That means, your trigger will run for whole batch at once. But your batch contains more than one row. Therefore your trigger algorithm (The thing you supposed to do to a single record)  will work for one record, not for all the records.

Now you know why it doesn't work for all, so the solution is improve your trigger to work with multiple rows. Which means iterate throw all rows comes with INSERTED temporary table and execute your algorithm for all records. You can use CURSOR or a simple WHILE LOOP. Its up to you.

You can find examples here.

Body:
I am using SqlBulkCopy class to insert 50k rows at a time in table tbl_records
I have set a After Insert trigger on this table and using following code

SqlBulkCopy SqlBc1 = new SqlBulkCopy(strConnString, SqlBulkCopyOptions.FireTriggers);

// Set DataReader For SqlBulkCopy

sqlComm = new SqlCommand(strQuery, sqlTemCon);
sqlComm.CommandTimeout = 3600000;
sqlComm.CommandType = System.Data.CommandType.Text;
SqlDataReader dReader = sqlComm.ExecuteReader();
SqlBc1.WriteToServer(dReader);

But after execution of prog. It fire trigger for only First  row out of 50k inserted

I wanna it should fire for every row. How can i do this??

Body:
In case another person come across this problem and looking for a solution, here I will post my findings as well.

IMPORTANT: usr has already given the answer, but I will explain it a little bit.

First, this is what Microsoft documentation says about bulk insert,

If FIRE_TRIGGERS is not specified, no insert triggers execute.

FIRE_TRIGGERS Specifies that any insert triggers defined on the
  destination table execute during the bulk-import operation. If
  triggers are defined for INSERT operations on the target table, they
  are fired for every completed batch.

FIRE_TRIGGERS is a argument use with BULK INSERT T-SQL statement.

And if you are trying to use bulk insert with SqlBulkCopyclass (.Net Framework/Core) you have to use SqlBulkCopyOptions Enum (docs).

You can use the SqlBulkCopyOptions enumeration when you construct a
  SqlBulkCopy instance to change how the WriteToServer methods for that
  instance behave.

Here is a sample,

var options = SqlBulkCopyOptions.CheckConstraints | SqlBulkCopyOptions.FireTriggers | SqlBulkCopyOptions.KeepIdentity;
var bulkCopy = new SqlBulkCopy(connectionString, options);

OK. Now triggers will run with bulk insert, But why for only one record. Read what Microsoft said about FIRE_TRIGGER argument again.

If triggers are defined for INSERT operations on the target table,
  they are fired for every completed batch.

That means, your trigger will run for whole batch at once. But your batch contains more than one row. Therefore your trigger algorithm (The thing you supposed to do to a single record)  will work for one record, not for all the records.

Now you know why it doesn't work for all, so the solution is improve your trigger to work with multiple rows. Which means iterate throw all rows comes with INSERTED temporary table and execute your algorithm for all records. You can use CURSOR or a simple WHILE LOOP. Its up to you.

You can find examples here.


问:
how to understand the wifi code flow in android?
I am new to the android. I just want to understand the Wi-Fi code flow in android. I have already grasp some basic stuff about it, need some more detail about it.</p>

答:
This is a good starting point..
https://source.android.com/devices/tech/connect/wifi-overview</p>


问:
Debugger stopping at a non existent breakpoint in Xcode 4
Since upgrading to Xcode 4 my app stops at what I think are non existent break points. When it breaks there is no breakpoint showing in the breakpoint navigator and the editor says:

Thread:1 Stopped at breakpoint 17

Anyone else seeing this? Is this something new, maybe?

答:
Xcode 4 introduced an Exception breakpoint which seems to be on by default.
i.e. when there's an exception it breaks.

This will catch an exception even if you haven't clicked the Breakpoints button.

You can check via the Debug Navigator whether it's been triggered - you'll see an "objc_exception_throw".


问:
FontAwesome 5 bootstrap tooltip issue producing two tooltips
I faced issue of getting two tooltips instead of one while using FontAwesome 5 as It will create additional SVG tag with bootstrap tooltip. I even disable the tooltip everywhere for bootstrap tooltip but still I was getting undesired tooltip.

Issue can be reproduced with following code

```

答:
This issue was solved following the solution by @serghost found in link below using a wrapper for the tag instead using it with in same tag.

https://github.com/FortAwesome/Font-Awesome/issues/11902

```

Body:
I faced issue of getting two tooltips instead of one while using FontAwesome 5 as It will create additional SVG tag with bootstrap tooltip. I even disable the tooltip everywhere for bootstrap tooltip but still I was getting undesired tooltip.

Issue can be reproduced with following code

<span
           class="fa fa-question-circle"
           data-toggle="tooltip"
           data-placement="right"
           title="Some Title"
           data-tt-head="Some Header"
           data-tt-footer="Read More ...
" >

Body:
This issue was solved following the solution by @serghost found in link below using a wrapper for the tag instead using it with in same tag.

https://github.com/FortAwesome/Font-Awesome/issues/11902

<span
           data-toggle="tooltip"
           data-placement="right"
           title="Some Title"
           data-tt-head="Some Header"
           data-tt-footer="<a style='opacity: 70%' target='_blank' href=''>Read More ...
</a>" >
<i class="fa fa-question-circle"></i>
</span>


问:
How to access value of child element in a object?
I want to access friends array of every user  (values of the array are user's id's) and return the value of the friend's array of the given user (friend)

```<code>const users = [
{
   "id": 1,
   "firstName": "Paul",
   "surname": "Crowe",
   "friends": [2]
 },
 {
   "id": 2,
   "firstName": "Rob",
   "surname": "Fitz",
   "friends": [1,3]
 },
 {
   "id": 3,
   "firstName": "Ben",
   "surname": "O'Carolan",
   "friends": [2]
 },
</code>```

This is what I have tried:

```<code>const fof = users.filter(user => {
      if (friend == user.id) {
        return true;
      }
    });
</code>```

答:
Updated now that I see your response about the expected output.

```<code>function getFriendsOfFriends(userId) {
  const user = users.find(u => userId === u.id);
  const userFriends = user.friends;

  let friendsOfFriends = [];
  for (let i = 0, l = userFriends.length; i < l; i ++) {
    const myFriendId = userFriends[i];
    const myFriend = users.find(u => myFriendId === u.id);
    friendsOfFriends = friendsOfFriends.concat(myFriend.friends);
  }
  // remove duplicates
  friendsOfFriends = friendsOfFriends.reduce((acc, curr) => {
    if (acc.indexOf(curr) === -1) {
      acc.push(curr);
    }
    return acc;
  }, []);
  return friendsOfFriends;
}
</code>```

This does a few things:

Find the user by id

Get the list of their friends' ids

Loop through the list of friends' id and:

get that user & their friends

collect all friends of friends' ids in a single array

After looping through the user's friends, remove duplicates from the friendsOfFriends array.

Added: looping through all users

```<code>const friendsOfFriendsForEachUser  = {};
for (let i = 0, l = users.length; i < l; i ++) {
  const user = users[i];
  const friendsOfFriends = getFriendsOfFriends(user.id);
  friendsOfFriendsForEachUser[user.id] = friendsOfFriends;
}
</code>```

This will store friends of friends in a dictionary. The loop can be adjusted, depending on how you need to store & access the information.

Body:
I want to access friends array of every user  (values of the array are user's id's) and return the value of the friend's array of the given user (friend)

const users = [
{
   "id": 1,
   "firstName": "Paul",
   "surname": "Crowe",
   "friends": [2]
 },
 {
   "id": 2,
   "firstName": "Rob",
   "surname": "Fitz",
   "friends": [1,3]
 },
 {
   "id": 3,
   "firstName": "Ben",
   "surname": "O'Carolan",
   "friends": [2]
 },

This is what I have tried:

const fof = users.filter(user => {
      if (friend == user.id) {
        return true;
      }
    });

Body:
Updated now that I see your response about the expected output.

function getFriendsOfFriends(userId) {
  const user = users.find(u => userId === u.id);
  const userFriends = user.friends;

  let friendsOfFriends = [];
  for (let i = 0, l = userFriends.length; i < l; i ++) {
    const myFriendId = userFriends[i];
    const myFriend = users.find(u => myFriendId === u.id);
    friendsOfFriends = friendsOfFriends.concat(myFriend.friends);
  }
  // remove duplicates
  friendsOfFriends = friendsOfFriends.reduce((acc, curr) => {
    if (acc.indexOf(curr) === -1) {
      acc.push(curr);
    }
    return acc;
  }, []);
  return friendsOfFriends;
}

This does a few things:

Find the user by id

Get the list of their friends' ids

Loop through the list of friends' id and:

get that user & their friends

collect all friends of friends' ids in a single array

After looping through the user's friends, remove duplicates from the friendsOfFriends array.

Added: looping through all users

const friendsOfFriendsForEachUser  = {};
for (let i = 0, l = users.length; i < l; i ++) {
  const user = users[i];
  const friendsOfFriends = getFriendsOfFriends(user.id);
  friendsOfFriendsForEachUser[user.id] = friendsOfFriends;
}

This will store friends of friends in a dictionary. The loop can be adjusted, depending on how you need to store & access the information.


问:
Unable to send data to a specific websocket client in python
I'm writing a program with websockets in python. I've got an example server and client code running and they work well if only one client is connected. If there are multiple clients, data from the server will go randomly to one of the clients.

I would like for:

Server to keep track of the various clients connected

Server to be able to direct messages to a specific client out of multiple(For eg. 5) clients

websockets is the library I'm using.
Python version 3.7.2

Server Code:

```<code>import asyncio
import websockets

uri='localhost'

async def response(websocket, path):

    msg = input("What do you want to send : ")
    print("message:",msg)
    await websocket.send(msg)

start_server = websockets.serve(response, uri, 5000)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
</code>```

Client Code:

```<code>import asyncio
import websockets

uri="ws://localhost:5000"
async def message():

                async with websockets.connect(uri) as socket:
                        print(await socket.recv())

while True:
        asyncio.get_event_loop().run_until_complete(message())
</code>```

If I create 2 files with the client code as client1.py and client2.py, and send message from the server side, I get the sent data going to either on of the clients.

I would like to:

Server keeps track of the various clients connected

Server is able to direct messages to a specific client out of multiple clients

As I am just starting out with websockets, all input is appreciated.

In this output given, I intended to send all my messages to client 1, yet they got split up between client 1 and 2

答:
I'm not familiar with asyncio, so I will try to get to the point with functions/threads;

Usually, my server side listens to one connection and once it accepts it, I have a function 'handler' that is threaded to each connection that gets accepted.

part of my server and handler:

```<code>def handler(conn, addr):
    global data1

    while True:
        data = conn.recv(2048)
        data1 = json.loads(data.decode())
        # treat it as you need

while True:
    s.listen(1)
    conn, addr = s.accept()
    print('Conectado com', addr[0],':', str(addr[1]))
    thr = threading.Thread(target = handler, args = (conn, addr)).start()
</code>```

Now, for the control of the clients and such, I always use a dictionary. The key should be the username or any other particular info. The value of the key is the 'conn' from that user. This way you can get the connection of user 'x' by its specific key.

Something like:

```<code>import socket
import time
import datetime as dt
import base64
import os
import json
import threading

HOST = ''
PORT = 12999

global s

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((HOST,PORT))

whoto = {}

def autenticacao():

    global data1
    global conn
    global nomeuser

    user1 = data1[1]
    passwd = data1[2]

    auth = c.execute('SELECT usuario FROM fullinfo WHERE usuario= ? AND password = ?', (user1,passwd)).fetchone()
    if auth is not None:
        word = 'autenticado'
        conn.sendall(word.encode())
        nomeuser = auth[0]
        whoto[nomeuser] = conn
</code>```

I'm sorry i'm leaving it unreproducible, but my point is to show the 'algorithm'. This dictionary is what I use to keep record of who is online, the 'adress' (conn) of each client to send messages to single clients and such.
On the example above, I add the user (key) and conn (value) once it's authenticated inside my server.

Hope this helps. Good luck!

Body:
I'm writing a program with websockets in python. I've got an example server and client code running and they work well if only one client is connected. If there are multiple clients, data from the server will go randomly to one of the clients.

I would like for:

Server to keep track of the various clients connected

Server to be able to direct messages to a specific client out of multiple(For eg. 5) clients

websockets is the library I'm using.
Python version 3.7.2

Server Code:

import asyncio
import websockets

uri='localhost'

async def response(websocket, path):

    msg = input("What do you want to send : ")
    print("message:",msg)
    await websocket.send(msg)

start_server = websockets.serve(response, uri, 5000)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()

Client Code:

import asyncio
import websockets

uri="ws://localhost:5000"
async def message():

                async with websockets.connect(uri) as socket:
                        print(await socket.recv())

while True:
        asyncio.get_event_loop().run_until_complete(message())

If I create 2 files with the client code as client1.py and client2.py, and send message from the server side, I get the sent data going to either on of the clients.

I would like to:

Server keeps track of the various clients connected

Server is able to direct messages to a specific client out of multiple clients

As I am just starting out with websockets, all input is appreciated.

In this output given, I intended to send all my messages to client 1, yet they got split up between client 1 and 2

Body:
I'm not familiar with asyncio, so I will try to get to the point with functions/threads;

Usually, my server side listens to one connection and once it accepts it, I have a function 'handler' that is threaded to each connection that gets accepted.

part of my server and handler:

def handler(conn, addr):
    global data1

    while True:
        data = conn.recv(2048)
        data1 = json.loads(data.decode())
        # treat it as you need

while True:
    s.listen(1)
    conn, addr = s.accept()
    print('Conectado com', addr[0],':', str(addr[1]))
    thr = threading.Thread(target = handler, args = (conn, addr)).start()

Now, for the control of the clients and such, I always use a dictionary. The key should be the username or any other particular info. The value of the key is the 'conn' from that user. This way you can get the connection of user 'x' by its specific key.

Something like:

import socket
import time
import datetime as dt
import base64
import os
import json
import threading

HOST = ''
PORT = 12999

global s

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((HOST,PORT))

whoto = {}

def autenticacao():

    global data1
    global conn
    global nomeuser

    user1 = data1[1]
    passwd = data1[2]

    auth = c.execute('SELECT usuario FROM fullinfo WHERE usuario= ? AND password = ?', (user1,passwd)).fetchone()
    if auth is not None:
        word = 'autenticado'
        conn.sendall(word.encode())
        nomeuser = auth[0]
        whoto[nomeuser] = conn

I'm sorry i'm leaving it unreproducible, but my point is to show the 'algorithm'. This dictionary is what I use to keep record of who is online, the 'adress' (conn) of each client to send messages to single clients and such.
On the example above, I add the user (key) and conn (value) once it's authenticated inside my server.

Hope this helps. Good luck!


问:
serverless remove lamda using gitlab CI
I'm using gitlab CI for deployment.

I'm running into a problem when the review branch is deleted.

```<code>stop_review:
  variables:
    GIT_STRATEGY: none
  stage: cleanup
  script:
    - echo "$AWS_REGION"
    - echo "Stopping review branch"
    - serverless config credentials --provider aws --key ${AWS_ACCESS_KEY_ID} --secret ${AWS_SECRET_ACCESS_KEY}
    - echo "$CI_COMMIT_REF_NAME"
    - serverless remove --stage=$CI_COMMIT_REF_NAME --verbose
  only:
    - branches
  except:
    - master
  environment:
    name: review/$CI_COMMIT_REF_NAME
    action: stop
  when: manual
</code>```

error is This command can only be run in a Serverless service directory. Make sure to reference a valid config file in the current working directory if you're using a custom config file

I have tried different GIT_STRATEGY, can some point me in right direction?

答:
In order to run serverless remove, you'll need to have the serverless.yml file available, which means the actual repository will need to be cloned. (or that file needs to get to GitLab in some way).

It's required to have a serverless.yml configuration file available when you run serverless remove because the Serverless Framework allows users to provision infrastructure using not only the framework's YML configuration but also additional resources (like CloudFormation in AWS) which may or may not live outside of the specified app or stage CF Stack entirely.

In fact, you can also provision infrastructure into other providers as well (AWS, GCP, Azure, OpenWhisk, or actually any combination of these).

So it's not sufficient to simply identify the stage name when running sls remove, you'll need the full serverless.yml template.

Title: serverless remove lamda using gitlab CI

Body:
I'm using gitlab CI for deployment.

I'm running into a problem when the review branch is deleted.

stop_review:
  variables:
    GIT_STRATEGY: none
  stage: cleanup
  script:
    - echo "$AWS_REGION"
    - echo "Stopping review branch"
    - serverless config credentials --provider aws --key ${AWS_ACCESS_KEY_ID} --secret ${AWS_SECRET_ACCESS_KEY}
    - echo "$CI_COMMIT_REF_NAME"
    - serverless remove --stage=$CI_COMMIT_REF_NAME --verbose
  only:
    - branches
  except:
    - master
  environment:
    name: review/$CI_COMMIT_REF_NAME
    action: stop
  when: manual

error is This command can only be run in a Serverless service directory. Make sure to reference a valid config file in the current working directory if you're using a custom config file

I have tried different GIT_STRATEGY, can some point me in right direction?


问:
Custom WPF control for showing a Graph and highlighting Points of Interest
Question for you all, I've been charged with developing an application to view data about a testing cycle we do for environmental screening, products are placed in an environmental control, freezing and heating the product while a variety of self-tests are run. My manager would like to see a graph of temperature over time as an x/y graph, but he'd also like to have an indicator for where the test is currently at that has a small box, giving additional info, (test status, current test, running time etc.)

So what I'm thinking is I need to make a custom control that is capable of displaying this scatter graph and can also contain another content control for my additional info box, what base control should I use as a foundation, what should I look at for drawing my graph, and how can I do my layout for this? I'm assuming the use of a canvas control is my best bet for layout, and DrawingGroups with PathFigures for the graph... anyone capable of giving me more guidance?

答: maybe you should check out Sacha Barber's WPF Graph Control. This may be a good starting point</p>

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Joachim Kerschbaumer


问:
git clone: Authentication failed for <URL>
Trying to access private corporate tfs.
They gave me access by giving appropriate rights to windows user (domain\login).

I'm fine with accessing web interface of tfs, browse repository and stuff.

But when I try to run

```<code> git clone https://tfs.somehostname.com/tfs/somefolder/_git/therepository
</code>```

It fails with

```<code>Cloning into 'therepository'...

fatal: Authentication failed for 'https://tfs.somehostname.com/tfs/somefolder/_git/therepository/'
</code>```

Tried with home pc without corporate network stuff - same error.

Tried in PowerShell, Git Bash, Clone via VisualStudio - same error.

SSH is closed (gave request timeout).

Web & Git both ask for credentials once (tried deleting in Credentials Manager - asks again, after submitting web is fine, git fails)

Corporate helper tried to help, but all he gave is tfs logs.
He says, my username doesn't come with requests (tracked by syncing my attempts timestamps with logs).

```<code>2018-07-19 07:04:00 SOMEIP GET /tfs/SOMEFOLDER/_git/REPOSITORY/info/refs service=git-upload-pack 443 - ANOTHERIP git/2.12.2+(Microsoft+Windows+NT+6.3.9600.0;+Win32NT+x64)+CLR/4.0.30319+VS15/15.0.0 - 401 2 5 62
2018-07-19 07:23:00 SOMEIP GET /tfs/SOMEFOLDER/_git/REPOSITORY/info/refs service=git-upload-pack 443 - ANOTHERIP git/2.18.0.windows.1 - 401 2 5 62
2018-07-19 07:23:00 SOMEIP GET /tfs/SOMEFOLDER/_git/REPOSITORY/info/refs service=git-upload-pack 443 - ANOTHERIP git/2.18.0.windows.1 - 401 1 3221225581 187
</code>```

while others include it

```<code>2018-07-19 05:44:27 SOMEIP GET /tfs/SOMEFOLDER/_git/REPOSITORY/info/refs service=git-upload-pack 443 DOMAIN\LOGIN ANOTHERIP git/2.12.2+(Microsoft+Windows+NT+6.1.7601+Service+Pack+1;+Win32NT+x64)+CLR/4.0.30319+VS15/15.0.0 - 200 0 0 265
</code>```

答:
I had the same issue when Cloning the repository via Bash/VS Code with "fatal:Authentication failed". I used SSH Key authentication instead to connect my repository following the article: [https://learn.microsoft.com/en-us/azure/devops/repos/git/use-ssh-keys-to-authenticate?view=azure-devops&tabs=current-page][1]
I didn't get any errors after with any bash commands!</p>

Body:
Trying to access private corporate tfs.
They gave me access by giving appropriate rights to windows user (domain\login).

I'm fine with accessing web interface of tfs, browse repository and stuff.

But when I try to run

 git clone https://tfs.somehostname.com/tfs/somefolder/_git/therepository

It fails with

Cloning into 'therepository'...

fatal: Authentication failed for 'https://tfs.somehostname.com/tfs/somefolder/_git/therepository/'

Tried with home pc without corporate network stuff - same error.

Tried in PowerShell, Git Bash, Clone via VisualStudio - same error.

SSH is closed (gave request timeout).

Web & Git both ask for credentials once (tried deleting in Credentials Manager - asks again, after submitting web is fine, git fails)

Corporate helper tried to help, but all he gave is tfs logs.
He says, my username doesn't come with requests (tracked by syncing my attempts timestamps with logs).

2018-07-19 07:04:00 SOMEIP GET /tfs/SOMEFOLDER/_git/REPOSITORY/info/refs service=git-upload-pack 443 - ANOTHERIP git/2.12.2+(Microsoft+Windows+NT+6.3.9600.0;+Win32NT+x64)+CLR/4.0.30319+VS15/15.0.0 - 401 2 5 62
2018-07-19 07:23:00 SOMEIP GET /tfs/SOMEFOLDER/_git/REPOSITORY/info/refs service=git-upload-pack 443 - ANOTHERIP git/2.18.0.windows.1 - 401 2 5 62
2018-07-19 07:23:00 SOMEIP GET /tfs/SOMEFOLDER/_git/REPOSITORY/info/refs service=git-upload-pack 443 - ANOTHERIP git/2.18.0.windows.1 - 401 1 3221225581 187

while others include it

2018-07-19 05:44:27 SOMEIP GET /tfs/SOMEFOLDER/_git/REPOSITORY/info/refs service=git-upload-pack 443 DOMAIN\LOGIN ANOTHERIP git/2.12.2+(Microsoft+Windows+NT+6.1.7601+Service+Pack+1;+Win32NT+x64)+CLR/4.0.30319+VS15/15.0.0 - 200 0 0 265


问:
C/Lex char pointer printing value of other pointer as well
I am writing a lex program. I have initialized 3 char pointers. And then I am defining them to tokens if they satisfy the criteria. But when I print them afterwards, the first prints value of all 3, second of last two and last of itself. Why is this happenning? Here is my code:

```<code>%{
    #include<stdio.h>
    #include<string.h>

    int for_cond = 0;
    char *cond1, *cond2, *cond3;
    char * for_body = "";
    //char * loop = "";
    %}
    VAR [a-zA-Z_]+[a-zA-Z0-9_]*
    %%
    for[ ]*\( {for_cond++;}
    int[ ]+{VAR}[ ]*\=[ ]*[0-9]+ {if(for_cond==1){cond1 = yytext;}else if(for_cond==4){for_body = strcat(for_body,yytext);}}
    ; {if(for_cond==1||for_cond==2){for_cond++;} else if(for_cond==4){for_body = strcat(for_body,yytext);}}
    {VAR}[ ]*(\<|\>|\<\=|\>\=|\=\=)[ ]*[0-9]+ {if(for_cond==2){cond2 = yytext;}else if(for_cond==4){for_body = strcat(for_body,yytext);}}
    {VAR}[ ]*((\+\+|\-\-)|((\+\=|\-\=|\*\=|\/\=)[ ]*({VAR}|[0-9]+))) {if(for_cond==3){cond3 = yytext;}else if(for_cond==4){for_body = strcat(for_body,yytext);}}
    %%
    int yywrap(void){}
    int main(){

        yylex();
        printf("cond1 = %s\ncond2 = %s\ncond3 = %s\n", cond1, cond2, cond3);

        return 0;
    }
</code>```

example input:

```<code>for(int i=0;i<=2;i++)
</code>```

expected output:

```<code>cond1 = int i=0

cond2 = i<=2

cond3 = i++
</code>```

What I am getting:

```<code>cond1 = int i=0;i<=2;i++)

cond2 = i<=2;i++)

cond3 = i++)
</code>```

Why is this happenning? How do I fix this?

答:
yytext points to a temporary data structure internal to the lexer whose lifetime is limited to the lexer action. (More precisely, its lifetime starts with the lexer action and ends just prior to the lexical scan.)

In other words, you cannot save the value of yytext as a pointer. You must copy the contents of the string pointed to by yytext if you want to preserve the string for later use. If you have strdup, you can use it to create a copy of the string (but don't forget to free() the copy when you no longer need it.) If you don't have strdup, or for whatever reason don't want to use it, you can dynamically allocate space yourself:

```<code>char* theToken = malloc(yyleng + 1); strcpy(theToken, yytext);
</code>```

It's also worth mentioning that given that for_body points to an immutable string of length 0 (char * for_body = "";), attempting to add text to it is Undefined Behaviour:

```<code>strcat(for_body,yytext);
</code>```

On many platforms, that call will segfault because for_body's initialization leaves it pointing to read-only memory. But if the memory is writable, it is not part of the array pointed to by for_body, which means that it is part of some other object whose value will be destroyed by the call to strcat.

Body:
I am writing a lex program. I have initialized 3 char pointers. And then I am defining them to tokens if they satisfy the criteria. But when I print them afterwards, the first prints value of all 3, second of last two and last of itself. Why is this happenning? Here is my code:

%{
    #include<stdio.h>
    #include<string.h>

    int for_cond = 0;
    char *cond1, *cond2, *cond3;
    char * for_body = "";
    //char * loop = "";
    %}
    VAR [a-zA-Z_]+[a-zA-Z0-9_]*
    %%
    for[ ]*\( {for_cond++;}
    int[ ]+{VAR}[ ]*\=[ ]*[0-9]+ {if(for_cond==1){cond1 = yytext;}else if(for_cond==4){for_body = strcat(for_body,yytext);}}
    ; {if(for_cond==1||for_cond==2){for_cond++;} else if(for_cond==4){for_body = strcat(for_body,yytext);}}
    {VAR}[ ]*(\<|\>|\<\=|\>\=|\=\=)[ ]*[0-9]+ {if(for_cond==2){cond2 = yytext;}else if(for_cond==4){for_body = strcat(for_body,yytext);}}
    {VAR}[ ]*((\+\+|\-\-)|((\+\=|\-\=|\*\=|\/\=)[ ]*({VAR}|[0-9]+))) {if(for_cond==3){cond3 = yytext;}else if(for_cond==4){for_body = strcat(for_body,yytext);}}
    %%
    int yywrap(void){}
    int main(){

        yylex();
        printf("cond1 = %s\ncond2 = %s\ncond3 = %s\n", cond1, cond2, cond3);

        return 0;
    }

example input:

for(int i=0;i<=2;i++)

expected output:

cond1 = int i=0

cond2 = i<=2

cond3 = i++

What I am getting:

cond1 = int i=0;i<=2;i++)

cond2 = i<=2;i++)

cond3 = i++)

Why is this happenning? How do I fix this?

Body:
yytext points to a temporary data structure internal to the lexer whose lifetime is limited to the lexer action. (More precisely, its lifetime starts with the lexer action and ends just prior to the lexical scan.)

In other words, you cannot save the value of yytext as a pointer. You must copy the contents of the string pointed to by yytext if you want to preserve the string for later use. If you have strdup, you can use it to create a copy of the string (but don't forget to free() the copy when you no longer need it.) If you don't have strdup, or for whatever reason don't want to use it, you can dynamically allocate space yourself:

char* theToken = malloc(yyleng + 1); strcpy(theToken, yytext);

It's also worth mentioning that given that for_body points to an immutable string of length 0 (char * for_body = "";), attempting to add text to it is Undefined Behaviour:

strcat(for_body,yytext);

On many platforms, that call will segfault because for_body's initialization leaves it pointing to read-only memory. But if the memory is writable, it is not part of the array pointed to by for_body, which means that it is part of some other object whose value will be destroyed by the call to strcat.


答:
Should be able to just run a COUNT() in your query instead of counting them up in PHP.</p>

```<code>SELECT COUNT(*) as NumOnline FROM settings WHERE value = 'players.online';
</code>```

Title: Count live online players

Body:
I have a playable client and I want to echo/show my online users on my index page. In my database I have the table settings and in that 2 rows
setting and value. e.g. players.online and value 0 as standard counting up to every number how much players there are online. But, it's not counting. The counter stays on 0.

function onlineusers(){
    $link = mysqli_connect("xxx", "xxx", "xxx" "`xxx");
    mysqli_query($link, "SELECT value FROM settings WHERE value = 'players.online'");
    $i = 0;
    while($b = mysqli_fetch_array($link)){
        if(onlineusers($b['players.online'])){
            $i++;
        }
    }
    return $i;
}

Body:
Should be able to just run a COUNT() in your query instead of counting them up in PHP.

SELECT COUNT(*) as NumOnline FROM settings WHERE value = 'players.online';


问:
postgres : Enforce password change on user first login
My script is creating a list of NEW users with DEFAULT password, but I must enfornce them to change their password on their first login PROGRAMMATICALLY.

I do have a command like,

```<code>CREATE USER david WITH 'PASSWORD'
ALTER USER david VALID UNTIL 'Mar 17 2020';
</code>```

Here I can run above command soon after creating a user, set previous day, but that would expire user TOTAL login itself.
Any other better way/approach ? Thanks

答:
I think that you can't do this with PostgreSQL.  You can't change the password from outside the database, so once the password is expired you can't get into the database in order to change it (unless you have multiple methods configured, like a certain machine letting you connect without a password). You need to be rescued by a privileged user.

You would need some kind of restricted login which lets you change your password but nothing else, and that does not exist.  (Although it is possible there is some non-core extension that could allow that).

Body:
My script is creating a list of NEW users with DEFAULT password, but I must enfornce them to change their password on their first login PROGRAMMATICALLY.

I do have a command like,

CREATE USER david WITH 'PASSWORD'
ALTER USER david VALID UNTIL 'Mar 17 2020';

Here I can run above command soon after creating a user, set previous day, but that would expire user TOTAL login itself.
Any other better way/approach ? Thanks


问:
A calculator with no if's
So i wanted to ask if its possible to make a calculator but without if statements like normally i do it like:

```<code>Scanner userInput1 = new Scanner(System.in);
System.out.print("Number: ");
double number1 = userInput1.nextDouble();
System.out.print("Operator: ");
String operator = userInput1.next();
System.out.print("Another Number: ");
double number2 = userInput1.nextDouble();
if(operator.equals(+))
{
   double result = number1 + number2;
   System.out.println("The result is " + result);
}
</code>```

And i need to make a if statement and "ask" if the operator equals plus. is it possible to make it that you dont need to to that with the if statements and do it like that:

```<code>Scanner userInput1 = new Scanner(System.in);
System.out.print("Number: ");
double number1 = userInput1.nextDouble();
System.out.print("Operator: ");
String operator = userInput1.next();
System.out.print("Another Number: ");
double number2 = userInput1.nextDouble();
System.out.println("The result is " number1 + operator + number2);
</code>```

Now it would just say as example: The result is 15+17 and i wanted to ask if its possible to make it  that it gives me the result without the if statements.
Thanks

答:
Here is a partial model.  It does not have all the necessary error controls for invalid input and it only supports one operator.  But it is a start.</p>

```<code>        Scanner input = new Scanner(System.in);
        boolean more = true;
        while (more) {
            int result = 0;
            System.out.print(
                    "Enter two ints separated by spaces");
            int a = input.nextInt();
            int b = input.nextInt();
            System.out.println("Enter the operator");
            String c = input.next();
            switch (c) {
            case "+":
                System.out.println(a + b);
                break;
            default:
                System.out.println("Unknown operator");
            }
            System.out.print("Another? ");
            String answer = input.next();
            switch (answer.charAt(0)) {
            case 'n':
            case 'N':
                more = false;
                break;
            }
        }

</code>```

Title: A calculator with no if's

Body:
So i wanted to ask if its possible to make a calculator but without if statements like normally i do it like:

Scanner userInput1 = new Scanner(System.in);
System.out.print("Number: ");
double number1 = userInput1.nextDouble();
System.out.print("Operator: ");
String operator = userInput1.next();
System.out.print("Another Number: ");
double number2 = userInput1.nextDouble();
if(operator.equals(+))
{
   double result = number1 + number2;
   System.out.println("The result is " + result);
}

And i need to make a if statement and "ask" if the operator equals plus. is it possible to make it that you dont need to to that with the if statements and do it like that:

Scanner userInput1 = new Scanner(System.in);
System.out.print("Number: ");
double number1 = userInput1.nextDouble();
System.out.print("Operator: ");
String operator = userInput1.next();
System.out.print("Another Number: ");
double number2 = userInput1.nextDouble();
System.out.println("The result is " number1 + operator + number2);

Now it would just say as example: The result is 15+17 and i wanted to ask if its possible to make it  that it gives me the result without the if statements.
Thanks

Body:
Here is a partial model.  It does not have all the necessary error controls for invalid input and it only supports one operator.  But it is a start.

        Scanner input = new Scanner(System.in);
        boolean more = true;
        while (more) {
            int result = 0;
            System.out.print(
                    "Enter two ints separated by spaces");
            int a = input.nextInt();
            int b = input.nextInt();
            System.out.println("Enter the operator");
            String c = input.next();
            switch (c) {
            case "+":
                System.out.println(a + b);
                break;
            default:
                System.out.println("Unknown operator");
            }
            System.out.print("Another? ");
            String answer = input.next();
            switch (answer.charAt(0)) {
            case 'n':
            case 'N':
                more = false;
                break;
            }
        }


问:
Alternative to standard deviation to indicate the restlessness of signal
I want to get a measure for the 'restlessness' of a signal.

I thought that the standard deviation could be right.

(In the end, I want to have a moving window over my signal, where an indicator tells me how restless my signal is. But for the beginning I just analysed some toy data over a fixed and static amount of data.)

Unfortunately, if I take some generated signals like in the example below, I can see that quite different signals result in the same value for the standard deviation.

I could imagine that a fourier transformation or a power spectrum might deliver a better indication how unsteady my signal is, but my question is: are there any other (easier to use) indicators for my use case?

The example:

```<code>import numpy as np
import matplotlib

matplotlib.use('QT5Agg')
import matplotlib.pyplot as plt

x = np.linspace(0, 2 * np.pi, 1000)
y1 = np.sin(x)
print("y1.std()=", y1.std())

y2 = np.sin(10 * x)
print("y2.std()=", y2.std())

plt.plot(x,y1, '-o', markersize=2, c='r')
plt.plot(x,y2, '-o', markersize=2, c='g')
plt.grid()

plt.show()
</code>```

The output:

```<code>y1.std()= 0.7067531393633848
y2.std()= 0.7067531393633849
</code>```

答:
It sounds like you want a combination of "How quickly does this change" and "how much does this change". At some level the distinction is arbitrary - obviously the lines in your data are identical, just at different scales. Please note that I'm no mathematician/data scientist, and while I've had to write code to do the same thing you're trying to do, none of my suggestions are likely to be anything more than an approximation, on some arbitrary scale.

That said:

You could perhaps try some combination of stdev, and the stdev of approximations of the first- and second- derivatives.

You could also look into kalman filters, and instead of using the filtered output, just measure how far the actual value is from the filtered one.

What I actually did when I had to solve a similar problem, was, every time I got a new point, I drew a line between the previous two points, and measured the distance from the new point to that line, and just kept a rolling average-queue of those distances. It felt hacky though, so I'd probably try one of the above first.

Also, I saw this in the 'Related questions' panel, and just want to durably link them:
How to efficiently calculate a running standard deviation?
(The main conclusion being Welford's algorithm)

Body:
I want to get a measure for the 'restlessness' of a signal.

I thought that the standard deviation could be right.

(In the end, I want to have a moving window over my signal, where an indicator tells me how restless my signal is. But for the beginning I just analysed some toy data over a fixed and static amount of data.)

Unfortunately, if I take some generated signals like in the example below, I can see that quite different signals result in the same value for the standard deviation.

I could imagine that a fourier transformation or a power spectrum might deliver a better indication how unsteady my signal is, but my question is: are there any other (easier to use) indicators for my use case?

The example:

import numpy as np
import matplotlib

matplotlib.use('QT5Agg')
import matplotlib.pyplot as plt

x = np.linspace(0, 2 * np.pi, 1000)
y1 = np.sin(x)
print("y1.std()=", y1.std())

y2 = np.sin(10 * x)
print("y2.std()=", y2.std())

plt.plot(x,y1, '-o', markersize=2, c='r')
plt.plot(x,y2, '-o', markersize=2, c='g')
plt.grid()

plt.show()

The output:

y1.std()= 0.7067531393633848
y2.std()= 0.7067531393633849


问:
MySQL Error 1093 - Can't specify target table for update in FROM clause (two joins)
I'm trying to update the unit_price in a sales_order_parts detail table with calculation from the  applied_discount field from sales_orders.  Also, the price is in the master_part_list table as price.  When I run from the select statement down, it runs fine and returns the list of values from order_number 209 with the correct calculation.  When I run it complete from the update line, it returns "Error Code: 1093. You can't specify target table 'sop' for update in FROM clause" Any ideas?</p>

```<code>update sales_order_parts as sop
    set unit_price =
    (select (master_part_list.price * (1-(so.applied_discount/100)))
    from sales_orders as so
        inner join sales_order_parts as sop2
            on so.id = sop2.order_id
        inner join master_part_list
            on sop2.part_id = master_part_list.id
        where so.order_number = 209);

</code>```

答:
You could try with a join without subquery  </p>

```<code>update sales_order_parts as sop
INNER JOIN sales_orders as so on so.id = sop.order_id
  AND so.order_number = 209
inner join master_part_list on sop.part_id = master_part_list.id
SET sop.unit_price = master_part_list.price * (1-(so.applied_discount/100))
</code>```

Body:
I'm trying to update the unit_price in a sales_order_parts detail table with calculation from the  applied_discount field from sales_orders.  Also, the price is in the master_part_list table as price.  When I run from the select statement down, it runs fine and returns the list of values from order_number 209 with the correct calculation.  When I run it complete from the update line, it returns "Error Code: 1093. You can't specify target table 'sop' for update in FROM clause" Any ideas?

update sales_order_parts as sop
    set unit_price =
    (select (master_part_list.price * (1-(so.applied_discount/100)))
    from sales_orders as so
        inner join sales_order_parts as sop2
            on so.id = sop2.order_id
        inner join master_part_list
            on sop2.part_id = master_part_list.id
        where so.order_number = 209);

Body:
You could try with a join without subquery

update sales_order_parts as sop
INNER JOIN sales_orders as so on so.id = sop.order_id
  AND so.order_number = 209
inner join master_part_list on sop.part_id = master_part_list.id
SET sop.unit_price = master_part_list.price * (1-(so.applied_discount/100))


问:
How can I filter information ordering by two different factors on SQL?
I have the three following tables:

```<code>create table Person (

    id int,
    popularity int,
    primary key (id)
);

create table Movie (

    id int,
    year int,
    primary key (id)
);

create table Person_Movie (

    id_person int,
    id_movie int,
    primary key (id_person, id_movie),
    foreign key (id_person) references Person (id_person),
    foreign key (id_movie) references Movie (id_movie)
);
</code>```

I want to execute a SELECT to check which person has the higher number of popularity BUT has but has participated in less movies.

How can I do this?

To check the most popular person I'd execute this:

```<code>select P.id from Person as P, Movie as M, Person_Movie as PM
where P.id = PM.id and PM.id = M.id
group by (P.id)
order by popularity;
</code>```

And, if I am correct, to check the person that has participated in less movies I'd execute this:

```<code>select P.id from Person as P, Movie as M, Person_Movie as PM
where P.id = PM.id and PM.id = M.id
group by (P.id)
order by count(M.id);
</code>```

But, how can I filter the two cases in one SELECT?

Thanks in advance.

EDIT

I'm using MySQL.

Also I'll provide an example of what I'm trying to get:

Table Person

```<code>id      popularity
-------------------
1          50
2          35
3          120
4          45
</code>```

Table Movie

```<code>id        year
----------------
1         1999
2         2014
3         1969
4         1977
5         2019
</code>```

Table Person_Movie

```<code>id_person       id_movie
--------------------------
    1              1
    2              4
    2              5
    3              3
    4              1
    4              2
</code>```

So, given this example, the output I would like to get is:

```<code>id_person
----------
    3
</code>```

Because both persons with id 1 and 3 have participated in just ONE movie, but person with id 3 has the higher number of popularity.

答:
Looking at your desired output, I assume you want to select the people who participated in the lowest number of movies out of the ones who are the most popular. (I assume popularity is your first priority)
Then the following query might work in MySQL

```<code>select A.id
from (select id from Person where popularity=(select max(popularity) from Person)) A, Person_Movie B
where A.id = B.id
group by A.id
order by count(*)
</code>```

The first subquery returns the most popular people and then I tried to sort them by the number of movies they attended. (if you need only a single result you can add a LIMIT 1 in the end)

Body:
I have the three following tables:

create table Person (

    id int,
    popularity int,
    primary key (id)
);

create table Movie (

    id int,
    year int,
    primary key (id)
);

create table Person_Movie (

    id_person int,
    id_movie int,
    primary key (id_person, id_movie),
    foreign key (id_person) references Person (id_person),
    foreign key (id_movie) references Movie (id_movie)
);

I want to execute a SELECT to check which person has the higher number of popularity BUT has but has participated in less movies.

How can I do this?

To check the most popular person I'd execute this:

select P.id from Person as P, Movie as M, Person_Movie as PM
where P.id = PM.id and PM.id = M.id
group by (P.id)
order by popularity;

And, if I am correct, to check the person that has participated in less movies I'd execute this:

select P.id from Person as P, Movie as M, Person_Movie as PM
where P.id = PM.id and PM.id = M.id
group by (P.id)
order by count(M.id);

But, how can I filter the two cases in one SELECT?

Thanks in advance.

EDIT

I'm using MySQL.

Also I'll provide an example of what I'm trying to get:

Table Person

id      popularity
-------------------
1          50
2          35
3          120
4          45

Table Movie

id        year
----------------
1         1999
2         2014
3         1969
4         1977
5         2019

Table Person_Movie

id_person       id_movie
--------------------------
    1              1
    2              4
    2              5
    3              3
    4              1
    4              2

So, given this example, the output I would like to get is:

id_person
----------
    3

Because both persons with id 1 and 3 have participated in just ONE movie, but person with id 3 has the higher number of popularity.

Body:
Looking at your desired output, I assume you want to select the people who participated in the lowest number of movies out of the ones who are the most popular. (I assume popularity is your first priority)
Then the following query might work in MySQL

select A.id
from (select id from Person where popularity=(select max(popularity) from Person)) A, Person_Movie B
where A.id = B.id
group by A.id
order by count(*)

The first subquery returns the most popular people and then I tried to sort them by the number of movies they attended. (if you need only a single result you can add a LIMIT 1 in the end)


问:
Creating a non-bias dataframe from a bias dataset in Pandas
I'm working with the COMPAS dataset and looking to create two Pandas DataFrame with the data --one with bias and one without, by splitting the set into two. As of now, I have the below working that will create one dataframe, but it will carry over the bias originally found in COMPAS because "replace" must be set to True given the distribution in size between races.

```<code>import os
import tempfile
import urllib

_DATA_ROOT = tempfile.mkdtemp(prefix='tfx-data')
_DATA_PATH = 'https://storage.googleapis.com/what-if-tool-resources/computefest2019/cox-violent-parsed_filt.csv'
_DATA_FILEPATH = os.path.join(_DATA_ROOT, 'compas-scores-two-years.csv')
urllib.request.urlretrieve(_DATA_PATH, _DATA_FILEPATH)

_COMPAS_DF = _COMPAS_DF[_COMPAS_DF['is_recid'] != -1]
_GROUPBY_DF = _COMPAS_DF.groupby('race')
_COMPAS_DF = _GROUPBY_DF.apply(lambda x: x.sample(5000, replace=True).reset_index(drop=True))
_COMPAS_DF['race'].value_counts()
</code>```

The output of this dataframe is below but the bias of 'is_recid', which is a bool value of the defendant's recidivism stays the same.

```<code>African-American    5000
Other               5000
Caucasian           5000
Asian               5000
Hispanic            5000
Native American     5000
Name: race, dtype: int64
</code>```

The starting dataframe is listed below:

```<code>is_recid  Race              Count is_recid
0         African-American  4338    24.79%
          Caucasian         3308    18.91%
          Hispanic          860     4.92%
          Other             502     2.87%
          Asian             45      0.26%
          Native American   26      0.15%
1         African-American  5081    29.04%
          Caucasian         2474    14.14%
          Hispanic          495     2.83%
          Other             323     1.85%
          Native American   25      0.14%
          Asian             19      0.11%
Total                       17496   100.00%
</code>```

My hope is to create a dataframe like the below and a second dataframe with the remaining values from the original dataset. Note that the count doesn't necessarily need to be exactly as listed but the distribution between race and is_recid is balanced.

```<code>is_recid  Race              Count   is_recid
0         African-American  3000    29.85%
          Caucasian         1500    14.93%
          Hispanic          300     2.99%
          Other             200     1.99%
          Asian             10      0.10%
          Native American   15      0.15%
1         African-American  3000    29.85%
          Caucasian         1500    14.93%
          Hispanic          300     2.99%
          Other             200     1.99%
          Native American   15      0.15%
          Asian             10      0.10%
Total                       10050   100.00%
</code>```

Many thanks in advance!

答:
The below ended up working for me:</p>

```<code>_COMPAS_DF_TUPLES = dict(tuple(_COMPAS_DF.groupby(['race', 'is_recid'])))
_UNBIASED_COMPAS = pd.DataFrame()
_BIASED_COMPAS = pd.DataFrame()

for race in _COMPAS_DF['race'].unique():
  # Find the minimum difference between race and is_recid to create an unbiased
  # dataset.
  min_bias_count = min(_COMPAS_DF_TUPLES[(race, 0)].shape[0],
                       _COMPAS_DF_TUPLES[(race, 1)].shape[0])

  # Split the data into two DataFrames --one biased and one unbiased.
  _UNBIASED_COMPAS = pd.concat(
      [_COMPAS_DF_TUPLES[(race, 0)][:min_bias_count], _UNBIASED_COMPAS])
  _UNBIASED_COMPAS = pd.concat(
      [_COMPAS_DF_TUPLES[(race, 1)][:min_bias_count], _UNBIASED_COMPAS])

  _BIASED_COMPAS = pd.concat(
      [_COMPAS_DF_TUPLES[(race, 0)][min_bias_count:], _BIASED_COMPAS])
  _BIASED_COMPAS = pd.concat(
      [_COMPAS_DF_TUPLES[(race, 1)][min_bias_count:], _BIASED_COMPAS])
</code>```

Body:
I'm working with the COMPAS dataset and looking to create two Pandas DataFrame with the data --one with bias and one without, by splitting the set into two. As of now, I have the below working that will create one dataframe, but it will carry over the bias originally found in COMPAS because "replace" must be set to True given the distribution in size between races.

import os
import tempfile
import urllib

_DATA_ROOT = tempfile.mkdtemp(prefix='tfx-data')
_DATA_PATH = 'https://storage.googleapis.com/what-if-tool-resources/computefest2019/cox-violent-parsed_filt.csv'
_DATA_FILEPATH = os.path.join(_DATA_ROOT, 'compas-scores-two-years.csv')
urllib.request.urlretrieve(_DATA_PATH, _DATA_FILEPATH)

_COMPAS_DF = _COMPAS_DF[_COMPAS_DF['is_recid'] != -1]
_GROUPBY_DF = _COMPAS_DF.groupby('race')
_COMPAS_DF = _GROUPBY_DF.apply(lambda x: x.sample(5000, replace=True).reset_index(drop=True))
_COMPAS_DF['race'].value_counts()

The output of this dataframe is below but the bias of 'is_recid', which is a bool value of the defendant's recidivism stays the same.

African-American    5000
Other               5000
Caucasian           5000
Asian               5000
Hispanic            5000
Native American     5000
Name: race, dtype: int64

The starting dataframe is listed below:

is_recid  Race              Count is_recid
0         African-American  4338    24.79%
          Caucasian         3308    18.91%
          Hispanic          860     4.92%
          Other             502     2.87%
          Asian             45      0.26%
          Native American   26      0.15%
1         African-American  5081    29.04%
          Caucasian         2474    14.14%
          Hispanic          495     2.83%
          Other             323     1.85%
          Native American   25      0.14%
          Asian             19      0.11%
Total                       17496   100.00%

My hope is to create a dataframe like the below and a second dataframe with the remaining values from the original dataset. Note that the count doesn't necessarily need to be exactly as listed but the distribution between race and is_recid is balanced.

is_recid  Race              Count   is_recid
0         African-American  3000    29.85%
          Caucasian         1500    14.93%
          Hispanic          300     2.99%
          Other             200     1.99%
          Asian             10      0.10%
          Native American   15      0.15%
1         African-American  3000    29.85%
          Caucasian         1500    14.93%
          Hispanic          300     2.99%
          Other             200     1.99%
          Native American   15      0.15%
          Asian             10      0.10%
Total                       10050   100.00%

Many thanks in advance!

Body:
The below ended up working for me:

_COMPAS_DF_TUPLES = dict(tuple(_COMPAS_DF.groupby(['race', 'is_recid'])))
_UNBIASED_COMPAS = pd.DataFrame()
_BIASED_COMPAS = pd.DataFrame()

for race in _COMPAS_DF['race'].unique():
  # Find the minimum difference between race and is_recid to create an unbiased
  # dataset.
  min_bias_count = min(_COMPAS_DF_TUPLES[(race, 0)].shape[0],
                       _COMPAS_DF_TUPLES[(race, 1)].shape[0])

  # Split the data into two DataFrames --one biased and one unbiased.
  _UNBIASED_COMPAS = pd.concat(
      [_COMPAS_DF_TUPLES[(race, 0)][:min_bias_count], _UNBIASED_COMPAS])
  _UNBIASED_COMPAS = pd.concat(
      [_COMPAS_DF_TUPLES[(race, 1)][:min_bias_count], _UNBIASED_COMPAS])

  _BIASED_COMPAS = pd.concat(
      [_COMPAS_DF_TUPLES[(race, 0)][min_bias_count:], _BIASED_COMPAS])
  _BIASED_COMPAS = pd.concat(
      [_COMPAS_DF_TUPLES[(race, 1)][min_bias_count:], _BIASED_COMPAS])


问:
Can't connect to Browsermob-proxy ProxyServerError
I'm new to using browsermob-proxy utility tool. Here's my code that runs perfectly fine on my local instance but when I try it on my ec2 instance(using headless browser) gives me an error:

```<code> raise ProxyServerError("Can't connect to Browsermob-Proxy")
browsermobproxy.exceptions.ProxyServerError: Can't connect to Browsermob-Proxy
</code>```

The only difference between my local and ec2 instance setup is that on ec2 it's running on the headless browser.

Code Snippet:

```<code>def start_proxy_server():
    for proc in psutil.process_iter():
        # check whether the process name matches
        if proc.name() == "browsermob-proxy":
            proc.kill()
    dict = {'port': 7190}
    server = Server(path="path_to_browswermob/browsermob-proxy-2.1.4/bin/browsermob-proxy", options=dict)
    server.start()
    time.sleep(1)
    proxy = server.create_proxy()
    time.sleep(1)
    chrome_options = webdriver.ChromeOptions()
    chrome_options.add_argument("--proxy-server={0}".format(proxy.proxy)) #Configure chrome options
    driver = webdriver.Chrome('path_to_chromedriver/chromedriver',options=chrome_options)
    options = Options()
    options.headless = True
    driver.get("www.google.com")
    return driver, proxy
</code>```

Any help would be appreciated!

答:
I got it working with some changes</p>

```<code>def start_proxy_server():
for proc in psutil.process_iter():
    # check whether the process name matches
    if proc.name() == "browsermob-proxy":
        proc.kill()

dict = {'port': 8080}
server = Server(path="path_to_browswermob/browsermob-proxy-2.1.4/bin/browsermob-proxy", options=dict)
server.start()
time.sleep(1)
proxy = server.create_proxy()
time.sleep(1)
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument("--headless")
chrome_options.add_argument("--proxy-server={0}".format(proxy.proxy)) #Configure chrome options
</code>```

Body:
I'm new to using browsermob-proxy utility tool. Here's my code that runs perfectly fine on my local instance but when I try it on my ec2 instance(using headless browser) gives me an error:

 raise ProxyServerError("Can't connect to Browsermob-Proxy")
browsermobproxy.exceptions.ProxyServerError: Can't connect to Browsermob-Proxy

The only difference between my local and ec2 instance setup is that on ec2 it's running on the headless browser.

Code Snippet:

def start_proxy_server():
    for proc in psutil.process_iter():
        # check whether the process name matches
        if proc.name() == "browsermob-proxy":
            proc.kill()
    dict = {'port': 7190}
    server = Server(path="path_to_browswermob/browsermob-proxy-2.1.4/bin/browsermob-proxy", options=dict)
    server.start()
    time.sleep(1)
    proxy = server.create_proxy()
    time.sleep(1)
    chrome_options = webdriver.ChromeOptions()
    chrome_options.add_argument("--proxy-server={0}".format(proxy.proxy)) #Configure chrome options
    driver = webdriver.Chrome('path_to_chromedriver/chromedriver',options=chrome_options)
    options = Options()
    options.headless = True
    driver.get("www.google.com")
    return driver, proxy

Any help would be appreciated!

Body:
I got it working with some changes

def start_proxy_server():
for proc in psutil.process_iter():
    # check whether the process name matches
    if proc.name() == "browsermob-proxy":
        proc.kill()

dict = {'port': 8080}
server = Server(path="path_to_browswermob/browsermob-proxy-2.1.4/bin/browsermob-proxy", options=dict)
server.start()
time.sleep(1)
proxy = server.create_proxy()
time.sleep(1)
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument("--headless")
chrome_options.add_argument("--proxy-server={0}".format(proxy.proxy)) #Configure chrome options


问:
Indexing View on Aggregate Field
I am just wondering if there is any way to create index on agregate field?

```<code>CREATE TABLE test2 (
id INTEGER,
name VARCHAR(10),
family VARCHAR(10),
amount INTEGER)

CREATE VIEW dbo.test2_v WITH SCHEMABINDING
AS
SELECT id, SUM(amount) as amount, COUNT_BIG(*) as tmp
FROM dbo.test2
GROUP BY id

CREATE UNIQUE CLUSTERED INDEX vIdx ON test2_v(amount)
</code>```

I have next error message with this code:

Cannot create the clustered index
  "vIdx" on view "test.dbo.test2_v"
  because the index key includes columns
  that are not in the GROUP BY clause.
  Consider eliminating columns that are
  not in the GROUP BY clause from the
  index key.

答:
One of the restrictions when creating an unique clustered index on a view is.

If the view definition contains a
  GROUP BY clause, the key of the unique
  clustered index can reference only the
  columns specified in the GROUP BY
  clause.

http://msdn.microsoft.com/en-us/library/ms188783.aspx

So you firstly need to create a UNIQUE CLUSTERED index on your key, then you can create a NONCLUSTERED index on your amount column.

```<code>CREATE UNIQUE CLUSTERED INDEX vIdx ON test2_v(id)
CREATE NONCLUSTERED INDEX ix_test2_v_amount ON test2_v(amount)
</code>```

Title: Indexing View on Aggregate Field

Body:
I am just wondering if there is any way to create index on agregate field?

CREATE TABLE test2 (
id INTEGER,
name VARCHAR(10),
family VARCHAR(10),
amount INTEGER)

CREATE VIEW dbo.test2_v WITH SCHEMABINDING
AS
SELECT id, SUM(amount) as amount, COUNT_BIG(*) as tmp
FROM dbo.test2
GROUP BY id

CREATE UNIQUE CLUSTERED INDEX vIdx ON test2_v(amount)

I have next error message with this code:

Cannot create the clustered index
  "vIdx" on view "test.dbo.test2_v"
  because the index key includes columns
  that are not in the GROUP BY clause.
  Consider eliminating columns that are
  not in the GROUP BY clause from the
  index key.

Body:
One of the restrictions when creating an unique clustered index on a view is.

If the view definition contains a
  GROUP BY clause, the key of the unique
  clustered index can reference only the
  columns specified in the GROUP BY
  clause.

http://msdn.microsoft.com/en-us/library/ms188783.aspx

So you firstly need to create a UNIQUE CLUSTERED index on your key, then you can create a NONCLUSTERED index on your amount column.

CREATE UNIQUE CLUSTERED INDEX vIdx ON test2_v(id)
CREATE NONCLUSTERED INDEX ix_test2_v_amount ON test2_v(amount)


问:
Keras inconsistent prediction time
I tried to get an estimate of the prediction time of my keras model and realised something strange. Apart from being fairly fast normally, every once in a while the model needs quite long to come up with a prediction. And not only that, those times also increase the longer the model runs. I added a minimal working example to reproduce the error.

import time
import numpy as np
from sklearn.datasets import make_classification
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Flatten

# Make a dummy classification problem
X, y = make_classification()

# Make a dummy model
model = Sequential()
model.add(Dense(10, activation='relu',name='input',input_shape=(X.shape[1],)))
model.add(Dense(2, activation='softmax',name='predictions'))
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])

model.fit(X, y, verbose=0, batch_size=20, epochs=100)

for i in range(1000):
    # Pick a random sample
    sample = np.expand_dims(X[np.random.randint(99), :], axis=0)
    # Record the prediction time 10x and then take the average
    start = time.time()
    for j in range(10):
        y_pred = model.predict_classes(sample)
    end = time.time()
    print('%d, %0.7f' % (i, (end-start)/10))
```

<p>The time does  not depend on the sample (it is being picked randomly). If the test is repeated, the indices in the for loop where the prediction takes longer are going to be (nearly) the same again.</p>

<p><img src="https://i.stack.imgur.com/m0alO.png" alt="enter image description here"></p>

<p>I'm using:</p>

```tensorflow 2.0.0
python 3.7.4
```

For my application I need to guarantee the execution in a certain time. This is however impossible considering that behaviour. What is going wrong? Is it a bug in Keras or a bug in the tensorflow backend?

EDIT:
predict_on_batch shows the same behavior, however, more sparse:

y_pred = model(sample, training=False).numpy() shows some heavy outliers as well, however, they are not increasing.

EDIT 2:
I downgraded to the latest tensorflow 1 version (1.15). Not only is the problem not existent anymore, also the "normal" prediction time significantly improved! I do not see the two spikes as problematic, as they didn't appear when I repeated the test (at least not at the same indices and linearly increasing) and are percentual not as large as in the first plot.

We can thus conclude that this seems to be a problem inherent to tensorflow 2.0, which shows similar behaviour in other situations as @OverLordGoldDragon mentions.

答:
TF2 generally exhibits poor and bug-like memory management in several instances I've encountered - brief description here and here. With prediction in particular, the most performant feeding method is via model(x) directly - see here, and its linked discussions.

In a nutshell: model(x) acts via its its __call__ method (which it inherits from base_layer.Layer), whereas predict(), predict_classes(), etc. involve a dedicated loop function via _select_training_loop(); each utilize different data pre- and post-processing methods suited for different use-cases, and model(x) in 2.1 was designed specifically to yield fastest small-model / small-batch (and maybe any-size) performance (and still fastest in 2.0).

Quoting a TensorFlow dev from linked discussions:

You can predict the output using model call, not model predict, i.e., calling model(x) would make this much faster because there are no "conversion to dataset" part, and also it's directly calling a cached tf.function.

Note: this should be less of an issue in 2.1, and especially 2.2 - but test each method anyway. Also I realize this doesn't directly answer your question on the time spikes; I suspect it's related to Eager caching mechanisms, but the surest way to determine is via TF Profiler, which is broken in 2.1.

Update: regarding increasing spikes, possible GPU throttling; you've done ~1000 iters, try 10,000 instead - eventually, the increasing should stop. As you noted in your comments, this doesn't occur with model(x); makes sense as one less GPU step is involved ("conversion to dataset").

Update2: you could bug the devs here about it if you face this issue; it's mostly me singing there

Title: Keras inconsistent prediction time

Body:
I tried to get an estimate of the prediction time of my keras model and realised something strange. Apart from being fairly fast normally, every once in a while the model needs quite long to come up with a prediction. And not only that, those times also increase the longer the model runs. I added a minimal working example to reproduce the error.

import time
import numpy as np
from sklearn.datasets import make_classification
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Flatten

# Make a dummy classification problem
X, y = make_classification()

# Make a dummy model
model = Sequential()
model.add(Dense(10, activation='relu',name='input',input_shape=(X.shape[1],)))
model.add(Dense(2, activation='softmax',name='predictions'))
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])

model.fit(X, y, verbose=0, batch_size=20, epochs=100)

for i in range(1000):
    # Pick a random sample
    sample = np.expand_dims(X[np.random.randint(99), :], axis=0)
    # Record the prediction time 10x and then take the average
    start = time.time()
    for j in range(10):
        y_pred = model.predict_classes(sample)
    end = time.time()
    print('%d, %0.7f' % (i, (end-start)/10))

The time does  not depend on the sample (it is being picked randomly). If the test is repeated, the indices in the for loop where the prediction takes longer are going to be (nearly) the same again.

I'm using:

tensorflow 2.0.0
python 3.7.4

For my application I need to guarantee the execution in a certain time. This is however impossible considering that behaviour. What is going wrong? Is it a bug in Keras or a bug in the tensorflow backend?

EDIT:
predict_on_batch shows the same behavior, however, more sparse:

y_pred = model(sample, training=False).numpy() shows some heavy outliers as well, however, they are not increasing.

EDIT 2:
I downgraded to the latest tensorflow 1 version (1.15). Not only is the problem not existent anymore, also the "normal" prediction time significantly improved! I do not see the two spikes as problematic, as they didn't appear when I repeated the test (at least not at the same indices and linearly increasing) and are percentual not as large as in the first plot.

We can thus conclude that this seems to be a problem inherent to tensorflow 2.0, which shows similar behaviour in other situations as @OverLordGoldDragon mentions.


问:
MIssing the last step to map Json to a List/Array (Flutter)
I'm new to the Flutter (Dart) environment, so looking for some guidance on what I hope is a trivial coding issue on my side.

I have the following json, which I've validated,.....

```<code>[{"refModel":[{"firstName":"John","lastName":"Smith","os":"121212","refStatus":"Y","refActivationDate":"0000-00-00","gamesMiddles":0,"middles":[],"gamesLines":0,"lines":[],"gamesToReport":0,"reports":[]}]}]
</code>```

The following is the class structure I use (not final version, needs further definitions).....

Data looks good after using json.decode (see below)

but when trying to map the data to the defined class, RefProfile, using the following....

```<code>setState(() {
  refProfile = RefProfile.fromJson(refMap);
});
</code>```

with following code generated by json_annotation.dart

the resulting refProfile.refModel list(array) contains 1 record but all fields are null.
I've been reworking the code based on reading stackoverflow and googling for suggestions for the past 3 days but no luck, so any insight would be appreciated!

答:
as suspected, coding issue on my side.  To make this work, I changed

refProfile = RefProfile.fromJson(refMap);

to

refProfile = RefProfile.fromJson(refMap['refModel']);

so the mapping script now properly finds the json object and maps the api data to the local model.

Body:
I'm new to the Flutter (Dart) environment, so looking for some guidance on what I hope is a trivial coding issue on my side.

I have the following json, which I've validated,.....

[{"refModel":[{"firstName":"John","lastName":"Smith","os":"121212","refStatus":"Y","refActivationDate":"0000-00-00","gamesMiddles":0,"middles":[],"gamesLines":0,"lines":[],"gamesToReport":0,"reports":[]}]}]

The following is the class structure I use (not final version, needs further definitions).....

Data looks good after using json.decode (see below)

but when trying to map the data to the defined class, RefProfile, using the following....

setState(() {
  refProfile = RefProfile.fromJson(refMap);
});

with following code generated by json_annotation.dart

the resulting refProfile.refModel list(array) contains 1 record but all fields are null.
I've been reworking the code based on reading stackoverflow and googling for suggestions for the past 3 days but no luck, so any insight would be appreciated!