问:
Encoding for special characters not working in email subject for sendgrid templates
I have been using the sendgrid-ruby gem for sending emails. The subject of the email doesn't decode special characters properly.
Eg. Sending this subject for the email How's it going translates to this in the actual email How's it going

I have tried encoding the string for subject to different formats such as ASCII, ISO_8859_1 but none of this works.

```<code>@body_json['personalizations'][0]['dynamic_template_data'] = {
    'email_title': @email_title,
    'content': @description,
    'subject': "How's it going"
}

SendGrid::API.new(api_key: ENV['SENDGRID_API_KEY']).client.mail._('send').post(request_body: @body_json)
</code>```

The subject for email should show special characters correctly such as ' & :

答:
You should be using triple brackets in your subject section i.e. {{{subject}}} for subjects with special characters.
If you use the double brackets approach your string is going to be HTML encoded.

Check this link from SendGrid repository https://github.com/sendgrid/sendgrid-nodejs/issues/741#issuecomment-422026634

Body:
I have been using the sendgrid-ruby gem for sending emails. The subject of the email doesn't decode special characters properly.
Eg. Sending this subject for the email How's it going translates to this in the actual email How's it going

I have tried encoding the string for subject to different formats such as ASCII, ISO_8859_1 but none of this works.

@body_json['personalizations'][0]['dynamic_template_data'] = {
    'email_title': @email_title,
    'content': @description,
    'subject': "How's it going"
}

SendGrid::API.new(api_key: ENV['SENDGRID_API_KEY']).client.mail._('send').post(request_body: @body_json)

The subject for email should show special characters correctly such as ' & :


来源: stackexchange

答:
Yes, it could be done pretty easy by using array_reduce:

```<code>$lastCheckedItem = ['id' => 0];

$finalArray = array_reduce($array, static function(array $carry, array $item) use (&$lastCheckedItem) {
    if ($lastCheckedItem['id'] === $item['id'] && !empty($carry)) {
        $lastKey = array_key_last($carry);
        $carry[$lastKey][] = $item;
    }
    else {
        $carry[] = [$item];
    }

    $lastCheckedItem = $item;

    return $carry;
}, []);
</code>```

ContentLicense: CC BY-SA 4.0

Title: PHP How to organize array into groups but keep the order?

Body:
I want to make arrays into groups by id,

but still keep the orders, that means it might have duplicate groups,
like:

Group1 [id: 1]
Group2 [id: 2]
Group3 [id: 1]
....
...
..
.

Array:

array (
  0 =>
  array (
    'id' => 1,
    'message' => 'AAA',
    'sent_on' => 1582097767
  ),

  1 =>
  array (
    'id' => 2,
    'message' => 'AAAQAW',
    'sent_on' => 1582097770
  ),

  2 =>
  array (
    'id' => 2,
    'message' => 'dqwdq',
    'sent_on' => 1582097772
  ),

  3 =>
  array (
    'id' => 1,
    'message' => 'dqwdq',
    'sent_on' => 1582097773
  ),

  4 =>
  array (
    'id' => 1,
    'message' => 'wq',
    'sent_on' => 1582097773
  ),

  5 =>
  array (
    'id' => 2,
    'message' => 'd',
    'sent_on' => 1582097774
  ),

  6 =>
  array (
    'id' => 1,
    'message' => 'dew',
    'sent_on' => 1582112219
  )
)

Hoped result:

array (
    0 =>
    array (
        0 =>
        array (
          'id' => 1,
          'message' => 'AAA',
          'sent_on' => 1582097767

        ),
    ),

    1 =>
    array (
        0 =>
        array (
          'id' => 2,
          'message' => 'AAAQAW',
          'sent_on' => 1582097770

        ),
        1 =>
        array (
          'id' => 2,
          'message' => 'dqwdq',
          'sent_on' => 1582097772

        )
    ),

    2 =>
    array (
        0 =>
        array (
          'id' => 1,
          'message' => 'dqwdq',
          'sent_on' => 1582097773

        ),
        1 =>
        array (
          'id' => 1,
          'message' => 'wq',
          'sent_on' => 1582097773

        )
    ),

    3 =>
    array (
        0 =>
        array (
          'id' => 2,
          'message' => 'd',
          'sent_on' => 1582097774

        )
    ),

    4 =>
    array (
        0 =>
        array (
          'id' => 1,
          'message' => 'dew',
          'sent_on' => 1582112219

        )
    )
)

Body:
Yes, it could be done pretty easy by using array_reduce:

$lastCheckedItem = ['id' => 0];

$finalArray = array_reduce($array, static function(array $carry, array $item) use (&$lastCheckedItem) {
    if ($lastCheckedItem['id'] === $item['id'] && !empty($carry)) {
        $lastKey = array_key_last($carry);
        $carry[$lastKey][] = $item;
    }
    else {
        $carry[] = [$item];
    }

    $lastCheckedItem = $item;

    return $carry;
}, []);


问:
Is there a way to initialize a vector by index in c++11?
It is easy to fill the elements of a vector by index after it has been initialized:

```<code>std::vector<int> myVector {0, 0, 0};
int indexOfInterest = 1;
myVector[indexOfInterest] = 999;
// myVector now contains {0, 999, 0}
</code>```

However, is there a way to initialize a vector directly with the index? indexOfInterest may change in my code in the future, and I would like to avoid hard-coding the vector with

```<code>std::vector<int> myVector {0, 999, 0};
</code>```

Is there some syntax like

```<code>int indexOfInterest = 1;
std::vector<int> myVector[3] {indexOfInterest : 999}; // this is made-up syntax!
// desired: myVector contains {0, 999, 0} and is 3 elements large
</code>```

that can be used in C++11 to achieve this effect?

答:
No there is no such thing in C++11. If it is only a single index that needs a different initializer than all the others, I wouldn't use anything other than

```<code>std::vector<int> myVector(3);
myVector[1] = 999;
</code>```

I think it wouldn't be too difficult to write some fake iterator class that lets you write something along the line of

```<code>auto pit = pair_of_fake_iterators(3,1,999);
std::vector<int> myVector( pit.first, pit.second);
</code>```

Which calls the constructor that takes two iterators and "copies" elements. Though, I wouldn't go there. It saves you nothing on typing and readers of your code will applaude for the level of obfuscation.

Body:
It is easy to fill the elements of a vector by index after it has been initialized:

std::vector<int> myVector {0, 0, 0};
int indexOfInterest = 1;
myVector[indexOfInterest] = 999;
// myVector now contains {0, 999, 0}

However, is there a way to initialize a vector directly with the index? indexOfInterest may change in my code in the future, and I would like to avoid hard-coding the vector with

std::vector<int> myVector {0, 999, 0};

Is there some syntax like

int indexOfInterest = 1;
std::vector<int> myVector[3] {indexOfInterest : 999}; // this is made-up syntax!
// desired: myVector contains {0, 999, 0} and is 3 elements large

that can be used in C++11 to achieve this effect?

Body:
No there is no such thing in C++11. If it is only a single index that needs a different initializer than all the others, I wouldn't use anything other than

std::vector<int> myVector(3);
myVector[1] = 999;

I think it wouldn't be too difficult to write some fake iterator class that lets you write something along the line of

auto pit = pair_of_fake_iterators(3,1,999);
std::vector<int> myVector( pit.first, pit.second);

Which calls the constructor that takes two iterators and "copies" elements. Though, I wouldn't go there. It saves you nothing on typing and readers of your code will applaude for the level of obfuscation.


问:
How can I write a short-hand expression that validates an integer, and returns an integer or a null?
I have a need to end up with a variable $id that contains either an integer, or a null value.

Currently I have this:

```<code>$id = $_POST['id'];
$id = filter_var($id, FILTER_VALIDATE_INT); //false or integer
if (!$id)
    $id = null;
</code>```

Is there a more concise way to write this?  I am looking to consolidate 3 statements into one line if possible.

答:
There is actually a FILTER_NULL_ON_FAILURE:

```<code>$id = filter_var($_POST['id'], FILTER_VALIDATE_INT, FILTER_NULL_ON_FAILURE);
</code>```

Body:
I have a need to end up with a variable $id that contains either an integer, or a null value.

Currently I have this:

$id = $_POST['id'];
$id = filter_var($id, FILTER_VALIDATE_INT); //false or integer
if (!$id)
    $id = null;

Is there a more concise way to write this?  I am looking to consolidate 3 statements into one line if possible.

Body:
There is actually a FILTER_NULL_ON_FAILURE:

$id = filter_var($_POST['id'], FILTER_VALIDATE_INT, FILTER_NULL_ON_FAILURE);


问:
How to setup a swagger API login with authorize button in asp.net web api?
I have an asp.net web api project integrated with swagger ui. I am new in swagger.I installed all required OWIN packages for authentication.It works fine with postman but when i give authorize attribute in any controller it's not working in swagger.

How can i make a login panel for authentication in swagger and how to add the bearer+access_token automatically with every request in swagger after successful login?
Thanx in advance

答:
The ApiKeyAuth class is not called.

I have added [Authorize] to the controller.

Added this code to StartUp.

services.AddAuthentication("ApiKey").AddScheme("ApiKey", null);


问:
Android - Camera preview is sideways
I am using a Preview to display what the camera see's on the screen.

I can get everything working fine, surface created, surface set and the surface is displayed.

However it always displays the picture at an incorrect 90 degree angle in portrait mode.

Such as in the picture:

I am aware that using the following code will set the picture straight:

```<code>setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
</code>```

However I have the Preview within an Activity that has other elements in it and it does not make sense for my Activity to be displayed in landscape mode. (Its disabled by default)

So I was wondering is there anyway to just change the orientation of the Preview? And leave the rest of my Activity correctly displayed in Portrait mode?

Or anyway to rotate the preview so that it is displayed correctly?

答:
I think the SENSOR_ORIENTATION value will explain what value to be used for the rotation instead of hardcoding to 90 degrees</p>

```<code>CameraManager manager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
        if (manager == null) {
            Log.i(TAG, "camera manager is null");
            return;
        }
        for (String id: manager.getCameraIdList()) {
            CameraCharacteristics characteristics = manager.getCameraCharacteristics(id);
            Integer orientation = characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION);
            Log.i(TAG, "camera sensor orientation is " + orientation);
        }
</code>```

ContentLicense: CC BY-SA 2.5

Title: Android - Camera preview is sideways

Body:
I am using a Preview to display what the camera see's on the screen.

I can get everything working fine, surface created, surface set and the surface is displayed.

However it always displays the picture at an incorrect 90 degree angle in portrait mode.

Such as in the picture:

I am aware that using the following code will set the picture straight:

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

However I have the Preview within an Activity that has other elements in it and it does not make sense for my Activity to be displayed in landscape mode. (Its disabled by default)

So I was wondering is there anyway to just change the orientation of the Preview? And leave the rest of my Activity correctly displayed in Portrait mode?

Or anyway to rotate the preview so that it is displayed correctly?

Body:
I think the SENSOR_ORIENTATION value will explain what value to be used for the rotation instead of hardcoding to 90 degrees

CameraManager manager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
        if (manager == null) {
            Log.i(TAG, "camera manager is null");
            return;
        }
        for (String id: manager.getCameraIdList()) {
            CameraCharacteristics characteristics = manager.getCameraCharacteristics(id);
            Integer orientation = characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION);
            Log.i(TAG, "camera sensor orientation is " + orientation);
        }


问:
Trying to add formula to a column in Excel output using C# Windows application. But getting #NAME? error
I am using Windows app to export data into the Excel. Assigned the below formula in lastcolumn

```<code>=IFNA(IF(VLOOKUP(CONCAT(S2,T2),'data table'!$C:$C,1,0)=CONCAT(S2,T2),"Yes"),"No")
</code>```

. The excel is already having 'data table' sheet. I got the output with formula in the Excel column but its showing #NAME? error. when i double click on the cell then exit from the cell, value of the formula is coming. Not sure why i am not getting the value without double clicking on the cell manually.

Could someone please help me to get the value of the formula when i export from application.
Thanks in Advance!!

答:
Try the following:

```<code>=IFNA(IF(VLOOKUP(CONCATENATE(C2;D2);'data table'!A:A;1;0)=CONCATENATE(C2;D2);"Yes");"No")
</code>```

I have been using Excel 2013 and worked correctly.

Body:
I am using Windows app to export data into the Excel. Assigned the below formula in lastcolumn

=IFNA(IF(VLOOKUP(CONCAT(S2,T2),'data table'!$C:$C,1,0)=CONCAT(S2,T2),"Yes"),"No")

. The excel is already having 'data table' sheet. I got the output with formula in the Excel column but its showing #NAME? error. when i double click on the cell then exit from the cell, value of the formula is coming. Not sure why i am not getting the value without double clicking on the cell manually.

Could someone please help me to get the value of the formula when i export from application.
Thanks in Advance!!

Body:
Try the following:

=IFNA(IF(VLOOKUP(CONCATENATE(C2;D2);'data table'!A:A;1;0)=CONCATENATE(C2;D2);"Yes");"No")

I have been using Excel 2013 and worked correctly.


问:
global() function for list in python
Python: 3.8.1

I am unable to append data in class variables using global() function.

```<code>class test():
    __cv__ = []

        def testglobalmethod(self, data):
            globals()['__cv__']=[data]
            print(__cv__)

    rrr = test()
    rrr.testglobalmethod("1")
    rrr.testglobalmethod("2")
</code>```

Expected Results:-
['1','2']

Actual Results:-
['1']
['2']

The append function produces below error:-

```<code>def testglobalmethod(self, data):
    globals()['__cv__'].append(data)
    print(__cv__)
</code>```

Error: KeyError: '__cv__'

答:
You have a class attribute, not a global variable.</p>

```<code>class Test():
    __cv__ = []

    def testglobalmethod(self, data):
        Test.__cv__.append(data)
        print(Test.__cv__)

rrr = Test()
rrr.testglobalmethod("1")
rrr.testglobalmethod("2")
</code>```

Title: global() function for list in python

Body:
Python: 3.8.1

I am unable to append data in class variables using global() function.

class test():
    __cv__ = []

        def testglobalmethod(self, data):
            globals()['__cv__']=[data]
            print(__cv__)

    rrr = test()
    rrr.testglobalmethod("1")
    rrr.testglobalmethod("2")

Expected Results:-
['1','2']

Actual Results:-
['1']
['2']

The append function produces below error:-

def testglobalmethod(self, data):
    globals()['__cv__'].append(data)
    print(__cv__)

Error: KeyError: '__cv__'

Body:
You have a class attribute, not a global variable.

class Test():
    __cv__ = []

    def testglobalmethod(self, data):
        Test.__cv__.append(data)
        print(Test.__cv__)

rrr = Test()
rrr.testglobalmethod("1")
rrr.testglobalmethod("2")


问:
How to get pinch effect to an image in iphone
Thanks in advance.

I want to get the pinch effect to an image means i want to change the shape of an image when i perform pinching on an image. I don't know is it possible or not, if it is possible can any one help me to do it using objective c in iphone.

答:
You can find help here : Limit maximum scale for scaling image with pinch gesture in IOS

Basically, using a gesture, you get a factor that you use to scale your image.

ContentLicense: CC BY-SA 3.0


问:
I can't see or edit MySQL stored procedures in NetBeans
I can connect to MySQL database (5.7.23) from NetBeans (8.2) using JDBC (MySQL-AB JDBC Driver, mysql-connector-java-5.1.23). I can see tables and views, execute SQL statements and everything else with database but I cannot see or edit stored procedures (or functions) in NetBeans. I have them inside database, I can see and manage them in MySQL Workbench but cannot see them in NetBeans (folder "Procedures" in NetBeans is empty). What could be the problem?

Left in NetBeans, right in Workbench:

I have 64-bit Windows 10 Pro (1709), 64-bit NetBeans 8.2 (PHP) and 64-bit MySQL 5.7.14 (from WAMP).

答: The proof that it is the solution.

Body: The proof that it is the solution.


问:
zend framework url generation problems
I'm having some difficulties generating simple urls with zf version 1.11.6. I'm using the url helper for this.

Example:

$this->url(array('controller' => 'index', 'action' => 'index'))

$this->url(array('controller' => 'index', 'action' => 'view', 'id' => 1))

Result:

domain.com/index/index/id/1

domain.com/index/view/id/1

As you can see, the problem is that even I have not specified any id param to the first rule, the generated url contains it. This happens also with action. If I let the first rule without the action parameter, it will be generated having the view value (instead of using the default value of index). Let's say that I can live with the action thing, but this is absurd when it comes to the other parameters.

This happens even though I use the first rule inside my controller and the second one inside a view file.

Any thoughts on this ? Thank you.

答:
Now see its quite easy.

```
$this->view->url(array(),'admin/index');
```

Result in
domain.com
and now chekc this

```
$this->url(array('selected_id'=>$this->rd[$i]->id),'admin/index/detail')
```

Results in
domain.com/detail/14

You should provide empty array where you dont want to have id value

Title: zend framework url generation problems

Body:
Now see its quite easy.

$this->view->url(array(),'admin/index');

Result in
domain.com
and now chekc this

$this->url(array('selected_id'=>$this->rd[$i]->id),'admin/index/detail')

Results in
domain.com/detail/14

You should provide empty array where you dont want to have id value


问:
Jenkins does not wait for docker exec command to complete
Here's the situation:

I have a docker container (jenkins). I've mounted the sockets to my container so that I can perform docker commands inside my jenkins container.

Manually, everything works in the container. However, when Jenkins executes the job, it doesn't "wait" for the docker exec command to run to completion.

Below, is an extract from the Jenkinsfile. The short-lived printenv command runs correctly, and prints the environment variables. The next command (python) just gets run and then Jenkins moves on immediately, not waiting for completion. The Jenkins agent (slave) is running on an Ubuntu image. Running all these commands outside Jenkins work as expected.

```<code>echo "Running the app docker container in detached tty mode to keep it up"
docker run --detach --tty --name "${CONTAINER_NAME}" "${IMAGE_NAME}"

echo "Listing environment variables"
docker exec --interactive "${CONTAINER_NAME}" bash -c "printenv"

echo "Running test coverage"
docker exec --interactive "${CONTAINER_NAME}" bash -c "python -m coverage run --source . --branch -m pytest -vs"
</code>```

It seems maybe related to this question.

Please can anyone explain how to get Jenkins to wait for the docker exec command to complete before proceeding to the next step.

Have considered alternatives, like the Docker Pipeline Plugin, but would much prefer to use something close to what I have above where possible.

Ok, another approach, I've tried using Docker Pipeline plugin here.

答:
You can use docker.sock as volume mount to orchestrate containers on your host machine like this in your docker-compose.yml

```<code>volumes:
  - /var/run/docker.sock:/var/run/docker.sock
</code>```

Depending on your setup you might need to run

```<code>chmod 666 /var/run/docker.sock
</code>```

to get going in the first place.

This works on macOS as well as Linux.

Body:
Here's the situation:

I have a docker container (jenkins). I've mounted the sockets to my container so that I can perform docker commands inside my jenkins container.

Manually, everything works in the container. However, when Jenkins executes the job, it doesn't "wait" for the docker exec command to run to completion.

Below, is an extract from the Jenkinsfile. The short-lived printenv command runs correctly, and prints the environment variables. The next command (python) just gets run and then Jenkins moves on immediately, not waiting for completion. The Jenkins agent (slave) is running on an Ubuntu image. Running all these commands outside Jenkins work as expected.

echo "Running the app docker container in detached tty mode to keep it up"
docker run --detach --tty --name "${CONTAINER_NAME}" "${IMAGE_NAME}"

echo "Listing environment variables"
docker exec --interactive "${CONTAINER_NAME}" bash -c "printenv"

echo "Running test coverage"
docker exec --interactive "${CONTAINER_NAME}" bash -c "python -m coverage run --source . --branch -m pytest -vs"

It seems maybe related to this question.

Please can anyone explain how to get Jenkins to wait for the docker exec command to complete before proceeding to the next step.

Have considered alternatives, like the Docker Pipeline Plugin, but would much prefer to use something close to what I have above where possible.

Ok, another approach, I've tried using Docker Pipeline plugin here.

Body:
You can use docker.sock as volume mount to orchestrate containers on your host machine like this in your docker-compose.yml

volumes:
  - /var/run/docker.sock:/var/run/docker.sock

Depending on your setup you might need to run

chmod 666 /var/run/docker.sock

to get going in the first place.

This works on macOS as well as Linux.


问:
I'm trying to receive a webhook from an Autodesk Forge workflow.transition event but they aren't firing
I've been experimenting with the Fusion Lifecycle webhooks in Forge and have been successful using the item created/updated events but the workflow transition webhooks aren't firing.

The webhooks are created in Forge according to the Docs, as you can see below, but none of the transitions performed in the workspace will trigger the call.

They were created using a three-legged token associated with a Fusion Lifecycle user that has the proper workflow permissions on the workspace.

The following JSON excerpt is the workflow. transition webhook as returned from developer.api.autodesk.com/webhooks/v1/hooks endpoint on Forge showing it was indeed created.

    {
      "hookId": "909fd040-4e34-11ea-a842-651c9013b5e8",
      "tenant": "TENANTNAMEREMOVED4SO",
      "callbackUrl": "callbackurl removed for SO",
      "createdBy": "46FGNL6DBN6D",
      "event": "workflow.transition",
      "createdDate": "2020-02-13T07:43:45.988+0000",
      "system": "adsk.flc.production",
      "creatorType": "O2User",
      "status": "active",
      "scope": {
        "workflow.transition": "urn:adsk.plm:tenant.workspace.workflow.transition:TENANTNAMEREMOVED4SO.119.1.765"
      },
      "hookAttribute": {
        "creator": "D3 Forge Playground",
        "notification": {
          "class": "alert-danger",
          "system": "flc"
        }
      },
      "urn": "urn:adsk.webhooks:events.hook:909fd040-4e34-11ea-a842-651c9013b5e8",
      "__self__": "/systems/adsk.flc.production/events/workflow.transition/hooks/909fd040-4e34-11ea-a842-651c9013b5e8"
    }

I've pushed the workflow through the transition events numerous times and no webhook is being fired and no failed requests on our webhook receiving server either. if I mimic the payload for the workflow. transition event and post it to our endpoint, it is received as expected.

I have yet to see a live example of the workflow. transition webhook being fired and can't find any sample code from Autodesk using them. Not sure the service is even working as expected at this point even though the item.created and item.updated webhook events seem to work fine.

Has anyone successfully received a workflow. transition webhook from Autodesk Forge? If yes, could you provide some guidance on how?

答:
Seems to be working fine on my end in a Production tenant. This is the payload I used to create the webhook:

```<code>{
    "callbackUrl": "https://webhook.site/SOME_ID",
    "scope": {
        "workflow.transition": "urn:adsk.plm:tenant.workspace.workflow.transition:TENANT.107.1.421"
    }
}
</code>```

Does it look like the payload you used when creating the hook?

Body:
Seems to be working fine on my end in a Production tenant. This is the payload I used to create the webhook:

{
    "callbackUrl": "https://webhook.site/SOME_ID",
    "scope": {
        "workflow.transition": "urn:adsk.plm:tenant.workspace.workflow.transition:TENANT.107.1.421"
    }
}

Does it look like the payload you used when creating the hook?


问:
Terraform 0.12 Creating ingress rules with template
I wonder if something like this could be used. I have functional code working, but as pods in kubernetes will grow up fast, I want to convert into templates. This is an example for the creation of each nginx ingress rule for each wordpress site pod.

Now, each pod has its wordpress ingress entry with:

```<code>resource "kubernetes_ingress" "ingress_nginx_siteA" {
  metadata {
    name        = "ingress-nginx-siteA"
    namespace   = "default"
    annotations = { "kubernetes.io/ingress.class" = "nginx", "nginx.ingress.kubernetes.io/configuration-snippet" = "modsecurity_rules '\n SecRuleEngine On\n SecRequestBodyAccess On\n SecAuditEngine RelevantOnly\n SecAuditLogParts ABCIJDEFHZ\n SecAuditLog /var/log/modsec_audit.log\n SecRuleRemoveById 932140\n';\n", "nginx.ingress.kubernetes.io/ssl-passthrough" = "true" }
  }
  spec {
    tls {
      hosts       = ["siteA.test.com"]
      secret_name = "wildcard-test-com"
    }
    rule {
      host = "siteA.test.com"
      http {
        path {
          path = "/"
          backend {
            service_name = "siteA"
            service_port = "80"
          }
        }
      }
    }
  }
}
</code>```

Now I want to split into variables.tf that contain the whole sites variables, a template file rules.tpl and the main.tf that orchestrate this stuff.

variables.tf:

```<code>variable "wordpress_site" {
  type = map(object({
    name        = string
    url         = string
    certificate = string
  }))
    default = {
    siteA = {
      name        = siteA
      url         = siteA.test.com
      certificate = wildcard-test-com
    }
    siteB = {
      name        = siteB
      url         = siteB.test.com
      certificate = wildcard-test-com
    }
  }
}

</code>```

rules.tpl:

```<code>%{ for name in wordpress_site.name ~}
resource "kubernetes_ingress" "ingress_nginx_${name}" {
  metadata {
    name        = "ingress-nginx-${name}"
    namespace   = "default"
    annotations = { "kubernetes.io/ingress.class" = "nginx", "nginx.ingress.kubernetes.io/configuration-snippet" = "modsecurity_rules '\n SecRuleEngine On\n SecRequestBodyAccess On\n SecAuditEngine RelevantOnly\n SecAuditLogParts ABCIJDEFHZ\n SecAuditLog /var/log/modsec_audit.log\n SecRuleRemoveById 932140\n';\n", "nginx.ingress.kubernetes.io/ssl-passthrough" = "true" }
  }
  spec {
    tls {
      hosts       = ["${wordpress_site.url}"]
      secret_name = "${wordpress_site.certificate}"
    }
    rule {
      host = "${wordpress_site.url}"
      http {
        path {
          path = "/"
          backend {
            service_name = "${name}"
            service_port = "80"
          }
        }
      }
    }
  }
}
%{ endfor ~}
</code>```

and now, in main.tf, what is the best way in order to mix it all? I see that new functionalities are added in TF 0.12 like templatefile function, but didn't know at all if I can use it like:

main.tf:

```<code>templatefile(${path.module}/rules.tpl, ${module.var.wordpress_site})

</code>```

Thanks all for your support!

答:
The templatefile function is for generating strings from a template, not for generating Terraform configuration. Although it would be possible to render your given template to produce a string containing Terraform configuration, Terraform would just see the result as a normal string, not as more configuration to be evaluated.

Instead, what we need to get the desired result is resource for_each, which allows creating multiple instances from a single resource based on a map value.

```<code>resource "kubernetes_ingress" "nginx" {
  for_each = var.wordpress_site

  metadata {
    name        = "ingress-nginx-${each.value.name}"
    namespace   = "default"
    annotations = {
      "kubernetes.io/ingress.class" = "nginx"
      "nginx.ingress.kubernetes.io/configuration-snippet" = <<-EOT
        modsecurity_rules '
         SecRuleEngine On
         SecRequestBodyAccess On
         SecAuditEngine RelevantOnly
         SecAuditLogParts ABCIJDEFHZ
         SecAuditLog /var/log/modsec_audit.log
         SecRuleRemoveById 932140
        ';
      EOT
      "nginx.ingress.kubernetes.io/ssl-passthrough" = "true"
    }
  }
  spec {
    tls {
      hosts       = [each.value.url]
      secret_name = each.value.certificate
    }
    rule {
      host = each.value.url
      http {
        path {
          path = "/"
          backend {
            service_name = each.value.name
            service_port = "80"
          }
        }
      }
    }
  }
}
</code>```

When a resource has for_each set, Terraform will evaluate the given argument to obtain a map, and will then create one instance of the resource for each element in that map, with each one identified by its corresponding map key. In this case, assuming the default value of var.wordpress_site, you'll get two instances with the following addresses:

kubernetes_ingress.nginx["siteA"]

kubernetes_ingress.nginx["siteB"]

Inside the resource block, references starting with each.value refer to the values from the map, which in this case are the objects describing each site.

Body:
I wonder if something like this could be used. I have functional code working, but as pods in kubernetes will grow up fast, I want to convert into templates. This is an example for the creation of each nginx ingress rule for each wordpress site pod.

Now, each pod has its wordpress ingress entry with:

resource "kubernetes_ingress" "ingress_nginx_siteA" {
  metadata {
    name        = "ingress-nginx-siteA"
    namespace   = "default"
    annotations = { "kubernetes.io/ingress.class" = "nginx", "nginx.ingress.kubernetes.io/configuration-snippet" = "modsecurity_rules '\n SecRuleEngine On\n SecRequestBodyAccess On\n SecAuditEngine RelevantOnly\n SecAuditLogParts ABCIJDEFHZ\n SecAuditLog /var/log/modsec_audit.log\n SecRuleRemoveById 932140\n';\n", "nginx.ingress.kubernetes.io/ssl-passthrough" = "true" }
  }
  spec {
    tls {
      hosts       = ["siteA.test.com"]
      secret_name = "wildcard-test-com"
    }
    rule {
      host = "siteA.test.com"
      http {
        path {
          path = "/"
          backend {
            service_name = "siteA"
            service_port = "80"
          }
        }
      }
    }
  }
}

Now I want to split into variables.tf that contain the whole sites variables, a template file rules.tpl and the main.tf that orchestrate this stuff.

variables.tf:

variable "wordpress_site" {
  type = map(object({
    name        = string
    url         = string
    certificate = string
  }))
    default = {
    siteA = {
      name        = siteA
      url         = siteA.test.com
      certificate = wildcard-test-com
    }
    siteB = {
      name        = siteB
      url         = siteB.test.com
      certificate = wildcard-test-com
    }
  }
}

rules.tpl:

%{ for name in wordpress_site.name ~}
resource "kubernetes_ingress" "ingress_nginx_${name}" {
  metadata {
    name        = "ingress-nginx-${name}"
    namespace   = "default"
    annotations = { "kubernetes.io/ingress.class" = "nginx", "nginx.ingress.kubernetes.io/configuration-snippet" = "modsecurity_rules '\n SecRuleEngine On\n SecRequestBodyAccess On\n SecAuditEngine RelevantOnly\n SecAuditLogParts ABCIJDEFHZ\n SecAuditLog /var/log/modsec_audit.log\n SecRuleRemoveById 932140\n';\n", "nginx.ingress.kubernetes.io/ssl-passthrough" = "true" }
  }
  spec {
    tls {
      hosts       = ["${wordpress_site.url}"]
      secret_name = "${wordpress_site.certificate}"
    }
    rule {
      host = "${wordpress_site.url}"
      http {
        path {
          path = "/"
          backend {
            service_name = "${name}"
            service_port = "80"
          }
        }
      }
    }
  }
}
%{ endfor ~}

and now, in main.tf, what is the best way in order to mix it all? I see that new functionalities are added in TF 0.12 like templatefile function, but didn't know at all if I can use it like:

main.tf:

templatefile(${path.module}/rules.tpl, ${module.var.wordpress_site})

Thanks all for your support!

Body:
The templatefile function is for generating strings from a template, not for generating Terraform configuration. Although it would be possible to render your given template to produce a string containing Terraform configuration, Terraform would just see the result as a normal string, not as more configuration to be evaluated.

Instead, what we need to get the desired result is resource for_each, which allows creating multiple instances from a single resource based on a map value.

resource "kubernetes_ingress" "nginx" {
  for_each = var.wordpress_site

  metadata {
    name        = "ingress-nginx-${each.value.name}"
    namespace   = "default"
    annotations = {
      "kubernetes.io/ingress.class" = "nginx"
      "nginx.ingress.kubernetes.io/configuration-snippet" = <<-EOT
        modsecurity_rules '
         SecRuleEngine On
         SecRequestBodyAccess On
         SecAuditEngine RelevantOnly
         SecAuditLogParts ABCIJDEFHZ
         SecAuditLog /var/log/modsec_audit.log
         SecRuleRemoveById 932140
        ';
      EOT
      "nginx.ingress.kubernetes.io/ssl-passthrough" = "true"
    }
  }
  spec {
    tls {
      hosts       = [each.value.url]
      secret_name = each.value.certificate
    }
    rule {
      host = each.value.url
      http {
        path {
          path = "/"
          backend {
            service_name = each.value.name
            service_port = "80"
          }
        }
      }
    }
  }
}

When a resource has for_each set, Terraform will evaluate the given argument to obtain a map, and will then create one instance of the resource for each element in that map, with each one identified by its corresponding map key. In this case, assuming the default value of var.wordpress_site, you'll get two instances with the following addresses:

kubernetes_ingress.nginx["siteA"]

kubernetes_ingress.nginx["siteB"]

Inside the resource block, references starting with each.value refer to the values from the map, which in this case are the objects describing each site.


问:
selenium and lxml - how to set html?
I have a script that parses a document and changes form values with lxml.  Now I want to use selenium to navigate to the page and do it.

Unfortunately selenium doesn't seem to be advanced enough support some of the things I'm doing in lxml, for example, "if 'attrName' in tag.attrib"

Then I said, "Aha!, But selenium provides webdriver.page_source where I can get the html!"
Yeah, sort of... I can get it, then parse it with lxml... but annoyingly, page_source is not writeable so I cannot persist my changes!

I still feel like I'm on the right path with that, but is there some way I can write the modified html back to the browser?

UPDATE:
I tried several ways of trying to rewrite all page contents, but the firefox webdriver started throwing security exceptions like it didn't like the looks of what I was trying to do.  Below I'll post the alternative I used instead.

答:
What I wound up doing was to create an lxml-like intermediary class.  This implements only those features which I needed, but still, I thought I'd share as a starting point for others trying to do the same thing.</p>

```<code>import lxml.etree
import collections.abc

class AttribWrapper(collections.abc.MutableMapping):
    """
    Make something that acts like a dict to use as a mock lxml.etree.element attrib value

    see also:
        https://docs.python.org/3/reference/datamodel.html?emulating-container-types#emulating-container-types
    """
    def __init__(self,seleniumTag):
        self.seleniumTag=seleniumTag
        while not hasattr(seleniumTag,'execute_script'):
            seleniumTag=seleniumTag.parent
        self.webdriver=seleniumTag

    def hasAttribute(self,attrName):
        """
        determine if a tag has an attribute
        """
        try:
            val=self.seleniumTag.get_attribute(attrName)
        except Exception:
            return False
        return val is not None

    def getAttribute(self,attrName,default=None):
        """
        get a tag's attribute or default if not present
        """
        try:
            return self.seleniumTag.get_attribute(attrName)
        except Exception:
            pass
        return default

    def setAttribute(self,attrName,attrValue):
        """
        get a tag's attribute
        """
        self.webdriver.execute_script("arguments[0].setAttribute(arguments[1],arguments[2]);",self.seleniumTag,attrName,attrValue);

    def __getitem__(self,key):
        if key not in self.keys():
            raise KeyError()
        return self.getAttribute(key)

    def __setitem__(self,key,value):
        self.setAttribute(key,value)

    def __delitem__(self,key):
        self.webdriver.execute_script('arguments[0].attributes.removeNamedItem("%s");'%key,self.seleniumTag)

    def __iter__(self):
        items=[]
        for k in self.keys():
            v=self[k]
            items.append((k,v))
        return self.keys().__iter__()

    def __len__(self):
        return self.webdriver.execute_script('return arguments[0].attributes.length',self.seleniumTag)

    def keys(self):
        n=self.webdriver.execute_script('return arguments[0].attributes.length',self.seleniumTag)
        names=[]
        for idx in range(n):
            result=self.webdriver.execute_script('return arguments[0].attributes.item(%d).nodeName'%idx,self.seleniumTag)
            names.append(result)
        return names

    def __repr__(self):
        ret=[]
        for k,v in self.items():
            ret.append('("%s":"%s")'%(k,v))
        return "{%s}"%(', '.join(ret))

class LikeEtreeElement:

    def __init__(self,seleniumTag):
        self.seleniumTag=seleniumTag
        self.attrib=AttribWrapper(seleniumTag)
        while not hasattr(seleniumTag,'execute_script'):
            seleniumTag=seleniumTag.parent
        self.webdriver=seleniumTag

    @property
    def tag(self):
        return self.seleniumTag.tag_name

    def getchildren(self):
        """
        get all child elements
        (NOTE: this will dip into the html every single time just
            in case things have changed.)
        """
        return self.seleniumTag.find_elements_by_xpath('/*')

    @property
    def innerHTML(self):
        return self.webdriver.execute_script('return arguments[0].innerHTML',self.seleniumTag)
    @innerHTML.setter
    def innerHTML(self,value):
        value=str(value).replace('\\\\','\\').replace('\n','\\n').replace('"','\\"')
        return self.webdriver.execute_script('arguments[0].innerHTML="%s"'%(value),self.seleniumTag)

    def __getitem__(self,idx):
        return self.getchildren()[idx]

    def __iter__(self):
        return self.getchildren().__iter__()

    def __len__(self):
        return len(self.getchildren())
</code>```

Title: selenium and lxml - how to set html?

Body:
What I wound up doing was to create an lxml-like intermediary class.  This implements only those features which I needed, but still, I thought I'd share as a starting point for others trying to do the same thing.

import lxml.etree
import collections.abc

class AttribWrapper(collections.abc.MutableMapping):
    """
    Make something that acts like a dict to use as a mock lxml.etree.element attrib value

    see also:
        https://docs.python.org/3/reference/datamodel.html?emulating-container-types#emulating-container-types
    """
    def __init__(self,seleniumTag):
        self.seleniumTag=seleniumTag
        while not hasattr(seleniumTag,'execute_script'):
            seleniumTag=seleniumTag.parent
        self.webdriver=seleniumTag

    def hasAttribute(self,attrName):
        """
        determine if a tag has an attribute
        """
        try:
            val=self.seleniumTag.get_attribute(attrName)
        except Exception:
            return False
        return val is not None

    def getAttribute(self,attrName,default=None):
        """
        get a tag's attribute or default if not present
        """
        try:
            return self.seleniumTag.get_attribute(attrName)
        except Exception:
            pass
        return default

    def setAttribute(self,attrName,attrValue):
        """
        get a tag's attribute
        """
        self.webdriver.execute_script("arguments[0].setAttribute(arguments[1],arguments[2]);",self.seleniumTag,attrName,attrValue);

    def __getitem__(self,key):
        if key not in self.keys():
            raise KeyError()
        return self.getAttribute(key)

    def __setitem__(self,key,value):
        self.setAttribute(key,value)

    def __delitem__(self,key):
        self.webdriver.execute_script('arguments[0].attributes.removeNamedItem("%s");'%key,self.seleniumTag)

    def __iter__(self):
        items=[]
        for k in self.keys():
            v=self[k]
            items.append((k,v))
        return self.keys().__iter__()

    def __len__(self):
        return self.webdriver.execute_script('return arguments[0].attributes.length',self.seleniumTag)

    def keys(self):
        n=self.webdriver.execute_script('return arguments[0].attributes.length',self.seleniumTag)
        names=[]
        for idx in range(n):
            result=self.webdriver.execute_script('return arguments[0].attributes.item(%d).nodeName'%idx,self.seleniumTag)
            names.append(result)
        return names

    def __repr__(self):
        ret=[]
        for k,v in self.items():
            ret.append('("%s":"%s")'%(k,v))
        return "{%s}"%(', '.join(ret))

class LikeEtreeElement:

    def __init__(self,seleniumTag):
        self.seleniumTag=seleniumTag
        self.attrib=AttribWrapper(seleniumTag)
        while not hasattr(seleniumTag,'execute_script'):
            seleniumTag=seleniumTag.parent
        self.webdriver=seleniumTag

    @property
    def tag(self):
        return self.seleniumTag.tag_name

    def getchildren(self):
        """
        get all child elements
        (NOTE: this will dip into the html every single time just
            in case things have changed.)
        """
        return self.seleniumTag.find_elements_by_xpath('/*')

    @property
    def innerHTML(self):
        return self.webdriver.execute_script('return arguments[0].innerHTML',self.seleniumTag)
    @innerHTML.setter
    def innerHTML(self,value):
        value=str(value).replace('\\\\','\\').replace('\n','\\n').replace('"','\\"')
        return self.webdriver.execute_script('arguments[0].innerHTML="%s"'%(value),self.seleniumTag)

    def __getitem__(self,idx):
        return self.getchildren()[idx]

    def __iter__(self):
        return self.getchildren().__iter__()

    def __len__(self):
        return len(self.getchildren())


问:
Problem finding duplicate numbers in array, is my technique bad?
I used a HashMap to store the occurrences of each element, and then iterated over the hash map to get duplicated element, but something doesn't feel right about this solution.

Problem statement in Firecode.io:

Write a method duplicate to find the repeated or duplicate elements in an array. This method should return a list of repeated integers in a string with the elements sorted in ascending order (as illustrated below).

duplicate({1,3,4,2,1}) --> "[1]"

duplicate({1,3,4,2,1,2,4}) --> "[1, 2, 4]"

Note: You may use toString() method to return the standard string representation of most data structures, and Arrays.sort() to sort your result.*

Here is my code:

```<code> public String duplicate(int[] numbers) {
      HashMap < Integer, Integer > hs = new HashMap < Integer, Integer > ();
      for (int i = 0; i < numbers.length; i++) {
           if (hs.get(numbers[i]) == null) {
                hs.put(numbers[i], 1);
           } else hs.put(numbers[i], (Integer) hs.get(numbers[i]) + 1);
      }

      int size = 0;
      for (int i: hs.keySet()) {
           if (hs.get(i) > 1) {
                size++;
           }
      }
      int j = 0;
      int[] a = new int[size];
      for (int i: hs.keySet()) {
           if (hs.get(i) > 1) {
                a[j++] = i;
           }
      }

      Arrays.sort(a);
      return Arrays.toString(a);
 }
</code>```

答:
Here's the way I would do it: (comments for educational purposes, would probably not have them in production code.)</p>

```<code>public String duplicate(int[] numbers) {

  // holds the items we've encountered more than once.
  // TreeSet<> keeps things in sorted order for us.
  final SortedSet<Integer> duplicates = new TreeSet<>();

  // keeps track of items we've encountered.
  final Set<Integer> encountered = new HashSet<>();

  // iterate over every number
  for (final int number : numbers) {
    // Add the item to encountered. Set.add() will return true if
    // the element is new to the set.
    if (!encountered.add(number)) {
       // Since the element wasn't new, ensure this item exists in the duplicates collection.
       duplicates.add(number);
    }
  }

  return duplicates.toString();
}
</code>```

Body:
I used a HashMap to store the occurrences of each element, and then iterated over the hash map to get duplicated element, but something doesn't feel right about this solution.

Problem statement in Firecode.io:

Write a method duplicate to find the repeated or duplicate elements in an array. This method should return a list of repeated integers in a string with the elements sorted in ascending order (as illustrated below).

duplicate({1,3,4,2,1}) --> "[1]"

duplicate({1,3,4,2,1,2,4}) --> "[1, 2, 4]"

Note: You may use toString() method to return the standard string representation of most data structures, and Arrays.sort() to sort your result.*

Here is my code:

 public String duplicate(int[] numbers) {
      HashMap < Integer, Integer > hs = new HashMap < Integer, Integer > ();
      for (int i = 0; i < numbers.length; i++) {
           if (hs.get(numbers[i]) == null) {
                hs.put(numbers[i], 1);
           } else hs.put(numbers[i], (Integer) hs.get(numbers[i]) + 1);
      }

      int size = 0;
      for (int i: hs.keySet()) {
           if (hs.get(i) > 1) {
                size++;
           }
      }
      int j = 0;
      int[] a = new int[size];
      for (int i: hs.keySet()) {
           if (hs.get(i) > 1) {
                a[j++] = i;
           }
      }

      Arrays.sort(a);
      return Arrays.toString(a);
 }

Body:
Here's the way I would do it: (comments for educational purposes, would probably not have them in production code.)

public String duplicate(int[] numbers) {

  // holds the items we've encountered more than once.
  // TreeSet<> keeps things in sorted order for us.
  final SortedSet<Integer> duplicates = new TreeSet<>();

  // keeps track of items we've encountered.
  final Set<Integer> encountered = new HashSet<>();

  // iterate over every number
  for (final int number : numbers) {
    // Add the item to encountered. Set.add() will return true if
    // the element is new to the set.
    if (!encountered.add(number)) {
       // Since the element wasn't new, ensure this item exists in the duplicates collection.
       duplicates.add(number);
    }
  }

  return duplicates.toString();
}


问:
Swift perform action when become first responder
Is there a default method that is called when a UITextField or similar becomes the first responder, in order to have actions occur at that point?</p>

答:
You could subclass your UITextField to handle first responder notifications. Just conform the view controller to the protocol and implement the two delegate methods. You'll be notified there.

```<code>protocol UITextFieldResponderDelegate: AnyObject {
    func becameFirstResponder()
    func resignedAsFirstResponder()
}

class UITextFieldCustom: UITextField {

    weak var responderDelegate: UITextFieldResponderDelegate?

    override func becomeFirstResponder() -> Bool {
        responderDelegate?.becameFirstResponder()
        return super.becomeFirstResponder()
    }

    override func resignFirstResponder() -> Bool {
        responderDelegate?.resignedAsFirstResponder()
        return super.resignFirstResponder()
    }

}

class SomeViewController: UIViewController, UITextFieldResponderDelegate {

    private let textField = UITextFieldCustom()

    override func viewDidLoad() {
        super.viewDidLoad()
        textField.responderDelegate = self
    }

    func becameFirstResponder() {
        print("became first responder")
    }

    func resignedAsFirstResponder() {
        print("resigned as first responder")
    }

}
</code>```

If you had multiple text fields within the same view controller that you wanted to handle notifications on, simply switch on them in the delegate.

Body:
You could subclass your UITextField to handle first responder notifications. Just conform the view controller to the protocol and implement the two delegate methods. You'll be notified there.

protocol UITextFieldResponderDelegate: AnyObject {
    func becameFirstResponder()
    func resignedAsFirstResponder()
}

class UITextFieldCustom: UITextField {

    weak var responderDelegate: UITextFieldResponderDelegate?

    override func becomeFirstResponder() -> Bool {
        responderDelegate?.becameFirstResponder()
        return super.becomeFirstResponder()
    }

    override func resignFirstResponder() -> Bool {
        responderDelegate?.resignedAsFirstResponder()
        return super.resignFirstResponder()
    }

}

class SomeViewController: UIViewController, UITextFieldResponderDelegate {

    private let textField = UITextFieldCustom()

    override func viewDidLoad() {
        super.viewDidLoad()
        textField.responderDelegate = self
    }

    func becameFirstResponder() {
        print("became first responder")
    }

    func resignedAsFirstResponder() {
        print("resigned as first responder")
    }

}

If you had multiple text fields within the same view controller that you wanted to handle notifications on, simply switch on them in the delegate.


问:
Problem with oh-my-zsh arrows colors in vscode
I'm trying to modify a ZSH theme but there's something wrong with colors

I can see everything ok in windows terminal:

I also can see everything ok when I connect to my WSL with the vscode remote tool:

But when i'm in a local context this happens:

This is the relevant part of my vscode config:

```<code>"terminal.integrated.fontFamily": "DejaVuSansMono Nerd Font",
"terminal.integrated.shell.windows": "C:\\WINDOWS\\System32\\wsl.exe",
"files.exclude": {
    "**/.git": false
 },
"terminal.integrated.shell.linux": "/usr/bin/zsh",
"gitlens.views.repositories.branches.layout": "list",
"window.zoomLevel": 0,
"workbench.colorCustomizations": {
"terminalCursor.background":"#C5C8C6",
"terminalCursor.foreground":"#C5C8C6",
// "terminal.ansiBlack":"#1D1F21",
"terminal.ansiBlue":"#27aecf",
"terminal.ansiBrightBlack":"#969896",
// "terminal.ansiBrightBlue":"#81A2BE",
// "terminal.ansiBrightCyan":"#8ABEB7",
// "terminal.ansiBrightGreen":"#B5BD68",
// "terminal.ansiBrightMagenta":"#B294BB",
// "terminal.ansiBrightRed":"#CC6666",
// "terminal.ansiBrightWhite":"#FFFFFF",
// "terminal.ansiBrightYellow":"#F0C674",
// "terminal.ansiCyan":"#8ABEB7",
"terminal.ansiGreen":"#438b43",
// "terminal.ansiMagenta":"#B294BB",
// "terminal.ansiRed":"#CC6666",
"terminal.ansiWhite":"#ffffff",
"terminal.ansiYellow":"#9e983c"

},
"materialTheme.accent": "Cyan",
"terminal.external.linuxExec": "zsh",
"python.terminal.activateEnvInCurrentTerminal": true
  }
</code>```

I'd love to fix the color of those triangles.
I've tried almost everything in my hand but now I have no clue of what to do...

Thanks in advance!

答:
Okey I fixed it,

My problem was that in I needed to add a color for foreground in the vscode setting

```<code>"terminal.foreground":"#ffffff"
</code>```

apparently the default color for this is some kind of grey and that's what it draw when you don't specify any color.

Body:
I'm trying to modify a ZSH theme but there's something wrong with colors

I can see everything ok in windows terminal:

I also can see everything ok when I connect to my WSL with the vscode remote tool:

But when i'm in a local context this happens:

This is the relevant part of my vscode config:

"terminal.integrated.fontFamily": "DejaVuSansMono Nerd Font",
"terminal.integrated.shell.windows": "C:\\WINDOWS\\System32\\wsl.exe",
"files.exclude": {
    "**/.git": false
 },
"terminal.integrated.shell.linux": "/usr/bin/zsh",
"gitlens.views.repositories.branches.layout": "list",
"window.zoomLevel": 0,
"workbench.colorCustomizations": {
"terminalCursor.background":"#C5C8C6",
"terminalCursor.foreground":"#C5C8C6",
// "terminal.ansiBlack":"#1D1F21",
"terminal.ansiBlue":"#27aecf",
"terminal.ansiBrightBlack":"#969896",
// "terminal.ansiBrightBlue":"#81A2BE",
// "terminal.ansiBrightCyan":"#8ABEB7",
// "terminal.ansiBrightGreen":"#B5BD68",
// "terminal.ansiBrightMagenta":"#B294BB",
// "terminal.ansiBrightRed":"#CC6666",
// "terminal.ansiBrightWhite":"#FFFFFF",
// "terminal.ansiBrightYellow":"#F0C674",
// "terminal.ansiCyan":"#8ABEB7",
"terminal.ansiGreen":"#438b43",
// "terminal.ansiMagenta":"#B294BB",
// "terminal.ansiRed":"#CC6666",
"terminal.ansiWhite":"#ffffff",
"terminal.ansiYellow":"#9e983c"

},
"materialTheme.accent": "Cyan",
"terminal.external.linuxExec": "zsh",
"python.terminal.activateEnvInCurrentTerminal": true
  }

I'd love to fix the color of those triangles.
I've tried almost everything in my hand but now I have no clue of what to do...

Thanks in advance!

Body:
Okey I fixed it,

My problem was that in I needed to add a color for foreground in the vscode setting

"terminal.foreground":"#ffffff"

apparently the default color for this is some kind of grey and that's what it draw when you don't specify any color.


问:
React - can't stream video from webcam
I'm trying to fix my Component to streaming data from webcam. It renders successfully and successfully gets access to webcam. But I have no idea why video tag do not plays anything. How to fix this? What am I missing?</p>

```<code>export class WebcamStream extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            src: null
        }
        this.videoRef = React.createRef()
    }

    componentDidMount() {
        // getting access to webcam
        navigator.mediaDevices
            .getUserMedia({video: true})
            .then(stream => this.setState({src: stream}))
            .catch(console.log);
    }

    render() {
        return <video id={this.props.id}
                      ref={() => this.videoRef.srcObject = this.state.src}
                      width={this.props.width}
                      height={this.props.height}
                      autoPlay="autoplay"
                      title={this.props.title}></video>
    }
}
</code>```

答:
The component that worked for me is the following</p>

```<code>import React, { useState, useEffect } from 'react';

export default function ModalVideo(props) {
    const [video,]=useState(React.createRef());

    const videoError=(error)=>{
        console.log("error",error);
    }

    const handleVideo=(stream)=>{
        video.current.srcObject = stream;
    }

    useEffect(() => {
        navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia || navigator.oGetUserMedia;
        if (navigator.getUserMedia) {
            navigator.getUserMedia({video: true}, handleVideo, videoError);
        }
    });

    return (
        <div>
            <video ref={video}  autoPlay={true} />
        </div>
    )
}
</code>```

Title: React - can't stream video from webcam

Body:
I'm trying to fix my Component to streaming data from webcam. It renders successfully and successfully gets access to webcam. But I have no idea why video tag do not plays anything. How to fix this? What am I missing?

export class WebcamStream extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            src: null
        }
        this.videoRef = React.createRef()
    }

    componentDidMount() {
        // getting access to webcam
        navigator.mediaDevices
            .getUserMedia({video: true})
            .then(stream => this.setState({src: stream}))
            .catch(console.log);
    }

    render() {
        return <video id={this.props.id}
                      ref={() => this.videoRef.srcObject = this.state.src}
                      width={this.props.width}
                      height={this.props.height}
                      autoPlay="autoplay"
                      title={this.props.title}></video>
    }
}

Body:
The component that worked for me is the following

import React, { useState, useEffect } from 'react';

export default function ModalVideo(props) {
    const [video,]=useState(React.createRef());

    const videoError=(error)=>{
        console.log("error",error);
    }

    const handleVideo=(stream)=>{
        video.current.srcObject = stream;
    }

    useEffect(() => {
        navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia || navigator.oGetUserMedia;
        if (navigator.getUserMedia) {
            navigator.getUserMedia({video: true}, handleVideo, videoError);
        }
    });

    return (
        <div>
            <video ref={video}  autoPlay={true} />
        </div>
    )
}


问:
How do I check present viewController or root viewController?
I have set up my class with UITabBarDelegate and implemented its method didSelectItem to detect when a certain tabBar item is pressed. Works great. In each tabBar item I have one containerView that can show a "you have to login"-page if the user is not logged in, and another containerView that present viewControllers that are embedded in a navigationController.

I would like to keep track of the viewController that is presented in the current tab item, and/or the root viewController of that tab.

I have tried a number of different approaches, but most of them return nil or I can't get it to work. I think the whole container situation makes it harder to handle.

It looks something like this:

```<code>@interface MyTabBarController () <UITabBarDelegate>

- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item {

    NSUInteger indexOfTab = [[tabBar items] indexOfObject:item];

    switch (indexOfTab) {
        case 0: {
            NSLog(@"PRESSIIING %lu", (unsigned long)[[tabBar items] indexOfObject:item]);
            break;
        }
        case 1: {
           NSLog(@"PRESSIIING %lu", (unsigned long)[[tabBar items] indexOfObject:item]);
           break;
        }
        case 2: {
           NSLog(@"PRESSIIING %lu", (unsigned long)[[tabBar items] indexOfObject:item]);

//These return nil
            NSLog(@"AAAAAA %@", ((UINavigationController*)_appD.window.rootViewController).visibleViewController);
            NSLog(@"AAAAAA %@", ((UITabBarController*)_appD.window.rootViewController).selectedViewController);
            NSLog(@"AAAAAA %@", self.navigationController.topViewController);
            NSLog(@"AAAAAA %@", self.navigationController.visibleViewController);

//This returns with a value, but can't get it to work with conditionals, that is, when I'm in root, the else is triggered
            NSLog(@"AAAAAA %@", self.tabBar.window.rootViewController);

            if(!self.tabBar.window.rootViewController) {
                NSLog(@"THIS IS NOT ROOT");

            }else {
                NSLog(@"this is ROOT");
            }

// This returns nil
            ((UINavigationController*)_appD.window.rootViewController).visibleViewController;
            ((UITabBarController*)_appD.window.rootViewController).selectedViewController;

            //Doesn't work
            if([self.navigationController.viewControllers[0] isKindOfClass:[ExperiencesListViewController class]]) {
                           NSLog(@"IS KIND OF CLASS LIST");
                       }
                       if([self.navigationController.viewControllers[0].childViewControllers isKindOfClass:[ExperiencesContainerViewController class]]) {
                           NSLog(@"IS KIND OF CLASS CONTAINER");
                     }
           break;
       }
        case 3: {
           NSLog(@"PRESSIIING %lu", (unsigned long)[[tabBar items] indexOfObject:item]);
           break;
       }
        case 4: {
           NSLog(@"PRESSIIING %lu", (unsigned long)[[tabBar items] indexOfObject:item]);
           break;
       }
        default:
            break;
    }
}

So, what else can I try? Seems like I have to use `self.tabBar.window.rootViewController` in some way, no?

***EDIT***
Oh, and I have tried the `tabBarController` delegate but that doesn't trigger. Also, the `tabBar` is constructed programmatically if that helps.

</code>```

答:
When you're setting up each view controller for each of the tabs, set the tag property of the UITabBarItem to correspond to the index of the view controller in the tab bar's viewControllers array.

```<code>UIViewController* myFirstVC = [[UIViewController alloc] init];
UIViewController* mySecondVC = [[UIViewController alloc] init];

// "self" is your ApolloTabBarController.
[self setViewControllers:@[myFirstVC, mySecondVC]];

myFirstVC.tabBarItem =
    [[UITabBarItem alloc] initWithTitle:@"First" image:nil tag:0];

mySecondVC.tabBarItem =
    [[UITabBarItem alloc] initWithTitle:@"Second" image:nil tag:1];
</code>```

Then, you'll be able to grab a reference to view controller.

```<code>// In your example, your ApolloTabBarController acts as its own delegate.
- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item
{
    UIViewController* activeVC =
        [[self viewControllers] objectAtIndex:[item tag]];
}
</code>```

Body:
I have set up my class with UITabBarDelegate and implemented its method didSelectItem to detect when a certain tabBar item is pressed. Works great. In each tabBar item I have one containerView that can show a "you have to login"-page if the user is not logged in, and another containerView that present viewControllers that are embedded in a navigationController.

I would like to keep track of the viewController that is presented in the current tab item, and/or the root viewController of that tab.

I have tried a number of different approaches, but most of them return nil or I can't get it to work. I think the whole container situation makes it harder to handle.

It looks something like this:

@interface MyTabBarController () <UITabBarDelegate>

- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item {

    NSUInteger indexOfTab = [[tabBar items] indexOfObject:item];

    switch (indexOfTab) {
        case 0: {
            NSLog(@"PRESSIIING %lu", (unsigned long)[[tabBar items] indexOfObject:item]);
            break;
        }
        case 1: {
           NSLog(@"PRESSIIING %lu", (unsigned long)[[tabBar items] indexOfObject:item]);
           break;
        }
        case 2: {
           NSLog(@"PRESSIIING %lu", (unsigned long)[[tabBar items] indexOfObject:item]);

//These return nil
            NSLog(@"AAAAAA %@", ((UINavigationController*)_appD.window.rootViewController).visibleViewController);
            NSLog(@"AAAAAA %@", ((UITabBarController*)_appD.window.rootViewController).selectedViewController);
            NSLog(@"AAAAAA %@", self.navigationController.topViewController);
            NSLog(@"AAAAAA %@", self.navigationController.visibleViewController);

//This returns with a value, but can't get it to work with conditionals, that is, when I'm in root, the else is triggered
            NSLog(@"AAAAAA %@", self.tabBar.window.rootViewController);

            if(!self.tabBar.window.rootViewController) {
                NSLog(@"THIS IS NOT ROOT");

            }else {
                NSLog(@"this is ROOT");
            }

// This returns nil
            ((UINavigationController*)_appD.window.rootViewController).visibleViewController;
            ((UITabBarController*)_appD.window.rootViewController).selectedViewController;

            //Doesn't work
            if([self.navigationController.viewControllers[0] isKindOfClass:[ExperiencesListViewController class]]) {
                           NSLog(@"IS KIND OF CLASS LIST");
                       }
                       if([self.navigationController.viewControllers[0].childViewControllers isKindOfClass:[ExperiencesContainerViewController class]]) {
                           NSLog(@"IS KIND OF CLASS CONTAINER");
                     }
           break;
       }
        case 3: {
           NSLog(@"PRESSIIING %lu", (unsigned long)[[tabBar items] indexOfObject:item]);
           break;
       }
        case 4: {
           NSLog(@"PRESSIIING %lu", (unsigned long)[[tabBar items] indexOfObject:item]);
           break;
       }
        default:
            break;
    }
}

So, what else can I try? Seems like I have to use `self.tabBar.window.rootViewController` in some way, no?

***EDIT***
Oh, and I have tried the `tabBarController` delegate but that doesn't trigger. Also, the `tabBar` is constructed programmatically if that helps.

Body:
When you're setting up each view controller for each of the tabs, set the tag property of the UITabBarItem to correspond to the index of the view controller in the tab bar's viewControllers array.

UIViewController* myFirstVC = [[UIViewController alloc] init];
UIViewController* mySecondVC = [[UIViewController alloc] init];

// "self" is your ApolloTabBarController.
[self setViewControllers:@[myFirstVC, mySecondVC]];

myFirstVC.tabBarItem =
    [[UITabBarItem alloc] initWithTitle:@"First" image:nil tag:0];

mySecondVC.tabBarItem =
    [[UITabBarItem alloc] initWithTitle:@"Second" image:nil tag:1];

Then, you'll be able to grab a reference to view controller.

// In your example, your ApolloTabBarController acts as its own delegate.
- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item
{
    UIViewController* activeVC =
        [[self viewControllers] objectAtIndex:[item tag]];
}


问:
Upsert a document with value from filter
I have a collection with following structure in MongoDB:

```<code>{
  "userId": String,
  "refs": Set<String>
}
</code>```

I need to update the collections with those documents. I want to add to refs a new string, for users that are in the filter $in.
But, if the user is not exists I need to "upsert" him.

In code (golang) it looks like this:

filter := bson.M{
    "userId": bson.M{
        "$in:": tokens // tokens is []string
    }
}

update := bson.M{
    "$addToSet": bson.M{
        "refs": newReference
    }
}

ctx, _ := newDbOperationContext()
_, err := driver.UpdateMany(ctx, filter, update)
```

<p>So, for existing users it works ok, the reference is added. But, for users that not exists nothing happen.</p>

<p>I set in <code>driver.UpdateMany(bson, bson, opts...)</code> opts to <code>options.UpdateOptions.SetUpsert(true)"</code>, but as a result I got a document without userId:</p>

```{
  "_id": ObjectId("..."),
  "refs": ["new_reference"]
}
```

So, my question is, how to upsert the new values with userId field.

The scale is like 2*10^6 users to update, so I would like to do that using batch request. Creating using "one by one" and updating him is not an option here, I think.

Thanks for your support!

答: In case of upsert if the document is not present then only the updator part of query is going to insert in the database. So that's why your output is like that. You can see here.</p>

Body:
I have a collection with following structure in MongoDB:

{
  "userId": String,
  "refs": Set<String>
}

I need to update the collections with those documents. I want to add to refs a new string, for users that are in the filter $in.
But, if the user is not exists I need to "upsert" him.

In code (golang) it looks like this:

filter := bson.M{
    "userId": bson.M{
        "$in:": tokens // tokens is []string
    }
}

update := bson.M{
    "$addToSet": bson.M{
        "refs": newReference
    }
}

ctx, _ := newDbOperationContext()
_, err := driver.UpdateMany(ctx, filter, update)

So, for existing users it works ok, the reference is added. But, for users that not exists nothing happen.

I set in driver.UpdateMany(bson, bson, opts...) opts to options.UpdateOptions.SetUpsert(true)", but as a result I got a document without userId:

{
  "_id": ObjectId("..."),
  "refs": ["new_reference"]
}

So, my question is, how to upsert the new values with userId field.

The scale is like 2*10^6 users to update, so I would like to do that using batch request. Creating using "one by one" and updating him is not an option here, I think.

Thanks for your support!


问:
Duck-typing user-defined classes
So Python's core language and built-ins use a lot of duck typing. But for our own code, say I want to create my own class with a method that deals with "certain types" of objects, is it more idiomatic to use duck typing:

class MerkleTree:

    def method(self, document):
        try:
            hash_ = document.sha256_hash()
        except AttributeError:
            raise TypeError()
        do_smth_with_hash(hash_)
```

<p>or is it more idiomatic to just use a normal type check:</p>

<pre class="lang-py prettyprint-override"><code>class MerkleTree:

    def method(self, document):
        if isinstance(document, SHA256Hashable):
            raise TypeError()
        hash_ = document.sha256_hash()
        do_smth_with_hash(hash_)
</code>```

答:
You're better off with duck typing for small or even medium projects, and PEP484+mypy for large projects.

EG:

```<code>python3 -m mypy --disallow-untyped-calls ${files}
</code>```

And:

```<code>def pad(number: int) -> str:
</code>```

BTW, if you already have a large project without PEP484 type annotations, you can use something like MonkeyType to add them.

Title: Duck-typing user-defined classes

Body:
So Python's core language and built-ins use a lot of duck typing. But for our own code, say I want to create my own class with a method that deals with "certain types" of objects, is it more idiomatic to use duck typing:

class MerkleTree:

    def method(self, document):
        try:
            hash_ = document.sha256_hash()
        except AttributeError:
            raise TypeError()
        do_smth_with_hash(hash_)

or is it more idiomatic to just use a normal type check:

class MerkleTree:

    def method(self, document):
        if isinstance(document, SHA256Hashable):
            raise TypeError()
        hash_ = document.sha256_hash()
        do_smth_with_hash(hash_)

Body:
You're better off with duck typing for small or even medium projects, and PEP484+mypy for large projects.

EG:

python3 -m mypy --disallow-untyped-calls ${files}

And:

def pad(number: int) -> str:

BTW, if you already have a large project without PEP484 type annotations, you can use something like MonkeyType to add them.


问:
Dumping a java object's properties
Is there a library that will recursively dump/print an objects properties?  I'm looking for something similar to the console.dir() function in Firebug.

I'm aware of the commons-lang ReflectionToStringBuilder but it does not recurse into an object. I.e., if I run the following:

```<code>public class ToString {

    public static void main(String [] args) {
        System.out.println(ReflectionToStringBuilder.toString(new Outer(), ToStringStyle.MULTI_LINE_STYLE));
    }

    private static class Outer {
        private int intValue = 5;
        private Inner innerValue = new Inner();
    }

    private static class Inner {
        private String stringValue = "foo";
    }
}
</code>```

I receive:

ToString$Outer@1b67f74[
  intValue=5

  innerValue=ToString$Inner@530daa
  ]

I realize that in my example, I could have overriden the toString() method for Inner but in the real world, I'm dealing with external objects that I can't modify.

答:
You could try XStream.

```<code>XStream xstream = new XStream(new Sun14ReflectionProvider(
  new FieldDictionary(new ImmutableFieldKeySorter())),
  new DomDriver("utf-8"));
System.out.println(xstream.toXML(new Outer()));
</code>```

prints out:

```<code><foo.ToString_-Outer>
  <intValue>5</intValue>
  <innerValue>
    <stringValue>foo</stringValue>
  </innerValue>
</foo.ToString_-Outer>
</code>```

You could also output in JSON

And be careful of circular references ;)

OwnerDisplayName: Kevin

Title: Dumping a java object's properties

Body:
Is there a library that will recursively dump/print an objects properties?  I'm looking for something similar to the console.dir() function in Firebug.

I'm aware of the commons-lang ReflectionToStringBuilder but it does not recurse into an object. I.e., if I run the following:

public class ToString {

    public static void main(String [] args) {
        System.out.println(ReflectionToStringBuilder.toString(new Outer(), ToStringStyle.MULTI_LINE_STYLE));
    }

    private static class Outer {
        private int intValue = 5;
        private Inner innerValue = new Inner();
    }

    private static class Inner {
        private String stringValue = "foo";
    }
}

I receive:

ToString$Outer@1b67f74[
  intValue=5

  innerValue=ToString$Inner@530daa
  ]

I realize that in my example, I could have overriden the toString() method for Inner but in the real world, I'm dealing with external objects that I can't modify.

Body:
You could try XStream.

XStream xstream = new XStream(new Sun14ReflectionProvider(
  new FieldDictionary(new ImmutableFieldKeySorter())),
  new DomDriver("utf-8"));
System.out.println(xstream.toXML(new Outer()));

prints out:

<foo.ToString_-Outer>
  <intValue>5</intValue>
  <innerValue>
    <stringValue>foo</stringValue>
  </innerValue>
</foo.ToString_-Outer>

You could also output in JSON

And be careful of circular references ;)

OwnerDisplayName: cherouvim


问:
static IDisposable dictionary pattern
I have a situation like below in a web application. I just wanted to check that it is a good pattern. Could something happen that meant my dictionary was corrupt (some members were disposed and some not, for example)? Have I implemented this idea correctly? </p>

```<code>static IDictionary<string, IDisposable>() _map;

Application_Start()
{
    if (_map == null)
    {
         _map = new IDictionary<string, IDisposable>();
         _map.Add(...);
         _map.Add(...);
    }
}

Application_End
{
    if (_map != null)
    {
        foreach (var m in _map)
        {
            m.Value.Dispose();
        }
        _map = null;
    }
}
</code>```

答:
I see the following problem:

Removing an object from the map during the runtime of the application doesn't dispose it. You will have to do that manually. The same is true for replacing an object in the map.

UPDATE:

The following will leave undisposed objects around:

```<code>_map[key] = new DisposableObject();
</code>```

The object that was previously identified by key will never be disposed.

About the whole concept:

It doesn't make too much sense. The .NET runtime frees all memory of your application when it exits. So, implementing IDisposable on objects that live as long as the application itself seems to be unneeded, unless they hold references to unmanaged resources like a open file handle.

Title: static IDisposable dictionary pattern

Body:
I have a situation like below in a web application. I just wanted to check that it is a good pattern. Could something happen that meant my dictionary was corrupt (some members were disposed and some not, for example)? Have I implemented this idea correctly?

static IDictionary<string, IDisposable>() _map;

Application_Start()
{
    if (_map == null)
    {
         _map = new IDictionary<string, IDisposable>();
         _map.Add(...);
         _map.Add(...);
    }
}

Application_End
{
    if (_map != null)
    {
        foreach (var m in _map)
        {
            m.Value.Dispose();
        }
        _map = null;
    }
}

Body:
I see the following problem:

Removing an object from the map during the runtime of the application doesn't dispose it. You will have to do that manually. The same is true for replacing an object in the map.

UPDATE:

The following will leave undisposed objects around:

_map[key] = new DisposableObject();

The object that was previously identified by key will never be disposed.

About the whole concept:

It doesn't make too much sense. The .NET runtime frees all memory of your application when it exits. So, implementing IDisposable on objects that live as long as the application itself seems to be unneeded, unless they hold references to unmanaged resources like a open file handle.


问:
Best practice for packaging modules with sub-modules - most using the same libraries
I am currently packaging my own module for distribution. In general everything is working fine, but fine-tuning/best-practice for structuring sub-modules is giving me some trouble.

Assuming a module structure of:

```<code>mdl
├── mdl
│   ├── __init__.py
│   ├── core.py
|   ├── sub_one
|   |   ├── __init__.py
|   |   └── core_sub_one.py
|   └── sub_two
|       ├── __init__.py
|       └── core_sub_two.py
├── README
└── setup.py
</code>```

core file headers

With the header of core.py starting with:

```<code>import numpy as np

...some fairly large module code...
</code>```

And the headers of both core_sub_one.py and core_sub_two.py starting with:

```<code>import numpy as np

from .. import core as cr
</code>```

So all submodules require np and cr.

init.py structure

The mdl/__init__.py (core-level) looks like:

```<code>from . import sub_one as so
from . import sub_two as st
</code>```

And __init__.py of both submodules looks like (replace one with two for the other submodule):

```<code>from . import core_sub_one
from .core_sub_one import *
</code>```

I've "learnt" this structure from numpy, see f.i. numpy/ma/__init__.py

Problem description

Now I've got some trouble with the submodule-access after running setup.py and importing my module with import mdl.

I can now access my submodules with f.i. mdl.so.some_function_in_sub_one(). This is expected and what I want.

But I can also access the top level module cr and numpy with mdl.so.cr and mdl.so.np, which I want to avoid. Is there any way to avoid this?
If not: Is there any drawback of importing/connecting modules and submodules like this?

And is there any best practice for how to import libraries like numpy in sub-modules, when they are required in all submodules?

Edit:

Since some seem to have trouble with the fact that asking for best practice is opinion based (which I know and which I intended, since imho most design decisions in real life are not clear binary 1-0 decisions), I have to add:

I want to comply with the module packaging style used in the scipy, and more specifically numpy, package environment. So if these packages found a solution for any of the questions I asked, this will be the most welcome solution for me.

答:
First thing first:

from .core_sub_one import *

DONT DO THIS. Yes, even if you seen it in some "big name" package, read it in some tutorials or whatever. This is officially considered bad practice, and for good reasons (from experience, it's a maintaince hell).

If you really really insist on doing this (but seriously, don't), at least define an explicit __all__ var in those modules so you keep exposed names under control (and it helps documenting what's supposed to be part of the module's API).

But I can also access the top level module cr and numpy with mdl.so.cr and mdl.so.np, which I want to avoid. Is there any way to avoid this?

Not really. If you're really worried about it, you can import those names as "protected" in your submodules:

```<code># core_sub_xxx.py

import numpy as _np
from .. import core as _cr
</code>```

(of course you'll have to replace all occurrences of 'np' and 'cr' but any half-decent text editor can do this)

This doesn't prevent access to mysubmodule._cr or mysubmodule._np but at least it makes it clear that one should NOT access those names.

But really, this is not a big issue, as long as your API is clearly documented.

Body:
I am currently packaging my own module for distribution. In general everything is working fine, but fine-tuning/best-practice for structuring sub-modules is giving me some trouble.

Assuming a module structure of:

mdl
├── mdl
│   ├── __init__.py
│   ├── core.py
|   ├── sub_one
|   |   ├── __init__.py
|   |   └── core_sub_one.py
|   └── sub_two
|       ├── __init__.py
|       └── core_sub_two.py
├── README
└── setup.py

core file headers

With the header of core.py starting with:

import numpy as np

...some fairly large module code...

And the headers of both core_sub_one.py and core_sub_two.py starting with:

import numpy as np

from .. import core as cr

So all submodules require np and cr.

init.py structure

The mdl/__init__.py (core-level) looks like:

from . import sub_one as so
from . import sub_two as st

And __init__.py of both submodules looks like (replace one with two for the other submodule):

from . import core_sub_one
from .core_sub_one import *

I've "learnt" this structure from numpy, see f.i. numpy/ma/__init__.py

Problem description

Now I've got some trouble with the submodule-access after running setup.py and importing my module with import mdl.

I can now access my submodules with f.i. mdl.so.some_function_in_sub_one(). This is expected and what I want.

But I can also access the top level module cr and numpy with mdl.so.cr and mdl.so.np, which I want to avoid. Is there any way to avoid this?
If not: Is there any drawback of importing/connecting modules and submodules like this?

And is there any best practice for how to import libraries like numpy in sub-modules, when they are required in all submodules?

Edit:

Since some seem to have trouble with the fact that asking for best practice is opinion based (which I know and which I intended, since imho most design decisions in real life are not clear binary 1-0 decisions), I have to add:

I want to comply with the module packaging style used in the scipy, and more specifically numpy, package environment. So if these packages found a solution for any of the questions I asked, this will be the most welcome solution for me.

Body:
First thing first:

from .core_sub_one import *

DONT DO THIS. Yes, even if you seen it in some "big name" package, read it in some tutorials or whatever. This is officially considered bad practice, and for good reasons (from experience, it's a maintaince hell).

If you really really insist on doing this (but seriously, don't), at least define an explicit __all__ var in those modules so you keep exposed names under control (and it helps documenting what's supposed to be part of the module's API).

But I can also access the top level module cr and numpy with mdl.so.cr and mdl.so.np, which I want to avoid. Is there any way to avoid this?

Not really. If you're really worried about it, you can import those names as "protected" in your submodules:

# core_sub_xxx.py

import numpy as _np
from .. import core as _cr

(of course you'll have to replace all occurrences of 'np' and 'cr' but any half-decent text editor can do this)

This doesn't prevent access to mysubmodule._cr or mysubmodule._np but at least it makes it clear that one should NOT access those names.

But really, this is not a big issue, as long as your API is clearly documented.


问:
How can I list Kafka consumer groups using Confluent's .NET Client
I have installed Kafka on my development windows machine (kafka_2.11-2.4.0.tgz). It all works fine and I'm able to send and receive messages using the sample batch scripts.

Trying to build a C# windows application, I'm using Confluent's .NET Client for Apache Kafka (version 1.3.0.0) on a C# windows application. However when I'm using the sample given by Confluent to list the group subscriptions I'm getting the error System.ArgumentNullException: 'Argument 'group' must not be null. Parameter name: group' but there is no such argument that I pass into the method. Here's the code sample:

```<code>private static string ListConsumerGroups(string bootstrapServers) {
    string s = ($"Consumer Groups:");
    using (var adminClient = new AdminClientBuilder(new AdminClientConfig { BootstrapServers = bootstrapServers }).Build()) {
        var groups = adminClient.ListGroups(TimeSpan.FromSeconds(10));
        foreach (var g in groups) {
            s += "\r\n" + ($"  Group: {g.Group} {g.Error} {g.State}");
            s += "\r\n" + ($"  Broker: {g.Broker.BrokerId} {g.Broker.Host}:{g.Broker.Port}");
            s += "\r\n" + ($"  Protocol: {g.ProtocolType} {g.Protocol}");
            s += "\r\n" + ($"  Members:");
            foreach (var m in g.Members) {
                s += "\r\n" + ($"    {m.MemberId} {m.ClientId} {m.ClientHost}");
                s += "\r\n" + ($"    Metadata: {m.MemberMetadata.Length} bytes");
                s += "\r\n" + ($"    Assignment: {m.MemberAssignment.Length} bytes");
            }
        }
    }
    return s;
}
</code>```

The code fails when making the call to adminClient.ListGroups with the timespan argument (no other arguments allowed into this method). I dont understand whether there is a bug in the API or I'm just missing something.
When using the batch scripts to list the consumer group I do get a valid answer back.

> kafka-consumer-groups.bat --list --bootstrap-server "localhost:9092"

答: this was a regression introduced in v1.3.0. It's resolved in v1.4.0-RC1 and later.</p>

Body:
I have installed Kafka on my development windows machine (kafka_2.11-2.4.0.tgz). It all works fine and I'm able to send and receive messages using the sample batch scripts.

Trying to build a C# windows application, I'm using Confluent's .NET Client for Apache Kafka (version 1.3.0.0) on a C# windows application. However when I'm using the sample given by Confluent to list the group subscriptions I'm getting the error System.ArgumentNullException: 'Argument 'group' must not be null. Parameter name: group' but there is no such argument that I pass into the method. Here's the code sample:

private static string ListConsumerGroups(string bootstrapServers) {
    string s = ($"Consumer Groups:");
    using (var adminClient = new AdminClientBuilder(new AdminClientConfig { BootstrapServers = bootstrapServers }).Build()) {
        var groups = adminClient.ListGroups(TimeSpan.FromSeconds(10));
        foreach (var g in groups) {
            s += "\r\n" + ($"  Group: {g.Group} {g.Error} {g.State}");
            s += "\r\n" + ($"  Broker: {g.Broker.BrokerId} {g.Broker.Host}:{g.Broker.Port}");
            s += "\r\n" + ($"  Protocol: {g.ProtocolType} {g.Protocol}");
            s += "\r\n" + ($"  Members:");
            foreach (var m in g.Members) {
                s += "\r\n" + ($"    {m.MemberId} {m.ClientId} {m.ClientHost}");
                s += "\r\n" + ($"    Metadata: {m.MemberMetadata.Length} bytes");
                s += "\r\n" + ($"    Assignment: {m.MemberAssignment.Length} bytes");
            }
        }
    }
    return s;
}

The code fails when making the call to adminClient.ListGroups with the timespan argument (no other arguments allowed into this method). I dont understand whether there is a bug in the API or I'm just missing something.
When using the batch scripts to list the consumer group I do get a valid answer back.

> kafka-consumer-groups.bat --list --bootstrap-server "localhost:9092"


问:
Is there an kotlin equivalent of ?: java operator?
Reluctant kotlin newbie here.

Is there an kotlin equivalent of ?: java operator?

I tried searching on google. Most results talk about ?: (elvis operator) in kotlin.

Looking for a way to write this in kotlin:

```<code>//java example
//return condition ? a : b;
</code>```

答:
kotlin doesn't have ternary operator, but you can use if, when, try catch as expression

```<code>return if (condition) a else b
</code>```

Body:
Reluctant kotlin newbie here.

Is there an kotlin equivalent of ?: java operator?

I tried searching on google. Most results talk about ?: (elvis operator) in kotlin.

Looking for a way to write this in kotlin:

//java example
//return condition ? a : b;

Body:
kotlin doesn't have ternary operator, but you can use if, when, try catch as expression

return if (condition) a else b


问:
How can i redirect to an Angular router link with oauth2 login?
I want to make an oauth2 login with Twitch on my website and I have an angular2 website and I'm working with router links.
When I want to log me in with twitch acc to say yes it is me and so everything is fine. Ok the end not xD

When i go to the twitch oauth2 for authorizing i need an redirectUri. My problem is now how can i make this in angular2? Because I can't type www.page.com/app/afterlogin/afterlogin.php or somethink like that.

I need this because I need from the user the access token, I dont want that he need to authorize himself x times.

Maybe this helps for helping me:

```<code>https://api.twitch.tv/kraken/oauth2/authorize?client_id=[client_id]&redirect_uri=http://www.page.com/app/AfterLogin/afterlogin.php&response_type=code&scope=user_read
</code>```

I hope someone can help me with redirecting and some oauth2 logins :)

答:
Let me assume a RESTful backend with Single Page Application front and answer the question. The process in general is like the following

Your SPA --> Your Server --> Your Provider --> Your Browser --> Your Provider --> Your Server --> Your SPA

Your SPA => initializes login and passess redirect_uri

Your Server => Stores redirect_uri in a cookie and sends request to
provider

Your Provider => Gets Success and Failure Urls and loads login page
to your browser

Your Browser => Loads the provider login page

Your Provider => Sends request to your server success or failure
handler

Your Server => Extracts the redirect_uri and redirects the browser
to it

Your SPA => Gets afterLoginUrl from redirect_uri and route the
user to it

Below are the steps to achieve this

When your front end sends the authentication request to your server,
append the redirect_uri. In that url, pass a afterLoginUrl query
parameter. That is used by your front end SPA to route the user to
the specific page that triggered the login. (i.e. If the request has
been triggered by a user trying to access
{base_uri}/profile/project/projects for example, it is a good
practice to route the user to this page rather than to the default
page that a normal login takes to like base_uri/profile/about). As
a result you will have a url that looks like the following.

```<code>`http://localhost:8080/oauth2/authorize/google?redirect_uri=http://localhost:4200/oauth2/redirect&afterLoginUrl=/profile/project/projects`
</code>```

port 8080 being for the back end and 4200 for the front end.

Since you are using a RESTful service, you don't have a way by which you can save the redirect_uri on your server (since REST is stateless). Because of this you need to send it with the request you send to the provider as a cookie.

When the success is received from the provider, you will know which route of your SPA to hit by extracting the cookie you sent. Then you dedicate a route to handle your request from your own server (in my case oauth2/redirect) in your front end app.

On the component specified for the route in step 3 you will receive token and afterLoginUrl(if there is). You will have something like the following on the url

http://localhost:4200/oauth2/redirect?afterLoginUrl=/profile/project/projects&token={token value}

Verify your token, check whether or not there is afterLoginUrl and redirect to the route specified by afterLoginUrl if there is one or to the default profile page if there isn't.

I think a wonderful resource can be found here.

Body:
I want to make an oauth2 login with Twitch on my website and I have an angular2 website and I'm working with router links.
When I want to log me in with twitch acc to say yes it is me and so everything is fine. Ok the end not xD

When i go to the twitch oauth2 for authorizing i need an redirectUri. My problem is now how can i make this in angular2? Because I can't type www.page.com/app/afterlogin/afterlogin.php or somethink like that.

I need this because I need from the user the access token, I dont want that he need to authorize himself x times.

Maybe this helps for helping me:

https://api.twitch.tv/kraken/oauth2/authorize?client_id=[client_id]&redirect_uri=http://www.page.com/app/AfterLogin/afterlogin.php&response_type=code&scope=user_read

I hope someone can help me with redirecting and some oauth2 logins :)

Body:
Let me assume a RESTful backend with Single Page Application front and answer the question. The process in general is like the following

Your SPA --> Your Server --> Your Provider --> Your Browser --> Your Provider --> Your Server --> Your SPA

Your SPA => initializes login and passess redirect_uri

Your Server => Stores redirect_uri in a cookie and sends request to
provider

Your Provider => Gets Success and Failure Urls and loads login page
to your browser

Your Browser => Loads the provider login page

Your Provider => Sends request to your server success or failure
handler

Your Server => Extracts the redirect_uri and redirects the browser
to it

Your SPA => Gets afterLoginUrl from redirect_uri and route the
user to it

Below are the steps to achieve this

When your front end sends the authentication request to your server,
append the redirect_uri. In that url, pass a afterLoginUrl query
parameter. That is used by your front end SPA to route the user to
the specific page that triggered the login. (i.e. If the request has
been triggered by a user trying to access
{base_uri}/profile/project/projects for example, it is a good
practice to route the user to this page rather than to the default
page that a normal login takes to like base_uri/profile/about). As
a result you will have a url that looks like the following.

`http://localhost:8080/oauth2/authorize/google?redirect_uri=http://localhost:4200/oauth2/redirect&afterLoginUrl=/profile/project/projects`

port 8080 being for the back end and 4200 for the front end.

Since you are using a RESTful service, you don't have a way by which you can save the redirect_uri on your server (since REST is stateless). Because of this you need to send it with the request you send to the provider as a cookie.

When the success is received from the provider, you will know which route of your SPA to hit by extracting the cookie you sent. Then you dedicate a route to handle your request from your own server (in my case oauth2/redirect) in your front end app.

On the component specified for the route in step 3 you will receive token and afterLoginUrl(if there is). You will have something like the following on the url

http://localhost:4200/oauth2/redirect?afterLoginUrl=/profile/project/projects&token={token value}

Verify your token, check whether or not there is afterLoginUrl and redirect to the route specified by afterLoginUrl if there is one or to the default profile page if there isn't.

I think a wonderful resource can be found here.


问:
Angular7, get ElementRef
i need to get ElementRef in child nodes.

my template

```<code><div #charts *ngFor="let tag of _tags">
  <jqxBulletChart
    style="margin-left: 10px; float: left;"
    [width]='50'
    [height]='350'
    [barSize]='"35%"'
    [labelsFormat]='"c"'
    [title]="''"
    description="{{tag.configuration.name}}"
    [showTooltip]='true'
    [labelsFormatFunction]="labelsFormatFunction"
    [tooltipFormatFunction]="tooltipFormatFunction" [ticks]='ticks'
    [ranges]='tag.value'
    [pointer]='pointer'
    [orientation]="'vertical'"
  >
  </jqxBulletChart>
</div>
</code>```

I call to

@ViewChildren('charts') infoCharts: ElementRef;

and get child

```<code>for (let chart of this.arrCharts) {
            console.log(chart);
            console.log(chart.nativeElement.lastChild)
            let child: jqxBulletChartComponent = chart.nativeElement.lastChild;
            console.log(child);
            console.log(+this.tags[count].displayValue);
            child.val(+this.tags[count].displayValue || 0);
            // child.val(20);
            count++;
        }
</code>```

but my "child"  should be ElementRef type, and i don't know how to do it

答:
Please try below code it will give you the ElementRef for jqxBulletChart

```<code>@ViewChildren(jqxBulletChartComponent,{read: ElementRef}) hellos: QueryList<ElementRef>;
</code>```

Please note that you need to provide the JQXBulletChartComponent and you must read the viewChildren as ElementRef.

Let me know if it works for you.

Happy Coding!!!

Title: Angular7, get ElementRef

Body:
i need to get ElementRef in child nodes.

my template

  <jqxBulletChart
    style="margin-left: 10px; float: left;"
    [width]='50'
    [height]='350'
    [barSize]='"35%"'
    [labelsFormat]='"c"'
    [title]="''"
    description="{{tag.configuration.name}}"
    [showTooltip]='true'
    [labelsFormatFunction]="labelsFormatFunction"
    [tooltipFormatFunction]="tooltipFormatFunction" [ticks]='ticks'
    [ranges]='tag.value'
    [pointer]='pointer'
    [orientation]="'vertical'"
  >
  </jqxBulletChart>

I call to

@ViewChildren('charts') infoCharts: ElementRef;

and get child

for (let chart of this.arrCharts) {
            console.log(chart);
            console.log(chart.nativeElement.lastChild)
            let child: jqxBulletChartComponent = chart.nativeElement.lastChild;
            console.log(child);
            console.log(+this.tags[count].displayValue);
            child.val(+this.tags[count].displayValue || 0);
            // child.val(20);
            count++;
        }

but my "child"  should be ElementRef type, and i don't know how to do it

Body:
Please try below code it will give you the ElementRef for jqxBulletChart

@ViewChildren(jqxBulletChartComponent,{read: ElementRef}) hellos: QueryList<ElementRef>;

Please note that you need to provide the JQXBulletChartComponent and you must read the viewChildren as ElementRef.

Let me know if it works for you.

Happy Coding!!!