问:
alignItem: center not working in a flex container containing a material button
https://codesandbox.io/s/card-material-ui-cqvet?file=/src/index.js

As you can see in this codesandbox.io, the div inside which there's a button doesn't seem to have an effect on the button inside of it as it behaves like a left float for some reason. Is there something I am missing here. I understand that there are several flex box around that container, but in my understanding it should not have any effect on it, or am I wrong?

```<code>button: {
    display: "flex",
    width: "100%",
    alignItems: "center",
    flexDirection: "row"
  }
</code>```

答:
to align along main axis use

justify-content: center

instead of align-items

Body:
https://codesandbox.io/s/card-material-ui-cqvet?file=/src/index.js

As you can see in this codesandbox.io, the div inside which there's a button doesn't seem to have an effect on the button inside of it as it behaves like a left float for some reason. Is there something I am missing here. I understand that there are several flex box around that container, but in my understanding it should not have any effect on it, or am I wrong?

button: {
    display: "flex",
    width: "100%",
    alignItems: "center",
    flexDirection: "row"
  }


来源: stackexchange

问:
Git - Get the version of a library from the url
Suppose I know that a swift library is located at a given url, such as https://github.com/Peter-Schorn/Swift_Utilities. Is there a way to get the latest version tag of the library without downloading it first?

答:
If you know that all of the versions of the library are specified by tags, you can use git ls-remote to read the tags and process the latest version:

```<code>$ git ls-remote https://github.com/Peter-Schorn/Swift_Utilities.git 'refs/tags/*' | \
    grep -v '{}' | tail -n1 | sed 's!.*refs/tags/!!'
2.0.7
</code>```

Note that you may want to use a better sort function than the last item lexicographically, but that's left as an exercise to the reader.

If you want anything more complex (like the latest version on a given branch or non-tagged releases), then you'll either need to clone the repository or use a suitable API for the site you're looking at.

ContentLicense: CC BY-SA 4.0

Body:
If you know that all of the versions of the library are specified by tags, you can use git ls-remote to read the tags and process the latest version:

$ git ls-remote https://github.com/Peter-Schorn/Swift_Utilities.git 'refs/tags/*' | \
    grep -v '{}' | tail -n1 | sed 's!.*refs/tags/!!'
2.0.7

Note that you may want to use a better sort function than the last item lexicographically, but that's left as an exercise to the reader.

If you want anything more complex (like the latest version on a given branch or non-tagged releases), then you'll either need to clone the repository or use a suitable API for the site you're looking at.


问:
How to pick up passengers by capacity? (ANYLOGİC)
While picking up, I want to get as many passengers as the bus capacity, and I have to drop a certain amount of passengers in the drop off, but in the scenario I do, it takes it all and leaves it all.
enter image description here</p>

答:
If you want to pick up all the passengers you want up to the bus capacity, you need to define the pick up block as follows (assuming that the bus agent has a variable or parameter called capacity that defines the capacity of the bus, and if you don't have that variable you need to create it)

You can define your quantity as agent.capacity-container.contents().size()
This means that the pick up will take either the maximum it can take, or whatever amount of passengers there are waiting

If you want to fill the bus waiting for passengers until you have the bus full:

The dropoff has similar conditions you can use to define how many passengers to drop off... You need to explore that yourself depending on what you want.


问:
Property 'XYZ' does not exist on type 'Readonly<{ children?: ReactNode; }> & Readonly<{}>'
I get a syntax error when trying to access .props for the both the RecipeList.js and Recipe.js.

Here is a code sample for Recipe.js:

```<code>import React, {Component} from 'react';
import "./Recipe.css";

class Recipe extends Component {

    // props: any; uncommenting this will fix the bug

    render() {
        // don't have to use return and parentheses for arrow with JSX
        const ingredients = this.props.ingredients.map((ing, ind) => (
            <li key={ind}>{ing}</li>
        ));
        const {title, img, instructions} = this.props

        return (
            <div className="recipe-card">
                <div className="recipe-card-img">
                    <img src={img} alt={title}/>
                </div>
                <div className="recipe-card-content">
                    <h3 className="recipe-title">
                        {title}
                    </h3>
                    <h4>
                        Ingredients:
                    </h4>
                    <ul>
                        {ingredients}
                    </ul>
                    <h4>
                        Instructions:
                    </h4>
                    <p>
                        {instructions}
                    </p>
                </div>
            </div>
        )
    }
}
</code>```

Screenshot of .props error

However, the project throws no compile-time errors and the website works perfectly fine.

Screenshot of app working fine with no chrome console or terminal errors

I'm thinking this less has to do with my code and more so with TypeScript or some sort of preset config with Javascript for VScode having trouble identifying the .props property for each component because I get similar problems when I built the React Tutorial Project into my editor (I even copy pasted the final index.js code from the site just to be sure), despite the app working fine with no compile-time errors.

Screenshot of the same .prop errors after following React Tutorial

The only way to solve this problem is if I actually hardcode and create a props property for each class and set it to any like so:

Screenshot of only solution to the syntax error

Here are my updated dependencies

```<code>"dependencies": {
  "@types/react": "^16.4.13",
  "prop-types": "^15.6.2",
  "react": "^16.5.0",
  "react-dom": "^16.5.0",
  "react-scripts": "1.1.5",
  "typescript": "^3.0.3"
 }
</code>```

答:
Basing on Klugjos answer. You could do the same with React's functional component (FC) and use the useState Hook to manage the state.

```<code>import React, {FC} from 'react';
import "./Recipe.css";

interface IRecipeProps {
  ingredients?: string[];
  title?: string;
  img?: string;
  instructions?: string;
}

interface IRecipeState {
}

const Recipe:FC<IRecipeProps> = (props) => {

    const { ingredients, title, img, instructions} = props;

    ingredients.map(( ingredient, index) => (
        <li key={index}>
          { ingredient}
        </li>
    ));

    return (
        <div className="recipe-card">
            Your render code here
        </div>
    )
}
</code>```

Body:
I get a syntax error when trying to access .props for the both the RecipeList.js and Recipe.js.

Here is a code sample for Recipe.js:

import React, {Component} from 'react';
import "./Recipe.css";

class Recipe extends Component {

    // props: any; uncommenting this will fix the bug

    render() {
        // don't have to use return and parentheses for arrow with JSX
        const ingredients = this.props.ingredients.map((ing, ind) => (

{ing}

        ));
        const {title, img, instructions} = this.props

        return (

                        {title}

                        Ingredients:

                        {ingredients}

                        Instructions:

                        {instructions}

        )
    }
}

Screenshot of .props error

However, the project throws no compile-time errors and the website works perfectly fine.

Screenshot of app working fine with no chrome console or terminal errors

I'm thinking this less has to do with my code and more so with TypeScript or some sort of preset config with Javascript for VScode having trouble identifying the .props property for each component because I get similar problems when I built the React Tutorial Project into my editor (I even copy pasted the final index.js code from the site just to be sure), despite the app working fine with no compile-time errors.

Screenshot of the same .prop errors after following React Tutorial

The only way to solve this problem is if I actually hardcode and create a props property for each class and set it to any like so:

Screenshot of only solution to the syntax error

Here are my updated dependencies

"dependencies": {
  "@types/react": "^16.4.13",
  "prop-types": "^15.6.2",
  "react": "^16.5.0",
  "react-dom": "^16.5.0",
  "react-scripts": "1.1.5",
  "typescript": "^3.0.3"
 }

Body:
Basing on Klugjos answer. You could do the same with React's functional component (FC) and use the useState Hook to manage the state.

import React, {FC} from 'react';
import "./Recipe.css";

interface IRecipeProps {
  ingredients?: string[];
  title?: string;
  img?: string;
  instructions?: string;
}

interface IRecipeState {
}

const Recipe:FC<IRecipeProps> = (props) => {

    const { ingredients, title, img, instructions} = props;

    ingredients.map(( ingredient, index) => (
        <li key={index}>
          { ingredient}
        </li>
    ));

    return (
        <div className="recipe-card">
            Your render code here
        </div>
    )
}


问:
How do I access the Connection-specific DNS Suffix for each NetworkInterface in Java?
Is it possible within a Java program to access the string contained in the "Connection-specific DNS Suffix" field of a Windows machine's ipconfig /all output?

Eg:

C:>ipconfig /all

Ethernet adapter Local Area Connection:

```<code>    Connection-specific DNS Suffix  . : myexample.com  <======== This string
    Description . . . . . . . . . . . : Broadcom NetXtreme Gigabit Ethernet
    Physical Address. . . . . . . . . : 00-30-1B-B2-77-FF
    Dhcp Enabled. . . . . . . . . . . : Yes
    Autoconfiguration Enabled . . . . : Yes
    IP Address. . . . . . . . . . . . : 192.168.1.66
    Subnet Mask . . . . . . . . . . . : 255.255.255.0
</code>```

I know that getDisplayName() will get return the Description (Eg: Broadcom NetXtreme Gigabit Ethernet above) and that getInetAddresses() will give me a list of the IP addresses bound to this network interface.

But are there also ways of reading the "Connection-specific DNS Suffix"?

答:
Ok so I figured out how to do this on Windows XP and Windows 7:

The string (eg: myexample.com)
contained in the Connection-specific
DNS Suffix field of each network
interface listed in the output of
ipconfig /all can be found in the
registry at
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces{GUID}
(where GUID is the GUID of the
network interface of interest) as the
string value (type REG_SZ) named DhcpDomain.

Accessing windows registry keys is not straightforward in Java but by some clever use of reflection it is possible to access the required network adaptor's key found under HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces\ and then read the string data element with name DhcpDomain; its value is the required string.

See the following links for examples
of accessing the windows registry
from Java:

http://www.rgagnon.com/javadetails/java-0630.html

http://lenkite.blogspot.com/2008/05/access-windows-registry-using-java.html

ContentLicense: CC BY-SA 3.0

Body:
Is it possible within a Java program to access the string contained in the "Connection-specific DNS Suffix" field of a Windows machine's ipconfig /all output?

Eg:

C:>ipconfig /all

Ethernet adapter Local Area Connection:

    Connection-specific DNS Suffix  . : myexample.com  <======== This string
    Description . . . . . . . . . . . : Broadcom NetXtreme Gigabit Ethernet
    Physical Address. . . . . . . . . : 00-30-1B-B2-77-FF
    Dhcp Enabled. . . . . . . . . . . : Yes
    Autoconfiguration Enabled . . . . : Yes
    IP Address. . . . . . . . . . . . : 192.168.1.66
    Subnet Mask . . . . . . . . . . . : 255.255.255.0

I know that getDisplayName() will get return the Description (Eg: Broadcom NetXtreme Gigabit Ethernet above) and that getInetAddresses() will give me a list of the IP addresses bound to this network interface.

But are there also ways of reading the "Connection-specific DNS Suffix"?


问:
Pandas Detect Non-Numberic Data types
I need to detect and prevent any non-numeric data getting into my dataframe.

example:

```<code>     value       in       out     transf      inc        buy
0   208372  4206.84   4692.22     215976   725.41  105339.92
1      abs     0.00   1270.28      13602  1151.29       0.00
2   230172     0.00   1930.40      21539  1938.59       0.00
3   394391     0.00  11517.96     174320  1517.06  170032.09
4   382101     0.00   2962.82          0  3001.14   10000.00
</code>```

print(df.dtypes) gives me this:

```<code>value         object
in           float64
out          float64
transf         int64
inc          float64
buy          float64
dtype: object
</code>```

So how do I detect if there are any non-number (float64, int64) datatype?

Thank you.

答:
Try with pd.to_numeric, it will change the non numeric to NaN. Then we just need detect the NaN with isna or isnull

```<code>df.apply(pd.to_numeric,errors='coerce')
      value       in       out  transf      inc        buy
0  208372.0  4206.84   4692.22  215976   725.41  105339.92
1       NaN     0.00   1270.28   13602  1151.29       0.00
2  230172.0     0.00   1930.40   21539  1938.59       0.00
3  394391.0     0.00  11517.96  174320  1517.06  170032.09
4  382101.0     0.00   2962.82       0  3001.14   10000.00
</code>```

Let us add

```<code>df.apply(pd.to_numeric,errors='coerce').isnull().any().any()
</code>```

If True should be a problem , if False should be ok

Title: Pandas Detect Non-Numberic Data types

Body:
I need to detect and prevent any non-numeric data getting into my dataframe.

example:

     value       in       out     transf      inc        buy
0   208372  4206.84   4692.22     215976   725.41  105339.92
1      abs     0.00   1270.28      13602  1151.29       0.00
2   230172     0.00   1930.40      21539  1938.59       0.00
3   394391     0.00  11517.96     174320  1517.06  170032.09
4   382101     0.00   2962.82          0  3001.14   10000.00

print(df.dtypes) gives me this:

value         object
in           float64
out          float64
transf         int64
inc          float64
buy          float64
dtype: object

So how do I detect if there are any non-number (float64, int64) datatype?

Thank you.

Body:
Try with pd.to_numeric, it will change the non numeric to NaN. Then we just need detect the NaN with isna or isnull

df.apply(pd.to_numeric,errors='coerce')
      value       in       out  transf      inc        buy
0  208372.0  4206.84   4692.22  215976   725.41  105339.92
1       NaN     0.00   1270.28   13602  1151.29       0.00
2  230172.0     0.00   1930.40   21539  1938.59       0.00
3  394391.0     0.00  11517.96  174320  1517.06  170032.09
4  382101.0     0.00   2962.82       0  3001.14   10000.00

Let us add

df.apply(pd.to_numeric,errors='coerce').isnull().any().any()

If True should be a problem , if False should be ok


问:
How can I copy a tweet into python and print it out?
I'm trying to copy text in a tweet from Twitter and then assign it to the word "tweet" to then modify it</p>

答:
If you are trying to create a string, you just need to write the text in quotation marks and assign it to the variable tweet. You assign a string to a variable by using the equal sign followed by the text in quotation marks. You can do that like this:</p>

```<code>tweet = "text from twitter"
</code>```

Body:
If you are trying to create a string, you just need to write the text in quotation marks and assign it to the variable tweet. You assign a string to a variable by using the equal sign followed by the text in quotation marks. You can do that like this:

tweet = "text from twitter"


问:
Scaling down video conference software in Kubernetes
I'm planning to deploy a WebRTC custom videoconference software (based on NodeJS, using websockets) with Kubernetes, but I have some doubts about scaling down this environment.

Actually, I'm planning to use cloud hosted Kubernetes (GKE, EKS, AKS or any) to be able to auto-scale nodes in the cluster to attend the demand increase and decrease. But, scaling up is not the problem, but it's about scaling down.

The cluster will scale down based on some CPU average usage metrics across the cluster, as I understand, and if it tries to remove some node, it will start to drain connections and stop receiving new connections, right? But now, imagine that there's a videoconference still running in this "pending deletion" node. There are two problems:

1 - Stopping the node before the videoconference finishes (it will drop the meeting)

2 - With the draining behaviour when it starts to scale down, it will stop receiving new connections, so if someone tries to join in this running video conference, it will receive a timeout, right?

So, which is the best strategy to scale down nodes for a video conference solution? Any ideas?

Thanks

答:
There is no best strategy at your use case. When a cloud provider scales down, it is going to get one node randomly and kill it. It's not going to check whether this node has less resource consumption, so let's kill this one. It might end up killing the node with most pods running on it.

I would focus on how you want to schedule your pods. I would try to schedule them, if possible, on a node with running pods already (Pod inter-affinity), and would set up a Pod Disruption Budget to all Deployments/StatefulSets/etc (depending on how you want to run the pods). As a result it would only scale down when there are no pods running on a specific node, and it would kill that node, because on the other nodes there are pods; protected by a PDB.


问:
Close `showModalBottomSheet` after a timeout
I tried to close showModalBottomSheet widget through an event listener.

```<code>          showModalBottomSheet(
              useRootNavigator: true,
              context: context,
              builder: (newcontext) {
                return MyBottomDialog();
              });
</code>```

I tried to close this through an event listener:

```<code>class _MyBottomDialogState extends State<MyBottomDialog> {
...
...
  void initState() {
    _myEventStream.listen((state) {
      if (state == 'timeout') {
        Navigator.of(context, rootNavigator: true).pop();
      }
    });
    super.initState();
  }

</code>```

```<code>TypeError: Cannot read property 'findAncestorStateOfType' of null
.
.
.
Looking up a deactivated widget's ancestor is unsafe.
At this point the state of the widget's element tree is no longer stable.
To safely refer to a widget's ancestor in its dispose() method, save a
reference to the ancestor by calling dependOnInheritedWidgetOfExactType() in
the widget's didChangeDependencies() method.
</code>```

How do I achieve this?

答: The stream class actually comes with a timeout method. You just have to feed it a duration and if it exceeds that duration it throws a TimeoutException. Wrap the execution in a try block and call the close modal sheet method from the on TimeoutException catch (e) block perhaps.

Body:
I tried to close showModalBottomSheet widget through an event listener.

          showModalBottomSheet(
              useRootNavigator: true,
              context: context,
              builder: (newcontext) {
                return MyBottomDialog();
              });

I tried to close this through an event listener:

class _MyBottomDialogState extends State<MyBottomDialog> {
...
...
  void initState() {
    _myEventStream.listen((state) {
      if (state == 'timeout') {
        Navigator.of(context, rootNavigator: true).pop();
      }
    });
    super.initState();
  }

TypeError: Cannot read property 'findAncestorStateOfType' of null
.
.
.
Looking up a deactivated widget's ancestor is unsafe.
At this point the state of the widget's element tree is no longer stable.
To safely refer to a widget's ancestor in its dispose() method, save a
reference to the ancestor by calling dependOnInheritedWidgetOfExactType() in
the widget's didChangeDependencies() method.

How do I achieve this?


问:
Pass command line arguments via sbatch
Suppose that I have the following simple bash script which I want to submit to a batch server through SLURM:

```<code>#!/bin/bash

#SBATCH -o "outFile"$1".txt"
#SBATCH -e "errFile"$1".txt"

hostname

exit 0
</code>```

In this script, I simply want to write the output of hostname on a textfile whose full name I control via the command-line, like so:

```<code>login-2:jobs$ sbatch -D `pwd` exampleJob.sh 1
Submitted batch job 203775
</code>```

Unfortunately, it seems that my last command-line argument (1) is not parsed through sbatch, since the files created do not have the suffix I'm looking for and the string "$1" is interpreted literally:

```<code>login-2:jobs$ ls
errFile$1.txt  exampleJob.sh outFile$1.txt
</code>```

I've looked around places in SO and elsewhere, but I haven't had any luck. Essentially what I'm looking for is the equivalent of the -v switch of the qsub utility in Torque-enabled clusters.

Edit: As mentioned in the underlying comment thread, I solved my problem the hard way: instead of having one single script that would be submitted several times to the batch server, each with different command line arguments, I created a "master script" that simply echoed and redirected the same content onto different scripts, the content of each being changed by the command line parameter passed. Then I submitted all of those to my batch server through sbatch. However, this does not answer the original question, so I hesitate to add it as an answer to my question or mark this question solved.

答:
This is an old question but I just stumbled into the same task and I think this solution is simpler:

Let's say I have the variable $OUT_PATH in the bash script launch_analysis.bash and I want to pass this variable to task_0_generate_features.sl which is my SLURM file to send the computation to a batch server. I would have the following in launch_analysis.bash:

`sbatch --export=OUT_PATH=$OUT_PATH task_0_generate_features.sl`
```

<p>Which is directly accessible in <code>task_0_generate_features.sl</code></p>

<p>In @Jason case we would have:</p>

<pre class="lang-sh prettyprint-override"><code>sbatch -D `pwd` --export=hostname=$hostname exampleJob.sh
</code>```

Reference: Using Variables in SLURM Jobs

Title: Pass command line arguments via sbatch

Body:
Suppose that I have the following simple bash script which I want to submit to a batch server through SLURM:

#!/bin/bash

#SBATCH -o "outFile"$1".txt"
#SBATCH -e "errFile"$1".txt"

hostname

exit 0

In this script, I simply want to write the output of hostname on a textfile whose full name I control via the command-line, like so:

login-2:jobs$ sbatch -D `pwd` exampleJob.sh 1
Submitted batch job 203775

Unfortunately, it seems that my last command-line argument (1) is not parsed through sbatch, since the files created do not have the suffix I'm looking for and the string "$1" is interpreted literally:

login-2:jobs$ ls
errFile$1.txt  exampleJob.sh outFile$1.txt

I've looked around places in SO and elsewhere, but I haven't had any luck. Essentially what I'm looking for is the equivalent of the -v switch of the qsub utility in Torque-enabled clusters.

Edit: As mentioned in the underlying comment thread, I solved my problem the hard way: instead of having one single script that would be submitted several times to the batch server, each with different command line arguments, I created a "master script" that simply echoed and redirected the same content onto different scripts, the content of each being changed by the command line parameter passed. Then I submitted all of those to my batch server through sbatch. However, this does not answer the original question, so I hesitate to add it as an answer to my question or mark this question solved.

Body:
This is an old question but I just stumbled into the same task and I think this solution is simpler:

Let's say I have the variable $OUT_PATH in the bash script launch_analysis.bash and I want to pass this variable to task_0_generate_features.sl which is my SLURM file to send the computation to a batch server. I would have the following in launch_analysis.bash:

`sbatch --export=OUT_PATH=$OUT_PATH task_0_generate_features.sl`

Which is directly accessible in task_0_generate_features.sl

In @Jason case we would have:

sbatch -D `pwd` --export=hostname=$hostname exampleJob.sh

Reference: Using Variables in SLURM Jobs


问:
R.id Cannot be resolved
I guess something should be done with the Android-Manifest.xml file or something in the layout folder. I am new to Android so I don't know what I should write.</p>

```<code>public class AndroidPong extends Activity implements  OnClickListener {
    static String tag;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super .onCreate(savedInstanceState);

        tag = getResources().getString(R.string.app_name);
        fullScreen();
        splashScreen();
    }

    @Override
    protected Dialog onCreateDialog(int id) {
        // TODO Auto-generated method stub
        return super .onCreateDialog(id);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // TODO Auto-generated method stub
        return super .onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // TODO Auto-generated method stub
        return super .onOptionsItemSelected(item);
    }

    @Override
    protected void onStop() {
        // TODO Auto-generated method stub
        super .onStop();
    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super .onDestroy();
    }

    void startGame() {
        setContentView(R.layout.game);// error
        this .findViewById(R.id.Button01).setOnClickListener(this );//error
        this .findViewById(R.id.Button02).setOnClickListener(this );//Error
    }

    void splashScreen() {
        setContentView(R.layout.splash);// error
        this .findViewById(R.id.pongtable).setOnClickListener(this );//error
    }

    void gameMenu() {

    }

    void fullScreen() {
        this .requestWindowFeature(Window.FEATURE_NO_TITLE);
        this .getWindow().setFlags(
                WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }

    public static void debug(String debug) {
        Log.d(tag, debug);
    }

<?xml version="1.0" encoding="utf-8"?>
<absoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="fill_parent"
     android:layout_height="fill_parent">

<Button android:id="@+id/Button01"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"

<Button android:id="+id/Button02"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
 </absoluteLayout>
</code>```

答:
Some tricks:

You were able to use R.id before, then clean project and build it again. I don't recommend build automatically.

In project properties you can order your /gen folder before your /src folder. This will cause gen folder to be compiled first, so R will be first generated and your changes could be reflect.

Ensure that you haven't got any other kind of compilation errors.

Title: R.id Cannot be resolved

Body:
I guess something should be done with the Android-Manifest.xml file or something in the layout folder. I am new to Android so I don't know what I should write.

public class AndroidPong extends Activity implements  OnClickListener {
    static String tag;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super .onCreate(savedInstanceState);

        tag = getResources().getString(R.string.app_name);
        fullScreen();
        splashScreen();
    }

    @Override
    protected Dialog onCreateDialog(int id) {
        // TODO Auto-generated method stub
        return super .onCreateDialog(id);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // TODO Auto-generated method stub
        return super .onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // TODO Auto-generated method stub
        return super .onOptionsItemSelected(item);
    }

    @Override
    protected void onStop() {
        // TODO Auto-generated method stub
        super .onStop();
    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super .onDestroy();
    }

    void startGame() {
        setContentView(R.layout.game);// error
        this .findViewById(R.id.Button01).setOnClickListener(this );//error
        this .findViewById(R.id.Button02).setOnClickListener(this );//Error
    }

    void splashScreen() {
        setContentView(R.layout.splash);// error
        this .findViewById(R.id.pongtable).setOnClickListener(this );//error
    }

    void gameMenu() {

    }

    void fullScreen() {
        this .requestWindowFeature(Window.FEATURE_NO_TITLE);
        this .getWindow().setFlags(
                WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }

    public static void debug(String debug) {
        Log.d(tag, debug);
    }

<?xml version="1.0" encoding="utf-8"?>
<absoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="fill_parent"
     android:layout_height="fill_parent">

<Button android:id="@+id/Button01"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"

<Button android:id="+id/Button02"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
 </absoluteLayout>


问:
Updating SQL table converting varchar to int
I currently have a table new_funeralhomes as below, which has the new data i wish to add to another table:

,

Within that table, i can easily send address,postal,phone, website and email to this table addressTest:

.

However as you can see by the new_funeralhomes table, the city/state are text value and in the second table (addressTest) they are int values connecting to these tables:

city:

,

province:

.

How would i go about updating the addressTest table with the new city and province? The iid and id values match up and are the same throughout.

Im newer to this so any help would be appreciated, thank you.

答:
You seem to be looking for an insert ... select  statement with joins. The logic is:

```<code>insert into addressTest
    (address, province, postcalcode, city, primaryphone, secondaryphoe, website)
select
    n.address
    p.id,
    n.postcal,
    c.id,
    n.phone,
    n.phone2,
    n.website
from new_funeralhomes n
inner join city c on c.name = n.city
inner join province p on p.name = n.state
</code>```

Side note: it seems like the source table has less columns than the target; I adapted the column list for what seem to be the matching columns - you might need to review that so it properly matches your requirement (but the join logic, which is the heart of your question, stays the same).

Body:
You seem to be looking for an insert ... select  statement with joins. The logic is:

insert into addressTest
    (address, province, postcalcode, city, primaryphone, secondaryphoe, website)
select
    n.address
    p.id,
    n.postcal,
    c.id,
    n.phone,
    n.phone2,
    n.website
from new_funeralhomes n
inner join city c on c.name = n.city
inner join province p on p.name = n.state

Side note: it seems like the source table has less columns than the target; I adapted the column list for what seem to be the matching columns - you might need to review that so it properly matches your requirement (but the join logic, which is the heart of your question, stays the same).


问:
How solve bidirectional relationships on JSONB serialization?
I'm trying to serialize an entity with have a bidirectional relationship:

```<code>class TypeA {
  String name;
  TypeB typeB;
}

class TypeB {
  String identifier;
  TypeA typeA;
}
</code>```

With Jackson I solve with @JsonBackReference in typeB attribute and @JsonManagedReference in typeA attribute, but how i can do this on JSONB (Eclipse Yasson implementation)?

```<code>Caused by: javax.json.bind.JsonbException: Recursive reference has been found in class class xxxxxx.model.Analysis.
        at org.eclipse.yasson.internal.serializer.ObjectSerializer.serializeInternal(ObjectSerializer.java:76)
        at org.eclipse.yasson.internal.serializer.AbstractContainerSerializer.serialize(AbstractContainerSerializer.java:107)
        at org.eclipse.yasson.internal.serializer.AbstractContainerSerializer.serializerCaptor(AbstractContainerSerializer.java:125)
        at org.eclipse.yasson.internal.serializer.ObjectSerializer.marshallProperty(ObjectSerializer.java:121)
        at org.eclipse.yasson.internal.serializer.ObjectSerializer.serializeInternal(ObjectSerializer.java:69)
        ... 45 more
</code>```

OBS: I solved with a DTO but the doubt stayed.

答:
For solving the circular structure you should use @JsonbTransient. As stated in documentation [0]:

By default, JSONB ignores properties with a non public access. All public properties - either public fields or non public fields with public getters are serialized into JSON text.

Class properties annotated with @JsonbTransient annotation are ignored by JSON Binding engine.

[0]: http://json-b.net/docs/user-guide.html#ignoring-properties

Body:
I'm trying to serialize an entity with have a bidirectional relationship:

class TypeA {
  String name;
  TypeB typeB;
}

class TypeB {
  String identifier;
  TypeA typeA;
}

With Jackson I solve with @JsonBackReference in typeB attribute and @JsonManagedReference in typeA attribute, but how i can do this on JSONB (Eclipse Yasson implementation)?

Caused by: javax.json.bind.JsonbException: Recursive reference has been found in class class xxxxxx.model.Analysis.
        at org.eclipse.yasson.internal.serializer.ObjectSerializer.serializeInternal(ObjectSerializer.java:76)
        at org.eclipse.yasson.internal.serializer.AbstractContainerSerializer.serialize(AbstractContainerSerializer.java:107)
        at org.eclipse.yasson.internal.serializer.AbstractContainerSerializer.serializerCaptor(AbstractContainerSerializer.java:125)
        at org.eclipse.yasson.internal.serializer.ObjectSerializer.marshallProperty(ObjectSerializer.java:121)
        at org.eclipse.yasson.internal.serializer.ObjectSerializer.serializeInternal(ObjectSerializer.java:69)
        ... 45 more

OBS: I solved with a DTO but the doubt stayed.


问:
Unable to authenticate mongodb from springboot application
I am using a spring boot application to connect MongoDB instance. We have enabled authentication on MongoDB with following roles

roles: [ { role: "dbOwner", db: "{{ mongo.database_name }}" }

roles: [ { role: "readWrite", db: "{{ mongo.database_name }}" }

We are providing the credential using conf files

data:

mongodb.uri: mongodb://127.0.0.1/testDB

mongodb.authentication-database: admin

mongodb.username: 'admin'

mongodb.password: 'admin'

repositories.enabled: true

While booting the application, we are inserting in a particular collection. However during the insertion, it tried to create index and fails with following exception

org.springframework.data.mongodb.UncategorizedMongoDbException:
 { "serverUsed" : "localhost:27017" , "ok" : 0.0 , "errmsg" : "not authorized on testDB to execute command
 { createIndexes: \"ws.city\", indexes: [ { name: \"code\", ns: \"testDB.ws.city\", unique: true, key: { code: 1 } } ] }" , "code" : 13};

FULL stacktrace:

Unsatisfied dependency expressed through constructor argument with index 0 of type [XYZRepository]:
   : Error creating bean with name 'XYZRepository': Invocation of init method failed;
   nested exception is org.springframework.data.mongodb.UncategorizedMongoDbException:
   { "serverUsed" : "localhost:27017" , "ok" : 0.0 , "errmsg" : "not authorized on testDB to execute command
   { createIndexes: \"ws.city\", indexes: [ { name: \"code\", ns: \"testDB.ws.city\", unique: true, key: { code: 1 } } ] }" , "code" : 13};
    nested exception is com.mongodb.CommandFailureException: { "serverUsed" : "localhost:27017" , "ok" : 0.0 ,
    "errmsg" : "not authorized on testDB to execute command { createIndexes: \"ws.city\", indexes: [ { name: \"code\", ns: \"testDB.ws.city\", unique: true, key: { code: 1 } } ] }" , "code" : 13};
    nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'XYZRepository':
    Invocation of init method failed; nested exception is org.springframework.data.mongodb.UncategorizedMongoDbException:
    { "serverUsed" : "localhost:27017" , "ok" : 0.0 ,
    "errmsg" : "not authorized on testDB to execute command { createIndexes: \"ws.city\", indexes: [ { name: \"code\", ns: \"testDB.ws.city\", unique: true, key: { code: 1 } } ] }" , "code" : 13};
    nested exception is com.mongodb.CommandFailureException: { "serverUsed" : "localhost:27017" , "ok" : 0.0 , "errmsg" : "not authorized on testDB to execute command
     { createIndexes: \"ws.city\", indexes: [ { name: \"code\", ns: \"testDB.ws.city\", unique: true, key: { code: 1 } } ] }" , "code" : 13}
      at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:749)
      at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:185)
      at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1143)
      at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1046)
      at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:510)
      at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
      at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
      at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
      at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
      at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
      at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:772)
      at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:839)
      at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:538)
      at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:118)
      at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:764)
      at org.springframework.boot.SpringApplication.doRun(SpringApplication.java:357)
      at org.springframework.boot.SpringApplication.run(SpringApplication.java:305)
      at org.springframework.boot.SpringApplication.run(SpringApplication.java:1124)
      at org.springframework.boot.SpringApplication.run(SpringApplication.java:1113)
      at com.app.ws.WSApplication.main(WSApplication.java:22)
      at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
      at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
      at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
      at java.lang.reflect.Method.invoke(Method.java:498)
      at org.springframework.boot.loader.MainMethodRunner.run(MainMethodRunner.java:53)
      at java.lang.Thread.run(Thread.java:745)

Ideally, I understand that the role which should be required for an application to interact with mongodb should be "readWrite".

Does it expects a different role?

Does the spring tries to create index automatically while inserting and require higher / different role?

Anything which we are missing in this scenario?

We are using mongoDB latest version : 3.2.4
Springboot 1.3.1

答:
This answer worked for me, as mine was a standalone mongo, refer docs, For a standalone that enforces access control.</p>

```<code>mongodb://myDBReader:D1fficultP%40ssw0rd@mongodb0.example.com:27017/?authSource=admin
</code>```

Body:
This answer worked for me, as mine was a standalone mongo, refer docs, For a standalone that enforces access control.

mongodb://myDBReader:D1fficultP%40ssw0rd@mongodb0.example.com:27017/?authSource=admin


问:
grep inverse read match pattern from two files
I have a file (note that some lines have more than 2 columns, also some lines are 1 space delimited, and some are multiple space delimited, this file is quite large...)

```<code> file1.txt:
there is a line here that has more than two columns
## this line is a comment
blahblah:     blahblahSierraexample7272
foo: foo@foobar.com
nonsense:                    nonsense59s59S
nonsense:   someRandomColumn
.....
</code>```

I have another file that is a subset of file1.txt, this file has two columns only and columns are "1" space delimited!

```<code>file2.txt
foo: foo@foo.com
nonsense: nonsense59s59S
</code>```

now, I would like to delete all lines that appear in file2.txt from file1.txt, how can I do that in a shell script? note that the second file (file2.txt) has two columns only, while file1.txt has multiple... so if a matching needs to be done it should be like: $1(from file2) match $1(from file1) and $NF(from file2) match $NF(from file1) and then inverse the match and print...

P.S. already tried grep -vf file2.txt file1.txt but since the space between column1 and $NF is not fixed it didn't work...
sed and awk should do the trick but can't come up with the code...

```<code>sed -i '/^<firstColumnOfFile2> .* <lastColumnOfFile2>$/d' file1.txt (perhaps in a while loop!)
</code>```

or something like: grep -vw -f ^[(1stColofFile2)] and also [(lastColOfFile2)]$ file1.txt

答:
```<code>$ awk 'NR==FNR{a[$0]; next} {orig=$0; $1=$1} !($0 in a){print orig}' file2 file1
there is a line here that has more than two columns
## this line is a comment
blahblah:     blahblahSierraexample7272
foo: foo@foobar.com
nonsense:   someRandomColumn
.....
</code>```

Body:
I have a file (note that some lines have more than 2 columns, also some lines are 1 space delimited, and some are multiple space delimited, this file is quite large...)

 file1.txt:
there is a line here that has more than two columns
## this line is a comment
blahblah:     blahblahSierraexample7272
foo: foo@foobar.com
nonsense:                    nonsense59s59S
nonsense:   someRandomColumn
.....

I have another file that is a subset of file1.txt, this file has two columns only and columns are "1" space delimited!

file2.txt
foo: foo@foo.com
nonsense: nonsense59s59S

now, I would like to delete all lines that appear in file2.txt from file1.txt, how can I do that in a shell script? note that the second file (file2.txt) has two columns only, while file1.txt has multiple... so if a matching needs to be done it should be like: $1(from file2) match $1(from file1) and $NF(from file2) match $NF(from file1) and then inverse the match and print...

P.S. already tried grep -vf file2.txt file1.txt but since the space between column1 and $NF is not fixed it didn't work...
sed and awk should do the trick but can't come up with the code...

sed -i '/^<firstColumnOfFile2> .* <lastColumnOfFile2>$/d' file1.txt (perhaps in a while loop!)

or something like: grep -vw -f ^[(1stColofFile2)] and also [(lastColOfFile2)]$ file1.txt


问:
How can I define a function to create a variable with an especific name based on another variable? (Python 3)
Example:

x = 5

list(I want to place the value of x here, in the name of this variable) = 1

P.S.: I know that I can't use parentheses in this case.

so I could do:

print(list5)

and return 1

答:
Generally, as other comments have described, you should not be dynamically creating variables as it shouldn’t be done in general for reasons outlined by the comments. Assuming you still want to do it anyways for whatever reason here’s the code:</p>

```<code> exec “list” + str(x) + “ = 1”
</code>```

Body:
Generally, as other comments have described, you should not be dynamically creating variables as it shouldn’t be done in general for reasons outlined by the comments. Assuming you still want to do it anyways for whatever reason here’s the code:

 exec “list” + str(x) + “ = 1”


问:
Add Attribute to Select Field in Rails
I'm using Slim Select for my select fields in my Rails 6 app. In order to allow users to select multiple options in the select, I have to add the attribute multiple to my select tag.

So it renders HTML, like: <select id="foo" multiple>.

How do I get multiple to show in the select tag?

I've read:

rails select tag with multiple values pre selected

Add attribute to rails helper text field?

Ruby on Rails -- multiple selection in f.select

And I've tried:

```<code><%= f.collection_select :foo, Tag.order(:name),:id,:name, include_blank: true, :html => 'multiple' %>

<%= f.collection_select :foo, Tag.order(:name),:id,:name, include_blank: true, input_html: { data: { multiple: "required"} } %>

<%= f.collection_select :foo, Tag.order(:name),:id,:name, include_blank: true, :html => {:multiple => true}  %>

<%= f.collection_select :foo, Tag.order(:name),:id,:name, include_blank: true, multiple: true %>

<%= f.collection_select :foo, Tag.order(:name),:id,:name, include_blank: true, :multiple => true %>
</code>```

However, none of these add multiple in the select tag.

答:
make sure :foo is an array that can save multiple ids, and put multiple: true as follow</p>

```<code><%= f.collection_select :foo, Tag.order(:name),:id,:name, {} , {multiple: true, class: '...'} %>
</code>```

Title: Add Attribute to Select Field in Rails

Body:
I'm using Slim Select for my select fields in my Rails 6 app. In order to allow users to select multiple options in the select, I have to add the attribute multiple to my select tag.

So it renders HTML, like: <select id="foo" multiple>.

How do I get multiple to show in the select tag?

I've read:

rails select tag with multiple values pre selected

Add attribute to rails helper text field?

Ruby on Rails -- multiple selection in f.select

And I've tried:

<%= f.collection_select :foo, Tag.order(:name),:id,:name, include_blank: true, :html => 'multiple' %>

<%= f.collection_select :foo, Tag.order(:name),:id,:name, include_blank: true, input_html: { data: { multiple: "required"} } %>

<%= f.collection_select :foo, Tag.order(:name),:id,:name, include_blank: true, :html => {:multiple => true}  %>

<%= f.collection_select :foo, Tag.order(:name),:id,:name, include_blank: true, multiple: true %>

<%= f.collection_select :foo, Tag.order(:name),:id,:name, include_blank: true, :multiple => true %>

However, none of these add multiple in the select tag.

Body:
make sure :foo is an array that can save multiple ids, and put multiple: true as follow

<%= f.collection_select :foo, Tag.order(:name),:id,:name, {} , {multiple: true, class: '...'} %>


答:
You can't.

That's not really true, but for almost every single case where this question is asked, the answer is either "you can't do what you want" or "what you want to do is use a list".

You mention having a variable named list5. So maybe what you really want is a list-of-lists or something. Have a look at the Python Data Structures tutorial to see if something there matches the problem you're trying to solve.

Here are some things you might try. These use nested comprehensions, but you don't have to do that -- you can just type out an initializer if you want.

```<code>list_of_lists = [[i ** 2 for i in range(j + 1, j * 2)] for j in range(5)]

dict_of_lists = { 'list' + str(j): [i ** 2 for i in range(j + 1, j * 2)]
                  for j in range(5)
                }
</code>```

Title: How can I define a function to create a variable with an especific name based on another variable? (Python 3)

Body:
Example:

x = 5

list(I want to place the value of x here, in the name of this variable) = 1

P.S.: I know that I can't use parentheses in this case.

so I could do:

print(list5)

and return 1

Body:
You can't.

That's not really true, but for almost every single case where this question is asked, the answer is either "you can't do what you want" or "what you want to do is use a list".

You mention having a variable named list5. So maybe what you really want is a list-of-lists or something. Have a look at the Python Data Structures tutorial to see if something there matches the problem you're trying to solve.

Here are some things you might try. These use nested comprehensions, but you don't have to do that -- you can just type out an initializer if you want.

list_of_lists = [[i ** 2 for i in range(j + 1, j * 2)] for j in range(5)]

dict_of_lists = { 'list' + str(j): [i ** 2 for i in range(j + 1, j * 2)]
                  for j in range(5)
                }


问:
How implement SFINAE limited to few types, using template parameter pack
I need enable std::string and int, but using a parameter pack.

```<code>template <typename... ParamType, typename = typename std::enable_if<std::is_same<ParamType..., std::string>::value || std::is_same<ParamType..., int>::value>::type>
static inline void Log(const ParamType & ... args)
{

}
</code>```

but i have errors when call

```<code>Log("hello"s, "world"s); //syntax ERROR
</code>```

Desired result

```<code>Log(4,3,"Hello"s); //OK
Log("Hello"s); //OK
Log(5); //OK
</code>```

答:
You want (is_string_or_int(param_0)) && (is_string_or_int(param_1)) && (is_string_or_int(param_2)) && .... This can be written with the fold expression:

```<code>typename std::enable_if<
    (true && ... && (
        std::is_same<ParamType, std::string>::value ||
        std::is_same<ParamType, int>::value
    ))
>::type
</code>```

This only works with C++17 and above. For a C++11 friendly solution, you can go for struct specializations to iterate over the types:

// true iff Testing is any of Required...
template<typename Testing, typename... Required>
struct one_match : std::false_type {};

template<typename Testing, typename First, typename... Rest>
struct one_match<Testing, First, Rest...> : std::bool_constant<std::is_same<Testing, First>::value || one_match<Testing, Rest...>::value> {};

// true iff all of TestingTypes... are in the tuple RequiredTypesTuple
template<typename RequiredTypesTuple, typename... TestingTypes>
struct all_match;

template<typename... RequiredTypes>
struct all_match<std::tuple<RequiredTypes...>> : std::true_type {};

template<typename... RequiredTypes, typename First, typename... Rest>
struct all_match<std::tuple<RequiredTypes...>, First, Rest...> : std::bool_constant<one_match<First, RequiredTypes...>::value && all_match<std::tuple<RequiredTypes...>, Rest...>::value> {};

template <typename... ParamType, typename enabler =
typename std::enable_if<
    all_match<std::tuple<std::string, int>, ParamType...>::value
>::type>
static inline void Log(const ParamType & ... args)
{

}
```

Body:
I need enable std::string and int, but using a parameter pack.

template <typename... ParamType, typename = typename std::enable_if<std::is_same<ParamType..., std::string>::value || std::is_same<ParamType..., int>::value>::type>
static inline void Log(const ParamType & ... args)
{

}

but i have errors when call

Log("hello"s, "world"s); //syntax ERROR

Desired result

Log(4,3,"Hello"s); //OK
Log("Hello"s); //OK
Log(5); //OK

Body:
You want (is_string_or_int(param_0)) && (is_string_or_int(param_1)) && (is_string_or_int(param_2)) && .... This can be written with the fold expression:

typename std::enable_if<
    (true && ... && (
        std::is_same<ParamType, std::string>::value ||
        std::is_same<ParamType, int>::value
    ))
>::type

This only works with C++17 and above. For a C++11 friendly solution, you can go for struct specializations to iterate over the types:

// true iff Testing is any of Required...
template<typename Testing, typename... Required>
struct one_match : std::false_type {};

template<typename Testing, typename First, typename... Rest>
struct one_match<Testing, First, Rest...> : std::bool_constant<std::is_same<Testing, First>::value || one_match<Testing, Rest...>::value> {};

// true iff all of TestingTypes... are in the tuple RequiredTypesTuple
template<typename RequiredTypesTuple, typename... TestingTypes>
struct all_match;

template<typename... RequiredTypes>
struct all_match<std::tuple<RequiredTypes...>> : std::true_type {};

template<typename... RequiredTypes, typename First, typename... Rest>
struct all_match<std::tuple<RequiredTypes...>, First, Rest...> : std::bool_constant<one_match<First, RequiredTypes...>::value && all_match<std::tuple<RequiredTypes...>, Rest...>::value> {};

template <typename... ParamType, typename enabler =
typename std::enable_if<
    all_match<std::tuple<std::string, int>, ParamType...>::value
>::type>
static inline void Log(const ParamType & ... args)
{

}


答:
This solution uses a few C++17-ism (std::void_t). There are various implementations of them for earlier C++ standards floating everywhere, if needed:

```<code>template <typename ... ParamType,
      typename = std::void_t<std::enable_if_t
                 <std::is_same_v<ParamType, std::string> ||
                  std::is_same_v<ParamType, int>>...>>
static inline void Log(const ParamType & ... args)
{

}
</code>```

Title: How implement SFINAE limited to few types, using template parameter pack

Body:
This solution uses a few C++17-ism (std::void_t). There are various implementations of them for earlier C++ standards floating everywhere, if needed:

template <typename ... ParamType,
      typename = std::void_t<std::enable_if_t
                 <std::is_same_v<ParamType, std::string> ||
                  std::is_same_v<ParamType, int>>...>>
static inline void Log(const ParamType & ... args)
{

}


问:
How can I troubleshoot the delete row function
I am attempting to delete a row like this:

data <- data[-1645,]

However, after running the code, the row is still there. I can tell because there is an outlier in that row that is showing up on all my graphs, and when I view the data I can sort a column to easily find the offending outlier. I have had no trouble deleting rows in the past- has anyone run into anything similar? I do understand the limitations of outlier removal and I don't typically remove them however for a number of reasons I would like to see what the data look like without this one (in this case, all other values in the response variable are between -1 and 0, and in this row the value is 10^4).

答:
You really need to provide more information, but there are several ways you can troubleshoot the problem. The first one is to print out the line you are removing:

data[1645, ]

Is that the outlier? You did not tell us how you identified the outlier. If lines have been removed from the data frame, the row names are not changed but the index values are changed, e.g.

```<code>set.seed(42)
x <- sample.int(25)
y <- sample.int(25)
data <- data.frame(x, y)
head(data)
#    x  y
# 1 17  2
# 2  5  8
# 3  1  3
# 4 10  1
# 5  4 10
# 6 18 11
data <- data[-c(5, 10, 15, 20, 25), ]
head(data)
#    x  y
# 1 17  2
# 2  5  8
# 3  1  3
# 4 10  1
# 6 18 11
# 7 25 15
data[6, ]
#    x  y
# 7 25 15
data["6", ]
#    x  y
# 6 18 11
</code>```

Notice that the 6th row of the data has a row name of "7" but the row with name "6" is the 5th row in the data frame because we deleted the 5th row. The which function will give you the index value, but if you identified the outlier by looking at the printout, you got the row name and that may be different from the index. If we want to remove values in x greater than 24, here is one way to do that:

```<code>data[data$x<25, ]
</code>```

Body:
You really need to provide more information, but there are several ways you can troubleshoot the problem. The first one is to print out the line you are removing:

data[1645, ]

Is that the outlier? You did not tell us how you identified the outlier. If lines have been removed from the data frame, the row names are not changed but the index values are changed, e.g.

set.seed(42)
x <- sample.int(25)
y <- sample.int(25)
data <- data.frame(x, y)
head(data)
#    x  y
# 1 17  2
# 2  5  8
# 3  1  3
# 4 10  1
# 5  4 10
# 6 18 11
data <- data[-c(5, 10, 15, 20, 25), ]
head(data)
#    x  y
# 1 17  2
# 2  5  8
# 3  1  3
# 4 10  1
# 6 18 11
# 7 25 15
data[6, ]
#    x  y
# 7 25 15
data["6", ]
#    x  y
# 6 18 11

Notice that the 6th row of the data has a row name of "7" but the row with name "6" is the 5th row in the data frame because we deleted the 5th row. The which function will give you the index value, but if you identified the outlier by looking at the printout, you got the row name and that may be different from the index. If we want to remove values in x greater than 24, here is one way to do that:

data[data$x<25, ]


问:
Recursion sum numbers *with rule* - Recursion only
So the exercise is:

Using recursion only (no loops)

Find if there is sub ground of numbers that are equal to the given number in an array and follow the rule.

Let's say I have this array, I give the function a number for sum and it must adhere to this rule:
you cannot repeat the same number, and you can't sum 3 numbers in a row (can't do i+1 and i+2)

```<code>int[] a = {5,4,2,1,3};
</code>```

So in this case:
num 8 = true (4+3+1) ( 5+3)
num 11 = false (4+5+2 are 3 but are three in a row) (5+2+1+3 also three in a row)

My attempt is:

```<code>public static boolean sumRule(int[] a , int num){
        if (num == 0){
            return true;
        } else {

    return sumRule(a,num,0,a.length);
        }
}

private static boolean sumRule(int[] a, int num, int low,int high){
    if(low >= high || low < 0){
        return false;
    }

    if (a[low] == -1){
        return false;
    }

    if(a[low] == num || num-a[low] == 0 ){
        return true;
    }

    int temp = a[low];
    a[low] = -1;

    return  sumRule(a,num,low,high) || sumRule(a,num-temp,low+3,high) || sumRule(a,num-temp,low+1,high) ;

}
</code>```

But when I send 11 to this, it still returns true, anyone has an idea what am i missing here?

Thanks,

答:
I have the full code answer below, and here's the explanation:

Essentially you need to break this problem down to a recurrence. What that means is, you look at the choice at each step (i.e. whether to use a number or not in the sum) and recursively calculate both options.

The base case:
If num == 0 then we know it's true. But if num != 0 and the array has length 0, then we know it's false

Recursive case:
We check if the first number in the array is less than or equal to num. If not, then we can't use it. So we do a recursive call with all the same parameters except the array is now the original array minus the first number

If we CAN use the number (i.e. a[0] <= num) then the true answer might use this or it may not use it. We make a recursive call for each case, and return true if either of the recursive calls return true.

The consecutive number rule:
This is easy to enforce. We add a parameter called 'left' which tells us the number of elements we can consecutively take from the beginning of the array. To start with, left is 2 because at most we can take 2 consecutive numbers. Then in the cases where we DO use the first number in the array in our sum, we decrement left. If we don't use the first number in the array, we reset left to 2. In the cases where left becomes 0, we have no choice but to skip the current number at the top of the array.

```<code>class Main {
  public static void main(String[] args) {
    int[] a = new int[] {5,4,2,1,3};
    System.out.println(sumRule(a, 8));
    System.out.println(sumRule(a, 11));
  }

  public static boolean sumRule(int[] a , int num){
    if (num == 0){
        return true;
    } else {
      return sumRule(a,num,2);
    }
  }

  private static boolean sumRule(int[] a, int num, int left){
      if (num == 0) {
        return true;
      }

      if (a.length == 0) {
        return false;
      }

      int[] a_new = new int[a.length-1];
      for (int i = 1; i < a.length; i++) a_new[i-1] = a[i];

      if (left == 0) {
        return sumRule(a_new, num, 2);
      }

      boolean using_a0 = false;
      if (a[0] <= num) {
        using_a0 = sumRule(a_new, num-a[0], left-1);
      }

      boolean not_using_a0 = sumRule(a_new, num, 2);

      return (not_using_a0 || using_a0);
  }
}
</code>```

Edit - A variation on the code above without copying the array:

```<code>class Main {
  public static void main(String[] args) {
    int[] a = new int[] {5,4,2,1,3};
    System.out.println(sumRule(a, 8));
    System.out.println(sumRule(a, 11));
  }

  public static boolean sumRule(int[] a , int num){
    if (num == 0){
        return true;
    } else {
      return sumRuleNoLoop(a,num,2,0);
    }
  }

  private static boolean sumRuleNoLoop(int[] a, int num, int left, int startIdx){
      if (num == 0) {
        return true;
      }

      if (startIdx >= a.length) {
        return false;
      }

      if (left == 0) {
        return sumRuleNoLoop(a, num, 2, startIdx+1);
      }

      boolean using_a0 = false;
      if (a[startIdx] <= num) {
        using_a0 = sumRuleNoLoop(a, num-a[startIdx], left-1, startIdx+1);
      }

      boolean not_using_a0 = sumRuleNoLoop(a, num, 2, startIdx+1);

      return (not_using_a0 || using_a0);
  }
}
</code>```

Body:
So the exercise is:

Using recursion only (no loops)

Find if there is sub ground of numbers that are equal to the given number in an array and follow the rule.

Let's say I have this array, I give the function a number for sum and it must adhere to this rule:
you cannot repeat the same number, and you can't sum 3 numbers in a row (can't do i+1 and i+2)

int[] a = {5,4,2,1,3};

So in this case:
num 8 = true (4+3+1) ( 5+3)
num 11 = false (4+5+2 are 3 but are three in a row) (5+2+1+3 also three in a row)

My attempt is:

public static boolean sumRule(int[] a , int num){
        if (num == 0){
            return true;
        } else {

    return sumRule(a,num,0,a.length);
        }
}

private static boolean sumRule(int[] a, int num, int low,int high){
    if(low >= high || low < 0){
        return false;
    }

    if (a[low] == -1){
        return false;
    }

    if(a[low] == num || num-a[low] == 0 ){
        return true;
    }

    int temp = a[low];
    a[low] = -1;

    return  sumRule(a,num,low,high) || sumRule(a,num-temp,low+3,high) || sumRule(a,num-temp,low+1,high) ;

}

But when I send 11 to this, it still returns true, anyone has an idea what am i missing here?

Thanks,

Body:
I have the full code answer below, and here's the explanation:

Essentially you need to break this problem down to a recurrence. What that means is, you look at the choice at each step (i.e. whether to use a number or not in the sum) and recursively calculate both options.

The base case:
If num == 0 then we know it's true. But if num != 0 and the array has length 0, then we know it's false

Recursive case:
We check if the first number in the array is less than or equal to num. If not, then we can't use it. So we do a recursive call with all the same parameters except the array is now the original array minus the first number

If we CAN use the number (i.e. a[0] <= num) then the true answer might use this or it may not use it. We make a recursive call for each case, and return true if either of the recursive calls return true.

The consecutive number rule:
This is easy to enforce. We add a parameter called 'left' which tells us the number of elements we can consecutively take from the beginning of the array. To start with, left is 2 because at most we can take 2 consecutive numbers. Then in the cases where we DO use the first number in the array in our sum, we decrement left. If we don't use the first number in the array, we reset left to 2. In the cases where left becomes 0, we have no choice but to skip the current number at the top of the array.

class Main {
  public static void main(String[] args) {
    int[] a = new int[] {5,4,2,1,3};
    System.out.println(sumRule(a, 8));
    System.out.println(sumRule(a, 11));
  }

  public static boolean sumRule(int[] a , int num){
    if (num == 0){
        return true;
    } else {
      return sumRule(a,num,2);
    }
  }

  private static boolean sumRule(int[] a, int num, int left){
      if (num == 0) {
        return true;
      }

      if (a.length == 0) {
        return false;
      }

      int[] a_new = new int[a.length-1];
      for (int i = 1; i < a.length; i++) a_new[i-1] = a[i];

      if (left == 0) {
        return sumRule(a_new, num, 2);
      }

      boolean using_a0 = false;
      if (a[0] <= num) {
        using_a0 = sumRule(a_new, num-a[0], left-1);
      }

      boolean not_using_a0 = sumRule(a_new, num, 2);

      return (not_using_a0 || using_a0);
  }
}

Edit - A variation on the code above without copying the array:

class Main {
  public static void main(String[] args) {
    int[] a = new int[] {5,4,2,1,3};
    System.out.println(sumRule(a, 8));
    System.out.println(sumRule(a, 11));
  }

  public static boolean sumRule(int[] a , int num){
    if (num == 0){
        return true;
    } else {
      return sumRuleNoLoop(a,num,2,0);
    }
  }

  private static boolean sumRuleNoLoop(int[] a, int num, int left, int startIdx){
      if (num == 0) {
        return true;
      }

      if (startIdx >= a.length) {
        return false;
      }

      if (left == 0) {
        return sumRuleNoLoop(a, num, 2, startIdx+1);
      }

      boolean using_a0 = false;
      if (a[startIdx] <= num) {
        using_a0 = sumRuleNoLoop(a, num-a[startIdx], left-1, startIdx+1);
      }

      boolean not_using_a0 = sumRuleNoLoop(a, num, 2, startIdx+1);

      return (not_using_a0 || using_a0);
  }
}


问:
How to use Python function in for loop
I want to read Python function output line by line without printing None object on screen

Created function called server_array, now using same function in for loop:

```<code>for i in [server_array()]:
    print (i)
</code>```

But it's printing None too:

```<code>(venv) C:\myproject>python API\execution.py
/api/deployments/1360294004/server_arrays
/api/deployments/1360332004/server_arrays
/api/deployments/1360356004/server_arrays
/api/deployments/1360368004/server_arrays
/api/deployments/1360376004/server_arrays
/api/deployments/1360388004/server_arrays
/api/deployments/1360392004/server_arrays
/api/deployments/1360408004/server_arrays
/api/deployments/1360418004/server_arrays
/api/deployments/1360426004/server_arrays
/api/deployments/1360430004/server_arrays
/api/deployments/1360433004/server_arrays
/api/deployments/1360447004/server_arrays
/api/deployments/1360448004/server_arrays
/api/deployments/1360452004/server_arrays
/api/deployments/1360473004/server_arrays
None
</code>```

答:
Try this:

```<code>responses = [element for element in server_array() if element is not None]
</code>```

Then either:

```<code>print(responses)
</code>```

or

```<code>for curr_response in responses:
    print(curr_response)
</code>```

This will get rid of your None, but other commenters are right in that maybe that function shouldn't tack on None to the end of its responses.

Good luck, Happy Coding!

Title: How to use Python function in for loop

Body:
I want to read Python function output line by line without printing None object on screen

Created function called server_array, now using same function in for loop:

for i in [server_array()]:
    print (i)

But it's printing None too:

(venv) C:\myproject>python API\execution.py
/api/deployments/1360294004/server_arrays
/api/deployments/1360332004/server_arrays
/api/deployments/1360356004/server_arrays
/api/deployments/1360368004/server_arrays
/api/deployments/1360376004/server_arrays
/api/deployments/1360388004/server_arrays
/api/deployments/1360392004/server_arrays
/api/deployments/1360408004/server_arrays
/api/deployments/1360418004/server_arrays
/api/deployments/1360426004/server_arrays
/api/deployments/1360430004/server_arrays
/api/deployments/1360433004/server_arrays
/api/deployments/1360447004/server_arrays
/api/deployments/1360448004/server_arrays
/api/deployments/1360452004/server_arrays
/api/deployments/1360473004/server_arrays
None

Body:
Try this:

responses = [element for element in server_array() if element is not None]

Then either:

print(responses)

or

for curr_response in responses:
    print(curr_response)

This will get rid of your None, but other commenters are right in that maybe that function shouldn't tack on None to the end of its responses.

Good luck, Happy Coding!


问:
how to make a derived class of qtreeview without error: undefined reference to `vtable for RoomTree'
I am trying to keep a drag and drop from being able to place some objects in the tree under other objects. To do this I want to change how ONE function works.  So I tried to use QTreeView as a base class to a new class.

QT_Creator however throws an error: undefined reference to `vtable for RoomTree'

In an attempt to get rid of the error I have added every virtual function in the QTreeView I could find but it still will not work.

So two questions
1:   What do i need to add to get this to work.
2:   And Is this really the only way to create a derived class from the QTreeView or is there a way to tell C++ That if the function is not in the class just use the base class virtual function.

I do know that I don't need to say virtual in the derived class but it makes it clear what I added to match the virtuals in the QTreeView

Thanks for any help you can give.

```<code>#ifndef ROOMTREE_H
#define ROOMTREE_H
#include <QTreeView>
class RoomTree : public QTreeView
{
    public:
    RoomTree(QWidget *parent = nullptr);
//    ~RoomTree();
    virtual ~RoomTree();

    virtual void    dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight, const QVector<int> &roles = QVector<int>()) override{return QTreeView::dataChanged(topLeft, bottomRight, roles);}
    virtual QModelIndex indexAt(const QPoint &point) const override{return QTreeView::indexAt(point);}
    virtual void    keyboardSearch(const QString &search) override{return QTreeView::keyboardSearch(search);}
    virtual void    reset() override{return QTreeView::reset();}
    virtual void    scrollTo(const QModelIndex &index, QAbstractItemView::ScrollHint hint = EnsureVisible) override{return QTreeView::scrollTo(index, hint);}
    virtual void    selectAll() override{return QTreeView::selectAll();}
    virtual void    setModel(QAbstractItemModel *model) override{return QTreeView::setModel(model);}
    virtual void    setRootIndex(const QModelIndex &index) override{return QTreeView::setRootIndex(index);}
    virtual void    setSelectionModel(QItemSelectionModel *selectionModel) override{return QTreeView::setSelectionModel(selectionModel);}
    virtual QRect   visualRect(const QModelIndex &index) const override{return QTreeView::visualRect(index);}
protected:
    virtual void    drawBranches(QPainter *painter, const QRect &rect, const QModelIndex &index) const{return QTreeView::drawBranches(painter, rect, index);}
    virtual void    drawRow(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const{return QTreeView::drawRow(painter, option, index);}

    virtual void    currentChanged(const QModelIndex &current, const QModelIndex &previous) override{return QTreeView::currentChanged(current, previous);}
    virtual void    dragMoveEvent(QDragMoveEvent *event) override{return QTreeView::dragMoveEvent(event);}
    virtual int horizontalOffset() const override{return QTreeView::horizontalOffset();}
    virtual bool    isIndexHidden(const QModelIndex &index) const override{return QTreeView::isIndexHidden(index);}
    virtual void    keyPressEvent(QKeyEvent *event) override{return QTreeView::keyPressEvent(event);}
    virtual void    mouseDoubleClickEvent(QMouseEvent *event) override{return QTreeView::mouseDoubleClickEvent(event);}
    virtual void    mouseMoveEvent(QMouseEvent *event) override{return QTreeView::mouseMoveEvent(event);}
    virtual void    mousePressEvent(QMouseEvent *event) override{return QTreeView::mousePressEvent(event);}
    virtual void    mouseReleaseEvent(QMouseEvent *event) override{return QTreeView::mouseReleaseEvent(event);}
    virtual QModelIndex moveCursor(QAbstractItemView::CursorAction cursorAction, Qt::KeyboardModifiers modifiers) override{return QTreeView::moveCursor(cursorAction, modifiers);}
    virtual void    paintEvent(QPaintEvent *event) override{return QTreeView::paintEvent(event);}
    virtual void    rowsAboutToBeRemoved(const QModelIndex &parent, int start, int end) override{return QTreeView::rowsAboutToBeRemoved(parent, start, end);}
    virtual void    rowsInserted(const QModelIndex &parent, int start, int end) override{return QTreeView::rowsInserted(parent, start, end);}
    virtual void    scrollContentsBy(int dx, int dy) override{return QTreeView::scrollContentsBy(dx, dy);}
    virtual QModelIndexList selectedIndexes() const override{return QTreeView::selectedIndexes();}
    virtual void    selectionChanged(const QItemSelection &selected, const QItemSelection &deselected) override{return QTreeView::selectionChanged(selected, deselected);}
    virtual void    setSelection(const QRect &rect, QItemSelectionModel::SelectionFlags command) override{return QTreeView::setSelection(rect, command);}
    virtual int sizeHintForColumn(int column) const override{return QTreeView::sizeHintForColumn(column);}
    virtual void    timerEvent(QTimerEvent *event) override{return QTreeView::timerEvent(event);}
    virtual void    updateGeometries() override{return QTreeView::updateGeometries();}
    virtual int verticalOffset() const override{return QTreeView::verticalOffset();}
    virtual bool    viewportEvent(QEvent *event) override{return QTreeView::viewportEvent(event);}
    virtual QSize   viewportSizeHint() const override{return QTreeView::viewportSizeHint();}
    virtual QRegion visualRegionForSelection(const QItemSelection &selection) const override{return QTreeView::visualRegionForSelection(selection);}
};

#endif // ROOMTREE_H
</code>```

答:
bnaecker Was correct all I needed to do was add Q_OBJECT to the class.  I also had to do a complete rebuild for some reason.

This works:

```<code>class RoomTree : public QTreeView
{
Q_OBJECT
    public:
    RoomTree(QWidget *parent = nullptr);
//    ~RoomTree();
    ~RoomTree(){};

};
</code>```

Body:
I am trying to keep a drag and drop from being able to place some objects in the tree under other objects. To do this I want to change how ONE function works.  So I tried to use QTreeView as a base class to a new class.

QT_Creator however throws an error: undefined reference to `vtable for RoomTree'

In an attempt to get rid of the error I have added every virtual function in the QTreeView I could find but it still will not work.

So two questions
1:   What do i need to add to get this to work.
2:   And Is this really the only way to create a derived class from the QTreeView or is there a way to tell C++ That if the function is not in the class just use the base class virtual function.

I do know that I don't need to say virtual in the derived class but it makes it clear what I added to match the virtuals in the QTreeView

Thanks for any help you can give.

#ifndef ROOMTREE_H
#define ROOMTREE_H
#include <QTreeView>
class RoomTree : public QTreeView
{
    public:
    RoomTree(QWidget *parent = nullptr);
//    ~RoomTree();
    virtual ~RoomTree();

    virtual void    dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight, const QVector<int> &roles = QVector<int>()) override{return QTreeView::dataChanged(topLeft, bottomRight, roles);}
    virtual QModelIndex indexAt(const QPoint &point) const override{return QTreeView::indexAt(point);}
    virtual void    keyboardSearch(const QString &search) override{return QTreeView::keyboardSearch(search);}
    virtual void    reset() override{return QTreeView::reset();}
    virtual void    scrollTo(const QModelIndex &index, QAbstractItemView::ScrollHint hint = EnsureVisible) override{return QTreeView::scrollTo(index, hint);}
    virtual void    selectAll() override{return QTreeView::selectAll();}
    virtual void    setModel(QAbstractItemModel *model) override{return QTreeView::setModel(model);}
    virtual void    setRootIndex(const QModelIndex &index) override{return QTreeView::setRootIndex(index);}
    virtual void    setSelectionModel(QItemSelectionModel *selectionModel) override{return QTreeView::setSelectionModel(selectionModel);}
    virtual QRect   visualRect(const QModelIndex &index) const override{return QTreeView::visualRect(index);}
protected:
    virtual void    drawBranches(QPainter *painter, const QRect &rect, const QModelIndex &index) const{return QTreeView::drawBranches(painter, rect, index);}
    virtual void    drawRow(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const{return QTreeView::drawRow(painter, option, index);}

    virtual void    currentChanged(const QModelIndex &current, const QModelIndex &previous) override{return QTreeView::currentChanged(current, previous);}
    virtual void    dragMoveEvent(QDragMoveEvent *event) override{return QTreeView::dragMoveEvent(event);}
    virtual int horizontalOffset() const override{return QTreeView::horizontalOffset();}
    virtual bool    isIndexHidden(const QModelIndex &index) const override{return QTreeView::isIndexHidden(index);}
    virtual void    keyPressEvent(QKeyEvent *event) override{return QTreeView::keyPressEvent(event);}
    virtual void    mouseDoubleClickEvent(QMouseEvent *event) override{return QTreeView::mouseDoubleClickEvent(event);}
    virtual void    mouseMoveEvent(QMouseEvent *event) override{return QTreeView::mouseMoveEvent(event);}
    virtual void    mousePressEvent(QMouseEvent *event) override{return QTreeView::mousePressEvent(event);}
    virtual void    mouseReleaseEvent(QMouseEvent *event) override{return QTreeView::mouseReleaseEvent(event);}
    virtual QModelIndex moveCursor(QAbstractItemView::CursorAction cursorAction, Qt::KeyboardModifiers modifiers) override{return QTreeView::moveCursor(cursorAction, modifiers);}
    virtual void    paintEvent(QPaintEvent *event) override{return QTreeView::paintEvent(event);}
    virtual void    rowsAboutToBeRemoved(const QModelIndex &parent, int start, int end) override{return QTreeView::rowsAboutToBeRemoved(parent, start, end);}
    virtual void    rowsInserted(const QModelIndex &parent, int start, int end) override{return QTreeView::rowsInserted(parent, start, end);}
    virtual void    scrollContentsBy(int dx, int dy) override{return QTreeView::scrollContentsBy(dx, dy);}
    virtual QModelIndexList selectedIndexes() const override{return QTreeView::selectedIndexes();}
    virtual void    selectionChanged(const QItemSelection &selected, const QItemSelection &deselected) override{return QTreeView::selectionChanged(selected, deselected);}
    virtual void    setSelection(const QRect &rect, QItemSelectionModel::SelectionFlags command) override{return QTreeView::setSelection(rect, command);}
    virtual int sizeHintForColumn(int column) const override{return QTreeView::sizeHintForColumn(column);}
    virtual void    timerEvent(QTimerEvent *event) override{return QTreeView::timerEvent(event);}
    virtual void    updateGeometries() override{return QTreeView::updateGeometries();}
    virtual int verticalOffset() const override{return QTreeView::verticalOffset();}
    virtual bool    viewportEvent(QEvent *event) override{return QTreeView::viewportEvent(event);}
    virtual QSize   viewportSizeHint() const override{return QTreeView::viewportSizeHint();}
    virtual QRegion visualRegionForSelection(const QItemSelection &selection) const override{return QTreeView::visualRegionForSelection(selection);}
};

#endif // ROOMTREE_H

Body:
bnaecker Was correct all I needed to do was add Q_OBJECT to the class.  I also had to do a complete rebuild for some reason.

This works:

class RoomTree : public QTreeView
{
Q_OBJECT
    public:
    RoomTree(QWidget *parent = nullptr);
//    ~RoomTree();
    ~RoomTree(){};

};


问:
How to mock non virtual methods?
```<code>[TestMethod]
public void TestMethod1()
{
    var mock = new Mock<EmailService>();
    mock.Setup(x => x.SendEmail()).Returns(true);
    var cus = new Customer();
    var result = cus.AddCustomer(mock.Object);
    Assert.IsTrue(result);
}

public class Customer
{
    public bool AddCustomer(EmailService emailService)
    {
        emailService.SendEmail();
        Debug.WriteLine("new customer added");
        return true;
    }
}

public class EmailService
{
    public virtual bool SendEmail()
    {
        throw  new Exception("send email failed cuz bla bla bla");
    }
}
</code>```

The EmailService.SendEmail method must be virtual to mock it. Is there any way to mock non virtual methods?

答:
I saw this question much time ago and realized that I would want to create something opensourced to solve the issue. So it is ready - AutoFake. The most exciting thing is that it doesn't require any crazy CLR Profiler API. It is just a normal .NET package and that's it. Bellow is the example of what you can do using the library:</p>
```<code>public class Calendar
{
    public static DateTime Yesterday => DateTime.Now.AddDays(-1);
    internal Task<DateTime> AddSomeMinutesAsync(DateTime date) => Task.Run(() => AddSomeMinutes(date));
    public static DateTime AddSomeMinutes(DateTime date) => date.AddMinutes(new Random().Next(1, 10));
}

[Fact]
public void Yesterday_SomeDay_ThePrevDay()
{
    var fake = new Fake<Calendar>();

    var sut = fake.Rewrite(() => Calendar.Yesterday);
    sut.Replace(() => DateTime.Now).Return(new DateTime(2016, 8, day: 8));

    Assert.Equal(new DateTime(2016, 8, 7), sut.Execute());
}

[Fact]
public async Task AddSomeMinutesAsync_SomeDay_MinutesAdded()
{
    var randomValue = 7;
    var date = new DateTime(2016, 8, 8, hour: 0, minute: 0, second: 0);
    var fake = new Fake<Calendar>();

    var sut = fake.Rewrite(f => f.AddSomeMinutesAsync(date));
    sut.Replace((Random r) => r.Next(1, 10)) // Arg.Is<int>(i => i == 10) is also possible
                           // r.Next(1, 11) fails with "Expected - 11, actual - 10"
        .ExpectedCalls(1) // c => c > 1 fails with "Actual value - 1"
        .Return(randomValue);

    Assert.Equal(date.AddMinutes(randomValue), await sut.Execute());
}

[Fact]
public void AddSomeMinutes_SomeDay_EventsRecorded()
{
    var events = new List<string>();
    var fake = new Fake<Calendar>();

    var sut = fake.Rewrite(() => Calendar.AddSomeMinutes(new DateTime(2016, 8, 8)));

    sut.Prepend(() => events.Add("The first line"));
    sut.Prepend(() => events.Add("The line before AddMinutes(...) call"))
        .Before((DateTime date) => date.AddMinutes(Arg.IsAny<int>()));

    sut.Append(() => events.Add("The line after new Random() call"))
        .After(() => new Random());
    sut.Append(() => events.Add("The last line"));

    sut.Execute();
    Assert.Equal(new[]
        {
            "The first line",
            "The line after new Random() call", // indeed, this call is earlier
            "The line before AddMinutes(...) call",
            "The last line"
        },
        events);
}
</code>```

Title: How to mock non virtual methods?

Body:
[TestMethod]
public void TestMethod1()
{
    var mock = new Mock<EmailService>();
    mock.Setup(x => x.SendEmail()).Returns(true);
    var cus = new Customer();
    var result = cus.AddCustomer(mock.Object);
    Assert.IsTrue(result);
}

public class Customer
{
    public bool AddCustomer(EmailService emailService)
    {
        emailService.SendEmail();
        Debug.WriteLine("new customer added");
        return true;
    }
}

public class EmailService
{
    public virtual bool SendEmail()
    {
        throw  new Exception("send email failed cuz bla bla bla");
    }
}

The EmailService.SendEmail method must be virtual to mock it. Is there any way to mock non virtual methods?

Body:
I saw this question much time ago and realized that I would want to create something opensourced to solve the issue. So it is ready - AutoFake. The most exciting thing is that it doesn't require any crazy CLR Profiler API. It is just a normal .NET package and that's it. Bellow is the example of what you can do using the library:

public class Calendar
{
    public static DateTime Yesterday => DateTime.Now.AddDays(-1);
    internal Task<DateTime> AddSomeMinutesAsync(DateTime date) => Task.Run(() => AddSomeMinutes(date));
    public static DateTime AddSomeMinutes(DateTime date) => date.AddMinutes(new Random().Next(1, 10));
}

[Fact]
public void Yesterday_SomeDay_ThePrevDay()
{
    var fake = new Fake<Calendar>();

    var sut = fake.Rewrite(() => Calendar.Yesterday);
    sut.Replace(() => DateTime.Now).Return(new DateTime(2016, 8, day: 8));

    Assert.Equal(new DateTime(2016, 8, 7), sut.Execute());
}

[Fact]
public async Task AddSomeMinutesAsync_SomeDay_MinutesAdded()
{
    var randomValue = 7;
    var date = new DateTime(2016, 8, 8, hour: 0, minute: 0, second: 0);
    var fake = new Fake<Calendar>();

    var sut = fake.Rewrite(f => f.AddSomeMinutesAsync(date));
    sut.Replace((Random r) => r.Next(1, 10)) // Arg.Is<int>(i => i == 10) is also possible
                           // r.Next(1, 11) fails with "Expected - 11, actual - 10"
        .ExpectedCalls(1) // c => c > 1 fails with "Actual value - 1"
        .Return(randomValue);

    Assert.Equal(date.AddMinutes(randomValue), await sut.Execute());
}

[Fact]
public void AddSomeMinutes_SomeDay_EventsRecorded()
{
    var events = new List<string>();
    var fake = new Fake<Calendar>();

    var sut = fake.Rewrite(() => Calendar.AddSomeMinutes(new DateTime(2016, 8, 8)));

    sut.Prepend(() => events.Add("The first line"));
    sut.Prepend(() => events.Add("The line before AddMinutes(...) call"))
        .Before((DateTime date) => date.AddMinutes(Arg.IsAny<int>()));

    sut.Append(() => events.Add("The line after new Random() call"))
        .After(() => new Random());
    sut.Append(() => events.Add("The last line"));

    sut.Execute();
    Assert.Equal(new[]
        {
            "The first line",
            "The line after new Random() call", // indeed, this call is earlier
            "The line before AddMinutes(...) call",
            "The last line"
        },
        events);
}


答:
It is technically possible to do this by modifying the dict returned by locals():

```<code>x = 5
locals()[f"list{x}"] = 1
print(list5)  # prints 1
</code>```

This is needlessly complicated, though, and it's very easy to accidentally overwrite something you didn't mean to.  You're almost always going to be better off creating your own dictionary or list:

```<code>x = 5
my_vars = {
    f"list{x}": 1
}
print(my_vars["list5"])  # prints 1
</code>```

Body:
It is technically possible to do this by modifying the dict returned by locals():

x = 5
locals()[f"list{x}"] = 1
print(list5)  # prints 1

This is needlessly complicated, though, and it's very easy to accidentally overwrite something you didn't mean to.  You're almost always going to be better off creating your own dictionary or list:

x = 5
my_vars = {
    f"list{x}": 1
}
print(my_vars["list5"])  # prints 1


问:
Combining multiple git repositories
Let's say I've got a setup that look something like

```<code>phd/code/
phd/figures/
phd/thesis/
</code>```

For historical reasons, these all have their own git repositories. But I'd like to combine them into a single one to simplify things a little. For example, right now I might make two sets of changes and have to do something like

```<code>cd phd/code
git commit
cd ../figures
git commit
</code>```

It'd be (now) nice to just to perform

```<code>cd phd
git commit
</code>```

There seems to be a couple of ways of doing this using submodules or pulling from my sub-repositories, but that's a little more complex than I'm looking for. At the very least, I'd be happy with

```<code>cd phd
git init
git add [[everything that's already in my other repositories]]
</code>```

but that doesn't seem like a one-liner. Is there anything in git that can help me out?

答:
I have created a tool that make this task. The method used is similar (internally make some things like --filter-branch) but is more friendly. Is GPL 2.0

http://github.com/geppo12/GitCombineRepo

OwnerDisplayName: Will Robertson

ContentLicense: CC BY-SA 2.5

Title: Combining multiple git repositories

Body:
Let's say I've got a setup that look something like

phd/code/
phd/figures/
phd/thesis/

For historical reasons, these all have their own git repositories. But I'd like to combine them into a single one to simplify things a little. For example, right now I might make two sets of changes and have to do something like

cd phd/code
git commit
cd ../figures
git commit

It'd be (now) nice to just to perform

cd phd
git commit

There seems to be a couple of ways of doing this using submodules or pulling from my sub-repositories, but that's a little more complex than I'm looking for. At the very least, I'd be happy with

cd phd
git init
git add [[everything that's already in my other repositories]]

but that doesn't seem like a one-liner. Is there anything in git that can help me out?


问:
Easily aligning characters after whitespace in vim
I would like to create a mapped vim command that helps me align assignments for variables across multiple lines. Imagine I have the following text in a file:

```<code>foo                     = 1;
barbar            = 2;
asdfasd    = 3;
jjkjfh                = 4;
baz              = 5;
</code>```

If I select multiple lines and use the regex below, noting that column 10 is in the whitespace for all lines, stray whitespace after column 10 will be deleted up to the equals sign.

```<code>:'<,'>s/^\(.\{10}\)\s*\(=.*\)$/\1\2/g
</code>```

Here's the result:

```<code>foo       = 1;
barbar    = 2;
asdfasd   = 3;
jjkjfh    = 4;
baz       = 5;
</code>```

Is there a way to get the current cursor position (specifically the column position) while performing a visual block selection and use that column in the regular expression?

Alternatively, if it is possible to find the max column for any of the equals signs on the selected lines and insert whitespace so all equals signs are aligned by column, that is preferred to solving the previous problem. Imagine quickly converting:

```<code>foo = 1;
barbar = 2;
asdfasd = 3;
jjkjfh = 4;
baz = 5;
</code>```

to:

```<code>foo     = 1;
barbar  = 2;
asdfasd = 3;
jjkjfh  = 4;
baz     = 5;
</code>```

with a block selection and a key-combo.

答:
Without plugins

In this case

```<code>foo = 1
fizzbuzz = 2
bar = 3
</code>```

You can add many spaces with a macro:

0f=10iSPACEESCj

where 10 is an arbitrary number just to add enough space.

Apply the macro M times (for M lines) and get

```<code>foo           = 1
fizzbuzz           = 2
bar           = 3
</code>```

Then remove excessive spaces with a macro that removes all characters till some column N:

0f=d12|j

where 12 is the column number you want to align along and | is a vertical bar (SHIFT + \). Together 12| is a "go to column 12" command.

Repeat for each line and get

```<code>foo        = 1
fizzbuzz   = 2
bar        = 3
</code>```

You can combine the two macros into one:

0f=10iSPACEESCd11|j

Body:
I would like to create a mapped vim command that helps me align assignments for variables across multiple lines. Imagine I have the following text in a file:

foo                     = 1;
barbar            = 2;
asdfasd    = 3;
jjkjfh                = 4;
baz              = 5;

If I select multiple lines and use the regex below, noting that column 10 is in the whitespace for all lines, stray whitespace after column 10 will be deleted up to the equals sign.

:'<,'>s/^\(.\{10}\)\s*\(=.*\)$/\1\2/g

Here's the result:

foo       = 1;
barbar    = 2;
asdfasd   = 3;
jjkjfh    = 4;
baz       = 5;

Is there a way to get the current cursor position (specifically the column position) while performing a visual block selection and use that column in the regular expression?

Alternatively, if it is possible to find the max column for any of the equals signs on the selected lines and insert whitespace so all equals signs are aligned by column, that is preferred to solving the previous problem. Imagine quickly converting:

foo = 1;
barbar = 2;
asdfasd = 3;
jjkjfh = 4;
baz = 5;

to:

foo     = 1;
barbar  = 2;
asdfasd = 3;
jjkjfh  = 4;
baz     = 5;

with a block selection and a key-combo.

Body:
Without plugins

In this case

foo = 1
fizzbuzz = 2
bar = 3

You can add many spaces with a macro:

0f=10iSPACEESCj

where 10 is an arbitrary number just to add enough space.

Apply the macro M times (for M lines) and get

foo           = 1
fizzbuzz           = 2
bar           = 3

Then remove excessive spaces with a macro that removes all characters till some column N:

0f=d12|j

where 12 is the column number you want to align along and | is a vertical bar (SHIFT + \). Together 12| is a "go to column 12" command.

Repeat for each line and get

foo        = 1
fizzbuzz   = 2
bar        = 3

You can combine the two macros into one:

0f=10iSPACEESCd11|j


问:
Argument must be a string or number [ Label Encoding ]
I am trying to append my data frame to new data frame but I am getting a 'Argument must be a string or number '  error.

```<code># The encoders
le = LabelEncoder()
ohc = OneHotEncoder()
for col in num_ohc_cols.index:

   # Integer encode the string categories
   dat = le.fit_transform(df_ohc[col]).astype(np.int)
   # Remove the original column from the dataframe
    df_ohc = df_ohc.drop(col,axis=1)
   # One hot encode the data--this returns a sparse array
   new_dat = ohc.fit_transform(dat.reshape(-1,1))
   # Create unique column names

   n_cols = new_dat.shape[1]

   col_names = ['_'.join([col,str(x)]) for x in range(n_cols)]
   print(col_names)
   # Create the new dataframe
</code>```

I'm getting the error here, in creating new dataframe:

```<code>new_df=pd.DataFrame(
 new_dat.toarray(),index=df_ohc.index,columns=col_names)
</code>```

答:
This error is caused because your data actually does have both a number and a string. The best way to fix this would be to convert all data to a string as follows:</p>

```<code>new_df = new_df.apply(lambda x: le.fit_transform(x.astype(str)), axis=0, result_type='expand')
</code>```

Body:
I am trying to append my data frame to new data frame but I am getting a 'Argument must be a string or number '  error.

# The encoders
le = LabelEncoder()
ohc = OneHotEncoder()
for col in num_ohc_cols.index:

   # Integer encode the string categories
   dat = le.fit_transform(df_ohc[col]).astype(np.int)
   # Remove the original column from the dataframe
    df_ohc = df_ohc.drop(col,axis=1)
   # One hot encode the data--this returns a sparse array
   new_dat = ohc.fit_transform(dat.reshape(-1,1))
   # Create unique column names

   n_cols = new_dat.shape[1]

   col_names = ['_'.join([col,str(x)]) for x in range(n_cols)]
   print(col_names)
   # Create the new dataframe

I'm getting the error here, in creating new dataframe:

new_df=pd.DataFrame(
 new_dat.toarray(),index=df_ohc.index,columns=col_names)

Body:
This error is caused because your data actually does have both a number and a string. The best way to fix this would be to convert all data to a string as follows:

new_df = new_df.apply(lambda x: le.fit_transform(x.astype(str)), axis=0, result_type='expand')