问:
How can I use cache tags whith a mocked Cache in phpunit tests?
I have implemented Cache tags on a laravel project and I have something like this in my controller :

```<code>if (Cache::tags(['api'])->has('someKey')) {
    return new JsonResponse(Cache::tags(['api'])->get('someKey'));
}
</code>```

I would like to write a phpunit test to test this code : I mocked the Cache like found in the laravel documentation, but I haven't found anything on how to use tags on a mocked cache

I tried :

```<code>Cache::tags(['api'])->shouldReceive('has')->with('someKey')->andReturn(true)->once();
</code>```

or

```<code>Cache::shouldReceive('has')->tags(['api'])->with('someKey')->andReturn(true)->once();
</code>```

But none of this works, I got Call to undefined method Illuminate\Cache\ArrayStore::shouldReceive() or
call_user_func_array() expects parameter 1 to be a valid callback, class 'Mockery\Expectation' does not have a method 'tags'

Does anybody have a clue ? thanks a lot :)

答:
You will need to mock tags call by itself and use ->andReturnSelf() to be able to make the mock chain. So calling Cache::tags(['api']) returns the mock instance.

```<code>Cache::shouldReceive('tags')->with(['api'])->andReturnSelf();

Cache::shouldReceive('has')->once()->with('someKey')->andReturn(true);
Cache::shouldReceive('get')->once()->with('someKey')->andReturn('result');
</code>```

Body:
I have implemented Cache tags on a laravel project and I have something like this in my controller :

if (Cache::tags(['api'])->has('someKey')) {
    return new JsonResponse(Cache::tags(['api'])->get('someKey'));
}

I would like to write a phpunit test to test this code : I mocked the Cache like found in the laravel documentation, but I haven't found anything on how to use tags on a mocked cache

I tried :

Cache::tags(['api'])->shouldReceive('has')->with('someKey')->andReturn(true)->once();

or

Cache::shouldReceive('has')->tags(['api'])->with('someKey')->andReturn(true)->once();

But none of this works, I got Call to undefined method Illuminate\Cache\ArrayStore::shouldReceive() or
call_user_func_array() expects parameter 1 to be a valid callback, class 'Mockery\Expectation' does not have a method 'tags'

Does anybody have a clue ? thanks a lot :)

Body:
You will need to mock tags call by itself and use ->andReturnSelf() to be able to make the mock chain. So calling Cache::tags(['api']) returns the mock instance.

Cache::shouldReceive('tags')->with(['api'])->andReturnSelf();

Cache::shouldReceive('has')->once()->with('someKey')->andReturn(true);
Cache::shouldReceive('get')->once()->with('someKey')->andReturn('result');


来源: stackexchange

问:
Update based on same column
I have a table like this:

```<code>ID | Flag
-----------
 1 | True
 1 | True
 1 | NULL
 1 | True
 1 | NULL
 2 | False
 2 | False
 2 | False
 2 | NULL
 2 | NULL
</code>```

And I want an output like this:

```<code>ID | Flag
-----------
 1 | True
 1 | True
 1 | True
 1 | True
 1 | True
 2 | False
 2 | False
 2 | False
 2 | False
 2 | False
</code>```

I want to replace nulls with the value assigned in different records. Is there a way to do it in a single update statement?

答:
One option uses a correlated subquery:

```<code>update mytable t
set flag = (select bool_or(flag) from mytable t1 where t1.id = t.id)
</code>```

Demo on DB Fiddle:

```
id | flag
-: | :---
 1 | t
 1 | t
 1 | t
 1 | t
 1 | t
 2 | f
 2 | f
 2 | f
 2 | f
 2 | f
```

ContentLicense: CC BY-SA 4.0

Title: Update based on same column

Body:
I have a table like this:

ID | Flag
-----------
 1 | True
 1 | True
 1 | NULL
 1 | True
 1 | NULL
 2 | False
 2 | False
 2 | False
 2 | NULL
 2 | NULL

And I want an output like this:

ID | Flag
-----------
 1 | True
 1 | True
 1 | True
 1 | True
 1 | True
 2 | False
 2 | False
 2 | False
 2 | False
 2 | False

I want to replace nulls with the value assigned in different records. Is there a way to do it in a single update statement?

Body:
One option uses a correlated subquery:

update mytable t
set flag = (select bool_or(flag) from mytable t1 where t1.id = t.id)

Demo on DB Fiddle:

id | flag
-: | :---
 1 | t
 1 | t
 1 | t
 1 | t
 1 | t
 2 | f
 2 | f
 2 | f
 2 | f
 2 | f


问:
tabBar viewControllers in IB: send custom init?
My tabBarController-based app has several tabs. Each has a custom viewController class, the only difference being the way the instance is initialized. Is there a way to make interface builder send the different tabs custom init parameters?

Currently I'm doing the initialisation in viewWillAppear, but for a bunch of reasons it would make sense to do it in IB instead of in the code.

Any suggestions?

thanks,
Kelso

答: I don't think there's any way to change what methods are called by the IB runtime when your nib is loaded. If you described what you were trying to accomplish (i.e. why doing the setup in viewDidAppear doesn't work for you), you might get a suggestion of a better way to handle your initialization.</p>

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: benzado

OwnerDisplayName: Mark Bessey


答:
The main problem is that the parameters are not uniquely identifiable.  We can multiply a by an arbitrary number and divide c, d and e by that same number and we get the same model. Omit a.

Although it won't hurt the use of as.formula is redundant since it is already a formula.

Having an assignment within an nls formula is highly unusual.  nls will think that Rref is a parameter and fail on that account.  Remove the assignment.

If we make these changes then it does give an answer with the data in the updated version of the question.

```<code>form_Q10_parabolic_SM <- Lin_Flux..mymol.m.2.s.1. ~
 exp(b*Mean_Soil_Temp_V2..C.) * ( (-c*Soil_Moist_V3**2) + (d*Soil_Moist_V3) + e)

Q10_parabolic_SM <- nls(form_Q10_parabolic_SM, data = conB1_2015,
  start = list(b = 0.11, c = 0.0001, d = 0.01, e = 0.1))
</code>```

giving:

```<code>> Q10_parabolic_SM
Nonlinear regression model
  model: Lin_Flux..mymol.m.2.s.1. ~ exp(b * Mean_Soil_Temp_V2..C.) * ((-c *     Soil_Moist_V3^2) + (d * Soil_Moist_V3) + e)
   data: conB1_2015
        b         c         d         e
 0.103062 -0.001564 -0.135531  3.528621
 residual sum-of-squares: 3.979

Number of iterations to convergence: 6
Achieved convergence tolerance: 4.401e-06
</code>```

plinear

Note that nls also has the plinear algorithm which has the advantage that only nonlinear parameters (in this case only b) need starting values.  In that case the formula's RHS should be a matrix with the columns that multiply each linear parameter.  It gives the same answer as above except the linear parameters are given names starting with .lin .  Note that the plinear version converges in fewer iterations than the version using the default algorithm above.  (Also it seems that the plinear version is not very sensitive to the starting value and even if we use b=1 as the starting value it converges.)

```<code>fo <- Lin_Flux..mymol.m.2.s.1. ~
  cbind(-Soil_Moist_V3**2, Soil_Moist_V3, 1) * exp(b*Mean_Soil_Temp_V2..C.)
fm <- nls(fo, data = conB1_2015, start = list(b = 0.11), algorithm = "plinear")
</code>```

giving:

```<code>> fm
Nonlinear regression model
  model: Lin_Flux..mymol.m.2.s.1. ~ cbind(-Soil_Moist_V3^2, Soil_Moist_V3,     1) * exp(b * Mean_Soil_Temp_V2..C.)
   data: conB1_2015
                 b              .lin1 .lin.Soil_Moist_V3              .lin3
          0.103062          -0.001564          -0.135528           3.528593
 residual sum-of-squares: 3.979

Number of iterations to convergence: 3
Achieved convergence tolerance: 2.189e-06
</code>```

Title: R nls() Initial Parameter Problem, nonlinear Regression

Body:
I get a error message:

Error in nlsModel(formula, mf, start, wts) :
  singular gradient matrix at initial parameter estimates

when using the nls() function like

form_Q10_parabolic_SM <- as.formula(Lin_Flux..mymol.m.2.s.1. ~ (rRef<- 5.5354)*a*exp(b*Mean_Soil_Temp_V2..C.)*((-c*Soil_Moist_V3**2)+(d*Soil_Moist_V3)+e))
Q10_parabolic_SM <- nls(form_Q10_parabolic_SM, data = conB1_2015, start = list(a = 1, b = 0.11, c = 0.0001, d = 0.01, e = 0.1))

I got my initial parameters by using the preview() function of the nsltools library like this (same definition of the formula like above)

preview(form_Q10_parabolic_SM, data = conB1_2015, start = c(a = 1, b = 0.11, c = 0.0001, d = 0.01, e = 0.1), variable = 1)

Which gives me this output with the parameters a-e above:

This looks quite good by my eyes and I really don't know what to do at this point since the preview() works just fine.

Is my model too complex or overparameterized? Or did I just do something wrong with the nls function?

Any tips would be really appreciated!

> dput(head(conB1_2015, 30))
structure(list(X = c(13L, 68L, 69L, 70L, 71L, 72L, 73L, 74L,
75L, 76L, 77L, 78L, 79L, 80L, 81L, 82L, 83L, 84L, 85L, 86L, 87L,
88L, 89L, 90L, 91L, 92L, 93L, 94L, 95L, 96L), IV_Date = c("2015-01-14",
"2015-03-11", "2015-03-12", "2015-03-13", "2015-03-14", "2015-03-15",
"2015-03-16", "2015-03-17", "2015-03-18", "2015-03-19", "2015-03-20",
"2015-03-21", "2015-03-22", "2015-03-23", "2015-03-24", "2015-03-25",
"2015-03-26", "2015-03-27", "2015-03-28", "2015-03-29", "2015-03-30",
"2015-03-31", "2015-04-01", "2015-04-02", "2015-04-03", "2015-04-04",
"2015-04-05", "2015-04-06", "2015-04-07", "2015-04-08"), SMmean010.... = c(24.5341666666667,
23.4754166666667, 23.0585416666667, 22.830625, 22.7447916666667,
22.7729166666666, 22.7929166666667, 22.7354166666667, 22.6579166666667,
22.5935416666667, 22.5233333333333, 22.7641666666667, 23.6010416666667,
23.445625, 23.404375, 23.2845833333333, 23.0672916666667, 22.9347916666667,
22.8272916666667, 23.0316666666667, 23.988125, 25.5647916666667,
27.055, 27.7995833333333, 26.23125, 25.4658333333333, 25.0845833333333,
24.8175, 24.605, 24.4216666666667), Lin_Flux..mymol.m.2.s.1. = c(1.13,
2.146, 1.98708333333333, 1.88416666666667, 1.57083333333333,
1.93041666666667, 2.69875, 2.8075, 3.23272727272727, 2.35818181818182,
2.23833333333333, 1.84958333333333, 2.18695652173913, 2.16958333333333,
2.69791666666667, 3.025, 1.985, 1.88083333333333, 2.30416666666667,
2.775, 1.44458333333333, 1.78791666666667, 1.04863636363636,
1.03458333333333, 1.4725, 1.86833333333333, 1.71125, 1.79, 1.53166666666667,
1.97666666666667), Mean_Soil_Temp_V2..C. = c(4.739, 5.1864, 4.08408333333333,
3.61625, 3.68508333333333, 4.09925, 4.87079166666667, 5.64720833333333,
6.58433333333333, 5.05075, 4.93708333333333, 4.109, 3.2295, 3.537,
5.1395, 5.65270833333333, 5.931875, 5.61775, 5.88695833333333,
6.86308333333333, 5.61833333333333, 4.24566666666667, 3.05952173913043,
2.45716666666667, 3.6365, 3.68820833333333, 3.83766666666667,
4.3435, 4.8745, 6.29133333333333), Soil_Moist_V3 = c(25.603137,
21.98744709, 21.8053864833333, 21.6770563291667, 20.1319423708333,
19.9826592666667, 19.8279438958333, 20.1589541791667, 21.5796382,
21.5971315083333, 21.3742824541667, 21.8992939333333, 23.9737254583333,
23.4506886041667, 23.0956395708333, 22.574581225, 22.3561680833333,
21.3806269916667, 21.4045219791667, 21.5611478916667, 25.5090813166667,
28.6440265, 31.4434210347826, 31.9276734541667, 27.5706909333333,
25.1139413583333, 24.2945348333333, 24.0232171416667, 23.705631425,
22.8323341625), precip50..mm. = c(0.6, 0, 0, 0, 0.9, 1.3, 0,
0, 0, 0, 0, 6.6, 0, 0, 0, 0, 0.1, 0.2, 0.1, 6.1, 5, 17.6, 10.4,
6.6, 0, 0, 0, 0, 0, 0), RWI = c(0.6, 0.4, 0.2, 0.133333333333333,
0.9, 1.3, 1.3, 0.65, 0.433333333333333, 0.325, 0.26, 6.6, 6.6,
3.3, 2.2, 1.65, 0.1, 0.2, 0.1, 6.1, 5, 17.6, 10.4, 6.6, 6.6,
3.3, 2.2, 1.65, 1.32, 1.1)), na.action = structure(c(`1` = 1L,
`2` = 2L, `3` = 3L, `4` = 4L, `5` = 5L, `6` = 6L, `7` = 7L, `8` = 8L,
`9` = 9L, `10` = 10L, `11` = 11L, `12` = 12L, `13` = 13L, `15` = 15L,
`16` = 16L, `17` = 17L, `18` = 18L, `19` = 19L, `20` = 20L, `21` = 21L,
`22` = 22L, `23` = 23L, `24` = 24L, `25` = 25L, `26` = 26L, `27` = 27L,
`28` = 28L, `29` = 29L, `30` = 30L, `31` = 31L, `32` = 32L, `33` = 33L,
`34` = 34L, `35` = 35L, `36` = 36L, `37` = 37L, `38` = 38L, `39` = 39L,
`40` = 40L, `41` = 41L, `42` = 42L, `43` = 43L, `44` = 44L, `45` = 45L,
`46` = 46L, `47` = 47L, `48` = 48L, `49` = 49L, `50` = 50L, `51` = 51L,
`52` = 52L, `53` = 53L, `54` = 54L, `55` = 55L, `56` = 56L, `57` = 57L,
`58` = 58L, `59` = 59L, `60` = 60L, `61` = 61L, `62` = 62L, `63` = 63L,
`64` = 64L, `65` = 65L, `66` = 66L, `67` = 67L, `68` = 68L, `199` = 199L,
`218` = 218L, `219` = 219L, `220` = 220L, `221` = 221L, `222` = 222L,
`223` = 223L, `224` = 224L, `225` = 225L, `226` = 226L, `227` = 227L,
`228` = 228L, `229` = 229L, `230` = 230L, `231` = 231L, `232` = 232L,
`264` = 264L, `265` = 265L, `266` = 266L, `267` = 267L, `352` = 352L,
`353` = 353L, `354` = 354L, `355` = 355L, `356` = 356L, `357` = 357L,
`358` = 358L, `359` = 359L, `360` = 360L, `361` = 361L, `362` = 362L,
`363` = 363L, `364` = 364L, `365` = 365L, `366` = 366L), class = "omit"), row.names = c(14L,
69L, 70L, 71L, 72L, 73L, 74L, 75L, 76L, 77L, 78L, 79L, 80L, 81L,
82L, 83L, 84L, 85L, 86L, 87L, 88L, 89L, 90L, 91L, 92L, 93L, 94L,
95L, 96L, 97L), class = "data.frame")

Body:
The main problem is that the parameters are not uniquely identifiable.  We can multiply a by an arbitrary number and divide c, d and e by that same number and we get the same model. Omit a.

Although it won't hurt the use of as.formula is redundant since it is already a formula.

Having an assignment within an nls formula is highly unusual.  nls will think that Rref is a parameter and fail on that account.  Remove the assignment.

If we make these changes then it does give an answer with the data in the updated version of the question.

form_Q10_parabolic_SM <- Lin_Flux..mymol.m.2.s.1. ~
 exp(b*Mean_Soil_Temp_V2..C.) * ( (-c*Soil_Moist_V3**2) + (d*Soil_Moist_V3) + e)

Q10_parabolic_SM <- nls(form_Q10_parabolic_SM, data = conB1_2015,
  start = list(b = 0.11, c = 0.0001, d = 0.01, e = 0.1))

giving:

> Q10_parabolic_SM
Nonlinear regression model
  model: Lin_Flux..mymol.m.2.s.1. ~ exp(b * Mean_Soil_Temp_V2..C.) * ((-c *     Soil_Moist_V3^2) + (d * Soil_Moist_V3) + e)
   data: conB1_2015
        b         c         d         e
 0.103062 -0.001564 -0.135531  3.528621
 residual sum-of-squares: 3.979

Number of iterations to convergence: 6
Achieved convergence tolerance: 4.401e-06

plinear

Note that nls also has the plinear algorithm which has the advantage that only nonlinear parameters (in this case only b) need starting values.  In that case the formula's RHS should be a matrix with the columns that multiply each linear parameter.  It gives the same answer as above except the linear parameters are given names starting with .lin .  Note that the plinear version converges in fewer iterations than the version using the default algorithm above.  (Also it seems that the plinear version is not very sensitive to the starting value and even if we use b=1 as the starting value it converges.)

fo <- Lin_Flux..mymol.m.2.s.1. ~
  cbind(-Soil_Moist_V3**2, Soil_Moist_V3, 1) * exp(b*Mean_Soil_Temp_V2..C.)
fm <- nls(fo, data = conB1_2015, start = list(b = 0.11), algorithm = "plinear")

giving:

> fm
Nonlinear regression model
  model: Lin_Flux..mymol.m.2.s.1. ~ cbind(-Soil_Moist_V3^2, Soil_Moist_V3,     1) * exp(b * Mean_Soil_Temp_V2..C.)
   data: conB1_2015
                 b              .lin1 .lin.Soil_Moist_V3              .lin3
          0.103062          -0.001564          -0.135528           3.528593
 residual sum-of-squares: 3.979

Number of iterations to convergence: 3
Achieved convergence tolerance: 2.189e-06


问:
WebPack + WebExtensions/Chrome Extension - getBackground() not working
I'm developing a Firefox/Chrome Addon/Extension with the same codebase by utilizing the WebExtensions API and the web-extensions-browser polyfill (through webpack and RequireJS).

I noticed Firefox requires code to be unobfuscated and unminified when submitting a version, and thus had to install the unminify-webpack-plugin here.

The last hindering issue I have is that since webpack includes all the required files in one file (as it usually does), the functionality for browser.extension.getBackground() here doesn't work, as all my functions in my background.js are added to an anonymous module function.

Any suggestions on how I'd go about solving this?

Edit 1: Here's some more insight

My folder structure is as follows:

```<code>plugin/
├── wepback.config.js
├── manifest.json
├── package.json
├── package-lock.json
├── node_modules/
├── *dist/
├── img/
│   ├── icon.png
│   ├── ... etc
├── src/
│   ├── background/
│   │   ├── background.js
│   │   └── background.html
│   └── popup/
│       ├── popup.js
│       └── popup.html
</code>```

Where my config is as follows:

```<code>const path = require('path');
const CopyPlugin = require('copy-webpack-plugin');
var UnminifiedWebpackPlugin = require('unminified-webpack-plugin');

module.exports = {
  entry: {
    background: './src/background/background.js',
    popup: './src/popup/popup.js'
  },
  output: {
    path: path.resolve(__dirname, "dist"),
    filename: "[name]/[name].min.js"
  },
  plugins: [
    new CopyPlugin([
      { from: './src/background/background.html', to: 'background/background.html'},
      { from: './src/popup/popup.html', to: 'popup/popup.html'},
      { from: './src/popup/popup.css', to: 'popup/popup.css'},
      { from: './manifest.json', to: 'manifest.json'},
      { from: './img', to: 'img/[name].[ext]'},
    ]),
    new UnminifiedWebpackPlugin()
  ],
};
</code>```

Edit 2:

Found the following boiler plate which looks promising. This does seem like an issue that, once solved, can just be reused - so I'll try it out soon and move my project over and test.

https://github.com/fstanis/webextensions-webpack-boilerplate

答:
The best way to work around this is using the extension API's message system, with the  sendMessage function and onMessage event - or the port system. See chrome's tutorial on message passing for more information.

Alternatively, you can access the window object directly in your background page - for example, with window.foo = 'bar'. Then getBackgroundPage() will work as expected. Directly mutating or accessing variables across contexts is slightly bad practice, and I'm guessing accessing variables through the window object may be as well, but I think it's probably fine as this is what getBackgroundPage() is intended for anyway.

Body:
I'm developing a Firefox/Chrome Addon/Extension with the same codebase by utilizing the WebExtensions API and the web-extensions-browser polyfill (through webpack and RequireJS).

I noticed Firefox requires code to be unobfuscated and unminified when submitting a version, and thus had to install the unminify-webpack-plugin here.

The last hindering issue I have is that since webpack includes all the required files in one file (as it usually does), the functionality for browser.extension.getBackground() here doesn't work, as all my functions in my background.js are added to an anonymous module function.

Any suggestions on how I'd go about solving this?

Edit 1: Here's some more insight

My folder structure is as follows:

plugin/
├── wepback.config.js
├── manifest.json
├── package.json
├── package-lock.json
├── node_modules/
├── *dist/
├── img/
│   ├── icon.png
│   ├── ... etc
├── src/
│   ├── background/
│   │   ├── background.js
│   │   └── background.html
│   └── popup/
│       ├── popup.js
│       └── popup.html

Where my config is as follows:

const path = require('path');
const CopyPlugin = require('copy-webpack-plugin');
var UnminifiedWebpackPlugin = require('unminified-webpack-plugin');

module.exports = {
  entry: {
    background: './src/background/background.js',
    popup: './src/popup/popup.js'
  },
  output: {
    path: path.resolve(__dirname, "dist"),
    filename: "[name]/[name].min.js"
  },
  plugins: [
    new CopyPlugin([
      { from: './src/background/background.html', to: 'background/background.html'},
      { from: './src/popup/popup.html', to: 'popup/popup.html'},
      { from: './src/popup/popup.css', to: 'popup/popup.css'},
      { from: './manifest.json', to: 'manifest.json'},
      { from: './img', to: 'img/[name].[ext]'},
    ]),
    new UnminifiedWebpackPlugin()
  ],
};

Edit 2:

Found the following boiler plate which looks promising. This does seem like an issue that, once solved, can just be reused - so I'll try it out soon and move my project over and test.

https://github.com/fstanis/webextensions-webpack-boilerplate


问:
Google Drive UI Integration, Submit Failed
I am doing an integration with Google Drive user interface. However when I submit the form for doing so I get this message (with no feedback on the error):

This is the form as it was when I send it:

I have tried sending it from an incognito tap, other browsers, other IPs, other accounts.....
Is there anithing I am not seeing?

答: I solved the problem, the open url has to return status 200. My url required auth and so it returned 403</p>


问:
Custom Query Join in JPA using Criteria Builder API
Currently I am doing it like this:

```<code>List<Table1Entity> findAllMatchingEntities(Table1Entity table1Entity) {
    String queryString = "SELECT table1.* FROM table1 "
                    + "JOIN table2 t2 ON table1.id=t2.table1_id";

    if (table1Entity.getName() != null) {
          queryString +=" where name like ?";
    }

    Query query = em.createNativeQuery(queryString, Table1Entity.class);

    if (table1Entity.getName() != null) {
        query.setParameter(1, table1Entity.getName())
    }

    return query.getResultedList();
}
</code>```

If I want to check more parameters in this join this will quickly turn into a lot of if statements and it would be really complicated to set parameters correctly.

I know I can check parameters with criteria Builder API like this:

```<code>if(table1Entity.getName() != null) {
    table1EntitySpecification = (root, query, criteriaBuilder)
                         -> criteriaBuilder.like(
                            criteriaBuilder.lower(root
                           .get("name")),
                           ("%" + table1Entity.getName() + "%")
                           .toLowerCase());;
}
</code>```

and after that get them all with:

findAll(table1EntitySpecification) with findAll from simpleJPARepository. Now I can chain them together with .or or .and etc. and avoid setting the parameter and checking for null second time.

But how do I do join with criteria APi?

I know I can have in my @Repository something like this:

```<code>@Query(value = "SELECT table1.* FROM table1 JOIN table2 t2 ON table1.id=t2.table1_id", nativeQuery = true)
List<Table1Entity> findAllMatchingEntities(Table1Entity table1Entity);
</code>```

But since name is optional (can be null) I can't just leave it in @Query.

What is the best solution here to avoid using native query and in case of having to check many parameters to avoid using if statements?

答:
I don't know if I fully get your question, but regarding the possibility of nulls, and using the CRUD repository, you can always do a null check before like:

```<code>@Query(value = "SELECT table1.* FROM table1 JOIN table2 t2 ON table1.id=t2.table1_id WHERE table1.id is not null", nativeQuery = true)
List<Table1Entity> findAllMatchingEntities(Table1Entity table1Entity);
</code>```

Depending on what you are trying to achieve, you can always compose the query with similar checks like (not related to your code):

```<code>@Query("SELECT c FROM Certificate c WHERE (:id is null or upper(c.id) = :id) "
           + "and (:name is null or upper(c.name) = :name)")
List<Table1> findStuff(@Param("id") String id,
                       @Param("name") String name);
</code>```

Body:
Currently I am doing it like this:

List<Table1Entity> findAllMatchingEntities(Table1Entity table1Entity) {
    String queryString = "SELECT table1.* FROM table1 "
                    + "JOIN table2 t2 ON table1.id=t2.table1_id";

    if (table1Entity.getName() != null) {
          queryString +=" where name like ?";
    }

    Query query = em.createNativeQuery(queryString, Table1Entity.class);

    if (table1Entity.getName() != null) {
        query.setParameter(1, table1Entity.getName())
    }

    return query.getResultedList();
}

If I want to check more parameters in this join this will quickly turn into a lot of if statements and it would be really complicated to set parameters correctly.

I know I can check parameters with criteria Builder API like this:

if(table1Entity.getName() != null) {
    table1EntitySpecification = (root, query, criteriaBuilder)
                         -> criteriaBuilder.like(
                            criteriaBuilder.lower(root
                           .get("name")),
                           ("%" + table1Entity.getName() + "%")
                           .toLowerCase());;
}

and after that get them all with:

findAll(table1EntitySpecification) with findAll from simpleJPARepository. Now I can chain them together with .or or .and etc. and avoid setting the parameter and checking for null second time.

But how do I do join with criteria APi?

I know I can have in my @Repository something like this:

@Query(value = "SELECT table1.* FROM table1 JOIN table2 t2 ON table1.id=t2.table1_id", nativeQuery = true)
List<Table1Entity> findAllMatchingEntities(Table1Entity table1Entity);

But since name is optional (can be null) I can't just leave it in @Query.

What is the best solution here to avoid using native query and in case of having to check many parameters to avoid using if statements?

Body:
I don't know if I fully get your question, but regarding the possibility of nulls, and using the CRUD repository, you can always do a null check before like:

@Query(value = "SELECT table1.* FROM table1 JOIN table2 t2 ON table1.id=t2.table1_id WHERE table1.id is not null", nativeQuery = true)
List<Table1Entity> findAllMatchingEntities(Table1Entity table1Entity);

Depending on what you are trying to achieve, you can always compose the query with similar checks like (not related to your code):

@Query("SELECT c FROM Certificate c WHERE (:id is null or upper(c.id) = :id) "
           + "and (:name is null or upper(c.name) = :name)")
List<Table1> findStuff(@Param("id") String id,
                       @Param("name") String name);


问:
WP Custom plugin: Create table and insert data once.
This is my complete Wordpress plugin file:

```<code><?php
function wp_create_table_install()
{
    global $wpdb;

    $table_name = $wpdb->prefix.'createtable';
    $sql = 'CREATE TABLE '.$table_name.'(
        id INT(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
        name VARCHAR(75)
    );';

    require_once(ABSPATH.'wp-admin/includes/upgrade.php');
    dbDelta($sql);
}

function wp_create_table_insert_data()
{
    global $wpdb;

    $table_name = $wpdb->prefix.'createtable';
    $id = 1;
    $name = 'WP Create Table!';

    $wpdb->insert($table_name, array('id' => $id, 'name' => $name));
}

register_activation_hook(__FILE__, 'wp_create_table_install');
register_activation_hook(__FILE__, 'wp_create_table_insert_data');
?>
</code>```

When I activate the plugin, it always tries to create a table and insert data. How could I do it once, just in the first plugin activation?

Thank you.

答: A quicker way would be to add  [IF NOT EXISTS] in your CREATE statement so that you don't get an error if your table already exists.</p>

ContentLicense: CC BY-SA 3.0

Body:
This is my complete Wordpress plugin file:

<?php
function wp_create_table_install()
{
    global $wpdb;

    $table_name = $wpdb->prefix.'createtable';
    $sql = 'CREATE TABLE '.$table_name.'(
        id INT(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
        name VARCHAR(75)
    );';

    require_once(ABSPATH.'wp-admin/includes/upgrade.php');
    dbDelta($sql);
}

function wp_create_table_insert_data()
{
    global $wpdb;

    $table_name = $wpdb->prefix.'createtable';
    $id = 1;
    $name = 'WP Create Table!';

    $wpdb->insert($table_name, array('id' => $id, 'name' => $name));
}

register_activation_hook(__FILE__, 'wp_create_table_install');
register_activation_hook(__FILE__, 'wp_create_table_insert_data');
?>

When I activate the plugin, it always tries to create a table and insert data. How could I do it once, just in the first plugin activation?

Thank you.


问:
git filter branch to git filter repo conversion
I am following this command to perform prettier over all commits in my git repository:

```<code>git filter-branch --tree-filter 'prettier --write "**/**.js" || echo “Error formatting, possibly invalid JS“' -- --all
</code>```

I want to perform the same in git filter repo but I am not even sure whether that is achievable. Can anyone help on how to approach this with git filter repo?

答:
I want to perform the same in git filter repo but I am not even sure whether that is achievable

Yes, it is a blob callback and allows you to call any script/command you want on said blob, similar to what is done in newren/git-filter-repo issue 45, and this example

```<code>git filter-repo --force --blob-callback '
  import black
  blob.data = black.reformat_commit(blob.data.decode(), mode=black.FileMode()).encode()
'
</code>```

With reformat_commit as in this python script.

Body:
I am following this command to perform prettier over all commits in my git repository:

git filter-branch --tree-filter 'prettier --write "**/**.js" || echo “Error formatting, possibly invalid JS“' -- --all

I want to perform the same in git filter repo but I am not even sure whether that is achievable. Can anyone help on how to approach this with git filter repo?

Body:
I want to perform the same in git filter repo but I am not even sure whether that is achievable

Yes, it is a blob callback and allows you to call any script/command you want on said blob, similar to what is done in newren/git-filter-repo issue 45, and this example

git filter-repo --force --blob-callback '
  import black
  blob.data = black.reformat_commit(blob.data.decode(), mode=black.FileMode()).encode()
'

With reformat_commit as in this python script.


问:
An argument working outside a function but fails inside a function in R
When outside a function, argument pbkrtest.limit = nobs(m1) below works just fine (thus, no message is generated).

But when inside the foo() function, nobs(m1) is not recognized (thus, a message is generated)! I'm really wondering what is going on?

```<code>library(lme4)
library(emmeans)
dat <- read.csv('https://raw.githubusercontent.com/hkil/m/master/z.csv')

m1 <- lmer(y~ year*group + (1|stid), data = dat)

## WORKS FINE:
emtrends(m1, pairwise ~ group, var = "year", infer = c(T, T), pbkrtest.limit = nobs(m1))

## BUT NOW `nobs(m)` doesn't work inside the function:
foo <- function(m){

 emtrends(m, pairwise ~ group, var = "year", infer = c(T, T), pbkrtest.limit = nobs(m))
}

## RUN:
foo(m = m1)
</code>```

答:
I have looked at this more closely in terms of the actual code in emtrends(). It boils down to what is demonstrated in the following code:

# comparison of evaluation methods with lazy eval

# a trivial function
foo = function(x, ...)
    x^2

# calls foo three ways
foodoo = function(...) {
    message("x1 = ", foo(...))
    message("x2 = ", do.call("foo", list(...)))
    cl = match.call()
    cl[[1]] = quote(foo)
    message("x3 = ", eval(cl))
}

# test value
val = 3.5

# test runs
foodoo(x = 5)
## x1 = 25
## x2 = 25
## x3 = 25

foodoo(x = val)
## x1 = 12.25
## x2 = 12.25
## x3 = 12.25

# same tests, wrapped in a function...
bar = function(z) {
    foodoo(x = z)
}

bar(5)
## x1 = 25
## x2 = 25
## Error in foo(x = z): object 'z' not found

bar(val)
## x1 = 12.25
## x2 = 12.25
## Error in foo(x = z): object 'z' not found
```

<p><sup>Created on 2020-05-31 by the reprex package (v0.3.0)</sup></p>

<p>The problem the OP experienced is related to that third method of evaluation. In <code>emtrends()</code>, the code matches the call, doctors it up for use by a different function, and then evaluates it. I'm not sure I fully understand all of this, but what is passed in function calls are actually promises, not values; a promose consists of an unevaluated expression and the environment in which it should be evaluated. </p>

<p>In looking at <code>foodoo()</code>, it appears that, with the first two methods, those promises are updated to the current environment before <code>foo</code> is called, whereas in the third method, the original call is kept intact so that the promises are not changed. And apparently (I'm still not quite sure why), those original environments are good enough when we call <code>foodoo()</code> from the global environment, but obviously not good enough when called from a different environment. If anybody cares to comment and explain further, I'm all ears.</p>

<p>Anyway, I am happy because I was able to fix the problem by forcing evaluation of all <code>...</code> arguments and replacing them in <code>cl</code>:</p>

<pre class="lang-r prettyprint-override"><code># new foodoo
foodoo = function(...) {
    message("x1 = ", foo(...))
    message("x2 = ", do.call("foo", list(...)))
    cl = match.call()
    cl[[1]] = quote(foo)
    dots = eval(list(...))      # added
    cl[names(dots)] = dots      # added
    message("x3 = ", eval(cl))
}

bar(5)
## x1 = 25
## x2 = 25
## x3 = 25

bar(val)
## x1 = 12.25
## x2 = 12.25
## x3 = 12.25
</code>```

Body:
When outside a function, argument pbkrtest.limit = nobs(m1) below works just fine (thus, no message is generated).

But when inside the foo() function, nobs(m1) is not recognized (thus, a message is generated)! I'm really wondering what is going on?

library(lme4)
library(emmeans)
dat <- read.csv('https://raw.githubusercontent.com/hkil/m/master/z.csv')

m1 <- lmer(y~ year*group + (1|stid), data = dat)

## WORKS FINE:
emtrends(m1, pairwise ~ group, var = "year", infer = c(T, T), pbkrtest.limit = nobs(m1))

## BUT NOW `nobs(m)` doesn't work inside the function:
foo <- function(m){

 emtrends(m, pairwise ~ group, var = "year", infer = c(T, T), pbkrtest.limit = nobs(m))
}

## RUN:
foo(m = m1)

Body:
I have looked at this more closely in terms of the actual code in emtrends(). It boils down to what is demonstrated in the following code:

# comparison of evaluation methods with lazy eval

# a trivial function
foo = function(x, ...)
    x^2

# calls foo three ways
foodoo = function(...) {
    message("x1 = ", foo(...))
    message("x2 = ", do.call("foo", list(...)))
    cl = match.call()
    cl[[1]] = quote(foo)
    message("x3 = ", eval(cl))
}

# test value
val = 3.5

# test runs
foodoo(x = 5)
## x1 = 25
## x2 = 25
## x3 = 25

foodoo(x = val)
## x1 = 12.25
## x2 = 12.25
## x3 = 12.25

# same tests, wrapped in a function...
bar = function(z) {
    foodoo(x = z)
}

bar(5)
## x1 = 25
## x2 = 25
## Error in foo(x = z): object 'z' not found

bar(val)
## x1 = 12.25
## x2 = 12.25
## Error in foo(x = z): object 'z' not found

Created on 2020-05-31 by the reprex package (v0.3.0)

The problem the OP experienced is related to that third method of evaluation. In emtrends(), the code matches the call, doctors it up for use by a different function, and then evaluates it. I'm not sure I fully understand all of this, but what is passed in function calls are actually promises, not values; a promose consists of an unevaluated expression and the environment in which it should be evaluated.

In looking at foodoo(), it appears that, with the first two methods, those promises are updated to the current environment before foo is called, whereas in the third method, the original call is kept intact so that the promises are not changed. And apparently (I'm still not quite sure why), those original environments are good enough when we call foodoo() from the global environment, but obviously not good enough when called from a different environment. If anybody cares to comment and explain further, I'm all ears.

Anyway, I am happy because I was able to fix the problem by forcing evaluation of all ... arguments and replacing them in cl:

# new foodoo
foodoo = function(...) {
    message("x1 = ", foo(...))
    message("x2 = ", do.call("foo", list(...)))
    cl = match.call()
    cl[[1]] = quote(foo)
    dots = eval(list(...))      # added
    cl[names(dots)] = dots      # added
    message("x3 = ", eval(cl))
}

bar(5)
## x1 = 25
## x2 = 25
## x3 = 25

bar(val)
## x1 = 12.25
## x2 = 12.25
## x3 = 12.25


问:
manipulation of lists and dictionaries
This site has helping me a lot. Thank you!
I have a question I would like to resolve.
I have a list of dictionaries, like the one below.

```<code>[{'time': 98000, 'leader': 0, 'vision': 1},
{'time': 98000, 'leader': 1, 'vision': 0},
{'time': 99000, 'leader': 0, 'vision': 1},
{'time': 99000, 'leader': 0, 'vision': 2},
{'time': 99000, 'leader': 1, 'vision': 0},
{'time': 99000, 'leader': 1, 'vision': 2},
{'time': 99000, 'leader': 2, 'vision': 1},
{'time': 99000, 'leader': 2, 'vision': 0}]
</code>```

I need to find the following matches:

{'time': 98000, 'leader': 0, 'vision': 1} = = {'time': 98000, 'leader': 1, 'vision': 0}OK
...
{'time': 99000, 'leader': 2, 'vision': 1} = = {'time': 99000, 'leader': 1, 'vision': 2`} OK
and so on

When the 'leader' value is 0, I want to identify, within the specified time (for example 'time': 99000), if there is any other line where the 'vision' value: is 0. When I find it, I I want to know if the value of the 'leader': of this line is equal to the value of 'vision': of the 'leader': 0. I will follow the same logic for other values of leaders, at different times.

best wishes

答:
If I understand correctly, your best bet will to be loop through the list and verify with the in operator, which can be done relatively cleanly with list comprehension:

```<code>def not_unique(el):
    print(el, "has a reciprocal")

def unique(el):
    print(el, "is unique")

tlv_list = [{'time': 98000, 'leader': 0, 'vision': 1},
            {'time': 98000, 'leader': 1, 'vision': 0},
            {'time': 99000, 'leader': 0, 'vision': 1},
            {'time': 99000, 'leader': 0, 'vision': 2},
            {'time': 99000, 'leader': 1, 'vision': 0},
            {'time': 99000, 'leader': 1, 'vision': 2},
            {'time': 99000, 'leader': 2, 'vision': 1},
            {'time': 99000, 'leader': 2, 'vision': 0}]

[not_unique(i) if {'time': i['time'], 'leader': i['vision'], 'vision': i['leader']} in tlv_list else unique(i) for i in tlv_list]
</code>```

Title: manipulation of lists and dictionaries

Body:
This site has helping me a lot. Thank you!
I have a question I would like to resolve.
I have a list of dictionaries, like the one below.

[{'time': 98000, 'leader': 0, 'vision': 1},
{'time': 98000, 'leader': 1, 'vision': 0},
{'time': 99000, 'leader': 0, 'vision': 1},
{'time': 99000, 'leader': 0, 'vision': 2},
{'time': 99000, 'leader': 1, 'vision': 0},
{'time': 99000, 'leader': 1, 'vision': 2},
{'time': 99000, 'leader': 2, 'vision': 1},
{'time': 99000, 'leader': 2, 'vision': 0}]

I need to find the following matches:

{'time': 98000, 'leader': 0, 'vision': 1} = = {'time': 98000, 'leader': 1, 'vision': 0}OK
...
{'time': 99000, 'leader': 2, 'vision': 1} = = {'time': 99000, 'leader': 1, 'vision': 2`} OK
and so on

When the 'leader' value is 0, I want to identify, within the specified time (for example 'time': 99000), if there is any other line where the 'vision' value: is 0. When I find it, I I want to know if the value of the 'leader': of this line is equal to the value of 'vision': of the 'leader': 0. I will follow the same logic for other values of leaders, at different times.

best wishes

Body:
If I understand correctly, your best bet will to be loop through the list and verify with the in operator, which can be done relatively cleanly with list comprehension:

def not_unique(el):
    print(el, "has a reciprocal")

def unique(el):
    print(el, "is unique")

tlv_list = [{'time': 98000, 'leader': 0, 'vision': 1},
            {'time': 98000, 'leader': 1, 'vision': 0},
            {'time': 99000, 'leader': 0, 'vision': 1},
            {'time': 99000, 'leader': 0, 'vision': 2},
            {'time': 99000, 'leader': 1, 'vision': 0},
            {'time': 99000, 'leader': 1, 'vision': 2},
            {'time': 99000, 'leader': 2, 'vision': 1},
            {'time': 99000, 'leader': 2, 'vision': 0}]

[not_unique(i) if {'time': i['time'], 'leader': i['vision'], 'vision': i['leader']} in tlv_list else unique(i) for i in tlv_list]


问:
Java: two threads executing until the boolean flag is false: the second thread's first run stops the first thread
I have this threaded program that has three threads: main, lessonThread, questionThread.

It works like this:

Lesson continues continues to gets printed while the finished
the variable is true;

every 5 seconds the questionThread asks Finish
the lesson? and if the answer is y, it sets finished to false

The problem is that the Lesson continues never gets printed after the question gets asked the first time:

Also, as seen on the picture, sometimes lessonThread sneaks in with its Lesson continues before the user can enter the answer to the questionThread's question.

```<code>public class Lesson {
    private boolean finished;
    private boolean waitingForAnswer;
    private Scanner scanner = new Scanner(System.in);

    private Thread lessonThread;
    private Thread questionThread;

    public static void main(String[] args) {
        Lesson lesson = new Lesson();
        lesson.lessonThread = lesson.new LessonThread();
        lesson.questionThread = lesson.new QuestionThread();

        lesson.lessonThread.start();
        lesson.questionThread.start();
    }

    class LessonThread extends Thread  {
        @Override
        public void run()  {
            while (!finished && !waitingForAnswer)  {
                System.out.println("Lesson continues");
            }
        }
    }

    class QuestionThread extends Thread {
        private Instant sleepStart = Instant.now();
        private boolean isAsleep = true;
        @Override
        public void run() {
            while (!finished) {
                if (isAsleep && Instant.now().getEpochSecond() - sleepStart.getEpochSecond() >= 5) {
                    System.out.print("Finish a lesson? y/n");
                    waitingForAnswer = true;
                    String reply = scanner.nextLine().substring(0, 1);
                    switch (reply.toLowerCase()) {
                        case "y":
                            finished = true;
                    }
                    waitingForAnswer = false;

                    isAsleep = true;
                    sleepStart = Instant.now();
                }
            }
        }
    }
}
</code>```

I think the waitingForAnswer = true might be at fault here, but then, the lessonThread has 5 seconds until the questionThread asks the question again, during which the waitingForAnswer is false.

Any help is greatly appreciated.

EDIT: I found a buy in the loop in the lessonThread and changed it to:

```<code>    @Override
        public void run()  {
            while (!finished)  {
                if (!waitingForAnswer)  {
                    System.out.println("Lesson continues");
                }
            }
        }
</code>```

However, I get the same result.

EDIT: I can get it working when inside a debugger:

答:
this just isn't how you're supposed to work with threads. You have 2 major problems here:

java memory model.

Imagine that one thread writes to some variable, and a fraction of a second later, another thread reads it. If that would be guaranteed to work the way you want it to, that means that write has to propagate all the way through any place that could ever see it before code can continue.. and because you have absolutely no idea which fields are read by some thread until a thread actually reads it (java is not in the business of attempting to look ahead and predict what the code will be doing later), that means every single last write to any variable needs a full propagate sync across all threads that can see it... which is all of them! Modern CPUs have multiple cores and each core has their own cache, and if we apply that rule (all changes must be visible immediately everywhere) you might as well take all that cache and chuck it in the garbage because you wouldn't be able to use it.

If it worked like that - java would be slower than molasses.

So java does not work like that. Any thread is free to make a copy of any field or not, at its discretion. If thread A writes 'true' to some instance's variable, and thread B reads that boolean from the exact same instance many seconds later, java is entirely free to act as if the value is 'false'... even if when code in thread A looks at it, it sees 'true'. At some arbitrary later point the values will sync up. It may take a long time, no guarantees are available to you.

So how do you work with threads in java?

The JMM (Java Memory Model) works by describing so called comes-before/comes-after relationships: Only if code is written to clearly indicate that you intend for some event in thread A to clearly come before some other event in thread B, then java will guarantee that any effects performed in thread A and visible there will also be visible in thread B once B's event (the one that 'came after') has finished.

For example, if thread A does:

```<code>synchronized (someRef) {
    someRef.intVal1 = 1;
    someRef.intVal2 = 2;
}
</code>```

and thread B does:

```<code>synchronized(someRef) {
    System.out.println(someRef.intVal1 + someRef.intVal2);
}
</code>```

then you are guaranteed to witness in B either 0 (which will be the case where B 'won' the fight and got to the synchronized statement first), or 3, which is always printed if B got there last; that synchronized block is establishing a CBCA relationship: The 'winning' thread's closing } 'comes before' the losing thread's opening one, as far as execution is concerned, therefore any writes done by thread A will be visible by thread B by the time it enters it sync block.

Your code does not establish any such relationships, therefore, you have no guarantees.

You establish them with writes/reads from volatile fields, with synchronized(), and with any code that itself uses these, which is a lot of code: Most classes in the java.util.concurrent package, starting threads, and many other things do some sync/volatile access internally.

The flying laptop issue.

It's not the 1980s anymore. Your CPU is capable of doing enough calculations at any given moment to draw enough power to heat a small house comfortably. The reason your laptop or desktop or phone isn't a burning ball of lava is because the CPU is almost always doing entirely nothing whatsoever, and thus not drawing any current and heating up. In fact, once a CPU gets going, it will very very quickly overheat itself and throttle down and run slower. That's because 95%+ of common PC workloads involve a 'burst' of calculations to be done, which the CPU can do in a fraction of a second at full turboboosted power, and then it can go back to idling again whilst the fans and the cooling paste and the heat fins dissipate the heat that this burst of power caused. That's why if you try to do something that causes the CPU to be engaged for a long time, such as encoding video, it seems to go a little faster at first before it slows down to a stable level.. whilst your battery is almost visibly draining down and your fans sound like the laptop is about to take off for higher orbit and follow Doug and Bob to the ISS - because that stable level is 'as fast as the fans and heat sinks can draw the heat away from the CPU so that it doesn't explode'. Which is not as fast as when it was still colder, but still pretty fast. Especially if you have powerful fans.

The upshot of all this?

You must idle that CPU.

something like:

while (true) {}

is a so-called 'busy loop': It does nothing, looping forever, whilst keeping the CPU occupied, burning a hole into the laptop and causing the fans to go ape. This is not a good thing. If you want execution to wait for some event before continuing, then wait for it. Keyword: wait. If you just want to wait for 5 seconds, Thread.sleep(5000) is what you want. Not a busy-loop. If you want to wait until some other thread has performed a job, use the core wait/notifyAll system (these are methods on j.l.Object and interact with the synchronized keyword), or better yet, use a latch or a lock object from java.util.concurrent, those classes are fantastic. If you just want to ensure that 2 threads don't conflict while they touch the same data, use synchronized. All these features will let the CPU idle down. endlessly spinning away in a while loop, checking an if clause - that is a bad idea.

And you get CBCA relationships to boot, which is what is required for any 2 threads to communicate with each other.

And because you're overloading the CPU with work, that sync point where your '= false' writes get synced back over to the other thread probably aren't happening - normally it's relatively hard to observe JMM issues (which is what makes multithreaded programming so tricky - it is complex, you will mess up, it's hard to test for errors, and it's plausible you'll never personally run into this problem today. But tomorrow, with another song on the winamp, on another system, happens all the time). This is a fine way to observe it a lot.

Body:
I have this threaded program that has three threads: main, lessonThread, questionThread.

It works like this:

Lesson continues continues to gets printed while the finished
the variable is true;

every 5 seconds the questionThread asks Finish
the lesson? and if the answer is y, it sets finished to false

The problem is that the Lesson continues never gets printed after the question gets asked the first time:

Also, as seen on the picture, sometimes lessonThread sneaks in with its Lesson continues before the user can enter the answer to the questionThread's question.

public class Lesson {
    private boolean finished;
    private boolean waitingForAnswer;
    private Scanner scanner = new Scanner(System.in);

    private Thread lessonThread;
    private Thread questionThread;

    public static void main(String[] args) {
        Lesson lesson = new Lesson();
        lesson.lessonThread = lesson.new LessonThread();
        lesson.questionThread = lesson.new QuestionThread();

        lesson.lessonThread.start();
        lesson.questionThread.start();
    }

    class LessonThread extends Thread  {
        @Override
        public void run()  {
            while (!finished && !waitingForAnswer)  {
                System.out.println("Lesson continues");
            }
        }
    }

    class QuestionThread extends Thread {
        private Instant sleepStart = Instant.now();
        private boolean isAsleep = true;
        @Override
        public void run() {
            while (!finished) {
                if (isAsleep && Instant.now().getEpochSecond() - sleepStart.getEpochSecond() >= 5) {
                    System.out.print("Finish a lesson? y/n");
                    waitingForAnswer = true;
                    String reply = scanner.nextLine().substring(0, 1);
                    switch (reply.toLowerCase()) {
                        case "y":
                            finished = true;
                    }
                    waitingForAnswer = false;

                    isAsleep = true;
                    sleepStart = Instant.now();
                }
            }
        }
    }
}

I think the waitingForAnswer = true might be at fault here, but then, the lessonThread has 5 seconds until the questionThread asks the question again, during which the waitingForAnswer is false.

Any help is greatly appreciated.

EDIT: I found a buy in the loop in the lessonThread and changed it to:

    @Override
        public void run()  {
            while (!finished)  {
                if (!waitingForAnswer)  {
                    System.out.println("Lesson continues");
                }
            }
        }

However, I get the same result.

EDIT: I can get it working when inside a debugger:

Body:
this just isn't how you're supposed to work with threads. You have 2 major problems here:

java memory model.

Imagine that one thread writes to some variable, and a fraction of a second later, another thread reads it. If that would be guaranteed to work the way you want it to, that means that write has to propagate all the way through any place that could ever see it before code can continue.. and because you have absolutely no idea which fields are read by some thread until a thread actually reads it (java is not in the business of attempting to look ahead and predict what the code will be doing later), that means every single last write to any variable needs a full propagate sync across all threads that can see it... which is all of them! Modern CPUs have multiple cores and each core has their own cache, and if we apply that rule (all changes must be visible immediately everywhere) you might as well take all that cache and chuck it in the garbage because you wouldn't be able to use it.

If it worked like that - java would be slower than molasses.

So java does not work like that. Any thread is free to make a copy of any field or not, at its discretion. If thread A writes 'true' to some instance's variable, and thread B reads that boolean from the exact same instance many seconds later, java is entirely free to act as if the value is 'false'... even if when code in thread A looks at it, it sees 'true'. At some arbitrary later point the values will sync up. It may take a long time, no guarantees are available to you.

So how do you work with threads in java?

The JMM (Java Memory Model) works by describing so called comes-before/comes-after relationships: Only if code is written to clearly indicate that you intend for some event in thread A to clearly come before some other event in thread B, then java will guarantee that any effects performed in thread A and visible there will also be visible in thread B once B's event (the one that 'came after') has finished.

For example, if thread A does:

synchronized (someRef) {
    someRef.intVal1 = 1;
    someRef.intVal2 = 2;
}

and thread B does:

synchronized(someRef) {
    System.out.println(someRef.intVal1 + someRef.intVal2);
}

then you are guaranteed to witness in B either 0 (which will be the case where B 'won' the fight and got to the synchronized statement first), or 3, which is always printed if B got there last; that synchronized block is establishing a CBCA relationship: The 'winning' thread's closing } 'comes before' the losing thread's opening one, as far as execution is concerned, therefore any writes done by thread A will be visible by thread B by the time it enters it sync block.

Your code does not establish any such relationships, therefore, you have no guarantees.

You establish them with writes/reads from volatile fields, with synchronized(), and with any code that itself uses these, which is a lot of code: Most classes in the java.util.concurrent package, starting threads, and many other things do some sync/volatile access internally.

The flying laptop issue.

It's not the 1980s anymore. Your CPU is capable of doing enough calculations at any given moment to draw enough power to heat a small house comfortably. The reason your laptop or desktop or phone isn't a burning ball of lava is because the CPU is almost always doing entirely nothing whatsoever, and thus not drawing any current and heating up. In fact, once a CPU gets going, it will very very quickly overheat itself and throttle down and run slower. That's because 95%+ of common PC workloads involve a 'burst' of calculations to be done, which the CPU can do in a fraction of a second at full turboboosted power, and then it can go back to idling again whilst the fans and the cooling paste and the heat fins dissipate the heat that this burst of power caused. That's why if you try to do something that causes the CPU to be engaged for a long time, such as encoding video, it seems to go a little faster at first before it slows down to a stable level.. whilst your battery is almost visibly draining down and your fans sound like the laptop is about to take off for higher orbit and follow Doug and Bob to the ISS - because that stable level is 'as fast as the fans and heat sinks can draw the heat away from the CPU so that it doesn't explode'. Which is not as fast as when it was still colder, but still pretty fast. Especially if you have powerful fans.

The upshot of all this?

You must idle that CPU.

something like:

while (true) {}

is a so-called 'busy loop': It does nothing, looping forever, whilst keeping the CPU occupied, burning a hole into the laptop and causing the fans to go ape. This is not a good thing. If you want execution to wait for some event before continuing, then wait for it. Keyword: wait. If you just want to wait for 5 seconds, Thread.sleep(5000) is what you want. Not a busy-loop. If you want to wait until some other thread has performed a job, use the core wait/notifyAll system (these are methods on j.l.Object and interact with the synchronized keyword), or better yet, use a latch or a lock object from java.util.concurrent, those classes are fantastic. If you just want to ensure that 2 threads don't conflict while they touch the same data, use synchronized. All these features will let the CPU idle down. endlessly spinning away in a while loop, checking an if clause - that is a bad idea.

And you get CBCA relationships to boot, which is what is required for any 2 threads to communicate with each other.

And because you're overloading the CPU with work, that sync point where your '= false' writes get synced back over to the other thread probably aren't happening - normally it's relatively hard to observe JMM issues (which is what makes multithreaded programming so tricky - it is complex, you will mess up, it's hard to test for errors, and it's plausible you'll never personally run into this problem today. But tomorrow, with another song on the winamp, on another system, happens all the time). This is a fine way to observe it a lot.


问:
Wordpress Permalink Issue w/ Subdomains
My setup: I have domain.com pointing to Server 1 and have set up blog.domain.com to point to another wordpress Server 2 that hosts multiple wordpress sites. Server 2 has multiple wordpress sites in a single Ubuntu server as per these instructions. Because this manual is outdated, I also follow wordpress virtual host configuration based on Step 4 detailed in this post. Describing my setup up front because I'm not sure if my problem is because of this setup.

Question:

Based on this setup, Wordpress works fine with the default permalink option. Below are the details in my conf file

```<code>DocumentRoot /var/www/domain
ServerName blog.domain.com
ServerAlias blog.domain.com
<Directory "/var/www/domain">
    Options Indexes FollowSymLinks MultiViews
    AllowOverride None
    Order allow,deny
    allow from all
</Directory>
</code>```

When plain permalinks are selected, my htaccess file in /var/www/domain is empty and everything works fine.However, when I change the permalink to Post name (blog.domain.com/sample-post/) the homepage (blog.domain.com) works fine but my individual post url (blog.domain.com/sample-post/) does not work. My htaccess file looks like this:

```<code><IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
</code>```

WordPress Address (URL) = blog.domain.com
Site Address (URL) = blog.domain.com

Could you please help resolve this. I'd like permalinks to be enabled but have been stuck with this issue for several months. Really appreciate all your comments & feedback.

答: I was able to resolve this by following instructions by Robert in this thread - WordPress Multisite 404 error on posts and subsites</p>

Title: Wordpress Permalink Issue w/ Subdomains

Body:
My setup: I have domain.com pointing to Server 1 and have set up blog.domain.com to point to another wordpress Server 2 that hosts multiple wordpress sites. Server 2 has multiple wordpress sites in a single Ubuntu server as per these instructions. Because this manual is outdated, I also follow wordpress virtual host configuration based on Step 4 detailed in this post. Describing my setup up front because I'm not sure if my problem is because of this setup.

Question:

Based on this setup, Wordpress works fine with the default permalink option. Below are the details in my conf file

DocumentRoot /var/www/domain
ServerName blog.domain.com
ServerAlias blog.domain.com
<Directory "/var/www/domain">
    Options Indexes FollowSymLinks MultiViews
    AllowOverride None
    Order allow,deny
    allow from all
</Directory>

When plain permalinks are selected, my htaccess file in /var/www/domain is empty and everything works fine.However, when I change the permalink to Post name (blog.domain.com/sample-post/) the homepage (blog.domain.com) works fine but my individual post url (blog.domain.com/sample-post/) does not work. My htaccess file looks like this:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

WordPress Address (URL) = blog.domain.com
Site Address (URL) = blog.domain.com

Could you please help resolve this. I'd like permalinks to be enabled but have been stuck with this issue for several months. Really appreciate all your comments & feedback.


问:
Zend bootstrap, including javascript files for certain pages only
I'm loading javascript files in the bootstrap as usual, but there's a file that I want to have included only if it's a page that has a form

```<code>->appendFile('http://myurl.com/js/formscript.js');
</code>```

Is there a way to detect the page being loaded, from the bootstrap so I can decide whether or not to include this file?

I thought about passing a variable from the Form to the view, and then checking for that variable in the bootstrap, but it's not working.

This would be in my form

```<code>$layout = new Zend_Layout();
$view = $layout->getView();
$view->formscript = true;
</code>```

and this would be in my bootstrap

```<code>if ($view->formscript)
</code>```

but var_dump($view->formscript) give me null, so any other ideas to activate js files only in specific conditions?

答:
Why not move over appendFile() to your form class (of course if you use Zend_Form), you would be sure that your JS line will be created only in the same time as your form. The place for this line is good in init() as well as in render()

```<code>class Your_Form extends Zend_Form {
    public init(){
        $this->getView()->appendFile('http://myurl.com/js/formscript.js');
        [...]
    }
}
</code>```

Body:
I'm loading javascript files in the bootstrap as usual, but there's a file that I want to have included only if it's a page that has a form

->appendFile('http://myurl.com/js/formscript.js');

Is there a way to detect the page being loaded, from the bootstrap so I can decide whether or not to include this file?

I thought about passing a variable from the Form to the view, and then checking for that variable in the bootstrap, but it's not working.

This would be in my form

$layout = new Zend_Layout();
$view = $layout->getView();
$view->formscript = true;

and this would be in my bootstrap

if ($view->formscript)

but var_dump($view->formscript) give me null, so any other ideas to activate js files only in specific conditions?

Body:
Why not move over appendFile() to your form class (of course if you use Zend_Form), you would be sure that your JS line will be created only in the same time as your form. The place for this line is good in init() as well as in render()

class Your_Form extends Zend_Form {
    public init(){
        $this->getView()->appendFile('http://myurl.com/js/formscript.js');
        [...]
    }
}


问:
Policy to prevent adding users of Chrome
In the Chrome UI, there's an avatar displayed next to the settings dots which when pressed allows the user to perform actions related to users of Chrome.  They can add a user.  If they go into 'other people' settings they can remove a previously added user.  And the user can chose to sign in if they want to sync things like bookmarks across devices.

There's also a guest option, which allows a guest user to have their own temporary profile; this allows someone to use Chrome without messing up the other persons history, bookmarks or cookies.  This guest account can be turned off by using the BrowserGuestModeEnabled Chrome policy.

How can I prevent the user from adding additional accounts (or removing any that are in place)?  I thought maybe BrowserSignin would work, but it doesn't seem to be what I want.

答: I found it.  BrowserAddPersonEnabled</p>

Body: I found it.  BrowserAddPersonEnabled


问:
Responsive Textarea on Image (Bootstrap)
Somehow i cant figure that out.
Hello everyone.

Ive got a simple frontend with a navbar and 2 Cols underneath.
left col got fixed size of 80px, and the right one got an image inside (so this image is fluid / responsive).

To add an input field over the image isnt the problem at all, but here comes my blockade.
I cant get the inputfield to be responsive to the size of the image.

So my thoughts was, to get the scale of the image and downscale the input.

something like this in JS

```<code>$(window).resize(function() {
    // 1192 is the original imagewidth
    let scale  = $(".step:visible").width() / 1192;

    let inputposition = document.getElementById(testid);
    inputposition .css('transform', 'scale(' + scale + ')');
    inputposition .css('transform-origin', 'top left');
});
</code>```

now i thought about transform: scale(scale); on  but this downscales the image too.

maybe someone of you can give me some food for thoughts.

So my goal is, that the inputfield minimizes as well reposition if the window resizes.

heres the sample code im workin with:

```<code><!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no">
    <title>Test</title>

    <link rel="stylesheet" href="assets/bootstrap/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Montserrat:400,400i,700,700i,600,600i">
    <script src="assets/js/jquery.min.js"></script>
</head>

<body>
    <nav class="navbar navbar-light navbar-expand-lg bg-danger clean-navbar">
        <div class="container"><a class="navbar-brand logo" >Test</a><button class="navbar-toggler" data-toggle="collapse" data-target="#navcol-1"><span class="navbar-toggler-icon"></span></button>
            <div class="collapse navbar-collapse" id="navcol-1">
                <ul class="nav navbar-nav ml-auto">
                </ul>
            </div>
        </div>
    </nav>
    <main class="page landing-page">
        <section class="clean-block clean-info dark" style="padding: 0px;">
            <div class="container" style="">
                <div class="row align-items-start" style="">
                    <div id="sidebar" class="col-1 d-md-flex flex-grow-0 flex-shrink-0 bg-danger active" style="max-width: 80px;min-width: 80px;height: 100%;padding:0px">
                        <ul class="list-unstyled components" style="padding:0px">
                            <li class="active" id="page1_li" style="position: relative; padding: 10px;">
                                <a onclick="function(this);" id="page1">
                                    <img src="thumb_page1.jpg" class="img-fluid" alt="Responsive image" style="width:100%">
                                    <div class="overlay">
                                        <i id="overlay_page<?= $i ?>" class=""></i>
                                    </div>
                                </a>
                            </li>
                        </ul>
                    </div>
                    <div class="col text-center bg-primary" style="padding: 0px;">
                        <form class="form-horizontal form" action="submit.php" method="post">
                            <div class="step " id="page1">
                                <div class="fullpage" style="" data-fullpage="fullpage">

                                    <img class="img-thumbnail align-items-center" src="page1.jpg" alt="" draggable="false" contenteditable="false">

                                    <!-- input that needs to be scaled -->
                                    <input type="textarea" id="testid" name="testid" value="" style="position:absolute;left:100px;top:150px;width:300px;height:100px">

                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </section>
    </main>

    <script src="assets/bootstrap/js/bootstrap.min.js"></script>
</body>

</html>

</code>```

With best regards.

答:
This is really simple. Don't add position:absolute to <input> but use
 for that.

You need a
 with position:relative as container. Add image with classes w-100 d-block to make it responsive. Create a
 overlay and place content inside. <input> and <textarea> with class .form-control will have width:100% by default.

/*DEMO*/body{padding:3rem}

#overlay{
  position:absolute;
  top:50%;
  right:3rem;
  left:3rem;
  transform:translateY(-50%);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">

<div class="position-relative">
  <img class="w-100 d-block" src="https://via.placeholder.com/400x300/007bff/ffffff" alt="">
  <div id="overlay">
    <input class="form-control" placeholder="Lorem Ipsum">
    <hr>
    <textarea class="form-control" placeholder="Lorem Ipsum"></textarea>
  </div>
</div></code>```

Body:
Somehow i cant figure that out.
Hello everyone.

Ive got a simple frontend with a navbar and 2 Cols underneath.
left col got fixed size of 80px, and the right one got an image inside (so this image is fluid / responsive).

To add an input field over the image isnt the problem at all, but here comes my blockade.
I cant get the inputfield to be responsive to the size of the image.

So my thoughts was, to get the scale of the image and downscale the input.

something like this in JS

$(window).resize(function() {
    // 1192 is the original imagewidth
    let scale  = $(".step:visible").width() / 1192;

    let inputposition = document.getElementById(testid);
    inputposition .css('transform', 'scale(' + scale + ')');
    inputposition .css('transform-origin', 'top left');
});

now i thought about transform: scale(scale); on  but this downscales the image too.

maybe someone of you can give me some food for thoughts.

So my goal is, that the inputfield minimizes as well reposition if the window resizes.

heres the sample code im workin with:

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no">
    <title>Test</title>

    <link rel="stylesheet" href="assets/bootstrap/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Montserrat:400,400i,700,700i,600,600i">

Test<button class="navbar-toggler" data-toggle="collapse" data-target="#navcol-1"></button>

                                        <i id="overlay_page<?= $i ?>" class="">

                        <form class="form-horizontal form" action="submit.php" method="post">

                                    <input type="textarea" id="testid" name="testid" value="" style="position:absolute;left:100px;top:150px;width:300px;height:100px">

                        </form>

With best regards.

Body:
This is really simple. Don't add position:absolute to <input> but use <div> for that.

You need a <div> with position:relative as container. Add image with classes w-100 d-block to make it responsive. Create a <div> overlay and place content inside. <input> and <textarea> with class .form-control will have width:100% by default.

/*DEMO*/body{padding:3rem}

#overlay{
  position:absolute;
  top:50%;
  right:3rem;
  left:3rem;
  transform:translateY(-50%);
}

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">

<div class="position-relative">
  <img class="w-100 d-block" src="https://via.placeholder.com/400x300/007bff/ffffff" alt="">
  <div id="overlay">
    <input class="form-control" placeholder="Lorem Ipsum">
    <hr>
    <textarea class="form-control" placeholder="Lorem Ipsum"></textarea>
  </div>
</div>


问:
What is batch quota in the context of offline inference (machine learning)?
The slide below mentions "batch quota". This is from this video from Google's ML Course with TensorFlow.

What do they mean by "batch quota"? and why is it an upside of an offline inference engine?

答: It's just mean to parallel or distributed algorithm over N batches (i.e. MapReduce) instead of all dataset sizes. Offline as you just predict some large number of data points locally rather than real-time prediction, so that is the case you have a larger amount of data you are trying to predict (ex. weather data)


问:
How do I get into a Docker container's shell?
I'm getting started working with Docker. I'm using the WordPress base image and docker-compose.

I'm trying to ssh into one of the containers to inspect the files/directories that were created during the initial build. I tried to run docker-compose run containername ls -la, but that didn't do anything. Even if it did, I'd rather have a console where I can traverse the directory structure, rather than run a single command. What is the right way to do this with Docker?

答:
To exec into a running container named test, below is the following commands

If the container has bash shell

```<code>docker exec -it test /bin/bash
</code>```

If the container has bourne shell and most of the cases it's present

```<code>docker run -it test /bin/sh
</code>```

Body:
To exec into a running container named test, below is the following commands

If the container has bash shell

docker exec -it test /bin/bash

If the container has bourne shell and most of the cases it's present

docker run -it test /bin/sh


问:
Where trailing return type is actually needed in C++?
I am reading about trailing return type. I came across this site https://blog.petrzemek.net/2017/01/17/pros-and-cons-of-alternative-function-syntax-in-cpp/ which is explaining about the need of these return types and it mentioned as below.

```<code>template<typename Lhs, typename Rhs>
decltype(lhs + rhs) add(const Lhs& lhs, const Rhs& rhs) {
    // error: ^^^ 'lhs' and 'rhs' were not declared in this scope
    return lhs + rhs;
}
</code>```

... Since the compiler parses the source code from left to right, it sees lhs and rhs before their definitions, and rejects the code. By using the trailing return type, we can circumvent this limitation.

But as per my understanding, by the time compiler reaches decltype(lhs + rhs), it should already know the types of lhs and rhs. Can any one please let me know why compiler is not able to deduce the return types of the function and are there any other uses where we must use trailing return type other than templates.

答: It knows the capitalized types Lhs and Rhs, but not the lowercase variables lhs and rhs. They're declared after the decltype.

Body:
I am reading about trailing return type. I came across this site https://blog.petrzemek.net/2017/01/17/pros-and-cons-of-alternative-function-syntax-in-cpp/ which is explaining about the need of these return types and it mentioned as below.

template<typename Lhs, typename Rhs>
decltype(lhs + rhs) add(const Lhs& lhs, const Rhs& rhs) {
    // error: ^^^ 'lhs' and 'rhs' were not declared in this scope
    return lhs + rhs;
}

... Since the compiler parses the source code from left to right, it sees lhs and rhs before their definitions, and rejects the code. By using the trailing return type, we can circumvent this limitation.

But as per my understanding, by the time compiler reaches decltype(lhs + rhs), it should already know the types of lhs and rhs. Can any one please let me know why compiler is not able to deduce the return types of the function and are there any other uses where we must use trailing return type other than templates.


问:
I need to make 4 squares move vertically using a loop
I need to make 4 individual squares that move vertically and when they touch the window edge they change directions. I can do it with one square but how do i do it with 4 to avoid repeating the loop. This has to be done in processing</p>

答:
The code you are looking for looks like this (tested):

```<code>int x[] = new int[4];
int y[] = new int[x.length];
int s[] = new int[x.length];
int vx[] = new int[x.length];
int vy[] = new int[x.length];

void setup(){
  size(400, 400);

  for(int i = 0; i < x.length; i++){
    x[i] = round(random(width) - s[i]);
    y[i] = round(random(height) - s[i]);
    s[i] = round(random(90));
    vx[i] = round(random(-6, 6));
    vy[i] = round(random(-6, 6));
  }
}

void draw(){
  background(0);
  for(int i = 0; i < x.length; i++){
    rect(x[i], y[i], s[i], s[i]);
    x[i] += vx[i];
    y[i] += vy[i];
    if(vx[i] + x[i] > width - s[i] / 2 || vx[i] + x[i] < 0 + s[i] / 2) vx[i] *= -1;
    if(vy[i] + y[i] > height - s[i] / 2 || vy[i] + y[i] < 0 + s[i] / 2) vy[i] *= -1;
  }
}
</code>```

To add more squares, just change the number 4 in the first line to the amount of squares you want. To change the squares presets / properties, just change what they are set to inside the for loop in the setup(). The way this works is it generates some random squares at random positions with random sizes moving with random constant velocities. the squares do not, however, collide with each other. If you want to know how to make them collide with each other, just ask that in a different question and rest assured I will be there to answer [:)]. Also, I can see that you are a beginner to processing. I recommend this set of playlists starting at 4.0: processing 3 - The Coding Train.

Body:
The code you are looking for looks like this (tested):

int x[] = new int[4];
int y[] = new int[x.length];
int s[] = new int[x.length];
int vx[] = new int[x.length];
int vy[] = new int[x.length];

void setup(){
  size(400, 400);

  for(int i = 0; i < x.length; i++){
    x[i] = round(random(width) - s[i]);
    y[i] = round(random(height) - s[i]);
    s[i] = round(random(90));
    vx[i] = round(random(-6, 6));
    vy[i] = round(random(-6, 6));
  }
}

void draw(){
  background(0);
  for(int i = 0; i < x.length; i++){
    rect(x[i], y[i], s[i], s[i]);
    x[i] += vx[i];
    y[i] += vy[i];
    if(vx[i] + x[i] > width - s[i] / 2 || vx[i] + x[i] < 0 + s[i] / 2) vx[i] *= -1;
    if(vy[i] + y[i] > height - s[i] / 2 || vy[i] + y[i] < 0 + s[i] / 2) vy[i] *= -1;
  }
}

To add more squares, just change the number 4 in the first line to the amount of squares you want. To change the squares presets / properties, just change what they are set to inside the for loop in the setup(). The way this works is it generates some random squares at random positions with random sizes moving with random constant velocities. the squares do not, however, collide with each other. If you want to know how to make them collide with each other, just ask that in a different question and rest assured I will be there to answer [:)]. Also, I can see that you are a beginner to processing. I recommend this set of playlists starting at 4.0: processing 3 - The Coding Train.


问:
Java SOAP webservice always return null
I have a simple SOAP webservice server like this:

```<code>public class receiver extends JAXMServlet implements ReqRespListener {

    public SOAPMessage onMessage(SOAPMessage soapm) {
        return soapm;
    }
}
</code>```

In the client I send a message to this server:

```<code>public class sender {

    /** This is a sample web service operation */

    SOAPConnectionFactory scfac = null;
    SOAPConnection con =null;
    MessageFactory fac = null;
    SOAPMessage message = null;
    SOAPMessage response = null;
    @WebMethod(operationName = "sender")
    public String sender(@WebParam(name = "a") String a)
    {
        try{
        //Creat Connection
        scfac = SOAPConnectionFactory.newInstance();
        con = scfac.createConnection();
        fac = MessageFactory.newInstance();
        message = fac.createMessage();
        SOAPPart soapPart = message.getSOAPPart();
        SOAPEnvelope envelope = soapPart.getEnvelope();
        SOAPHeader header = envelope.getHeader();
        header.detachNode();
        SOAPBody body = envelope.getBody();
        body.addTextNode(a);
        URL endpoint = new URL("http://localhost:8080/Target/receiver");
        //log("Bat dau gui");
        response = con.call(message, endpoint);
        //log("Da nhan ve");
        SOAPPart sp = response.getSOAPPart();
        SOAPEnvelope ev = sp.getEnvelope();
        SOAPBody bd = ev.getBody();
        String result = bd.getValue();
        return result;
        }
        catch (Exception e)
        {
            String fail = "Fail to send";
            return  fail;
        }
}
}
</code>```

I called the sender function in a jsp file and passed a String to it.
I had built it with Netbeans and Tomcat server but it just responds with a null message.
How can I fix the problem?

答:
I had fixed the problem by 2 steps:

The SOAP server: In the web.xml file fix the servlet class from com.sun.xml.ws.transport.http.servlet.WSServlet to your own Java class (in my case it is receive.receiver)

Add saaj-impl-1.3.1 library to NetBeans (the library with method com.sun.xml.messaging)

Title: Java SOAP webservice always return null

Body:
I have a simple SOAP webservice server like this:

public class receiver extends JAXMServlet implements ReqRespListener {

    public SOAPMessage onMessage(SOAPMessage soapm) {
        return soapm;
    }
}

In the client I send a message to this server:

public class sender {

    /** This is a sample web service operation */

    SOAPConnectionFactory scfac = null;
    SOAPConnection con =null;
    MessageFactory fac = null;
    SOAPMessage message = null;
    SOAPMessage response = null;
    @WebMethod(operationName = "sender")
    public String sender(@WebParam(name = "a") String a)
    {
        try{
        //Creat Connection
        scfac = SOAPConnectionFactory.newInstance();
        con = scfac.createConnection();
        fac = MessageFactory.newInstance();
        message = fac.createMessage();
        SOAPPart soapPart = message.getSOAPPart();
        SOAPEnvelope envelope = soapPart.getEnvelope();
        SOAPHeader header = envelope.getHeader();
        header.detachNode();
        SOAPBody body = envelope.getBody();
        body.addTextNode(a);
        URL endpoint = new URL("http://localhost:8080/Target/receiver");
        //log("Bat dau gui");
        response = con.call(message, endpoint);
        //log("Da nhan ve");
        SOAPPart sp = response.getSOAPPart();
        SOAPEnvelope ev = sp.getEnvelope();
        SOAPBody bd = ev.getBody();
        String result = bd.getValue();
        return result;
        }
        catch (Exception e)
        {
            String fail = "Fail to send";
            return  fail;
        }
}
}

I called the sender function in a jsp file and passed a String to it.
I had built it with Netbeans and Tomcat server but it just responds with a null message.
How can I fix the problem?


问:
python api automation / getting status code = 500 and {Message ":"An error has occured."}
```<code>import requests
import json
import jsonpath

def test_add_new_data():
    # url = "http://thetestingworldapi.com/api/studentsDetails"
    # f = open('/Users/sunghunkwak/PycharmProjects/apiTesting/postStudent.json', 'r')
    # requests_post_id = json.loads(f.read())
    # result = requests.post(url, requests_post_id)
    # assert result.status_code == 201
    # id = jsonpath.jsonpath(result.json(), 'id')
    # print(id[0])

    url_tech = "http://thetestingworldapi.com/api/technicalskills"
    f = open('/Users/sunghunkwak/PycharmProjects/apiTesting/postTechskills.json', 'r')
    requests_post_tech = json.loads(f.read())
    result = requests.post(url_tech, requests_post_tech)
    assert result.status_code == 200
    print(result.text)

    url_addr = "http://thetestingworldapi.com/api/addresses"
    f = open('/Users/sunghunkwak/PycharmProjects/apiTesting/postAddress.json', 'r')
    requests_post_addr = json.loads(f.read())
    result = requests.post(url_addr, requests_post_addr)
    print(result.status_code)
    # assert result.status_code == 200

    url_final = "http://thetestingworldapi.com/api/FinalStudentDetails/189969"
    requests_get = requests.get(url_final)
    print(requests_get.text)
</code>```

I tried to test, but it keeps getting errors like below.

test.py {"status":"true","msg":"Add  data success"}
500
{"Message":"An error has occurred."}

post address and get final data are getting errors.
How can I solve it??
Thank you.

答:
Are you sure your JSON files are correct that you're trying to post? Here is an example post request:

```<code>import requests

url = 'https://reqres.in/api/users'
payload = {
    "name": "foo",
    "job": "bar"
}

x = requests.post(url, data=payload)

print(x.text)
</code>```

When I tried to change the "URL" the URL to "http://thetestingworldapi.com/api/addresses" also throws the same error {"Message":"An error has occurred."}

Here is an another example I read it from JSON file and requested:

```<code>import requests
import os
import json

url = 'https://reqres.in/api/users'

filename = "foo.json"
folder_ = os.path.dirname(os.path.abspath(__file__))
absolute_filename = os.path.join(folder_, filename)
f = open(absolute_filename, 'r')
payload = json.loads(f.read())
x = requests.post(url, payload)

print(x.text)
</code>```

Looks like you have an error in server side.
Also I suggest you read HTTP response status codes:
https://developer.mozilla.org/en-US/docs/Web/HTTP/Status

Body:
import requests
import json
import jsonpath

def test_add_new_data():
    # url = "http://thetestingworldapi.com/api/studentsDetails"
    # f = open('/Users/sunghunkwak/PycharmProjects/apiTesting/postStudent.json', 'r')
    # requests_post_id = json.loads(f.read())
    # result = requests.post(url, requests_post_id)
    # assert result.status_code == 201
    # id = jsonpath.jsonpath(result.json(), 'id')
    # print(id[0])

    url_tech = "http://thetestingworldapi.com/api/technicalskills"
    f = open('/Users/sunghunkwak/PycharmProjects/apiTesting/postTechskills.json', 'r')
    requests_post_tech = json.loads(f.read())
    result = requests.post(url_tech, requests_post_tech)
    assert result.status_code == 200
    print(result.text)

    url_addr = "http://thetestingworldapi.com/api/addresses"
    f = open('/Users/sunghunkwak/PycharmProjects/apiTesting/postAddress.json', 'r')
    requests_post_addr = json.loads(f.read())
    result = requests.post(url_addr, requests_post_addr)
    print(result.status_code)
    # assert result.status_code == 200

    url_final = "http://thetestingworldapi.com/api/FinalStudentDetails/189969"
    requests_get = requests.get(url_final)
    print(requests_get.text)

I tried to test, but it keeps getting errors like below.

test.py {"status":"true","msg":"Add  data success"}
500
{"Message":"An error has occurred."}

post address and get final data are getting errors.
How can I solve it??
Thank you.

Body:
Are you sure your JSON files are correct that you're trying to post? Here is an example post request:

import requests

url = 'https://reqres.in/api/users'
payload = {
    "name": "foo",
    "job": "bar"
}

x = requests.post(url, data=payload)

print(x.text)

When I tried to change the "URL" the URL to "http://thetestingworldapi.com/api/addresses" also throws the same error {"Message":"An error has occurred."}

Here is an another example I read it from JSON file and requested:

import requests
import os
import json

url = 'https://reqres.in/api/users'

filename = "foo.json"
folder_ = os.path.dirname(os.path.abspath(__file__))
absolute_filename = os.path.join(folder_, filename)
f = open(absolute_filename, 'r')
payload = json.loads(f.read())
x = requests.post(url, payload)

print(x.text)

Looks like you have an error in server side.
Also I suggest you read HTTP response status codes:
https://developer.mozilla.org/en-US/docs/Web/HTTP/Status


问:
sizeof class with int , function, virtual function in C++?
This is an online C++ test question, which has been done.

```<code>#include<iostream>
using namespace std;
class A
{

};
class B
{
int i;
};

class C
{
void foo();
};
class D
{
virtual void foo();
};

class E
{
int i ;
    virtual void foo();
};
class F
{
int i;
    void foo();
};
class G
{
    void foo();
    int i;
    void foo1();
};

class H
{
    int i ;
    virtual void foo();
    virtual void foo1();
};
int main()
{
cout <<"sizeof(class A) : " << sizeof(A) << endl ;
cout <<"sizeof(class B) adding the member int i : " << sizeof(B) << endl ;
cout <<"sizeof(class C) adding the member void foo() : " << sizeof(C) << endl ;
cout <<"sizeof(class D) after making foo virtual : " << sizeof(D) << endl ;
cout <<"sizeof(class E) after adding foo virtual , int : " << sizeof(E) << endl ;
cout <<"sizeof(class F) after adding foo  , int : " << sizeof(F) << endl ;
cout <<"sizeof(class G) after adding foo  , int : " << sizeof(G) << endl ;
G g;
cout <<"sizeof(class G) after adding foo  , int : " << sizeof(g) << endl ;
cout <<"sizeof(class H) after adding int 2 virtual " << sizeof(H) << endl ;
return 0;
}
</code>```

output:

```<code>sizeof(class A) : 1
sizeof(class B) adding the member int i : 4
sizeof(class C) adding the member void foo() : 1
sizeof(class D) after making foo virtual : 8
sizeof(class E) after adding foo virtual , int : 16
sizeof(class F) after adding foo  , int : 4
sizeof(class G) after adding foo   , unsigned int : 4
sizeof(class g) after adding foo  , unsigned int : 4
sizeof(class H) after adding int 2 virtual 16
</code>```

My questions:

Why siszeof(A) is 1 and sizeof(C) is 1 too ?

Why siszeof(H) is 16 but sizeof(G) is 4 ?

Why siszeof(E) is 16 but sizeof(F) is 4 ?

Why siszeof(D) is 8 but sizeof(E) is 16 ?

My guess:

A virtual function is a pointer with 8 bytes.
But, I do not know why E size is 16 ?
Adding a function to an empty class does not change its size ?

Any help is appreciated.

thanks

答:
why not try printing out the layout? From system V abi

dsize(O): the data size of an object, which is the size of O without tail padding.

nvsize(O): the non-virtual size of an object, which is the size of O without virtual bases.

nvalign(O): the non-virtual alignment of an object, which is the alignment of O without virtual bases.

for example (put your code and remember to apply sizeof to the type you want to check)

struct Base1 {
  virtual int method_base_11() {
    return 11;
  }
  virtual ~Base1() = default;
};

struct Base2 {
  virtual int method_base_21() {
    return 22;
  }
  virtual ~Base2() = default;
};

struct Foo: public Base1, public Base2 {
  int a;
};

int main() {
  Foo foo;
  foo.method_base_21();
  return sizeof(Foo);
}
```

<p>output,</p>

<pre class="lang-sh prettyprint-override"><code>$ clang -cc1 -std=c++11 -fdump-record-layouts foo.cc

*** Dumping AST Record Layout
         0 | struct Base1
         0 |   (Base1 vtable pointer)
           | [sizeof=8, dsize=8, align=8,
           |  nvsize=8, nvalign=8]

*** Dumping AST Record Layout
         0 | struct Base2
         0 |   (Base2 vtable pointer)
           | [sizeof=8, dsize=8, align=8,
           |  nvsize=8, nvalign=8]

*** Dumping AST Record Layout
         0 | struct Foo
         0 |   struct Base1 (primary base)
         0 |     (Base1 vtable pointer)
         8 |   struct Base2 (base)
         8 |     (Base2 vtable pointer)
        16 |   int a
           | [sizeof=24, dsize=20, align=8,
           |  nvsize=20, nvalign=8]

</code>```

Body:
This is an online C++ test question, which has been done.

#include<iostream>
using namespace std;
class A
{

};
class B
{
int i;
};

class C
{
void foo();
};
class D
{
virtual void foo();
};

class E
{
int i ;
    virtual void foo();
};
class F
{
int i;
    void foo();
};
class G
{
    void foo();
    int i;
    void foo1();
};

class H
{
    int i ;
    virtual void foo();
    virtual void foo1();
};
int main()
{
cout <<"sizeof(class A) : " << sizeof(A) << endl ;
cout <<"sizeof(class B) adding the member int i : " << sizeof(B) << endl ;
cout <<"sizeof(class C) adding the member void foo() : " << sizeof(C) << endl ;
cout <<"sizeof(class D) after making foo virtual : " << sizeof(D) << endl ;
cout <<"sizeof(class E) after adding foo virtual , int : " << sizeof(E) << endl ;
cout <<"sizeof(class F) after adding foo  , int : " << sizeof(F) << endl ;
cout <<"sizeof(class G) after adding foo  , int : " << sizeof(G) << endl ;
G g;
cout <<"sizeof(class G) after adding foo  , int : " << sizeof(g) << endl ;
cout <<"sizeof(class H) after adding int 2 virtual " << sizeof(H) << endl ;
return 0;
}

output:

sizeof(class A) : 1
sizeof(class B) adding the member int i : 4
sizeof(class C) adding the member void foo() : 1
sizeof(class D) after making foo virtual : 8
sizeof(class E) after adding foo virtual , int : 16
sizeof(class F) after adding foo  , int : 4
sizeof(class G) after adding foo   , unsigned int : 4
sizeof(class g) after adding foo  , unsigned int : 4
sizeof(class H) after adding int 2 virtual 16

My questions:

Why siszeof(A) is 1 and sizeof(C) is 1 too ?

Why siszeof(H) is 16 but sizeof(G) is 4 ?

Why siszeof(E) is 16 but sizeof(F) is 4 ?

Why siszeof(D) is 8 but sizeof(E) is 16 ?

My guess:

A virtual function is a pointer with 8 bytes.
But, I do not know why E size is 16 ?
Adding a function to an empty class does not change its size ?

Any help is appreciated.

thanks

Body:
why not try printing out the layout? From system V abi

dsize(O): the data size of an object, which is the size of O without tail padding.

nvsize(O): the non-virtual size of an object, which is the size of O without virtual bases.

nvalign(O): the non-virtual alignment of an object, which is the alignment of O without virtual bases.

for example (put your code and remember to apply sizeof to the type you want to check)

struct Base1 {
  virtual int method_base_11() {
    return 11;
  }
  virtual ~Base1() = default;
};

struct Base2 {
  virtual int method_base_21() {
    return 22;
  }
  virtual ~Base2() = default;
};

struct Foo: public Base1, public Base2 {
  int a;
};

int main() {
  Foo foo;
  foo.method_base_21();
  return sizeof(Foo);
}

output,

$ clang -cc1 -std=c++11 -fdump-record-layouts foo.cc

*** Dumping AST Record Layout
         0 | struct Base1
         0 |   (Base1 vtable pointer)
           | [sizeof=8, dsize=8, align=8,
           |  nvsize=8, nvalign=8]

*** Dumping AST Record Layout
         0 | struct Base2
         0 |   (Base2 vtable pointer)
           | [sizeof=8, dsize=8, align=8,
           |  nvsize=8, nvalign=8]

*** Dumping AST Record Layout
         0 | struct Foo
         0 |   struct Base1 (primary base)
         0 |     (Base1 vtable pointer)
         8 |   struct Base2 (base)
         8 |     (Base2 vtable pointer)
        16 |   int a
           | [sizeof=24, dsize=20, align=8,
           |  nvsize=20, nvalign=8]


问:
Xamarin.Forms default DatePicker value?
How can I set a default or starting value for a Xamarin.Forms DatePicker?

At the moment, it begins on January 1st, 1900. This isn't a very useful date, and worse, a user has to scroll needlessly to get the right year, then the right month.

I'd like the default date to be the current date. I know how to get the current date, and I can set MinimumDate attribute of the DatePicker tag in the .xaml. This will make the current date the start date of the picker, but then I can't go back to a previous year or month.

Thanks,

答:
2020 update: the default value is now the current date. If you want to change it to a different value you can do it in the xaml by using the Date attribute, as noted by Giancarlo. You can pass in a string like this:</p>

```<code><DatePicker Date="06/13/2000"/>
</code>```

Title: Xamarin.Forms default DatePicker value?

Body:
2020 update: the default value is now the current date. If you want to change it to a different value you can do it in the xaml by using the Date attribute, as noted by Giancarlo. You can pass in a string like this:

<DatePicker Date="06/13/2000"/>


问:
Get last execution time of script python
Im writting a script in Python that takes as an input a timestamp. For the first execution, it should be something as the now() function. However, for further executions, the input parameter should be the last execution time of the same script. This is being done to avoid getting duplicates results.

Can anyone give me a clue please?

答:
As far as I know, there is no "last executed" attribute for files. Some operating systems have a "last accessed" attribute, but even if that's updated on execution, it would also be updated any time the file was read, which is probably not what you want.

If you need to be able to store information between runs, you'll need to save that data somewhere. You could write it to a file, save it to a database, or write it to a caching service, such as memcached.