问:
How to validate model object instance in Laravel?
I've got the following model:

```<code><?php
namespace App;
use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    protected $guarded = ['id'];

    public static function rules()
    {
        return [
            'created_at'    => 'nullable',
            'updated_at'    => 'nullable',
            'name'          => 'required|string|between:1,255',
            'description'   => 'required|string|between:1,255',
            'date_added'    => 'nullable',
            'date_edited'   => 'nullable',
            'unit'          => 'required|string|between:1,255',
            'unit_type'     => 'required|integer',
            'stock'         => 'nullable|string|between:0,255',
            'barcode'       => 'nullable|string|between:0,32',
            'tax'           => 'nullable|float',
            'price'         => 'nullable|float',
            'category_id'   => 'required|integer|gt:0'
        ];
    }
}
</code>```

And there's a controller ProductController that has an action insertProduct.

```<code>class class ProductController extends ApiController { // controller class

    public function insertProduct(Request $request) {

        $inputJson = $request->input('data_json', null);

        if(empty($inputJson)) {
            $inputJson = $request->getContent();
            if(empty($inputJson)) {
                return $this->errorResponse(
                    'Either data_json formdata parameter or request body should contain a JSON string.'
                );
            }
        }

        try {
            $product = $this->extractProductFromJSON($inputJson);
        } catch(\Exception $e) {
            return $this->errorResponse($e->getMessage(), 400);
        }

        // When I dump the Product ($product) instance using dd(), it is just as expected and its
        // properties contain the right values.

        $validator = Validator::make($product, Product::rules());
        /* Above line causes exception:
         TypeError: Argument 1 passed to Illuminate\Validation\Factory::make() must be of the type
         array, object given,
         called in /.../vendor/laravel/framework/src/Illuminate/Support/Facades/Facade.php
         on line 261 in file /.../vendor/laravel/framework/src/Illuminate/Validation/Factory.php
         on line 98
        */

        if($validator->fails()) {
            return $this->errorResponse($validator->errors()->first());
        }

        // ...
    }

    // How I extract the data from the JSON string (which is input).
    // Although I don't think this has anything to do with my problem.

    private function extractProductFromJSON(string $json) {

        $data = \json_decode($json);

        if(\json_last_error() != JSON_ERROR_NONE) {
            throw new \Exception('Error parsing JSON: ' . \json_last_error_msg());
        }

        try {

            $productData = $data->product;

            $productId = empty($productData->id) ? null : $productData->id;
            // Product id is allowed to be absent

            $product = new Product(); // My \App\Product model instance.
            $product->id = $productId;
            $product->name = $productData->name;
            $product->description = $productData->description;
            $product->date_added = $productData->date_added;
            $product->date_edited = $productData->date_edited;
            $product->unit = $productData->unit;
            $product->unit_type = $productData->unit_type;
            $product->stock = $productData->stock;
            $product->barcode = $productData->barcode;
            $product->tax = $productData->tax;
            $product->price = $productData->price;
            $product->category_id = $productData->category_id;

            return $product;

        } catch(\Exception $e) {
            echo 'EXCEPTION...';
        }
    }

} // end of controller class
</code>```

It seems pretty clear there's something wrong with the following line:
$validator = Validator::make($product, Product::rules());
The simplest cause I can think of, is that the validator simply does not accept objects and only wants arrays.
If not, what could be the problem?
If Laravel's validation only works with arrays, is it somehow possible to validate an object?

答:
```<code>class Cliente extends Eloquent
{
    public static $autoValidates = true;
    protected static $rules = [];
    protected static function boot()
    {
        parent::boot();
        // or static::creating, or static::updating
        static::saving(function($model)
        {
            if ($model::$autoValidates) {
                return $model->validate();
            }
        });
    }
    public function validate()
    {
    }
}
</code>```

Body:
I've got the following model:

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    protected $guarded = ['id'];

    public static function rules()
    {
        return [
            'created_at'    => 'nullable',
            'updated_at'    => 'nullable',
            'name'          => 'required|string|between:1,255',
            'description'   => 'required|string|between:1,255',
            'date_added'    => 'nullable',
            'date_edited'   => 'nullable',
            'unit'          => 'required|string|between:1,255',
            'unit_type'     => 'required|integer',
            'stock'         => 'nullable|string|between:0,255',
            'barcode'       => 'nullable|string|between:0,32',
            'tax'           => 'nullable|float',
            'price'         => 'nullable|float',
            'category_id'   => 'required|integer|gt:0'
        ];
    }
}

And there's a controller ProductController that has an action insertProduct.

class class ProductController extends ApiController { // controller class

    public function insertProduct(Request $request) {

        $inputJson = $request->input('data_json', null);

        if(empty($inputJson)) {
            $inputJson = $request->getContent();
            if(empty($inputJson)) {
                return $this->errorResponse(
                    'Either data_json formdata parameter or request body should contain a JSON string.'
                );
            }
        }

        try {
            $product = $this->extractProductFromJSON($inputJson);
        } catch(\Exception $e) {
            return $this->errorResponse($e->getMessage(), 400);
        }

        // When I dump the Product ($product) instance using dd(), it is just as expected and its
        // properties contain the right values.

        $validator = Validator::make($product, Product::rules());
        /* Above line causes exception:
         TypeError: Argument 1 passed to Illuminate\Validation\Factory::make() must be of the type
         array, object given,
         called in /.../vendor/laravel/framework/src/Illuminate/Support/Facades/Facade.php
         on line 261 in file /.../vendor/laravel/framework/src/Illuminate/Validation/Factory.php
         on line 98
        */

        if($validator->fails()) {
            return $this->errorResponse($validator->errors()->first());
        }

        // ...
    }

    // How I extract the data from the JSON string (which is input).
    // Although I don't think this has anything to do with my problem.

    private function extractProductFromJSON(string $json) {

        $data = \json_decode($json);

        if(\json_last_error() != JSON_ERROR_NONE) {
            throw new \Exception('Error parsing JSON: ' . \json_last_error_msg());
        }

        try {

            $productData = $data->product;

            $productId = empty($productData->id) ? null : $productData->id;
            // Product id is allowed to be absent

            $product = new Product(); // My \App\Product model instance.
            $product->id = $productId;
            $product->name = $productData->name;
            $product->description = $productData->description;
            $product->date_added = $productData->date_added;
            $product->date_edited = $productData->date_edited;
            $product->unit = $productData->unit;
            $product->unit_type = $productData->unit_type;
            $product->stock = $productData->stock;
            $product->barcode = $productData->barcode;
            $product->tax = $productData->tax;
            $product->price = $productData->price;
            $product->category_id = $productData->category_id;

            return $product;

        } catch(\Exception $e) {
            echo 'EXCEPTION...';
        }
    }

} // end of controller class

It seems pretty clear there's something wrong with the following line:
$validator = Validator::make($product, Product::rules());
The simplest cause I can think of, is that the validator simply does not accept objects and only wants arrays.
If not, what could be the problem?
If Laravel's validation only works with arrays, is it somehow possible to validate an object?


来源: stackexchange

问:
Roboguice /getInstance + best practice
I just started using Roboguice (+Guice) and I am not sure about the best practice how to use it.

In my Activity I have about 5 functions (out of about 30) which uses an object called "ProviderQueries" (Singleton). I could use it in two ways:

1.)

```<code>    protected void onResume() {
       super.onResume();
       getInjector().getInstance(ProviderQueries.class).setLanguage("EN");
}
</code>```

2.)

```<code>class MyActivity extends RoboActivity {
    @Inject
    private ProviderQueries pv;

    ...

       protected void onResume() {
          super.onResume();
          pv.setLanguage("EN");
          }
 }
</code>```

1 - too long but the instance of ProviderQueries is used where it is needed

2 - short and nice but "pv" is available for the whole Activity but only needed in 5 different function...

Which approach would you use, or do you have a better solution?

Thanks in advance!

答:
This is a bit of a judgement call.  To me, 5 functions seems justification enough to put this in a member variable, which uses a cleaner syntax and reduces the explicit dependency on the injector.  I see your point about it not being used in all 30 methods, but that seems of a secondary concern in my personal opinion (your own sense of aesthetics of course may be different).

If ProviderQueries is especially memory intensive, you may want to consider going with option 2 instead of 1 since option 1 will keep the object live for the duration of the activity.  Not a consideration for most objects, but could be an issue for some.

If you weren't using Guice, how would you access your singleton?  Presumably through an accessor method?  You can, of course, always write your own accessor that performs #2 for you in a more compact way, although it won't bypass the small reflection overhead incurred for each access to the singleton.

ContentLicense: CC BY-SA 3.0

Title: Roboguice /getInstance + best practice

Body:
I just started using Roboguice (+Guice) and I am not sure about the best practice how to use it.

In my Activity I have about 5 functions (out of about 30) which uses an object called "ProviderQueries" (Singleton). I could use it in two ways:

1.)

    protected void onResume() {
       super.onResume();
       getInjector().getInstance(ProviderQueries.class).setLanguage("EN");
}

2.)

class MyActivity extends RoboActivity {
    @Inject
    private ProviderQueries pv;

    ...

       protected void onResume() {
          super.onResume();
          pv.setLanguage("EN");
          }
 }

1 - too long but the instance of ProviderQueries is used where it is needed

2 - short and nice but "pv" is available for the whole Activity but only needed in 5 different function...

Which approach would you use, or do you have a better solution?

Thanks in advance!


问:
Angular devextreme problem in error popup
I'm using angular with devextreme , when an error occurs the error message is hidden behind the popup form , how can I send it to the front ?
thanks in advance

答:
It depends on the order in which you added the dxPopup Html Element. I guess your error popup is defined before the form popup:

<dx-popup id="error-popup"></dx-popup>
<dx-popup id="form-popup"></dx-popup>
```
<p>You should change the order to:</p>
<pre class="lang-html prettyprint-override"><code><dx-popup id="form-popup"></dx-popup>
<dx-popup id="error-popup"></dx-popup>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
It depends on the order in which you added the dxPopup Html Element. I guess your error popup is defined before the form popup:

<dx-popup id="error-popup"></dx-popup>
<dx-popup id="form-popup"></dx-popup>

You should change the order to:

<dx-popup id="form-popup"></dx-popup>
<dx-popup id="error-popup"></dx-popup>


问:
Draw2D alignement in react, or Draw2D boxing
I found a simple application with React and draw2D.

The dashbox is the div and the canvas.

The circle is a

```<code>draw2d.shape.basic.Circle({
        x: 40,
        y: 10,
        stroke: 3
      })
</code>```

How to change the code to draw the circle inside the box dashed (the canvas)?

https://codesandbox.io/s/exciting-cray-97g6r?file=/src/App.js

thanks.

答:
The first solution

```<code><span>
<p>Avec canvas2</p>
<div ref={inputRef} id="canvas"
style={{ height: 200, width: 300, border: "dashed brown",position:"relative" }}/>
</span>
</code>```

Only add position:"relative", to the div.

I improve this solution again.

```<code>componentDidMount() {
    this.canvas = new draw2d.Canvas("canvas", 9000, 9000));

    this.canvas.add(
      new draw2d.shape.basic.Circle({
        x: 40,
        y: 10,
        stroke: 3
      })
    );
}

render() {
    return (
      <span>
        <p>Avec canvas2</p>
        <div
          id="canvas"
          style={{ height: 600, width: 600, border: "dashed brown" }}
        />
      </span>
    );
}
</code>```

Now, we have a big picture inside a window ..

Body:
I found a simple application with React and draw2D.

The dashbox is the div and the canvas.

The circle is a

draw2d.shape.basic.Circle({
        x: 40,
        y: 10,
        stroke: 3
      })

How to change the code to draw the circle inside the box dashed (the canvas)?

https://codesandbox.io/s/exciting-cray-97g6r?file=/src/App.js

thanks.

Body:
The first solution

<span>
<p>Avec canvas2</p>
<div ref={inputRef} id="canvas"
style={{ height: 200, width: 300, border: "dashed brown",position:"relative" }}/>
</span>

Only add position:"relative", to the div.

I improve this solution again.

componentDidMount() {
    this.canvas = new draw2d.Canvas("canvas", 9000, 9000));

    this.canvas.add(
      new draw2d.shape.basic.Circle({
        x: 40,
        y: 10,
        stroke: 3
      })
    );
}

render() {
    return (
      <span>
        <p>Avec canvas2</p>
        <div
          id="canvas"
          style={{ height: 600, width: 600, border: "dashed brown" }}
        />
      </span>
    );
}

Now, we have a big picture inside a window ..


问:
How can I use gettext in a kivy app on android?
I have a kivy app that uses a module from another package. The packages are organised as follows:

```<code>.
├── kivy_app
│   ├── bin
│   │   └── myapp-0.1-debug.apk
│   ├── buildozer.spec
│   └── kivy_app
│       ├── __init__.py
│       ├── __main__.py
│       ├── main.py
│       ├── python_pkg -> /home/jeff/projects/kivy_pkg/python_pkg/python_pkg
│       └── source
│           └── kivy_app.py
└── python_pkg
    └── python_pkg
        ├── __init__.py
        ├── locale
        │   └── en_GB
        │       └── LC_MESSAGES
        │           └── python_pkg.mo
        └── source
            └── version.py
</code>```

The module kivy_app.py accesses version.py in python_pkg. This latter package uses a translation file based on gettext, set up in the normal way.

The application works perfectly on the PC, but when the app is run on an android device it crashes. The relevant lines in the logcat output are:

```<code>09-07 16:28:22.142 10274 10340 I python  :    File "/home/jeff/projects/kivy_pkg/kivy_app/.buildozer/android/platform/build/build/other_builds/python3-libffi-openssl-sqlite3/armeabi-v7a__ndk_target_21/python3/Lib/gettext.py", line 524, in translation
09-07 16:28:22.142 10274 10340 I python  :  FileNotFoundError: [Errno 2] No translation file found for domain: 'python_pkg'
</code>```

I cannot find where gettext.py is trying to locate the mo files.  Can someone please suggest how I might change things so that it works?

PS It works if I set the fallback value to True in gettext.translation(), but then no translation gets done!

答:
I see that it is an old question, but recently I had the same problem: on PC it worked, on android crashed. And the output in the logcat was the same.

All .mo files were included in package. So, I've copied gettext.py to my project and added print-statements in function find. There is a part, where it goes through all possible languages, builds a path to .mo file and checks if it exists.

It appeared that on PC and android these language arrays are different. All I've got to do, was to change in my project locale directory name from EN to en, etc. Now it works.

Body:
I have a kivy app that uses a module from another package. The packages are organised as follows:

.
├── kivy_app
│   ├── bin
│   │   └── myapp-0.1-debug.apk
│   ├── buildozer.spec
│   └── kivy_app
│       ├── __init__.py
│       ├── __main__.py
│       ├── main.py
│       ├── python_pkg -> /home/jeff/projects/kivy_pkg/python_pkg/python_pkg
│       └── source
│           └── kivy_app.py
└── python_pkg
    └── python_pkg
        ├── __init__.py
        ├── locale
        │   └── en_GB
        │       └── LC_MESSAGES
        │           └── python_pkg.mo
        └── source
            └── version.py

The module kivy_app.py accesses version.py in python_pkg. This latter package uses a translation file based on gettext, set up in the normal way.

The application works perfectly on the PC, but when the app is run on an android device it crashes. The relevant lines in the logcat output are:

09-07 16:28:22.142 10274 10340 I python  :    File "/home/jeff/projects/kivy_pkg/kivy_app/.buildozer/android/platform/build/build/other_builds/python3-libffi-openssl-sqlite3/armeabi-v7a__ndk_target_21/python3/Lib/gettext.py", line 524, in translation
09-07 16:28:22.142 10274 10340 I python  :  FileNotFoundError: [Errno 2] No translation file found for domain: 'python_pkg'

I cannot find where gettext.py is trying to locate the mo files.  Can someone please suggest how I might change things so that it works?

PS It works if I set the fallback value to True in gettext.translation(), but then no translation gets done!


问:
How to concatenate a newly added file to pandas dataframe?
I am trying to write a script which will be grabbing newly added csv file from the folder and adding it to one big file. Basically, I want all of the csv files added to a particular folder, being stored in one resulting csv file. I have a code below which generates the list of files and I am selecting the newly added file there:

```<code>def check_dir(fh,start_path='/Users/.../Desktop/files',new_cb=None,changed_cb=None):
    total_size = 0
    for dirpath, dirnames, filenames in os.walk(start_path):
        for f in filenames:
            fp = os.path.join(dirpath, f)
            if not os.path.islink(fp):
                fs = os.path.getsize(fp)
                total_size += fs
                if f in fh:
                    if fh[f] == fs:
                        # file unchanged
                        pass
                    else:
                        if changed_cb:
                            changed_cb(fp)
                else:
                    #new file
                    if new_cb:
                        new_cb(fp)
                fh[f] = fs

    return total_size

def new_file(fp):
    print("New File {0}!".format(fp))

def changed_file(fp):
    print("File {0} changed!".format(fp))

if __name__ == '__main__':
    file_history={}
    total = 0

    while(True):
        nt = check_dir(file_history,'/Users/.../Desktop/files',new_file,changed_file)
        if total and nt != total:
            print("Total size changed from {0} to {1}".format(total,nt))
            total = nt
        time.sleep(200)
        print("File list:\n{0}".format(file_history))
        print(list(dict.keys(file_history))[-1])
</code>```

I don't really know how to create this empty pandas data frame to which this latest added file will be added on a regular basis (that's why I have a time.sleep there). In the end I want to have this big csv file with all the files added to it.

Please, help :(

P.S. I am new to Python, so please don't judge if it is super simple..

答: I think that pandas.concat() is what you are looking for

Body:
I am trying to write a script which will be grabbing newly added csv file from the folder and adding it to one big file. Basically, I want all of the csv files added to a particular folder, being stored in one resulting csv file. I have a code below which generates the list of files and I am selecting the newly added file there:

def check_dir(fh,start_path='/Users/.../Desktop/files',new_cb=None,changed_cb=None):
    total_size = 0
    for dirpath, dirnames, filenames in os.walk(start_path):
        for f in filenames:
            fp = os.path.join(dirpath, f)
            if not os.path.islink(fp):
                fs = os.path.getsize(fp)
                total_size += fs
                if f in fh:
                    if fh[f] == fs:
                        # file unchanged
                        pass
                    else:
                        if changed_cb:
                            changed_cb(fp)
                else:
                    #new file
                    if new_cb:
                        new_cb(fp)
                fh[f] = fs

    return total_size

def new_file(fp):
    print("New File {0}!".format(fp))

def changed_file(fp):
    print("File {0} changed!".format(fp))

if __name__ == '__main__':
    file_history={}
    total = 0

    while(True):
        nt = check_dir(file_history,'/Users/.../Desktop/files',new_file,changed_file)
        if total and nt != total:
            print("Total size changed from {0} to {1}".format(total,nt))
            total = nt
        time.sleep(200)
        print("File list:\n{0}".format(file_history))
        print(list(dict.keys(file_history))[-1])

I don't really know how to create this empty pandas data frame to which this latest added file will be added on a regular basis (that's why I have a time.sleep there). In the end I want to have this big csv file with all the files added to it.

Please, help :(

P.S. I am new to Python, so please don't judge if it is super simple..


问:
Changing color of some portion of an image
Is there any way I can change the color of some portion of an image in Android?

I searched a lot, but I did not find any solution.

Body: Use android.graphics.BitMap.setPixel(x,y,Color) method.


问:
How does one use a custom firefox profile with PHPUnit's Webdriver framework?
I know with selenium RC, I used to pass a commandline operator... -firefoxProfileTemplate and that would work. Now working with Selenium2 (Webdriver), that doesn't seem to work anymore.

Since I'm using PHPUnit for other tests, I would like to continue to use it. Anyone know how to define a custom firefox profile for it?

答:
Lets say you use php-webdriver with FirefoxDriver.
And you want to start FirefoxDriver with specific Firefox profile. (for staying logged in and save your login and cookies every selenium run)

First of all, find directory with you firefox profile data. For me on Win 10 it is C:/Users/MyWinProfile/AppData/Roaming/Mozilla/Firefox/Profiles/pivdau5sa.selen

After that use such code for opening firefox php-webdriver:

```<code>namespace Facebook\WebDriver;
use Facebook\WebDriver\Remote\DesiredCapabilities;
use Facebook\WebDriver\Remote\RemoteWebDriver;
use Facebook\WebDriver\Firefox\FirefoxDriver;
use Facebook\WebDriver\Firefox\FirefoxOptions;
require_once('vendor/autoload.php');

$firefoxOptions = new FirefoxOptions();
$firefoxOptions->addArguments(['-profile', 'C:/Users/<MyUserName>/AppData/Roaming/Mozilla/Firefox/Profiles/pivdau5sa.selen']);
$capabilities = DesiredCapabilities::firefox();
$capabilities->setCapability(FirefoxOptions::CAPABILITY, $firefoxOptions);
putenv('WEBDRIVER_FIREFOX_DRIVER=C:\PHP\geckodriver.exe'); // you may dont need this line

$driver = FirefoxDriver::start($capabilities);
</code>```

Body:
Lets say you use php-webdriver with FirefoxDriver.
And you want to start FirefoxDriver with specific Firefox profile. (for staying logged in and save your login and cookies every selenium run)

First of all, find directory with you firefox profile data. For me on Win 10 it is C:/Users/MyWinProfile/AppData/Roaming/Mozilla/Firefox/Profiles/pivdau5sa.selen

After that use such code for opening firefox php-webdriver:

namespace Facebook\WebDriver;
use Facebook\WebDriver\Remote\DesiredCapabilities;
use Facebook\WebDriver\Remote\RemoteWebDriver;
use Facebook\WebDriver\Firefox\FirefoxDriver;
use Facebook\WebDriver\Firefox\FirefoxOptions;
require_once('vendor/autoload.php');

$firefoxOptions = new FirefoxOptions();
$firefoxOptions->addArguments(['-profile', 'C:/Users/<MyUserName>/AppData/Roaming/Mozilla/Firefox/Profiles/pivdau5sa.selen']);
$capabilities = DesiredCapabilities::firefox();
$capabilities->setCapability(FirefoxOptions::CAPABILITY, $firefoxOptions);
putenv('WEBDRIVER_FIREFOX_DRIVER=C:\PHP\geckodriver.exe'); // you may dont need this line

$driver = FirefoxDriver::start($capabilities);


问:
Vue ApexCharts is not smooth
I'm using apex charts to create a graph of real-time data coming in from the back-end.

I have used the demo as a guide and implemented my own real-time chart (https://apexcharts.com/vue-chart-demos/line-charts/realtime/)

I want the data to scroll like in the linked example, currently, mine appears to redraw the line each time it's updated (https://imgur.com/a/1aTc1JV)

I use this function to update the series data with a fixed-length queue which is updated every second (queue.append(newData) and then queue.pop(0))

```<code>updateChart: function () {
  var me = this;
  this.intervalid1 = setInterval(() => {

    me.$refs.chart.updateSeries([
      {
        data: this.temperature,
      },
    ]);

  }, 1000);
},
</code>```

答:
Insted of doing queue.pop(0) set range in xaxis to length - 1 of your initial data (if type: "numeric").
https://apexcharts.com/docs/options/xaxis/#range

Title: Vue ApexCharts is not smooth

Body:
I'm using apex charts to create a graph of real-time data coming in from the back-end.

I have used the demo as a guide and implemented my own real-time chart (https://apexcharts.com/vue-chart-demos/line-charts/realtime/)

I want the data to scroll like in the linked example, currently, mine appears to redraw the line each time it's updated (https://imgur.com/a/1aTc1JV)

I use this function to update the series data with a fixed-length queue which is updated every second (queue.append(newData) and then queue.pop(0))

updateChart: function () {
  var me = this;
  this.intervalid1 = setInterval(() => {

    me.$refs.chart.updateSeries([
      {
        data: this.temperature,
      },
    ]);

  }, 1000);
},


问:
How to Integrate Amazon EKS and Jenkins
I'm currently using Kubernetes Client Plugin in Jenkins but still it's confusing to configure, because it looks for Kubernetes config, and those credetials are not available even I configured them in the credentials section.

Please see the screenshot below for my credentials which are configure in my Jenkins.

When I do try to add those credentials from Jenkins side, which is not listed under the Kubernetes credentials. The red colored are has no kist of my credentials.

How can I configure this Kubernetes plugin in Jenkins ? or any other alternative methods to configure Jenkins + Amazon EKS ?

Thanks.

Plugin : https://wiki.jenkins.io/display/JENKINS/Kubernetes+Plugin

答:
Just dealt with this problem.

For some reason, Kubernetes Credentials don't show up in the credentials drop-down menu for configuring the Kubernetes Cloud.

The way I got the Kubernetes Cloud to connect to EKS was by selecting "-none-" for the credentials and pasting in the cert where it says "Kubernetes server certificate key".

Title: How to Integrate Amazon EKS and Jenkins


问:
Change format of sunrise/sunset from API-reactjs
I would like to ask someone could help me here with this error. I've got this error when I try to change format

"Uncaught TypeError: Cannot read properties of undefined (reading 'sunrise')"

edit. Update: I found out something odd. I have this weather app. it works with current API. U load app and type location (city) and hit enter for search. When weather info is loaded and then I write this code it will console.log sunrise/sunset. but if I write this code before searching location it gives me this error. Data exist for sure. Path is forecast.sys.sunrise or forecast.sys.sunrise. If I write this path in some div it will display. U can check path in API which I use

I want to change format and display only HH:MM.

I am using this API

Here is my fetch function

```<code>const [query, setQuery] = useState('');
const [forecast, setForecast] = useState({});

const search = evt =>{
 if(evt.key === "Enter"){
  fetch(`${api.base}weather?q=${query}&units=metric&appid=${api.key}`)
  .then(res => res.json())
  .then(result => {
    setForecast(result);
    setQuery('');
    console.log(result);
  })
 }
}
</code>```

and here is my code where I try to change format

```<code>const sunrise = new Date(forecast.sys.sunrise * 1000);
const sunset = new Date(forecast.sys.sunset * 1000);
console.log(sunrise);
console.log(sunset);
console.log(sunrise.getHours());
console.log(sunset.getHours());
</code>```

Thanks for your helps

答: Perhaps the new Date function is called before the fetch returns your data.</p>

Body:
I would like to ask someone could help me here with this error. I've got this error when I try to change format

"Uncaught TypeError: Cannot read properties of undefined (reading 'sunrise')"

edit. Update: I found out something odd. I have this weather app. it works with current API. U load app and type location (city) and hit enter for search. When weather info is loaded and then I write this code it will console.log sunrise/sunset. but if I write this code before searching location it gives me this error. Data exist for sure. Path is forecast.sys.sunrise or forecast.sys.sunrise. If I write this path in some div it will display. U can check path in API which I use

I want to change format and display only HH:MM.

I am using this API

Here is my fetch function

const [query, setQuery] = useState('');
const [forecast, setForecast] = useState({});

const search = evt =>{
 if(evt.key === "Enter"){
  fetch(`${api.base}weather?q=${query}&units=metric&appid=${api.key}`)
  .then(res => res.json())
  .then(result => {
    setForecast(result);
    setQuery('');
    console.log(result);
  })
 }
}

and here is my code where I try to change format

const sunrise = new Date(forecast.sys.sunrise * 1000);
const sunset = new Date(forecast.sys.sunset * 1000);
console.log(sunrise);
console.log(sunset);
console.log(sunrise.getHours());
console.log(sunset.getHours());

Thanks for your helps


问:
how to avoid this exception when i use file stream in dot net core 6
I'm using visual studio 2022 dot net core6 and i want to save image file stream in my folder i have used stream files written to successfully but i want to avoid this exception

Exception:

The process cannot access the file 'D:\muthu\ads\Screenshot (1).png' because it is being used by another process.

code:

```<code>var file = contents.File;
                var fileCount = contents.File.Length;
                var folderName = Path.Combine("Uploads");

                var pathToSave = Path.Combine(Directory.GetCurrentDirectory(), folderName);
                if (file.Length > 0)
                {
                    string uploadsFolder = Path.Combine(environment.ContentRootPath, "Uploads");
                    var uniqueFileName = file.FileName;
                    string filePath = Path.Combine(uploadsFolder, uniqueFileName);
                    //File.Create(filePath);
                    //using (var fileStream = new FileStream(filePath, FileMode.Create))
                    //{
                    //  file.CopyTo(fileStream);
                    //}
                    using (var stream = System.IO.File.Create(filePath))
                    {
                        await file.CopyToAsync(stream); //exception line
                    }
</code>```

答:
i want to avoid this exception

A "file in use" exception is an exogenous exception, so it cannot be avoided. It can, however, be caught and handled.

If you want to build retries (e.g., retry once per second for 10 seconds while the file is in use), then you can use Polly to build your retry logic.

Body:
I'm using visual studio 2022 dot net core6 and i want to save image file stream in my folder i have used stream files written to successfully but i want to avoid this exception

Exception:

The process cannot access the file 'D:\muthu\ads\Screenshot (1).png' because it is being used by another process.

code:

var file = contents.File;
                var fileCount = contents.File.Length;
                var folderName = Path.Combine("Uploads");

                var pathToSave = Path.Combine(Directory.GetCurrentDirectory(), folderName);
                if (file.Length > 0)
                {
                    string uploadsFolder = Path.Combine(environment.ContentRootPath, "Uploads");
                    var uniqueFileName = file.FileName;
                    string filePath = Path.Combine(uploadsFolder, uniqueFileName);
                    //File.Create(filePath);
                    //using (var fileStream = new FileStream(filePath, FileMode.Create))
                    //{
                    //  file.CopyTo(fileStream);
                    //}
                    using (var stream = System.IO.File.Create(filePath))
                    {
                        await file.CopyToAsync(stream); //exception line
                    }


问:
Get the rank of each string extracted from split_string
I have a TABLE with STR DNA DATA the following Table [DYS]

Id
DYS385

3
10-19

4
13-16

5
13-18

6
13-19

7
13-17

8
13-18

9
13-18

10
14-19

11
13-19

12
13-18

I am USING the following script to split the values of [DYS385]

```<code>select top 10 id,[DYS385],t.Value
from dys
OUTER APPLY(select * from string_split([DYS385],'-')) t
where dys385 is not null
</code>```

Output

Id
DYS385
VALUE

3
10-19
10

3
10-19
19

4
13-16
13

4
13-16
16

5
13-18
13

5
13-18
18

6
13-19
13

6
13-19
19

7
13-17
13

7
13-17
17

I want to get for each Value, the Rank
example
10-19 => 10: Rank 1, 19: Rank 2

Desired results:

Id
DYS385
VALUE
RANK

3
10-19
10
1

3
10-19
19
2

4
13-16
13
1

4
13-16
16
2

5
13-18
13
1

5
13-18
18
2

6
13-19
13
1

6
13-19
19
2

7
13-17
13
1

7
13-17
17
2

答:
Use an alternative string-split method, such as XML or Json that can return an ordinal position, such as:

```<code>create function dbo.SplitString(@string varchar(1000), @Delimiter varchar(10))
returns table
as
   return(
      select j.[value], 1 + Convert(tinyint,j.[key]) Seq
      from OpenJson(Concat('["',replace(@string,@delimiter, '","'),'"]')) j
   );

select value, Seq as [Rank]
from dbo.SplitString('10-19','-')
order by [Rank];
</code>```

Example fiddle

Body:
I have a TABLE with STR DNA DATA the following Table [DYS]

Id
DYS385

3
10-19

4
13-16

5
13-18

6
13-19

7
13-17

8
13-18

9
13-18

10
14-19

11
13-19

12
13-18

I am USING the following script to split the values of [DYS385]

select top 10 id,[DYS385],t.Value
from dys
OUTER APPLY(select * from string_split([DYS385],'-')) t
where dys385 is not null

Output

Id
DYS385
VALUE

3
10-19
10

3
10-19
19

4
13-16
13

4
13-16
16

5
13-18
13

5
13-18
18

6
13-19
13

6
13-19
19

7
13-17
13

7
13-17
17

I want to get for each Value, the Rank
example
10-19 => 10: Rank 1, 19: Rank 2

Desired results:

Id
DYS385
VALUE
RANK

3
10-19
10
1

3
10-19
19
2

4
13-16
13
1

4
13-16
16
2

5
13-18
13
1

5
13-18
18
2

6
13-19
13
1

6
13-19
19
2

7
13-17
13
1

7
13-17
17
2

Body:
Use an alternative string-split method, such as XML or Json that can return an ordinal position, such as:

create function dbo.SplitString(@string varchar(1000), @Delimiter varchar(10))
returns table
as
   return(
      select j.[value], 1 + Convert(tinyint,j.[key]) Seq
      from OpenJson(Concat('["',replace(@string,@delimiter, '","'),'"]')) j
   );

select value, Seq as [Rank]
from dbo.SplitString('10-19','-')
order by [Rank];

Example fiddle


问:
Adding secondary X-axis to a Powerbi document connected to SSAS?
Our powerbi document is connected to an SSAS cube (Connect Live option).

In our case, we have a Fact table, a DimDate table, and a DimHour table.

I need to show the trend, per day and hour, of all the sales. In my powerbi, I filtered from 5/1-5/5. When I only add HourKey to my X-Axis, it shows me the total by hour (no date slicing). It's technically correct because I'm only showing hours, so it's grouping both days by hours:

When I add Full Date Alternate Key so that the X-axis groups by Date and hour, this is what the chart looks like:

My question: how can I have a secondary X-axis so that I can see the days and the hours?

答:
Under "Data/Drill" menu, click on "Expand next level". In my case, this will show a secondary x-axis of hours:

Goes from this:

To this:


问:
Show the output of Powershell script in a WPF application
I have a WPF application that executes a Powershell script and then displays a message in a textbox in the application. The Powershell script is executed like this:

```<code>string scriptPath = folderPath + "/EXECUTE.ps1";
string powershellPath = @"C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe";
string outputLog = folderPath + "output.log";

bool is64 = IntPtr.Size == 8;
var ENV = "Get-ItemProperty HKLM:\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\* "
       + (is64 ? ",HKLM:\\Software\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\*" : "")
       + " | Select-Object DisplayName";
ProcessStartInfo startInstall = new ProcessStartInfo(powershellPath, ENV);
startInstall.UseShellExecute = false;
startInstall.Arguments = scriptPath;
startInstall.EnvironmentVariables.Add("RedirectStandardOutput", "true");
startInstall.EnvironmentVariables.Add("RedirectStandardError", "true");
startInstall.EnvironmentVariables.Add("UseShellExecute", "false");
startInstall.EnvironmentVariables.Add("CreateNoWindow", "true");
Process Install = Process.Start(startInstall);
Install.Close();
Console.WriteLine("Script executed successfully");
Console.WriteLine("Output available at: " + outputLog);
</code>```

The last two lines in Console.WriteLine are printed out in a textbox. I was wondering, is there a way that I can show the output of the Powershell terminal window inside of this textbox named txtboxExecutionResult? I am not executing any Powershell command from my application, just starting and executing the EXECUTE.ps1 file from the application. I'd really appreciate any help to point me in some direction.

答:
I had a similar issue once with reading output from another application and I solved it by reading the standard output of the process.</p>
```<code>Process process = new Process();
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = false;
process.StartInfo.CreateNoWindow = false;
process.StartInfo.FileName = "example.exe";

process.StartInfo.Arguments = args;
process.Start();
output = await process.StandardOutput.ReadToEndAsync();
</code>```

Body:
I have a WPF application that executes a Powershell script and then displays a message in a textbox in the application. The Powershell script is executed like this:

string scriptPath = folderPath + "/EXECUTE.ps1";
string powershellPath = @"C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe";
string outputLog = folderPath + "output.log";

bool is64 = IntPtr.Size == 8;
var ENV = "Get-ItemProperty HKLM:\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\* "
       + (is64 ? ",HKLM:\\Software\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\*" : "")
       + " | Select-Object DisplayName";
ProcessStartInfo startInstall = new ProcessStartInfo(powershellPath, ENV);
startInstall.UseShellExecute = false;
startInstall.Arguments = scriptPath;
startInstall.EnvironmentVariables.Add("RedirectStandardOutput", "true");
startInstall.EnvironmentVariables.Add("RedirectStandardError", "true");
startInstall.EnvironmentVariables.Add("UseShellExecute", "false");
startInstall.EnvironmentVariables.Add("CreateNoWindow", "true");
Process Install = Process.Start(startInstall);
Install.Close();
Console.WriteLine("Script executed successfully");
Console.WriteLine("Output available at: " + outputLog);

The last two lines in Console.WriteLine are printed out in a textbox. I was wondering, is there a way that I can show the output of the Powershell terminal window inside of this textbox named txtboxExecutionResult? I am not executing any Powershell command from my application, just starting and executing the EXECUTE.ps1 file from the application. I'd really appreciate any help to point me in some direction.

Body:
I had a similar issue once with reading output from another application and I solved it by reading the standard output of the process.

Process process = new Process();
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = false;
process.StartInfo.CreateNoWindow = false;
process.StartInfo.FileName = "example.exe";

process.StartInfo.Arguments = args;
process.Start();
output = await process.StandardOutput.ReadToEndAsync();


问:
jquery (windows).height increase every time I resize the window
I want to resize a div on resize of the window to make it fill the entire browser window...

I searched a lot on internet finding a solution, but everything I tried cause the same problem...

at first load of the page it works well, but when I try to resize the window the value of bodyheight keeps increasing...

this is my code

```<code>$(document).ready(function() {
  body_sizer();
  $(window).resize(body_sizer);
});
function body_sizer() {
  var bodyheight = $(window).height();
  $("#contenitore_full").css('height', bodyheight);
}
</code>```

EDIT

OK!!! my fault as i thought :)
problem was caused by a wrong way to call jquery in wordpress.
i'm sorry for let you loose time
thanks a lot everyone
ale

答:
I had the exact same problem. I recommend using javascript instead of jQuery.</p>
```<code>  const width = window.innerWidth;
  const height = window.innerHeight;
</code>```

Body:
I want to resize a div on resize of the window to make it fill the entire browser window...

I searched a lot on internet finding a solution, but everything I tried cause the same problem...

at first load of the page it works well, but when I try to resize the window the value of bodyheight keeps increasing...

this is my code

$(document).ready(function() {
  body_sizer();
  $(window).resize(body_sizer);
});
function body_sizer() {
  var bodyheight = $(window).height();
  $("#contenitore_full").css('height', bodyheight);
}

EDIT

OK!!! my fault as i thought :)
problem was caused by a wrong way to call jquery in wordpress.
i'm sorry for let you loose time
thanks a lot everyone
ale

Body:
I had the exact same problem. I recommend using javascript instead of jQuery.

  const width = window.innerWidth;
  const height = window.innerHeight;


问:
how to convert a binary number into a string
Would anyone know how to convert a binary number into a string that represents its digits ?

```<code>let  s: u32 = 0b00100000001011001100001101110001110000110010110011100000;
</code>```

I need study different parts of this binary number by cuting it into pieces (ex first 5 digits, then digit 6 to 15, etc...).

In order to do so, I'm thinking using string slices but first I need to convert the binary number into a string ( "00100000010110011...").

Thank you !

Body:
Would anyone know how to convert a binary number into a string that represents its digits ?

let  s: u32 = 0b00100000001011001100001101110001110000110010110011100000;

I need study different parts of this binary number by cuting it into pieces (ex first 5 digits, then digit 6 to 15, etc...).

In order to do so, I'm thinking using string slices but first I need to convert the binary number into a string ( "00100000010110011...").

Thank you !

Body:
Use binary format:

fn main() {
    let s: u64 = 0b00100000001011001100001101110001110000110010110011100000u64;
    let s_str: String = format!("{s:b}");
    println!("{s_str}");
}

Playground


问:
How to write Big files into Blobstore using experimental API?
I have dilemma.. I'm uploading files both in scribd store and blobstore using tipfy as framework.
I have webform with action is not created by blobstore.create_upload_url (i'm just using url_for('myhandler')). I did it because if i'm using blobstore handler the POST response parsed and I cannot use normal python-scribd api to upload file into scribd store.
Now I have working scribd saver:

```<code>class UploadScribdHandler(RequestHandler, BlobstoreUploadMixin):
    def post(self):
        uploaded_file = self.request.files.get('upload_file')
        fname = uploaded_file.filename.strip()
        try:
            self.post_to_scribd(uploaded_file, fname)
        except Exception, e:
            # ... get the exception message and do something with it
            msg = e.message
            # ...
        # reset the stream to zero (beginning) so the file can be read again
        uploaded_file.seek(0)
        #removed try-except to see debug info in browser window
        # Create the file

        file_name = files.blobstore.create(_blobinfo_uploaded_filename=fname)
        # Open the file and write to it
        with files.open(file_name, 'a') as f:
            f.write(uploaded_file.read())
        # Finalize the file. Do this before attempting to read it.
        files.finalize(file_name)
        # Get the file's blob key
        blob_key = files.blobstore.get_blob_key(file_name)

        return Response('done')

    def post_to_scribd(self, uploaded_file, fname):
        errmsg =''
        uploaded_file = self.request.files.get('upload_file')
        fname = uploaded_file.filename.strip()
        fext = fname[fname.rfind('.')+1:].lower()
        if (fext not in ALLOWED_EXTENSION):
            raise Exception('This file type does not allowed to be uploaded\n')
        if SCRIBD_ENABLED:
            doc_title = self.request.form.get('title')
            doc_description = self.request.form.get('description')
            doc_tags = self.request.form.get('tags')
            try:
                document = scribd.api_user.upload(uploaded_file, fname, access='private')
                #while document.get_conversion_status() != 'DONE':
                #   time.sleep(2)
                if not doc_title:
                    document.title = fname[:fname.rfind('.')]
                else:
                    document.title = doc_title
                if not doc_description:
                    document.description = 'This document was uploaded at ' + str(datetime.datetime.now()) +'\n'
                else:
                    document.description = doc_description
                document.tags = doc_tags
                document.save()
            except scribd.ResponseError, err:
                raise Exception('Scribd failed: error code:%d, error message: %s\n' % (err.errno, err.strerror))
            except scribd.NotReadyError, err:
                raise Exception('Scribd failed: error code:%d, error message: %s\n' % (err.errno, err.strerror))
            except:
                raise Exception('something wrong exception')
</code>```

As you can see it also saves file into blobstore.. But If i'm uploading big file (i.e. 5Mb) I'm receiving

```<code>RequestTooLargeError: The request to API call file.Append() was too large.
Request: docs.upload(access='private', doc_type='pdf', file=('PK\x03\x04\n\x00\x00\x00\x00\x00"\x01\x10=\x00\x00(...)', 'test.pdf'))
</code>```

How can I fix it?
Thanks!

答:
finally i found solution.

Nick Johneson's answer occurred attribute error because uploaded_file is treated as string.
string didn't have read() method.

Cause string doesn't have method read(), i spliced file string and write it just like he wrote.

```<code>class UploadRankingHandler(webapp.RequestHandler):
  def post(self):
    fish_image_file = self.request.get('file')

    file_name = files.blobstore.create(mime_type='image/png', _blobinfo_uploaded_filename="testfilename.png")

    file_str_list = splitCount(fish_image_file,65520)

    with files.open(file_name, 'a') as f:
      for line in file_str_list:
        f.write(line)
</code>```

you can check about splitCount(). here

http://www.bdhwan.com/entry/gaewritebigfile

Body:
I have dilemma.. I'm uploading files both in scribd store and blobstore using tipfy as framework.
I have webform with action is not created by blobstore.create_upload_url (i'm just using url_for('myhandler')). I did it because if i'm using blobstore handler the POST response parsed and I cannot use normal python-scribd api to upload file into scribd store.
Now I have working scribd saver:

class UploadScribdHandler(RequestHandler, BlobstoreUploadMixin):
    def post(self):
        uploaded_file = self.request.files.get('upload_file')
        fname = uploaded_file.filename.strip()
        try:
            self.post_to_scribd(uploaded_file, fname)
        except Exception, e:
            # ... get the exception message and do something with it
            msg = e.message
            # ...
        # reset the stream to zero (beginning) so the file can be read again
        uploaded_file.seek(0)
        #removed try-except to see debug info in browser window
        # Create the file

        file_name = files.blobstore.create(_blobinfo_uploaded_filename=fname)
        # Open the file and write to it
        with files.open(file_name, 'a') as f:
            f.write(uploaded_file.read())
        # Finalize the file. Do this before attempting to read it.
        files.finalize(file_name)
        # Get the file's blob key
        blob_key = files.blobstore.get_blob_key(file_name)

        return Response('done')

    def post_to_scribd(self, uploaded_file, fname):
        errmsg =''
        uploaded_file = self.request.files.get('upload_file')
        fname = uploaded_file.filename.strip()
        fext = fname[fname.rfind('.')+1:].lower()
        if (fext not in ALLOWED_EXTENSION):
            raise Exception('This file type does not allowed to be uploaded\n')
        if SCRIBD_ENABLED:
            doc_title = self.request.form.get('title')
            doc_description = self.request.form.get('description')
            doc_tags = self.request.form.get('tags')
            try:
                document = scribd.api_user.upload(uploaded_file, fname, access='private')
                #while document.get_conversion_status() != 'DONE':
                #   time.sleep(2)
                if not doc_title:
                    document.title = fname[:fname.rfind('.')]
                else:
                    document.title = doc_title
                if not doc_description:
                    document.description = 'This document was uploaded at ' + str(datetime.datetime.now()) +'\n'
                else:
                    document.description = doc_description
                document.tags = doc_tags
                document.save()
            except scribd.ResponseError, err:
                raise Exception('Scribd failed: error code:%d, error message: %s\n' % (err.errno, err.strerror))
            except scribd.NotReadyError, err:
                raise Exception('Scribd failed: error code:%d, error message: %s\n' % (err.errno, err.strerror))
            except:
                raise Exception('something wrong exception')

As you can see it also saves file into blobstore.. But If i'm uploading big file (i.e. 5Mb) I'm receiving

RequestTooLargeError: The request to API call file.Append() was too large.
Request: docs.upload(access='private', doc_type='pdf', file=('PK\x03\x04\n\x00\x00\x00\x00\x00"\x01\x10=\x00\x00(...)', 'test.pdf'))

How can I fix it?
Thanks!

Body:
finally i found solution.

Nick Johneson's answer occurred attribute error because uploaded_file is treated as string.
string didn't have read() method.

Cause string doesn't have method read(), i spliced file string and write it just like he wrote.

class UploadRankingHandler(webapp.RequestHandler):
  def post(self):
    fish_image_file = self.request.get('file')

    file_name = files.blobstore.create(mime_type='image/png', _blobinfo_uploaded_filename="testfilename.png")

    file_str_list = splitCount(fish_image_file,65520)

    with files.open(file_name, 'a') as f:
      for line in file_str_list:
        f.write(line)

you can check about splitCount(). here

http://www.bdhwan.com/entry/gaewritebigfile


问:
Kubernetes Minikube - Invalid memory value assigned for 'minikube'
Setting up Minikube on my Windows 10 Surface laptop and the cluster fails to create. Performed the following steps:

Installed all Hyper-V features

Created Hyper-V external switch

Installed Minikube using choco install minikube

Configured minikube using minikube config --driver=hyperv

Attempted to start minikube using minikube start --hyperv-virtual-switch=ExternalWifi

When attempting to start, minikube throws the following error:

```<code>PS C:\WINDOWS\system32> minikube start --driver=hyperv
* minikube v1.8.1 on Microsoft Windows 10 Enterprise 10.0.18363 Build 18363
* Using the hyperv driver based on user configuration
* Downloading VM boot image ...
* Creating hyperv VM (CPUs=2, Memory=4077MB, Disk=20000MB) ...
* Downloading preloaded images tarball for k8s v1.17.3 ...
> preloaded-images-k8s-v1-v1.17.3-docker-overlay2.tar.lz4: 280.46 MiB / 499E0309 09:38:58.605779   11932 main.go:106] libmachine: [stderr =====>] : Hyper-V\New-VM : Failed to modify device 'Memory'.
Invalid memory value assigned for 'minikube'. Memory values must be properly aligned.
'minikube' failed to modify device 'Memory'. (Virtual machine ID 06BCBFDB-C000-4BF4-97BF-D16008DAC326)
Invalid memory value assigned for 'minikube'. The memory value assigned ('4077' MB) is not properly aligned. Try again with a memory value that is properly aligned. (Virtual machine ID
06BCBFDB-C000-4BF4-97BF-D16008DAC326)
At line:1 char:1
+ Hyper-V\New-VM minikube -Path 'C:\Users\myuser\.minikube\machines\m ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [New-VM], VirtualizationException
    + FullyQualifiedErrorId : InvalidParameter,Microsoft.HyperV.PowerShell.Commands.NewVM

    > preloaded-images-k8s-v1-v1.17.3-docker-overlay2.tar.lz4: 289.28 MiB / 499*
X Unable to start VM. Please investigate and run 'minikube delete' if possible: creating host: create: creating: exit status 1
</code>```

答:
I used to have a similar issue.It stuck right after:
"Creating hyperv VM (CPUs=2, Memory=4096MB, Disk=20000MB)"

That`s why I delete minikube with:
minikube delete

And run it again with less ram:

minikube start --driver=hyperv --cpus 2 --memory=2048

Body:
Setting up Minikube on my Windows 10 Surface laptop and the cluster fails to create. Performed the following steps:

Installed all Hyper-V features

Created Hyper-V external switch

Installed Minikube using choco install minikube

Configured minikube using minikube config --driver=hyperv

Attempted to start minikube using minikube start --hyperv-virtual-switch=ExternalWifi

When attempting to start, minikube throws the following error:

PS C:\WINDOWS\system32> minikube start --driver=hyperv
* minikube v1.8.1 on Microsoft Windows 10 Enterprise 10.0.18363 Build 18363
* Using the hyperv driver based on user configuration
* Downloading VM boot image ...
* Creating hyperv VM (CPUs=2, Memory=4077MB, Disk=20000MB) ...
* Downloading preloaded images tarball for k8s v1.17.3 ...
> preloaded-images-k8s-v1-v1.17.3-docker-overlay2.tar.lz4: 280.46 MiB / 499E0309 09:38:58.605779   11932 main.go:106] libmachine: [stderr =====>] : Hyper-V\New-VM : Failed to modify device 'Memory'.
Invalid memory value assigned for 'minikube'. Memory values must be properly aligned.
'minikube' failed to modify device 'Memory'. (Virtual machine ID 06BCBFDB-C000-4BF4-97BF-D16008DAC326)
Invalid memory value assigned for 'minikube'. The memory value assigned ('4077' MB) is not properly aligned. Try again with a memory value that is properly aligned. (Virtual machine ID
06BCBFDB-C000-4BF4-97BF-D16008DAC326)
At line:1 char:1
+ Hyper-V\New-VM minikube -Path 'C:\Users\myuser\.minikube\machines\m ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [New-VM], VirtualizationException
    + FullyQualifiedErrorId : InvalidParameter,Microsoft.HyperV.PowerShell.Commands.NewVM

    > preloaded-images-k8s-v1-v1.17.3-docker-overlay2.tar.lz4: 289.28 MiB / 499*
X Unable to start VM. Please investigate and run 'minikube delete' if possible: creating host: create: creating: exit status 1


问:
How do I make a list comprehension for 1/3 of a dictionary?
I am relatively new to python and I started to learn list comprehensions, they seemed a bit complicated at first but start to get intuitive over time.
However, there is one problem I could not solve yet

A function receives a dictionary as a parameter with the values looking like this:

```<code>datadict = dict(a1=[], a2=[], a3=[], b1=[], b2=[], b3=[], c1=[], c2[], c3=[])
</code>```

One dictionary with some lists in it, which of course, also contain (float) values
all lists have the same len()

The function should seperate the nested lists from the dict according to the letters in to a list of tuples like this:

```<code>    list_a = []

for entry in range(len(datadict["a"])):
    list_a.append((
        datadict["a1"][entry],
        datadict["a2"][entry],
        datadict["a3"][entry]
    ))
</code>```

This works but looks very clunky / hard to read, in my opinion and I wasn't able to make a list comprehension out of it.
I tried using the zip() method, tried unpacking, but I couldn't figure it out.

答:
I am not sure I have understood correctly the description of the task.
In general, you should make a custom function to embed the logic and use that in the list comprehension. It is way more readable.

Here an example based on your post:

```<code>datadict = dict(a1=[1,2,3], a2=[4,5,6], a3=[7,8,9], b1=[0,0,0], b2=[1,1,1], b3=[2,2,2])

def f(d, i):
    return (d['a1'][i], d['a2'][i], d['a3'][i])

result = [f(datadict, n) for n in range(len(datadict['a1']))]

print(result)
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
</code>```

Body:
I am relatively new to python and I started to learn list comprehensions, they seemed a bit complicated at first but start to get intuitive over time.
However, there is one problem I could not solve yet

A function receives a dictionary as a parameter with the values looking like this:

datadict = dict(a1=[], a2=[], a3=[], b1=[], b2=[], b3=[], c1=[], c2[], c3=[])

One dictionary with some lists in it, which of course, also contain (float) values
all lists have the same len()

The function should seperate the nested lists from the dict according to the letters in to a list of tuples like this:

    list_a = []

for entry in range(len(datadict["a"])):
    list_a.append((
        datadict["a1"][entry],
        datadict["a2"][entry],
        datadict["a3"][entry]
    ))

This works but looks very clunky / hard to read, in my opinion and I wasn't able to make a list comprehension out of it.
I tried using the zip() method, tried unpacking, but I couldn't figure it out.

Body:
I am not sure I have understood correctly the description of the task.
In general, you should make a custom function to embed the logic and use that in the list comprehension. It is way more readable.

Here an example based on your post:

datadict = dict(a1=[1,2,3], a2=[4,5,6], a3=[7,8,9], b1=[0,0,0], b2=[1,1,1], b3=[2,2,2])

def f(d, i):
    return (d['a1'][i], d['a2'][i], d['a3'][i])

result = [f(datadict, n) for n in range(len(datadict['a1']))]

print(result)
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]


问:
Flutter login Provider AuthService
My application was working fine but after I update the whole package and flutter with the android studio it shows an error in the login section when I login/signup below is the error :

```<code>======== Exception caught by gesture ===================================================
The following ProviderNotFoundException was thrown while handling a gesture:
Error: Could not find the correct Provider<AuthService> above this SignIn Widget
</code>```

This happens because you used a BuildContext that does not include the provider
of your choice. There are a few common scenarios:

You added a new provider in your main.dart and performed a hot-reload.
To fix, perform a hot-restart.

The provider you are trying to read it in a different route.

Providers are "scoped". So if you insert of provider inside a route, then
other routes will not be able to access that provider.

You used a BuildContext that is an ancestor of the provider you are trying to read.

Make sure that SignIn is under your MultiProvider/Provider.
This usually happens when you are creating a provider and trying to read it immediately.

For example, instead of:

```<code>Widget build(BuildContext context) {
  return Provider<Example>(
    create: (_) => Example(),
    // Will throw a ProviderNotFoundError, because `context` is associated
    // to the widget that is the parent of `Provider<Example>`
    child: Text(context.watch<Example>()),
  ),
}
</code>```

consider using builder like so:

```<code> Widget build(BuildContext context) {
  return Provider<Example>(
    create: (_) => Example(),
    // we use `builder` to obtain a new `BuildContext` that has access to the provider
    builder: (context) {
      // No longer throws
      return Text(context.watch<Example>()),
    }
  ),
}
</code>```

When the exception was thrown, this was the stack:

```<code>  #0      Provider._inheritedElementOf (package:provider/src/provider.dart:329:7)
  #1      Provider.of (package:provider/src/provider.dart:281:30)
  #2      ReadContext.read (package:provider/src/provider.dart:607:21)
  #3      _SignInState._toggleSignInButton (package:wallet_ui_app/pages/Login/pages/login_page.dart:391:13)
  #4      _SignInState.build.<anonymous closure> (package:wallet_ui_app/pages/Login/pages/login_page.dart:376:21)
  #5      _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:989:21)
  #6      GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:193:24)
  #7      TapGestureRecognizer.handleTapUp (package:flutter/src/gestures/tap.dart:608:11)
  #8      BaseTapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:296:5)
  #9      BaseTapGestureRecognizer.acceptGesture (package:flutter/src/gestures/tap.dart:267:7)
  #10     GestureArenaManager.sweep (package:flutter/src/gestures/arena.dart:157:27)
  #11     GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:444:20)
  #12     GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:420:22)
  #13     RendererBinding.dispatchEvent (package:flutter/src/rendering/binding.dart:278:11)
  #14     GestureBinding._handlePointerEventImmediately (package:flutter/src/gestures/binding.dart:374:7)
  #15     GestureBinding.handlePointerEvent (package:flutter/src/gestures/binding.dart:338:5)
  #16     GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:296:7)
  #17     GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:279:7)
  #21     _invoke1 (dart:ui/hooks.dart:185:10)
  #22     PlatformDispatcher._dispatchPointerDataPacket (dart:ui/platform_dispatcher.dart:293:7)
  #23     _dispatchPointerDataPacket (dart:ui/hooks.dart:98:31)

(elided 3 frames from dart:async)
Handler: "onTap"
Recognizer: TapGestureRecognizer#0cb65
  debugOwner: GestureDetector
  state: ready
  won arena
  finalPosition: Offset(216.1, 537.3)
  finalLocalPosition: Offset(98.3, 28.9)
  button: 1
  sent tap down
</code>```

I will post now below the code that I am getting an error from:

```<code>  void _onSignInButtonPress() {
    _pageController.animateToPage(0,
        duration: const Duration(milliseconds: 500), curve: Curves.decelerate);
  }

 void _toggleSignInButton() {
    print('_toggleSignInButton clicked');
    final String email = loginEmailController.text.trim();
    final String password = loginPasswordController.text.trim();
    context.read<AuthService>().login(
      email,
      password,
    ).whenComplete(() => IfAdminLoggedIn());
  }
</code>```

Authservices.dart :

```<code> class AuthService {
  final FirebaseAuth _auth;

  AuthService(this._auth);

  Stream<User> get authStateChanges => _auth.idTokenChanges();

  Future<String> login(String email, String password) async {

await _auth.signInWithEmailAndPassword(email: email, password: password);
}
</code>```

is there any solution for this?

答:
The simplest solution for all providers is to include them at the root of your application, above MaterialApp.

And for the purpose of finding and debugging issues related to these providers I recommend using dart dev tools on a browser and checking out the widget hierarchy and see if the widget where you're trying to access the provider at falls under the hierarchy or not.

I had a similar issue earlier and I solved this using dart dev tools (I was easily able to spot that the provider I added was falling out of hierarchy and was not accessible, i.e. there was a sibling relation between widgets, which I did not expect, resulting the provider to be inaccessible).

Hope this also works for you.

Title: Flutter login Provider AuthService

Body:
My application was working fine but after I update the whole package and flutter with the android studio it shows an error in the login section when I login/signup below is the error :

======== Exception caught by gesture ===================================================
The following ProviderNotFoundException was thrown while handling a gesture:
Error: Could not find the correct Provider<AuthService> above this SignIn Widget

This happens because you used a BuildContext that does not include the provider
of your choice. There are a few common scenarios:

You added a new provider in your main.dart and performed a hot-reload.
To fix, perform a hot-restart.

The provider you are trying to read it in a different route.

Providers are "scoped". So if you insert of provider inside a route, then
other routes will not be able to access that provider.

You used a BuildContext that is an ancestor of the provider you are trying to read.

Make sure that SignIn is under your MultiProvider/Provider.
This usually happens when you are creating a provider and trying to read it immediately.

For example, instead of:

Widget build(BuildContext context) {
  return Provider<Example>(
    create: (_) => Example(),
    // Will throw a ProviderNotFoundError, because `context` is associated
    // to the widget that is the parent of `Provider<Example>`
    child: Text(context.watch<Example>()),
  ),
}

consider using builder like so:

 Widget build(BuildContext context) {
  return Provider<Example>(
    create: (_) => Example(),
    // we use `builder` to obtain a new `BuildContext` that has access to the provider
    builder: (context) {
      // No longer throws
      return Text(context.watch<Example>()),
    }
  ),
}

When the exception was thrown, this was the stack:

  #0      Provider._inheritedElementOf (package:provider/src/provider.dart:329:7)
  #1      Provider.of (package:provider/src/provider.dart:281:30)
  #2      ReadContext.read (package:provider/src/provider.dart:607:21)
  #3      _SignInState._toggleSignInButton (package:wallet_ui_app/pages/Login/pages/login_page.dart:391:13)
  #4      _SignInState.build.<anonymous closure> (package:wallet_ui_app/pages/Login/pages/login_page.dart:376:21)
  #5      _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:989:21)
  #6      GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:193:24)
  #7      TapGestureRecognizer.handleTapUp (package:flutter/src/gestures/tap.dart:608:11)
  #8      BaseTapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:296:5)
  #9      BaseTapGestureRecognizer.acceptGesture (package:flutter/src/gestures/tap.dart:267:7)
  #10     GestureArenaManager.sweep (package:flutter/src/gestures/arena.dart:157:27)
  #11     GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:444:20)
  #12     GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:420:22)
  #13     RendererBinding.dispatchEvent (package:flutter/src/rendering/binding.dart:278:11)
  #14     GestureBinding._handlePointerEventImmediately (package:flutter/src/gestures/binding.dart:374:7)
  #15     GestureBinding.handlePointerEvent (package:flutter/src/gestures/binding.dart:338:5)
  #16     GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:296:7)
  #17     GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:279:7)
  #21     _invoke1 (dart:ui/hooks.dart:185:10)
  #22     PlatformDispatcher._dispatchPointerDataPacket (dart:ui/platform_dispatcher.dart:293:7)
  #23     _dispatchPointerDataPacket (dart:ui/hooks.dart:98:31)

(elided 3 frames from dart:async)
Handler: "onTap"
Recognizer: TapGestureRecognizer#0cb65
  debugOwner: GestureDetector
  state: ready
  won arena
  finalPosition: Offset(216.1, 537.3)
  finalLocalPosition: Offset(98.3, 28.9)
  button: 1
  sent tap down

I will post now below the code that I am getting an error from:

  void _onSignInButtonPress() {
    _pageController.animateToPage(0,
        duration: const Duration(milliseconds: 500), curve: Curves.decelerate);
  }

 void _toggleSignInButton() {
    print('_toggleSignInButton clicked');
    final String email = loginEmailController.text.trim();
    final String password = loginPasswordController.text.trim();
    context.read<AuthService>().login(
      email,
      password,
    ).whenComplete(() => IfAdminLoggedIn());
  }

Authservices.dart :

 class AuthService {
  final FirebaseAuth _auth;

  AuthService(this._auth);

  Stream<User> get authStateChanges => _auth.idTokenChanges();

  Future<String> login(String email, String password) async {

await _auth.signInWithEmailAndPassword(email: email, password: password);
}

is there any solution for this?


问:
Eclipse Java shortcut for "printf"?
When coding in Java in Eclipse, is there a shortcut similar to typing "syso" and pressing CTRL+Space for System.out.println(), but for printf instead of println?</p>

答:
I created my own System.out.printf() shortcut on Eclipse.

Simply, go to Windows > Preferences > Java > Editor > Templates

Click on New, then fill the form with the following information:

Name: the shortcut you would like to use in the editor (e.g. printf)

Description: print formatted text (or any other description)

Pattern: System.out.printf(${word_selection}${});${cursor}

That's it! Now you can just type "printf" in your editor, followed by [Ctrl + space], then [Enter], and the editor will place a System.out.printf() for you.

Title: Eclipse Java shortcut for "printf"?


问:
How to get the list of all content controls in the document?
I am using interop and I want to get the list of all content controls contained in word document (in the body, shapes, header, footer..). Is this the correct and the best way to do this :

```<code>public static List<ContentControl> GetAllContentControls(Document wordDocument)
{
  if (null == wordDocument)
    throw new ArgumentNullException("wordDocument");

  List<ContentControl> ccList = new List<ContentControl>(); ;
  // Body cc
  var inBodyCc = (from r in wordDocument.ContentControls.Cast<ContentControl>()
          select r);
  ccList.AddRange(inBodyCc);

  // cc within shapes
  foreach (Shape shape in wordDocument.Shapes)
  {
    if (shape.Type == Microsoft.Office.Core.MsoShapeType.msoTextBox)
    {
      ccList.AddRange(WordDocumentHelper.GetContentControlsInRange(shape.TextFrame.TextRange));
    }
  }

  // Get the list of cc in the story ranges : wdFirstPageHeaderStory, wdFirstPageFooterStory, wdTextFrameStory (textbox)...
  foreach (Range range in wordDocument.StoryRanges)
  {
    ccList.AddRange(WordDocumentHelper.GetContentControlsInRange(range));
  }
  return ccList;
}

public static List<ContentControl> GetContentControlsInRange(Range range)
{
  if (null == range)
    throw new ArgumentNullException("range");

  List<ContentControl> returnValue = new List<ContentControl>();

  foreach (ContentControl cc in range.ContentControls)
  {
    returnValue.Add(cc);
  }

  return returnValue;
}
</code>```

Regards.

答:
Yes Lars Holm,you are right, the content controls inside text boxs in header and footer are missing , here is the complete solution for this:

```<code>/// <summary>
/// Get all content controls contained in the document.
/// </summary>
/// <param name="wordDocument"></param>
/// <returns></returns>
public static List<ContentControl> GetAllContentControls(Document wordDocument)
{
    if (null == wordDocument)
        throw new ArgumentNullException("wordDocument");

    List<ContentControl> ccList = new List<ContentControl>();

    // The code below search content controls in all
    // word document stories see http://word.mvps.org/faqs/customization/ReplaceAnywhere.htm
    Range rangeStory;
    foreach (Range range in wordDocument.StoryRanges)
    {
        rangeStory = range;
        do
        {
            try
            {
                foreach (ContentControl cc in range.ContentControls)
                {
                    ccList.Add(cc);
                }

                // Get the content controls in the shapes ranges
                foreach (Shape shape in range.ShapeRange)
                {
                    foreach (ContentControl cc in shape.TextFrame.TextRange.ContentControls)
                    {
                        ccList.Add(cc);
                    }

                }
            }
            catch (COMException) { }
            rangeStory = rangeStory.NextStoryRange;

        }
        while (rangeStory != null);
    }
    return ccList;
}
</code>```

Regards

ContentLicense: CC BY-SA 2.5

Body:
I am using interop and I want to get the list of all content controls contained in word document (in the body, shapes, header, footer..). Is this the correct and the best way to do this :

public static List<ContentControl> GetAllContentControls(Document wordDocument)
{
  if (null == wordDocument)
    throw new ArgumentNullException("wordDocument");

  List<ContentControl> ccList = new List<ContentControl>(); ;
  // Body cc
  var inBodyCc = (from r in wordDocument.ContentControls.Cast<ContentControl>()
          select r);
  ccList.AddRange(inBodyCc);

  // cc within shapes
  foreach (Shape shape in wordDocument.Shapes)
  {
    if (shape.Type == Microsoft.Office.Core.MsoShapeType.msoTextBox)
    {
      ccList.AddRange(WordDocumentHelper.GetContentControlsInRange(shape.TextFrame.TextRange));
    }
  }

  // Get the list of cc in the story ranges : wdFirstPageHeaderStory, wdFirstPageFooterStory, wdTextFrameStory (textbox)...
  foreach (Range range in wordDocument.StoryRanges)
  {
    ccList.AddRange(WordDocumentHelper.GetContentControlsInRange(range));
  }
  return ccList;
}

public static List<ContentControl> GetContentControlsInRange(Range range)
{
  if (null == range)
    throw new ArgumentNullException("range");

  List<ContentControl> returnValue = new List<ContentControl>();

  foreach (ContentControl cc in range.ContentControls)
  {
    returnValue.Add(cc);
  }

  return returnValue;
}

Regards.

Body:
Yes Lars Holm,you are right, the content controls inside text boxs in header and footer are missing , here is the complete solution for this:

/// <summary>
/// Get all content controls contained in the document.
/// </summary>
/// <param name="wordDocument"></param>
/// <returns></returns>
public static List<ContentControl> GetAllContentControls(Document wordDocument)
{
    if (null == wordDocument)
        throw new ArgumentNullException("wordDocument");

    List<ContentControl> ccList = new List<ContentControl>();

    // The code below search content controls in all
    // word document stories see http://word.mvps.org/faqs/customization/ReplaceAnywhere.htm
    Range rangeStory;
    foreach (Range range in wordDocument.StoryRanges)
    {
        rangeStory = range;
        do
        {
            try
            {
                foreach (ContentControl cc in range.ContentControls)
                {
                    ccList.Add(cc);
                }

                // Get the content controls in the shapes ranges
                foreach (Shape shape in range.ShapeRange)
                {
                    foreach (ContentControl cc in shape.TextFrame.TextRange.ContentControls)
                    {
                        ccList.Add(cc);
                    }

                }
            }
            catch (COMException) { }
            rangeStory = rangeStory.NextStoryRange;

        }
        while (rangeStory != null);
    }
    return ccList;
}

Regards


问:
How do I trigger a macro to run when a sheet is renamed?
I have a worksheet, and I want to run a macro when the active sheet is renamed (renamed to anything).

The reason for this is as follows:

I have a Pivot table that is filtered based on a cell (D1) value, using VBA.
(When the D1 is changed, the pivot table filter changes).
D1 is, in turn, determined (matched) by the sheet name, using a formula.
(I.e. if the sheet name is RG01, then D1 automatically changes RG01)

The problem is, when the sheet name is changed (and D1 changes with it) it does not trigger a change in the Pivot table filter. It's only when I edit D1 that the Pivot table filter changes. I.e. If I select D1 and re-enter the formula, the Pivot Table filter changes.

So, I'm thinking, I could write a macro that re-enters the formula in D1 whenever the sheet is renamed. I can do most of this by 'recording' a macro, but I don't know how to trigger the macro when the sheet is renamed.

By "re-enter" I mean clicking the cell (D1), clicking the formula bar, then pressing enter.

Apologies, I'm not proficient in VBA or excel so my terminology may be wrong. I'm so close to making my spreadsheet work and this is the final hurdle that I just cannot seem to get around.

Thank you so much is anticipation!

答:
For a project where I wanted to capture sheet renaming I used a public variable for the active sheet name and with a Workbook_SheetCalculate I was capturing the change.
(Note that this worked for the active sheet renamed by hand and not programmaticaly renaming other sheets name from a macro. That would probably need a public array/dict with alll the sheet names stored on opening the workbook)
A sample code would be:

(ThisWorkbook):

Public LastSheet As String

Private Sub Workbook_SheetActivate(ByVal Sh As Object)

    LastSheet = ActiveSheet.Name

End Sub

Private Sub Workbook_SheetCalculate(ByVal Sh As Object)

    If LastSheet <> ActiveSheet.Name Then

        '... do something here

        LastSheet = ActiveSheet.Name

    End If

End Sub
```

The calculate sub would fire in every change in the active sheet but run the desired code only when the sheet name changes.

Body:
For a project where I wanted to capture sheet renaming I used a public variable for the active sheet name and with a Workbook_SheetCalculate I was capturing the change.
(Note that this worked for the active sheet renamed by hand and not programmaticaly renaming other sheets name from a macro. That would probably need a public array/dict with alll the sheet names stored on opening the workbook)
A sample code would be:

(ThisWorkbook):

Public LastSheet As String

Private Sub Workbook_SheetActivate(ByVal Sh As Object)

    LastSheet = ActiveSheet.Name

End Sub

Private Sub Workbook_SheetCalculate(ByVal Sh As Object)

    If LastSheet <> ActiveSheet.Name Then

        '... do something here

        LastSheet = ActiveSheet.Name

    End If

End Sub

The calculate sub would fire in every change in the active sheet but run the desired code only when the sheet name changes.


问:
Force Android App Link to open in browser
We have a React Native app which shows our mobile website and adds some extra features.

Since Android 12 App links (like domain.com) always open our app: https://developer.android.com/training/app-links

This behaviour is not always desirable, for example in this scenario:

Customer is logged in and starts an order via their browser

Customer needs to pay via an app from their bank

After payment, the customer is redirected back to our website (domain.com/returnUrl)

Now the app is opened, instead of the browser, so the customer isn't logged-in and isn't allowed to view the page.

In this case, after payment started from the browser, we would like to redirect the customer back to the browser instead of the app.

Is there a way to open a link in the browser (ie. via domain.com/returnUrl?force-browser) instead of the app?

Related: Android App link - Open a url from app in browser without triggering App Link

答:
Deep and universal linking happens on the operating level and it's hard to control the behavior of other app linking I think it should security breach as some apps try to override the deep link behaviors of another app.

Try to create your simple page with your custom URL https://my-domain.com which redirect to tour target URL without opening associated app.


问:
Meaning of 'mu' in 'uWSGI' Web-server gateway interface?
What does 'mu' stand for in uWSGI? I see that uWSGI pronounced "mu wiz gee". And WSGI means web-server gateway interface. But what about the 'mu' part?

答:
It refers to the letter mu, μ, which looks like u if you squint. Since mu is the letter for the SI prefix micro-, the idea is that uWSGI (or rather, μWSGI) would be a small WSGI.

However, the official documentation or repository for uWSGI don't use the letter mu, nor does the official logo, so I'd pronounce it "You Whiskey".


问:
Database calls in Custom Authorization Handler returning a NullReference Error in Blazor Server
I'm currently creating a Blazor Server application that uses Azure AD for Authentication. The authentication works perfectly but I want to set up some AuthorisedView's within the application.

I've created a custom Authorization Handler whereby I take the user's email and find what user group they belong to within my own sql server. For the database calls I'm using Dapper with some table models. When I make a database call within the HandleRequirementAsync function it returns a NullReference exception. I cannot see where there could be an error within the code, am I missing something obvious?

The users list should return the user in the database and then groups list should return the group that user is assigned to based on an ID. Both of these calls work perfectly throughout the rest of the application, it only causes errors within this section below.

GroupHandler.cs

```<code>public class GroupHandler : AuthorizationHandler<GroupRequirement>
{
    public IUserData _dbUser;
    public IGroupData _dbGroup;

    protected async override Task<Task> HandleRequirement(AuthorizationHandlerContect context, GroupRequirement requirement)
    {
        var emailAddress = context.User.Identity.Name;

        List<UserModel> users = await _dbUser.GetUserByEmail(emailAddress);
        List<GroupModel> groups = await _dbGroup.GetGroupByID(users[0].Group_ID.ToString());

        if(groups[0].Group.Contains(requirement.Group))
        {
            context.Succeed(requirement);
        }

        return Task.CompletedTask;
    }
}
</code>```

GroupRequirement.cs

```<code>public class GroupRequirement : IAuthorizationRequirement
{
    public string Group { get; }

    public GroupRequirement(string group)
    {
        Group = group;
    }
}
</code>```

Startup.cs

```<code>services.AddAuthorization(config =>
{
    config.AddPolicy("IsAdmin", policy =>
        policy.Requirements.Add(new GroupRequirement("Admin")));
});
</code>```

Error

```<code>NullReferenceException: Object reference not set an instance of an object

GroupHandler.HandleRequirementAsync(AuthorizationHandlerContext context, GroupRequirement requirement) in GroupHandler.cs, line 30

List<UserModel> users = await _dbUser.GetUserByEmail(emailAddress);
</code>```

答:
The problem lies inside these lines, as you don't initialize your objects at all. So, they are null by default. Please, initialize this properties.

```<code>    public IUserData _dbUser;
    public IGroupData _dbGroup;
</code>```

Body:
I'm currently creating a Blazor Server application that uses Azure AD for Authentication. The authentication works perfectly but I want to set up some AuthorisedView's within the application.

I've created a custom Authorization Handler whereby I take the user's email and find what user group they belong to within my own sql server. For the database calls I'm using Dapper with some table models. When I make a database call within the HandleRequirementAsync function it returns a NullReference exception. I cannot see where there could be an error within the code, am I missing something obvious?

The users list should return the user in the database and then groups list should return the group that user is assigned to based on an ID. Both of these calls work perfectly throughout the rest of the application, it only causes errors within this section below.

GroupHandler.cs

public class GroupHandler : AuthorizationHandler<GroupRequirement>
{
    public IUserData _dbUser;
    public IGroupData _dbGroup;

    protected async override Task<Task> HandleRequirement(AuthorizationHandlerContect context, GroupRequirement requirement)
    {
        var emailAddress = context.User.Identity.Name;

        List<UserModel> users = await _dbUser.GetUserByEmail(emailAddress);
        List<GroupModel> groups = await _dbGroup.GetGroupByID(users[0].Group_ID.ToString());

        if(groups[0].Group.Contains(requirement.Group))
        {
            context.Succeed(requirement);
        }

        return Task.CompletedTask;
    }
}

GroupRequirement.cs

public class GroupRequirement : IAuthorizationRequirement
{
    public string Group { get; }

    public GroupRequirement(string group)
    {
        Group = group;
    }
}

Startup.cs

services.AddAuthorization(config =>
{
    config.AddPolicy("IsAdmin", policy =>
        policy.Requirements.Add(new GroupRequirement("Admin")));
});

Error

NullReferenceException: Object reference not set an instance of an object

GroupHandler.HandleRequirementAsync(AuthorizationHandlerContext context, GroupRequirement requirement) in GroupHandler.cs, line 30

List<UserModel> users = await _dbUser.GetUserByEmail(emailAddress);

Body:
The problem lies inside these lines, as you don't initialize your objects at all. So, they are null by default. Please, initialize this properties.

    public IUserData _dbUser;
    public IGroupData _dbGroup;


问:
adding entries to NSMutableDictionary
I'm having trouble with adding dictionary's to a nsmutabledictionary. Can anyone see what I'm doing wrong?</p>

```<code>@interface viewMap : UIViewController<MKMapViewDelegate> {

     NSMutableDictionary *onclickDic;

}

@property (nonatomic, retain) NSMutableDictionary *onclickDic;
@end

@implementation viewMap
@synthesize onclickDic;

-(MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation {

    NSString *pushLat   = [NSString stringWithFormat:@"%f", [annotation coordinate].latitude];
    NSString *pushLng   = [NSString stringWithFormat:@"%f", [annotation coordinate].longitude];

    NSDictionary *latlngDic = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:pushLat, pushLng, nil] forKeys:[NSArray arrayWithObjects:@"lat", @"lng", nil]];

    NSDictionary *toPush    = [NSDictionary dictionaryWithObject:latlngDic forKey:[NSString stringWithFormat:@"%i", i]];

    NSLog(@"toPush is %@", toPush); // this one is correct and works

    [self.onclickDic addEntriesFromDictionary:toPush];

    NSLog(@"onclickDic is %@", onclickDic); // this one gives (null)
}
@end
</code>```

答:
It doesn't look like onclickDic is ever assigned.  Make sure you are allocating an instance before your mapView:viewForAnnotation: method gets called.

Also, not related to the problem, but your toPush dictionary is unnecessary.  Just add the key/value to onclickDic directly:

```<code>[onclickDic setValue:latlngDic forKey:[NSString stringWithFormat:@"%i", i]];
</code>```

Title: adding entries to NSMutableDictionary

Body:
I'm having trouble with adding dictionary's to a nsmutabledictionary. Can anyone see what I'm doing wrong?

@interface viewMap : UIViewController<MKMapViewDelegate> {

     NSMutableDictionary *onclickDic;

}

@property (nonatomic, retain) NSMutableDictionary *onclickDic;
@end

@implementation viewMap
@synthesize onclickDic;

-(MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation {

    NSString *pushLat   = [NSString stringWithFormat:@"%f", [annotation coordinate].latitude];
    NSString *pushLng   = [NSString stringWithFormat:@"%f", [annotation coordinate].longitude];

    NSDictionary *latlngDic = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:pushLat, pushLng, nil] forKeys:[NSArray arrayWithObjects:@"lat", @"lng", nil]];

    NSDictionary *toPush    = [NSDictionary dictionaryWithObject:latlngDic forKey:[NSString stringWithFormat:@"%i", i]];

    NSLog(@"toPush is %@", toPush); // this one is correct and works

    [self.onclickDic addEntriesFromDictionary:toPush];

    NSLog(@"onclickDic is %@", onclickDic); // this one gives (null)
}
@end

Body:
It doesn't look like onclickDic is ever assigned.  Make sure you are allocating an instance before your mapView:viewForAnnotation: method gets called.

Also, not related to the problem, but your toPush dictionary is unnecessary.  Just add the key/value to onclickDic directly:

[onclickDic setValue:latlngDic forKey:[NSString stringWithFormat:@"%i", i]];


问:
Java code for verification of FusionAuth HS256 signed id token
How to verify HS256 ID Token using FusionAuth java Client libraries ?

Description: I have created an app in FusionAuth that has a Client ID and Client Secret generated, I have not touched any other section/tab like JWT etc, default JWT signing algo is OIDC standard HMAC SHA256.

I tried using following code approach to validate the token based on public key, but its not working for HS256 signed token, I searched over internet and found public key is not applicable for HS256

Could you please provide me a Java code to verify HS256 signed token using FusionAuth Java client libraries (https://github.com/FusionAuth/fusionauth-jwt).
Please also let me know that do I need any additional configuration on FusionAuth Admin Console.

Code which I tried: It's giving blank public keys.

```<code>List<JSONWebKey> keys = JSONWebKeySetHelper.retrieveKeysFromJWKS("http://localhost:9011/.well-known/jwks.json");

Map<String, Verifier> publicKeyVerifiers = new HashMap<String, Verifier>();

JWT jwtDecoded = JWT.getDecoder().decode(idToken, publicKeyVerifiers);
</code>```

答:
It looks like there is an example in the README:

```<code>// Build an HMC verifier using the same secret that was used to sign the JWT
Verifier verifier = HMACVerifier.newVerifier("too many secrets");

// Verify and decode the encoded string JWT to a rich object
JWT jwt = JWT.getDecoder().decode(encodedJWT, verifier);

// Assert the subject of the JWT is as expected
assertEquals(jwt.subject, "f1e33ab3-027f-47c5-bb07-8dd8ab37a2d3");
</code>```

https://github.com/FusionAuth/fusionauth-jwt#verify-and-decode-a-jwt-using-hmac

With HMAC signing you need to distribute the secret ("too many secrets" in the example above) to all locations which need to verify the JWT.

Body:
How to verify HS256 ID Token using FusionAuth java Client libraries ?

Description: I have created an app in FusionAuth that has a Client ID and Client Secret generated, I have not touched any other section/tab like JWT etc, default JWT signing algo is OIDC standard HMAC SHA256.

I tried using following code approach to validate the token based on public key, but its not working for HS256 signed token, I searched over internet and found public key is not applicable for HS256

Could you please provide me a Java code to verify HS256 signed token using FusionAuth Java client libraries (https://github.com/FusionAuth/fusionauth-jwt).
Please also let me know that do I need any additional configuration on FusionAuth Admin Console.

Code which I tried: It's giving blank public keys.

List<JSONWebKey> keys = JSONWebKeySetHelper.retrieveKeysFromJWKS("http://localhost:9011/.well-known/jwks.json");

Map<String, Verifier> publicKeyVerifiers = new HashMap<String, Verifier>();

JWT jwtDecoded = JWT.getDecoder().decode(idToken, publicKeyVerifiers);

Body:
It looks like there is an example in the README:

// Build an HMC verifier using the same secret that was used to sign the JWT
Verifier verifier = HMACVerifier.newVerifier("too many secrets");

// Verify and decode the encoded string JWT to a rich object
JWT jwt = JWT.getDecoder().decode(encodedJWT, verifier);

// Assert the subject of the JWT is as expected
assertEquals(jwt.subject, "f1e33ab3-027f-47c5-bb07-8dd8ab37a2d3");

https://github.com/FusionAuth/fusionauth-jwt#verify-and-decode-a-jwt-using-hmac

With HMAC signing you need to distribute the secret ("too many secrets" in the example above) to all locations which need to verify the JWT.


问:
Bash command - how to grep and then truncate but keep grep-ed part?
I am trying to splice out a particular piece of string. I used:

```<code>myVar=$(grep --color 'GACCT[ATCG]*AGGTC' FILE.txt | cat)
</code>```

then, I used the code below to remove everything before and after my desired portion.

```<code>myVar1=$(echo ${myVar##*GACCT})
echo ${myVar1%%AGGTC*}
</code>```

The code is working however, it cuts off the GACCT and AGGTC at the beginning and end of the desired fragmen that I want to keep. Is there anyway to cut the beginning and end off while still keeping the GACCT and AGGTC?

Thank you!

答:
If you have a GNU grep, you can make use of

myVar=$(grep --color=never -oP 'GACCT\K[ATCG]+(?=AGGTC)' FILE.txt)
```
<p>See the online demo:</p>
<pre class="lang-sh prettyprint-override"><code>#!/bin/bash
s='GACCTAAATTTGGGCCCAGGTC'

# Original script
myVar=$(grep --color 'GACCT[ATCG]*AGGTC' <<< "$s" | cat)
myVar1=$(echo ${myVar##*GACCT})
echo ${myVar1%%AGGTC*}
# => AAATTTGGGCCC

# My suggestion:
grep --color=never -oP 'GACCT\K[ATCG]+(?=AGGTC)' <<< "$s"
# => AAATTTGGGCCC
</code>```

With --color=never, your matches are not colored.

The -o option outputs the matched texts, and the P option enables the PCRE regex engine. It is necessary here since the regex pattern contains specific operators, like \K and (?=...).

More details

GACCT - a literal string

\K - operator that makes the regex engine "forget" what has been consumed

[ATCG]+ - one or more letters from the set

(?=AGGTC) - a positive lookahead that requires an AGGTC string immediately to the right of the current location.

Note you can get this result with pcregrep, too, if you install it:

myVar=$(pcregrep -o 'GACCT\K[ATCG]+(?=AGGTC)' FILE.txt)
```

Body:
I am trying to splice out a particular piece of string. I used:

myVar=$(grep --color 'GACCT[ATCG]*AGGTC' FILE.txt | cat)

then, I used the code below to remove everything before and after my desired portion.

myVar1=$(echo ${myVar##*GACCT})
echo ${myVar1%%AGGTC*}

The code is working however, it cuts off the GACCT and AGGTC at the beginning and end of the desired fragmen that I want to keep. Is there anyway to cut the beginning and end off while still keeping the GACCT and AGGTC?

Thank you!

Body:
If you have a GNU grep, you can make use of

myVar=$(grep --color=never -oP 'GACCT\K[ATCG]+(?=AGGTC)' FILE.txt)

See the online demo:

#!/bin/bash
s='GACCTAAATTTGGGCCCAGGTC'

# Original script
myVar=$(grep --color 'GACCT[ATCG]*AGGTC' <<< "$s" | cat)
myVar1=$(echo ${myVar##*GACCT})
echo ${myVar1%%AGGTC*}
# => AAATTTGGGCCC

# My suggestion:
grep --color=never -oP 'GACCT\K[ATCG]+(?=AGGTC)' <<< "$s"
# => AAATTTGGGCCC

With --color=never, your matches are not colored.

The -o option outputs the matched texts, and the P option enables the PCRE regex engine. It is necessary here since the regex pattern contains specific operators, like \K and (?=...).

More details

GACCT - a literal string

\K - operator that makes the regex engine "forget" what has been consumed

[ATCG]+ - one or more letters from the set

(?=AGGTC) - a positive lookahead that requires an AGGTC string immediately to the right of the current location.

Note you can get this result with pcregrep, too, if you install it:

myVar=$(pcregrep -o 'GACCT\K[ATCG]+(?=AGGTC)' FILE.txt)