问:
Acquiring the class object of the class which was annotated with @ContextConfiguration?
This problem isn't a showstopper, but I've been wondering if it is possible to acquire the class object of the class (the test class) which was annotated with @ContextConfiguration("mycontext.xml") from a bean's code defined in mycontext.xml?

The motive:

In my current project I keep quite a few test spring contexts, which have become more and more similar to eachother over the months (so instead of fine-tuning each, I've started just pulling in everything lazily). It has come to a point where they mostly differ only in the database initialization script(s) they run with  (if they differ at all to begin with).
So I was thinking of a neat way of getting rid of all the context xmls which contain nothing but an import and and an init-db tag.

The solution I'm primarily looking for:

Annotate the unit test classes with an annotation which somehow sets the paths to the db init scripts I'd like to run for the test cases. Injecting property-placeholder value(s) would more or less do it, but it would be nice to be able to run 1..n db scripts.

I recon that with BeanFactoryPostProcessors and BeanPostProcessors a lot can be achieved, but for starters, how do I acquire the magic annotation I put on my test class?

I hope this post makes some sense, any input is welcome :)

答:
I you use JUnit, then there is an other Pitfall that you mayby not have considered yet. Junit create an NEW instance of the test class for EACH test case!

I have the feeling that you try do do the whole stuff in the wrong way, or lets say a to complicated one.

Why not have a small spring configuration fill for each db script that include the core spring configuration and also reference the db init script.
Then you can use the @ContextConfiguration for that specific configuration.

Example

junit test case

```<code>@RunWith(SpringJUnit4ClassRunner.class)
@Transactional
@ContextConfiguration("classpath:/META-INF/spring/config1.xml")
public class MyTest {...}
</code>```

config1.xml

```<code>...
<import resource="classpath:/META-INF/spring/applicationContext.xml" />
<bean class="MyDbScript">
   <property name="file" value"classpath:/SCRIPTS/config1.sql" />
</bean>
...
</code>```

An other solution would be not automatically setup the database on startup, but after an invocation.
I am not 100% sure if its work, because I do not know if @Before annotated test methods run before or after Spring has injected the beans in the test case.

Assume you have a bean of class HandTriggeredDbScriptExecutor that has a method run which takes the script to run:

```<code>@RunWith(SpringJUnit4ClassRunner.class)
@Transactional
@ContextConfiguration("classpath:/META-INF/spring/applicationContext.xml")
public class MyTest {

    @Autowire
    HandTriggeredDbScriptExecutor handTriggeredDbScriptExecutor;

    @Before
    public void setUpDb() {
       this.handTriggeredDbScriptExecutor.run("classpath:/SCRIPTS/config1.sql");
    }
}
</code>```

Body:
I you use JUnit, then there is an other Pitfall that you mayby not have considered yet. Junit create an NEW instance of the test class for EACH test case!

I have the feeling that you try do do the whole stuff in the wrong way, or lets say a to complicated one.

Why not have a small spring configuration fill for each db script that include the core spring configuration and also reference the db init script.
Then you can use the @ContextConfiguration for that specific configuration.

Example

junit test case

@RunWith(SpringJUnit4ClassRunner.class)
@Transactional
@ContextConfiguration("classpath:/META-INF/spring/config1.xml")
public class MyTest {...}

config1.xml

...
<import resource="classpath:/META-INF/spring/applicationContext.xml" />
<bean class="MyDbScript">
   <property name="file" value"classpath:/SCRIPTS/config1.sql" />
</bean>
...

An other solution would be not automatically setup the database on startup, but after an invocation.
I am not 100% sure if its work, because I do not know if @Before annotated test methods run before or after Spring has injected the beans in the test case.

Assume you have a bean of class HandTriggeredDbScriptExecutor that has a method run which takes the script to run:

@RunWith(SpringJUnit4ClassRunner.class)
@Transactional
@ContextConfiguration("classpath:/META-INF/spring/applicationContext.xml")
public class MyTest {

    @Autowire
    HandTriggeredDbScriptExecutor handTriggeredDbScriptExecutor;

    @Before
    public void setUpDb() {
       this.handTriggeredDbScriptExecutor.run("classpath:/SCRIPTS/config1.sql");
    }
}


来源: stackexchange

问:
Keras: where are the input_length, input_dim, output_dim, etc
when I try to build a lstm model using keras. I see lots of models on internet that have a parameters setting like the code as follows:

```<code>from keras.models import Sequential
from keras.layers.recurrent import LSTM
model = Sequential()

model.add(LSTM(output_dim=32,
               input_shape=(2, 3),
               activation='relu',
               return_sequences=True))
model.compile(loss='mae', optimizer='adam', metrics=['accuracy'])
</code>```

but when i refer to the documents in the keras website, I didn't see any parameters named input shape or output dim. why is that?
enter image description here

答:
As given in the Tensorflow document https://www.tensorflow.org/api_docs/python/tf/keras/layers/LSTM

tf.keras.layers.LSTM expects units as parameter for output_dim as a result of output number of neurons.

```<code>tf.keras.layers.LSTM(
    units, activation='tanh', recurrent_activation='sigmoid',
    use_bias=True, kernel_initializer='glorot_uniform',
    recurrent_initializer='orthogonal',
    bias_initializer='zeros', unit_forget_bias=True,
    kernel_regularizer=None, recurrent_regularizer=None, bias_regularizer=None,
    activity_regularizer=None, kernel_constraint=None, recurrent_constraint=None,
    bias_constraint=None, dropout=0.0, recurrent_dropout=0.0,
    return_sequences=False, return_state=False, go_backwards=False, stateful=False,
    time_major=False, unroll=False, **kwargs
)
</code>```

Your code should be

```<code>from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import LSTM
model = Sequential()

model.add(LSTM(units=32,
               input_shape=(2, 3),
               activation='relu',
               return_sequences=True))
model.compile(loss='mae', optimizer='adam', metrics=['accuracy'])
</code>```

ContentLicense: CC BY-SA 4.0

Body:
when I try to build a lstm model using keras. I see lots of models on internet that have a parameters setting like the code as follows:

from keras.models import Sequential
from keras.layers.recurrent import LSTM
model = Sequential()

model.add(LSTM(output_dim=32,
               input_shape=(2, 3),
               activation='relu',
               return_sequences=True))
model.compile(loss='mae', optimizer='adam', metrics=['accuracy'])

but when i refer to the documents in the keras website, I didn't see any parameters named input shape or output dim. why is that?
enter image description here

Body:
As given in the Tensorflow document https://www.tensorflow.org/api_docs/python/tf/keras/layers/LSTM

tf.keras.layers.LSTM expects units as parameter for output_dim as a result of output number of neurons.

tf.keras.layers.LSTM(
    units, activation='tanh', recurrent_activation='sigmoid',
    use_bias=True, kernel_initializer='glorot_uniform',
    recurrent_initializer='orthogonal',
    bias_initializer='zeros', unit_forget_bias=True,
    kernel_regularizer=None, recurrent_regularizer=None, bias_regularizer=None,
    activity_regularizer=None, kernel_constraint=None, recurrent_constraint=None,
    bias_constraint=None, dropout=0.0, recurrent_dropout=0.0,
    return_sequences=False, return_state=False, go_backwards=False, stateful=False,
    time_major=False, unroll=False, **kwargs
)

Your code should be

from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import LSTM
model = Sequential()

model.add(LSTM(units=32,
               input_shape=(2, 3),
               activation='relu',
               return_sequences=True))
model.compile(loss='mae', optimizer='adam', metrics=['accuracy'])


问:
how to remove index.php from the url in laravel
suppose my site open with the url https://www.example.com and it also opens with the https://www.example.com/index.php but i want it to open only with the https://www.example.com ONLY and not with https://www.example.com/index.php

just want to know how to remove index.php from my url

答:
You can create a route with https://www.example.com/index.php that will redirect to user to https://www.example.com whenever user try to access https://www.example.com/index.php.

Eg. In you web.php file you can add a route like this.

```<code>Route::get('https://www.example.com/index.php', function () {
    return redirect('https://www.example.com');
});
</code>```

Body:
You can create a route with https://www.example.com/index.php that will redirect to user to https://www.example.com whenever user try to access https://www.example.com/index.php.

Eg. In you web.php file you can add a route like this.

Route::get('https://www.example.com/index.php', function () {
    return redirect('https://www.example.com');
});


问:
How do I crop a video steam that's already been resized?
I'm using PILs ImageGrab function to capture an application window in real-time for image detection with OpenCV. I've managed to scale the captured window down to increase the speed of image detection. However, I'm getting a number of false positives I can't seem to avoid. I actually only need to capture a small section of the window 761 34 1142 68

```<code>while True:
    # Grab PSS Window and find size
    window = pygetwindow.getWindowsWithTitle('App')[0]
    x1 = window.left
    y1 = window.top
    height = window.height
    width = window.width
    x2 = x1 + width
    y2 = y1 + height
    # Actual Video Loop, cropped down to the specific window,
    # resized to 1/2 size, and converted to BGR for OpenCV
    haystack_img = ImageGrab.grab(bbox=(x1, y1, x2, y2))
    (width, height) = (haystack_img.width // 2, haystack_img.height // 2)
    haystack_img_resized = haystack_img.resize((width, height))

    ########### Line in Question ##############
    haystack_img_cropped = haystack_img_resized[761: 34, 1142:68]

    haystack_img_np = np.array(haystack_img_cropped)
    haystack = cv.cvtColor(haystack_img_np, cv.COLOR_BGR2GRAY)
    cv.imshow("Screen", haystack)
</code>```

I tried using OpenCV to slice  the image but I get the error:

```<code>C:\Users\coyle\OneDrive\froggy-pirate-master\avoidShips>C:/Users/coyle/AppData/Local/Programs/Python/Python39/python.exe c:/Users/coyle/OneDrive/froggy-pirate-master/avoidShips/avoidShipActual/test7.py
Traceback (most recent call last):
  File "c:\Users\test7.py", line 103, in <module>
    objectDetection(ships_to_avoid, 0.92)
  File "c:\Users\test7.py", line 61, in objectDetection
    haystack_img_cropped = haystack_img_resized[761:34, 1142:68]
TypeError: 'Image' object is not subscriptable
</code>```

And I tried the .crop method:

```<code> haystack_img_resized = haystack_img.resize((width, height))
 haystack_img_resized.crop((761,34,1164,65))
 haystack_img_np = np.array(haystack_img_resized)
</code>```

which produces no error but hasn't actually cropped anything.

How do I crop my video stream?

答:
haystack_img_cropped = np.array(haystack_img_resized)[761: 34, 1142:68] should work.

For your questions,

You have to convert PIL's Image to Numpy's array before slicing.

.crop() returns new modified PIL's Image instance rather than modifying the existing one. PIL's methods typically return a new Image instance.

Body:
I'm using PILs ImageGrab function to capture an application window in real-time for image detection with OpenCV. I've managed to scale the captured window down to increase the speed of image detection. However, I'm getting a number of false positives I can't seem to avoid. I actually only need to capture a small section of the window 761 34 1142 68

while True:
    # Grab PSS Window and find size
    window = pygetwindow.getWindowsWithTitle('App')[0]
    x1 = window.left
    y1 = window.top
    height = window.height
    width = window.width
    x2 = x1 + width
    y2 = y1 + height
    # Actual Video Loop, cropped down to the specific window,
    # resized to 1/2 size, and converted to BGR for OpenCV
    haystack_img = ImageGrab.grab(bbox=(x1, y1, x2, y2))
    (width, height) = (haystack_img.width // 2, haystack_img.height // 2)
    haystack_img_resized = haystack_img.resize((width, height))

    ########### Line in Question ##############
    haystack_img_cropped = haystack_img_resized[761: 34, 1142:68]

    haystack_img_np = np.array(haystack_img_cropped)
    haystack = cv.cvtColor(haystack_img_np, cv.COLOR_BGR2GRAY)
    cv.imshow("Screen", haystack)

I tried using OpenCV to slice  the image but I get the error:

C:\Users\coyle\OneDrive\froggy-pirate-master\avoidShips>C:/Users/coyle/AppData/Local/Programs/Python/Python39/python.exe c:/Users/coyle/OneDrive/froggy-pirate-master/avoidShips/avoidShipActual/test7.py
Traceback (most recent call last):
  File "c:\Users\test7.py", line 103, in <module>
    objectDetection(ships_to_avoid, 0.92)
  File "c:\Users\test7.py", line 61, in objectDetection
    haystack_img_cropped = haystack_img_resized[761:34, 1142:68]
TypeError: 'Image' object is not subscriptable

And I tried the .crop method:

 haystack_img_resized = haystack_img.resize((width, height))
 haystack_img_resized.crop((761,34,1164,65))
 haystack_img_np = np.array(haystack_img_resized)

which produces no error but hasn't actually cropped anything.

How do I crop my video stream?


问:
Is it possible to change playback speed of only one MovieClip without changing framerate using only AS3?
Is it possible to change playback speed of only one MovieClip without changing framerate using only AS3? I mean, is there any function/property in MovieClip or somewhere that changes the playback speed of ONLY one MovieClip at the same time not affecting general framerate? Thank you in advance :-) </p>

答:
using Timer class u can do that.

but, Timer will vary depends on the swf's framrate or available memory and other factors.

for more click here

ContentLicense: CC BY-SA 3.0


问:
how to connect storage account to AAS using powershell script in azure function

## Get the storage account from which container has to be retrieved

```<code>$StorageKey = Get-AzStorageAccountKey -ResourceGroupName $resourceGroupName -Name $storageAccName
</code>```

getting error:
[Error] Import-AzContext : The term 'Import-AzContext' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.at run.ps1: line 3+ Import-AzContext+ ________________+ CategoryInfo          : ObjectNotFound: (Import-AzContext:String) [], CommandNotFoundException+ FullyQualifiedErrorId : CommandNotFoundException
2022-02-08T10:26:01.327 [Error] : Cannot process command because of one or more missing mandatory parameters: Name.at run.ps1: line 4+++ CategoryInfo          : InvalidArgument: (:) [Import-Module], ParameterBindingException+ FullyQualifiedErrorId : MissingMandatoryParameter,Microsoft.PowerShell.Commands.ImportModuleCommand,run.ps1
2022-02-08T10:26:01.468 [Error] param : The term 'param' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.at run.ps1: line 7+ param+ _____+ CategoryInfo          : ObjectNotFound: (param:String) [], CommandNotFoundException+ FullyQualifiedErrorId : CommandNotFoundException
2022-02-08T10:26:01.546 [Error] Exception while executing function: Functions.HttpTrigger2. Microsoft.Azure.WebJobs.Script: PowerShell script error. System.Management.Automation: The term 'Import-AzContext' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
2022-02-08T10:26:01.561 [Error] Function completed (Failure, Id=2339b513-6a62-4687-b418-c31db73fd8c8, Duration=408ms)

答:
When I ran this command from my PowerShell Get-AzStorageAccountKey -ResourceGroupName MyResourceGroupName -Name MyStorageAccountName It showed output like this:

If your desired output is like this then you can update your PowerShell Az module once by running this command: Update-Module Az -Force.

After successfully updating then try again.

If you didn't install Az Module yet then you need to install that module first. You can follow the following steps:

Install the Azure Az PowerShell Module

The Azure Az PowerShell module is a rollup module. Installing it downloads the generally available Az PowerShell modules, and makes their cmdlets available for use.
Azure PowerShell has no additional requirements when run on PowerShell 7.0.6 LTS and PowerShell 7.1.3 or higher. To check your PowerShell version, run the following command from within a PowerShell session:

```<code>$PSVersionTable.PSVersion
</code>```

Install the latest version of PowerShell available for your operating system from here.

The Azure Az PowerShell module is also supported for use with PowerShell 5.1 on Windows. To use the Azure Az PowerShell module in PowerShell 5.1 on Windows:

Update to Windows PowerShell 5.1. If you're on Windows 10 version 1607 or higher, you already have PowerShell 5.1 installed.

Install .NET Framework 4.7.2 or later.

Make sure you have the latest version of PowerShellGet. Run this command.

```<code>Install-Module -Name PowerShellGet -Force
</code>```

Now set the execution policy. PowerShell script execution policy must be set to remote signed or less restrictive. Get-ExecutionPolicy -List can be used to determine the current execution policy. Run this command:

```<code>Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
</code>```

Using the Install-Module cmdlet is the preferred installation method for the Az PowerShell module. Install the Az module for the current user only. This is the recommended installation scope. This method works the same on Windows, macOS, and Linux platforms. Run the following command from a PowerShell session:

```<code>Install-Module -Name Az -Scope CurrentUser -Repository PSGallery -Force
</code>```

Now Update the Az module by running this command.

```<code>Update-Module Az -Force
</code>```

Body:
## Get the storage account from which container has to be retrieved

$StorageKey = Get-AzStorageAccountKey -ResourceGroupName $resourceGroupName -Name $storageAccName

getting error:
[Error] Import-AzContext : The term 'Import-AzContext' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.at run.ps1: line 3+ Import-AzContext+ ________________+ CategoryInfo          : ObjectNotFound: (Import-AzContext:String) [], CommandNotFoundException+ FullyQualifiedErrorId : CommandNotFoundException
2022-02-08T10:26:01.327 [Error] : Cannot process command because of one or more missing mandatory parameters: Name.at run.ps1: line 4+++ CategoryInfo          : InvalidArgument: (:) [Import-Module], ParameterBindingException+ FullyQualifiedErrorId : MissingMandatoryParameter,Microsoft.PowerShell.Commands.ImportModuleCommand,run.ps1
2022-02-08T10:26:01.468 [Error] param : The term 'param' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.at run.ps1: line 7+ param+ _____+ CategoryInfo          : ObjectNotFound: (param:String) [], CommandNotFoundException+ FullyQualifiedErrorId : CommandNotFoundException
2022-02-08T10:26:01.546 [Error] Exception while executing function: Functions.HttpTrigger2. Microsoft.Azure.WebJobs.Script: PowerShell script error. System.Management.Automation: The term 'Import-AzContext' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
2022-02-08T10:26:01.561 [Error] Function completed (Failure, Id=2339b513-6a62-4687-b418-c31db73fd8c8, Duration=408ms)

Body:
When I ran this command from my PowerShell Get-AzStorageAccountKey -ResourceGroupName MyResourceGroupName -Name MyStorageAccountName It showed output like this:

If your desired output is like this then you can update your PowerShell Az module once by running this command: Update-Module Az -Force.

After successfully updating then try again.

If you didn't install Az Module yet then you need to install that module first. You can follow the following steps:

Install the Azure Az PowerShell Module

The Azure Az PowerShell module is a rollup module. Installing it downloads the generally available Az PowerShell modules, and makes their cmdlets available for use.
Azure PowerShell has no additional requirements when run on PowerShell 7.0.6 LTS and PowerShell 7.1.3 or higher. To check your PowerShell version, run the following command from within a PowerShell session:

$PSVersionTable.PSVersion

Install the latest version of PowerShell available for your operating system from here.

The Azure Az PowerShell module is also supported for use with PowerShell 5.1 on Windows. To use the Azure Az PowerShell module in PowerShell 5.1 on Windows:

Update to Windows PowerShell 5.1. If you're on Windows 10 version 1607 or higher, you already have PowerShell 5.1 installed.

Install .NET Framework 4.7.2 or later.

Make sure you have the latest version of PowerShellGet. Run this command.

Install-Module -Name PowerShellGet -Force

Now set the execution policy. PowerShell script execution policy must be set to remote signed or less restrictive. Get-ExecutionPolicy -List can be used to determine the current execution policy. Run this command:

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser

Using the Install-Module cmdlet is the preferred installation method for the Az PowerShell module. Install the Az module for the current user only. This is the recommended installation scope. This method works the same on Windows, macOS, and Linux platforms. Run the following command from a PowerShell session:

Install-Module -Name Az -Scope CurrentUser -Repository PSGallery -Force

Now Update the Az module by running this command.

Update-Module Az -Force


问:
how i can disable php 8 and enable php7.4 in arch linux
when I run the command php -v
I have version 8.0
I would like to change the version to 7.4
despite I have installed php7.4
but I don't know how to switch between the two versions

thank you

答:
As your question is about the Arch Linux and it doesn't have the a2enmod & a2dismod. I am gonna providing working answer in the arch:

I assume you have installed php7 & php8 and just want to make apache to use the version 7.

first uninstall apache-php module and install the right one.

```<code>sudo pacman -R php-apache
sudo pacman -S php7-apache
</code>```

then in the /etc/httpd/conf/httpd.conf change the module name:

from :

```<code>LoadModule php_module modules/libphp.so
Include conf/extra/php_module.conf
AddHandler php-script php

</code>```

to:

```<code>LoadModule php7_module modules/libphp7.so
Include conf/extra/php7_module.conf
AddHandler php7-script php
</code>```

after that you can reload the server:

```<code>sudo systemctl reload httpd
</code>```

Body:
As your question is about the Arch Linux and it doesn't have the a2enmod & a2dismod. I am gonna providing working answer in the arch:

I assume you have installed php7 & php8 and just want to make apache to use the version 7.

first uninstall apache-php module and install the right one.

sudo pacman -R php-apache
sudo pacman -S php7-apache

then in the /etc/httpd/conf/httpd.conf change the module name:

from :

LoadModule php_module modules/libphp.so
Include conf/extra/php_module.conf
AddHandler php-script php

to:

LoadModule php7_module modules/libphp7.so
Include conf/extra/php7_module.conf
AddHandler php7-script php

after that you can reload the server:

sudo systemctl reload httpd


问:
ExpressJS closes connection on bigger data requests
I am trying to create an ExpressJS API that interpolates some data. I use Python requests to test my API. Everything works just fine if I send smaller datasets. However, when I send a bigger dataset Python (on Windows) returns a requests.exceptions.ChunkedEncodingError: "Connection broken: ConnectionResetError 10054 Exception.

The dataset size I am trying to send is 732808 bytes. I tried increasing the timeout limit and the datalimit, that did not help me:

```<code>app.use('/tests', test_router)
app.use(express.json({limit: '10mb'}))
app.listen(5000, () => console.log('Server running')).setTimeout(120000)
</code>```

I tried to debug and found that none of my middleware gets invoked at all (router is "test_router" in code above).

```<code>router.get('/test_interpolation', (req, res) => {
    console.log('Hello') //Never gets called
    res = test_controller.do_something(req, res)
})
</code>```

Why does ExpressJS not accept the request? Thank you for helping!

答:
My first mistake was using router.get(). Apparently ExpressJS only accepts bigger datasets through a post request. Also, my middleware was not configured right either. This is what it looks like now:

```<code>app.use(express.json({ limit: '100mb' }));
app.use(express.urlencoded({ limit: '100mb' }));
app.use(bodyParser.json({ limit: '100mb' }));
app.use(
    bodyParser.urlencoded({
        limit: '100mb',
        extended: true,
    }),
);
</code>```

I used npm body-parser for "bodyParser". It does give me a message that urlencode is deprecated, but this does not bother me right now.

Body:
I am trying to create an ExpressJS API that interpolates some data. I use Python requests to test my API. Everything works just fine if I send smaller datasets. However, when I send a bigger dataset Python (on Windows) returns a requests.exceptions.ChunkedEncodingError: "Connection broken: ConnectionResetError 10054 Exception.

The dataset size I am trying to send is 732808 bytes. I tried increasing the timeout limit and the datalimit, that did not help me:

app.use('/tests', test_router)
app.use(express.json({limit: '10mb'}))
app.listen(5000, () => console.log('Server running')).setTimeout(120000)

I tried to debug and found that none of my middleware gets invoked at all (router is "test_router" in code above).

router.get('/test_interpolation', (req, res) => {
    console.log('Hello') //Never gets called
    res = test_controller.do_something(req, res)
})

Why does ExpressJS not accept the request? Thank you for helping!

Body:
My first mistake was using router.get(). Apparently ExpressJS only accepts bigger datasets through a post request. Also, my middleware was not configured right either. This is what it looks like now:

app.use(express.json({ limit: '100mb' }));
app.use(express.urlencoded({ limit: '100mb' }));
app.use(bodyParser.json({ limit: '100mb' }));
app.use(
    bodyParser.urlencoded({
        limit: '100mb',
        extended: true,
    }),
);

I used npm body-parser for "bodyParser". It does give me a message that urlencode is deprecated, but this does not bother me right now.


问:
pub get failed:version solving failed
Flutter_test depends on meta 1.1.8 and firebase_login depends on meta ^1.2.2.
firebase_login depends on flutter_test any from sdk, version solving failed.
pub get failed

pubspec.yaml

```<code>version: 1.0.0+1

environment:
  sdk: ">=2.7.0 <3.0.0"

dependencies:
  flutter:
    sdk: flutter
  firebase_auth: ^0.18.0+1
  equatable: ^1.2.4
  google_sign_in: ^4.5.3
  meta: ^1.2.2

  cupertino_icons: ^0.1.3

dev_dependencies:
  flutter_test:
    sdk: flutter
  lint: any
</code>```

答:
I have same problem with bloc:

Because every version of passcode_navigator from git depends on flutter_bloc ^7.3.3 and every version of feature_menu from path depends on flutter_bloc ^8.0.0, passcode_navigator from git is incompatible with feature_menu from path

I resolve it with adding to pubspec:

```<code>dependency_overrides:
  flutter_bloc: any
</code>```

Title: pub get failed:version solving failed

Body:
Flutter_test depends on meta 1.1.8 and firebase_login depends on meta ^1.2.2.
firebase_login depends on flutter_test any from sdk, version solving failed.
pub get failed

pubspec.yaml

version: 1.0.0+1

environment:
  sdk: ">=2.7.0 <3.0.0"

dependencies:
  flutter:
    sdk: flutter
  firebase_auth: ^0.18.0+1
  equatable: ^1.2.4
  google_sign_in: ^4.5.3
  meta: ^1.2.2

  cupertino_icons: ^0.1.3

dev_dependencies:
  flutter_test:
    sdk: flutter
  lint: any

Body:
I have same problem with bloc:

Because every version of passcode_navigator from git depends on flutter_bloc ^7.3.3 and every version of feature_menu from path depends on flutter_bloc ^8.0.0, passcode_navigator from git is incompatible with feature_menu from path

I resolve it with adding to pubspec:

dependency_overrides:
  flutter_bloc: any


问:
First-Visit vs Every-Visit Monte Carlo
I have recently been looking into reinforcement learning. For this, I have been reading the famous book by Sutton, but there is something I do not fully understand yet.

For Monte-Carlo learning, we can choose between first-visit and every-visit algorithm, and it can be proved that both converges to the right solution asymptotically. But I guess that there are a difference between both (I understand the difference by definition, but I do not understand what are the drawbacks of each method). Should I in some cases use first-visit, and sometimes last visit ?

Thanks a lot,
Djaz

答:
From my personal experience I have noticed first visit monte carlo converges faster and for control problems gets the optimal policy in fewer iterations.

I'm not sure if there exists a mathematical analysis on the rate of convergence of the two, but they both will converge to the true mean due to the law of large numbers.

Title: First-Visit vs Every-Visit Monte Carlo


问:
Terraform fail to download existing bitnami chart
I am planning to setup jenkins pipeline on K8S using terraform to provising my CI/CD environment.

I am using Terraform v0.12.18

My terraform file has following resource

```<code>resource "helm_release" "jenkins-master" {
  name = "jenkins"
  chart = "jenkins"
  version = "7.0.3"
  repository = "https://charts.bitnami.com/bitnami"

  set {
    name = "jenkinsUser"
    value = "admin"
  }
  set {
    name = "jenkinsPassword"
    value = "admin"
  }
}
</code>```

When I ran
terraform apply -input=false provision-plan

I am getting following error.

```<code>Error: failed to download "https://charts.bitnami.com/bitnami/jenkins-7.0.3.tgz" (hint: running `helm repo update` may help)
</code>```

But when I ran direct helm install using

helm install my-jenkins bitnami/jenkins --version 7.0.3

then jenkins get install.

If I click on the linke https://charts.bitnami.com/bitnami/jenkins-7.0.3.tgz then also I am able to download the chart.

Can someone please helm to find the issue ?

Thanks
Alpesh

答:
If the repo is not added to your local helm repo list then you get an error like;

```<code>Error: failed to download "https://github.com/kubernetes/autoscaler/releases/download/cluster-autoscaler-chart-9.13.1/cluster-autoscaler-9.13.1.tgz" at version "9.13.1"
</code>```

then if you add the target repo to your local everything should be fine

```<code>helm repo add [NAME] [URL]
</code>```

Body:
I am planning to setup jenkins pipeline on K8S using terraform to provising my CI/CD environment.

I am using Terraform v0.12.18

My terraform file has following resource

resource "helm_release" "jenkins-master" {
  name = "jenkins"
  chart = "jenkins"
  version = "7.0.3"
  repository = "https://charts.bitnami.com/bitnami"

  set {
    name = "jenkinsUser"
    value = "admin"
  }
  set {
    name = "jenkinsPassword"
    value = "admin"
  }
}

When I ran
terraform apply -input=false provision-plan

I am getting following error.

Error: failed to download "https://charts.bitnami.com/bitnami/jenkins-7.0.3.tgz" (hint: running `helm repo update` may help)

But when I ran direct helm install using

helm install my-jenkins bitnami/jenkins --version 7.0.3

then jenkins get install.

If I click on the linke https://charts.bitnami.com/bitnami/jenkins-7.0.3.tgz then also I am able to download the chart.

Can someone please helm to find the issue ?

Thanks
Alpesh

Body:
If the repo is not added to your local helm repo list then you get an error like;

Error: failed to download "https://github.com/kubernetes/autoscaler/releases/download/cluster-autoscaler-chart-9.13.1/cluster-autoscaler-9.13.1.tgz" at version "9.13.1"

then if you add the target repo to your local everything should be fine

helm repo add [NAME] [URL]


问:
How to make a fill parent+wrap_content (in that order) Android
I'll try to simplify the problem for avoiding long code pieces: I want to do something like that in my layout

The structure should be easy with something like:

```<code> LinearLayoutA (vertical)
      LinearLayoutB (vertical)
           LinearLayoutC    (horizontal)
           LinearLayoutC'   (horizontal)
      LinearLayoutB' (vertical)
           LinearLayoutC''  (horizontal)
           LinearLayoutC''' (horizontal)
  All with weight=1
</code>```

the problem for me is define what to put within the LinearLayoutC. So focusing now the elements inside LinearLayoutC:

My first option was another LinearLayout (vertical) the problem is that if the image is taller than the LinearLayoutC the TextView is not visible.

So I used that RelativeLayout:

```<code><RelativeLayout
    android:id="@+id/RelativeLayout"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
>
    <TextView
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:text="Eiffel"
        android:textSize="45sp"
        android:id="@+id/text"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:gravity="center"
    ></TextView>
    <ImageView
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:src="@drawable/eiffel2"
        android:id="@+id/image"
        android:layout_above="@id/text"
    android:layout_centerHorizontal="true"></ImageView>

</RelativeLayout>
</code>```

Nice it works! But not for long =(. (We will call it from now RelativeLayout1) When the screen is smaller than the views the layout seems perfect but when going into a larger screen the block is aligned to the bottom of the parent and I'd like it to be centered in the screen (or the sublayout). Like shows that screen:

That is because of the android:layout_alignParentBottom="true" at the TextView.

Trying to solve that I used a RelativeLayout2 for wrap the RelativeLayout1 with a code like:

```<code><RelativeLayout2
android:layout_width="fill_parent"
    android:layout_height="fill_parent"
>

     <RelativeLayout1
      android:layout_centerInParent="true"
      .....
     ></RelativeLayout1>

 </RelativeLayout2>
</code>```

But even with that the layout RelativeLayout1 still aligned to the bottom of the image (and filling all the screen vertically as it had a height= fill_parent and I don't understand why is that happening and how can I solve it. Please can you help me? I've tried for hours. Thanks in advance

答:
set

```<code>                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
</code>```

in the ImageView and the TextView, and then use a LinearLayout (with gravity= center) as container and it work

Body:
I'll try to simplify the problem for avoiding long code pieces: I want to do something like that in my layout

The structure should be easy with something like:

 LinearLayoutA (vertical)
      LinearLayoutB (vertical)
           LinearLayoutC    (horizontal)
           LinearLayoutC'   (horizontal)
      LinearLayoutB' (vertical)
           LinearLayoutC''  (horizontal)
           LinearLayoutC''' (horizontal)
  All with weight=1

the problem for me is define what to put within the LinearLayoutC. So focusing now the elements inside LinearLayoutC:

My first option was another LinearLayout (vertical) the problem is that if the image is taller than the LinearLayoutC the TextView is not visible.

So I used that RelativeLayout:

<RelativeLayout
    android:id="@+id/RelativeLayout"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
>
    <TextView
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:text="Eiffel"
        android:textSize="45sp"
        android:id="@+id/text"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:gravity="center"
    ></TextView>
    <ImageView
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:src="@drawable/eiffel2"
        android:id="@+id/image"
        android:layout_above="@id/text"
    android:layout_centerHorizontal="true"></ImageView>

</RelativeLayout>

Nice it works! But not for long =(. (We will call it from now RelativeLayout1) When the screen is smaller than the views the layout seems perfect but when going into a larger screen the block is aligned to the bottom of the parent and I'd like it to be centered in the screen (or the sublayout). Like shows that screen:

That is because of the android:layout_alignParentBottom="true" at the TextView.

Trying to solve that I used a RelativeLayout2 for wrap the RelativeLayout1 with a code like:

<RelativeLayout2
android:layout_width="fill_parent"
    android:layout_height="fill_parent"
>

     <RelativeLayout1
      android:layout_centerInParent="true"
      .....
     ></RelativeLayout1>

 </RelativeLayout2>

But even with that the layout RelativeLayout1 still aligned to the bottom of the image (and filling all the screen vertically as it had a height= fill_parent and I don't understand why is that happening and how can I solve it. Please can you help me? I've tried for hours. Thanks in advance

Body:
set

                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"

in the ImageView and the TextView, and then use a LinearLayout (with gravity= center) as container and it work


问:
Loop through each div of containers and compare the height index wise
Really sorry if there is any mistake in typo for title. But I need help in looping through 2 main divs and their child divs too. Here is the code sample:

```<code><div class="containers">
    <div class="columns">Content 1</div>
    <div class="columns">Content 2</div>
    <div class="columns">Content 3</div>
</div>
<div class="containers">
    <div class="columns">Content 1</div>
    <div class="columns">Content 2</div>
    <div class="columns">Content 3</div>
</div>
</code>```

What I need is that jquery loop through first .containers and get the height of first child and then loop to second .containers and get the height of first child and compare both height and apply which one is max height to both first elements of .containers.
Now go to second indexes of .containers, compare the height and apply maximum height to both second indexes and so on.

答:
Try this

$(document).ready(function() {
    let $container2Columns = $('#container2 .columns');

    $('#container1 .columns').each(function(i){
        let $relatedColumn = $container2Columns.eq(i);
        let maxHeight      = Math.max($(this).height(), $relatedColumn.height());

        $(this).height(maxHeight);
        $relatedColumn.height(maxHeight);
    });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.columns {
    width: 100px;
    background: #000;
    display: inline-block;
    margin: 0 5px 10px;
}</code>```

Content 1

Content 2

Content 3

Content 1

Content 2

Content 3

```

Body:
Really sorry if there is any mistake in typo for title. But I need help in looping through 2 main divs and their child divs too. Here is the code sample:

Content 1

Content 2

Content 3

Content 1

Content 2

Content 3

What I need is that jquery loop through first .containers and get the height of first child and then loop to second .containers and get the height of first child and compare both height and apply which one is max height to both first elements of .containers.
Now go to second indexes of .containers, compare the height and apply maximum height to both second indexes and so on.

Body:
Try this

$(document).ready(function() {
    let $container2Columns = $('#container2 .columns');

    $('#container1 .columns').each(function(i){
        let $relatedColumn = $container2Columns.eq(i);
        let maxHeight      = Math.max($(this).height(), $relatedColumn.height());

        $(this).height(maxHeight);
        $relatedColumn.height(maxHeight);
    });
});

.columns {
    width: 100px;
    background: #000;
    display: inline-block;
    margin: 0 5px 10px;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="containers" id="container1">
    <div class="columns" style="height: 100px;">Content 1</div>
    <div class="columns" style="height: 400px;">Content 2</div>
    <div class="columns" style="height: 300px;">Content 3</div>
</div>
<div class="containers" id="container2">
    <div class="columns" style="height: 150px;">Content 1</div>
    <div class="columns" style="height: 200px;">Content 2</div>
    <div class="columns" style="height: 300px;">Content 3</div>
</div>


问:
Android TabLayout - How do i achieve this tablayout indicator
I have a tab layout in my app, but I don't want the default tab indicator. I want something similar to the attached image. Please how do I achieve it. Thanks.

Tab indicator I want to achieve (photo)

答:
You can use external libraries

Some libraries listed below :

un-material-tab

https://github.com/creageek/un-material-tab

JSTabLayout

https://github.com/honglei92/JSTabLayout

MagicIndicator

https://github.com/hackware1993/MagicIndicator

FlycoTabLayout

https://github.com/H07000223/FlycoTabLayout


问:
Instance member 'reload' can't be accessed using static access
I'm working on aflutter project and i'm trying to reload my webview using this but they give me this error : Instance member 'reload' can't be accessed using static access
this is my code

```<code>bool connectionStatus = true;
Future check() async {
  Timer.periodic(new Duration(seconds: 10), (time) async {
    if (connectionStatus == false) WebViewController.reload();
    try {
      final result = await InternetAddress.lookup('google.com');
      if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
        connectionStatus = true;
      }
    } on SocketException catch (_) {
      connectionStatus = false;
    } });
}
</code>```

答:
You need to call the reload() method for you instance of the WebViewController since it is not a static method.

So you must have created an instance of WebViewController somewhere. You need to save a reference, like

```<code>final _controller = WebViewController();
</code>```

Then, in your check() method, use

```<code>_controller.reload();
</code>```

Body:
I'm working on aflutter project and i'm trying to reload my webview using this but they give me this error : Instance member 'reload' can't be accessed using static access
this is my code

bool connectionStatus = true;
Future check() async {
  Timer.periodic(new Duration(seconds: 10), (time) async {
    if (connectionStatus == false) WebViewController.reload();
    try {
      final result = await InternetAddress.lookup('google.com');
      if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
        connectionStatus = true;
      }
    } on SocketException catch (_) {
      connectionStatus = false;
    } });
}

Body:
You need to call the reload() method for you instance of the WebViewController since it is not a static method.

So you must have created an instance of WebViewController somewhere. You need to save a reference, like

final _controller = WebViewController();

Then, in your check() method, use

_controller.reload();


问:
Why, in Ansible, I can't have same key in many children groups?
I want to make some clean stuff with my ansible hosts file.

If i use ansible-playbook --limit calendar -i hosts update_common.yml

Ansible execute my playbook on all hosts, even on hostname in other groups.

Apparently, it seems to comme from my keys dev and prod :

all:
  children:
    gitlab:
      children:
        dev:
          hosts:
            gitlab-dev:  # Stretch
        prod:
          hosts:
            gitlab-A:   # Stretch
            gitlab-B:   # Stretch
            gitlab-C.mysociety.fr:
              ansible_port: 22
    intranet:
      children:
        dev:
          hosts:
            intra-dev:      # Buster
            wordpress-dev:  # Buster
        prod:
          hosts:
            intra-prod:     # Buster
    calendar:
      children:
        dev:
          hosts:
            calendar-dev:
        prod:
          hosts:
            calendar:
```

答:
I believe Ansible interprets the inventory slightly different.

You specify the playbook to be executed on all hosts in the calendar group. That one contains everything in the children group. And since children also contains gitlab and intranet...

Very likely the problem is that you use the keyword at many different levels and locations. If that should work, you'd have to specify a path for the playbook run. Seems just not the way Ansible was designed.


问:
Passing variable from JS using ajax to PHP undefined variable
I want to pass variable rating_index to the PHP code and send to database. Rating_index is set I'll not pass the code here because it is long, but right before AJAX i console.log(rating_index) and it has value(int). Add-review is a button that after click should send variable. In js script I am using AJAX :

```<code>$('#add-review').click(function(){
     $.ajax({
        url:"rating-data.php",
        method:"POST",
        data: {
            rating_index: rating_index
        },
        success:function(data)
        {

            console.log(data);
        }
    })
}
</code>```

in my php file rating-data.php:

```<code><?php
    include 'connection.php';
    echo "work";
    echo $_POST["rating_index"];
?>
</code>```

I got a console.log ('work') from PHP file and this error:
Notice: Undefined index: rating_index in /Applications/XAMPP/xamppfiles/htdocs/bookwarm-app/rating-data.php on line 4

So it is getting my to php page but the variable are not passing correctly.

I was trying everything and I have no idea what is wrong and why this variable is undefined in php file. Thanks for any clue

答:
This is the problem in your code, sir

```<code>$user_name = $_GET["user_name"];
$user_rating = $_GET["rating_index"];
$user_review = $_GET["user_review"];
</code>```

you're doing a $_POST request from Ajax and in php file you're getting values from $_GET.....?

Body:
I want to pass variable rating_index to the PHP code and send to database. Rating_index is set I'll not pass the code here because it is long, but right before AJAX i console.log(rating_index) and it has value(int). Add-review is a button that after click should send variable. In js script I am using AJAX :

$('#add-review').click(function(){
     $.ajax({
        url:"rating-data.php",
        method:"POST",
        data: {
            rating_index: rating_index
        },
        success:function(data)
        {

            console.log(data);
        }
    })
}

in my php file rating-data.php:

<?php
    include 'connection.php';
    echo "work";
    echo $_POST["rating_index"];
?>

I got a console.log ('work') from PHP file and this error:
Notice: Undefined index: rating_index in /Applications/XAMPP/xamppfiles/htdocs/bookwarm-app/rating-data.php on line 4

So it is getting my to php page but the variable are not passing correctly.

I was trying everything and I have no idea what is wrong and why this variable is undefined in php file. Thanks for any clue

Body:
This is the problem in your code, sir

$user_name = $_GET["user_name"];
$user_rating = $_GET["rating_index"];
$user_review = $_GET["user_review"];

you're doing a $_POST request from Ajax and in php file you're getting values from $_GET.....?


问:
Error loading MySQLdb Module 'Did you install mysqlclient or MySQL-python?'
I am using windows 10 command line for a django project using python34 however, I am facing difficulties with SQL.

I have already installed mysqlclient using pip install mysqlclient==1.3.5 and located the file to make sure I was not delusional. I then ran python manage.py migrate to migrate the tables to the SQL database (I am using phpmyadmin). However when the command returned with...

```<code> File "C:\Users\user\env\lib\site-packages\django\db\backends\mysql\base.py", line 30, in <module>
    'Did you install mysqlclient or MySQL-python?' % e
django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named 'MySQLdb'.
Did you install mysqlclient or MySQL-python?
</code>```

I am aware that questions like these already exist, but not one solution seems to have made any impact on attempts.

答:
Inspired by @elad silver's answer (thanks).

For OSx (Monterey) this worked for me:

Install protobuf

```<code>brew install protobuf
</code>```

edit your .bashrc, or .zshenv file with these lines:

```<code>export LDFLAGS="${LDFLAGS} -L/usr/local/opt/protobuf/lib"
export CPPFLAGS="${CPPFLAGS} -I/usr/local/opt/protobuf/include"
</code>```

Reinstall mysqlclient

```<code>pip uninstall mysqlclient
pip install mysqlclient
</code>```

Body:
I am using windows 10 command line for a django project using python34 however, I am facing difficulties with SQL.

I have already installed mysqlclient using pip install mysqlclient==1.3.5 and located the file to make sure I was not delusional. I then ran python manage.py migrate to migrate the tables to the SQL database (I am using phpmyadmin). However when the command returned with...

 File "C:\Users\user\env\lib\site-packages\django\db\backends\mysql\base.py", line 30, in <module>
    'Did you install mysqlclient or MySQL-python?' % e
django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named 'MySQLdb'.
Did you install mysqlclient or MySQL-python?

I am aware that questions like these already exist, but not one solution seems to have made any impact on attempts.

Body:
Inspired by @elad silver's answer (thanks).

For OSx (Monterey) this worked for me:

Install protobuf

brew install protobuf

edit your .bashrc, or .zshenv file with these lines:

export LDFLAGS="${LDFLAGS} -L/usr/local/opt/protobuf/lib"
export CPPFLAGS="${CPPFLAGS} -I/usr/local/opt/protobuf/include"

Reinstall mysqlclient

pip uninstall mysqlclient
pip install mysqlclient


问:
Angular 12 - Setting Global HTTP Headers for every get/post request in Angular
I tried setting up an Angular Interceptor where every request must have all the necessary HTTP headers and tokens before the API Call takes place. Earlier I used to do this in every Service, but now I am trying with HTTP Interceptors, which sets the Headers with every HTTP Request.

However, upon checking the browser, I dont find the headers being sent from the app. Here is my code:-

```<code>import { Injectable } from '@angular/core';
import {
  HttpRequest,
  HttpHandler,
  HttpEvent,
  HttpInterceptor,
  HttpHeaders
} from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable()
export class MasterAPIInterceptor implements HttpInterceptor {

  constructor() {}

  intercept(req: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
    //const headers= new HttpHeaders();
    const userToken = 'secure-user-token';
      req.headers.set('content-type', 'application/json')
      .set('Access-Control-Allow-Origin', '*');
      req.headers.set('Authorization', `Bearer ${userToken}`)
     const headerReq = req.clone({ headers: req.headers });

    return next.handle(headerReq);
  }
}

</code>```

Where am I going wrong?

Also, is there any clearer way to check if the headers are set properly?

答:
The reason is that HttpHeaders.set returns a new object. So you need to store a reference to this new object into a some variable. In you code you don't do this.

See the detailed answer here https://stackoverflow.com/a/49768617/12488082

Body:
I tried setting up an Angular Interceptor where every request must have all the necessary HTTP headers and tokens before the API Call takes place. Earlier I used to do this in every Service, but now I am trying with HTTP Interceptors, which sets the Headers with every HTTP Request.

However, upon checking the browser, I dont find the headers being sent from the app. Here is my code:-

import { Injectable } from '@angular/core';
import {
  HttpRequest,
  HttpHandler,
  HttpEvent,
  HttpInterceptor,
  HttpHeaders
} from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable()
export class MasterAPIInterceptor implements HttpInterceptor {

  constructor() {}

  intercept(req: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
    //const headers= new HttpHeaders();
    const userToken = 'secure-user-token';
      req.headers.set('content-type', 'application/json')
      .set('Access-Control-Allow-Origin', '*');
      req.headers.set('Authorization', `Bearer ${userToken}`)
     const headerReq = req.clone({ headers: req.headers });

    return next.handle(headerReq);
  }
}

Where am I going wrong?

Also, is there any clearer way to check if the headers are set properly?


问:
How to show only if an active employee not clocks in?
I am saving a employee as status = 'Active', so when an status having Active Employee clocks in for current day than i am writing a query to show who have not clocked in for current working day.
But when an active employee clocks in still his name remains in Not clocked in dashboard. I am new to Laravel. Can anyone help me out yrr. Thanks in advance. Note if an employee status is Ex-Employee than don't show.</p>
```<code>

  $notClockIn    = AttendanceEmployee::where('date', '=', $currentDate)->get()->pluck('employee_id');

 $notClockIns    = Employee::where('created_by', '=', \Auth::user()->creatorId())
                ->whereRaw('status = "Active" or status =""')
                ->whereNotIn('id',$notClockIn)->get();

</code>```

答:
Trying ! = Ex-employee Worked for me.</p>
```<code>
$notClockIns    = Employee::where('created_by', '=',
                  \Auth::user()>creatorId())
               ->where('status', '!=' , 'Ex-Employee')
               ->whereNotIn('id',$notClockIn)->get();

</code>```

Body:
I am saving a employee as status = 'Active', so when an status having Active Employee clocks in for current day than i am writing a query to show who have not clocked in for current working day.
But when an active employee clocks in still his name remains in Not clocked in dashboard. I am new to Laravel. Can anyone help me out yrr. Thanks in advance. Note if an employee status is Ex-Employee than don't show.

  $notClockIn    = AttendanceEmployee::where('date', '=', $currentDate)->get()->pluck('employee_id');

 $notClockIns    = Employee::where('created_by', '=', \Auth::user()->creatorId())
                ->whereRaw('status = "Active" or status =""')
                ->whereNotIn('id',$notClockIn)->get();

Body:
Trying ! = Ex-employee Worked for me.

$notClockIns    = Employee::where('created_by', '=',
                  \Auth::user()>creatorId())
               ->where('status', '!=' , 'Ex-Employee')
               ->whereNotIn('id',$notClockIn)->get();


问:
While building GCC 8.5.0: "error: `CC' has changed since the previous run"
I'm building GCC 8.5.0 on a Devuan Chimaera GNU/Linux system (using GCC 10). I've configured with ./configure --disable-gnat, then ran make. At some point, I get:

```<code>echo timestamp > s-selftest-c
rm gcc.pod
make[3]: Leaving directory '/usr/local/src/gcc-8.5.0/host-x86_64-pc-linux-gnu/gcc'
Checking multilib configuration for libgcc...
Configuring stage 1 in x86_64-pc-linux-gnu/libgcc
configure: loading cache ./config.cache
configure: error: `CC' has changed since the previous run:
configure:   former value:  `/usr/local/src/gcc-8.5.0/host-x86_64-pc-linux-gnu/gcc/xgcc -B/usr/local/src/gcc-8.5.0/host-x86_64-pc-linux-gnu/gcc/ -B/opt/gcc-8.5.0/x86_64-pc-linux-gnu/bin/ -B/opt/gcc-8.5.0/x86_64-pc-linux-gnu/lib/ -isystem /opt/gcc-8.5.0/x86_64-pc-linux-gnu/include -isystem /opt/gcc-8.5.0/x86_64-pc-linux-gnu/sys-include   '
configure:   current value: `/usr/local/src/gcc-8.5.0/host-x86_64-pc-linux-gnu/gcc/xgcc -B/usr/local/src/gcc-8.5.0/host-x86_64-pc-linux-gnu/gcc/ -B/usr/local/x86_64-pc-linux-gnu/bin/ -B/usr/local/x86_64-pc-linux-gnu/lib/ -isystem /usr/local/x86_64-pc-linux-gnu/include -isystem /usr/local/x86_64-pc-linux-gnu/sys-include   '
configure: error: in `/usr/local/src/gcc-8.5.0/x86_64-pc-linux-gnu/libgcc':
configure: error: changes in the environment can compromise the build
configure: error: run `make distclean' and/or `rm ./config.cache' and start over
make[2]: *** [Makefile:18716: configure-stage1-target-libgcc] Error 1
make[2]: Leaving directory '/usr/local/src/gcc-8.5.0'
make[1]: *** [Makefile:24352: stage1-bubble] Error 2
make[1]: Leaving directory '/usr/local/src/gcc-8.5.0'
make: *** [Makefile:945: all] Error 2
</code>```

Why is this happening? I tried make distclean and repeating the process, but it didn't help.

答:
GCC build prerequisites ...

```<code># apt install g++ autoconf libtool gawk flex bison binutils-dev libelf-dev texinfo zlib1g-dev
</code>```

Example configuring gcc-8.5.0

```<code>tar xvf gcc-8.5.0.tar.xz
cd gcc-8.5.0/

tar xvf mpfr-4.0.2.tar.xz && mv -v mpfr-4.0.2 mpfr
tar xvf gmp-6.1.2.tar.xz && mv -v gmp-6.1.2 gmp
tar xvf mpc-1.1.0.tar.gz && mv -v mpc-1.1.0 mpc

cd ../
mkdir build-gcc850
cd build-gcc850/

export CC=gcc73 CXX=g++73 && \
../gcc-8.5.0/configure --prefix=/usr/local/gcc85 \
--program-suffix=85 --enable-languages=c,c++,fortran \
--disable-multilib --disable-libstdcxx-pch --with-system-zlib
</code>```

Body:
I'm building GCC 8.5.0 on a Devuan Chimaera GNU/Linux system (using GCC 10). I've configured with ./configure --disable-gnat, then ran make. At some point, I get:

echo timestamp > s-selftest-c
rm gcc.pod
make[3]: Leaving directory '/usr/local/src/gcc-8.5.0/host-x86_64-pc-linux-gnu/gcc'
Checking multilib configuration for libgcc...
Configuring stage 1 in x86_64-pc-linux-gnu/libgcc
configure: loading cache ./config.cache
configure: error: `CC' has changed since the previous run:
configure:   former value:  `/usr/local/src/gcc-8.5.0/host-x86_64-pc-linux-gnu/gcc/xgcc -B/usr/local/src/gcc-8.5.0/host-x86_64-pc-linux-gnu/gcc/ -B/opt/gcc-8.5.0/x86_64-pc-linux-gnu/bin/ -B/opt/gcc-8.5.0/x86_64-pc-linux-gnu/lib/ -isystem /opt/gcc-8.5.0/x86_64-pc-linux-gnu/include -isystem /opt/gcc-8.5.0/x86_64-pc-linux-gnu/sys-include   '
configure:   current value: `/usr/local/src/gcc-8.5.0/host-x86_64-pc-linux-gnu/gcc/xgcc -B/usr/local/src/gcc-8.5.0/host-x86_64-pc-linux-gnu/gcc/ -B/usr/local/x86_64-pc-linux-gnu/bin/ -B/usr/local/x86_64-pc-linux-gnu/lib/ -isystem /usr/local/x86_64-pc-linux-gnu/include -isystem /usr/local/x86_64-pc-linux-gnu/sys-include   '
configure: error: in `/usr/local/src/gcc-8.5.0/x86_64-pc-linux-gnu/libgcc':
configure: error: changes in the environment can compromise the build
configure: error: run `make distclean' and/or `rm ./config.cache' and start over
make[2]: *** [Makefile:18716: configure-stage1-target-libgcc] Error 1
make[2]: Leaving directory '/usr/local/src/gcc-8.5.0'
make[1]: *** [Makefile:24352: stage1-bubble] Error 2
make[1]: Leaving directory '/usr/local/src/gcc-8.5.0'
make: *** [Makefile:945: all] Error 2

Why is this happening? I tried make distclean and repeating the process, but it didn't help.

Body:
GCC build prerequisites ...

# apt install g++ autoconf libtool gawk flex bison binutils-dev libelf-dev texinfo zlib1g-dev

Example configuring gcc-8.5.0

tar xvf gcc-8.5.0.tar.xz
cd gcc-8.5.0/

tar xvf mpfr-4.0.2.tar.xz && mv -v mpfr-4.0.2 mpfr
tar xvf gmp-6.1.2.tar.xz && mv -v gmp-6.1.2 gmp
tar xvf mpc-1.1.0.tar.gz && mv -v mpc-1.1.0 mpc

cd ../
mkdir build-gcc850
cd build-gcc850/

export CC=gcc73 CXX=g++73 && \
../gcc-8.5.0/configure --prefix=/usr/local/gcc85 \
--program-suffix=85 --enable-languages=c,c++,fortran \
--disable-multilib --disable-libstdcxx-pch --with-system-zlib


答:
Group names must be unique, it's just the way ansible works. You can either create separate inventory files with same group names, and invoke your playbooks with different inventories or have unique group names.

See this issue https://github.com/ansible/ansible/issues/32247 and comment from one of the devs:

This won't work as group names are unique, they are not based on their relationships with other groups.

I recommend creating parent1_subgroup1 named groups that have the hierarchy you want built in.

Title: Why, in Ansible, I can't have same key in many children groups?

Body:
I want to make some clean stuff with my ansible hosts file.

If i use ansible-playbook --limit calendar -i hosts update_common.yml

Ansible execute my playbook on all hosts, even on hostname in other groups.

Apparently, it seems to comme from my keys dev and prod :

all:
  children:
    gitlab:
      children:
        dev:
          hosts:
            gitlab-dev:  # Stretch
        prod:
          hosts:
            gitlab-A:   # Stretch
            gitlab-B:   # Stretch
            gitlab-C.mysociety.fr:
              ansible_port: 22
    intranet:
      children:
        dev:
          hosts:
            intra-dev:      # Buster
            wordpress-dev:  # Buster
        prod:
          hosts:
            intra-prod:     # Buster
    calendar:
      children:
        dev:
          hosts:
            calendar-dev:
        prod:
          hosts:
            calendar:


问:
Keras: how to output learning rate onto tensorboard
I added a callback to decay the learning rate:

```<code> keras.callbacks.ReduceLROnPlateau(monitor='val_loss', factor=0.5, patience=100,
                                   verbose=0, mode='auto',epsilon=0.00002, cooldown=20, min_lr=0)
</code>```

Here is my tensorboard callback:

```<code>keras.callbacks.TensorBoard(log_dir='./graph/rank{}'.format(hvd.rank()), histogram_freq=10, batch_size=FLAGS.batch_size,
                            write_graph=True, write_grads=True, write_images=False)
</code>```

I want to make sure the learning rate scheduler has kicked in during training, so I want to output the learning rate onto tensorboard. But I can not find where I can set it.

I also checked the optimizer api, but no luck.

```<code>keras.optimizers.Adam(lr=0.001, beta_1=0.9, beta_2=0.999, epsilon=None, decay=0.0, amsgrad=False)
</code>```

How can I output the learning rate to tensorboad?

答:
For tensorflor 2.5 if you have some custom Learning Rate Scheduler:

```<code>class LearningRateLogger(tf.keras.callbacks.Callback):
def __init__(self, log_dir):
    super().__init__()
    self._supports_tf_logs = True
    self.log_dir = log_dir

def set_model(self, model):
    self.model = model
    self.sess = tf.compat.v1.keras.backend.get_session()
    self.writer = tf.summary.create_file_writer(self.log_dir)

def on_epoch_end(self, epoch, logs=None):
    if logs is None or "learning_rate" in logs:
        return
    logs["learning_rate"] = self.model.optimizer.lr
    logs.update({'learning_rate': self.model.optimizer.lr})
    self._write_logs(logs, epoch)

def _write_logs(self, logs, index):

    with self.writer.as_default():
        for name, value in logs.items():
            if name in ['batch', 'size']:
                continue
            if isinstance(value, np.ndarray):
                tf.summary.scalar(name, value.item(), step=index)
            else:
                tf.summary.scalar(name, value, step=index)

        self.writer.flush()
</code>```

Then for calling the callback in your model.fit:

```<code>model.fit(x=..., y=..., callbacks=[LearningRateLogger(log_dir="/path/to/folder/where/tensorboard/is/logging")])
</code>```

Body:
I added a callback to decay the learning rate:

 keras.callbacks.ReduceLROnPlateau(monitor='val_loss', factor=0.5, patience=100,
                                   verbose=0, mode='auto',epsilon=0.00002, cooldown=20, min_lr=0)

Here is my tensorboard callback:

keras.callbacks.TensorBoard(log_dir='./graph/rank{}'.format(hvd.rank()), histogram_freq=10, batch_size=FLAGS.batch_size,
                            write_graph=True, write_grads=True, write_images=False)

I want to make sure the learning rate scheduler has kicked in during training, so I want to output the learning rate onto tensorboard. But I can not find where I can set it.

I also checked the optimizer api, but no luck.

keras.optimizers.Adam(lr=0.001, beta_1=0.9, beta_2=0.999, epsilon=None, decay=0.0, amsgrad=False)

How can I output the learning rate to tensorboad?

Body:
For tensorflor 2.5 if you have some custom Learning Rate Scheduler:

class LearningRateLogger(tf.keras.callbacks.Callback):
def __init__(self, log_dir):
    super().__init__()
    self._supports_tf_logs = True
    self.log_dir = log_dir

def set_model(self, model):
    self.model = model
    self.sess = tf.compat.v1.keras.backend.get_session()
    self.writer = tf.summary.create_file_writer(self.log_dir)

def on_epoch_end(self, epoch, logs=None):
    if logs is None or "learning_rate" in logs:
        return
    logs["learning_rate"] = self.model.optimizer.lr
    logs.update({'learning_rate': self.model.optimizer.lr})
    self._write_logs(logs, epoch)

def _write_logs(self, logs, index):

    with self.writer.as_default():
        for name, value in logs.items():
            if name in ['batch', 'size']:
                continue
            if isinstance(value, np.ndarray):
                tf.summary.scalar(name, value.item(), step=index)
            else:
                tf.summary.scalar(name, value, step=index)

        self.writer.flush()

Then for calling the callback in your model.fit:

model.fit(x=..., y=..., callbacks=[LearningRateLogger(log_dir="/path/to/folder/where/tensorboard/is/logging")])


问:
Jupyter Notebook can't find modules for python 3.6
Not sure what happened but whenever I use ipython, hydrogen (atom) or jupyter notebook can't find any of the installed modules. I know I have pandas installed but the notebook says its not found.

I should add that when I run the script normally (python script.py) it does import without any errors.

Suggestions?

Thanks!

答:
I had the same issue with other packages (scikit-commpy and ModulationPy).
import <package_name> was working on a script.py but not on a notebook.ipynb

What worked for me:

to run !pip install <package_name> inside the notebook.

You only need to do it once
(it will probably say "dependencies already installed" but afterwards it will solve the issue).

what didn't work for me but might be helpful:

compare sys.version from both script.py and notebook.ipynb

call help('modules') on both and compare

you can also do help('modules <package_name>') for filtering the long list to your specific package.

reinstalling any of the following packages:

defected package

ipython

ipykernel

on Pycharm: File > Invalidate caches


问:
VoiceOver reads table header twice and always adds the word "heading"
Here is my code:

```<code>func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    return self.setupFriendsHeaderView()
}

func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
    view.accessibilityTraits = .none
    for subView in view.subviews {
        subView.accessibilityTraits = .none
    }
}

func setupFriendsHeaderView() -> UIView? {
    let view = UIView(frame: CGRect(origin: CGPoint.zero, size: CGSize(width: tableView.frame.width, height: 44)))

    view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.switchPendingRequestsStatus)))
    view.isAccessibilityElement = true
    view.accessibilityLabel = "Pending requests"

    return view
}
</code>```

When you tap the header first time VoiceOver says: "Pending requests. Pending requests header." Sometimes it doesn't manage to finish the first sentence and starts speaking the next one. The second time it just says "Pending requests header." What I need it to do is say "Pending requests" once, and no word "heading".
I saw the answer recommending to use willDisplayHeaderView method, but it doesn't help at all.

答:
The reason behind of announcing "Heading" is that UITableView adds header trait to the header views. To avoid this just simply subclass from UITableViewHeaderFooterView and override accessibilityTraits with empty traits like this:

```<code>override var accessibilityTraits: UIAccessibilityTraits {
  get { [] }
  set { }
}
</code>```

Body:
Here is my code:

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    return self.setupFriendsHeaderView()
}

func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
    view.accessibilityTraits = .none
    for subView in view.subviews {
        subView.accessibilityTraits = .none
    }
}

func setupFriendsHeaderView() -> UIView? {
    let view = UIView(frame: CGRect(origin: CGPoint.zero, size: CGSize(width: tableView.frame.width, height: 44)))

    view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.switchPendingRequestsStatus)))
    view.isAccessibilityElement = true
    view.accessibilityLabel = "Pending requests"

    return view
}

When you tap the header first time VoiceOver says: "Pending requests. Pending requests header." Sometimes it doesn't manage to finish the first sentence and starts speaking the next one. The second time it just says "Pending requests header." What I need it to do is say "Pending requests" once, and no word "heading".
I saw the answer recommending to use willDisplayHeaderView method, but it doesn't help at all.

Body:
The reason behind of announcing "Heading" is that UITableView adds header trait to the header views. To avoid this just simply subclass from UITableViewHeaderFooterView and override accessibilityTraits with empty traits like this:

override var accessibilityTraits: UIAccessibilityTraits {
  get { [] }
  set { }
}


问:
How to link a Vaadin Grid with the result of Spring Mono WebClient data
This seems to be a missing part in the documentation of Vaadin...

I call an API to get data in my UI like this:

```<code>@Override
public URI getUri(String url, PageRequest page) {
    return UriComponentsBuilder.fromUriString(url)
            .queryParam("page", page.getPageNumber())
            .queryParam("size", page.getPageSize())
            .queryParam("sort", (page.getSort().isSorted() ? page.getSort() : ""))
            .build()
            .toUri();
}

@Override
public Mono<Page<SomeDto>> getDataByPage(PageRequest pageRequest) {
    return webClient.get()
            .uri(getUri(URL_API + "/page", pageRequest))
            .retrieve()
            .bodyToMono(new ParameterizedTypeReference<>() {
            });
}
</code>```

In the Vaadin documentation (https://vaadin.com/docs/v10/flow/binding-data/tutorial-flow-data-provider), I found an example with DataProvider.fromCallbacks but this expects streams and that doesn't feel like the correct approach as I need to block on the requests to get the streams...

```<code>DataProvider<SomeDto, Void> lazyProvider = DataProvider.fromCallbacks(
     q -> service.getData(PageRequest.of(q.getOffset(), q.getLimit())).block().stream(),
     q -> service.getDataCount().block().intValue()
);
</code>```

When trying this implementation, I get the following error:

```<code>org.springframework.core.codec.CodecException: Type definition error: [simple type, class org.springframework.data.domain.Page]; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `org.springframework.data.domain.Page` (no Creators, like default constructor, exist): abstract types either need to be mapped to concrete types, have custom deserializer, or contain additional type information
 at [Source: (io.netty.buffer.ByteBufInputStream); line: 1, column: 1]
grid.setItems(lazyProvider);
</code>```

答:
I don't have experience with vaadin, so i'll talk about the deserialization problem.

Jackson needs a Creator when deserializing. That's either:

the default no-arg constructor

another constructor annotated with @JsonCreator

static factory method annotated with @JsonCreator

If we take a look at spring's implementations of Page - PageImpl and GeoPage, they have neither of those. So you have two options:

Write your custom deserializer and register it with the ObjectMapper instance

The deserializer:

```<code>public class PageDeserializer<T> extends StdDeserializer<Page<T>> {

    public PageDeserializer() {
        super(Page.class);
    }

    @Override
    public Page<T> deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JacksonException {
        //TODO implement for your case
        return null;
    }
}
</code>```

And registration:

```<code>SimpleModule module = new SimpleModule();
module.addDeserializer(Page.class, new PageDeserializer<>());
objectMapper.registerModule(module);
</code>```

Make your own classes extending PageImpl, PageRequest, etc. and annotate their constructors with @JsonCreator and arguments with @JsonProperty.

Your page:

```<code>public class MyPage<T> extends PageImpl<T> {

    @JsonCreator
    public MyPage(@JsonProperty("content_prop_from_json") List<T> content, @JsonProperty("pageable_obj_from_json") MyPageable pageable, @JsonProperty("total_from_json") long total) {
        super(content, pageable, total);
    }
}
</code>```

Your pageable:

```<code>public class MyPageable extends PageRequest {

    @JsonCreator
    public MyPageable(@JsonProperty("page_from_json") int page, @JsonProperty("size_from_json") int size, @JsonProperty("sort_object_from_json") Sort sort) {
        super(page, size, sort);
    }
}
</code>```

Depending on your needs for Sort object, you might need to create MySort as well, or you can remove it from constructor and supply unsorted sort, for example, to the super constructor. If you are deserializing from input manually you need to provide type parameters like this:

```<code>JavaType javaType = TypeFactory.defaultInstance().constructParametricType(MyPage.class, MyModel.class);
Page<MyModel> deserialized = objectMapper.readValue(pageString, javaType);
</code>```

If the input is from request body, for example, just declaring the generic type in the variable is enough for object mapper to pick it up.

```<code>@PostMapping("/deserialize")
public ResponseEntity<String> deserialize(@RequestBody MyPage<MyModel> page) {
    return ResponseEntity.ok("OK");
}
</code>```

Personally i would go for the second option, even though you have to create more classes, it spares the tediousness of extracting properties and creating instances manually when writing deserializers.

Body:
This seems to be a missing part in the documentation of Vaadin...

I call an API to get data in my UI like this:

@Override
public URI getUri(String url, PageRequest page) {
    return UriComponentsBuilder.fromUriString(url)
            .queryParam("page", page.getPageNumber())
            .queryParam("size", page.getPageSize())
            .queryParam("sort", (page.getSort().isSorted() ? page.getSort() : ""))
            .build()
            .toUri();
}

@Override
public Mono<Page<SomeDto>> getDataByPage(PageRequest pageRequest) {
    return webClient.get()
            .uri(getUri(URL_API + "/page", pageRequest))
            .retrieve()
            .bodyToMono(new ParameterizedTypeReference<>() {
            });
}

In the Vaadin documentation (https://vaadin.com/docs/v10/flow/binding-data/tutorial-flow-data-provider), I found an example with DataProvider.fromCallbacks but this expects streams and that doesn't feel like the correct approach as I need to block on the requests to get the streams...

DataProvider<SomeDto, Void> lazyProvider = DataProvider.fromCallbacks(
     q -> service.getData(PageRequest.of(q.getOffset(), q.getLimit())).block().stream(),
     q -> service.getDataCount().block().intValue()
);

When trying this implementation, I get the following error:

org.springframework.core.codec.CodecException: Type definition error: [simple type, class org.springframework.data.domain.Page]; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `org.springframework.data.domain.Page` (no Creators, like default constructor, exist): abstract types either need to be mapped to concrete types, have custom deserializer, or contain additional type information
 at [Source: (io.netty.buffer.ByteBufInputStream); line: 1, column: 1]
grid.setItems(lazyProvider);

Body:
I don't have experience with vaadin, so i'll talk about the deserialization problem.

Jackson needs a Creator when deserializing. That's either:

the default no-arg constructor

another constructor annotated with @JsonCreator

static factory method annotated with @JsonCreator

If we take a look at spring's implementations of Page - PageImpl and GeoPage, they have neither of those. So you have two options:

Write your custom deserializer and register it with the ObjectMapper instance

The deserializer:

public class PageDeserializer<T> extends StdDeserializer<Page<T>> {

    public PageDeserializer() {
        super(Page.class);
    }

    @Override
    public Page<T> deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JacksonException {
        //TODO implement for your case
        return null;
    }
}

And registration:

SimpleModule module = new SimpleModule();
module.addDeserializer(Page.class, new PageDeserializer<>());
objectMapper.registerModule(module);

Make your own classes extending PageImpl, PageRequest, etc. and annotate their constructors with @JsonCreator and arguments with @JsonProperty.

Your page:

public class MyPage<T> extends PageImpl<T> {

    @JsonCreator
    public MyPage(@JsonProperty("content_prop_from_json") List<T> content, @JsonProperty("pageable_obj_from_json") MyPageable pageable, @JsonProperty("total_from_json") long total) {
        super(content, pageable, total);
    }
}

Your pageable:

public class MyPageable extends PageRequest {

    @JsonCreator
    public MyPageable(@JsonProperty("page_from_json") int page, @JsonProperty("size_from_json") int size, @JsonProperty("sort_object_from_json") Sort sort) {
        super(page, size, sort);
    }
}

Depending on your needs for Sort object, you might need to create MySort as well, or you can remove it from constructor and supply unsorted sort, for example, to the super constructor. If you are deserializing from input manually you need to provide type parameters like this:

JavaType javaType = TypeFactory.defaultInstance().constructParametricType(MyPage.class, MyModel.class);
Page<MyModel> deserialized = objectMapper.readValue(pageString, javaType);

If the input is from request body, for example, just declaring the generic type in the variable is enough for object mapper to pick it up.

@PostMapping("/deserialize")
public ResponseEntity<String> deserialize(@RequestBody MyPage<MyModel> page) {
    return ResponseEntity.ok("OK");
}

Personally i would go for the second option, even though you have to create more classes, it spares the tediousness of extracting properties and creating instances manually when writing deserializers.


问:
How do I make an http request with fetch in node? node-fetch
I am trying to make a request in node.  Here is my code:

```<code>fetch("http://www.test.com", options).catch(err => {
    console.error(err);

    return err;
  });
</code>```

Here is the error that I get.
TypeError: Only HTTP(S) protocols are supported

I have tried to create a new agent and pass it in the options like this:

```<code>const httpAgent = new http.Agent({
    keepAlive: true
});
const httpsAgent = new https.Agent({
    keepAlive: true
});

const options = {
    agent: function (_parsedURL) {
        if (_parsedURL.protocol == 'http:') {
            return httpAgent;
        } else {
            return httpsAgent;
        }
    }
}
</code>```

I still get the same error.

When I run this in the client, I can send an http or an https request to the same fetch and there isn't an issue.  Apparently it is different on with node.

What is the best way to handle this?

答: Check if you've passed a url with a protocol. Error "Only HTTP(S) protocols are supported" means that there's neither HTTP nor HTTPS protocol found.</p>

Body:
I am trying to make a request in node.  Here is my code:

fetch("http://www.test.com", options).catch(err => {
    console.error(err);

    return err;
  });

Here is the error that I get.
TypeError: Only HTTP(S) protocols are supported

I have tried to create a new agent and pass it in the options like this:

const httpAgent = new http.Agent({
    keepAlive: true
});
const httpsAgent = new https.Agent({
    keepAlive: true
});

const options = {
    agent: function (_parsedURL) {
        if (_parsedURL.protocol == 'http:') {
            return httpAgent;
        } else {
            return httpsAgent;
        }
    }
}

I still get the same error.

When I run this in the client, I can send an http or an https request to the same fetch and there isn't an issue.  Apparently it is different on with node.

What is the best way to handle this?


问:
Convert Christian solar calendar into Muslim Lunar calander using PHP
I am using PHP and want to mark religious holidays on Christian calendar. How could I convert Christian solar calendar into Muslim Lunar calendar?

Thanks.

答:
PHP doesn't seem to have inbuilt support for this, but there are several libraries available. Take a look at this for example:

http://www.phpclasses.org/package/3850-PHP-Convert-between-Hijri-Gregorian-dates-and-format-.html


问:
Ext.Direct functions available within javascript
I have implemented Ext.Direct to return data to a Store however the directFn methods are not available within the javascript.

api.php returns
 var Ext = Ext || {}; Ext.REMOTING_API = {"url":"php/api/router.php","type":"remoting","actions":{"RaStatuses":[{"name":"get_ra_statuses","len":1}]}};

router.php returns
 {"type":"rpc","tid":1,"action":"RaStatuses","method":"get_ra_statuses","result":[{"ra_no":"2"},{"ra_no":"4"},{"ra_no":"6"},{"ra_no":"8"},{"ra_no":"10"}]}

...and successfully populates this store

```<code>Ext.define('CSM.store.ra.Statuses', {
  extend: 'Ext.data.Store',
  model: 'CSM.model.ra.Status',
  proxy: {
    type: 'direct',
    directFn: "RaStatuses.get_ra_statuses"
  },
  autoLoad: true
});
</code>```

However when I use this line from within a javascript function
a = RaStatuses.get_ra_statuses();

...I get
'ReferenceError: RaStatuses is not defined'

Have I misunderstood? Should Ext.Direct make this object available inside the js or was this wishful thinking?

答:
This now works (ExtJS 6.0.2). I amended api.php to return...

```<code>Ext.namespace('RPC');
var Ext = Ext || {};
RPC.REMOTING_API = {
    "url": "php/api/router.php",
    "type": "remoting",
    "namespace": "RPC",
    "descriptor": "RPC.REMOTING_API",
    "actions": {
        "RaStatuses": [{
            "name": "get_ra_statuses",
            "len": 0
        }]
    }
};
Ext.direct.Manager.addProvider(RPC.REMOTING_API);
</code>```

This call now returns data

```<code>RPC.RaStatuses.get_ra_statuses();
</code>```

Body:
I have implemented Ext.Direct to return data to a Store however the directFn methods are not available within the javascript.

api.php returns
 var Ext = Ext || {}; Ext.REMOTING_API = {"url":"php/api/router.php","type":"remoting","actions":{"RaStatuses":[{"name":"get_ra_statuses","len":1}]}};

router.php returns
 {"type":"rpc","tid":1,"action":"RaStatuses","method":"get_ra_statuses","result":[{"ra_no":"2"},{"ra_no":"4"},{"ra_no":"6"},{"ra_no":"8"},{"ra_no":"10"}]}

...and successfully populates this store

Ext.define('CSM.store.ra.Statuses', {
  extend: 'Ext.data.Store',
  model: 'CSM.model.ra.Status',
  proxy: {
    type: 'direct',
    directFn: "RaStatuses.get_ra_statuses"
  },
  autoLoad: true
});

However when I use this line from within a javascript function
a = RaStatuses.get_ra_statuses();

...I get
'ReferenceError: RaStatuses is not defined'

Have I misunderstood? Should Ext.Direct make this object available inside the js or was this wishful thinking?

Body:
This now works (ExtJS 6.0.2). I amended api.php to return...

Ext.namespace('RPC');
var Ext = Ext || {};
RPC.REMOTING_API = {
    "url": "php/api/router.php",
    "type": "remoting",
    "namespace": "RPC",
    "descriptor": "RPC.REMOTING_API",
    "actions": {
        "RaStatuses": [{
            "name": "get_ra_statuses",
            "len": 0
        }]
    }
};
Ext.direct.Manager.addProvider(RPC.REMOTING_API);

This call now returns data

RPC.RaStatuses.get_ra_statuses();


问:
How to loop list class
I have below  class. And data is serialized using JsonConvert.DeserializeObject. The data is returning from list. But I want to loop using for or for each. Please advice.

Thank you.

```<code>    var result = client.getInvocieLine
    (call Context);

   string strResultJson = JsonConvert.SerializeObject(result);

   System.IO.File.WriteAllText(@"D:\jsondata\invoicedata.json", strResultJson);

   string fileName = @"D:\jsondata\invoicedata.json";
   string jsonText = System.IO.File.ReadAllText(fileName)
  List<EInvoiceModel.Class1> data = Newtonsoft.Json.JsonConvert.DeserializeObject<List<EInvoiceModel.Class1>>(jsonText);

            EInvoiceModel.Invoiceline invoicelined = new EInvoiceModel.Invoiceline();

            for(int i=0; i < data.Count; i++)
            {
                invoicelined.parmItemId = data[i].invoiceLines[i].parmItemId; //Its bring only one record. I need all record from data. Please advice.
            }
            return Ok(invoicelined);

</code>```

Please find my EInvoiceModel contains below structure, Which i designed as per my json response. yes I need same index for data and invoiceLines in data[i].invoiceLines[i]. How can I get this to return all values. Index currently pointing only one record and return one record. If I change position its return another record. But I need all please.

```<code>public class Class1
{
    public Invoiceline[] invoiceLines { get; set; }
    public string parmCustName { get; set; }
    public DateTime parmInvoiceDate { get; set; }
}     public class Invoiceline
{
    public string parmItemId { get; set; }
    public string parmItemNameDisplay { get; set; }
    public float parmQty { get; set; }}
</code>```

Please find my json structure. I wist to repeat all parameter-ids from json response.

```<code>{"invoiceLines":[{"parmCurrencyCode":null,"parmCustExchRate":0.0,"parmInvoiceId":null,"parmItemId":null,"parmItemNameDisplay":null,"parmQty":0.0,"parmSalesLinePercent":0.0,"parmSalesUnit":null,"parmdiscountAmount":0.0,"parmnetTotal":0.0,"parmsalesPrice":0.0,"parmsalesTotal":0.0,"parmtotalItemsLineDisc":0.0,"parmtotalTaxableFees":0.0}],"parmCustName":null,"parmInvoiceDate":"0001-01-01T00:00:00","parmInvoiceId":null,"parmSalesId":null,"parmnetAmount":0.0,"parmtotalAmount":0.0,"parmtotalAmountWithDisc":0.0,"parmtotalItemsDiscountAmount":0.0,"parmtotalSalesAmount":0.0}
</code>```

Please I want return all parmItemId below way. I don't want damage my json structure.

```<code>      EInvoiceModel.Class1 ds = new EInvoiceModel.Class1();
       List<EInvoiceModel.Class1> data = Newtonsoft.Json.JsonConvert.DeserializeObject<List<EInvoiceModel.Class1>>(jsonText);
       // List<EInvoiceModel.Invoiceline> data = Newtonsoft.Json.JsonConvert.DeserializeObject<List<EInvoiceModel.Invoiceline>>(jsonText);

        for (int i = 0; i < data.Count; i++)
        {

            ds.invoiceLines = new List<EInvoiceModel.Invoiceline>
        {
             new EInvoiceModel.Invoiceline
             {
             parmItemId = data[i].invoiceLines[i].parmItemId
             }
        };

        }
        return Ok(ds);
</code>```

答:
You have used to Generic list

To get all list

```<code>List<EInvoiceModel.Invoiceline> data = Newtonsoft.Json.JsonConvert.DeserializeObject<List<EInvoiceModel.Invoiceline>>(jsonText);

List<EInvoiceModel.Invoiceline> invoicelines = new List<EInvoiceModel.Invoiceline>();

for(int i=0; i < data.Count; i++)
{
    invoicelines.Add(new EInvoiceModel.Invoiceline()
      {
         parmItemId = data[i].parmItemId
      });
}
return Ok(invoicelines);
</code>```

Title: How to loop list class

Body:
I have below  class. And data is serialized using JsonConvert.DeserializeObject. The data is returning from list. But I want to loop using for or for each. Please advice.

Thank you.

    var result = client.getInvocieLine
    (call Context);

   string strResultJson = JsonConvert.SerializeObject(result);

   System.IO.File.WriteAllText(@"D:\jsondata\invoicedata.json", strResultJson);

   string fileName = @"D:\jsondata\invoicedata.json";
   string jsonText = System.IO.File.ReadAllText(fileName)
  List<EInvoiceModel.Class1> data = Newtonsoft.Json.JsonConvert.DeserializeObject<List<EInvoiceModel.Class1>>(jsonText);

            EInvoiceModel.Invoiceline invoicelined = new EInvoiceModel.Invoiceline();

            for(int i=0; i < data.Count; i++)
            {
                invoicelined.parmItemId = data[i].invoiceLines[i].parmItemId; //Its bring only one record. I need all record from data. Please advice.
            }
            return Ok(invoicelined);

Please find my EInvoiceModel contains below structure, Which i designed as per my json response. yes I need same index for data and invoiceLines in data[i].invoiceLines[i]. How can I get this to return all values. Index currently pointing only one record and return one record. If I change position its return another record. But I need all please.

public class Class1
{
    public Invoiceline[] invoiceLines { get; set; }
    public string parmCustName { get; set; }
    public DateTime parmInvoiceDate { get; set; }
}     public class Invoiceline
{
    public string parmItemId { get; set; }
    public string parmItemNameDisplay { get; set; }
    public float parmQty { get; set; }}

Please find my json structure. I wist to repeat all parameter-ids from json response.

{"invoiceLines":[{"parmCurrencyCode":null,"parmCustExchRate":0.0,"parmInvoiceId":null,"parmItemId":null,"parmItemNameDisplay":null,"parmQty":0.0,"parmSalesLinePercent":0.0,"parmSalesUnit":null,"parmdiscountAmount":0.0,"parmnetTotal":0.0,"parmsalesPrice":0.0,"parmsalesTotal":0.0,"parmtotalItemsLineDisc":0.0,"parmtotalTaxableFees":0.0}],"parmCustName":null,"parmInvoiceDate":"0001-01-01T00:00:00","parmInvoiceId":null,"parmSalesId":null,"parmnetAmount":0.0,"parmtotalAmount":0.0,"parmtotalAmountWithDisc":0.0,"parmtotalItemsDiscountAmount":0.0,"parmtotalSalesAmount":0.0}

Please I want return all parmItemId below way. I don't want damage my json structure.

      EInvoiceModel.Class1 ds = new EInvoiceModel.Class1();
       List<EInvoiceModel.Class1> data = Newtonsoft.Json.JsonConvert.DeserializeObject<List<EInvoiceModel.Class1>>(jsonText);
       // List<EInvoiceModel.Invoiceline> data = Newtonsoft.Json.JsonConvert.DeserializeObject<List<EInvoiceModel.Invoiceline>>(jsonText);

        for (int i = 0; i < data.Count; i++)
        {

            ds.invoiceLines = new List<EInvoiceModel.Invoiceline>
        {
             new EInvoiceModel.Invoiceline
             {
             parmItemId = data[i].invoiceLines[i].parmItemId
             }
        };

        }
        return Ok(ds);

Body:
You have used to Generic list

To get all list

List<EInvoiceModel.Invoiceline> data = Newtonsoft.Json.JsonConvert.DeserializeObject<List<EInvoiceModel.Invoiceline>>(jsonText);

List<EInvoiceModel.Invoiceline> invoicelines = new List<EInvoiceModel.Invoiceline>();

for(int i=0; i < data.Count; i++)
{
    invoicelines.Add(new EInvoiceModel.Invoiceline()
      {
         parmItemId = data[i].parmItemId
      });
}
return Ok(invoicelines);