问:
Tkd widget not finding row and column options
I am trying to create a simple GUI application using tkd package and following code:

```<code>// modified from: https://github.com/nomad-software/tkd

import tkd.tkdapplication;

class Application : TkdApplication    {
    auto labellist = ["First", "Second", "Third", "Fourth", "Fifth", "Sixth", ];
    override protected void initInterface() {
        int ncol =0;
        auto frame = new Frame(2, ReliefStyle.groove);
        frame.pack(10);
        foreach(lab; labellist){
            auto label = new Label(frame, lab);
            label.grid(row=nrow, column=0);
            auto entry = new Entry(frame);
            entry.grid(row=nrow, column=1);
            nrow += 1;
        }
        auto exitButton = new Button(frame, "Exit").setCommand(&this.exitCommand).pack(10);
    }
    private void exitCommand(CommandArgs args)  {
        this.exit();
    }
}

void main(string[] args){
    auto app = new Application();
    app.run();
}
</code>```

However, it is giving following error:

```<code>$ dub run
Performing "debug" build using /usr/bin/dmd for x86_64.
x11 1.0.21: target for configuration "tcltk-import" is up to date.
tcltk 8.6.5: target for configuration "library" is up to date.
tkd 1.1.12: target for configuration "library" is up to date.
tkdgui ~master: building configuration "application"...
source/app.d(15,15): Error: undefined identifier row
source/app.d(15,25): Error: undefined identifier column
source/app.d(17,15): Error: undefined identifier row
source/app.d(17,25): Error: undefined identifier column
source/app.d(18,4): Error: undefined identifier nrow
/usr/bin/dmd failed with exit code 1.
</code>```

Details about grid are mentioned here. Row and column are valid options to be entered.

Where is the problem and how can it be solved.

答:
There are two issues in your code. Here's the first:

```<code>label.grid(row=nrow, column=0);
           ^^^^      ^^^^^^^
</code>```

D does not support named parameters, which you're attempting to use. Instead you will need to use positional parameters:

```<code>label.grid(0, nrow);
</code>```

FWIW, there are some proposals to add named parameters to D, but none are in the language as of now.

The second issue is nrow is not defined anywhere. Judging by the existence of ncol and the fact it's used nowhere, it seems you changed the code from dealing with columns to dealing with rows and did not change the name of ncol to nrow.

Body:
I am trying to create a simple GUI application using tkd package and following code:

// modified from: https://github.com/nomad-software/tkd

import tkd.tkdapplication;

class Application : TkdApplication    {
    auto labellist = ["First", "Second", "Third", "Fourth", "Fifth", "Sixth", ];
    override protected void initInterface() {
        int ncol =0;
        auto frame = new Frame(2, ReliefStyle.groove);
        frame.pack(10);
        foreach(lab; labellist){
            auto label = new Label(frame, lab);
            label.grid(row=nrow, column=0);
            auto entry = new Entry(frame);
            entry.grid(row=nrow, column=1);
            nrow += 1;
        }
        auto exitButton = new Button(frame, "Exit").setCommand(&this.exitCommand).pack(10);
    }
    private void exitCommand(CommandArgs args)  {
        this.exit();
    }
}

void main(string[] args){
    auto app = new Application();
    app.run();
}

However, it is giving following error:

$ dub run
Performing "debug" build using /usr/bin/dmd for x86_64.
x11 1.0.21: target for configuration "tcltk-import" is up to date.
tcltk 8.6.5: target for configuration "library" is up to date.
tkd 1.1.12: target for configuration "library" is up to date.
tkdgui ~master: building configuration "application"...
source/app.d(15,15): Error: undefined identifier row
source/app.d(15,25): Error: undefined identifier column
source/app.d(17,15): Error: undefined identifier row
source/app.d(17,25): Error: undefined identifier column
source/app.d(18,4): Error: undefined identifier nrow
/usr/bin/dmd failed with exit code 1.

Details about grid are mentioned here. Row and column are valid options to be entered.

Where is the problem and how can it be solved.

Body:
There are two issues in your code. Here's the first:

label.grid(row=nrow, column=0);
           ^^^^      ^^^^^^^

D does not support named parameters, which you're attempting to use. Instead you will need to use positional parameters:

label.grid(0, nrow);

FWIW, there are some proposals to add named parameters to D, but none are in the language as of now.

The second issue is nrow is not defined anywhere. Judging by the existence of ncol and the fact it's used nowhere, it seems you changed the code from dealing with columns to dealing with rows and did not change the name of ncol to nrow.


来源: stackexchange

问:
Finding unique values of a node property
I have a neo4j database with several nodes each having many properties. I am trying to find a list of unique values available for each property.

Currently, I can search for nodes that have a certain value 'xxx' with a query in this manner below however, I want to find all the unique values 'xxx','yyy', etc. that may exist in all the nodes in my database.

```<code>match (n:Db_Nodes) where n.stringProperty = "xxx" return n
</code>```

How should I go about structuring the query desired?

答:
You can use the DISTINCT Clause to return all the unique values for this property.

There are two ways to get all the values:

Get all the values in a list. Here result will be one single record with all the unique values in the form of a list.

```<code>MATCH (n:Db_Nodes) RETURN COLLECT(DISTINCT n.stringProperty) as propertyList
</code>```

Get one value per record. Here multiple records will be returned(One per unique property value).

```<code>MATCH (n:Db_Nodes) RETURN DISTINCT n.stringProperty
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a neo4j database with several nodes each having many properties. I am trying to find a list of unique values available for each property.

Currently, I can search for nodes that have a certain value 'xxx' with a query in this manner below however, I want to find all the unique values 'xxx','yyy', etc. that may exist in all the nodes in my database.

match (n:Db_Nodes) where n.stringProperty = "xxx" return n

How should I go about structuring the query desired?

Body:
You can use the DISTINCT Clause to return all the unique values for this property.

There are two ways to get all the values:

Get all the values in a list. Here result will be one single record with all the unique values in the form of a list.

MATCH (n:Db_Nodes) RETURN COLLECT(DISTINCT n.stringProperty) as propertyList

Get one value per record. Here multiple records will be returned(One per unique property value).

MATCH (n:Db_Nodes) RETURN DISTINCT n.stringProperty


问:
How to create SWIG typemap for a function that takes 2 tables?
I'm trying to create a SWIG typemap for the following function:

```<code>void mix(int size, float *in1, float *in2, float *out1)
{
    for (int i = 0; i < size; ++i)
        out1[i] = in1[i] + in2[i];
}
</code>```

In lua, I want this function to take 2 table arguments and return 1 table like the following:

```<code>local t = m.mix({1,2,3}, {4,5,6})
</code>```

Then the table t should be {5,7,9} which is sum of the two tables.

I tried to use built-in typemaps but I could only wrap a function that takes and returns one table which is the following:

```<code>%apply (float *INOUT, int) {(float *inout, int size)};
</code>```

How can I create a SWIG typemap for a function that takes two tables and returns one table?

答:
I found a simple way to do it.

```<code>%apply (float *INOUT, int) {(float *in1, int n1)};
%apply (float *INPUT, int) {(float *in2, int n2)};
</code>```

It seems to work fine for my purpose.

Body:
I'm trying to create a SWIG typemap for the following function:

void mix(int size, float *in1, float *in2, float *out1)
{
    for (int i = 0; i < size; ++i)
        out1[i] = in1[i] + in2[i];
}

In lua, I want this function to take 2 table arguments and return 1 table like the following:

local t = m.mix({1,2,3}, {4,5,6})

Then the table t should be {5,7,9} which is sum of the two tables.

I tried to use built-in typemaps but I could only wrap a function that takes and returns one table which is the following:

%apply (float *INOUT, int) {(float *inout, int size)};

How can I create a SWIG typemap for a function that takes two tables and returns one table?

Body:
I found a simple way to do it.

%apply (float *INOUT, int) {(float *in1, int n1)};
%apply (float *INPUT, int) {(float *in2, int n2)};

It seems to work fine for my purpose.


问:
PLSQL-Parametric definition of group function
I have a table where i want to apply some aggregation functions having as criteria the grouping of spesific element of specific column. Assume the example below:

```<code>TIMESTAMP   SITE    VALUE

10:00            A  100
10:00            B  50
10:00            C  25
10:00            D  25
10:05            A  25
10:05            B  15
10:05            C  5
10:05            D  10
</code>```

i want to find the average value grouping by SITE, TIMESTAMP but the site A,B i want it to be estimated as one, meaning that i wanted to REPLACE B WITH A have AND THEN find the average:

```<code>TIMESTAMP   SITE    VALUE
10:00            A  75
10:00            A  75
10:00            C  25
10:00            D  25
10:05            A  20
10:05            A  20
10:05            C  5
10:05            D  10
</code>```

One way is to update the table setting B=A, but this is not such a sophisticated solution if i want in future to group more SITES

答:
You can find the averages of uncombined and combined sites separately and then union them togeather, like this -

```<code>SELECT timestamp, site, AVG(value) FROM
(
    -- uncombined
    SELECT timestamp, site, value FROM TABLE WHERE site NOT IN ('A', 'B')

    UNION ALL

    -- combined A, B
    SELECT timestamp, 'AB' site, AVG(value) val
    FROM TABLE
    GROUP BY timestamp
    WHERE site IN ('A', 'B')
) U
GROUP BY timestamp, site
</code>```

Just an idea, not tested the sql

ContentLicense: CC BY-SA 3.0

Body:
I have a table where i want to apply some aggregation functions having as criteria the grouping of spesific element of specific column. Assume the example below:

TIMESTAMP   SITE    VALUE

10:00            A  100
10:00            B  50
10:00            C  25
10:00            D  25
10:05            A  25
10:05            B  15
10:05            C  5
10:05            D  10

i want to find the average value grouping by SITE, TIMESTAMP but the site A,B i want it to be estimated as one, meaning that i wanted to REPLACE B WITH A have AND THEN find the average:

TIMESTAMP   SITE    VALUE
10:00            A  75
10:00            A  75
10:00            C  25
10:00            D  25
10:05            A  20
10:05            A  20
10:05            C  5
10:05            D  10

One way is to update the table setting B=A, but this is not such a sophisticated solution if i want in future to group more SITES

Body:
You can find the averages of uncombined and combined sites separately and then union them togeather, like this -

SELECT timestamp, site, AVG(value) FROM
(
    -- uncombined
    SELECT timestamp, site, value FROM TABLE WHERE site NOT IN ('A', 'B')

    UNION ALL

    -- combined A, B
    SELECT timestamp, 'AB' site, AVG(value) val
    FROM TABLE
    GROUP BY timestamp
    WHERE site IN ('A', 'B')
) U
GROUP BY timestamp, site

Just an idea, not tested the sql


问:
Generate a 64 bit .so file of GDAL Library
I used the GDAL Library in my application and it has been working properly. The Google play service announced that they upload only 64-bit compliant APK after 1st Aug 2019. So I rendered the project to 64 bit compliant. Unfortunately, there has some issue happened in GDAL library. they showing that no implementation for the gdal library(ie the .so file according to the ABI type). So I think the corresponding GDAL 64 bit were unavailable for this scope.
I have the .so file in armeabi folder which is 32 bit compliant. Then I switched to arm64-V8a compliant. After that I generate the build, the corresponding .so file is not there in arm64-v8a folder.
So my question is, How we can generate the 64 bit .so files from GDAL Library?
Note:
Normally I used 32 bit compliant APK and it has been running properly. According to the new requirement of Playstore I used 64-bit compliant APK and done a smoke testing,unfortunately they get crashed, the issue of this crash is that, I used a GDAL library,which has a .so files with respect to ABI type. so when I run in 64 bit, the error showing that no implementation found for GDAL.
Hence I used the apk analyzer to look the difference from 32 bit compliant. so I identified that there is no .so file related to arm64-V8a folder.
So I think we need to generate the 64 bit .so file for the GDAL Library.
Is there any solution to generate this
I here by adding the screen shots, see the lib folder
32 bit compliant
64bit compliant
3`.so files inside armeabi</p>

答:
How we can generate the 64 bit .so files from GDAL Library?

You have to build the library from its original source code using Android NDK.

See:

https://github.com/paamand/GDAL4Android

https://trac.osgeo.org/gdal/wiki/BuildingForAndroid


问:
Bootstrap div- align to center of page
I'm trying to center a col-span-6 div to the center of the page using Twitter Bootstrap 3. Unfortunately, nothing I do is working. I used Firefox developer tools to discern the issue was most likely stemming from the fact that the col-span-6 class was floated left. Therefore, I added a style="float: none !important;" to the col-span-6 element, but that did nothing.

Help!!

```<code><div class="panel-group col-sm-6" style="float: none;">
<div class="panel panel-default">
    <div class="panel-heading">
        <h5 class="card-title">test</h5>
    </div>
    <div class="panel-body">
        <p class="card-text">test</p>
    </div>
</div>
</div>
</code>```

答:
I'm not sure but it seems to me that you wanted to achieve this effect:

.super-center {
  margin: 0 auto !important;
  float: none !important;
}
 ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<div class="super-center panel-group col-sm-6">
<div class="panel panel-default">
    <div class="panel-heading">
        <h5 class="card-title">test</h5>
    </div>
    <div class="panel-body">
        <p class="card-text">test</p>
    </div>
</div>
</div></code>```

It was enough to add to your div's: margin: 0 auto;

Title: Bootstrap div- align to center of page

Body:
I'm trying to center a col-span-6 div to the center of the page using Twitter Bootstrap 3. Unfortunately, nothing I do is working. I used Firefox developer tools to discern the issue was most likely stemming from the fact that the col-span-6 class was floated left. Therefore, I added a style="float: none !important;" to the col-span-6 element, but that did nothing.

Help!!

test

test

Body:
I'm not sure but it seems to me that you wanted to achieve this effect:

.super-center {
  margin: 0 auto !important;
  float: none !important;
}

<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<div class="super-center panel-group col-sm-6">
<div class="panel panel-default">
    <div class="panel-heading">
        <h5 class="card-title">test</h5>
    </div>
    <div class="panel-body">
        <p class="card-text">test</p>
    </div>
</div>
</div>

It was enough to add to your div's: margin: 0 auto;


问:
Pushing x:latest which is the same image as x:<semver-version>
I ran this:

```<code>docker build -t "oresoftware/live-mutex-broker:1.0.2" .
docker push "oresoftware/live-mutex-broker:1.0.2"
</code>```

that worked. So how can I can then tag this as latest, and "push" the same image to

```<code>docker push "oresoftware/live-mutex-broker:latest"
</code>```

what's the proper way to do this? My guess is:

```<code>docker tag "oresoftware/live-mutex-broker:latest" "oresoftware/live-mutex-broker:1.0.2"
</code>```

but I don't really know. Nope didn't work, I tried that, and I get:

Error response from daemon: No such image:
  oresoftware/live-mutex-broker:latest

so maybe switch the operands?

答:
Use the following command to tag the currently created image for online repository

```<code> $ docker tag oresoftware/live-mutex-broker:1.0.2 oresoftware/live-mutex-broker:latest
</code>```

Then upload the image to docker hub with the command

```<code>$ docker push "oresoftware/live-mutex-broker:latest"
</code>```

Explaination

To tag a docker image you use this pattern:

```<code>docker tag <container-image-name> <username>/<repo>:<tag>
</code>```

And then just remove the <container-image-name> from the above command and replace tag key-word with push to push it to the repository.

```<code>docker push <username>/<repo>:<tag>
</code>```

Body:
I ran this:

docker build -t "oresoftware/live-mutex-broker:1.0.2" .
docker push "oresoftware/live-mutex-broker:1.0.2"

that worked. So how can I can then tag this as latest, and "push" the same image to

docker push "oresoftware/live-mutex-broker:latest"

what's the proper way to do this? My guess is:

docker tag "oresoftware/live-mutex-broker:latest" "oresoftware/live-mutex-broker:1.0.2"

but I don't really know. Nope didn't work, I tried that, and I get:

Error response from daemon: No such image:
  oresoftware/live-mutex-broker:latest

so maybe switch the operands?

Body:
Use the following command to tag the currently created image for online repository

 $ docker tag oresoftware/live-mutex-broker:1.0.2 oresoftware/live-mutex-broker:latest

Then upload the image to docker hub with the command

$ docker push "oresoftware/live-mutex-broker:latest"

Explaination

To tag a docker image you use this pattern:

docker tag <container-image-name> <username>/<repo>:<tag>

And then just remove the <container-image-name> from the above command and replace tag key-word with push to push it to the repository.

docker push <username>/<repo>:<tag>


答:
I keep the pad content in memory and render only one single window as:

```<code>----------------------------0 Window----------------------------
----------------------------1 Window----------------------------
----------------------------2 Window----------------------------
----------------------------3 Window----------------------------
----------------------------3 Window----------------------------
----------------------------3 Window----------------------------
</code>```

This enables mimicing a pad, since in 3 Window only the viewpoint of my data is rendered as lines. Scrolling can be simulated by changeing the range or index in my data structure and rerender only one 3 Window line if a line got selected and the whole window if scroll in- or decreases the memory viewport index. This way a pad is simulaed and I avoid the different ncurses calls as prefresh, pnoutrefresh, pechochar etc.  and can use only window, wrefresh, calls. As an example, a scroll down would change:

```<code>----------------------------3 Window-index 0--------------------
----------------------------3 Window-index 1--------------------
----------------------------3 Window-index 2--------------------
</code>```

to

```<code>----------------------------3 Window-index 1--------------------
----------------------------3 Window-index 2--------------------
----------------------------3 Window-index 3--------------------
</code>```

and so on and so forth. In the ncurses API, windows seam to have more features, I can use all of them too instead of having possible future constraints by using pads now.

I'm sure, the author of ncurses had his reasons, but I only would have made an API of ncurses with one window type with a flag to enable pad functionality. Pads seam unneccessarly cumbersome and reduced to me.

Title: Position in ncurses a pad below a window in c++

Body:
I create 3 windows on top of the standard screen, with screen-width columns and one row height with:

WINDOW* pWindow = newwin(0, COLS - 1, windowNr, 0); // windowNr 0 - 2

Which renders normally as consequitive windows:

----------------------------0 Window----------------------------
----------------------------1 Window----------------------------
----------------------------2 Window----------------------------

My problem is under the last created window I want a pad which I create
with:

WINDOW* pPad = newpad(LINES - 3, COLS - 1); // 3 because of the three pWindows

But pad is rendered above all pWindows:

----------------------------0 Pad----------------------------
----------------------------0 Pad----------------------------
----------------------------0 Pad----------------------------

How can I position the pad below the last window that the output is:

----------------------------0 Window----------------------------
----------------------------1 Window----------------------------
----------------------------2 Window----------------------------
------------------------------0 Pad-----------------------------
------------------------------0 Pad-----------------------------
------------------------------0 Pad-----------------------------

The newpad has unfortunately no (y,x) cooridnates as newwin has. To simply fill the pad with debug content I do:

werase(pPad); // Clear window, https://invisible-island.net/ncurses/man/curs_clear.3x.html
wmove(pPad, 0, 0); // Moves cursor in pad to y,x

for(int c = 0; c < 40; c++){
    string s = to_string(c) + ".\n";
    wprintw(pPad, s.c_str());
}

prefresh(pPad, 0, 0, 0, 0, maxRows, maxCols);

I also put different values in prefresh, its viewport scrolling or rather refreshing works perfectly as described in the documentation.

Body:
I keep the pad content in memory and render only one single window as:

----------------------------0 Window----------------------------
----------------------------1 Window----------------------------
----------------------------2 Window----------------------------
----------------------------3 Window----------------------------
----------------------------3 Window----------------------------
----------------------------3 Window----------------------------

This enables mimicing a pad, since in 3 Window only the viewpoint of my data is rendered as lines. Scrolling can be simulated by changeing the range or index in my data structure and rerender only one 3 Window line if a line got selected and the whole window if scroll in- or decreases the memory viewport index. This way a pad is simulaed and I avoid the different ncurses calls as prefresh, pnoutrefresh, pechochar etc.  and can use only window, wrefresh, calls. As an example, a scroll down would change:

----------------------------3 Window-index 0--------------------
----------------------------3 Window-index 1--------------------
----------------------------3 Window-index 2--------------------

to

----------------------------3 Window-index 1--------------------
----------------------------3 Window-index 2--------------------
----------------------------3 Window-index 3--------------------

and so on and so forth. In the ncurses API, windows seam to have more features, I can use all of them too instead of having possible future constraints by using pads now.

I'm sure, the author of ncurses had his reasons, but I only would have made an API of ncurses with one window type with a flag to enable pad functionality. Pads seam unneccessarly cumbersome and reduced to me.


问:
How to start and stop an ASP.NET Core 2.1 app programmatically with Windows Authentication enabled?
I have a very specific set of needs for an ASP.NET Core 2.1 application, that I can't seem to resolve. The purpose of the app is to demonstrate use of a web proxy with automation tools like Selenium, specifically against a site that uses NTLM authentication.

Because this is a demo site to be used in the context of other running code, I need to be able to start and stop it programmatically. I can't seem to find any way to use Kestral and IIS/IIS Express effectively to start and stop the app appropriately.

Because I want to demonstrate use of web browsers configured with a proxy to browse and be authenticated by this site, and because most browsers bypass a proxy when browsing localhost sites (and its cousins 127.0.0.1 and ::1), I need to be able to use a host name other than localhost to browse the site, and I'm using a simple alias in my hosts file for this purpose. However, this lets HTTP.sys right out, as attempting to register any URL prefix other than localhost results, entirely unsurprisingly knowing how HTTP.sys works, in an Access deniederror.

I've examined several other answers, all of which seem to be outdated, or just do not work for me.

Startup class is as follows:

```<code>public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.Configure<IISOptions>(iis => { iis.AutomaticAuthentication = false; });
        services.AddAuthentication(IISDefaults.AuthenticationScheme);
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseMvc();
    }
}
</code>```

If I manually launch the app in the debugger using the "IIS Express" profile, it works in that I get prompted for credentials. If I use the "project" profile, of course, it doesn't work because Kestrel doesn't appear to understand Windows Authentication without HTTP.sys. If I attempt to use any programmatic means to start the app (WebHost.CreateDefaultBuilder().Build().StartAsync, for example), it fails to prompt for authentication, I'm guessing for the same reasons it doesn't work under the "project" profile in the debugger.

The point is to avoid a minimum of configuration for users once cloning the demonstration repo. Hosting the web app in full-blown IIS is a non-starter. Similarly, solutions that require admin access (like using netsh http add urlacl) or running as admin are also non-starters, as many users do not have administrative access to their machines.

Is what I'm attempting even possible? How can I cobble this together to make it work? "What you're trying to do is impossible," is a perfectly valid answer, but if that's the answer given, I'd like additional information of why this it's impossible.

答:
I do not have much experience with IIS, nor do I fully understand your situation, but I hope I can share enough to help you figure this out.

There seem to be three aspects to your question:

Not using localhost as the hostname.

Windows Authentication

Starting & Stopping the app programmatically.

I can't help with 1. Regarding windows authentication:

ASP.NET Core supports two hosting models with IIS: InProcess and OutOfProcess.

When you choose "IIS Express", IIS runs the ASP.NET Core Application for you (InProcess) -- so there's no kestrel in the picture. When you choose the project profile, you're essentially self-hosting the application with Kestrel (OutOfProcess) -- so there's no IIS in the picture unless you explicitly configure it to act as a reverse proxy.

As long as you got IIS in the picture whether with InProcess or OutOfProcess, you should be able to get Windows Authentication working.

Kestrel's support for windows authentication depends on HTTP.sys.

Recommended reading: Configure Windows Authentication in ASP.NET Core | Host ASP.NET Core on Windows with IIS

Regarding starting and stopping the application:

With OutOfProcess you have full control, you can start and stop at will since you have access to the WebHost object.

With InProcess, I'm not sure if starting/stopping with WebHost would work, but you can stop it using IApplicationLifetime.StopApplication() and let IIS start it back up for you on the next request.

Body:
I have a very specific set of needs for an ASP.NET Core 2.1 application, that I can't seem to resolve. The purpose of the app is to demonstrate use of a web proxy with automation tools like Selenium, specifically against a site that uses NTLM authentication.

Because this is a demo site to be used in the context of other running code, I need to be able to start and stop it programmatically. I can't seem to find any way to use Kestral and IIS/IIS Express effectively to start and stop the app appropriately.

Because I want to demonstrate use of web browsers configured with a proxy to browse and be authenticated by this site, and because most browsers bypass a proxy when browsing localhost sites (and its cousins 127.0.0.1 and ::1), I need to be able to use a host name other than localhost to browse the site, and I'm using a simple alias in my hosts file for this purpose. However, this lets HTTP.sys right out, as attempting to register any URL prefix other than localhost results, entirely unsurprisingly knowing how HTTP.sys works, in an Access deniederror.

I've examined several other answers, all of which seem to be outdated, or just do not work for me.

Startup class is as follows:

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.Configure<IISOptions>(iis => { iis.AutomaticAuthentication = false; });
        services.AddAuthentication(IISDefaults.AuthenticationScheme);
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseMvc();
    }
}

If I manually launch the app in the debugger using the "IIS Express" profile, it works in that I get prompted for credentials. If I use the "project" profile, of course, it doesn't work because Kestrel doesn't appear to understand Windows Authentication without HTTP.sys. If I attempt to use any programmatic means to start the app (WebHost.CreateDefaultBuilder().Build().StartAsync, for example), it fails to prompt for authentication, I'm guessing for the same reasons it doesn't work under the "project" profile in the debugger.

The point is to avoid a minimum of configuration for users once cloning the demonstration repo. Hosting the web app in full-blown IIS is a non-starter. Similarly, solutions that require admin access (like using netsh http add urlacl) or running as admin are also non-starters, as many users do not have administrative access to their machines.

Is what I'm attempting even possible? How can I cobble this together to make it work? "What you're trying to do is impossible," is a perfectly valid answer, but if that's the answer given, I'd like additional information of why this it's impossible.


问:
Does the android application may allow another app to modify own files?
I am wondering about new skinning mechanism for my app. However I don't want to make my application bigger.

Is it possible to create another app, which will be able add/change files of another my app in /data/data/com.myfirstapp directory ?

答: You could set up aContentProvider that other apps could use to transfer data to your app, which could then save it to its own data directory.


问:
Android Studio Emulator and "Process finished with exit code 0"
I've updated android studio from 3.0 to 3.0.1 but when I launch Emulator it didn't get launched and gives message in event log:</p>

```<code>Emulator: Process finished with exit code 0
</code>```

答:
In AVD Manager,

Go to Edit Icon on AVD Manager for selected Device.

Click on show advanced settings and increase ram size from 1500 mb to 2 GB.

Then it works.

NOTE: Some virtual devices do not allow you to update RAM, but if so, try installing Nexus 4. because it does.

NOTE2: If still doesnt work, dont give up. just uninstall and reinstall the device with changing RAM again. in some cases this is how it works

NOTE3: If still doesnt work, this means your pc doesnt have enough ram space. so increase the ram to 3gb. it might work but it will suffer

NOTE4: If still doesnt work, try it with multicore 2 instead of 4.

NOTE5: Still doesnt work. Close the Android Studio and NEVER open it back :)

Body:
I've updated android studio from 3.0 to 3.0.1 but when I launch Emulator it didn't get launched and gives message in event log:

Emulator: Process finished with exit code 0


问:
FFMPEG: output scene change times in frames
I'm successfully using the -vf select='gte(scene,0.4)',metadata=print:file=shotcuts.txt command to get FFMPEG to detect scene changes and output the results to file. Is it possible to force the pts field to be in frames rather than the default, which seems to vary depending on the video format (e.g. frames for AVI files, nanosecs for MOV/MP4)?

Processing an AVI file, for example, outputs time stamps in frames:

frame 0 pts 151

frame 1 pts 206

Whereas an MP4 file outputs as media time:

frame 0 pts 540000

frame 1 pts 738000

答:
PTS stands for Presentation Timestamps and so cannot be in frames. However, PTS are denominated in terms of a timebase, and so if the timebase is set to 1/fps, then the PTS and frame index will coincide. This will work well only for streams which are constant frame rate and have an integer framerate.

Set the timebase by using the settb filter before select. For a 30 fps CFR stream,

```<code>-vf settb=1/30,select='gte(scene,0.4)',metadata=print:file=shotcuts.txt
</code>```

Body:
PTS stands for Presentation Timestamps and so cannot be in frames. However, PTS are denominated in terms of a timebase, and so if the timebase is set to 1/fps, then the PTS and frame index will coincide. This will work well only for streams which are constant frame rate and have an integer framerate.

Set the timebase by using the settb filter before select. For a 30 fps CFR stream,

-vf settb=1/30,select='gte(scene,0.4)',metadata=print:file=shotcuts.txt


问:
LinkedIn api v2 serviceErrorCode:65603 message:Multiple access token provided
After LinkedIn changed his API to v2 my users cannot login on my website anymore. The error message is

Multiple access token provided

With LinkedIn v1 API everything was good. For development purpose I added a second app in my LinkedIn account with a subdomain of the original domain. With the "subdomain"-app I received the error message that v1 is not supported anymore. The "original" domain app still worked with v1 until a couple of days ago. I adjusted the request to v2 and I received the error message "Multiple access token provided". I deleted the subdomain app, but the error still occurred.

With:

```<code>https://api.linkedin.com/v2/me?projection=(id,firstName,lastName,profilePicture(displayImage~:playableStreams))&format=json&access_token=xxxx
</code>```

I receive:

```<code>"serviceErrorCode":100,"message":"Unpermitted fields present in PARAMETER: Data Processing Exception while processing fields [/access_token, /format]","status":403
</code>```

I changed the access token name to oauth2_access_token:

```<code>https://api.linkedin.com/v2/me?projection=(id,firstName,lastName,profilePicture(displayImage~:playableStreams))&format=json&oauth2_access_token=xxxxx
</code>```

I receive:

```<code>serviceErrorCode":65603,"message":"Multiple access token provided","status":401
</code>```

What do I have to do, to provide just one (the right) access token?

答: Your access token needs to be included in the Authorization: Bearer {token} header of your request. You do not need to append the format=json query parameter as all API responses are returned in JSON format.

Body:
After LinkedIn changed his API to v2 my users cannot login on my website anymore. The error message is

Multiple access token provided

With LinkedIn v1 API everything was good. For development purpose I added a second app in my LinkedIn account with a subdomain of the original domain. With the "subdomain"-app I received the error message that v1 is not supported anymore. The "original" domain app still worked with v1 until a couple of days ago. I adjusted the request to v2 and I received the error message "Multiple access token provided". I deleted the subdomain app, but the error still occurred.

With:

https://api.linkedin.com/v2/me?projection=(id,firstName,lastName,profilePicture(displayImage~:playableStreams))&format=json&access_token=xxxx

I receive:

"serviceErrorCode":100,"message":"Unpermitted fields present in PARAMETER: Data Processing Exception while processing fields [/access_token, /format]","status":403

I changed the access token name to oauth2_access_token:

https://api.linkedin.com/v2/me?projection=(id,firstName,lastName,profilePicture(displayImage~:playableStreams))&format=json&oauth2_access_token=xxxxx

I receive:

serviceErrorCode":65603,"message":"Multiple access token provided","status":401

What do I have to do, to provide just one (the right) access token?


问:
Adium - XMPP Account add stucks at Registering
I'm trying to add an XMPP localhost account in Adium and failed to do so.

 While adding it I'm not getting any error, it just showsRegistering...

I've found a link of a similar question here and gone through some of the discussions, but unable to get an idea of how to solve it.
Unable to register XMPP user using Adium

I'm using ejabberd XMPP localhost server.

答:
Since you're using a local server you could just enable in-band registration. That way you can register as many accounts as you want.

However, if you're going to make your server public, just use this configs:
Allow anyone to register:
register-> all: allow
Only registrations from localhost:
trusted_network-> loopback:allow
With that configuration you could build a program on your localhost that accepts or denies registration based on some criteria.


问:
How to sort map without using comparable and Comparator Interface? How to write Custom Sorting?
Problem - I have a Student class, it contains Name, roll number, three subject marks m1,m2,m3, and total marks. I need to sort Student object according to their total marks if two or more students marks are equal then sort it according to their name. Note - I have to google it but not getting expected solution in stackoverflow question every one using Comparable and Comparator interface.

I have created class Studnt

```<code>public class Student {
    private String name;
    private Integer rollNumber;
    private int m1;
    private int m2;
    private int m3;
    private int totMarks;
    //Getter setter
}
</code>```

Main class

```<code>public class StudentData {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enetr the number of Student");
        int totalStudent = sc.nextInt();
        Map<Integer,Student> map = new TreeMap<Integer,Student>();
        for(int i =0;i<totalStudent;i++) {
            Student ss = new Student();
            System.out.println("Enter the Student roll number");
            ss.setRollNumber(sc.nextInt());
            System.out.println("Enter the Student Name");
            ss.setName(sc.next());
            System.out.println("Enter the m1 marks ");
            ss.setM1(sc.nextInt());
            System.out.println("Enetr the m2 marks ");
            ss.setM2(sc.nextInt());
            System.out.println("Enter the m3 marks ");
            ss.setM3(sc.nextInt());
            ss.setTotMarks(ss.getM1()+ss.getM2()+ss.getM3());

            map.put(ss.getTotMarks(),ss);
            ss=null;
        }
        //stdList.forEach(System.out::print);
        for(Map.Entry<Integer,Student> m :map.entrySet()) {
            System.out.println(m);
        }

    }
}
</code>```

Actually, I am using TreeMap it sort the value by key(total marks is key in my TreeMap). but two or more students have equal marks. Then older student object (value) replaced by the new student because of Key not allowed duplicate

output

6=Student [name=ved, rollNumber=12, m1=2, m2=2, m3=2, totMarks=6]

9=Student [name=prakash, rollNumber=56, m1=3, m2=3, m3=3, totMarks=9]

the only unique totMarks stored in the map

答:
Since you can't use existing Comparator or sorting algorithms, you need to do it on your own. I have implemented a static function <s>lessOrEqual which accepts 2 Student instances, compares them and returns whether or not s1 is less or equal to s2.</s> larger(Student s1, Student s2) which returns true ONLY IF s1 is larger than s2. There can be many different ways of doing this, it's really up to you as it's just a comprison. The function first checks the grades, if the grades match, it will then check the name and return accordingly.

EDIT: As you can see I replaced lessOrEqual with larger since the selection sort I'm using needs to find larger. It's the same effect, I only did it for better readability of the sort.

Then I implemented another static function that accepts ArrayList<Student>, sorts it and returns it sorted. The sorting algorithm used is very basic: Selection sort. It's O(N^2) which isn't efficient, but I did it for the sake of simplicity in the demo below.

Code:

```<code>import java.util.ArrayList;

public class Student {
    private String name;
    private Integer rollNumber;
    private int m1;
    private int m2;
    private int m3;
    private int totMarks;

    public static boolean larger(Student s1, Student s2){
        if(s1.totMarks < s2.totMarks) return false;
        else if (s1.totMarks > s2.totMarks) return true;
        // compare names
        else return s1.name.compareTo(s2.name) > 0;
    }

    public static ArrayList<Student> sortSelection(ArrayList<Student> list){
        for(int i=0; i<list.size(); i++){
            for(int j=i+1; j< list.size(); j++){
                if(larger(list.get(i), list.get(j))){ // swap
                    Student temp = list.get(i);
                    list.set(i, list.get(j));
                    list.set(j, temp);
                }
            }
        }
        return list;
    }
    //Getter setter
    public String getName(){
        return name;
    }

    public void setName(String name){
        this.name = name;
    }

    public int getTotMarks(){
        return totMarks;
    }

    public void setTotMarks(int totMarks){
        this.totMarks = totMarks;
    }

    @Override
    public String toString(){
        return String.format("Name: %20s - Total Marks: %3d", name, totMarks);
    }

    public static void main(String[] args){
        Student s1 = new Student();
        Student s2 = new Student();
        Student s3 = new Student();
        Student s4 = new Student();

        s1.setName("John Smith");
        s1.setTotMarks(98);
        s2.setName("Jack Smith");
        s2.setTotMarks(98);
        s3.setName("Adam Noob");
        s3.setTotMarks(100);
        s4.setName("Ved Parkash");
        s4.setTotMarks(99);

        ArrayList<Student> list = new ArrayList<>();
        list.add(s4);
        list.add(s3);
        list.add(s1);
        list.add(s2);

        System.out.println("Array before sorting:");
        for(int i=0; i<list.size(); i++){
            System.out.println(list.get(i).toString());
        }

        Student.sortSelection(list);

        System.out.println("Array after sorting:");
        for(int i=0; i<list.size(); i++){
            System.out.println(list.get(i).toString());
        }
    }
}
</code>```

Output:

```<code>Array before sorting:
Name:          Ved Parkash - Total Marks:  99
Name:            Adam Noob - Total Marks: 100
Name:           John Smith - Total Marks:  98
Name:           Jack Smith - Total Marks:  98
Array after sorting:
Name:           Jack Smith - Total Marks:  98
Name:           John Smith - Total Marks:  98
Name:          Ved Parkash - Total Marks:  99
Name:            Adam Noob - Total Marks: 100
</code>```

Notes:

1) See the order of addition of Students into the list, it's 4,3, 1 then 2. This is to prove that it sorts according to name when the grades match (Jack Smith vs John Smith).

2) I hardcoded the students to make for a better demo.

3) As you may notice, I'm not setting any of the other variables since the question is solely about sorting, and the only contributing variables to sorting are: name and totMarks. You will have to do the rest.

4) I am using ArrayList, but this isn't limited to that, with simple changes you can use it on a normal Student[] array.

5) The function larger doesn't have to be static, you can make it a member function and use it differently. For example, the code above would change to:

```<code>    public boolean larger(Student other){
        if(totMarks < other.totMarks) return false;
        else if (totMarks > other.totMarks) return true;
        // compare names
        else return name.compareTo(other.name) > 0;
    }

    public static ArrayList<Student> sortSelection(ArrayList<Student> list){
        for(int i=0; i<list.size(); i++){
            for(int j=i+1; j< list.size(); j++){
                // comparison way changes accordingly
                if(list.get(i).larger(list.get(j))){ // swap
                    Student temp = list.get(i);
                    list.set(i, list.get(j));
                    list.set(j, temp);
                }
            }
        }
        return list;
    }
</code>```

Body:
Problem - I have a Student class, it contains Name, roll number, three subject marks m1,m2,m3, and total marks. I need to sort Student object according to their total marks if two or more students marks are equal then sort it according to their name. Note - I have to google it but not getting expected solution in stackoverflow question every one using Comparable and Comparator interface.

I have created class Studnt

public class Student {
    private String name;
    private Integer rollNumber;
    private int m1;
    private int m2;
    private int m3;
    private int totMarks;
    //Getter setter
}

Main class

public class StudentData {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enetr the number of Student");
        int totalStudent = sc.nextInt();
        Map<Integer,Student> map = new TreeMap<Integer,Student>();
        for(int i =0;i<totalStudent;i++) {
            Student ss = new Student();
            System.out.println("Enter the Student roll number");
            ss.setRollNumber(sc.nextInt());
            System.out.println("Enter the Student Name");
            ss.setName(sc.next());
            System.out.println("Enter the m1 marks ");
            ss.setM1(sc.nextInt());
            System.out.println("Enetr the m2 marks ");
            ss.setM2(sc.nextInt());
            System.out.println("Enter the m3 marks ");
            ss.setM3(sc.nextInt());
            ss.setTotMarks(ss.getM1()+ss.getM2()+ss.getM3());

            map.put(ss.getTotMarks(),ss);
            ss=null;
        }
        //stdList.forEach(System.out::print);
        for(Map.Entry<Integer,Student> m :map.entrySet()) {
            System.out.println(m);
        }

    }
}

Actually, I am using TreeMap it sort the value by key(total marks is key in my TreeMap). but two or more students have equal marks. Then older student object (value) replaced by the new student because of Key not allowed duplicate

output

6=Student [name=ved, rollNumber=12, m1=2, m2=2, m3=2, totMarks=6]

9=Student [name=prakash, rollNumber=56, m1=3, m2=3, m3=3, totMarks=9]

the only unique totMarks stored in the map

Body:
Since you can't use existing Comparator or sorting algorithms, you need to do it on your own. I have implemented a static function <s>lessOrEqual which accepts 2 Student instances, compares them and returns whether or not s1 is less or equal to s2.</s> larger(Student s1, Student s2) which returns true ONLY IF s1 is larger than s2. There can be many different ways of doing this, it's really up to you as it's just a comprison. The function first checks the grades, if the grades match, it will then check the name and return accordingly.

EDIT: As you can see I replaced lessOrEqual with larger since the selection sort I'm using needs to find larger. It's the same effect, I only did it for better readability of the sort.

Then I implemented another static function that accepts ArrayList<Student>, sorts it and returns it sorted. The sorting algorithm used is very basic: Selection sort. It's O(N^2) which isn't efficient, but I did it for the sake of simplicity in the demo below.

Code:

import java.util.ArrayList;

public class Student {
    private String name;
    private Integer rollNumber;
    private int m1;
    private int m2;
    private int m3;
    private int totMarks;

    public static boolean larger(Student s1, Student s2){
        if(s1.totMarks < s2.totMarks) return false;
        else if (s1.totMarks > s2.totMarks) return true;
        // compare names
        else return s1.name.compareTo(s2.name) > 0;
    }

    public static ArrayList<Student> sortSelection(ArrayList<Student> list){
        for(int i=0; i<list.size(); i++){
            for(int j=i+1; j< list.size(); j++){
                if(larger(list.get(i), list.get(j))){ // swap
                    Student temp = list.get(i);
                    list.set(i, list.get(j));
                    list.set(j, temp);
                }
            }
        }
        return list;
    }
    //Getter setter
    public String getName(){
        return name;
    }

    public void setName(String name){
        this.name = name;
    }

    public int getTotMarks(){
        return totMarks;
    }

    public void setTotMarks(int totMarks){
        this.totMarks = totMarks;
    }

    @Override
    public String toString(){
        return String.format("Name: %20s - Total Marks: %3d", name, totMarks);
    }

    public static void main(String[] args){
        Student s1 = new Student();
        Student s2 = new Student();
        Student s3 = new Student();
        Student s4 = new Student();

        s1.setName("John Smith");
        s1.setTotMarks(98);
        s2.setName("Jack Smith");
        s2.setTotMarks(98);
        s3.setName("Adam Noob");
        s3.setTotMarks(100);
        s4.setName("Ved Parkash");
        s4.setTotMarks(99);

        ArrayList<Student> list = new ArrayList<>();
        list.add(s4);
        list.add(s3);
        list.add(s1);
        list.add(s2);

        System.out.println("Array before sorting:");
        for(int i=0; i<list.size(); i++){
            System.out.println(list.get(i).toString());
        }

        Student.sortSelection(list);

        System.out.println("Array after sorting:");
        for(int i=0; i<list.size(); i++){
            System.out.println(list.get(i).toString());
        }
    }
}

Output:

Array before sorting:
Name:          Ved Parkash - Total Marks:  99
Name:            Adam Noob - Total Marks: 100
Name:           John Smith - Total Marks:  98
Name:           Jack Smith - Total Marks:  98
Array after sorting:
Name:           Jack Smith - Total Marks:  98
Name:           John Smith - Total Marks:  98
Name:          Ved Parkash - Total Marks:  99
Name:            Adam Noob - Total Marks: 100

Notes:

1) See the order of addition of Students into the list, it's 4,3, 1 then 2. This is to prove that it sorts according to name when the grades match (Jack Smith vs John Smith).

2) I hardcoded the students to make for a better demo.

3) As you may notice, I'm not setting any of the other variables since the question is solely about sorting, and the only contributing variables to sorting are: name and totMarks. You will have to do the rest.

4) I am using ArrayList, but this isn't limited to that, with simple changes you can use it on a normal Student[] array.

5) The function larger doesn't have to be static, you can make it a member function and use it differently. For example, the code above would change to:

    public boolean larger(Student other){
        if(totMarks < other.totMarks) return false;
        else if (totMarks > other.totMarks) return true;
        // compare names
        else return name.compareTo(other.name) > 0;
    }

    public static ArrayList<Student> sortSelection(ArrayList<Student> list){
        for(int i=0; i<list.size(); i++){
            for(int j=i+1; j< list.size(); j++){
                // comparison way changes accordingly
                if(list.get(i).larger(list.get(j))){ // swap
                    Student temp = list.get(i);
                    list.set(i, list.get(j));
                    list.set(j, temp);
                }
            }
        }
        return list;
    }


问:
How to INDEX and MATCH with 4 Criteria
I'm using 4  criteria to determine the retail price and SKU (secondary concern).
I've previously had success when using INDEX and MATCH for 2 criteria. With 4 criteria I'm running into errors

I've attempted to use this formula

```<code>=ArrayFormula(index(CFanPriceList,match(1,(A18=CFanStyle)*(B18=CFanColour),*(C18=CFanSize),*(D18=CFanLight),0),7))
</code>```

The Named Ranges are:

```<code>CFanPrices  A2:H15

CFanStyle   A2:A15

CFanColour  B2:B15

CFanSize    C2:C15

CFanLight   D2:D15
</code>```

So,  in the example:

```<code>Fanco Eco Silent,   White,  48',    TRUE
</code>```

I'd expect to return the figure $279

Instead, I get

ERROR! formula parse error

Any thoughts?

答:
use this instead of your formula: </p>

```<code>=ARRAYFORMULA(IFERROR(VLOOKUP(A18&B18&C18&D18,
 {A1:A16&B1:B16&C1:C16&D1:D16, A1:G16}, 8, 0)))
</code>```

<p>or with your named ranges: </p>

```<code>=ARRAYFORMULA(IFERROR(VLOOKUP(A18&B18&C18&D18,
 {CFanStyle&CFanColour&CFanSize&CFanLight, CFanPrices}, 8, 0)))
</code>```

Title: How to INDEX and MATCH with 4 Criteria

Body:
I'm using 4  criteria to determine the retail price and SKU (secondary concern).
I've previously had success when using INDEX and MATCH for 2 criteria. With 4 criteria I'm running into errors

I've attempted to use this formula

=ArrayFormula(index(CFanPriceList,match(1,(A18=CFanStyle)*(B18=CFanColour),*(C18=CFanSize),*(D18=CFanLight),0),7))

The Named Ranges are:

CFanPrices  A2:H15

CFanStyle   A2:A15

CFanColour  B2:B15

CFanSize    C2:C15

CFanLight   D2:D15

So,  in the example:

Fanco Eco Silent,   White,  48',    TRUE

I'd expect to return the figure $279

Instead, I get

ERROR! formula parse error

Any thoughts?

Body:
use this instead of your formula:

=ARRAYFORMULA(IFERROR(VLOOKUP(A18&B18&C18&D18,
 {A1:A16&B1:B16&C1:C16&D1:D16, A1:G16}, 8, 0)))

or with your named ranges:

=ARRAYFORMULA(IFERROR(VLOOKUP(A18&B18&C18&D18,
 {CFanStyle&CFanColour&CFanSize&CFanLight, CFanPrices}, 8, 0)))


问:
sql query related issue
I have one more question in want to the user between the operator in php. This is my SQL query.

```<code>$results=$wpdb->get_results( "SELECT user_id,day,activity,hotel
FROM wp_user_activity
WHERE user_id = '$user_id' AND date BETWEEN $start AND $end ");
</code>```

it gives me an error

```<code>$results=$wpdb->get_results( "SELECT user_id,day,activity,hotel
FROM wp_user_activity
WHERE user_id = '$user_id' AND date BETWEEN '26/05/2019' AND '31/05/2019' ");
</code>```

am getting data in this why in the $start and $end am not getting any data

答:
your date format is wrong
please use standard date format that is YYYY-MM-DD
Use this

```<code>$results=$wpdb->get_results( "SELECT user_id,day,activity,hotel
FROM wp_user_activity
WHERE user_id = '$user_id' AND date BETWEEN '2019-05-26' AND '2019-05-31' ");
</code>```

Hope this will help you

Title: sql query related issue

Body:
I have one more question in want to the user between the operator in php. This is my SQL query.

$results=$wpdb->get_results( "SELECT user_id,day,activity,hotel
FROM wp_user_activity
WHERE user_id = '$user_id' AND date BETWEEN $start AND $end ");

it gives me an error

$results=$wpdb->get_results( "SELECT user_id,day,activity,hotel
FROM wp_user_activity
WHERE user_id = '$user_id' AND date BETWEEN '26/05/2019' AND '31/05/2019' ");

am getting data in this why in the $start and $end am not getting any data

Body:
your date format is wrong
please use standard date format that is YYYY-MM-DD
Use this

$results=$wpdb->get_results( "SELECT user_id,day,activity,hotel
FROM wp_user_activity
WHERE user_id = '$user_id' AND date BETWEEN '2019-05-26' AND '2019-05-31' ");

Hope this will help you


问:
How big is too big for an array stored in state with ngrx?
I have an array of around 4000 to 5000 objects that I need to work with throughout the life cycle of my angular app. I use ngrx for state management in this app and would load this data using an effect with the startWith operator. I was wondering how big is too big for an array of objects to be loaded and stored in state in this way.</p>

答:
It will really depends what's in your array, and what you plan to do with it. An array itself can contains a lot of values before it has any impact on your app.

But if you've got an array containing a humongous amount of values, here's my advice:

Do not display all the items at once, either use pagination or infinite scrolling solutions that you can find out there (there's a generic one into Material CDK for example!). This will be one of the biggest issue you might encounter: Displaying too much in the view

If you know you'll have to search into the array, try to build an index for your search as soon as you receive the array, not every time the search changes. For example if you've got an array of users and you know that your UI has a "Show only people with an age of +18", then you could create a Set containing all those people (only references to them)

Keep your data immutable and use the basic Angular functionalities: trackBy on your list with your *ngFor and also changeDetectionStrategy: ChangeDetectionStrategy.OnPush`

I've already tried to see if an app could handle 100K items and the answer is yes, even though it started to feel slightly unresponsive sometimes.
So 4 or 5k should be all good following the information above.


问:
using POST API in ios using URLSession
I'm learning IOS right now and I completely wrote same code with the tutorial. But I got an error like this

"2019-05-29 14:01:25.974883+0900 URLSessionJSONRequests[18165:938499]
  Task <0EC532CF-8CA6-42C9-9BD8-6D6E74BB9C06>.<10> finished with error -
  code: -1002"

My Code is this.

```<code>@IBAction func onPostTab(_ sender: UIButton) {

    let parameters = ["id":"uuzaza@naver.com","pw":"1q2w3e4r"]

    guard let url = URL(string:"https//taky.co.kr/login/app_login") else{return}
    var request = URLRequest(url: url)
    request.httpMethod = "POST"
    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    guard let httpBody = try? JSONSerialization.data(withJSONObject: parameters, options: [])else{
        return}
    request.httpBody = httpBody
    let session = URLSession.shared
    session.dataTask(with: request) { (data, response, error) in
        if let response = response {
            print(response)

        }
        if let data = data {
            do {
                let json = try JSONSerialization.jsonObject(with: data, options: [] )
                print(json)
            }catch{
                print(error)
            }
        }
    }.resume()

}
</code>```

what is error code -1002?? I used placeholder API and it is still supported and I think the server is not the problem. Any reference or advice would be grateful!

答:
Kindly check URL first you missed ':' after https.

Just replace your API End-point

https//taky.co.kr/login/app_login

With

https://taky.co.kr/login/app_login

After doing the above changes everything works fine.

API Response:

```<code><NSHTTPURLResponse: 0x60000327d120> { URL: https://taky.co.kr/login/app_login } { Status Code: 200, Headers {
    "Cache-Control" =     (
        "no-store, no-cache, must-revalidate"
    );
    Connection =     (
        "Keep-Alive"
    );
    "Content-Encoding" =     (
        gzip
    );
    "Content-Length" =     (
        93
    );
    "Content-Type" =     (
        "text/html; charset=UTF-8"
    );
    Date =     (
        "Wed, 29 May 2019 05:32:58 GMT"
    );
    Expires =     (
        "Thu, 19 Nov 1981 08:52:00 GMT"
    );
    "Keep-Alive" =     (
        "timeout=5, max=100"
    );
    Pragma =     (
        "no-cache"
    );
    Server =     (
        "Apache/2.4.18 (Ubuntu)"
    );
    "Set-Cookie" =     (
        "cookie=9f73o1c13mggukb15fq25usfpc6ms6cp; expires=Wed, 29-May-2019 09:32:58 GMT; Max-Age=14400; path=/; HttpOnly"
    );
    Vary =     (
        "Accept-Encoding"
    );
} }
{
    code = E01;
    message = "\Uc544\Uc774\Ub514\Ub97c \Uc785\Ub825\Ud574 \Uc8fc\Uc138\Uc694.";
}
</code>```

Title: using POST API in ios using URLSession

Body:
I'm learning IOS right now and I completely wrote same code with the tutorial. But I got an error like this

"2019-05-29 14:01:25.974883+0900 URLSessionJSONRequests[18165:938499]
  Task <0EC532CF-8CA6-42C9-9BD8-6D6E74BB9C06>.<10> finished with error -
  code: -1002"

My Code is this.

@IBAction func onPostTab(_ sender: UIButton) {

    let parameters = ["id":"uuzaza@naver.com","pw":"1q2w3e4r"]

    guard let url = URL(string:"https//taky.co.kr/login/app_login") else{return}
    var request = URLRequest(url: url)
    request.httpMethod = "POST"
    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    guard let httpBody = try? JSONSerialization.data(withJSONObject: parameters, options: [])else{
        return}
    request.httpBody = httpBody
    let session = URLSession.shared
    session.dataTask(with: request) { (data, response, error) in
        if let response = response {
            print(response)

        }
        if let data = data {
            do {
                let json = try JSONSerialization.jsonObject(with: data, options: [] )
                print(json)
            }catch{
                print(error)
            }
        }
    }.resume()

}

what is error code -1002?? I used placeholder API and it is still supported and I think the server is not the problem. Any reference or advice would be grateful!

Body:
Kindly check URL first you missed ':' after https.

Just replace your API End-point

https//taky.co.kr/login/app_login

With

https://taky.co.kr/login/app_login

After doing the above changes everything works fine.

API Response:

<NSHTTPURLResponse: 0x60000327d120> { URL: https://taky.co.kr/login/app_login } { Status Code: 200, Headers {
    "Cache-Control" =     (
        "no-store, no-cache, must-revalidate"
    );
    Connection =     (
        "Keep-Alive"
    );
    "Content-Encoding" =     (
        gzip
    );
    "Content-Length" =     (
        93
    );
    "Content-Type" =     (
        "text/html; charset=UTF-8"
    );
    Date =     (
        "Wed, 29 May 2019 05:32:58 GMT"
    );
    Expires =     (
        "Thu, 19 Nov 1981 08:52:00 GMT"
    );
    "Keep-Alive" =     (
        "timeout=5, max=100"
    );
    Pragma =     (
        "no-cache"
    );
    Server =     (
        "Apache/2.4.18 (Ubuntu)"
    );
    "Set-Cookie" =     (
        "cookie=9f73o1c13mggukb15fq25usfpc6ms6cp; expires=Wed, 29-May-2019 09:32:58 GMT; Max-Age=14400; path=/; HttpOnly"
    );
    Vary =     (
        "Accept-Encoding"
    );
} }
{
    code = E01;
    message = "\Uc544\Uc774\Ub514\Ub97c \Uc785\Ub825\Ud574 \Uc8fc\Uc138\Uc694.";
}


问:
Laravel & Vue warning issue
I have worked on Laravel & Vue js project.

This is Laravel code

The code works well but there is a warning in developer mode (inspect)

Laravel View code

```<code>@extends('layouts/app')

@section('content')

    <div id="app">
     </div>

@endsection
</code>```

app.js code

```<code>const router = new VueRouter({ mode: 'history', routes: routes});
const app = new Vue(Vue.util.extend({ router }, App)).$mount('#app');

app.js:74791 [Vue warn]: Cannot find element: #app
warn @ app.js:74791
query @ app.js:79817
./node_modules/vue/dist/vue.common.dev.js.Vue.$mount @ app.js:86018
./resources/js/app.js @ app.js:86329
__webpack_require__ @ app.js:20
0 @ app.js:86576
__webpack_require__ @ app.js:20
(anonymous) @ app.js:84
(anonymous) @ app.js:87
app.js:74791 [Vue warn]: Property or method "single" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property. See: https://v2.vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.

found in

---> <Overlap> at resources/js/components/OutwardComponent.vue
       <Root>
</code>```

答:
Your div that needs to reference the Vue should be in Layout file,
It might be possible that your div is rendering after the Vue Initialization.
Put

 in layouts/app file and see if its gone or not.

Title: Laravel & Vue warning issue

Body:
I have worked on Laravel & Vue js project.

This is Laravel code

The code works well but there is a warning in developer mode (inspect)

Laravel View code

@extends('layouts/app')

@section('content')

@endsection

app.js code

const router = new VueRouter({ mode: 'history', routes: routes});
const app = new Vue(Vue.util.extend({ router }, App)).$mount('#app');

app.js:74791 [Vue warn]: Cannot find element: #app
warn @ app.js:74791
query @ app.js:79817
./node_modules/vue/dist/vue.common.dev.js.Vue.$mount @ app.js:86018
./resources/js/app.js @ app.js:86329
__webpack_require__ @ app.js:20
0 @ app.js:86576
__webpack_require__ @ app.js:20
(anonymous) @ app.js:84
(anonymous) @ app.js:87
app.js:74791 [Vue warn]: Property or method "single" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property. See: https://v2.vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.

found in

---> <Overlap> at resources/js/components/OutwardComponent.vue
       <Root>

Body:
Your div that needs to reference the Vue should be in Layout file,
It might be possible that your div is rendering after the Vue Initialization.
Put <div id="app"></div> in layouts/app file and see if its gone or not.


问:
Accessibility on back to top link
I am working on a web page which is relatively long (4+ pages). For ease of use I have added the back to top link at the bottom of the page.

I would like to know, whether I can skip this link from screen readers or assistive tools by using aria-hidden="true" and tabindex="-1". Does this fail the accessibility criteria ?

Since the back to top arrow is visible at the bottom of the page, is it necessary to make this link available for screen reader users ?  So far my understanding is home key serves as back to top for keyboard/screen reader users.

Any suggestions would be really helpful.

答:
WCAG 2.1.1 is pretty clear on this topic.

All functionality of the content is operable through a keyboard interface...

It doesn't say "most" functionality.

The home key works for mouse users too so why should they also have the ability to click on the "back to top" link and no one else?

Title: Accessibility on back to top link


问:
Custom ordering by calculation in Django
Any solutions for custom calculation sorting in Django? I want to create a view that shows the Top Posts in my Blog. The ranking will be calculated by Post's attributes. Let's just say I have 3 IntegerFields called x, y, and z, and the ranking calculation will be x * y / z.

Any ideas? I would like to do Top Post ever, and also other variations filtered by time such as last 24 hours, 7 days, 1 month, etc.

Thanks!

答: The extra() queryset method should allow you to do this.  See the docs</p>


问:
sort list of custom objects based on enum in kotlin
I have a list of custom object and an Enum class. I have to sort the list based on the enum properties. For example:

My list:

```<code>val list = listOf(Item(1,Severity.CRITICAL), Item(3, Severity.LOW), Item(2, Severity.SEVERE))
</code>```

My enum class:

```<code>enum class Severity{
 CRITICAL, SEVERE, MODERATE, LOW
}
</code>```

My sorted list should be:

```<code>listOf(Item(1,Severity.CRITICAL), Item(2, Severity.SEVERE), Item(3, Severity.LOW))
</code>```

Ordering is done as per the order in enum class. How can I achieve this?

答:
Use sortedBy function. It will do the job very easily.

```<code>val ans = list.sortedBy { it.severity }
</code>```

Body:
I have a list of custom object and an Enum class. I have to sort the list based on the enum properties. For example:

My list:

val list = listOf(Item(1,Severity.CRITICAL), Item(3, Severity.LOW), Item(2, Severity.SEVERE))

My enum class:

enum class Severity{
 CRITICAL, SEVERE, MODERATE, LOW
}

My sorted list should be:

listOf(Item(1,Severity.CRITICAL), Item(2, Severity.SEVERE), Item(3, Severity.LOW))

Ordering is done as per the order in enum class. How can I achieve this?

Body:
Use sortedBy function. It will do the job very easily.

val ans = list.sortedBy { it.severity }


问:
How to remove top status bar black background
I'd like to create a TRUE fullscreen activity, but there is always a black status bar on screen top. Android 9.0.

I've tried almost all I can find with Google and existing Apps with similar jobs. Manifest, code, style, AS sample fullscreen activity, all were tried.

styles.xml:

```

<p>Manifest:</p>

<pre class="lang-xml prettyprint-override"><code><activity android:name=".ScreenActivity" android:theme="@style/AppThemeA" />
</code>```

Layout:

<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <FrameLayout
        android:id="@+id/rootLayout"
        android:fitsSystemWindows="true"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</androidx.coordinatorlayout.widget.CoordinatorLayout>
```

<p>Kotlin (commented lines are tried and failed):</p>

```class ScreenActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        //setTheme(R.style.AppThemeDetector)
        super.onCreate(savedInstanceState)

        //window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN)
        //window.setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS)
        //window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY or View.SYSTEM_UI_FLAG_FULLSCREEN

        /*
        window.decorView.systemUiVisibility = (
                View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                        or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                        or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                        or View.SYSTEM_UI_FLAG_FULLSCREEN
                )*/

        setContentView(R.layout.activity_screen_detector)
        ...
    }
}
```

The expected result:

What I actually got:

[[[[ Solution ]]]]

Found what caused this. You should set the App to FullScreen App in Settings -> Display.

https://www.gottabemobile.com/how-to-enable-full-screen-apps-on-galaxy-s10

So fixed. Thanks for all your help.

答:
Try this:

```<code>if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    Window window = getWindow();
    window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
    window.setStatusBarColor(getResources().getColor(R.color.colorPrimary));
} else if (Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT) {
    Window window = mContext.getWindow();
    window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
    int statusBarHeight = (int) dpToPx(24);

    View view = new View(mContext);
    view.setLayoutParams(new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT));
    view.getLayoutParams().height = statusBarHeight;
    ((ViewGroup) window.getDecorView()).addView(view);
     view.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
}
</code>```

dpToPx

```<code>public float dpToPx(float dp) {
    return (dp * Resources.getSystem().getDisplayMetrics().density);
}
</code>```

Body:
I'd like to create a TRUE fullscreen activity, but there is always a black status bar on screen top. Android 9.0.

I've tried almost all I can find with Google and existing Apps with similar jobs. Manifest, code, style, AS sample fullscreen activity, all were tried.

styles.xml:

Manifest:

<activity android:name=".ScreenActivity" android:theme="@style/AppThemeA" />

Layout:

<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <FrameLayout
        android:id="@+id/rootLayout"
        android:fitsSystemWindows="true"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</androidx.coordinatorlayout.widget.CoordinatorLayout>

Kotlin (commented lines are tried and failed):

class ScreenActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        //setTheme(R.style.AppThemeDetector)
        super.onCreate(savedInstanceState)

        //window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN)
        //window.setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS)
        //window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY or View.SYSTEM_UI_FLAG_FULLSCREEN

        /*
        window.decorView.systemUiVisibility = (
                View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                        or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                        or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                        or View.SYSTEM_UI_FLAG_FULLSCREEN
                )*/

        setContentView(R.layout.activity_screen_detector)
        ...
    }
}

The expected result:

What I actually got:

[[[[ Solution ]]]]

Found what caused this. You should set the App to FullScreen App in Settings -> Display.

https://www.gottabemobile.com/how-to-enable-full-screen-apps-on-galaxy-s10

So fixed. Thanks for all your help.

Body:
Try this:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    Window window = getWindow();
    window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
    window.setStatusBarColor(getResources().getColor(R.color.colorPrimary));
} else if (Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT) {
    Window window = mContext.getWindow();
    window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
    int statusBarHeight = (int) dpToPx(24);

    View view = new View(mContext);
    view.setLayoutParams(new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT));
    view.getLayoutParams().height = statusBarHeight;
    ((ViewGroup) window.getDecorView()).addView(view);
     view.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
}

dpToPx

public float dpToPx(float dp) {
    return (dp * Resources.getSystem().getDisplayMetrics().density);
}


问:
Vector iterator
I have a vector like this

```<code>std::vector<Sprite*> mDrawings;
std::vector<Sprite*>::iterator it = mDrawings.begin();
</code>```

This gives an error

```<code>Error: no suitable user-defined conversion from std::_Vector_iterator<std::_Vector_val<Sprite *, std::allocator<Sprite *>>> to std::_Vector_iterator<std::_Vector_val<Sprite *, std::allocator<Sprite *>>> exists
</code>```

But if i do the following

```<code>typedef std::vector<Sprite*> list;
list mDrawings;
list::iterator it = mDrawings.begin();
</code>```

Then it works ???.

UPDATE:
Im sorry it seems like the error was generated because of errors not related to the current code. I just saw the IDE underline with red and i thought that was the reason my application would not compile.

答:
Your pasted code doesn't actually show the error. However, here's another shot in the dark:

Is it possible that in your original case, mDrawings is a member variable of some class (just guessign from the m prefix) and that your real code is in a const method? If so, you'd be trying to assing a const_iterator (since that's what calling begin() on a const vector will yield) to an iterator, which isn't possible.

Try using

```<code>std::vector<Sprite *>::const_iterator it = mDrawings.begin();
</code>```

does that work better?

Title: Vector iterator

Body:
I have a vector like this

std::vector<Sprite*> mDrawings;
std::vector<Sprite*>::iterator it = mDrawings.begin();

This gives an error

Error: no suitable user-defined conversion from std::_Vector_iterator<std::_Vector_val<Sprite *, std::allocator<Sprite *>>> to std::_Vector_iterator<std::_Vector_val<Sprite *, std::allocator<Sprite *>>> exists

But if i do the following

typedef std::vector<Sprite*> list;
list mDrawings;
list::iterator it = mDrawings.begin();

Then it works ???.

UPDATE:
Im sorry it seems like the error was generated because of errors not related to the current code. I just saw the IDE underline with red and i thought that was the reason my application would not compile.

Body:
Your pasted code doesn't actually show the error. However, here's another shot in the dark:

Is it possible that in your original case, mDrawings is a member variable of some class (just guessign from the m prefix) and that your real code is in a const method? If so, you'd be trying to assing a const_iterator (since that's what calling begin() on a const vector will yield) to an iterator, which isn't possible.

Try using

std::vector<Sprite *>::const_iterator it = mDrawings.begin();

does that work better?


问:
Using PythonService.exe to host python service while using virtualenv
I've got a Windows 7 environment where I need to develop a Python Windows Service using Python 3.4. I'm using pywin32's win32service module to setup the service and most of the hooks seem to be working ok.

The problem is when I attempt to run the service from source code (using python service.py install followed by python service.py start). This uses PythonService.exe to host service.py - but I'm using a venv virtual environment and the script can't find it's modules (error message discovered with python service.py debug).

Pywin32 is installed in the virtualenv and in looking at the source code of PythonService.exe, it dynamically links in Python34.dll, imports my service.py and invokes it.

How can I get PythonService.exe to use my virtualenv when running my service.py?

答:
I read all the answers, but no solution can fix my problem.

After carefully researched David K. Hess's code, I made some change, and it finally works.

But my reputation doesn't enough, so I just post the code here.

```<code># 1. Custom your Project's name and Virtual Environment folder's name
# 2. Import this before all third part models
# 3. If you still failed, check the link below:
# https://stackoverflow.com/questions/34696815/using-pythonservice-exe-to-host-python-service-while-using-virtualenv
# 2019-05-29 by oraant, modified from David K. Hess's answer.

import os, sys, site

project_name = "PythonService"  # Change this for your own project !!!!!!!!!!!!!!
venv_folder_name = "venv"  # Change this for your own venv path !!!!!!!!!!!!!!

if sys.executable.lower().endswith("pythonservice.exe"):

    # Get root path for the project
    service_directory = os.path.abspath(os.path.dirname(__file__))
    project_directory = service_directory[:service_directory.find(project_name)+len(project_name)]

    # Get venv path for the project
    def file_path(x): return os.path.join(project_directory, x)
    venv_base = file_path(venv_folder_name)
    venv_scripts = os.path.join(venv_base, "Scripts")
    venv_packages = os.path.join(venv_base, 'Lib', 'site-packages')

    # Change current working directory from PythonService.exe location to something better.
    os.chdir(project_directory)
    sys.path.append(".")
    prev_sys_path = list(sys.path)

    # Manually activate a virtual environment inside an already initialized interpreter.
    os.environ['PATH'] = venv_scripts + os.pathsep + os.environ['PATH']

    site.addsitedir(venv_packages)
    sys.real_prefix = sys.prefix
    sys.prefix = venv_base

    # Move some sys path in front of others
    new_sys_path = []
    for item in list(sys.path):
        if item not in prev_sys_path:
            new_sys_path.append(item)
            sys.path.remove(item)
    sys.path[:0] = new_sys_path
</code>```

How to use it? It's simple, just paste it into a new python file, and import it before any third part model like this:

```<code>import service_in_venv  # import at top
import win32serviceutil
import win32service
import win32event
import servicemanager
import time
import sys, os
........
</code>```

And now you should fix your problem.

Body:
I read all the answers, but no solution can fix my problem.

After carefully researched David K. Hess's code, I made some change, and it finally works.

But my reputation doesn't enough, so I just post the code here.

# 1. Custom your Project's name and Virtual Environment folder's name
# 2. Import this before all third part models
# 3. If you still failed, check the link below:
# https://stackoverflow.com/questions/34696815/using-pythonservice-exe-to-host-python-service-while-using-virtualenv
# 2019-05-29 by oraant, modified from David K. Hess's answer.

import os, sys, site

project_name = "PythonService"  # Change this for your own project !!!!!!!!!!!!!!
venv_folder_name = "venv"  # Change this for your own venv path !!!!!!!!!!!!!!

if sys.executable.lower().endswith("pythonservice.exe"):

    # Get root path for the project
    service_directory = os.path.abspath(os.path.dirname(__file__))
    project_directory = service_directory[:service_directory.find(project_name)+len(project_name)]

    # Get venv path for the project
    def file_path(x): return os.path.join(project_directory, x)
    venv_base = file_path(venv_folder_name)
    venv_scripts = os.path.join(venv_base, "Scripts")
    venv_packages = os.path.join(venv_base, 'Lib', 'site-packages')

    # Change current working directory from PythonService.exe location to something better.
    os.chdir(project_directory)
    sys.path.append(".")
    prev_sys_path = list(sys.path)

    # Manually activate a virtual environment inside an already initialized interpreter.
    os.environ['PATH'] = venv_scripts + os.pathsep + os.environ['PATH']

    site.addsitedir(venv_packages)
    sys.real_prefix = sys.prefix
    sys.prefix = venv_base

    # Move some sys path in front of others
    new_sys_path = []
    for item in list(sys.path):
        if item not in prev_sys_path:
            new_sys_path.append(item)
            sys.path.remove(item)
    sys.path[:0] = new_sys_path

How to use it? It's simple, just paste it into a new python file, and import it before any third part model like this:

import service_in_venv  # import at top
import win32serviceutil
import win32service
import win32event
import servicemanager
import time
import sys, os
........

And now you should fix your problem.


问:
How to parameterize 'Synchronizing Timer' parameters in Jmeter
How to read synchronizing timer parameters value from csv file.

CSV file consists of two columns: Value and Count

I want to read 'Count' field value to parameterize 'Number of simulated users to group by field' .

I have tried :
1)${__BeanShell(1*${Count})}

2)${Count}

答:
Add csv config file in your as child of your http request and add the following

and then add the following in sync timer

And your csv should look something like this


答:
You can do:

```<code>row.names(df) = df[,1]
with(data.frame(as.table(as.matrix(df[,-1]))),
         data.frame('Year-Month' = paste(Var1,Var2,sep='-'),Value=Freq))
</code>```

or you can also do:

```<code>with(cbind(year=df[,1],stack(df[,-1])),
      data.frame(year=paste(year,ind,sep='-'),val=values)[order(year),])
</code>```

Title: Making a time series data

Body:
I have a dataframe of time series observations like below

 Year/Month APR MAY JUN.......MAR
    2012     201 203 208...   2016
    2013     220 221 222......2018
    2014      ....................
     .        .
     .        .
     .        .
    2019      230 235 237      240

I need the data to be like this

 Period      Value
Apr-2012      .
May-2012      .
Jun-2012      .
.
.
.
.
.
Apr-2013
May-2013
Jun-2013
.
.
.
Jan-2019
Feb-2019
Mar-2019       .

Body:
You can do:

row.names(df) = df[,1]
with(data.frame(as.table(as.matrix(df[,-1]))),
         data.frame('Year-Month' = paste(Var1,Var2,sep='-'),Value=Freq))

or you can also do:

with(cbind(year=df[,1],stack(df[,-1])),
      data.frame(year=paste(year,ind,sep='-'),val=values)[order(year),])


问:
Creating "constructor function": __new__ with the __init__'s signature
The problem is simple: I want to create a callable reference to the "constructor" of some class. And I want that constructor function to have correct signature.

The answer is not just func = MyClass since it lacks the signature (and is not quite a function).

```<code>>>> inspect.signature(MyClass.__call__)
<Signature (*args, **kwargs)>
</code>```

The answer is not just func = MyClass.__new__ since it lacks the signature.

```<code>>>> inspect.signature(MyClass.__new__)
<Signature (*args, **kwargs)>
</code>```

The answer is not just func = MyClass.__init__ since it returns None and needs a self.

```<code>>>> inspect.signature(MyClass.__init__)
<Signature (self, a, b)>
</code>```

So, I need __new__ with the __init__'s signature (but without self).

```<code>func = MyClass.???
inspect.signature(func)
<Signature (a, b)>
</code>```

What's the easiest way to make it?

答:
This works for me:

```<code>class Test():

    def __init__(self,a,b):
        print(a)

Test("hello","world")
func = Test.__call__
func("foo","bar")
</code>```

(*args, **kwargs) is very similar to (a, b) with *args being the array of required arguments and **kwargs being the dictionary of optional arguments. So you can call it normally and the syntactic sugar will change the array into arguments.

Body:
The problem is simple: I want to create a callable reference to the "constructor" of some class. And I want that constructor function to have correct signature.

The answer is not just func = MyClass since it lacks the signature (and is not quite a function).

>>> inspect.signature(MyClass.__call__)
<Signature (*args, **kwargs)>

The answer is not just func = MyClass.__new__ since it lacks the signature.

>>> inspect.signature(MyClass.__new__)
<Signature (*args, **kwargs)>

The answer is not just func = MyClass.__init__ since it returns None and needs a self.

>>> inspect.signature(MyClass.__init__)
<Signature (self, a, b)>

So, I need __new__ with the __init__'s signature (but without self).

func = MyClass.???
inspect.signature(func)
<Signature (a, b)>

What's the easiest way to make it?

Body:
This works for me:

class Test():

    def __init__(self,a,b):
        print(a)

Test("hello","world")
func = Test.__call__
func("foo","bar")

(*args, **kwargs) is very similar to (a, b) with *args being the array of required arguments and **kwargs being the dictionary of optional arguments. So you can call it normally and the syntactic sugar will change the array into arguments.