问:
Using Flink with thrift
I'm seeing some logs within my flink app with respect to my thrift classes:

```<code>2020-06-01 14:31:28 INFO  TypeExtractor:1885 - Class class com.test.TestStruct contains custom serialization methods we do not call, so it cannot be used as a POJO type and must be processed as GenericType. Please read the Flink documentation on "Data Types & Serialization" for details of the effect on performance.
</code>```

So I followed the instructions here:

https://flink.apache.org/news/2020/04/15/flink-serialization-tuning-vol-1.html#apache-thrift-via-kryo

And I did that for the thrift of TestStruct along with all the thrift structs within that. ( I've skipped over named types though ).

Also the thrift code that got generated is in Java whereas the flink app is written using scala.

How would I make that error disappear? Because I'm getting another bug where if I pass my dataStream to convert into that TestStruct, some fields are missing. I suspect this is due to serialization issues?

答:
Actually, as of now, you can't get rid of this warning, but it is also not a problem for the following reason:

The warning basically just says that Flink's type system is not using any of its internal serializers but will instead treat the type as a "generic type" which means, it is serialized via Kryo. If you followed my blog post on this, this is exactly what you want: use Kryo to serialize via Thrift. You could use a debugger to set a breakpoint into TBaseSerializer to verify that Thrift is being used.

As for the missing fields, I would suspect that this happens during the conversion into your TestStruct in your (flat)map operator and maybe not in the serialization that is used to pass this struct to the next operator. You should verify where these fields get missing - if you have this reproducible, a breakpoint in the debugger of your favourite IDE should help you find the cause.

Title: Using Flink with thrift

Body:
I'm seeing some logs within my flink app with respect to my thrift classes:

2020-06-01 14:31:28 INFO  TypeExtractor:1885 - Class class com.test.TestStruct contains custom serialization methods we do not call, so it cannot be used as a POJO type and must be processed as GenericType. Please read the Flink documentation on "Data Types & Serialization" for details of the effect on performance.

So I followed the instructions here:

https://flink.apache.org/news/2020/04/15/flink-serialization-tuning-vol-1.html#apache-thrift-via-kryo

And I did that for the thrift of TestStruct along with all the thrift structs within that. ( I've skipped over named types though ).

Also the thrift code that got generated is in Java whereas the flink app is written using scala.

How would I make that error disappear? Because I'm getting another bug where if I pass my dataStream to convert into that TestStruct, some fields are missing. I suspect this is due to serialization issues?


来源: stackexchange

问:
CS cockpit perspective is not coming in Hybris-1811
I have added CS-Agent role for my use. After login into backoffice, I can see below perspectives in the dropdown, but not cs perspective. Did I miss anything?

Administration

Product Cockpit

Adaptive Search

Check Warehousing Availability

答:
Need to add below user groups:

customersupportagentgroup

customersupportdirectorrole

customersupportmanagergroup

customersupportsupervisorrole

ContentLicense: CC BY-SA 4.0


问:
looking for Windows RAM-based shared memory solution in C++
I'm facing a situation where I need to pass up to several hundreds of megabytes of memory from one process to another. Right now I'm doing it via files and it's too slow.
I guess that to make it quicker, those files should be written directly to RAM and be accessible from another process. No fancy synchronization required. One process would create  shared memory objects and would fill them with data. The other process would read and remove them. However I've done a quick research and it seems like you can't share memory in RAM in Windows - the shared memory is backed by either a file or paging file. The docs of boost::interprocess confirm this. Where is the speed up then if the shared memory implementation still uses disk? Is there any C++ library that uses RAM-based shared memory?

EDIT: I made some further reading:
1. from boost::interprocess docs:
"as the operating system has to synchronize the file contents with the memory contents, memory-mapped files are not as fast as shared memory. "
2. from http://msdn.microsoft.com/en-us/library/ms810613.aspx:
"A memory-mapped file can also be mapped by more than one application simultaneously. This represents the only mechanism for two or more processes to directly share data in Windows NT."

答:
I would still suggested memory mapped files instead of the approach I will mention.

If you really want to read from another process memory, use Win32 API ReadProcessMemory().

If you are paranoid on keeping data in RAM, there are Unix mlock() equivalents in MS Windows VirtualLock()

ContentLicense: CC BY-SA 3.0


问:
selenium isn't loading the page
```<code>from selenium import webdriver
driver= webdriver.Chrome()
driver.get('https://www.realestate.com.au/sold/') #opens normally but anything I search for doesn't load
driver.get('https://www.realestate.com.au/sold/in-alice+springs+-+greater+region%2c+nt%3b/list-1')
</code>```

The website opens and I don't get any captcha or block but the page doesn't load

答:
It seem some "Flash" problem (you can read the error in "chromedriver" window:

```<code>Browser not compatible with given flash manifest
</code>```

This site use flash and your browser need flash player.
By saying your browser I mean selenium browser, not that chrome you open manually.

To install "flash player" in selenium chrome browser, run your script; it will open the browser, then go to https://get.adobe.com/flashplayer/ and install flash player.

This should solve the problem

Title: selenium isn't loading the page

Body:
from selenium import webdriver
driver= webdriver.Chrome()
driver.get('https://www.realestate.com.au/sold/') #opens normally but anything I search for doesn't load
driver.get('https://www.realestate.com.au/sold/in-alice+springs+-+greater+region%2c+nt%3b/list-1')

The website opens and I don't get any captcha or block but the page doesn't load

Body:
It seem some "Flash" problem (you can read the error in "chromedriver" window:

Browser not compatible with given flash manifest

This site use flash and your browser need flash player.
By saying your browser I mean selenium browser, not that chrome you open manually.

To install "flash player" in selenium chrome browser, run your script; it will open the browser, then go to https://get.adobe.com/flashplayer/ and install flash player.

This should solve the problem


问:
Why does a blur filter with a transition have some lag and problem?
After hovering on an image, I have a white lag in the edges of the image and then this will be hidden!!! How can I fix this?

The code is here:

```<code>img {
    width: 100%;
    transform: scale(1.1);
    @include transition_all(0.3s);
}

img:hover {
    filter: blur(10px);
    -webkit-filter: blur(10px);
    -moz-filter: blur(10px);
    -o-filter: blur(10px);
    -ms-filter: blur(10px);
}

<a href="assets/images/portfolio/1.jpg" class="portfolio-item images" data-featherlight="image">
    <div class="portfolio-item-wrap">
        <img src="assets/images/portfolio/1.jpg" alt="portfolio title"/>
        <div class="desc">
             <h5>Gallery</h5>
             <h4>Fruits Images</h4>
        </div>
    </div>
</a>
</code>```

答: The blur filter is quite heavy on resources, and you can't do anything about it. I usually avoid using blur filters for that reason.</p>

Body:
After hovering on an image, I have a white lag in the edges of the image and then this will be hidden!!! How can I fix this?

The code is here:

img {
    width: 100%;
    transform: scale(1.1);
    @include transition_all(0.3s);
}

img:hover {
    filter: blur(10px);
    -webkit-filter: blur(10px);
    -moz-filter: blur(10px);
    -o-filter: blur(10px);
    -ms-filter: blur(10px);
}

Gallery

Fruits Images


问:
Spring API + Vue JS Web Application slows down extremely in production
I built a basic web application to learn about Spring Boot and Vue.js.

When running the applications on localhost, everything runs smoothly, i.e. every request needs well under 1 sec.

Now I deployed the application on heroku to put it into production, but the performance slowed down tremendously. Every action that requires an API call takes quite exactly 5-7 seconds.

Of course a slow down is to be expected when using a free hosting provider. However, this is extreme.

Now the region set in Heroku for the Spring API is Europe, the database for the application is in SG and I sit in the PHilippines, which I assume could explain some of the lag.

When following the logs in heroku, the API call shows up about 6 seconds after I send it, with the response coming right after (<1sec).

Which leads to my question:

How will I be able to find the bottleneck here and what can I do to fix this?

Here is the link for the API (the api contains only demo data, so please don't mind the exposed passwords...)
https://brownbag-api.herokuapp.com/api/pos/all

答:
The issue was the delay between the Spring Boot API and the MySQL database.

Moving to a database on the same dyno as the Spring boot API fixed the issue.


问:
How to get round value if value is in decimal in php?
```<code>$str = 6.87;
$x = ceil($str/5) * 5;
echo $x;
</code>```

I have a variable str and I want to covert str round value. In above I have 6.87 and I want 6.9 and if I have 6.43 then it should be 6.4 similarly if $str = 6.45 then it become 6.5. So, How can I do this? Please help me.

Thank You

答:
You should use round() with 2nd parameter 1 like following code :

```<code>echo $str = round(6.45,1);
</code>```

Output:

```<code>6.5
</code>```

Body:
$str = 6.87;
$x = ceil($str/5) * 5;
echo $x;

I have a variable str and I want to covert str round value. In above I have 6.87 and I want 6.9 and if I have 6.43 then it should be 6.4 similarly if $str = 6.45 then it become 6.5. So, How can I do this? Please help me.

Thank You

Body:
You should use round() with 2nd parameter 1 like following code :

echo $str = round(6.45,1);

Output:

6.5


问:
PowerBI Dax creating a summary table from many other tables
I have a number of tables 18 or so and i'm trying to create a summary table that brings all this together, however i'm struggling to workout how i create a column that each cell looks at a different table and gets me a total from each table. Example below

If anyone can help on how to do this in powerbi that would be awsome

答: In PowerBI go to modelling tab -> Select new table and create a new table Like below:


问:
Taking experimental errors into account in lmfit
I am trying to implement lmfit into my fitting routines, and I am having issues defining the errors. I premise that I read previous questions regarding the topic on this platform, and I also went through the docs, but some of my doubts are still there.

Below is a complete and minimal example of what I am trying to achieve.

```<code>import corner
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import scipy as sp
import lmfit

font = {'fontname':'candara', "fontweight":"light"}
plt.style.use('ggplot')
plt.rcParams["figure.figsize"] = (8,4)
ax_fit_kws = dict(xlim=(0,0.12), ylim=(0.5,1.1))
ax_res_kws = dict(xlim=(0,0.12), ylim=(-0.1,0.1))

def mono_exp(SL_array, a, b):
    model = a * np.exp(-b * SL_array)
    return model
model = lmfit.Model(mono_exp)

SL_array = np.array((0.030, 0.040, 0.060, 0.080, 0.10))
data= np.array((1., 0.9524336, 0.92452666, 0.87995659, 0.82845576))
errs = np.array((0.00029904, 0.00049384, 0.00076344, 0.00053886, 0.00066012))

params = model.make_params(a=0, b=0)

result = model.fit(data=data, params=params, SL_array=SL_array, method="Nelder", markersize=10, weights=errs)

lmfit.report_fit(result)
result.plot(yerr = errs, ax_fit_kws=ax_fit_kws, ax_res_kws=ax_res_kws)

emcee_kws = dict(steps=400, burn=30, thin=20, is_weighted=False,
                 progress=True)
emcee_params = result.params.copy()
emcee_params.add('__lnsigma', value=np.log(0.1), min=np.log(0.001), max=np.log(2.0))
result_emcee = model.fit(data=data, SL_array=SL_array, params=emcee_params, method='emcee',
                         nan_policy='omit', fit_kws=emcee_kws)

lmfit.report_fit(result_emcee)

ax = plt.plot(SL_array, model.eval(params=result.params, SL_array=SL_array), label='Nelder', zorder=100)
result_emcee.plot_fit(ax=ax, data_kws=dict(color='gray', markersize=10), yerr = errs)
emcee_corner = corner.corner(result_emcee.flatchain, labels=result_emcee.var_names,
                             truths=list(result_emcee.params.valuesdict().values()))
plt.show()
</code>```

My problem is rather simple: I would like the initial Nelder fitting routine to take into account the errs array as errors on the data array (which are my experimentally determined points). I am not sure that calling weights=errs achieves this goal. I have tried the solution implemented here: How do I include errors for my data in the lmfit least squares miniimization, and what is this error for conf_interval2d function in lmfit?
But I could not make it work.

Another point which is not really clear to me is: does the emcee part of my fit take into account the residuals from the Nelder routine?

Many thanks in advance!

EDIT

After a bit more of research, I now believe that when calling weights I should actually give 1/err. By implementing this change, and applying scale_covar=False as described elsewhere (How to properly get the errors in lmfit) while artifically incrementing the error values (for instance, deliberate multiplication of the errs array by 100-fold) I do get the fitted parameters errors to increase substantially, which is an expected behaviour. In short: result = model.fit(data=data, params=params, SL_array=SL_array, method="Nelder", markersize=10, weights=errs) was changed to result = model.fit(data=data, params=params, SL_array=SL_array, method="Nelder", markersize=10, weights=1/errs). Is this correct?

I am still rather confused on the implementation of emcee in my case.

答:
What you say in your edits is correct:   You want to use weights=1./err to properly weight the residual of data and model by the uncertainties in the data, err.

You probably want to use the same in your call to model.fit(..., method='emcee') too.

I should say that the use of emcee in lmfit is rather confusing and gives the unfortunate impression that it is doing a fit. This is simply not true, as emcee (and, really MCMC as a method) can not really do a fit in the sense of "systematically refine parameter values in order to find an improved solution".  What it is doing is exploring parameter space in the vicinity of the input parameter values (that happen to be the solution from the Nelder method).
This exploration may find (more like "stumble upon" than "seek") an improved solution and the results will reflect the exploration it does.

Body:
I am trying to implement lmfit into my fitting routines, and I am having issues defining the errors. I premise that I read previous questions regarding the topic on this platform, and I also went through the docs, but some of my doubts are still there.

Below is a complete and minimal example of what I am trying to achieve.

import corner
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import scipy as sp
import lmfit

font = {'fontname':'candara', "fontweight":"light"}
plt.style.use('ggplot')
plt.rcParams["figure.figsize"] = (8,4)
ax_fit_kws = dict(xlim=(0,0.12), ylim=(0.5,1.1))
ax_res_kws = dict(xlim=(0,0.12), ylim=(-0.1,0.1))

def mono_exp(SL_array, a, b):
    model = a * np.exp(-b * SL_array)
    return model
model = lmfit.Model(mono_exp)

SL_array = np.array((0.030, 0.040, 0.060, 0.080, 0.10))
data= np.array((1., 0.9524336, 0.92452666, 0.87995659, 0.82845576))
errs = np.array((0.00029904, 0.00049384, 0.00076344, 0.00053886, 0.00066012))

params = model.make_params(a=0, b=0)

result = model.fit(data=data, params=params, SL_array=SL_array, method="Nelder", markersize=10, weights=errs)

lmfit.report_fit(result)
result.plot(yerr = errs, ax_fit_kws=ax_fit_kws, ax_res_kws=ax_res_kws)

emcee_kws = dict(steps=400, burn=30, thin=20, is_weighted=False,
                 progress=True)
emcee_params = result.params.copy()
emcee_params.add('__lnsigma', value=np.log(0.1), min=np.log(0.001), max=np.log(2.0))
result_emcee = model.fit(data=data, SL_array=SL_array, params=emcee_params, method='emcee',
                         nan_policy='omit', fit_kws=emcee_kws)

lmfit.report_fit(result_emcee)

ax = plt.plot(SL_array, model.eval(params=result.params, SL_array=SL_array), label='Nelder', zorder=100)
result_emcee.plot_fit(ax=ax, data_kws=dict(color='gray', markersize=10), yerr = errs)
emcee_corner = corner.corner(result_emcee.flatchain, labels=result_emcee.var_names,
                             truths=list(result_emcee.params.valuesdict().values()))
plt.show()

My problem is rather simple: I would like the initial Nelder fitting routine to take into account the errs array as errors on the data array (which are my experimentally determined points). I am not sure that calling weights=errs achieves this goal. I have tried the solution implemented here: How do I include errors for my data in the lmfit least squares miniimization, and what is this error for conf_interval2d function in lmfit?
But I could not make it work.

Another point which is not really clear to me is: does the emcee part of my fit take into account the residuals from the Nelder routine?

Many thanks in advance!

EDIT

After a bit more of research, I now believe that when calling weights I should actually give 1/err. By implementing this change, and applying scale_covar=False as described elsewhere (How to properly get the errors in lmfit) while artifically incrementing the error values (for instance, deliberate multiplication of the errs array by 100-fold) I do get the fitted parameters errors to increase substantially, which is an expected behaviour. In short: result = model.fit(data=data, params=params, SL_array=SL_array, method="Nelder", markersize=10, weights=errs) was changed to result = model.fit(data=data, params=params, SL_array=SL_array, method="Nelder", markersize=10, weights=1/errs). Is this correct?

I am still rather confused on the implementation of emcee in my case.


问:
Sharing an API gateway between micro services in Serverless
I'm fairly new to Serverless. I recently hit the dreaded 200 resource limit issue on Serverless and hence I'm trying to break down my services and use a common API gateway between them but I keep getting Another resource with the same parent already has this name: assets. I am using the common api gateway property because I don't have a domain for this service.

This is my main serverless.yml

```<code>    app: xxx
    org: xxx
    service: xxx
    provider:
      name: aws
      runtime: nodejs12.x
      region: xxx
functions:
....
    resources:
      Outputs:

        ApiGatewayRestId:
          Value:
            Ref: ApiGatewayRestApi
          Export:
            Name: assetsapi-${opt:stage, self:provider.stage}-ApiGatewayRestId
        RootResourceId:
          Value:
            Fn::GetAtt:
              - ApiGatewayRestApi
              - RootResourceId
          Export:
            Name: assetsapi-${opt:stage, self:provider.stage}-RootResourceId
        IamRoleLambdaExecution:
          Value:
            Fn::GetAtt: IamRoleLambdaExecution.Arn
          Export:
            Name: assetsapi-${opt:stage, self:provider.stage}-IamRoleLambdaExecution
        ApiGatewayResourceMaintainence:
          Value:
            Ref: ApiGatewayResourceMaintainence
          Export:
            Name: assetsapi-${opt:stage, self:provider.stage}-ApiGatewayResourceMaintainence
    Resources:
        # Rest API
        ApiGatewayRestApi:
          Type: AWS::ApiGateway::RestApi
          Properties:
            Name: assetsapi
            Description: assets API Gateway

        # Rest API Paths
        ApiGatewayResourceMaintainence:
          Type: AWS::ApiGateway::Resource
          Properties:
            RestApiId: { Ref: 'ApiGatewayRestApi' }
            ParentId: { Fn::GetAtt: 'ApiGatewayRestApi.RootResourceId' }
            PathPart: maintain
</code>```

This the serverless.yml file for the second service which resides inside the path api/maintainence/serverless.yml

```<code>    service: maintainencemanagementservice
    custom:
      stage: '${opt:stage, self:provider.stage}'
      region: ${opt:region, self:provider.region}
      prefix: ${self:service}-${self:custom.region}-${self:custom.stage}
      rootApiGatewayId: 'assets-api-${self:custom.region}-${self:custom.stage}-restApiId'
      rootApiGatewayResourceId: 'assets-api-${self:custom.region}-${self:custom.stage}-rootResourceId'
    provider:
      name: aws
      runtime: nodejs12.x
      stage: dev
      region: xxxx
      apiGateway:
        restApiId:
          Fn::ImportValue: assetsapi-${opt:stage, self:provider.stage}-ApiGatewayRestId
        restApiRootResourceId:
          Fn::ImportValue: assetsapi-${opt:stage, self:provider.stage}-RootResourceId
        restApiResources:
          /maintainence:
            Fn::ImportValue: assetsapi-${opt:stage, self:provider.stage}-ApiGatewayResourceMaintainence,
      role:
        Fn::ImportValue: assetsapi-${opt:stage, self:provider.stage}-IamRoleLambdaExecution
</code>```

答: I accidentally used the same path beginning in the second service function i.e. assets/addmaintainence Changing it to maintainence/addmaintainence did the trick

Body:
I'm fairly new to Serverless. I recently hit the dreaded 200 resource limit issue on Serverless and hence I'm trying to break down my services and use a common API gateway between them but I keep getting Another resource with the same parent already has this name: assets. I am using the common api gateway property because I don't have a domain for this service.

This is my main serverless.yml

    app: xxx
    org: xxx
    service: xxx
    provider:
      name: aws
      runtime: nodejs12.x
      region: xxx
functions:
....
    resources:
      Outputs:

        ApiGatewayRestId:
          Value:
            Ref: ApiGatewayRestApi
          Export:
            Name: assetsapi-${opt:stage, self:provider.stage}-ApiGatewayRestId
        RootResourceId:
          Value:
            Fn::GetAtt:
              - ApiGatewayRestApi
              - RootResourceId
          Export:
            Name: assetsapi-${opt:stage, self:provider.stage}-RootResourceId
        IamRoleLambdaExecution:
          Value:
            Fn::GetAtt: IamRoleLambdaExecution.Arn
          Export:
            Name: assetsapi-${opt:stage, self:provider.stage}-IamRoleLambdaExecution
        ApiGatewayResourceMaintainence:
          Value:
            Ref: ApiGatewayResourceMaintainence
          Export:
            Name: assetsapi-${opt:stage, self:provider.stage}-ApiGatewayResourceMaintainence
    Resources:
        # Rest API
        ApiGatewayRestApi:
          Type: AWS::ApiGateway::RestApi
          Properties:
            Name: assetsapi
            Description: assets API Gateway

        # Rest API Paths
        ApiGatewayResourceMaintainence:
          Type: AWS::ApiGateway::Resource
          Properties:
            RestApiId: { Ref: 'ApiGatewayRestApi' }
            ParentId: { Fn::GetAtt: 'ApiGatewayRestApi.RootResourceId' }
            PathPart: maintain

This the serverless.yml file for the second service which resides inside the path api/maintainence/serverless.yml

    service: maintainencemanagementservice
    custom:
      stage: '${opt:stage, self:provider.stage}'
      region: ${opt:region, self:provider.region}
      prefix: ${self:service}-${self:custom.region}-${self:custom.stage}
      rootApiGatewayId: 'assets-api-${self:custom.region}-${self:custom.stage}-restApiId'
      rootApiGatewayResourceId: 'assets-api-${self:custom.region}-${self:custom.stage}-rootResourceId'
    provider:
      name: aws
      runtime: nodejs12.x
      stage: dev
      region: xxxx
      apiGateway:
        restApiId:
          Fn::ImportValue: assetsapi-${opt:stage, self:provider.stage}-ApiGatewayRestId
        restApiRootResourceId:
          Fn::ImportValue: assetsapi-${opt:stage, self:provider.stage}-RootResourceId
        restApiResources:
          /maintainence:
            Fn::ImportValue: assetsapi-${opt:stage, self:provider.stage}-ApiGatewayResourceMaintainence,
      role:
        Fn::ImportValue: assetsapi-${opt:stage, self:provider.stage}-IamRoleLambdaExecution


问:
Is there a way to parameterize the HTTP method when using System.Net.Http.HttpClient?
I'm using HttpClient in .Net core 3.1. Most of my requests follow a similar pattern regardless of the HTTP method used:

build URL

build (optional) JSON payload

send request

await response

check status code

parse (optional) JSON response

so I've built a wrapper function that does all these things, and it takes the HTTP method as a parameter. However, when it comes to the "send request" step, I need to use a switch statement to invoke the appropriate method on HttpClient to invoke.

I'm sure that under the skin, get GetAsync() PostAsync() etc. are calling the same underlying function and passing the Http method as a parameter. but I can't see any way of calling it like this from the outside. It seems a strange omission as in my experience most HTTP libraries work that way.

答:
Hope this will help you.</p>

```<code>// For JsonConvert use Newtonsoft.Json
string url = "YourURL";
string body = JsonConvert.SerializeObject(BodyModel);
string headerParameter = "ASD123456789";
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); // Content-Type of request, it can be application/xml to other
client.DefaultRequestHeaders.Add("Device", headerParameter ); // first is name, second one is value
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, url) // there you can have Get, Post, Put, Delete and etc. And every request needs to be configured by its settings
{
    Content = new StringContent(body, Encoding.UTF8, "application/json")
};
HttpResponseMessage response = await client.SendAsync(request);
if ((int)response.StatusCode == 200)
{
    string responseString = await response.Content.ReadAsStringAsync();
    ResponseModel responseModel = JsonConvert.DeserializeObject<ResponseModel>(responseString);
}
</code>```

Body:
Hope this will help you.

// For JsonConvert use Newtonsoft.Json
string url = "YourURL";
string body = JsonConvert.SerializeObject(BodyModel);
string headerParameter = "ASD123456789";
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); // Content-Type of request, it can be application/xml to other
client.DefaultRequestHeaders.Add("Device", headerParameter ); // first is name, second one is value
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, url) // there you can have Get, Post, Put, Delete and etc. And every request needs to be configured by its settings
{
    Content = new StringContent(body, Encoding.UTF8, "application/json")
};
HttpResponseMessage response = await client.SendAsync(request);
if ((int)response.StatusCode == 200)
{
    string responseString = await response.Content.ReadAsStringAsync();
    ResponseModel responseModel = JsonConvert.DeserializeObject<ResponseModel>(responseString);
}


问:
Ambari server can not register ambari agents
I want to install hadoop cluster with ambari server, but following error occurs

Registering with the server...

Registration with the server failed.

Steps

I have manually installed ambari agents on two slave hosts

Then I have ran agent services on slaves.

Provided ambari-server's ip in agent config file

Provided FQDNs of hosts during cluster installation wizard

During connecting to agents error occurs.

Note: With ping command I am able to rich out to slaves from master.

Error image

答:
@GrigVardanyan

Based on the image you provided, it looks like there is no resolve for the FQDNs from the ambari-server to the agents.  If it was able to connect the modal you click for FAILED will have much more detailed information.

Here are some very important points in very specific order:

You can install an agent on the Ambari Server too.

Make sure each servers hostname is set to the FQDN

Make sure /etc/hosts on Ambari Server, and Agent Servers defines all the FQDNs to the correct ip addresses.

Complete the steps to generate ssh keys on the Ambari Server (ssh-keygen)

Copy the Ambari Server SSH Public Key (~/.ssh/id_rsa.pub) to all nodes file: ~/.ssh/authorized_keys

SSH from Ambari Server to each Agent Server to confirm SSH Keys work and allow password less login.  During first login you need to answer the prompt YES.

During cluster install wizard use the Ambari Server Private Key (~/.ssh/id_rsa) on the declare hosts page.  Let ambari use SSH to install, configure the agents.  If you complete it in this manner, you will not need to touch the agent configuration files.


问:
Naming convention for Azure B2C
If I have a company, xyz, with a domain name, xyz.com, I would have a tenant, xyz.onmicrosoft.com. My AD for employees would be xyz. What would I typically name my B2C tenant? It can't be xyz, correct? What have others done?

UPDATE
In looking at examples I saw a reference to contosob2c, and it seemed to make sense to me as a good approach. In my example xyz would be the AD domain/directory/tenant for employees (xyz.onmicrosoft.com) and I would create a B2C directory as xyzb2c for customers (xyzb2c.onmicrosoft.com).

答: You determine what your audience (customers) would deem sensible, since they will authenticate at xyz.b2clogin.com.</p>

Title: Naming convention for Azure B2C


答:
it should be more like this.. the 1 being number of position(s) to round up to.

```<code>$str = 6.87;
echo(round($str,1));
</code>```

which will give you 6.9

Title: How to get round value if value is in decimal in php?

Body:
it should be more like this.. the 1 being number of position(s) to round up to.

$str = 6.87;
echo(round($str,1));

which will give you 6.9


问:
itertools: How to generate n-tuple list out of (n-1)-tuple list and a list?
I would like to create a list of n-tuples based on a list of (n-1)-tuples and a list.

Below a minimized example for n=3 and list length of 5.

```<code>import itertools

# create a list with 5 elements
t1_list = [x for x in range(1,6)]
print(t1_list)    # [1, 2, 3, 4, 5]

# create 2-tuples out of t1_list
t2 = itertools.combinations(t1_list,2)
t2_list = [x for x in t2]
print(t2_list)    # [(1, 2), (1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5), (3, 4), (3, 5), (4, 5)]

# remove some tuples based on some criterion
del t2_list[1]
del t2_list[4]
print(t2_list)    # [(1, 2), (1, 4), (1, 5), (2, 3), (2, 5), (3, 4), (3, 5), (4, 5)]

# now create a list of 3-tuples based on t2_list and t1_list
# i.e. without combinations containing (1,3) and (2,4) because they have been removed
# ???

# Result should be:
# [(1, 2, 5), (1, 4, 5), (2, 3, 5), (3, 4, 5)]
</code>```

I guess would not be a good idea to create all possible n-tuples from t1_list and then delete the ones which contain the removed (n-1)-tuples, because at a later stage I would like to do this with up to 10-tuples out of a 100 element list.

Is there maybe a smart way to do this with itertools?

Edit:  Clarification how to get to the desired result:

(1, 2, 4) is excluded because (2, 4) is not present in t2_list and (1, 2, 3) is excluded because (1,3) is not present in t2_list.

The general rule would be: a n-tuple will be included only if all its (n-1)-tuples are existing in the t(n-1)_list. Or the other way round: an n-tuple will be excluded if one or more of its (n-1)-tuples are missing in the t(n-1)_list.

答:
That's how far I've gotten in the meantime. The example below shows a list of length 6 (different from the original question).
The result seems to be correct. However, I don't know whether this is nice and efficient code, especially when t1_list will have 100 elements and it goes up to 8- or 10-tuples. I need to test further. Suggestions for improvements are very welcome.

Code:

```<code>### create n-tuples list based on (n-1)-tuples list and a list
import itertools

# create a list with nmax elements
nmax = 6
t1_list = [x for x in range(1,nmax+1)]
print("T1_list:", t1_list)

# create 2-tuples out of t1_list
t2 = itertools.combinations(t1_list,2)
t2_list = [x for x in t2]
print("T2_list:", t2_list)

# remove some tuples based on a calculation result
del t2_list[1]
del t2_list[4]
print("T2_list after removal of some elements:", t2_list)

def create_ntuple_list(tn1_list, t1_list):   # create n-tuples out of (n-1)_list and t1_list
    tn_list = []
    for tn1 in tn1_list:    # i.e. t(n-1)_list
        n = len(tn1) + 1        # determine n
        tn1max = max(tn1)
        for t1 in t1_list:
            if t1 > tn1max:
                tn_tmp = tuple(list(tn1)+[t1])
                tn1_iter = itertools.combinations(tn_tmp,n-1)
                for tn1_tmp in tn1_iter:
                    if tn1_tmp not in tn1_list:
                        break
                else:
                    tn_list.append(tn_tmp)
    return tn_list

# create 3-tuples
t3_list = create_ntuple_list(t2_list, t1_list)
print("T3_list:", t3_list)

# remove some tuples based on a calculation result
del t3_list[2]
print("T3_list after removal of some elements", t3_list)

# create 4-tuples
t4_list = create_ntuple_list(t3_list, t1_list)
print("T4_list:", t4_list)

### end of code
</code>```

Result:

```<code>T1_list: [1, 2, 3, 4, 5, 6]

T2_list: [(1, 2), (1, 3), (1, 4), (1, 5), (1, 6), (2, 3), (2, 4), (2, 5), (2, 6), (3, 4), (3, 5), (3, 6), (4, 5), (4, 6), (5, 6)]

T2_list after removal of some elements: [(1, 2), (1, 4), (1, 5), (1, 6), (2, 4), (2, 5), (2, 6), (3, 4), (3, 5), (3, 6), (4, 5), (4, 6), (5, 6)]

T3_list: [(1, 2, 4), (1, 2, 5), (1, 2, 6), (1, 4, 5), (1, 4, 6), (1, 5, 6), (2, 4, 5), (2, 4, 6), (2, 5, 6), (3, 4, 5), (3, 4, 6), (3, 5, 6), (4, 5, 6)]

T3_list after removal of some elements [(1, 2, 4), (1, 2, 5), (1, 4, 5), (1, 4, 6), (1, 5, 6), (2, 4, 5), (2, 4, 6), (2, 5, 6), (3, 4, 5), (3, 4, 6), (3, 5, 6), (4, 5, 6)]

T4_list: [(1, 2, 4, 5), (1, 4, 5, 6), (2, 4, 5, 6), (3, 4, 5, 6)]
</code>```

Body:
I would like to create a list of n-tuples based on a list of (n-1)-tuples and a list.

Below a minimized example for n=3 and list length of 5.

import itertools

# create a list with 5 elements
t1_list = [x for x in range(1,6)]
print(t1_list)    # [1, 2, 3, 4, 5]

# create 2-tuples out of t1_list
t2 = itertools.combinations(t1_list,2)
t2_list = [x for x in t2]
print(t2_list)    # [(1, 2), (1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5), (3, 4), (3, 5), (4, 5)]

# remove some tuples based on some criterion
del t2_list[1]
del t2_list[4]
print(t2_list)    # [(1, 2), (1, 4), (1, 5), (2, 3), (2, 5), (3, 4), (3, 5), (4, 5)]

# now create a list of 3-tuples based on t2_list and t1_list
# i.e. without combinations containing (1,3) and (2,4) because they have been removed
# ???

# Result should be:
# [(1, 2, 5), (1, 4, 5), (2, 3, 5), (3, 4, 5)]

I guess would not be a good idea to create all possible n-tuples from t1_list and then delete the ones which contain the removed (n-1)-tuples, because at a later stage I would like to do this with up to 10-tuples out of a 100 element list.

Is there maybe a smart way to do this with itertools?

Edit:  Clarification how to get to the desired result:

(1, 2, 4) is excluded because (2, 4) is not present in t2_list and (1, 2, 3) is excluded because (1,3) is not present in t2_list.

The general rule would be: a n-tuple will be included only if all its (n-1)-tuples are existing in the t(n-1)_list. Or the other way round: an n-tuple will be excluded if one or more of its (n-1)-tuples are missing in the t(n-1)_list.

Body:
That's how far I've gotten in the meantime. The example below shows a list of length 6 (different from the original question).
The result seems to be correct. However, I don't know whether this is nice and efficient code, especially when t1_list will have 100 elements and it goes up to 8- or 10-tuples. I need to test further. Suggestions for improvements are very welcome.

Code:

### create n-tuples list based on (n-1)-tuples list and a list
import itertools

# create a list with nmax elements
nmax = 6
t1_list = [x for x in range(1,nmax+1)]
print("T1_list:", t1_list)

# create 2-tuples out of t1_list
t2 = itertools.combinations(t1_list,2)
t2_list = [x for x in t2]
print("T2_list:", t2_list)

# remove some tuples based on a calculation result
del t2_list[1]
del t2_list[4]
print("T2_list after removal of some elements:", t2_list)

def create_ntuple_list(tn1_list, t1_list):   # create n-tuples out of (n-1)_list and t1_list
    tn_list = []
    for tn1 in tn1_list:    # i.e. t(n-1)_list
        n = len(tn1) + 1        # determine n
        tn1max = max(tn1)
        for t1 in t1_list:
            if t1 > tn1max:
                tn_tmp = tuple(list(tn1)+[t1])
                tn1_iter = itertools.combinations(tn_tmp,n-1)
                for tn1_tmp in tn1_iter:
                    if tn1_tmp not in tn1_list:
                        break
                else:
                    tn_list.append(tn_tmp)
    return tn_list

# create 3-tuples
t3_list = create_ntuple_list(t2_list, t1_list)
print("T3_list:", t3_list)

# remove some tuples based on a calculation result
del t3_list[2]
print("T3_list after removal of some elements", t3_list)

# create 4-tuples
t4_list = create_ntuple_list(t3_list, t1_list)
print("T4_list:", t4_list)

### end of code

Result:

T1_list: [1, 2, 3, 4, 5, 6]

T2_list: [(1, 2), (1, 3), (1, 4), (1, 5), (1, 6), (2, 3), (2, 4), (2, 5), (2, 6), (3, 4), (3, 5), (3, 6), (4, 5), (4, 6), (5, 6)]

T2_list after removal of some elements: [(1, 2), (1, 4), (1, 5), (1, 6), (2, 4), (2, 5), (2, 6), (3, 4), (3, 5), (3, 6), (4, 5), (4, 6), (5, 6)]

T3_list: [(1, 2, 4), (1, 2, 5), (1, 2, 6), (1, 4, 5), (1, 4, 6), (1, 5, 6), (2, 4, 5), (2, 4, 6), (2, 5, 6), (3, 4, 5), (3, 4, 6), (3, 5, 6), (4, 5, 6)]

T3_list after removal of some elements [(1, 2, 4), (1, 2, 5), (1, 4, 5), (1, 4, 6), (1, 5, 6), (2, 4, 5), (2, 4, 6), (2, 5, 6), (3, 4, 5), (3, 4, 6), (3, 5, 6), (4, 5, 6)]

T4_list: [(1, 2, 4, 5), (1, 4, 5, 6), (2, 4, 5, 6), (3, 4, 5, 6)]


问:
How to backup a local Git repository?
I am using git on a relatively small project and I find that zipping the .git directory's contents might be a fine way to back up the project. But this is kind of weird because, when I restore, the first thing I need to do is git reset --hard.

Are there any problems with backing up a git repo this way? Also, is there any better way to do it (e.g., a portable git format or something similar?)?

答:
Found the simple official way after wading through the walls of text above that would make you think there is none.

Create a complete bundle with:

```<code>$ git bundle create <filename> --all
</code>```

Restore it with:

```<code>$ git clone <filename> <folder>
</code>```

This operation is atomic AFAIK. Check official docs for the gritty details.

Regarding "zip": git bundles are compressed and surprisingly small compared to the .git folder size.

Title: How to backup a local Git repository?

Body:
Found the simple official way after wading through the walls of text above that would make you think there is none.

Create a complete bundle with:

$ git bundle create <filename> --all

Restore it with:

$ git clone <filename> <folder>

This operation is atomic AFAIK. Check official docs for the gritty details.

Regarding "zip": git bundles are compressed and surprisingly small compared to the .git folder size.


问:
Removing password_digest from API json?
I'm using Sinatra to make a simple little API. I have not been able to figure out a way to remove the 'password_digest' field from the JSON I'm outputting. Well, I know of a long way that I can do it, but I have a feeling there is a much simpler way.

```<code>get "/users/all" do
content_type :json
@users = User.all

response = @users.map do |user|
  user = user.to_h
  user.delete("password_digest")
  user
end
response.to_json
</code>```

end

All I'm trying to do is remove the password_digest field from the output. Is there a simple way to do this? I've tried searching with no luck.

答:
```<code>get "/users/all" do
  content_type :json
  @users = User.all
  @users.to_json(except: [:password_digest])
end
</code>```

You can also overide #as_json on the model to remove the attribute completely from serialization:

```<code>class User < ActiveRecord::Base
  def as_json(**options)
    # this coerces the option into an array and merges the passed
    # values with defaults
    excluding = [options[:exclude]].flatten
                                   .compact
                                   .union([:password_digest])
    super(options.merge(exclude: excluding))
  end
end
</code>```

Title: Removing password_digest from API json?

Body:
I'm using Sinatra to make a simple little API. I have not been able to figure out a way to remove the 'password_digest' field from the JSON I'm outputting. Well, I know of a long way that I can do it, but I have a feeling there is a much simpler way.

get "/users/all" do
content_type :json
@users = User.all

response = @users.map do |user|
  user = user.to_h
  user.delete("password_digest")
  user
end
response.to_json

end

All I'm trying to do is remove the password_digest field from the output. Is there a simple way to do this? I've tried searching with no luck.

Body:
get "/users/all" do
  content_type :json
  @users = User.all
  @users.to_json(except: [:password_digest])
end

You can also overide #as_json on the model to remove the attribute completely from serialization:

class User < ActiveRecord::Base
  def as_json(**options)
    # this coerces the option into an array and merges the passed
    # values with defaults
    excluding = [options[:exclude]].flatten
                                   .compact
                                   .union([:password_digest])
    super(options.merge(exclude: excluding))
  end
end


问:
Display data from DataSet
I want to display data from DataSet to my ReportViewer. Currently I have 4 reports which contain basic data like NameSurname, NetworkLogin, Status, OrgUnitID and I created a filter which will filter this data using Status and OrgUnitID.

So far here is code

```<code>public void BindToData()
{
    try
    {
        DataSet ds = new DataSet();
        string connString = @"Data Source=(LocalDb)\MSSQLLocalDB;Initial Catalog=DesignSaoOsig1;Integrated Security=True";
        SqlConnection conn = new SqlConnection(connString);
        string strproc = "TestReport";
        using (SqlDataAdapter sda = new SqlDataAdapter(strproc, connString))
        {
            SqlCommand cmd = new SqlCommand();
            sda.SelectCommand.CommandType = CommandType.StoredProcedure;

            sda.SelectCommand.Parameters.Add("@Status", SqlDbType.Bit).Value = ddlStatus.SelectedValue == "1" ? true : false;
            sda.SelectCommand.Parameters.Add("@OrgJed", SqlDbType.Int).Value = ddlOrgUnit.SelectedValue;
            sda.Fill(ds);

            XtraReport report = new XtraReport();

            string nazivIzvjestaja = ds.Tables[0].Rows[0].ItemArray[0].ToString();

            if (string.IsNullOrEmpty(nazivIzvjestaja))
            {
                conn.Close();
            }

            report.DataSource = ds;
            report.DataMember = ds.Tables[0].ToString();

            string[] arrvalues = new string[ds.Tables[0].Rows.Count];

            for (int loopcounter = 0; loopcounter < ds.Tables[0].Rows.Count; loopcounter++)
            {
                //assign dataset values to array
                arrvalues[loopcounter] = ds.Tables[0].Rows[loopcounter]["PrezimeIme"].ToString();
                arrvalues[loopcounter] = ds.Tables[0].Rows[loopcounter]["NetworkLogin"].ToString();
                arrvalues[loopcounter] = ds.Tables[0].Rows[loopcounter]["Status"].ToString();
                arrvalues[loopcounter] = ds.Tables[0].Rows[loopcounter]["OrgUnitID"].ToString();
                arrvalues[loopcounter] = ds.Tables[0].Rows[loopcounter]["DT_Creat"].ToString();
                arrvalues[loopcounter] = ds.Tables[0].Rows[loopcounter]["DT_Modif"].ToString();
            }
        }
    }
    catch (Exception)
    {
        throw;
    }
}
</code>```

So far I use DevExpress. SO far I catch all data using for loop but I have problem and I don't know how to display these data to Report.

Any help will be more then welcome.

答:
As you have already said that you have bound the DataSet with the report you can preview the report for checking the result by inserting the following line after loop finished:

```<code>        report.ShowPreview();
</code>```

I noticed that you are using an untyped dataset for DevExpress it is need to be serialized as it is explained in detail official post of Dev Express:
Check for the Official Website blog

Title: Display data from DataSet

Body:
I want to display data from DataSet to my ReportViewer. Currently I have 4 reports which contain basic data like NameSurname, NetworkLogin, Status, OrgUnitID and I created a filter which will filter this data using Status and OrgUnitID.

So far here is code

public void BindToData()
{
    try
    {
        DataSet ds = new DataSet();
        string connString = @"Data Source=(LocalDb)\MSSQLLocalDB;Initial Catalog=DesignSaoOsig1;Integrated Security=True";
        SqlConnection conn = new SqlConnection(connString);
        string strproc = "TestReport";
        using (SqlDataAdapter sda = new SqlDataAdapter(strproc, connString))
        {
            SqlCommand cmd = new SqlCommand();
            sda.SelectCommand.CommandType = CommandType.StoredProcedure;

            sda.SelectCommand.Parameters.Add("@Status", SqlDbType.Bit).Value = ddlStatus.SelectedValue == "1" ? true : false;
            sda.SelectCommand.Parameters.Add("@OrgJed", SqlDbType.Int).Value = ddlOrgUnit.SelectedValue;
            sda.Fill(ds);

            XtraReport report = new XtraReport();

            string nazivIzvjestaja = ds.Tables[0].Rows[0].ItemArray[0].ToString();

            if (string.IsNullOrEmpty(nazivIzvjestaja))
            {
                conn.Close();
            }

            report.DataSource = ds;
            report.DataMember = ds.Tables[0].ToString();

            string[] arrvalues = new string[ds.Tables[0].Rows.Count];

            for (int loopcounter = 0; loopcounter < ds.Tables[0].Rows.Count; loopcounter++)
            {
                //assign dataset values to array
                arrvalues[loopcounter] = ds.Tables[0].Rows[loopcounter]["PrezimeIme"].ToString();
                arrvalues[loopcounter] = ds.Tables[0].Rows[loopcounter]["NetworkLogin"].ToString();
                arrvalues[loopcounter] = ds.Tables[0].Rows[loopcounter]["Status"].ToString();
                arrvalues[loopcounter] = ds.Tables[0].Rows[loopcounter]["OrgUnitID"].ToString();
                arrvalues[loopcounter] = ds.Tables[0].Rows[loopcounter]["DT_Creat"].ToString();
                arrvalues[loopcounter] = ds.Tables[0].Rows[loopcounter]["DT_Modif"].ToString();
            }
        }
    }
    catch (Exception)
    {
        throw;
    }
}

So far I use DevExpress. SO far I catch all data using for loop but I have problem and I don't know how to display these data to Report.

Any help will be more then welcome.

Body:
As you have already said that you have bound the DataSet with the report you can preview the report for checking the result by inserting the following line after loop finished:

        report.ShowPreview();

I noticed that you are using an untyped dataset for DevExpress it is need to be serialized as it is explained in detail official post of Dev Express:
Check for the Official Website blog


问:
PHP: Extract string from another
i have some strings (address), all like this:

2 rue lambda, 75018, PARIS

I want to get the postal code, in this exemple "75018". I've been trying different solution, but i'm not familiar with escaped characters , and don't know how to detect coma in the string. Which function should i use to extract the postal code?

答:
Is that always the format it will be in? If so you can explode.</p>

```<code>$str = '2 rue lambda, 75018, PARIS';
$array = explode(',',$str);
$street = $array[0];
$postal = $array[1];
$city = $array[2];
</code>```

Title: PHP: Extract string from another

Body:
Is that always the format it will be in? If so you can explode.

$str = '2 rue lambda, 75018, PARIS';
$array = explode(',',$str);
$street = $array[0];
$postal = $array[1];
$city = $array[2];


问:
Loading images results in 404 (Not Found) - webpack
This is the text of the error

I'm trying to load a few images in my game in Phaser 3.23.0
The images are loaded in the function preload() in the file below

main.js

```<code>import Phaser from 'phaser';

function preload() {
  this.load.image('sky', 'assets/sky.png');
  this.load.image('ground', 'assets/platform.png');
  this.load.image('star', 'assets/star.png');
  this.load.image('bomb', 'assets/bomb.png');
  this.load.spritesheet('dude',
    'assets/dude.png',
    { frameWidth: 32, frameHeight: 48 });
}

function create() {
  this.add.image(400, 300, 'sky');
}

function update() {
}

const config = {
  type: Phaser.AUTO,
  width: 800,
  height: 600,
  scene: {
    preload,
    create,
    update,
  },
};

// eslint-disable-next-line no-unused-vars
const game = new Phaser.Game(config);

const canvas = document.querySelector('canvas');

console.log(game);
</code>```

I type

```<code>npm run webpack-dev-server --mode development
</code>```

And starts webpack-dev-server in localhost:8080

Then I get these errors:

These are the errors in the console. Chrome browser.

These are the errors in the network. Chrome browser

These are the errors in the console. Firefox browser.

Firefox is not having any network activity. Not even one request.

index.html

```<code>    <!doctype html>
    <html lang="en">
    <head>
        <meta charset="UTF-8" />
        <title>Making your first Phaser 3 Game - Part 1</title>
        <style type="text/css">

        </style>
    </head>
    <body>
    </body>
    </html>
</code>```

webpack.config.js

```<code>const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');

const config = {
  entry: './src/scripts/main.js',
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        loader: 'babel-loader',
      },
      {
        test: /\.scss$/,
        use: [
          'style-loader',
          'css-loader',
          'sass-loader',
        ],
      },
      {
        test: /\.(jpe?g|png|gif|svg)$/i,
        use: {
          loader: 'file-loader?name=/src/assets/[name].[ext]',
          options: {
            name: '[name].[hash].[ext]',
            outputPath: 'assets/',
          },
        },
      },
      {
        test: /\.html$/i,
        loader: 'html-loader',
      },
    ],
  },
  output: {
    path: path.resolve(
      __dirname,
      'dist',
    ),
  },
  plugins: [
    new HtmlWebpackPlugin({
      title: 'Output Management',
      template: './src/index.html',
    }),
  ],
};

module.exports = (env, argv) => {
  if (argv.mode === 'development') {
    config.devtool = 'source-map';
    config.output.filename = 'main.bundle.js';
  }

  if (argv.mode === 'production') {
    config.plugins.push(new CleanWebpackPlugin());
    config.output.filename = 'main.[hash].bundle.js';
  }

  return config;
};
</code>```

This is the repo at the time this question was made.

答:
You have a 404.

change you main.js to:

```<code>function preload() {
  this.load.image('sky', require("../assets/sky.png").default);
  this.load.image('ground', require("../assets/platform.png").default);
  this.load.image('star', require("../assets/star.png").default);
  this.load.image('bomb', require("../assets/bomb.png").default);
  this.load.spritesheet('dude',
  require("../assets/dude.png").default,
    { frameWidth: 32, frameHeight: 48 });
}
</code>```

Now execute:

```<code>yarn start / npm start
</code>```

Body:
This is the text of the error

I'm trying to load a few images in my game in Phaser 3.23.0
The images are loaded in the function preload() in the file below

main.js

import Phaser from 'phaser';

function preload() {
  this.load.image('sky', 'assets/sky.png');
  this.load.image('ground', 'assets/platform.png');
  this.load.image('star', 'assets/star.png');
  this.load.image('bomb', 'assets/bomb.png');
  this.load.spritesheet('dude',
    'assets/dude.png',
    { frameWidth: 32, frameHeight: 48 });
}

function create() {
  this.add.image(400, 300, 'sky');
}

function update() {
}

const config = {
  type: Phaser.AUTO,
  width: 800,
  height: 600,
  scene: {
    preload,
    create,
    update,
  },
};

// eslint-disable-next-line no-unused-vars
const game = new Phaser.Game(config);

const canvas = document.querySelector('canvas');

console.log(game);

I type

npm run webpack-dev-server --mode development

And starts webpack-dev-server in localhost:8080

Then I get these errors:

These are the errors in the console. Chrome browser.

These are the errors in the network. Chrome browser

These are the errors in the console. Firefox browser.

Firefox is not having any network activity. Not even one request.

index.html

    <!doctype html>

        <meta charset="UTF-8" />
        <title>Making your first Phaser 3 Game - Part 1</title>

webpack.config.js

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');

const config = {
  entry: './src/scripts/main.js',
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        loader: 'babel-loader',
      },
      {
        test: /\.scss$/,
        use: [
          'style-loader',
          'css-loader',
          'sass-loader',
        ],
      },
      {
        test: /\.(jpe?g|png|gif|svg)$/i,
        use: {
          loader: 'file-loader?name=/src/assets/[name].[ext]',
          options: {
            name: '[name].[hash].[ext]',
            outputPath: 'assets/',
          },
        },
      },
      {
        test: /\.html$/i,
        loader: 'html-loader',
      },
    ],
  },
  output: {
    path: path.resolve(
      __dirname,
      'dist',
    ),
  },
  plugins: [
    new HtmlWebpackPlugin({
      title: 'Output Management',
      template: './src/index.html',
    }),
  ],
};

module.exports = (env, argv) => {
  if (argv.mode === 'development') {
    config.devtool = 'source-map';
    config.output.filename = 'main.bundle.js';
  }

  if (argv.mode === 'production') {
    config.plugins.push(new CleanWebpackPlugin());
    config.output.filename = 'main.[hash].bundle.js';
  }

  return config;
};

This is the repo at the time this question was made.

Body:
You have a 404.

change you main.js to:

function preload() {
  this.load.image('sky', require("../assets/sky.png").default);
  this.load.image('ground', require("../assets/platform.png").default);
  this.load.image('star', require("../assets/star.png").default);
  this.load.image('bomb', require("../assets/bomb.png").default);
  this.load.spritesheet('dude',
  require("../assets/dude.png").default,
    { frameWidth: 32, frameHeight: 48 });
}

Now execute:

yarn start / npm start


答:
Here is a nice and fast trick you can use (assuming l is your list):

```<code>list({ s.split(';', 1)[1] : s for s in l }.values())
</code>```

No need to import anything, and fast as can be.

In general you can define:

```<code>def custom_unique(L, keyfunc):
    return list({ keyfunc(li): li for li in L }.values())
</code>```

Title: What is an easy way to remove duplicates from only part of the string in Python?

Body:
I have a list of strings that goes like this:

1;213;164
2;213;164
3;213;164
4;213;164
5;213;164
6;213;164
7;213;164
8;213;164
9;145;112
10;145;112
11;145;112
12;145;112
13;145;112
14;145;112
15;145;112
16;145;112
17;145;112
1001;1;151
1002;2;81
1003;3;171
1004;4;31

I would like to remove all duplicates where second 2 numbers are the same. So after running it through program I would get something like this:

1;213;164
9;145;112
1001;1;151
1002;2;81
1003;3;171
1004;4;31

But something like

8;213;164
15;145;112
1001;1;151
1002;2;81
1003;3;171
1004;4;31

would also be correct.

Body:
Here is a nice and fast trick you can use (assuming l is your list):

list({ s.split(';', 1)[1] : s for s in l }.values())

No need to import anything, and fast as can be.

In general you can define:

def custom_unique(L, keyfunc):
    return list({ keyfunc(li): li for li in L }.values())


问:
How can i edit an existing Typo3 Extension (Backend Configuration Page)?
i want to edit an existing Typo3 Backend configuration page.
I want to edit a configuration page like this here:

Where can i edit the extensions backend?
To be more clear: where can i change the edit page that an editor can use to change content.

Can someone give me a hint to the right directory or file in generall?

I'm using Typo3-7.6

Thanks

答:
Sorry, can't manage to put all questions in an unformatted comment.

there are a lot of questions, as you are not clear what you want. Maybe that is a problem of the correct words, the vocabluary, but in TYPO3 we have some fix terms for specific object. And I think you do not handle these terms according to the TYPO3 community.

let's define some terms:

first the concept of TYPO3:

all data is stored in record of differnt database tables. All records are organized with some fields and teh main field is uid, the unique ID.

the main table is pages according to the folders of your disk. those folders can contain other records (like files). (nearly) each record in TYPO3 has a relation to a pagesrecord ina field named pid. even pagesrecords have this field and so they build a tree of pages and subpages.

There is one special page, which is no real page: the page with the ' uid' zero. As there is no real pagesrecord with the uidzero, there are other records with are stored in that page by having a pid zero. for example the start of your page tree is anchored in page zero, or global records like languages, user, storages.

Aside of being the anchor to other records, the pagesrecords have information themself. (page name, kind of page, a teaser image, SEO-information, visibility, accessibility, ...)

your screenshot looks like a content record (normaly in the table tt_content), in the lower right corner there you can see the table name and the uidthe the currently edited record.

'Backend': with backend we name the view to the data where an editor can change the content of the website.  The real website is the frontend. This can be seen by everyone without the need to login in the backend (you might have access-restriccted areas of your website which need a login, but that still is 'frontend' as there is no option to edit content.

in the backend the editor might be restricted what he can access and what he can modify. An adminuser has no restriction (up until version 9 where the role of a maintainer occured to manage more general and basic options)

so we have not a single 'backend configuration page' but multiple places where we could configure special aspects of the website.

also there is no special 'extension backend'. we have global extension configuration and records belonging to an extension. (And an extension can enhance existing records with additional fields.)

Please be more specific what you want to change


问:
Accessing Azure B2C-protected odata feed using PowerBI desktop / excel
I'm working on OData/webAPI service implementation. PowerBI desktop app will be used to retrieve info from the service using odata feed datasource.
Service in protected by Azure B2C auth. Accessing odata endpoints using browser works fine - after signing in access is granted. But when I'm trying to connect to the feed using powerbi desktop by performing signin attempt, it reports that token source is not trusted.

picture related: sign in error

Also, in case of single-tenant Azure AD auth (not B2C) usage, authentication in PowerBI worked though.
So, is there a possibility to make PowerBI work with Azure AD B2C (to make it trust the token source)?

答:
No, Azure AD B2C does not issue tokens which Microsoft first party services recognize. AAD B2C is used to protect you own services which you supply to your own customers.

If you would like your customers to have self service sign up, and access Power Bi resource, then have your front end web app talk to a backend API. Protect the front end and backend with AAD B2C. That backend API should use client_credentials to authenticate via AAD endpoints to access Power Bi data on behalf of the user.


问:
How can i dynamically assign the props as variables to colors from my own color pallet in scss/css with react?
I am calling a component "MyRadioButton" with following props:

```<code><MyRadioButton
          label="Radio Group"
          theme="custom-red"  //this line
          error="Field is required "
          radioBtns={options}
          id="radioBtns"
          name="radioBtns"
          getValue={this.getValue}
        />
</code>```

I have created a react component "MyRadioButton" that will accept color name(theme) as props.

```<code>export const MyRadioButton = props => {
const {theme} = props;
return (
    <div className="my-radio-buttons"> // need to use theme here
      <input
              onChange={onChange}
              type="radio"
       />
     </div>
)}
</code>```

Based on this prop i want to assign the variable in my components scss file, which will take the color code from my custom defined color pallet.

my-radio-button.scss

```<code>/* custom color pallet */
  $custom-orange: #F060D6;
  $custom-red: #BB532E;
  $custom-blue: #4C9FEB;

.my-radio-buttons {
  .input{
     border: 2px solid $custom-red; // i want to assign the color variable based on input prop value to this property
   }
}
</code>```

I have already tried setting variable at css root with javascript and accessing it with variable function var(),  it works fine.
But because of some limitations i dont want to use that approach.
also because the color pallet list is huge, i dont want to use separate classes for all of them.

I am looking for some other solution or different approach.

答:
So you can use a combination of custom css variables and your passed theme property. In you css, you would define the basecolor of the border for example:

```<code>.my-radio-buttons {
  --theme-color: red;

  input {
     border: 2px solid var(--theme-color);
   }
}
</code>```

This can be updated by your components via componentDidMount or useEffect with the passed theme:

```<code>const MyRadioButton = props => {
  const { theme } = props;

  React.useEffect(() => {
    const input = document.querySelector(".my-radio-buttons input");

    input.style.setProperty("--theme-color", props.theme);
  }, []);

  return (
    <div className="my-radio-buttons">
      <input />
    </div>
  );
};
</code>```

Depending on your code style, you can replace the querySelector with a ref.

Body:
I am calling a component "MyRadioButton" with following props:

<MyRadioButton
          label="Radio Group"
          theme="custom-red"  //this line
          error="Field is required "
          radioBtns={options}
          id="radioBtns"
          name="radioBtns"
          getValue={this.getValue}
        />

I have created a react component "MyRadioButton" that will accept color name(theme) as props.

export const MyRadioButton = props => {
const {theme} = props;
return (

 // need to use theme here
      <input
              onChange={onChange}
              type="radio"
       />

)}

Based on this prop i want to assign the variable in my components scss file, which will take the color code from my custom defined color pallet.

my-radio-button.scss

/* custom color pallet */
  $custom-orange: #F060D6;
  $custom-red: #BB532E;
  $custom-blue: #4C9FEB;

.my-radio-buttons {
  .input{
     border: 2px solid $custom-red; // i want to assign the color variable based on input prop value to this property
   }
}

I have already tried setting variable at css root with javascript and accessing it with variable function var(),  it works fine.
But because of some limitations i dont want to use that approach.
also because the color pallet list is huge, i dont want to use separate classes for all of them.

I am looking for some other solution or different approach.

Body:
So you can use a combination of custom css variables and your passed theme property. In you css, you would define the basecolor of the border for example:

.my-radio-buttons {
  --theme-color: red;

  input {
     border: 2px solid var(--theme-color);
   }
}

This can be updated by your components via componentDidMount or useEffect with the passed theme:

const MyRadioButton = props => {
  const { theme } = props;

  React.useEffect(() => {
    const input = document.querySelector(".my-radio-buttons input");

    input.style.setProperty("--theme-color", props.theme);
  }, []);

  return (
    <div className="my-radio-buttons">
      <input />
    </div>
  );
};

Depending on your code style, you can replace the querySelector with a ref.


问:
Is Django middleware thread safe?
Are Django middleware thread safe? Can I do something like this,</p>

```<code>class ThreadsafeTestMiddleware(object):

    def process_request(self, request):
        self.thread_safe_variable = some_dynamic_value_from_request

    def process_response(self, request, response):
        # will self.thread_safe_variable always equal to some_dynamic_value_from_request?
</code>```

答:
No, very definitely not. I write about this issue here - the upshot is that storing state in a middleware class is a very bad idea.

As Steve points out, the solution is to add it to the request instead.

Title: Is Django middleware thread safe?

Body:
Are Django middleware thread safe? Can I do something like this,

class ThreadsafeTestMiddleware(object):

    def process_request(self, request):
        self.thread_safe_variable = some_dynamic_value_from_request

    def process_response(self, request, response):
        # will self.thread_safe_variable always equal to some_dynamic_value_from_request?


问:
Ticks in slider is not showing when style is given
Ticks are showing if I gave without style. But if i added styles to Slider, ticks is not showing.

Expected Style

Style given for Slider

```<code><Style x:Key="SliderRepeatButton" TargetType="RepeatButton">
    <Setter Property="SnapsToDevicePixels" Value="true" />
    <Setter Property="OverridesDefaultStyle" Value="true" />
    <Setter Property="IsTabStop" Value="false" />
    <Setter Property="Focusable" Value="false" />
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="RepeatButton">
                <Border  BorderThickness="1" BorderBrush="#c3c3c3" Background="#c3c3c3" Height="3"/>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

<Style x:Key="SliderRepeatButton1" TargetType="RepeatButton">
    <Setter Property="SnapsToDevicePixels" Value="true" />
    <Setter Property="OverridesDefaultStyle" Value="true" />
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="RepeatButton">
                <Border SnapsToDevicePixels="True" Background="#e94480"  BorderThickness="1" BorderBrush="#e94480" Height="3"/>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

<Style x:Key="SliderThumb" TargetType="Thumb">
    <Setter Property="SnapsToDevicePixels" Value="true" />
    <Setter Property="OverridesDefaultStyle" Value="true" />
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="Thumb">
                <Ellipse Height="13" Width="13" Fill="#e94480"></Ellipse>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

<ControlTemplate x:Key="Slider"  TargetType="Slider">
    <Grid Background="White">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto"  />
        </Grid.RowDefinitions>
        <TickBar Visibility="Visible" Grid.Row="0" Fill="Red"  Placement="Bottom"   VerticalAlignment="Bottom" Height="10" Width="5" />

        <Track Grid.Row="1" x:Name="PART_Track">
            <Track.DecreaseRepeatButton>
                <RepeatButton Style="{StaticResource SliderRepeatButton1}"  Command="Slider.DecreaseLarge" />
            </Track.DecreaseRepeatButton>
            <Track.Thumb>
                <Thumb Style="{StaticResource SliderThumb}"  />
            </Track.Thumb>
            <Track.IncreaseRepeatButton>
                <RepeatButton Style="{StaticResource SliderRepeatButton}" Command="Slider.IncreaseLarge" />
            </Track.IncreaseRepeatButton>
        </Track>
    </Grid>
</ControlTemplate>

<Style x:Key="Horizontal_Slider" TargetType="Slider">
    <Setter Property="Focusable" Value="False"/>
    <Setter Property="SnapsToDevicePixels" Value="true" />
    <Setter Property="OverridesDefaultStyle" Value="true" />
    <Style.Triggers>
        <Trigger Property="Orientation" Value="Horizontal">
            <Setter Property="MinHeight" Value="21" />
            <Setter Property="MinWidth" Value="104" />
            <Setter Property="Template" Value="{StaticResource Slider}" />
        </Trigger>
    </Style.Triggers>
</Style>

                                <Slider IsSnapToTickEnabled="True" VerticalAlignment="Bottom"  Name="SliderProgress"  Value="0" Height="40"  Thumb.DragCompleted="prog_DragCompleted" PreviewMouseLeftButtonDown="prog_PreviewMouseLeftButtonDown" PreviewMouseLeftButtonUp="prog_PreviewMouseLeftButtonUp" Margin="20,0,20,10" Style="{StaticResource Horizontal_Slider}"/>
</code>```

Added Ticks in cs file. Ticks will be added according to the duration of the videos added in the list.

```<code>            SliderProgress.Ticks.Add(totoalDuration);
</code>```

How to achieve expected slider style?

Any idea why ticks are not displaying?

答: Try to remove the width of the TickBar</p>

Body:
Ticks are showing if I gave without style. But if i added styles to Slider, ticks is not showing.

Expected Style

Style given for Slider

<ControlTemplate x:Key="Slider"  TargetType="Slider">
    <Grid Background="White">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto"  />
        </Grid.RowDefinitions>
        <TickBar Visibility="Visible" Grid.Row="0" Fill="Red"  Placement="Bottom"   VerticalAlignment="Bottom" Height="10" Width="5" />

        <Track Grid.Row="1" x:Name="PART_Track">
            <Track.DecreaseRepeatButton>
                <RepeatButton Style="{StaticResource SliderRepeatButton1}"  Command="Slider.DecreaseLarge" />
            </Track.DecreaseRepeatButton>
            <Track.Thumb>
                <Thumb Style="{StaticResource SliderThumb}"  />
            </Track.Thumb>
            <Track.IncreaseRepeatButton>
                <RepeatButton Style="{StaticResource SliderRepeatButton}" Command="Slider.IncreaseLarge" />
            </Track.IncreaseRepeatButton>
        </Track>
    </Grid>
</ControlTemplate>

</Style>

                                <Slider IsSnapToTickEnabled="True" VerticalAlignment="Bottom"  Name="SliderProgress"  Value="0" Height="40"  Thumb.DragCompleted="prog_DragCompleted" PreviewMouseLeftButtonDown="prog_PreviewMouseLeftButtonDown" PreviewMouseLeftButtonUp="prog_PreviewMouseLeftButtonUp" Margin="20,0,20,10" Style="{StaticResource Horizontal_Slider}"/>

Added Ticks in cs file. Ticks will be added according to the duration of the videos added in the list.

            SliderProgress.Ticks.Add(totoalDuration);

How to achieve expected slider style?

Any idea why ticks are not displaying?

Body: Try to remove the width of the TickBar


问:
AttributeError at /accounts/signup/ Manager isn't available; 'auth.User' has been swapped for 'accounts.CustomUser'
I have a custom signup form SignupForm that checks for existing email for the custom user object CustomUser and raises a ValidationError if exists. But when I try to raise the error, I get AttributeError at /accounts/signup/  Manager isn't available; 'auth.User' has been swapped for 'accounts.CustomUser'.

Here are my codes.

forms.py

from django.contrib.auth.forms import UserCreationForm
from django import forms
from django.core.exceptions import ValidationError

from django.contrib.auth import get_user_model

class SignupForm(UserCreationForm):

    def __init__(self, *args, **kwargs):
        super(UserCreationForm, self).__init__(*args, **kwargs)

    email = forms.CharField(
        widget=forms.EmailInput(
        attrs={
            'class': 'input',
            'placeholder': 'bearclaw@example.com'
        }
    ))

    ...
    # other fields (username and password)
    ...

    def clean(self):
       User = get_user_model()
       email = self.cleaned_data.get('email')
       if User.objects.filter(email=email).exists():
            raise ValidationError("An account with this email exists.")
       return self.cleaned_data
```

<p><strong>views.py</strong></p>

<pre class="lang-py prettyprint-override"><code>from django.urls import reverse_lazy
from django.views.generic import CreateView
from .forms import SignupForm
from .models import CustomUser

...
# other views and imports
...

class CustomSignup(CreateView):
    form_class = SignupForm
    success_url = reverse_lazy('login')
    template_name = 'registration/signup.html'
</code>```

models.py

from django.db import models
from django.contrib.auth.models import AbstractUser

class CustomUser(AbstractUser):
    email = models.EmailField(unique=True)

    def __str__(self):
        return self.username
```

<p><strong>settings.py</strong></p>

<pre class="lang-py prettyprint-override"><code>AUTH_USER_MODEL = "accounts.CustomUser"
</code>```

What am I missing?

答:
Basically you are missing ModelForm Meta

try this

```<code>class SignupForm(UserCreationForm):

    def __init__(self, *args, **kwargs):
        super(UserCreationForm, self).__init__(*args, **kwargs)

    email = forms.CharField(
        widget=forms.EmailInput(
        attrs={
            'class': 'input',
            'placeholder': 'bearclaw@example.com'
        }
    ))

    ...
    # other fields (username and password)
    ...

    def clean(self):
       User = get_user_model()
       email = self.cleaned_data.get('email')
       if User.objects.filter(email=email).exists():
            raise ValidationError("An account with this email exists.")
       return self.cleaned_data

   class Meta:
       model = get_user_model()
       fields = ('username', 'email')
</code>```

Body:
I have a custom signup form SignupForm that checks for existing email for the custom user object CustomUser and raises a ValidationError if exists. But when I try to raise the error, I get AttributeError at /accounts/signup/  Manager isn't available; 'auth.User' has been swapped for 'accounts.CustomUser'.

Here are my codes.

forms.py

from django.contrib.auth.forms import UserCreationForm
from django import forms
from django.core.exceptions import ValidationError

from django.contrib.auth import get_user_model

class SignupForm(UserCreationForm):

    def __init__(self, *args, **kwargs):
        super(UserCreationForm, self).__init__(*args, **kwargs)

    email = forms.CharField(
        widget=forms.EmailInput(
        attrs={
            'class': 'input',
            'placeholder': 'bearclaw@example.com'
        }
    ))

    ...
    # other fields (username and password)
    ...

    def clean(self):
       User = get_user_model()
       email = self.cleaned_data.get('email')
       if User.objects.filter(email=email).exists():
            raise ValidationError("An account with this email exists.")
       return self.cleaned_data

views.py

from django.urls import reverse_lazy
from django.views.generic import CreateView
from .forms import SignupForm
from .models import CustomUser

...
# other views and imports
...

class CustomSignup(CreateView):
    form_class = SignupForm
    success_url = reverse_lazy('login')
    template_name = 'registration/signup.html'

models.py

from django.db import models
from django.contrib.auth.models import AbstractUser

class CustomUser(AbstractUser):
    email = models.EmailField(unique=True)

    def __str__(self):
        return self.username

settings.py

AUTH_USER_MODEL = "accounts.CustomUser"

What am I missing?

Body:
Basically you are missing ModelForm Meta

try this

class SignupForm(UserCreationForm):

    def __init__(self, *args, **kwargs):
        super(UserCreationForm, self).__init__(*args, **kwargs)

    email = forms.CharField(
        widget=forms.EmailInput(
        attrs={
            'class': 'input',
            'placeholder': 'bearclaw@example.com'
        }
    ))

    ...
    # other fields (username and password)
    ...

    def clean(self):
       User = get_user_model()
       email = self.cleaned_data.get('email')
       if User.objects.filter(email=email).exists():
            raise ValidationError("An account with this email exists.")
       return self.cleaned_data

   class Meta:
       model = get_user_model()
       fields = ('username', 'email')


问:
WinDbg issues only in Windows 7
I'm pretty new to using WinDbg, but recently my application started having issues, but only on Windows 7 machines (it runs fine the first time the PC is started but crashes or just disappears silently each time after).

I got the mdmp file, but find myself somewhat lacking on how best to extract the data I need from it.  I got the following analysis (might be doing it wrong)...

Can anyone hopefully help shed some light on my issue or if I'm running the analysis incorrectly:

```<code>0:000> !analyze -v
*******************************************************************************
*                                                                             *
*                        Exception Analysis                                   *
*                                                                             *
*******************************************************************************

GetPageUrlData failed, server returned HTTP status 404
URL requested: http://watson.microsoft.com/StageOne/Star_exe/1_0_0_0/4dbad268/KERNELBASE_dll/6_1_7600_16385/4a5bdaae/e0434352/00009617.htm?Retriage=1

FAULTING_IP:
KERNELBASE!RaiseException+58
752d9617 c9              leave

EXCEPTION_RECORD:  ffffffff -- (.exr 0xffffffffffffffff)
ExceptionAddress: 752d9617 (KERNELBASE!RaiseException+0x00000058)
   ExceptionCode: e0434352 (CLR exception)
  ExceptionFlags: 00000001
NumberParameters: 5
   Parameter[0]: 80070002
   Parameter[1]: 00000000
   Parameter[2]: 00000000
   Parameter[3]: 00000000
   Parameter[4]: 57af0000

PROCESS_NAME:  Star.exe

ERROR_CODE: (NTSTATUS) 0xe0434352 - <Unable to get error code text>

EXCEPTION_CODE: (NTSTATUS) 0xe0434352 - <Unable to get error code text>

EXCEPTION_PARAMETER1:  80070002

EXCEPTION_PARAMETER2:  00000000

EXCEPTION_PARAMETER3:  00000000

EXCEPTION_PARAMETER4: 0

MOD_LIST: <ANALYSIS/>

NTGLOBALFLAG:  0

APPLICATION_VERIFIER_FLAGS:  0

MANAGED_STACK: !dumpstack -EE
No export dumpstack found

MANAGED_BITNESS_MISMATCH:
Managed code needs matching platform of sos.dll for proper analysis. Use 'x86' debugger.

ADDITIONAL_DEBUG_TEXT:  Followup set based on attribute [Is_ChosenCrashFollowupThread] from Frame:[0] on thread:[PSEUDO_THREAD]

LAST_CONTROL_TRANSFER:  from 57c03970 to 752d9617

FAULTING_THREAD:  ffffffff

DEFAULT_BUCKET_ID:  STACKIMMUNE

PRIMARY_PROBLEM_CLASS:  STACKIMMUNE

BUGCHECK_STR:  APPLICATION_FAULT_STACKIMMUNE_NOSOS_CLR_EXCEPTION_WRONG_SYMBOLS

STACK_TEXT:
00000000 00000000 star.exe+0x0

SYMBOL_NAME:  star.exe

FOLLOWUP_NAME:  MachineOwner

MODULE_NAME: star

IMAGE_NAME:  Star.exe

DEBUG_FLR_IMAGE_TIMESTAMP:  4dbad268

STACK_COMMAND:  ** Pseudo Context ** ; kb

FAILURE_BUCKET_ID:  STACKIMMUNE_e0434352_Star.exe!Unknown

BUCKET_ID:  APPLICATION_FAULT_STACKIMMUNE_NOSOS_CLR_EXCEPTION_WRONG_SYMBOLS_star.exe

FOLLOWUP_IP: *** WARNING: Unable to verify timestamp for Star.exe

Star!.ctor+0 [C:\Users\Aj\Documents\Visual Studio 2010\Projects\Star\Star\ViewModels\ViewModelBase.cs @ 22]
00360000 ??              ???

WATSON_STAGEONE_URL:  http://watson.microsoft.com/StageOne/Star_exe/1_0_0_0/4dbad268/KERNELBASE_dll/6_1_7600_16385/4a5bdaae/e0434352/00009617.htm?Retriage=1

Followup: MachineOwner
---------
</code>```

答:
Well after several weeks of searching (maybe more), it turns out that when using Trend Micro Corporate, XP to Server 2003 is fine, Vista and Windows 7 to 2003 is fine, and even XP/Vista to server 2008 is fine, but (and I have no idea why), when using Windows 7 and trying to run a network application using a UNC path in the shortcut, it blocks certain pieces of the network traffic for that application, and it does so sporadically and what seems to be without any sound logic.  I can't say why as we never quite figured out what exactly the catalyst was for setting off Trend, but I do know that when we disabled Trend, all was back to normal (something I wished we tried sooner).  We found that by mapping a drive to our share and changing our shortcuts on our users workstations to use the mapped drive rather than a UNC path, the issue was averted.

Hopefully no one else runs into this problem, but if they do, this will perhaps shed some light on the issue.

Thank you!
Aj

Title: WinDbg issues only in Windows 7

Body:
I'm pretty new to using WinDbg, but recently my application started having issues, but only on Windows 7 machines (it runs fine the first time the PC is started but crashes or just disappears silently each time after).

I got the mdmp file, but find myself somewhat lacking on how best to extract the data I need from it.  I got the following analysis (might be doing it wrong)...

Can anyone hopefully help shed some light on my issue or if I'm running the analysis incorrectly:

0:000> !analyze -v
*******************************************************************************
*                                                                             *
*                        Exception Analysis                                   *
*                                                                             *
*******************************************************************************

GetPageUrlData failed, server returned HTTP status 404
URL requested: http://watson.microsoft.com/StageOne/Star_exe/1_0_0_0/4dbad268/KERNELBASE_dll/6_1_7600_16385/4a5bdaae/e0434352/00009617.htm?Retriage=1

FAULTING_IP:
KERNELBASE!RaiseException+58
752d9617 c9              leave

EXCEPTION_RECORD:  ffffffff -- (.exr 0xffffffffffffffff)
ExceptionAddress: 752d9617 (KERNELBASE!RaiseException+0x00000058)
   ExceptionCode: e0434352 (CLR exception)
  ExceptionFlags: 00000001
NumberParameters: 5
   Parameter[0]: 80070002
   Parameter[1]: 00000000
   Parameter[2]: 00000000
   Parameter[3]: 00000000
   Parameter[4]: 57af0000

PROCESS_NAME:  Star.exe

ERROR_CODE: (NTSTATUS) 0xe0434352 - <Unable to get error code text>

EXCEPTION_CODE: (NTSTATUS) 0xe0434352 - <Unable to get error code text>

EXCEPTION_PARAMETER1:  80070002

EXCEPTION_PARAMETER2:  00000000

EXCEPTION_PARAMETER3:  00000000

EXCEPTION_PARAMETER4: 0

MOD_LIST: <ANALYSIS/>

NTGLOBALFLAG:  0

APPLICATION_VERIFIER_FLAGS:  0

MANAGED_STACK: !dumpstack -EE
No export dumpstack found

MANAGED_BITNESS_MISMATCH:
Managed code needs matching platform of sos.dll for proper analysis. Use 'x86' debugger.

ADDITIONAL_DEBUG_TEXT:  Followup set based on attribute [Is_ChosenCrashFollowupThread] from Frame:[0] on thread:[PSEUDO_THREAD]

LAST_CONTROL_TRANSFER:  from 57c03970 to 752d9617

FAULTING_THREAD:  ffffffff

DEFAULT_BUCKET_ID:  STACKIMMUNE

PRIMARY_PROBLEM_CLASS:  STACKIMMUNE

BUGCHECK_STR:  APPLICATION_FAULT_STACKIMMUNE_NOSOS_CLR_EXCEPTION_WRONG_SYMBOLS

STACK_TEXT:
00000000 00000000 star.exe+0x0

SYMBOL_NAME:  star.exe

FOLLOWUP_NAME:  MachineOwner

MODULE_NAME: star

IMAGE_NAME:  Star.exe

DEBUG_FLR_IMAGE_TIMESTAMP:  4dbad268

STACK_COMMAND:  ** Pseudo Context ** ; kb

FAILURE_BUCKET_ID:  STACKIMMUNE_e0434352_Star.exe!Unknown

BUCKET_ID:  APPLICATION_FAULT_STACKIMMUNE_NOSOS_CLR_EXCEPTION_WRONG_SYMBOLS_star.exe

FOLLOWUP_IP: *** WARNING: Unable to verify timestamp for Star.exe

Star!.ctor+0 [C:\Users\Aj\Documents\Visual Studio 2010\Projects\Star\Star\ViewModels\ViewModelBase.cs @ 22]
00360000 ??              ???

WATSON_STAGEONE_URL:  http://watson.microsoft.com/StageOne/Star_exe/1_0_0_0/4dbad268/KERNELBASE_dll/6_1_7600_16385/4a5bdaae/e0434352/00009617.htm?Retriage=1

Followup: MachineOwner
---------


问:
svn 1.7.8 database is locked, cannot release
when I run:

```<code>svn cleanup
</code>```

I get the error message:

```<code>svn: E200033: database is locked, executing statement 'RELEASE   s0'
</code>```

or any other command to change DB, e.g. commit, update etc.

This is on linux server, the directory is nfs.

I can checkout another version and copy my changes, but it is a hassle and I think this error will come back.

how do I fix this on a working directory, and is there a way to prevent it.

p.s. there are no processes currently running, maybe eclipse crashed in the middle of some action.

答:
I had same trouble here on windows 10.

Working in selenium tests, when I try to commit my changes, the SNV shows the error: Database is locked.

I have executed svn cleanup and still no working.

So, I opened the windows task manager (ctrl + shift + esc) and I saw some chromedriver.exe process still running. I killed all of them and executed svn cleanup again and this worked!

Body:
when I run:

svn cleanup

I get the error message:

svn: E200033: database is locked, executing statement 'RELEASE   s0'

or any other command to change DB, e.g. commit, update etc.

This is on linux server, the directory is nfs.

I can checkout another version and copy my changes, but it is a hassle and I think this error will come back.

how do I fix this on a working directory, and is there a way to prevent it.

p.s. there are no processes currently running, maybe eclipse crashed in the middle of some action.


答:
Create DataFrame from dictionaries and then use DataFrame.join:

```<code>new = pd.DataFrame({'male_count':male_counts, 'female_count':female_count})
df = df.join(new, on='Code')
</code>```

Title: Create Multiple New Columns From Multiple Dictionaries

Body:
I can successfully create a single new attribute on a dataframe called df using a single dictionary as follows:

Create Precursor DataFrame mye2_men:

In [13]: mye2_men = pd.read_csv("~/03_Maps_March_2020/mye2_men.csv",index_col="Code")
    ...: mye2_men.head()
Out[13]:
                        Name Geography1  All ages       0       1       2       3       4       5       6       7       8       9  ...      78      79      80      81      82      83      84      85     86     87     88     89      90
Code                                                                                ...
K02000001     UNITED KINGDOM    Country  32790202  382332  395273  408684  408882  412553  421934  434333  427809  419161  414994  ...  192839  186251  175626  160475  146314  132941  116050  103669  93155  81174  68110  55652  183486
K03000001      GREAT BRITAIN    Country  31864002  370474  382933  395754  396181  399764  409061  420947  414613  406062  401647  ...  188073  181546  171350  156506  142851  129815  113306  101194  91038  79342  66699  54387  179629
K04000001  ENGLAND AND WALES    Country  29215251  343642  355122  366722  366885  370156  379046  389944  382853  375940  370701  ...  172046  166392  157065  143896  131207  119193  104143   93055  83798  73224  61794  50297  167009
E92000001            ENGLAND    Country  27667942  327309  338368  349229  349199  352148  360688  370995  363496  356965  351790  ...  161540  156343  147733  135514  123492  112133   98000   87528  79030  69067  58264  47498  157788
E12000001         NORTH EAST     Region   1305486   13992   14423   15124   15159   15542   15839   16314   16283   16068   15748  ...    8130    8108    7601    6977    6118    5723    4958    4383   3889   3360   2747   2148    6822

[5 rows x 94 columns]

Create Target DataFrame df

In [14]: df = pd.DataFrame({"A":[num for num in range(0,430)],
    ...:                    "B":[num**2 for num in range(0,430)],
    ...:                    "Code":mye2_men.index})
    ...: df.head()
Out[14]:
   A   B       Code
0  0   0  K02000001
1  1   1  K03000001
2  2   4  K04000001
3  3   9  E92000001
4  4  16  E12000001

Create Dictionary To Use In Mapping:

In [15]: male_counts = mye2_men["All ages"].to_dict()
    ...: male_counts
Out[15]:
{'K02000001': 32790202,
 'K03000001': 31864002,
 'K04000001': 29215251,
 'E92000001': 27667942,
 'E12000001': 1305486,
 'E06000047': 259299,
 'E06000005': 51919,
 'E06000001': 45524 ....}

Map the male_counts Dictionary to DataFrame df To Create New Column "male_count":

In [19]: # CREATE NEW male_count COLUMN IN df
    ...: df["male_count"] = df["Code"].map(male_counts)
    ...: df.head()
Out[19]:
   A   B       Code  male_count
0  0   0  K02000001    32790202
1  1   1  K03000001    31864002
2  2   4  K04000001    29215251
3  3   9  E92000001    27667942
4  4  16  E12000001     1305486

For the 2nd dictionary:

In [20]: female_counts = (mye2_men["All ages"]+10).to_dict()
    ...: female_counts
Out[20]:
{'K02000001': 32790212,
 'K03000001': 31864012,
 'K04000001': 29215261,
 'E92000001': 27667952,
 'E12000001': 1305496,
 'E06000047': 259309,
 'E06000005': 51929 ...}

I can successfully produce a second attribute called df["female_count"] by repeating step 4 above, but this time using the female_counts dictionary.

How can I create multiple new df columns (ie df["male_count"] and df["female_count"]) in a single step?

Many thanks

Note:
The mye2_men data is from the "MYE2 - Males" tab of the following excel doc:
https://www.ons.gov.uk/file?uri=%2fpeoplepopulationandcommunity%2fpopulationandmigration%2fpopulationestimates%2fdatasets%2fpopulationestimatesforukenglandandwalesscotlandandnorthernireland%2fmid2019april2020localauthoritydistrictcodes/ukmidyearestimates20192020ladcodes.xls

Body:
Create DataFrame from dictionaries and then use DataFrame.join:

new = pd.DataFrame({'male_count':male_counts, 'female_count':female_count})
df = df.join(new, on='Code')


问:
Ping website URL before loading it in WebView in Android Kotlin
Before loading a website in WebView, I want to check the URL and make sure that it loads. If it does, show the WebView; if not, show another View with a message.

The idea is to check if the website can be loaded and depending on the response show either the "Website cannot be loaded" screen or show the WebView with URL loaded.

I have already checked if the connection is available, so no need to worry about that.

Need to support API 25+.

答:
Another (shorter) alternative to AsyncTask would it be using Thread:

```<code>Thread {
    val result = isHostAvailable(BuildConfig.BASE_URL)
    runOnUiThread {
        if (result) {
            // do something ...
        }
        else showToast("no connection to server")
    }
}.start()
</code>```

and

```<code>fun isHostAvailable(urlPath: String): Boolean {
    try {
        val url = URL(urlPath)
        val connection: HttpURLConnection = url.openConnection() as HttpURLConnection
        connection.setRequestProperty("Connection", "close")
        connection.connectTimeout = 3000
        connection.connect()

        return when (connection.responseCode) {
            200, 403 -> true
            else -> false
        }

    } catch (e: Exception) {
        when (e) {
            is MalformedURLException -> "loadLink: Invalid URL ${e.message}"
            is IOException -> "loadLink: IO Exception reading data: ${e.message}"
            is SecurityException -> {
                e.printStackTrace()
                "loadLink: Security Exception. Needs permission? ${e.message}"
            }
            else -> "Unknown error: ${e.message}"
        }
    }
    return false
}
</code>```

Body:
Another (shorter) alternative to AsyncTask would it be using Thread:

Thread {
    val result = isHostAvailable(BuildConfig.BASE_URL)
    runOnUiThread {
        if (result) {
            // do something ...
        }
        else showToast("no connection to server")
    }
}.start()

and

fun isHostAvailable(urlPath: String): Boolean {
    try {
        val url = URL(urlPath)
        val connection: HttpURLConnection = url.openConnection() as HttpURLConnection
        connection.setRequestProperty("Connection", "close")
        connection.connectTimeout = 3000
        connection.connect()

        return when (connection.responseCode) {
            200, 403 -> true
            else -> false
        }

    } catch (e: Exception) {
        when (e) {
            is MalformedURLException -> "loadLink: Invalid URL ${e.message}"
            is IOException -> "loadLink: IO Exception reading data: ${e.message}"
            is SecurityException -> {
                e.printStackTrace()
                "loadLink: Security Exception. Needs permission? ${e.message}"
            }
            else -> "Unknown error: ${e.message}"
        }
    }
    return false
}


问:
DevExpress GridControl seletcted rows belong to Parent View or Child View in Master-Details mode
I'm using Dev-express GridControl in my Win-forms project.

How can I detect that selected rows belongs to a Parent View or a Child View in Master-Details mode?

答: You can use the GridView's IsMasterRow method or the GridView's IsDetailRowIndex method to determine if a row handle belongs to a master or child view.</p>


问:
Freezes application in button action
I doing a game application using cocos2d.In this application two game are include together. When playing game i include a action for switching the game. when i use this button two or three times change the game but after that the game is freezes & not work any more until the game is close the game. If anyone have a solution than give me some information that how can i overcome in this problem.</p>

答:
Are you sure you don't have memory leak problems when switching games?

Its difficult to diagnose correctly with so little information but my guess would be that the switch process isnt done correctly and after a few times some memory/variables get corrupted

OwnerDisplayName: Rana

ContentLicense: CC BY-SA 2.5

Title: Freezes application in button action

OwnerDisplayName: Eric


问:
Prometheus create rules for all accounts
I want to create some complicated function on Prometheus for every account, for simplify let's say that I want to divide sum of rate by average of it, so the rule will look like this:

```<code>record: requests_my_account1
  expr:
  sum(rate(requests_total{account="my_account1"}[5m]))
  /
  avg_over_time(sum(rate(requests_total{account="my_account1"}[5m]))[1w:])
</code>```

Is it possible to put some placeholder instead of my_account1, so prometheus use every account, which it has stored or at least for manually creating list of accounts, so I don't have to create separate rule for every account?

答:
You could try the following rule expression:</p>

```<code>sum by(account) (rate(requests_total[5m]))
/
avg_over_time(sum by(account) (rate(requests_total[5m]))[1w:])
</code>```

Body:
I want to create some complicated function on Prometheus for every account, for simplify let's say that I want to divide sum of rate by average of it, so the rule will look like this:

record: requests_my_account1
  expr:
  sum(rate(requests_total{account="my_account1"}[5m]))
  /
  avg_over_time(sum(rate(requests_total{account="my_account1"}[5m]))[1w:])

Is it possible to put some placeholder instead of my_account1, so prometheus use every account, which it has stored or at least for manually creating list of accounts, so I don't have to create separate rule for every account?

Body:
You could try the following rule expression:

sum by(account) (rate(requests_total[5m]))
/
avg_over_time(sum by(account) (rate(requests_total[5m]))[1w:])


问:
How to change required attribute in @RequestParam?
I have controller end point like this:

```<code>    @GetMapping
    public List<QuestionnaireModel> getQuestionnaireList (
        @PathVariable String userId,
        @RequestParam(required = false, value = "userId") Long orderId
    ){
</code>```

Now, how can I change my required attribute in @RequestParam depending on value that will be in @PathVariable?

For example :

```<code>if(userId==5){
    //My @RequestParam required must be true so I must provide `orderId`
}
</code>```

答:
@RequestParam  & @PathVariable are two different annotations which have no common dependency. You would need to annotate @RequestParam to this method and apply validation then execute your code.</p>

```<code>@RequestParam(value="something")
if(something!=null){
//code goes here
}
</code>```

Body:
I have controller end point like this:

    @GetMapping
    public List<QuestionnaireModel> getQuestionnaireList (
        @PathVariable String userId,
        @RequestParam(required = false, value = "userId") Long orderId
    ){

Now, how can I change my required attribute in @RequestParam depending on value that will be in @PathVariable?

For example :

if(userId==5){
    //My @RequestParam required must be true so I must provide `orderId`
}

Body:
@RequestParam  & @PathVariable are two different annotations which have no common dependency. You would need to annotate @RequestParam to this method and apply validation then execute your code.

@RequestParam(value="something")
if(something!=null){
//code goes here
}