问:
Preserve Encapsulation while Displaying Information
Suppose I've got the following class to represent a Car and Tire:

```<code>public final class Tire{

    private final String brand
    private final TireType type;

    public Tire(String brand, type)
    {
      this.brand = brand
      this.type = type;
    }

    //getters and toString() for tire attributes
}

public final class Car{

    private final String name;
    private final Tire tire;

    public Car(String name, Tire tire){
        this.name = name;
        this.tire = tire;
    }

    public String getName(){
        return this.name;
    }
}
</code>```

I'm fully aware that my Car and Tire example are lacking notable attributes, but that's not the focus of my question, it's the simplest MCVE I could come up with.

From Effective Java(p. 53):

Whether or not you specify the format, provide programmatic access to
  all of the information contained in the value returned by toString.

In my Car class, the toString() method will obviously return the name, and according to Effective Java, as quoted above I should provide a getter as well. My problem is when returning the details of the Tire.

Question:

Given the advice quoted from Effective Java, how would I properly return the details of my car including the Tire for display purposes?

Would I do this:

```<code>public Tire getTire(){
    return this.tire
}

public String toString(){
     return  "Name:  " + this.name + " Tire: " + this.tire;
}
</code>```

Or to put it another way, when you have a class, in my case(Tire), that is also an attribute of another class, in my case(Car), when returning the details to be printed in a GUI, how would I do so and perverse encapsulation?

答:
From book:

Whether or not you specify the format, provide programmatic access to all of the information contained in the value returned by toString
  If you fail to do this, you force programmers who need this information to parse the string.

If you use some really really private information in ToString, than there is a chance that someone will extract it. I would say it differently: use only public information in toString or use toString only for debugging, not for implementation logic.

Body:
Suppose I've got the following class to represent a Car and Tire:

public final class Tire{

    private final String brand
    private final TireType type;

    public Tire(String brand, type)
    {
      this.brand = brand
      this.type = type;
    }

    //getters and toString() for tire attributes
}

public final class Car{

    private final String name;
    private final Tire tire;

    public Car(String name, Tire tire){
        this.name = name;
        this.tire = tire;
    }

    public String getName(){
        return this.name;
    }
}

I'm fully aware that my Car and Tire example are lacking notable attributes, but that's not the focus of my question, it's the simplest MCVE I could come up with.

From Effective Java(p. 53):

Whether or not you specify the format, provide programmatic access to
  all of the information contained in the value returned by toString.

In my Car class, the toString() method will obviously return the name, and according to Effective Java, as quoted above I should provide a getter as well. My problem is when returning the details of the Tire.

Question:

Given the advice quoted from Effective Java, how would I properly return the details of my car including the Tire for display purposes?

Would I do this:

public Tire getTire(){
    return this.tire
}

public String toString(){
     return  "Name:  " + this.name + " Tire: " + this.tire;
}

Or to put it another way, when you have a class, in my case(Tire), that is also an attribute of another class, in my case(Car), when returning the details to be printed in a GUI, how would I do so and perverse encapsulation?


来源: stackexchange

问:
Using array to pass through a find loop
here is my code, its almost working but only passes the first part of the array. I think its the second end if, but if i remove it. It says no next without for even though for for part is at the beginning of the loop. Can someone tell me what I did wrong please.</p>

```<code>Sub findEG()
Dim rng, s, e As Range
Dim rws As Long, w As Long
Dim vWHATs As Variant

lastrow = Worksheets("MOO_filtered").Range("B" & Rows.Count).End(xlUp).Row

vWHATs = Array("LIFES - Sup Life - Sps", "LIFEE - Sup Life - Emp", "LIFEC - Supp Life - Ch", _
               "VLTD  - Vol LTD MOO", "VSTD  - Vol STD MOO")

With Worksheets("MOO Data")
For w = LBound(vWHATs) To UBound(vWHATs)
Set r = .Range("B:B").Find(vWHATs)

      If Not r Is Nothing Then
        Set e = .Range("B:B").Find("Totals for:", r)
        If Not e Is Nothing Then
            .Range(r, e).EntireRow.Copy Worksheets("MOO_filtered").Range("A" & lastrow)
        End If

      End If
Next w

End With
End Sub
</code>```

答:
I've tested the code below and I believe it does what you want it to do:</p>

```<code>Sub findEG()
Dim rng, s As Range
Dim rws As Long, w As Long
Dim vWHATs As Variant
lastrow = Worksheets("MOO_filtered").Range("B" & Rows.Count).End(xlUp).Row

vWHATs = Array("LIFES - Sup Life - Sps", "LIFEE - Sup Life - Emp", "LIFEC - Supp Life - Ch", _
               "VLTD  - Vol LTD MOO", "VSTD  - Vol STD MOO")

With Worksheets("MOO Data")
For w = LBound(vWHATs) To UBound(vWHATs)
Set r = .Range("B:B").Find(vWHATs(w)) 'included the (w) so the array values go in sequence in the For Loop
      If Not r Is Nothing Then
        Set e = .Range("B:B").Find("Totals for:" & r.Value & "*") ' here are you sure you are looking for the possible string: "Totals for:LIFES - Sup Life - Sps" without the space between the :?
        If Not e Is Nothing Then
            .Rows(r.Row & ":" & e.Row).EntireRow.Copy Worksheets("MOO_filtered").Range("A" & lastrow +1)
        End If

      End If
Next w
End With
End Sub
</code>```

ContentLicense: CC BY-SA 3.0

Title: Using array to pass through a find loop

Body:
here is my code, its almost working but only passes the first part of the array. I think its the second end if, but if i remove it. It says no next without for even though for for part is at the beginning of the loop. Can someone tell me what I did wrong please.

Sub findEG()
Dim rng, s, e As Range
Dim rws As Long, w As Long
Dim vWHATs As Variant

lastrow = Worksheets("MOO_filtered").Range("B" & Rows.Count).End(xlUp).Row

vWHATs = Array("LIFES - Sup Life - Sps", "LIFEE - Sup Life - Emp", "LIFEC - Supp Life - Ch", _
               "VLTD  - Vol LTD MOO", "VSTD  - Vol STD MOO")

With Worksheets("MOO Data")
For w = LBound(vWHATs) To UBound(vWHATs)
Set r = .Range("B:B").Find(vWHATs)

      If Not r Is Nothing Then
        Set e = .Range("B:B").Find("Totals for:", r)
        If Not e Is Nothing Then
            .Range(r, e).EntireRow.Copy Worksheets("MOO_filtered").Range("A" & lastrow)
        End If

      End If
Next w

End With
End Sub

Body:
I've tested the code below and I believe it does what you want it to do:

Sub findEG()
Dim rng, s As Range
Dim rws As Long, w As Long
Dim vWHATs As Variant
lastrow = Worksheets("MOO_filtered").Range("B" & Rows.Count).End(xlUp).Row

vWHATs = Array("LIFES - Sup Life - Sps", "LIFEE - Sup Life - Emp", "LIFEC - Supp Life - Ch", _
               "VLTD  - Vol LTD MOO", "VSTD  - Vol STD MOO")

With Worksheets("MOO Data")
For w = LBound(vWHATs) To UBound(vWHATs)
Set r = .Range("B:B").Find(vWHATs(w)) 'included the (w) so the array values go in sequence in the For Loop
      If Not r Is Nothing Then
        Set e = .Range("B:B").Find("Totals for:" & r.Value & "*") ' here are you sure you are looking for the possible string: "Totals for:LIFES - Sup Life - Sps" without the space between the :?
        If Not e Is Nothing Then
            .Rows(r.Row & ":" & e.Row).EntireRow.Copy Worksheets("MOO_filtered").Range("A" & lastrow +1)
        End If

      End If
Next w
End With
End Sub


问:
laravel validation update: It must 'required' only if stored record is empty
I have a filed for validation:

```<code>public function update(request $request, Sight $sight)
   {
     $validator = Validator::make($request->all(), [
         'img' => 'required|image|max:3000',
         ...
</code>```

It must be 'required',if only 'img' field in stored record is null.

Is it possible?

答:
This is PHP, it is dynamic. We have conditionals and variables and all that fun jazz.  You control the string that contains all the rules you want to use and you have the model there. Just build your string.

```<code>public function update(Request $request, Sight $sight)
{
    $required = $sight->img === null ? 'required|' : '';

    $validator = Validator::make($request->all(), [
        'img' => $required .'image|max:30
</code>```

Thats one way without getting into extending anything.

Body:
I have a filed for validation:

public function update(request $request, Sight $sight)
   {
     $validator = Validator::make($request->all(), [
         'img' => 'required|image|max:3000',
         ...

It must be 'required',if only 'img' field in stored record is null.

Is it possible?

Body:
This is PHP, it is dynamic. We have conditionals and variables and all that fun jazz.  You control the string that contains all the rules you want to use and you have the model there. Just build your string.

public function update(Request $request, Sight $sight)
{
    $required = $sight->img === null ? 'required|' : '';

    $validator = Validator::make($request->all(), [
        'img' => $required .'image|max:30

Thats one way without getting into extending anything.


问:
How to get Number of bits from Hex
For example how do I get 8 from 0x01, or 16 from 0x0001.

I want to know the number of bits a variable has.

```<code>var someNumber = 0x123456;
var len = whatToDoHere(someNumber);
console.log(len); // => 24 for example
</code>```

答:
Another possible solution is to convert to a hex string and then measure the length of the string:

const someNumber = 0x123456;
const hexString = someNumber.toString( 16 );
const numberOfBits = hexString.length * 4;   //each character is half a byte
console.log( "Number of bits: ", numberOfBits );```

Title: How to get Number of bits from Hex

Body:
For example how do I get 8 from 0x01, or 16 from 0x0001.

I want to know the number of bits a variable has.

var someNumber = 0x123456;
var len = whatToDoHere(someNumber);
console.log(len); // => 24 for example


问:
Database Design for Facebook Message like, application
Designing a facebook message like application for an internal application.

Is this how you would design it? any way to improve on this design? thanks :)

```<code>MESSAGE
Id
Subject
Content
ReadDate -- datetime
DeletedDate -- datetime
CreatedBy -- userid
CreatedOn -- datetime

MESSAGE_COMMENT
Id
MessageId
Content
CreatedBy -- userid
CreatedOn -- datetime

MESSAGE_RECIPIENT
Id
MessageId
Recipient -- UserId
ReadDate -- datetime
DeletedDate -- datetime
</code>```

EDIT: there might be something missing with the design or it may be incorrect, let me know.

答:
I think, this is pretty enogh, for sending/receiving messages.

More depends on what you would like to do...

ContentLicense: CC BY-SA 2.5

Body:
Designing a facebook message like application for an internal application.

Is this how you would design it? any way to improve on this design? thanks :)

MESSAGE
Id
Subject
Content
ReadDate -- datetime
DeletedDate -- datetime
CreatedBy -- userid
CreatedOn -- datetime

MESSAGE_COMMENT
Id
MessageId
Content
CreatedBy -- userid
CreatedOn -- datetime

MESSAGE_RECIPIENT
Id
MessageId
Recipient -- UserId
ReadDate -- datetime
DeletedDate -- datetime

EDIT: there might be something missing with the design or it may be incorrect, let me know.


问:
Count multiple items in the same column pulling data from 2 tables - mysql
I have 2 tables and I need to count the number of times any role shows up in each movie

Example of Tables:

Movie Table

```<code>TITLE           MOVIEID     OTHER STUFF....
-------------   -------
MOVIE TITLE 1   ID# 1
MOVIE TITLE 2   ID# 2
MOVIE TITLE 3   ID# 3
ETC...
</code>```

Role Table

```<code>ROLEID      MOVIEID     OTHER STUFF....
-------     -------
ROLE #1     ID# 1
ROLE #2     ID# 1
ROLE #3     ID# 2
ROLE #4     ID# 2
ROLE #5     ID# 3
ROLE #6     ID# 4
ROLE #7     ID# 5
ROLE #8     ID# 3
ETC....
</code>```

I would like to get an output that looks like this:

```<code>TITLE           NUMROLES
-------------   --------------------------------------
MOVIE TITLE 1   COUNT (ROLE.MOVIEID) FOR MOVIE TITLE 1
MOVIE TITLE 2   COUNT (ROLE.MOVIEID) FOR MOVIE TITLE 2
MOVIE TITLE 3   COUNT (ROLE.MOVIEID) FOR MOVIE TITLE 3
MOVIE TITLE 4   COUNT (ROLE.MOVIEID) FOR MOVIE TITLE 4
MOVIE TITLE 5   COUNT (ROLE.MOVIEID) FOR MOVIE TITLE 5
ETC...
</code>```

I have tried a several different things but I seem to always get a total count of all the roles instead of them being counted individually.

My "best" output Example:

```<code>mysql> SELECT TITLE, COUNT(ROLE.MOVIEID) AS NUMROLES
    -> FROM MOVIE, ROLE
    -> GROUP BY TITLE;
+-----------------------------+----------+
| TITLE                       | NUMROLES |
+-----------------------------+----------+
| Amadeus                     |      138 |
| Apollo 13                   |      138 |
| Batman                      |      138 |
| Batman & Robin              |      138 |
| Batman Begins               |      138 |
| Batman Forever              |      138 |
| Batman Returns              |      138 |
| Casablanca                  |      138 |
| Dirty Harry                 |      138 |
| Few Good Men, A             |      138 |
| Field of Dreams             |      138 |
| Fly, The                    |      138 |
| Forrest Gump                |      138 |
| Godfather, The              |      138 |
| Gone with the Wind          |      138 |
| Jerry Maguire               |      138 |
| Mrs. Doubtfire              |      138 |
| Naked City, The             |      138 |
| Sixth Sense, The            |      138 |
| Sudden Impact               |      138 |
| Terminator 2:  Judgment Day |      138 |
| Terminator, The             |      138 |
| Tootsie                     |      138 |
| Wizard of Oz, The           |      138 |
+-----------------------------+----------+
24 rows in set (0.02 sec)
</code>```

I am thinking I don't have the proper knowledge of what I should be using in this case, can anyone point me in the right direction without just giving me the answer??

Bonus:

I also need to filter out any titles that don't have at least 6 for count of (ROLE.MOVIEID) - I am thinking I need to use HAVING for that.

答:
Your Query:

```<code>SELECT TITLE, COUNT(ROLE.MOVIEID) AS NUMROLES
FROM MOVIE, ROLE
GROUP BY TITLE;
</code>```

Here, you're doing Cross Join between tables MOVIE & ROLE. Which leads you to wrong result.

What you need here is Inner Join of these 2 tables based on the common column  MOVIEID.

Following query should work:

```<code>SELECT m.TITLE, COUNT(r.MOVIEID) AS NUMROLES
FROM MOVIE m
inner join ROLE r
on m.MOVIEID = r.MOVIEID
GROUP BY m.TITLE
having NUMROLES >=6;
</code>```

having NUMROLES >=6 is used to filter out TITLE with 5 or less than 5 counts.

You can learn more about JOIN by clicking here.

Body:
I have 2 tables and I need to count the number of times any role shows up in each movie

Example of Tables:

Movie Table

TITLE           MOVIEID     OTHER STUFF....
-------------   -------
MOVIE TITLE 1   ID# 1
MOVIE TITLE 2   ID# 2
MOVIE TITLE 3   ID# 3
ETC...

Role Table

ROLEID      MOVIEID     OTHER STUFF....
-------     -------
ROLE #1     ID# 1
ROLE #2     ID# 1
ROLE #3     ID# 2
ROLE #4     ID# 2
ROLE #5     ID# 3
ROLE #6     ID# 4
ROLE #7     ID# 5
ROLE #8     ID# 3
ETC....

I would like to get an output that looks like this:

TITLE           NUMROLES
-------------   --------------------------------------
MOVIE TITLE 1   COUNT (ROLE.MOVIEID) FOR MOVIE TITLE 1
MOVIE TITLE 2   COUNT (ROLE.MOVIEID) FOR MOVIE TITLE 2
MOVIE TITLE 3   COUNT (ROLE.MOVIEID) FOR MOVIE TITLE 3
MOVIE TITLE 4   COUNT (ROLE.MOVIEID) FOR MOVIE TITLE 4
MOVIE TITLE 5   COUNT (ROLE.MOVIEID) FOR MOVIE TITLE 5
ETC...

I have tried a several different things but I seem to always get a total count of all the roles instead of them being counted individually.

My "best" output Example:

mysql> SELECT TITLE, COUNT(ROLE.MOVIEID) AS NUMROLES
    -> FROM MOVIE, ROLE
    -> GROUP BY TITLE;
+-----------------------------+----------+
| TITLE                       | NUMROLES |
+-----------------------------+----------+
| Amadeus                     |      138 |
| Apollo 13                   |      138 |
| Batman                      |      138 |
| Batman & Robin              |      138 |
| Batman Begins               |      138 |
| Batman Forever              |      138 |
| Batman Returns              |      138 |
| Casablanca                  |      138 |
| Dirty Harry                 |      138 |
| Few Good Men, A             |      138 |
| Field of Dreams             |      138 |
| Fly, The                    |      138 |
| Forrest Gump                |      138 |
| Godfather, The              |      138 |
| Gone with the Wind          |      138 |
| Jerry Maguire               |      138 |
| Mrs. Doubtfire              |      138 |
| Naked City, The             |      138 |
| Sixth Sense, The            |      138 |
| Sudden Impact               |      138 |
| Terminator 2:  Judgment Day |      138 |
| Terminator, The             |      138 |
| Tootsie                     |      138 |
| Wizard of Oz, The           |      138 |
+-----------------------------+----------+
24 rows in set (0.02 sec)

I am thinking I don't have the proper knowledge of what I should be using in this case, can anyone point me in the right direction without just giving me the answer??

Bonus:

I also need to filter out any titles that don't have at least 6 for count of (ROLE.MOVIEID) - I am thinking I need to use HAVING for that.

Body:
Your Query:

SELECT TITLE, COUNT(ROLE.MOVIEID) AS NUMROLES
FROM MOVIE, ROLE
GROUP BY TITLE;

Here, you're doing Cross Join between tables MOVIE & ROLE. Which leads you to wrong result.

What you need here is Inner Join of these 2 tables based on the common column  MOVIEID.

Following query should work:

SELECT m.TITLE, COUNT(r.MOVIEID) AS NUMROLES
FROM MOVIE m
inner join ROLE r
on m.MOVIEID = r.MOVIEID
GROUP BY m.TITLE
having NUMROLES >=6;

having NUMROLES >=6 is used to filter out TITLE with 5 or less than 5 counts.

You can learn more about JOIN by clicking here.


问:
Set python variables to operators?

Python, Operators set to variables?

I am making a calculator and I want the user to be able to enter words like add to +.
 Is there any way to set python variables to operands. e.g.

```<code>operands = {
    "add": +
}
</code>```

etc.

Is there any way to do this  without modules. But if not possible is there a module?

答:
Here is the alternative using libraries (a standard one so no reason not to)

```<code>import operator as op

d = dict([
    ('^', op.pow),
    ('**', op.pow),
    ('*', op.mul),
    ('/', op.truediv),
    ('//', op.floordiv),
    ('+', op.add),
    ('-', op.sub)
    ])

d['*'](2,3)
</code>```

Returns: 6

Title: Set python variables to operators?

Body:
Python, Operators set to variables?

I am making a calculator and I want the user to be able to enter words like add to +.
 Is there any way to set python variables to operands. e.g.

operands = {
    "add": +
}

etc.

Is there any way to do this  without modules. But if not possible is there a module?

Body:
Here is the alternative using libraries (a standard one so no reason not to)

import operator as op

d = dict([
    ('^', op.pow),
    ('**', op.pow),
    ('*', op.mul),
    ('/', op.truediv),
    ('//', op.floordiv),
    ('+', op.add),
    ('-', op.sub)
    ])

d['*'](2,3)

Returns: 6


问:
Python lambda code using AWS Cloudwatch data input
So, I have a Cloudwatch rule which can send a SNS topic when triggered. Now, I'm setting up a lambda function to change the security group of the EC2 instance when the CloudWatch rule triggers.  I'm using python in Lambda, but my code it generating some "module errors".  The tricky part is that I am trying to take the cloudwatch data and pass it as a variable. The event variable is in this syntax-
 event['detail']['resource']['instanceDetails']['instanceId']
so in my python code, it looks like this...
I'm VERY new to python and lambda, but I'm trying to learn as much as I can. As you can see I'm trying to use this event variable and then utilize the SDK to execute the appropriate ModifyInstanceAttribute to change the security groups associated with the instance (for example with python):
This code will replace the Security Group associated with the Instance specified as described in the boto3 docs here: http://boto3.readthedocs.io/en/latest/reference/services/ec2.html#EC2.Client.modify_instance_attribute

my code so far below...

```<code>import boto3
client = boto3.client('ec2')
response =
client.modify_instance_attribute(InstanceId=event['detail']. ['resource']['instanceDetails']['instanceId'],
    Groups=['sg-4e499332',]
)
</code>```

error I get is this module initialization error: name 'event' is not defined

答:
You don't write code like that for Lambda. Your handler needs to be a function which takes the event and context parameters.

See the Lambda handler docs for Python.

Body:
So, I have a Cloudwatch rule which can send a SNS topic when triggered. Now, I'm setting up a lambda function to change the security group of the EC2 instance when the CloudWatch rule triggers.  I'm using python in Lambda, but my code it generating some "module errors".  The tricky part is that I am trying to take the cloudwatch data and pass it as a variable. The event variable is in this syntax-
 event['detail']['resource']['instanceDetails']['instanceId']
so in my python code, it looks like this...
I'm VERY new to python and lambda, but I'm trying to learn as much as I can. As you can see I'm trying to use this event variable and then utilize the SDK to execute the appropriate ModifyInstanceAttribute to change the security groups associated with the instance (for example with python):
This code will replace the Security Group associated with the Instance specified as described in the boto3 docs here: http://boto3.readthedocs.io/en/latest/reference/services/ec2.html#EC2.Client.modify_instance_attribute

my code so far below...

import boto3
client = boto3.client('ec2')
response =
client.modify_instance_attribute(InstanceId=event['detail']. ['resource']['instanceDetails']['instanceId'],
    Groups=['sg-4e499332',]
)

error I get is this module initialization error: name 'event' is not defined


问:
strncpy documentation question
At the following regarding strncpy: http://www.cplusplus.com/reference/clibrary/cstring/strncpy/, it mentions the following:

No null-character is implicitly appended to the end of destination, so destination will only be null-terminated if the length of the C string in source is less than num.

What is meant by this sentence?

答:
It means that, for example, if your source string is 20 characters plus a null terminator and your strncpy specifies less than 21 characters, the target string will not have a null appended to it.

It's because of the way it works: strncpy guarantees that it will write exactly N bytes where N is the length value passed in.

If the length of the source string (sans null byte) is less than that, it will pad the destination area with nulls. If it's equal or greater, you won't get a null added to the destination.

That means it may not technically be a C string that you get. This can be solved with code like:

```<code>char d[11];          // Have enough room for string and null.
strncpy (d, s, 10);  // Copy up to 10 bytes of string, null the rest.
d[10] = '\0';        // Then append null manually in case s was too long.
</code>```

You allocate 11 bytes (array indexes 0..10), copy up to 10 (indexes 0..9) then set the 11th (index 10) to null.

Here's a diagram showing the three possibilities for writing various-sized strings to a 10-character area with strncpy (d, s, 10) where . represents a null byte:

```<code>s              d
-------------  ----------
Hello.         Hello.....
Hello Fred.    Hello Fred
Hello George.  Hello Geor
</code>```

Note that in the second and third case, no null byte is written so, if you treat d as a string, you're likely to be disappointed in the outcome.

Title: strncpy documentation question

Body:
It means that, for example, if your source string is 20 characters plus a null terminator and your strncpy specifies less than 21 characters, the target string will not have a null appended to it.

It's because of the way it works: strncpy guarantees that it will write exactly N bytes where N is the length value passed in.

If the length of the source string (sans null byte) is less than that, it will pad the destination area with nulls. If it's equal or greater, you won't get a null added to the destination.

That means it may not technically be a C string that you get. This can be solved with code like:

char d[11];          // Have enough room for string and null.
strncpy (d, s, 10);  // Copy up to 10 bytes of string, null the rest.
d[10] = '\0';        // Then append null manually in case s was too long.

You allocate 11 bytes (array indexes 0..10), copy up to 10 (indexes 0..9) then set the 11th (index 10) to null.

Here's a diagram showing the three possibilities for writing various-sized strings to a 10-character area with strncpy (d, s, 10) where . represents a null byte:

s              d
-------------  ----------
Hello.         Hello.....
Hello Fred.    Hello Fred
Hello George.  Hello Geor

Note that in the second and third case, no null byte is written so, if you treat d as a string, you're likely to be disappointed in the outcome.


问:
Open Launch URL in an my app web view

Hello i set up onesignal Notification in my android app web view

but android when open notification will launch web browsers not in android app.

i want launch web url into  my app

please help me

答:
Ankit Mehta Is partially correct. Not only will you need a webChromeClient but you will have to declare the specific scheme, host & path pattern in your manifest along with the proper category for the specific activity you wish to open only specific urls with. If you wish to open any link you can omit the host & path.</p>

```<code><intent-filter>
                <action android:name="android.intent.action.VIEW" />
                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.BROWSABLE" />
                <data android:scheme="https" />
                <data android:scheme="http" />
                <data android:host="yoursite.com" />
                <data android:host="www.yoursite.com" />
                <data android:pathPattern="/subdirectory" />
</intent-filter>
</code>```

Title: Open Launch URL in an my app web view

Body:
Ankit Mehta Is partially correct. Not only will you need a webChromeClient but you will have to declare the specific scheme, host & path pattern in your manifest along with the proper category for the specific activity you wish to open only specific urls with. If you wish to open any link you can omit the host & path.

<intent-filter>
                <action android:name="android.intent.action.VIEW" />
                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.BROWSABLE" />
                <data android:scheme="https" />
                <data android:scheme="http" />
                <data android:host="yoursite.com" />
                <data android:host="www.yoursite.com" />
                <data android:pathPattern="/subdirectory" />
</intent-filter>


问:
The namespace System.Net.Cache does not exist
I am using the namespace System.Net.Http namespace with Xamarin in order to make calls to my HTTP REST API and it works fine. My http client code resides in the common portable project, and I call it from my android-only project (iOS is still in the backlogs)

Below is how it looks like:

```<code>Uri apiUri = new Uri("/example");
var request = (HttpWebRequest)HttpWebRequest.Create(apiUri);
request.ContentType = "application/json";
request.Method = "GET";
WebResponse response = await request.GetResponseAsync();
</code>```

However, I suspect that consecutive GET to the same URL are cached.
I have seen that it possible to remove the cache through HttpRequestCachePolicy objects, as described in https://developer.xamarin.com/api/type/System.Net.Cache.HttpRequestCachePolicy/ . My could should then look like:

```<code>Uri apiUri = new Uri("/example");
var request = (HttpWebRequest)HttpWebRequest.Create(apiUri);
request.ContentType = "application/json";
request.Method = "GET";
HttpRequestCachePolicy noCachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore);
request.CachePolicy = noCachePolicy;
WebResponse response = await request.GetResponseAsync();
</code>```

However, the namespace System.Net.Cache is not defined anywhere and I cannot use this method.
I am using the .NET SDK 4.5.

Is there some settings I am missing? Or should I look for a different way to disable GET request caching?

Below is the error I get:

```<code>The type or namespace name 'Cache' does not exist in the namespace 'System.Net' (are you missing an assembly reference?)
</code>```

答:
Regardless what is the best way to hit an HTTP API (WebClient vs. HttpClient vs. HttpWebRequest), the comment from @ShushiHangover help we to figure out the point of my question.

The PCL output format used to be the norm for Xamarin "portable" projects. However, the namespace System.Net.Cache is not usable in PCL libraries.
It is available in .NET Standard 2.0, which itself is not usable in PCL. PCL has been deprecated in summer 2017 in favor of .NET standard libraries, that allows to access to the .NET Standard 2.0 (among other benefits).

There is however no way to "convert" a project from PCL to .NET standard library but to make a new project and move all your files.
Therefore I decided to create a new .NET standard library project that contains only my HTTP client code.

Body:
I am using the namespace System.Net.Http namespace with Xamarin in order to make calls to my HTTP REST API and it works fine. My http client code resides in the common portable project, and I call it from my android-only project (iOS is still in the backlogs)

Below is how it looks like:

Uri apiUri = new Uri("/example");
var request = (HttpWebRequest)HttpWebRequest.Create(apiUri);
request.ContentType = "application/json";
request.Method = "GET";
WebResponse response = await request.GetResponseAsync();

However, I suspect that consecutive GET to the same URL are cached.
I have seen that it possible to remove the cache through HttpRequestCachePolicy objects, as described in https://developer.xamarin.com/api/type/System.Net.Cache.HttpRequestCachePolicy/ . My could should then look like:

Uri apiUri = new Uri("/example");
var request = (HttpWebRequest)HttpWebRequest.Create(apiUri);
request.ContentType = "application/json";
request.Method = "GET";
HttpRequestCachePolicy noCachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore);
request.CachePolicy = noCachePolicy;
WebResponse response = await request.GetResponseAsync();

However, the namespace System.Net.Cache is not defined anywhere and I cannot use this method.
I am using the .NET SDK 4.5.

Is there some settings I am missing? Or should I look for a different way to disable GET request caching?

Below is the error I get:

The type or namespace name 'Cache' does not exist in the namespace 'System.Net' (are you missing an assembly reference?)


问:
WebSocket4Net simple example fails with "Operation already in progress"
I'm trying to get a simple test going with Xamarin and WebSocket4Net but it fails on Open() with "Operation already in progress". Example code below:

```<code>using Xamarin.Forms;
using WebSocket4Net;
using System;
using SuperSocket.ClientEngine;

namespace SocketTest
{
    public partial class SocketTest : ContentPage
    {
        private WebSocket websocket;
        public SocketTest()
        {
            InitializeComponent();

        }

        void Handle_Clicked(object sender, System.EventArgs e)
        {
            websocket = new WebSocket("ws://echo.websocket.org/");
            websocket.Opened += Websocket_Opened;
            websocket.Error += Websocket_Error;
            websocket.Closed += Websocket_Closed;
            websocket.MessageReceived += Websocket_MessageReceived;
            websocket.Open();
        }

        private void Websocket_Error(object sender, ErrorEventArgs e)
        {
            Console.WriteLine(e.Exception.Message);
        }

        private void Websocket_MessageReceived(object sender, EventArgs e)
        {
            Console.WriteLine(e.ToString());
        }

        private void Websocket_Closed(object sender, EventArgs e)
        {
            Console.WriteLine(e.ToString());
        }

        private void Websocket_Opened(object sender, EventArgs e)
        {
            websocket.Send("Hello World!");
        }
    }
}
</code>```

I started with the standard multi-platform project (PCL) and added a button to initiate the connection.

```<code>Versions:
0.15.0 WebSocket4Net
0.8.0.13 SuperSocket
</code>```

The PCL is configured with: .NET Standard Platform = netstandard1.4

I'm fairly new to .NET/Xamarin but have many years of software development behind me.

答:
I've got the same issue with 0.15. Have you tried downgrading to 0.14, and removing SuperSocket?

There's a GitHub issue regarding this problem.

Getting this error when trying to connect in StartReceive()

Here's an excerpt:

Body:
I'm trying to get a simple test going with Xamarin and WebSocket4Net but it fails on Open() with "Operation already in progress". Example code below:

using Xamarin.Forms;
using WebSocket4Net;
using System;
using SuperSocket.ClientEngine;

namespace SocketTest
{
    public partial class SocketTest : ContentPage
    {
        private WebSocket websocket;
        public SocketTest()
        {
            InitializeComponent();

        }

        void Handle_Clicked(object sender, System.EventArgs e)
        {
            websocket = new WebSocket("ws://echo.websocket.org/");
            websocket.Opened += Websocket_Opened;
            websocket.Error += Websocket_Error;
            websocket.Closed += Websocket_Closed;
            websocket.MessageReceived += Websocket_MessageReceived;
            websocket.Open();
        }

        private void Websocket_Error(object sender, ErrorEventArgs e)
        {
            Console.WriteLine(e.Exception.Message);
        }

        private void Websocket_MessageReceived(object sender, EventArgs e)
        {
            Console.WriteLine(e.ToString());
        }

        private void Websocket_Closed(object sender, EventArgs e)
        {
            Console.WriteLine(e.ToString());
        }

        private void Websocket_Opened(object sender, EventArgs e)
        {
            websocket.Send("Hello World!");
        }
    }
}

I started with the standard multi-platform project (PCL) and added a button to initiate the connection.

Versions:
0.15.0 WebSocket4Net
0.8.0.13 SuperSocket

The PCL is configured with: .NET Standard Platform = netstandard1.4

I'm fairly new to .NET/Xamarin but have many years of software development behind me.


问:
while and foreach loops in PHP
I would like to save into a mySQL column the values taken from an external text file.

The text file is simply as follows:

```<code>line 1,
line 2,
line 3
</code>```

As you can see, a comma on each line, followed by a linebreak.
Now, I need to update the database table (which counts 3 rows), with the text values (line 1, line 2 and line 3) in the column text.

So far, I have this:

```<code><?php
$text = file_get_contents("docs/text");
$lines = explode(",\n", $text);
$sql = "SELECT * FROM table'";
$qsql = mysql_query($sql) or die ("Error Query [".$sql."]");
while ($array = mysql_fetch_assoc($qsql)){
  foreach($lines as $line){
  mysql_query("UPDATE `table` SET `text`='".$line."'") or die(mysql_error());
  }
}
?>
</code>```

The code above saves in all rows the same value (line 3).

答:
You have to specify which row you want to UPDATE (or INSERT if rows don't exist already). Here some quick and dirty  pseudo code:

```<code>for( $i=0; $i < count($lines); $i++ ){
  mysql_query("UPDATE `table` SET `text`='".$line[$i]."' where ID = ".$i) or die(mysql_error());
}
</code>```

Note: It's recommended using PDO or mysqli instead of mysql_*- functions because of security implications.

Title: while and foreach loops in PHP

Body:
I would like to save into a mySQL column the values taken from an external text file.

The text file is simply as follows:

line 1,
line 2,
line 3

As you can see, a comma on each line, followed by a linebreak.
Now, I need to update the database table (which counts 3 rows), with the text values (line 1, line 2 and line 3) in the column text.

So far, I have this:

<?php
$text = file_get_contents("docs/text");
$lines = explode(",\n", $text);
$sql = "SELECT * FROM table'";
$qsql = mysql_query($sql) or die ("Error Query [".$sql."]");
while ($array = mysql_fetch_assoc($qsql)){
  foreach($lines as $line){
  mysql_query("UPDATE `table` SET `text`='".$line."'") or die(mysql_error());
  }
}
?>

The code above saves in all rows the same value (line 3).

Body:
You have to specify which row you want to UPDATE (or INSERT if rows don't exist already). Here some quick and dirty  pseudo code:

for( $i=0; $i < count($lines); $i++ ){
  mysql_query("UPDATE `table` SET `text`='".$line[$i]."' where ID = ".$i) or die(mysql_error());
}

Note: It's recommended using PDO or mysqli instead of mysql_*- functions because of security implications.


问:
Merging 2 nearly identical functions in perl
I have a script that gets some data from a website. The data comes in JSON format and the site offers an option to "flatten" the JSON output into a single JSON object, or leave it as multiple objects.

The script has options that allow for converting the JSON data to YAML (whether flattened or not), or leaving it in JSON format.

In addition the script colorizes the values in both formats.

In order to accomplish the coloring, I currently have 2 functions, one for JSON colorization, and one for YAML colorization.

Colorization itself is achieved with Term::ANSIColor, by searching and replacing the text in either a Scalar or an Array, depending on which output format the data is in.

I would like to get this down to one function in order to reduce the code duplication, but I am at a loss for how to accomplish this.

To be clear, the main focus of this question, for clarity's sake, is how to make one of the colorization functions reusable so that it can work on both the YAML and the JSON output. Because the search patterns are very very similar, and the replacement patterns are identical, I feel like it should be really easy to accomplish this but I'm drawing a blank on how to do it.

```<code>use JSON;
use YAML::Tiny;

sub colorize_yaml
{
    my $OUTPUT                                                                               = shift;
    my $OPTIONS                                                                              = shift;

    if (ref $OUTPUT eq 'SCALAR')
    {
        foreach (${$OUTPUT})
        {

            # Hide this if debugging is disabled, else show it and color it
            if (!$OPTIONS->{debug})
            {
                s{(statusCode|success|dataExist|verumModelObjectName):\ [a-zA-Z0-9]+\n}
{}gxms;
            }
            else
            {
            s{(statusCode|success|dataExist|verumModelObjectName):}
{$OPTIONS->{color} ? BOLD YELLOW $1 . ':', BOLD GREEN : $1 . ':'}gxmse;
            }

            # Colorize 5 segment flat output
            s{([a-zA-Z0-9]+:)([a-zA-Z0-9]+:)([a-zA-Z0-9]+:)([a-zA-Z0-9]+:)([a-zA-Z0-9]+:\ )}
{$OPTIONS->{color} ? BOLD CYAN $1, BOLD YELLOW $2, BOLD MAGENTA $3, BOLD RED $4, RESET $5: $1 . $2 . $3 . $4 . $5}gxmse;

            # Colorize 4 segment flat output
            s{([a-zA-Z0-9]+:)([a-zA-Z0-9]+:)([a-zA-Z0-9]+:)([a-zA-Z0-9]+:\ )}
{$OPTIONS->{color} ? BOLD CYAN $1, BOLD YELLOW $2, BOLD MAGENTA $3, RESET $4 : $1 . $2 . $3 . $4}gxmse;

            # Colorize 3 segment flat output
            s{([a-zA-Z0-9]+:)([a-zA-Z0-9]+:)([a-zA-Z0-9]+:\ )}
{$OPTIONS->{color} ? BOLD CYAN $1, BOLD YELLOW $2, RESET $3 : $1 . $2 . $3}gxmse;

            # Colorize 2 segment flat output
            s{([a-zA-Z0-9]+:)([a-zA-Z0-9]+:\ )}
{$OPTIONS->{color} ? BOLD CYAN $1, RESET $2 : $1 . $2}gxmse;

            # Colorize values in all output
            s{(:\ )}
{$OPTIONS->{color} ? $1 . BOLD GREEN : $1}gxmse;

            # Reset colors before newlines so that the next line starts with a clean color pattern.
            s{\n}
{$OPTIONS->{color} ? RESET "\n" : "\n"}gxmse;
        }
    }
    else
    {
        pretty_print_error("WARNING: Unable to colorize YAML output\n", $OPTIONS->{color});
        return;
    }

    return;
}

sub colorize_json
{
    my $OUTPUT                                                                               = shift;
    my $OPTIONS                                                                              = shift;

    if (ref $OUTPUT eq 'ARRAY')
    {
        foreach (@{$OUTPUT})
        {
            if ($OPTIONS->{debug})
            {
                s{(statusCode|success|dataExist|verumModelObjectName):}
{$OPTIONS->{color} ? BOLD YELLOW $1 . ':', BOLD GREEN : $1 . ':'}gxmse;
            }
            else
            {
                s{(statusCode|success|dataExist|verumModelObjectName):\ [a-zA-Z0-9]+\n}
{}gxms;
            }

            # Colorize 5 segment flat output
            s{^([a-zA-Z0-9]+:)([a-zA-Z0-9]+:)([a-zA-Z0-9]+:)([a-zA-Z0-9]+:)([a-zA-Z0-9]+:\ .*$)}
{$OPTIONS->{color} ? BOLD CYAN $1, BOLD YELLOW $2, BOLD MAGENTA $3, BOLD RED, $4, RESET $5: $1 . $2 . $3 . $4 . $5}gxmse;

            # Colorize 4 segment flat output
            s{^([a-zA-Z0-9]+:)([a-zA-Z0-9]+:)([a-zA-Z0-9]+:)([a-zA-Z0-9]+:\ )}
{$OPTIONS->{color} ? BOLD CYAN $1, BOLD YELLOW $2, BOLD MAGENTA $3, RESET $4 : $1 . $2 . $3 . $4}gxmse;

            # Colorize 3 segment flat output
            s{^([a-zA-Z0-9]+:)([a-zA-Z0-9]+:)([a-zA-Z0-9]+:\ )}
{$OPTIONS->{color} ? BOLD CYAN $1, BOLD YELLOW $2, RESET $3 : $1 . $2 . $3}gxmse;

            # Colorize 2 segment flat output
            s{^([a-zA-Z0-9]+:)([a-zA-Z0-9]+:\ )}
{$OPTIONS->{color} ? BOLD CYAN $1, RESET $2 : $1 . $2}gxmse;

            # Colorize values in all output
            s{(:\ )}
{$OPTIONS->{color} ? $1 . BOLD GREEN : $1}gxmse;

            # Reset colors before newlines so that the next line starts with a clean color pattern.
            s{$}
{$OPTIONS->{color} ? RESET '' : ''}gxmse;
        }
    }
    else
    {
        pretty_print_error("WARNING: Unable to colorize JSON output.\n", $OPTIONS->{color});
        return;
    }

    return;
}
</code>```

JSON converted to YAML

```<code>---
message: Success
ObjectList:
  -
    assetName: xxxxxxxx
    backupAsset:
      -
        backupFlag: xxxxxxxx
        fullyCertified: xxxxxxxx
</code>```

Flattened JSON converted to YAML

```<code>---
message: Success
verumObjectList:
  -
    assetName: xxxxxxxx
    backupAsset:backupFlag: xxxxxxxx
    backupAsset:fullyCertified: xxxxxxxx
</code>```

JSON (the data in JSON format is stripped by the script to make it plain text)

```<code>assetName: xxxxxxxx
backupFlag: xxxxxxxx
fullyCertified: xxxxxxxx
message: Success
</code>```

Flattened JSON (the data in JSON format is stripped by the script to make it plain text)

```<code>assetName: xxxxxxxx
backupAsset:backupFlag: xxxxxxxx
backupAsset:fullyCertified: xxxxxxxx
message: Success
</code>```

The correct answer is awarded to @zdim though I did have to tweak the code slightly.

I'm posting my updated code below.

```<code>use JSON;
use YAML::Tiny;

sub colorize_output
{
    my $OUTPUT   = shift;
    my $OPTIONS  = shift;

    my $RE_START = $EMPTY;
    my $RE_END   = q{\ };

    if (ref $OUTPUT eq $EMPTY)
    {
        pretty_print_error("WARNING: Unable to colorize output.\n",
            $OPTIONS->{color});
        return;
    }
    elsif (ref $OUTPUT eq 'ARRAY')
    {
        $RE_START = q{^};
        $RE_END   = q{\ .*};
    }

    my $ANCHOR    = q{[a-zA-Z0-9]+:};
    my $PATTERN   = qq{($ANCHOR)};

    Readonly my $SEGMENT_LIMIT => 4;

    my $VERUM_RE = qr{(statusCode|success|dataExist|verumModelObjectName):}xms;

    my ($SEGMENT_2PART_RE, $SEGMENT_3PART_RE, $SEGMENT_4PART_RE, $SEGMENT_5PART_RE)
        = map {
            qr{$RE_START}xms . ($PATTERN x $ARG) . qr{($ANCHOR$RE_END)}xms
        } 1..$SEGMENT_LIMIT;

    foreach ((ref $OUTPUT eq 'SCALAR')?${$OUTPUT}:@{$OUTPUT})
    {

        # Hide this if debugging is disabled, else show it and color it
        if (!$OPTIONS->{debug})
        {
            s{$VERUM_RE\ [a-zA-Z0-9]+}{}gxms;
        }
        else
        {
            s{$VERUM_RE}
             {$OPTIONS->{color} ? BOLD YELLOW $1 . ':', BOLD GREEN : $1 . ':'}gxmse;
        }

        # Colorize sections in flat output
        if ($OPTIONS->{color})
        {
            s{$SEGMENT_5PART_RE}
             {BOLD CYAN $1, BOLD YELLOW $2, BOLD MAGENTA $3, BOLD RED $4, RESET $5}gxmse;
            s{$SEGMENT_4PART_RE}
             {BOLD CYAN $1, BOLD YELLOW $2, BOLD MAGENTA $3, RESET $4}gxmse;
            s{$SEGMENT_3PART_RE}
             {BOLD CYAN $1, BOLD YELLOW $2, RESET $3}gxmse;
            s{$SEGMENT_2PART_RE}
             {BOLD CYAN $1, RESET $2}gxmse;

            # Colorize values in all output
            s{(:\ )}{$1 . BOLD GREEN}gxmse;

            # Reset colors before newlines or next entry in the list so that
            # the next line starts with a clean color pattern.
            s{(\n|$)}{RESET $1}gxmse;
        }
    }

    return;
}
</code>```

答:
This answers the question of how to refactor these functions, without any broader context.

One difference is the input: it is either a scalarref or an arrayref.

The more involved two other differences are in the regex: arrayref patterns are anchored and their last alphanumeric pattern ends with \ .*$, while scalarref ones are not anchored and their last match ends with an escaped space.

Finally, if $OPTIONS->{color} is false then the whole pattern is replaced by itself, in all cases; so the variable doesn't change. Then the condition should be pulled out.

```<code>sub colorize_yaml_json {
    my ($OUTPUT, $OPTIONS) = @_;

    my $anchor = '';
    my $last   = qr{\ };
    my @iter_refs;

    if    (ref $OUTPUT eq 'SCALAR') { @iter_refs = $$OUTPUT }
    elsif (ref $OUTPUT eq 'ARRAY')  {
        @iter_refs = @$OUTPUT;
        $anchor = qr{^};
        $last   = qr{\ .*$};
    }
    else {
        pretty_print_error(...);
        return;
    }

    my $anc  = qr{[a-zA-Z0-9]+:};  # alphanumeric with colon
    my $patt = qr{($anc)};

    my ($seg2_re, $seg3_re, $seg4_re, $seg5_re) = map {
        qr/$anchor/ . ($patt x $_) . qr/($anc$last)/
    } 1..4;

    foreach (@iter_refs) {
        if ($OPTIONS->{debug}) {
            ...
        }
        if ($OPTIONS->{color}) {
            s{$seg5_re}{BOLD CYAN $1, ... }gxmse;
            ...
        }
    }
    return 1;
}
</code>```

The map assembles the whole pattern for the four cases, by stacking the alphanumeric (with :) pattern $patt the needed 2–5 times, using x N for 1..4 and then appending the last pattern.

The unpleasant complication is that each of base patterns $anc need be captured.

I could only test this on my mock-up data so please check carefully (as always!).

There is also the other issue of how to best handle the whole scenario, but that wasn't the question and so there isn't enough information to deal with it without much guessing.

Body:
I have a script that gets some data from a website. The data comes in JSON format and the site offers an option to "flatten" the JSON output into a single JSON object, or leave it as multiple objects.

The script has options that allow for converting the JSON data to YAML (whether flattened or not), or leaving it in JSON format.

In addition the script colorizes the values in both formats.

In order to accomplish the coloring, I currently have 2 functions, one for JSON colorization, and one for YAML colorization.

Colorization itself is achieved with Term::ANSIColor, by searching and replacing the text in either a Scalar or an Array, depending on which output format the data is in.

I would like to get this down to one function in order to reduce the code duplication, but I am at a loss for how to accomplish this.

To be clear, the main focus of this question, for clarity's sake, is how to make one of the colorization functions reusable so that it can work on both the YAML and the JSON output. Because the search patterns are very very similar, and the replacement patterns are identical, I feel like it should be really easy to accomplish this but I'm drawing a blank on how to do it.

use JSON;
use YAML::Tiny;

sub colorize_yaml
{
    my $OUTPUT                                                                               = shift;
    my $OPTIONS                                                                              = shift;

    if (ref $OUTPUT eq 'SCALAR')
    {
        foreach (${$OUTPUT})
        {

            # Hide this if debugging is disabled, else show it and color it
            if (!$OPTIONS->{debug})
            {
                s{(statusCode|success|dataExist|verumModelObjectName):\ [a-zA-Z0-9]+\n}
{}gxms;
            }
            else
            {
            s{(statusCode|success|dataExist|verumModelObjectName):}
{$OPTIONS->{color} ? BOLD YELLOW $1 . ':', BOLD GREEN : $1 . ':'}gxmse;
            }

            # Colorize 5 segment flat output
            s{([a-zA-Z0-9]+:)([a-zA-Z0-9]+:)([a-zA-Z0-9]+:)([a-zA-Z0-9]+:)([a-zA-Z0-9]+:\ )}
{$OPTIONS->{color} ? BOLD CYAN $1, BOLD YELLOW $2, BOLD MAGENTA $3, BOLD RED $4, RESET $5: $1 . $2 . $3 . $4 . $5}gxmse;

            # Colorize 4 segment flat output
            s{([a-zA-Z0-9]+:)([a-zA-Z0-9]+:)([a-zA-Z0-9]+:)([a-zA-Z0-9]+:\ )}
{$OPTIONS->{color} ? BOLD CYAN $1, BOLD YELLOW $2, BOLD MAGENTA $3, RESET $4 : $1 . $2 . $3 . $4}gxmse;

            # Colorize 3 segment flat output
            s{([a-zA-Z0-9]+:)([a-zA-Z0-9]+:)([a-zA-Z0-9]+:\ )}
{$OPTIONS->{color} ? BOLD CYAN $1, BOLD YELLOW $2, RESET $3 : $1 . $2 . $3}gxmse;

            # Colorize 2 segment flat output
            s{([a-zA-Z0-9]+:)([a-zA-Z0-9]+:\ )}
{$OPTIONS->{color} ? BOLD CYAN $1, RESET $2 : $1 . $2}gxmse;

            # Colorize values in all output
            s{(:\ )}
{$OPTIONS->{color} ? $1 . BOLD GREEN : $1}gxmse;

            # Reset colors before newlines so that the next line starts with a clean color pattern.
            s{\n}
{$OPTIONS->{color} ? RESET "\n" : "\n"}gxmse;
        }
    }
    else
    {
        pretty_print_error("WARNING: Unable to colorize YAML output\n", $OPTIONS->{color});
        return;
    }

    return;
}

sub colorize_json
{
    my $OUTPUT                                                                               = shift;
    my $OPTIONS                                                                              = shift;

    if (ref $OUTPUT eq 'ARRAY')
    {
        foreach (@{$OUTPUT})
        {
            if ($OPTIONS->{debug})
            {
                s{(statusCode|success|dataExist|verumModelObjectName):}
{$OPTIONS->{color} ? BOLD YELLOW $1 . ':', BOLD GREEN : $1 . ':'}gxmse;
            }
            else
            {
                s{(statusCode|success|dataExist|verumModelObjectName):\ [a-zA-Z0-9]+\n}
{}gxms;
            }

            # Colorize 5 segment flat output
            s{^([a-zA-Z0-9]+:)([a-zA-Z0-9]+:)([a-zA-Z0-9]+:)([a-zA-Z0-9]+:)([a-zA-Z0-9]+:\ .*$)}
{$OPTIONS->{color} ? BOLD CYAN $1, BOLD YELLOW $2, BOLD MAGENTA $3, BOLD RED, $4, RESET $5: $1 . $2 . $3 . $4 . $5}gxmse;

            # Colorize 4 segment flat output
            s{^([a-zA-Z0-9]+:)([a-zA-Z0-9]+:)([a-zA-Z0-9]+:)([a-zA-Z0-9]+:\ )}
{$OPTIONS->{color} ? BOLD CYAN $1, BOLD YELLOW $2, BOLD MAGENTA $3, RESET $4 : $1 . $2 . $3 . $4}gxmse;

            # Colorize 3 segment flat output
            s{^([a-zA-Z0-9]+:)([a-zA-Z0-9]+:)([a-zA-Z0-9]+:\ )}
{$OPTIONS->{color} ? BOLD CYAN $1, BOLD YELLOW $2, RESET $3 : $1 . $2 . $3}gxmse;

            # Colorize 2 segment flat output
            s{^([a-zA-Z0-9]+:)([a-zA-Z0-9]+:\ )}
{$OPTIONS->{color} ? BOLD CYAN $1, RESET $2 : $1 . $2}gxmse;

            # Colorize values in all output
            s{(:\ )}
{$OPTIONS->{color} ? $1 . BOLD GREEN : $1}gxmse;

            # Reset colors before newlines so that the next line starts with a clean color pattern.
            s{$}
{$OPTIONS->{color} ? RESET '' : ''}gxmse;
        }
    }
    else
    {
        pretty_print_error("WARNING: Unable to colorize JSON output.\n", $OPTIONS->{color});
        return;
    }

    return;
}

JSON converted to YAML

---
message: Success
ObjectList:
  -
    assetName: xxxxxxxx
    backupAsset:
      -
        backupFlag: xxxxxxxx
        fullyCertified: xxxxxxxx

Flattened JSON converted to YAML

---
message: Success
verumObjectList:
  -
    assetName: xxxxxxxx
    backupAsset:backupFlag: xxxxxxxx
    backupAsset:fullyCertified: xxxxxxxx

JSON (the data in JSON format is stripped by the script to make it plain text)

assetName: xxxxxxxx
backupFlag: xxxxxxxx
fullyCertified: xxxxxxxx
message: Success

Flattened JSON (the data in JSON format is stripped by the script to make it plain text)

assetName: xxxxxxxx
backupAsset:backupFlag: xxxxxxxx
backupAsset:fullyCertified: xxxxxxxx
message: Success

The correct answer is awarded to @zdim though I did have to tweak the code slightly.

I'm posting my updated code below.

use JSON;
use YAML::Tiny;

sub colorize_output
{
    my $OUTPUT   = shift;
    my $OPTIONS  = shift;

    my $RE_START = $EMPTY;
    my $RE_END   = q{\ };

    if (ref $OUTPUT eq $EMPTY)
    {
        pretty_print_error("WARNING: Unable to colorize output.\n",
            $OPTIONS->{color});
        return;
    }
    elsif (ref $OUTPUT eq 'ARRAY')
    {
        $RE_START = q{^};
        $RE_END   = q{\ .*};
    }

    my $ANCHOR    = q{[a-zA-Z0-9]+:};
    my $PATTERN   = qq{($ANCHOR)};

    Readonly my $SEGMENT_LIMIT => 4;

    my $VERUM_RE = qr{(statusCode|success|dataExist|verumModelObjectName):}xms;

    my ($SEGMENT_2PART_RE, $SEGMENT_3PART_RE, $SEGMENT_4PART_RE, $SEGMENT_5PART_RE)
        = map {
            qr{$RE_START}xms . ($PATTERN x $ARG) . qr{($ANCHOR$RE_END)}xms
        } 1..$SEGMENT_LIMIT;

    foreach ((ref $OUTPUT eq 'SCALAR')?${$OUTPUT}:@{$OUTPUT})
    {

        # Hide this if debugging is disabled, else show it and color it
        if (!$OPTIONS->{debug})
        {
            s{$VERUM_RE\ [a-zA-Z0-9]+}{}gxms;
        }
        else
        {
            s{$VERUM_RE}
             {$OPTIONS->{color} ? BOLD YELLOW $1 . ':', BOLD GREEN : $1 . ':'}gxmse;
        }

        # Colorize sections in flat output
        if ($OPTIONS->{color})
        {
            s{$SEGMENT_5PART_RE}
             {BOLD CYAN $1, BOLD YELLOW $2, BOLD MAGENTA $3, BOLD RED $4, RESET $5}gxmse;
            s{$SEGMENT_4PART_RE}
             {BOLD CYAN $1, BOLD YELLOW $2, BOLD MAGENTA $3, RESET $4}gxmse;
            s{$SEGMENT_3PART_RE}
             {BOLD CYAN $1, BOLD YELLOW $2, RESET $3}gxmse;
            s{$SEGMENT_2PART_RE}
             {BOLD CYAN $1, RESET $2}gxmse;

            # Colorize values in all output
            s{(:\ )}{$1 . BOLD GREEN}gxmse;

            # Reset colors before newlines or next entry in the list so that
            # the next line starts with a clean color pattern.
            s{(\n|$)}{RESET $1}gxmse;
        }
    }

    return;
}

Body:
This answers the question of how to refactor these functions, without any broader context.

One difference is the input: it is either a scalarref or an arrayref.

The more involved two other differences are in the regex: arrayref patterns are anchored and their last alphanumeric pattern ends with \ .*$, while scalarref ones are not anchored and their last match ends with an escaped space.

Finally, if $OPTIONS->{color} is false then the whole pattern is replaced by itself, in all cases; so the variable doesn't change. Then the condition should be pulled out.

sub colorize_yaml_json {
    my ($OUTPUT, $OPTIONS) = @_;

    my $anchor = '';
    my $last   = qr{\ };
    my @iter_refs;

    if    (ref $OUTPUT eq 'SCALAR') { @iter_refs = $$OUTPUT }
    elsif (ref $OUTPUT eq 'ARRAY')  {
        @iter_refs = @$OUTPUT;
        $anchor = qr{^};
        $last   = qr{\ .*$};
    }
    else {
        pretty_print_error(...);
        return;
    }

    my $anc  = qr{[a-zA-Z0-9]+:};  # alphanumeric with colon
    my $patt = qr{($anc)};

    my ($seg2_re, $seg3_re, $seg4_re, $seg5_re) = map {
        qr/$anchor/ . ($patt x $_) . qr/($anc$last)/
    } 1..4;

    foreach (@iter_refs) {
        if ($OPTIONS->{debug}) {
            ...
        }
        if ($OPTIONS->{color}) {
            s{$seg5_re}{BOLD CYAN $1, ... }gxmse;
            ...
        }
    }
    return 1;
}

The map assembles the whole pattern for the four cases, by stacking the alphanumeric (with :) pattern $patt the needed 2–5 times, using x N for 1..4 and then appending the last pattern.

The unpleasant complication is that each of base patterns $anc need be captured.

I could only test this on my mock-up data so please check carefully (as always!).

There is also the other issue of how to best handle the whole scenario, but that wasn't the question and so there isn't enough information to deal with it without much guessing.

ContentLicense: CC BY-SA 4.0


问:
Rails how to check size of current session (cookies)
I was happily throwing things into the session instead of direct saving into the database (like in multistep forms) and thought those 4kb is more than enough. Since I use Devise I thought it uses some session storage but felt safe until I tried to p session and OH!!! My terminal couldn't event print all data from it. That data is hard to understand - there are some items that I pass to it, but also some local routes and other weird things.

So no I wonder how to check the size of it at some stages? I found similar question but following that I get @encryptor as undefined / nil..

Also tried:

```<code>@encryptor = ActiveSupport::MessageEncryptor.new(secret, cipher: encrypted_cookie_cipher, serializer: SERIALIZER)

data = session.to_hash.delete_if { |k,v| v.nil? }
data = @encryptor.encrypt_and_sign(serialize(name, data))
p data.bytesize
</code>```

But then secret is undefined:

undefined local variable or method `secret'

答:
I also tried to find a way to display the cookie-size with rails, without success.
But another way to check the size of your current session cookie is the developer tool in the browser.

There you can see all cookies with some information and its sizes.
It's maybe not the best way, but better than nothing.

Body:
I was happily throwing things into the session instead of direct saving into the database (like in multistep forms) and thought those 4kb is more than enough. Since I use Devise I thought it uses some session storage but felt safe until I tried to p session and OH!!! My terminal couldn't event print all data from it. That data is hard to understand - there are some items that I pass to it, but also some local routes and other weird things.

So no I wonder how to check the size of it at some stages? I found similar question but following that I get @encryptor as undefined / nil..

Also tried:

@encryptor = ActiveSupport::MessageEncryptor.new(secret, cipher: encrypted_cookie_cipher, serializer: SERIALIZER)

data = session.to_hash.delete_if { |k,v| v.nil? }
data = @encryptor.encrypt_and_sign(serialize(name, data))
p data.bytesize

But then secret is undefined:

undefined local variable or method `secret'


问:
calculate the percentage of substring occurrence in string, python
I've written a function that works for strings of length 1, but I have no idea how to make it work for longer ones.

```<code>def function(text, n):
    dict={}
    char_count=0

    for c in text:
        keys=dict.keys()
        if c.isalpha()==True:
            char_count+=1
            if c in keys:
                dict[c] +=1
            else:
                dict[c]=1
    for key in dict:
        dict[key]=dict[key]/char_count

    return dict
</code>```

The use of import is not very welcome :/

答:
Three steps:

Split the input into individual words; Python's split function will return a nice list for you.

Make a corresponding list of word lengths; use len on each element.

Use the count function to count the occurrences of each length; put those results in a dictionary.

For instance, if you start with:

```<code>sentence = "Now I will a rhyme construct "       + \
           "By chosen words the young instruct " + \
           "Cunningly ensured endeavour "        + \
           "Con it and remember ever "           + \
           "Widths of circle here you see "      + \
           "Stretchd out in strange obscurity "
</code>```

Split this into individual words.  List the length of each word; it would look like this:

```<code>[3, 1, 4, 1, 5, 9, 2, 6,
 5, 3, 5, 8, 9, 7, 9, 3,
 2, 3, 8, 4, 6, 2, 6, 4,
 3, 3, 8, 3, 2, 7, 9]
</code>```

Then you count how many of each number are in this list.
Does that get you moving?

Body:
I've written a function that works for strings of length 1, but I have no idea how to make it work for longer ones.

def function(text, n):
    dict={}
    char_count=0

    for c in text:
        keys=dict.keys()
        if c.isalpha()==True:
            char_count+=1
            if c in keys:
                dict[c] +=1
            else:
                dict[c]=1
    for key in dict:
        dict[key]=dict[key]/char_count

    return dict

The use of import is not very welcome :/

Body:
Three steps:

Split the input into individual words; Python's split function will return a nice list for you.

Make a corresponding list of word lengths; use len on each element.

Use the count function to count the occurrences of each length; put those results in a dictionary.

For instance, if you start with:

sentence = "Now I will a rhyme construct "       + \
           "By chosen words the young instruct " + \
           "Cunningly ensured endeavour "        + \
           "Con it and remember ever "           + \
           "Widths of circle here you see "      + \
           "Stretchd out in strange obscurity "

Split this into individual words.  List the length of each word; it would look like this:

[3, 1, 4, 1, 5, 9, 2, 6,
 5, 3, 5, 8, 9, 7, 9, 3,
 2, 3, 8, 4, 6, 2, 6, 4,
 3, 3, 8, 3, 2, 7, 9]

Then you count how many of each number are in this list.
Does that get you moving?


问:
Python: how to sort a list of strings by substring relevance?
I have some list of strings, for example:

```<code>["foo bar SOME baz TEXT bob",
"SOME foo bar baz bob TEXT",
"SOME foo TEXT",
"foo bar SOME TEXT baz",
"SOME TEXT"]
</code>```

I want it to be sorted by exactness to SOME TEXT substring (upper case doesn't matter). Something like this order:

```<code>["SOME TEXT",
"foo bar SOME TEXT baz",
"SOME foo TEXT",
"foo bar SOME baz TEXT bob",
"SOME foo bar baz bob TEXT"]
</code>```

The idea is - the best score gets the string with the best match to substring words position. And for bigger amount of "sloppy" words between substring's words - the lower ordering it gets.

I have found some libraries like fuzzyset, or Levenshtein distance but I'm not sure this is what I need. I know the exact substring by what I want to sort and those libs search the similar words, as I understood.

Actually I need to do this sort after some database query (Postgresql) in my Django project. I have already tried full-text search with its ORM, but didn't get this relevant sort order (it doesn't count the distance between substring words). Next I have tried Haystack+Whoosh, but also at this moment didn't find info how to do this sort there. So idea now is to get query set and next sort it out of the database (yep, I know that might be a bad decision, but for now I want it just work). But if anybody tells me how to do this within any of technologies, I have mentioned here - that will be also super cool. Thank you!

p.s. The length of substring supposed to be 2-10 words in max 20 word string.

答:
Here is my take on it.

```<code>l = ["foo bar SOME baz TEXT bob",
"SOME foo bar baz bob TEXT",
"SOME foo TEXT",
"foo bar SOME TEXT baz",
"SOME TEXT"]

l.sort(key=lambda x: (x.find("SOME")-x.find("TEXT"))*0.9-0.1*x.find("SOME"), reverse=True)

print(l)
</code>```

OUTPUT:

```<code>['SOME TEXT', 'foo bar SOME TEXT baz', 'SOME foo TEXT', 'foo bar SOME baz TEXT bob', 'SOME foo bar baz bob TEXT']
</code>```

So what we have done is sorted the list based on major weight to the distance between "SOME" and "TEXT" and some minor weight to the occurrence of "SOME" in the string.

Another longer way would be to first group the list based on the their distance between SOME and TEXT. And then sort the each group based on the position of "SOME".

Body:
I have some list of strings, for example:

["foo bar SOME baz TEXT bob",
"SOME foo bar baz bob TEXT",
"SOME foo TEXT",
"foo bar SOME TEXT baz",
"SOME TEXT"]

I want it to be sorted by exactness to SOME TEXT substring (upper case doesn't matter). Something like this order:

["SOME TEXT",
"foo bar SOME TEXT baz",
"SOME foo TEXT",
"foo bar SOME baz TEXT bob",
"SOME foo bar baz bob TEXT"]

The idea is - the best score gets the string with the best match to substring words position. And for bigger amount of "sloppy" words between substring's words - the lower ordering it gets.

I have found some libraries like fuzzyset, or Levenshtein distance but I'm not sure this is what I need. I know the exact substring by what I want to sort and those libs search the similar words, as I understood.

Actually I need to do this sort after some database query (Postgresql) in my Django project. I have already tried full-text search with its ORM, but didn't get this relevant sort order (it doesn't count the distance between substring words). Next I have tried Haystack+Whoosh, but also at this moment didn't find info how to do this sort there. So idea now is to get query set and next sort it out of the database (yep, I know that might be a bad decision, but for now I want it just work). But if anybody tells me how to do this within any of technologies, I have mentioned here - that will be also super cool. Thank you!

p.s. The length of substring supposed to be 2-10 words in max 20 word string.

Body:
Here is my take on it.

l = ["foo bar SOME baz TEXT bob",
"SOME foo bar baz bob TEXT",
"SOME foo TEXT",
"foo bar SOME TEXT baz",
"SOME TEXT"]

l.sort(key=lambda x: (x.find("SOME")-x.find("TEXT"))*0.9-0.1*x.find("SOME"), reverse=True)

print(l)

OUTPUT:

['SOME TEXT', 'foo bar SOME TEXT baz', 'SOME foo TEXT', 'foo bar SOME baz TEXT bob', 'SOME foo bar baz bob TEXT']

So what we have done is sorted the list based on major weight to the distance between "SOME" and "TEXT" and some minor weight to the occurrence of "SOME" in the string.

Another longer way would be to first group the list based on the their distance between SOME and TEXT. And then sort the each group based on the position of "SOME".


问:
Why does this "Slow network detected..." log appear in Chrome?
I noticed this info log began to appear in Google Chrome Dev (Version 55.0.2883.18 dev) and I can't imagine why.

Slow network is detected. Fallback font will be used while loading: http://font-path.extension`

It appears on all websites that use font-face, even on local pages and Chrome extensions.

答:
I just managed to make the filter regex work: /^((?!Fallback\sfont).)*$/.

Add it to the filter field just above the console and it'll hide all messages containing Fallback font.

You can make it more specific if you want.


问:
Angular5 ng-bootstrap - how to use just the ngb-panel
How can you render just a Panel outside of an accordion ?

This does not render anything...

```<code> <ngb-panel title="Login">
  <ng-template ngbPanelContent>
    Hello
  </ng-template>
 </ngb-panel>
</code>```

But this does (with collapsable accordion behaviour - which I dont want...)

```<code><ngb-accordion #acc="ngbAccordion" activeIds="ngb-panel-0">
 <ngb-panel title="Login">
  <ng-template ngbPanelContent>
    Hello
  </ng-template>
 </ngb-panel>
</ngb-accordion>
</code>```

答:
According to the Bootstrap 4 documentation, the Panel component has been replaced by the Card component, which is not included in ng-bootstrap because it is obtained simply by styling with CSS selectors.

For those who are interested in having a collapsible container outside of the Accordion, they can use ng-bootstrap's Collapse component.

Body:
How can you render just a Panel outside of an accordion ?

This does not render anything...

 <ngb-panel title="Login">
  <ng-template ngbPanelContent>
    Hello
  </ng-template>
 </ngb-panel>

But this does (with collapsable accordion behaviour - which I dont want...)

<ngb-accordion #acc="ngbAccordion" activeIds="ngb-panel-0">
 <ngb-panel title="Login">
  <ng-template ngbPanelContent>
    Hello
  </ng-template>
 </ngb-panel>
</ngb-accordion>


问:
Make matplotlib contour plot give a filled colorbar
Take this example matplotlib plot

```<code>import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 4, 1000)
y = np.linspace(-1, 1, 1000)
xx, yy = np.meshgrid(x, y)
z = np.sin(xx + yy**2)
plt.figure()
CS = plt.contourf(x, y, z)
CS = plt.contour(x, y, z)
plt.clabel(CS, fontsize=8, colors='black')
cbar = plt.colorbar(CS)
plt.savefig('test.png')
</code>```

This produces

The colorbar is very hard to read, because it only puts lines for the colors, and the rest is white.

How do I make the colorbar have filled colors, not just lines, like in the examples?

答:
Turns out it matters whether you use the CS from contour or from contourf.  You want the one from contourf to get a filled colorbar.

```<code>import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 4, 1000)
y = np.linspace(-1, 1, 1000)
xx, yy = np.meshgrid(x, y)
z = np.sin(xx + yy**2)
plt.figure()
CS = plt.contour(x, y, z)
CS = plt.contourf(x, y, z)
plt.clabel(CS, fontsize=8, colors='black')
cbar = plt.colorbar(CS)
plt.savefig('test.png')
</code>```

Note how I swapped the contour and contourf lines.

I don't know how to make a filled colorbar using just contour.

Body:
Take this example matplotlib plot

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 4, 1000)
y = np.linspace(-1, 1, 1000)
xx, yy = np.meshgrid(x, y)
z = np.sin(xx + yy**2)
plt.figure()
CS = plt.contourf(x, y, z)
CS = plt.contour(x, y, z)
plt.clabel(CS, fontsize=8, colors='black')
cbar = plt.colorbar(CS)
plt.savefig('test.png')

This produces

The colorbar is very hard to read, because it only puts lines for the colors, and the rest is white.

How do I make the colorbar have filled colors, not just lines, like in the examples?

Body:
Turns out it matters whether you use the CS from contour or from contourf.  You want the one from contourf to get a filled colorbar.

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 4, 1000)
y = np.linspace(-1, 1, 1000)
xx, yy = np.meshgrid(x, y)
z = np.sin(xx + yy**2)
plt.figure()
CS = plt.contour(x, y, z)
CS = plt.contourf(x, y, z)
plt.clabel(CS, fontsize=8, colors='black')
cbar = plt.colorbar(CS)
plt.savefig('test.png')

Note how I swapped the contour and contourf lines.

I don't know how to make a filled colorbar using just contour.


问:
How to define 'value' property setter parameter
With the following C# code:

```<code>public interface IFoo
{
    int Bar
    {
        get;
        set;
    }
}
</code>```

the property setter signature compiles to:

```<code>.method public hidebysig specialname newslot abstract virtual
    instance void set_X (
        int32 'value'
    ) cil managed
{
}
</code>```

when inspected with ILSpy or ildasm.

If I attempt to generate an identical method signature using the System.Reflection.Emit API, the resulting input parameter name is either empty:

```<code>.method public hidebysig specialname newslot abstract virtual
    instance void set_X (
        int32 ''
    ) cil managed
{
}
</code>```

(signature generated by ilspy)

... or a seemingly generated reference name (A_1 in this case):

```<code>.method public hidebysig newslot specialname abstract virtual
    instance void  set_X(
        int32 A_1
    ) cil managed
{
}
</code>```

(signature generated by ildasm)

How can I give the input parameter the name "value" like in the C# compiled example?

Here's the code I've used to generate the setter with:

```<code>PropertyBuilder property = typeDef.DefineProperty("X", PropertyAttributes.HasDefault, CallingConventions.HasThis, typeof(int), null);

MethodAttributes ma = MethodAttributes.Public
                    | MethodAttributes.HideBySig
                    | MethodAttributes.NewSlot
                    | MethodAttributes.SpecialName
                    | MethodAttributes.Abstract
                    | MethodAttributes.Virtual;
MethodBuilder setMethod = typeDef.DefineMethod("set_X", ma, CallingConventions.HasThis, null, new[] { typeof(int) });

property.SetSetMethod(setMethod);
</code>```

Even when I explicitly attempt to define the parameter name, the result is still the same:

```<code>MethodBuilder setMethod = typeDef.DefineMethod("set_X", ma, CallingConventions.HasThis, null, new[] { typeof(int) });

ParameterBuilder pb = setMethod.DefineParameter(0, ParameterAttributes.None, "value");

property.SetSetMethod(setMethod);
</code>```

答:
I think you have to use index 1 for the first parameter. From the msdn entry for MethodBuilder.DefineParameter Method:

Remarks

[...]

Parameter numbering begins with 1, so position is 1 for the first parameter. If position is zero, this method affects the return value.

Body:
With the following C# code:

public interface IFoo
{
    int Bar
    {
        get;
        set;
    }
}

the property setter signature compiles to:

.method public hidebysig specialname newslot abstract virtual
    instance void set_X (
        int32 'value'
    ) cil managed
{
}

when inspected with ILSpy or ildasm.

If I attempt to generate an identical method signature using the System.Reflection.Emit API, the resulting input parameter name is either empty:

.method public hidebysig specialname newslot abstract virtual
    instance void set_X (
        int32 ''
    ) cil managed
{
}

(signature generated by ilspy)

... or a seemingly generated reference name (A_1 in this case):

.method public hidebysig newslot specialname abstract virtual
    instance void  set_X(
        int32 A_1
    ) cil managed
{
}

(signature generated by ildasm)

How can I give the input parameter the name "value" like in the C# compiled example?

Here's the code I've used to generate the setter with:

PropertyBuilder property = typeDef.DefineProperty("X", PropertyAttributes.HasDefault, CallingConventions.HasThis, typeof(int), null);

MethodAttributes ma = MethodAttributes.Public
                    | MethodAttributes.HideBySig
                    | MethodAttributes.NewSlot
                    | MethodAttributes.SpecialName
                    | MethodAttributes.Abstract
                    | MethodAttributes.Virtual;
MethodBuilder setMethod = typeDef.DefineMethod("set_X", ma, CallingConventions.HasThis, null, new[] { typeof(int) });

property.SetSetMethod(setMethod);

Even when I explicitly attempt to define the parameter name, the result is still the same:

MethodBuilder setMethod = typeDef.DefineMethod("set_X", ma, CallingConventions.HasThis, null, new[] { typeof(int) });

ParameterBuilder pb = setMethod.DefineParameter(0, ParameterAttributes.None, "value");

property.SetSetMethod(setMethod);


问:
Bose Soundtouch 30II connect with Google Assistant
I'm using Google Home and Google Chromecast Audio to play Google Play Music or Spotify on my Soundtouch 30 II. It's working fine but I got ONE BIG PROBLEM. I always have to turn my Soundtouch with the remote or the Soundtouch App on to hear the music. It's not that smart if you have to do this step by hand.

Now I'm searching for a solution to integrate my Soundtouch 30 with the Google Assistant. Are there any possibilites like IFTTT, an App, SDK, API or something to do it?

答: Yes! You can use the Spotify Connect Web APIs to control Spotify from your Google Assistant.</p>


问:
Galaxy S8: screen height returning wrong value
This is how we're getting screen height:

```<code>getResources().getDisplayMetrics().heightPixels;
</code>```

The problem we're having is that with the Galaxy S8's hidden nav bar, the value returned is the height minus the nav bar size (even though the nav bar is hidden by the user).  How do we get the full usable height?

example:  screen height is 2220 pixels but the value returned is 2076

The answer needs to be able to work on Galaxy S8 with or without the nav bar hidden as well as other devices

thank you so much in advance

答:
Try to use this :

```<code>Point displaySize = new Point();
activity.getWindowManager().getDefaultDisplay().getRealSize(displaySize);
</code>```

Point is a class from android.graphics package.

From docs : https://developer.android.com/reference/android/view/Display.html#getRealSize(android.graphics.Point)

Gets the real size of the display without subtracting any window decor
  or applying any compatibility scale factors.

The size is adjusted based on the current rotation of the display.

The real size may be smaller than the physical size of the screen when
  the window manager is emulating a smaller display (using adb shell wm
  size).

Edit :

I checked this code on LG G4 and it works fine :

```<code>//get the full height of device
      Point displaySize = new Point();
      getWindowManager().getDefaultDisplay().getRealSize(displaySize);

      Resources resources = getResources();
            int navBarId = resources.getIdentifier("navigation_bar_height", "dimen", "android");

          int fullHeight = displaySize.y;
//get nav bar size
          int navbarSize = resources.getDimensionPixelSize(navBarId);
          int availableSize = fullHeight;
//check is navbar is visible
          boolean navBarVisible = (getWindow().getDecorView().getSystemUiVisibility() &
                        View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) == 0;
          if(navBarVisible){
                    availableSize -= navbarSize;
                }
</code>```

Also you can use this code :

```<code>view.setOnSystemUiVisibilityChangeListener(new View.OnSystemUiVisibilityChangeListener() {
            @Override
            public void onSystemUiVisibilityChange(int i) {
                Log.d("Nav bar visible : ", String.valueOf((i & View.SYSTEM_UI_FLAG_HIDE_NAVIGATION)==0));
            }
        });
</code>```

to check when nav bar is hiding.

Body:
This is how we're getting screen height:

getResources().getDisplayMetrics().heightPixels;

The problem we're having is that with the Galaxy S8's hidden nav bar, the value returned is the height minus the nav bar size (even though the nav bar is hidden by the user).  How do we get the full usable height?

example:  screen height is 2220 pixels but the value returned is 2076

The answer needs to be able to work on Galaxy S8 with or without the nav bar hidden as well as other devices

thank you so much in advance

Body:
Try to use this :

Point displaySize = new Point();
activity.getWindowManager().getDefaultDisplay().getRealSize(displaySize);

Point is a class from android.graphics package.

From docs : https://developer.android.com/reference/android/view/Display.html#getRealSize(android.graphics.Point)

Gets the real size of the display without subtracting any window decor
  or applying any compatibility scale factors.

The size is adjusted based on the current rotation of the display.

The real size may be smaller than the physical size of the screen when
  the window manager is emulating a smaller display (using adb shell wm
  size).

Edit :

I checked this code on LG G4 and it works fine :

//get the full height of device
      Point displaySize = new Point();
      getWindowManager().getDefaultDisplay().getRealSize(displaySize);

      Resources resources = getResources();
            int navBarId = resources.getIdentifier("navigation_bar_height", "dimen", "android");

          int fullHeight = displaySize.y;
//get nav bar size
          int navbarSize = resources.getDimensionPixelSize(navBarId);
          int availableSize = fullHeight;
//check is navbar is visible
          boolean navBarVisible = (getWindow().getDecorView().getSystemUiVisibility() &
                        View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) == 0;
          if(navBarVisible){
                    availableSize -= navbarSize;
                }

Also you can use this code :

view.setOnSystemUiVisibilityChangeListener(new View.OnSystemUiVisibilityChangeListener() {
            @Override
            public void onSystemUiVisibilityChange(int i) {
                Log.d("Nav bar visible : ", String.valueOf((i & View.SYSTEM_UI_FLAG_HIDE_NAVIGATION)==0));
            }
        });

to check when nav bar is hiding.


问:
Nested For Loop Parallel with global dictionary
I am trying to make this block of code run in parallel.

Currently it is running at about 6 minutes per model which is way too slow.

```<code>d_mtry={}
# ------------------------------------------------------------------------
pass; count = 0; itr = COUNT
while count < itr
    kf = KFold(n_splits = 10)
    # --------------------------------------------------------------------
    for j in range (2, 25):
        avg_acc = 0
        for train_index, test_index in kf.split(X_train):
            X_train_K, X_test_K = X_train[train_index], X_train[test_index]
            y_train_K, y_test_K = y_train[train_index], y_train[test_index]
            rotf = RRForestClassifier( n_estimators = 30,
                                       criterion    =  'entropy',
                                       max_features =  j,
                                       n_jobs       = -1,
                                       random_state =  1
                                       )
            rotf.fit(X_train_K, y_train_K)

            y_predict_K = rotf.predict(X_test_K)
            y_prob = rotf.predict_proba(X_test_K)

            acc_score = accuracy_score(y_test_K, y_predict_K)
            avg_acc += acc_score

        d_mtry[str(j)] = avg_acc/10

    # --------------------------------------------------------------------
    best_mtry = max(d_mtry.iteritems(), key=operator.itemgetter(1))[0]

    f.write("\n" + "Iteration: " + str(count+1) + " Best M_Try: " + str(best_mtry)+ "\n")
    f.write(str(d_mtry))

    rotf = RRForestClassifier( n_estimators = 30,
                               criterion    =  'entropy',
                               max_features =  int( best_mtry ),
                               n_jobs       = -1,
                               random_state =  1
                               )
    # there is more code after this
    # I don't think it is relevant,
    # it has to do with calculations on the model rotf
    # --------------------------------------------------------------------
    count += 1
# ------------------------------------------------------------------------
</code>```

The main issue I've been having is that the dictionary doesn't update properly in parallel for the attempts I've made. It also didn't seem to run much faster when doing a method using multiprocessing.Pool() instance, I found in another post.

The goal here is to find the best value for j ( for max_features class-instance attribute ), based on the average accuracy over the folds and use that when I create my model and run it on the test set.

Originally, I tried to use GridSearchCV(), but that ran into an issue on fitting and never finished running, even on AWS-hosted setup, there having 36 cores.

Any help is appreciated.

答:
I love python for the ease of prototyping.

I also know, when it comes the time to change architecture-design priorities for ultimate performance.

Fact #1: n_jobs == -1 actually occupies all the CPU-cores

This said, there are no free CPU-resources ( and you may belong to those kids of the Fortune, if not also headbanging into the [SPACE]-dimension of the Hardware-constraints ( yes, speaking about in-RAM computing, later translated into [TIME]-dimension, once your model stopped to fit in-RAM and performance will jump many orders of magnitude worse ) during intensive ML-model tuning ).

In cases, where there are no spare resources available, any process-scheduling will resort to either a pure-[SERIAL] system-scheduling ( going one after another ) or at maximum to a "just"-[CONCURRENT]  system-scheduling, when actual blocks-of-execution are interleaved, by an O/S system-scheduler, onto a restricted ( in size ) subset of CPU-resources, because no other "free" CPU-core is not available to do any better.

In this very case none of the tools available to Python code from the multiprocessing module will ever improve the code-execution performance, but the very contrary ( might have already benchmarked this or have just felt this in your own shoes ).

None of the both above named system-scheduling policies are the true-[PARALLEL] system-scheduling examples.

Fact #2: "just"-[CONCURRENT] helps I/O-bound, not CPU-bound cases

Except for the initial DataSET loading into RAM, there is no other I/O-related performance blocking. So, any "increased" ( also any multiprocessing module tools' injected ) concurrency will never improve your  localhost processing throughput ( no I/O-latency masking appears to be better, than lost performance on increased CPU job-schedule interleaving and context-switching costs ).

SOLUTION: If in a need for an indeed increased prototyping throughput

Having prototyped an AI/ML-prototyping factory, running almost a 24/7/365 BAU, this may help you either.

Think of a different architecture, than making a dict globally accessible.

The process-flow can be orchestrated:

A host_00 being a "parameter-server", telling others what [ aMlMODEL, aParamSET, DataSET ]

A host_01 being a "worker-pool-member", running on full steam, having n_jobs = -1

A host_02 being a "worker-pool-member", running on full steam, having n_jobs = -1

A host_03 being a "worker-pool-member", running on full steam, having n_jobs = -1

..

A host_NN being a "worker-pool-member", running on full steam, having n_jobs = -1

Having this prototyping Factory concept:

- the throughput is at max,

- the throughput is possible to get dynamically extended ( overnight et al ),

- the throughput is almost at linear scale proportional to N

- the Factory architecture has lowest possible orchestration overheads, compared to any other naive attempts to "parallelise-a-code"

Body:
I am trying to make this block of code run in parallel.

Currently it is running at about 6 minutes per model which is way too slow.

d_mtry={}
# ------------------------------------------------------------------------
pass; count = 0; itr = COUNT
while count < itr
    kf = KFold(n_splits = 10)
    # --------------------------------------------------------------------
    for j in range (2, 25):
        avg_acc = 0
        for train_index, test_index in kf.split(X_train):
            X_train_K, X_test_K = X_train[train_index], X_train[test_index]
            y_train_K, y_test_K = y_train[train_index], y_train[test_index]
            rotf = RRForestClassifier( n_estimators = 30,
                                       criterion    =  'entropy',
                                       max_features =  j,
                                       n_jobs       = -1,
                                       random_state =  1
                                       )
            rotf.fit(X_train_K, y_train_K)

            y_predict_K = rotf.predict(X_test_K)
            y_prob = rotf.predict_proba(X_test_K)

            acc_score = accuracy_score(y_test_K, y_predict_K)
            avg_acc += acc_score

        d_mtry[str(j)] = avg_acc/10

    # --------------------------------------------------------------------
    best_mtry = max(d_mtry.iteritems(), key=operator.itemgetter(1))[0]

    f.write("\n" + "Iteration: " + str(count+1) + " Best M_Try: " + str(best_mtry)+ "\n")
    f.write(str(d_mtry))

    rotf = RRForestClassifier( n_estimators = 30,
                               criterion    =  'entropy',
                               max_features =  int( best_mtry ),
                               n_jobs       = -1,
                               random_state =  1
                               )
    # there is more code after this
    # I don't think it is relevant,
    # it has to do with calculations on the model rotf
    # --------------------------------------------------------------------
    count += 1
# ------------------------------------------------------------------------

The main issue I've been having is that the dictionary doesn't update properly in parallel for the attempts I've made. It also didn't seem to run much faster when doing a method using multiprocessing.Pool() instance, I found in another post.

The goal here is to find the best value for j ( for max_features class-instance attribute ), based on the average accuracy over the folds and use that when I create my model and run it on the test set.

Originally, I tried to use GridSearchCV(), but that ran into an issue on fitting and never finished running, even on AWS-hosted setup, there having 36 cores.

Any help is appreciated.


问:
Using robots.txt to block /?param=X
I have created a website using wordpress, and the first day it was full of dummy content until I uploaded mine. Google indexed pages such as:

www.url.com/?cat=1

Now these pages doesn't exists, and to make a removal request google ask me to block them on robots.txt

Should I use:

```<code>User-Agent: *
Disallow: /?cat=
</code>```

or

```<code>User-Agent: *
Disallow: /?cat=*
</code>```

My robots.txt file would look something like this:

```<code>User-agent: *
Disallow: /cgi-bin
Disallow: /wp-admin
Disallow: /wp-includes
Disallow: /wp-content
Disallow: /wp-login.php
Disallow: /wp-register.php
Disallow: /author
Disallow: /?cat=
Sitemap: http://url.com/sitemap.xml.gz
</code>```

Does this look fine or can it cause any problem with search engines? Should I use Allow: / along with all the Disallow:?

答:
In general, you should not use the robots.txt directives to handle removed content. If a search engine can't crawl it, it can't tell whether or not it's been removed and may continue to index (or even start indexing) those URLs. The right solution is to make sure that your site returns a 404 (or 410) HTTP result code for those URLs, then they'll drop out automatically over time.

If you want to use Google's urgent URL removal tools, you would have to submit these URLs individually anyway, so you would not gain anything by using a robots.txt disallow.

Title: Using robots.txt to block /?param=X

Body:
I have created a website using wordpress, and the first day it was full of dummy content until I uploaded mine. Google indexed pages such as:

www.url.com/?cat=1

Now these pages doesn't exists, and to make a removal request google ask me to block them on robots.txt

Should I use:

User-Agent: *
Disallow: /?cat=

or

User-Agent: *
Disallow: /?cat=*

My robots.txt file would look something like this:

User-agent: *
Disallow: /cgi-bin
Disallow: /wp-admin
Disallow: /wp-includes
Disallow: /wp-content
Disallow: /wp-login.php
Disallow: /wp-register.php
Disallow: /author
Disallow: /?cat=
Sitemap: http://url.com/sitemap.xml.gz

Does this look fine or can it cause any problem with search engines? Should I use Allow: / along with all the Disallow:?


问:
Count multiple items in the same column pulling data from 2 tables - mysql
I have 2 tables and I need to count the number of times any role shows up in each movie

Example of Tables:

Movie Table

```<code>TITLE           MOVIEID     OTHER STUFF....
-------------   -------
MOVIE TITLE 1   ID# 1
MOVIE TITLE 2   ID# 2
MOVIE TITLE 3   ID# 3
ETC...
</code>```

Role Table

```<code>ROLEID      MOVIEID     OTHER STUFF....
-------     -------
ROLE #1     ID# 1
ROLE #2     ID# 1
ROLE #3     ID# 2
ROLE #4     ID# 2
ROLE #5     ID# 3
ROLE #6     ID# 4
ROLE #7     ID# 5
ROLE #8     ID# 3
ETC....
</code>```

I would like to get an output that looks like this:

```<code>TITLE           NUMROLES
-------------   --------------------------------------
MOVIE TITLE 1   COUNT (ROLE.MOVIEID) FOR MOVIE TITLE 1
MOVIE TITLE 2   COUNT (ROLE.MOVIEID) FOR MOVIE TITLE 2
MOVIE TITLE 3   COUNT (ROLE.MOVIEID) FOR MOVIE TITLE 3
MOVIE TITLE 4   COUNT (ROLE.MOVIEID) FOR MOVIE TITLE 4
MOVIE TITLE 5   COUNT (ROLE.MOVIEID) FOR MOVIE TITLE 5
ETC...
</code>```

I have tried a several different things but I seem to always get a total count of all the roles instead of them being counted individually.

My "best" output Example:

```<code>mysql> SELECT TITLE, COUNT(ROLE.MOVIEID) AS NUMROLES
    -> FROM MOVIE, ROLE
    -> GROUP BY TITLE;
+-----------------------------+----------+
| TITLE                       | NUMROLES |
+-----------------------------+----------+
| Amadeus                     |      138 |
| Apollo 13                   |      138 |
| Batman                      |      138 |
| Batman & Robin              |      138 |
| Batman Begins               |      138 |
| Batman Forever              |      138 |
| Batman Returns              |      138 |
| Casablanca                  |      138 |
| Dirty Harry                 |      138 |
| Few Good Men, A             |      138 |
| Field of Dreams             |      138 |
| Fly, The                    |      138 |
| Forrest Gump                |      138 |
| Godfather, The              |      138 |
| Gone with the Wind          |      138 |
| Jerry Maguire               |      138 |
| Mrs. Doubtfire              |      138 |
| Naked City, The             |      138 |
| Sixth Sense, The            |      138 |
| Sudden Impact               |      138 |
| Terminator 2:  Judgment Day |      138 |
| Terminator, The             |      138 |
| Tootsie                     |      138 |
| Wizard of Oz, The           |      138 |
+-----------------------------+----------+
24 rows in set (0.02 sec)
</code>```

I am thinking I don't have the proper knowledge of what I should be using in this case, can anyone point me in the right direction without just giving me the answer??

Bonus:

I also need to filter out any titles that don't have at least 6 for count of (ROLE.MOVIEID) - I am thinking I need to use HAVING for that.

答:
You're really close, just need to tweak your JOIN (it is missing a predicate), and add your HAVING for your bonus:

```<code>SELECT TITLE, COUNT(*) AS NUMROLES
FROM MOVIE M
JOIN ROLE R ON M.MOVIEID = R.MOVIEID --This is the join predicate (condition)
GROUP BY TITLE
HAVING COUNT(*) > 5;
</code>```

This is explicit JOIN syntax.  It's best practice to use this as the implicit variant (ie. commas in your FROM clause) is long since depreciated and harder to use anyway.

Note that you can use COUNT(r.movieID) if you want, but COUNT(*) will count the rows in the same fashion.

Body:
I have 2 tables and I need to count the number of times any role shows up in each movie

Example of Tables:

Movie Table

TITLE           MOVIEID     OTHER STUFF....
-------------   -------
MOVIE TITLE 1   ID# 1
MOVIE TITLE 2   ID# 2
MOVIE TITLE 3   ID# 3
ETC...

Role Table

ROLEID      MOVIEID     OTHER STUFF....
-------     -------
ROLE #1     ID# 1
ROLE #2     ID# 1
ROLE #3     ID# 2
ROLE #4     ID# 2
ROLE #5     ID# 3
ROLE #6     ID# 4
ROLE #7     ID# 5
ROLE #8     ID# 3
ETC....

I would like to get an output that looks like this:

TITLE           NUMROLES
-------------   --------------------------------------
MOVIE TITLE 1   COUNT (ROLE.MOVIEID) FOR MOVIE TITLE 1
MOVIE TITLE 2   COUNT (ROLE.MOVIEID) FOR MOVIE TITLE 2
MOVIE TITLE 3   COUNT (ROLE.MOVIEID) FOR MOVIE TITLE 3
MOVIE TITLE 4   COUNT (ROLE.MOVIEID) FOR MOVIE TITLE 4
MOVIE TITLE 5   COUNT (ROLE.MOVIEID) FOR MOVIE TITLE 5
ETC...

I have tried a several different things but I seem to always get a total count of all the roles instead of them being counted individually.

My "best" output Example:

mysql> SELECT TITLE, COUNT(ROLE.MOVIEID) AS NUMROLES
    -> FROM MOVIE, ROLE
    -> GROUP BY TITLE;
+-----------------------------+----------+
| TITLE                       | NUMROLES |
+-----------------------------+----------+
| Amadeus                     |      138 |
| Apollo 13                   |      138 |
| Batman                      |      138 |
| Batman & Robin              |      138 |
| Batman Begins               |      138 |
| Batman Forever              |      138 |
| Batman Returns              |      138 |
| Casablanca                  |      138 |
| Dirty Harry                 |      138 |
| Few Good Men, A             |      138 |
| Field of Dreams             |      138 |
| Fly, The                    |      138 |
| Forrest Gump                |      138 |
| Godfather, The              |      138 |
| Gone with the Wind          |      138 |
| Jerry Maguire               |      138 |
| Mrs. Doubtfire              |      138 |
| Naked City, The             |      138 |
| Sixth Sense, The            |      138 |
| Sudden Impact               |      138 |
| Terminator 2:  Judgment Day |      138 |
| Terminator, The             |      138 |
| Tootsie                     |      138 |
| Wizard of Oz, The           |      138 |
+-----------------------------+----------+
24 rows in set (0.02 sec)

I am thinking I don't have the proper knowledge of what I should be using in this case, can anyone point me in the right direction without just giving me the answer??

Bonus:

I also need to filter out any titles that don't have at least 6 for count of (ROLE.MOVIEID) - I am thinking I need to use HAVING for that.

Body:
You're really close, just need to tweak your JOIN (it is missing a predicate), and add your HAVING for your bonus:

SELECT TITLE, COUNT(*) AS NUMROLES
FROM MOVIE M
JOIN ROLE R ON M.MOVIEID = R.MOVIEID --This is the join predicate (condition)
GROUP BY TITLE
HAVING COUNT(*) > 5;

This is explicit JOIN syntax.  It's best practice to use this as the implicit variant (ie. commas in your FROM clause) is long since depreciated and harder to use anyway.

Note that you can use COUNT(r.movieID) if you want, but COUNT(*) will count the rows in the same fashion.