问:
CakePHP 4.x: How to access logged-in user info from within a custom Behavior?
I am trying to add a custom Behavior that is a clone of the default Timestamp.  Mine is "Userstamp" adding the current user to audit-trail fields on all tables.  At the point where Timestamp sets the field to "new FrozenTime($ts)", I want to set to "$identity->get('username')" or similar.  I am having trouble reaching anything from Authentication/Authorization or Identity from within the Behavior.

I know that the information is there, somewhere.  But what do I need to include in my Behavior class in order to retrieve it?
I found this link, but I don't see where to put the suggested code.

In my Table:

```<code>public function initialize(array $config): void
    {
        parent::initialize($config);

        $this->setTable('users');
        $this->setDisplayField('name');
        $this->setPrimaryKey('id');

        $this->addBehavior('Timestamp');
        $this->addBehavior('Userstamp');

        .
        .
        .
}
</code>```

Cake's timestamp Behavior:

```<code>    public function timestamp(?DateTimeInterface $ts = null, bool $refreshTimestamp = false): DateTimeInterface
    {
        if ($ts) {
            if ($this->_config['refreshTimestamp']) {
                $this->_config['refreshTimestamp'] = false;
            }
            $this->_ts = new FrozenTime($ts);
        } elseif ($this->_ts === null || $refreshTimestamp) {
            $this->_ts = new FrozenTime();
        }

        return $this->_ts;
    }
</code>```

My userstamp Behavior:

```<code>    public function userstamp($userstamp = null, bool $refreshUserstamp = false)
    {
// Variations of this do not work, the Property is not available in UserstampBehavior
//        $currentUser = $this->Authentication
//            ->getIdentity()
//            ->getIdentifier();
        $currentUser = 'abc';   <<<<<<<<<<<<< Hard-coded temporarily

        if ($userstamp) {
            if ($this->_config['refreshUserstamp']) {
                $this->_config['refreshUserstamp'] = false;
            }
            $this->_userstamp = $currentUser;
        } elseif ($this->_userstamp === null || $refreshUserstamp) {
            $this->_userstamp = $currentUser;
        }

        return $this->_userstamp;
    }
</code>```

答:
Your Auth-Informations lives also in the session.

So you can access Session-stuff in a table-class like this:
(new Session)->read('Auth')

And therefore you give this information from a table-class to your Behaviour like this:

```<code>$this->addBehavior('Userstamp', ['user_info'=>(new Session)->read('Auth')]);
</code>```

Then you can access this information in your behaviour:

```<code>public function initialize(array $config){
    $this->user_info = $config['user_info'];
}

public function myFunction(){
   // do something with $this->user_info
}
</code>```

Body:
I am trying to add a custom Behavior that is a clone of the default Timestamp.  Mine is "Userstamp" adding the current user to audit-trail fields on all tables.  At the point where Timestamp sets the field to "new FrozenTime($ts)", I want to set to "$identity->get('username')" or similar.  I am having trouble reaching anything from Authentication/Authorization or Identity from within the Behavior.

I know that the information is there, somewhere.  But what do I need to include in my Behavior class in order to retrieve it?
I found this link, but I don't see where to put the suggested code.

In my Table:

public function initialize(array $config): void
    {
        parent::initialize($config);

        $this->setTable('users');
        $this->setDisplayField('name');
        $this->setPrimaryKey('id');

        $this->addBehavior('Timestamp');
        $this->addBehavior('Userstamp');

        .
        .
        .
}

Cake's timestamp Behavior:

    public function timestamp(?DateTimeInterface $ts = null, bool $refreshTimestamp = false): DateTimeInterface
    {
        if ($ts) {
            if ($this->_config['refreshTimestamp']) {
                $this->_config['refreshTimestamp'] = false;
            }
            $this->_ts = new FrozenTime($ts);
        } elseif ($this->_ts === null || $refreshTimestamp) {
            $this->_ts = new FrozenTime();
        }

        return $this->_ts;
    }

My userstamp Behavior:

    public function userstamp($userstamp = null, bool $refreshUserstamp = false)
    {
// Variations of this do not work, the Property is not available in UserstampBehavior
//        $currentUser = $this->Authentication
//            ->getIdentity()
//            ->getIdentifier();
        $currentUser = 'abc';   <<<<<<<<<<<<< Hard-coded temporarily

        if ($userstamp) {
            if ($this->_config['refreshUserstamp']) {
                $this->_config['refreshUserstamp'] = false;
            }
            $this->_userstamp = $currentUser;
        } elseif ($this->_userstamp === null || $refreshUserstamp) {
            $this->_userstamp = $currentUser;
        }

        return $this->_userstamp;
    }

Body:
Your Auth-Informations lives also in the session.

So you can access Session-stuff in a table-class like this:
(new Session)->read('Auth')

And therefore you give this information from a table-class to your Behaviour like this:

$this->addBehavior('Userstamp', ['user_info'=>(new Session)->read('Auth')]);

Then you can access this information in your behaviour:

public function initialize(array $config){
    $this->user_info = $config['user_info'];
}

public function myFunction(){
   // do something with $this->user_info
}


来源: stackexchange

问:
Would this class have a Strict Weak Ordering
Say I had class/struct Foo

```<code>struct Foo {
    int a, b;
    bool operator< (Foo const& r){
        return a < r.a;
    }
    bool operator== (Foo const& r){
        return a==r.a&&b==r.b;
    }
};
Foo bar = { 5, 1 };
Foo baz = { 5, 2 };
</code>```

Now bar == baz is false but so are bar < baz and baz < bar.

Note that here the ordering completely ignores b but b is part of the equality relation.

答:
Technically yes, you are ordering them by the a member directly, which should be fine for eg. std::set. Basically they behave like integers, ie. if a < b and b < c then a < c, etc. I don't think operator == affects the validity of the ordering implied by operator <.

However - it is a bad idea to define two operators on the same class which imply different things about it, because it is likely to prove confusing to users of that class. As far as I know it wouldn't directly break any STL containers since they use only one of the two operators, but it would certainly confuse me that you can have this case where !(bar < baz) and !(baz < bar) but !(bar == baz).

In a case like this I would prefer to provide as a member only the operator that is more natural for the class, and make the other available through a standalone struct that can be supplied as a template parameter to the STL container. To me that makes it clearer that it's a way of ordering instances of the class which isn't necessarily equivalent to the other member operators.

ContentLicense: CC BY-SA 3.0

Body:
Say I had class/struct Foo

struct Foo {
    int a, b;
    bool operator< (Foo const& r){
        return a < r.a;
    }
    bool operator== (Foo const& r){
        return a==r.a&&b==r.b;
    }
};
Foo bar = { 5, 1 };
Foo baz = { 5, 2 };

Now bar == baz is false but so are bar < baz and baz < bar.

Note that here the ordering completely ignores b but b is part of the equality relation.


问:
restrict qualifier placement with pointers to pointers
Here are a couple of C and POSIX functions that need to fetch some data from or put some data into a buffer and tell the caller how much, so they take a pointer to the starting buffer address and write the adjusted pointer there on return:

size_t mbstowcs(wchar_t *restrict pwcs, const char *restrict s,
                size_t n); /* for comparison */
size_t mbsrtowcs(wchar_t *restrict dst, const char **restrict src,
                 size_t len, mbstate_t *restrict ps);
size_t mbsnrtowcs(wchar_t *restrict dst, const char **restrict src,
                  size_t nmc, size_t len, mbstate_t *restrict ps);
size_t iconv(iconv_t cd,
             char **restrict inbuf, size_t *restrict inbytesleft,
             char **restrict outbuf, size_t *restrict outbytesleft);
```
<p>I expect the (principal) meaning of the restrict qualifiers on the buffers is that those functions assume the input and output buffers to not overlap; and for <code>mbstowcs</code> (that just takes the buffer addresses by value) that indeed seems to be the case.</p>
<p>But why do the rest of the functions take <code>ELEMENT **restrict</code> pointers and not <code>ELEMENT *restrict *</code> or <code>ELEMENT *restrict *restrict</code> pointers? To me these declarations as written would imply that it is the <em>buffer addresses</em>, the <code>ELEMENT *</code>s themselves as they are stored in memory, that must not alias, which is... probably a bit helpful, yes, but not that as important? These declarations make it look to me like the code</p>
<pre class="lang-c prettyprint-override"><code>iconv_t cd = /* ... */;
char data[] = /* ... */, *inp = data, *outp = data;
size_t inn = sizeof data, outn = sizeof data;
iconv(cd, &inp, &inn, &outp, &outn);
</code>```

is valid, which is surely not the intention?

In C17 subclause 6.7.3.1 (Formal definition of restrict), paragraph 4, we can find a passage that seems vaguely relevant:

[... L]et L be any lvalue that has &L based on P [a restrict-qualified pointer]. If L is used to access the value of the object X that it designates, and X is also modified (by any means), then the following requirements apply: T shall not be const-qualified. Every other lvalue used to access the value of X shall also have its address based on P [as defined in a preceding paragraph]. Every access that modifies X shall be considered also to modify P [italics mine], for the purposes of this subclause. [...]

but I cannot for the life of me figure out what the importance of that italicized sentence is.

答: The semantics of applying a restrict qualifier to anything other than standalone objects of automatic duration whose addresses aren't taken are murky at best.  The restrict qualifier offers the most value in cases where its semantics are clearest, and compilers are allowed to effectively ignore the qualifier in cases where the effort required to perform optimizations based upon it would exceed the benefit of such optimizations.  Using the qualifier in cases with murky semantics and low payoff is apt to at best be a waste of time, since compilers are likely to simply ignore it, and if they don't ignore it they may interpret in a manner contrary to programmer expectation.</p>

ContentLicense: CC BY-SA 4.0

Body:
Here are a couple of C and POSIX functions that need to fetch some data from or put some data into a buffer and tell the caller how much, so they take a pointer to the starting buffer address and write the adjusted pointer there on return:

size_t mbstowcs(wchar_t *restrict pwcs, const char *restrict s,
                size_t n); /* for comparison */
size_t mbsrtowcs(wchar_t *restrict dst, const char **restrict src,
                 size_t len, mbstate_t *restrict ps);
size_t mbsnrtowcs(wchar_t *restrict dst, const char **restrict src,
                  size_t nmc, size_t len, mbstate_t *restrict ps);
size_t iconv(iconv_t cd,
             char **restrict inbuf, size_t *restrict inbytesleft,
             char **restrict outbuf, size_t *restrict outbytesleft);

I expect the (principal) meaning of the restrict qualifiers on the buffers is that those functions assume the input and output buffers to not overlap; and for mbstowcs (that just takes the buffer addresses by value) that indeed seems to be the case.

But why do the rest of the functions take ELEMENT **restrict pointers and not ELEMENT *restrict * or ELEMENT *restrict *restrict pointers? To me these declarations as written would imply that it is the buffer addresses, the ELEMENT *s themselves as they are stored in memory, that must not alias, which is... probably a bit helpful, yes, but not that as important? These declarations make it look to me like the code

iconv_t cd = /* ... */;
char data[] = /* ... */, *inp = data, *outp = data;
size_t inn = sizeof data, outn = sizeof data;
iconv(cd, &inp, &inn, &outp, &outn);

is valid, which is surely not the intention?

In C17 subclause 6.7.3.1 (Formal definition of restrict), paragraph 4, we can find a passage that seems vaguely relevant:

[... L]et L be any lvalue that has &L based on P [a restrict-qualified pointer]. If L is used to access the value of the object X that it designates, and X is also modified (by any means), then the following requirements apply: T shall not be const-qualified. Every other lvalue used to access the value of X shall also have its address based on P [as defined in a preceding paragraph]. Every access that modifies X shall be considered also to modify P [italics mine], for the purposes of this subclause. [...]

but I cannot for the life of me figure out what the importance of that italicized sentence is.


问:
DotNetCore ILogger error parameter logger value cannot be null
I have included Serilog in my project. It works well with other controllers.

When I try to pass the logger reference to a different class(instantiated) I am facing the below error

Message = "Value cannot be null. (Parameter 'logger')"

Below is pseudo code

```<code>using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Xml;
using Serilog;
using Serilog.AspNetCore;
using Serilog.Core;
using Serilog.Sinks;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using Microsoft.Extensions.Logging;

namespace SomeNameSpace
{
    public class EmployeeDAO : IDisposable
    {
        //DataUpload Service implements IDataUpload
        private readonly IDataUpload dataUpload;

         private readonly ILogger<EmployeeDAO> log;
        public readonly ILogger<DataUploadService> dataLogger;

        public EmployeeDAO(ILogger<EmployeeDAO> logger)
        {
            log = logger;
        }

        private void SaveData(object obj)
        {
            switch (obj.GetType().Name)
            {
                case "SaveData":
                    this.dataupload = new DataUploadService(a, b, obj, dataLogger);
    //Error thrown at above line logger is null
                    break;
                default:
                    log.LogError($"Logging Some Error");
            }
        }
        }
}
</code>```

I this to be done in a different way ?
Please provide a better way to handle this.

答:
Your primary error is that dataLogger is never set.
To Resolve that issue you can do like Danny Boy suggest, and inject the logger as well.

However, I would suggest that you inject DataUploadService as well, instead of constructing it in your class. Optionally you can inject Func<DataUploadService> to lazy inject the service. If you want to lazy inject it, you need a third party container like Autofac.

Body:
I have included Serilog in my project. It works well with other controllers.

When I try to pass the logger reference to a different class(instantiated) I am facing the below error

Message = "Value cannot be null. (Parameter 'logger')"

Below is pseudo code

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Xml;
using Serilog;
using Serilog.AspNetCore;
using Serilog.Core;
using Serilog.Sinks;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using Microsoft.Extensions.Logging;

namespace SomeNameSpace
{
    public class EmployeeDAO : IDisposable
    {
        //DataUpload Service implements IDataUpload
        private readonly IDataUpload dataUpload;

         private readonly ILogger<EmployeeDAO> log;
        public readonly ILogger<DataUploadService> dataLogger;

        public EmployeeDAO(ILogger<EmployeeDAO> logger)
        {
            log = logger;
        }

        private void SaveData(object obj)
        {
            switch (obj.GetType().Name)
            {
                case "SaveData":
                    this.dataupload = new DataUploadService(a, b, obj, dataLogger);
    //Error thrown at above line logger is null
                    break;
                default:
                    log.LogError($"Logging Some Error");
            }
        }
        }
}

I this to be done in a different way ?
Please provide a better way to handle this.


问:
Group array of string arrays with LINQ
I have array like this, values are string:

```<code>var arr1 = new [] { "H", "item1", "item2" };
var arr2 = new [] { "T", "thing1", "thing2" };
var arr3 = new [] { "T", "thing1", "thing2" };
var arr4 = new [] { "END", "something" };
var arr5 = new [] { "H", "item1", "item2" };
var arr6 = new [] { "T", "thing1", "thing2" };
var arr7 = new [] { "T", "thing1", "thing2" };
var arr8 = new [] { "END", "something" };

var allArrays = new [] { arr1, arr2, arr3, arr4, arr5, arr6, arr7, arr8 };
</code>```

I need to group this in to a new array of arrays, so that one array has arrays that start with H or T. The END records (not included in the results) are the delimiters between each section; each new array starts after an END array.

In the end I would like to have somethng like this:

```<code>[
[ [H, item1, item2], [T, thing1, thing2], [T, thing1, thing2] ]
[ [H, item1, item2], [T, thing1, thing2], [T, thing1, thing2] ]
]
</code>```

I know how I can do this with for each loop, but I'm looking for a cleaner way, possibly using linq. All suggestions are much valued, thank you!

答:
So arr1, arr2, etc are string[].
allArrays is a string[][].

I hope you gave a meaningful example. From this example it seems that you want all string[] from allArrays, except the string[] that have a [0] that equals the word "END".

If this is what you want, your result is:

```<code>string[][] result = allArrays.Where(stringArray => stringArray[0] != "END");
</code>```

I need to group this in to a new array of arrays, so that one array has arrays that start with H or T. The END records (not included in the results) are the delimiters between each section; each new array starts after an END array.

This is not exactly the same as I see in your example: what if one of the string arrays in allArrays is an empty array, or if it has the value null values. What if one of the the arrays of strings is empty (= length 0), and what if one of the string arrays doesn't start with "H", nor "T", nor "END"?

Literally you say that you only want the string arrays that start with "H" or "T", no other ones. You don't want string arrays that are null, nor empty string arrays. You also don't want string arrays that start with "END", nor the ones that start with String.Empty, or "A" or "B" or anything else than "H" or "T".

If I take your requirement literally, your code should be:

```<code>string[] requiredStringAtIndex0 = new string[] {"H", "T"};
string[][] result = allArrays.Where(stringArray => stringArray != null
    && stringArray.Length != 0
    && requiredStringAtIndex0.Contains(stringArray[0]));
</code>```

In words: from allArrays, keep only those arrays of strings, that are not null, AND that have at least one element AND where the element at index 0 contains either "H" or "T"

Title: Group array of string arrays with LINQ

Body:
I have array like this, values are string:

var arr1 = new [] { "H", "item1", "item2" };
var arr2 = new [] { "T", "thing1", "thing2" };
var arr3 = new [] { "T", "thing1", "thing2" };
var arr4 = new [] { "END", "something" };
var arr5 = new [] { "H", "item1", "item2" };
var arr6 = new [] { "T", "thing1", "thing2" };
var arr7 = new [] { "T", "thing1", "thing2" };
var arr8 = new [] { "END", "something" };

var allArrays = new [] { arr1, arr2, arr3, arr4, arr5, arr6, arr7, arr8 };

I need to group this in to a new array of arrays, so that one array has arrays that start with H or T. The END records (not included in the results) are the delimiters between each section; each new array starts after an END array.

In the end I would like to have somethng like this:

[
[ [H, item1, item2], [T, thing1, thing2], [T, thing1, thing2] ]
[ [H, item1, item2], [T, thing1, thing2], [T, thing1, thing2] ]
]

I know how I can do this with for each loop, but I'm looking for a cleaner way, possibly using linq. All suggestions are much valued, thank you!

Body:
So arr1, arr2, etc are string[].
allArrays is a string[][].

I hope you gave a meaningful example. From this example it seems that you want all string[] from allArrays, except the string[] that have a [0] that equals the word "END".

If this is what you want, your result is:

string[][] result = allArrays.Where(stringArray => stringArray[0] != "END");

I need to group this in to a new array of arrays, so that one array has arrays that start with H or T. The END records (not included in the results) are the delimiters between each section; each new array starts after an END array.

This is not exactly the same as I see in your example: what if one of the string arrays in allArrays is an empty array, or if it has the value null values. What if one of the the arrays of strings is empty (= length 0), and what if one of the string arrays doesn't start with "H", nor "T", nor "END"?

Literally you say that you only want the string arrays that start with "H" or "T", no other ones. You don't want string arrays that are null, nor empty string arrays. You also don't want string arrays that start with "END", nor the ones that start with String.Empty, or "A" or "B" or anything else than "H" or "T".

If I take your requirement literally, your code should be:

string[] requiredStringAtIndex0 = new string[] {"H", "T"};
string[][] result = allArrays.Where(stringArray => stringArray != null
    && stringArray.Length != 0
    && requiredStringAtIndex0.Contains(stringArray[0]));

In words: from allArrays, keep only those arrays of strings, that are not null, AND that have at least one element AND where the element at index 0 contains either "H" or "T"


问:
Failed to load resource: net::ERR_UNKNOWN_URL_SCHEME
I'm trying to build a snapchat clone using react with redux. I'm at a point where i can take the picture but the problem is when i take the picture, that picture doesn't get saved in it's current state and in the console this error "Failed to load resource: net::ERR_UNKNOWN_URL_SCHEME" is thrown. when i tried to use redux dev tools, it showed that the image comes back as "nulldata:img/jpeg..."

I'm using chrome as my default browser.

this is a snippet of the code that i have to show the preview

```<code>function Preview() {
const cameraImage = useSelector(selectCameraImage);
const history = useHistory()
const dispatch = useDispatch()

useEffect(() => {
    if (!cameraImage) {
        history.replace('/')

    }
}, [cameraImage, history])

const closePreview = () => {
    dispatch(resetCameraImage());
}

return <div className="preview">
        <CloseIcon onClick={closePreview} className="preview__close"/>
        <img src={cameraImage} alt="" />
        </div>;
</code>```

答:
cameraSlice.js

```<code>import { createSlice } from "@reduxjs/toolkit";

const initialState = {
  cameraImage: "",// instead of null use ""(though null works fine for me)
};

export const cameraSlice = createSlice({
  name: "camera",
  initialState,

  reducers: {
    resetCameraImage: (state) => {
      state.cameraImage = null;// try changing null to "" here too
    },
    setCameraImage: (state, action) => {
      state.cameraImage = action.payload;// take care to change the default += to just =, most probably the mistake you're making
    },
  },
});

export const { setCameraImage, resetCameraImage } = cameraSlice.actions;

export const selectCamera = (state) => state.camera.cameraImage;

export default cameraSlice.reducer;
</code>```

WebcamCapture.js

```<code>import React, { useRef, useCallback } from "react";
import Webcam from "react-webcam";
import RadioButtonUncheckedOutlinedIcon from "@mui/icons-material/RadioButtonUncheckedOutlined";
import { useDispatch, useSelector } from "react-redux";
import { selectCamera, setCameraImage } from "./features/cameraSlice";

const videoConstraints = {
  width: 250,
  height: 400,
  facingMode: "user",
};

function WebcamCapture() {
  const webcamRef = useRef(null);
  const dispatch = useDispatch();
  const camImage = useSelector(selectCamera);

  const capture = useCallback(() => {
    const imageSrc = webcamRef.current.getScreenshot();
    dispatch(setCameraImage(imageSrc));
  }, [dispatch, webcamRef]);

  return (
    <div className="webcamCapture">
      <Webcam
        audio={false}
        height={videoConstraints.height}
        ref={webcamRef}
        screenshotFormat={videoConstraints}
        width={videoConstraints.width}
        videoConstraints={videoConstraints}
      />

      <RadioButtonUncheckedOutlinedIcon
        className="webcamCapture__button"
        onClick={capture}
        fontSize="large"
      />

      <img src={camImage} alt="" />
    </div>
  );
}

export default WebcamCapture;
</code>```

This worked for me.

Body:
I'm trying to build a snapchat clone using react with redux. I'm at a point where i can take the picture but the problem is when i take the picture, that picture doesn't get saved in it's current state and in the console this error "Failed to load resource: net::ERR_UNKNOWN_URL_SCHEME" is thrown. when i tried to use redux dev tools, it showed that the image comes back as "nulldata:img/jpeg..."

I'm using chrome as my default browser.

this is a snippet of the code that i have to show the preview

function Preview() {
const cameraImage = useSelector(selectCameraImage);
const history = useHistory()
const dispatch = useDispatch()

useEffect(() => {
    if (!cameraImage) {
        history.replace('/')

    }
}, [cameraImage, history])

const closePreview = () => {
    dispatch(resetCameraImage());
}

return

        <CloseIcon onClick={closePreview} className="preview__close"/>

;

Body:
cameraSlice.js

import { createSlice } from "@reduxjs/toolkit";

const initialState = {
  cameraImage: "",// instead of null use ""(though null works fine for me)
};

export const cameraSlice = createSlice({
  name: "camera",
  initialState,

  reducers: {
    resetCameraImage: (state) => {
      state.cameraImage = null;// try changing null to "" here too
    },
    setCameraImage: (state, action) => {
      state.cameraImage = action.payload;// take care to change the default += to just =, most probably the mistake you're making
    },
  },
});

export const { setCameraImage, resetCameraImage } = cameraSlice.actions;

export const selectCamera = (state) => state.camera.cameraImage;

export default cameraSlice.reducer;

WebcamCapture.js

import React, { useRef, useCallback } from "react";
import Webcam from "react-webcam";
import RadioButtonUncheckedOutlinedIcon from "@mui/icons-material/RadioButtonUncheckedOutlined";
import { useDispatch, useSelector } from "react-redux";
import { selectCamera, setCameraImage } from "./features/cameraSlice";

const videoConstraints = {
  width: 250,
  height: 400,
  facingMode: "user",
};

function WebcamCapture() {
  const webcamRef = useRef(null);
  const dispatch = useDispatch();
  const camImage = useSelector(selectCamera);

  const capture = useCallback(() => {
    const imageSrc = webcamRef.current.getScreenshot();
    dispatch(setCameraImage(imageSrc));
  }, [dispatch, webcamRef]);

  return (
    <div className="webcamCapture">
      <Webcam
        audio={false}
        height={videoConstraints.height}
        ref={webcamRef}
        screenshotFormat={videoConstraints}
        width={videoConstraints.width}
        videoConstraints={videoConstraints}
      />

      <RadioButtonUncheckedOutlinedIcon
        className="webcamCapture__button"
        onClick={capture}
        fontSize="large"
      />

      <img src={camImage} alt="" />
    </div>
  );
}

export default WebcamCapture;

This worked for me.


问:
Given a table of numbers, can I get all the rows which add up to less than or equal to a number?
Say I have a table with an incrementing id column and a random positive non zero number.

id
rand

1
12

2
5

3
99

4
87

Write a query to return the rows which add up to a given number.

A couple rules:

Rows must be "consumed" in order, even if a later row makes it a a perfect match. For example, querying for 104 would be a perfect match for rows 1, 2, and 4 but rows 1-3 would still be returned.

You can use a row partially if there is more available than is necessary to add up to whatever is leftover on the number E.g. rows 1, 2, and 3 would be returned if your max number is 50 because 12 + 5 + 33 equals 50 and 90 is a partial result.

If there are not enough rows to satisfy the amount, then return ALL the rows. E.g. in the above example a query for 1,000 would return rows 1-4. In other words, the sum of the rows should be less than or equal to the queried number.

It's possible for the answer to be "no this is not possible with SQL alone" and that's fine but I was just curious. This would be a trivial problem with a programming language but I was wondering what SQL provides out of the box to do something as a thought experiment and learning exercise.

答:
You didn't mention which RDBMS, but assuming SQL Server:</p>
```<code>DROP TABLE #t;

CREATE TABLE #t (id int, rand int);

INSERT INTO #t (id,rand)
VALUES (1,12),(2,5),(3,99),(4,87);

DECLARE @target int = 104;

WITH dat
AS
(
SELECT id, rand, SUM(rand) OVER (ORDER BY id) as runsum
FROM #t
),
dat2
as
(
SELECT id, rand
, runsum
, COALESCE(LAG(runsum,1) OVER (ORDER BY id),0) as prev_runsum
from dat
)
SELECT id, rand
FROM dat2
WHERE @target >= runsum
OR @target BETWEEN prev_runsum AND runsum;
</code>```

Body:
You didn't mention which RDBMS, but assuming SQL Server:

DROP TABLE #t;

CREATE TABLE #t (id int, rand int);

INSERT INTO #t (id,rand)
VALUES (1,12),(2,5),(3,99),(4,87);

DECLARE @target int = 104;

WITH dat
AS
(
SELECT id, rand, SUM(rand) OVER (ORDER BY id) as runsum
FROM #t
),
dat2
as
(
SELECT id, rand
, runsum
, COALESCE(LAG(runsum,1) OVER (ORDER BY id),0) as prev_runsum
from dat
)
SELECT id, rand
FROM dat2
WHERE @target >= runsum
OR @target BETWEEN prev_runsum AND runsum;


问:
Mootools get the child-index of an element from its parent
I am using event delegation in mootools.  I want to know the row number that has been clicked.  My solution is shown in this jsfiddle: Is there a better way than what I am currently doing?

My approach was to compare the elements until i found the match.  Is there an IndexOf method I could use?

(The following is the data from the jsfiddle for the future)

HTML:

```<code><div id="Record_List">
    <div class="Row">
        <input type="submit" name="Row" value="Edit"/>
    </div>
    <div class="Row">
        <input type="submit" name="Row" value="Edit"/>
    </div>
</div>
</code>```

Javascript:

```<code>window.addEvent(
    'domready',
    function()
    {
        $('Record_List').addEvent(
            'click:relay(input)',
            function(evt, target)
            {
                evt.stop();

                var rowElem = target.getParent();
                var rowNumber = -1;

                $('Record_List').getChildren('div.Row').each(
                    function (el, num)
                    {
                        if (rowElem === el)
                        {
                            rowNumber = num;
                        }
                    });

                // Find the position of the row and display it here:
                alert('Row number: ' + rowNumber);
            });
    });
</code>```

答:
The type (Elements) returned by getChildren contains Array methods, including indexOf. MooTools will provide an implementation of that method if it does not exist for the browser. With that in mind, you could write:

```<code>$('Record_List').getChildren('div.Row').indexOf(rowElem);
</code>```

Updated example: http://jsfiddle.net/andrewwhitaker/uJarB/

Body:
I am using event delegation in mootools.  I want to know the row number that has been clicked.  My solution is shown in this jsfiddle: Is there a better way than what I am currently doing?

My approach was to compare the elements until i found the match.  Is there an IndexOf method I could use?

(The following is the data from the jsfiddle for the future)

HTML:

        <input type="submit" name="Row" value="Edit"/>

        <input type="submit" name="Row" value="Edit"/>

Javascript:

window.addEvent(
    'domready',
    function()
    {
        $('Record_List').addEvent(
            'click:relay(input)',
            function(evt, target)
            {
                evt.stop();

                var rowElem = target.getParent();
                var rowNumber = -1;

                $('Record_List').getChildren('div.Row').each(
                    function (el, num)
                    {
                        if (rowElem === el)
                        {
                            rowNumber = num;
                        }
                    });

                // Find the position of the row and display it here:
                alert('Row number: ' + rowNumber);
            });
    });

Body:
The type (Elements) returned by getChildren contains Array methods, including indexOf. MooTools will provide an implementation of that method if it does not exist for the browser. With that in mind, you could write:

$('Record_List').getChildren('div.Row').indexOf(rowElem);

Updated example: http://jsfiddle.net/andrewwhitaker/uJarB/


问:
How to reduce mongo log verbosity in a docker-compose image?
I'm running MongoDB inside a larger server, controlled by docker-compose.

I'd like to reduce the verbosity of the Mongo logs (and probably eventually control other Mongo settings too).  Not sure where to fit this into my minimal config; I currently just have:

```<code>  mongo:
    image: mongo:3.2
    volumes:
      - ${MONGO_DATA_DB}:/data/db
    ports:
      - ${EXPOSED_MONGO_PORT}:27017
</code>```

答:
Setting logpath worked for me. It's not showing the logs output instead it's saving to the file.</p>
```<code>    mongo:
        container_name: mongo
        image: mongo
        restart: unless-stopped
        command:
            - '--logpath'
            - '/var/log/mongodb/mongod.log'
        ports:
            - '27017:27017'
</code>```

Body:
I'm running MongoDB inside a larger server, controlled by docker-compose.

I'd like to reduce the verbosity of the Mongo logs (and probably eventually control other Mongo settings too).  Not sure where to fit this into my minimal config; I currently just have:

  mongo:
    image: mongo:3.2
    volumes:
      - ${MONGO_DATA_DB}:/data/db
    ports:
      - ${EXPOSED_MONGO_PORT}:27017

Body:
Setting logpath worked for me. It's not showing the logs output instead it's saving to the file.

    mongo:
        container_name: mongo
        image: mongo
        restart: unless-stopped
        command:
            - '--logpath'
            - '/var/log/mongodb/mongod.log'
        ports:
            - '27017:27017'


问:
Find the maximum value for each group in dataframe and retrieve the entire row
I've the following dataframe (With many records) and would like to retrieve the entire row for each day with maximum differences.

```<code>require(dplyr)
# This gets the maximum value for each date
maxInfo = results %>% group_by(t) %>% summarise(Value = max(differences))
</code>```

I'm able to get the max value for each day but how to get the entire row?

答:
data.table method if speed is important

```<code>results[ results[, .I[ differences == max(differences )], .(t)]$V1 ]
</code>```

Body:
I've the following dataframe (With many records) and would like to retrieve the entire row for each day with maximum differences.

require(dplyr)
# This gets the maximum value for each date
maxInfo = results %>% group_by(t) %>% summarise(Value = max(differences))

I'm able to get the max value for each day but how to get the entire row?

Body:
data.table method if speed is important

results[ results[, .I[ differences == max(differences )], .(t)]$V1 ]


问:
How to modify body of the spring boot reactive oauth2 authorization request
When I use WebClient defined below, authorization request is created and sent.

How can I modify authorization POST request, which is sent by spring boot to get the bearer token? I need to add some fields to the request body.

Client and Provider Configurations

```<code>spring.security.oauth2.client.registration.d365.authorization-grant-type=client_credentials
spring.security.oauth2.client.registration.d365.client-id=my-client-id
spring.security.oauth2.client.registration.d365.client-secret=my-secret
spring.security.oauth2.client.provider.d365.token-uri=http://localhost:8085/oauth/token
</code>```

WebClient configuration

```<code>@Bean
WebClient webClient(ReactiveClientRegistrationRepository clientRegistrations) {
    ServerOAuth2AuthorizedClientExchangeFilterFunction oauth =
      new ServerOAuth2AuthorizedClientExchangeFilterFunction(
        clientRegistrations,
        new UnAuthenticatedServerOAuth2AuthorizedClientRepository());
    oauth.setDefaultClientRegistrationId("d365");
    return WebClient.builder()
      .filter(oauth)
      .build();
}
</code>```

答:
you can extract/read/modify/manipulate the request and response and their headers with the help of ServerHttpRequestDecorator & ServerHttpResponseDecorator see below

Note: i implemented GatewayFilter because i have this logic in gateway service level, if you want to modify at micro service level you can use WebFilter

```<code>import lombok.extern.log4j.Log4j2;
import org.apache.commons.io.IOUtils;
import org.reactivestreams.Publisher;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.DefaultDataBuffer;
import org.springframework.core.io.buffer.DefaultDataBufferFactory;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpRequestDecorator;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.http.server.reactive.ServerHttpResponseDecorator;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Schedulers;

import java.io.ByteArrayOutputStream;
import java.nio.channels.Channels;
import java.nio.charset.StandardCharsets;

@Configuration
@Log4j2
public class RequestResponseModifyFilter implements GatewayFilter/WebFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        String path = exchange.getRequest().getPath().toString();
        ServerHttpResponse response = exchange.getResponse();
        ServerHttpRequest request = exchange.getRequest();
        DataBufferFactory dataBufferFactory = response.bufferFactory();

        // log the request body
        ServerHttpRequest decoratedRequest = getDecoratedRequest(request);
        // log the response body
        ServerHttpResponseDecorator decoratedResponse = getDecoratedResponse(path, response, request, dataBufferFactory);
        return chain.filter(exchange.mutate().request(decoratedRequest).response(decoratedResponse).build());
    }

    private ServerHttpResponseDecorator getDecoratedResponse(String path, ServerHttpResponse response, ServerHttpRequest request, DataBufferFactory dataBufferFactory) {
        return new ServerHttpResponseDecorator(response) {

            @Override
            public Mono<Void> writeWith(final Publisher<? extends DataBuffer> body) {

                if (body instanceof Flux) {

                    Flux<? extends DataBuffer> fluxBody = (Flux<? extends DataBuffer>) body;

                    return super.writeWith(fluxBody.buffer().map(dataBuffers -> {

                        DefaultDataBuffer joinedBuffers = new DefaultDataBufferFactory().join(dataBuffers);
                        byte[] content = new byte[joinedBuffers.readableByteCount()];
                        joinedBuffers.read(content);
                         String responseBody = new String(content, StandardCharsets.UTF_8);//MODIFY RESPONSE and Return the Modified response
                        log.debug("requestId: {}, method: {}, url: {}, \nresponse body :{}", request.getId(), request.getMethodValue(), request.getURI(), responseBody);

                        return dataBufferFactory.wrap(responseBody.getBytes());
                    })).onErrorResume(err -> {

                        log.error("error while decorating Response: {}",err.getMessage());
                        return Mono.empty();
                    });

                }
                return super.writeWith(body);
            }
        };
    }

    private ServerHttpRequest getDecoratedRequest(ServerHttpRequest request) {

        return new ServerHttpRequestDecorator(request) {
            @Override
            public Flux<DataBuffer> getBody() {

                log.debug("requestId: {}, method: {} , url: {}", request.getId(), request.getMethodValue(), request.getURI());
                return super.getBody().publishOn(Schedulers.boundedElastic()).doOnNext(dataBuffer -> {

                    try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) {

                        Channels.newChannel(byteArrayOutputStream).write(dataBuffer.asByteBuffer().asReadOnlyBuffer());
                        String requestBody = IOUtils.toString(byteArrayOutputStream.toByteArray(), StandardCharsets.UTF_8.toString());//MODIFY REQUEST and Return the Modified request
                        log.debug("for requestId: {}, request body :{}", request.getId(), requestBody);
                    } catch (Exception e) {
                        log.error(e.getMessage());
                    }
                });
            }
        };
    }

    @Override
    public int getOrder() { return -2;}
}
</code>```

Body:
When I use WebClient defined below, authorization request is created and sent.

How can I modify authorization POST request, which is sent by spring boot to get the bearer token? I need to add some fields to the request body.

Client and Provider Configurations

spring.security.oauth2.client.registration.d365.authorization-grant-type=client_credentials
spring.security.oauth2.client.registration.d365.client-id=my-client-id
spring.security.oauth2.client.registration.d365.client-secret=my-secret
spring.security.oauth2.client.provider.d365.token-uri=http://localhost:8085/oauth/token

WebClient configuration

@Bean
WebClient webClient(ReactiveClientRegistrationRepository clientRegistrations) {
    ServerOAuth2AuthorizedClientExchangeFilterFunction oauth =
      new ServerOAuth2AuthorizedClientExchangeFilterFunction(
        clientRegistrations,
        new UnAuthenticatedServerOAuth2AuthorizedClientRepository());
    oauth.setDefaultClientRegistrationId("d365");
    return WebClient.builder()
      .filter(oauth)
      .build();
}

Body:
you can extract/read/modify/manipulate the request and response and their headers with the help of ServerHttpRequestDecorator & ServerHttpResponseDecorator see below

Note: i implemented GatewayFilter because i have this logic in gateway service level, if you want to modify at micro service level you can use WebFilter

import lombok.extern.log4j.Log4j2;
import org.apache.commons.io.IOUtils;
import org.reactivestreams.Publisher;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.DefaultDataBuffer;
import org.springframework.core.io.buffer.DefaultDataBufferFactory;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpRequestDecorator;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.http.server.reactive.ServerHttpResponseDecorator;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Schedulers;

import java.io.ByteArrayOutputStream;
import java.nio.channels.Channels;
import java.nio.charset.StandardCharsets;

@Configuration
@Log4j2
public class RequestResponseModifyFilter implements GatewayFilter/WebFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        String path = exchange.getRequest().getPath().toString();
        ServerHttpResponse response = exchange.getResponse();
        ServerHttpRequest request = exchange.getRequest();
        DataBufferFactory dataBufferFactory = response.bufferFactory();

        // log the request body
        ServerHttpRequest decoratedRequest = getDecoratedRequest(request);
        // log the response body
        ServerHttpResponseDecorator decoratedResponse = getDecoratedResponse(path, response, request, dataBufferFactory);
        return chain.filter(exchange.mutate().request(decoratedRequest).response(decoratedResponse).build());
    }

    private ServerHttpResponseDecorator getDecoratedResponse(String path, ServerHttpResponse response, ServerHttpRequest request, DataBufferFactory dataBufferFactory) {
        return new ServerHttpResponseDecorator(response) {

            @Override
            public Mono<Void> writeWith(final Publisher<? extends DataBuffer> body) {

                if (body instanceof Flux) {

                    Flux<? extends DataBuffer> fluxBody = (Flux<? extends DataBuffer>) body;

                    return super.writeWith(fluxBody.buffer().map(dataBuffers -> {

                        DefaultDataBuffer joinedBuffers = new DefaultDataBufferFactory().join(dataBuffers);
                        byte[] content = new byte[joinedBuffers.readableByteCount()];
                        joinedBuffers.read(content);
                         String responseBody = new String(content, StandardCharsets.UTF_8);//MODIFY RESPONSE and Return the Modified response
                        log.debug("requestId: {}, method: {}, url: {}, \nresponse body :{}", request.getId(), request.getMethodValue(), request.getURI(), responseBody);

                        return dataBufferFactory.wrap(responseBody.getBytes());
                    })).onErrorResume(err -> {

                        log.error("error while decorating Response: {}",err.getMessage());
                        return Mono.empty();
                    });

                }
                return super.writeWith(body);
            }
        };
    }

    private ServerHttpRequest getDecoratedRequest(ServerHttpRequest request) {

        return new ServerHttpRequestDecorator(request) {
            @Override
            public Flux<DataBuffer> getBody() {

                log.debug("requestId: {}, method: {} , url: {}", request.getId(), request.getMethodValue(), request.getURI());
                return super.getBody().publishOn(Schedulers.boundedElastic()).doOnNext(dataBuffer -> {

                    try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) {

                        Channels.newChannel(byteArrayOutputStream).write(dataBuffer.asByteBuffer().asReadOnlyBuffer());
                        String requestBody = IOUtils.toString(byteArrayOutputStream.toByteArray(), StandardCharsets.UTF_8.toString());//MODIFY REQUEST and Return the Modified request
                        log.debug("for requestId: {}, request body :{}", request.getId(), requestBody);
                    } catch (Exception e) {
                        log.error(e.getMessage());
                    }
                });
            }
        };
    }

    @Override
    public int getOrder() { return -2;}
}


问:
Is it possible to List Azure Blobs Where Last Modified Date > Some Date
Is it possible to List all blobs on a container where Last Modified Date is greater than a specified date.

I have a container with millions of blobs and want to copy those blobs to a backup container, however don't want to loop through all blobs checking each for Last Modified Date.

答:
This is how I did it in Java. It prints the blobs modified in the last day. I am sure the C# equivalent is pretty similar:</p>
```<code>
BlobServiceClient blobServiceClient = new BlobServiceClientBuilder().endpoint("https://youraccount.blob.core.windows.net").sasToken("yourtoken").buildClient();
BlobContainerClient blobContainerClient = blobServiceClient.getBlobContainerClient("yourcontainer");

BlobListDetails details = new BlobListDetails().setRetrieveMetadata(true);
ListBlobsOptions options = new ListBlobsOptions().setPrefix("yourprefix").setDetails(details);

blobContainerClient.listBlobs(options, null).stream().filter(blob ->  blob.getProperties().getLastModified().isAfter(OffsetDateTime.now().minusDays(1))).forEach(blob -> System.out.printf("Name: %s %s%n", blob.getName(), blob.getProperties().getLastModified()));
```</code>

Body:
This is how I did it in Java. It prints the blobs modified in the last day. I am sure the C# equivalent is pretty similar:

BlobServiceClient blobServiceClient = new BlobServiceClientBuilder().endpoint("https://youraccount.blob.core.windows.net").sasToken("yourtoken").buildClient();
BlobContainerClient blobContainerClient = blobServiceClient.getBlobContainerClient("yourcontainer");

BlobListDetails details = new BlobListDetails().setRetrieveMetadata(true);
ListBlobsOptions options = new ListBlobsOptions().setPrefix("yourprefix").setDetails(details);

blobContainerClient.listBlobs(options, null).stream().filter(blob ->  blob.getProperties().getLastModified().isAfter(OffsetDateTime.now().minusDays(1))).forEach(blob -> System.out.printf("Name: %s %s%n", blob.getName(), blob.getProperties().getLastModified()));


问:
Android: How to show a spinner while performing a long-running operation?
I have a ProgressBar in .xml that I want to show when a long-running operation. I use

```<code>ProgressBar progressSpinner = (ProgressBar)findViewById(R.id.progressSpinner);
progressSpinner.setVisibility(View.VISIBLE);
</code>```

to set its visibility in some onButtonClick method. If the above code is all that is in the method, it works just fine. The problem is when I have a method like this:

```<code>public void onButtonClick (android.view.View view){
    ProgressBar progressSpinner = (ProgressBar)findViewById(R.id.progressSpinner);
    progressSpinner.setVisibility(View.VISIBLE);

    longRunningMethod(); // This method takes 5-10 seconds to run

    progressSpinner.setVisibility(View.GONE);
}
</code>```

The UI just locks up until longRunningMethod is done. That method works just fine, but the spinner never shows.

I tried running everything on a different thread with this:

```<code>public void onButtonClick (android.view.View view){
    ExecutorService executorService = Executors.newSingleThreadExecutor();
    executorService.submit(this::longRunningMethod);
}
</code>```

And I added the spinner visibility changing stuff to longRunningMethod:

```<code>private void longRunningMethod(){
    ProgressBar progressSpinner = (ProgressBar)findViewById(R.id.progressSpinner);
    progressSpinner.setVisibility(View.VISIBLE);

    // Logic that takes 5-10 seconds to run.

    progressSpinner.setVisibility(View.GONE);
}
</code>```

When I do this, the UI doesn't lock up, but nothing in longRunningMethod works. The spinner won't show and the logic also doesn't seem to work, although this may just be a problem with that logic not playing nice on not-the-UI-thread. I am very confused that the spinner visibility won't update from here though.

答:
Taking Sina's suggestion to use a Thread, the class now looks like:

```<code>public class MainActivity extends AppCompatActivity{

    // Irrelevant code (fields, init, other button handlers, etc...)

    private void onButtonClick(android.view.View view){
        LongRunningThread longRunningThread = new LongRunningThread();
        longRunningThread.start();
    }

    private class LongRunningThread extends Thread{
        public void run(){
            runOnUiThread(MainActivity.this::showSpinner);

            // Logic that takes 5-10 seconds to run

            runOnUiThread(MainActivity.this::hideSpinner);
        }
    }

    private void showSpinner(){
        ProgressBar progressSpinner = (ProgressBar)findViewById(R.id.progressSpinner);
        progressSpinner.setVisibility(View.VISIBLE);
    }

    private void hideSpinner(){
        ProgressBar progressSpinner = (ProgressBar)findViewById(R.id.progressSpinner);
        progressSpinner.setVisibility(View.GONE);
    }

}

</code>```

Doing this shows the progress spinner while the long-running logic is running and then hides the progress spinner after the long-running logic has completed. The UI stays responsive throughout and doesn't lock up.

Compared to the original code, this uses Thread instead of ExecutorService. It also runs UI logic via AppCompatActivity.runOnUiThread().

It would seem the answer to doing any long-running tasks alongside UI updates, without locking up the UI, is to create a Thread and call Thread.start(). The Thread should contain the long-running logic as well as the UI logic. The UI logic within that Thread must be run using runOnUiThread().

Body:
I have a ProgressBar in .xml that I want to show when a long-running operation. I use

ProgressBar progressSpinner = (ProgressBar)findViewById(R.id.progressSpinner);
progressSpinner.setVisibility(View.VISIBLE);

to set its visibility in some onButtonClick method. If the above code is all that is in the method, it works just fine. The problem is when I have a method like this:

public void onButtonClick (android.view.View view){
    ProgressBar progressSpinner = (ProgressBar)findViewById(R.id.progressSpinner);
    progressSpinner.setVisibility(View.VISIBLE);

    longRunningMethod(); // This method takes 5-10 seconds to run

    progressSpinner.setVisibility(View.GONE);
}

The UI just locks up until longRunningMethod is done. That method works just fine, but the spinner never shows.

I tried running everything on a different thread with this:

public void onButtonClick (android.view.View view){
    ExecutorService executorService = Executors.newSingleThreadExecutor();
    executorService.submit(this::longRunningMethod);
}

And I added the spinner visibility changing stuff to longRunningMethod:

private void longRunningMethod(){
    ProgressBar progressSpinner = (ProgressBar)findViewById(R.id.progressSpinner);
    progressSpinner.setVisibility(View.VISIBLE);

    // Logic that takes 5-10 seconds to run.

    progressSpinner.setVisibility(View.GONE);
}

When I do this, the UI doesn't lock up, but nothing in longRunningMethod works. The spinner won't show and the logic also doesn't seem to work, although this may just be a problem with that logic not playing nice on not-the-UI-thread. I am very confused that the spinner visibility won't update from here though.

Body:
Taking Sina's suggestion to use a Thread, the class now looks like:

public class MainActivity extends AppCompatActivity{

    // Irrelevant code (fields, init, other button handlers, etc...)

    private void onButtonClick(android.view.View view){
        LongRunningThread longRunningThread = new LongRunningThread();
        longRunningThread.start();
    }

    private class LongRunningThread extends Thread{
        public void run(){
            runOnUiThread(MainActivity.this::showSpinner);

            // Logic that takes 5-10 seconds to run

            runOnUiThread(MainActivity.this::hideSpinner);
        }
    }

    private void showSpinner(){
        ProgressBar progressSpinner = (ProgressBar)findViewById(R.id.progressSpinner);
        progressSpinner.setVisibility(View.VISIBLE);
    }

    private void hideSpinner(){
        ProgressBar progressSpinner = (ProgressBar)findViewById(R.id.progressSpinner);
        progressSpinner.setVisibility(View.GONE);
    }

}

Doing this shows the progress spinner while the long-running logic is running and then hides the progress spinner after the long-running logic has completed. The UI stays responsive throughout and doesn't lock up.

Compared to the original code, this uses Thread instead of ExecutorService. It also runs UI logic via AppCompatActivity.runOnUiThread().

It would seem the answer to doing any long-running tasks alongside UI updates, without locking up the UI, is to create a Thread and call Thread.start(). The Thread should contain the long-running logic as well as the UI logic. The UI logic within that Thread must be run using runOnUiThread().


问:
Compare folder size and run script if the size changed
I am trying to write a code which will carry out something with the newly added file to the folder. So, the way I see it is to calculate the folder size, compare it with the one calculated ±10 mins ago, and then to do something with the newly added file if the size of the folder did change.

```<code>while (True):
    def get_size(start_path='/Users/.../Desktop/files'):
        total_size = 0
        for dirpath, dirnames, filenames in os.walk(start_path):
            for f in filenames:
                fp = os.path.join(dirpath, f)
                # skip if it is symbolic link
                if not os.path.islink(fp):
                    total_size += os.path.getsize(fp)

        return total_size

    print(get_size(), 'bytes')
    time.sleep(10)
</code>```

The code above calculates the size of the folder every 10 seconds. I don't know how to compare it to the previous size though :(

Please, help..

答:
Tracking the total size of the directory is limiting. How about you keep a list of files and their sizes? That way you can act on changed files and new files. Using a dictionary here as a basic example, you can really make it as complicated as you wish, tracking creation, modification dates etc. If you don't want the complexity I have retained tracking of total size, however you still need to track which file(s) have changed.</p>
```<code>import os
import time

def check_dir(fh,start_path='/tmp',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,'/tmp/test',new_file,changed_file)
        if total and nt != total:
            print("Total size changed from {0} to {1}".format(total,nt))
            total = nt
        time.sleep(10)
        print("File list:\n{0}".format(file_history))
</code>```

Body:
I am trying to write a code which will carry out something with the newly added file to the folder. So, the way I see it is to calculate the folder size, compare it with the one calculated ±10 mins ago, and then to do something with the newly added file if the size of the folder did change.

while (True):
    def get_size(start_path='/Users/.../Desktop/files'):
        total_size = 0
        for dirpath, dirnames, filenames in os.walk(start_path):
            for f in filenames:
                fp = os.path.join(dirpath, f)
                # skip if it is symbolic link
                if not os.path.islink(fp):
                    total_size += os.path.getsize(fp)

        return total_size

    print(get_size(), 'bytes')
    time.sleep(10)

The code above calculates the size of the folder every 10 seconds. I don't know how to compare it to the previous size though :(

Please, help..

Body:
Tracking the total size of the directory is limiting. How about you keep a list of files and their sizes? That way you can act on changed files and new files. Using a dictionary here as a basic example, you can really make it as complicated as you wish, tracking creation, modification dates etc. If you don't want the complexity I have retained tracking of total size, however you still need to track which file(s) have changed.

import os
import time

def check_dir(fh,start_path='/tmp',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,'/tmp/test',new_file,changed_file)
        if total and nt != total:
            print("Total size changed from {0} to {1}".format(total,nt))
            total = nt
        time.sleep(10)
        print("File list:\n{0}".format(file_history))


问:
How can I execute code with a list of arguments
I want to run a process in the following way

python3 code_to_execute.py arg-1

But I want to run it for n arguments (arg-1,...,arg-n). I can run it this way

python3 code_to_execute.py arg-2
python3 code_to_execute.py arg-3
.
.
.
python3 code_to_execute.py arg-n
```

But I'd like to know if it can be run with just one line. Otherwise maybe I can create a .sh file with all the executables and run just the .sh

Thank you everyone

答:
if you are using a linux/WSL terminal, then you could use 'xargs':</p>
```<code>echo arg-1 arg-2 arg-3 | xargs -n 1 python3 code_to_execute.py
</code>```

Body:
I want to run a process in the following way

python3 code_to_execute.py arg-1

But I want to run it for n arguments (arg-1,...,arg-n). I can run it this way

python3 code_to_execute.py arg-2
python3 code_to_execute.py arg-3
.
.
.
python3 code_to_execute.py arg-n

But I'd like to know if it can be run with just one line. Otherwise maybe I can create a .sh file with all the executables and run just the .sh

Thank you everyone

Body:
if you are using a linux/WSL terminal, then you could use 'xargs':

echo arg-1 arg-2 arg-3 | xargs -n 1 python3 code_to_execute.py


问:
PHP Deprecated issue when running artisan command
Whenever I run an artisan command I am getting this issue.

I am using Valet and PHP 8.1. I have tried changing versions of PHP but I still get this issue.

When i run:

```<code>jakefeeley@Jakes-MBP marketing % php artisan plugin:install vojtasvoboda.twigextensions
</code>```

Returns:

```<code>PHP Deprecated:  Return type of Illuminate\Container\Container::offsetExists($key) should either be compatible with ArrayAccess::offsetExists(mixed $offset): bool, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /Users/jakefeeley/Sites/certhub/marketing/vendor/laravel/framework/src/Illuminate/Container/Container.php on line 1231

Deprecated: Return type of Illuminate\Container\Container::offsetExists($key) should either be compatible with ArrayAccess::offsetExists(mixed $offset): bool, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /Users/jakefeeley/Sites/certhub/marketing/vendor/laravel/framework/src/Illuminate/Container/Container.php on line 1231
PHP Deprecated:  Return type of Illuminate\Container\Container::offsetGet($key) should either be compatible with ArrayAccess::offsetGet(mixed $offset): mixed, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /Users/jakefeeley/Sites/certhub/marketing/vendor/laravel/framework/src/Illuminate/Container/Container.php on line 1242

Deprecated: Return type of October\Rain\Config\Repository::offsetGet($key) should either be compatible with ArrayAccess::offsetGet(mixed $offset): mixed, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /Users/jakefeeley/Sites/certhub/marketing/vendor/october/rain/src/Config/Repository.php on line 446
PHP Deprecated:  Return type of October\Rain\Config\Repository::offsetSet($key, $value) should either be compatible with ArrayAccess::offsetSet(mixed $offset, mixed $value): void, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /Users/jakefeeley/Sites/certhub/marketing/vendor/october/rain/src/Config/Repository.php on line 458

Deprecated: Return type of October\Rain\Config\Repository::offsetSet($key, $value) should either be compatible with ArrayAccess::offsetSet(mixed $offset, mixed $value): void, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /Users/jakefeeley/Sites/certhub/marketing/vendor/october/rain/src/Config/Repository.php on line 458
PHP Deprecated:  Return type of October\Rain\Config\Repository::offsetUnset($key) should either be compatible with ArrayAccess::offsetUnset(mixed $offset): void, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /Users/jakefeeley/Sites/certhub/marketing/vendor/october/rain/src/Config/Repository.php on line 469

Deprecated: Return type of October\Rain\Config\Repository::offsetUnset($key) should either be compatible with ArrayAccess::offsetUnset(mixed $offset): void, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /Users/jakefeeley/Sites/certhub/marketing/vendor/october/rain/src/Config/Repository.php on line 469
PHP Fatal error:  During inheritance of ArrayAccess: Uncaught ErrorException: Return type of Illuminate\Support\Collection::offsetExists($key) should either be compatible with ArrayAccess::offsetExists(mixed $offset): bool, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /Users/jakefeeley/Sites/certhub/marketing/vendor/laravel/framework/src/Illuminate/Support/Collection.php:1277
Stack trace:
#0 /Users/jakefeeley/Sites/certhub/marketing/vendor/laravel/framework/src/Illuminate/Support/Collection.php(11): Illuminate\Foundation\Bootstrap\HandleExceptions->handleError(8192, 'Return type of ...', '/Users/jakefeel...', 1277)
#1 /Users/jakefeeley/Sites/certhub/marketing/vendor/composer/ClassLoader.php(478): include('/Users/jakefeel...')
#2 /Users/jakefeeley/Sites/certhub/marketing/vendor/composer/ClassLoader.php(346): Composer\Autoload\includeFile('/Users/jakefeel...')
#3

In Collection.php line 11:

  During inheritance of ArrayAccess: Uncaught ErrorException: Return type of Illuminate\Support\Collection::offsetExists($key) should either be compatible with ArrayAccess::offsetExists(mixed $offset
  ): bool, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /Users/jakefeeley/Sites/certhub/marketing/vendor/laravel/framework/src/Illuminate/Support/Col
  lection.php:1277
  Stack trace:
  #0 /Users/jakefeeley/Sites/certhub/marketing/vendor/laravel/framework/src/Illuminate/Support/Collection.php(11): Illuminate\Foundation\Bootstrap\HandleExceptions->handleError(8192, 'Return type of
  ...', '/Users/jakefeel...', 1277)
  #1 /Users/jakefeeley/Sites/certhub/marketing/vendor/composer/ClassLoader.php(478): include('/Users/jakefeel...')
  #2 /Users/jakefeeley/Sites/certhub/marketing/vendor/composer/ClassLoader.php(346): Composer\Autoload\includeFile('/Users/jakefeel...')
  #3 /Users/jakefeeley/Sites/certhub/marketing/vendor/october/rain/src/Support/Collection.php(11): Composer\Autoload\ClassLoader->loadClass('Illuminate\\Supp...')
  #4 /Users/jakefeeley/Sites/certhub/marketing/vendor/composer/ClassLoader.php(478): include('/Users/jakefeel...')
  #5 /Users/jakefeeley/Sites/certhub/marketing/vendor/composer/ClassLoader.php(346): Composer\Autoload\includeFile('/Users/jakefeel...')
  #6 /Users/jakefeeley/Sites/certhub/marketing/vendor/october/rain/src/Support/helpers.php(269): Composer\Autoload\ClassLoader->loadClass('October\\Rain\\Su...')
  #7 /Users/jakefeeley/Sites/certhub/marketing/vendor/laravel/framework/src/Illuminate/Foundation/PackageManifest.php(89): collect(Array)
  #8 /Users/jakefeeley/Sites/certhub/marketing/vendor/laravel/framework/src/Illuminate/Foundation/PackageManifest.php(78): Illuminate\Foundation\PackageManifest->config('aliases')
  #9 /Users/jakefeeley/Sites/certhub/marketing/vendor/laravel/framework/src/Illuminate/Foundation/Bootstrap/RegisterFacades.php(26): Illuminate\Foundation\PackageManifest->aliases()
  #10 /Users/jakefeeley/Sites/certhub/marketing/vendor/laravel/framework/src/Illuminate/Foundation/Application.php(219): Illuminate\Foundation\Bootstrap\RegisterFacades->bootstrap(Object(October\Rain
  \Foundation\Application))
  #11 /Users/jakefeeley/Sites/certhub/marketing/vendor/laravel/framework/src/Illuminate/Foundation/Console/Kernel.php(320): Illuminate\Foundation\Application->bootstrapWith(Array)
  #12 /Users/jakefeeley/Sites/certhub/marketing/vendor/laravel/framework/src/Illuminate/Foundation/Console/Kernel.php(129): Illuminate\Foundation\Console\Kernel->bootstrap()
  #13 /Users/jakefeeley/Sites/certhub/marketing/artisan(35): Illuminate\Foundation\Console\Kernel->handle(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\Co
  nsoleOutput))
  #14 {main}
</code>```

答:
In my experience this is due to attempting to run Laravel 7 (or earlier) under PHP 8.1. I know you said you tried changing PHP versions, but I would double-check that your changes definitely took effect.

For Laravel 7, switching back to PHP 8.0 fixed the issue for me.

nb: Laravel 7's composer.json incorrectly specifies "php": "^7.2.5|^8.0", which implies it can run under PHP 8.1.

Body:
Whenever I run an artisan command I am getting this issue.

I am using Valet and PHP 8.1. I have tried changing versions of PHP but I still get this issue.

When i run:

jakefeeley@Jakes-MBP marketing % php artisan plugin:install vojtasvoboda.twigextensions

Returns:

PHP Deprecated:  Return type of Illuminate\Container\Container::offsetExists($key) should either be compatible with ArrayAccess::offsetExists(mixed $offset): bool, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /Users/jakefeeley/Sites/certhub/marketing/vendor/laravel/framework/src/Illuminate/Container/Container.php on line 1231

Deprecated: Return type of Illuminate\Container\Container::offsetExists($key) should either be compatible with ArrayAccess::offsetExists(mixed $offset): bool, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /Users/jakefeeley/Sites/certhub/marketing/vendor/laravel/framework/src/Illuminate/Container/Container.php on line 1231
PHP Deprecated:  Return type of Illuminate\Container\Container::offsetGet($key) should either be compatible with ArrayAccess::offsetGet(mixed $offset): mixed, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /Users/jakefeeley/Sites/certhub/marketing/vendor/laravel/framework/src/Illuminate/Container/Container.php on line 1242

Deprecated: Return type of October\Rain\Config\Repository::offsetGet($key) should either be compatible with ArrayAccess::offsetGet(mixed $offset): mixed, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /Users/jakefeeley/Sites/certhub/marketing/vendor/october/rain/src/Config/Repository.php on line 446
PHP Deprecated:  Return type of October\Rain\Config\Repository::offsetSet($key, $value) should either be compatible with ArrayAccess::offsetSet(mixed $offset, mixed $value): void, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /Users/jakefeeley/Sites/certhub/marketing/vendor/october/rain/src/Config/Repository.php on line 458

Deprecated: Return type of October\Rain\Config\Repository::offsetSet($key, $value) should either be compatible with ArrayAccess::offsetSet(mixed $offset, mixed $value): void, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /Users/jakefeeley/Sites/certhub/marketing/vendor/october/rain/src/Config/Repository.php on line 458
PHP Deprecated:  Return type of October\Rain\Config\Repository::offsetUnset($key) should either be compatible with ArrayAccess::offsetUnset(mixed $offset): void, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /Users/jakefeeley/Sites/certhub/marketing/vendor/october/rain/src/Config/Repository.php on line 469

Deprecated: Return type of October\Rain\Config\Repository::offsetUnset($key) should either be compatible with ArrayAccess::offsetUnset(mixed $offset): void, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /Users/jakefeeley/Sites/certhub/marketing/vendor/october/rain/src/Config/Repository.php on line 469
PHP Fatal error:  During inheritance of ArrayAccess: Uncaught ErrorException: Return type of Illuminate\Support\Collection::offsetExists($key) should either be compatible with ArrayAccess::offsetExists(mixed $offset): bool, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /Users/jakefeeley/Sites/certhub/marketing/vendor/laravel/framework/src/Illuminate/Support/Collection.php:1277
Stack trace:
#0 /Users/jakefeeley/Sites/certhub/marketing/vendor/laravel/framework/src/Illuminate/Support/Collection.php(11): Illuminate\Foundation\Bootstrap\HandleExceptions->handleError(8192, 'Return type of ...', '/Users/jakefeel...', 1277)
#1 /Users/jakefeeley/Sites/certhub/marketing/vendor/composer/ClassLoader.php(478): include('/Users/jakefeel...')
#2 /Users/jakefeeley/Sites/certhub/marketing/vendor/composer/ClassLoader.php(346): Composer\Autoload\includeFile('/Users/jakefeel...')
#3

In Collection.php line 11:

  During inheritance of ArrayAccess: Uncaught ErrorException: Return type of Illuminate\Support\Collection::offsetExists($key) should either be compatible with ArrayAccess::offsetExists(mixed $offset
  ): bool, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /Users/jakefeeley/Sites/certhub/marketing/vendor/laravel/framework/src/Illuminate/Support/Col
  lection.php:1277
  Stack trace:
  #0 /Users/jakefeeley/Sites/certhub/marketing/vendor/laravel/framework/src/Illuminate/Support/Collection.php(11): Illuminate\Foundation\Bootstrap\HandleExceptions->handleError(8192, 'Return type of
  ...', '/Users/jakefeel...', 1277)
  #1 /Users/jakefeeley/Sites/certhub/marketing/vendor/composer/ClassLoader.php(478): include('/Users/jakefeel...')
  #2 /Users/jakefeeley/Sites/certhub/marketing/vendor/composer/ClassLoader.php(346): Composer\Autoload\includeFile('/Users/jakefeel...')
  #3 /Users/jakefeeley/Sites/certhub/marketing/vendor/october/rain/src/Support/Collection.php(11): Composer\Autoload\ClassLoader->loadClass('Illuminate\\Supp...')
  #4 /Users/jakefeeley/Sites/certhub/marketing/vendor/composer/ClassLoader.php(478): include('/Users/jakefeel...')
  #5 /Users/jakefeeley/Sites/certhub/marketing/vendor/composer/ClassLoader.php(346): Composer\Autoload\includeFile('/Users/jakefeel...')
  #6 /Users/jakefeeley/Sites/certhub/marketing/vendor/october/rain/src/Support/helpers.php(269): Composer\Autoload\ClassLoader->loadClass('October\\Rain\\Su...')
  #7 /Users/jakefeeley/Sites/certhub/marketing/vendor/laravel/framework/src/Illuminate/Foundation/PackageManifest.php(89): collect(Array)
  #8 /Users/jakefeeley/Sites/certhub/marketing/vendor/laravel/framework/src/Illuminate/Foundation/PackageManifest.php(78): Illuminate\Foundation\PackageManifest->config('aliases')
  #9 /Users/jakefeeley/Sites/certhub/marketing/vendor/laravel/framework/src/Illuminate/Foundation/Bootstrap/RegisterFacades.php(26): Illuminate\Foundation\PackageManifest->aliases()
  #10 /Users/jakefeeley/Sites/certhub/marketing/vendor/laravel/framework/src/Illuminate/Foundation/Application.php(219): Illuminate\Foundation\Bootstrap\RegisterFacades->bootstrap(Object(October\Rain
  \Foundation\Application))
  #11 /Users/jakefeeley/Sites/certhub/marketing/vendor/laravel/framework/src/Illuminate/Foundation/Console/Kernel.php(320): Illuminate\Foundation\Application->bootstrapWith(Array)
  #12 /Users/jakefeeley/Sites/certhub/marketing/vendor/laravel/framework/src/Illuminate/Foundation/Console/Kernel.php(129): Illuminate\Foundation\Console\Kernel->bootstrap()
  #13 /Users/jakefeeley/Sites/certhub/marketing/artisan(35): Illuminate\Foundation\Console\Kernel->handle(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\Co
  nsoleOutput))
  #14 {main}


问:
Is for(1) always the same as do in perl?
```<code>for(1){
  print 1;
}

do {
  print 1;
}
</code>```

Is it true?

Or is there any special case these two doesn't equal?

答:
About the same.

You can next, last and redo a for loop, but a do is not a loop--including as part of a do-while "loop". So in a non-trivial block, you couldn't be sure. However, this will work:

```<code>do {{
    ...
}};
</code>```

Also do will not automatically set $_ to each member of the list, the way a bare for loop will.

Body:
for(1){
  print 1;
}

do {
  print 1;
}

Is it true?

Or is there any special case these two doesn't equal?

Body:
About the same.

You can next, last and redo a for loop, but a do is not a loop--including as part of a do-while "loop". So in a non-trivial block, you couldn't be sure. However, this will work:

do {{
    ...
}};

Also do will not automatically set $_ to each member of the list, the way a bare for loop will.


问:
no pointerenter event if you touch and then move into element
I'm trying to build a React app where a user touches one element and then moves to a neighboring element while still holding down. The pointerover and pointerenter events fire when the user touches the first element, but not when the user moves the pointer to the neighboring element. I would like to know when the pointer enters any element, regardless of whether the touch started in that element. (If the pointer element is a mouse instead of touch, this point and drag behavior does work as I expect.)

Example code pen trying out various events: https://codepen.io/skedwards88/pen/OJOXwRm If you use a mouse, the pointerover and pointerenter events are fired when you enter an element even if the mouse was clicked and then dragged into the element. (This is my desired behavior.) However, if you use touch, when you touch down and then move the touch into a different element, the pointerover and pointerenter are not fired for that second element.

Code from the codepen

JSX

function App() {

  function myF(e, myv) {
    // e.preventDefault()
    console.log(`POINTER ${myv}`)
  }

  return (

 myF(e, "a")}>pointer move

 myF(e, "b")}>pointer move

 myF(e, "a")}>pointer over

 myF(e, "b")}>pointer over

 myF(e, "a")}>pointer enter

 myF(e, "b")}>pointer enter

 myF(e, "a")}>pointer move capture

 myF(e, "b")}>pointer move capture

 myF(e, "a")}>pointer move, touch-action none

 myF(e, "b")}>pointer move, touch-action none

 myF(e, "a")}>pointer over, touch-action none

 myF(e, "b")}>pointer over, touch-action none

 myF(e, "a")}>pointer enter, touch-action none

 myF(e, "b")}>pointer enter, touch-action none

 myF(e, "a")}>pointer move capture, touch-action none

 myF(e, "b")}>pointer move capture, touch-action none

 myF(e, "a")}>touch move

 myF(e, "b")}>touch move

 myF(e, "a")}>Touch move capture

 myF(e, "b")}>Touch move capture

 myF(e, "a")}>mouse move

 myF(e, "b")}>mouse move

 myF(e, "a")}>mouse over

 myF(e, "b")}>mouse over

 myF(e, "a")}>mouse enter

 myF(e, "b")}>mouse enter

 myF(e, "a")}>mouse move capture

 myF(e, "b")}>mouse move capture

  );
}

ReactDOM.render(<App />,
document.getElementById("root"))
```
<h3>CSS</h3>
<pre class="lang-css prettyprint-override"><code>.App {
  display: flex;
  flex-direction: row;
}

div {
  border: 1px solid black;
  padding: 10px;
}

.no-touch {
  touch-action: none;
/*   pointer-events: all; */
}
</code>```

HTML

```

答: I made a newbie mistake of declaring the functional component within the top level App component. More details here for anyone else having this same problem: https://github.com/facebook/react/issues/23238#issuecomment-1031936780</p>

Body:
I'm trying to build a React app where a user touches one element and then moves to a neighboring element while still holding down. The pointerover and pointerenter events fire when the user touches the first element, but not when the user moves the pointer to the neighboring element. I would like to know when the pointer enters any element, regardless of whether the touch started in that element. (If the pointer element is a mouse instead of touch, this point and drag behavior does work as I expect.)

Example code pen trying out various events: https://codepen.io/skedwards88/pen/OJOXwRm If you use a mouse, the pointerover and pointerenter events are fired when you enter an element even if the mouse was clicked and then dragged into the element. (This is my desired behavior.) However, if you use touch, when you touch down and then move the touch into a different element, the pointerover and pointerenter are not fired for that second element.

Code from the codepen

JSX

function App() {

  function myF(e, myv) {
    // e.preventDefault()
    console.log(`POINTER ${myv}`)
  }

  return (

 myF(e, "a")}>pointer move

 myF(e, "b")}>pointer move

 myF(e, "a")}>pointer over

 myF(e, "b")}>pointer over

 myF(e, "a")}>pointer enter

 myF(e, "b")}>pointer enter

 myF(e, "a")}>pointer move capture

 myF(e, "b")}>pointer move capture

 myF(e, "a")}>pointer move, touch-action none

 myF(e, "b")}>pointer move, touch-action none

 myF(e, "a")}>pointer over, touch-action none

 myF(e, "b")}>pointer over, touch-action none

 myF(e, "a")}>pointer enter, touch-action none

 myF(e, "b")}>pointer enter, touch-action none

 myF(e, "a")}>pointer move capture, touch-action none

 myF(e, "b")}>pointer move capture, touch-action none

 myF(e, "a")}>touch move

 myF(e, "b")}>touch move

 myF(e, "a")}>Touch move capture

 myF(e, "b")}>Touch move capture

 myF(e, "a")}>mouse move

 myF(e, "b")}>mouse move

 myF(e, "a")}>mouse over

 myF(e, "b")}>mouse over

 myF(e, "a")}>mouse enter

 myF(e, "b")}>mouse enter

 myF(e, "a")}>mouse move capture

 myF(e, "b")}>mouse move capture

  );
}

ReactDOM.render(<App />,
document.getElementById("root"))

CSS

.App {
  display: flex;
  flex-direction: row;
}

div {
  border: 1px solid black;
  padding: 10px;
}

.no-touch {
  touch-action: none;
/*   pointer-events: all; */
}

HTML


问:
Keycloak.json configuration file import
I have configured my goclient with keycloak.I am reading the keycloak server details from keycloak.json file which is present inside my Go client.

My whole setup is in Kubernetes cluster.Everytime when new keycloak server comes up how should I pass keycloak.json file to the Go client so that it can read the details from json file?

Is there a way I can get the keycloak.json file with all the client configuration details without having to login to keycloak and download it ?

```<code>  "realm": "SolutionAdmin",
  "auth-server-url": "localhost:8081/auth",
  "ssl-required": "none",
  "resource": "admin",
  "credentials": {
    "secret": "6ee0f523-c392-4406-bb14-ba315125c6ea"
  },
  "confidential-port": 0
}
</code>```

答:
if you want to have a pre-configured embedded keycloak server, you'll need to extend KeycloakApplication and have it configured to trigger in lieu of the base class. in this example, KeycloakProperties is just a representation of all the keycloak properties we used in application.properties. but you can get the gist of it. fair warning: i did not write this, but am figuring out how a coworker did for another project.

```<code>public class EmbeddedKeycloakApplication extends KeycloakApplication {

  public final KeycloakProperties keycloakProperties;

  public EmbeddedKeycloakApplication() {

    super();

    keycloakProperties = SpringContextAdapter.getBean(KeycloakProperties.class);
    System.getProperties().putAll(keycloakProperties.getRealmProperties());

    createMasterRealmAdminUser();

    createRealm();
  }

  private void createMasterRealmAdminUser() {

    log.debug("Creating administrative user.");

    String username = keycloakProperties.getServer(KeycloakProperties.ADMIN_USER_USERNAME);
    String password = keycloakProperties.getServer(KeycloakProperties.ADMIN_USER_PASSWORD);
    String email = keycloakProperties.getServer(KeycloakProperties.ADMIN_USER_EMAIL);

    KeycloakSession session = getSessionFactory().create();
    ApplianceBootstrap applianceBootstrap = new ApplianceBootstrap(session);

    try {
      session.getTransactionManager().begin();

      if (!applianceBootstrap.isNoMasterUser()) {
        log.debug("Administrative user already exists. No work to do.");
        return;
      }

      applianceBootstrap.createMasterRealmUser(username, password);
      RealmModel adminRealm = session.realms().getRealm(Config.getAdminRealm());
      UserModel adminUser = session.users().getUserByUsername(username, adminRealm);
      adminUser.setEmail(email);
      adminUser.setEmailVerified(true);
      session.getTransactionManager().commit();
      log.info("Created administrative user {}", username);
    } catch (Exception ex) {
      log.error("Couldn't create keycloak master admin user: {}", ex.getMessage());
      session.getTransactionManager().rollback();
    }

    session.close();
  }

  private void createRealm() {

    String realmImportFilename = keycloakProperties.getRealmImportFile();
    KeycloakSession session = getSessionFactory().create();
    String realmId = keycloakProperties.getRealm(KeycloakProperties.REALM_ID);

    try {
      session.getTransactionManager().begin();

      RealmManager manager = new RealmManager(session);

      if (manager.getRealm(realmId) != null) {
        log.debug("{} realm already exists. No work to do.", realmId);
        return;
      }

      Resource realmImportFile = new ClassPathResource(realmImportFilename);

      RealmRepresentation rep =
          JsonSerialization.readValue(
              realmImportFile.getInputStream(), RealmRepresentation.class, true);
      manager.importRealm(rep);
      log.info("Imported Realm json file {}", realmImportFilename);
      session.getTransactionManager().commit();
    } catch (Exception e) {
      log.error("Failed to import Realm json file {}: {}", realmImportFilename, e.getMessage(), e);
      session.getTransactionManager().rollback();
    }

    session.close();
  }

}

</code>```
```<code>@Configuration
public class EmbeddedKeycloakConfig {

  @Bean
  ServletRegistrationBean<HttpServlet30Dispatcher> keycloakJaxRsApplication(
      KeycloakProperties keycloakProperties, DataSource dataSource) throws NamingException {

    mockJndiEnvironment(dataSource);

    var contextPath = keycloakProperties.getServer(KeycloakProperties.SERVER_CONTEXT_PATH);

    ServletRegistrationBean<HttpServlet30Dispatcher> servlet =
        new ServletRegistrationBean<>(new HttpServlet30Dispatcher());
    servlet.addInitParameter(
        "javax.ws.rs.Application", EmbeddedKeycloakApplication.class.getName());
    servlet.addInitParameter(
        ResteasyContextParameters.RESTEASY_SERVLET_MAPPING_PREFIX, contextPath);
    servlet.addInitParameter(ResteasyContextParameters.RESTEASY_USE_CONTAINER_FORM_PARAMS, "true");
    servlet.addInitParameter(ResteasyContextParameters.RESTEASY_DISABLE_HTML_SANITIZER, "true");
    servlet.addUrlMappings(contextPath + "/*");
    servlet.setLoadOnStartup(1);
    servlet.setAsyncSupported(true);

    return servlet;
  }

  @Bean
  FilterRegistrationBean<EmbeddedKeycloakRequestFilter> keycloakSessionManagement(
      KeycloakProperties keycloakProperties) {

    FilterRegistrationBean<EmbeddedKeycloakRequestFilter> filter = new FilterRegistrationBean<>();
    filter.setName("Keycloak Session Management");
    filter.setFilter(new EmbeddedKeycloakRequestFilter());
    filter.addUrlPatterns(
        keycloakProperties.getServer(KeycloakProperties.SERVER_CONTEXT_PATH) + "/*");

    return filter;
  }

  private void mockJndiEnvironment(DataSource dataSource) throws NamingException {
    NamingManager.setInitialContextFactoryBuilder(
        env ->
            environment ->
                new InitialContext() {

                  @Override
                  public Object lookup(Name name) {
                    return lookup(name.toString());
                  }

                  @Override
                  public Object lookup(String name) {

                    if ("spring/datasource".equals(name)) {
                      return dataSource;
                    }

                    return null;
                  }

                  @Override
                  public NameParser getNameParser(String name) {
                    return CompositeName::new;
                  }

                  @Override
                  public void close() {
                    // NOOP
                  }
                });
  }
}
</code>```

Title: Keycloak.json configuration file import

Body:
I have configured my goclient with keycloak.I am reading the keycloak server details from keycloak.json file which is present inside my Go client.

My whole setup is in Kubernetes cluster.Everytime when new keycloak server comes up how should I pass keycloak.json file to the Go client so that it can read the details from json file?

Is there a way I can get the keycloak.json file with all the client configuration details without having to login to keycloak and download it ?

  "realm": "SolutionAdmin",
  "auth-server-url": "localhost:8081/auth",
  "ssl-required": "none",
  "resource": "admin",
  "credentials": {
    "secret": "6ee0f523-c392-4406-bb14-ba315125c6ea"
  },
  "confidential-port": 0
}

Body:
if you want to have a pre-configured embedded keycloak server, you'll need to extend KeycloakApplication and have it configured to trigger in lieu of the base class. in this example, KeycloakProperties is just a representation of all the keycloak properties we used in application.properties. but you can get the gist of it. fair warning: i did not write this, but am figuring out how a coworker did for another project.

public class EmbeddedKeycloakApplication extends KeycloakApplication {

  public final KeycloakProperties keycloakProperties;

  public EmbeddedKeycloakApplication() {

    super();

    keycloakProperties = SpringContextAdapter.getBean(KeycloakProperties.class);
    System.getProperties().putAll(keycloakProperties.getRealmProperties());

    createMasterRealmAdminUser();

    createRealm();
  }

  private void createMasterRealmAdminUser() {

    log.debug("Creating administrative user.");

    String username = keycloakProperties.getServer(KeycloakProperties.ADMIN_USER_USERNAME);
    String password = keycloakProperties.getServer(KeycloakProperties.ADMIN_USER_PASSWORD);
    String email = keycloakProperties.getServer(KeycloakProperties.ADMIN_USER_EMAIL);

    KeycloakSession session = getSessionFactory().create();
    ApplianceBootstrap applianceBootstrap = new ApplianceBootstrap(session);

    try {
      session.getTransactionManager().begin();

      if (!applianceBootstrap.isNoMasterUser()) {
        log.debug("Administrative user already exists. No work to do.");
        return;
      }

      applianceBootstrap.createMasterRealmUser(username, password);
      RealmModel adminRealm = session.realms().getRealm(Config.getAdminRealm());
      UserModel adminUser = session.users().getUserByUsername(username, adminRealm);
      adminUser.setEmail(email);
      adminUser.setEmailVerified(true);
      session.getTransactionManager().commit();
      log.info("Created administrative user {}", username);
    } catch (Exception ex) {
      log.error("Couldn't create keycloak master admin user: {}", ex.getMessage());
      session.getTransactionManager().rollback();
    }

    session.close();
  }

  private void createRealm() {

    String realmImportFilename = keycloakProperties.getRealmImportFile();
    KeycloakSession session = getSessionFactory().create();
    String realmId = keycloakProperties.getRealm(KeycloakProperties.REALM_ID);

    try {
      session.getTransactionManager().begin();

      RealmManager manager = new RealmManager(session);

      if (manager.getRealm(realmId) != null) {
        log.debug("{} realm already exists. No work to do.", realmId);
        return;
      }

      Resource realmImportFile = new ClassPathResource(realmImportFilename);

      RealmRepresentation rep =
          JsonSerialization.readValue(
              realmImportFile.getInputStream(), RealmRepresentation.class, true);
      manager.importRealm(rep);
      log.info("Imported Realm json file {}", realmImportFilename);
      session.getTransactionManager().commit();
    } catch (Exception e) {
      log.error("Failed to import Realm json file {}: {}", realmImportFilename, e.getMessage(), e);
      session.getTransactionManager().rollback();
    }

    session.close();
  }

}

@Configuration
public class EmbeddedKeycloakConfig {

  @Bean
  ServletRegistrationBean<HttpServlet30Dispatcher> keycloakJaxRsApplication(
      KeycloakProperties keycloakProperties, DataSource dataSource) throws NamingException {

    mockJndiEnvironment(dataSource);

    var contextPath = keycloakProperties.getServer(KeycloakProperties.SERVER_CONTEXT_PATH);

    ServletRegistrationBean<HttpServlet30Dispatcher> servlet =
        new ServletRegistrationBean<>(new HttpServlet30Dispatcher());
    servlet.addInitParameter(
        "javax.ws.rs.Application", EmbeddedKeycloakApplication.class.getName());
    servlet.addInitParameter(
        ResteasyContextParameters.RESTEASY_SERVLET_MAPPING_PREFIX, contextPath);
    servlet.addInitParameter(ResteasyContextParameters.RESTEASY_USE_CONTAINER_FORM_PARAMS, "true");
    servlet.addInitParameter(ResteasyContextParameters.RESTEASY_DISABLE_HTML_SANITIZER, "true");
    servlet.addUrlMappings(contextPath + "/*");
    servlet.setLoadOnStartup(1);
    servlet.setAsyncSupported(true);

    return servlet;
  }

  @Bean
  FilterRegistrationBean<EmbeddedKeycloakRequestFilter> keycloakSessionManagement(
      KeycloakProperties keycloakProperties) {

    FilterRegistrationBean<EmbeddedKeycloakRequestFilter> filter = new FilterRegistrationBean<>();
    filter.setName("Keycloak Session Management");
    filter.setFilter(new EmbeddedKeycloakRequestFilter());
    filter.addUrlPatterns(
        keycloakProperties.getServer(KeycloakProperties.SERVER_CONTEXT_PATH) + "/*");

    return filter;
  }

  private void mockJndiEnvironment(DataSource dataSource) throws NamingException {
    NamingManager.setInitialContextFactoryBuilder(
        env ->
            environment ->
                new InitialContext() {

                  @Override
                  public Object lookup(Name name) {
                    return lookup(name.toString());
                  }

                  @Override
                  public Object lookup(String name) {

                    if ("spring/datasource".equals(name)) {
                      return dataSource;
                    }

                    return null;
                  }

                  @Override
                  public NameParser getNameParser(String name) {
                    return CompositeName::new;
                  }

                  @Override
                  public void close() {
                    // NOOP
                  }
                });
  }
}


问:
Firebase sendPasswordResetEmail doesn't send email
I have a problem concerning my application using firebase: If I want to enable the users to reset their password themselves firebase doesn't send an email to their address. If I do it myself from the firebase console it works fine. I'm trying it like this:

```<code>   resetPassword(email: string) {
        sendPasswordResetEmail(this.auth, email)
            .then(() => {
                // Password reset email sent!
                // ..
            })
            .catch((error) => {
                const errorCode = error.code;
                const errorMessage = error.message;
                // ..
            });
    }
</code>```

Has someone some insights for me, why this isn't working? I get my auth like this:

```<code>this.firebaseApp = initializeApp(environment.firebaseConfig);
this.auth = getAuth(firebaseApp);
</code>```

I am using the Firebase Modular SDK (V9.0.0+).

I would be really grateful if someone can help me!
Cheers!

答:
sorry for not providing the most useful answer, what I suggest is:

Verify the console is not throwing Firebase errors

Validate that the firebase env variables are correct

Body:
I have a problem concerning my application using firebase: If I want to enable the users to reset their password themselves firebase doesn't send an email to their address. If I do it myself from the firebase console it works fine. I'm trying it like this:

   resetPassword(email: string) {
        sendPasswordResetEmail(this.auth, email)
            .then(() => {
                // Password reset email sent!
                // ..
            })
            .catch((error) => {
                const errorCode = error.code;
                const errorMessage = error.message;
                // ..
            });
    }

Has someone some insights for me, why this isn't working? I get my auth like this:

this.firebaseApp = initializeApp(environment.firebaseConfig);
this.auth = getAuth(firebaseApp);

I am using the Firebase Modular SDK (V9.0.0+).

I would be really grateful if someone can help me!
Cheers!