问:
NumPy get index inside multidimensional array
I have a Python NumPy array like this:

```<code>array([[[  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255]],

       [[  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255]],

       [[  0,   0, 125, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255]],

       [[  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255]]], dtype=uint8)
</code>```

And I'm trying to get the index of 125 inside the array with 2 numbers in it. At first I had only 3 values, instead of 4, and this worked to get the indexed position:

```<code>p = np.unravel_index(tiles[tileindex].argmax(), tiles[tileindex].shape)
</code>```

Can't seem to find what I need to use now instead of argmax();
the value 125, can be 255 as well, so I'd like to make my selection based on the number of non-zero values in the nested arrays instead of the value itself.

So basically, how to find the line with two values, and then get the position of 125 in this example.

Any help much appreciated.

答:
This will return the position of the value of interest, with both its first and second axis' index:

```<code>axis0, axis1 = np.where((a > 0).cumsum(2)[...,-1] > 1)
</code>```

Or similarly:

```<code>axis0, axis1 = np.where((a>0).view('i1').sum(-1) > 1)
</code>```

```<code>print(axis0)
#2
print(axis1)
#0
print(a[axis0, axis1])
# array([[  0,   0, 125, 255]])
</code>```

Body:
I have a Python NumPy array like this:

array([[[  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255]],

       [[  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255]],

       [[  0,   0, 125, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255]],

       [[  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255]]], dtype=uint8)

And I'm trying to get the index of 125 inside the array with 2 numbers in it. At first I had only 3 values, instead of 4, and this worked to get the indexed position:

p = np.unravel_index(tiles[tileindex].argmax(), tiles[tileindex].shape)

Can't seem to find what I need to use now instead of argmax();
the value 125, can be 255 as well, so I'd like to make my selection based on the number of non-zero values in the nested arrays instead of the value itself.

So basically, how to find the line with two values, and then get the position of 125 in this example.

Any help much appreciated.

Body:
This will return the position of the value of interest, with both its first and second axis' index:

axis0, axis1 = np.where((a > 0).cumsum(2)[...,-1] > 1)

Or similarly:

axis0, axis1 = np.where((a>0).view('i1').sum(-1) > 1)

print(axis0)
#2
print(axis1)
#0
print(a[axis0, axis1])
# array([[  0,   0, 125, 255]])


来源: stackexchange

问:
Simple way to play a sound file (.aif)
I'm making an app for Mac OS X using Xcode, and I want it to play a alert sound when something happens.

What is the simplest code for playing a sound in Objective-C/Cocoa? Note that my sound file is an .aif.

Also, where do I put the sound file inside my project?

Thank you.

答:
To play audio on the Mac, you can either use NSSound for basic activities, or the more robust CoreAudio framework for more complicated tasks.

If you were to use NSSound to achieve this goal, your code would look something like this:

```<code>NSString *resourcePath = [[NSBundle mainBundle] pathForResource:@"replace-with-file-name" ofType:@"aif"];
NSSound *sound = [[NSSound alloc] initWithContentsOfFile:resourcePath byReference:YES];
// Do something with sound, like [sound play] and release.
</code>```

OR

```<code>NSSound *sound = [NSSound soundNamed:@"replace-with-file-name-without-the-extension"];
// Do something with sound, like [sound play], but don't release (it's autoreleased).
</code>```

If you were to use the second snippet, you would have to ensure that the sound file's extension is aiff and not just aif, since +soundNamed: looks for very specific file extensions; I don't think aif is on that list.

Using CoreAudio is more complicated, so if you just want to play it and mess around with very simple settings, just use NSSound

ContentLicense: CC BY-SA 3.0

Title: Simple way to play a sound file (.aif)

Body:
To play audio on the Mac, you can either use NSSound for basic activities, or the more robust CoreAudio framework for more complicated tasks.

If you were to use NSSound to achieve this goal, your code would look something like this:

NSString *resourcePath = [[NSBundle mainBundle] pathForResource:@"replace-with-file-name" ofType:@"aif"];
NSSound *sound = [[NSSound alloc] initWithContentsOfFile:resourcePath byReference:YES];
// Do something with sound, like [sound play] and release.

OR

NSSound *sound = [NSSound soundNamed:@"replace-with-file-name-without-the-extension"];
// Do something with sound, like [sound play], but don't release (it's autoreleased).

If you were to use the second snippet, you would have to ensure that the sound file's extension is aiff and not just aif, since +soundNamed: looks for very specific file extensions; I don't think aif is on that list.

Using CoreAudio is more complicated, so if you just want to play it and mess around with very simple settings, just use NSSound


问:
Overload -> arrow operator in shared_ptr<interface> instance with no pure virtual destructor in interface
I'm trying to overload the -> operator to eventually execute something along the lines:

```<code>MyInterface *myInstance = (MyInterface *)(new A());
myInstance->Toggle(); //this works wonderfully

std::shared_ptr<Wrapper<MyInterface>> sharedPtrWrapper = std::make_shared<Wrapper<MyInterface>>(myInstance);

//the next line doesn't compile, I would like to achieve something like this, but even
//sharedPtrWrapper.get()->Toggle();
//would be nice to achieve, is this possible?
sharedPtrWrapper->Toggle();

//this works:
sharedPtrWrapper->operator->()->Toggle();
</code>```

Note: I have no control over MyInterface, cannot implement the pure virtual destructor.

Here is what I tried (the below code runs):

```<code>#import <memory>
#import <iostream>

struct MyInterface {
    virtual bool Toggle() = 0;
};

class A : public MyInterface {
public:
    bool Toggle() {
        stateEnabled = !stateEnabled;
        std::cout<<"current state " << stateEnabled << std::endl;
        return true;
    }
private:
    bool stateEnabled = false;
};

template <typename T>
class Wrapper {
private:
    T *unsafePointer = nullptr;
public:
    Wrapper<T>()
    { }

    T *operator->() const {
        return unsafePointer;
    }
    T *getInner() {
        return unsafePointer;
    }
    Wrapper<T>(T *stuff) {
        unsafePointer = stuff;
    }

    ~Wrapper<T>() {}
};

int main(int argc, const char * argv[]) {
    MyInterface *myInstance = (MyInterface *)(new A());
    myInstance->Toggle();

    Wrapper<MyInterface> wrapperS(myInstance);
    wrapperS->Toggle();

    std::shared_ptr<Wrapper<MyInterface>> sharedPtrWrapper = std::make_shared<Wrapper<MyInterface>>(myInstance);
    sharedPtrWrapper->operator->()->Toggle();
    sharedPtrWrapper.operator->()->operator->()->Toggle();

    sharedPtrWrapper.get()->operator->()->Toggle();

    (*sharedPtrWrapper).operator->()->Toggle();

    return 0;
}
</code>```

Output:

```<code>current state 1
current state 0
current state 1
current state 0
current state 1
current state 0
Program ended with exit code: 0
</code>```

To reiterate:
This code doesn't compile:

```<code>sharedPtrWrapper->Toggle();
</code>```

How to make it compile?

Edit : I'm using a wrapper because I have no control over the MyInterface, I get it from a library, also shared_ptr<MyInterface> mySharedPointer = std::make_shared<MyInterface>(myInstance); doesn't compile, because of the missing pure virtual destructor from the above mentioned interface.

Edit2: Example library usage in pseudocode:

```<code>void firstcallbackFromLib(Framework *framework) {
    MyInterface *myInstance = framework->getInstance();

    {
        Wrapper<MyInterface> wrapperS(myInstance);
        std::shared_ptr<Wrapper<MyInterface>> sharedPtrWrapper = std::make_shared<Wrapper<MyInterface>>(wrapperS);
        //assign sharedPtrWrapper and framework to static instances
    }
}
void myFunction() {
    sharedPtrWrapper->Toggle(); //this doesn't work, this is what i'm trying to achieve
    sharedPtrWrapper->operator->()->Toggle(); //this ugly thing works

}
void lastUninitCallbackFromLibrary() {
    MyInterface *p = sharedPtrWrapper.get()->getInner();
    framework->releaseInterface(p);
    //etc
}
</code>```

答:
I am confused about the question. Why wrapper class that does nothing?

If you want to put a class inside shared pointer yet do something uncommon at destruction: like, calling dll's function that performs the destruction, do some preprocessing, perform file closure instead of delete, or do nothing at all if that's what you want. Then you can simply specify it at shared pointer instantiation:
https://en.cppreference.com/w/cpp/memory/shared_ptr/shared_ptr - see construction option 5.

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to overload the -> operator to eventually execute something along the lines:

MyInterface *myInstance = (MyInterface *)(new A());
myInstance->Toggle(); //this works wonderfully

std::shared_ptr<Wrapper<MyInterface>> sharedPtrWrapper = std::make_shared<Wrapper<MyInterface>>(myInstance);

//the next line doesn't compile, I would like to achieve something like this, but even
//sharedPtrWrapper.get()->Toggle();
//would be nice to achieve, is this possible?
sharedPtrWrapper->Toggle();

//this works:
sharedPtrWrapper->operator->()->Toggle();

Note: I have no control over MyInterface, cannot implement the pure virtual destructor.

Here is what I tried (the below code runs):

#import <memory>
#import <iostream>

struct MyInterface {
    virtual bool Toggle() = 0;
};

class A : public MyInterface {
public:
    bool Toggle() {
        stateEnabled = !stateEnabled;
        std::cout<<"current state " << stateEnabled << std::endl;
        return true;
    }
private:
    bool stateEnabled = false;
};

template <typename T>
class Wrapper {
private:
    T *unsafePointer = nullptr;
public:
    Wrapper<T>()
    { }

    T *operator->() const {
        return unsafePointer;
    }
    T *getInner() {
        return unsafePointer;
    }
    Wrapper<T>(T *stuff) {
        unsafePointer = stuff;
    }

    ~Wrapper<T>() {}
};

int main(int argc, const char * argv[]) {
    MyInterface *myInstance = (MyInterface *)(new A());
    myInstance->Toggle();

    Wrapper<MyInterface> wrapperS(myInstance);
    wrapperS->Toggle();

    std::shared_ptr<Wrapper<MyInterface>> sharedPtrWrapper = std::make_shared<Wrapper<MyInterface>>(myInstance);
    sharedPtrWrapper->operator->()->Toggle();
    sharedPtrWrapper.operator->()->operator->()->Toggle();

    sharedPtrWrapper.get()->operator->()->Toggle();

    (*sharedPtrWrapper).operator->()->Toggle();

    return 0;
}

Output:

current state 1
current state 0
current state 1
current state 0
current state 1
current state 0
Program ended with exit code: 0

To reiterate:
This code doesn't compile:

sharedPtrWrapper->Toggle();

How to make it compile?

Edit : I'm using a wrapper because I have no control over the MyInterface, I get it from a library, also shared_ptr<MyInterface> mySharedPointer = std::make_shared<MyInterface>(myInstance); doesn't compile, because of the missing pure virtual destructor from the above mentioned interface.

Edit2: Example library usage in pseudocode:

void firstcallbackFromLib(Framework *framework) {
    MyInterface *myInstance = framework->getInstance();

    {
        Wrapper<MyInterface> wrapperS(myInstance);
        std::shared_ptr<Wrapper<MyInterface>> sharedPtrWrapper = std::make_shared<Wrapper<MyInterface>>(wrapperS);
        //assign sharedPtrWrapper and framework to static instances
    }
}
void myFunction() {
    sharedPtrWrapper->Toggle(); //this doesn't work, this is what i'm trying to achieve
    sharedPtrWrapper->operator->()->Toggle(); //this ugly thing works

}
void lastUninitCallbackFromLibrary() {
    MyInterface *p = sharedPtrWrapper.get()->getInner();
    framework->releaseInterface(p);
    //etc
}


问:
How to update multiple rows using more than one CASE statement in SQL Server?
How can I use more than one CASE to update my rows in my table? I've been trying to write the script in different ways, but I'm sure the syntax is wrong. Any idea where the error is?

```<code>UPDATE NameToSplit
SET Aliases = CASE LEN(Alias)
    WHEN CHARINDEX('.', Alias) + 4 THEN Alias
    ELSE STUFF(Alias, CHARINDEX('.', Alias) + 5, 0, '-')END;
              CASE LEN(Alias)
    WHEN CHARINDEX('.', Alias) + 5 THEN Alias
    ELSE STUFF(Alias, CHARINDEX('.', Alias) + 6, 0, '-')END;
              CASE LEN(Alias)
    WHEN CHARINDEX('.', Alias) + 6 THEN Alias
    ELSE STUFF(Alias, CHARINDEX('.', Alias) + 7, 0, '-')END;
              CASE LEN(Alias)
    WHEN CHARINDEX('.', Alias) + 7 THEN Alias
    ELSE STUFF(Alias, CHARINDEX('.', Alias) + 8, 0, '-')END;
             CASE LEN(Alias)
    WHEN CHARINDEX('.', Alias) + 8 THEN Alias
    ELSE STUFF(Alias, CHARINDEX('.', Alias) + 9, 0, '-')END;
             CASE LEN(Alias)
    WHEN CHARINDEX('.', Alias) + 9 THEN Alias
    ELSE STUFF(Alias, CHARINDEX('.', Alias) + 10, 0, '-')END;
</code>```

The results must be like:

```<code>        Names                              Alias                  Aliases
    -------------------------------------------------------------------------
    idealink.core.usergroup            core.usergroup         core.user-group
    idealink.core.userloginhistory     core.userloginhistory  core.user-loginhistory
   idealink.core.challengecategories   core.challengecategories core.challenge-categories
   idealink.core.activitydetails       core.activitydetails    core.activity-details
</code>```

The length of the words after (core.) are different that's why I needed to create different cases to get all of them.

答:
Per the docs, you have your ELSE in the wrong spot. The syntax would be like this:

```<code>CASE ProductLine
  WHEN 'R' THEN 'Road'
  WHEN 'M' THEN 'Mountain'
  WHEN 'T' THEN 'Touring'
  WHEN 'S' THEN 'Other sale items'
  ELSE 'Not for sale'
END,
</code>```

It ends up acting more like a switch statement where the subsequent when statements will only make an assertion if the previous statements have asserted false.

Body:
How can I use more than one CASE to update my rows in my table? I've been trying to write the script in different ways, but I'm sure the syntax is wrong. Any idea where the error is?

UPDATE NameToSplit
SET Aliases = CASE LEN(Alias)
    WHEN CHARINDEX('.', Alias) + 4 THEN Alias
    ELSE STUFF(Alias, CHARINDEX('.', Alias) + 5, 0, '-')END;
              CASE LEN(Alias)
    WHEN CHARINDEX('.', Alias) + 5 THEN Alias
    ELSE STUFF(Alias, CHARINDEX('.', Alias) + 6, 0, '-')END;
              CASE LEN(Alias)
    WHEN CHARINDEX('.', Alias) + 6 THEN Alias
    ELSE STUFF(Alias, CHARINDEX('.', Alias) + 7, 0, '-')END;
              CASE LEN(Alias)
    WHEN CHARINDEX('.', Alias) + 7 THEN Alias
    ELSE STUFF(Alias, CHARINDEX('.', Alias) + 8, 0, '-')END;
             CASE LEN(Alias)
    WHEN CHARINDEX('.', Alias) + 8 THEN Alias
    ELSE STUFF(Alias, CHARINDEX('.', Alias) + 9, 0, '-')END;
             CASE LEN(Alias)
    WHEN CHARINDEX('.', Alias) + 9 THEN Alias
    ELSE STUFF(Alias, CHARINDEX('.', Alias) + 10, 0, '-')END;

The results must be like:

        Names                              Alias                  Aliases
    -------------------------------------------------------------------------
    idealink.core.usergroup            core.usergroup         core.user-group
    idealink.core.userloginhistory     core.userloginhistory  core.user-loginhistory
   idealink.core.challengecategories   core.challengecategories core.challenge-categories
   idealink.core.activitydetails       core.activitydetails    core.activity-details

The length of the words after (core.) are different that's why I needed to create different cases to get all of them.

Body:
Per the docs, you have your ELSE in the wrong spot. The syntax would be like this:

CASE ProductLine
  WHEN 'R' THEN 'Road'
  WHEN 'M' THEN 'Mountain'
  WHEN 'T' THEN 'Touring'
  WHEN 'S' THEN 'Other sale items'
  ELSE 'Not for sale'
END,

It ends up acting more like a switch statement where the subsequent when statements will only make an assertion if the previous statements have asserted false.


问:
Unable to start minikube with Hyper-V on windows 10
When I run this command:

minikube start --vm-driver=hyperv

minikube cannot start and displays the following error:

minikube v1.7.2 on Microsoft Windows 10 Enterprise

Using the hyperv driver based on user configuration

! 'hyperv' driver reported an issue: C:\WINDOWS\System32\WindowsPowerShell\v1.0\powershell.exe Get-WindowsOptionalFeature -FeatureName Microsoft-Hyper-V-All -Online failed:

Suggestion: Start PowerShell as Administrator, and run: 'Enable-WindowsOptionalFeature -Online -FeatureName Microsoft-Hyper-V -All'

X hyperv does not appear to be installed

so I followed the message displayed and I launched the command:

Get-WindowsOptionalFeature -FeatureName Microsoft-Hyper-V-All -Online

and it shows me the following result:

FeatureName      : Microsoft-Hyper-V-All
  DisplayName      : Hyper-V
  Description      : Provides management services and tools for creating and running virtual machines and their resources
                     virtuels et de leurs ressources.
  RestartRequired  : Possible
  State            : Enabled
  CustomProperties :

Also, I have verified that Hyper-v is installed correctly.
I have minikube 1.7.2 installed.
Any idea how to solve this issues ?

Thanks for your help.

答:
try

minikube start --vm-driver=hyperv --force


问:
Columns containing circles overlap vertically in Bootrap 4
I'm trying to achieve the look displayed in the image below with 'Bootstrap 4'. What I achieved is partly what I want, because there is too much vertical distance between the dots.

I first tried nesting the cols and then I used negative 'margins', but it didn't help move the circles vertically closer to each other. Is it even possible to make the 'cols' "overlap", or do I have to find another way to achieve the Look I want?

.block {
  text-align: center;
  vertical-align: middle;
}
.circle {
  background-color: darkred;
  color: white;
  border-radius: 200px;
  height: 110px;
  width: 110px;
  display: table;
  /* margin-bottom: -50px; */

}
.circle p {
  vertical-align: middle;
  display: table-cell;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!--Circles-->
  <div class="row no-gutters justify-content-center">
    <div class="col-lg-3 ">
      <div class="col-lg-2 block">
        <div class="circle   ">
          <p>Circle 1</p>
        </div>
      </div>
      <div class="col-lg-1 block offset-5">
        <div class="circle  ">
          <p>Circle 2</p>
        </div>
      </div>
      <div class="col-lg-1 block ">
        <div class="circle  ">
          <p>Circle 3</p>
        </div>
      </div>
      <div class="col-lg-1 block  offset-5 ">
        <div class="circle  ">
          <p>Circle 4</p>
        </div>
      </div>
      <div class="col-lg-1 block ">
        <div class="circle  ">
          <p>Circle 5</p>
        </div>
      </div>
<!-- Text-->
    </div>
    <div class="col-lg-7 ">
      <p>
        Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et
        dolore magna aliquyam erat, sed diam voluptua.
      </p>
    </div>
  </div></code>```

答:
```<code>
<!DOCTYPE html>
<html lang="en">
<head>
     <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">

</head>
<style>
    .block {
    text-align: center;
    vertical-align: middle;
}
.circle {
    background-color: darkred;
    color: white;
    border-radius: 200px;
    height: 110px;
    width: 110px;
    display: table;
    margin-bottom:1vw;

}
.circle p {
    vertical-align: middle;
    display: table-cell;

}
    </style>
<body>

<!--Circles-->
    <div class="row no-gutters justify-content-center">
      <div class="col-lg-1 ">
        <div class="col-lg-2 block">
          <div class="circle">
            <p>Circle 1</p>
          </div>
        </div>

        <div class="col-lg-1 block ">
          <div class="circle  ">
            <p>Circle 3</p>
          </div>
        </div>

        <div class="col-lg-1 block ">
          <div class="circle  ">
            <p>Circle 5</p>
          </div>
        </div>
<!-- Text-->
      </div>
      <div style="margin-top: 4vw; margin-left: -2 vw;"class="col-lg-1 ">
       <div class="col-lg-1 block ">
          <div class="circle  ">
            <p>Circle 2</p>
          </div>
        </div>
 <div class="col-lg-1 block   ">
          <div class="circle  ">
            <p>Circle 4</p>
          </div>
        </div>
        </div>
      <div  class="col-lg-3 ">
        <p>
          Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et
          dolore magna aliquyam erat, sed diam voluptua.
        </p>
      </div>
    </div>
</body>
</html>
</code>```

Body:
I'm trying to achieve the look displayed in the image below with 'Bootstrap 4'. What I achieved is partly what I want, because there is too much vertical distance between the dots.

I first tried nesting the cols and then I used negative 'margins', but it didn't help move the circles vertically closer to each other. Is it even possible to make the 'cols' "overlap", or do I have to find another way to achieve the Look I want?

.block {
  text-align: center;
  vertical-align: middle;
}
.circle {
  background-color: darkred;
  color: white;
  border-radius: 200px;
  height: 110px;
  width: 110px;
  display: table;
  /* margin-bottom: -50px; */

}
.circle p {
  vertical-align: middle;
  display: table-cell;
}

Circle 1

Circle 2

Circle 3

Circle 4

Circle 5

        Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et
        dolore magna aliquyam erat, sed diam voluptua.


问:
Reshape panda dataframe in a specific way
I'm new in Python and I want to reshape the data structure for further analysis. I want to reshape the table so that I can only have one row for each ID. I read that some libraries can do that but I don't know how.

The code for the example attached looks like:

```<code>import pandas as pd

data = {'ID': [123, 123], 'Method': ['angular', 'angular'], 'Colour': ['red', 'blue'] }

df = pd.DataFrame (data, columns = ['ID','Method','Colour'])
df
</code>```

every help will be really appreciated

Thanks in advance

Reshape_data

答:
unstack is your friend for this kind of reshaping. Possible code could be:

```<code>resul = df.reset_index().set_index(['ID', 'Method', 'index']
                                   ).unstack().reset_index()

# clean up the column names
resul.columns = [i if j == '' else i + '_' + str(j)
                 for i, j in resul.columns.tolist()]
</code>```

It gives as expected:

```<code>    ID   Method Colour_0 Colour_1
0  123  angular      red     blue
</code>```

Body:
I'm new in Python and I want to reshape the data structure for further analysis. I want to reshape the table so that I can only have one row for each ID. I read that some libraries can do that but I don't know how.

The code for the example attached looks like:

import pandas as pd

data = {'ID': [123, 123], 'Method': ['angular', 'angular'], 'Colour': ['red', 'blue'] }

df = pd.DataFrame (data, columns = ['ID','Method','Colour'])
df

every help will be really appreciated

Thanks in advance

Reshape_data

Body:
unstack is your friend for this kind of reshaping. Possible code could be:

resul = df.reset_index().set_index(['ID', 'Method', 'index']
                                   ).unstack().reset_index()

# clean up the column names
resul.columns = [i if j == '' else i + '_' + str(j)
                 for i, j in resul.columns.tolist()]

It gives as expected:

    ID   Method Colour_0 Colour_1
0  123  angular      red     blue


问:
Java Library Path in Eclipse - Add dll library to multiple jars at once?
I have used the accepted answer provided to the question "How to set the java.library.path from Eclipse?" for setting the library path for a specific jar.

In my case, I have about 10 third party jars and each jar depends on the same set of dlls, but I need to do this process for each jar. I can do this manually, but is there any way to do this for more than one jar at a time?

答:
In your case, manually editing the project's .classpath file might gain you a bit of efficiency. When I set the location of a JAR's native library, the following entry is added to my .classpath file:

```<code><classpathentry exported="true" kind="lib" path="path/to/library.jar" sourcepath="/path/to/src">
    <attributes>
        <attribute name="org.eclipse.jdt.launching.CLASSPATH_ATTR_LIBRARY_PATH_ENTRY" value="path/to/native/library.dll"/>
    </attributes>
</classpathentry>
</code>```

You might manually set up the first JAR (via the Eclipse UI), close Eclipse and copy/paste the generated classpath entries in .classpath with the appropriate modifications, and then restart Eclipse.

ContentLicense: CC BY-SA 2.5

Body:
In your case, manually editing the project's .classpath file might gain you a bit of efficiency. When I set the location of a JAR's native library, the following entry is added to my .classpath file:

<classpathentry exported="true" kind="lib" path="path/to/library.jar" sourcepath="/path/to/src">
    <attributes>
        <attribute name="org.eclipse.jdt.launching.CLASSPATH_ATTR_LIBRARY_PATH_ENTRY" value="path/to/native/library.dll"/>
    </attributes>
</classpathentry>

You might manually set up the first JAR (via the Eclipse UI), close Eclipse and copy/paste the generated classpath entries in .classpath with the appropriate modifications, and then restart Eclipse.


问:
How to Set environment $PATH for flutter in Ubuntu 19.10?
I looked for documentations  , too looked for update your PATH

The file that I used in step 4(update your path) /home/paulo/.bashrc
but not working for me, then when reboot my system, open my terminal and type flutter, return "flutter: command not found".

How could I get that after start my system the command flutter simply work?

English is not my first language, so tell me if there was any misundestanding.

答:
Please try these steps :

```<code>cd $HOME

gedit .bashrc
</code>```

the bashrc will be opened, then add the sdk path to file :

```<code>export PATH=~/your_path_to_your_flutter_sdk/flutter/bin:$PATH

source $HOME/.bashrc
</code>```

Body:
Please try these steps :

cd $HOME

gedit .bashrc

the bashrc will be opened, then add the sdk path to file :

export PATH=~/your_path_to_your_flutter_sdk/flutter/bin:$PATH

source $HOME/.bashrc


问:
Library management system - How to store both tamil and english books details in the same table in phpmyadmin?
I want to store a Tamil and English books details in the library management system database table, Is this possible to do, can you provide me some idea to store both the languages.

while I am trying to store the Tamil language in the DB table, the English fonts have changed completely. I don't know how to store both fonts.

I have downloaded Tamil font Bamini, and I keep the Bamini.ttf into the fonts folder, then I call the src using CSS code.

This is my CSS code:

```<code>     @fontface{
      font-family : Bamini;
src: url(fonts/Bamini.ttf);
}

td{
   font-family: Bamini;
 }
</code>```

This is working fine but if I am trying to add an English font(English does not work). It shows like... ????????

答:
You need to only use the custom font for the relevant rows.

Something like this:

```<code><td class="lang-{{ $book->language }}">
</code>```

and then:

```<code>td.lang-tamil { font-family: Bamini; }
</code>```

Body:
I want to store a Tamil and English books details in the library management system database table, Is this possible to do, can you provide me some idea to store both the languages.

while I am trying to store the Tamil language in the DB table, the English fonts have changed completely. I don't know how to store both fonts.

I have downloaded Tamil font Bamini, and I keep the Bamini.ttf into the fonts folder, then I call the src using CSS code.

This is my CSS code:

     @fontface{
      font-family : Bamini;
src: url(fonts/Bamini.ttf);
}

td{
   font-family: Bamini;
 }

This is working fine but if I am trying to add an English font(English does not work). It shows like... ????????

Body:
You need to only use the custom font for the relevant rows.

Something like this:

<td class="lang-{{ $book->language }}">

and then:

td.lang-tamil { font-family: Bamini; }


问:
use a C++ class with Rcpp to modify it from C or R
I'm starting to play with rcpp and I'd like to make an object in which I can modify the variables from R or rcpp.
It seems that making a class is somehow a good solution, as I can modify the fields using the '$' from R, or directly using Rcpp functions. My problem is that when I try to modify a variable of my class from rcpp with a class method, R simply crashes...

below is a small example. The class contains some variables of different types, plus a constructor and two functions, one to print values (to test if changes are trully done when I do something), and one to change the variables of the class.

```<code>library(Rcpp)
library(RcppArmadillo)

# ODEs can also be described using Rcpp
Rcpp::sourceCpp(code = '

#include <Rcpp.h>
//#include <RcppArmadillo.h>
using namespace Rcpp;

// [[Rcpp::export]]
class parameters{
public:
  NumericMatrix mat;
  double val;
  int n;
  NumericVector dB;

  parameters(double x):
    val(x) {}

  NumericVector changes(){
    dB[0] = val;
    dB[1] = 12;
    //dB[1] = mean(mat(1,_));
  }

  void print(){
    Rcout << "val:"  << std::endl << val << std::endl;
    Rcout << "mat:"  << std::endl << mat << std::endl;
  }
};

RCPP_MODULE(ParamModule){
using namespace Rcpp;
  class_<parameters>("parameters")

  .constructor<double>("constructor")

  .method("changes", &parameters::changes)
  .method("print", &parameters::print)

  .field("val", &parameters::val)
  .field("mat", &parameters::mat)
  .field("n", &parameters::n)
  .field("dB", &parameters::dB)
  ;
}

// [[Rcpp::export]]
NumericMatrix addVal(NumericMatrix mat, double val, int n){
  int i = 0;
  for (i=0; i<n; i++){
    mat(i, 1) = mat(i,1) + val;
  }

  return mat;
}

')
</code>```

and here is the code that I use to test it:

```<code>p = new(parameters,5)
str(p) # constructor initialise the field val, ok
p$mat = matrix(5, nrow = 5, ncol = 5)
p$print()  # field mat initialised, ok
p$mat = matrix(0.1, nrow = 5, ncol = 5)
p$print()  # field mat changed, ok
addVal(p$mat, 2, 5)
p$print() # sounds like p is a pointer, ok
p$changes() #...
</code>```

This last line is where the problem occurs (no error message, as R simply crashes).

When I compile the class I have this warning:

```<code>Warning message:
No function found for Rcpp::export attribute at file215bf0ef501.cpp:8
</code>```

Also, I saw here that I might need to use these two lines:

```<code>ParamModule = Module("ParamModule")
parameters = ParamModule$parameters
</code>```

but I obtain an error message when I run the last one:

```<code>Error in Module(module, mustStart = TRUE) :
  Failed to initialize module pointer: Error in FUN(X[[i]], ...): no such symbol _rcpp_module_boot_ParamModule in package .GlobalEnv
</code>```

(ParamModule is present as an environment in the global environment).

So, my questions are:

1) Why the function p$changes() is not working

2) Do I need to load paramModule? It doesn't seem to change anything...

Thanks!

答:
There is support for exposing C++ classes via Rcpp Modules, which you found.

Also in the package, less well-known, but added by John Chambers himself is Rcpp Classes, an extension to Rcpp Modules which seems to be exactly what you are asking for.

Have at the example in the complete example package that ships with Rcpp as a full directory and test.  There is also documentation in the package.

Body:
I'm starting to play with rcpp and I'd like to make an object in which I can modify the variables from R or rcpp.
It seems that making a class is somehow a good solution, as I can modify the fields using the '$' from R, or directly using Rcpp functions. My problem is that when I try to modify a variable of my class from rcpp with a class method, R simply crashes...

below is a small example. The class contains some variables of different types, plus a constructor and two functions, one to print values (to test if changes are trully done when I do something), and one to change the variables of the class.

library(Rcpp)
library(RcppArmadillo)

# ODEs can also be described using Rcpp
Rcpp::sourceCpp(code = '

#include <Rcpp.h>
//#include <RcppArmadillo.h>
using namespace Rcpp;

// [[Rcpp::export]]
class parameters{
public:
  NumericMatrix mat;
  double val;
  int n;
  NumericVector dB;

  parameters(double x):
    val(x) {}

  NumericVector changes(){
    dB[0] = val;
    dB[1] = 12;
    //dB[1] = mean(mat(1,_));
  }

  void print(){
    Rcout << "val:"  << std::endl << val << std::endl;
    Rcout << "mat:"  << std::endl << mat << std::endl;
  }
};

RCPP_MODULE(ParamModule){
using namespace Rcpp;
  class_<parameters>("parameters")

  .constructor<double>("constructor")

  .method("changes", &parameters::changes)
  .method("print", &parameters::print)

  .field("val", &parameters::val)
  .field("mat", &parameters::mat)
  .field("n", &parameters::n)
  .field("dB", &parameters::dB)
  ;
}

// [[Rcpp::export]]
NumericMatrix addVal(NumericMatrix mat, double val, int n){
  int i = 0;
  for (i=0; i<n; i++){
    mat(i, 1) = mat(i,1) + val;
  }

  return mat;
}

')

and here is the code that I use to test it:

p = new(parameters,5)
str(p) # constructor initialise the field val, ok
p$mat = matrix(5, nrow = 5, ncol = 5)
p$print()  # field mat initialised, ok
p$mat = matrix(0.1, nrow = 5, ncol = 5)
p$print()  # field mat changed, ok
addVal(p$mat, 2, 5)
p$print() # sounds like p is a pointer, ok
p$changes() #...

This last line is where the problem occurs (no error message, as R simply crashes).

When I compile the class I have this warning:

Warning message:
No function found for Rcpp::export attribute at file215bf0ef501.cpp:8

Also, I saw here that I might need to use these two lines:

ParamModule = Module("ParamModule")
parameters = ParamModule$parameters

but I obtain an error message when I run the last one:

Error in Module(module, mustStart = TRUE) :
  Failed to initialize module pointer: Error in FUN(X[[i]], ...): no such symbol _rcpp_module_boot_ParamModule in package .GlobalEnv

(ParamModule is present as an environment in the global environment).

So, my questions are:

1) Why the function p$changes() is not working

2) Do I need to load paramModule? It doesn't seem to change anything...

Thanks!


问:
Is there a way to make the compiler throw an error whenever I put a string instead of a nlohmann::json object?
I have this situation where my method needs a nlohmann::json object as the argument.

```<code>class MyClass {
  public:
    MyClass();
    ~MyClass();

    bool parse(const nlohmann::json& configuration);
};
</code>```

My current approach to give the JSON, which is fine, is the next one:

```<code>std::string filePath = "../folder/folder/file.json"
std::ifstream file(filePath);
nlohmann::json configJSON = nlohmann::json::parse(file);

MyClass object;
object.parse(configJSON);
</code>```

My problem is that the compiler accepts the next piece of code, but I want it to differentiate between std::string and nlohmann::json, to make sure that I am passing a JSON already parsed object and not a random string.

```<code>std::string filePath = "../folder/folder/file.json"

MyClass object;
object.parse(filePath);
</code>```

Then inside the parse method I am getting a runtime error when I launch the program because of course I am trying to access a string in a way that is not possible.

Is there a way to do it either in the code or with a compilation flag in the CMakeList.txt?

答:
You might add a deleted overload:</p>

```<code>class MyClass {
  public:
    MyClass();
    ~MyClass();

    bool parse(const nlohmann::json& configuration);
    bool parse(const std::string&) = delete;
    // bool parse(const char*) = delete; // Else you would have ambiguous call error message
};
</code>```

Body:
I have this situation where my method needs a nlohmann::json object as the argument.

class MyClass {
  public:
    MyClass();
    ~MyClass();

    bool parse(const nlohmann::json& configuration);
};

My current approach to give the JSON, which is fine, is the next one:

std::string filePath = "../folder/folder/file.json"
std::ifstream file(filePath);
nlohmann::json configJSON = nlohmann::json::parse(file);

MyClass object;
object.parse(configJSON);

My problem is that the compiler accepts the next piece of code, but I want it to differentiate between std::string and nlohmann::json, to make sure that I am passing a JSON already parsed object and not a random string.

std::string filePath = "../folder/folder/file.json"

MyClass object;
object.parse(filePath);

Then inside the parse method I am getting a runtime error when I launch the program because of course I am trying to access a string in a way that is not possible.

Is there a way to do it either in the code or with a compilation flag in the CMakeList.txt?

Body:
You might add a deleted overload:

class MyClass {
  public:
    MyClass();
    ~MyClass();

    bool parse(const nlohmann::json& configuration);
    bool parse(const std::string&) = delete;
    // bool parse(const char*) = delete; // Else you would have ambiguous call error message
};


问:
Not able to download .csv file through Google Chrome in headless mode
I have been trying to download a csv file using selenium in Chrome headless mode but it is not working for my scenario. I tried to run the same script without headless and it works. I tried the same headless configuration with https://www.mockaroo.com/ site and it worked. Below is the chrome headless configuration that I'm using

```<code>System.setProperty("webdriver.chrome.driver", Constants.CHROME_DRIVER);
ChromeOptions options = new ChromeOptions();
options.addArguments("--test-type");
options.addArguments("--headless");
options.addArguments("--disable-extensions"); //to disable browser extension popup
options.addArguments("window-size=1980,1080");
options.addArguments("--disable-web-security");
options.addArguments("--no-sandbox");
options.addArguments("--disable-gpu");
options.addArguments("--disable-popup-blocking");
options.addArguments("--start-maximized");
options.addArguments("--allow-running-insecure-content");
options.setExperimentalOption("w3c", false);
options.addArguments("--ignore-certificate-errors");
options.addArguments("user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36");

DesiredCapabilities cap = DesiredCapabilities.chrome();
cap.setCapability(ChromeOptions.CAPABILITY, options);

// set performance logger
// this sends Network.enable to chromedriver
LoggingPreferences logPrefs = new LoggingPreferences();
logPrefs.enable(LogType.PERFORMANCE, Level.ALL);
cap.setCapability("goog:loggingPrefs", logPrefs);

ChromeDriverService driverService = ChromeDriverService.createDefaultService();
driver = new ChromeDriver(driverService, cap);
String downloadFilepath = "C:\\Users\\User\\Downloads";
System.out.println(downloadFilepath);
Map < String, Object > commandParams = new HashMap<String, Object>();
commandParams.put("cmd", "Page.setDownloadBehavior");
Map < String, Object > params = new HashMap<String, Object>();
params.put("behavior", "allow");
params.put("download.prompt_for_download", false);
params.put("downloadPath", downloadFilepath);
commandParams.put("params", params);
ObjectMapper objectMapper = new ObjectMapper();
HttpClient httpClient = HttpClientBuilder.create().build();
try {
    String command = objectMapper.writeValueAsString(commandParams);
    String u = driverService.getUrl().toString() + "/session/" + ((ChromeDriver)driver).getSessionId() + "/chromium/send_command";
    System.out.println("U: " + u.toString());
    HttpPost request = new HttpPost(u);
    request.addHeader("content-type", "application/json");
    request.setEntity(new StringEntity(command));
    httpClient.execute(request);
} catch (Exception e) { }

driver.get(prop.getProperty("url"));
</code>```

With the above driver configuration (after authenticating the user), I'm clicking a button which submits the form data and in response, I am getting:

```<code>Content-Disposition: attachment;filename=WIS_mop_mis3.csv
</code>```

which downloads the file.

Please find the logs below where you can see the highlighted part where it says that net::ERR_ABORTED but I am getting this error for both headless & without headless;

Performance logs for headless mode

Anyone have any idea, where I am doing wrong.

Edit: The application flow is when user clicks on the export button a new window gets opened where user fills the data and clicks on a button which calls a function for some sort of validation. After validation, it submits the form using document.formName.submit().

答:
I am able to figure out the solution. Below is the working code

```<code>System.setProperty("webdriver.chrome.driver", Constants.CHROME_DRIVER);
ChromeOptions options = new ChromeOptions();
options.addArguments("--test-type");
options.addArguments("--headless");
options.addArguments("--disable-extensions"); //to disable browser extension popup
options.addArguments("window-size=1980,1080");
options.addArguments("--disable-web-security");
options.addArguments("--no-sandbox");
options.addArguments("--disable-gpu");
options.addArguments("--disable-popup-blocking");
options.addArguments("--start-maximized");
options.addArguments("--allow-running-insecure-content");
options.setExperimentalOption("w3c", false);
options.addArguments("--ignore-certificate-errors");
options.addArguments("user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36");

HashMap<String, Object> chromePreferences = new HashMap<String, Object>();

// This part was missing in my old code.
chromePreferences.put("download.prompt_for_download", false);
chromePreferences.put("download.directory_upgrade", true);
chromePreferences.put("safebrowsing.enabled", false);
chromePreferences.put("profile.default_content_settings.popups", 0);
chromePreferences.put("safebrowsing.disable_download_protection", true);
chromePreferences.put("download.default_directory", downloadFilepath);
options.setExperimentalOption("prefs", chromePreferences);

DesiredCapabilities cap = DesiredCapabilities.chrome();
cap.setCapability(ChromeOptions.CAPABILITY, options);

// set performance logger
// this sends Network.enable to chromedriver
LoggingPreferences logPrefs = new LoggingPreferences();
logPrefs.enable(LogType.PERFORMANCE, Level.ALL);
cap.setCapability("goog:loggingPrefs", logPrefs);

ChromeDriverService driverService = ChromeDriverService.createDefaultService();
driver = new ChromeDriver(driverService, cap);
String downloadFilepath = "C:\\Users\\User\\Downloads";
System.out.println(downloadFilepath);
Map < String, Object > commandParams = new HashMap<String, Object>();
commandParams.put("cmd", "Page.setDownloadBehavior");
Map < String, Object > params = new HashMap<String, Object>();
params.put("behavior", "allow");
params.put("downloadPath", downloadFilepath);
commandParams.put("params", params);
ObjectMapper objectMapper = new ObjectMapper();
HttpClient httpClient = HttpClientBuilder.create().build();
try {
    String command = objectMapper.writeValueAsString(commandParams);
    String u = driverService.getUrl().toString() + "/session/" + ((ChromeDriver)driver).getSessionId() + "/chromium/send_command";
    System.out.println("U: " + u.toString());
    HttpPost request = new HttpPost(u);
    request.addHeader("content-type", "application/json");
    request.setEntity(new StringEntity(command));
    httpClient.execute(request);
} catch (Exception e) { }

</code>```

This post helped me to fix this issue https://stackoverflow.com/a/52384942/6017332

Body:
I have been trying to download a csv file using selenium in Chrome headless mode but it is not working for my scenario. I tried to run the same script without headless and it works. I tried the same headless configuration with https://www.mockaroo.com/ site and it worked. Below is the chrome headless configuration that I'm using

System.setProperty("webdriver.chrome.driver", Constants.CHROME_DRIVER);
ChromeOptions options = new ChromeOptions();
options.addArguments("--test-type");
options.addArguments("--headless");
options.addArguments("--disable-extensions"); //to disable browser extension popup
options.addArguments("window-size=1980,1080");
options.addArguments("--disable-web-security");
options.addArguments("--no-sandbox");
options.addArguments("--disable-gpu");
options.addArguments("--disable-popup-blocking");
options.addArguments("--start-maximized");
options.addArguments("--allow-running-insecure-content");
options.setExperimentalOption("w3c", false);
options.addArguments("--ignore-certificate-errors");
options.addArguments("user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36");

DesiredCapabilities cap = DesiredCapabilities.chrome();
cap.setCapability(ChromeOptions.CAPABILITY, options);

// set performance logger
// this sends Network.enable to chromedriver
LoggingPreferences logPrefs = new LoggingPreferences();
logPrefs.enable(LogType.PERFORMANCE, Level.ALL);
cap.setCapability("goog:loggingPrefs", logPrefs);

ChromeDriverService driverService = ChromeDriverService.createDefaultService();
driver = new ChromeDriver(driverService, cap);
String downloadFilepath = "C:\\Users\\User\\Downloads";
System.out.println(downloadFilepath);
Map < String, Object > commandParams = new HashMap<String, Object>();
commandParams.put("cmd", "Page.setDownloadBehavior");
Map < String, Object > params = new HashMap<String, Object>();
params.put("behavior", "allow");
params.put("download.prompt_for_download", false);
params.put("downloadPath", downloadFilepath);
commandParams.put("params", params);
ObjectMapper objectMapper = new ObjectMapper();
HttpClient httpClient = HttpClientBuilder.create().build();
try {
    String command = objectMapper.writeValueAsString(commandParams);
    String u = driverService.getUrl().toString() + "/session/" + ((ChromeDriver)driver).getSessionId() + "/chromium/send_command";
    System.out.println("U: " + u.toString());
    HttpPost request = new HttpPost(u);
    request.addHeader("content-type", "application/json");
    request.setEntity(new StringEntity(command));
    httpClient.execute(request);
} catch (Exception e) { }

driver.get(prop.getProperty("url"));

With the above driver configuration (after authenticating the user), I'm clicking a button which submits the form data and in response, I am getting:

Content-Disposition: attachment;filename=WIS_mop_mis3.csv

which downloads the file.

Please find the logs below where you can see the highlighted part where it says that net::ERR_ABORTED but I am getting this error for both headless & without headless;

Performance logs for headless mode

Anyone have any idea, where I am doing wrong.

Edit: The application flow is when user clicks on the export button a new window gets opened where user fills the data and clicks on a button which calls a function for some sort of validation. After validation, it submits the form using document.formName.submit().

Body:
I am able to figure out the solution. Below is the working code

System.setProperty("webdriver.chrome.driver", Constants.CHROME_DRIVER);
ChromeOptions options = new ChromeOptions();
options.addArguments("--test-type");
options.addArguments("--headless");
options.addArguments("--disable-extensions"); //to disable browser extension popup
options.addArguments("window-size=1980,1080");
options.addArguments("--disable-web-security");
options.addArguments("--no-sandbox");
options.addArguments("--disable-gpu");
options.addArguments("--disable-popup-blocking");
options.addArguments("--start-maximized");
options.addArguments("--allow-running-insecure-content");
options.setExperimentalOption("w3c", false);
options.addArguments("--ignore-certificate-errors");
options.addArguments("user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36");

HashMap<String, Object> chromePreferences = new HashMap<String, Object>();

// This part was missing in my old code.
chromePreferences.put("download.prompt_for_download", false);
chromePreferences.put("download.directory_upgrade", true);
chromePreferences.put("safebrowsing.enabled", false);
chromePreferences.put("profile.default_content_settings.popups", 0);
chromePreferences.put("safebrowsing.disable_download_protection", true);
chromePreferences.put("download.default_directory", downloadFilepath);
options.setExperimentalOption("prefs", chromePreferences);

DesiredCapabilities cap = DesiredCapabilities.chrome();
cap.setCapability(ChromeOptions.CAPABILITY, options);

// set performance logger
// this sends Network.enable to chromedriver
LoggingPreferences logPrefs = new LoggingPreferences();
logPrefs.enable(LogType.PERFORMANCE, Level.ALL);
cap.setCapability("goog:loggingPrefs", logPrefs);

ChromeDriverService driverService = ChromeDriverService.createDefaultService();
driver = new ChromeDriver(driverService, cap);
String downloadFilepath = "C:\\Users\\User\\Downloads";
System.out.println(downloadFilepath);
Map < String, Object > commandParams = new HashMap<String, Object>();
commandParams.put("cmd", "Page.setDownloadBehavior");
Map < String, Object > params = new HashMap<String, Object>();
params.put("behavior", "allow");
params.put("downloadPath", downloadFilepath);
commandParams.put("params", params);
ObjectMapper objectMapper = new ObjectMapper();
HttpClient httpClient = HttpClientBuilder.create().build();
try {
    String command = objectMapper.writeValueAsString(commandParams);
    String u = driverService.getUrl().toString() + "/session/" + ((ChromeDriver)driver).getSessionId() + "/chromium/send_command";
    System.out.println("U: " + u.toString());
    HttpPost request = new HttpPost(u);
    request.addHeader("content-type", "application/json");
    request.setEntity(new StringEntity(command));
    httpClient.execute(request);
} catch (Exception e) { }

This post helped me to fix this issue https://stackoverflow.com/a/52384942/6017332


问:
Which architecture is suited the best for a changing URL?
Exam Question: You're using an external API, where the URL changes frequently. Which architecture is suited the best to solve this problem, without ever-changing the code for the program again?

I recently took an exam and there was this task to which i still cannot figure out the appropriate answer.The architectures mentioned in the lecture were P2P, C/S and SOA.

If anyone has a clue... Thanks!

答:
I think the answer is p2p. In a Peer-to-peer network, computers advertise their services capabilities on the network. A changing URL would not be a problem, as the new URL is published to the network automatically and picked up by the consumers of the API.

In SOA and Client/Server the consumers of the API have no means to know about a change in the API URL.


问:
How to add a grid line at a specific location in matplotlib plot?
How do I add grid at a specific location on the y axis in a matplotlib plot? </p>

答:
To improve the answer of @tacaswell here's an example using the concept of axhline and tweaking it to look similar to a line grid. In this exapmle it's used a starting default grid only on the x-axis, but  it's possible to add a grid also on the y-axis (or only on this axis) by simpy add ax.xaxis.grid(True) to the code.

First one simply start drawing a line at the desired position:

```<code>import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.xaxis.grid(True)
ynew = 0.3
ax.axhline(ynew)

plt.show()
</code>```

obtaining the following result

that is not very similar to a line grid.

By changing color and line width like below:

```<code>import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.xaxis.grid(True)
ynew = 0.3
ax.axhline(ynew, color='gray', linewidth=0.5)

plt.show()
</code>```

we obtain this, that now is in practice equal to a line grid.

If then we want also to add a tick and related label on the y-axis, in the position where the new line is:

```<code>import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots()
ax.xaxis.grid(True)
ynew = 0.3
ax.axhline(ynew, color='gray', linewidth=0.5)

yt = ax.get_yticks()
yt=np.append(yt,ynew)

ax.set_yticks(yt)
ax.set_yticklabels(yt)

plt.show()
</code>```

that leads to:

Oh no! Some approximation occurred and the label at 0.6 not represents exactly the number 0.6. Don't worry, we can fix that simply by rounding the label array like follow:

```<code>import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots()
ax.xaxis.grid(True)
ynew = 0.3
ax.axhline(ynew, color='gray', linewidth=0.5)

yt = ax.get_yticks()
yt=np.append(yt,ynew)

ax.set_yticks(yt)
ax.set_yticklabels(np.round(yt,1))

plt.show()
</code>```

and TA-DAAA :)

Body:
To improve the answer of @tacaswell here's an example using the concept of axhline and tweaking it to look similar to a line grid. In this exapmle it's used a starting default grid only on the x-axis, but  it's possible to add a grid also on the y-axis (or only on this axis) by simpy add ax.xaxis.grid(True) to the code.

First one simply start drawing a line at the desired position:

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.xaxis.grid(True)
ynew = 0.3
ax.axhline(ynew)

plt.show()

obtaining the following result

that is not very similar to a line grid.

By changing color and line width like below:

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.xaxis.grid(True)
ynew = 0.3
ax.axhline(ynew, color='gray', linewidth=0.5)

plt.show()

we obtain this, that now is in practice equal to a line grid.

If then we want also to add a tick and related label on the y-axis, in the position where the new line is:

import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots()
ax.xaxis.grid(True)
ynew = 0.3
ax.axhline(ynew, color='gray', linewidth=0.5)

yt = ax.get_yticks()
yt=np.append(yt,ynew)

ax.set_yticks(yt)
ax.set_yticklabels(yt)

plt.show()

that leads to:

Oh no! Some approximation occurred and the label at 0.6 not represents exactly the number 0.6. Don't worry, we can fix that simply by rounding the label array like follow:

import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots()
ax.xaxis.grid(True)
ynew = 0.3
ax.axhline(ynew, color='gray', linewidth=0.5)

yt = ax.get_yticks()
yt=np.append(yt,ynew)

ax.set_yticks(yt)
ax.set_yticklabels(np.round(yt,1))

plt.show()

and TA-DAAA :)


问:
Need some help with regular expressions (php)
For example, I have the following code :

```<code>$string  = "adf  gggg  eere value aaaa bbb (10) value
ddttt ggg www (20) value ddttt ggg www dddd (40) ";
preg_match("/(value).*(\(\d+\))/is", $string, $result);
var_dump($result[2]); // outputs 40.
</code>```

I'm trying to get the first value (10). The code above outputs 40 which makes sense, but not what I want. The string pattern is : word "value", then a number of any characters, then "(", integer, ")". It seems that I'm missing something obvious... I haven't worked too much with regular expressions, but I believe it can be solved somehow with ?<!value, no luck so far though.

Thanks for any help.

答:
What's wrong with your regex is that .* is greedy, and tries to matchs as many letters as possible.

```<code>preg_match("#value.*?\((\d+)\)#is", $string, $result);
</code>```

But you can make it faster by using a negative class:

```<code>preg_match("#value[^(]+\((\d+)\)#is", $string, $result);
</code>```

Body:
For example, I have the following code :

$string  = "adf  gggg  eere value aaaa bbb (10) value
ddttt ggg www (20) value ddttt ggg www dddd (40) ";
preg_match("/(value).*(\(\d+\))/is", $string, $result);
var_dump($result[2]); // outputs 40.

I'm trying to get the first value (10). The code above outputs 40 which makes sense, but not what I want. The string pattern is : word "value", then a number of any characters, then "(", integer, ")". It seems that I'm missing something obvious... I haven't worked too much with regular expressions, but I believe it can be solved somehow with ?<!value, no luck so far though.

Thanks for any help.

Body:
What's wrong with your regex is that .* is greedy, and tries to matchs as many letters as possible.

preg_match("#value.*?\((\d+)\)#is", $string, $result);

But you can make it faster by using a negative class:

preg_match("#value[^(]+\((\d+)\)#is", $string, $result);


问:
How to fix an error "Resize medium operation for this format is not implemented yet"?
I'm trying to increase disk size of my vmdk-file. Command line:

```<code>VBoxManage clonehd "source.vmdk" "cloned.vdi" --format vdi
</code>```

Cloned.vdi has been created successfully (45.2Gb). But then I'm writing:

```<code>VBoxManage modifyhd "cloned.vdi" --resize 60200
</code>```

And get an error

```<code>Progress state: VBOX_E_NOT_SUPPORTED
VBoxManage.exe: error: Resize medium operation for this format is not implemented yet!
</code>```

Ok, I'm opening my VM VirtualBox Machine Setting -> Storage -> Adds hard disk -> Cloned.VDI.

On the right in the information section  I have:
Type(format): Normal (VMDK).
It's ok? How to fix this error? I have free 110Gb of ROM on my disk

答:
Omid's answer is correct.

NOTE however that you can get pretty confusing "not supported for this version" error also in case your vdi-disk file has size 45GB on disk, but it is dynamic size disk with max size e.g. 80GB and your try to run

```<code>vboxmanage modifymedium vdi-disk-file-name --resize 60000
</code>```

This is because you are actually trying to decrease the size, which virtualbox does not support for any format currently.

Body:
I'm trying to increase disk size of my vmdk-file. Command line:

VBoxManage clonehd "source.vmdk" "cloned.vdi" --format vdi

Cloned.vdi has been created successfully (45.2Gb). But then I'm writing:

VBoxManage modifyhd "cloned.vdi" --resize 60200

And get an error

Progress state: VBOX_E_NOT_SUPPORTED
VBoxManage.exe: error: Resize medium operation for this format is not implemented yet!

Ok, I'm opening my VM VirtualBox Machine Setting -> Storage -> Adds hard disk -> Cloned.VDI.

On the right in the information section  I have:
Type(format): Normal (VMDK).
It's ok? How to fix this error? I have free 110Gb of ROM on my disk

Body:
Omid's answer is correct.

NOTE however that you can get pretty confusing "not supported for this version" error also in case your vdi-disk file has size 45GB on disk, but it is dynamic size disk with max size e.g. 80GB and your try to run

vboxmanage modifymedium vdi-disk-file-name --resize 60000

This is because you are actually trying to decrease the size, which virtualbox does not support for any format currently.


问:
Use a CodeBehind Boolean to update visibility of control
I have the following code;

```<code>public partial class MainWindow : Window, INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        bool _myValue;
        public bool myValue
        {
            get { return _myValue; }
            set {
                _myValue = value;
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("myValue"));
            }
        }

        public MainWindow() {
            myValue = false;
            DispatcherTimer timer = new DispatcherTimer();
            timer.Interval = TimeSpan.FromSeconds(1);
            timer.Tick += timer_Tick;
            timer.Start();
        }

        void timer_Tick(object sender, EventArgs e) {
            myValue = !myValue;
            lblTime.Content = myValue.ToString();
        }
    }
</code>```

and the corresponding xaml:

```<code>    <Window.Resources>
        <BooleanToVisibilityConverter x:Key="BoolToVis" />
    </Window.Resources>
    <DockPanel Margin="10">
        <Button x:Name="HideMe"
             Height="50" Width="50"
            Cursor="Hand"
            Visibility="{Binding Path=myValue, Converter={StaticResource BoolToVis}}"/>
        <Label x:Name="lblTime" />
    </DockPanel>

</code>```

What i am trying to do; is update the visibility of the button with every timer_tick;
The label is updated, yet the binding refuses to work

I am very sure there is an oversight, but after following numerous tutorials, there is none on how I can make this work.. most work with a checkbox on the WPF; but I need the boolean in the codebehind to send to control the visibility of the button, once it's updated..

答:
Set the DataContext of the window to itself and don't forgot to call InitializeComponent():

```<code>public MainWindow()
{
    InitializeComponent();
    DataContext = this; //<--

    myValue = false;
    DispatcherTimer timer = new DispatcherTimer();
    timer.Interval = TimeSpan.FromSeconds(1);
    timer.Tick += timer_Tick;
    timer.Start();
}
</code>```

Body:
I have the following code;

public partial class MainWindow : Window, INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        bool _myValue;
        public bool myValue
        {
            get { return _myValue; }
            set {
                _myValue = value;
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("myValue"));
            }
        }

        public MainWindow() {
            myValue = false;
            DispatcherTimer timer = new DispatcherTimer();
            timer.Interval = TimeSpan.FromSeconds(1);
            timer.Tick += timer_Tick;
            timer.Start();
        }

        void timer_Tick(object sender, EventArgs e) {
            myValue = !myValue;
            lblTime.Content = myValue.ToString();
        }
    }

and the corresponding xaml:

    <Window.Resources>
        <BooleanToVisibilityConverter x:Key="BoolToVis" />
    </Window.Resources>
    <DockPanel Margin="10">
        <Button x:Name="HideMe"
             Height="50" Width="50"
            Cursor="Hand"
            Visibility="{Binding Path=myValue, Converter={StaticResource BoolToVis}}"/>

    </DockPanel>

What i am trying to do; is update the visibility of the button with every timer_tick;
The label is updated, yet the binding refuses to work

I am very sure there is an oversight, but after following numerous tutorials, there is none on how I can make this work.. most work with a checkbox on the WPF; but I need the boolean in the codebehind to send to control the visibility of the button, once it's updated..

Body:
Set the DataContext of the window to itself and don't forgot to call InitializeComponent():

public MainWindow()
{
    InitializeComponent();
    DataContext = this; //<--

    myValue = false;
    DispatcherTimer timer = new DispatcherTimer();
    timer.Interval = TimeSpan.FromSeconds(1);
    timer.Tick += timer_Tick;
    timer.Start();
}


问:
CRTP Singleton Incomplete type or Non-literal type
I'm trying to make a CRTP Singleton. There's a couple examples on here already. I'm not sure how mine is different or why it fails to compile. First attempt:

```<code>template<class Impl>
class Base
{
public:
  static const Impl& getInstance();
  static int foo(int x);
private:
  static const Impl impl{};
};
template<class Impl> inline
const Impl& Base<Impl>::getInstance()
{
  return impl;
}
template<class Impl> inline
int Base<Impl>::foo(int x)
{
  return impl.foo_impl(x);
}

class Derived1 : public Base<Derived1>
{
public:
  int foo_impl(int x) const;
};
int Derived1::foo_impl(int x) const
{
  return x + 3;
}

int main(int argc, char** argv)
{
  const Derived1& d = Derived1::getInstance();
  std::cout << Derived1::foo(3) << std::endl;
  return 0;
}
</code>```

g++ 7.4.0 tells me: error: in-class initialization of static data member ‘const Derived1 Base<Derived1>::impl’ of incomplete type.

Well. Ok then. Not sure why that type isn't complete. Try:

```<code> . . .
 private:
   static constexpr Impl impl{};
 };
</code>```

Now we fail at link time: undefined reference to 'Base<Derived1>::impl'
Really?! Looks defined and initialized to me... But even if it did link I have a Derived with a non-trivial destructor so then the compiler is going to bomb at compiletime complaining about a non-literal type used in constexpr.

Why isn't Derived1 complete? How can I build this?

答:
To the point of time that Base<Derived1> is instantiated (right at the start of the definition of Derived1) the class Derived1 is incomplete, since it is that untill the end of its declaration. It is indeed not possible to have a complete type in the CRTP, since the derived type will never be complete before you have declared its inheritance.

For non-static data members the only way around that is to use some kind of pointer to the incomplete type (most probably a std::unique_ptr). For static members this does also work, but can also just split the declaration and the definition of a static member. So instead of

```<code>template<Impl>
struct Base {
   static Impl impl{};
};
</code>```

write

```<code>template<Impl>
struct Base {
    static Impl impl;
};
</code>```

and define it like this

```<code>template<Impl>
static Base<Impl>::impl ={};
</code>```

after Derived1 is complete. (Note that I am not sure how this works for private static members). In my opinion it would be cleanest, if each implementation would do this for itself, i.e. after Derived1 is complete add

```<code>template<>
static Base<Derived1>::impl = {};
</code>```

otherwise getting the order right for multiple implementations will be tricky, I think.

Body:
I'm trying to make a CRTP Singleton. There's a couple examples on here already. I'm not sure how mine is different or why it fails to compile. First attempt:

template<class Impl>
class Base
{
public:
  static const Impl& getInstance();
  static int foo(int x);
private:
  static const Impl impl{};
};
template<class Impl> inline
const Impl& Base<Impl>::getInstance()
{
  return impl;
}
template<class Impl> inline
int Base<Impl>::foo(int x)
{
  return impl.foo_impl(x);
}

class Derived1 : public Base<Derived1>
{
public:
  int foo_impl(int x) const;
};
int Derived1::foo_impl(int x) const
{
  return x + 3;
}

int main(int argc, char** argv)
{
  const Derived1& d = Derived1::getInstance();
  std::cout << Derived1::foo(3) << std::endl;
  return 0;
}

g++ 7.4.0 tells me: error: in-class initialization of static data member ‘const Derived1 Base<Derived1>::impl’ of incomplete type.

Well. Ok then. Not sure why that type isn't complete. Try:

 . . .
 private:
   static constexpr Impl impl{};
 };

Now we fail at link time: undefined reference to 'Base<Derived1>::impl'
Really?! Looks defined and initialized to me... But even if it did link I have a Derived with a non-trivial destructor so then the compiler is going to bomb at compiletime complaining about a non-literal type used in constexpr.

Why isn't Derived1 complete? How can I build this?

Body:
To the point of time that Base<Derived1> is instantiated (right at the start of the definition of Derived1) the class Derived1 is incomplete, since it is that untill the end of its declaration. It is indeed not possible to have a complete type in the CRTP, since the derived type will never be complete before you have declared its inheritance.

For non-static data members the only way around that is to use some kind of pointer to the incomplete type (most probably a std::unique_ptr). For static members this does also work, but can also just split the declaration and the definition of a static member. So instead of

template<Impl>
struct Base {
   static Impl impl{};
};

write

template<Impl>
struct Base {
    static Impl impl;
};

and define it like this

template<Impl>
static Base<Impl>::impl ={};

after Derived1 is complete. (Note that I am not sure how this works for private static members). In my opinion it would be cleanest, if each implementation would do this for itself, i.e. after Derived1 is complete add

template<>
static Base<Derived1>::impl = {};

otherwise getting the order right for multiple implementations will be tricky, I think.


问:
Count numbers that are lower by constant from current number
Imagine that I have a list of numbers (i.e. numbers column in data.table/data.frame).

```<code>1
5
5
10
11
12
</code>```

for each number in a list a want to count how many unique numbers are there which are lower than that particular number + 5.

The explanation for upper case, first number = 1, search range is 1+5 = 6, so three numbers are in range, less than or equal to: c(1,5,5), and then count unique is 2.
This is all by assuming we've got the additional condition, that the number must not only be lower than current_number + 5, but also its index in the list must be >= that of current_number.

The result in this case would be:

```<code>2
2
2
3
2
1
</code>```

Note: Is there a fast solution for huge dataset, in data.frame or data.table? My dataset is rather huge, 10+M rows.

答:
One option is to use a sql self-join

```<code>library(sqldf)

df$r <- seq(nrow(df))

sqldf('
select    a.V1
          , count(distinct b.V1) as n
from      df a
          left join df b
            on  b.V1 <= a.V1 + 5
                and b.r >= a.r
group by  a.r
')

#   V1 n
# 1  1 2
# 2  5 2
# 3  5 2
# 4 10 3
# 5 11 2
# 6 12 1
</code>```

Data used:

```<code>df <- structure(list(V1 = c(1L, 5L, 5L, 10L, 11L, 12L)), row.names = c(NA,
-6L), class = "data.frame")
</code>```

Body:
Imagine that I have a list of numbers (i.e. numbers column in data.table/data.frame).

1
5
5
10
11
12

for each number in a list a want to count how many unique numbers are there which are lower than that particular number + 5.

The explanation for upper case, first number = 1, search range is 1+5 = 6, so three numbers are in range, less than or equal to: c(1,5,5), and then count unique is 2.
This is all by assuming we've got the additional condition, that the number must not only be lower than current_number + 5, but also its index in the list must be >= that of current_number.

The result in this case would be:

2
2
2
3
2
1

Note: Is there a fast solution for huge dataset, in data.frame or data.table? My dataset is rather huge, 10+M rows.

Body:
One option is to use a sql self-join

library(sqldf)

df$r <- seq(nrow(df))

sqldf('
select    a.V1
          , count(distinct b.V1) as n
from      df a
          left join df b
            on  b.V1 <= a.V1 + 5
                and b.r >= a.r
group by  a.r
')

#   V1 n
# 1  1 2
# 2  5 2
# 3  5 2
# 4 10 3
# 5 11 2
# 6 12 1

Data used:

df <- structure(list(V1 = c(1L, 5L, 5L, 10L, 11L, 12L)), row.names = c(NA,
-6L), class = "data.frame")


问:
Sitecore OMS - achieving a goal on a form submission
I inherited a Sitecore solution that has a sublayout that contains a complex ASP.NET ascx form which handles both payments and integration with 3rd party web services.

This sublayout uses parameters templates to provide some level of control on the way the form looks like.

The .ascx control contains multiple views:

In the first view the user fills the
form and click NEXT.

In the second view the user can review the entered data before
clicking the SUBMIT button.

The third view is the thank you page of the form.

If I want to create a goal for the submission of this form, am I supposed to set the goal as "achieved" via API on submission of the form itself? Should I add, maybe, the name of the goal as one of the parameter templates so that the marketing editors will be able to change it, if needed?

Thanks

答:
Yes, you can set the goal as achieved using the AnalyticsTracker.TriggerEvent method at the appropriate point in your form's workflow. Putting the name of the goal as a template parameter is a great idea. Even better, use a droplink and point the source at /sitecore/system/Marketing Center/Goals/.

EDIT

See the Analytics Configuration Reference on how to programmatically "Register an Analytics Page Event."


问:
Material ui table not updating
I'm currently updating my react site to 16.8 and have stumbled into an issue with a material ui table. In my app users pick some options, a rest call is then made when a user clicks a button, and the result of said call is added to the table.

Currently the table stays blank even when a result is returned. I've created an example of the behaviour using the material ui table example. (Note that the table data is in the format the web service returns it in, and I have also tried moving the arr.map function into the handleClick function and setting that as Arr, and then simply putting arr inside TableBody)

Does anyone have any idea what I'm doing wrong?

```<code>//imports done above here
//example data used instead of performing rest call

var outRo = {
  id: 'Frozen yoghurt',
  calories: 159,
  fat: 6.0,
  carbs: 24,
  protein: 4.0,
};

export default function SimpleTable() {
  const [arr, setArr] = useState([]);

  function handleClick() {
    console.log('inside');
    //rest call gets data, stores into outRo

    setArr(Array.from(outRo));
  }

  return (
    <div>
      <Button onClick = {handleClick}> Add to Table </Button>
      <TableContainer component={Paper}>
        <Table className={'table'}>
          <TableHead>
            <TableRow>
              <TableCell>Dessert (100g serving)</TableCell>
              <TableCell>Calories</TableCell>
              <TableCell>Fat (g)</TableCell>
              <TableCell>Carbs (g)</TableCell>
              <TableCell>Protein (g)</TableCell>
            </TableRow>
          </TableHead>
          <TableBody>
            {arr.map(row => (
              <TableRow key={row.id}>
                <TableCell>
                  {row.id}
                </TableCell>
                <TableCell>{row.calories}</TableCell>
                <TableCell>{row.fat}</TableCell>
                <TableCell>{row.carbs}</TableCell>
                <TableCell>{row.protein}</TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
      </TableContainer>
    </div>
  );
}
</code>```

答:
EDIT - Requested to update answer to show how to include multiple items:

```<code>// imports removed for brevity
const row1 = {
  Name: "Frozen yoghurt",
  calories: 159,
  fat: 6.0,
  carbs: 24,
  protein: 4.0
};

const row2 = {
  Name: "foyo",
  calories: 222,
  fat: 4.0,
  carbs: 124,
  protein: 5.0
};

//results are captured and put into an array like such
var testAr = [];
testAr.push(row1, row2);

export default function SimpleTable() {
  const [resultRows, setResultRows] = useState([]);

  function handleClick() {
    setResultRows(testAr);
  }

  return (
    <div>
      <Button onClick={handleClick}> click</Button>
      <TableContainer component={Paper}>
        <Table className={"table"} aria-label="simple table">
          <TableHead>
            <TableRow>
              <TableCell>Dessert (100g serving)</TableCell>
              <TableCell>Calories</TableCell>
              <TableCell>Fat (g)</TableCell>
              <TableCell>Carbs (g)</TableCell>
              <TableCell>Protein (g)</TableCell>
            </TableRow>
          </TableHead>
          <TableBody>
            {resultRows.map(row => (
              <TableRow key={row.Name}>
                <TableCell>{row.Name} </TableCell>
                <TableCell>{row.calories}</TableCell>
                <TableCell>{row.fat}</TableCell>
                <TableCell>{row.carbs}</TableCell>
                <TableCell>{row.protein}</TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
      </TableContainer>
    </div>
  );
}
</code>```

This is actually way easier than the first request, because you've already created the array from your objects.

So all you need to do, is use your setResultRows to push the newly created array, as above.

Title: Material ui table not updating

Body:
I'm currently updating my react site to 16.8 and have stumbled into an issue with a material ui table. In my app users pick some options, a rest call is then made when a user clicks a button, and the result of said call is added to the table.

Currently the table stays blank even when a result is returned. I've created an example of the behaviour using the material ui table example. (Note that the table data is in the format the web service returns it in, and I have also tried moving the arr.map function into the handleClick function and setting that as Arr, and then simply putting arr inside TableBody)

Does anyone have any idea what I'm doing wrong?

//imports done above here
//example data used instead of performing rest call

var outRo = {
  id: 'Frozen yoghurt',
  calories: 159,
  fat: 6.0,
  carbs: 24,
  protein: 4.0,
};

export default function SimpleTable() {
  const [arr, setArr] = useState([]);

  function handleClick() {
    console.log('inside');
    //rest call gets data, stores into outRo

    setArr(Array.from(outRo));
  }

  return (

      <Button onClick = {handleClick}> Add to Table </Button>
      <TableContainer component={Paper}>

          <TableHead>
            <TableRow>
              <TableCell>Dessert (100g serving)</TableCell>
              <TableCell>Calories</TableCell>
              <TableCell>Fat (g)</TableCell>
              <TableCell>Carbs (g)</TableCell>
              <TableCell>Protein (g)</TableCell>
            </TableRow>
          </TableHead>
          <TableBody>
            {arr.map(row => (
              <TableRow key={row.id}>
                <TableCell>
                  {row.id}
                </TableCell>
                <TableCell>{row.calories}</TableCell>
                <TableCell>{row.fat}</TableCell>
                <TableCell>{row.carbs}</TableCell>
                <TableCell>{row.protein}</TableCell>
              </TableRow>
            ))}
          </TableBody>

      </TableContainer>

  );
}

Body:
EDIT - Requested to update answer to show how to include multiple items:

// imports removed for brevity
const row1 = {
  Name: "Frozen yoghurt",
  calories: 159,
  fat: 6.0,
  carbs: 24,
  protein: 4.0
};

const row2 = {
  Name: "foyo",
  calories: 222,
  fat: 4.0,
  carbs: 124,
  protein: 5.0
};

//results are captured and put into an array like such
var testAr = [];
testAr.push(row1, row2);

export default function SimpleTable() {
  const [resultRows, setResultRows] = useState([]);

  function handleClick() {
    setResultRows(testAr);
  }

  return (
    <div>
      <Button onClick={handleClick}> click</Button>
      <TableContainer component={Paper}>
        <Table className={"table"} aria-label="simple table">
          <TableHead>
            <TableRow>
              <TableCell>Dessert (100g serving)</TableCell>
              <TableCell>Calories</TableCell>
              <TableCell>Fat&nbsp;(g)</TableCell>
              <TableCell>Carbs&nbsp;(g)</TableCell>
              <TableCell>Protein&nbsp;(g)</TableCell>
            </TableRow>
          </TableHead>
          <TableBody>
            {resultRows.map(row => (
              <TableRow key={row.Name}>
                <TableCell>{row.Name} </TableCell>
                <TableCell>{row.calories}</TableCell>
                <TableCell>{row.fat}</TableCell>
                <TableCell>{row.carbs}</TableCell>
                <TableCell>{row.protein}</TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
      </TableContainer>
    </div>
  );
}

This is actually way easier than the first request, because you've already created the array from your objects.

So all you need to do, is use your setResultRows to push the newly created array, as above.


问:
'@react-navigation/stack' has stopped working with error - unable to resolve module
I have been successfully using React Navigation Stack (V5) for about a week now and today my app will not build as the error - unable to resolve module is now shown.

Error Message

The module is installed as shown in my package.json file -

```<code>{
  "scripts": {
    "postinstall": "jetify",
    "android": "react-native run-android",
    "ios": "react-native run-ios",
    "web": "expo start --web",
    "start": "react-native start",
    "test": "jest"
  },
  "dependencies": {
    "@react-native-community/masked-view": "^0.1.6",
    "expo": "~36.0.0",
    "expo-linear-gradient": "^8.0.0",
    "react": "~16.9.0",
    "react-dom": "~16.9.0",
    "react-native": "~0.61.4",
    "react-native-fontawesome": "^7.0.0",
    "react-native-gesture-handler": "^1.5.6",
    "react-native-keyboard-aware-scroll-view": "^0.9.1",
    "react-native-reanimated": "^1.7.0",
    "react-native-safe-area-context": "^0.7.2",
    "react-native-screens": "^2.0.0-beta.2",
    "react-native-unimodules": "~0.7.0",
    "react-native-web": "~0.11.7",
    "react-navigation": "^4.0.10",
    "react-navigation-stack": "^1.10.3"
  },
  "devDependencies": {
    "@babel/core": "~7.6.0",
    "babel-jest": "~24.9.0",
    "jest": "~24.9.0",
    "jetifier": "~1.6.4",
    "metro-react-native-babel-preset": "~0.56.0",
    "react-test-renderer": "~16.9.0"
  },
  "jest": {
    "preset": "react-native"
  },
  "private": true
}
</code>```

I have tried the following steps to try resolve the issue -

Deleted node_modules

Cleared yarn and npm cache

Ran npm install to install dependencies again

Cleared expo cache

Deleted and re-downoaded expo app on iOS device

Also tried installing the react navigation stack package again

Still receiving the same error message.

Would MASSIVELY appreciate any ideas.. currently losing my head over this :|

答: Try to delete the package-lock file and run npm i

Body:
I have been successfully using React Navigation Stack (V5) for about a week now and today my app will not build as the error - unable to resolve module is now shown.

Error Message

The module is installed as shown in my package.json file -

{
  "scripts": {
    "postinstall": "jetify",
    "android": "react-native run-android",
    "ios": "react-native run-ios",
    "web": "expo start --web",
    "start": "react-native start",
    "test": "jest"
  },
  "dependencies": {
    "@react-native-community/masked-view": "^0.1.6",
    "expo": "~36.0.0",
    "expo-linear-gradient": "^8.0.0",
    "react": "~16.9.0",
    "react-dom": "~16.9.0",
    "react-native": "~0.61.4",
    "react-native-fontawesome": "^7.0.0",
    "react-native-gesture-handler": "^1.5.6",
    "react-native-keyboard-aware-scroll-view": "^0.9.1",
    "react-native-reanimated": "^1.7.0",
    "react-native-safe-area-context": "^0.7.2",
    "react-native-screens": "^2.0.0-beta.2",
    "react-native-unimodules": "~0.7.0",
    "react-native-web": "~0.11.7",
    "react-navigation": "^4.0.10",
    "react-navigation-stack": "^1.10.3"
  },
  "devDependencies": {
    "@babel/core": "~7.6.0",
    "babel-jest": "~24.9.0",
    "jest": "~24.9.0",
    "jetifier": "~1.6.4",
    "metro-react-native-babel-preset": "~0.56.0",
    "react-test-renderer": "~16.9.0"
  },
  "jest": {
    "preset": "react-native"
  },
  "private": true
}

I have tried the following steps to try resolve the issue -

Deleted node_modules

Cleared yarn and npm cache

Ran npm install to install dependencies again

Cleared expo cache

Deleted and re-downoaded expo app on iOS device

Also tried installing the react navigation stack package again

Still receiving the same error message.

Would MASSIVELY appreciate any ideas.. currently losing my head over this :|


问:
Overload -> arrow operator in shared_ptr<interface> instance with no pure virtual destructor in interface
I'm trying to overload the -> operator to eventually execute something along the lines:

```<code>MyInterface *myInstance = (MyInterface *)(new A());
myInstance->Toggle(); //this works wonderfully

std::shared_ptr<Wrapper<MyInterface>> sharedPtrWrapper = std::make_shared<Wrapper<MyInterface>>(myInstance);

//the next line doesn't compile, I would like to achieve something like this, but even
//sharedPtrWrapper.get()->Toggle();
//would be nice to achieve, is this possible?
sharedPtrWrapper->Toggle();

//this works:
sharedPtrWrapper->operator->()->Toggle();
</code>```

Note: I have no control over MyInterface, cannot implement the pure virtual destructor.

Here is what I tried (the below code runs):

```<code>#import <memory>
#import <iostream>

struct MyInterface {
    virtual bool Toggle() = 0;
};

class A : public MyInterface {
public:
    bool Toggle() {
        stateEnabled = !stateEnabled;
        std::cout<<"current state " << stateEnabled << std::endl;
        return true;
    }
private:
    bool stateEnabled = false;
};

template <typename T>
class Wrapper {
private:
    T *unsafePointer = nullptr;
public:
    Wrapper<T>()
    { }

    T *operator->() const {
        return unsafePointer;
    }
    T *getInner() {
        return unsafePointer;
    }
    Wrapper<T>(T *stuff) {
        unsafePointer = stuff;
    }

    ~Wrapper<T>() {}
};

int main(int argc, const char * argv[]) {
    MyInterface *myInstance = (MyInterface *)(new A());
    myInstance->Toggle();

    Wrapper<MyInterface> wrapperS(myInstance);
    wrapperS->Toggle();

    std::shared_ptr<Wrapper<MyInterface>> sharedPtrWrapper = std::make_shared<Wrapper<MyInterface>>(myInstance);
    sharedPtrWrapper->operator->()->Toggle();
    sharedPtrWrapper.operator->()->operator->()->Toggle();

    sharedPtrWrapper.get()->operator->()->Toggle();

    (*sharedPtrWrapper).operator->()->Toggle();

    return 0;
}
</code>```

Output:

```<code>current state 1
current state 0
current state 1
current state 0
current state 1
current state 0
Program ended with exit code: 0
</code>```

To reiterate:
This code doesn't compile:

```<code>sharedPtrWrapper->Toggle();
</code>```

How to make it compile?

Edit : I'm using a wrapper because I have no control over the MyInterface, I get it from a library, also shared_ptr<MyInterface> mySharedPointer = std::make_shared<MyInterface>(myInstance); doesn't compile, because of the missing pure virtual destructor from the above mentioned interface.

Edit2: Example library usage in pseudocode:

```<code>void firstcallbackFromLib(Framework *framework) {
    MyInterface *myInstance = framework->getInstance();

    {
        Wrapper<MyInterface> wrapperS(myInstance);
        std::shared_ptr<Wrapper<MyInterface>> sharedPtrWrapper = std::make_shared<Wrapper<MyInterface>>(wrapperS);
        //assign sharedPtrWrapper and framework to static instances
    }
}
void myFunction() {
    sharedPtrWrapper->Toggle(); //this doesn't work, this is what i'm trying to achieve
    sharedPtrWrapper->operator->()->Toggle(); //this ugly thing works

}
void lastUninitCallbackFromLibrary() {
    MyInterface *p = sharedPtrWrapper.get()->getInner();
    framework->releaseInterface(p);
    //etc
}
</code>```

答:
The problem is, that shared_ptr behaves like a pointer and Wrapper does that as well. In summary, you have code that behaves like a pointer to a pointer. In short, you could call (*sharedPtrWrapper)->Toggle(); instead of the abomination sharedPtrWrapper->operator->()->Toggle();.

Careful though: It's unclear what all this is supposed to achieve, because the example code is just an abstraction of your actual code. So, maybe it would just be more elegant to put a forwarding Toggle() method into class Wrapper, but that's impossible to tell with the info provided here.

Body:
I'm trying to overload the -> operator to eventually execute something along the lines:

MyInterface *myInstance = (MyInterface *)(new A());
myInstance->Toggle(); //this works wonderfully

std::shared_ptr<Wrapper<MyInterface>> sharedPtrWrapper = std::make_shared<Wrapper<MyInterface>>(myInstance);

//the next line doesn't compile, I would like to achieve something like this, but even
//sharedPtrWrapper.get()->Toggle();
//would be nice to achieve, is this possible?
sharedPtrWrapper->Toggle();

//this works:
sharedPtrWrapper->operator->()->Toggle();

Note: I have no control over MyInterface, cannot implement the pure virtual destructor.

Here is what I tried (the below code runs):

#import <memory>
#import <iostream>

struct MyInterface {
    virtual bool Toggle() = 0;
};

class A : public MyInterface {
public:
    bool Toggle() {
        stateEnabled = !stateEnabled;
        std::cout<<"current state " << stateEnabled << std::endl;
        return true;
    }
private:
    bool stateEnabled = false;
};

template <typename T>
class Wrapper {
private:
    T *unsafePointer = nullptr;
public:
    Wrapper<T>()
    { }

    T *operator->() const {
        return unsafePointer;
    }
    T *getInner() {
        return unsafePointer;
    }
    Wrapper<T>(T *stuff) {
        unsafePointer = stuff;
    }

    ~Wrapper<T>() {}
};

int main(int argc, const char * argv[]) {
    MyInterface *myInstance = (MyInterface *)(new A());
    myInstance->Toggle();

    Wrapper<MyInterface> wrapperS(myInstance);
    wrapperS->Toggle();

    std::shared_ptr<Wrapper<MyInterface>> sharedPtrWrapper = std::make_shared<Wrapper<MyInterface>>(myInstance);
    sharedPtrWrapper->operator->()->Toggle();
    sharedPtrWrapper.operator->()->operator->()->Toggle();

    sharedPtrWrapper.get()->operator->()->Toggle();

    (*sharedPtrWrapper).operator->()->Toggle();

    return 0;
}

Output:

current state 1
current state 0
current state 1
current state 0
current state 1
current state 0
Program ended with exit code: 0

To reiterate:
This code doesn't compile:

sharedPtrWrapper->Toggle();

How to make it compile?

Edit : I'm using a wrapper because I have no control over the MyInterface, I get it from a library, also shared_ptr<MyInterface> mySharedPointer = std::make_shared<MyInterface>(myInstance); doesn't compile, because of the missing pure virtual destructor from the above mentioned interface.

Edit2: Example library usage in pseudocode:

void firstcallbackFromLib(Framework *framework) {
    MyInterface *myInstance = framework->getInstance();

    {
        Wrapper<MyInterface> wrapperS(myInstance);
        std::shared_ptr<Wrapper<MyInterface>> sharedPtrWrapper = std::make_shared<Wrapper<MyInterface>>(wrapperS);
        //assign sharedPtrWrapper and framework to static instances
    }
}
void myFunction() {
    sharedPtrWrapper->Toggle(); //this doesn't work, this is what i'm trying to achieve
    sharedPtrWrapper->operator->()->Toggle(); //this ugly thing works

}
void lastUninitCallbackFromLibrary() {
    MyInterface *p = sharedPtrWrapper.get()->getInner();
    framework->releaseInterface(p);
    //etc
}


问:
React, Invalid value for prop `component` in Link
I have read another questions about this but in my situation I don't know how to handle it.
I got this warning:

Warning: Invalid value for prop component on  tag. Either remove it from the element, or pass a string or number value to keep it in the DOM.

```<code><Link component={MyLink} to='/summary-upload-tco'>
  <Button>asdas</Button>}
</Link>
</code>```

and

```<code>const MyLink = props => <Link to={props.to} {...props} />;
</code>```

Is there a way then to pass the props component to  with that MyLink defined as it is?

答:
The Link component doesn't accept a component props. If you want to create your own custom Link you can just wrap it and use the useRouteMatch hook as a helper:

Example taken from react-router's DOCS

```<code>// This example show how you could create a custom
// <Link> that renders something special when the URL
// is the same as the one the <Link> points to.

export default function CustomLinkExample() {
  return (
    <Router>
      <div>
        <OldSchoolMenuLink
          activeOnlyWhenExact={true}
          to="/"
          label="Home"
        />
        <OldSchoolMenuLink to="/about" label="About" />

        <hr />

        <Switch>
          <Route exact path="/">
            <Home />
          </Route>
          <Route path="/about">
            <About />
          </Route>
        </Switch>
      </div>
    </Router>
  );
}

function OldSchoolMenuLink({ label, to, activeOnlyWhenExact }) {
  let match = useRouteMatch({
    path: to,
    exact: activeOnlyWhenExact
  });

  return (
    <div className={match ? "active" : ""}>
      {match && "> "}
      <Link to={to}>{label}</Link>
    </div>
  );
}
</code>```

Body:
I have read another questions about this but in my situation I don't know how to handle it.
I got this warning:

Warning: Invalid value for prop component on  tag. Either remove it from the element, or pass a string or number value to keep it in the DOM.

<Link component={MyLink} to='/summary-upload-tco'>
  <Button>asdas</Button>}
</Link>

and

const MyLink = props => <Link to={props.to} {...props} />;

Is there a way then to pass the props component to  with that MyLink defined as it is?

Body:
The Link component doesn't accept a component props. If you want to create your own custom Link you can just wrap it and use the useRouteMatch hook as a helper:

Example taken from react-router's DOCS

// This example show how you could create a custom
// <Link> that renders something special when the URL
// is the same as the one the <Link> points to.

export default function CustomLinkExample() {
  return (
    <Router>
      <div>
        <OldSchoolMenuLink
          activeOnlyWhenExact={true}
          to="/"
          label="Home"
        />
        <OldSchoolMenuLink to="/about" label="About" />

        <hr />

        <Switch>
          <Route exact path="/">
            <Home />
          </Route>
          <Route path="/about">
            <About />
          </Route>
        </Switch>
      </div>
    </Router>
  );
}

function OldSchoolMenuLink({ label, to, activeOnlyWhenExact }) {
  let match = useRouteMatch({
    path: to,
    exact: activeOnlyWhenExact
  });

  return (
    <div className={match ? "active" : ""}>
      {match && "> "}
      <Link to={to}>{label}</Link>
    </div>
  );
}


问:
Combining two columns to generate index in pd Dataframe
Firstly, excuses if this has been asked and answered.
I have looked here and here, went through the titles of recommended duplicates and try to use search engines, but cannot seem to come up with the right keyword.

problem

My problem is the following: given a dataframe with two "identifier" columns, I want to create an index that uniquely describes each combination of values in the two columns:

For instance: column 'a' has value 0, and column 'b' has value '0' and this should get index number 1. Same combinations should map to the same value.

approach

```<code>df = pd.DataFrame({
    'a': np.random.randint(0,3,10),
    'b': np.random.randint(0,3,10),
    'c': np.random.randint(0,10,10)
})

mapping = [(*key, i+1) for i, key in enumerate(df.groupby(by=['a', 'b']).groups.keys())]
crutch = pd.DataFrame(mapping, columns=['a', 'b', 'new_index'])
df = df.merge(crutch, left_on=['a', 'b'], right_on=['a', 'b'])
</code>```

This works, but it seems like there should be something built into pandas that I am missing.

question

So, is there something built into pandas that would help and that I could not figure out?

thanks

Help is greatly appreciated.

Body:
Firstly, excuses if this has been asked and answered.
I have looked here and here, went through the titles of recommended duplicates and try to use search engines, but cannot seem to come up with the right keyword.

problem

My problem is the following: given a dataframe with two "identifier" columns, I want to create an index that uniquely describes each combination of values in the two columns:

For instance: column 'a' has value 0, and column 'b' has value '0' and this should get index number 1. Same combinations should map to the same value.

approach

df = pd.DataFrame({
    'a': np.random.randint(0,3,10),
    'b': np.random.randint(0,3,10),
    'c': np.random.randint(0,10,10)
})

mapping = [(*key, i+1) for i, key in enumerate(df.groupby(by=['a', 'b']).groups.keys())]
crutch = pd.DataFrame(mapping, columns=['a', 'b', 'new_index'])
df = df.merge(crutch, left_on=['a', 'b'], right_on=['a', 'b'])

This works, but it seems like there should be something built into pandas that I am missing.

question

So, is there something built into pandas that would help and that I could not figure out?

thanks

Help is greatly appreciated.

Body:
IIUC, groupby.ngroup

df['new_index'] = df.groupby(['a','b']).ngroup().add(1)
print(df)
   a  b  c  new_index
0  2  1  4          6
1  1  1  5          3
2  1  1  8          3
3  1  1  2          3
4  2  2  8          7
5  2  2  5          7
6  2  0  8          5
7  0  1  7          1
8  1  2  5          4
9  0  2  5          2


问:
How to change the color of all Labels in a UIView in Swift?
I found a similar question here. But the problem is it is in OBJ-C. I do not know the code and am working in SWIFT so please can anyone explain and translate this code in swift.
I am still new to swift so please help me.

Regards

答:
```<code>self.view.subviews.forEach { (view) in    // Loop
     if let label = view as? UILabel {    // check the type
          label.textColor = .red          // assign the color
     }
}
</code>```

And self is your viewController

As explain in the similar question, you have to

Loop through all the UIView's in self.view.subviews and check if it's
  of type UILabel.

Body:
self.view.subviews.forEach { (view) in    // Loop
     if let label = view as? UILabel {    // check the type
          label.textColor = .red          // assign the color
     }
}

And self is your viewController

As explain in the similar question, you have to

Loop through all the UIView's in self.view.subviews and check if it's
  of type UILabel.