问:
Dependency injection for a bundle controller
I have a simple, working SecurityController that I would like to turn into a bundle so that I can share basic authentication functionality across a few basic websites I create. Everything is working as desired until I try to turn my code into a bundle.

I have created my bundle class, a Resources/config/routing.xml file to declare my login and logout routes, have a template in Resources/views/Security/login.html.twig but the following class is throwing an error.

```<code><!-- Controller/SecurityController.php -->
<?php

namespace JustinVoelker\EssentialSecurityBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;

class SecurityController extends AbstractController
{
    private $authenticationUtils;

    public function __construct(AuthenticationUtils $authenticationUtils)
    {
        $this->authenticationUtils = $authenticationUtils;
    }

    public function loginAction()
    {
        $error = $this->authenticationUtils->getLastAuthenticationError();

        return $this->render('@EssentialSecurity/Security/login.html.twig', [
            'error' => $error,
        ]);
    }

    ... Comments and additional functions removed for simplicity

}
</code>```

The error I am getting when I go to the login page is Controller "JustinVoelker\EssentialSecurityBundle\Controller\SecurityController" has required constructor arguments and does not exist in the container. Did you forget to define such a service?

Following a few different examples/tutorials, I tried creating a services.xml file and loading it via DependencyInjection/EssentialSecurityExtension.php in an attempt to make AuthenticationUtils available to my constructor but that does not appear to change anything.

```<code><!-- DependencyInjection/EssentialSecurityExtension.php -->
<?php

namespace JustinVoelker\EssentialSecurityBundle\DependencyInjection;

use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Extension\Extension;
use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;

class EssentialSecurityExtension extends Extension
{
    public function load(array $configs, ContainerBuilder $container)
    {
        $loader = new XmlFileLoader(
            $container,
            new FileLocator(__DIR__.'/../Resources/config')
        );
        $loader->load('services.xml');
    }
}
</code>```

```<code><!-- Resources/config/services.xml -->
<?xml version="1.0" encoding="UTF-8" ?>

<container xmlns="http://symfony.com/schema/dic/services"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">
    <services>
        <service id="essential_security.controller"
                 class="JustinVoelker\EssentialSecurityBundle\Controller\SecurityController">
            <argument type="service" id="security.authentication_utils"/>
        </service>
    </services>
</container>
</code>```

What am I missing that allows me to use dependency injection inside a bundle as I was able to before moving this code into a bundle?

If I simply remove any reference to AuthenticationUtils (the private property, the entire constructor, and its usage inside loginAction) the page renders, though it will not function as desired without that last authentication error that I am using AuthenticationUtils for in the first place.

Side note, if I manually add JustinVoelker\EssentialSecurityBundle\Controller\SecurityController: ~ to my applications main config/services.xml file, The controller error disappears so clearly I'm missing something inside my bundle to make this work.

Perhaps there is another way to achieve my ultimate end goal of returning the last authentication error message to the login page, but my question is what am I missing that is preventing this dependency injection from working as it did before I bundled my controller and as it appears to work in so many examples I've seen.

EDIT 2019-05-30 Including a portion of my original routing.xml

```<code><route id="essential_security_login" path="/login">
    <default key="_controller">EssentialSecurityBundle:Security:login</default>
</route>
</code>```

答:
Looks like in your routing you use JustinVoelker\EssentialSecurityBundle\Controller\SecurityController but your service name is essential_security.controller
You should either change your routing or service definition

You can add an alias

<service id="JustinVoelker\EssentialSecurityBundle\Controller\SecurityController" alias="essential_security.controller"/>

<service id="essential_security.controller" class="JustinVoelker\EssentialSecurityBundle\Controller\SecurityController">
    <argument type="service" id="security.authentication_utils"/>
    <tag name="controller.service_arguments"/>
</service>
```

<p>or just rename it (note you can omit <code>class</code> parameter)</p>

<pre class="lang-xml prettyprint-override"><code><!-- Resources/config/services.xml -->
<service id="JustinVoelker\EssentialSecurityBundle\Controller\SecurityController">
    <argument type="service" id="security.authentication_utils"/>
    <tag name="controller.service_arguments"/>
</service>
</code>```

or in your routing:

```<code>route_name:
    path:     /path
    controller: JustinVoelker\EssentialSecurityBundle\Controller\SecurityController::loginAction
</code>```

```<code>route_name:
    path:     /path
    controller: essential_security.controller::loginAction
</code>```

depends on your service name

Body:
I have a simple, working SecurityController that I would like to turn into a bundle so that I can share basic authentication functionality across a few basic websites I create. Everything is working as desired until I try to turn my code into a bundle.

I have created my bundle class, a Resources/config/routing.xml file to declare my login and logout routes, have a template in Resources/views/Security/login.html.twig but the following class is throwing an error.

<?php

namespace JustinVoelker\EssentialSecurityBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;

class SecurityController extends AbstractController
{
    private $authenticationUtils;

    public function __construct(AuthenticationUtils $authenticationUtils)
    {
        $this->authenticationUtils = $authenticationUtils;
    }

    public function loginAction()
    {
        $error = $this->authenticationUtils->getLastAuthenticationError();

        return $this->render('@EssentialSecurity/Security/login.html.twig', [
            'error' => $error,
        ]);
    }

    ... Comments and additional functions removed for simplicity

}

The error I am getting when I go to the login page is Controller "JustinVoelker\EssentialSecurityBundle\Controller\SecurityController" has required constructor arguments and does not exist in the container. Did you forget to define such a service?

Following a few different examples/tutorials, I tried creating a services.xml file and loading it via DependencyInjection/EssentialSecurityExtension.php in an attempt to make AuthenticationUtils available to my constructor but that does not appear to change anything.

<?php

namespace JustinVoelker\EssentialSecurityBundle\DependencyInjection;

use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Extension\Extension;
use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;

class EssentialSecurityExtension extends Extension
{
    public function load(array $configs, ContainerBuilder $container)
    {
        $loader = new XmlFileLoader(
            $container,
            new FileLocator(__DIR__.'/../Resources/config')
        );
        $loader->load('services.xml');
    }
}

<?xml version="1.0" encoding="UTF-8" ?>

<container xmlns="http://symfony.com/schema/dic/services"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">
    <services>
        <service id="essential_security.controller"
                 class="JustinVoelker\EssentialSecurityBundle\Controller\SecurityController">
            <argument type="service" id="security.authentication_utils"/>
        </service>
    </services>
</container>

What am I missing that allows me to use dependency injection inside a bundle as I was able to before moving this code into a bundle?

If I simply remove any reference to AuthenticationUtils (the private property, the entire constructor, and its usage inside loginAction) the page renders, though it will not function as desired without that last authentication error that I am using AuthenticationUtils for in the first place.

Side note, if I manually add JustinVoelker\EssentialSecurityBundle\Controller\SecurityController: ~ to my applications main config/services.xml file, The controller error disappears so clearly I'm missing something inside my bundle to make this work.

Perhaps there is another way to achieve my ultimate end goal of returning the last authentication error message to the login page, but my question is what am I missing that is preventing this dependency injection from working as it did before I bundled my controller and as it appears to work in so many examples I've seen.

EDIT 2019-05-30 Including a portion of my original routing.xml

<route id="essential_security_login" path="/login">
    <default key="_controller">EssentialSecurityBundle:Security:login</default>
</route>

Body:
Looks like in your routing you use JustinVoelker\EssentialSecurityBundle\Controller\SecurityController but your service name is essential_security.controller
You should either change your routing or service definition

You can add an alias

<!-- Resources/config/services.xml -->
<service id="JustinVoelker\EssentialSecurityBundle\Controller\SecurityController" alias="essential_security.controller"/>

<service id="essential_security.controller" class="JustinVoelker\EssentialSecurityBundle\Controller\SecurityController">
    <argument type="service" id="security.authentication_utils"/>
    <tag name="controller.service_arguments"/>
</service>

or just rename it (note you can omit class parameter)

<!-- Resources/config/services.xml -->
<service id="JustinVoelker\EssentialSecurityBundle\Controller\SecurityController">
    <argument type="service" id="security.authentication_utils"/>
    <tag name="controller.service_arguments"/>
</service>

or in your routing:

route_name:
    path:     /path
    controller: JustinVoelker\EssentialSecurityBundle\Controller\SecurityController::loginAction

route_name:
    path:     /path
    controller: essential_security.controller::loginAction

depends on your service name


来源: stackexchange

问:
How to specify the type of an "async as" variable?
I get the error Argument of type '() => Observable<Device[]>' is not assignable to parameter of type 'Promise<any>' from this markup:

```<code><div *ngIf="(deviceStoreService.getDevices | async) as devices">
  <tr *ngFor="let device of devices">
    <td>{{device.name}} <midi-keyboard [device]="device"></midi-keyboard></td>
  </tr>
</div>
</code>```

I get the same error from this markup:

```<code><tr *ngFor="let device of (deviceStoreService.getDevices | async)">
  <td>{{device.name}} <midi-keyboard [device]="device"></midi-keyboard></td>
</tr>
</code>```

I don't get the error if I assign a controller class member variable, with the markup:

```<code><tr *ngFor="let device of (devices | async)">
  <td>{{device.name}} <midi-keyboard [device]="device"></midi-keyboard></td>
</tr>
</code>```

and the controller class:

```<code>export class DeviceComponent implements OnInit {

  devices: Observable<Array<Device>>;

  constructor(
    private deviceStoreService: DeviceStoreService,
  ) { }

  ngOnInit() {
    this.devices = this.deviceStoreService.getDevices();
  }
</code>```

Why is this ?

答:
You're missing the parens. If getDevices is a function, then

```<code><div *ngIf="(deviceStoreService.getDevices() | async) as devices">
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I get the error Argument of type '() => Observable<Device[]>' is not assignable to parameter of type 'Promise<any>' from this markup:

    {{device.name}} <midi-keyboard [device]="device"></midi-keyboard>

I get the same error from this markup:

  {{device.name}} <midi-keyboard [device]="device"></midi-keyboard>

I don't get the error if I assign a controller class member variable, with the markup:

  {{device.name}} <midi-keyboard [device]="device"></midi-keyboard>

and the controller class:

export class DeviceComponent implements OnInit {

  devices: Observable<Array<Device>>;

  constructor(
    private deviceStoreService: DeviceStoreService,
  ) { }

  ngOnInit() {
    this.devices = this.deviceStoreService.getDevices();
  }

Why is this ?

Body:
You're missing the parens. If getDevices is a function, then

<div *ngIf="(deviceStoreService.getDevices() | async) as devices">


问:
How to bypass keycloak consent screen for ext-idm users if user already present in keycloak and want to link automatically
We have configured a SAML based ext-idp with keycloak. Now we are trying to onboard users from ext-idm to keycloak. Usecase is, same user is already present in keycloak and same user is trying to login from ext-idm. Now keycloak is showing a consent page for linking the user. Is there a way to bypass this consent and link the ext-idm user to keycloak user?

For all Client Scopes in keycloak we disabled the 'Display On Consent Screen' option.
All clients 'Consent Required' is disabled.
Both changes did not help.

After disabling consent in Client scope we expected ext-idm users auto link with keycloak user. But as of now Keycloak asks for a consent before linking.

答:
Probably you changed a SAML client (SAML SP) settings but you need to change Identity Brokering (SAML IdP) settings. Please read this section:

https://www.keycloak.org/docs/latest/server_admin/index.html#automatically-link-existing-first-login-flow


问:
Oracle 10G driver with Weblogic 10.3
Which JDBC driver should I use to connect Oracle 10G from Weblogic 10.3. I am presently using Weblogic's oracle driver in development . Can I use it in production environment ?</p>

答: Use the Oracle Thin Driver if possible.</p>

ContentLicense: CC BY-SA 3.0

Title: Oracle 10G driver with Weblogic 10.3

Body: Use the Oracle Thin Driver if possible.


Title: format data with year and moth presence javascript

Body:
I have this kind of json object

[  {
    "camera_name": "Bolands Mills Arup",
    "exid": "bolands-mills-arup",
    "latest_snapshot_date": "2019-05-30T07:06:55+01:00",
    "oldest_snapshot_date": "2015-12-24T23:33:23+00:00",
    "years": {
      "2015": [
        "12"
      ],
      "2016": [
        "04",
        "08",
        "09",
        "10",
        "02",
        "06",
        "03",
        "11",
        "12",
        "01",
        "07",
        "05"
      ],
      "2017": [
        "04",
        "07",
        "10",
        "09",
        "11",
        "01",
        "02",
        "03",
        "05",
        "06",
        "08",
        "11",
        "12"
      ],
      "2018": [
        "03",
        "05",
        "06",
        "10",
        "11",
        "01",
        "02",
        "08",
        "09",
        "04",
        "07",
        "11",
        "12"
      ],
      "2019": [
        "01",
        "02",
        "03",
        "04",
        "05"
      ]
    }
  },
  {
    "camera_name": "Walls Demo",
    "exid": "central-bank-fusion",
    "latest_snapshot_date": "2019-05-30T07:07:02+01:00",
    "oldest_snapshot_date": "2015-11-08T16:30:48+00:00",
    "years": {
      "2015": [
        "12",
        "11"
      ],
      "2016": [
        "02",
        "03",
        "05"
      ],
      "2017": [
        "03",
        "08",
        "10",
        "02",
        "04",
        "05",
        "06",
        "07",
        "09",
        "11",
        "01",
        "11",
        "12"
      ],
      "2018": [
        "03",
        "04",
        "07",
        "09",
        "01",
        "02",
        "08",
        "10",
        "11",
        "05",
        "06",
        "11",
        "12"
      ],
      "2019": [
        "01",
        "02",
        "03",
        "04",
        "05"
      ]
    }
  }
]

And I have a parameter with the name of the year, whom value can be 2015 to 2019. What I am trying to do is create a method which will formate this data with year and months values.

I have this pattern of months as

 let months_chars = {
    "01":"jan",
    "02":"feb",
    "03":"mar",
    "04":"apr",
    "05":"may",
    "06":"jun",
    "07":"jul",
    "08":"aug",
    "09":"sep",
    "10":"oct",
    "11":"nov",
    "12":"dec"
  }

Year value is being selected by the user, For example, if the user will select 2016 then the lower data will look like this.

  {
    "camera_name": "Walls Demo",
    "exid": "central-bank-fusion",
    "latest_snapshot_date": "2019-05-30T07:07:02+01:00",
    "oldest_snapshot_date": "2015-11-08T16:30:48+00:00",
    "jan": 0,
    "feb": 1,
    "mar": 1,
    "apr": 0,
    "may", 1,
    ...
    "dec": 0
  }

It will go through the years present values if the month is present then it will add months chars and place 1 in front, if not then still place a month and place 0 in front.

Any help would be thankful, I have reached this far with that,

  let months_chars = {
    "01":"jan",
    "02":"feb",
    "03":"mar",
    "04":"apr",
    "05":"may",
    "06":"jun",
    "07":"jul",
    "08":"aug",
    "09":"sep",
    "10":"oct",
    "11":"nov",
    "12":"dec"
  }
  let year = this.year;

  let formatedData =
    data.map((camera) => {
      let present_months = data["years"][`${year}`]

    });

Further, I am unable to format the data as required.

Body:
This should work. Use map() to loop over each object, and loop over each months_chars to check if the years includes the key, and return 1 if true and 0 if false:

const cameras = [{
    "camera_name": "Bolands Mills Arup",
    "exid": "bolands-mills-arup",
    "latest_snapshot_date": "2019-05-30T07:06:55+01:00",
    "oldest_snapshot_date": "2015-12-24T23:33:23+00:00",
    "years": {
      "2015": [
        "12"
      ],
      "2016": [
        "04",
        "08",
        "09",
        "10",
        "02",
        "06",
        "03",
        "11",
        "12",
        "01",
        "07",
        "05"
      ],
      "2017": [
        "04",
        "07",
        "10",
        "09",
        "11",
        "01",
        "02",
        "03",
        "05",
        "06",
        "08",
        "11",
        "12"
      ],
      "2018": [
        "03",
        "05",
        "06",
        "10",
        "11",
        "01",
        "02",
        "08",
        "09",
        "04",
        "07",
        "11",
        "12"
      ],
      "2019": [
        "01",
        "02",
        "03",
        "04",
        "05"
      ]
    }
  },
  {
    "camera_name": "Walls Demo",
    "exid": "central-bank-fusion",
    "latest_snapshot_date": "2019-05-30T07:07:02+01:00",
    "oldest_snapshot_date": "2015-11-08T16:30:48+00:00",
    "years": {
      "2015": [
        "12",
        "11"
      ],
      "2016": [
        "02",
        "03",
        "05"
      ],
      "2017": [
        "03",
        "08",
        "10",
        "02",
        "04",
        "05",
        "06",
        "07",
        "09",
        "11",
        "01",
        "11",
        "12"
      ],
      "2018": [
        "03",
        "04",
        "07",
        "09",
        "01",
        "02",
        "08",
        "10",
        "11",
        "05",
        "06",
        "11",
        "12"
      ],
      "2019": [
        "01",
        "02",
        "03",
        "04",
        "05"
      ]
    }
  }
]

let months_chars = {
  "01": "jan",
  "02": "feb",
  "03": "mar",
  "04": "apr",
  "05": "may",
  "06": "jun",
  "07": "jul",
  "08": "aug",
  "09": "sep",
  "10": "oct",
  "11": "nov",
  "12": "dec"
}

var input = 2016
var obj = cameras.map(({years, ...obj}) => {
  var months = years[input]
  for(var i in months_chars) {
    months.includes(i) ? obj[months_chars[i]] = 1 : obj[months_chars[i]] = 0
  }
  return obj

})

console.log(obj)


问:
Configuring Swashbuckle
I'm having problems getting Swashbuckle to run..

I installed packages:

```<code>PM> Install-Package Microsoft.AspNet.WebApi.WebHost
PM> Install-Package WebActivatorEx
PM> Install-Package Microsoft.AspNet.WebApi.Core
PM> Install-Package Swashbuckle.Core
PM> Install-Package Swashbuckle
</code>```

I cant navigate to /swagger... how can I make my api to get swagger?

答: Link Will guide you because Microsoft is supporting now.</p>

Title: Configuring Swashbuckle

Body:
I'm having problems getting Swashbuckle to run..

I installed packages:

PM> Install-Package Microsoft.AspNet.WebApi.WebHost
PM> Install-Package WebActivatorEx
PM> Install-Package Microsoft.AspNet.WebApi.Core
PM> Install-Package Swashbuckle.Core
PM> Install-Package Swashbuckle

I cant navigate to /swagger... how can I make my api to get swagger?


问:
Retrieving one value from JSON works, but identical approach on the other value fails
The source .json file is as simple as this:

```<code>{
  "rates": {
    "EURUSD": {
      "rate": 1.112656,
      "timestamp": 1559200864
    }
  },
  "code": 200
}
</code>```

I can return the "timestamp" value, but using the identical approach I cannot return the "rate" value.

This runs with no problems:

```<code>Sub current_eur_usd()

  Dim scriptControl As Object
  Set scriptControl = CreateObject("MSScriptControl.ScriptControl")
  scriptControl.Language = "JScript"
  Dim oJSON As Object

  With CreateObject("MSXML2.XMLHTTP")
    .Open "GET", "https://www.freeforexapi.com/api/live?pairs=EURUSD", False
    .send
    Set oJSON = scriptControl.Eval("(" + .responsetext + ")")
    .abort
  End With
  MsgBox oJSON.rates.EURUSD.timestamp   '<<< 'timestamp' works, 'rate' fails

  Set oJSON = Nothing
  Set scriptControl = Nothing
End Sub
</code>```

But when I try to replace timestamp with rate, I get the error message highlighting the MsgBox line.

Run-time error '438':

  Object doesn't support this property or method

I think the problem lies in VBA automatically capitalizing rate.

```<code>MsgBox oJSON.rates.EURUSD.rate
</code>```

auto-transforms into

```<code>MsgBox oJSON.rates.EURUSD.Rate
</code>```

How can I return the "rate" value?

答:
I use this tool to parse the JSON response like this:

```<code>With CreateObject("MSXML2.XMLHTTP")
    .Open "GET", "https://www.freeforexapi.com/api/live?pairs=EURUSD", False
    .send
    Set oJSON = ParseJson(.responseText)
    .abort
End With
</code>```

Try that way, you can loop later to check all the items inside the oJSON like this:
For Each Item in oJSON.Items and see if rates are there.

Body:
The source .json file is as simple as this:

{
  "rates": {
    "EURUSD": {
      "rate": 1.112656,
      "timestamp": 1559200864
    }
  },
  "code": 200
}

I can return the "timestamp" value, but using the identical approach I cannot return the "rate" value.

This runs with no problems:

Sub current_eur_usd()

  Dim scriptControl As Object
  Set scriptControl = CreateObject("MSScriptControl.ScriptControl")
  scriptControl.Language = "JScript"
  Dim oJSON As Object

  With CreateObject("MSXML2.XMLHTTP")
    .Open "GET", "https://www.freeforexapi.com/api/live?pairs=EURUSD", False
    .send
    Set oJSON = scriptControl.Eval("(" + .responsetext + ")")
    .abort
  End With
  MsgBox oJSON.rates.EURUSD.timestamp   '<<< 'timestamp' works, 'rate' fails

  Set oJSON = Nothing
  Set scriptControl = Nothing
End Sub

But when I try to replace timestamp with rate, I get the error message highlighting the MsgBox line.

Run-time error '438':

  Object doesn't support this property or method

I think the problem lies in VBA automatically capitalizing rate.

MsgBox oJSON.rates.EURUSD.rate

auto-transforms into

MsgBox oJSON.rates.EURUSD.Rate

How can I return the "rate" value?

Body:
I use this tool to parse the JSON response like this:

With CreateObject("MSXML2.XMLHTTP")
    .Open "GET", "https://www.freeforexapi.com/api/live?pairs=EURUSD", False
    .send
    Set oJSON = ParseJson(.responseText)
    .abort
End With

Try that way, you can loop later to check all the items inside the oJSON like this:
For Each Item in oJSON.Items and see if rates are there.


问:
Assigning a function call to a variable in Kotlin
Does assigning a variable to a function call actually call the function then or just store it (so it's ready to be called)?

For example does:

```<code>val userData = GraphRequest.newMeRequest(
    accessToken,
    object : GraphRequest.GraphJSONObjectCallback {
        override fun onCompleted(`object`: JSONObject?, response: GraphResponse?) {
            Log.d(TAG, `object`.toString())
        }

    }
)
</code>```

actually call GraphRequest.newMeRequest()?

答:
Yes, that code first calls GraphRequest.newMeRequest(), and assigns its result to userData.

In general, any time you see parens after a function name (or lambda), that will call the function.

If you want a reference to the function without calling it (e.g. to call later, or to return or pass to another function), you can use GraphRequest::newMeRequest.  You'll then need to pass the relevant arguments when you call it.

More info here.

Body:
Does assigning a variable to a function call actually call the function then or just store it (so it's ready to be called)?

For example does:

val userData = GraphRequest.newMeRequest(
    accessToken,
    object : GraphRequest.GraphJSONObjectCallback {
        override fun onCompleted(`object`: JSONObject?, response: GraphResponse?) {
            Log.d(TAG, `object`.toString())
        }

    }
)

actually call GraphRequest.newMeRequest()?


问:
sys.stdin as a file to iterate over
I am writing a script that searches a regex in a file (input is file path), or in stdin in case a '-' was entered instead of a file path.

I did some debugging and I think the problem is on "for i, line in enumerate(file):" because it doesn't go inside there.

When I do this in Python 3.x it works, but in python 2.7 it just doesn't go inside that loop

Here is some part of the script

```<code>def init_parser():
    parser = argparse.ArgumentParser(description="The script searches one or \
                                     more named input files for lines \
                                     containing a match to a regular \
                                     expression pattern.")
    parser.add_argument('regex', help='the regular expression.')
    parser.add_argument('infile', nargs='*', type=argparse.FileType('r'), default='-',
                        help='the name of the file(s) to search.')

    return parser

args = init_parser().parse_args()
for file in args.infile:
    if args.infile == '-':
        file = sys.stdin
    for i, line in enumerate(file):
        substrings = re.finditer(args.regex, line)
        if substrings:
            for substring in substrings:
                    print_line(file.name, i + 1, line[:-1])
</code>```

答:
Python 2 uses a different buffering scheme than Python 3 for iterating over files. It wants to either fill the buffer or see the end of the file before it starts the first iteration. You're typing input into stdin by hand, and you haven't either typed enough to fill the buffer or signaled end-of-file, so you never reach the first iteration.

To iterate over a file without this buffering, you can use two-argument iter. This works in both Python 2 and Python 3:

```<code>for line in iter(file.readline, ''):
    ...
</code>```

Also, you have (at least) two other bugs. First, the following two lines aren't doing what you think they are:

```<code>if args.infile == '-':
    file = sys.stdin
</code>```

args.infile is a sequence of file objects, not a string. You don't notice the bug because argparse.FileType is actually handling - for you.

There's a second bug, that the first bug happens to be hiding. The default value of infile:

```<code>parser.add_argument('infile', nargs='*', type=argparse.FileType('r'), default='-',
                    help='the name of the file(s) to search.')
</code>```

should be [sys.stdin], not '-'. The default value doesn't go through type handling or automatically get wrapped in a list, so you have to do that yourself. Otherwise, this loop:

```<code>for file in args.infile:
</code>```

ends up iterating over the characters of '-' instead of iterating over files.

To fix these bugs, change the default for infile to [sys.stdin], and remove the if args.infile == '-': handling.

Title: sys.stdin as a file to iterate over

Body:
I am writing a script that searches a regex in a file (input is file path), or in stdin in case a '-' was entered instead of a file path.

I did some debugging and I think the problem is on "for i, line in enumerate(file):" because it doesn't go inside there.

When I do this in Python 3.x it works, but in python 2.7 it just doesn't go inside that loop

Here is some part of the script

def init_parser():
    parser = argparse.ArgumentParser(description="The script searches one or \
                                     more named input files for lines \
                                     containing a match to a regular \
                                     expression pattern.")
    parser.add_argument('regex', help='the regular expression.')
    parser.add_argument('infile', nargs='*', type=argparse.FileType('r'), default='-',
                        help='the name of the file(s) to search.')

    return parser

args = init_parser().parse_args()
for file in args.infile:
    if args.infile == '-':
        file = sys.stdin
    for i, line in enumerate(file):
        substrings = re.finditer(args.regex, line)
        if substrings:
            for substring in substrings:
                    print_line(file.name, i + 1, line[:-1])

Body:
Python 2 uses a different buffering scheme than Python 3 for iterating over files. It wants to either fill the buffer or see the end of the file before it starts the first iteration. You're typing input into stdin by hand, and you haven't either typed enough to fill the buffer or signaled end-of-file, so you never reach the first iteration.

To iterate over a file without this buffering, you can use two-argument iter. This works in both Python 2 and Python 3:

for line in iter(file.readline, ''):
    ...

Also, you have (at least) two other bugs. First, the following two lines aren't doing what you think they are:

if args.infile == '-':
    file = sys.stdin

args.infile is a sequence of file objects, not a string. You don't notice the bug because argparse.FileType is actually handling - for you.

There's a second bug, that the first bug happens to be hiding. The default value of infile:

parser.add_argument('infile', nargs='*', type=argparse.FileType('r'), default='-',
                    help='the name of the file(s) to search.')

should be [sys.stdin], not '-'. The default value doesn't go through type handling or automatically get wrapped in a list, so you have to do that yourself. Otherwise, this loop:

for file in args.infile:

ends up iterating over the characters of '-' instead of iterating over files.

To fix these bugs, change the default for infile to [sys.stdin], and remove the if args.infile == '-': handling.


问:
How many times functions can be deployed per project?
visit resource limits - https://cloud.google.com/functions/quotas

Number of functions : The total number of functions that can be deployed per project- 1000 limit.

its means 1000 separated functions can deployed or each function deployed 1000 versions?

答:
Whichever that comes first, same thing....Per project the limit is 1,000 times or versions total in one project.

Then each function size must be <= 100MB for sources and <= 500MB for sources plus modules.

Check here for more.


问:
Swing JTree with Checkbox and JFileChooser
By using JFileChooser I am able to select file and folders getting JList with File Objects and I am showing it with checkbox. Now my requirement is like I want to show the selected file and folder in tree structure with checkbox and the checkbox should be only for root elements not for all child elements.

Example : For Example, I selected folders ABC and PQR which containt sub folders and few files
now on UI It should be display

```<code>Checkbox1 ABC--
          --SubFolders
          .           --SubFolder
          .                      --Files
          --Files
Checkbox2 PQR--
          --SubFolders
          .           --SubFolder
          .                      --Files
          --Files
</code>```

答:
Sounds a bit complicated... as far as the tree goes, there's an online post of code from the OReilly Java Cookbook that might help you:

http://java.codefetch.com/cache?url=http://examples.oreilly.com/javacook2/javacooksrc2.jar&path=gui/FileTree.java&lang=java&qy=jtree+file

Body:
By using JFileChooser I am able to select file and folders getting JList with File Objects and I am showing it with checkbox. Now my requirement is like I want to show the selected file and folder in tree structure with checkbox and the checkbox should be only for root elements not for all child elements.

Example : For Example, I selected folders ABC and PQR which containt sub folders and few files
now on UI It should be display

Checkbox1 ABC--
          --SubFolders
          .           --SubFolder
          .                      --Files
          --Files
Checkbox2 PQR--
          --SubFolders
          .           --SubFolder
          .                      --Files
          --Files


问:
Why I get more then one window per key in flink session window
My requirements is to check if both begin and success events in a session. I use session window, of course.But it seems there're overlapped windows per key. I've searched online and couldn't know why.

Data format: myForm(timestamp, roomId, role, sessionId, event), for example:

```<code>myform(1559128942, 123, kid, 37890, begin) # timestamp equals to 2019-05-29 19:22:22.605
myform(1559128944, 123, kid, 37890, success) # timestamp equals to 2019-05-29 19:22:24.844
myform(1559129977, 456, kid, 38239, begin) # timestamp equals to 2019-05-29 19:39:37
...
</code>```

session may have only one pair of begin and success events, may also several pairs of events of begin and sucess events.

event may arrive late, and is allowed late to maxinum 3 minutes.

My key is roomId + role + sessionId like '123_kid_37890', seesionGap is 60s

// use event time
env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime)
val stream = ... // from kafka, steam of myform
val sessionStream = stream
    .assignTimestampsAndWatermarks(new MyFormEventWatermarks(0L))
    .keyBy(mf => mf.roomId + "_" + mf.role + "_" + mf.sessionId)
 .window(EventTimeSessionWindows.withGap(Time.milliseconds(60 * 1000L))
.allowedLateness(Time.minutes(3))
.apply(myFormWindowFunction)

//MyFormEventWatermarks is :
class MyFormEventWatermarks[T <: AbstractForm](dely: Long) extends AssignerWithPeriodicWatermarks[T] {

  private var currentMaxTimestamp = Long.MinValue
  val maxOutOfOrderness = dely

  @transient
  var waterMark : Watermark = null

  override def getCurrentWatermark: Watermark = {
    if (currentMaxTimestamp == Long.MinValue){
      waterMark = new Watermark(Long.MinValue)
      waterMark
    }
    else{
      waterMark = new Watermark(currentMaxTimestamp - maxOutOfOrderness)
      waterMark
    }
  }

  override def extractTimestamp(data: T, previousElementTimestamp: Long): Long = {
    val timestamp = data.timestamp
    currentMaxTimestamp = Math.max(timestamp, currentMaxTimestamp)
    timestamp
  }

}

//window func is
class myFormWindowFunction extends RichWindowFunction ... {
    ...
    override def apply(key: String, window: TimeWindow, input: Iterable[myForm], out: Collector[List[myForm]]): Unit = {
        println("window is " + window.getStart() + "-" + window.getEnd() + "|" + data.tostring)

    }
    ...

}
```

<p>In method <code>apply</code> of <code>myFormWindowFunction</code>, results of <code>println</code> like:</p>

```// like this session data:
myform(1559128942, 123, kid, 37890, begin) # timestamp equals to 2019-05-29 19:22:22.605
myform(1559128944, 123, kid, 37890, success) # timestamp equals to 2019-05-29 19:22:24.844
```

I got a window of 2019-05-29 19:22:22.605- 2019-05-29 19:23:22.605,data is myform(1559128942, 123, kid, 37890, begin), then I got a second window of 2019-05-29 19:22:22.605 - 2019-05-29 19:23:24.844and data is myform(1559128942, 123, kid, 37890, begin), myform(1559128944, 123, kid, 37890, success).
It looks like window initalize to (2019-05-29 19:22:22.605, 2019-05-29 19:23:22.605) and (2019-05-29 19:22:24.844, 2019-05-29 19:23:24.844), and onMerge method merged but not 'droped' window (2019-05-29 19:22:22.605, 2019-05-29 19:23:22.605). I've looked up the source function of EventTimeSessionWindows and examples of flink session window, and still don't known where program goes wrong?

答: I've found the problem, I made a misunderstanding of allowedLateness. When it's used, window is saved and when window  + allowedLateness time arrives, window will be triggered again.</p>

Body:
My requirements is to check if both begin and success events in a session. I use session window, of course.But it seems there're overlapped windows per key. I've searched online and couldn't know why.

Data format: myForm(timestamp, roomId, role, sessionId, event), for example:

myform(1559128942, 123, kid, 37890, begin) # timestamp equals to 2019-05-29 19:22:22.605
myform(1559128944, 123, kid, 37890, success) # timestamp equals to 2019-05-29 19:22:24.844
myform(1559129977, 456, kid, 38239, begin) # timestamp equals to 2019-05-29 19:39:37
...

session may have only one pair of begin and success events, may also several pairs of events of begin and sucess events.

event may arrive late, and is allowed late to maxinum 3 minutes.

My key is roomId + role + sessionId like '123_kid_37890', seesionGap is 60s

// use event time
env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime)
val stream = ... // from kafka, steam of myform
val sessionStream = stream
    .assignTimestampsAndWatermarks(new MyFormEventWatermarks(0L))
    .keyBy(mf => mf.roomId + "_" + mf.role + "_" + mf.sessionId)
 .window(EventTimeSessionWindows.withGap(Time.milliseconds(60 * 1000L))
.allowedLateness(Time.minutes(3))
.apply(myFormWindowFunction)

//MyFormEventWatermarks is :
class MyFormEventWatermarks[T <: AbstractForm](dely: Long) extends AssignerWithPeriodicWatermarks[T] {

  private var currentMaxTimestamp = Long.MinValue
  val maxOutOfOrderness = dely

  @transient
  var waterMark : Watermark = null

  override def getCurrentWatermark: Watermark = {
    if (currentMaxTimestamp == Long.MinValue){
      waterMark = new Watermark(Long.MinValue)
      waterMark
    }
    else{
      waterMark = new Watermark(currentMaxTimestamp - maxOutOfOrderness)
      waterMark
    }
  }

  override def extractTimestamp(data: T, previousElementTimestamp: Long): Long = {
    val timestamp = data.timestamp
    currentMaxTimestamp = Math.max(timestamp, currentMaxTimestamp)
    timestamp
  }

}

//window func is
class myFormWindowFunction extends RichWindowFunction ... {
    ...
    override def apply(key: String, window: TimeWindow, input: Iterable[myForm], out: Collector[List[myForm]]): Unit = {
        println("window is " + window.getStart() + "-" + window.getEnd() + "|" + data.tostring)

    }
    ...

}

In method apply of myFormWindowFunction, results of println like:

// like this session data:
myform(1559128942, 123, kid, 37890, begin) # timestamp equals to 2019-05-29 19:22:22.605
myform(1559128944, 123, kid, 37890, success) # timestamp equals to 2019-05-29 19:22:24.844

I got a window of 2019-05-29 19:22:22.605- 2019-05-29 19:23:22.605,data is myform(1559128942, 123, kid, 37890, begin), then I got a second window of 2019-05-29 19:22:22.605 - 2019-05-29 19:23:24.844and data is myform(1559128942, 123, kid, 37890, begin), myform(1559128944, 123, kid, 37890, success).
It looks like window initalize to (2019-05-29 19:22:22.605, 2019-05-29 19:23:22.605) and (2019-05-29 19:22:24.844, 2019-05-29 19:23:24.844), and onMerge method merged but not 'droped' window (2019-05-29 19:22:22.605, 2019-05-29 19:23:22.605). I've looked up the source function of EventTimeSessionWindows and examples of flink session window, and still don't known where program goes wrong?


问:
Start/Stop receiving data on UDP port on a timed interval
I have a function that listens for UDP packets on a specific port. Whenever I receive data, I want the function to STOP receiving data on that port, wait 5 seconds, then resume listening for data. The basic flow is:

Listen for UDP packets.

Receive a UDP packet and do any necessary processing of that data.

Block incoming UDP packets and wait 5 seconds.

Repeat.

I have the function working, but I can't figure out how to block UDP packets during the 5-second wait period. I've used the EnableBroadcast boolean on the UdpClient, but it does nothing. I've also tried setting the SocketOptionName of Broadcast and BlockSource to true/false and it does nothing as well.

```<code>private async void ReceiveUdpPackets()
{
    await Task.Run(async () =>
    {
        try
        {
            while (receivePackets)
            {
                Log.Info("Listening for UDP packets...");

                listener.Client.SetSocketOption(SocketOptionLevel.Udp, SocketOptionName.BlockSource, false);
                byte[] bytes = listener.Receive(ref groupEP);
                listener.Client.SetSocketOption(SocketOptionLevel.Udp, SocketOptionName.BlockSource, true);

                Log.Info($"Received UDP broadcast from {groupEP} :");
                Log.Info($"{Encoding.ASCII.GetString(bytes, 0, bytes.Length)}");

                var bString = BitConverter.ToString(bytes).Replace("-", "");
                Log.Info("UDP ByteString: " + bString);

                DecodeByteString(bString);
                await Task.Delay(5000);
            }
        }
        catch (Exception ex)
        {
            Log.Error("There was an issue decoding the UDP packet: " + ex.ToString());
        }
    });
}
</code>```

答:
If you want clients to be unable to send anything during the waiting period, you'll need some sort of way for them to know that the server isn't in a listening state. You could run a separate task on a different port, which clients may query to see if data can be transmitted and processed on the main port. There are many ways to go about this, but the basic idea is as simple as it sounds: the client queries the secondary port, the server responds with a message indicating whether or not the primary port is "online". If not, the client waits until it receives the go-ahead from the server. If so, the client can immediately send its information over.

If that doesn't sound appealing, you can also implement a data queuing model on the server side. You could have one task populate a BlockingCollection with incoming data from client(s) and another thread to process data drawn from this source. Note that this wouldn't stop transmissions, so it's not a perfect solution to your problem, but it does have several benefits. Here's a (flawed) example of what the code might look like:

using System.Collections.Concurrent;
using System.Net;
using System.Net.Sockets;
using System.Threading.Tasks;

namespace ExampleNamespace
{

    /*
     * data class; encapsulates byte array data received from a client.
     * in an actual implementation this might be a nice spot to put code
     * that interprets bytes from the client in some way
     */
    public class Transmission
    {
        public IPEndPoint Client { get; set; }

        public byte[] Data { get; set; }

        public Transmission(IPEndPoint client, byte[] data)
        {
            Client = client;
            Data = data;
        }
    }

    public class Server
    {
        private UdpClient listener;

        /*
         * you probably want to make this a bounded collection to prevent the
         * collection from getting too big
         */
        private BlockingCollection<Transmission> dataReceived = new BlockingCollection<Transmission>();

        private bool receivePackets = true;

        private bool processData = true;

        private IPEndPoint groupEP;

        public Server(IPEndPoint listenAt)
        {
            listener = new UdpClient(listenAt);
            groupEP = listenAt;
        }

        public void Run()
        {
            ProcessData();
            ReceiveData();
        }

        public async void ReceiveData()
        {
            await Task.Run(() => {
                while (receivePackets)
                {
                    byte[] data = listener.Receive(ref groupEP);
                    dataReceived.Add(new Transmission(groupEP, data));
                }
            });
        }

        public async void ProcessData()
        {
            //you could run just a few of these to increase your processing
            //speed without changing how things work
            await Task.Run(async () => {
                while (processData)
                {
                    //blocks until data is available
                    Transmission data = dataReceived.Take();

                    //do things with the data...

                    await Task.Delay(5000);
                }
            });
        }
    }
}
```

As stated, this example has some issues — if you want to actually implement this I highly recommend looking into making dataReceived a bounded blocking collection so you don't have to worry about memory issues. Also, it's generally useful to be able to shut down the whole process by passing a CancellationToken to your Take() and TryTake() calls, as well as any threads you create. However, the design itself should allow for easy multitasking in the event that processing clients becomes a performance problem.

Body:
I have a function that listens for UDP packets on a specific port. Whenever I receive data, I want the function to STOP receiving data on that port, wait 5 seconds, then resume listening for data. The basic flow is:

Listen for UDP packets.

Receive a UDP packet and do any necessary processing of that data.

Block incoming UDP packets and wait 5 seconds.

Repeat.

I have the function working, but I can't figure out how to block UDP packets during the 5-second wait period. I've used the EnableBroadcast boolean on the UdpClient, but it does nothing. I've also tried setting the SocketOptionName of Broadcast and BlockSource to true/false and it does nothing as well.

private async void ReceiveUdpPackets()
{
    await Task.Run(async () =>
    {
        try
        {
            while (receivePackets)
            {
                Log.Info("Listening for UDP packets...");

                listener.Client.SetSocketOption(SocketOptionLevel.Udp, SocketOptionName.BlockSource, false);
                byte[] bytes = listener.Receive(ref groupEP);
                listener.Client.SetSocketOption(SocketOptionLevel.Udp, SocketOptionName.BlockSource, true);

                Log.Info($"Received UDP broadcast from {groupEP} :");
                Log.Info($"{Encoding.ASCII.GetString(bytes, 0, bytes.Length)}");

                var bString = BitConverter.ToString(bytes).Replace("-", "");
                Log.Info("UDP ByteString: " + bString);

                DecodeByteString(bString);
                await Task.Delay(5000);
            }
        }
        catch (Exception ex)
        {
            Log.Error("There was an issue decoding the UDP packet: " + ex.ToString());
        }
    });
}

Body:
If you want clients to be unable to send anything during the waiting period, you'll need some sort of way for them to know that the server isn't in a listening state. You could run a separate task on a different port, which clients may query to see if data can be transmitted and processed on the main port. There are many ways to go about this, but the basic idea is as simple as it sounds: the client queries the secondary port, the server responds with a message indicating whether or not the primary port is "online". If not, the client waits until it receives the go-ahead from the server. If so, the client can immediately send its information over.

If that doesn't sound appealing, you can also implement a data queuing model on the server side. You could have one task populate a BlockingCollection with incoming data from client(s) and another thread to process data drawn from this source. Note that this wouldn't stop transmissions, so it's not a perfect solution to your problem, but it does have several benefits. Here's a (flawed) example of what the code might look like:

using System.Collections.Concurrent;
using System.Net;
using System.Net.Sockets;
using System.Threading.Tasks;

namespace ExampleNamespace
{

    /*
     * data class; encapsulates byte array data received from a client.
     * in an actual implementation this might be a nice spot to put code
     * that interprets bytes from the client in some way
     */
    public class Transmission
    {
        public IPEndPoint Client { get; set; }

        public byte[] Data { get; set; }

        public Transmission(IPEndPoint client, byte[] data)
        {
            Client = client;
            Data = data;
        }
    }

    public class Server
    {
        private UdpClient listener;

        /*
         * you probably want to make this a bounded collection to prevent the
         * collection from getting too big
         */
        private BlockingCollection<Transmission> dataReceived = new BlockingCollection<Transmission>();

        private bool receivePackets = true;

        private bool processData = true;

        private IPEndPoint groupEP;

        public Server(IPEndPoint listenAt)
        {
            listener = new UdpClient(listenAt);
            groupEP = listenAt;
        }

        public void Run()
        {
            ProcessData();
            ReceiveData();
        }

        public async void ReceiveData()
        {
            await Task.Run(() => {
                while (receivePackets)
                {
                    byte[] data = listener.Receive(ref groupEP);
                    dataReceived.Add(new Transmission(groupEP, data));
                }
            });
        }

        public async void ProcessData()
        {
            //you could run just a few of these to increase your processing
            //speed without changing how things work
            await Task.Run(async () => {
                while (processData)
                {
                    //blocks until data is available
                    Transmission data = dataReceived.Take();

                    //do things with the data...

                    await Task.Delay(5000);
                }
            });
        }
    }
}

As stated, this example has some issues — if you want to actually implement this I highly recommend looking into making dataReceived a bounded blocking collection so you don't have to worry about memory issues. Also, it's generally useful to be able to shut down the whole process by passing a CancellationToken to your Take() and TryTake() calls, as well as any threads you create. However, the design itself should allow for easy multitasking in the event that processing clients becomes a performance problem.


问:
define array in excel cell and use that cell in excel array formula
I have an excel cell A1 having cell content {"Q15","R15","S15"}.

How can I use A1 cell in array formula in excel?

I have used this formula:

```<code>=SUM(COUNTIFS('sheet1'!$D$2:$D$838,"<>NA",'sheet1'!$E$2:$E$838,{"Q15","R15","S15"}))
</code>```

the above formula works fine.

but when replaced with A1, it gives 0. And formula becomes

```<code>=SUM(COUNTIFS('sheet1'!$D$2:$D$838,"<>NA",'sheet1'!$E$2:$E$838,A1))
</code>```

How can I use A1 so that the resulting formula contains the actual array?

答:
The problem you have here is that Excel is reading {"Q15","R15","S15"} from A1  as a String (="{""Q15"",""R15"",""S15""}"), not as an array.

You can get around this using MID and TRIM to artificially split the string via a SUMPRODUCT

=SUMPRODUCT(COUNTIFS('sheet1'!$D$2:$D$838, "<>NA", 'sheet1'!$E$2:$E$838, TRIM(MID(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(A1, """,""", REPT(" ", 99)), "{""", ""), """}", ""), 99*ROW(A1:INDEX(A:A, 1+LEN(A1)-LEN(SUBSTITUTE(A1, ",", ""))))-98, 60))))
```

<p>The "magic" bit here is the rather convoluted line below</p>

<p>TRIM(MID(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(A1,""",""",REPT(" ",99)),"{""",""),"""}",""),99*Row(A1:INDEX(A:A,1+Len(A1)-Len(SUBSTITUTE(A1,",","")))-98,60))</p>

<p>Turns <code>{"Q15","R15","S15"}</code> into <code>Q15</code>, <code>R15</code> and <code>S15</code>, separated by 99 spaces.  It then counts how many commas are in <code>A1</code>, and (that many times) takes 60 characters (starting at position 1 the first time, then position 100 the second time, then position 199, et cetera) and trims the spaces - this gives an array <code>{"Q15","R15","S15"}</code></p>

<p>So, as Tim Williams says in comments, you might be better off using VBA.  A basic User Defined Function to split the array like this would work:</p>

<pre class="lang-vb prettyprint-override"><code>Public Function SplitArray(Text As String) As Variant
    'If we error, show #NA!
    SplitArray = CVErr(xlErrNA)
    On Error GoTo FunctionErred
    'Split the array
    If Left(Text, 1) = "{" And Right(Text, 1) = "}" Then
        SplitArray = Split(Replace(Mid(Text, 2, Len(Text) - 2), """", ""), ",")
    Else
        SplitArray = Text
    End If
FunctionErred:
End Function
</code>```

Giving

=SUM(COUNTIFS('sheet1'!$D$2:$D$838,"<>NA",'sheet1'!$E$2:$E$838,SplitArray(A1)))
```

Body:
I have an excel cell A1 having cell content {"Q15","R15","S15"}.

How can I use A1 cell in array formula in excel?

I have used this formula:

=SUM(COUNTIFS('sheet1'!$D$2:$D$838,"<>NA",'sheet1'!$E$2:$E$838,{"Q15","R15","S15"}))

the above formula works fine.

but when replaced with A1, it gives 0. And formula becomes

=SUM(COUNTIFS('sheet1'!$D$2:$D$838,"<>NA",'sheet1'!$E$2:$E$838,A1))

How can I use A1 so that the resulting formula contains the actual array?

Body:
The problem you have here is that Excel is reading {"Q15","R15","S15"} from A1  as a String (="{""Q15"",""R15"",""S15""}"), not as an array.

You can get around this using MID and TRIM to artificially split the string via a SUMPRODUCT

=SUMPRODUCT(COUNTIFS('sheet1'!$D$2:$D$838, "<>NA", 'sheet1'!$E$2:$E$838, TRIM(MID(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(A1, """,""", REPT(" ", 99)), "{""", ""), """}", ""), 99*ROW(A1:INDEX(A:A, 1+LEN(A1)-LEN(SUBSTITUTE(A1, ",", ""))))-98, 60))))

The "magic" bit here is the rather convoluted line below

TRIM(MID(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(A1,""",""",REPT(" ",99)),"{""",""),"""}",""),99*Row(A1:INDEX(A:A,1+Len(A1)-Len(SUBSTITUTE(A1,",","")))-98,60))

Turns {"Q15","R15","S15"} into Q15, R15 and S15, separated by 99 spaces.  It then counts how many commas are in A1, and (that many times) takes 60 characters (starting at position 1 the first time, then position 100 the second time, then position 199, et cetera) and trims the spaces - this gives an array {"Q15","R15","S15"}

So, as Tim Williams says in comments, you might be better off using VBA.  A basic User Defined Function to split the array like this would work:

Public Function SplitArray(Text As String) As Variant
    'If we error, show #NA!
    SplitArray = CVErr(xlErrNA)
    On Error GoTo FunctionErred
    'Split the array
    If Left(Text, 1) = "{" And Right(Text, 1) = "}" Then
        SplitArray = Split(Replace(Mid(Text, 2, Len(Text) - 2), """", ""), ",")
    Else
        SplitArray = Text
    End If
FunctionErred:
End Function

Giving

=SUM(COUNTIFS('sheet1'!$D$2:$D$838,"<>NA",'sheet1'!$E$2:$E$838,SplitArray(A1)))


问:
Docker Build Stuck on MariaDB Installation
I am trying to build a set of Docker images that includes an installation of Magento 2 and MariaDB. In rare cases it succeeds (although this could be due to small changes in the app), but in most cases it is stuck on the following:

```<code>magento2-db    | Version: '10.3.11-MariaDB-1:10.3.11+maria~bionic'  socket: '/var/run/mysqld/mysqld.sock'  port: 3306  mariadb.org binary distribution
</code>```

I see that someone else had this issue, but the cause was actual RUN commands for MariaDB installation, which I don't directly call. There doesn't seem to be anything in the log to indicate an error either.

The last lines in the log are:

```<code>[16:49:18.424][Moby           ][Info   ] [25693.252573] br-83922f7da47b: port 2(vethac51834) entered blocking state
[16:49:18.453][Moby           ][Info   ] [25693.290035] br-83922f7da47b: port 2(vethac51834) entered forwarding state
[16:49:18.637][ApiProxy       ][Info   ] time="2018-11-28T16:49:18+02:00" msg="proxy << POST /v1.25/containers/67175238f0e7a75ef527dbebbb1f5d992f1d01ee166643186dc5f727638aa66b/start (1.0560013s)\n"
[16:49:18.645][ApiProxy       ][Info   ] time="2018-11-28T16:49:18+02:00" msg="proxy >> GET /v1.25/events?filters=%7B%22label%22%3A+%5B%22com.docker.compose.project%3Dmagento2%22%2C+%22com.docker.compose.oneoff%3DFalse%22%5D%7D\n"
</code>```

It seems to actually finish executing all steps in the Dockerfile, but I suspect there might be a problem in my docker-compose file, which looks like this:

```<code>version: '3.0'
services:
  app:
    build:
      context: .
      dockerfile: .docker/Dockerfile
    container_name: 'magento-2.2.6'
    ports:
      - "80:80"
    volumes:
      - magento2-test-env:/var/www/html/magento2 # will be mounted on /var/www/html
    links:
      - magento2-db
    env_file:
      - .docker/env
    depends_on:
      - magento2-db
  magento2-db:
    container_name: 'magento2-db'
    image: mariadb:latest
    ports:
      - "9809:3306"
    volumes:
      - magento2-db-data:/var/lib/mysql/data
    env_file:
      - .docker/env
volumes:
  magento2-db-data:
  magento2-test-env:
    external: true
</code>```

Is there anything obviously wrong with my setup, and is there a good way to troubleshoot this, maybe look for something specific in the log?

答:
maybe the way you're building your composer what's the problem.

Try use this one:

```<code>version: '3.0'
services:
  app:
    build:
      context: .
      dockerfile: .docker/Dockerfile
    container_name: 'magento-2.2.6'
    ports:
      - "80:80"
    volumes:
      - magento2-test-env:/var/www/html/magento2 # will be mounted on /var/www/html
    links:
      - magento2-db
    env_file:
      - .docker/env
    depends_on:
      - db
  db:
    container_name: 'magento2-db'
    image: mariadb:latest
    ports:
      - "9809:3306"
    volumes:
      - /var/lib/mysql/data
    env_file:
      - .docker/env
volumes:
  magento2-db-data:
  magento2-test-env:
    external: true
</code>```

Avoid to use services names like 'blabla-something' if you need put a name use as container_name it'll be enough, and the db, links always should links in the services itself no in the containers name.

I hope this could help you.

Body:
I am trying to build a set of Docker images that includes an installation of Magento 2 and MariaDB. In rare cases it succeeds (although this could be due to small changes in the app), but in most cases it is stuck on the following:

magento2-db    | Version: '10.3.11-MariaDB-1:10.3.11+maria~bionic'  socket: '/var/run/mysqld/mysqld.sock'  port: 3306  mariadb.org binary distribution

I see that someone else had this issue, but the cause was actual RUN commands for MariaDB installation, which I don't directly call. There doesn't seem to be anything in the log to indicate an error either.

The last lines in the log are:

[16:49:18.424][Moby           ][Info   ] [25693.252573] br-83922f7da47b: port 2(vethac51834) entered blocking state
[16:49:18.453][Moby           ][Info   ] [25693.290035] br-83922f7da47b: port 2(vethac51834) entered forwarding state
[16:49:18.637][ApiProxy       ][Info   ] time="2018-11-28T16:49:18+02:00" msg="proxy << POST /v1.25/containers/67175238f0e7a75ef527dbebbb1f5d992f1d01ee166643186dc5f727638aa66b/start (1.0560013s)\n"
[16:49:18.645][ApiProxy       ][Info   ] time="2018-11-28T16:49:18+02:00" msg="proxy >> GET /v1.25/events?filters=%7B%22label%22%3A+%5B%22com.docker.compose.project%3Dmagento2%22%2C+%22com.docker.compose.oneoff%3DFalse%22%5D%7D\n"

It seems to actually finish executing all steps in the Dockerfile, but I suspect there might be a problem in my docker-compose file, which looks like this:

version: '3.0'
services:
  app:
    build:
      context: .
      dockerfile: .docker/Dockerfile
    container_name: 'magento-2.2.6'
    ports:
      - "80:80"
    volumes:
      - magento2-test-env:/var/www/html/magento2 # will be mounted on /var/www/html
    links:
      - magento2-db
    env_file:
      - .docker/env
    depends_on:
      - magento2-db
  magento2-db:
    container_name: 'magento2-db'
    image: mariadb:latest
    ports:
      - "9809:3306"
    volumes:
      - magento2-db-data:/var/lib/mysql/data
    env_file:
      - .docker/env
volumes:
  magento2-db-data:
  magento2-test-env:
    external: true

Is there anything obviously wrong with my setup, and is there a good way to troubleshoot this, maybe look for something specific in the log?

Body:
maybe the way you're building your composer what's the problem.

Try use this one:

version: '3.0'
services:
  app:
    build:
      context: .
      dockerfile: .docker/Dockerfile
    container_name: 'magento-2.2.6'
    ports:
      - "80:80"
    volumes:
      - magento2-test-env:/var/www/html/magento2 # will be mounted on /var/www/html
    links:
      - magento2-db
    env_file:
      - .docker/env
    depends_on:
      - db
  db:
    container_name: 'magento2-db'
    image: mariadb:latest
    ports:
      - "9809:3306"
    volumes:
      - /var/lib/mysql/data
    env_file:
      - .docker/env
volumes:
  magento2-db-data:
  magento2-test-env:
    external: true

Avoid to use services names like 'blabla-something' if you need put a name use as container_name it'll be enough, and the db, links always should links in the services itself no in the containers name.

I hope this could help you.


问:
No values from JSON
I'd like to display values from my JSON just for testing purposes, but I've received literally nothing. Where can be an issue? The link in Utils is correctly for sure, I've runned it on my browser, and everything was good.

Here's the code

Utils class

```<code>public class WeatherUtils {
public WeatherUtils(){}

public static ArrayList<Weather> getHourlyData (double minTemp, double maxTemp, double currentTemp, double airPressure){

    ArrayList<Weather> weatherList = new ArrayList<>();

    try {
        JSONObject reader = new JSONObject("https://api.openweathermap.org/data/2.5/forecast?q=London,us&units=metric&appid=ID...");
        JSONArray array = reader.getJSONArray("list");
        for (int i = 0; i<array.length(); i++){

            JSONObject secondReader = array.getJSONObject(i);
            JSONObject dataObject = secondReader.getJSONObject("main");
            for (int j = 0; j<dataObject.length(); j++){
                currentTemp = dataObject.getDouble("temp");
                minTemp = dataObject.getDouble("temp_min");
                maxTemp = dataObject.getDouble("temp_max");
                airPressure = dataObject.getDouble("pressure");
            }
            weatherList.add(new Weather(currentTemp,minTemp,maxTemp,airPressure));
        }

    } catch (JSONException e) {
        e.printStackTrace();
    }
    return weatherList;
 }
}
</code>```

MainActivity
       Double a,b,c,d;

```<code>    a = 0.0;
    b = 0.0;
    c = 0.0;
    d = 0.0;

    ArrayList<Weather> weathers = WeatherUtils.getHourlyData(a,b,c,d);
    System.out.println(weathers);
</code>```

JSON structure

```<code> {
  "cod": "200",
  "message": 0.0074,
  "cnt": 40,
  "list": [
    {
      "dt": 1559131200,
      "main": {
        "temp": 22.1,
        "temp_min": 21.32,
        "temp_max": 22.1,
        "pressure": 1012.31,
        "sea_level": 1012.31,
        "grnd_level": 976.84,
        "humidity": 92,
        "temp_kf": 0.78
      },
      "weather": [
        {
          "id": 500,
          "main": "Rain",
          "description": "light rain",
          "icon": "10d"
        }
      ],
      "clouds": {
        "all": 89
      },
      "wind": {
        "speed": 3.08,
        "deg": 213.025
      },
      "rain": {
        "3h": 0.875
      },
      "sys": {
        "pod": "d"
      },
      "dt_txt": "2019-05-29 12:00:00"
    },
    {
</code>```

Of course, there are more data. I've posted one "block"

How I may fix that?

答:
Well, given that you just want to "test" the json parsing, you have few options but let's go with a simple one. But first, I would say to extract the parser and put it in its own class/method so it becomes easier to test, something like this:

```<code>public class WeatherUtils {
public WeatherUtils(){}

public static ArrayList<Weather> getHourlyData (double minTemp, double maxTemp, double currentTemp, double airPressure){

    final ArrayList<Weather> weatherList = new ArrayList<>();

    try {
        final JSONObject response = httpCall();
        weatherList = mapWeatherResponse(response);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return weatherList;
 }

public static List<Weather> mapWeatherResponse(JSONObject reader){
    final ArrayList<Weather> weatherList = new ArrayList<>();
    JSONArray array = reader.getJSONArray("list");
    for (int i = 0; i<array.length(); i++){
        JSONObject secondReader = array.getJSONObject(i);
        JSONObject dataObject = secondReader.getJSONObject("main");
        for (int j = 0; j<dataObject.length(); j++){
            currentTemp = dataObject.getDouble("temp");
            minTemp = dataObject.getDouble("temp_min");
            maxTemp = dataObject.getDouble("temp_max");
            airPressure = dataObject.getDouble("pressure");
        }
        weatherList.add(new Weather(currentTemp,minTemp,maxTemp,airPressure));
    }
}
}

</code>```

Test the response parser with a junit test:

You can create a junit test like this:

```<code>public class WeatherUtilsTest {
    @Test
    public void parserResponseTEst() {
        final List<String> expectedResponse = new ArrayList<>();
        //fill the expectedResponse with the correspondent values

        final String json = "{\n" +
                "  \"cod\": \"200\",\n" +
                "  \"message\": 0.0074,\n" +
                "  \"cnt\": 40,\n" +
                "  \"list\": [\n" +
                "    {\n" +
                "      \"dt\": 1559131200,\n" +
                "      \"main\": {\n" +
                "        \"temp\": 22.1,\n" +
                "        \"temp_min\": 21.32,\n" +
                "        \"temp_max\": 22.1,\n" +
                "        \"pressure\": 1012.31,\n" +
                "        \"sea_level\": 1012.31,\n" +
                "        \"grnd_level\": 976.84,\n" +
                "        \"humidity\": 92,\n" +
                "        \"temp_kf\": 0.78\n" +
                "      },\n" +
                "      \"weather\": [\n" +
                "        {\n" +
                "          \"id\": 500,\n" +
                "          \"main\": \"Rain\",\n" +
                "          \"description\": \"light rain\",\n" +
                "          \"icon\": \"10d\"\n" +
                "        }\n" +
                "      ],\n" +
                "      \"clouds\": {\n" +
                "        \"all\": 89\n" +
                "      },\n" +
                "      \"wind\": {\n" +
                "        \"speed\": 3.08,\n" +
                "        \"deg\": 213.025\n" +
                "      },\n" +
                "      \"rain\": {\n" +
                "        \"3h\": 0.875\n" +
                "      }\n" +
                "    }]\n" +
                "    }";

        final List<String> response = WeatherUtils.mapWeatherResponse(new JSONObject(json));
        assertEquals(expectedResponse, response);
    }
}
</code>```

There is nothing wrong with the JSONObject parser you are doing. You mentioned the link you are using in Utils is correct, do you get a proper response when you test it in your browser, postman, insomnia?

OBS JSONObject reader = new JSONObject("https://api..."); does not fetch anything, what you are doing there is creating a JSONObject from the given String, i.e. "https://....". To fetch the data you need to implement some http client. Here is an example https://stackoverflow.com/a/4457526/761668

Title: No values from JSON

Body:
I'd like to display values from my JSON just for testing purposes, but I've received literally nothing. Where can be an issue? The link in Utils is correctly for sure, I've runned it on my browser, and everything was good.

Here's the code

Utils class

public class WeatherUtils {
public WeatherUtils(){}

public static ArrayList<Weather> getHourlyData (double minTemp, double maxTemp, double currentTemp, double airPressure){

    ArrayList<Weather> weatherList = new ArrayList<>();

    try {
        JSONObject reader = new JSONObject("https://api.openweathermap.org/data/2.5/forecast?q=London,us&units=metric&appid=ID...");
        JSONArray array = reader.getJSONArray("list");
        for (int i = 0; i<array.length(); i++){

            JSONObject secondReader = array.getJSONObject(i);
            JSONObject dataObject = secondReader.getJSONObject("main");
            for (int j = 0; j<dataObject.length(); j++){
                currentTemp = dataObject.getDouble("temp");
                minTemp = dataObject.getDouble("temp_min");
                maxTemp = dataObject.getDouble("temp_max");
                airPressure = dataObject.getDouble("pressure");
            }
            weatherList.add(new Weather(currentTemp,minTemp,maxTemp,airPressure));
        }

    } catch (JSONException e) {
        e.printStackTrace();
    }
    return weatherList;
 }
}

MainActivity
       Double a,b,c,d;

    a = 0.0;
    b = 0.0;
    c = 0.0;
    d = 0.0;

    ArrayList<Weather> weathers = WeatherUtils.getHourlyData(a,b,c,d);
    System.out.println(weathers);

JSON structure

 {
  "cod": "200",
  "message": 0.0074,
  "cnt": 40,
  "list": [
    {
      "dt": 1559131200,
      "main": {
        "temp": 22.1,
        "temp_min": 21.32,
        "temp_max": 22.1,
        "pressure": 1012.31,
        "sea_level": 1012.31,
        "grnd_level": 976.84,
        "humidity": 92,
        "temp_kf": 0.78
      },
      "weather": [
        {
          "id": 500,
          "main": "Rain",
          "description": "light rain",
          "icon": "10d"
        }
      ],
      "clouds": {
        "all": 89
      },
      "wind": {
        "speed": 3.08,
        "deg": 213.025
      },
      "rain": {
        "3h": 0.875
      },
      "sys": {
        "pod": "d"
      },
      "dt_txt": "2019-05-29 12:00:00"
    },
    {

Of course, there are more data. I've posted one "block"

How I may fix that?

Body:
Well, given that you just want to "test" the json parsing, you have few options but let's go with a simple one. But first, I would say to extract the parser and put it in its own class/method so it becomes easier to test, something like this:

public class WeatherUtils {
public WeatherUtils(){}

public static ArrayList<Weather> getHourlyData (double minTemp, double maxTemp, double currentTemp, double airPressure){

    final ArrayList<Weather> weatherList = new ArrayList<>();

    try {
        final JSONObject response = httpCall();
        weatherList = mapWeatherResponse(response);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return weatherList;
 }

public static List<Weather> mapWeatherResponse(JSONObject reader){
    final ArrayList<Weather> weatherList = new ArrayList<>();
    JSONArray array = reader.getJSONArray("list");
    for (int i = 0; i<array.length(); i++){
        JSONObject secondReader = array.getJSONObject(i);
        JSONObject dataObject = secondReader.getJSONObject("main");
        for (int j = 0; j<dataObject.length(); j++){
            currentTemp = dataObject.getDouble("temp");
            minTemp = dataObject.getDouble("temp_min");
            maxTemp = dataObject.getDouble("temp_max");
            airPressure = dataObject.getDouble("pressure");
        }
        weatherList.add(new Weather(currentTemp,minTemp,maxTemp,airPressure));
    }
}
}

Test the response parser with a junit test:

You can create a junit test like this:

public class WeatherUtilsTest {
    @Test
    public void parserResponseTEst() {
        final List<String> expectedResponse = new ArrayList<>();
        //fill the expectedResponse with the correspondent values

        final String json = "{\n" +
                "  \"cod\": \"200\",\n" +
                "  \"message\": 0.0074,\n" +
                "  \"cnt\": 40,\n" +
                "  \"list\": [\n" +
                "    {\n" +
                "      \"dt\": 1559131200,\n" +
                "      \"main\": {\n" +
                "        \"temp\": 22.1,\n" +
                "        \"temp_min\": 21.32,\n" +
                "        \"temp_max\": 22.1,\n" +
                "        \"pressure\": 1012.31,\n" +
                "        \"sea_level\": 1012.31,\n" +
                "        \"grnd_level\": 976.84,\n" +
                "        \"humidity\": 92,\n" +
                "        \"temp_kf\": 0.78\n" +
                "      },\n" +
                "      \"weather\": [\n" +
                "        {\n" +
                "          \"id\": 500,\n" +
                "          \"main\": \"Rain\",\n" +
                "          \"description\": \"light rain\",\n" +
                "          \"icon\": \"10d\"\n" +
                "        }\n" +
                "      ],\n" +
                "      \"clouds\": {\n" +
                "        \"all\": 89\n" +
                "      },\n" +
                "      \"wind\": {\n" +
                "        \"speed\": 3.08,\n" +
                "        \"deg\": 213.025\n" +
                "      },\n" +
                "      \"rain\": {\n" +
                "        \"3h\": 0.875\n" +
                "      }\n" +
                "    }]\n" +
                "    }";

        final List<String> response = WeatherUtils.mapWeatherResponse(new JSONObject(json));
        assertEquals(expectedResponse, response);
    }
}

There is nothing wrong with the JSONObject parser you are doing. You mentioned the link you are using in Utils is correct, do you get a proper response when you test it in your browser, postman, insomnia?

OBS JSONObject reader = new JSONObject("https://api..."); does not fetch anything, what you are doing there is creating a JSONObject from the given String, i.e. "https://....". To fetch the data you need to implement some http client. Here is an example https://stackoverflow.com/a/4457526/761668


问:
<class 'AttributeError'> at / module 'web' has no attribute 'config_session'
I'm following ex25 on LPTHW, tried to run the website http://0.0.0.0:8080/ by  python3 bin/app.py
the directory structure as following:

```<code>__init__.py docs        map.py      templates   web
bin     gothonweb   sessions    tests

./bin:
__init__.py __pycache__ app.py

./bin/__pycache__:
__init__.cpython-37.pyc app.cpython-37.pyc

./docs:

./gothonweb:
__init__.py __init__.pyc    __pycache__ map.py      map.pyc

./gothonweb/__pycache__:
__init__.cpython-37.pyc map.cpython-37.pyc

./sessions:
07cb99819409e9eafd8ec3d4bc86cdbb3ac20238

./templates:
layout.html show_room.html  you_died.html

./tests:
__init__.py __pycache__ app_tests.py    map_tests.py    tools.py

./tests/__pycache__:
__init__.cpython-37.pyc     map_tests.cpython-37.pyc
app_tests.cpython-37.pyc    tools.cpython-37.pyc

./web:
__init__.py contrib     http.py     session.py  webapi.py
__pycache__ db.py       httpserver.py   template.py webopenid.py
application.py  debugerror.py   net.py      test.py     wsgi.py
browser.py  form.py     py3helpers.py   utils.py

./web/__pycache__:
__init__.cpython-37.pyc     net.cpython-37.pyc

./web/contrib:
__init__.py __pycache__ template.py

./web/contrib/__pycache__:
__init__.cpython-37.pyc
</code>```

can't figure out how to fix this error and run the web page successfully.

code files as following:

app.py

```<code>from gothonweb import map

urls=(
    '/game','GameEngine',
    '/','Index',
)

app=web.application(urls,globals())

#title hack so that debug mode works with sessions
if web.config.get('_session')is None:
    store=web.session.DiskStore('sessions')
    session=web.session.Session(app,store,initializer={'room':None})
    web.config._session=session
else:
    session=web.config_session

render=web.template.render('templates/',base="layout")

class Index(object):
    def GET(self):
        #this is used to "setup" the session with starting values
        session.room=map.START
        web.seeother("/game")

class GameEngine(object):
    def GET(self):
        if session.room:
            return render.show_room(room=session.room)
        else:
            #Why is there here?do you need it?
            return render.you_died()
    def POST(self):
        form=web.input(action=None)
        #there is a bug here,can you fix it?
        if session.room and form.action:
            session.room=session.room.go(form.action)
        else:
            session.room=None

if __name__=="__main__":
    app.run()

</code>```

tools.py

```<code>import re

def assert_response(resp,contains=None,matches=None,headers=None,status="200"):
    assert status in resp.status,"Excepted response %r not in %r" %(status,resp.status)
    if status=="200":
        assert resp.data,"Response data is empty."
    if contains:
        assert contains in resp.data,"Response dose not contain %r"%contains
    if matches:
        reg=re.compile(matches)
        assert reg.matches(resp.data),"Response does not match %r"%matches
    if headers:
        assert_equal(resp.headers,headers)

</code>```

app_tests.py

```<code>from bin.app import app
from tests.tools import assert_response

def test_index():
    #check that we get a 303 on the /URL
    #this is because web.seeother()will always send the browser this http code
    resp=app.request("/")
    assert_response(resp,status="303")
def test_game():
    #checkt that we get a 200 on /game
    resp=app.request("/game")
    assert_response(resp,status='200')

    #check that we have response data on a form submit
    resp=app.request ("/game",method="POST")
    assert_response(resp)
</code>```

I got following result on page when I open the url

```<code>module 'web' has no attribute 'config_session'```
and traceback
AttributeError: module 'web' has no attribute 'config_session'

```

答: Your if else block at the top of app.py has a typo. Specifically your else statement tries to access web.config_session instead of web.config._session

Body:
I'm following ex25 on LPTHW, tried to run the website http://0.0.0.0:8080/ by  python3 bin/app.py
the directory structure as following:

__init__.py docs        map.py      templates   web
bin     gothonweb   sessions    tests

./bin:
__init__.py __pycache__ app.py

./bin/__pycache__:
__init__.cpython-37.pyc app.cpython-37.pyc

./docs:

./gothonweb:
__init__.py __init__.pyc    __pycache__ map.py      map.pyc

./gothonweb/__pycache__:
__init__.cpython-37.pyc map.cpython-37.pyc

./sessions:
07cb99819409e9eafd8ec3d4bc86cdbb3ac20238

./templates:
layout.html show_room.html  you_died.html

./tests:
__init__.py __pycache__ app_tests.py    map_tests.py    tools.py

./tests/__pycache__:
__init__.cpython-37.pyc     map_tests.cpython-37.pyc
app_tests.cpython-37.pyc    tools.cpython-37.pyc

./web:
__init__.py contrib     http.py     session.py  webapi.py
__pycache__ db.py       httpserver.py   template.py webopenid.py
application.py  debugerror.py   net.py      test.py     wsgi.py
browser.py  form.py     py3helpers.py   utils.py

./web/__pycache__:
__init__.cpython-37.pyc     net.cpython-37.pyc

./web/contrib:
__init__.py __pycache__ template.py

./web/contrib/__pycache__:
__init__.cpython-37.pyc

can't figure out how to fix this error and run the web page successfully.

code files as following:

app.py

from gothonweb import map

urls=(
    '/game','GameEngine',
    '/','Index',
)

app=web.application(urls,globals())

#title hack so that debug mode works with sessions
if web.config.get('_session')is None:
    store=web.session.DiskStore('sessions')
    session=web.session.Session(app,store,initializer={'room':None})
    web.config._session=session
else:
    session=web.config_session

render=web.template.render('templates/',base="layout")

class Index(object):
    def GET(self):
        #this is used to "setup" the session with starting values
        session.room=map.START
        web.seeother("/game")

class GameEngine(object):
    def GET(self):
        if session.room:
            return render.show_room(room=session.room)
        else:
            #Why is there here?do you need it?
            return render.you_died()
    def POST(self):
        form=web.input(action=None)
        #there is a bug here,can you fix it?
        if session.room and form.action:
            session.room=session.room.go(form.action)
        else:
            session.room=None

if __name__=="__main__":
    app.run()

tools.py

import re

def assert_response(resp,contains=None,matches=None,headers=None,status="200"):
    assert status in resp.status,"Excepted response %r not in %r" %(status,resp.status)
    if status=="200":
        assert resp.data,"Response data is empty."
    if contains:
        assert contains in resp.data,"Response dose not contain %r"%contains
    if matches:
        reg=re.compile(matches)
        assert reg.matches(resp.data),"Response does not match %r"%matches
    if headers:
        assert_equal(resp.headers,headers)

app_tests.py

from bin.app import app
from tests.tools import assert_response

def test_index():
    #check that we get a 303 on the /URL
    #this is because web.seeother()will always send the browser this http code
    resp=app.request("/")
    assert_response(resp,status="303")
def test_game():
    #checkt that we get a 200 on /game
    resp=app.request("/game")
    assert_response(resp,status='200')

    #check that we have response data on a form submit
    resp=app.request ("/game",method="POST")
    assert_response(resp)

I got following result on page when I open the url

module 'web' has no attribute 'config_session'```
and traceback
AttributeError: module 'web' has no attribute 'config_session'


问:
Does the linked service support dynamic json in azure data factory?
Currently, I'm trying to set up a dynamic key vault linked service.
Unfortunately, whatever I try I'm not able to successfully test the connection.

```<code>{
    "name": "AzureKeyVault1",
    "properties": {
        "type": "AzureKeyVault",
        "typeProperties": {
            "baseUrl": {
                "value": "@concat('https://vault.azure.net','/')",
                "type": "Expression"
            }
        }
    }
}
</code>```

The above code using concat is not a real use case but just a way to test if dynamic json is possible for linked service.
I was expecting (based on the documentation) that I could make the baseUrl property dynamic. Am I using the right formatting?

I get the following error:

Error: Error: Can't get property concat

答:
@Wim

To Answer your question, this is the correct formatting.

I have been able to parameterize a pipeline parameter, and then pass it as the baseurl in a dynamic expression.

Body:
Currently, I'm trying to set up a dynamic key vault linked service.
Unfortunately, whatever I try I'm not able to successfully test the connection.

{
    "name": "AzureKeyVault1",
    "properties": {
        "type": "AzureKeyVault",
        "typeProperties": {
            "baseUrl": {
                "value": "@concat('https://vault.azure.net','/')",
                "type": "Expression"
            }
        }
    }
}

The above code using concat is not a real use case but just a way to test if dynamic json is possible for linked service.
I was expecting (based on the documentation) that I could make the baseUrl property dynamic. Am I using the right formatting?

I get the following error:

Error: Error: Can't get property concat


问:
FeathersJS express.rest api questions
I was following the documentation on FeathersJS and came across this https://docs.feathersjs.com/guides/basics/rest.html.
Under the section of Rest and Services, the doc mentions for GET method, you can go to /messages/1 to retrieve object with id:1 .

I understand that this is related to the API of express.rest() (https://docs.feathersjs.com/api/express.html#expressrest). But I want to get a clearer picture why I could retrieve whatever object by keying in the id I want simply at /messages/{id}/. The doc does not paint it clear so I wonder whether is it a hidden FeatherJS api feature or part of Express concept?

答:
If you read the previous services chapter you can see how the get method is implemented on a service. All that happens with the REST adapters is that a GET messages/{id} will be turned into a service.get(id) call. For example something like

```<code>class SimpleService {
  async find (params) {
    return [{
      desription: '.find results'
    }]
  }

  async get(id) {
    return {
      description: `You have to do ${id}`
    }
  }
}

app.use('/messages', new SimpleService());
</code>```

Would return [{ description: '.find results' }] for GET /messages. For GET /messages/dishes it would return { description: 'You have to do dishes' }.

More details about the patterns behind this can be found in Design Patterns For Modern Web APIs.

Title: FeathersJS express.rest api questions

Body:
If you read the previous services chapter you can see how the get method is implemented on a service. All that happens with the REST adapters is that a GET messages/{id} will be turned into a service.get(id) call. For example something like

class SimpleService {
  async find (params) {
    return [{
      desription: '.find results'
    }]
  }

  async get(id) {
    return {
      description: `You have to do ${id}`
    }
  }
}

app.use('/messages', new SimpleService());

Would return [{ description: '.find results' }] for GET /messages. For GET /messages/dishes it would return { description: 'You have to do dishes' }.

More details about the patterns behind this can be found in Design Patterns For Modern Web APIs.


问:
how to redirect using react router
The maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.

```<code>  import React, { Component } from "react";
  import { BrowserRouter, Route, Redirect, Switch } from "react-router-dom";
  import Login from "./component/auth/Login";
  import HomeScreen from "./component/home-screen/HomeScreen";
       class App extends Component {
           constructor(props) {
            super(props);

              this.state = {
                   user: {}
                 };
                 }

              componentDidMount() {
                    this.authListener();
               }

     authListener() {
firebase.auth().onAuthStateChanged(user => {
  if (user) {
    this.setState({ user });
  } else {
    this.setState({ user: null });
  }
});
}

render() {
  return (
  <BrowserRouter>
    <div className="App">
      <Switch>
        <Route exact path="/" component={Landing} />
        {this.state.user ? (
          <Redirect to="/homescreen" />
        ) : (
          <Redirect to="/login" />
        )}
        <Route exact path="/login" component={Login} />
        <Route exact path="/homescreen" component={HomeScreen} />
        <Route exact path="/users" component={Users} />
        <Route exact path="/users/:id" component={UserDetail} />
        <Route component={Error} />
      </Switch>
    </div>
  </BrowserRouter>
);
}
}

 export default App;
</code>```

答:
react router v4+ supports use of PrivateRoute.

```<code>// create a private route, if user is not logged in redirect to login page
const PrivateRoute = ({ component: Component, ...rest }) => (
  <Route {...rest} render={(props) => (
      isAuthenticated() === true
        ? <Component {...props} />
        : <Redirect to='/login' />
  )} />
)
</code>```

Use it like a normal route and check authentication in the private route.

```<code><BrowserRouter>
  <Route path="/login" exact component={FormularAuth} />
  <PrivateRoute path='/private' component={Private} />
</BrowserRouter>
</code>```

Demo

Title: how to redirect using react router

Body:
The maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.

  import React, { Component } from "react";
  import { BrowserRouter, Route, Redirect, Switch } from "react-router-dom";
  import Login from "./component/auth/Login";
  import HomeScreen from "./component/home-screen/HomeScreen";
       class App extends Component {
           constructor(props) {
            super(props);

              this.state = {
                   user: {}
                 };
                 }

              componentDidMount() {
                    this.authListener();
               }

     authListener() {
firebase.auth().onAuthStateChanged(user => {
  if (user) {
    this.setState({ user });
  } else {
    this.setState({ user: null });
  }
});
}

render() {
  return (
  <BrowserRouter>

      <Switch>
        <Route exact path="/" component={Landing} />
        {this.state.user ? (
          <Redirect to="/homescreen" />
        ) : (
          <Redirect to="/login" />
        )}
        <Route exact path="/login" component={Login} />
        <Route exact path="/homescreen" component={HomeScreen} />
        <Route exact path="/users" component={Users} />
        <Route exact path="/users/:id" component={UserDetail} />
        <Route component={Error} />
      </Switch>

  </BrowserRouter>
);
}
}

 export default App;

Body:
react router v4+ supports use of PrivateRoute.

// create a private route, if user is not logged in redirect to login page
const PrivateRoute = ({ component: Component, ...rest }) => (
  <Route {...rest} render={(props) => (
      isAuthenticated() === true
        ? <Component {...props} />
        : <Redirect to='/login' />
  )} />
)

Use it like a normal route and check authentication in the private route.

<BrowserRouter>
  <Route path="/login" exact component={FormularAuth} />
  <PrivateRoute path='/private' component={Private} />
</BrowserRouter>

Demo


问:
What is the use of SPHttpUtility.NoEncode method?
Does anybody know what is the usefulness of the SPHttpUtility.NoEncode method? It seems like it takes a string as parameters and returns it without any modification.

Is there a case where you can use this and I'm missing it?

答:
The data in sharepoint that is markup content has to be encoded so that it can be passed around in xml without it breaking.

for example & lt;a / & gt; instead of "" (without the spaces)

Therefore if you want to ouput the rendered  instead of >a /< you use the NoEncode function to convert it to valid xml.

Hope that makes sense.

Body:
The data in sharepoint that is markup content has to be encoded so that it can be passed around in xml without it breaking.

for example & lt;a / & gt; instead of "< a/ >" (without the spaces)

Therefore if you want to ouput the rendered  instead of >a /< you use the NoEncode function to convert it to valid xml.

Hope that makes sense.


问:
How can I adapt a unix Perl command to Windows?
In https://oracle-base.com/articles/misc/install-sample-schemas. Tim Hall proposes the following command (once positioned in a particular directory) to replace the string __SUB__CWD__ by the name of the current directory in sql files and dat files:

```<code>cd ...
perl -p -i.bak -e 's#__SUB__CWD__#'$(pwd)'#g' *.sql */*.sql */*.dat
</code>```

How can adapt this command for Windows?
Even if the name of directory is constant (ex: C:\app\soutou\product\18.0.0\dbhomeXE\demo\schema). I am not a user of Perl (Oracle dev)

答:
If you install Strawberry Perl on your windows box this command should just work from the cmd.com shell</p>

```<code>perl -i.bak -MCwd -pe"BEGIN{ $cwd = cwd; @ARGV = map glob, @ARGV; } s#__SUB__CWD__#$cwd#g" *.sql *\*.sql *\*.dat
</code>```

Body:
In https://oracle-base.com/articles/misc/install-sample-schemas. Tim Hall proposes the following command (once positioned in a particular directory) to replace the string __SUB__CWD__ by the name of the current directory in sql files and dat files:

cd ...
perl -p -i.bak -e 's#__SUB__CWD__#'$(pwd)'#g' *.sql */*.sql */*.dat

How can adapt this command for Windows?
Even if the name of directory is constant (ex: C:\app\soutou\product\18.0.0\dbhomeXE\demo\schema). I am not a user of Perl (Oracle dev)

Body:
If you install Strawberry Perl on your windows box this command should just work from the cmd.com shell

perl -i.bak -MCwd -pe"BEGIN{ $cwd = cwd; @ARGV = map glob, @ARGV; } s#__SUB__CWD__#$cwd#g" *.sql *\*.sql *\*.dat