问:
Should websites expand on window resize?
I'm asking this question purely from a usability standpoint!

Should a website expand/stretch to fill the viewing area when you resize a browser window?

I know for sure there are the obvious cons:

Wide columns of text are hard to read.

Writing html/css using percents can be a pain.

It makes you vulnerable to having your design stretched past it's limits if an image is too wide, or a block of text is added that is too long. (see it's a pain to code the html/css).

The only Pro I can think of is that users who use the font-resizing that is built into their browser won't have to deal with columns that are only a few words long, with a body of white-space on either side.

However, I think that may be a browser problem more than anything else (Firefox 3 allows you to zoom everything instead of just the text, which comes in handy all the time)

edit: I noticed stack overflow is fixed width, but coding horror resizes. It seems Jeff doesn't have a strong preference either way.

答:
I'd say fluid all the way. The user can always go back to a smaller size window if he doesn't like the result of enlarging it, but he can't do anything about a fixed layout.

If you really, really hate the idea of your site looking ugly because of something a user with a large screen does, then for the sake of all that is true and beautiful, at least never use pixel-based fixed layouts! CSS has these neat text-relative size units like "em" that allow parts of your page to scale with the font size while others (like images) stay in their "natural" size.

Why not use them and make your page scale well without relying on the less flexible "scale everything" of FF3 that's really just a workaround for sites that use a dumb pixel-based fixed layout?

OwnerDisplayName: Jim Robert

LastEditorDisplayName: Jim Robert

OwnerDisplayName: Michael Borgwardt

ContentLicense: CC BY-SA 2.5


来源: stackexchange

问:
How to scroll listview smoothly to a certain row before SDK 8
I want to programmatically scroll a row to the top of listview,
I tried the setSelection method, but no scroll animation
how to? please.</p>

答: I've searched and searched myself, and I do not believe there is any way to do this before API Level 8. If anyone suggests the View.scrollTo() or View.scrollBy() methods they will not work. Those move the entire View, not the content of the list.</p>

ContentLicense: CC BY-SA 3.0


问:
React Native Error: Invariant Violation: View config not found for name RNC safe Area
Hey everyone I am new to React Native and cannot figure this simple error out. Looked everywhere no solutions :[ The image provided shows the error I Keep getting. I am working from a windows 10 machine. I am using Expo, NPM, React-Native... Ive been stuck and tried to follow a few tutorials on 2020 react native Navigation I keep getting this error w them all.

Emulator Error

App.js

```<code>import 'react-native-gesture-handler';
import * as React from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import Home from './screens/Home';

const Stack = createStackNavigator();

export default function App() {
  return (
    <NavigationContainer>
     <Stack.Navigator>
      <Stack.Screen name="Home" component={Home} />
    </Stack.Navigator>
    </NavigationContainer>
  );
}
</code>```

Home.js

```<code>import React from 'react';
import { StyleSheet, View, Button, Text } from 'react-native';

/**
 * Home screen
 */
export default class Home extends React.Component {

    render() {
        return (
            <View style={styles.container}>

            </View>
        );

    }

}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        alignItems: 'center',
        justifyContent: 'center'
    }
});
</code>```

package.json

```<code>{
  "main": "node_modules/expo/AppEntry.js",
  "scripts": {
    "start": "expo start",
    "android": "expo start --android",
    "ios": "expo start --ios",
    "web": "expo start --web",
    "eject": "expo eject"
  },
  "dependencies": {
    "@react-native-community/masked-view": "^0.1.10",
    "@react-navigation/native": "^5.5.0",
    "@react-navigation/stack": "^5.4.1",
    "expo": "~37.0.3",
    "react": "~16.9.0",
    "react-dom": "~16.9.0",
    "react-native": "https://github.com/expo/react-native/archive/sdk-37.0.1.tar.gz",
    "react-native-gesture-handler": "^1.6.1",
    "react-native-reanimated": "^1.9.0",
    "react-native-safe-area-context": "^3.0.2",
    "react-native-screens": "^2.8.0",
    "react-native-web": "~0.11.7",
    "react-navigation": "^4.3.9"
  },
  "devDependencies": {
    "babel-preset-expo": "~8.1.0",
    "@babel/core": "^7.8.6"
  },
  "private": true
}
</code>```

答: You should use expo install react-native-safe-area-context to get the correct version. The installation instructions for React Navigation also advise this. I'd also check out the Using Libraries docs page for more info. Lastly, I imagine you're getting a warning when you start your project about library incompatibility, be sure to keep an eye out for those warnings in the future.

ContentLicense: CC BY-SA 4.0

Body:
Hey everyone I am new to React Native and cannot figure this simple error out. Looked everywhere no solutions :[ The image provided shows the error I Keep getting. I am working from a windows 10 machine. I am using Expo, NPM, React-Native... Ive been stuck and tried to follow a few tutorials on 2020 react native Navigation I keep getting this error w them all.

Emulator Error

App.js

import 'react-native-gesture-handler';
import * as React from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import Home from './screens/Home';

const Stack = createStackNavigator();

export default function App() {
  return (
    <NavigationContainer>
     <Stack.Navigator>
      <Stack.Screen name="Home" component={Home} />
    </Stack.Navigator>
    </NavigationContainer>
  );
}

Home.js

import React from 'react';
import { StyleSheet, View, Button, Text } from 'react-native';

/**
 * Home screen
 */
export default class Home extends React.Component {

    render() {
        return (
            <View style={styles.container}>

            </View>
        );

    }

}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        alignItems: 'center',
        justifyContent: 'center'
    }
});

package.json

{
  "main": "node_modules/expo/AppEntry.js",
  "scripts": {
    "start": "expo start",
    "android": "expo start --android",
    "ios": "expo start --ios",
    "web": "expo start --web",
    "eject": "expo eject"
  },
  "dependencies": {
    "@react-native-community/masked-view": "^0.1.10",
    "@react-navigation/native": "^5.5.0",
    "@react-navigation/stack": "^5.4.1",
    "expo": "~37.0.3",
    "react": "~16.9.0",
    "react-dom": "~16.9.0",
    "react-native": "https://github.com/expo/react-native/archive/sdk-37.0.1.tar.gz",
    "react-native-gesture-handler": "^1.6.1",
    "react-native-reanimated": "^1.9.0",
    "react-native-safe-area-context": "^3.0.2",
    "react-native-screens": "^2.8.0",
    "react-native-web": "~0.11.7",
    "react-navigation": "^4.3.9"
  },
  "devDependencies": {
    "babel-preset-expo": "~8.1.0",
    "@babel/core": "^7.8.6"
  },
  "private": true
}


问:
I wanted to convert the following C# Code to Python Code
Friends how to convert the following C# code to Python:</p>

```<code>class BaseClass {
    //some member(s)
}

class DerivedClass : BaseClass {
   //some member(s)
}

class Program {
    public static void Main(){
        BaseClass bc = new DerivedClass();
    }
}
</code>```

答:
To define a class in python, you use the syntax class ClassName: or class ClassName(BaseName):. Then we define a main method(def main():) that will be run. Finally, if we tell the interpreter to run the main method if this file is being run as the main process (if __name__ == "__main__").

```<code>#! /usr/bin/env python

class BaseClass:
    def baseMethod(self):
        return "base"

class DerivedClass(BaseClass):
    def derivedMethod(self):
        return "derived"

def main():
    bc = DerivedClass()
    print(bc.baseMethod())
    print(bc.derivedMethod())

if __name__ == "__main__":
    main()
</code>```

Body:
Friends how to convert the following C# code to Python:

class BaseClass {
    //some member(s)
}

class DerivedClass : BaseClass {
   //some member(s)
}

class Program {
    public static void Main(){
        BaseClass bc = new DerivedClass();
    }
}

Body:
To define a class in python, you use the syntax class ClassName: or class ClassName(BaseName):. Then we define a main method(def main():) that will be run. Finally, if we tell the interpreter to run the main method if this file is being run as the main process (if __name__ == "__main__").

#! /usr/bin/env python

class BaseClass:
    def baseMethod(self):
        return "base"

class DerivedClass(BaseClass):
    def derivedMethod(self):
        return "derived"

def main():
    bc = DerivedClass()
    print(bc.baseMethod())
    print(bc.derivedMethod())

if __name__ == "__main__":
    main()


问:
How to design the icon of a Modelica component?
Is there any software that allows designing the icon of a Modelica component, and then copy into Dymola?
It is hard to draw the picture in Dymola.

A short summary of the answers, there is 4 software support this task:

OMEdit;

MoVE;

InkSpace;

PowerPoint;

答: Yes, there is MoVE, but it seems development is stopped.</p>


问:
I can't able to add an array after declaring the array
In this program

```<code>marks[0]="50";
</code>```

is not working. It gives the error

```<code>[Error] invalid conversion from 'const char*' to 'int' [-fpermissive]
</code>```

Here's the program:

```<code>int main()

{

    int marks[40];

    marks[0]={"50"};

    cout<<"Enter the marks: "<<endl;

    cin>>marks[1];

    cout<<marks[0];

    cout<<marks[1];

    return 0;

}
</code>```

答:
When you do:

```<code>marks[0] = "50";
</code>```

you are trying to assign a char const * to an int. Hence the error message.

The code you probably mean to write is:

```<code>marks[0] = 50;
</code>```

which assigns an int to an int.

Body:
In this program

marks[0]="50";

is not working. It gives the error

[Error] invalid conversion from 'const char*' to 'int' [-fpermissive]

Here's the program:

int main()

{

    int marks[40];

    marks[0]={"50"};

    cout<<"Enter the marks: "<<endl;

    cin>>marks[1];

    cout<<marks[0];

    cout<<marks[1];

    return 0;

}

Body:
When you do:

marks[0] = "50";

you are trying to assign a char const * to an int. Hence the error message.

The code you probably mean to write is:

marks[0] = 50;

which assigns an int to an int.


问:
Spoof $_SERVER['HTTPS'] on local wamp-server for testing
Is it possible to configure my local setup (running Wampserver) so that my PHP application thinks HTTPS is enabled locally?  The application requires HTTPS (by checking $_SERVER['HTTPS']) before doing stuff, but I don't want to go through the hassle of a full HTTPS setup locally.  Thanks.

Edit:  I should mention this isn't an application I wrote, just one I am tasked with maintaining.  This check is performed in many places (50-100) around the server.

答:
Move the check into an object

```<code>   class Request
   {
       function isHttps()
       {
            // check for local site here,
            // or better still, use a DevRequest class or a Mock to pass
            // your local requirements
       }

   }
</code>```

and then use

```<code>if($request->isHttps()) {...}
</code>```

Body:
Move the check into an object

   class Request
   {
       function isHttps()
       {
            // check for local site here,
            // or better still, use a DevRequest class or a Mock to pass
            // your local requirements
       }

   }

and then use

if($request->isHttps()) {...}


问:
Perl: Combine hash with Keys of Keys containing identical Key
I am trying to merge these hashmaps in perl and unable to figure out how to do it when the key is identical. The desired input is VAR1 and VAR2 and output is mentioned as well.

Input:

```<code>my $VAR1 = { 'p'=> { 'a' => 2,
                     'b' => 3}};

my $VAR2 = { 'p'=> { 'c' => 4,
                     'd' => 7}};
</code>```

Desired Output:

```<code>{'p'=> {
        'a' => 2,
        'b' => 3,
        'c' => 4,
        'd' => 7}};
</code>```

答:
Say you had

my %h1 = ( a => 2, b => 3 );
my %h2 = ( c => 4, d => 7 );
```

<p>To combine them into a third hash, you can use</p>

<pre class="lang-perl prettyprint-override"><code>my %h = ( %h1, %h2 );
</code>```

It would be as if you had done

my %h = ( a => 2, b => 3, c => 4, d => 7 );
```

<p>Any keys in common will be taken from the hash later in the list.</p>

<hr>

<p>In your case, you have anonymous hashes. So where we would have used <code>%NAME</code>, we will use <code>%BLOCK</code>, where the block returns a reference to the hash we want to use. This gives us the following:</p>

<pre class="lang-perl prettyprint-override"><code>my %h_inner = (
   %{ $VAR1->{p} },
   %{ $VAR2->{p} },
);
</code>```

This can also be written as follows:[1]

my %h_inner = (
   $VAR1->{p}->%*,
   $VAR2->{p}->%*,
);
```

<p>Finally, you also want to second new hash with a single element keyed with <code>p</code> whose value is a reference to this first new hash.</p>

<pre class="lang-perl prettyprint-override"><code>my %h_outer = ( p => \%h_inner );
</code>```

So, all together, you want

my %h_inner = (
   %{ $VAR1->{p} },
   %{ $VAR2->{p} },
);

my %h_outer = ( p => \%h_inner );
```

<p>We could also use the anonymous hash constructor (<code>{}</code>) instead.</p>

<pre class="lang-perl prettyprint-override"><code>my %h_outer = (
   p => {
      %{ $VAR1->{p} },
      %{ $VAR2->{p} },
   },
};
</code>```

Docs:

perlreftut

perllol

Check version compatibility here.

Body:
I am trying to merge these hashmaps in perl and unable to figure out how to do it when the key is identical. The desired input is VAR1 and VAR2 and output is mentioned as well.

Input:

my $VAR1 = { 'p'=> { 'a' => 2,
                     'b' => 3}};

my $VAR2 = { 'p'=> { 'c' => 4,
                     'd' => 7}};

Desired Output:

{'p'=> {
        'a' => 2,
        'b' => 3,
        'c' => 4,
        'd' => 7}};

Body:
Say you had

my %h1 = ( a => 2, b => 3 );
my %h2 = ( c => 4, d => 7 );

To combine them into a third hash, you can use

my %h = ( %h1, %h2 );

It would be as if you had done

my %h = ( a => 2, b => 3, c => 4, d => 7 );

Any keys in common will be taken from the hash later in the list.

In your case, you have anonymous hashes. So where we would have used %NAME, we will use %BLOCK, where the block returns a reference to the hash we want to use. This gives us the following:

my %h_inner = (
   %{ $VAR1->{p} },
   %{ $VAR2->{p} },
);

This can also be written as follows:[1]

my %h_inner = (
   $VAR1->{p}->%*,
   $VAR2->{p}->%*,
);

Finally, you also want to second new hash with a single element keyed with p whose value is a reference to this first new hash.

my %h_outer = ( p => \%h_inner );

So, all together, you want

my %h_inner = (
   %{ $VAR1->{p} },
   %{ $VAR2->{p} },
);

my %h_outer = ( p => \%h_inner );

We could also use the anonymous hash constructor ({}) instead.

my %h_outer = (
   p => {
      %{ $VAR1->{p} },
      %{ $VAR2->{p} },
   },
};

Docs:

perlreftut

perllol

Check version compatibility here.


问:
Create a CSV file of a 2D matrix of zeros using bash, or tiniest bit of python where not possible in bash
This is for a numerical data science application. I need to create a matrix of zeros, in a file, separated by commas (within a line) and ending with newline (at end of each line). This bash code was the closest:

```<code>l=`python -c "print(f'{\"0, \" * 9}0')"`  # 10 zeros comma separated in one line
yes $l | head -n 3  # print line 3 times
0, 0, 0, 0, 0, 0, 0, 0, 0, 0
0, 0, 0, 0, 0, 0, 0, 0, 0, 0
0, 0, 0, 0, 0, 0, 0, 0, 0, 0
</code>```

That’s fine as far as it goes, until you try to change the two literals 9 and 3 to shell variables. However, it is difficult (to me) to code it correctly to replace literal 9 with a shell variable n=9. I tried using bash and python but still not working.
For example these two different attempts don’t actually work (for me) with variables:

```<code>l=$(printf '0,%.0s' {1..$((n-1))}; printf '0')  # 100% bash code
yes $l | head -n $k  # print line 3 times
0,0
0,0
0,0

l=`python -c "print(f'{\"0, \" * 9}0')"`  # using a bit of python, 10 literal zeros comma separated in one line
yes $l | head -n 3  # print line 3 times
0, 0, 0, 0, 0, 0, 0, 0, 0, 0
0, 0, 0, 0, 0, 0, 0, 0, 0, 0
0, 0, 0, 0, 0, 0, 0, 0, 0, 0
</code>```

In this case, changing literal 9 to variable in the python was even worse, and gave me something crazy, like some kind of directory listing, which I definitely don’t want.

Body:
This is for a numerical data science application. I need to create a matrix of zeros, in a file, separated by commas (within a line) and ending with newline (at end of each line). This bash code was the closest:

l=`python -c "print(f'{\"0, \" * 9}0')"`  # 10 zeros comma separated in one line
yes $l | head -n 3  # print line 3 times
0, 0, 0, 0, 0, 0, 0, 0, 0, 0
0, 0, 0, 0, 0, 0, 0, 0, 0, 0
0, 0, 0, 0, 0, 0, 0, 0, 0, 0

That’s fine as far as it goes, until you try to change the two literals 9 and 3 to shell variables. However, it is difficult (to me) to code it correctly to replace literal 9 with a shell variable n=9. I tried using bash and python but still not working.
For example these two different attempts don’t actually work (for me) with variables:

l=$(printf '0,%.0s' {1..$((n-1))}; printf '0')  # 100% bash code
yes $l | head -n $k  # print line 3 times
0,0
0,0
0,0

l=`python -c "print(f'{\"0, \" * 9}0')"`  # using a bit of python, 10 literal zeros comma separated in one line
yes $l | head -n 3  # print line 3 times
0, 0, 0, 0, 0, 0, 0, 0, 0, 0
0, 0, 0, 0, 0, 0, 0, 0, 0, 0
0, 0, 0, 0, 0, 0, 0, 0, 0, 0

In this case, changing literal 9 to variable in the python was even worse, and gave me something crazy, like some kind of directory listing, which I definitely don’t want.

Body:
In pure bash:

#!/usr/bin/env bash
cols=$1
rows=$2
declare -a row
for ((i = 0; i < cols; i++)); do
    row+=(0)
done
IFS=, line="${row[*]}"
for ((i = 0; i < rows; i++)); do
    echo "$line"
done

Example:

$ ./demo.sh 10 3
0,0,0,0,0,0,0,0,0,0
0,0,0,0,0,0,0,0,0,0
0,0,0,0,0,0,0,0,0,0


问:
selecting a subset of a matrix
I am new to R and feel a bit stupid asking this question.

Below is my code. Say if my data is a matrix of 100 rows and 3 columns. I want to split my data into train and test data using the first 80 rows as my training data & the last 20 as my testing data.

However running the code below, I can see x_test & y_test both have 100 rows, why?

```<code>data_dim <- dim(data_input)
split_row <- round(data_dim[1] * 0.8)

x_train <- data_input[1:split_row, 1 : data_dim[2]-1]
y_train <- data_input[1:split_row, data_dim[2]]
x_test <- data_input[split_row + 1 : data_dim[1], 1 : data_dim[2]-1]
y_test <- data_input[split_row + 1 : data_dim[1], data_dim[2]]
</code>```

答:
I recommend looking into tidymodels</p>

```<code>library(tidyverse)
library(rsample)

mtcars_split <- mtcars %>% initial_split(prop = .8)
train <- mtcars_split %>% training()
test <- mtcars_split %>% testing()

# Should not be needed on tidymodels

y_train <- train %>% select(mpg)
x_train <- train %>% select(-mpg)

y_test <- test %>% select(mpg)
x_test <- test %>% select(-mpg)
</code>```

Title: selecting a subset of a matrix

Body:
I am new to R and feel a bit stupid asking this question.

Below is my code. Say if my data is a matrix of 100 rows and 3 columns. I want to split my data into train and test data using the first 80 rows as my training data & the last 20 as my testing data.

However running the code below, I can see x_test & y_test both have 100 rows, why?

data_dim <- dim(data_input)
split_row <- round(data_dim[1] * 0.8)

x_train <- data_input[1:split_row, 1 : data_dim[2]-1]
y_train <- data_input[1:split_row, data_dim[2]]
x_test <- data_input[split_row + 1 : data_dim[1], 1 : data_dim[2]-1]
y_test <- data_input[split_row + 1 : data_dim[1], data_dim[2]]

Body:
I recommend looking into tidymodels

library(tidyverse)
library(rsample)

mtcars_split <- mtcars %>% initial_split(prop = .8)
train <- mtcars_split %>% training()
test <- mtcars_split %>% testing()

# Should not be needed on tidymodels

y_train <- train %>% select(mpg)
x_train <- train %>% select(-mpg)

y_test <- test %>% select(mpg)
x_test <- test %>% select(-mpg)


问:
I have a problem with my MySql 'SELECT' command
I want to get the first id from my table and write it at label16.text to create a pages for my program.Why the following code returns system.threading.tasks.unwrappromise'1[system.object]?

```<code>await sqlConnection.OpenAsync();
SqlCommand command = new SqlCommand("SELECT Id from Recipes order by id asc limit 1", sqlConnection);
label16.Text = command.ExecuteScalarAsync().Result.ToString();
</code>```

答:
You should change

label16.Text = command.ExecuteScalarAsync().Result.ToString();
```

<p>To</p>

<pre class="lang-cs prettyprint-override"><code>var t = await command.ExecuteScalarAsync();
label16.Text = t.Unwrap().ToString();
</code>```

And to fullfill the answer, I'll paste this from comments too.

Another thing you have to do, is fixing your SQL query, it should be

SELECT TOP(1) Id from Recipes order by id asc
```

<p>Third question</p>

<p>I'd do that this way</p>

<pre class="lang-cs prettyprint-override"><code>try
{
    var id = int.Parse(label16.Text);
    sqlDataAdapter = new SqlDataAdapter($"SELECT * FROM Recipes WHERE Id = {id}", sqlConnection);
} catch { // error handling }
</code>```

Body:
I want to get the first id from my table and write it at label16.text to create a pages for my program.Why the following code returns system.threading.tasks.unwrappromise'1[system.object]?

await sqlConnection.OpenAsync();
SqlCommand command = new SqlCommand("SELECT Id from Recipes order by id asc limit 1", sqlConnection);
label16.Text = command.ExecuteScalarAsync().Result.ToString();

Body:
You should change

label16.Text = command.ExecuteScalarAsync().Result.ToString();

To

var t = await command.ExecuteScalarAsync();
label16.Text = t.Unwrap().ToString();

And to fullfill the answer, I'll paste this from comments too.

Another thing you have to do, is fixing your SQL query, it should be

SELECT TOP(1) Id from Recipes order by id asc

Third question

I'd do that this way

try
{
    var id = int.Parse(label16.Text);
    sqlDataAdapter = new SqlDataAdapter($"SELECT * FROM Recipes WHERE Id = {id}", sqlConnection);
} catch { // error handling }


问:
Valgrind reports memory leak on QThread::start()
The issue is on VMware, somehow 3D acceleration causes memory leak and SIGSEGV, resulting in program crashing.

=============================

I have a problem with following codes:

```<code>    gc = new GameController(scene);
    subthread = new QThread(this);
    gc->moveToThread(subthread);
    subthread->start();
</code>```

This should be a regular sub-thread initialization, but valgrind memory analyzer says:

```<code>416 bytes in 1 blocks are possibly lost in loss record 8,318 of 8,856
  in Widget::Widget(QWidget*) in /home/closer_ex/QtProjects/LifeGameWithTest/LifeGame/widget.cpp:15
  1: calloc in /builddir/build/BUILD/valgrind-3.15.0/coregrind/m_replacemalloc/vg_replace_malloc.c:762
  2: allocate_dtv in /usr/lib64/ld-2.28.so
  3: _dl_allocate_tls in /usr/lib64/ld-2.28.so
  4: pthread_create@@GLIBC_2.2.5 in /usr/lib64/libpthread-2.28.so
  5: QThread::start(QThread::Priority) in /home/closer_ex/Qt5.13.2/5.13.2/gcc_64/lib/libQt5Core.so.5.13.2
  6: Widget::Widget(QWidget*) in /home/closer_ex/QtProjects/LifeGameWithTest/LifeGame/widget.cpp:15
  7: main in /home/closer_ex/QtProjects/LifeGameWithTest/LifeGame/main.cpp:8
</code>```

directly pointing to subthread->start().
The scene is not the parent but a QGraphicsScene pointer passed to do some computing in sub-thread, and I manually delete gc after quit()&wait() subthread in my destructor. The program runs smoothly, but I cant do any memory analyzing because of this.

There are 2 definite leaks if I check External Errors, leading to QApplication a(argc, argv); and malloc in 'vg_replace_malloc.c'.

```<code>544 bytes in 11 blocks are definitely lost in loss record 8,418 of 8,861
  in _dl_close_worker in /usr/lib64/ld-2.28.so
  1: malloc in /builddir/build/BUILD/valgrind-3.15.0/coregrind/m_replacemalloc/vg_replace_malloc.c:309
  2: _dl_close_worker in /usr/lib64/ld-2.28.so
  3: _dl_close in /usr/lib64/ld-2.28.so
  4: _dl_catch_exception in /usr/lib64/libc-2.28.so
  5: _dl_catch_error in /usr/lib64/libc-2.28.so
  6: _dlerror_run in /usr/lib64/libdl-2.28.so
  7: dlclose in /usr/lib64/libdl-2.28.so
  8: g_module_close in /usr/lib64/libgmodule-2.0.so.0.5600.4
  9: /usr/lib64/libgio-2.0.so.0.5600.4
  10: g_type_module_unuse in /usr/lib64/libgobject-2.0.so.0.5600.4
  11: /usr/lib64/libgio-2.0.so.0.5600.4
  12: g_io_extension_point_get_extensions in /usr/lib64/libgio-2.0.so.0.5600.4
  13: /usr/lib64/libgio-2.0.so.0.5600.4
  14: g_settings_backend_get_default in /usr/lib64/libgio-2.0.so.0.5600.4
  15: /usr/lib64/libgio-2.0.so.0.5600.4
  16: /usr/lib64/libgobject-2.0.so.0.5600.4
  17: g_object_new_valist in /usr/lib64/libgobject-2.0.so.0.5600.4
  18: g_object_new in /usr/lib64/libgobject-2.0.so.0.5600.4
  19: g_settings_new_full in /usr/lib64/libgio-2.0.so.0.5600.4
  20: /usr/lib64/libgdk-3.so.0.2200.30
  21: /usr/lib64/libgdk-3.so.0.2200.30
  22: gdk_display_manager_open_display in /usr/lib64/libgdk-3.so.0.2200.30
  23: gtk_init_check in /usr/lib64/libgtk-3.so.0.2200.30
  24: gtk_init in /usr/lib64/libgtk-3.so.0.2200.30
  25: QGtk3Theme::QGtk3Theme() in /home/closer_ex/Qt5.13.2/5.13.2/gcc_64/plugins/platformthemes/libqgtk3.so
</code>```

Where could the leak happen?

答:
You're using the GTK+ style in your Qt application. That's clearly visible in the call stack from the crash: all those symbols that contain gtk in them are the GTK+ Qt style. This is bad news in most cases as far as profiling or memory leak testing is concerned.

Start your program like myprogram -style Fusion - that way the GTK+ style won't be used.

For example, to start it under valgrind:

```<code>valgrind myprogram -style Fusion
</code>```

You don't want to be fixing GTK and Qt/GTK interop layer bugs along with your own code :)

Body:
The issue is on VMware, somehow 3D acceleration causes memory leak and SIGSEGV, resulting in program crashing.

=============================

I have a problem with following codes:

    gc = new GameController(scene);
    subthread = new QThread(this);
    gc->moveToThread(subthread);
    subthread->start();

This should be a regular sub-thread initialization, but valgrind memory analyzer says:

416 bytes in 1 blocks are possibly lost in loss record 8,318 of 8,856
  in Widget::Widget(QWidget*) in /home/closer_ex/QtProjects/LifeGameWithTest/LifeGame/widget.cpp:15
  1: calloc in /builddir/build/BUILD/valgrind-3.15.0/coregrind/m_replacemalloc/vg_replace_malloc.c:762
  2: allocate_dtv in /usr/lib64/ld-2.28.so
  3: _dl_allocate_tls in /usr/lib64/ld-2.28.so
  4: pthread_create@@GLIBC_2.2.5 in /usr/lib64/libpthread-2.28.so
  5: QThread::start(QThread::Priority) in /home/closer_ex/Qt5.13.2/5.13.2/gcc_64/lib/libQt5Core.so.5.13.2
  6: Widget::Widget(QWidget*) in /home/closer_ex/QtProjects/LifeGameWithTest/LifeGame/widget.cpp:15
  7: main in /home/closer_ex/QtProjects/LifeGameWithTest/LifeGame/main.cpp:8

directly pointing to subthread->start().
The scene is not the parent but a QGraphicsScene pointer passed to do some computing in sub-thread, and I manually delete gc after quit()&wait() subthread in my destructor. The program runs smoothly, but I cant do any memory analyzing because of this.

There are 2 definite leaks if I check External Errors, leading to QApplication a(argc, argv); and malloc in 'vg_replace_malloc.c'.

544 bytes in 11 blocks are definitely lost in loss record 8,418 of 8,861
  in _dl_close_worker in /usr/lib64/ld-2.28.so
  1: malloc in /builddir/build/BUILD/valgrind-3.15.0/coregrind/m_replacemalloc/vg_replace_malloc.c:309
  2: _dl_close_worker in /usr/lib64/ld-2.28.so
  3: _dl_close in /usr/lib64/ld-2.28.so
  4: _dl_catch_exception in /usr/lib64/libc-2.28.so
  5: _dl_catch_error in /usr/lib64/libc-2.28.so
  6: _dlerror_run in /usr/lib64/libdl-2.28.so
  7: dlclose in /usr/lib64/libdl-2.28.so
  8: g_module_close in /usr/lib64/libgmodule-2.0.so.0.5600.4
  9: /usr/lib64/libgio-2.0.so.0.5600.4
  10: g_type_module_unuse in /usr/lib64/libgobject-2.0.so.0.5600.4
  11: /usr/lib64/libgio-2.0.so.0.5600.4
  12: g_io_extension_point_get_extensions in /usr/lib64/libgio-2.0.so.0.5600.4
  13: /usr/lib64/libgio-2.0.so.0.5600.4
  14: g_settings_backend_get_default in /usr/lib64/libgio-2.0.so.0.5600.4
  15: /usr/lib64/libgio-2.0.so.0.5600.4
  16: /usr/lib64/libgobject-2.0.so.0.5600.4
  17: g_object_new_valist in /usr/lib64/libgobject-2.0.so.0.5600.4
  18: g_object_new in /usr/lib64/libgobject-2.0.so.0.5600.4
  19: g_settings_new_full in /usr/lib64/libgio-2.0.so.0.5600.4
  20: /usr/lib64/libgdk-3.so.0.2200.30
  21: /usr/lib64/libgdk-3.so.0.2200.30
  22: gdk_display_manager_open_display in /usr/lib64/libgdk-3.so.0.2200.30
  23: gtk_init_check in /usr/lib64/libgtk-3.so.0.2200.30
  24: gtk_init in /usr/lib64/libgtk-3.so.0.2200.30
  25: QGtk3Theme::QGtk3Theme() in /home/closer_ex/Qt5.13.2/5.13.2/gcc_64/plugins/platformthemes/libqgtk3.so

Where could the leak happen?

Body:
You're using the GTK+ style in your Qt application. That's clearly visible in the call stack from the crash: all those symbols that contain gtk in them are the GTK+ Qt style. This is bad news in most cases as far as profiling or memory leak testing is concerned.

Start your program like myprogram -style Fusion - that way the GTK+ style won't be used.

For example, to start it under valgrind:

valgrind myprogram -style Fusion

You don't want to be fixing GTK and Qt/GTK interop layer bugs along with your own code :)


问:
Change the key name to be the key value structure of a nested JSON
I'm trying to clean a JSON that i request from an API, because the DB insert a key name, key value structure and mess everything, unfortunate i don't have access to the back, so i have to clean the JSON in the front, one of the problems is that the data not always is the same structure, so, i need a recursive solution to iterate in all the nested JSON, the real JSON have more nested childs, but for demonstration purpose i show only a part of the JSON.

This is an example of the structure, but sometimes the structure is not the same, sometimes i don't get the population or one of the values of the population.

```<code>[
  { "Name": "code", "Value": "18187" },
  { "Name": "date", "Value": "2020-05-10" },
  {
    "Name": "countries",
    "Value": [
      [
        { "Name": "id", "Value": "1" },
        { "Name": "name", "Value": "Canada" },
        {
          "Name": "population",
          "Value": [
            [
              { "Name": "id", "Value": "1" },
              { "Name": "male", "Value": "1000" }
            ],
            [
              { "Name": "id", "Value": "2" },
              { "Name": "female", "Value": "1000" }
            ]
          ]
        }
      ],
      [
        { "Name": "id", "Value": "2" },
        { "Name": "name", "Value": "Italy" },
        {
          "Name": "population",
          "Value": [
            [
              { "Name": "id", "Value": "1" },
              { "Name": "male", "Value": "1000" }
            ],
            [
              { "Name": "id", "Value": "2" },
              { "Name": "female", "Value": "1000" }
            ]
          ]
        }
      ]
    ]
  }
]

</code>```

And i'm trying to clean all the key name, key value, to get something like this:

```<code>[
  { "code": "18187" },
  { "date": "2020-05-10" },
  {
    "countries": [
      [
        { "id": "1" },
        { "name": "Canada" },
        {
          "population": [
            { "male": "1000" },
            { "female": "1000" }
          ]
        }
      ],
      [
        { "id": "2" },
        { "name": "Italy" },
        {
          "population": [
            { "male": "1000" },
            { "female": "1000" }
          ]
        }
      ]
    ]
  }
]
</code>```

答:
You could do with recursive function that uses map method.

const data = [{"Name":"code","Value":"18187"},{"Name":"date","Value":"2020-05-10"},{"Name":"countries","Value":[[{"Name":"id","Value":"1"},{"Name":"name","Value":"Canada"},{"Name":"population","Value":[[{"Name":"id","Value":"1"},{"Name":"male","Value":"1000"}],[{"Name":"id","Value":"2"},{"Name":"female","Value":"1000"}]]}],[{"Name":"id","Value":"2"},{"Name":"name","Value":"Italy"},{"Name":"population","Value":[[{"Name":"id","Value":"1"},{"Name":"male","Value":"1000"}],[{"Name":"id","Value":"2"},{"Name":"female","Value":"1000"}]]}]]}]

function modify(data) {
  return data.map(e => {
    if (Array.isArray(e)) return modify(e)
    else {
      const { Name, Value } = e;
      return ({
        [Name]: Array.isArray(Value) ?
          modify(Value) : Value
      })
    }
  })
}

const result = modify(data);
console.log(result)```

Body:
I'm trying to clean a JSON that i request from an API, because the DB insert a key name, key value structure and mess everything, unfortunate i don't have access to the back, so i have to clean the JSON in the front, one of the problems is that the data not always is the same structure, so, i need a recursive solution to iterate in all the nested JSON, the real JSON have more nested childs, but for demonstration purpose i show only a part of the JSON.

This is an example of the structure, but sometimes the structure is not the same, sometimes i don't get the population or one of the values of the population.

[
  { "Name": "code", "Value": "18187" },
  { "Name": "date", "Value": "2020-05-10" },
  {
    "Name": "countries",
    "Value": [
      [
        { "Name": "id", "Value": "1" },
        { "Name": "name", "Value": "Canada" },
        {
          "Name": "population",
          "Value": [
            [
              { "Name": "id", "Value": "1" },
              { "Name": "male", "Value": "1000" }
            ],
            [
              { "Name": "id", "Value": "2" },
              { "Name": "female", "Value": "1000" }
            ]
          ]
        }
      ],
      [
        { "Name": "id", "Value": "2" },
        { "Name": "name", "Value": "Italy" },
        {
          "Name": "population",
          "Value": [
            [
              { "Name": "id", "Value": "1" },
              { "Name": "male", "Value": "1000" }
            ],
            [
              { "Name": "id", "Value": "2" },
              { "Name": "female", "Value": "1000" }
            ]
          ]
        }
      ]
    ]
  }
]

And i'm trying to clean all the key name, key value, to get something like this:

[
  { "code": "18187" },
  { "date": "2020-05-10" },
  {
    "countries": [
      [
        { "id": "1" },
        { "name": "Canada" },
        {
          "population": [
            { "male": "1000" },
            { "female": "1000" }
          ]
        }
      ],
      [
        { "id": "2" },
        { "name": "Italy" },
        {
          "population": [
            { "male": "1000" },
            { "female": "1000" }
          ]
        }
      ]
    ]
  }
]


问:
How to make python read a file to make sure it's fits the restrictions
I have the code where you read a file called ranks and you have to make sure that the

Rank - Word of Size 15 or less - the Name of the Card

Power - Integer less than 100 - the Power of the Card

Number - Integer less than 100 - the Number of these cards

and then you're supposed to store each of those fields into their own lists. This is what I have so far. I'm not sure how to do the rest.

```<code># Reading from a file
numFile = open("ranks.dat", "r")

while True:
    text = numFile.readline()
    text = text.rstrip("\n")
    if text=="":
        break
    print (text, end = "\t")

numFile.close()

</code>```

An example of a ranks file could be:

```<code>Captain,40,2
General,35,1
Lieutenant,25,2
Colonel,20,3
Major,15,2
Admiral,10,5
Corporal,5,6
Sergeant,4,4
Private,1,10
</code>```

答:
```<code>with open(file, "r") as f:
    for line in f:
        arr = line.split(",")
        if len(arr[0]) > 15:
            # length condition not met, write necessary code here
            pass
        elif int(arr[1]) > 100:
            # power greater than 100, write necessary code here
            pass
        elif int(arr[2]) > 100:
            # number greater than 100, write necessary code here
            pass
</code>```

Always use with to open a file so that you don't have to worry about closing the file.

```<code>while True:
    ...
    if text=="":
        break
</code>```

This is not a good way to read a file. Better use .readlines() or a loop on the file.

Body:
I have the code where you read a file called ranks and you have to make sure that the

Rank - Word of Size 15 or less - the Name of the Card

Power - Integer less than 100 - the Power of the Card

Number - Integer less than 100 - the Number of these cards

and then you're supposed to store each of those fields into their own lists. This is what I have so far. I'm not sure how to do the rest.

# Reading from a file
numFile = open("ranks.dat", "r")

while True:
    text = numFile.readline()
    text = text.rstrip("\n")
    if text=="":
        break
    print (text, end = "\t")

numFile.close()

An example of a ranks file could be:

Captain,40,2
General,35,1
Lieutenant,25,2
Colonel,20,3
Major,15,2
Admiral,10,5
Corporal,5,6
Sergeant,4,4
Private,1,10

Body:
with open(file, "r") as f:
    for line in f:
        arr = line.split(",")
        if len(arr[0]) > 15:
            # length condition not met, write necessary code here
            pass
        elif int(arr[1]) > 100:
            # power greater than 100, write necessary code here
            pass
        elif int(arr[2]) > 100:
            # number greater than 100, write necessary code here
            pass

Always use with to open a file so that you don't have to worry about closing the file.

while True:
    ...
    if text=="":
        break

This is not a good way to read a file. Better use .readlines() or a loop on the file.


问:
Having problems editing text files in java
Hey there somy code below is supposed to do one thing its hard to explain but i will try
for example this is the content of my txt file

```<code>atif12,123,0
kamran11,134,0
abh3,123,0
</code>```

now if my username is kamran 11 and password is 134 which I entered so this program should turn the 0 to 500 and keep the rest as it is but my file gets updated and only shows this

```<code>kamran11,134,500
</code>```

thus all is deleted and I don't know where I went wrong can someone correct me, please?

```<code>         File file = new File("customer.txt");//this is the txtfile
                        ArrayList<String> lines = new ArrayList<>();

                        try (Scanner in = new Scanner(file)) {
                            while (in.hasNext()) {
                                lines.add(in.nextLine());
                            }
                        } catch (FileNotFoundException eo) {
                            throw new RuntimeException("File not found");
                        }

                        String comp=username+","+pass;

                        try (FileWriter out = new FileWriter(file)) {

                            for (int i = 0; i < lines.size(); i++) { //iterate over lines
                                String comp2=lines.get(i);
                                System.out.println(comp2);
                                if(comp2.contains(comp)){
                                String[] parts = lines.get(i).split(","); //split line by commas

                                for (int j = 0; j < parts.length; j++) { //iterate over parts
                                    if (j == 2) { //if I hit the first element in this line that is a zero
                                        int temp = Integer.parseInt(parts[j]);
                                        temp = temp + 500;
                                        parts[j] = Integer.toString(temp);
                                        break; //break out of the loop
                                    }
                                }

                                for (int j = 0; j < parts.length; j++) { //iterate over all the parts and write them back
                                     System.out.println("this work");
                                    out.write(parts[j]);

                                    if (j < parts.length - 1) { //only add a comma if it isn't at the end of the line
                                        out.write(',');
                                    }
                                }

                                if (i < lines.size() - 1) { //add a line break if it isn't the last line
                                    System.out.println("this work1");
                                    out.write('\n');
                                }
                                //break;
                            }
                                else{
                                    System.out.println("this dont work");
                                }

                        }

                            out.flush(); //write everything to the file
                        } catch (IOException ep) {
                            throw new RuntimeException("IO exception occurred");
                        }
</code>```

答:
Based on our discussion here, and the information provided in this question, I believe you want the following:</p>

```<code>File file = new File("customer.txt");
ArrayList<String> lines = new ArrayList<>();
Scanner sc = new Scanner(System.in);
String user = sc.nextLine(); //ask user for the username
String pwd = sc.nextLine(); //ask user for the password

try (Scanner in = new Scanner(file)) {
    while (in.hasNext()) { //read in all lines
        lines.add(in.nextLine());
    }
} catch (FileNotFoundException e) {
    throw new RuntimeException("File not found");
}

try (FileWriter out = new FileWriter(file)) {
    for (int i = 0; i < lines.size(); i++) { //iterate over lines
        String[] parts = lines.get(i).split(","); //split line by commas

        if (parts[0].equals(user) && parts[1].equals(pwd)) { //if username and password match first and second parts of line, respectively
            parts[2] = "500"; //set third part of line to 500
        }

        for (int j = 0; j < parts.length; j++) { //iterate over all the parts and write them back
            out.write(parts[j]);

            if (j < parts.length - 1) { //only add a comma if it isn't at the end of the line
                out.write(',');
            }
        }

        if (i < lines.size() - 1) { //add a line break if it isn't the last line
            out.write('\n');
        }
    }

    out.flush(); //write everything to the file
} catch (IOException e) {
    throw new RuntimeException("IO exception occurred");
}
</code>```

Body:
Hey there somy code below is supposed to do one thing its hard to explain but i will try
for example this is the content of my txt file

atif12,123,0
kamran11,134,0
abh3,123,0

now if my username is kamran 11 and password is 134 which I entered so this program should turn the 0 to 500 and keep the rest as it is but my file gets updated and only shows this

kamran11,134,500

thus all is deleted and I don't know where I went wrong can someone correct me, please?

         File file = new File("customer.txt");//this is the txtfile
                        ArrayList<String> lines = new ArrayList<>();

                        try (Scanner in = new Scanner(file)) {
                            while (in.hasNext()) {
                                lines.add(in.nextLine());
                            }
                        } catch (FileNotFoundException eo) {
                            throw new RuntimeException("File not found");
                        }

                        String comp=username+","+pass;

                        try (FileWriter out = new FileWriter(file)) {

                            for (int i = 0; i < lines.size(); i++) { //iterate over lines
                                String comp2=lines.get(i);
                                System.out.println(comp2);
                                if(comp2.contains(comp)){
                                String[] parts = lines.get(i).split(","); //split line by commas

                                for (int j = 0; j < parts.length; j++) { //iterate over parts
                                    if (j == 2) { //if I hit the first element in this line that is a zero
                                        int temp = Integer.parseInt(parts[j]);
                                        temp = temp + 500;
                                        parts[j] = Integer.toString(temp);
                                        break; //break out of the loop
                                    }
                                }

                                for (int j = 0; j < parts.length; j++) { //iterate over all the parts and write them back
                                     System.out.println("this work");
                                    out.write(parts[j]);

                                    if (j < parts.length - 1) { //only add a comma if it isn't at the end of the line
                                        out.write(',');
                                    }
                                }

                                if (i < lines.size() - 1) { //add a line break if it isn't the last line
                                    System.out.println("this work1");
                                    out.write('\n');
                                }
                                //break;
                            }
                                else{
                                    System.out.println("this dont work");
                                }

                        }

                            out.flush(); //write everything to the file
                        } catch (IOException ep) {
                            throw new RuntimeException("IO exception occurred");
                        }

Body:
Based on our discussion here, and the information provided in this question, I believe you want the following:

File file = new File("customer.txt");
ArrayList<String> lines = new ArrayList<>();
Scanner sc = new Scanner(System.in);
String user = sc.nextLine(); //ask user for the username
String pwd = sc.nextLine(); //ask user for the password

try (Scanner in = new Scanner(file)) {
    while (in.hasNext()) { //read in all lines
        lines.add(in.nextLine());
    }
} catch (FileNotFoundException e) {
    throw new RuntimeException("File not found");
}

try (FileWriter out = new FileWriter(file)) {
    for (int i = 0; i < lines.size(); i++) { //iterate over lines
        String[] parts = lines.get(i).split(","); //split line by commas

        if (parts[0].equals(user) && parts[1].equals(pwd)) { //if username and password match first and second parts of line, respectively
            parts[2] = "500"; //set third part of line to 500
        }

        for (int j = 0; j < parts.length; j++) { //iterate over all the parts and write them back
            out.write(parts[j]);

            if (j < parts.length - 1) { //only add a comma if it isn't at the end of the line
                out.write(',');
            }
        }

        if (i < lines.size() - 1) { //add a line break if it isn't the last line
            out.write('\n');
        }
    }

    out.flush(); //write everything to the file
} catch (IOException e) {
    throw new RuntimeException("IO exception occurred");
}


问:
Private Google Access for cross project bucket access
Does Google private access allow access to Google Storage bucket available in a different project (cross-project access)? We would like to access the Google bucket without an external IP attached to the machine (and possibly without NAT as the dataset we have is huge).</p>

答:
Referencing to your query, for accessing the Cloud Storage Bucket without External IP:

1) If you are accessing from the GCP project through Google APIs for domains restricted.googleapis.com or private.googleapis.com then you need to configure DNS such that VMs in your VPC network resolve requests to *.googleapis.com and *.gcr.io using the set of IP addresses associated with the chosen domain.

2) If you are accessing outside of GCP projects ( on prem ) then by configuring the Cloud VPN or Cloud Interconnect by connecting to Google APIs and services by using the virtual IP addresses (VIPs)


问:
Loop to display time in react
I am new to react and want to render the below code

```<code><div className="timeSection">
    <input type="radio" id="control_001" name="select"  />
    <label htmlFor="control_001"><h4>00:00 - 01:00</h4></label>
</div>
<div className="timeSection">
    <input type="radio" id="control_001" name="select"  />
    <label htmlFor="control_001"><h4>01:00 - 02:00</h4></label>
</div>
<div className="timeSection">
    <input type="radio" id="control_001" name="select"  />
    <label htmlFor="control_001"><h4>02:00-03:00</h4></label>
</div>
<div className="timeSection">
    <input type="radio" id="control_001" name="select"  />
    <label htmlFor="control_001"><h4>03:00 - 04:00</h4></label>
</div>
</code>```

I want to run a loop to change the values between
00:00 - 01:00
 to display between 00 to 24, please assist

答:
const MyComponent = () => {

  // I think you can find smarter ways to create this array depends on your logic
  // But you better not do so much array operation inside component, unless you really need it. Because it runs in every render!
  // Do array operations (loops, map, filters) outside of component so that it won't need to run in every render.
  const arr = ["00:00 - 01:00", "01:00 - 02:00"];

  return (

      {arr.map((intervalStr)=>

        <input type="radio" id="control_001" name="select"  />

{intervalStr}

)}

  )
}

```

Title: Loop to display time in react

Body:
I am new to react and want to render the below code

    <input type="radio" id="control_001" name="select"  />

00:00 - 01:00

    <input type="radio" id="control_001" name="select"  />

01:00 - 02:00

    <input type="radio" id="control_001" name="select"  />

02:00-03:00

    <input type="radio" id="control_001" name="select"  />

03:00 - 04:00

I want to run a loop to change the values between
00:00 - 01:00
 to display between 00 to 24, please assist

Body:
const MyComponent = () => {

  // I think you can find smarter ways to create this array depends on your logic
  // But you better not do so much array operation inside component, unless you really need it. Because it runs in every render!
  // Do array operations (loops, map, filters) outside of component so that it won't need to run in every render.
  const arr = ["00:00 - 01:00", "01:00 - 02:00"];

  return (
    <div>
      {arr.map((intervalStr)=><div className="timeSection">
        <input type="radio" id="control_001" name="select"  />
        <label htmlFor="control_001"><h4>{intervalStr}</h4></label>
      </div>)}
    </div>
  )
}


答:
Sorry to answer my own question but as often happens, I figured out a good working answer soon after posting!  I just combined a couple of other SO answers together. Thank you in advance for other people that find anything simpler than mine, as always.

This works right:

```<code>export n
yes `python -c "import os; n=int(os.environ['n']); print(f'{\"0.0, \" * n}0.0')"` | head -n $k
0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0
0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0
0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0
</code>```

This still might help other numerical programmers in my opinion.

Title: Create a CSV file of a 2D matrix of zeros using bash, or tiniest bit of python where not possible in bash

Body:
Sorry to answer my own question but as often happens, I figured out a good working answer soon after posting!  I just combined a couple of other SO answers together. Thank you in advance for other people that find anything simpler than mine, as always.

This works right:

export n
yes `python -c "import os; n=int(os.environ['n']); print(f'{\"0.0, \" * n}0.0')"` | head -n $k
0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0
0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0
0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0

This still might help other numerical programmers in my opinion.


问:
Why is my VBScript throwing nine Pop Ups instead of one?
I have a Win7 64 bit Windows Professional Laptop. I have a VB Script taken from the net  and with certain alterations I am trying to  get  at Link speed for all Adaptors on my Laptop. The Vb script seems to be working except that I have to enter 9 times to get a complete list of all instances. This means that  when I double click the  script, the pop up shows only one instance. When I  press Enter again, it shows the  first and the second one, and likewise till I press Enter, nine times, I get the complete list, in one Pop Up. I know this is possible on the command prompt using CScript, but I prefer to get a single Popup. I am  not very versatile on VBScripts but I am willing to learn. Am I missing something ? Any help will be appreciated. Here's my script.</p>

```<code>strComputer = "."
strRslt = Wscript.ScriptName _
    & vbTab & "Computer Information " & vbcr _
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\WMI")
Set colItems = objWMIService.ExecQuery("SELECT * FROM MSNdis_LinkSpeed" ,,48)
For Each objItem in colItems
strRslt = strRslt & vbNewLine  _
& "InstanceName: " & vbTab & objItem.InstanceName & vbcr _
& "NdisLinkSpeed: " & vbTab & objItem.NdisLinkSpeed/10 & " kbps"
msgbox strRslt,&h51000, "speed"
Next
</code>```

答:
The issue is a simple one that many can make when first starting out with VBScript or other similar languages.

The For Each statement will iterate through a list of objects until it reaches the end of the list, in this case nine object instances. The command is structured in such a way that any commands within the For and Next block will be executed for the current instance that is identified by the variable after Each.
As the MsgBox() function is running inside the For it will be displayed for each object instance.

If you didn’t expect this the simple fix is to move the MsgBox() outside of the loop.

```<code>For Each objItem in colItems
    strRslt = strRslt & vbNewLine  _
    & "InstanceName: " & vbTab & objItem.InstanceName & vbcr _
    & "NdisLinkSpeed: " & vbTab & objItem.NdisLinkSpeed/10 & " kbps"
Next
msgbox strRslt,&h51000, "speed"
</code>```

Body:
I have a Win7 64 bit Windows Professional Laptop. I have a VB Script taken from the net  and with certain alterations I am trying to  get  at Link speed for all Adaptors on my Laptop. The Vb script seems to be working except that I have to enter 9 times to get a complete list of all instances. This means that  when I double click the  script, the pop up shows only one instance. When I  press Enter again, it shows the  first and the second one, and likewise till I press Enter, nine times, I get the complete list, in one Pop Up. I know this is possible on the command prompt using CScript, but I prefer to get a single Popup. I am  not very versatile on VBScripts but I am willing to learn. Am I missing something ? Any help will be appreciated. Here's my script.

strComputer = "."
strRslt = Wscript.ScriptName _
    & vbTab & "Computer Information " & vbcr _
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\WMI")
Set colItems = objWMIService.ExecQuery("SELECT * FROM MSNdis_LinkSpeed" ,,48)
For Each objItem in colItems
strRslt = strRslt & vbNewLine  _
& "InstanceName: " & vbTab & objItem.InstanceName & vbcr _
& "NdisLinkSpeed: " & vbTab & objItem.NdisLinkSpeed/10 & " kbps"
msgbox strRslt,&h51000, "speed"
Next

Body:
The issue is a simple one that many can make when first starting out with VBScript or other similar languages.

The For Each statement will iterate through a list of objects until it reaches the end of the list, in this case nine object instances. The command is structured in such a way that any commands within the For and Next block will be executed for the current instance that is identified by the variable after Each.
As the MsgBox() function is running inside the For it will be displayed for each object instance.

If you didn’t expect this the simple fix is to move the MsgBox() outside of the loop.

For Each objItem in colItems
    strRslt = strRslt & vbNewLine  _
    & "InstanceName: " & vbTab & objItem.InstanceName & vbcr _
    & "NdisLinkSpeed: " & vbTab & objItem.NdisLinkSpeed/10 & " kbps"
Next
msgbox strRslt,&h51000, "speed"


答:
You can fill an array with the numbers, then you can generate the div to each member of the array.

I added a small function to add leading zeros if neccessary.

Something like this:

```<code>import React from "react";
import "./styles.css";

export default function App() {
  const times = [];
  for (let i = 1; i < 24; i++) {
    times.push(i);
  }

  const zeroPad = num => String(num).padStart(2, "0");

  return (
    <div className="App">
      {times.map(time => (
        <div className="timeSection">
          <input type="radio" id="control_001" name="select" />
          <label htmlFor="control_001">
            <h4>{`${zeroPad(time)}:00 - ${zeroPad(time + 1)}:00`}</h4>
          </label>
        </div>
      ))}
    </div>
  );
}
</code>```

https://codesandbox.io/s/nameless-cherry-u3k6h?file=/src/App.js:0-550

Title: Loop to display time in react

Body:
You can fill an array with the numbers, then you can generate the div to each member of the array.

I added a small function to add leading zeros if neccessary.

Something like this:

import React from "react";
import "./styles.css";

export default function App() {
  const times = [];
  for (let i = 1; i < 24; i++) {
    times.push(i);
  }

  const zeroPad = num => String(num).padStart(2, "0");

  return (
    <div className="App">
      {times.map(time => (
        <div className="timeSection">
          <input type="radio" id="control_001" name="select" />
          <label htmlFor="control_001">
            <h4>{`${zeroPad(time)}:00 - ${zeroPad(time + 1)}:00`}</h4>
          </label>
        </div>
      ))}
    </div>
  );
}

https://codesandbox.io/s/nameless-cherry-u3k6h?file=/src/App.js:0-550


问:
Google Map API - ReferenceError: google is not defined
I am learning to create google maps by studying the basic examples from google.
I use Angular Google Maps to display a google map in my angular 9 app.
I get an error in the console ( Uncaught ReferenceError: google is not defined ).I just want to calculate the distance between to points in the map.

home.component.ts

```<code>import { Component, OnInit } from '@angular/core';
declare var google: any;
@Component({

selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']

})
export class HomeComponent implements OnInit {

location: Location
selectedMarker: Marker
origin: any;
destination: any;
distance: String;

ngOnInit(){

this.distance = this.calculateDistance(this.origin, this.destination);

this.origin = {
  lat: 32.6950,
  lng: 35.2820
};
this.destination = {
  lat: 32.6050,
  lng: 35.2020
};

this.location = {
  latitude: 32.6950,
  longitude: 35.2820,
  zoom: 15,
  markers: [
      {
          lat: 32.6950,
          lng: 35.2820
      }
  ]
  }

 this.loadScript('assets/js/jquery-3.3.1.min.js');
 this.loadScript('assets/vendors/appear/jquery.appear.min.js');
 this.loadScript('assets/vendors/jquery.easing/jquery.easing.min.js');
 this.loadScript('assets/js/popper.min.js');
 this.loadScript('assets/js/bootstrap.min.js');
 this.loadScript('assets/vendors/common/common.min.js');
 this.loadScript('assets/vendors/fancybox/jquery.fancybox.min.js');
 this.loadScript('assets/vendors/menu/src/main.menu.js');
 this.loadScript('assets/vendors/owl.carousel/owl.carousel.min.js');
 this.loadScript('assets/vendors/animated-headline/js/animated-headline.js');
 this.loadScript('assets/js/main.js');
 this.loadScript('assets/js/theme.init.js');
 this.loadScript('assets/js/custom.js');

 }

 public loadScript(url: string) {
 const body = <HTMLDivElement> document.body;
 const script = document.createElement('script');
 script.innerHTML = '';
 script.src = url;
 script.async = false;
 script.defer = true;
 body.appendChild(script);
 }

addMarker(lat: number, lng: number) {
this.location.markers.push({
    lat,
    lng
 })
 }

selectMarker(event) {
this.selectedMarker = {
    lat: event.latitude,
    lng: event.longitude
 }
 }

calculateDistance(point1, point2) {

const p1 = new google.maps.LatLng(
point1.lat,
point1.lng
);
const p2 = new google.maps.LatLng(
point2.lat,
point2.lng
);

return (
google.maps.geometry.spherical.computeDistanceBetween(p1, p2)/1000
).toFixed(2);
}

}

interface Marker {
lat: number;
lng: number;
}

interface Location {
latitude: number;
longitude: number;
zoom: number;
markers: Array<Marker>;
}
</code>```

home.component.html

```<code><agm-map [latitude]="location.latitude" [longitude]="location.longitude"
[zoom]="location.zoom" (mapClick)="addMarker($event.coords.lat, $event.coords.lng)">
<!-- ... -->
<agm-direction
    [origin]="origin"
    [destination]="destination"
></agm-direction>
</agm-map>
<div>
 Distance: {{distance}}
 </div>
 <!-- ... -->
</code>```

答:
I had found a solution and this is the code updated </p>

<p>home.component.ts     </p>

```<code>import { Component, OnInit ,ViewChild} from '@angular/core';
import { MapsAPILoader, AgmMap } from '@agm/core';
declare var google: any;

@Component({

  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']

})
export class HomeComponent implements OnInit {

  location: Location
  selectedMarker: Marker
  origin: any;
  destination: any;
  distance: String;
  geocoder: any;

   ngOnInit(){

    this.origin = {
      lat: 32.6950,
      lng: 35.2820
    };
  this.destination = {
      lat: 32.6050,
      lng: 35.2020
   };

    this.location = {
      latitude: 32.6950,
      longitude: 35.2820,
      zoom: 15,
      markers: [
          {
              lat: 32.6950,
              lng: 35.2820
          }
      ]
  }

     this.loadScript('assets/js/jquery-3.3.1.min.js');
     this.loadScript('assets/vendors/appear/jquery.appear.min.js');
     this.loadScript('assets/vendors/jquery.easing/jquery.easing.min.js');
     this.loadScript('assets/js/popper.min.js');
     this.loadScript('assets/js/bootstrap.min.js');
     this.loadScript('assets/vendors/common/common.min.js');
     this.loadScript('assets/vendors/fancybox/jquery.fancybox.min.js');
     this.loadScript('assets/vendors/menu/src/main.menu.js');
     this.loadScript('assets/vendors/owl.carousel/owl.carousel.min.js');
     this.loadScript('assets/vendors/animated-headline/js/animated-headline.js');
     this.loadScript('assets/js/main.js');
     this.loadScript('assets/js/theme.init.js');
     this.loadScript('assets/js/custom.js');
  }

  @ViewChild(AgmMap, { static: true }) map: AgmMap;

  constructor(public mapsApiLoader: MapsAPILoader) {
    this.mapsApiLoader = mapsApiLoader;

    this.mapsApiLoader.load().then(() => {
      this.geocoder = new google.maps.Geocoder();
      this.distance = this.calculateDistance(this.origin, this.destination);
    });
  }

  public loadScript(url: string) {
    const body = <HTMLDivElement> document.body;
    const script = document.createElement('script');
    script.innerHTML = '';
    script.src = url;
    script.async = false;
    script.defer = true;
    body.appendChild(script);
  }

  addMarker(lat: number, lng: number) {
    this.location.markers.push({
        lat,
        lng
    })
  }

  selectMarker(event) {
    this.selectedMarker = {
        lat: event.latitude,
        lng: event.longitude
    }
  }

  calculateDistance(point1, point2) {

    const p1 = new google.maps.LatLng(
    point1.lat,
    point1.lng
    );
    const p2 = new google.maps.LatLng(
    point2.lat,
    point2.lng
    );

    return (
    google.maps.geometry.spherical.computeDistanceBetween(p1, p2)/1000
    ).toFixed(2);
}

}

interface Marker {
lat: number;
lng: number;
}

interface Location {
latitude: number;
longitude: number;
zoom: number;
markers: Array<Marker>;
}
</code>```

Body:
I am learning to create google maps by studying the basic examples from google.
I use Angular Google Maps to display a google map in my angular 9 app.
I get an error in the console ( Uncaught ReferenceError: google is not defined ).I just want to calculate the distance between to points in the map.

home.component.ts

import { Component, OnInit } from '@angular/core';
declare var google: any;
@Component({

selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']

})
export class HomeComponent implements OnInit {

location: Location
selectedMarker: Marker
origin: any;
destination: any;
distance: String;

ngOnInit(){

this.distance = this.calculateDistance(this.origin, this.destination);

this.origin = {
  lat: 32.6950,
  lng: 35.2820
};
this.destination = {
  lat: 32.6050,
  lng: 35.2020
};

this.location = {
  latitude: 32.6950,
  longitude: 35.2820,
  zoom: 15,
  markers: [
      {
          lat: 32.6950,
          lng: 35.2820
      }
  ]
  }

 this.loadScript('assets/js/jquery-3.3.1.min.js');
 this.loadScript('assets/vendors/appear/jquery.appear.min.js');
 this.loadScript('assets/vendors/jquery.easing/jquery.easing.min.js');
 this.loadScript('assets/js/popper.min.js');
 this.loadScript('assets/js/bootstrap.min.js');
 this.loadScript('assets/vendors/common/common.min.js');
 this.loadScript('assets/vendors/fancybox/jquery.fancybox.min.js');
 this.loadScript('assets/vendors/menu/src/main.menu.js');
 this.loadScript('assets/vendors/owl.carousel/owl.carousel.min.js');
 this.loadScript('assets/vendors/animated-headline/js/animated-headline.js');
 this.loadScript('assets/js/main.js');
 this.loadScript('assets/js/theme.init.js');
 this.loadScript('assets/js/custom.js');

 }

 public loadScript(url: string) {
 const body = <HTMLDivElement> document.body;
 const script = document.createElement('script');
 script.innerHTML = '';
 script.src = url;
 script.async = false;
 script.defer = true;
 body.appendChild(script);
 }

addMarker(lat: number, lng: number) {
this.location.markers.push({
    lat,
    lng
 })
 }

selectMarker(event) {
this.selectedMarker = {
    lat: event.latitude,
    lng: event.longitude
 }
 }

calculateDistance(point1, point2) {

const p1 = new google.maps.LatLng(
point1.lat,
point1.lng
);
const p2 = new google.maps.LatLng(
point2.lat,
point2.lng
);

return (
google.maps.geometry.spherical.computeDistanceBetween(p1, p2)/1000
).toFixed(2);
}

}

interface Marker {
lat: number;
lng: number;
}

interface Location {
latitude: number;
longitude: number;
zoom: number;
markers: Array<Marker>;
}

home.component.html

<agm-map [latitude]="location.latitude" [longitude]="location.longitude"
[zoom]="location.zoom" (mapClick)="addMarker($event.coords.lat, $event.coords.lng)">

<agm-direction
    [origin]="origin"
    [destination]="destination"
></agm-direction>
</agm-map>

 Distance: {{distance}}

Body:
I had found a solution and this is the code updated

home.component.ts

import { Component, OnInit ,ViewChild} from '@angular/core';
import { MapsAPILoader, AgmMap } from '@agm/core';
declare var google: any;

@Component({

  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']

})
export class HomeComponent implements OnInit {

  location: Location
  selectedMarker: Marker
  origin: any;
  destination: any;
  distance: String;
  geocoder: any;

   ngOnInit(){

    this.origin = {
      lat: 32.6950,
      lng: 35.2820
    };
  this.destination = {
      lat: 32.6050,
      lng: 35.2020
   };

    this.location = {
      latitude: 32.6950,
      longitude: 35.2820,
      zoom: 15,
      markers: [
          {
              lat: 32.6950,
              lng: 35.2820
          }
      ]
  }

     this.loadScript('assets/js/jquery-3.3.1.min.js');
     this.loadScript('assets/vendors/appear/jquery.appear.min.js');
     this.loadScript('assets/vendors/jquery.easing/jquery.easing.min.js');
     this.loadScript('assets/js/popper.min.js');
     this.loadScript('assets/js/bootstrap.min.js');
     this.loadScript('assets/vendors/common/common.min.js');
     this.loadScript('assets/vendors/fancybox/jquery.fancybox.min.js');
     this.loadScript('assets/vendors/menu/src/main.menu.js');
     this.loadScript('assets/vendors/owl.carousel/owl.carousel.min.js');
     this.loadScript('assets/vendors/animated-headline/js/animated-headline.js');
     this.loadScript('assets/js/main.js');
     this.loadScript('assets/js/theme.init.js');
     this.loadScript('assets/js/custom.js');
  }

  @ViewChild(AgmMap, { static: true }) map: AgmMap;

  constructor(public mapsApiLoader: MapsAPILoader) {
    this.mapsApiLoader = mapsApiLoader;

    this.mapsApiLoader.load().then(() => {
      this.geocoder = new google.maps.Geocoder();
      this.distance = this.calculateDistance(this.origin, this.destination);
    });
  }

  public loadScript(url: string) {
    const body = <HTMLDivElement> document.body;
    const script = document.createElement('script');
    script.innerHTML = '';
    script.src = url;
    script.async = false;
    script.defer = true;
    body.appendChild(script);
  }

  addMarker(lat: number, lng: number) {
    this.location.markers.push({
        lat,
        lng
    })
  }

  selectMarker(event) {
    this.selectedMarker = {
        lat: event.latitude,
        lng: event.longitude
    }
  }

  calculateDistance(point1, point2) {

    const p1 = new google.maps.LatLng(
    point1.lat,
    point1.lng
    );
    const p2 = new google.maps.LatLng(
    point2.lat,
    point2.lng
    );

    return (
    google.maps.geometry.spherical.computeDistanceBetween(p1, p2)/1000
    ).toFixed(2);
}

}

interface Marker {
lat: number;
lng: number;
}

interface Location {
latitude: number;
longitude: number;
zoom: number;
markers: Array<Marker>;
}


问:
Quickest way to migrate win application to web - .NET
I have one win application with presentation layer done as windows forms.
Now I have request to transfer it whole to the web. Of course, this is a lot of work, so I'm wondering is it maybe somehow possible to achieve this without rewriting whole presentation layer to the web forms? I've heard that SAP has some technology to expose same forms in both win and web, so I'm wondering now how did they do it, and is it possible to somehow do this with C#?

I'm in a delicate situation where I have to transfer win client application to web as quickly as possible, disregarding performance or other issues, with as little effort as possible.

I'm using .NET framework (C#), and I should transfer this to ASP.NET.

EDIT: If I transform my win forms to win controls, can I then host them in IE? Maybe this could be fastest way to achieve my goals?

答: You can do some of this with WPF/silverlight but there is no want to host a windows form on the web.</p>


问:
Subtract and Sum Operations On Columns
I have an output like this:

```<code>Volume               c1                     c2
--------------------------------------------------
0                   1000                     0
1-20                 100                    10
20+                   50                    40
</code>```

I get this output by this:

```<code>SELECT
case when volume=0 then '0' when volume <21 then '1-20' when volume>=21 then '21+' as Volume,
sum(ab) as c1,
sum(xy) as c2
FROM
table t
GROUP BY
case when volume=0 then '0' when volume <21 then '1-20' when volume>=21 then '21+'
</code>```

However, I need to get the output just like below. I am trying to subtract sum of c1 column from sum of c2 column and result must be placed at first row under c2 column just like this:

```<code>Volume                c1                  c2
--------------------------------------------------
0                   1000                **1100**
1-20                 100                  10
20+                   50                  40
</code>```

How can I do this?

Thanks in advance.

答:
```<code>WITH x
AS
(
  SELECT
    case when volume=0 then '0' when volume <21 then '1-20' when volume>=21 then '21+' as Volume,
    sum(ab) as c1,
    sum(xy) as c2
  FROM
    table t
  GROUP BY
    CASE when volume=0 then '0' when volume <21 then '1-20' when volume>=21 then '21+'
)
SELECT x.Volume, x.c1, (CASE WHEN x.Volume = 0
                             THEN (SELECT SUM(x2.c1 - x2.c2)
                                   FROM x AS x2)
                             ELSE x.c2 END)
FROM x
</code>```

Title: Subtract and Sum Operations On Columns

Body:
I have an output like this:

Volume               c1                     c2
--------------------------------------------------
0                   1000                     0
1-20                 100                    10
20+                   50                    40

I get this output by this:

SELECT
case when volume=0 then '0' when volume <21 then '1-20' when volume>=21 then '21+' as Volume,
sum(ab) as c1,
sum(xy) as c2
FROM
table t
GROUP BY
case when volume=0 then '0' when volume <21 then '1-20' when volume>=21 then '21+'

However, I need to get the output just like below. I am trying to subtract sum of c1 column from sum of c2 column and result must be placed at first row under c2 column just like this:

Volume                c1                  c2
--------------------------------------------------
0                   1000                **1100**
1-20                 100                  10
20+                   50                  40

How can I do this?

Thanks in advance.


问:
SwiftUI, weird NavigationLink behavior when working with actionSheet
I want to detect if the user meets the prerequisite first before I let him/her in. If the prerequisite is not met, the app will pop an actionSheet and show the user some ways to unlock the feature.
It works perfectly fine when I tap on the text. But when I tap on the blank place on the list. It just skip the Binding. And the weird thing is that in my actually project, the Binding becomes "true" even if I only set it to false.
Here's the question. Am I using the correct approach or did I miss anything? Or is this a bug?
Thank you.

```<code>struct ContentView: View {
    @State var linkOne = false
    @State var linkTwo = false
    @State var linkThree = false
    @State var actionOne = false
    @State var actionTwo = false
    @State var actionThree = false
    var body: some View {
        NavigationView{
            List{
                        NavigationLink("Destination View One", destination: DestOneView(), isActive: self.$linkOne)
                            .actionSheet(isPresented: self.$actionOne) { () -> ActionSheet in
                                ActionSheet(title: Text("Hello"), message:Text("This is weird"), buttons: [ActionSheet.Button.cancel()])
                        }.onTapGesture {
                            self.actionOne = true
//                            self.linkOne = true
                        }
                        NavigationLink("Destination View Two", destination: DestTwoView(), isActive: self.$linkTwo)
                        .actionSheet(isPresented: self.$actionTwo) { () -> ActionSheet in
                        ActionSheet(title: Text("Hello"), message:Text("This is weird"), buttons: [ActionSheet.Button.cancel()])
                        }
                        .onTapGesture {
                            self.actionTwo = true
//                            self.linkTwo = true
                        }
                        NavigationLink("Destination View Three", destination: DestThreeView(), isActive: self.$linkThree)
                        .actionSheet(isPresented: self.$actionThree) { () -> ActionSheet in
                        ActionSheet(title: Text("Hello"), message:Text("This is weird"), buttons: [ActionSheet.Button.cancel()])
                        }
                        .onTapGesture {
                            self.actionThree = true
//                            self.linkThree = true
                        }
                    }
        }

    }
}
</code>```

Three other views.

```<code>struct DestOneView: View {
    var body: some View {
        Text("First View")
    }
}

struct DestTwoView: View {
    var body: some View {
        Text("Second View")
    }
}

struct DestThreeView: View {
    var body: some View {
        Text("Third View")
    }
}
</code>```

答:
When I came back and tested my the code. The solution didn't really work. May be because of the List's bug. People on another post said that the List in the new view only show once if the sheet is inside the List. So I only got an empty List in the new view when I tap the button in Xcode Version 11.5. For some reasion, if I use NavigationView, all contents are shrunk into the middle of the view instead of aligning to the top.

My work around is to set the Binding in .onAppear. It pops the actionSheet when the view loads. And then use the presentationMode method to return to the previous view.

```<code>@Environment(\.presentationMode) var presentationMode
.
.
.
ActionSheet.Button.default(Text("Dismiss"), action: {
          self.presentationMode.wrappedValue.dismiss()}
</code>```

Body:
I want to detect if the user meets the prerequisite first before I let him/her in. If the prerequisite is not met, the app will pop an actionSheet and show the user some ways to unlock the feature.
It works perfectly fine when I tap on the text. But when I tap on the blank place on the list. It just skip the Binding. And the weird thing is that in my actually project, the Binding becomes "true" even if I only set it to false.
Here's the question. Am I using the correct approach or did I miss anything? Or is this a bug?
Thank you.

struct ContentView: View {
    @State var linkOne = false
    @State var linkTwo = false
    @State var linkThree = false
    @State var actionOne = false
    @State var actionTwo = false
    @State var actionThree = false
    var body: some View {
        NavigationView{
            List{
                        NavigationLink("Destination View One", destination: DestOneView(), isActive: self.$linkOne)
                            .actionSheet(isPresented: self.$actionOne) { () -> ActionSheet in
                                ActionSheet(title: Text("Hello"), message:Text("This is weird"), buttons: [ActionSheet.Button.cancel()])
                        }.onTapGesture {
                            self.actionOne = true
//                            self.linkOne = true
                        }
                        NavigationLink("Destination View Two", destination: DestTwoView(), isActive: self.$linkTwo)
                        .actionSheet(isPresented: self.$actionTwo) { () -> ActionSheet in
                        ActionSheet(title: Text("Hello"), message:Text("This is weird"), buttons: [ActionSheet.Button.cancel()])
                        }
                        .onTapGesture {
                            self.actionTwo = true
//                            self.linkTwo = true
                        }
                        NavigationLink("Destination View Three", destination: DestThreeView(), isActive: self.$linkThree)
                        .actionSheet(isPresented: self.$actionThree) { () -> ActionSheet in
                        ActionSheet(title: Text("Hello"), message:Text("This is weird"), buttons: [ActionSheet.Button.cancel()])
                        }
                        .onTapGesture {
                            self.actionThree = true
//                            self.linkThree = true
                        }
                    }
        }

    }
}

Three other views.

struct DestOneView: View {
    var body: some View {
        Text("First View")
    }
}

struct DestTwoView: View {
    var body: some View {
        Text("Second View")
    }
}

struct DestThreeView: View {
    var body: some View {
        Text("Third View")
    }
}

Body:
When I came back and tested my the code. The solution didn't really work. May be because of the List's bug. People on another post said that the List in the new view only show once if the sheet is inside the List. So I only got an empty List in the new view when I tap the button in Xcode Version 11.5. For some reasion, if I use NavigationView, all contents are shrunk into the middle of the view instead of aligning to the top.

My work around is to set the Binding in .onAppear. It pops the actionSheet when the view loads. And then use the presentationMode method to return to the previous view.

@Environment(\.presentationMode) var presentationMode
.
.
.
ActionSheet.Button.default(Text("Dismiss"), action: {
          self.presentationMode.wrappedValue.dismiss()}


问:
How can i resolve this npm errror?
enter image description here

I am doing npm run update and got this error, (unable to update local ref
npm run pull also did not work .

答:
Try these steps. Go to the directory where your package.json resides.

git reset --hard

Delete node-modules

Delete package.lock.json if there's any (don't delete package.json by mistake btw)

npm install

Title: How can i resolve this npm errror?


问:
How to change the chart title width to match slide width in python-pptx?
Hi I have simple code which generates one ppt slide like below but the slide title width is smaller than slide width? how can I increase the title width ?

```<code>from pptx.util import Inches, Pt
from pptx import Presentation

prs = Presentation()
prs.slide_width = Inches(16)
prs.slide_height = Inches(9)
blank_slide_layout = prs.slide_layouts[5]
slide = prs.slides.add_slide(blank_slide_layout)
title = slide.shapes.title

title.text = "This is test slide.This is test slide.This is test slide.This is test slide.This is test slide.This is test slide"
title.text_frame.paragraphs[0].font.size = Pt(20)

prs.save('test.pptx')
</code>```

答:
The position and size of the slide title is normally determined by the slide layout. In this case you seem to have chosen the one layout which does not have a title shape.

I would start by using a different slide layout, like slide_layouts[1] and see if the title isn't closer to what you want.

The benefit of using the slide layout for that job is that all slides created with that layout have a consistently positioned and formatted title with no extra work on your part. It also has benefits for when you change templates.

Otherwise, if you really want to adjust the size in a particular case, slide.shapes.title is a shape, and has .left, .top, .width, and .height properties like any other shapes.

Body:
Hi I have simple code which generates one ppt slide like below but the slide title width is smaller than slide width? how can I increase the title width ?

from pptx.util import Inches, Pt
from pptx import Presentation

prs = Presentation()
prs.slide_width = Inches(16)
prs.slide_height = Inches(9)
blank_slide_layout = prs.slide_layouts[5]
slide = prs.slides.add_slide(blank_slide_layout)
title = slide.shapes.title

title.text = "This is test slide.This is test slide.This is test slide.This is test slide.This is test slide.This is test slide"
title.text_frame.paragraphs[0].font.size = Pt(20)

prs.save('test.pptx')


问:
Do unused functions get optimized out?
Compilers these days tend to do a significant amount of optimizations. Do they also remove unused functions from the final output?</p>

答:
GCC, if you turn on the optimizations, can remove unused functions and dead code.

More on GCC optimizations can be found here.

Title: Do unused functions get optimized out?


问:
Snowflake json_extract_path_text does not accept a key with spaces
The data coming into the warehouse is structured like this

{"Client ID":"1234567","client_name":"Kareem" }

when I use the function

```<code>JSON_EXTRACT_PATH_TEXT(COLUMN_NAME, 'Client ID')
</code>```

it give me this error :

```<code>Invalid extraction path 'Client ID': invalid token at position 7.
</code>```

is there another workaround to get the value for this key ? or for using this key with the function to get the value out of the JSON column ?

答:
Per its documentation, the JSON_EXTRACT_PATH_TEXT function follows the standard notation for object keys. Keys that carry spaces are required to be double-quoted, and the same applies here. The following works for your example:

JSON_EXTRACT_PATH_TEXT(COLUMN_NAME, '"Client ID"')
```

Body:
The data coming into the warehouse is structured like this

{"Client ID":"1234567","client_name":"Kareem" }

when I use the function

JSON_EXTRACT_PATH_TEXT(COLUMN_NAME, 'Client ID')

it give me this error :

Invalid extraction path 'Client ID': invalid token at position 7.

is there another workaround to get the value for this key ? or for using this key with the function to get the value out of the JSON column ?


问:
I'm getting request too large Error 413 when submiting file in laravel
I'm using laravel and filepond to upload some files. It works fine with files smaller than 100MB, but if I try to upload bigger (400MB) files I get 413 error.
I have already increased post_max_size and upload_max_filesize in php.ini and changed client_max_body_size in nginx, but it still does not work.
I'm missing something?

Best regards

答:
Its php and nginx related.

Check which php.ini is used php --ini

Sometimes there are multiple ones that change the original value

Search in all php.ini files cat /path/php.ini | grep upload_max_filesize

Last thing is, make sure you restart nginx and php after the changes


问:
How to access snakemake.input[0]?
This should be a simple problem, but for the life of me I cannot figure it out. I have a very, very simple Snakefile (shown below):

```<code>rule test:
    input:
        "/home/username/input_data"
    script:
        "scripts/test.py"
</code>```

And in my test.py file, I am doing the following:

```<code>import snakemake
print(snakemake.input[0])
</code>```

But I cannot access snakemake.input[0]. The docs have an example as simple as mine, but I can't get it to work. Additionally, in a Python interactive shell I am able to import snakemake, but I get an error:

```<code>ImportError: No module named snakemake
</code>```

when importing it from my test.py script.

I am calling snakemake test from the command line in the same folder as the Snakefile to run this.

I appreciate any help on this.

答: I was able to fix my problem by removing a snakemake installation at /usr/bin/snakemake, then reinstalling by following the installation guide here

Title: How to access snakemake.input[0]?

Body:
This should be a simple problem, but for the life of me I cannot figure it out. I have a very, very simple Snakefile (shown below):

rule test:
    input:
        "/home/username/input_data"
    script:
        "scripts/test.py"

And in my test.py file, I am doing the following:

import snakemake
print(snakemake.input[0])

But I cannot access snakemake.input[0]. The docs have an example as simple as mine, but I can't get it to work. Additionally, in a Python interactive shell I am able to import snakemake, but I get an error:

ImportError: No module named snakemake

when importing it from my test.py script.

I am calling snakemake test from the command line in the same folder as the Snakefile to run this.

I appreciate any help on this.


问:
Rails, Webpack & FontAwesome, how to stop conversion to SVG?
I've added FontAwesome pro with Yarn to my Rails 6 application and added it to application.js like this:

```<code>import "@fortawesome/fontawesome-pro/js/all";
import "@fortawesome/fontawesome-pro/css/all.css";
</code>```

Before (when using FontAwesome through the asset pipeline) the generated HTML came out like this:

```<code><i class="fal fa-heart-rate"></i>
</code>```

Now it comes out like this:

```<code><svg class="svg-inline--fa fa-heart-rate fa-w-20" aria-hidden="true" focusable="false" data-prefix="fal" data-icon="heart-rate" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 512" data-fa-i2svg=""><path fill="currentColor" d="M480 224c-6.53 0-12.44 3.98-14.84 10.06l-45.62 114.05-84-335.98C333.72 4.86 327.69.17 319.62 0c-7.5.19-13.84 5.53-15.31 12.86l-82.06 410.23-46.72-186.97A16.005 16.005 0 0 0 160 224H8c-4.42 0-8 3.58-8 8v16c0 4.42 3.58 8 8 8h139.5l60.97 243.88c1.78 7.14 8.22 12.12 15.53 12.12h.38c7.5-.19 13.84-5.53 15.31-12.86l82.06-410.23 78.72 314.97c1.69 6.73 7.53 11.62 14.44 12.09 7.62.28 13.38-3.59 15.94-10.03l60-149.94H632c4.42 0 8-3.58 8-8v-16c0-4.42-3.58-8-8-8H480z"></path></svg>
</code>```

Is there a way to prevent this?  I'm asking because I do stacking of icons which worked perfectly before and now it doesn't come out correctly anymore.

答:
I removed the JS and the font-icon appeared as li tag, like before, so you only need to remove the line:

import "@fortawesome/fontawesome-pro/js/all";

Body:
I've added FontAwesome pro with Yarn to my Rails 6 application and added it to application.js like this:

import "@fortawesome/fontawesome-pro/js/all";
import "@fortawesome/fontawesome-pro/css/all.css";

Before (when using FontAwesome through the asset pipeline) the generated HTML came out like this:

Now it comes out like this:

<svg class="svg-inline--fa fa-heart-rate fa-w-20" aria-hidden="true" focusable="false" data-prefix="fal" data-icon="heart-rate" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 512" data-fa-i2svg=""><path fill="currentColor" d="M480 224c-6.53 0-12.44 3.98-14.84 10.06l-45.62 114.05-84-335.98C333.72 4.86 327.69.17 319.62 0c-7.5.19-13.84 5.53-15.31 12.86l-82.06 410.23-46.72-186.97A16.005 16.005 0 0 0 160 224H8c-4.42 0-8 3.58-8 8v16c0 4.42 3.58 8 8 8h139.5l60.97 243.88c1.78 7.14 8.22 12.12 15.53 12.12h.38c7.5-.19 13.84-5.53 15.31-12.86l82.06-410.23 78.72 314.97c1.69 6.73 7.53 11.62 14.44 12.09 7.62.28 13.38-3.59 15.94-10.03l60-149.94H632c4.42 0 8-3.58 8-8v-16c0-4.42-3.58-8-8-8H480z"></path></svg>

Is there a way to prevent this?  I'm asking because I do stacking of icons which worked perfectly before and now it doesn't come out correctly anymore.


问:
Rust "Types differ in mutability"
I'm trying to remove an element from a vector if it existed in it:

```<code>use std::collections::HashMap;

fn test(map: HashMap<String, Vec<String>>, department: String, employee: String) {
    let &mut list = map.get(&department).unwrap();
    let index = list.iter().position(|x| x == &employee);
    match index {
        Some(i) => {
            list.remove(i);
        },
        None => {
            println!("No records of {} in {}!", &employee, &department);
        },
    }
}
</code>```

I'm getting this error:

error[E0308]: mismatched types
 --> src/lib.rs:4:9
  |
4 |     let &mut list = map.get(&department).unwrap();
  |         ^^^^^^^^^   ----------------------------- this expression has type `&std::vec::Vec<std::string::String>`
  |         |
  |         types differ in mutability
  |
  = note:      expected reference `&std::vec::Vec<std::string::String>`
          found mutable reference `&mut _`
```

<p><sup>Playground</sup></p>

<p>I thought I understood what the error is saying (line 170's RHS returns a immutable reference to the vector), but I'm not so sure how to resolve it. If try something like this instead:</p>

```let mut list = map.get(&department).unwrap();
let index = list.iter().position(|x| x == &employee);
match index {
    Some(i) => {
        list.remove(i);
    },
    ...
}
```

<p>I then get </p>

<pre class="lang-none prettyprint-override"><code>error[E0596]: cannot borrow `*list` as mutable, as it is behind a `&` reference
 --> src/lib.rs:8:13
  |
4 |     let mut list = map.get(&department).unwrap();
  |         -------- help: consider changing this to be a mutable reference: `&mut std::vec::Vec<std::string::String>`
...
8 |             list.remove(i);
  |             ^^^^ `list` is a `&` reference, so the data it refers to cannot be borrowed as mutable
</code>```

Playground

These errors seem kind of circular to me, which makes me feel I need to rethink my design. How would I go about fixing this issue?

答:
get returns an immutable Option<&V> which won't let you call .remove(i). Use get_mut to get a mutable Option<&mut V>. Calling it requires that the map itself be mutable, which is a sign that we're doing the right thing.

```<code>use std::collections::HashMap;

fn test(map: &mut HashMap<String, Vec<String>>, department: String, employee: String) {
    //       ^^^^
    let list = map.get_mut(&department).unwrap();
    //             ^^^^^^^
    let index = list.iter().position(|x| x == &employee);
    match index {
        Some(i) => {
            list.remove(i);
        },
        None => {
            println!("No records of {} in {}!", &employee, &department);
        },
    }
}
</code>```

Playground

Title: Rust "Types differ in mutability"

Body:
I'm trying to remove an element from a vector if it existed in it:

use std::collections::HashMap;

fn test(map: HashMap<String, Vec<String>>, department: String, employee: String) {
    let &mut list = map.get(&department).unwrap();
    let index = list.iter().position(|x| x == &employee);
    match index {
        Some(i) => {
            list.remove(i);
        },
        None => {
            println!("No records of {} in {}!", &employee, &department);
        },
    }
}

I'm getting this error:

error[E0308]: mismatched types
 --> src/lib.rs:4:9
  |
4 |     let &mut list = map.get(&department).unwrap();
  |         ^^^^^^^^^   ----------------------------- this expression has type `&std::vec::Vec<std::string::String>`
  |         |
  |         types differ in mutability
  |
  = note:      expected reference `&std::vec::Vec<std::string::String>`
          found mutable reference `&mut _`

Playground

I thought I understood what the error is saying (line 170's RHS returns a immutable reference to the vector), but I'm not so sure how to resolve it. If try something like this instead:

let mut list = map.get(&department).unwrap();
let index = list.iter().position(|x| x == &employee);
match index {
    Some(i) => {
        list.remove(i);
    },
    ...
}

I then get

error[E0596]: cannot borrow `*list` as mutable, as it is behind a `&` reference
 --> src/lib.rs:8:13
  |
4 |     let mut list = map.get(&department).unwrap();
  |         -------- help: consider changing this to be a mutable reference: `&mut std::vec::Vec<std::string::String>`
...
8 |             list.remove(i);
  |             ^^^^ `list` is a `&` reference, so the data it refers to cannot be borrowed as mutable

Playground

These errors seem kind of circular to me, which makes me feel I need to rethink my design. How would I go about fixing this issue?

Body:
get returns an immutable Option<&V> which won't let you call .remove(i). Use get_mut to get a mutable Option<&mut V>. Calling it requires that the map itself be mutable, which is a sign that we're doing the right thing.

use std::collections::HashMap;

fn test(map: &mut HashMap<String, Vec<String>>, department: String, employee: String) {
    //       ^^^^
    let list = map.get_mut(&department).unwrap();
    //             ^^^^^^^
    let index = list.iter().position(|x| x == &employee);
    match index {
        Some(i) => {
            list.remove(i);
        },
        None => {
            println!("No records of {} in {}!", &employee, &department);
        },
    }
}

Playground


问:
Google apps script converting date within formula
I'm using Google Apps Script to create a new set of tabs within a sheet, and everything is going well apart from one date within a formula. The code I'm using is

```<code>function MakeANewDaySheet() {
  var date = Utilities.formatDate(new Date(), "GMT", "dd/MM/yyyy")
  var spreadsheet = SpreadsheetApp.getActive();
...
...
  spreadsheet.getRange('O2').activate();
  spreadsheet.getCurrentCell().setFormula("=iferror(indirect(" + date + '!$B3),\"Please select a department\")')
}
</code>```

The formula I want the script to put in the cell points to another sheet that's created during this script, and its name is simply today's date. When the formula is entered using the script it puts ' around the year, which I cant seem to stop it doing.

I'm wanting to use the formula '=iferror(indirect(02/06/2020!$B3),"Please select a department")'
and its giving me '=iferror(indirect(2/6/'2020'!$B3),"Please select a department")'

I've tried changing around between " and ', including \ and not, hoping it was that easy, but no luck.

Can anyone point out what is probably (hopefully) a simple syntax error.

答:
The indirect function resolves cell reference written as string but in this case date is not being written as string in the formula. Please try this

spreadsheet.getCurrentCell().setFormula('=iferror(indirect("' + date + '" & "!$B3"),"Please select a department")')

Body:
I'm using Google Apps Script to create a new set of tabs within a sheet, and everything is going well apart from one date within a formula. The code I'm using is

function MakeANewDaySheet() {
  var date = Utilities.formatDate(new Date(), "GMT", "dd/MM/yyyy")
  var spreadsheet = SpreadsheetApp.getActive();
...
...
  spreadsheet.getRange('O2').activate();
  spreadsheet.getCurrentCell().setFormula("=iferror(indirect(" + date + '!$B3),\"Please select a department\")')
}

The formula I want the script to put in the cell points to another sheet that's created during this script, and its name is simply today's date. When the formula is entered using the script it puts ' around the year, which I cant seem to stop it doing.

I'm wanting to use the formula '=iferror(indirect(02/06/2020!$B3),"Please select a department")'
and its giving me '=iferror(indirect(2/6/'2020'!$B3),"Please select a department")'

I've tried changing around between " and ', including \ and not, hoping it was that easy, but no luck.

Can anyone point out what is probably (hopefully) a simple syntax error.