问:
js first progressbar in loop not updating
I have two progress bars which I want to update in sequence. After the first progressbar reached 100%. Then, the second progress bar should start. Progress bar follow the array key. a,b,c on first progress bar  and d,e,f on second progress bar. But, first progress stop at first task and continue to run second progress bar. I had tried increase the timeout. But, still the first progress bar stop in first task.

```<code><?php
 $grouped_records=
 [

                1=>array('a','b','c'),
                2=>array('d','e','f')

];

?>
<html>
 <head>
  <style>
        .progress-bar-1  .progress-bar-2
        {
            border: 1px solid black;
            background-color: #f0f0f0;
        }

        .progress-bar-1 div , .progress-bar-2 div
        {
            background-color: gray;
            height: 2.00em;
            font-size:30px;

        }

    </style>
      <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script>
        function delayedLoop(collection, delay, callback, context)
        {
            context = context || null;

            var i = 0,
            nextInteration = function()
            {
                if (i === collection.length)
                {
                    return;
                }

                callback.call(context, collection[i], i);
                i++;
                setTimeout(nextInteration, delay);
            };

            nextInteration();
        }
        Object.size = function(obj)
        {
            var size = 0, key;
            for (key in obj)
            {
                if (obj.hasOwnProperty(key)) size++;
            }
            return size;
        };

        $(document).ready(function()
        {

        var level_records       ='<?php echo json_encode($grouped_records);?>';
        level_records           =JSON.parse(level_records);
        //get object size-https://stackoverflow.com/questions/5223/length-of-a-javascript-object
        var size        =Object.size(level_records);
        interval_array  =[1000,1000];
            for(i=1;i<=size;i++)
            {
                css_class       =".progress-bar-"+i+" div";
                //delayedloop-https://stackoverflow.com/questions/30987218/update-progressbar-in-each-loop
                var progressBar = document.querySelector(css_class);
                items           =level_records[i];
                delayedLoop(items, interval_array[i], function(item, index)
                    {
                        perc        =((index + 1) / items.length * 100);
                        perc        =(Math.round(perc * 100) / 100).toFixed(2);
                        var width   =perc + "%";
                        progressBar.style.width = width;
                        progressBar.innerHTML = (index + 1) + '/' + items.length + ' - ' + items[index] + ' (' + width + ')';
                    });
            }

        })

    </script>

</head>
<body>
    <div class="progress-bar-1">
        <div style="width: 0">
        </div>
    </div>
    <div>interval</div>
    <div class="progress-bar-2">
        <div style="width: 0">
        </div>
    </div>

</body>
</code>```

Thanks in advance.

答:
I had refer this and tried replace for loop with an asynchronous loop that uses setTimeout(). I count current level itemlist, items_count. Since I put delay 1000 when loop in items in each level, I count delay from one level to another as items_count * 1000(if 9 items would be 9000 delay to proceed to second progressbar). This has solve my problem

```<code><?php

$grouped_records=
[

                1=>array('a','b','c'),//level 1-first progressbar
                2=>array('d','e','f')//level 2-second progressbar

 ];

 ?>
<html>
<head>
<style>
        .progress-bar-1  .progress-bar-2
        {
            border: 1px solid black;
            background-color: #f0f0f0;
        }

        .progress-bar-1 div , .progress-bar-2 div
        {
            background-color: gray;
            height: 2.00em;
            font-size:30px;

        }

    </style>
      <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script>
        function delayedLoop(collection, delay, callback, context)
        {
            context = context || null;

            var i = 0,
            nextInteration = function()
            {
                if (i === collection.length)
                {
                    return;
                }

                callback.call(context, collection[i], i);
                i++;
                setTimeout(nextInteration, delay);
            };

            nextInteration();
        }
        Object.size = function(obj)
        {
            var size = 0, key;
            for (key in obj)
            {
                if (obj.hasOwnProperty(key)) size++;
            }
            return size;
        };

        $(document).ready(function()
        {

        var level_records       ='<?php echo json_encode($grouped_records);?>';
        level_records           =JSON.parse(level_records);
        //get object size-https://stackoverflow.com/questions/5223/length-of-a-javascript-object
        var size        =Object.size(level_records);
        //interval_array    =[1000,1000];
        /*  for(i=1;i<=size;i++)
            {
                css_class       =".progress-bar-"+i+" div";
                //delayedloop-https://stackoverflow.com/questions/30987218/update-progressbar-in-each-loop
                var progressBar = document.querySelector(css_class);
                items           =level_records[i];
                console.log(items);
                delayedLoop(items, interval_array[i], function(item, index)
                    {
                        perc                    =((index + 1) / items.length * 100);
                        perc                    =(Math.round(perc * 100) / 100).toFixed(2);
                        var width               =perc + "%";
                        progressBar.style.width =width;
                        progressBar.innerHTML   =(index + 1) + '/' + items.length + ' - ' + items[index] + ' (' + width + ')';
                    });
            }*/
            //https://stackoverflow.com/questions/17957823/javascript-how-to-update-a-progress-bar-in-a-for-loop
            var i = 1;
            (function doSort()
                {
                    // update progress
                    css_class       =".progress-bar-"+i+" div";
                    //delayedloop-https://stackoverflow.com/questions/30987218/update-progressbar-in-each-loop
                    var progressBar     =document.querySelector(css_class);
                    items               =level_records[i];
                    items_count         =level_records[i].length;
                    interval_nextlevel  =items_count*1000;//count time for next level to start and pass to setTimout()
                    console.log(items_count);
                    //console.log(items);
                    delayedLoop(items, 1000, function(item, index)
                        {
                            perc                    =((index + 1) / items.length * 100);
                            perc                    =(Math.round(perc * 100) / 100).toFixed(2);
                            var width               =perc + "%";
                            progressBar.style.width =width;
                            progressBar.innerHTML   =(index + 1) + '/' + items.length + ' - ' + items[index] + ' (' + width + ')';
                        });

                    // do stuff
                    i++;
                    if (i <= size)
                    {
                        setTimeout(doSort, interval_nextlevel);
                    }
                })();

        })

    </script>

</head>
<body>
    <div class="progress-bar-1">
        <div style="width: 0">
        </div>
    </div>
    <div>interval</div>
    <div class="progress-bar-2">
        <div style="width: 0">
        </div>
    </div>

</body>
</code>```

Body:
I have two progress bars which I want to update in sequence. After the first progressbar reached 100%. Then, the second progress bar should start. Progress bar follow the array key. a,b,c on first progress bar  and d,e,f on second progress bar. But, first progress stop at first task and continue to run second progress bar. I had tried increase the timeout. But, still the first progress bar stop in first task.

<?php
 $grouped_records=
 [

                1=>array('a','b','c'),
                2=>array('d','e','f')

];

?>

interval

Thanks in advance.

Body:
I had refer this and tried replace for loop with an asynchronous loop that uses setTimeout(). I count current level itemlist, items_count. Since I put delay 1000 when loop in items in each level, I count delay from one level to another as items_count * 1000(if 9 items would be 9000 delay to proceed to second progressbar). This has solve my problem

<?php

$grouped_records=
[

                1=>array('a','b','c'),//level 1-first progressbar
                2=>array('d','e','f')//level 2-second progressbar

 ];

 ?>
<html>
<head>
<style>
        .progress-bar-1  .progress-bar-2
        {
            border: 1px solid black;
            background-color: #f0f0f0;
        }

        .progress-bar-1 div , .progress-bar-2 div
        {
            background-color: gray;
            height: 2.00em;
            font-size:30px;

        }

    </style>
      <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script>
        function delayedLoop(collection, delay, callback, context)
        {
            context = context || null;

            var i = 0,
            nextInteration = function()
            {
                if (i === collection.length)
                {
                    return;
                }

                callback.call(context, collection[i], i);
                i++;
                setTimeout(nextInteration, delay);
            };

            nextInteration();
        }
        Object.size = function(obj)
        {
            var size = 0, key;
            for (key in obj)
            {
                if (obj.hasOwnProperty(key)) size++;
            }
            return size;
        };

        $(document).ready(function()
        {

        var level_records       ='<?php echo json_encode($grouped_records);?>';
        level_records           =JSON.parse(level_records);
        //get object size-https://stackoverflow.com/questions/5223/length-of-a-javascript-object
        var size        =Object.size(level_records);
        //interval_array    =[1000,1000];
        /*  for(i=1;i<=size;i++)
            {
                css_class       =".progress-bar-"+i+" div";
                //delayedloop-https://stackoverflow.com/questions/30987218/update-progressbar-in-each-loop
                var progressBar = document.querySelector(css_class);
                items           =level_records[i];
                console.log(items);
                delayedLoop(items, interval_array[i], function(item, index)
                    {
                        perc                    =((index + 1) / items.length * 100);
                        perc                    =(Math.round(perc * 100) / 100).toFixed(2);
                        var width               =perc + "%";
                        progressBar.style.width =width;
                        progressBar.innerHTML   =(index + 1) + '/' + items.length + ' - ' + items[index] + ' (' + width + ')';
                    });
            }*/
            //https://stackoverflow.com/questions/17957823/javascript-how-to-update-a-progress-bar-in-a-for-loop
            var i = 1;
            (function doSort()
                {
                    // update progress
                    css_class       =".progress-bar-"+i+" div";
                    //delayedloop-https://stackoverflow.com/questions/30987218/update-progressbar-in-each-loop
                    var progressBar     =document.querySelector(css_class);
                    items               =level_records[i];
                    items_count         =level_records[i].length;
                    interval_nextlevel  =items_count*1000;//count time for next level to start and pass to setTimout()
                    console.log(items_count);
                    //console.log(items);
                    delayedLoop(items, 1000, function(item, index)
                        {
                            perc                    =((index + 1) / items.length * 100);
                            perc                    =(Math.round(perc * 100) / 100).toFixed(2);
                            var width               =perc + "%";
                            progressBar.style.width =width;
                            progressBar.innerHTML   =(index + 1) + '/' + items.length + ' - ' + items[index] + ' (' + width + ')';
                        });

                    // do stuff
                    i++;
                    if (i <= size)
                    {
                        setTimeout(doSort, interval_nextlevel);
                    }
                })();

        })

    </script>

</head>
<body>
    <div class="progress-bar-1">
        <div style="width: 0">
        </div>
    </div>
    <div>interval</div>
    <div class="progress-bar-2">
        <div style="width: 0">
        </div>
    </div>

</body>


来源: stackexchange

问:
PWA - is it possible to open a native app from a PWA?
I have a native app (requires functionality of a native app) but my site is now a PWA. Is there a way I can open my native app via a button in my PWA?</p>

答:
Yes, you can open native app via PWA.
However, there will be no data connection between your native app and PWA.

In your PWA side, you just need to execute the code below when the button is clicked.

For iOS:

```<code>document.location.href = 'your_app_schemes_url://';
</code>```

For Android:

```<code>document.location.href = 'intent:#Intent;scheme=app_scheme;package=app_package;end;';
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Yes, you can open native app via PWA.
However, there will be no data connection between your native app and PWA.

In your PWA side, you just need to execute the code below when the button is clicked.

For iOS:

document.location.href = 'your_app_schemes_url://';

For Android:

document.location.href = 'intent:#Intent;scheme=app_scheme;package=app_package;end;';


问:
How to wrap array into string in laravel
How can i wrap my return array into string in laravel?
Some thing like this

Laravel:

```<code>    $columnDefinitions = array();

    $columnDefinition = new \stdClass();
    $columnDefinition->label = "No";
    $columnDefinition->sortable = true;
    $columnDefinition->thClass = 'width-50';
    $columnDefinition->tdClass = 'text-center';
    //end add custom css
    $columnDefinitions["index_number"] = $columnDefinition;
    return $columnDefinitions;
</code>```

Expected result

```<code>'[{
   apple: {
             label: "No"
             sortable: true
             tdClass: "text-center"
          }
}]'
</code>```

答:
use this:</p>

```<code>$columnDefinition = new stdClass();
$columnDefinition->label = "No";
$columnDefinition->sortable = true;
$columnDefinition->thClass = 'width-50';
$columnDefinition->tdClass = 'text-center';

$column = new stdClass;
$column->apple = $columnDefinition;

$finalArray = [$column];
//end add custom css
return json_encode($finalArray);
</code>```

Body:
How can i wrap my return array into string in laravel?
Some thing like this

Laravel:

    $columnDefinitions = array();

    $columnDefinition = new \stdClass();
    $columnDefinition->label = "No";
    $columnDefinition->sortable = true;
    $columnDefinition->thClass = 'width-50';
    $columnDefinition->tdClass = 'text-center';
    //end add custom css
    $columnDefinitions["index_number"] = $columnDefinition;
    return $columnDefinitions;

Expected result

'[{
   apple: {
             label: "No"
             sortable: true
             tdClass: "text-center"
          }
}]'

Body:
use this:

$columnDefinition = new stdClass();
$columnDefinition->label = "No";
$columnDefinition->sortable = true;
$columnDefinition->thClass = 'width-50';
$columnDefinition->tdClass = 'text-center';

$column = new stdClass;
$column->apple = $columnDefinition;

$finalArray = [$column];
//end add custom css
return json_encode($finalArray);


问:
How to sort associative array by specific order array keys?
I'm initializing an array in my abstract class.

And I want to be sort this associative array in dynamically since the array index position has an effect when I export this as an excel sheet file.

```<code>public function setExportDetailsData() {
    $headers['barcode']            = Lang::get('core::label.barcode');
    $headers['stockNo']            = Lang::get('core::label.stock.no');
    $headers['productName']        = Lang::get('core::label.product.name');
    $headers['chineseName']        = Lang::get('core::label.chinese.name');
    $headers['category']           = Lang::get('core::label.category');
    $headers['discount2']          = Lang::get('core::label.discount.2');
    $headers['discount3']          = Lang::get('core::label.discount.3');
    $headers['discount4']          = Lang::get('core::label.discount.4');
    $headers['amount']             = Lang::get('core::label.amount');
    $headers['remarks']            = Lang::get('core::label.remarks');
}
</code>```

I need to change the order it depending on the page/module sorting.

So, example, the order of sorting for page/module 1:

```<code>$sorting = [
    'stockNo',
    'barcode',
    'chineseName',
    'productName',
    'category',
    'discount2',
    'discount3',
    'discount4',
    'amount',
    'remarks'
];
</code>```

And for other page/module has different page sorting.

I just want to sort this associative array dynamically depending on the page/module.

答:
Use array_flip to create an array that has the score for each column:

$scores = array_flip($sorting);
```

<ol start="2">
<li>Then use <code>sortBy</code> to sort by that score:</li>
</ol>

<pre class="lang-php prettyprint-override"><code>return collect($headers)->sortBy(fn ($value, $key) => $scores[$key])->all();
</code>```

Body:
I'm initializing an array in my abstract class.

And I want to be sort this associative array in dynamically since the array index position has an effect when I export this as an excel sheet file.

public function setExportDetailsData() {
    $headers['barcode']            = Lang::get('core::label.barcode');
    $headers['stockNo']            = Lang::get('core::label.stock.no');
    $headers['productName']        = Lang::get('core::label.product.name');
    $headers['chineseName']        = Lang::get('core::label.chinese.name');
    $headers['category']           = Lang::get('core::label.category');
    $headers['discount2']          = Lang::get('core::label.discount.2');
    $headers['discount3']          = Lang::get('core::label.discount.3');
    $headers['discount4']          = Lang::get('core::label.discount.4');
    $headers['amount']             = Lang::get('core::label.amount');
    $headers['remarks']            = Lang::get('core::label.remarks');
}

I need to change the order it depending on the page/module sorting.

So, example, the order of sorting for page/module 1:

$sorting = [
    'stockNo',
    'barcode',
    'chineseName',
    'productName',
    'category',
    'discount2',
    'discount3',
    'discount4',
    'amount',
    'remarks'
];

And for other page/module has different page sorting.

I just want to sort this associative array dynamically depending on the page/module.

Body:
Use array_flip to create an array that has the score for each column:

$scores = array_flip($sorting);

Then use sortBy to sort by that score:

return collect($headers)->sortBy(fn ($value, $key) => $scores[$key])->all();


问:
ValueError: could not convert string to float: '' in Python 3
I'm coding a little bot in Python and I'm having a problem. It seems to be a common problem, but I've never seen it asked in the same situation I'm in.

Ok so here is the code posing problem:

```<code>old_values = float((removeprc(browser.find_element_by_xpath('//*[@id="draggableNavRightResizable"]/section/section[2]/section[1]/div[3]/ul/li[1]/div[2]/div[6]/span').text)))
</code>```

browser.find_element_by_xpath('//*[@id="draggableNavRightResizable"]/section/section[2]/section[1]/div[3]/ul/li[1]/div[2]/div[6]/span').text) is a selenium tool used to get a value of a website. as you will see later, the element retrieved is a number which should work with float()
"remove prc" is a little function I created to remove the % of a number, here it is:

```<code>def removeprc(string): #removes the % from a string
    string = str(string)
    list = string.split('%')
    string = " ".join(list)

    return string
</code>```

It's probably not the best way to do it, but it works when I test it alone.

anyway, here is what I get when I run my entire code

```<code>loading page ...
page loaded
acquiring values ...
values acquired
running eth trade
-0.37
Traceback (most recent call last):
  File "C:\Users\pc adam\Documents\EISTI\algoprog\perso\python\fichiers\btc\ETHtradingbotV1.py", line 138, in <module>
    profit = float(browser.find_element_by_xpath('/html/body/div[3]/section[16]/section[2]/section[2]/section[2]/div/div[1]/table/tbody/tr/td[15]/span').text)
ValueError: could not convert string to float: ''
</code>```

the first 5 lines are useless. on the 6th line, I printed what i am trying to get the float()
of. As you can see, it should work and ... It does ! sometimes.

that's the weirdest thing about this, it works perfectly half the time!
I've read on the internet that this can happen if you try to float() things that are not numbers or that have weird shit in them, like spaces. As you can see, I think it's not the case here.

When I try to isolate the problem by running a simplified version of the program like this :

```<code>a = "-0.06%"
def removeprc(string): #removes the % from a string
    string = str(string)
    list = string.split('%')
    string = " ".join(list)
    return string

b = float(removeprc(a))
print(b)
</code>```

it outputs -0.06 and works perfectly ???

So I'm really stuck here. It should work, but it doesn't. Even worst, it works sometimes, for no reason. And when I isolate the problem, it works fine.

Any help would be extremely appreciated!

Oh and if you want to see the entire code, it's here: https://github.com/Madaxuorel/proj-ethTB/blob/master/ETHtradingbotV1.py

答:
You have used the keyword as a variable here. That's why sometimes it doesn't work I guess.
Like str(), list() is a method to convert a variable into a list. Try to rename the variable like below, I guess.</p>

```<code>def removeprc(string): #removes the % from a string
    string = str(string)
    l = string.split('%')
    string = " ".join(l)
    return string
</code>```

Body:
I'm coding a little bot in Python and I'm having a problem. It seems to be a common problem, but I've never seen it asked in the same situation I'm in.

Ok so here is the code posing problem:

old_values = float((removeprc(browser.find_element_by_xpath('//*[@id="draggableNavRightResizable"]/section/section[2]/section[1]/div[3]/ul/li[1]/div[2]/div[6]/span').text)))

browser.find_element_by_xpath('//*[@id="draggableNavRightResizable"]/section/section[2]/section[1]/div[3]/ul/li[1]/div[2]/div[6]/span').text) is a selenium tool used to get a value of a website. as you will see later, the element retrieved is a number which should work with float()
"remove prc" is a little function I created to remove the % of a number, here it is:

def removeprc(string): #removes the % from a string
    string = str(string)
    list = string.split('%')
    string = " ".join(list)

    return string

It's probably not the best way to do it, but it works when I test it alone.

anyway, here is what I get when I run my entire code

loading page ...
page loaded
acquiring values ...
values acquired
running eth trade
-0.37
Traceback (most recent call last):
  File "C:\Users\pc adam\Documents\EISTI\algoprog\perso\python\fichiers\btc\ETHtradingbotV1.py", line 138, in <module>
    profit = float(browser.find_element_by_xpath('/html/body/div[3]/section[16]/section[2]/section[2]/section[2]/div/div[1]/table/tbody/tr/td[15]/span').text)
ValueError: could not convert string to float: ''

the first 5 lines are useless. on the 6th line, I printed what i am trying to get the float()
of. As you can see, it should work and ... It does ! sometimes.

that's the weirdest thing about this, it works perfectly half the time!
I've read on the internet that this can happen if you try to float() things that are not numbers or that have weird shit in them, like spaces. As you can see, I think it's not the case here.

When I try to isolate the problem by running a simplified version of the program like this :

a = "-0.06%"
def removeprc(string): #removes the % from a string
    string = str(string)
    list = string.split('%')
    string = " ".join(list)
    return string

b = float(removeprc(a))
print(b)

it outputs -0.06 and works perfectly ???

So I'm really stuck here. It should work, but it doesn't. Even worst, it works sometimes, for no reason. And when I isolate the problem, it works fine.

Any help would be extremely appreciated!

Oh and if you want to see the entire code, it's here: https://github.com/Madaxuorel/proj-ethTB/blob/master/ETHtradingbotV1.py

Body:
You have used the keyword as a variable here. That's why sometimes it doesn't work I guess.
Like str(), list() is a method to convert a variable into a list. Try to rename the variable like below, I guess.

def removeprc(string): #removes the % from a string
    string = str(string)
    l = string.split('%')
    string = " ".join(l)
    return string


问:
param is not taking %2B
In my Karate Script, I am giving param input = '%2B61293744000'. I have used %2B for encoding + as it is a phone number with country code.
Now the URL that is formed is taking input as input=%252B61293744000 , which means that the % itself has been taken as %25
Any idea how to handle this?</p>

答:
Figured out that in Karate if i directly give  param input = '+61293744000' this is working fine, and url is formed as %2B which is correct
So no need to encode it in parameter.</p>

Title: param is not taking %2B


问:
PM2 log: Launching in no daemon mode
I tried to use docker to run graphql server in no daemon mode, but was getting bellow error:

```<code>docker run graphql-server

2020-01-29T22:08:31: PM2 log: Launching in no daemon mode
2020-01-29T22:08:31: PM2 error: Script not found: /usr/src/app/run
2020-01-29T22:08:31: PM2 log: PM2 successfully stopped
</code>```

Here are the files i was using:

The Dockerfile

```<code>FROM keymetrics/pm2:10-alpine

WORKDIR /usr/src/app
COPY package*.json ./
COPY .env ./
RUN apk add --no-cache curl && npm install --production
COPY . .
ENV NODE_ENV production
EXPOSE 5000
CMD [ "pm2-runtime", "run", "dev", "ecosystem.config.js" ]
</code>```

ecosystem.config.js

```<code>    module.exports = {
    apps : [{
      name: 'graphql-server',
      script: './index.js',

      autorestart: true,

      env: {
      },
      env_production: {
      }
    }],
  };
</code>```

package.json

```<code>"scripts": {
    "start": "node index.js",
    "dev": "nodemon index.js --ext js --exec babel-node",
    "lint": "standard",
    "lint:fix": "standard --fix"
  }
</code>```

What's the reason i was having this error?

答:
Are you using Windows ?
If you are, what is your windows docker desktop version ?
I am using windows and my windows docker desktop version is 2.2.0.3 .
And I have almost the same DockerFile as your, and I have the same problem.
After I Changed to use ubuntu 16.04 /18.04, it worked.
At now trying to windows docker desktop  2.1.0.5 ...</p>

Title: PM2 log: Launching in no daemon mode

Body:
I tried to use docker to run graphql server in no daemon mode, but was getting bellow error:

docker run graphql-server

2020-01-29T22:08:31: PM2 log: Launching in no daemon mode
2020-01-29T22:08:31: PM2 error: Script not found: /usr/src/app/run
2020-01-29T22:08:31: PM2 log: PM2 successfully stopped

Here are the files i was using:

The Dockerfile

FROM keymetrics/pm2:10-alpine

WORKDIR /usr/src/app
COPY package*.json ./
COPY .env ./
RUN apk add --no-cache curl && npm install --production
COPY . .
ENV NODE_ENV production
EXPOSE 5000
CMD [ "pm2-runtime", "run", "dev", "ecosystem.config.js" ]

ecosystem.config.js

    module.exports = {
    apps : [{
      name: 'graphql-server',
      script: './index.js',

      autorestart: true,

      env: {
      },
      env_production: {
      }
    }],
  };

package.json

"scripts": {
    "start": "node index.js",
    "dev": "nodemon index.js --ext js --exec babel-node",
    "lint": "standard",
    "lint:fix": "standard --fix"
  }

What's the reason i was having this error?


问:
How to do "call by reference" in Java?

How to do "call by reference" in Java?  (Assume that we are using that term in the same way that it has been used in peer-reviewed CS literature since the 1960's; see this Wikipedia page for a simple explanation.)

Since Java doesn't support pointers, how is it possible to call a function by reference in Java like we do in C and C++??

答:
How to do call by reference in Java?

You cannot do call by reference in Java.  Period.  Nothing even comes close.  And passing a reference by value is NOT the same as call by reference.

(Real "call by reference" allows you to do this kind of thing:

```<code>void swap(ref int i, ref int j) { int tmp = *i; *i = *j; *j = tmp }

int a = 1;
int b = 2;
swap(a, b);
print("a is %s, b is %s\n", a, b);  // -> "a = 2, b = 1"
</code>```

You simply can't do that in Java.)

Since Java doesn't support pointers ...

While this is technically true, it would not be an impediment to what you are trying to do.

Java does support references, which are like pointers in the most important respects.  The difference is that you can't treat references as memory addresses by doing arithmetic on them, converting them to and from integer types and so on.  And you can't create a reference to a variable because the concept does not exist in Java or the JVM architecture.

How is it possible to call a function by reference in Java like we do in C and C++??

Important note: this is NOT "call by reference".  It is "call by value" using a reference to a function1.

Prior to Java 8, references to functions were not supported as values.  So you could not pass them as arguments, and you cannot assign them to variables.

However, you can define a class with one instance method, and use an instance of the class instead of a function reference.  Other Answers give examples of this approach.

From Java 8 onwards, method references are supported using :: syntax.  There are 4 kinds of method reference:

Reference to a static method: ContainingClass::staticMethodName

Reference to an instance method of a particular object:     containingObject::instanceMethodName

Reference to an instance method of an arbitrary object of a particular type: ContainingType::methodName

Reference to a constructor: ClassName::new

1 - From a pedagogical perspective, it is unfortunate that C and C++ use the & symbol for both call-by-reference and for denoting function pointers.  However, from a language design perspective, I don't disagree with that design choice.

Title: How to do "call by reference" in Java?

Body:
How to do call by reference in Java?

You cannot do call by reference in Java.  Period.  Nothing even comes close.  And passing a reference by value is NOT the same as call by reference.

(Real "call by reference" allows you to do this kind of thing:

void swap(ref int i, ref int j) { int tmp = *i; *i = *j; *j = tmp }

int a = 1;
int b = 2;
swap(a, b);
print("a is %s, b is %s\n", a, b);  // -> "a = 2, b = 1"

You simply can't do that in Java.)

Since Java doesn't support pointers ...

While this is technically true, it would not be an impediment to what you are trying to do.

Java does support references, which are like pointers in the most important respects.  The difference is that you can't treat references as memory addresses by doing arithmetic on them, converting them to and from integer types and so on.  And you can't create a reference to a variable because the concept does not exist in Java or the JVM architecture.

How is it possible to call a function by reference in Java like we do in C and C++??

Important note: this is NOT "call by reference".  It is "call by value" using a reference to a function1.

Prior to Java 8, references to functions were not supported as values.  So you could not pass them as arguments, and you cannot assign them to variables.

However, you can define a class with one instance method, and use an instance of the class instead of a function reference.  Other Answers give examples of this approach.

From Java 8 onwards, method references are supported using :: syntax.  There are 4 kinds of method reference:

Reference to a static method: ContainingClass::staticMethodName

Reference to an instance method of a particular object:     containingObject::instanceMethodName

Reference to an instance method of an arbitrary object of a particular type: ContainingType::methodName

Reference to a constructor: ClassName::new

1 - From a pedagogical perspective, it is unfortunate that C and C++ use the & symbol for both call-by-reference and for denoting function pointers.  However, from a language design perspective, I don't disagree with that design choice.


问:
Two sets of curly braces using lambda functions?
I am wondering if someone could help me understand the following syntax snippet, specifically sections 1 and 2 (focusing on the two sets of curly brackets). Is it related to lamda function? If so, how?</p>

```<code>void Logger::LogContentionAndAllocations() {
    // 1
    LogDetail([&](AsyncDetail& detail) {
        {
            std::unique_lock<std::mutex> lock(tls_loggers_registerd_mutex_);
            for (auto tls_logger : tls_loggers_registerd_) {
                CollectTlsLoggerStats(tls_logger);
            }
        }
        //2.
        {
            std::unique_lock<std::mutex> lock(tls_logger_orphans_mutex_);
            for (auto& orphan : tls_logger_orphans_) {
                CollectTlsLoggerStats(orphan.get());
            }
        }

        detail("Log Contention Counters:");
        detail(std::to_string(swap_request_slots_retry_count_) + " : swap_request_slots_retry_count");
        detail(std::to_string(swap_request_slots_retry_retry_count_) + " : swap_request_slots_retry_retry_count");
        detail(std::to_string(swap_request_slots_retry_reencounter_count_) + " : swap_request_slots_retry_reencounter_count");
        detail(std::to_string(start_reading_entries_retry_count_) + " : start_reading_entries_retry_count");
        detail(std::to_string(tls_total_log_cas_fail_count_) + " : tls_total_log_cas_fail_count");
        detail(std::to_string(tls_total_swap_buffers_slot_retry_count_) + " : tls_total_swap_buffers_slot_retry_count");

        swap_request_slots_retry_count_ = 0;
        swap_request_slots_retry_retry_count_ = 0;

        swap_request_slots_retry_reencounter_count_ = 0;
        start_reading_entries_retry_count_ = 0;
        tls_total_log_cas_fail_count_ = 0;

        tls_total_swap_buffers_slot_retry_count_ = 0;
    });
}
</code>```

答:
The extra curly braces are simply being used to create additional scope blocks to limit the lifetime of the std::unique_lock objects.  The objects are destructed, releasing their locks, when they go out of scope.

```<code>[&](AsyncDetail& detail) {
    { // <-- new scope created here
        std::unique_lock<std::mutex> lock(tls_loggers_registerd_mutex_);
        for (auto tls_logger : tls_loggers_registerd_) {
            CollectTlsLoggerStats(tls_logger);
        }
    } // <-- lock destroyed here
    //2.
    { // <-- new scope created here
        std::unique_lock<std::mutex> lock(tls_logger_orphans_mutex_);
        for (auto& orphan : tls_logger_orphans_) {
            CollectTlsLoggerStats(orphan.get());
        }
    } // <-- lock destroyed here

    ...
}
</code>```

This is no different than the curly braces used for function bodies, if statements, loops, etc. Curly braces can be used to create new scopes, and scopes can be nested.

Body:
I am wondering if someone could help me understand the following syntax snippet, specifically sections 1 and 2 (focusing on the two sets of curly brackets). Is it related to lamda function? If so, how?

void Logger::LogContentionAndAllocations() {
    // 1
    LogDetail([&](AsyncDetail& detail) {
        {
            std::unique_lock<std::mutex> lock(tls_loggers_registerd_mutex_);
            for (auto tls_logger : tls_loggers_registerd_) {
                CollectTlsLoggerStats(tls_logger);
            }
        }
        //2.
        {
            std::unique_lock<std::mutex> lock(tls_logger_orphans_mutex_);
            for (auto& orphan : tls_logger_orphans_) {
                CollectTlsLoggerStats(orphan.get());
            }
        }

        detail("Log Contention Counters:");
        detail(std::to_string(swap_request_slots_retry_count_) + " : swap_request_slots_retry_count");
        detail(std::to_string(swap_request_slots_retry_retry_count_) + " : swap_request_slots_retry_retry_count");
        detail(std::to_string(swap_request_slots_retry_reencounter_count_) + " : swap_request_slots_retry_reencounter_count");
        detail(std::to_string(start_reading_entries_retry_count_) + " : start_reading_entries_retry_count");
        detail(std::to_string(tls_total_log_cas_fail_count_) + " : tls_total_log_cas_fail_count");
        detail(std::to_string(tls_total_swap_buffers_slot_retry_count_) + " : tls_total_swap_buffers_slot_retry_count");

        swap_request_slots_retry_count_ = 0;
        swap_request_slots_retry_retry_count_ = 0;

        swap_request_slots_retry_reencounter_count_ = 0;
        start_reading_entries_retry_count_ = 0;
        tls_total_log_cas_fail_count_ = 0;

        tls_total_swap_buffers_slot_retry_count_ = 0;
    });
}

Body:
The extra curly braces are simply being used to create additional scope blocks to limit the lifetime of the std::unique_lock objects.  The objects are destructed, releasing their locks, when they go out of scope.

[&](AsyncDetail& detail) {
    { // <-- new scope created here
        std::unique_lock<std::mutex> lock(tls_loggers_registerd_mutex_);
        for (auto tls_logger : tls_loggers_registerd_) {
            CollectTlsLoggerStats(tls_logger);
        }
    } // <-- lock destroyed here
    //2.
    { // <-- new scope created here
        std::unique_lock<std::mutex> lock(tls_logger_orphans_mutex_);
        for (auto& orphan : tls_logger_orphans_) {
            CollectTlsLoggerStats(orphan.get());
        }
    } // <-- lock destroyed here

    ...
}

This is no different than the curly braces used for function bodies, if statements, loops, etc. Curly braces can be used to create new scopes, and scopes can be nested.


问:
Summernote does not change the content correctly in Angular 8
I am trying to edit a summernote text in Angular 8. The issue is, on first selection of a post to edit, I actually see the post content in the summernote inside my modal. But when, I close the modal and select another post to edit, the content in the summernote does not change at all. Please see my code below on how I implement it.

Component

  // I select the post and the details is extracted from the backend and the data is placed on the corresponding form control

    onSelectPost(id: string) {
        $('#summernote').summernote('destroy');
        this.pService.getPostByIdToEdit(id).subscribe((data: PostToEdit) => {
          this.postToEdit = data;
          $('#summernote').summernote({
            height: 450,
            width: 1000,
            tooltip: false,
            toolbar: [
              ['style', ['style']],
              ['font', ['bold', 'underline', 'clear']],
              ['fontname', ['fontname']],
              ['color', ['color']],
              ['para', ['ul', 'ol', 'paragraph']],
              ['table', ['table']],
              ['insert', ['link', 'picture', 'video']]
            ],
          });
          this.createForm();
        });
    }
```
<p><strong>Html</strong></p>
<p>// This is the button I click to show the modal</p>
<pre class="lang-html prettyprint-override"><code>    <button
        type="button"
        mdbBtn
        color="info"
        class="btn btn-sm"
        rounded="true"
        data-toggle="modal"
        data-target="#basicExample"
        (click)="frame.show(); onSelectPost(el.id);"
        mdbWavesEffect
    >

<!--This is the modal-->

    <div
      mdbModal
      #frame="mdbModal"
      class="modal fade top"
      id="frameModalTop"
      tabindex="-1"
      role="dialog"
      aria-labelledby="myModalLabel"
      aria-hidden="true"
    >
      <div
        class="modal-dialog modal-notify modal-info modal-xl"
        role="document"
        *ngIf="postToEdit"
      >
        <!--Content-->
        <div class="modal-content">
          <!--Header-->
          <div class="modal-header">
            <p class="heading lead">
              Title:
              <span style="font-weight: bolder;">{{ postToEdit.title }}</span>
            </p>

            <button
              type="button"
              class="close"
              data-dismiss="modal"
              aria-label="Close"
              (click)="frame.hide()"
            >
              <span aria-hidden="true" class="white-text">×</span>
            </button>
          </div>

          <!--Body-->
          <div class="modal-body">
            <div class="col-md-12">
              <form [formGroup]="form" #fd="ngForm">
                <mdb-card class="card-size">
                  <mdb-card-body>
                    <div class="col-md-12">
                      <div class="row mb-1">
                        <input
                          id="post_title"
                          type="text"
                          formControlName="title"
                          placeholder="Title"
                          class="form-control"
                          [ngClass]="{ 'is-invalid': submitted && f.title.errors }"
                        />
                        <div
                          *ngIf="submitted && f.title.errors"
                          class="invalid-feedback"
                        >
                          <div *ngIf="f.title.errors.required">
                            Title is required
                          </div>
                        </div>
                      </div>
                      <div class="row mb-1">
                        <select class="form-control" formControlName="categoryId">
                          <option selected disabled>Select Categories</option>
                          <option
                            *ngFor="let item of categories"
                            [value]="item.id"
                            >{{ item.categoryName }}</option
                          >
                        </select>
                      </div>
                    </div>
                  </mdb-card-body>
                </mdb-card>
              </form>
              <div class="row mb-1 mt-3 ml-lg-4 ml-md-4 ml-sm-auto">
                <div id="summernote" [innerHtml]="postToEdit.postContent" class="sumnote"></div> <======= I get the post content the first time but it does not change
                                                                                on another selection
              </div>
            </div>

            <!--Footer-->
            <div class="modal-footer justify-content-center">
              <a
                type="button"
                mdbBtn
                color="danger"
                class="waves-effect"
                mdbWavesEffect
                >Edit
                <mdb-icon far icon="check" class="ml-1"></mdb-icon>
              </a>
              <a
                type="button"
                mdbBtn
                color="danger"
                outline="true"
                class="waves-effect"
                mdbWavesEffect
                (click)="frame.hide(); onCancel();"
                >Cancel</a
              >
            </div>
          </div>
          <!--/.Content-->
        </div>
      </div>
    </div>
</code>```

答: I found out that you have to reinitialize the summernote since it was created after the DOM. Also, I placed the summernote inside the forms and used textarea instead of div.</p>

Body:
I am trying to edit a summernote text in Angular 8. The issue is, on first selection of a post to edit, I actually see the post content in the summernote inside my modal. But when, I close the modal and select another post to edit, the content in the summernote does not change at all. Please see my code below on how I implement it.

Component

  // I select the post and the details is extracted from the backend and the data is placed on the corresponding form control

    onSelectPost(id: string) {
        $('#summernote').summernote('destroy');
        this.pService.getPostByIdToEdit(id).subscribe((data: PostToEdit) => {
          this.postToEdit = data;
          $('#summernote').summernote({
            height: 450,
            width: 1000,
            tooltip: false,
            toolbar: [
              ['style', ['style']],
              ['font', ['bold', 'underline', 'clear']],
              ['fontname', ['fontname']],
              ['color', ['color']],
              ['para', ['ul', 'ol', 'paragraph']],
              ['table', ['table']],
              ['insert', ['link', 'picture', 'video']]
            ],
          });
          this.createForm();
        });
    }

Html

// This is the button I click to show the modal

    <button
        type="button"
        mdbBtn
        color="info"
        class="btn btn-sm"
        rounded="true"
        data-toggle="modal"
        data-target="#basicExample"
        (click)="frame.show(); onSelectPost(el.id);"
        mdbWavesEffect
    >

              Title:
              {{ postToEdit.title }}

            <button
              type="button"
              class="close"
              data-dismiss="modal"
              aria-label="Close"
              (click)="frame.hide()"
            >
              ×
            </button>

              <form [formGroup]="form" #fd="ngForm">
                <mdb-card class="card-size">
                  <mdb-card-body>

                        <input
                          id="post_title"
                          type="text"
                          formControlName="title"
                          placeholder="Title"
                          class="form-control"
                          [ngClass]="{ 'is-invalid': submitted && f.title.errors }"
                        />

                            Title is required

                        <select class="form-control" formControlName="categoryId">
                          <option selected disabled>Select Categories</option>
                          <option
                            *ngFor="let item of categories"
                            [value]="item.id"
                            >{{ item.categoryName }}</option
                          >
                        </select>

                  </mdb-card-body>
                </mdb-card>
              </form>

 <======= I get the post content the first time but it does not change
                                                                                on another selection

              Edit
                <mdb-icon far icon="check" class="ml-1"></mdb-icon>

              Cancel


问:
Rpi3 BMP180 Barometer Sensor Interface Problem
im currently working on a Barometer sensor on my Raspberry Pi 3.
Unfortunately its not really working. My BMP180 Sensor is wired up as following:

```<code>VIN -> 3V3 (1)
GND -> GND (9)
SCL -> GPIO3 (5)
SDA -> GPIO2 (3)
</code>```

The cables and connections were double checked and replaced a few times so those are not the problem. I also enabled I2C in raspi-config. If I type in i2cdetect -y 1 i get something like this, so no connections are detected:

```<code>     0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f
00:          -- -- -- -- -- -- -- -- -- -- -- -- --
10: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
20: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
30: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
40: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
50: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
60: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
70: -- -- -- -- -- -- -- --
</code>```

If I let an example/test code from Adafruit run when everything is connected properly and checked (~/BMP180Code/Adafruit_Python_BMP/examplessimpletest.py) I get an output like that:

```<code>Traceback (most recent call last):
    File "simpletest.py", line 37, in <module>
        sensor = BMP085.BMP085()
    File "build/bdist.linux-armv7l/egg/Adafruit_BMP/BMP085.py", line 69, in __init__
    File "build/bdist.linux-armv7l/egg/Adafruit_BMP/BMP085.py", line 72, in _load_calibration
    File "build/bdist.linux-armv7l/egg/Adafruit_GPIO/I2C.py", line 202, in readS16BE
    File "build/bdist.linux-armv7l/egg/Adafruit_GPIO/I2C.py", line 179, in readS16
    File "build/bdist.linux-armv7l/egg/Adafruit_GPIO/I2C.py", line 166, in readU16
    File "build/bdist.linux-armv7l/egg/Adafruit_PureIO/smbus.py", line 187, in read_word_data
IOError: [Errno 110] Connection timed out
</code>```

I looked up a few solutions online, but nothing helped.
I would be happy if someone of you has a solution for that.
Thanks and have a good day, Leo

答:
Answer (v0.5 Last update 2020feb19gmt1914 Appendix F)

Let me see. I assume you are using the following outdated python program.  Please let me know otherwise.

(1) Adafruit /Adafruit_Python_BMP Archived (2014)

I found that following comments in lines 27~40 useful for debugging:

```<code># For the Raspberry Pi this means you should hook up to the only exposed I2C bus
# from the main GPIO header and the library will figure out the bus number based
# on the Pi's revision.
# Optionally you can override the bus number:
# sensor = BMP085.BMP085(busnum=2)
</code>```

Comments

(1) Old Rpi (2014) might use I2C0 instead of I2C1, the auto detect funtion might not be able to know Rpi3/4 and pick the wrong number not 1, but 0 or 2 (2 for BeagleBone perhaps)

(2) The python program is for BMP085 but you are using BMP180. You might like to check out any imcompatibilities and make necessary modifcations to the config functions.

(3) The error message is

```<code>"File "build/bdist.linux-armv7l/egg/Adafruit_PureIO/smbus.py", line 187, in read_word_data, IOError: [Errno 110] Connection timed out"
</code>```

Your "i2cdetec -y 1" shows no I2C device is detected, it may mean

(a) Hardware wiring is not correct (OK, so your have double checked wiring (open/short all point to point, neighbouring points etc) or

(b) Software problem such as (i) Wrong config, (ii) Wrong software library.

Either way, you might get the above "Time out, cannot connect" error message.

Troubleshooting Suggestions

(1) You may like to try and error modify the relevant bus number in the program, say

change default I2C bus number from 2 to 1.

(2) To make sure the hardware wiring, and software drivers etc are OK, (a) Remove the no detect BMP guy, (b) swap in any other I2C guy and "i2cdetect - y 1" again. If the new guy can be happily detected, then obviously the old guy is bad :(

Discussion and Recommendation

The AdaFruit BMP180 Library the OP uses is depreciated and no longer
supported.

I would suggest the OP to switch to

AdaFruit BMP280/BME280 CircuitPython Library

or

Pimoroni BMP280/BME280 Python Library

.

References

(1) Adafruit_2014 BMP085/BMP180 Python Library (Depreciated, No Longer Supported)

(2) BMP085 Datashet v2.5- Bosch 2009

(3) BMP180 Datasheet - Bosch 2009

(4) BMP280 Digital Pressure Sensor Datasheet v1.14 Bosch 2015

(5) BME280 Combined Humidity and Pressure Sensor Datasheet v.16 - Bosch 2018sep

(6) What's the difference between the BMP280 and the BME280 atmospheric sensors - 20,565 views 2017mar02

(7) UM10204 I2C-bus specification and user manual (referred in BMP180 Datasheet Section 5, Max clock = 3.4MHz) - 2014 NXP

(8) Adafruit BMP280 I2C or SPI Barometric Pressure & Altitude Sensor - US$10

(9) BMP280 Temperature, Pressure, & Altitude Sensor Python Library - Pimoroni 2019nov08

(10) BMP280 Pip Install - PyPi

Appendices

Appendix A - I2C wiring and Pull up resistors etc

(1) You should be using the only two I2C Clock and Data pins in the Rpi 40 pin header.

(2) The the two pins already have strong enough 1k8 pull up. There is no need to add more pull up resistor, with the risk of too strong pull up.

(3) Actually if you are putting too many I2C devices, say, more than 4, on the same bus, and the other devices have 4k7 or 10k pullups, the resultant pull up might be much less than 1k8, and overload the I2C pin current. I usually REMOVE those on device pullups to not to overload the Rpi I2C pins.

(4) Remove all other I2C devices on the same bus, for reason (3) above.

(5) Your hardware I2C connection wires CANNOT be too long, preferably less than 30cm.  Longer than that might result in too high impedance (For I2C, 400pf is the usual limit).

Appendix B - Difference between BMP085 and BMP180

I skim both datasheets to compare and contrast. My quick and dirty conclusion: (a) BMP180 is successor of BMP085, (b) They are functionally the same, meaning that software programming should be the "same".

Usually industry practice is that new hardware version is backward compatible, ie, BMP085 program can run for BMP180, but not vice versa. WARNING: I am just a friendly hobbyist. No guarantee No nothing won't melt down or blow up! Follow the hobbyist's suggestion at your own risk! :)

Appendix D - Suggestion to modify AdaFruit BMP180 Program for Rpi3/4

The main test program is actually very short.

The critical setup problem is the I2C bus number.

The program's default is I2C Bus #2. I would suggest to change default
to I2c Bus #1.

```<code># AdaFruit BMP180 Program Author: Tony DiCola
# https://github.com/adafruit/Adafruit_Python_BMP/blob/master/examples/simpletest.py
import Adafruit_BMP.BMP085 as BMP085
# Default constructor will pick a default I2C bus.
# For the Raspberry Pi this means you should hook up to the only exposed I2C bus
# from the main GPIO header and the library will figure out the bus number based
# on the Pi's revision.
sensor = BMP085.BMP085()
# Optionally you can override the bus number:
# sensor = BMP085.BMP085(busnum=2)
print('Temp = {0:0.2f} *C'.format(sensor.read_temperature()))
print('Pressure = {0:0.2f} Pa'.format(sensor.read_pressure()))
print('Altitude = {0:0.2f} m'.format(sensor.read_altitude()))
print('Sealevel Pressure = {0:0.2f} Pa'.format(sensor.read_sealevel_pressure()))
</code>```

Next is to update the class bmp085.  See next Appendix E below.

Appendix E - AdaFruit BMP085 Library BMP085 Class using Eazy Steup - Tony DiCola for Adafruit

The following notice from the AdaFruit BMP085 library says the library is depreciated. AdaFruit recommends:

(a) switch to AdaFruit CircuitPython sensor library (Note 1),

(b) Switch to BMP280.

Now we have a problem. This old library uses AdaFruit EasySetup tools which are no longer supported and might be incompatible to Raspberry Pi

Note 1 - Circuit Python is not 100% compatible to Raspberry Pi operating system Raspbian 10 buster.

```<code>DEPRECATED LIBRARY Adafruit Python BMP This library has been deprecated!
https://github.com/adafruit/Adafruit_Python_BMP/blob/master/README.md
the bmp085 and bmp180 are no longer made, and are replaced by the bmp280
we are now only using our circuitpython sensor libraries in python
we are leaving the code up for historical/research purposes but archiving the repository.
check out this guide for using the bmp280 with python! https://learn.adafruit.com/adafruit-bmp280-barometric-pressure-plus-temperature-sensor-breakout
Adafruit Python BMP
Python library for accessing the BMP series pressure and temperature sensors like the BMP085/BMP180 on a Raspberry Pi or Beaglebone Black.
Designed specifically to work with the Adafruit BMP085/BMP180 pressure sensors ----> https://www.adafruit.com/products/1603
To install, download the library by clicking the download zip link to the right and unzip the archive somewhere on your Raspberry Pi or Beaglebone Black. Then execute the following command in the directory of the library:~~
sudo python setup.py install
Make sure you have internet access on the device so it can download the required dependencies.
</code>```

Appendix F - BME280 Learning Notes

I have been playing with Gyrometer, Accelerometer, and Magnetometer, but never Pressure meter. I also played with Temperature and Humidity sensors, but never Pressure Sensor, because I always thing that Pressure or Altitude sensor is only for mountain climbers, not for my hobby home automation.  But after studying the OP's question, I found that there is a new sensor with three measurements in one chip, Temperature, Humidity, and Pressure. I also found that though the OP's AdaFruit BMP085 and even BMP180 Library is depreciated, there is actually another new successor BMP280 and BME280.  I also found that Pimoroni seems has joined force with Lada Ada, sell her BEM280 breakout board, and at the same created a library. I am hoping that Pimoroni's python library is NOT CircuitPython, but standard Python.

I am reading Pimoroni's product and writing up some learning notes for future reference:

/ to continue, ...

Update 2022sep17 hkt1258

Appendix G - Pico W testing BME680

1. Introduction

Now I am setting up a Rpi Pico W prototyping board for testing BME680.

2. References

References

(1) Rpi Pico

(1.1) Rpi Pico W Datasheet – Rpi 2022jun29
https://datasheets.raspberrypi.com/picow/pico-w-datasheet.pdf

(1.2) Rpi Pico W Pinout Diagram
https://datasheets.raspberrypi.com/picow/PicoW-A4-Pinout.pdf

(1.3) Rpi Pico W Schematic – Appenix B – Pico Datasheet
https://www.etechnophiles.com/wp-content/uploads/2022/07/Pico-W-Schematic.pdf

(1.4) New Pi Pico W- WiFi Features, Specs & Pinout Simplified – etechnophiles
https://www.etechnophiles.com/raspberry-pi-pico-w-wifi-specs-pinout/

(2) BME680

(2.1)

(3) Schottky Diode References

I surveyed Schottky diodes and found 1N5822 good (only 0.4V drop at 1A).

https://forums.raspberrypi.com/viewtopic.php?p=1417588&hilit=schottky+diode+tlfong01#p1417588

1N5408 Datasheet - Vishay
https://www.vishay.com/docs/88516/1n5400.pdf

/ to continue, ...

End of answer

Body:
im currently working on a Barometer sensor on my Raspberry Pi 3.
Unfortunately its not really working. My BMP180 Sensor is wired up as following:

VIN -> 3V3 (1)
GND -> GND (9)
SCL -> GPIO3 (5)
SDA -> GPIO2 (3)

The cables and connections were double checked and replaced a few times so those are not the problem. I also enabled I2C in raspi-config. If I type in i2cdetect -y 1 i get something like this, so no connections are detected:

     0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f
00:          -- -- -- -- -- -- -- -- -- -- -- -- --
10: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
20: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
30: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
40: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
50: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
60: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
70: -- -- -- -- -- -- -- --

If I let an example/test code from Adafruit run when everything is connected properly and checked (~/BMP180Code/Adafruit_Python_BMP/examplessimpletest.py) I get an output like that:

Traceback (most recent call last):
    File "simpletest.py", line 37, in <module>
        sensor = BMP085.BMP085()
    File "build/bdist.linux-armv7l/egg/Adafruit_BMP/BMP085.py", line 69, in __init__
    File "build/bdist.linux-armv7l/egg/Adafruit_BMP/BMP085.py", line 72, in _load_calibration
    File "build/bdist.linux-armv7l/egg/Adafruit_GPIO/I2C.py", line 202, in readS16BE
    File "build/bdist.linux-armv7l/egg/Adafruit_GPIO/I2C.py", line 179, in readS16
    File "build/bdist.linux-armv7l/egg/Adafruit_GPIO/I2C.py", line 166, in readU16
    File "build/bdist.linux-armv7l/egg/Adafruit_PureIO/smbus.py", line 187, in read_word_data
IOError: [Errno 110] Connection timed out

I looked up a few solutions online, but nothing helped.
I would be happy if someone of you has a solution for that.
Thanks and have a good day, Leo

Body:
Answer (v0.5 Last update 2020feb19gmt1914 Appendix F)

Let me see. I assume you are using the following outdated python program.  Please let me know otherwise.

(1) Adafruit /Adafruit_Python_BMP Archived (2014)

I found that following comments in lines 27~40 useful for debugging:

# For the Raspberry Pi this means you should hook up to the only exposed I2C bus
# from the main GPIO header and the library will figure out the bus number based
# on the Pi's revision.
# Optionally you can override the bus number:
# sensor = BMP085.BMP085(busnum=2)

Comments

(1) Old Rpi (2014) might use I2C0 instead of I2C1, the auto detect funtion might not be able to know Rpi3/4 and pick the wrong number not 1, but 0 or 2 (2 for BeagleBone perhaps)

(2) The python program is for BMP085 but you are using BMP180. You might like to check out any imcompatibilities and make necessary modifcations to the config functions.

(3) The error message is

"File "build/bdist.linux-armv7l/egg/Adafruit_PureIO/smbus.py", line 187, in read_word_data, IOError: [Errno 110] Connection timed out"

Your "i2cdetec -y 1" shows no I2C device is detected, it may mean

(a) Hardware wiring is not correct (OK, so your have double checked wiring (open/short all point to point, neighbouring points etc) or

(b) Software problem such as (i) Wrong config, (ii) Wrong software library.

Either way, you might get the above "Time out, cannot connect" error message.

Troubleshooting Suggestions

(1) You may like to try and error modify the relevant bus number in the program, say

change default I2C bus number from 2 to 1.

(2) To make sure the hardware wiring, and software drivers etc are OK, (a) Remove the no detect BMP guy, (b) swap in any other I2C guy and "i2cdetect - y 1" again. If the new guy can be happily detected, then obviously the old guy is bad :(

Discussion and Recommendation

The AdaFruit BMP180 Library the OP uses is depreciated and no longer
supported.

I would suggest the OP to switch to

AdaFruit BMP280/BME280 CircuitPython Library

or

Pimoroni BMP280/BME280 Python Library

.

References

(1) Adafruit_2014 BMP085/BMP180 Python Library (Depreciated, No Longer Supported)

(2) BMP085 Datashet v2.5- Bosch 2009

(3) BMP180 Datasheet - Bosch 2009

(4) BMP280 Digital Pressure Sensor Datasheet v1.14 Bosch 2015

(5) BME280 Combined Humidity and Pressure Sensor Datasheet v.16 - Bosch 2018sep

(6) What's the difference between the BMP280 and the BME280 atmospheric sensors - 20,565 views 2017mar02

(7) UM10204 I2C-bus specification and user manual (referred in BMP180 Datasheet Section 5, Max clock = 3.4MHz) - 2014 NXP

(8) Adafruit BMP280 I2C or SPI Barometric Pressure & Altitude Sensor - US$10

(9) BMP280 Temperature, Pressure, & Altitude Sensor Python Library - Pimoroni 2019nov08

(10) BMP280 Pip Install - PyPi

Appendices

Appendix A - I2C wiring and Pull up resistors etc

(1) You should be using the only two I2C Clock and Data pins in the Rpi 40 pin header.

(2) The the two pins already have strong enough 1k8 pull up. There is no need to add more pull up resistor, with the risk of too strong pull up.

(3) Actually if you are putting too many I2C devices, say, more than 4, on the same bus, and the other devices have 4k7 or 10k pullups, the resultant pull up might be much less than 1k8, and overload the I2C pin current. I usually REMOVE those on device pullups to not to overload the Rpi I2C pins.

(4) Remove all other I2C devices on the same bus, for reason (3) above.

(5) Your hardware I2C connection wires CANNOT be too long, preferably less than 30cm.  Longer than that might result in too high impedance (For I2C, 400pf is the usual limit).

Appendix B - Difference between BMP085 and BMP180

I skim both datasheets to compare and contrast. My quick and dirty conclusion: (a) BMP180 is successor of BMP085, (b) They are functionally the same, meaning that software programming should be the "same".

Usually industry practice is that new hardware version is backward compatible, ie, BMP085 program can run for BMP180, but not vice versa. WARNING: I am just a friendly hobbyist. No guarantee No nothing won't melt down or blow up! Follow the hobbyist's suggestion at your own risk! :)

Appendix D - Suggestion to modify AdaFruit BMP180 Program for Rpi3/4

The main test program is actually very short.

The critical setup problem is the I2C bus number.

The program's default is I2C Bus #2. I would suggest to change default
to I2c Bus #1.

# AdaFruit BMP180 Program Author: Tony DiCola
# https://github.com/adafruit/Adafruit_Python_BMP/blob/master/examples/simpletest.py
import Adafruit_BMP.BMP085 as BMP085
# Default constructor will pick a default I2C bus.
# For the Raspberry Pi this means you should hook up to the only exposed I2C bus
# from the main GPIO header and the library will figure out the bus number based
# on the Pi's revision.
sensor = BMP085.BMP085()
# Optionally you can override the bus number:
# sensor = BMP085.BMP085(busnum=2)
print('Temp = {0:0.2f} *C'.format(sensor.read_temperature()))
print('Pressure = {0:0.2f} Pa'.format(sensor.read_pressure()))
print('Altitude = {0:0.2f} m'.format(sensor.read_altitude()))
print('Sealevel Pressure = {0:0.2f} Pa'.format(sensor.read_sealevel_pressure()))

Next is to update the class bmp085.  See next Appendix E below.

Appendix E - AdaFruit BMP085 Library BMP085 Class using Eazy Steup - Tony DiCola for Adafruit

The following notice from the AdaFruit BMP085 library says the library is depreciated. AdaFruit recommends:

(a) switch to AdaFruit CircuitPython sensor library (Note 1),

(b) Switch to BMP280.

Now we have a problem. This old library uses AdaFruit EasySetup tools which are no longer supported and might be incompatible to Raspberry Pi

Note 1 - Circuit Python is not 100% compatible to Raspberry Pi operating system Raspbian 10 buster.

DEPRECATED LIBRARY Adafruit Python BMP This library has been deprecated!
https://github.com/adafruit/Adafruit_Python_BMP/blob/master/README.md
the bmp085 and bmp180 are no longer made, and are replaced by the bmp280
we are now only using our circuitpython sensor libraries in python
we are leaving the code up for historical/research purposes but archiving the repository.
check out this guide for using the bmp280 with python! https://learn.adafruit.com/adafruit-bmp280-barometric-pressure-plus-temperature-sensor-breakout
Adafruit Python BMP
Python library for accessing the BMP series pressure and temperature sensors like the BMP085/BMP180 on a Raspberry Pi or Beaglebone Black.
Designed specifically to work with the Adafruit BMP085/BMP180 pressure sensors ----> https://www.adafruit.com/products/1603
To install, download the library by clicking the download zip link to the right and unzip the archive somewhere on your Raspberry Pi or Beaglebone Black. Then execute the following command in the directory of the library:~~
sudo python setup.py install
Make sure you have internet access on the device so it can download the required dependencies.

Appendix F - BME280 Learning Notes

I have been playing with Gyrometer, Accelerometer, and Magnetometer, but never Pressure meter. I also played with Temperature and Humidity sensors, but never Pressure Sensor, because I always thing that Pressure or Altitude sensor is only for mountain climbers, not for my hobby home automation.  But after studying the OP's question, I found that there is a new sensor with three measurements in one chip, Temperature, Humidity, and Pressure. I also found that though the OP's AdaFruit BMP085 and even BMP180 Library is depreciated, there is actually another new successor BMP280 and BME280.  I also found that Pimoroni seems has joined force with Lada Ada, sell her BEM280 breakout board, and at the same created a library. I am hoping that Pimoroni's python library is NOT CircuitPython, but standard Python.

I am reading Pimoroni's product and writing up some learning notes for future reference:

/ to continue, ...

Update 2022sep17 hkt1258

Appendix G - Pico W testing BME680

1. Introduction

Now I am setting up a Rpi Pico W prototyping board for testing BME680.

2. References

References

(1) Rpi Pico

(1.1) Rpi Pico W Datasheet – Rpi 2022jun29
https://datasheets.raspberrypi.com/picow/pico-w-datasheet.pdf

(1.2) Rpi Pico W Pinout Diagram
https://datasheets.raspberrypi.com/picow/PicoW-A4-Pinout.pdf

(1.3) Rpi Pico W Schematic – Appenix B – Pico Datasheet
https://www.etechnophiles.com/wp-content/uploads/2022/07/Pico-W-Schematic.pdf

(1.4) New Pi Pico W- WiFi Features, Specs & Pinout Simplified – etechnophiles
https://www.etechnophiles.com/raspberry-pi-pico-w-wifi-specs-pinout/

(2) BME680

(2.1)

(3) Schottky Diode References

I surveyed Schottky diodes and found 1N5822 good (only 0.4V drop at 1A).

https://forums.raspberrypi.com/viewtopic.php?p=1417588&hilit=schottky+diode+tlfong01#p1417588

1N5408 Datasheet - Vishay
https://www.vishay.com/docs/88516/1n5400.pdf

/ to continue, ...

End of answer


问:
Update SSAS Tabular connection string during azure pipeline release
We are deploying Tabular SSAS instance as part of on-premise azure build and release pipeline, using Microsoft.AnalysisServices.Deployment.exe with .asdatabase file.

I am trying to figure out a way to update (relational DB) data source connection string during the release stage.

Most of the solutions I could find use SSIS, which we don't, so I would strongly prefer not to introduce it for this task.

I can see that connections are defined in .asdatabase file:

```<code>"dataSources": [
  {
    "name": "sourceDB1",
    "connectionString": "Data Source=xxxx",
    ...
  },
  {
    "name": "sourceDB2",
    ...
  }
 ]
</code>```

I use this powershell script to update connection strings :

```<code>if($args[0] -eq $null)
{
    Write-Host "Updates .asdatabase connection string. Parameters: %source name% %source connection string%"
}
else{

    $source=$args[0]
    $connectionstring=$args[1]

    write-host "updating "  $source  " connection string..."

    $a = Get-Content 'Model.asdatabase' -raw | ConvertFrom-Json
    $a.model.datasources | % {if($_.name -eq $source){$_.connectionString=$connectionstring}}
    $a | ConvertTo-Json -depth 100| set-content 'Model2.asdatabase'

    If ($?)
    {
        write-host "updated successfully"
    }
}
</code>```

Is there a more sane/sustainable approach?

Related Question: Continuous integration and Deploy SSAS tabular to Azure Analysis Services

答:
What about consider to make use one extension which name is Replace Text in Source Files.

It contains 2 method, and the first one is replace by search pattern.

Search Start of Text

As the description says you're looking in each line of the source code
  for a text starting with what is entered here.

Sample Line -> [assembly: AssemblyInformationalVersion("1.1.1.1")]

So if you enter 'AssemblyInformationalVersion("' it will look for a
  line containing that text and stopping just at the end before the
  version 1.1.1.1.

Search End of Text

As the description says the task is looking for the 'End of Text' but
  only on the lines where the Start of Text already found a result.

Sample Line -> [assembly: AssemblyInformationalVersion("1.1.1.1")]

So if you enter '")]' it will look for the position just at the end of
  version 1.1.1.1.

Also, you can use the another task Replace In Files Text By Text. What its work logic is same with replace A with B directly, so it needs you input the original connection string value every times.

Just based on your scenario and your actual considering to choose one of them.

Body:
We are deploying Tabular SSAS instance as part of on-premise azure build and release pipeline, using Microsoft.AnalysisServices.Deployment.exe with .asdatabase file.

I am trying to figure out a way to update (relational DB) data source connection string during the release stage.

Most of the solutions I could find use SSIS, which we don't, so I would strongly prefer not to introduce it for this task.

I can see that connections are defined in .asdatabase file:

"dataSources": [
  {
    "name": "sourceDB1",
    "connectionString": "Data Source=xxxx",
    ...
  },
  {
    "name": "sourceDB2",
    ...
  }
 ]

I use this powershell script to update connection strings :

if($args[0] -eq $null)
{
    Write-Host "Updates .asdatabase connection string. Parameters: %source name% %source connection string%"
}
else{

    $source=$args[0]
    $connectionstring=$args[1]

    write-host "updating "  $source  " connection string..."

    $a = Get-Content 'Model.asdatabase' -raw | ConvertFrom-Json
    $a.model.datasources | % {if($_.name -eq $source){$_.connectionString=$connectionstring}}
    $a | ConvertTo-Json -depth 100| set-content 'Model2.asdatabase'

    If ($?)
    {
        write-host "updated successfully"
    }
}

Is there a more sane/sustainable approach?

Related Question: Continuous integration and Deploy SSAS tabular to Azure Analysis Services


问:
python itertools product with steps
Currently, I have a NumPy array:

```<code>a = np.array([[1,2],[3,4],[5,6]])
</code>```

And I am doing the product operation in itertools, but I want to add a step function.
For example:

```<code>[ x for x in itertools.product(*a) ]
</code>```

Result in:

```<code>[(1, 3, 5), (1, 3, 6), (1, 4, 5), (1, 4, 6), (2, 3, 5), (2, 3, 6), (2, 4, 5), (2, 4, 6)]
</code>```

For the target output with step (1,1,2):

```<code>[(1, 3, 5), (1, 4, 5), (2, 3, 5), (2, 4, 5)]
</code>```

I can't figure it out, here is the problem.

Title: python itertools product with steps

Body:
Currently, I have a NumPy array:

a = np.array([[1,2],[3,4],[5,6]])

And I am doing the product operation in itertools, but I want to add a step function.
For example:

[ x for x in itertools.product(*a) ]

Result in:

[(1, 3, 5), (1, 3, 6), (1, 4, 5), (1, 4, 6), (2, 3, 5), (2, 3, 6), (2, 4, 5), (2, 4, 6)]

For the target output with step (1,1,2):

[(1, 3, 5), (1, 4, 5), (2, 3, 5), (2, 4, 5)]

I can't figure it out, here is the problem.

Body:
Just use a list slice:

In [578]: import itertools
In [579]: a=[[1,2],[3,4],[5,6]]
In [580]: list(itertools.product(*a))[::2]
Out[580]: [(1, 3, 5), (1, 4, 5), (2, 3, 5), (2, 4, 5)]

There may be a itertools tools to do this as well.

In [586]: list(itertools.islice(itertools.product(*a), None, None,2))
Out[586]: [(1, 3, 5), (1, 4, 5), (2, 3, 5), (2, 4, 5)]


问:
Pairwise Euclidean distance in DolphinDB
I have a matrix that represents a group of column vectors in DolphinDB. Each row is regarded as a component of the vector and each column is regarded as a column vector.

For example, the following 3*4 matrix A represents 4 column vectors with 3 components.

```<code>A = (1 4 5 -2 -3 6 9 4 3 1 0 3)$3:4
</code>```

I would like to compute the pairwise Euclidean distance of those vectors. Is there any way to avoid using a FOR loop?

答:
```<code>A = (1 4 5 -2 -3 6 9 4 3 1 0 3)$3:4
cross(def(x,y): sum2(x -y).sqrt(), A)
</code>```

DolphinDB has a higher order function cross to solve pairwise problems. Here we define a lambda function to calculate Euclidean distance

Body:
I have a matrix that represents a group of column vectors in DolphinDB. Each row is regarded as a component of the vector and each column is regarded as a column vector.

For example, the following 3*4 matrix A represents 4 column vectors with 3 components.

A = (1 4 5 -2 -3 6 9 4 3 1 0 3)$3:4

I would like to compute the pairwise Euclidean distance of those vectors. Is there any way to avoid using a FOR loop?

Body:
A = (1 4 5 -2 -3 6 9 4 3 1 0 3)$3:4
cross(def(x,y): sum2(x -y).sqrt(), A)

DolphinDB has a higher order function cross to solve pairwise problems. Here we define a lambda function to calculate Euclidean distance


问:
Automatic Down- and Upscaling of Kubernetes Cluster Depending on Request Frequency
I have a small Web Application running on a Google Kubernetes Cluster. But I want to save some money, because the web app does not get much traffic.

Thus my goal is to automatically downscale my Kubernetes cluster to 0 nodes if there was no traffic for more than some amount of time. And of course it should automatically spin up a node if there is incoming traffic.

Any ideas on how to do this?

答:
The GKE autoscaler scales up only when there are pods to be scheduled that do not fir on any current nodes and scaling up would allow the pod to be scheduled.

Scaling down occurs whenever a node is using less than half it's total memory and CPU, and all the pods running on the node can be scheduled on another node.

This being said, the autoscaler will never scale a cluster down to 0 as the reuirements for that can't be met.

However, you can configure Horizontal Pod Autoscaling for your application deployment. You can configure HPA to scale up or down based on the number of HTTP requests using a custom metric. Despite this, HPA should also not scale the deployment all the way down to 0, nor should it scale up from 0.

If you configure HPA properly, enable cluster autoscaling, and plan how your pods are being deployed by leveraging taints, tolerations, and affinity, then you can optimze autoscaling so that your cluster will scale down to a minimal size. But it still will not be 0.

All this being said, if you are running just a simple application with extended downtime, you may want to consider using Cloud Run or App Engine as those will be easier to manage than GKE and will have far less overhead (and likely less cost).


问:
Box for Text Not Working?
On this page, I'm trying to create a text box around the paragraph that begins "It's important not to...". I used this CSS:

```<code>.transbox  {
    background: #F5FBEF;
    border: 1px solid #E3F6CE;
    padding: 10px;
    margin: 10px auto;
}
</code>```

The text has moved slightly out of line with the other text in the article, but it's not showing how it's supposed to. Any ideas what's wrong?

答:
the text is out of line because your "transbox" is a div and not a p - you couljd just code it
 for it to inherit the other p CSS, or if their will be more
 elements inside this box you need to make the .transbox CSS (specifically margins) match your p's

then there is no .transbox CSS being applied, are you sure your updated CSS above is entered properly (i.e. the case of the classname)..  or is the old stylesheet maybe cached and needs a refresh to pick up your added code

ContentLicense: CC BY-SA 3.0

Title: Box for Text Not Working?

Body:
On this page, I'm trying to create a text box around the paragraph that begins "It's important not to...". I used this CSS:

.transbox  {
    background: #F5FBEF;
    border: 1px solid #E3F6CE;
    padding: 10px;
    margin: 10px auto;
}

The text has moved slightly out of line with the other text in the article, but it's not showing how it's supposed to. Any ideas what's wrong?

Body:
the text is out of line because your "transbox" is a div and not a p - you couljd just code it <p class="transbox"> for it to inherit the other p CSS, or if their will be more <p> elements inside this box you need to make the .transbox CSS (specifically margins) match your p's

then there is no .transbox CSS being applied, are you sure your updated CSS above is entered properly (i.e. the case of the classname)..  or is the old stylesheet maybe cached and needs a refresh to pick up your added code


问:
React Native: Refreshing gets stuck while scrolling in nesting FlatLists in Androdid
While using a horizontal FlatList with other vertical FlatList as items there seems to be an issue with the refreshing. This happens when refreshing is enabled on the vertical lists but not on the horizontal container list. It is actually possible to refresh each individual list if you are very carful and only scrolls vertically (this is very hard). But at once you scrolls sideways the refreshing gets stuck.

React Native nested FlatLists

Issue in Android. Works in iOS

Attempts
I have tried replacing the wrapping FlatList with a ScollView with the same result. I am fully aware of that it is possible to disable refreshing of the individual list and enable it on the containing FlatList but that is not very appropriate in my case.

I have also tried the upvoted answers on this similar question but it didn't solve it.

Example:

```<code> <FlatList
            horizontal={true}
            pagingEnabled={true}
            data={[{key: 'a'}, {key: 'b'}]}
            renderItem={({item}) =>
                <FlatList
                    style={{width: 400}}
                    ref="scrollView"
                    horizontal={false}
                    refreshing={false}
                    onRefresh={() => {}}
                    data={[{key: 'c'}, {key: 'd'}]}
                    renderItem={({item}) =>  <Text>{item.key}</Text>}
                />
            }
        />
</code>```

Does anyone have a solution to this?

答: ScrollView/ Flatlist import from react-native-gesture-handler can be stuck refresh when released outside of the screen. Use ScrollView import from react-native</p>

Body:
While using a horizontal FlatList with other vertical FlatList as items there seems to be an issue with the refreshing. This happens when refreshing is enabled on the vertical lists but not on the horizontal container list. It is actually possible to refresh each individual list if you are very carful and only scrolls vertically (this is very hard). But at once you scrolls sideways the refreshing gets stuck.

React Native nested FlatLists

Issue in Android. Works in iOS

Attempts
I have tried replacing the wrapping FlatList with a ScollView with the same result. I am fully aware of that it is possible to disable refreshing of the individual list and enable it on the containing FlatList but that is not very appropriate in my case.

I have also tried the upvoted answers on this similar question but it didn't solve it.

Example:

 <FlatList
            horizontal={true}
            pagingEnabled={true}
            data={[{key: 'a'}, {key: 'b'}]}
            renderItem={({item}) =>
                <FlatList
                    style={{width: 400}}
                    ref="scrollView"
                    horizontal={false}
                    refreshing={false}
                    onRefresh={() => {}}
                    data={[{key: 'c'}, {key: 'd'}]}
                    renderItem={({item}) =>  <Text>{item.key}</Text>}
                />
            }
        />

Does anyone have a solution to this?


问:
Install and run MongoDB connector for BI
I have already followed this link and installed mongosqld in my Mac OS. Now, I can see the folder under contents under bin/mongosqld.

But, when I followed this link and launched /bin/mongosqld, I got the error:

```<code>$ bin/mongosqld
dyld: Library not loaded: /usr/local/opt/openssl@1.1/lib/libssl.1.1.dylib
  Referenced from: /Users/chengtie/Downloads/mongodb-bi-osx-x86_64-v2.13.4/bin/mongosqld
  Reason: image not found
Abort trap: 6
</code>```

Does anyone know how to fix this?

答:
You need to install OpenSSL 1.1 if you haven't already.

If the libraries were not installed at /usr/local/opt/openssl@1.1/lib/ (I believe this is the default location if you install via HomeBrew), you will need to set up the environment so the linker can find them.

See Is it OK to use DYLD_LIBRARY_PATH on Mac OS X? And, what's the dynamic library search algorithm with it?

Body:
I have already followed this link and installed mongosqld in my Mac OS. Now, I can see the folder under contents under bin/mongosqld.

But, when I followed this link and launched /bin/mongosqld, I got the error:

$ bin/mongosqld
dyld: Library not loaded: /usr/local/opt/openssl@1.1/lib/libssl.1.1.dylib
  Referenced from: /Users/chengtie/Downloads/mongodb-bi-osx-x86_64-v2.13.4/bin/mongosqld
  Reason: image not found
Abort trap: 6

Does anyone know how to fix this?


问:
Java didn't work my regex, online editors did
Good evening,

I'm having this problem. I have a text file with several blocks of commits gathered form Github. I need to split this file in blocks each of one representing a commit. An example of the file is presented next:

```<code>commit 7aa32a74edba59f1c295a41e95f5deab0d1753c8
Author: borisperezg

commit b6e0a1749da95238af5be0081074ce123bf507bd
Author: borisperezg

commit 6d77c0a78b2a4b8386fbaeaaeaf28fcf89ec8b2c
Author: borisperezg
</code>```

However, when I use a regex in an online regex editor (or even a local text editor), it works grouping the blocks of text, but Java didn't. My regex is:

```<code>^(commit\s+[\w|\d|\n|:|\s]+)+
Another version: ^(commit\\s+[\\w|\\d|\\n|:|\\s]+).*$
Another version: .*^(commit\\s+[\\w|\\d|\\n|:|\\s]+).*$
</code>```

My Java implementation is presented next:

```<code>public static void main(String[] args) {

    String lines = // file reader and the content stored here;

    String pattern = "^(commit\\s+[\\w|\\d|\\n|:|\\s]+).*$";

    // Create a Pattern object
    Pattern r = Pattern.compile(pattern);

    // Now create matcher object.
    Matcher m = r.matcher(lines);
    m.matches();
    // Also tested m.find()

    System.out.println(m.group(0));
    System.out.println(m.group(1));
    System.out.println(m.group(2));

}
</code>```

I dont know, it should be straightforward.

Please, can somebody help me. Thank you in advance.

答:
If you want to get each commit separately, you need to use a find() loop, and your pattern must end when reaching the next commit line.

```<code>String lines = "commit 7aa32a74edba59f1c295a41e95f5deab0d1753c8\r\n" +
               "Author: borisperezg\r\n" +
               "\r\n" +
               "commit b6e0a1749da95238af5be0081074ce123bf507bd\r\n" +
               "Author: borisperezg \r\n" +
               "\r\n" +
               "commit 6d77c0a78b2a4b8386fbaeaaeaf28fcf89ec8b2c\r\n" +
               "Author: borisperezg \r\n";

String pattern = "commit [0-9a-f]+\\R(?:(?!\\Rcommit ).*\\R)*";

// Create a Pattern object
Pattern r = Pattern.compile(pattern);

// Now create matcher object.
Matcher m = r.matcher(lines);
while (m.find()) {
    System.out.print(m.group()); // Captured text ends with a line-separator
    System.out.println("==================================================");
}
</code>```

Output

commit 7aa32a74edba59f1c295a41e95f5deab0d1753c8
Author: borisperezg
==================================================
commit b6e0a1749da95238af5be0081074ce123bf507bd
Author: borisperezg
==================================================
commit 6d77c0a78b2a4b8386fbaeaaeaf28fcf89ec8b2c
Author: borisperezg
==================================================
```

Body:
Good evening,

I'm having this problem. I have a text file with several blocks of commits gathered form Github. I need to split this file in blocks each of one representing a commit. An example of the file is presented next:

commit 7aa32a74edba59f1c295a41e95f5deab0d1753c8
Author: borisperezg

commit b6e0a1749da95238af5be0081074ce123bf507bd
Author: borisperezg

commit 6d77c0a78b2a4b8386fbaeaaeaf28fcf89ec8b2c
Author: borisperezg

However, when I use a regex in an online regex editor (or even a local text editor), it works grouping the blocks of text, but Java didn't. My regex is:

^(commit\s+[\w|\d|\n|:|\s]+)+
Another version: ^(commit\\s+[\\w|\\d|\\n|:|\\s]+).*$
Another version: .*^(commit\\s+[\\w|\\d|\\n|:|\\s]+).*$

My Java implementation is presented next:

public static void main(String[] args) {

    String lines = // file reader and the content stored here;

    String pattern = "^(commit\\s+[\\w|\\d|\\n|:|\\s]+).*$";

    // Create a Pattern object
    Pattern r = Pattern.compile(pattern);

    // Now create matcher object.
    Matcher m = r.matcher(lines);
    m.matches();
    // Also tested m.find()

    System.out.println(m.group(0));
    System.out.println(m.group(1));
    System.out.println(m.group(2));

}

I dont know, it should be straightforward.

Please, can somebody help me. Thank you in advance.

Body:
If you want to get each commit separately, you need to use a find() loop, and your pattern must end when reaching the next commit line.

String lines = "commit 7aa32a74edba59f1c295a41e95f5deab0d1753c8\r\n" +
               "Author: borisperezg\r\n" +
               "\r\n" +
               "commit b6e0a1749da95238af5be0081074ce123bf507bd\r\n" +
               "Author: borisperezg \r\n" +
               "\r\n" +
               "commit 6d77c0a78b2a4b8386fbaeaaeaf28fcf89ec8b2c\r\n" +
               "Author: borisperezg \r\n";

String pattern = "commit [0-9a-f]+\\R(?:(?!\\Rcommit ).*\\R)*";

// Create a Pattern object
Pattern r = Pattern.compile(pattern);

// Now create matcher object.
Matcher m = r.matcher(lines);
while (m.find()) {
    System.out.print(m.group()); // Captured text ends with a line-separator
    System.out.println("==================================================");
}

Output

commit 7aa32a74edba59f1c295a41e95f5deab0d1753c8
Author: borisperezg
==================================================
commit b6e0a1749da95238af5be0081074ce123bf507bd
Author: borisperezg
==================================================
commit 6d77c0a78b2a4b8386fbaeaaeaf28fcf89ec8b2c
Author: borisperezg
==================================================


问:
Ajax Request being blocked by Cors when I abort or exit in the middle of the controller function
I recently started working on separate repositories for front-end and back-end by using Nuxt.js and Laravel. I have solved the Cors issue by creating a middleware.

However, it seems like some of my request still gets blocked by Cors when I try to abort, exit or die in the middle of the controller function... e.g. dd('test!');

P.S The requests are not blocked when I return the responses in correct json format.

console error

network tab when error

network tab when no error

Please help!

答:
Just to share what I found:

I think the middleware I created couldn't attach the headers because Laravel's dd() function terminates the entire request in the middle.
So I guess I will just have to make a habit to include the variable in the json response every time when there is a variable that I wanna dump out.

Please let me know if there is anyone with the better solution!


问:
Why would Mongo read from Secondary with read concern set to Primary
I have a mongo setup as a  P-S-S architecture, 1 the connection string looks like mongodb://mongo1,mongo2,mongo3/db1?replicaSet=rs .

One of my applications (nodejs) every once is a while will attempt to read and get a not master and slaveOk=false error. I expected the this to only read from the primary, given the default read concern.

Question: Why would the driver direct the read to a secondary?

答: well - to get a - not master and slaveOk=false error - when set to read primary - would be what correctly occurs when the primary is not available.  So maybe your real question is why is the primary not available? …..see what I mean? … in a replica set there should always be primary but who knows - there must be a transitory moment when the election occurs during failover....you might want to check the logs to see how often the primary is going down......now if you do not want to get this error change the read preference to Primary Preferred.</p>