问:
Avoid username/password prompt when running git credential fill
I'm trying to run the git credential fill command from a Node.js program. I want to use it to check whether there is a stored username/password for a given URL. If there is one, I'm parsing the output (stdout) of the git credential command to get the stored username and password.

If the OS credential helper does not have a stored username/password for the URL, I want the program to terminate silently. Unfortunately, this does not work. When running my program from a shell, the git credential fill command asks for username and password in the terminal:

```<code>$ git credential fill
url=http://foo.foo

Username for 'http://foo.foo': ^C
</code>```

In the above example, I stopped the execution by pressing Ctrl+C since I'm not interested in entering a username/password.

Is there a way to run git credential fill so that it does not ask for a username/password if it does not have one, and simply terminates silently?

When I call the git credential fill from a Node.js program using the child_process.spawn function, the same happens:

```<code>var output;

var command = spawn('git', ['credential', 'fill']);

command.stdout.on('data', function (data) {
    output = data;
});

command.stdout.on('end', function () {
    // callback is a function defined outside that receives the git command's output.
    callback(output);
});

command.stdin.write('url=http://foo\n\n');
</code>```

When running this from a standard bash shell, the same happens, it asks for username/password again.

When I run the above program from inside the WebStorm IDE using its run mode, the git credential program is not asking for username/password, it simply terminates silently. It looks like WebStorm runs this program in a shell that does not support user input. Is there a way to achieve the same when running in a shell?

答:
Set the GIT_ASKPASS environment variable to true or false.

With either, you'll get the output if git credential fill does not need to
ask for a password.

If git does not know the password with GIT_ASKPASS=true, the output will
have an empty password:

$ cat <<EOF | env GIT_ASKPASS=true git credential fill
protocol=https
host=github.com
username=allen

EOF
protocol=https
host=github.com
username=allen
password=
```
<p>With <code>GIT_ASKPASS=false</code>:</p>
<pre class="lang-sh prettyprint-override"><code>$ cat <<EOF | env GIT_ASKPASS=false git credential fill
protocol=https
host=github.com
username=allen

EOF
error: unable to read askpass response from 'false'
fatal: could not read Password for 'https://allen@github.com': Device not configured
</code>```

Body:
I'm trying to run the git credential fill command from a Node.js program. I want to use it to check whether there is a stored username/password for a given URL. If there is one, I'm parsing the output (stdout) of the git credential command to get the stored username and password.

If the OS credential helper does not have a stored username/password for the URL, I want the program to terminate silently. Unfortunately, this does not work. When running my program from a shell, the git credential fill command asks for username and password in the terminal:

$ git credential fill
url=http://foo.foo

Username for 'http://foo.foo': ^C

In the above example, I stopped the execution by pressing Ctrl+C since I'm not interested in entering a username/password.

Is there a way to run git credential fill so that it does not ask for a username/password if it does not have one, and simply terminates silently?

When I call the git credential fill from a Node.js program using the child_process.spawn function, the same happens:

var output;

var command = spawn('git', ['credential', 'fill']);

command.stdout.on('data', function (data) {
    output = data;
});

command.stdout.on('end', function () {
    // callback is a function defined outside that receives the git command's output.
    callback(output);
});

command.stdin.write('url=http://foo\n\n');

When running this from a standard bash shell, the same happens, it asks for username/password again.

When I run the above program from inside the WebStorm IDE using its run mode, the git credential program is not asking for username/password, it simply terminates silently. It looks like WebStorm runs this program in a shell that does not support user input. Is there a way to achieve the same when running in a shell?

Body:
Set the GIT_ASKPASS environment variable to true or false.

With either, you'll get the output if git credential fill does not need to
ask for a password.

If git does not know the password with GIT_ASKPASS=true, the output will
have an empty password:

$ cat <<EOF | env GIT_ASKPASS=true git credential fill
protocol=https
host=github.com
username=allen

EOF
protocol=https
host=github.com
username=allen
password=

With GIT_ASKPASS=false:

$ cat <<EOF | env GIT_ASKPASS=false git credential fill
protocol=https
host=github.com
username=allen

EOF
error: unable to read askpass response from 'false'
fatal: could not read Password for 'https://allen@github.com': Device not configured


来源: stackexchange

问:
Tableau integration in Angular not working
I am trying to add the Tableau in my angular app. I followed the steps but for some reason i can't see the table in my div.

my code is

```<code>declare var tableau: any;

@Component({
  selector: 'app-tableau',
  templateUrl: './tableau.component.html',
  styleUrls: ['./tableau.component.scss']
})
export class TableauComponent implements OnInit {
  viz: any;
  constructor() { }
  ngOnInit() {
  }

  initTableau() {
    const containerDiv = document.getElementById("vizContainer");
    const vizUrl =
        "https://public.tableau.com/views/VacationHome/VacationHome?:embed=y&:display_count=yes";

        const options = {
          hideTabs: true,
          onFirstInteractive: () => {
              console.log("onFirstInteractive");
          },
          // onFirstVizSizeKnown: () => {
          //     console.log("onFirstVizSizeKnown");
          // }
      };

    this.viz = new tableau.Viz(containerDiv, vizUrl, options);

}
HTML : <div id="vizContainer" style="width:800px; height:800px; display: flex; justify-content: right; border: 2px solid black;"></div>

</code>```

I donot see any errors in the terminal/console. I can see the empty div. What possibly am I missing?

答:
For anyone looking for another ways of embedding a Tableau report using the JavaScript API, I want to add two options:

The unofficial library ngx-tableau provides a simple interface
to the Tableau JavaScript API v2, offering multiple configuration
options.

The official Tableau Embedding API v3 exposes a web-component
with a very similar API and some other features.

ContentLicense: CC BY-SA 4.0

Body:
I am trying to add the Tableau in my angular app. I followed the steps but for some reason i can't see the table in my div.

my code is

declare var tableau: any;

@Component({
  selector: 'app-tableau',
  templateUrl: './tableau.component.html',
  styleUrls: ['./tableau.component.scss']
})
export class TableauComponent implements OnInit {
  viz: any;
  constructor() { }
  ngOnInit() {
  }

  initTableau() {
    const containerDiv = document.getElementById("vizContainer");
    const vizUrl =
        "https://public.tableau.com/views/VacationHome/VacationHome?:embed=y&:display_count=yes";

        const options = {
          hideTabs: true,
          onFirstInteractive: () => {
              console.log("onFirstInteractive");
          },
          // onFirstVizSizeKnown: () => {
          //     console.log("onFirstVizSizeKnown");
          // }
      };

    this.viz = new tableau.Viz(containerDiv, vizUrl, options);

}
HTML :

I donot see any errors in the terminal/console. I can see the empty div. What possibly am I missing?


问:
How can I edit web scraped text data using python?
Trying to build my first webscraper to print out how the stock market is doing on Yahoo finance. I have found out how to isolate the information I want but it returns super sloppy. How can I manipulate this data to present in an easier way?

```<code>import requests
from bs4 import BeautifulSoup

#Import your website here
html_text = requests.get('https://finance.yahoo.com/').text

soup = BeautifulSoup(html_text, 'lxml')

#Find the part of the webpage where your information is in
sp_market = soup.find('h3', class_ = 'Maw(160px)').text
print(sp_market)
</code>```

The return here is : S&P 5004,587.18+65.64(+1.45%)

I want to grab these elements such as the labels and percentages and isolate them so I can print them in a way I want. Anyone know how? Thanks so much!

edit:
((S&P 500
4,587.18+65.64(+1.45%)))

答:
I assume that the format is always S&P 500\n[number][+/-][number]([+/-][number]%).

If that is the case, we could do the following.

```<code>import re

# [your existing code]

# e.g.
# sp_market = 'S&P 500\n4,587.18+65.64(+1.45%)'

label,line2 = sp_market.split('\n')
pm = re.findall(r"[+-]",line2)
total,change,percent,_ = re.split(r"[\+\-\(\)%]+",line2)
total = float(''.join(total.split(',')))
change = float(change)
if pm[0]=='-':
    change=-change
percent = float(percent)
if pm[1]=='-':
    percent=-percent

print(label, total,change,percent)
# S&P 500 4587.18 65.64 1.45
</code>```

Body:
Trying to build my first webscraper to print out how the stock market is doing on Yahoo finance. I have found out how to isolate the information I want but it returns super sloppy. How can I manipulate this data to present in an easier way?

import requests
from bs4 import BeautifulSoup

#Import your website here
html_text = requests.get('https://finance.yahoo.com/').text

soup = BeautifulSoup(html_text, 'lxml')

#Find the part of the webpage where your information is in
sp_market = soup.find('h3', class_ = 'Maw(160px)').text
print(sp_market)

The return here is : S&P 5004,587.18+65.64(+1.45%)

I want to grab these elements such as the labels and percentages and isolate them so I can print them in a way I want. Anyone know how? Thanks so much!

edit:
((S&P 500
4,587.18+65.64(+1.45%)))

Body:
I assume that the format is always S&P 500\n[number][+/-][number]([+/-][number]%).

If that is the case, we could do the following.

import re

# [your existing code]

# e.g.
# sp_market = 'S&P 500\n4,587.18+65.64(+1.45%)'

label,line2 = sp_market.split('\n')
pm = re.findall(r"[+-]",line2)
total,change,percent,_ = re.split(r"[\+\-\(\)%]+",line2)
total = float(''.join(total.split(',')))
change = float(change)
if pm[0]=='-':
    change=-change
percent = float(percent)
if pm[1]=='-':
    percent=-percent

print(label, total,change,percent)
# S&P 500 4587.18 65.64 1.45


问:
How to filter out all records that have duplicates in SQL?
Trying to get this result from a table with duplicates

red
red
red
blue
green
```
<p>to</p>
<pre class="lang-none prettyprint-override"><code>blue
green
</code>```

Totally omitting all the records that has duplicates and only bringing in the unique records

答:
If you need more than just the colours.

```<code>select *
from paintmess
where colour in (
   select colour
   from paintmess
   group by colour
   having count(*)=1
   );
</code>```

id
colour

4
blue

5
green

db<>fiddle here

Body:
Trying to get this result from a table with duplicates

red
red
red
blue
green

to

blue
green

Totally omitting all the records that has duplicates and only bringing in the unique records

Body:
If you need more than just the colours.

select *
from paintmess
where colour in (
   select colour
   from paintmess
   group by colour
   having count(*)=1
   );

id
colour

4
blue

5
green

db<>fiddle here


问:
Issues with two Haskell commands, one attempting to find and print differences in two lists, and one attempting to output the longest length
Here is the first one, which is attempting to take two lists and print all the differences between the two .

EX.

> list_diff [1,6,1,3,4,3,5]  [3,8,5,4,7,4,8]
[1,6,1,8,7,8]

```<code>list_diff :: Eq a => [a] -> [a] -> [a]
list_diff [] [] = []
list_diff x y = list_helper x y

list_helper [] [] = []
list_helper (x:xs) y
     | x `elem` y = list_helper xs y
     | otherwise = x:(list_helper xs y)
</code>```

When I run a test for this one (using the example provided above), I reviece the following output:

[1,6,1*** Exception: HW1.hs:(12,1)-(15,39): Non-exhaustive patterns in function list_helper

For the second funtion, I am attempting to take a series of values and determine which list is the longest

EX.

```<code>progLanguages =
     [ ("CptS121" , ["C"]),
     ("CptS122" , ["C++"]),
     ("CptS223" , ["C++"]),
     ("CptS233" , ["Java"]),
     ("CptS321" , ["C#"]),
     ("CptS322" , ["Python", "JavaScript"])]

INPUT: max_count progLanguages

OUTPUT: ("CptS322" , 2)
</code>```

What I have so far isn't working at all, so needless to say I am stuck.

```<code>max_count [] = error "bad"
max_count [x] = x
max_count (x:xs) = x max_helper (max_count xs)
     where
     max_helper (a,b) (a',b')
          | length b > length b' = (a, length b)
          | otherwise = (a', length b')
</code>```

Thanks in advance for any help you can give.

答:
You've defined list_helper:

```<code>list_helper [] [] = []
list_helper (x:xs) y
     | x `elem` y = list_helper xs y
     | otherwise = x:(list_helper xs y)
</code>```

The warning about non-exhaustive pattern matching means that your function is evaluating arguments that you haven't told it how to handle. In this case, that's the first argument being an empty list, but the second argument not being empty.

You need to handle this pattern:

```<code>list_helper [] [] = []
list_helper [] y = y
list_helper (x:xs) y
     | x `elem` y = list_helper xs y
     | otherwise = x:(list_helper xs y)
</code>```

Prelude> :{
Prelude| list_helper [] [] = []
Prelude| list_helper [] y = y
Prelude| list_helper (x:xs) y
Prelude|      | x `elem` y = list_helper xs y
Prelude|      | otherwise = x:(list_helper xs y)
Prelude| :}
Prelude> list_helper [1, 2, 3] [4, 5, 6]
[1,2,3,4,5,6]
```

Body:
Here is the first one, which is attempting to take two lists and print all the differences between the two .

EX.

> list_diff [1,6,1,3,4,3,5]  [3,8,5,4,7,4,8]
[1,6,1,8,7,8]

list_diff :: Eq a => [a] -> [a] -> [a]
list_diff [] [] = []
list_diff x y = list_helper x y

list_helper [] [] = []
list_helper (x:xs) y
     | x `elem` y = list_helper xs y
     | otherwise = x:(list_helper xs y)

When I run a test for this one (using the example provided above), I reviece the following output:

[1,6,1*** Exception: HW1.hs:(12,1)-(15,39): Non-exhaustive patterns in function list_helper

For the second funtion, I am attempting to take a series of values and determine which list is the longest

EX.

progLanguages =
     [ ("CptS121" , ["C"]),
     ("CptS122" , ["C++"]),
     ("CptS223" , ["C++"]),
     ("CptS233" , ["Java"]),
     ("CptS321" , ["C#"]),
     ("CptS322" , ["Python", "JavaScript"])]

INPUT: max_count progLanguages

OUTPUT: ("CptS322" , 2)

What I have so far isn't working at all, so needless to say I am stuck.

max_count [] = error "bad"
max_count [x] = x
max_count (x:xs) = x max_helper (max_count xs)
     where
     max_helper (a,b) (a',b')
          | length b > length b' = (a, length b)
          | otherwise = (a', length b')

Thanks in advance for any help you can give.

Body:
You've defined list_helper:

list_helper [] [] = []
list_helper (x:xs) y
     | x `elem` y = list_helper xs y
     | otherwise = x:(list_helper xs y)

The warning about non-exhaustive pattern matching means that your function is evaluating arguments that you haven't told it how to handle. In this case, that's the first argument being an empty list, but the second argument not being empty.

You need to handle this pattern:

list_helper [] [] = []
list_helper [] y = y
list_helper (x:xs) y
     | x `elem` y = list_helper xs y
     | otherwise = x:(list_helper xs y)

Prelude> :{
Prelude| list_helper [] [] = []
Prelude| list_helper [] y = y
Prelude| list_helper (x:xs) y
Prelude|      | x `elem` y = list_helper xs y
Prelude|      | otherwise = x:(list_helper xs y)
Prelude| :}
Prelude> list_helper [1, 2, 3] [4, 5, 6]
[1,2,3,4,5,6]


问:
Apply onClick functions based on conditions within components React
I have a component which renders a bunch of components called ActionItem

```<code>            <ActionItem title={'Client Assigned'} icon={<MdOutlineAssignmentTurnedIn />} />
            <ActionItem title={'Inital Client Follow Up'} icon={<BsFillPersonCheckFill />} />
            <ActionItem title={'Validated Need'} icon={<BiDonateHeart />} />

            <ActionItem title={'Initiated Discovery'} icon={<RiCompassDiscoverLine />} />
            <ActionItem title={'Service In Progress'} icon={<GiProgression />} />
            <ActionItem title={'Fulfilled The Need'} icon={<ImCheckmark />} />
</code>```

Inside of my ActionItem I have a function: handleToggle() which fires  onClick and pretty much adds or removes an "active" class. I want this function available to every component EXCEPT the one with the title of 'Client Assigned'

ActionItem component:

```<code>  const [toggleItem, setToggleItem] = useState(false)
  const [date, setDate] = useState('')

  const handleToggle = () => {

    setToggleItem(!toggleItem)
    setDate(new Date())
    if (date !== '') {
      setDate('')
    }

  }

  useEffect(() => {
    title === 'Client Assigned' ? handleToggle() : null
  }, [])

  return (
    <React.Fragment>
      <div className={toggleItem ? 'ReportsModal' : 'ReportsModal not-active'}>
        <span
          style={title === 'Fulfilled The Need' ? (
            { borderColor: 'green', backgroundColor: 'green', color: '#fff' }
          ) : null}
          className={'hover'}
          onClick={title === 'Client Assigned' ? handleToggle : null}>
          {icon}
        </span>
        <div>
          <h3>{title}</h3>
          <p>{date !== '' ? moment(date).format('D MMM YYYY') : date}</p>
          {toggleItem ? (
            <h5 onClick={handleInitComment} className='hover'><AiOutlinePlusCircle style={iconStyles} /> Add Comment</h5>
          ) : null}

        </div>
      </div>
</code>```

the conditional I am trying to use is currently not working. Any advice?

答:
if you just want to fire handleToggle conditionally based on the title === "Client Assigned", I would do this.

```<code>const handleToggle = (title) => {
        if (title === "Client Assigned") {
            setToggleItem(!toggleItem)
            setDate(new Date())
            if (date !== '') {
                setDate('')
            }
        }
    }
</code>```

then your onClick would look like:

```<code>onClick={(title) => handleToggle(title)}>
</code>```

This should work and is a lot easier to read aswell

Body:
I have a component which renders a bunch of components called ActionItem

            <ActionItem title={'Client Assigned'} icon={<MdOutlineAssignmentTurnedIn />} />
            <ActionItem title={'Inital Client Follow Up'} icon={<BsFillPersonCheckFill />} />
            <ActionItem title={'Validated Need'} icon={<BiDonateHeart />} />

            <ActionItem title={'Initiated Discovery'} icon={<RiCompassDiscoverLine />} />
            <ActionItem title={'Service In Progress'} icon={<GiProgression />} />
            <ActionItem title={'Fulfilled The Need'} icon={<ImCheckmark />} />

Inside of my ActionItem I have a function: handleToggle() which fires  onClick and pretty much adds or removes an "active" class. I want this function available to every component EXCEPT the one with the title of 'Client Assigned'

ActionItem component:

  const [toggleItem, setToggleItem] = useState(false)
  const [date, setDate] = useState('')

  const handleToggle = () => {

    setToggleItem(!toggleItem)
    setDate(new Date())
    if (date !== '') {
      setDate('')
    }

  }

  useEffect(() => {
    title === 'Client Assigned' ? handleToggle() : null
  }, [])

  return (
    <React.Fragment>

          {icon}

{title}

{date !== '' ? moment(date).format('D MMM YYYY') : date}

          {toggleItem ? (

<AiOutlinePlusCircle style={iconStyles} /> Add Comment

          ) : null}

the conditional I am trying to use is currently not working. Any advice?

Body:
if you just want to fire handleToggle conditionally based on the title === "Client Assigned", I would do this.

const handleToggle = (title) => {
        if (title === "Client Assigned") {
            setToggleItem(!toggleItem)
            setDate(new Date())
            if (date !== '') {
                setDate('')
            }
        }
    }

then your onClick would look like:

onClick={(title) => handleToggle(title)}>

This should work and is a lot easier to read aswell


问:
Selenium - How to get values with the same tag name
I am stuck at one end, I am not able to get values.

For better view... I need to get these values

1)809

```<code><td class="tdResult" id="tdResultSpFlights" onclick="consultaSpFlights(809,1);" style="cursor:pointer;"><u>809</u></td>
</code>```

2)2

```<code><td class="tdResult" id="tdResultSpCanceledFlights" onclick="consultaSpCanceledFlights(2,1);" style="cursor:pointer;"><u>2</u></td>
</code>```

3)90

```<code><td class="tdResult" id="tdResultSpDelayedFlights" onclick="consultaSpDelayedFlights(90,1);" style="cursor:pointer;"><u>90</u></td>
</code>```

If I use

```<code>find_element(By.TAG_NAME,"u")
</code>```

Applying with the first one is correct, but i cannot get the others, due to they has the same tag name. I already try with xpath, class and id. How can i get values above?

答:
find_element() will return the first matching element. Instead you need to use find_elements() and to extract the texts you can use a list comprehension as follows:

```<code>print([my_elem.text for my_elem in driver.find_elements(By.TAG_NAME, "u")])
</code>```

Body:
I am stuck at one end, I am not able to get values.

For better view... I need to get these values

1)809

809

2)2

2

3)90

90

If I use

find_element(By.TAG_NAME,"u")

Applying with the first one is correct, but i cannot get the others, due to they has the same tag name. I already try with xpath, class and id. How can i get values above?

Body:
find_element() will return the first matching element. Instead you need to use find_elements() and to extract the texts you can use a list comprehension as follows:

print([my_elem.text for my_elem in driver.find_elements(By.TAG_NAME, "u")])


问:
Flutter: how can I permanently register a sensor (and never unregister it?)
TL;DR how can I have an Android sensor permanently running/active/registered for my app, even if I close it?

Objective:

I'm making a Flutter application that counts your steps using the pedometer package,

which uses the built-in sensor TYPE_STEP_COUNTER of Android,

which returns the # of steps taken since last boot (iOS). On Android, any steps taken before installing the app are not counted.

How I implemented it:

When the app is actively running in the foreground, each step causes
a myStepCount to increment by 1.

In all other cases (phone locked, went to home-screen, closed the app...), the android TYPE_STEP_COUNTER sensor should
still be running in the background, and once I open my app again, the
difference between new stepCount and last saved stepCount (saved
using shared_prefs) will be calculated and added to myStepCount.

Important:

The TYPE_STEP_COUNTER sensor must be permanently running/stay registered in the background, even after I lock my phone, go to the home-screen, or close the app...

Observations:

On my Samsung Galaxy A02s, my app works perfectly fine, as it it supposed to
(as described above).   That is because on that phone I also have the
Google Fit app installed, which tracks your steps 24/7 (so the
TYPE_STEP_COUNTER sensor is permanently registered).

On my Samsung Galaxy S7, my app does not work as it's supposed to.
myStepCount gets incremented when I take steps while the app is
running in the foreground. But steps taken while the app is closed
will NOT be added to myStepCount once I open the app again.

Note: I don't have any other step-counting-apps like Google Fit on this phone.

Conclusion:

I need to find a way to register the TYPE_STEP_COUNTER sensor from my Flutter app, and keep it registered even after I close the app.

2 Attempted (but unsuccessful) Solutions:

1st Attempt:

Calling Native Android Code from my Flutter Code to register the sensor

This is my main.dart file (with the unimportant parts left out for simplicity):

```<code>void main() {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(App());
}

class App extends StatefulWidget {
  @override
  _AppState createState() => _AppState();
}

class _AppState extends State<App> with WidgetsBindingObserver {

  @override
  void initState() {
    super.initState();

    if (Platform.isAndroid) {
      _activateStepCounterSensor();
    } else if (Platform.isIOS) {
      //TODO check if anything is needed to to here
    }
  }

  void _activateStepCounterSensor() async {
    MethodChannel _stepCounterChannel = MethodChannel('com.cedricds.wanderapp/stepCounter'); //convention
    dynamic result = await _stepCounterChannel.invokeMethod('activateStepCounterSensor');
    switch (result) {
      case "success":
        //The following line gets printed when I run the flutter app on my Samsung Galaxy S7:
        print('_activateStepCounterSensor(): successfully registered step counter sensor for android');
        break;
      case "error":
        print('_activateStepCounterSensor(): failed to register step counter sensor (not available) for android');
        //TODO display errorpage (because app is completely useless in this case)
        break;
      default:
        print('_activateStepCounterSensor(): unknown result: $result');
        break;
    }
  }

  //build() and other lifecycle-methods and helper methods: not important for this question
}
</code>```

This is my MainActivity.kt file:

```<code>package com.cedricds.wanderapp

import android.content.Context
import android.hardware.Sensor
import android.hardware.SensorEvent
import android.hardware.SensorEventListener
import android.hardware.SensorManager
import android.util.Log
import android.widget.Toast
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel

class MainActivity2: FlutterActivity(), SensorEventListener {

    private val STEP_COUNTER_CHANNEL = "com.cedricds.wanderapp/stepCounter";
    private lateinit var channel: MethodChannel

    override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
        super.configureFlutterEngine(flutterEngine)

        channel = MethodChannel(flutterEngine.dartExecutor.binaryMessenger, STEP_COUNTER_CHANNEL)
        channel.setMethodCallHandler { call, result ->
            when(call.method){ //this is like switch-case statement in Java
                "activateStepCounterSensor" -> {
                    activateStepCounterSensor(result)
                }
            }
        }
    }

    private var sensorManager : SensorManager?=null
    private var sensor: Sensor ?= null

    private fun activateStepCounterSensor(result: MethodChannel.Result) {
        //This line gets printed when I run the flutter app, so the method gets called successfully:
        Log.d("Android", "Native Android: activateStepCounterSensor()")

        sensorManager = getSystemService(Context.SENSOR_SERVICE) as SensorManager
        sensor = sensorManager?.getDefaultSensor(Sensor.TYPE_STEP_COUNTER)
        if (sensor == null) {
            Toast.makeText(this, "missing hardware.", Toast.LENGTH_LONG).show()
            result.error("error", "error", "error")
        } else {
            sensorManager?.registerListener(this, sensor, SensorManager.SENSOR_DELAY_NORMAL)
            //This line gets printed:
            Log.d("Android", "Native Android: registered TYPE_STEP_COUNTER")
            //and never unregister that listener
            result.success("success")
        }
    }

    override fun onSensorChanged(p0: SensorEvent?) {}
    override fun onAccuracyChanged(p0: Sensor?, p1: Int) {}
}
</code>```

Despite the few print(...) and Log.d(...) being printed in the console as expected, the app doesn't work how I expected it to work. When I exit the app, walk for example 50 steps, then open the app again, those 50 steps are missing. It seems the sensor is being unregistered somewhere.

2nd Attempt:

Modifying the pedometer package's code by removing unregisterListener(...):
The only changes I did to the file were 2 Log.d(...) statements and more importantly, commenting out a specific line of code.

modified SensorStreamHandler.kt from the pedometer package:

```<code>package com.example.pedometer

import android.content.Context
import android.hardware.Sensor
import android.hardware.SensorEventListener
import android.hardware.SensorManager
import android.os.Looper
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.plugin.common.BinaryMessenger
import io.flutter.plugin.common.EventChannel
import android.os.Handler
import android.util.Log

class SensorStreamHandler() : EventChannel.StreamHandler {

    private var sensorEventListener: SensorEventListener? = null
    private var sensorManager: SensorManager? = null
    private var sensor: Sensor? = null
    private lateinit var context: Context
    private lateinit var sensorName: String
    private lateinit var flutterPluginBinding: FlutterPlugin.FlutterPluginBinding

    constructor(flutterPluginBinding: FlutterPlugin.FlutterPluginBinding, sensorType: Int) : this() {
        this.context = flutterPluginBinding.applicationContext
        this.sensorName = if (sensorType == Sensor.TYPE_STEP_COUNTER) "StepCount" else "StepDetection"
        sensorManager = context.getSystemService(Context.SENSOR_SERVICE) as SensorManager
        sensor = sensorManager!!.getDefaultSensor(sensorType)
        this.flutterPluginBinding = flutterPluginBinding
    }

    override fun onListen(arguments: Any?, events: EventChannel.EventSink?) {
        Log.d("Pedometer", "Native Android: onListen()")
        if (sensor == null) {
            events!!.error("1", "$sensorName not available",
                    "$sensorName is not available on this device");
        } else {
            sensorEventListener = sensorEventListener(events!!);
            sensorManager!!.registerListener(sensorEventListener, sensor, SensorManager.SENSOR_DELAY_NORMAL);
        }
    }

    override fun onCancel(arguments: Any?) {
        Log.d("Pedometer", "Native Android: onCancel()")

        //The only change I did: commenting out the following line:
//        sensorManager!!.unregisterListener(sensorEventListener);
    }

}
</code>```

This also did not solve my problem. So if someone knows how I can permanently register the TYPE_STEP_COUNTER sensor in my flutter app, please let me know.

答:
Update:
I've contacted one of the developers of the pedometer package, and he suggested me to use flutter_foreground_service (which is developed by the same team/company as pedometer). It works.

But I would still find it interesting, if there is another way (maybe similar to my 2 failed attempts).

I have so many people asking me for a more detailed description of how I solved my problem. Unfortunately I can't share my whole code with you, just this small snipped which always gets run at the beginning (right after main()):

```<code>    if (Platform.isAndroid && !SharedPrefsHelper().isForegroundServiceStarted()) {
      ForegroundService().start();
      // ForegroundServiceNotification.setPriority(AndroidNotificationPriority.LOW);
      SharedPrefsHelper().setIsForegroundServiceStarted(true);
    }
</code>```

Don't worry about SharedPrefsHelper, that's just a class that I created to make it easier to work with shared_preferences.

Body:
TL;DR how can I have an Android sensor permanently running/active/registered for my app, even if I close it?

Objective:

I'm making a Flutter application that counts your steps using the pedometer package,

which uses the built-in sensor TYPE_STEP_COUNTER of Android,

which returns the # of steps taken since last boot (iOS). On Android, any steps taken before installing the app are not counted.

How I implemented it:

When the app is actively running in the foreground, each step causes
a myStepCount to increment by 1.

In all other cases (phone locked, went to home-screen, closed the app...), the android TYPE_STEP_COUNTER sensor should
still be running in the background, and once I open my app again, the
difference between new stepCount and last saved stepCount (saved
using shared_prefs) will be calculated and added to myStepCount.

Important:

The TYPE_STEP_COUNTER sensor must be permanently running/stay registered in the background, even after I lock my phone, go to the home-screen, or close the app...

Observations:

On my Samsung Galaxy A02s, my app works perfectly fine, as it it supposed to
(as described above).   That is because on that phone I also have the
Google Fit app installed, which tracks your steps 24/7 (so the
TYPE_STEP_COUNTER sensor is permanently registered).

On my Samsung Galaxy S7, my app does not work as it's supposed to.
myStepCount gets incremented when I take steps while the app is
running in the foreground. But steps taken while the app is closed
will NOT be added to myStepCount once I open the app again.

Note: I don't have any other step-counting-apps like Google Fit on this phone.

Conclusion:

I need to find a way to register the TYPE_STEP_COUNTER sensor from my Flutter app, and keep it registered even after I close the app.

2 Attempted (but unsuccessful) Solutions:

1st Attempt:

Calling Native Android Code from my Flutter Code to register the sensor

This is my main.dart file (with the unimportant parts left out for simplicity):

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(App());
}

class App extends StatefulWidget {
  @override
  _AppState createState() => _AppState();
}

class _AppState extends State<App> with WidgetsBindingObserver {

  @override
  void initState() {
    super.initState();

    if (Platform.isAndroid) {
      _activateStepCounterSensor();
    } else if (Platform.isIOS) {
      //TODO check if anything is needed to to here
    }
  }

  void _activateStepCounterSensor() async {
    MethodChannel _stepCounterChannel = MethodChannel('com.cedricds.wanderapp/stepCounter'); //convention
    dynamic result = await _stepCounterChannel.invokeMethod('activateStepCounterSensor');
    switch (result) {
      case "success":
        //The following line gets printed when I run the flutter app on my Samsung Galaxy S7:
        print('_activateStepCounterSensor(): successfully registered step counter sensor for android');
        break;
      case "error":
        print('_activateStepCounterSensor(): failed to register step counter sensor (not available) for android');
        //TODO display errorpage (because app is completely useless in this case)
        break;
      default:
        print('_activateStepCounterSensor(): unknown result: $result');
        break;
    }
  }

  //build() and other lifecycle-methods and helper methods: not important for this question
}

This is my MainActivity.kt file:

package com.cedricds.wanderapp

import android.content.Context
import android.hardware.Sensor
import android.hardware.SensorEvent
import android.hardware.SensorEventListener
import android.hardware.SensorManager
import android.util.Log
import android.widget.Toast
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel

class MainActivity2: FlutterActivity(), SensorEventListener {

    private val STEP_COUNTER_CHANNEL = "com.cedricds.wanderapp/stepCounter";
    private lateinit var channel: MethodChannel

    override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
        super.configureFlutterEngine(flutterEngine)

        channel = MethodChannel(flutterEngine.dartExecutor.binaryMessenger, STEP_COUNTER_CHANNEL)
        channel.setMethodCallHandler { call, result ->
            when(call.method){ //this is like switch-case statement in Java
                "activateStepCounterSensor" -> {
                    activateStepCounterSensor(result)
                }
            }
        }
    }

    private var sensorManager : SensorManager?=null
    private var sensor: Sensor ?= null

    private fun activateStepCounterSensor(result: MethodChannel.Result) {
        //This line gets printed when I run the flutter app, so the method gets called successfully:
        Log.d("Android", "Native Android: activateStepCounterSensor()")

        sensorManager = getSystemService(Context.SENSOR_SERVICE) as SensorManager
        sensor = sensorManager?.getDefaultSensor(Sensor.TYPE_STEP_COUNTER)
        if (sensor == null) {
            Toast.makeText(this, "missing hardware.", Toast.LENGTH_LONG).show()
            result.error("error", "error", "error")
        } else {
            sensorManager?.registerListener(this, sensor, SensorManager.SENSOR_DELAY_NORMAL)
            //This line gets printed:
            Log.d("Android", "Native Android: registered TYPE_STEP_COUNTER")
            //and never unregister that listener
            result.success("success")
        }
    }

    override fun onSensorChanged(p0: SensorEvent?) {}
    override fun onAccuracyChanged(p0: Sensor?, p1: Int) {}
}

Despite the few print(...) and Log.d(...) being printed in the console as expected, the app doesn't work how I expected it to work. When I exit the app, walk for example 50 steps, then open the app again, those 50 steps are missing. It seems the sensor is being unregistered somewhere.

2nd Attempt:

Modifying the pedometer package's code by removing unregisterListener(...):
The only changes I did to the file were 2 Log.d(...) statements and more importantly, commenting out a specific line of code.

modified SensorStreamHandler.kt from the pedometer package:

package com.example.pedometer

import android.content.Context
import android.hardware.Sensor
import android.hardware.SensorEventListener
import android.hardware.SensorManager
import android.os.Looper
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.plugin.common.BinaryMessenger
import io.flutter.plugin.common.EventChannel
import android.os.Handler
import android.util.Log

class SensorStreamHandler() : EventChannel.StreamHandler {

    private var sensorEventListener: SensorEventListener? = null
    private var sensorManager: SensorManager? = null
    private var sensor: Sensor? = null
    private lateinit var context: Context
    private lateinit var sensorName: String
    private lateinit var flutterPluginBinding: FlutterPlugin.FlutterPluginBinding

    constructor(flutterPluginBinding: FlutterPlugin.FlutterPluginBinding, sensorType: Int) : this() {
        this.context = flutterPluginBinding.applicationContext
        this.sensorName = if (sensorType == Sensor.TYPE_STEP_COUNTER) "StepCount" else "StepDetection"
        sensorManager = context.getSystemService(Context.SENSOR_SERVICE) as SensorManager
        sensor = sensorManager!!.getDefaultSensor(sensorType)
        this.flutterPluginBinding = flutterPluginBinding
    }

    override fun onListen(arguments: Any?, events: EventChannel.EventSink?) {
        Log.d("Pedometer", "Native Android: onListen()")
        if (sensor == null) {
            events!!.error("1", "$sensorName not available",
                    "$sensorName is not available on this device");
        } else {
            sensorEventListener = sensorEventListener(events!!);
            sensorManager!!.registerListener(sensorEventListener, sensor, SensorManager.SENSOR_DELAY_NORMAL);
        }
    }

    override fun onCancel(arguments: Any?) {
        Log.d("Pedometer", "Native Android: onCancel()")

        //The only change I did: commenting out the following line:
//        sensorManager!!.unregisterListener(sensorEventListener);
    }

}

This also did not solve my problem. So if someone knows how I can permanently register the TYPE_STEP_COUNTER sensor in my flutter app, please let me know.

Body:
Update:
I've contacted one of the developers of the pedometer package, and he suggested me to use flutter_foreground_service (which is developed by the same team/company as pedometer). It works.

But I would still find it interesting, if there is another way (maybe similar to my 2 failed attempts).

I have so many people asking me for a more detailed description of how I solved my problem. Unfortunately I can't share my whole code with you, just this small snipped which always gets run at the beginning (right after main()):

    if (Platform.isAndroid && !SharedPrefsHelper().isForegroundServiceStarted()) {
      ForegroundService().start();
      // ForegroundServiceNotification.setPriority(AndroidNotificationPriority.LOW);
      SharedPrefsHelper().setIsForegroundServiceStarted(true);
    }

Don't worry about SharedPrefsHelper, that's just a class that I created to make it easier to work with shared_preferences.


问:
Split netcdf4 file based on latitude values in python
I have a netCDF file with three variables:

```<code>input.variables

{'longitude': <class 'netCDF4._netCDF4.Variable'>
 float32 longitude(longitude)

'latitude': <class 'netCDF4._netCDF4.Variable'>
 float32 latitude(latitude)

'Values': <class 'netCDF4._netCDF4.Variable'>
 int16 Values(time, latitude, longitude)

{'time':
 Length: 504, dtype: datetime64[ns],
}
</code>```

I want to split this netcdf file in the northern and southern hemisphere. I would guess this is a simple boolean indexing issue, but this is simply not possible. I have tried it as the following:

```<code>south_mask = input[input.variables['latitude'][:] < 0]
north_mask = input[input.variables['latitude'][:] >= 0]
</code>```

But this doesn't work:

```<code>TypeError: expected str, bytes or os.PathLike object, not MaskedArray
</code>```

I need the full netcdf file as well in this particular project, so I want to do this within python not externally using the command line for instance.

Currently I am doing it like this:

```<code>middle_index = input.variables['longitude'][:].tolist().index(0.)

# create empty df
N_df = pd.DataFrame(columns = ['Time', 'Value'])
S_df = pd.DataFrame(columns = ['Time', 'Value'])

# Index based on values
for i in range(0, 504):
    # Get time
    time = input['time'][i]

    # Then loop and index from beginning to middle index, and middle index to end.
    N = np.average(input['Value'][i, :middle_index, :])
    S = np.average(input['Value'][i, middle_index:, :])

    # then making two dataframes and appending to two
    N_df_tmp = pd.DataFrame({'Time' : [time],
                                     'Value': [Value]})
    S_df_tmp = pd.DataFrame({'Time' : [time],
                                     'Value': [Value]})
    # Resulting in two dataframes.
    S_df = S_df.append(S_df_tmp)
    N_df = N_df.append(N_df_tmp)

</code>```

But I feel like there must be an easier method to slice the datasets in two, even without a loop.

答:
You should be looking at xarray.

```<code>import xarray as xr
ds = xr.open_dataset("globe.nc")
northern = ds.sel(latitude=slice(0, 90))
southern = ds.sel(latitude=slice(-90, 0))

# if latitude in decreasing order:
# northern = ds.sel(latitude=slice(90, 0))
</code>```

If you need to write files, look at the to_netcdf() method. But then command line tools would be better for this.

Body:
I have a netCDF file with three variables:

input.variables

{'longitude': <class 'netCDF4._netCDF4.Variable'>
 float32 longitude(longitude)

'latitude': <class 'netCDF4._netCDF4.Variable'>
 float32 latitude(latitude)

'Values': <class 'netCDF4._netCDF4.Variable'>
 int16 Values(time, latitude, longitude)

{'time':
 Length: 504, dtype: datetime64[ns],
}

I want to split this netcdf file in the northern and southern hemisphere. I would guess this is a simple boolean indexing issue, but this is simply not possible. I have tried it as the following:

south_mask = input[input.variables['latitude'][:] < 0]
north_mask = input[input.variables['latitude'][:] >= 0]

But this doesn't work:

TypeError: expected str, bytes or os.PathLike object, not MaskedArray

I need the full netcdf file as well in this particular project, so I want to do this within python not externally using the command line for instance.

Currently I am doing it like this:

middle_index = input.variables['longitude'][:].tolist().index(0.)

# create empty df
N_df = pd.DataFrame(columns = ['Time', 'Value'])
S_df = pd.DataFrame(columns = ['Time', 'Value'])

# Index based on values
for i in range(0, 504):
    # Get time
    time = input['time'][i]

    # Then loop and index from beginning to middle index, and middle index to end.
    N = np.average(input['Value'][i, :middle_index, :])
    S = np.average(input['Value'][i, middle_index:, :])

    # then making two dataframes and appending to two
    N_df_tmp = pd.DataFrame({'Time' : [time],
                                     'Value': [Value]})
    S_df_tmp = pd.DataFrame({'Time' : [time],
                                     'Value': [Value]})
    # Resulting in two dataframes.
    S_df = S_df.append(S_df_tmp)
    N_df = N_df.append(N_df_tmp)

But I feel like there must be an easier method to slice the datasets in two, even without a loop.

Body:
You should be looking at xarray.

import xarray as xr
ds = xr.open_dataset("globe.nc")
northern = ds.sel(latitude=slice(0, 90))
southern = ds.sel(latitude=slice(-90, 0))

# if latitude in decreasing order:
# northern = ds.sel(latitude=slice(90, 0))

If you need to write files, look at the to_netcdf() method. But then command line tools would be better for this.


问:
Finding Minimum For every group in ArrayList in Java
I have a class as below.

```<code>public class Employee{
int EmployeeDepartmentId;
int EmplyoyeeId;
int Salary;
}
</code>```

I an creating an ArrayList as Below.

```<code>ArrayList<Employee> arrEmployee = new ArrayList<Employee>;
</code>```

Now, I want to find out List of employees from every department with minimum salary.

How can this be achieved. I tried using Collections.Min(), but that will give me the minimum salary from whole list. I want it to be grouped by department.

Any suggestions?

答:
You should make your own comparator :

```<code>Collections.min(list,new Comparator<Employee>() {
              public int compare(Employee  e1, Employee e2) {
                        return e2.getSalary().compareTo(e1.getSalary());
                    }
                });
</code>```

I Hope this help.

This will only get the minimum salary.

ContentLicense: CC BY-SA 3.0

Body:
I have a class as below.

public class Employee{
int EmployeeDepartmentId;
int EmplyoyeeId;
int Salary;
}

I an creating an ArrayList as Below.

ArrayList<Employee> arrEmployee = new ArrayList<Employee>;

Now, I want to find out List of employees from every department with minimum salary.

How can this be achieved. I tried using Collections.Min(), but that will give me the minimum salary from whole list. I want it to be grouped by department.

Any suggestions?

Body:
You should make your own comparator :

Collections.min(list,new Comparator<Employee>() {
              public int compare(Employee  e1, Employee e2) {
                        return e2.getSalary().compareTo(e1.getSalary());
                    }
                });

I Hope this help.

This will only get the minimum salary.


问:
Is it more gas expensive to import an array from ipfs or create a state variable in solidity?
I want to have a whitelisted addresses array, but in a gas-efficient way. What I want is to let users that hold an ERC20 token which is on polygon, to mint nfts on ethereum. I know that from ethereum it is impossible to read from another blockchain (as I’m concerned), so, is it more gas expensive to create a state array of addresses or rather create a json file uploaded to ipfs, and then import it in solidity?</p>

答:
So let's start from the beginning.

there isn't any way to import json data inside solidity and parse it, you have also to import files at the time of deployment, this means that you already have the addresses of the people in the whitelist in your hand before the deploy, so if you really want to save,  you could hard coding them directly (even if it would be horrible)

even if it were possible to import json files, this would require a lot of memory usage, so it would be extremely expensive if the json started to be "medium" length

having said that leaving you few possibilities I would tell you to use state variables


问:
How to parse and convert string list to JSON string array in shell command?
How to parse and convert string list to JSON string array in shell command?

```<code>'["test1","test2","test3"]'
</code>```

to

```<code>test1
test2
test3
</code>```

I tried like below:

```<code>string=$1
array=${string#"["}
array=${array%"]"}

IFS=',' read -a array <<< $array;

echo "${array[@]}"
</code>```

Any other optimized way?

Body:
How to parse and convert string list to JSON string array in shell command?

'["test1","test2","test3"]'

to

test1
test2
test3

I tried like below:

string=$1
array=${string#"["}
array=${array%"]"}

IFS=',' read -a array <<< $array;

echo "${array[@]}"

Any other optimized way?

Body: eval "array=($( jq -r 'map( @sh ) | join(" ")' <<<"$json" ))"


问:
Batch conversion from json to parquet in python?
I have hundreds of json files need to be coverted to parquet files. I know we can read the json to pandas dataframe with pd.read_json and then save to parquet file using df.to_parquet. But the challenge is how to do it efficiently with hundreds of files.

Anybody know how to do it? Thank you very much!

答:
You could use multiprocessing to convert multiple files at once, in the convert function put your code, if you need to you could change filePath to the contents as a string or array and then also change the values of files

```<code>import multiprocessing

def convert(filePath):
    # Put the conversion code here

files = ["file1.json", "file2.json"]
with multiprocessing.Pool(processes=10) as pool: # You can change the number of processes
        pool.map(convert, files) # Tells multiprocessing to run the convert function with all of the file paths
</code>```

Body:
You could use multiprocessing to convert multiple files at once, in the convert function put your code, if you need to you could change filePath to the contents as a string or array and then also change the values of files

import multiprocessing

def convert(filePath):
    # Put the conversion code here

files = ["file1.json", "file2.json"]
with multiprocessing.Pool(processes=10) as pool: # You can change the number of processes
        pool.map(convert, files) # Tells multiprocessing to run the convert function with all of the file paths


问:
Email Table Layout - Overlapping text
I am using this template: https://mailbakery.com/template-store/product/basic-free-html-email-template/ for an email newsletter. I am having an issue with overlapping text in the testimonial on mobile. I have to have the quotation image which isn't in the jsfiddle but use your imagination lol. I've tried adding white-space: normal, a fixed-width, and word-break, but nothing. The tables have border-collapse: border.

Here is the jsFiddle: https://jsfiddle.net/z5jybrda/

 /* Linked Styles */
      body {
        padding: 0 !important;
        margin: 0 !important;
        display: block !important;
        min-width: 100% !important;
        width: 100% !important;
        background: #ffffff;
        -webkit-text-size-adjust: none;
      }
      a {
        color: #0000ee;
        text-decoration: none;
      }
      p {
        padding: 0 !important;
        margin: 0 !important;
      }

      /* Mobile styles */
      @media only screen and (max-device-width: 480px),
        only screen and (max-width: 480px) {
        .table_wrapper {
          width: 95%;
        }

        .mobile-full-width {
          width: 100% !important;
        }

        .mobile-shell {
          width: 100% !important;
          min-width: 100% !important;
        }

        .text-header,
        .m-center {
          text-align: center !important;
        }

        .m-font-15 {
          font-size: 15px !important;
        }

        .center {
          margin: 0 auto !important;
        }
        .container {
          padding: 20px 10px !important;
        }

        .td {
          width: 100% !important;
          min-width: 100% !important;
        }

        .m-br-15 {
          height: 15px !important;
        }
        .p30-15 {
          padding: 30px 15px !important;
        }
        .p0-15-30 {
          padding: 0px 15px 30px 15px !important;
        }
        .p0-15 {
          padding: 0px 15px !important;
        }
        .pb-30 {
          padding-bottom: 30px !important;
        }
        .mpb30 {
          padding-bottom: 30px !important;
        }
        .mpb15 {
          padding-bottom: 15px !important;
        }

        .m-td,
        .m-hide {
          display: none !important;
          width: 0 !important;
          height: 0 !important;
          font-size: 0 !important;
          line-height: 0 !important;
          min-height: 0 !important;
        }

        .column,
        .column-dir,
        .column-top,
        .column-empty,
        .column-empty2,
        .column-dir-top {
          float: left !important;
          width: 100% !important;
          display: block !important;
        }

        .column-empty {
          padding-bottom: 30px !important;
        }
        .column-empty2 {
          padding-bottom: 10px !important;
        }

        .content-spacing {
          width: 15px !important;
        }
      }

      @media only screen and (max-width: 310px) {
        .button {
          width: 195px !important;
        }

        img.quote {
          height: 22px;
          width: auto;
        }
        td.quote {
          width: 50px !important;
        }
      }```
<pre class="snippet-code-html lang-html prettyprint-override"><code>   <!-- WRAPPER -->
    <table width="100%" border="0" cellspacing="0" cellpadding="0" bgcolor="#ffffff">
      <tr>
        <td align="center" valign="top">
          <table width="100%" border="0" cellspacing="0" cellpadding="0" style="background: #f4f5f6">
            <tr>
              <td align="center">
                <table width="650" border="0" cellspacing="0" cellpadding="0" class="mobile-shell">
                  <tr>
                    <td class="td" style="
                        width: 650px;
                        min-width: 650px;
                        font-size: 0pt;
                        line-height: 0pt;
                        padding: 0;
                        margin: 0;
                        font-weight: normal;
                      ">

                      <!-- SPACER -->
                      <table width="100%" border="0" cellpadding="0" cellspacing="0">
                        <tr>
                          <td width="100%" height="30"></td>
                        </tr>
                      </table>

                      <!-- TESTIMONIAL -->
                      <table width="100%" border="0" cellpadding="0" cellspacing="0" style="background: #877454;">
                        <tr>
                          <td height="20"></td>
                        </tr>
                        <tr>
                          <td>
                            <table cellpadding="0" cellspacing="0" border="0" align="center" width="100%">
                              <tr>
                                <td width="20"></td>
                                <td>
                                  <table cellpadding="0" cellspacing="0" border="0" align="center" width="100%">
                                    <tr>
                                      <td valign="top" width="70" class="quote">
                                        <div><img src="./Newsletters/Images/colon.png" width="50" height="34" alt="quotation" style="display: block;" border="0" class="quote" />
                                        </div>
                                      </td>
                                      <td>
                                        <table cellpadding="0" cellspacing="0" border="0" align="center" width="100%">
                                          <tr>
                                            <td height="10"></td>
                                          </tr>
                                          <tr>
                                            <td style="font-size: 18px; color:#ffffff; font-family: 'Open Sans',Arial, sans-serif; font-style: italic; line-height: 1.5; " class="m-font-15">Thank you for your excellent leadership and support over the last year. We all greatly appreciate your efforts to steer us all in the right direction.
                                            </td>
                                          </tr>
                                          <tr>
                                            <td height="20"></td>
                                          </tr>
                                          <tr>
                                            <td style="font-size: 16px; color:#ffffff; font-family: 'Open Sans',Arial, sans-serif; ">
                                              <p>
                                                - John Doe recognizing <span style="text-decoration: underline;">John Doe</span>
                                              </p>
                                            </td>
                                          </tr>
                                        </table>
                                      </td>
                                    </tr>
                                  </table>
                                <td width="30"></td>
                          </td>
                        </tr>
                      </table>
                    </td>
                  </tr>
                  <tr>
                    <td height="40"></td>
                  </tr>
                </table>
                <!-- END TESTIMONIAL -->

              </td>
            </tr>
          </table>
        </td>
      </tr>
    </table>
    </td>
    </tr>
    </table>
  </body></code>```

I appreciate any help

答:
modifying the line height in the
 solves the issue (defined in the code you added as line-height:0, which causes the issue)

```<code><p> - John Doe recognizing <span style="text-decoration: underline;">John Doe</span> </p>
</code>```

would be

```<code><p style="line-height:1em;">  .... </p>
</code>```

Title: Email Table Layout - Overlapping text

Body:
I am using this template: https://mailbakery.com/template-store/product/basic-free-html-email-template/ for an email newsletter. I am having an issue with overlapping text in the testimonial on mobile. I have to have the quotation image which isn't in the jsfiddle but use your imagination lol. I've tried adding white-space: normal, a fixed-width, and word-break, but nothing. The tables have border-collapse: border.

Here is the jsFiddle: https://jsfiddle.net/z5jybrda/

 /* Linked Styles */
      body {
        padding: 0 !important;
        margin: 0 !important;
        display: block !important;
        min-width: 100% !important;
        width: 100% !important;
        background: #ffffff;
        -webkit-text-size-adjust: none;
      }
      a {
        color: #0000ee;
        text-decoration: none;
      }
      p {
        padding: 0 !important;
        margin: 0 !important;
      }

      /* Mobile styles */
      @media only screen and (max-device-width: 480px),
        only screen and (max-width: 480px) {
        .table_wrapper {
          width: 95%;
        }

        .mobile-full-width {
          width: 100% !important;
        }

        .mobile-shell {
          width: 100% !important;
          min-width: 100% !important;
        }

        .text-header,
        .m-center {
          text-align: center !important;
        }

        .m-font-15 {
          font-size: 15px !important;
        }

        .center {
          margin: 0 auto !important;
        }
        .container {
          padding: 20px 10px !important;
        }

        .td {
          width: 100% !important;
          min-width: 100% !important;
        }

        .m-br-15 {
          height: 15px !important;
        }
        .p30-15 {
          padding: 30px 15px !important;
        }
        .p0-15-30 {
          padding: 0px 15px 30px 15px !important;
        }
        .p0-15 {
          padding: 0px 15px !important;
        }
        .pb-30 {
          padding-bottom: 30px !important;
        }
        .mpb30 {
          padding-bottom: 30px !important;
        }
        .mpb15 {
          padding-bottom: 15px !important;
        }

        .m-td,
        .m-hide {
          display: none !important;
          width: 0 !important;
          height: 0 !important;
          font-size: 0 !important;
          line-height: 0 !important;
          min-height: 0 !important;
        }

        .column,
        .column-dir,
        .column-top,
        .column-empty,
        .column-empty2,
        .column-dir-top {
          float: left !important;
          width: 100% !important;
          display: block !important;
        }

        .column-empty {
          padding-bottom: 30px !important;
        }
        .column-empty2 {
          padding-bottom: 10px !important;
        }

        .content-spacing {
          width: 15px !important;
        }
      }

      @media only screen and (max-width: 310px) {
        .button {
          width: 195px !important;
        }

        img.quote {
          height: 22px;
          width: auto;
        }
        td.quote {
          width: 50px !important;
        }
      }

                                            Thank you for your excellent leadership and support over the last year. We all greatly appreciate your efforts to steer us all in the right direction.

                                                - John Doe recognizing John Doe

I appreciate any help

Body:
modifying the line height in the <p> solves the issue (defined in the code you added as line-height:0, which causes the issue)

<p> - John Doe recognizing <span style="text-decoration: underline;">John Doe</span> </p>

would be

<p style="line-height:1em;">  .... </p>


问:
What exact sequence of control characters ends a comment in C++?
The book A Tour of C++ states that

The double slash, //, begins a comment that extends to the end of the line.

What exact sequence of control characters constitutes the "end of line".

According to this wikipedia article, there are four different ways to represent a new line in ASCII.

These are the following sequences:

LF

CR

LF CR

CR LF

Will all of these work to separate the end of a comment from the beginning of the next line of code?

答: Yes. Any of these should work. CR LF (Windows) and LF (Unix-related) are the most commonly used these days, but the other two have been used historically.</p>


问:
How to connect mongodb with url
I am new to mongodb.
I have db url, and I want to connect to that server from my ubuntu terminal and access data on terminal.
can anyone please help me how to connect?</p>

答:
If mongodb version is 5.x.x
mongosh --host ip

Title: How to connect mongodb with url


问:
Python: Random numbers into a list
Create a 'list' called my_randoms of 10 random numbers between 0 and 100.

This is what I have so far:

```<code>import random
my_randoms=[]
for i in range (10):
    my_randoms.append(random.randrange(1, 101, 1))
    print (my_randoms)
</code>```

Unfortunately Python's output is this:

```<code>[34]
[34, 30]
[34, 30, 75]
[34, 30, 75, 27]
[34, 30, 75, 27, 8]
[34, 30, 75, 27, 8, 58]
[34, 30, 75, 27, 8, 58, 10]
[34, 30, 75, 27, 8, 58, 10, 1]
[34, 30, 75, 27, 8, 58, 10, 1, 59]
[34, 30, 75, 27, 8, 58, 10, 1, 59, 25]
</code>```

It generates the 10 numbers like I ask it to, but it generates it one at a time. What am I doing wrong?

答:
The one random list generator in the random module not mentioned here is random.choices:

```<code>my_randoms = random.choices(range(0, 100), k=10)
</code>```

It's like random.sample but with replacement. The sequence passed doesn't have to be a range; it doesn't even have to be numbers. The following works just as well:

```<code>my_randoms = random.choices(['a','b'], k=10)
</code>```

If we compare the runtimes, among random list generators, random.choices is the fastest no matter the size of the list to be created. However, for larger lists/arrays, numpy options are much faster. So for example, if you're creating a random list/array to assign to a pandas DataFrame column, then using np.random.randint is the fastest option.

Code used to produce the above plot:

```<code>import perfplot
import numpy as np
import random

perfplot.show(
    setup=lambda n: n,
    kernels=[
        lambda n: [random.randint(0, n*2) for x in range(n)],
        lambda n: random.sample(range(0, n*2), k=n),
        lambda n: [random.randrange(n*2) for i in range(n)],
        lambda n: random.choices(range(0, n*2), k=n),
        lambda n: np.random.rand(n),
        lambda n: np.random.randint(0, n*2, size=n),
        lambda n: np.random.choice(np.arange(n*2), size=n),
    ],
    labels=['random_randint', 'random_sample', 'random_randrange', 'random_choices',
            'np_random_rand', 'np_random_randint', 'np_random_choice'],
    n_range=[2 ** k for k in range(17)],
    equality_check=None,
    xlabel='~n'
)
</code>```

Title: Python: Random numbers into a list

Body:
Create a 'list' called my_randoms of 10 random numbers between 0 and 100.

This is what I have so far:

import random
my_randoms=[]
for i in range (10):
    my_randoms.append(random.randrange(1, 101, 1))
    print (my_randoms)

Unfortunately Python's output is this:

[34]
[34, 30]
[34, 30, 75]
[34, 30, 75, 27]
[34, 30, 75, 27, 8]
[34, 30, 75, 27, 8, 58]
[34, 30, 75, 27, 8, 58, 10]
[34, 30, 75, 27, 8, 58, 10, 1]
[34, 30, 75, 27, 8, 58, 10, 1, 59]
[34, 30, 75, 27, 8, 58, 10, 1, 59, 25]

It generates the 10 numbers like I ask it to, but it generates it one at a time. What am I doing wrong?

Body:
The one random list generator in the random module not mentioned here is random.choices:

my_randoms = random.choices(range(0, 100), k=10)

It's like random.sample but with replacement. The sequence passed doesn't have to be a range; it doesn't even have to be numbers. The following works just as well:

my_randoms = random.choices(['a','b'], k=10)

If we compare the runtimes, among random list generators, random.choices is the fastest no matter the size of the list to be created. However, for larger lists/arrays, numpy options are much faster. So for example, if you're creating a random list/array to assign to a pandas DataFrame column, then using np.random.randint is the fastest option.

Code used to produce the above plot:

import perfplot
import numpy as np
import random

perfplot.show(
    setup=lambda n: n,
    kernels=[
        lambda n: [random.randint(0, n*2) for x in range(n)],
        lambda n: random.sample(range(0, n*2), k=n),
        lambda n: [random.randrange(n*2) for i in range(n)],
        lambda n: random.choices(range(0, n*2), k=n),
        lambda n: np.random.rand(n),
        lambda n: np.random.randint(0, n*2, size=n),
        lambda n: np.random.choice(np.arange(n*2), size=n),
    ],
    labels=['random_randint', 'random_sample', 'random_randrange', 'random_choices',
            'np_random_rand', 'np_random_randint', 'np_random_choice'],
    n_range=[2 ** k for k in range(17)],
    equality_check=None,
    xlabel='~n'
)


问:
Filter consecutive identical values if at start or end of unique id
I have a dataset with GPS locations of birds doing multiple trips from a colony. I want to remove all points within 3 km from the colony, but ONLY those that are at the beginning or the end of an individual trip (Unique_id). If they come to within 3 km of the colony in the middle of a trip, and then head off again without returning to the colony first, I want to retain these points.

I calculated the distance to the colony and then defined using a logical column whether the location was < 3km (1) or > 3km (0). With the coordinates removed, the dataframe looks a bit like the below dummy data. So from here, I am looking to define something along the lines of "remove rows with dist3k == 1 for the first or last consecutive "1"s of a Unique_id.

Hope this makes sense, and look forward to suggestions.

```<code># what the data looks like
data_orig <- data.frame(
  Index = rep(c('1','2','3','4','5','6','7','8','9','10',
                '11','12','13','14','15','16','17','18','19','20')),
  Unique_id = rep(c('A1','A2'), each = 10),
  dist3k = rep(c('1','1','0','0','0','1','1','0','0','1','1','1','1','0','1','0','1','0','1','1')))

# what I want the output to be
data_new <-data_orig[-c(1,2,10,11,12,13,19,20),]

</code>```

答:
Here's an approach with dplyr and cumsum.

It works by inverting the binary values dist3k!=1 and then calculating the cumulative sum cumsum(dist3k!=1), which is always zero in the beginning when the vector starts with 1.

Then for the last values the same is done but in reverse.

We now have two vectors fil1 and fil2 where we can filter looking for non-zero values.

```<code>library(dplyr)

data_orig %>%
  group_by(Unique_id) %>%
  mutate(fil1=cumsum(dist3k!=1), fil2=rev(cumsum(rev(dist3k)!=1))) %>%
  filter(fil1!=0 & fil2!=0) %>%
  ungroup() %>%
  select(-starts_with("fil"))
# A tibble: 12 × 3
   Index Unique_id dist3k
   <chr> <chr>     <chr>
 1 3     A1        0
 2 4     A1        0
 3 5     A1        0
 4 6     A1        1
 5 7     A1        1
 6 8     A1        0
 7 9     A1        0
 8 14    A2        0
 9 15    A2        1
10 16    A2        0
11 17    A2        1
12 18    A2        0
</code>```

Body:
I have a dataset with GPS locations of birds doing multiple trips from a colony. I want to remove all points within 3 km from the colony, but ONLY those that are at the beginning or the end of an individual trip (Unique_id). If they come to within 3 km of the colony in the middle of a trip, and then head off again without returning to the colony first, I want to retain these points.

I calculated the distance to the colony and then defined using a logical column whether the location was < 3km (1) or > 3km (0). With the coordinates removed, the dataframe looks a bit like the below dummy data. So from here, I am looking to define something along the lines of "remove rows with dist3k == 1 for the first or last consecutive "1"s of a Unique_id.

Hope this makes sense, and look forward to suggestions.

# what the data looks like
data_orig <- data.frame(
  Index = rep(c('1','2','3','4','5','6','7','8','9','10',
                '11','12','13','14','15','16','17','18','19','20')),
  Unique_id = rep(c('A1','A2'), each = 10),
  dist3k = rep(c('1','1','0','0','0','1','1','0','0','1','1','1','1','0','1','0','1','0','1','1')))

# what I want the output to be
data_new <-data_orig[-c(1,2,10,11,12,13,19,20),]

Body:
Here's an approach with dplyr and cumsum.

It works by inverting the binary values dist3k!=1 and then calculating the cumulative sum cumsum(dist3k!=1), which is always zero in the beginning when the vector starts with 1.

Then for the last values the same is done but in reverse.

We now have two vectors fil1 and fil2 where we can filter looking for non-zero values.

library(dplyr)

data_orig %>%
  group_by(Unique_id) %>%
  mutate(fil1=cumsum(dist3k!=1), fil2=rev(cumsum(rev(dist3k)!=1))) %>%
  filter(fil1!=0 & fil2!=0) %>%
  ungroup() %>%
  select(-starts_with("fil"))
# A tibble: 12 × 3
   Index Unique_id dist3k
   <chr> <chr>     <chr>
 1 3     A1        0
 2 4     A1        0
 3 5     A1        0
 4 6     A1        1
 5 7     A1        1
 6 8     A1        0
 7 9     A1        0
 8 14    A2        0
 9 15    A2        1
10 16    A2        0
11 17    A2        1
12 18    A2        0


问:
How to process the redirect in post method using HttpClient?
In My App , I POST a xml file to the server , but sometimes the server will send back 302 and then redirect .

However , after the redirecting the method become GET , not POST, and my data in xml file can't deliver to server.

And finally the status code I got is 404.

Is there some way to process the redirect by myself ? Can I do something when the redirecting is happening?

Anyone can help? THX.!

答:
For the record, 302's should not be treated as an instruction to perform the redirected request as a GET, that is what 303's are for. This behaviour is sloppy and the developers of HttpClient should be ashamed of themselves... :-P

I suspect your only option would be write your own, socket level implementation of an HTTP Client, that handles the redirects properly. You can have a look round the internet to see if anyone else has already produced to some code you can borrow, but if not you will have to do it yourself.

I have done this before in PHP - it's not actually that hard, HTTP is a fairly simple protocol to implement. I think cURL handles these redirects properly, if you can sub the task out to that?


问:
Range for msg_id for send.reaction?
How i can set a range for msg_id for sending reactions in channel? For example i want to send reaction to last 10 posts in my channel.

Send a reaction

app.send_reaction(chat_id, message_id, "")

答:
There is no method to send a reaction to multiple messages at once.

You could use a for loop to iterate over multiple IDs to send a reaction to:

for message_id in list_of_message_ids:
   app.send_reaction(chat_id, message_id, "")
```

Title: Range for msg_id for send.reaction?


问:
Destination /etc/default/kubelet does not exist
I am trying to install kubernetes cluster with vagrant and ansible and it does not work.
As the error message, I've got:

```<code>TASK [Configure node ip] *******************************************************
fatal: [k8s-node-3]: FAILED! => {"changed": false, "msg": "Destination /etc/default/kubelet does not exist !", "rc": 257}

RUNNING HANDLER [docker status] ************************************************

PLAY RECAP *********************************************************************
k8s-node-3                 : ok=10   changed=8    unreachable=0    failed=1    skipped=1    rescued=0    ignored=0

Ansible failed to complete successfully. Any error output should be
visible above. Please fix these errors and try again.
</code>```

The vagrant file:

```<code>IMAGE_NAME = "ubuntu/bionic64"
Nodes = 3

Vagrant.configure("2") do |config|
    config.ssh.insert_key = false

    config.vm.provider "virtualbox" do |v|
        v.memory = 1024
        v.cpus = 2
    end

    config.vm.define "k8s-master" do |master|
        master.vm.box = IMAGE_NAME
        master.vm.network "private_network", ip: "192.168.99.100", name: "vboxnet0", adapter: 2
        master.vm.hostname = "k8s-master"
        master.vm.provision "ansible" do |ansible|
            ansible.playbook = "k8s-setup/master-playbook.yml"
            ansible.extra_vars = {
                node_ip: "192.168.99.100",
            }
        end
    end

    (1..Nodes).each do |i|
        config.vm.define "k8s-node-#{i}" do |node|
            node.vm.box = IMAGE_NAME
            node.vm.network "private_network", ip: "192.168.99.#{100 + i}", name: "vboxnet0", adapter: 2
            node.vm.hostname = "k8s-node-#{i}"
            node.vm.provision "ansible" do |ansible|
                ansible.playbook = "k8s-setup/node-playbook.yml"
                ansible.extra_vars = {
                    node_ip: "192.168.99.#{100 + i}",
                }
            end
        end
    end

end
</code>```

and the master-playbook.yml file

```<code>---
- hosts: all
  become: true
  tasks:
  - name: Install packages that allow apt to be used over HTTPS
    apt:
      name: "{{ packages }}"
      state: present
      update_cache: yes
    vars:
      packages:
      - apt-transport-https
      - ca-certificates
      - curl
      - gnupg-agent
      - software-properties-common

  - name: Add an apt signing key for Docker
    apt_key:
      url: https://download.docker.com/linux/ubuntu/gpg
      state: present

  - name: Add apt repository for stable version
    apt_repository:
      repo: deb [arch=amd64] https://download.docker.com/linux/ubuntu xenial stable
      state: present

  - name: Install docker and its dependecies
    apt:
      name: "{{ packages }}"
      state: present
      update_cache: yes
    vars:
      packages:
      - docker-ce
      - docker-ce-cli
      - containerd.io
    notify:
      - docker status

  - name: Add vagrant user to docker group
    user:
      name: vagrant
      group: docker

  - name: Remove swapfile from /etc/fstab
    mount:
      name: "{{ item }}"
      fstype: swap
      state: absent
    with_items:
      - swap
      - none

  - name: Disable swap
    command: swapoff -a
    when: ansible_swaptotal_mb > 0

  - name: Add an apt signing key for Kubernetes
    apt_key:
      url: https://packages.cloud.google.com/apt/doc/apt-key.gpg
      state: present

  - name: Adding apt repository for Kubernetes
    apt_repository:
      repo: deb https://apt.kubernetes.io/ kubernetes-xenial main
      state: present
      filename: kubernetes.list

  - name: Install Kubernetes binaries
    apt:
      name: "{{ packages }}"
      state: present
      update_cache: yes
    vars:
      packages:
        - kubelet
        - kubeadm
        - kubectl

  - name: Configure node ip
    lineinfile:
      path: /etc/default/kubelet
      line: KUBELET_EXTRA_ARGS=--node-ip={{ node_ip }}

  - name: Restart kubelet
    service:
      name: kubelet
      daemon_reload: yes
      state: restarted

  - name: Initialize the Kubernetes cluster using kubeadm
    command: kubeadm init --apiserver-advertise-address="192.168.99.100" --apiserver-cert-extra-sans="192.168.99.100"  --node-name k8s-master --pod-network-cidr=192.168.0.0/16

  - name: Setup kubeconfig for vagrant user
    command: "{{ item }}"
    with_items:
     - mkdir -p /home/vagrant/.kube
     - cp -i /etc/kubernetes/admin.conf /home/vagrant/.kube/config
     - chown vagrant:vagrant /home/vagrant/.kube/config

  - name: Install calico pod network
    become: false
    command: kubectl create -f https://docs.projectcalico.org/v3.4/getting-started/kubernetes/installation/hosted/calico.yaml

  - name: Generate join command
    command: kubeadm token create --print-join-command
    register: join_command

  - name: Copy join command to local file
    local_action: copy content="{{ join_command.stdout_lines[0] }}" dest="./join-command"

  handlers:
    - name: docker status
      service: name=docker state=started
</code>```

and the node-playbook.yml

```<code>---
- hosts: all
  become: true
  tasks:
  - name: Install packages that allow apt to be used over HTTPS
    apt:
      name: "{{ packages }}"
      state: present
      update_cache: yes
    vars:
      packages:
      - apt-transport-https
      - ca-certificates
      - curl
      - gnupg-agent
      - software-properties-common

  - name: Add an apt signing key for Docker
    apt_key:
      url: https://download.docker.com/linux/ubuntu/gpg
      state: present

  - name: Add apt repository for stable version
    apt_repository:
      repo: deb [arch=amd64] https://download.docker.com/linux/ubuntu xenial stable
      state: present

  - name: Install docker and its dependecies
    apt:
      name: "{{ packages }}"
      state: present
      update_cache: yes
    vars:
      packages:
      - docker-ce
      - docker-ce-cli
      - containerd.io
    notify:
      - docker status

  - name: Add vagrant user to docker group
    user:
      name: vagrant
      group: docker

  - name: Remove swapfile from /etc/fstab
    mount:
      name: "{{ item }}"
      fstype: swap
      state: absent
    with_items:
      - swap
      - none

  - name: Disable swap
    command: swapoff -a
    when: ansible_swaptotal_mb > 0

  - name: Add an apt signing key for Kubernetes
    apt_key:
      url: https://packages.cloud.google.com/apt/doc/apt-key.gpg
      state: present

  - name: Adding apt repository for Kubernetes
    apt_repository:
      repo: deb https://apt.kubernetes.io/ kubernetes-xenial main
      state: present
      filename: kubernetes.list

  - name: Install Kubernetes binaries
    apt:
      name: "{{ packages }}"
      state: present
      update_cache: yes
    vars:
      packages:
        - kubelet
        - kubeadm
        - kubectl

  - name: Configure node ip
    lineinfile:
      path: /etc/default/kubelet
      line: KUBELET_EXTRA_ARGS=--node-ip={{ node_ip }}

  - name: Restart kubelet
    service:
      name: kubelet
      daemon_reload: yes
      state: restarted

  - name: Copy the join command to server location
    copy: src=join-command dest=/tmp/join-command.sh mode=0777

  - name: Join the node to cluster
    command: sh /tmp/join-command.sh

  handlers:
  - name: docker status
    service: name=docker state=starte
</code>```

What is wrong? Why the kubelet file can not be found?

答:
I had the same error last time:

```<code>TASK [Configure node ip]
*******************************************************
fatal: [k8s-master]: FAILED! => {"changed": false, "msg": "Destination
/etc/default/kubelet does not exist !", "rc": 257}
</code>```

So please check your ansible-playbook and verify that the kubelet will be installed. If not please add create parameter:

```<code>create: yes
</code>```

So in your case, it should look like this:

```<code>- name: Configure node ip
  lineinfile:
    path: /etc/default/kubelet
    line: KUBELET_EXTRA_ARGS=--node-ip={{ node_ip }}
    create: yes
</code>```

Body:
I am trying to install kubernetes cluster with vagrant and ansible and it does not work.
As the error message, I've got:

TASK [Configure node ip] *******************************************************
fatal: [k8s-node-3]: FAILED! => {"changed": false, "msg": "Destination /etc/default/kubelet does not exist !", "rc": 257}

RUNNING HANDLER [docker status] ************************************************

PLAY RECAP *********************************************************************
k8s-node-3                 : ok=10   changed=8    unreachable=0    failed=1    skipped=1    rescued=0    ignored=0

Ansible failed to complete successfully. Any error output should be
visible above. Please fix these errors and try again.

The vagrant file:

IMAGE_NAME = "ubuntu/bionic64"
Nodes = 3

Vagrant.configure("2") do |config|
    config.ssh.insert_key = false

    config.vm.provider "virtualbox" do |v|
        v.memory = 1024
        v.cpus = 2
    end

    config.vm.define "k8s-master" do |master|
        master.vm.box = IMAGE_NAME
        master.vm.network "private_network", ip: "192.168.99.100", name: "vboxnet0", adapter: 2
        master.vm.hostname = "k8s-master"
        master.vm.provision "ansible" do |ansible|
            ansible.playbook = "k8s-setup/master-playbook.yml"
            ansible.extra_vars = {
                node_ip: "192.168.99.100",
            }
        end
    end

    (1..Nodes).each do |i|
        config.vm.define "k8s-node-#{i}" do |node|
            node.vm.box = IMAGE_NAME
            node.vm.network "private_network", ip: "192.168.99.#{100 + i}", name: "vboxnet0", adapter: 2
            node.vm.hostname = "k8s-node-#{i}"
            node.vm.provision "ansible" do |ansible|
                ansible.playbook = "k8s-setup/node-playbook.yml"
                ansible.extra_vars = {
                    node_ip: "192.168.99.#{100 + i}",
                }
            end
        end
    end

end

and the master-playbook.yml file

---
- hosts: all
  become: true
  tasks:
  - name: Install packages that allow apt to be used over HTTPS
    apt:
      name: "{{ packages }}"
      state: present
      update_cache: yes
    vars:
      packages:
      - apt-transport-https
      - ca-certificates
      - curl
      - gnupg-agent
      - software-properties-common

  - name: Add an apt signing key for Docker
    apt_key:
      url: https://download.docker.com/linux/ubuntu/gpg
      state: present

  - name: Add apt repository for stable version
    apt_repository:
      repo: deb [arch=amd64] https://download.docker.com/linux/ubuntu xenial stable
      state: present

  - name: Install docker and its dependecies
    apt:
      name: "{{ packages }}"
      state: present
      update_cache: yes
    vars:
      packages:
      - docker-ce
      - docker-ce-cli
      - containerd.io
    notify:
      - docker status

  - name: Add vagrant user to docker group
    user:
      name: vagrant
      group: docker

  - name: Remove swapfile from /etc/fstab
    mount:
      name: "{{ item }}"
      fstype: swap
      state: absent
    with_items:
      - swap
      - none

  - name: Disable swap
    command: swapoff -a
    when: ansible_swaptotal_mb > 0

  - name: Add an apt signing key for Kubernetes
    apt_key:
      url: https://packages.cloud.google.com/apt/doc/apt-key.gpg
      state: present

  - name: Adding apt repository for Kubernetes
    apt_repository:
      repo: deb https://apt.kubernetes.io/ kubernetes-xenial main
      state: present
      filename: kubernetes.list

  - name: Install Kubernetes binaries
    apt:
      name: "{{ packages }}"
      state: present
      update_cache: yes
    vars:
      packages:
        - kubelet
        - kubeadm
        - kubectl

  - name: Configure node ip
    lineinfile:
      path: /etc/default/kubelet
      line: KUBELET_EXTRA_ARGS=--node-ip={{ node_ip }}

  - name: Restart kubelet
    service:
      name: kubelet
      daemon_reload: yes
      state: restarted

  - name: Initialize the Kubernetes cluster using kubeadm
    command: kubeadm init --apiserver-advertise-address="192.168.99.100" --apiserver-cert-extra-sans="192.168.99.100"  --node-name k8s-master --pod-network-cidr=192.168.0.0/16

  - name: Setup kubeconfig for vagrant user
    command: "{{ item }}"
    with_items:
     - mkdir -p /home/vagrant/.kube
     - cp -i /etc/kubernetes/admin.conf /home/vagrant/.kube/config
     - chown vagrant:vagrant /home/vagrant/.kube/config

  - name: Install calico pod network
    become: false
    command: kubectl create -f https://docs.projectcalico.org/v3.4/getting-started/kubernetes/installation/hosted/calico.yaml

  - name: Generate join command
    command: kubeadm token create --print-join-command
    register: join_command

  - name: Copy join command to local file
    local_action: copy content="{{ join_command.stdout_lines[0] }}" dest="./join-command"

  handlers:
    - name: docker status
      service: name=docker state=started

and the node-playbook.yml

---
- hosts: all
  become: true
  tasks:
  - name: Install packages that allow apt to be used over HTTPS
    apt:
      name: "{{ packages }}"
      state: present
      update_cache: yes
    vars:
      packages:
      - apt-transport-https
      - ca-certificates
      - curl
      - gnupg-agent
      - software-properties-common

  - name: Add an apt signing key for Docker
    apt_key:
      url: https://download.docker.com/linux/ubuntu/gpg
      state: present

  - name: Add apt repository for stable version
    apt_repository:
      repo: deb [arch=amd64] https://download.docker.com/linux/ubuntu xenial stable
      state: present

  - name: Install docker and its dependecies
    apt:
      name: "{{ packages }}"
      state: present
      update_cache: yes
    vars:
      packages:
      - docker-ce
      - docker-ce-cli
      - containerd.io
    notify:
      - docker status

  - name: Add vagrant user to docker group
    user:
      name: vagrant
      group: docker

  - name: Remove swapfile from /etc/fstab
    mount:
      name: "{{ item }}"
      fstype: swap
      state: absent
    with_items:
      - swap
      - none

  - name: Disable swap
    command: swapoff -a
    when: ansible_swaptotal_mb > 0

  - name: Add an apt signing key for Kubernetes
    apt_key:
      url: https://packages.cloud.google.com/apt/doc/apt-key.gpg
      state: present

  - name: Adding apt repository for Kubernetes
    apt_repository:
      repo: deb https://apt.kubernetes.io/ kubernetes-xenial main
      state: present
      filename: kubernetes.list

  - name: Install Kubernetes binaries
    apt:
      name: "{{ packages }}"
      state: present
      update_cache: yes
    vars:
      packages:
        - kubelet
        - kubeadm
        - kubectl

  - name: Configure node ip
    lineinfile:
      path: /etc/default/kubelet
      line: KUBELET_EXTRA_ARGS=--node-ip={{ node_ip }}

  - name: Restart kubelet
    service:
      name: kubelet
      daemon_reload: yes
      state: restarted

  - name: Copy the join command to server location
    copy: src=join-command dest=/tmp/join-command.sh mode=0777

  - name: Join the node to cluster
    command: sh /tmp/join-command.sh

  handlers:
  - name: docker status
    service: name=docker state=starte

What is wrong? Why the kubelet file can not be found?

Body:
I had the same error last time:

TASK [Configure node ip]
*******************************************************
fatal: [k8s-master]: FAILED! => {"changed": false, "msg": "Destination
/etc/default/kubelet does not exist !", "rc": 257}

So please check your ansible-playbook and verify that the kubelet will be installed. If not please add create parameter:

create: yes

So in your case, it should look like this:

- name: Configure node ip
  lineinfile:
    path: /etc/default/kubelet
    line: KUBELET_EXTRA_ARGS=--node-ip={{ node_ip }}
    create: yes


问:
How do I run code after returned function subscription?
I have the following code that looks like this:

```<code>foo(){
   return this.service.asyncFunction();
}

//in another function:

this.foo().subscribe(() => { some_code });
</code>```

Is it possible to refactor the foo function too look like this:

```<code>foo(){
   return this.service.asyncFunction().subscribe();
}
</code>```

But still be able to run some_code after the subscription?

答:
If you want to subscribe inside foo() and still be able to send the observable you can do this

```<code>foo(){
   const myObs = this.service.asyncFunction();
   myObs.subscribe();
   return myObs;
}
</code>```

Somewhere else in the code, you can do this

```<code>this.foo().subscribe(() => { some_code });
</code>```

But if you want to use foo() and give it some code then you can do this

```<code>foo(callback){
   this.service.asyncFunction().subscribe(callback);
}
</code>```

And somewhere else in the code, do this

```<code>for(() => { some code });
</code>```

Body:
I have the following code that looks like this:

foo(){
   return this.service.asyncFunction();
}

//in another function:

this.foo().subscribe(() => { some_code });

Is it possible to refactor the foo function too look like this:

foo(){
   return this.service.asyncFunction().subscribe();
}

But still be able to run some_code after the subscription?

Body:
If you want to subscribe inside foo() and still be able to send the observable you can do this

foo(){
   const myObs = this.service.asyncFunction();
   myObs.subscribe();
   return myObs;
}

Somewhere else in the code, you can do this

this.foo().subscribe(() => { some_code });

But if you want to use foo() and give it some code then you can do this

foo(callback){
   this.service.asyncFunction().subscribe(callback);
}

And somewhere else in the code, do this

for(() => { some code });


问:
PL SQL Oracle Store Dynamic SQL result (Dynamic in a loop)
I'm new to PL/SQL on Oracle (have to do some work on this but it's clearly not my domain).

So I have to do an 'audit' of our DB which consists in giving for each column of each table of our schema its max length (how we declared it (VARCHAR2(15) for example) and the max value currently of this column (ID 15000 for example) (might evolve and want more data in my results but at the moment i just need this).

I will explain my problem with an example
to be clear :

I have a table EMPLOYEE with 3 columns :
NAME in VARCHAR2(50), the longest i have (in length) is 48
CITY in VARCHAR2(100), the longest i have (in length) is 95
AGE in NUMBER, the longest i have (in length) is 2

So for this table of my schema I would like to have as output of my script (to work on it in excel), it must be taken into account that here the employee table is only one among many others which is returned by the first request:

TABLE_NAME
COLUMN_NAME
MAX_LENGTH_DATA
MAX_LENGTH_COLUMN

EMPLOYEE
NAME
48
50

EMPLOYEE
CITY
95
100

EMPLOYEE
AGE
2
() (don't need)

So we will have 1 line per column and table, if my table have 5 columns i will have 5 lines.
I've tried many solutions with LOOP, CURSOR and now TYPE OBJECT but i'm doing something wrong i know but can't figure out what it is.

```<code>CREATE OR REPLACE TYPE t_output_allColumns FORCE AS OBJECT
           (maxLengthColumn  NUMBER,
            COLUMN_NAME     VARCHAR2(80),
            TABLE_NAME    VARCHAR2(80));
/
CREATE OR REPLACE TYPE output_allColumns FORCE AS TABLE OF t_output_allColumns;

DECLARE

    maxlengthTab  output_allColumns;
    v_requete_maxLength varchar2(4000);
    TYPE MyCurTyp  IS REF CURSOR;
    c1 MyCurTyp;
    v_column_name VARCHAR2(400);
    v_table_name VARCHAR2(400);

begin
 maxlengthTab:= output_allColumns();
 OPEN c1 FOR 'select TABLE_NAME, COLUMN_NAME from ALL_TAB_COLUMNS';

    FETCH c1 INTO v_column_name , v_table_name;
    v_requete_maxLength := 'SELECT MAX( LENGTH(' || v_column_name ||'), ' || v_column_name ||',' || v_table_name ||'  FROM ' ||v_table_name;
    EXECUTE IMMEDIATE v_requete_maxLength BULK COLLECT INTO maxlengthTab;
    dbms_output.put_line(output_allColumns);
  CLOSE c1;
END;
</code>```

Here is a script i tried, first thing i do is to select all columns from my schema (no problem with this, i already printed them to test and it's good)
But the main probleme is when i try to use dynamic SQL on my result

I try SELECT MAX( LENGTH(' ||  Colum_name i get from my 1st request||'), ' || Colum_name i get from my 1st request||',' || Table_name i get from my 1st request||'  FROM ' ||Table_name i get from my 1st request; and this is where I'm stuck, I can't store each result and display it.

答:
You can use a pipelined function.

Given the types:

CREATE TYPE t_output_allColumns AS OBJECT(
  OWNER           VARCHAR2(80),
  TABLE_NAME      VARCHAR2(80),
  COLUMN_NAME     VARCHAR2(80),
  maxLengthData   NUMBER,
  maxLengthColumn NUMBER
);

CREATE TYPE output_allColumns AS TABLE OF t_output_allColumns;
```
<p>Then the function:</p>
<pre class="lang-sql prettyprint-override"><code>CREATE FUNCTION column_details(
  i_owner IN VARCHAR2
)
RETURN output_allcolumns PIPELINED
IS
  v_data_length NUMBER;
BEGIN
  FOR r IN (
    SELECT owner,
           table_name,
           column_name,
           data_length
    FROM   all_tab_columns
    WHERE  owner = i_owner
  )
  LOOP
    EXECUTE IMMEDIATE
      'SELECT MAX(LENGTH("'||r.column_name||'")) FROM "'||r.owner||'"."'||r.table_name||'"'
      INTO v_data_length;
    PIPE ROW (
      t_output_allcolumns(
        r.owner,
        r.table_name,
        r.column_name,
        v_data_length,
        r.data_length
      )
    );
  END LOOP;
END;
/
</code>```

Then you can use:

SELECT * FROM TABLE(column_details('SCHEMA_NAME'));
```

Which outputs:

OWNER
TABLE_NAME
COLUMN_NAME
MAXLENGTHDATA
MAXLENGTHCOLUMN

SCHEMA_NAME
EMPLOYEES
NAME
48
50

SCHEMA_NAME
EMPLOYEES
AGE
2
22

SCHEMA_NAME
EMPLOYEES
CITY
95
100

db<>fiddle here

Body:
I'm new to PL/SQL on Oracle (have to do some work on this but it's clearly not my domain).

So I have to do an 'audit' of our DB which consists in giving for each column of each table of our schema its max length (how we declared it (VARCHAR2(15) for example) and the max value currently of this column (ID 15000 for example) (might evolve and want more data in my results but at the moment i just need this).

I will explain my problem with an example
to be clear :

I have a table EMPLOYEE with 3 columns :
NAME in VARCHAR2(50), the longest i have (in length) is 48
CITY in VARCHAR2(100), the longest i have (in length) is 95
AGE in NUMBER, the longest i have (in length) is 2

So for this table of my schema I would like to have as output of my script (to work on it in excel), it must be taken into account that here the employee table is only one among many others which is returned by the first request:

TABLE_NAME
COLUMN_NAME
MAX_LENGTH_DATA
MAX_LENGTH_COLUMN

EMPLOYEE
NAME
48
50

EMPLOYEE
CITY
95
100

EMPLOYEE
AGE
2
() (don't need)

So we will have 1 line per column and table, if my table have 5 columns i will have 5 lines.
I've tried many solutions with LOOP, CURSOR and now TYPE OBJECT but i'm doing something wrong i know but can't figure out what it is.

CREATE OR REPLACE TYPE t_output_allColumns FORCE AS OBJECT
           (maxLengthColumn  NUMBER,
            COLUMN_NAME     VARCHAR2(80),
            TABLE_NAME    VARCHAR2(80));
/
CREATE OR REPLACE TYPE output_allColumns FORCE AS TABLE OF t_output_allColumns;

DECLARE

    maxlengthTab  output_allColumns;
    v_requete_maxLength varchar2(4000);
    TYPE MyCurTyp  IS REF CURSOR;
    c1 MyCurTyp;
    v_column_name VARCHAR2(400);
    v_table_name VARCHAR2(400);

begin
 maxlengthTab:= output_allColumns();
 OPEN c1 FOR 'select TABLE_NAME, COLUMN_NAME from ALL_TAB_COLUMNS';

    FETCH c1 INTO v_column_name , v_table_name;
    v_requete_maxLength := 'SELECT MAX( LENGTH(' || v_column_name ||'), ' || v_column_name ||',' || v_table_name ||'  FROM ' ||v_table_name;
    EXECUTE IMMEDIATE v_requete_maxLength BULK COLLECT INTO maxlengthTab;
    dbms_output.put_line(output_allColumns);
  CLOSE c1;
END;

Here is a script i tried, first thing i do is to select all columns from my schema (no problem with this, i already printed them to test and it's good)
But the main probleme is when i try to use dynamic SQL on my result

I try SELECT MAX( LENGTH(' ||  Colum_name i get from my 1st request||'), ' || Colum_name i get from my 1st request||',' || Table_name i get from my 1st request||'  FROM ' ||Table_name i get from my 1st request; and this is where I'm stuck, I can't store each result and display it.

Body:
You can use a pipelined function.

Given the types:

CREATE TYPE t_output_allColumns AS OBJECT(
  OWNER           VARCHAR2(80),
  TABLE_NAME      VARCHAR2(80),
  COLUMN_NAME     VARCHAR2(80),
  maxLengthData   NUMBER,
  maxLengthColumn NUMBER
);

CREATE TYPE output_allColumns AS TABLE OF t_output_allColumns;

Then the function:

CREATE FUNCTION column_details(
  i_owner IN VARCHAR2
)
RETURN output_allcolumns PIPELINED
IS
  v_data_length NUMBER;
BEGIN
  FOR r IN (
    SELECT owner,
           table_name,
           column_name,
           data_length
    FROM   all_tab_columns
    WHERE  owner = i_owner
  )
  LOOP
    EXECUTE IMMEDIATE
      'SELECT MAX(LENGTH("'||r.column_name||'")) FROM "'||r.owner||'"."'||r.table_name||'"'
      INTO v_data_length;
    PIPE ROW (
      t_output_allcolumns(
        r.owner,
        r.table_name,
        r.column_name,
        v_data_length,
        r.data_length
      )
    );
  END LOOP;
END;
/

Then you can use:

SELECT * FROM TABLE(column_details('SCHEMA_NAME'));

Which outputs:

OWNER
TABLE_NAME
COLUMN_NAME
MAXLENGTHDATA
MAXLENGTHCOLUMN

SCHEMA_NAME
EMPLOYEES
NAME
48
50

SCHEMA_NAME
EMPLOYEES
AGE
2
22

SCHEMA_NAME
EMPLOYEES
CITY
95
100

db<>fiddle here