问:
c++ definition inheritance scheme
the code is probably bad written and I would like to know how it should be done correctly.

Thanks for help

For the following inheritance scheme: A→B→C

a) define classes assuming that class A is to be an abstract class

b) equip all classes with a virtual name method returning the class name

c) add virtual destructors

d) add a global function friend of class A so that it can perform the same function as in point b

```<code>#include <iostream>

using namespace std;

class A {

    public:

    A();
    virtual void name();
    {

        return A;

    }
    friend void ffriend()
    virtual ~A();

};

class B : public A{

    public:

    B();
    virtual void name();
    {

        return B;

    }

    virtual ~B();

};

class C : public B{

    public:

    C();
    virtual void name();
    {

        return C;

    }

    virtual ~C()

};

    friend void ffriend(&A){

        name.A();

    }
</code>```

答:
Your code cannot compile and have a lot of syntax error

b) equip all classes with a virtual name method returning the class name

that means the profile can be

```<code>virtual const char * name();
</code>```

or

```<code>virtual const char * name() const;
</code>```

or

```<code>virtual std::string name();
</code>```

or

```<code>virtual std::string name() const;
</code>```

but not virtual void name()

a) define classes assuming that class A is to be an abstract class

so at least one method must be abstract, typically in your case this is name

For the following inheritance scheme: A→B→C

probably because I do UML for me the arrows are in the wrong direction, but A being abstract very probably C inherits B which inherits  (realize) A

c) add virtual destructors

that is trivial, but do not forget to implement them, not only to declare them

d) add a global function friend of class A so that it can perform the same function as in point b

that typically means the function get a reference to A, notice in your case the declaration and the definition do not correspond, and the list of parameters (&A) is invalid

An example can be :

```<code>#include <iostream>

class A {
  public:
    // default contructor is enough
    virtual ~A() {} // c)

    virtual const char * name() const = 0; // a) and b)

    friend const char * ffriend(const A &); // d)
};

const char * ffriend(const A & a)
{
  return a.name(); // or return "A" ?
}

class B : public A {
  public:
    // default contructor is enough
    virtual ~B() {} // c)

    virtual const char * name() const { return "B"; } // b)

};

class C : public B {
  public:
    // default contructor is enough
    virtual ~C() {}

    virtual const char * name() const { return "C"; } // b)
};

int main()
{
  B b;
  C c;

  std::cout << b.name() << ' ' << c.name() << ' ' << ffriend(b) << std::endl;
}
</code>```

Compilation and execution:

```<code>pi@raspberrypi:/tmp $ g++ -Wall c.cc
pi@raspberrypi:/tmp $ ./a.out
B C B
pi@raspberrypi:/tmp $
</code>```

It is not very clear what name the friend function has to return, I supposed the real class name but it can be "A" either.

Note also in A the method name can be private to justify the presence of the friend method if I can say.

Title: c++ definition inheritance scheme

Body:
the code is probably bad written and I would like to know how it should be done correctly.

Thanks for help

For the following inheritance scheme: A→B→C

a) define classes assuming that class A is to be an abstract class

b) equip all classes with a virtual name method returning the class name

c) add virtual destructors

d) add a global function friend of class A so that it can perform the same function as in point b

#include <iostream>

using namespace std;

class A {

    public:

    A();
    virtual void name();
    {

        return A;

    }
    friend void ffriend()
    virtual ~A();

};

class B : public A{

    public:

    B();
    virtual void name();
    {

        return B;

    }

    virtual ~B();

};

class C : public B{

    public:

    C();
    virtual void name();
    {

        return C;

    }

    virtual ~C()

};

    friend void ffriend(&A){

        name.A();

    }

Body:
Your code cannot compile and have a lot of syntax error

b) equip all classes with a virtual name method returning the class name

that means the profile can be

virtual const char * name();

or

virtual const char * name() const;

or

virtual std::string name();

or

virtual std::string name() const;

but not virtual void name()

a) define classes assuming that class A is to be an abstract class

so at least one method must be abstract, typically in your case this is name

For the following inheritance scheme: A→B→C

probably because I do UML for me the arrows are in the wrong direction, but A being abstract very probably C inherits B which inherits  (realize) A

c) add virtual destructors

that is trivial, but do not forget to implement them, not only to declare them

d) add a global function friend of class A so that it can perform the same function as in point b

that typically means the function get a reference to A, notice in your case the declaration and the definition do not correspond, and the list of parameters (&A) is invalid

An example can be :

#include <iostream>

class A {
  public:
    // default contructor is enough
    virtual ~A() {} // c)

    virtual const char * name() const = 0; // a) and b)

    friend const char * ffriend(const A &); // d)
};

const char * ffriend(const A & a)
{
  return a.name(); // or return "A" ?
}

class B : public A {
  public:
    // default contructor is enough
    virtual ~B() {} // c)

    virtual const char * name() const { return "B"; } // b)

};

class C : public B {
  public:
    // default contructor is enough
    virtual ~C() {}

    virtual const char * name() const { return "C"; } // b)
};

int main()
{
  B b;
  C c;

  std::cout << b.name() << ' ' << c.name() << ' ' << ffriend(b) << std::endl;
}

Compilation and execution:

pi@raspberrypi:/tmp $ g++ -Wall c.cc
pi@raspberrypi:/tmp $ ./a.out
B C B
pi@raspberrypi:/tmp $

It is not very clear what name the friend function has to return, I supposed the real class name but it can be "A" either.

Note also in A the method name can be private to justify the presence of the friend method if I can say.


来源: stackexchange

问:
Invalid command name in Tcl when using format
I'm running the following commands

```<code>set full_pin_name [format "%s %s" $top_cell $encoded_name]
puts "full_pin_name is $full_pin_name"
</code>```

and I get the following error:

```<code>full_pin_name is invalid command name "A" B
</code>```

when top_cell equals A and encoded_name equals B.

Why is this happening?

答:
As far as I can tell without a TCL interpreter here it should work assuming a normal interpreter with format defined. so it looks like maybe format has been renamed or doesn't exist as a command in the interpreter you are using?

To get you going you don't really need format to join strings anyway

set fill_pin_name "$top_cell $encoded_name"

should so what you need

ContentLicense: CC BY-SA 3.0

Body:
I'm running the following commands

set full_pin_name [format "%s %s" $top_cell $encoded_name]
puts "full_pin_name is $full_pin_name"

and I get the following error:

full_pin_name is invalid command name "A" B

when top_cell equals A and encoded_name equals B.

Why is this happening?


问:
update anaconda virtual environment to specific python version
I installed python 3.7 with anaconda on my unbuntu server, and created a virtual env named py36.  I accidentally created it as a python 2.7 env.  Is there a way to update the virtual env py36 and all it's packages to python 3.5?</p>

答:
You can activate the environment and install whichever version of Python you want:

```<code>conda activate py36
conda install python=3.X
</code>```

This will automatically update all the packages to the version that you want.

ContentLicense: CC BY-SA 4.0

Body:
You can activate the environment and install whichever version of Python you want:

conda activate py36
conda install python=3.X

This will automatically update all the packages to the version that you want.


问:
Difference of n dictionaries
I'm looking for a way to determine the difference of n dictionaries in the following scenario:
There are n dictionaries. Some of their keys match, but not all. Like this:

```<code>dict_a = {
    'keyA': 'valueA',
    'keyB': 'valueB',
    'keyC': 'valueC',
    'keyD': 'valueD',
    'keyE': 'valueE',
    'keyF': 'valueF',
    'keyG': 'valueG'
}
</code>```

```<code>dict_b = {
    'keyA': 'valueA',
    'keyB': 'valueB',
    'keyX': 'valueX',
    'keyD': 'valueH',
    'keyE': 'valueE',
    'keyF': 'valueF',
    'keyG': 'valueG'
}
</code>```

I want to be able, to tell if the value of a key is different from the value of the same key in another dictionary. In the examble above keyD should be returned, because its value is different in dict_a and dict_b. keyX should not be returned, as it only occurs in dict_b This is relatively easy with only two dictionaries, but what is the best practise to accomplish this with n dictionaries?

答:
Iterate over the list of dictionaries to compare, and keep track of all keys you've previously seen and their values (done through the orig.update() call).

```<code>compare = [{
    'keyA': 'valueA',
    'keyB': 'valueB',
    'keyC': 'valueC',
    'keyD': 'valueD',
    'keyE': 'valueE',
    'keyF': 'valueF',
    'keyG': 'valueG'
},
{
    'keyA': 'valueA',
    'keyB': 'valueB',
    'keyX': 'valueX',
    'keyD': 'valueH',
    'keyE': 'valueE',
    'keyF': 'valueF',
    'keyG': 'valueG'
},
{
    'keyA': 'valueA',
    'keyB': 'valueB',
    'keyX': 'valueX',
    'keyD': 'valueH',
    'keyE': 'valueE',
    'keyF': 'valueF',
    'keyG': 'valueB'
}]

orig = compare[0]
diffs = []

for comp in compare[1:]:
    for k in comp:
        if k in orig and orig[k] != comp[k]:
            diffs.append(k)

    orig.update(comp)

print(diffs)
</code>```

.. outputs ['keyD', 'keyG'] which are the two keys that have differing values of the three dicts. Replace diffs with a dictionary and use dict.values() if you don't want the keys to show up multiple times (i.e. if you only need to know that they have changed, not how many times they've changed).

Title: Difference of n dictionaries

Body:
I'm looking for a way to determine the difference of n dictionaries in the following scenario:
There are n dictionaries. Some of their keys match, but not all. Like this:

dict_a = {
    'keyA': 'valueA',
    'keyB': 'valueB',
    'keyC': 'valueC',
    'keyD': 'valueD',
    'keyE': 'valueE',
    'keyF': 'valueF',
    'keyG': 'valueG'
}

dict_b = {
    'keyA': 'valueA',
    'keyB': 'valueB',
    'keyX': 'valueX',
    'keyD': 'valueH',
    'keyE': 'valueE',
    'keyF': 'valueF',
    'keyG': 'valueG'
}

I want to be able, to tell if the value of a key is different from the value of the same key in another dictionary. In the examble above keyD should be returned, because its value is different in dict_a and dict_b. keyX should not be returned, as it only occurs in dict_b This is relatively easy with only two dictionaries, but what is the best practise to accomplish this with n dictionaries?

Body:
Iterate over the list of dictionaries to compare, and keep track of all keys you've previously seen and their values (done through the orig.update() call).

compare = [{
    'keyA': 'valueA',
    'keyB': 'valueB',
    'keyC': 'valueC',
    'keyD': 'valueD',
    'keyE': 'valueE',
    'keyF': 'valueF',
    'keyG': 'valueG'
},
{
    'keyA': 'valueA',
    'keyB': 'valueB',
    'keyX': 'valueX',
    'keyD': 'valueH',
    'keyE': 'valueE',
    'keyF': 'valueF',
    'keyG': 'valueG'
},
{
    'keyA': 'valueA',
    'keyB': 'valueB',
    'keyX': 'valueX',
    'keyD': 'valueH',
    'keyE': 'valueE',
    'keyF': 'valueF',
    'keyG': 'valueB'
}]

orig = compare[0]
diffs = []

for comp in compare[1:]:
    for k in comp:
        if k in orig and orig[k] != comp[k]:
            diffs.append(k)

    orig.update(comp)

print(diffs)

.. outputs ['keyD', 'keyG'] which are the two keys that have differing values of the three dicts. Replace diffs with a dictionary and use dict.values() if you don't want the keys to show up multiple times (i.e. if you only need to know that they have changed, not how many times they've changed).


问:
ClickOnce application is signed, certs are in appropriate user store, but still says "Unknown Publisher"
I have an Office Add-In that I've deployed many times before. Here is the sequence I go through:

I get out my code signing certificate from a trusted CA (I actually have 2 from different CAs and both cause the same problem).

I put that in my Personal store so I can use it.

I export the public key to a .cer file.

I add that public key to the Trusted Publisher store.

I add the certificate above that one to the Intermediate store.

I add the root certificate to the Trusted Root CA store.

If installing from a network drive, I add it to the Intranet Sites list under IE > Internet Options > Security > Local Intranet > Sites > Advanced. In this case, I'm installing from a local drive.

Currently I'm using the user-level store, but for real deployment I put it in the machine-level store. AFAIK it doesn't really matter which store I use.

Usually, this results in a prompt-less, automatic installation. However, I switched machines and now I am getting prompted with an "Unknown Publisher" and a yellow warning icon.

It shouldn't be failing to check the CRL, I tried using the issuer's tools, and it says the cert is fine, and it happens even if CRL checks are turned off.

I dug through a lot of StackOverflow questions, and some google results too. Pretty much every question about this is a basic failure to adhere to the steps I listed above. I also turned on ClickOnce logging but it doesn't say anything about the publisher.

What else could be going wrong here?

答:
This was apparently due to using an old version of mage.exe that I had kept around for convenience's sake. Using a newer one, e.g. from C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin, made it go away. Probably due to the signing algorithm used.

e: No, it was something else, and I still am not entirely sure what it was. There was some strange interaction with having CRL checks enabled/disabled.


问:
connecting to network registry
In Windows you can launch the registry and them connect to another registry; does anyone know how to accomplish this in c#? or if you know how of an api call that would be helpful.

Thanks

答: The API function is RegConnectRegistry. I've linked to the MSDN documentation, where you'll find a list of all Registry Functions here.</p>

Title: connecting to network registry


问:
Unable to format Dollar Amount with Dollar sign and comma to simple number using Text to Column and Format Cells Option in Excel
I was revisiting a Data Science Tutorial where the tutor is performing the data preparation phase. He formats date and Dollar Amount using the Text to column and then applying the respective format cells options, earlier when i did this both dates and dollar amount formatted well but due to some reasons i had to format my pc so i reinstalled everything, but now i am able to format only date column properly the dollar amount Column is not changing at all with the text to columns option in which it should get converted to number but it still remains text until i manually remove the dollar sign and comma using the find and replace option original state of Date and Balancescreenshot after "Text to Column" and "Format Cells" option was applied --date changed correctly to yyyy-mm-dd but Balance remained unchanged.screenshot when the balance changed when i removed the , and $ sign using find and replace.I wanted to know how to change the balance the same way as i changed the date format using "Text to Column" option and then applying Format cells. Do i have to reformat my pc ?Some related articles said that it has something to do with the system regional Locale Settings, but i did not touched it neither earlier(before format) or after format.</p>

答: it worked when i changed my regional setting to English(US) all thing is in Dollar that's why i guess it worked as the countries with different standard money it excel working in that regional would not recognize the money as Dollar as there some else money is used like Yen, or Euros etc. </p>


问:
Create DataFrame from multiple lists?
I have two lists

```<code>list1=['a','b','c']

list2=[1,2]
</code>```

I want my dataframe output to look like:

col1     col2
a        1
a        2
b        1
b        2
c        1
c        2
```

How can this be done?

答:
Use itertools.product:

```<code>import itertools

list1 = ['a','b','c']
list2 = [1,2]
df = pd.DataFrame(itertools.product(list1, list2), columns=['col1', 'col2'])
print(df)
</code>```

Output:

```<code>  col1  col2
0    a     1
1    a     2
2    b     1
3    b     2
4    c     1
5    c     2
</code>```

Title: Create DataFrame from multiple lists?

Body:
I have two lists

list1=['a','b','c']

list2=[1,2]

I want my dataframe output to look like:

col1     col2
a        1
a        2
b        1
b        2
c        1
c        2

How can this be done?

Body:
Use itertools.product:

import itertools

list1 = ['a','b','c']
list2 = [1,2]
df = pd.DataFrame(itertools.product(list1, list2), columns=['col1', 'col2'])
print(df)

Output:

  col1  col2
0    a     1
1    a     2
2    b     1
3    b     2
4    c     1
5    c     2


问:
Applying conditions before executing variable nested loop for permutation
I need to get the permutations in the following way: I have N slots, and this slots can be filled with variables reaching from 1 to D. To get all possible permutations I wrote a loop that gives me every different possibility.  The loops look a little bit "strange" due to it being a nested loop that needs to be variable. This loop would take two days to complete (for my condition with N = 8, and D=25), however I only need the permutations where sum of the variables in the slots are equal to "D".

```<code>import numpy as np
from tqdm import tqdm

N = 4 # actualy 8
D = 16  # actually 25

test = np.ones(shape=N)

for k in range(0,pow(D-1,N)):

    if sum(test) == D:
        print("this is a suiting fit!",test)

    # last one gets always changed
    if test[N-1]+1 < D:
        test[N-1] += 1
    else:
        test[N-1] = 1

        for idx in range(2,len(test)+1):

            if test[len(test) -idx] + 1 < D:
                test[len(test) - idx] += 1
                break
            else:
                test[len(test) - idx] = 1
</code>```

Since the above loop might look a little bit confusing I enrolled it into nested loops

```<code>for i in range(0,D-1):
    for j in range(0,D-1):
        for k in range(0,D-1):
            for l in range(0,D-1):
                if k+1+l+1+j+1+i+1 == D:
                    print("this is a suting fit!",k+1,l+1,j+1,i+1)
</code>```

I cannot get my head around how to make it either faster by simplification or by applying the condition before iterating over the permutations, any help is appreciated

答:
It's possible I don't fully understand the question, but, if I do, this quite different approach solves the N=8, D=25 instance in a few seconds.

```<code>>>> sum(1 for x in gensums(4, 16))
455
</code>```

appears to match what your code returned, and

```<code>>>> sum(1 for x in gensums(8, 25))
346104
</code>```

An example x from the last run:

```<code>[9, 2, 3, 1, 1, 1, 1, 7]
</code>```

This uses recursion to apply constraints during the process of trying to extend a partial solution, so can cut off many fruitless paths early.

Caution:  for efficiency, the lists it yields are most often the same list object, so be sure to copy each result if you want to save results away for later use.

EDIT: replaced with a somewhat faster version, and perhaps a bit clearer.

EDIT: and one more refinement: adding the case for nslots == 1 allows to assert that remaining and nslots are both non-zero at function entry.

```<code>def gensums(N, D):
    def inner(sofar, nslots, remaining):
        assert remaining and nslots
        # If only 1 slot left, it's forced.
        if nslots == 1:
            sofar.append(remaining)
            yield sofar
            sofar.pop()
            return
        # If num slots equal to remaining, they must all be 1.
        if nslots == remaining:
            yield sofar + [1] * remaining
            return
        # What can we add next?
        # What's left over must be enough to put at least 1 into
        # each slot, so must have:
        #     remaining - candidate >= nslots - 1, or
        #     candidate <= remaining - nslots + 1
        sofar.append(None)
        for candidate in range(1, remaining - nslots + 2):
            sofar[-1] = candidate
            yield from inner(sofar, nslots - 1,
                             remaining - candidate)
        sofar.pop()
    return inner([], N, D)
</code>```

Body:
I need to get the permutations in the following way: I have N slots, and this slots can be filled with variables reaching from 1 to D. To get all possible permutations I wrote a loop that gives me every different possibility.  The loops look a little bit "strange" due to it being a nested loop that needs to be variable. This loop would take two days to complete (for my condition with N = 8, and D=25), however I only need the permutations where sum of the variables in the slots are equal to "D".

import numpy as np
from tqdm import tqdm

N = 4 # actualy 8
D = 16  # actually 25

test = np.ones(shape=N)

for k in range(0,pow(D-1,N)):

    if sum(test) == D:
        print("this is a suiting fit!",test)

    # last one gets always changed
    if test[N-1]+1 < D:
        test[N-1] += 1
    else:
        test[N-1] = 1

        for idx in range(2,len(test)+1):

            if test[len(test) -idx] + 1 < D:
                test[len(test) - idx] += 1
                break
            else:
                test[len(test) - idx] = 1

Since the above loop might look a little bit confusing I enrolled it into nested loops

for i in range(0,D-1):
    for j in range(0,D-1):
        for k in range(0,D-1):
            for l in range(0,D-1):
                if k+1+l+1+j+1+i+1 == D:
                    print("this is a suting fit!",k+1,l+1,j+1,i+1)

I cannot get my head around how to make it either faster by simplification or by applying the condition before iterating over the permutations, any help is appreciated

Body:
It's possible I don't fully understand the question, but, if I do, this quite different approach solves the N=8, D=25 instance in a few seconds.

>>> sum(1 for x in gensums(4, 16))
455

appears to match what your code returned, and

>>> sum(1 for x in gensums(8, 25))
346104

An example x from the last run:

[9, 2, 3, 1, 1, 1, 1, 7]

This uses recursion to apply constraints during the process of trying to extend a partial solution, so can cut off many fruitless paths early.

Caution:  for efficiency, the lists it yields are most often the same list object, so be sure to copy each result if you want to save results away for later use.

EDIT: replaced with a somewhat faster version, and perhaps a bit clearer.

EDIT: and one more refinement: adding the case for nslots == 1 allows to assert that remaining and nslots are both non-zero at function entry.

def gensums(N, D):
    def inner(sofar, nslots, remaining):
        assert remaining and nslots
        # If only 1 slot left, it's forced.
        if nslots == 1:
            sofar.append(remaining)
            yield sofar
            sofar.pop()
            return
        # If num slots equal to remaining, they must all be 1.
        if nslots == remaining:
            yield sofar + [1] * remaining
            return
        # What can we add next?
        # What's left over must be enough to put at least 1 into
        # each slot, so must have:
        #     remaining - candidate >= nslots - 1, or
        #     candidate <= remaining - nslots + 1
        sofar.append(None)
        for candidate in range(1, remaining - nslots + 2):
            sofar[-1] = candidate
            yield from inner(sofar, nslots - 1,
                             remaining - candidate)
        sofar.pop()
    return inner([], N, D)


问:
Activate MVC Web site on IIS 7 Windows Server 2008 R2 Enterprise SP2
I have create a new ASP.NET Core 2.1 project empty on Visual Studio 2019

This is generated by a line in the Startup.cs file

```<code>public class Startup
{
    // This method gets called by the runtime. Use this method to add services to the container.
    // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
    public void ConfigureServices(IServiceCollection services)
    {

    }

    // 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.Run(async (context) =>
        {
            await context.Response.WriteAsync("Hello World!");
        });
    }
}
</code>```

The application can serve static files HTML from the wwwroot folder.

```<code><!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title></title>
</head>
<body>
    <p>test</p>
</body>
</html>
</code>```

The project working on localhost

I need published it to a folder on remote server with SO Windows Server 2008 R2 Enterprise SP2.

I had IIS 7 installed on server.

I installed .Net 4.5.2 and asp.net 2.1 core runtime and asp.net core 3.1 runtime on the server 2008 R2 SP2

I copied the folder contiaining my published Web site to \inetpub\wwwroot on the server.

With this post I configured MVC website in IIS.

https://www.codeproject.com/Articles/1168712/How-to-Quickly-Configure-your-MVC-Website-in-IIS

But on the server the return is

When click on wwwroot project folder

What do I do to give the Web site a URL and otherwise make it active as a Web site?

Maybe I have to install more on the server?

update

Installed on the server

it finally worked thanks to everyone for the support and help

答:
You are probably missing https://dotnet.microsoft.com/permalink/dotnetcore-current-windows-runtime-bundle-installer

Read more at https://learn.microsoft.com/en-us/aspnet/core/tutorials/publish-to-iis?view=aspnetcore-3.1&tabs=visual-studio

Body:
I have create a new ASP.NET Core 2.1 project empty on Visual Studio 2019

This is generated by a line in the Startup.cs file

public class Startup
{
    // This method gets called by the runtime. Use this method to add services to the container.
    // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
    public void ConfigureServices(IServiceCollection services)
    {

    }

    // 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.Run(async (context) =>
        {
            await context.Response.WriteAsync("Hello World!");
        });
    }
}

The application can serve static files HTML from the wwwroot folder.

<!DOCTYPE html>

    <meta charset="utf-8" />
    <title></title>

test

The project working on localhost

I need published it to a folder on remote server with SO Windows Server 2008 R2 Enterprise SP2.

I had IIS 7 installed on server.

I installed .Net 4.5.2 and asp.net 2.1 core runtime and asp.net core 3.1 runtime on the server 2008 R2 SP2

I copied the folder contiaining my published Web site to \inetpub\wwwroot on the server.

With this post I configured MVC website in IIS.

https://www.codeproject.com/Articles/1168712/How-to-Quickly-Configure-your-MVC-Website-in-IIS

But on the server the return is

When click on wwwroot project folder

What do I do to give the Web site a URL and otherwise make it active as a Web site?

Maybe I have to install more on the server?

update

Installed on the server

it finally worked thanks to everyone for the support and help


问:
How to change the code to control the names of certain buttons?
There is a code

$("button").click(function() {
    var btn = this;
    if (btn.loaded) {
      $(btn).prev("div").html(btn.originalContent);
      btn.loaded = false;
      $(btn).text('Get Dynamic chart');
    } else {
      btn.originalContent = $(btn).prev("div").html();
      $(btn).prop('disabled', true);
      $.get($(btn).data("url"), function(html) {
        $(btn).prev("div").html(html);
        $(btn).prop('disabled', false).text('Close');
        btn.loaded = true;
      });
     }
  });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="div1">
  <h2>Dynamic chart1</h2>
</div>
<button data-url="https://stackoverflow.getsandbox.com:443/dashboard?a=1">Get Dynamic chart1</button>

<div id="div2">
  <h2>Dynamic chart2</h2>
</div>
<button data-url="https://stackoverflow.getsandbox.com:443/dashboard?a=2">Get Dynamic chart2</button>

<div id="div3">
  <h2>Dynamic chart3</h2>
</div>
<button data-url="https://stackoverflow.getsandbox.com:443/dashboard?a=3">Get Dynamic chart3</button>

<div id="div4">
  <h2>Dynamic chart4</h2>
</div>
<button data-url="https://stackoverflow.getsandbox.com:443/dashboard?a=4">Get Dynamic chart4</button>

<div id="div5">
  <h2>Dynamic chart5</h2>
</div>
<button data-url="https://stackoverflow.getsandbox.com:443/dashboard?a=5">Another button</button></code>```

So, Button 5 has a different name from everyone, but when you click on it, the name of the script changes to "Close", this is normal. But after clicking the close button, the name of the button is assigned a script on the Get Dynamic chart instead of "Another button", that is, the native name does not prevail. How to make sure that the 5th button before pressing and after pressing are not assigned names by the script, or how to assign the 5th button in the script its names for opening, closing and returning to the original name? Thanks

答:
But what's so unclear about it?

First time you click it, this runs:

```<code>   btn.originalContent = $(btn).prev("div").html();
      $(btn).prop('disabled', true);
      $.get($(btn).data("url"), function(html) {
        $(btn).prev("div").html(html);
        $(btn).prop('disabled', false).text('Close');
        btn.loaded = true;
      });
     }
</code>```

So btn.loaded=true, and text is now "Close"

Next time you click, this runs:

```<code>  $(btn).prev("div").html(btn.originalContent);
  btn.loaded = false;
  $(btn).text('Get Dynamic chart');
</code>```

It did exactly what you told it to do.

A better question is... What exactly do you MEAN for it to do?

Body:
There is a code

$("button").click(function() {
    var btn = this;
    if (btn.loaded) {
      $(btn).prev("div").html(btn.originalContent);
      btn.loaded = false;
      $(btn).text('Get Dynamic chart');
    } else {
      btn.originalContent = $(btn).prev("div").html();
      $(btn).prop('disabled', true);
      $.get($(btn).data("url"), function(html) {
        $(btn).prev("div").html(html);
        $(btn).prop('disabled', false).text('Close');
        btn.loaded = true;
      });
     }
  });

Dynamic chart1

<button data-url="https://stackoverflow.getsandbox.com:443/dashboard?a=1">Get Dynamic chart1</button>

Dynamic chart2

<button data-url="https://stackoverflow.getsandbox.com:443/dashboard?a=2">Get Dynamic chart2</button>

Dynamic chart3

<button data-url="https://stackoverflow.getsandbox.com:443/dashboard?a=3">Get Dynamic chart3</button>

Dynamic chart4

<button data-url="https://stackoverflow.getsandbox.com:443/dashboard?a=4">Get Dynamic chart4</button>

Dynamic chart5

<button data-url="https://stackoverflow.getsandbox.com:443/dashboard?a=5">Another button</button>

So, Button 5 has a different name from everyone, but when you click on it, the name of the script changes to "Close", this is normal. But after clicking the close button, the name of the button is assigned a script on the Get Dynamic chart instead of "Another button", that is, the native name does not prevail. How to make sure that the 5th button before pressing and after pressing are not assigned names by the script, or how to assign the 5th button in the script its names for opening, closing and returning to the original name? Thanks

Body:
But what's so unclear about it?

First time you click it, this runs:

   btn.originalContent = $(btn).prev("div").html();
      $(btn).prop('disabled', true);
      $.get($(btn).data("url"), function(html) {
        $(btn).prev("div").html(html);
        $(btn).prop('disabled', false).text('Close');
        btn.loaded = true;
      });
     }

So btn.loaded=true, and text is now "Close"

Next time you click, this runs:

  $(btn).prev("div").html(btn.originalContent);
  btn.loaded = false;
  $(btn).text('Get Dynamic chart');

It did exactly what you told it to do.

A better question is... What exactly do you MEAN for it to do?


问:
Filter Multiple Values using pandas
I am using Python and Pandas. I have a df that works similar to this:

```<code> +--------+--------+-------+
 |  Col1  |  Col2  | Col3 |
 +--------+--------+-------+
 | Team 1 | High   | Pizza |
 | Team 1 | Medium | Sauce |
 | Team 1 | Low    | Crust |
 +--------+--------+-------+
</code>```

I would like to filter the df so that I only see High or Medium from Col2.

This is what I have tried with no luck

```<code> df = df.loc[df['Col2'] == 'High' | (df['Col2'] == 'Medium')]
</code>```

This is the error I am getting

```<code> cannot compare a dtyped [bool] array with a scalar of type [bool]
</code>```

Any ideas how to make this work and what that error means?

答:
This works as well, more pythonic</p>

```<code>country_list = ['brazil','poland','russia','countrydummy','usa']

filtered_df = df[df['Country Name'].isin(country_list)]
print(filtered_df )
</code>```

Title: Filter Multiple Values using pandas

Body:
I am using Python and Pandas. I have a df that works similar to this:

 +--------+--------+-------+
 |  Col1  |  Col2  | Col3 |
 +--------+--------+-------+
 | Team 1 | High   | Pizza |
 | Team 1 | Medium | Sauce |
 | Team 1 | Low    | Crust |
 +--------+--------+-------+

I would like to filter the df so that I only see High or Medium from Col2.

This is what I have tried with no luck

 df = df.loc[df['Col2'] == 'High' | (df['Col2'] == 'Medium')]

This is the error I am getting

 cannot compare a dtyped [bool] array with a scalar of type [bool]

Any ideas how to make this work and what that error means?

Body:
This works as well, more pythonic

country_list = ['brazil','poland','russia','countrydummy','usa']

filtered_df = df[df['Country Name'].isin(country_list)]
print(filtered_df )


问:
Binding dropdown list in a gridview edit item template
i can bind the dropdownlist in the edit item template. The drop down list is having null values.

```<code>protected void grdDevelopment_RowDataBound(object sender, GridViewRowEventArgs e)
{
  DropDownList drpBuildServers = new DropDownList();

  if (grdDevelopment.EditIndex == e.Row.RowIndex)
  {
      drpBuildServers = (DropDownList)e.Row.Cells[0].FindControl("ddlBuildServers");
  }
}
</code>```

also getting an error

Failed to load viewstate. The control tree into which viewstate is being loaded must match the control tree that was used to save viewstate during the previous request. For example, when adding controls dynamically, the controls added during a post-back must match the type and position of the controls added during the initial request.

答:
```<code>protected void grdDevelopment_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        DropDownList drpBuildServers;

        drpBuildServers = e.Row.FindControl("ddlBuildServers") as DropDownList;

        if (drpBuildServers != null)
            // Write your code here
    }
}
</code>```

OwnerDisplayName: Renju

LastEditorDisplayName: ScarletGarden

ContentLicense: CC BY-SA 2.5

Body:
i can bind the dropdownlist in the edit item template. The drop down list is having null values.

protected void grdDevelopment_RowDataBound(object sender, GridViewRowEventArgs e)
{
  DropDownList drpBuildServers = new DropDownList();

  if (grdDevelopment.EditIndex == e.Row.RowIndex)
  {
      drpBuildServers = (DropDownList)e.Row.Cells[0].FindControl("ddlBuildServers");
  }
}

also getting an error

Failed to load viewstate. The control tree into which viewstate is being loaded must match the control tree that was used to save viewstate during the previous request. For example, when adding controls dynamically, the controls added during a post-back must match the type and position of the controls added during the initial request.

OwnerDisplayName: bahith

LastEditorDisplayName: bahith


问:
Does caching the return value of typeof(MyControl) provide any optimization?
I see code similar to the following sprinkled about some native WPF controls:

```<code>static MyControl {
    Type typeFromHandle = typeof(MyControl);

    // Which is used in various places
    SomeProperty.OverrideMetadata(typeFromHandle, ...);
    CommandManager.RegisterClassInputBinding(typeFromHandle, ...);
    EventManager.RegisterClassHandler(typeFromHandle, ...);
}
</code>```

Seems like the following code would have the same performance:

```<code>static MyControl {
    SomeProperty.OverrideMetadata(typeof(MyControl), ...);
    CommandManager.RegisterClassInputBinding(typeof(MyControl), ...);
    EventManager.RegisterClassHandler(typeof(MyControl), ...);
}
</code>```

Does this approach offer any benefit performance wise when JIT-ing the code or during runtime?

答:
Short answer

Yes, it is more optimal, but no, you shouldn't use it, as in almost every case it is a premature optimization.  If anything, use it as a way to maintain readability in code if you use typeof(MyControl) many times.

Long answer

If you look at the IL produced from a typeof(MyControl) statement in C#, you see the following:

```<code>IL_0001: ldtoken [mscorlib]MyControl
IL_0006: call class [mscorlib]System.Type
        [mscorlib]System.Type::GetTypeFromHandle(
            valuetype [mscorlib]System.RuntimeTypeHandle)
</code>```

These instructions do the following:

Loads the RuntimeTypeHandle (the ldtoken IL instruction) onto the stack (the CLR one, not C#/.NET concept of one).

Get the Type from the RuntimeTypeHandle (the call to Type.GetTypeFromHandle).

Compare this to assigning a Type variable type with one stored in an instance:

```<code>IL_0014: ldloc.2
</code>```

Note, the location (1, 2, etc.) will vary depending on other variables, but ultimately, it is a load of a reference type.

Comparing the two, the call to an already-assigned variable is always going to be faster.  The first has to load the type handle and then it has to call a method in order to resolve the handle into a Type; the second method is just a reference to a local variable.

However, like most other posts, this could most definitely be considered a case of premature optimization, so I would suggest not looking to do this if you think that your code is underperforming.

The argument can be made that it is better from a code reuse standpoint, as if you had to change the type, you would change it in less places; you won't be awash in a sea of typeof statements.

Finally, in regards to WPF, this is something that they had to do, given the requirements for performance (as any UI system has); WPF has a tremendous amount of managed objects, many more compared to Windows Forms and has to take into account the performance of those objects so that it can render the UI as quick as possible.

As a result, you would see something like this:

```<code>private static readonly object TrueObject = true;
private static readonly object FalseObject = false;

// Later on.
DoSomething(condition ? TrueObject : FalseObject);

// Where
void DoSomething(object value)
{
    // Compare to true/false objects.
    if (value == TrueObject)
    {
        // True case.
    }
    else if (value == FalseObject)
    {
        // False case.
    }
    else
    {
        // Invalid.
        throw new InvalidOperationException();
    }
}
</code>```

The reason for this is simple; most of WPF exposes properties/methods with objects as parameters instead of strongly-typed values.  When value types are involved, it can involve a tremendous amount of boxing/unboxing.

In order to get around this, they have a single instance which is boxed/unboxed when they know exactly which values are going to be boxed/unboxed; with a bool, it's easy, there is only true and false.

Again, I wouldn't necessarily recommend this approach for almost any system, but for some systems, it makes sense.

In your case, I'd simply assign the type to a variable, only for readability purposes, not for performance.  If you have performance issues, look at the overall process first, isolate through measurements, and then proceed from there.

Body:
I see code similar to the following sprinkled about some native WPF controls:

static MyControl {
    Type typeFromHandle = typeof(MyControl);

    // Which is used in various places
    SomeProperty.OverrideMetadata(typeFromHandle, ...);
    CommandManager.RegisterClassInputBinding(typeFromHandle, ...);
    EventManager.RegisterClassHandler(typeFromHandle, ...);
}

Seems like the following code would have the same performance:

static MyControl {
    SomeProperty.OverrideMetadata(typeof(MyControl), ...);
    CommandManager.RegisterClassInputBinding(typeof(MyControl), ...);
    EventManager.RegisterClassHandler(typeof(MyControl), ...);
}

Does this approach offer any benefit performance wise when JIT-ing the code or during runtime?

Body:
Short answer

Yes, it is more optimal, but no, you shouldn't use it, as in almost every case it is a premature optimization.  If anything, use it as a way to maintain readability in code if you use typeof(MyControl) many times.

Long answer

If you look at the IL produced from a typeof(MyControl) statement in C#, you see the following:

IL_0001: ldtoken [mscorlib]MyControl
IL_0006: call class [mscorlib]System.Type
        [mscorlib]System.Type::GetTypeFromHandle(
            valuetype [mscorlib]System.RuntimeTypeHandle)

These instructions do the following:

Loads the RuntimeTypeHandle (the ldtoken IL instruction) onto the stack (the CLR one, not C#/.NET concept of one).

Get the Type from the RuntimeTypeHandle (the call to Type.GetTypeFromHandle).

Compare this to assigning a Type variable type with one stored in an instance:

IL_0014: ldloc.2

Note, the location (1, 2, etc.) will vary depending on other variables, but ultimately, it is a load of a reference type.

Comparing the two, the call to an already-assigned variable is always going to be faster.  The first has to load the type handle and then it has to call a method in order to resolve the handle into a Type; the second method is just a reference to a local variable.

However, like most other posts, this could most definitely be considered a case of premature optimization, so I would suggest not looking to do this if you think that your code is underperforming.

The argument can be made that it is better from a code reuse standpoint, as if you had to change the type, you would change it in less places; you won't be awash in a sea of typeof statements.

Finally, in regards to WPF, this is something that they had to do, given the requirements for performance (as any UI system has); WPF has a tremendous amount of managed objects, many more compared to Windows Forms and has to take into account the performance of those objects so that it can render the UI as quick as possible.

As a result, you would see something like this:

private static readonly object TrueObject = true;
private static readonly object FalseObject = false;

// Later on.
DoSomething(condition ? TrueObject : FalseObject);

// Where
void DoSomething(object value)
{
    // Compare to true/false objects.
    if (value == TrueObject)
    {
        // True case.
    }
    else if (value == FalseObject)
    {
        // False case.
    }
    else
    {
        // Invalid.
        throw new InvalidOperationException();
    }
}

The reason for this is simple; most of WPF exposes properties/methods with objects as parameters instead of strongly-typed values.  When value types are involved, it can involve a tremendous amount of boxing/unboxing.

In order to get around this, they have a single instance which is boxed/unboxed when they know exactly which values are going to be boxed/unboxed; with a bool, it's easy, there is only true and false.

Again, I wouldn't necessarily recommend this approach for almost any system, but for some systems, it makes sense.

In your case, I'd simply assign the type to a variable, only for readability purposes, not for performance.  If you have performance issues, look at the overall process first, isolate through measurements, and then proceed from there.


问:
Handle URL from onCreateWindow WebView
Can I get URL from calling onCreateWindow on WebView?

```<code>@Override
public boolean onCreateWindow(WebView view, boolean isDialog, boolean isUserGesture,
        Message resultMsg) {

}
</code>```

答:
A version of albeee's solution that doesn't need to start loading the web page:</p>

```<code>@override
public boolean onCreateWindow(WebView view, boolean isDialog, boolean isUserGesture, Message resultMsg) {
    Logger.d(Constants.TAG, "onCreateWindow"+resultMsg);
    WebView targetWebView = new WebView(getActivity()); // pass a context
    targetWebView.setWebViewClient(new WebViewClient(){
        @Override
        public boolean shouldOverrideUrlLoading (WebView view, String url) {                   handleWebViewLinks(url); // you can get your target url here
            return true; // return false if you want the load to continue
        }
    });
    WebView.WebViewTransport transport = (WebView.WebViewTransport) resultMsg.obj;
    transport.setWebView(targetWebView);
    resultMsg.sendToTarget();
    return true;
}
</code>```

Title: Handle URL from onCreateWindow WebView

Body:
Can I get URL from calling onCreateWindow on WebView?

@Override
public boolean onCreateWindow(WebView view, boolean isDialog, boolean isUserGesture,
        Message resultMsg) {

}

Body:
A version of albeee's solution that doesn't need to start loading the web page:

@override
public boolean onCreateWindow(WebView view, boolean isDialog, boolean isUserGesture, Message resultMsg) {
    Logger.d(Constants.TAG, "onCreateWindow"+resultMsg);
    WebView targetWebView = new WebView(getActivity()); // pass a context
    targetWebView.setWebViewClient(new WebViewClient(){
        @Override
        public boolean shouldOverrideUrlLoading (WebView view, String url) {                   handleWebViewLinks(url); // you can get your target url here
            return true; // return false if you want the load to continue
        }
    });
    WebView.WebViewTransport transport = (WebView.WebViewTransport) resultMsg.obj;
    transport.setWebView(targetWebView);
    resultMsg.sendToTarget();
    return true;
}


问:
Return value of one field from Database[ Entity Framework ] [ ASP.NET MVC ]
I'm working on a ASP.NET MVC project with Entity Framework, and I want to return value of one field from an database, and I won't to return full record, just value of one field.

This what I try :

```<code>    public JsonResult DUR_json(string FL)
    {
        var R = from F in DB_Context.Con.FLs where F.CODE_FL == FL select F.DUR_FL.First();

        return Json(new { DUR = R });
    }
</code>```

But this code returns the full record, please any help ?
Thanks in advance.

答:
Just select your field and then return first result:

```<code>var R = (from F in DB_Context.Con.FLs
         where F.CODE_FL == FL
         select F.DUR_FL).First();
</code>```

Consider using FirstOrDefault() instead of First() if there might be no records with given CODE_FL

Body:
I'm working on a ASP.NET MVC project with Entity Framework, and I want to return value of one field from an database, and I won't to return full record, just value of one field.

This what I try :

    public JsonResult DUR_json(string FL)
    {
        var R = from F in DB_Context.Con.FLs where F.CODE_FL == FL select F.DUR_FL.First();

        return Json(new { DUR = R });
    }

But this code returns the full record, please any help ?
Thanks in advance.

Body:
Just select your field and then return first result:

var R = (from F in DB_Context.Con.FLs
         where F.CODE_FL == FL
         select F.DUR_FL).First();

Consider using FirstOrDefault() instead of First() if there might be no records with given CODE_FL


问:
System.EntryPointNotFoundException: 'Unable to find an entry point named '?' in DLL 'mip_dotnet'.' on CreateMipContext in Outlook VSTO add-in?
I'm trying to initialize MIP in Outlook VSTO add-in, it failed with System.EntryPointNotFoundException: 'Unable to find an entry point named '?' in DLL 'mip_dotnet'.' exception on MIP.CreateMipContext method.

```<code>   MipContext mipContext = MIP.CreateMipContext(appInfo,
                             "mip_data",
                             LogLevel.Trace,
                             null,
                             null);
</code>```

I wonder if there is a way to integrate MIP protection API in Outlook VSTO add-in? Thanks!

答:
You need to add a reference to the Microsoft.InformationProtection.dll assembly. Then you must call the MIP.Initialize method which loads the MIP dlls needed for UPE.

```<code>var subDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\\" + (Environment.Is64BitProcess ? "x64SubFolder" : "x86SubFOlder");
  var factory = MIP.Initialize(MipComponent.Policy, subDir);
</code>```

Body:
I'm trying to initialize MIP in Outlook VSTO add-in, it failed with System.EntryPointNotFoundException: 'Unable to find an entry point named '?' in DLL 'mip_dotnet'.' exception on MIP.CreateMipContext method.

   MipContext mipContext = MIP.CreateMipContext(appInfo,
                             "mip_data",
                             LogLevel.Trace,
                             null,
                             null);

I wonder if there is a way to integrate MIP protection API in Outlook VSTO add-in? Thanks!

Body:
You need to add a reference to the Microsoft.InformationProtection.dll assembly. Then you must call the MIP.Initialize method which loads the MIP dlls needed for UPE.

var subDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\\" + (Environment.Is64BitProcess ? "x64SubFolder" : "x86SubFOlder");
  var factory = MIP.Initialize(MipComponent.Policy, subDir);


问:
Filling the missing values in the specified format - Python
I'm given a problem that explicitly asks me not to use numpy or pandas.

Problem:

Given a string with digits and '_'(missing value) symbols you have to replace the '_' symbols as explained

```<code>Ex 1: _, _, _, 24 ==> 24/4, 24/4, 24/4, 24/4 i.e we. have distributed the 24 equally to all 4 places

Ex 2: 40, _, _, _, 60 ==> (60+40)/5,(60+40)/5,(60+40)/5,(60+40)/5,(60+40)/5 ==> 20, 20, 20, 20, 20 i.e. the sum of (60+40) is distributed qually to all 5 places

Ex 3: 80, _, _, _, _  ==> 80/5,80/5,80/5,80/5,80/5 ==> 16, 16, 16, 16, 16 i.e. the 80 is distributed qually to all 5 missing values that are right to it

Ex 4: _, _, 30, _, _, _, 50, _, _
==> we will fill the missing values from left to right
    a. first we will distribute the 30 to left two missing values (10, 10, 10, _, _, _, 50, _, _)
    b. now distribute the sum (10+50) missing values in between (10, 10, 12, 12, 12, 12, 12, _, _)
    c. now we will distribute 12 to right side missing values (10, 10, 12, 12, 12, 12, 4, 4, 4)
</code>```

for a given string with comma separated values, which will have both missing values numbers like ex: "_, _, x, _, _, " you need fill the missing values Q: your program reads a string like ex: ", _, x, _, _, _" and returns the filled sequence Ex:

```<code>Input1: "_,_,_,24"
Output1: 6,6,6,6

Input2: "40,_,_,_,60"
Output2: 20,20,20,20,20

Input3: "80,_,_,_,_"
Output3: 16,16,16,16,16

Input4: "_,_,30,_,_,_,50,_,_"
Output4: 10,10,12,12,12,12,4,4,4
</code>```

I'm trying to split the string in a list using the split function. I'm then trying to check for blanks on the left and the count the number of such blanks and then once I encounter a non-blank, I'm dividing that number by the total count i.e (no.blanks encountered before the number and number itself) and spreading the values and replacing the blanks left the number

Then I'm checking for the blanks in between two number and then applying the same logic, after which doing the same for blanks on the right.

However, the code I shared below is throwing all sorts of errors, and I believe there are gaps in logic I shared above, therefore would appreciate insights on solving this issue

```<code>def blanks(S):

  a= S.split()
  count = 0
  middle_store = 0
  #left
  for i in range(len(a)):
    if(a[i]=='_'):
      count = count+1  #find number of blanks to the left of a number
    else:
      for j in range(0,i+1):
        #if there are n blanks to the left of the number speard the number equal over n+1 spaces
        a[j] = str((int(a[i])/(count+1)))
        middle_store= i
    break

  #blanks in the middle
  denominator =0
  flag = 0
  for k in len(middle_store+1,len(a)):
    if(a[k] !='_'):
      denominator = (k+1-middle_store)
      flag=k
    break

  for p in len(middle_store,flag+1):
    a[p] = str((int(a[p])/denominator))

  #blanks at the right
  for q in len(flag,len(a)):
    a[q] = str((int(a[q])/(len(a)-flag+1)))

S=  "_,_,30,_,_,_,50,_,_"
print(blanks(S))
</code>```

答:
"Check this its work for all the inputs"

def replace(s):

```<code>val=0
lst=s.split(",")

if lst[0].isdigit():
    for i in range(1,len(lst)):
        if lst[i].isdigit():
            value=(int(lst[0])+int(lst[i]))//((i+1))
            for j in range(0,i+1):
                lst[j]=value
            index=i
            break
else:
    for i in range(len(s)):
        if lst[i].isdigit():
            for j in range(i+1):
                lst[j]=(int(lst[i]))//(i+1)
            index=i
            value=int(lst[i])
            break
for i in range(index+1,len(lst)):
    if lst[i].isdigit():
        temp=(value+int(lst[i]))//(i-index+1)
        for j in range(index,i+1):
            lst[j]=temp
        index=i
        value=int(lst[i])

try :
    for i in range(index+1,len(lst)):
        if not(lst[i].isdigit()):
            count=lst.count('_')
            break
    temp1=value//(count+1)
    for i in range(index,len(lst)):
        lst[i]=temp1
except UnboundLocalError as e:
    print (e)
return lst
</code>```

Body:
I'm given a problem that explicitly asks me not to use numpy or pandas.

Problem:

Given a string with digits and '_'(missing value) symbols you have to replace the '_' symbols as explained

Ex 1: _, _, _, 24 ==> 24/4, 24/4, 24/4, 24/4 i.e we. have distributed the 24 equally to all 4 places

Ex 2: 40, _, _, _, 60 ==> (60+40)/5,(60+40)/5,(60+40)/5,(60+40)/5,(60+40)/5 ==> 20, 20, 20, 20, 20 i.e. the sum of (60+40) is distributed qually to all 5 places

Ex 3: 80, _, _, _, _  ==> 80/5,80/5,80/5,80/5,80/5 ==> 16, 16, 16, 16, 16 i.e. the 80 is distributed qually to all 5 missing values that are right to it

Ex 4: _, _, 30, _, _, _, 50, _, _
==> we will fill the missing values from left to right
    a. first we will distribute the 30 to left two missing values (10, 10, 10, _, _, _, 50, _, _)
    b. now distribute the sum (10+50) missing values in between (10, 10, 12, 12, 12, 12, 12, _, _)
    c. now we will distribute 12 to right side missing values (10, 10, 12, 12, 12, 12, 4, 4, 4)

for a given string with comma separated values, which will have both missing values numbers like ex: "_, _, x, _, _, " you need fill the missing values Q: your program reads a string like ex: ", _, x, _, _, _" and returns the filled sequence Ex:

Input1: "_,_,_,24"
Output1: 6,6,6,6

Input2: "40,_,_,_,60"
Output2: 20,20,20,20,20

Input3: "80,_,_,_,_"
Output3: 16,16,16,16,16

Input4: "_,_,30,_,_,_,50,_,_"
Output4: 10,10,12,12,12,12,4,4,4

I'm trying to split the string in a list using the split function. I'm then trying to check for blanks on the left and the count the number of such blanks and then once I encounter a non-blank, I'm dividing that number by the total count i.e (no.blanks encountered before the number and number itself) and spreading the values and replacing the blanks left the number

Then I'm checking for the blanks in between two number and then applying the same logic, after which doing the same for blanks on the right.

However, the code I shared below is throwing all sorts of errors, and I believe there are gaps in logic I shared above, therefore would appreciate insights on solving this issue

def blanks(S):

  a= S.split()
  count = 0
  middle_store = 0
  #left
  for i in range(len(a)):
    if(a[i]=='_'):
      count = count+1  #find number of blanks to the left of a number
    else:
      for j in range(0,i+1):
        #if there are n blanks to the left of the number speard the number equal over n+1 spaces
        a[j] = str((int(a[i])/(count+1)))
        middle_store= i
    break

  #blanks in the middle
  denominator =0
  flag = 0
  for k in len(middle_store+1,len(a)):
    if(a[k] !='_'):
      denominator = (k+1-middle_store)
      flag=k
    break

  for p in len(middle_store,flag+1):
    a[p] = str((int(a[p])/denominator))

  #blanks at the right
  for q in len(flag,len(a)):
    a[q] = str((int(a[q])/(len(a)-flag+1)))

S=  "_,_,30,_,_,_,50,_,_"
print(blanks(S))

Body:
"Check this its work for all the inputs"

def replace(s):

val=0
lst=s.split(",")

if lst[0].isdigit():
    for i in range(1,len(lst)):
        if lst[i].isdigit():
            value=(int(lst[0])+int(lst[i]))//((i+1))
            for j in range(0,i+1):
                lst[j]=value
            index=i
            break
else:
    for i in range(len(s)):
        if lst[i].isdigit():
            for j in range(i+1):
                lst[j]=(int(lst[i]))//(i+1)
            index=i
            value=int(lst[i])
            break
for i in range(index+1,len(lst)):
    if lst[i].isdigit():
        temp=(value+int(lst[i]))//(i-index+1)
        for j in range(index,i+1):
            lst[j]=temp
        index=i
        value=int(lst[i])

try :
    for i in range(index+1,len(lst)):
        if not(lst[i].isdigit()):
            count=lst.count('_')
            break
    temp1=value//(count+1)
    for i in range(index,len(lst)):
        lst[i]=temp1
except UnboundLocalError as e:
    print (e)
return lst


问:
Dojo aspect cancel original method
I am using dojo aspect.before to perform some actions prior to calling my original method. However, I am trying to cancel the original method if some criteria is not met within the aspect.before method, but not able to cancel that event.</p>

```<code>require(["dojo/_base/declare",
"dojo/_base/lang",
"dojo/aspect",
"dojo/dom",
"dojo/on"],
function(declare, lang, aspect, dom, on) {
  aspect.before(target,"onSave", function(event){
     var mycriteria  = //some logic to determine this value;
     if(mycriteria == null || mycriteria == undefined){
         //cancel the "onSave" method.
         // if cancelling this is not possible, can I call "onCancel" method here that'll cancel this
         //event?
     }
  });
}
</code>```

答:
aspect.around is what you're looking for. It allows you to substitute the original method and apply it on your own terms.</p>

```<code>require(["dojo/_base/declare", "dojo/_base/lang", "dojo/aspect", "dojo/dom", "dojo/on"], function(declare, lang, aspect, dom, on) {
    aspect.around(target, "onSave", function(originalOnSave) {
        return function newOnSave() {//this function receives the parameters the onSave normally would.
            var myCriteria = true;
            if (myCriteria) {
                //invoke original
                originalOnSave.apply(this, arguments);
            } else {//do nothing
            }
        }
    });
});
</code>```

Title: Dojo aspect cancel original method

Body:
I am using dojo aspect.before to perform some actions prior to calling my original method. However, I am trying to cancel the original method if some criteria is not met within the aspect.before method, but not able to cancel that event.

require(["dojo/_base/declare",
"dojo/_base/lang",
"dojo/aspect",
"dojo/dom",
"dojo/on"],
function(declare, lang, aspect, dom, on) {
  aspect.before(target,"onSave", function(event){
     var mycriteria  = //some logic to determine this value;
     if(mycriteria == null || mycriteria == undefined){
         //cancel the "onSave" method.
         // if cancelling this is not possible, can I call "onCancel" method here that'll cancel this
         //event?
     }
  });
}

Body:
aspect.around is what you're looking for. It allows you to substitute the original method and apply it on your own terms.

require(["dojo/_base/declare", "dojo/_base/lang", "dojo/aspect", "dojo/dom", "dojo/on"], function(declare, lang, aspect, dom, on) {
    aspect.around(target, "onSave", function(originalOnSave) {
        return function newOnSave() {//this function receives the parameters the onSave normally would.
            var myCriteria = true;
            if (myCriteria) {
                //invoke original
                originalOnSave.apply(this, arguments);
            } else {//do nothing
            }
        }
    });
});


问:
Setting default or a combobox with Xaml (despite Binding)
I want to Bind the selectedItem of an RadCombobox to an Observable Collection in the DataContext. This works perfectly fine.
But now I want to set the default value for the combobox, this also works if I set the Variable in the Data Context. But It would be better in my opinion to set the deault within the Xaml. This should be possible with SelectedIndex="0" unfortunatly ths doesnt work anymore (no default shown) since the binding is active.

Is there an option to set deault value or the combobox while there is a binding for the SelectedItem?

```<code><telerik:RadComboBox x:Name="radComboBox"
                             ItemsSource="{Binding xyList, UpdateSourceTrigger=PropertyChanged}" SelectedIndex="0" SelectedItem="{Binding Selectedxy}"
                             HorizontalAlignment="Left" Margin="0,0,0,0"  VerticalAlignment="Top" Width="250" Height="25" Grid.Row="1">
        </telerik:RadComboBox>
</code>```

.

```<code>public string Selectedxy  {get;set; }

        public void FillxyDropdown()
        {
           xyList = new ObservableCollection<string>();
            foreach (KeyValuePair<string, int> Line in model.ReadxyList())
            {
                xyList.Add(Line.Key);
            }

            //Sets the default value but isnt the desired way.
            Selectedxy = "XY3.31";
        }
</code>```

答:
I agree with The One comment. You definitely should specify the default values in the View Model.

If you still want to do this in the XAML, you can set the binding mode of the SelectedItem property to OneWayToSource. In this case, Selectedxy will be updated when SelectedItem changes, but not the other way around.

<telerik:RadComboBox x:Name="radComboBox"
          ItemsSource="{Binding xyList, UpdateSourceTrigger=PropertyChanged}" SelectedIndex="1"
          SelectedItem="{Binding Selectedxy, Mode=OneWayToSource}" HorizontalAlignment="Left"
          Margin="0,0,0,0"  VerticalAlignment="Top" Width="250" Height="25" Grid.Row="1">
</telerik:RadComboBox>
```

Body:
I want to Bind the selectedItem of an RadCombobox to an Observable Collection in the DataContext. This works perfectly fine.
But now I want to set the default value for the combobox, this also works if I set the Variable in the Data Context. But It would be better in my opinion to set the deault within the Xaml. This should be possible with SelectedIndex="0" unfortunatly ths doesnt work anymore (no default shown) since the binding is active.

Is there an option to set deault value or the combobox while there is a binding for the SelectedItem?

<telerik:RadComboBox x:Name="radComboBox"
                             ItemsSource="{Binding xyList, UpdateSourceTrigger=PropertyChanged}" SelectedIndex="0" SelectedItem="{Binding Selectedxy}"
                             HorizontalAlignment="Left" Margin="0,0,0,0"  VerticalAlignment="Top" Width="250" Height="25" Grid.Row="1">
        </telerik:RadComboBox>

.

public string Selectedxy  {get;set; }

        public void FillxyDropdown()
        {
           xyList = new ObservableCollection<string>();
            foreach (KeyValuePair<string, int> Line in model.ReadxyList())
            {
                xyList.Add(Line.Key);
            }

            //Sets the default value but isnt the desired way.
            Selectedxy = "XY3.31";
        }


问:
Typescript type where an object consists of exactly a single property of a set of possible properties
I'm trying to model a particular pattern with the type system where an object consists of exactly a single property of a set of possible properties.

In other words, the type would be a partial type but with only one property allowed.

interface PossibleProperties {
  cat?: AllPropsOfSameType;
  dog?: AllPropsOfSameType;
  cow?: AllPropsOfSameType;
}

interface ShouldBeExactlyOneOfPossibleProperties {
  [P in keyof PossibleProperties]: AllPropsOfSameType; // Wupz, this allows for 0 or more...
}
```

<p>I've seen solutions for requiring at least one property:</p>

<pre class="lang-js prettyprint-override"><code>type AtLeastOne<T, U = {[K in keyof T]: Pick<T, K> }> = Partial<T> & U[keyof U]
</code>```

But I need something like AtMostOne<T, U = {[K in keyof T]: Pick<T, K> }> or ExactlyOne<T, U = {[K in keyof T]: Pick<T, K> }> which could possibly be the intersection type of AtMostOne and AtLeastOne

Any ideas if this is possible?

答:
The first my thought was to create a union type, like:

type ExactlyOne =
  { cat?: AllPropsOfSameType } |
  { dog?: AllPropsOfSameType } |
  { cow?: AllPropsOfSameType };
```

<p>It's possible using distributive conditional types:</p>

<pre class="lang-js prettyprint-override"><code>type ExactlyOne<T, TKey = keyof T> = TKey extends keyof T ? { [key in TKey]: T[TKey] } : never;
type ShouldBeExactlyOneOfPossibleProperties = ExactlyOne<PossibleProperties>;
</code>```

Playground

But it still allows to assign an object with multiple properties:

// this assignment gives no errors
const animal: ShouldBeExactlyOneOfPossibleProperties = {
  cat: 'a big cat',
  dog: 'a small dog'
};
```

<p>It's because union types in TypeScript are inclusive and you cannot create an exclusive union type at the moment. See this answer.</p>

<p>So we need to forbid additional properties somehow. An option might be to use <code>never</code> type, but unfortunately it's impossible to create an optional property of type <code>never</code> because <code>never | undefined</code> gives <code>undefined</code>. If it's ok to have <code>undefined</code> additional properties you can use the following monstrous type:</p>

<pre class="lang-js prettyprint-override"><code>type ExactlyOne<T, TKey = keyof T> = TKey extends keyof T
  ? { [key in Exclude<keyof T, TKey>]?: never } & { [key in TKey]: T[key] }
  : never;
</code>```

And the resulted type looks like:

({
    dog?: undefined;
    cow?: undefined;
} & {
    cat: string | undefined;
}) | ({
    cat?: undefined;
    cow?: undefined;
} & {
    dog: string | undefined;
}) | ({
    cat?: undefined;
    dog?: undefined;
} & {
    cow: string | undefined;
})
```

<p>It's horrible... but It's close to what is expected.</p>

<p>Playground</p>

<p>A disadvantage of this approach is an undescriptive error message if you try to assign an object with multiple properties, for example this assignment:</p>

<pre class="lang-js prettyprint-override"><code>const animal: ShouldBeExactlyOneOfPossibleProperties = {
  cat: 'a big cat',
  dog: 'a small dog'
};
</code>```

gives the following error:

Type '{ cat: string; dog: string; }' is not assignable to type '({ dog?: undefined; cow?: undefined; } & { cat: string | undefined; }) | ({ cat?: undefined; cow?: undefined; } & { dog: string | undefined; }) | ({ cat?: undefined; dog?: undefined; } & { cow: string | undefined; })'.
  Type '{ cat: string; dog: string; }' is not assignable to type '{ cat?: undefined; dog?: undefined; } & { cow: string | undefined; }'.
    Type '{ cat: string; dog: string; }' is not assignable to type '{ cat?: undefined; dog?: undefined; }'.
      Types of property 'cat' are incompatible.
        Type 'string' is not assignable to type 'undefined'.(2322)
```

<hr>

<p>Another approach: you can emulate an exclusive union type like suggested in this answer. But in this case an extra property is added to the object.</p>

<pre class="lang-js prettyprint-override"><code>type ExactlyOne<T, TKey = keyof T> = TKey extends keyof T
  ? { [key in TKey]: T[TKey] } & { prop: TKey }
  : never;

const animal: ExactlyOne<PossibleProperties> = {
  prop: 'cat',
  cat: 'a big cat'
};
</code>```

Playground

Body:
I'm trying to model a particular pattern with the type system where an object consists of exactly a single property of a set of possible properties.

In other words, the type would be a partial type but with only one property allowed.

interface PossibleProperties {
  cat?: AllPropsOfSameType;
  dog?: AllPropsOfSameType;
  cow?: AllPropsOfSameType;
}

interface ShouldBeExactlyOneOfPossibleProperties {
  [P in keyof PossibleProperties]: AllPropsOfSameType; // Wupz, this allows for 0 or more...
}

I've seen solutions for requiring at least one property:

type AtLeastOne<T, U = {[K in keyof T]: Pick<T, K> }> = Partial<T> & U[keyof U]

But I need something like AtMostOne<T, U = {[K in keyof T]: Pick<T, K> }> or ExactlyOne<T, U = {[K in keyof T]: Pick<T, K> }> which could possibly be the intersection type of AtMostOne and AtLeastOne

Any ideas if this is possible?

Body:
The first my thought was to create a union type, like:

type ExactlyOne =
  { cat?: AllPropsOfSameType } |
  { dog?: AllPropsOfSameType } |
  { cow?: AllPropsOfSameType };

It's possible using distributive conditional types:

type ExactlyOne<T, TKey = keyof T> = TKey extends keyof T ? { [key in TKey]: T[TKey] } : never;
type ShouldBeExactlyOneOfPossibleProperties = ExactlyOne<PossibleProperties>;

Playground

But it still allows to assign an object with multiple properties:

// this assignment gives no errors
const animal: ShouldBeExactlyOneOfPossibleProperties = {
  cat: 'a big cat',
  dog: 'a small dog'
};

It's because union types in TypeScript are inclusive and you cannot create an exclusive union type at the moment. See this answer.

So we need to forbid additional properties somehow. An option might be to use never type, but unfortunately it's impossible to create an optional property of type never because never | undefined gives undefined. If it's ok to have undefined additional properties you can use the following monstrous type:

type ExactlyOne<T, TKey = keyof T> = TKey extends keyof T
  ? { [key in Exclude<keyof T, TKey>]?: never } & { [key in TKey]: T[key] }
  : never;

And the resulted type looks like:

({
    dog?: undefined;
    cow?: undefined;
} & {
    cat: string | undefined;
}) | ({
    cat?: undefined;
    cow?: undefined;
} & {
    dog: string | undefined;
}) | ({
    cat?: undefined;
    dog?: undefined;
} & {
    cow: string | undefined;
})

It's horrible... but It's close to what is expected.

Playground

A disadvantage of this approach is an undescriptive error message if you try to assign an object with multiple properties, for example this assignment:

const animal: ShouldBeExactlyOneOfPossibleProperties = {
  cat: 'a big cat',
  dog: 'a small dog'
};

gives the following error:

Type '{ cat: string; dog: string; }' is not assignable to type '({ dog?: undefined; cow?: undefined; } & { cat: string | undefined; }) | ({ cat?: undefined; cow?: undefined; } & { dog: string | undefined; }) | ({ cat?: undefined; dog?: undefined; } & { cow: string | undefined; })'.
  Type '{ cat: string; dog: string; }' is not assignable to type '{ cat?: undefined; dog?: undefined; } & { cow: string | undefined; }'.
    Type '{ cat: string; dog: string; }' is not assignable to type '{ cat?: undefined; dog?: undefined; }'.
      Types of property 'cat' are incompatible.
        Type 'string' is not assignable to type 'undefined'.(2322)

Another approach: you can emulate an exclusive union type like suggested in this answer. But in this case an extra property is added to the object.

type ExactlyOne<T, TKey = keyof T> = TKey extends keyof T
  ? { [key in TKey]: T[TKey] } & { prop: TKey }
  : never;

const animal: ExactlyOne<PossibleProperties> = {
  prop: 'cat',
  cat: 'a big cat'
};

Playground


问:
Combining Vectors using a Loop
If I have vectors m1, m2, ... m"n" and I want to create a vector that includes all of the values, how would I go about this?

For example:

```<code>m1 = c(0, 2, 4)
m2 = c(1, 4)
m3 = (3)
</code>```

I want a vector "totalmods" which outputs {0, 2, 4, 1, 4, 3}

My attempt where nummod is "n", the vector with the largest number was:

```<code>for(i in 1:nummod){
  totalmods <- c(paste("m",i, sep = ""))
}
</code>```

Thanks for your help!

答:
You can use mget and unlist

```<code>unlist(mget(ls(pattern = "^m\\d+$")), use.names = FALSE)
# [1] 0 2 4 1 4 3
</code>```

We create a list with all objects whose names start with "m" (^m) and end with one or more digit (\\d+$). We use unlist to create a vector.

A user asked for a benchmark in the comments (and I became curious)

```<code>x <- 2:2000
y <- setNames(lapply(x, seq_len),  paste0("m", x))

library(microbenchmark)
microbenchmark(markus = unlist(y, use.names = FALSE),
               tmfmnk = Reduce(c, y),
               akrun = purrr::flatten_dbl(y)
               times = 10L)
#Unit: milliseconds
#   expr       min        lq       mean    median        uq       max neval
# markus   13.7329   13.8566   22.09223   13.9139   14.1638   75.9402    10
# tmfmnk 3427.3571 3614.2938 3761.36990 3806.0890 3928.1482 4004.7853    10
# akrun    42.7355   64.4865   153.8598  148.5418  240.0674  286.8956    10
</code>```

Title: Combining Vectors using a Loop

Body:
If I have vectors m1, m2, ... m"n" and I want to create a vector that includes all of the values, how would I go about this?

For example:

m1 = c(0, 2, 4)
m2 = c(1, 4)
m3 = (3)

I want a vector "totalmods" which outputs {0, 2, 4, 1, 4, 3}

My attempt where nummod is "n", the vector with the largest number was:

for(i in 1:nummod){
  totalmods <- c(paste("m",i, sep = ""))
}

Thanks for your help!

Body:
You can use mget and unlist

unlist(mget(ls(pattern = "^m\\d+$")), use.names = FALSE)
# [1] 0 2 4 1 4 3

We create a list with all objects whose names start with "m" (^m) and end with one or more digit (\\d+$). We use unlist to create a vector.

A user asked for a benchmark in the comments (and I became curious)

x <- 2:2000
y <- setNames(lapply(x, seq_len),  paste0("m", x))

library(microbenchmark)
microbenchmark(markus = unlist(y, use.names = FALSE),
               tmfmnk = Reduce(c, y),
               akrun = purrr::flatten_dbl(y)
               times = 10L)
#Unit: milliseconds
#   expr       min        lq       mean    median        uq       max neval
# markus   13.7329   13.8566   22.09223   13.9139   14.1638   75.9402    10
# tmfmnk 3427.3571 3614.2938 3761.36990 3806.0890 3928.1482 4004.7853    10
# akrun    42.7355   64.4865   153.8598  148.5418  240.0674  286.8956    10


问:
Selenium Chrome Driver : user data directory is already in use
For this same error there are many questions in Stackoverflow. But none of them solved my problem. So I have to post this again.

My Code:

```<code>            ChromeOptions options = new ChromeOptions();
            options.AddArguments("--disable-gpu");
            options.AddArguments("--disable-extensions");
            options.AddArgument(@"user-data-dir=C:\Users\myname\AppData\Roaming\Chrome\Profile 6");
            options.AddArgument("--profile-directory=Profile 6");
            IWebDriver driver = new ChromeDriver(options);
            driver.Navigate().GoToUrl("https://google.com");
</code>```

Initially I was getting an error " Unable to move cache folder, access denied."
then I have added the line options.AddArguments("--disable-gpu"); and the error is gone.

Now my Code is opening the browser with profile : "Profile 6". But after that its throwing the error
Error in the line : IWebDriver driver = new ChromeDriver(options);

"Exception thrown: 'OpenQA.Selenium.WebDriverException' in WebDriver.dll
An unhandled exception of type 'OpenQA.Selenium.WebDriverException' occurred in WebDriver.dll
invalid argument: user data directory is already in use, please specify a unique value for --user-data-dir argument, or don't use --user-data-dir
"

I have already read almost all topics related to this error. Few of them are :

How to open a Chrome Profile through --user-data-dir argument of Selenium

InvalidArgumentException: Message: invalid argument: user data directory is already in use error using --user-data-dir to start Chrome using Selenium

How to initiate a new Chrome session when the default session is already running using ChromeDriver and Chrome through Selenium and Python

I am stuck in this problem for more than a week now. Please help.

EDIT:
To confirm that I am not using the already opened default user profile, I checked Cheome://version to confirm the user data directory path. Its different than the default.

Also I tried to to run the code after closing all the open chrome instances. This Time I have not received the error. The browser opened by the webdriver. But after that nothing happened. The code got time out error after 60 seconds in the line :  IWebDriver driver = new ChromeDriver(options);

答:
Possibly you are specifying the wrong directory. Instead of:

```<code>C:\Users\myname\AppData\Roaming\Chrome\Profile 6
</code>```

You need to pass:

```<code>C:\Users\myname\AppData\Local\Chrome\Profile 6
</code>```

So the effective line of code will be:

```<code>options.AddArgument(@"user-data-dir=C:\Users\myname\AppData\Local\Chrome\Profile 6");
</code>```

Update 1

Additionally, you can remove the argument --profile-directory as in:

```<code>options.AddArgument("--profile-directory=Profile 6");
</code>```

Update 2

If I close all the chrome instances and run the code, I am not getting this error means ChromeDriver is able to open the Chrome browsing instance perfectly. But to analyze why nothing happened can be interpreted from the TRACE level logs.

Ensure that:

JDK is upgraded to  current levels JDK 8u251.

Selenium is upgraded to  current levels Version 3.141.59.

ChromeDriver is updated to  current ChromeDriver v83.0 level.

Chrome is updated to  current Chrome Version 83.0 level. (as per ChromeDriver v83.0 release notes)

If your base Web Client version is too old, then uninstall it and install a recent GA and released version of Web Client.

Clean your Project Workspace through your IDE and Rebuild your project with required dependencies only.

If your base Web Client version is too old, then uninstall it and install a recent GA and released version of Web Client.

Take a System Reboot.

Execute your @Test as non-root user.

Always invoke driver.quit() within tearDown(){} method to close & destroy the WebDriver and Web Client instances gracefully.

Body:
For this same error there are many questions in Stackoverflow. But none of them solved my problem. So I have to post this again.

My Code:

            ChromeOptions options = new ChromeOptions();
            options.AddArguments("--disable-gpu");
            options.AddArguments("--disable-extensions");
            options.AddArgument(@"user-data-dir=C:\Users\myname\AppData\Roaming\Chrome\Profile 6");
            options.AddArgument("--profile-directory=Profile 6");
            IWebDriver driver = new ChromeDriver(options);
            driver.Navigate().GoToUrl("https://google.com");

Initially I was getting an error " Unable to move cache folder, access denied."
then I have added the line options.AddArguments("--disable-gpu"); and the error is gone.

Now my Code is opening the browser with profile : "Profile 6". But after that its throwing the error
Error in the line : IWebDriver driver = new ChromeDriver(options);

"Exception thrown: 'OpenQA.Selenium.WebDriverException' in WebDriver.dll
An unhandled exception of type 'OpenQA.Selenium.WebDriverException' occurred in WebDriver.dll
invalid argument: user data directory is already in use, please specify a unique value for --user-data-dir argument, or don't use --user-data-dir
"

I have already read almost all topics related to this error. Few of them are :

How to open a Chrome Profile through --user-data-dir argument of Selenium

InvalidArgumentException: Message: invalid argument: user data directory is already in use error using --user-data-dir to start Chrome using Selenium

How to initiate a new Chrome session when the default session is already running using ChromeDriver and Chrome through Selenium and Python

I am stuck in this problem for more than a week now. Please help.

EDIT:
To confirm that I am not using the already opened default user profile, I checked Cheome://version to confirm the user data directory path. Its different than the default.

Also I tried to to run the code after closing all the open chrome instances. This Time I have not received the error. The browser opened by the webdriver. But after that nothing happened. The code got time out error after 60 seconds in the line :  IWebDriver driver = new ChromeDriver(options);

Body:
Possibly you are specifying the wrong directory. Instead of:

C:\Users\myname\AppData\Roaming\Chrome\Profile 6

You need to pass:

C:\Users\myname\AppData\Local\Chrome\Profile 6

So the effective line of code will be:

options.AddArgument(@"user-data-dir=C:\Users\myname\AppData\Local\Chrome\Profile 6");

Update 1

Additionally, you can remove the argument --profile-directory as in:

options.AddArgument("--profile-directory=Profile 6");

Update 2

If I close all the chrome instances and run the code, I am not getting this error means ChromeDriver is able to open the Chrome browsing instance perfectly. But to analyze why nothing happened can be interpreted from the TRACE level logs.

Ensure that:

JDK is upgraded to  current levels JDK 8u251.

Selenium is upgraded to  current levels Version 3.141.59.

ChromeDriver is updated to  current ChromeDriver v83.0 level.

Chrome is updated to  current Chrome Version 83.0 level. (as per ChromeDriver v83.0 release notes)

If your base Web Client version is too old, then uninstall it and install a recent GA and released version of Web Client.

Clean your Project Workspace through your IDE and Rebuild your project with required dependencies only.

If your base Web Client version is too old, then uninstall it and install a recent GA and released version of Web Client.

Take a System Reboot.

Execute your @Test as non-root user.

Always invoke driver.quit() within tearDown(){} method to close & destroy the WebDriver and Web Client instances gracefully.


问:
Unable to find testhost.dll. Please publish your test project and retry
I have a simple dotnet core class library with a single XUnit test method:

```<code>TestLib.csproj:
<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <TargetFramework>netstandard2.0</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.NET.Test.SDK" Version="15.9.0" />
    <PackageReference Include="xunit" Version="2.4.1" />
    <PackageReference Include="xunit.runner.console" Version="2.4.1">
      <IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
      <PrivateAssets>all</PrivateAssets>
    </PackageReference>
    <PackageReference Include="xunit.runner.visualstudio" Version="2.4.1">
      <IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
      <PrivateAssets>all</PrivateAssets>
    </PackageReference>
    <PackageReference Include="xunit.runners" Version="2.0.0" />
  </ItemGroup>

</Project>

BasicTest.cs:
using Xunit;

namespace TestLib
{
    public class BasicTest
    {
        [Fact(DisplayName = "Basic unit test")]
        [Trait("Category", "unit")]
        public void TestStringHelper()
        {
            var sut = "sut";
            var verify = "sut";

            Assert.Equal(sut, verify);
        }
    }
}
</code>```

If I enter the project on the CLI and type dotnet build the project builds. If I type dotnet test I get this:

```<code>C:\git\Testing\TestLib> dotnet test
C:\git\Testing\TestLib\TestLib.csproj : warning NU1701: Package 'xunit.runner.visualstudio 2.4.1' was restored using '.NETFramework,Version=v4.6.1' instead of the project target framework '.NETStandard,Version=v2.0'. This package may not be fully compatible with your project.
Build started, please wait...
C:\git\Testing\TestLib\TestLib.csproj : warning NU1701: Package 'xunit.runner.visualstudio 2.4.1' was restored using '.NETFramework,Version=v4.6.1' instead of the project target framework '.NETStandard,Version=v2.0'. This package may not be fully compatible with your project.
Build completed.

Test run for C:\git\Testing\TestLib\bin\Debug\netstandard2.0\TestLib.dll(.NETStandard,Version=v2.0)
Microsoft (R) Test Execution Command Line Tool Version 16.0.0-preview-20181205-02
Copyright (c) Microsoft Corporation.  All rights reserved.

Starting test execution, please wait...
Unable to find C:\git\Testing\TestLib\bin\Debug\netstandard2.0\testhost.dll. Please publish your test project and retry.

Test Run Aborted.
</code>```

What do I need to change to get the test to run?

If it helps, VS Code is not displaying the tests in its test explorer, either.

答:
I found a very interesting compatibility issue with a version. I did upgrade just as a normal practice, my code, and I switched to xUnit.runner.visualstudio 2.4.2. It stopped working for .Net Core 3.1. I had to downgrade to 2.4.1 and it started working again.

Additional information after one of my comments.

The package xunit.runner.visualstudio versions <= 2.4.1 includes a reference to Microsoft.NET.Test.Sdk. Later versions don't, so you need to add the reference to your project.

See https://stackoverflow.com/a/63786758/3248302

Body:
I have a simple dotnet core class library with a single XUnit test method:

TestLib.csproj:
<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <TargetFramework>netstandard2.0</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.NET.Test.SDK" Version="15.9.0" />
    <PackageReference Include="xunit" Version="2.4.1" />
    <PackageReference Include="xunit.runner.console" Version="2.4.1">
      <IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
      <PrivateAssets>all</PrivateAssets>
    </PackageReference>
    <PackageReference Include="xunit.runner.visualstudio" Version="2.4.1">
      <IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
      <PrivateAssets>all</PrivateAssets>
    </PackageReference>
    <PackageReference Include="xunit.runners" Version="2.0.0" />
  </ItemGroup>

</Project>

BasicTest.cs:
using Xunit;

namespace TestLib
{
    public class BasicTest
    {
        [Fact(DisplayName = "Basic unit test")]
        [Trait("Category", "unit")]
        public void TestStringHelper()
        {
            var sut = "sut";
            var verify = "sut";

            Assert.Equal(sut, verify);
        }
    }
}

If I enter the project on the CLI and type dotnet build the project builds. If I type dotnet test I get this:

C:\git\Testing\TestLib> dotnet test
C:\git\Testing\TestLib\TestLib.csproj : warning NU1701: Package 'xunit.runner.visualstudio 2.4.1' was restored using '.NETFramework,Version=v4.6.1' instead of the project target framework '.NETStandard,Version=v2.0'. This package may not be fully compatible with your project.
Build started, please wait...
C:\git\Testing\TestLib\TestLib.csproj : warning NU1701: Package 'xunit.runner.visualstudio 2.4.1' was restored using '.NETFramework,Version=v4.6.1' instead of the project target framework '.NETStandard,Version=v2.0'. This package may not be fully compatible with your project.
Build completed.

Test run for C:\git\Testing\TestLib\bin\Debug\netstandard2.0\TestLib.dll(.NETStandard,Version=v2.0)
Microsoft (R) Test Execution Command Line Tool Version 16.0.0-preview-20181205-02
Copyright (c) Microsoft Corporation.  All rights reserved.

Starting test execution, please wait...
Unable to find C:\git\Testing\TestLib\bin\Debug\netstandard2.0\testhost.dll. Please publish your test project and retry.

Test Run Aborted.

What do I need to change to get the test to run?

If it helps, VS Code is not displaying the tests in its test explorer, either.


问:
Invalid command name in Tcl when using format
I'm running the following commands

```<code>set full_pin_name [format "%s %s" $top_cell $encoded_name]
puts "full_pin_name is $full_pin_name"
</code>```

and I get the following error:

```<code>full_pin_name is invalid command name "A" B
</code>```

when top_cell equals A and encoded_name equals B.

Why is this happening?

答:
May be this code runs in a namespace which has the set command defined in it?
To demonstrate:

```<code>% namespace eval foo {
    proc set args {
      puts hey!
    }
    proc whatever {top_cell encoded_name} {
      set full_pin_name [format "%s %s" $top_cell $encoded_name]
      puts "full_pin_name is $full_pin_name"
    }
  }
% ::foo::whatever A B
hey!
can't read "full_pin_name": no such variable
%
</code>```

Body:
I'm running the following commands

set full_pin_name [format "%s %s" $top_cell $encoded_name]
puts "full_pin_name is $full_pin_name"

and I get the following error:

full_pin_name is invalid command name "A" B

when top_cell equals A and encoded_name equals B.

Why is this happening?

Body:
May be this code runs in a namespace which has the set command defined in it?
To demonstrate:

% namespace eval foo {
    proc set args {
      puts hey!
    }
    proc whatever {top_cell encoded_name} {
      set full_pin_name [format "%s %s" $top_cell $encoded_name]
      puts "full_pin_name is $full_pin_name"
    }
  }
% ::foo::whatever A B
hey!
can't read "full_pin_name": no such variable
%


问:
RxJS many Subjects with few Subscriptions vs Single Subject with many Subscriptions
I'm creating an Angular application which sends and receives data over a websocket connection. I have one service SocketService which opens and keeps the connection, that service is injected into other services.

Each message on the websocket looks like {ctrl: string, payload: any} and a Subject is created for each controller (ctrl) in the SocketService, to which other services can subscribe, so each service subscribes only to the messages intended for it.

With an increasing amout of services and therefor controllers I have an increasing amount of Subjects in the SocketService and now I was wondering if it was more efficent to let each service subscribe to the websocket messages directly and have the service itself check if the message was intended for it or not. But that would mean that each message on the socket triggers lots of subscribers.

```<code>// in the socketservice
private createSocketSubscription(): void {
  // Snipped from the socket service when receiving messages on the socket connection
  this._subscription = this._subject.pipe(map(msg => JSON.parse(msg.data))).subscribe((data) => {
    const ctrl = data[this.CTRL] || 'common';
    this._registry[ctrl].next(data[this.PAYLOAD]);
  }
}

public registerController(ctrl: string, def?: any) {
  if (!(this._registry[ctrl]))
    this._registry[ctrl] = new BehaviorSubject(def?def:{});
  return this._registry[ctrl].asObservable();
}

// in some service
constructor(private socketService: SocketService) {
  this.socketService.registerController('something').subscribe(payload=> {
    // do stuff with the payload
  });
}
</code>```

versus

```<code>// in some service
constructor(private socketService: SocketService) {
  this.socketService.getSubject().subscribe(data => {
    if(data['ctrl'] === 'something') {
      // do stuff with the payload
    }
  });
}
</code>```

Which approach is more efficient or does it even make a difference? I left out stopping and unsubscribing processes, I only wonder if it is better to have few subscriptions to many subjects or many subscriptions to a single subject?

答:
Subscription if should be a final destination, anything else should be a pipe. In angular apps the best way is to avoid subscriptions at all and to use async pipe in templates when you need data from a stream.

In your example

.subscribe(() => {
    .next
  }
```

<p>means that one stream should trigger another stream, the right way to do it is to use <code>mergeMap</code>, <code>switchMap</code> etc, when <code>.next</code> joins the <code>.subscribe</code> stream and handles its emits.</p>

<p>instead of <code>ctrl</code> map you could use <code>filter</code> operator</p>

<pre class="lang-js prettyprint-override"><code>this.socketService.getSubject().pipe(
  filter(data => data['ctrl'] === 'something'),
).subscribe(data => {
  // do stuff with the payload
});
</code>```

The way I would recommend

// in some service
public data$: Observable<any>;

constructor(private socketService: SocketService) {
  this.data$ = this.socketService.getSubject().pipe(
     filter(data => data['ctrl'] === 'something'),
     // map(data => data), // do something
  );
}
```

<p>and in the template</p>

<pre class="lang-html prettyprint-override"><code><ng-container *ngIf="data$ | async as data">
  {{ data | json }}
</ng-container>
</code>```

Body:
I'm creating an Angular application which sends and receives data over a websocket connection. I have one service SocketService which opens and keeps the connection, that service is injected into other services.

Each message on the websocket looks like {ctrl: string, payload: any} and a Subject is created for each controller (ctrl) in the SocketService, to which other services can subscribe, so each service subscribes only to the messages intended for it.

With an increasing amout of services and therefor controllers I have an increasing amount of Subjects in the SocketService and now I was wondering if it was more efficent to let each service subscribe to the websocket messages directly and have the service itself check if the message was intended for it or not. But that would mean that each message on the socket triggers lots of subscribers.

// in the socketservice
private createSocketSubscription(): void {
  // Snipped from the socket service when receiving messages on the socket connection
  this._subscription = this._subject.pipe(map(msg => JSON.parse(msg.data))).subscribe((data) => {
    const ctrl = data[this.CTRL] || 'common';
    this._registry[ctrl].next(data[this.PAYLOAD]);
  }
}

public registerController(ctrl: string, def?: any) {
  if (!(this._registry[ctrl]))
    this._registry[ctrl] = new BehaviorSubject(def?def:{});
  return this._registry[ctrl].asObservable();
}

// in some service
constructor(private socketService: SocketService) {
  this.socketService.registerController('something').subscribe(payload=> {
    // do stuff with the payload
  });
}

versus

// in some service
constructor(private socketService: SocketService) {
  this.socketService.getSubject().subscribe(data => {
    if(data['ctrl'] === 'something') {
      // do stuff with the payload
    }
  });
}

Which approach is more efficient or does it even make a difference? I left out stopping and unsubscribing processes, I only wonder if it is better to have few subscriptions to many subjects or many subscriptions to a single subject?

Body:
Subscription if should be a final destination, anything else should be a pipe. In angular apps the best way is to avoid subscriptions at all and to use async pipe in templates when you need data from a stream.

In your example

.subscribe(() => {
    .next
  }

means that one stream should trigger another stream, the right way to do it is to use mergeMap, switchMap etc, when .next joins the .subscribe stream and handles its emits.

instead of ctrl map you could use filter operator

this.socketService.getSubject().pipe(
  filter(data => data['ctrl'] === 'something'),
).subscribe(data => {
  // do stuff with the payload
});

The way I would recommend

// in some service
public data$: Observable<any>;

constructor(private socketService: SocketService) {
  this.data$ = this.socketService.getSubject().pipe(
     filter(data => data['ctrl'] === 'something'),
     // map(data => data), // do something
  );
}

and in the template

<ng-container *ngIf="data$ | async as data">
  {{ data | json }}
</ng-container>