问:
Laravel OBSERVER update process
In SESSObServer

public function updated(SESS $sESS)
{
    log::info("data updated");
    if ($sESS->wasChanged('is_active')) {
        log::info("data updated");
    }
}
```
<p>IN Observer, created(SESS $sESS) function run but update is not run. How can i solve problem ?</p>
<p>I changed my query. Now, this is run.
I didn't use get. I used first()</p>
``` $sess = SESS::where('sess_id', request('id'))->first();
        $sess->save();
```

答:
Make sure your Observer is registered.

# app/Providers/EventServiceProvider.php
use App\Models\SESS;
use App\Observers\SESSObserver;

class EventServiceProvider extends ServiceProvider
{
    public function boot()
    {
        SESS::observe(SESSObServer::class);
    }
}
```
<ol start="2">
<li>Make sure you're using the correct classes. The logger's class is <code>Log</code> (capital <code>L</code>)</li>
</ol>
<pre class="lang-php prettyprint-override"><code>public function updated(SESS $sESS)
{
    Log::info("data updated");
    if ($sESS->wasChanged('is_active')) {
        Log::info("data updated");
    }
}
</code>```

Alternatively, I think you can still use info().

public function updated(SESS $sESS)
{
    info("data updated");
    if ($sESS->wasChanged('is_active')) {
        info("data updated");
    }
}
```

If you're using apache, make sure the apache user can write to the log file.

Title: Laravel OBSERVER update process

Body:
In SESSObServer

public function updated(SESS $sESS)
{
    log::info("data updated");
    if ($sESS->wasChanged('is_active')) {
        log::info("data updated");
    }
}

IN Observer, created(SESS $sESS) function run but update is not run. How can i solve problem ?

I changed my query. Now, this is run.
I didn't use get. I used first()

 $sess = SESS::where('sess_id', request('id'))->first();
        $sess->save();

Body:
Make sure your Observer is registered.

# app/Providers/EventServiceProvider.php
use App\Models\SESS;
use App\Observers\SESSObserver;

class EventServiceProvider extends ServiceProvider
{
    public function boot()
    {
        SESS::observe(SESSObServer::class);
    }
}

Make sure you're using the correct classes. The logger's class is Log (capital L)

public function updated(SESS $sESS)
{
    Log::info("data updated");
    if ($sESS->wasChanged('is_active')) {
        Log::info("data updated");
    }
}

Alternatively, I think you can still use info().

public function updated(SESS $sESS)
{
    info("data updated");
    if ($sESS->wasChanged('is_active')) {
        info("data updated");
    }
}

If you're using apache, make sure the apache user can write to the log file.


来源: stackexchange

问:
Checkout several branches from Git
I want to clone some Git repository on local machine, and create 3 folders:

master - for master branch of the project

tag777 - for the specific    tag of the project

commit888 - for the specific commit from master    branch

I want these 3 folders with the specific versions of the project to reside on local machine simultaneously.

So the question is - do I have to clone git repo 3 times or it is sufficient to clone it only once and create these 3 folders after cloning?
What commands do I have to run?

For now I want only to "download" these 3 version of the project and don't want to modify or commit anything.

答:
Usually, people would clone once and then switch to a specific tag or specific commit whenever needed

In your case the steps would be

```<code>git clone <URL>/your-repo.git
</code>```

The content of the directory your-repo would then contain the content of master (by default). To be sure, you can specify the branch when cloning using the --branch option

```<code>cd your-repo
git checkout tag777
</code>```

The content of the directory your-repo would then corresponds to the content associated with tag777

Then if you do

```<code>git checkout commit888
</code>```

The content of the directory your-repo would then corresponds to the content associated with commit888

If for some reasons, you really want to have three separate folders, you would then

```<code>git clone --branch master <URL>/your-repo.git  your-repo-master
git clone --branch tag777 <URL>/your-repo.git  your-repo-tag777
git clone  <URL>/your-repo.git  your-repo-commit888; cd your-repo-commit888; git checkout commit888
</code>```

In that example, you end up with 3 folders your-repo-master, your-repo-tag777, your-repo-commit888 containing what you were looking for. The --branch option can be used with a branch name but also with a tag-name.

ContentLicense: CC BY-SA 4.0

Title: Checkout several branches from Git

Body:
Usually, people would clone once and then switch to a specific tag or specific commit whenever needed

In your case the steps would be

git clone <URL>/your-repo.git

The content of the directory your-repo would then contain the content of master (by default). To be sure, you can specify the branch when cloning using the --branch option

cd your-repo
git checkout tag777

The content of the directory your-repo would then corresponds to the content associated with tag777

Then if you do

git checkout commit888

The content of the directory your-repo would then corresponds to the content associated with commit888

If for some reasons, you really want to have three separate folders, you would then

git clone --branch master <URL>/your-repo.git  your-repo-master
git clone --branch tag777 <URL>/your-repo.git  your-repo-tag777
git clone  <URL>/your-repo.git  your-repo-commit888; cd your-repo-commit888; git checkout commit888

In that example, you end up with 3 folders your-repo-master, your-repo-tag777, your-repo-commit888 containing what you were looking for. The --branch option can be used with a branch name but also with a tag-name.


问:
Infinite loop when using onAppear in SwiftUI
I have a strange infinite loop when using onAppear and I cannot identify the root of the problem. It only happens when the view is the detail view of a navigation view, but it works fine when it's the root view.
Another interesting thing is that if I wrap the detail view in a NavigationView (so, now we have a navigation view inside a navigation view), then the issue does not appear anymore. Is this a bug in SwiftUI? Is conceptually my design OK? I mean, using onAppear like viewDidLoad to trigger the initial sequence.
Thanks for suggestions.

Here is the source code.
ContentView.swift:

```<code>import SwiftUI

struct ContentView: View {

    @StateObject var viewModel = ContentViewModel()

    var body: some View {
        NavigationView {
            VStack {
                Group {
                    switch viewModel.state {
                    case .loading:
                        Text("Loading...")
                    case .loaded:
                        HStack {
                            Text("Loaded")
                            Button("Retry") {
                                viewModel.fetchData()
                            }
                        }
                    }
                }
                .padding(.bottom, 20)
                NavigationLink("Go to detail screen", destination: DetailView())
            }
        }
        .onAppear() {
            viewModel.fetchData()
        }
    }
}

class ContentViewModel: ObservableObject  {

    enum State {
        case loading
        case loaded
    }

    @Published var state: State = .loading

    func fetchData() {
        state = .loading
        DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
            self.state = .loaded
        }
    }
}
</code>```

And here the code of the detail view:

```<code>import SwiftUI

struct DetailView: View {

    @StateObject var viewModel = DetailViewModel()

    var body: some View {
        Group {
            switch viewModel.state {
            case .loading:
                Text("Loading...")
            case .loaded:
                HStack {
                    Text("Loaded")
                    Button("Retry") {
                        viewModel.fetchData()
                    }
                }
            }
        }
        .onAppear() {
            print("infinite loop here")
            viewModel.fetchData()
        }
    }
}

class DetailViewModel: ObservableObject  {

    enum State {
        case loading
        case loaded
    }

    @Published var state: State = .loading

    func fetchData() {
        state = .loading
        DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
            self.state = .loaded
        }
    }
}
</code>```

Here I attach the project:
https://www.dropbox.com/s/5alokj3q81jbpj7/TestBug.zip?dl=0

I'm using Xcode Version 12.5.1 (12E507) and iOS 14.5

Thanks a lot.

答:
I saw something similar with iOS 15 and moving all the onAppear stuff to an initializer fixed things.
No more infinite looping trying to make the dialog appear. Weirdly this only happens with the settings in a certain state.

In onAppear I had code like:

```<code>useSecondary = data.settings.showSecondaryAxis
...
</code>```

But in the init function needs this to do the job:

```<code>   init(data: Binding<PlotData> {
      self._data = data
      _useSecondary = State(initialValue: data.wrappedValue.settings.showSecondaryAxis)
...
</code>```

}

…
Cumbersome but it works.

Body:
I have a strange infinite loop when using onAppear and I cannot identify the root of the problem. It only happens when the view is the detail view of a navigation view, but it works fine when it's the root view.
Another interesting thing is that if I wrap the detail view in a NavigationView (so, now we have a navigation view inside a navigation view), then the issue does not appear anymore. Is this a bug in SwiftUI? Is conceptually my design OK? I mean, using onAppear like viewDidLoad to trigger the initial sequence.
Thanks for suggestions.

Here is the source code.
ContentView.swift:

import SwiftUI

struct ContentView: View {

    @StateObject var viewModel = ContentViewModel()

    var body: some View {
        NavigationView {
            VStack {
                Group {
                    switch viewModel.state {
                    case .loading:
                        Text("Loading...")
                    case .loaded:
                        HStack {
                            Text("Loaded")
                            Button("Retry") {
                                viewModel.fetchData()
                            }
                        }
                    }
                }
                .padding(.bottom, 20)
                NavigationLink("Go to detail screen", destination: DetailView())
            }
        }
        .onAppear() {
            viewModel.fetchData()
        }
    }
}

class ContentViewModel: ObservableObject  {

    enum State {
        case loading
        case loaded
    }

    @Published var state: State = .loading

    func fetchData() {
        state = .loading
        DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
            self.state = .loaded
        }
    }
}

And here the code of the detail view:

import SwiftUI

struct DetailView: View {

    @StateObject var viewModel = DetailViewModel()

    var body: some View {
        Group {
            switch viewModel.state {
            case .loading:
                Text("Loading...")
            case .loaded:
                HStack {
                    Text("Loaded")
                    Button("Retry") {
                        viewModel.fetchData()
                    }
                }
            }
        }
        .onAppear() {
            print("infinite loop here")
            viewModel.fetchData()
        }
    }
}

class DetailViewModel: ObservableObject  {

    enum State {
        case loading
        case loaded
    }

    @Published var state: State = .loading

    func fetchData() {
        state = .loading
        DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
            self.state = .loaded
        }
    }
}

Here I attach the project:
https://www.dropbox.com/s/5alokj3q81jbpj7/TestBug.zip?dl=0

I'm using Xcode Version 12.5.1 (12E507) and iOS 14.5

Thanks a lot.

Body:
I saw something similar with iOS 15 and moving all the onAppear stuff to an initializer fixed things.
No more infinite looping trying to make the dialog appear. Weirdly this only happens with the settings in a certain state.

In onAppear I had code like:

useSecondary = data.settings.showSecondaryAxis
...

But in the init function needs this to do the job:

   init(data: Binding<PlotData> {
      self._data = data
      _useSecondary = State(initialValue: data.wrappedValue.settings.showSecondaryAxis)
...

}

…
Cumbersome but it works.


问:
Why have Origin and Referer headers when Referer has enough information?
If the Referer header has the Origin in it anyway, what is the point of having both?

If the server receiving an HTTP request wants to know the Origin, it can just look at the domain in the Referer header.

I understand that the Referer header is not sent if it's an HTTPS to HTTP request (and many other scenarios), but why didn't they design it so that instead of removing it, it was still sent, but it only had the domain name (what the Origin header would have)?

答:
Citing from here https://security.stackexchange.com/questions/158045/is-checking-the-referer-and-origin-headers-enough-to-prevent-csrf-provided-that

In order to preserve privacy, any browser request can decide to omit
the Referer header. So it is probably best to only check the Origin
header. (In case you want to allow for users to preserve their
privacy)

The Origin header is null in some cases. Note that all of these
requests are GET requests, which means they should not have any side
effects.


问:
CNN data doesn't fit in memory (kernel dies)
I am working on this dataset (the image part), normalized to 1103 images of size 1396 x 1676.
I am trying to feed it to a CNN (taken from here) of this shape:

```<code>n, w, h = X_train.shape # which is (n, 1396, 1676)
cnn = Sequential()
cnn.add(Conv2D(32, (3, 3), activation="relu", input_shape=(w, h, 1)))
cnn.add(MaxPooling2D(pool_size = (2, 2)))
cnn.add(Conv2D(32, (3, 3), activation="relu", input_shape=(w, h, 1)))
cnn.add(MaxPooling2D(pool_size = (2, 2)))
cnn.add(Conv2D(32, (3, 3), activation="relu", input_shape=(w, h, 1)))
cnn.add(MaxPooling2D(pool_size = (2, 2)))
cnn.add(Conv2D(64, (3, 3), activation="relu", input_shape=(w, h, 1)))
cnn.add(MaxPooling2D(pool_size = (2, 2)))
cnn.add(Conv2D(64, (3, 3), activation="relu", input_shape=(w, h, 1)))
cnn.add(MaxPooling2D(pool_size = (2, 2)))
cnn.add(Flatten())
cnn.add(Dense(activation = 'relu', units = 128))
cnn.add(Dense(activation = 'relu', units = 64))
cnn.add(Dense(activation = 'sigmoid', units = 1))
cnn.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])

early = EarlyStopping(monitor="val_loss", mode="min", patience=3)
learning_rate_reduction = ReduceLROnPlateau(monitor='val_loss', patience=2, verbose=1,factor=0.3, min_lr=0.000001)
callbacks_list = [early, learning_rate_reduction]

cnn.fit(X_train, Y_train, epochs=25, validation_split=0.7, callbacks=callbacks_list)
</code>```

Both in Google Colab and on a Jupyter in my 16Gb machine, it produces a kernel death. I tried to use a generator to feed just 10 images at a time, but it doesn't produce any good result (0.5 accuracy).

Could you suggest a way to solve this? Maybe tweaking some parameters too

答: Depending on what you are trying to train on (not considering the data and goal). Your first start is to not use big resolution of the images. Just start small (256x256 or 512x512). All you need to do is to resize the images first (use opencv to resize) Then train the model on that. It will surely give you (and the hardware) some breathing room.

Body:
I am working on this dataset (the image part), normalized to 1103 images of size 1396 x 1676.
I am trying to feed it to a CNN (taken from here) of this shape:

n, w, h = X_train.shape # which is (n, 1396, 1676)
cnn = Sequential()
cnn.add(Conv2D(32, (3, 3), activation="relu", input_shape=(w, h, 1)))
cnn.add(MaxPooling2D(pool_size = (2, 2)))
cnn.add(Conv2D(32, (3, 3), activation="relu", input_shape=(w, h, 1)))
cnn.add(MaxPooling2D(pool_size = (2, 2)))
cnn.add(Conv2D(32, (3, 3), activation="relu", input_shape=(w, h, 1)))
cnn.add(MaxPooling2D(pool_size = (2, 2)))
cnn.add(Conv2D(64, (3, 3), activation="relu", input_shape=(w, h, 1)))
cnn.add(MaxPooling2D(pool_size = (2, 2)))
cnn.add(Conv2D(64, (3, 3), activation="relu", input_shape=(w, h, 1)))
cnn.add(MaxPooling2D(pool_size = (2, 2)))
cnn.add(Flatten())
cnn.add(Dense(activation = 'relu', units = 128))
cnn.add(Dense(activation = 'relu', units = 64))
cnn.add(Dense(activation = 'sigmoid', units = 1))
cnn.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])

early = EarlyStopping(monitor="val_loss", mode="min", patience=3)
learning_rate_reduction = ReduceLROnPlateau(monitor='val_loss', patience=2, verbose=1,factor=0.3, min_lr=0.000001)
callbacks_list = [early, learning_rate_reduction]

cnn.fit(X_train, Y_train, epochs=25, validation_split=0.7, callbacks=callbacks_list)

Both in Google Colab and on a Jupyter in my 16Gb machine, it produces a kernel death. I tried to use a generator to feed just 10 images at a time, but it doesn't produce any good result (0.5 accuracy).

Could you suggest a way to solve this? Maybe tweaking some parameters too


问:
Precedence of function application
In order to illustrate function application has the highest precedence in Haskell the following example was provided (by schoolofhaskell):

```<code>sq b = b * b
main = print $
-- show
    sq 3+1
-- /show
</code>```

The result here is 10.

What puzzles me is that the argument constitutes a function application too. Consider the operator + being a short-cut of a function. So when the argument is taken, I would expect that its function application now takes precedence over the original one.

Written that way it delivers the expected result:

```<code>sq b = b * b
main = print $
    sq ((+) 3 1 )
</code>```

Any explanation?

答:
What puzzles me is that the argument constitutes a function application too. Consider the operator "+" being a short-cut of a function.

I think this is the heart of the misunderstanding (actually, very good understanding!) involved here. It is true that 3 + 1 is an expression denoting the application of the (+) function to 3 and 1, you have understood that correctly. However, Haskell has two kinds of function application syntax, prefix and infix. So the more precise version of "function application has the highest precedence" would be something like "syntactically prefix function application has higher precedence than any syntactically infix function application".

You can also convert back and forth between the two forms. Each function has a "natural" position: names with only symbols are naturally syntactically infix and names with letters and numbers and the like are naturally syntactically prefix. You can turn a naturally prefix function to infix with backticks, and a naturally infix function to prefix with parentheses. So, if we define

```<code>plus = (+)
</code>```

then all of the following really mean the same thing:

```<code>3 + 1
3 `plus` 1
(+) 3 1
plus 3 1
</code>```

Returning to your example:

```<code>sq 3+1
</code>```

Because sq is naturally prefix, and + is naturally infix, the sq application takes precedence.

Title: Precedence of function application

Body:
In order to illustrate function application has the highest precedence in Haskell the following example was provided (by schoolofhaskell):

sq b = b * b
main = print $
-- show
    sq 3+1
-- /show

The result here is 10.

What puzzles me is that the argument constitutes a function application too. Consider the operator + being a short-cut of a function. So when the argument is taken, I would expect that its function application now takes precedence over the original one.

Written that way it delivers the expected result:

sq b = b * b
main = print $
    sq ((+) 3 1 )

Any explanation?

Body:
What puzzles me is that the argument constitutes a function application too. Consider the operator "+" being a short-cut of a function.

I think this is the heart of the misunderstanding (actually, very good understanding!) involved here. It is true that 3 + 1 is an expression denoting the application of the (+) function to 3 and 1, you have understood that correctly. However, Haskell has two kinds of function application syntax, prefix and infix. So the more precise version of "function application has the highest precedence" would be something like "syntactically prefix function application has higher precedence than any syntactically infix function application".

You can also convert back and forth between the two forms. Each function has a "natural" position: names with only symbols are naturally syntactically infix and names with letters and numbers and the like are naturally syntactically prefix. You can turn a naturally prefix function to infix with backticks, and a naturally infix function to prefix with parentheses. So, if we define

plus = (+)

then all of the following really mean the same thing:

3 + 1
3 `plus` 1
(+) 3 1
plus 3 1

Returning to your example:

sq 3+1

Because sq is naturally prefix, and + is naturally infix, the sq application takes precedence.


问:
How to POST binary data (octet-stream) with swagger-client
I cannot find a resource to learn how to use this thing to send binary data. The following fails with status 415.

const fs = require('fs');
const SwaggerParser = require('swagger-parser');
const Swagger = require('swagger-client');

async function getClient() {
    let spec = await SwaggerParser.dereference('path/to/openapi.yaml')
    spec.servers = [{url: 'http://localhost:8080'}];
    return (await Swagger({spec})).apis.default;
}

(async function() {
    let client = getClient(); // client
    let data = fs.readFileSync('path/to/file.txt'); // buffer
    let response = client.createWithBinary(data) // <-- this is how we usually set req params and it fails
})();
```
<p>The contract is open api 3 and expects an octet-stream in the request body:</p>
<pre class="lang-yaml prettyprint-override"><code>...
paths:
  /binary:
    post:
      operationId: createWithBinary
      description: Create a resource by uploading binary data
      requestBody:
        required: true
        content:
          application/octet-stream:
            schema:
              type: string
              format: binary
    responses:
      200:
        description: ...
</code>```

The server works as expected with swagger-ui so the problem is not there.
Any help/resource would be greatly appreciated.

答:
After digging around in the swagger-js github issues, I've discovered that another input is needed in this case:

let response = client.createWithBinary({/* params */}, {requestBody: data});
```

Request params go inside the first arg; octet-stream goes in the second with a requestBody key.

Body:
I cannot find a resource to learn how to use this thing to send binary data. The following fails with status 415.

const fs = require('fs');
const SwaggerParser = require('swagger-parser');
const Swagger = require('swagger-client');

async function getClient() {
    let spec = await SwaggerParser.dereference('path/to/openapi.yaml')
    spec.servers = [{url: 'http://localhost:8080'}];
    return (await Swagger({spec})).apis.default;
}

(async function() {
    let client = getClient(); // client
    let data = fs.readFileSync('path/to/file.txt'); // buffer
    let response = client.createWithBinary(data) // <-- this is how we usually set req params and it fails
})();

The contract is open api 3 and expects an octet-stream in the request body:

...
paths:
  /binary:
    post:
      operationId: createWithBinary
      description: Create a resource by uploading binary data
      requestBody:
        required: true
        content:
          application/octet-stream:
            schema:
              type: string
              format: binary
    responses:
      200:
        description: ...

The server works as expected with swagger-ui so the problem is not there.
Any help/resource would be greatly appreciated.

Body:
After digging around in the swagger-js github issues, I've discovered that another input is needed in this case:

let response = client.createWithBinary({/* params */}, {requestBody: data});

Request params go inside the first arg; octet-stream goes in the second with a requestBody key.


问:
How can I identify these data types
I am trying to get the data type for a dataset in Postgres. What data type is:

country name, eg. Nigeria, Finland, etc.

decimals, eg. 7.3, 9.4, etc

whole numbers, eg. 2341, 8892, etc.

答:
Country name will be varchar(n) or char(n).

Decimals will be float(n).

Whole numbers will be int or one of its variations.

You need to define the maximum size of your data: how many characters are needed for the longest names? What are the biggest numbers that could need to be stored?

Title: How can I identify these data types


问:
How to get file names using FatFs?
I did not the understand how to get file names in SD card using FATFS. I am able to read and write .txt files with this code below:

```<code>if (f_mount(&fatfs, SDPath, 1) == FR_OK) {
    /* Write Test */
    res = f_open(&file, (const TCHAR*)"TESTTEST.TXT", FA_WRITE | FA_CREATE_ALWAYS);
    res = f_write(&file, txtWriteBuf, strlen((const char*)txtWriteBuf), &bytesW);
    res = f_close(&file);
    /* Read Test */
    res = f_open(&file, (const TCHAR*)"TESTTEST.TXT", FA_READ);
    res = f_read(&file, txtReadBuf, f_size(&file), &bytesR);
    res = f_close(&file);

    /* File Listing Code */
    ???

    /* LCD Display Code */
    ...
    /* My LCD Codes Here */
}
</code>```

After that I want to list these file names on my LCD screen. I am stuck at getting files names in root directory. I want these files to be listed on my LCD. And I have no idea about how to use f_opendir(...), f_readdir(...) etc. How to do it in correct way?

答:
First define DIR and FILINFO structures:

```<code>DIR dir;                    // Directory
FILINFO fno;                // File Info
</code>```

Then you can use the following code as sample:

```<code>f_opendir(&dir, "/");   // Open Root
do
{
    f_readdir(&dir, &fno);
    if(fno.fname[0] != 0)
        printf("File found: %s\n", fno.fname); // Print File Name
} while(fno.fname[0] != 0);

f_closedir(&dir);
</code>```

Also you can add error checks to be consistent, I use my own assert therefore omitted.

For Long File Name _USE_LFN in ffconf.h has to be set to 1. Also you need to declare buffer e.g. TCHAR lfname[_MAX_LFN];.
Afterwards assign the buffer and its size in your code:

```<code>fno.lfname = lfname;
fno.lfsize = _MAX_LFN - 1;
</code>```

Finaly you can replace fname with lfname in the code provided above.

Title: How to get file names using FatFs?

Body:
I did not the understand how to get file names in SD card using FATFS. I am able to read and write .txt files with this code below:

if (f_mount(&fatfs, SDPath, 1) == FR_OK) {
    /* Write Test */
    res = f_open(&file, (const TCHAR*)"TESTTEST.TXT", FA_WRITE | FA_CREATE_ALWAYS);
    res = f_write(&file, txtWriteBuf, strlen((const char*)txtWriteBuf), &bytesW);
    res = f_close(&file);
    /* Read Test */
    res = f_open(&file, (const TCHAR*)"TESTTEST.TXT", FA_READ);
    res = f_read(&file, txtReadBuf, f_size(&file), &bytesR);
    res = f_close(&file);

    /* File Listing Code */
    ???

    /* LCD Display Code */
    ...
    /* My LCD Codes Here */
}

After that I want to list these file names on my LCD screen. I am stuck at getting files names in root directory. I want these files to be listed on my LCD. And I have no idea about how to use f_opendir(...), f_readdir(...) etc. How to do it in correct way?

Body:
First define DIR and FILINFO structures:

DIR dir;                    // Directory
FILINFO fno;                // File Info

Then you can use the following code as sample:

f_opendir(&dir, "/");   // Open Root
do
{
    f_readdir(&dir, &fno);
    if(fno.fname[0] != 0)
        printf("File found: %s\n", fno.fname); // Print File Name
} while(fno.fname[0] != 0);

f_closedir(&dir);

Also you can add error checks to be consistent, I use my own assert therefore omitted.

For Long File Name _USE_LFN in ffconf.h has to be set to 1. Also you need to declare buffer e.g. TCHAR lfname[_MAX_LFN];.
Afterwards assign the buffer and its size in your code:

fno.lfname = lfname;
fno.lfsize = _MAX_LFN - 1;

Finaly you can replace fname with lfname in the code provided above.


问:
PAssert not executing and test always passing in unbounded source
I a writing simple test case to check generate Sequence is emitting elements as per duration.
Source code

```<code> pipeline.apply("Source", buildSource(options))
        .apply("Windowing", defineWindow(options))
       .apply("processingState", ParDo.of(new JdbcIoPreProcessing(duration)))

 protected PTransform<? super PBegin, PCollection<Long>> buildSource(PipelineDefaultOptions pipelineDefaultOptions) {
        return GenerateSequence.from(0).withRate(1, Duration.standardSeconds(options.getPollingDuration()));
    }
protected Window<Long> defineWindow(PipelineDefaultOptions pipelineDefaultOptions) {
        OrdersPipelineOptions options = (OrdersPipelineOptions) pipelineDefaultOptions;
        return Window.into(FixedWindows.of(Duration.standardSeconds(options.getPollingDuration())));
    }
</code>```

TestCase

```<code> Pipeline pipeline = TestPipeline.create()
                .enableAbandonedNodeEnforcement(false);
 pipeline.getOptions().as(DirectOptions.class).setBlockOnRun(false);
 PCollection<Long> actual = pipeline.apply(application.buildSource(options));
 PAssert.that(actual).containsInAnyOrder(10l)
 PipelineResult result = pipeline.run();
        PipelineResult.State state = result.waitUntilFinish(Duration.standardSeconds(10));
        result.cancel();
</code>```

Is this PAssert correct, or how to put PAssert in this scenario. I see in the docs, window has to be provided.

I tried interval window, bounded window
IntervalWindow windowFirstEvent = new IntervalWindow(baseTime.plus(Duration.standardSeconds(0)),
baseTime.plus(Duration.standardSeconds(options.getPollingDuration())));

```<code>BoundedWindow window = new BoundedWindow() {
    @Override
    public Instant maxTimestamp() {
        return baseTime.plus(Duration.standardSeconds(100));
    }
};
</code>```

PAssert.that(actual).inWindow(windowFirstEvent).containsInAnyOrder(10l)
but getting casting exception
cannot be cast to org.apache.beam.sdk.transforms.windowing.GlobalWindow
thanks in advance.

答:
you should use the TestStream when testing streaming pipelines. The TestStream is an invaluable streaming source that allows you to mock out both wall-time clock and watermark advancements. See this blog post and the documentation.

For your case, (this solution is not tested, feel free to edit afterwards), it can look something like this:

```<code>
TestStream<int> buildSource(PipelineOptions options) {
  TestStream.Builder<int> testStreamBuilder = new TestStream.create<>();
  for (int i = 0; i < MAX_TIME; ++i) {
    testStreamBuilder
      .addElements(i)
      .advanceProcessingTime(
          Duration.standardSeconds(options.getPollingDuration()));
  }

  return testStreamBuilder.advanceWatermarkToInfinity();
}

 pipeline.apply("Source", buildSource(options))
         .apply("Windowing", defineWindow(options))
         .apply("processingState", ParDo.of(new JdbcIoPreProcessing(duration)))

</code>```

Body:
I a writing simple test case to check generate Sequence is emitting elements as per duration.
Source code

 pipeline.apply("Source", buildSource(options))
        .apply("Windowing", defineWindow(options))
       .apply("processingState", ParDo.of(new JdbcIoPreProcessing(duration)))

 protected PTransform<? super PBegin, PCollection<Long>> buildSource(PipelineDefaultOptions pipelineDefaultOptions) {
        return GenerateSequence.from(0).withRate(1, Duration.standardSeconds(options.getPollingDuration()));
    }
protected Window<Long> defineWindow(PipelineDefaultOptions pipelineDefaultOptions) {
        OrdersPipelineOptions options = (OrdersPipelineOptions) pipelineDefaultOptions;
        return Window.into(FixedWindows.of(Duration.standardSeconds(options.getPollingDuration())));
    }

TestCase

 Pipeline pipeline = TestPipeline.create()
                .enableAbandonedNodeEnforcement(false);
 pipeline.getOptions().as(DirectOptions.class).setBlockOnRun(false);
 PCollection<Long> actual = pipeline.apply(application.buildSource(options));
 PAssert.that(actual).containsInAnyOrder(10l)
 PipelineResult result = pipeline.run();
        PipelineResult.State state = result.waitUntilFinish(Duration.standardSeconds(10));
        result.cancel();

Is this PAssert correct, or how to put PAssert in this scenario. I see in the docs, window has to be provided.

I tried interval window, bounded window
IntervalWindow windowFirstEvent = new IntervalWindow(baseTime.plus(Duration.standardSeconds(0)),
baseTime.plus(Duration.standardSeconds(options.getPollingDuration())));

BoundedWindow window = new BoundedWindow() {
    @Override
    public Instant maxTimestamp() {
        return baseTime.plus(Duration.standardSeconds(100));
    }
};

PAssert.that(actual).inWindow(windowFirstEvent).containsInAnyOrder(10l)
but getting casting exception
cannot be cast to org.apache.beam.sdk.transforms.windowing.GlobalWindow
thanks in advance.

Body:
you should use the TestStream when testing streaming pipelines. The TestStream is an invaluable streaming source that allows you to mock out both wall-time clock and watermark advancements. See this blog post and the documentation.

For your case, (this solution is not tested, feel free to edit afterwards), it can look something like this:

TestStream<int> buildSource(PipelineOptions options) {
  TestStream.Builder<int> testStreamBuilder = new TestStream.create<>();
  for (int i = 0; i < MAX_TIME; ++i) {
    testStreamBuilder
      .addElements(i)
      .advanceProcessingTime(
          Duration.standardSeconds(options.getPollingDuration()));
  }

  return testStreamBuilder.advanceWatermarkToInfinity();
}

 pipeline.apply("Source", buildSource(options))
         .apply("Windowing", defineWindow(options))
         .apply("processingState", ParDo.of(new JdbcIoPreProcessing(duration)))


问:
Div not hiding because of -web-kit effects
I am trying to hide some specific DIVS when the page is not viewed on a standalone Safari browser on an iPad via

```<code>$(function(){

            var mainNav = $( "#mainNav" );
            var body = $( document.body );

            if (
                ("standalone" in window.navigator) &&
                !window.navigator.standalone
                ){

                mainNav.hide();
            }
});
</code>```

and it works with every DIV except with a particular DIV that will not disappear, no matter what.

This DIV, let's call it "Buttons" I can see it briefly before it hides. The peculiarity of this DIV is that it has a background color, and when there is Text inside it, the background color appears briefly. If there is an image inside it or if there is no background color, then the DIV disappears completely as it should. But if I have background color AND text then it shows for a brief moment.

Any ideas why this is?

答:
Haven't stumbled upon this problem before, but from what you're saying you could do an ugly work around (if you need it fixed asap).

You say that the DIV doesn't have a background color it disappears right away. Couldn't you just add the background-color and text after it's been hidden? Yes, it's very ugly, but it could work for now as a quick-fix :)

You could also try using some server-side scripting (if possible) to check the browser before the page renders.

Guess that's my best suggestions, sorry for not giving you an awesome solution =/

ContentLicense: CC BY-SA 3.0

Body:
I am trying to hide some specific DIVS when the page is not viewed on a standalone Safari browser on an iPad via

$(function(){

            var mainNav = $( "#mainNav" );
            var body = $( document.body );

            if (
                ("standalone" in window.navigator) &&
                !window.navigator.standalone
                ){

                mainNav.hide();
            }
});

and it works with every DIV except with a particular DIV that will not disappear, no matter what.

This DIV, let's call it "Buttons" I can see it briefly before it hides. The peculiarity of this DIV is that it has a background color, and when there is Text inside it, the background color appears briefly. If there is an image inside it or if there is no background color, then the DIV disappears completely as it should. But if I have background color AND text then it shows for a brief moment.

Any ideas why this is?


问:
How to deal with 'class file has wrong version 55.0, should be 52.0' under OpenJFX?
```<code>Linux Mint 20.3
   os.name = Linux
   os.arch = amd64
   os.version = 5.13.0-25-generic

 Java :
    openjdk version "1.8.0_322"
    OpenJDK Runtime Environment (build 1.8.0_322-b06)
    OpenJDK 64-Bit Server VM (build 25.322-b06, mixed mode)

Maven 3.8.3

major version number of the class file format being used.[3]
Java SE 17 = 61 (0x3D hex),
Java SE 16 = 60 (0x3C hex),
Java SE 15 = 59 (0x3B hex),
Java SE 14 = 58 (0x3A hex),
Java SE 13 = 57 (0x39 hex),
Java SE 12 = 56 (0x38 hex),
Java SE 11 = 55 (0x37 hex),
Java SE 10 = 54 (0x36 hex),
Java SE 9 = 53 (0x35 hex),
Java SE 8 = 52 (0x34 hex),
</code>```

In pom.xml

```<code><dependency>
            <groupId>org.openjfx</groupId>
            <artifactId>javafx-controls</artifactId>
            <version>17</version>
        </dependency>
        <dependency>
            <groupId>org.openjfx</groupId>
            <artifactId>javafx-graphics</artifactId>
            <version>17</version>
        </dependency>
        <dependency>
            <groupId>org.openjfx</groupId>
            <artifactId>javafx-base</artifactId>
            <version>17</version>
        </dependency>
        <dependency>
            <groupId>org.openjfx</groupId>
            <artifactId>javafx-fxml</artifactId>
            <version>17</version>
        </dependency>
</code>```

In my class files:

```<code>package com.myproject;

import java.util.Collection;
import java.util.List;
import java.util.Map;

import javafx.util.Pair; // error here

@SuppressWarnings("rawtypes")
public interface ManagedGroupCommonDao extends GenericDao<ManagedGroupCommon, Integer> {
    Map<Integer, List<Pair<Integer,Integer>>> findAllMgIdsAssociatedNsPairs();
    List<Integer> findMGsParentsIdsAssociatedToNS(int nsDbId);
    Map<Integer, List<Integer>> findMGsParentsIdsAssociatedPerNSesAsMap(Collection<Integer> nsDbIds);

}
</code>```

But I get error:

```<code>ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.3:compile (default-compile) on project persistence-face: Compilation failure
[ERROR] /com/myproject/server-persistence/persistence-face/src/main/java/ManagedGroupCommonDao.java:[10,19] cannot access javafx.util.Pair
[ERROR]   bad class file: /home/alexeij/.m2/repository/org/openjfx/javafx-base/17/javafx-base-17-linux.jar(javafx/util/Pair.class)
[ERROR]     class file has wrong version 55.0, should be 52.0
[ERROR]     Please remove or make sure it appears in the correct subdirectory of the classpath.
</code>```

The project must build by OpenJDK 8. This is a client's requirement.

答:
According to the official documentation (https://openjfx.io/openjfx-docs/)

In any case, for both options, it is required to have a recent version of JDK 16, or at least JDK 11.

you have to use Java 11 or higher. Unfortunatley, it won't work with Java 8 as OpenJFX is build with a byte code level for Java 11.

Older versions of Java will bundle JavaFX, so If you are Java 8 based, you do not need to declare dependencies towards JavaFX in Maven, see this question: JavaFX comes with JDK 8? (but this JFX version is outdated)

Body:
Linux Mint 20.3
   os.name = Linux
   os.arch = amd64
   os.version = 5.13.0-25-generic

 Java :
    openjdk version "1.8.0_322"
    OpenJDK Runtime Environment (build 1.8.0_322-b06)
    OpenJDK 64-Bit Server VM (build 25.322-b06, mixed mode)

Maven 3.8.3

major version number of the class file format being used.[3]
Java SE 17 = 61 (0x3D hex),
Java SE 16 = 60 (0x3C hex),
Java SE 15 = 59 (0x3B hex),
Java SE 14 = 58 (0x3A hex),
Java SE 13 = 57 (0x39 hex),
Java SE 12 = 56 (0x38 hex),
Java SE 11 = 55 (0x37 hex),
Java SE 10 = 54 (0x36 hex),
Java SE 9 = 53 (0x35 hex),
Java SE 8 = 52 (0x34 hex),

In pom.xml

<dependency>
            <groupId>org.openjfx</groupId>
            <artifactId>javafx-controls</artifactId>
            <version>17</version>
        </dependency>
        <dependency>
            <groupId>org.openjfx</groupId>
            <artifactId>javafx-graphics</artifactId>
            <version>17</version>
        </dependency>
        <dependency>
            <groupId>org.openjfx</groupId>
            <artifactId>javafx-base</artifactId>
            <version>17</version>
        </dependency>
        <dependency>
            <groupId>org.openjfx</groupId>
            <artifactId>javafx-fxml</artifactId>
            <version>17</version>
        </dependency>

In my class files:

package com.myproject;

import java.util.Collection;
import java.util.List;
import java.util.Map;

import javafx.util.Pair; // error here

@SuppressWarnings("rawtypes")
public interface ManagedGroupCommonDao extends GenericDao<ManagedGroupCommon, Integer> {
    Map<Integer, List<Pair<Integer,Integer>>> findAllMgIdsAssociatedNsPairs();
    List<Integer> findMGsParentsIdsAssociatedToNS(int nsDbId);
    Map<Integer, List<Integer>> findMGsParentsIdsAssociatedPerNSesAsMap(Collection<Integer> nsDbIds);

}

But I get error:

ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.3:compile (default-compile) on project persistence-face: Compilation failure
[ERROR] /com/myproject/server-persistence/persistence-face/src/main/java/ManagedGroupCommonDao.java:[10,19] cannot access javafx.util.Pair
[ERROR]   bad class file: /home/alexeij/.m2/repository/org/openjfx/javafx-base/17/javafx-base-17-linux.jar(javafx/util/Pair.class)
[ERROR]     class file has wrong version 55.0, should be 52.0
[ERROR]     Please remove or make sure it appears in the correct subdirectory of the classpath.

The project must build by OpenJDK 8. This is a client's requirement.


问:
Docker-compose check if mysql connection is ready
I am trying to make sure that my app container does not run migrations / start until the db container is started and READY TO accept connections.

So I decided to use the healthcheck and depends on option in docker compose file v2.

In  the app, I have the following

```<code>app:
    ...
    depends_on:
      db:
      condition: service_healthy
</code>```

The db on the other hand has the following healthcheck

```<code>db:
  ...
  healthcheck:
    test: TEST_GOES_HERE
    timeout: 20s
    retries: 10
</code>```

I have tried a couple of approaches like :

making sure the db DIR is created

test: ["CMD", "test -f var/lib/mysql/db"]

Getting the mysql version:

test: ["CMD", "echo 'SELECT version();'| mysql"]

Ping the admin (marks the db container as healthy but does not seem to be a valid test)

test: ["CMD", "mysqladmin" ,"ping", "-h", "localhost"]

Does anyone have a solution to this?

答:
This worked for me:

```<code>version: '3'

services:

  john:
    build:
      context: .
      dockerfile: containers/cowboys/john/Dockerfile
      args:
        - SERVICE_NAME_JOHN
        - CONTAINER_PORT_JOHN
    ports:
      - "8081:8081" # Forward the exposed port on the container to port on the host machine
    restart: unless-stopped
    networks:
      - fullstack
    depends_on:
      db:
        condition: service_healthy
    links:
      - db

 db:
    build:
      context: containers/mysql
    environment:
      MYSQL_ROOT_PASSWORD: root
      MYSQL_USER: docker_user
      MYSQL_PASSWORD: docker_pass
      MYSQL_DATABASE: cowboys
    container_name: golang_db
    restart: on-failure
    networks:
      - fullstack
    ports:
      - "3306:3306"
    healthcheck:
      test: mysqladmin ping -h 127.0.0.1 -u $$MYSQL_USER --password=$$MYSQL_PASSWORD

networks:
  fullstack:
    driver: bridge
</code>```

// containers/mysql/Dockerfile

```<code>FROM mysql
COPY cowboys.sql /docker-entrypoint-initdb.d/cowboys.sql
</code>```

Body:
I am trying to make sure that my app container does not run migrations / start until the db container is started and READY TO accept connections.

So I decided to use the healthcheck and depends on option in docker compose file v2.

In  the app, I have the following

app:
    ...
    depends_on:
      db:
      condition: service_healthy

The db on the other hand has the following healthcheck

db:
  ...
  healthcheck:
    test: TEST_GOES_HERE
    timeout: 20s
    retries: 10

I have tried a couple of approaches like :

making sure the db DIR is created

test: ["CMD", "test -f var/lib/mysql/db"]

Getting the mysql version:

test: ["CMD", "echo 'SELECT version();'| mysql"]

Ping the admin (marks the db container as healthy but does not seem to be a valid test)

test: ["CMD", "mysqladmin" ,"ping", "-h", "localhost"]

Does anyone have a solution to this?

Body:
This worked for me:

version: '3'

services:

  john:
    build:
      context: .
      dockerfile: containers/cowboys/john/Dockerfile
      args:
        - SERVICE_NAME_JOHN
        - CONTAINER_PORT_JOHN
    ports:
      - "8081:8081" # Forward the exposed port on the container to port on the host machine
    restart: unless-stopped
    networks:
      - fullstack
    depends_on:
      db:
        condition: service_healthy
    links:
      - db

 db:
    build:
      context: containers/mysql
    environment:
      MYSQL_ROOT_PASSWORD: root
      MYSQL_USER: docker_user
      MYSQL_PASSWORD: docker_pass
      MYSQL_DATABASE: cowboys
    container_name: golang_db
    restart: on-failure
    networks:
      - fullstack
    ports:
      - "3306:3306"
    healthcheck:
      test: mysqladmin ping -h 127.0.0.1 -u $$MYSQL_USER --password=$$MYSQL_PASSWORD

networks:
  fullstack:
    driver: bridge

// containers/mysql/Dockerfile

FROM mysql
COPY cowboys.sql /docker-entrypoint-initdb.d/cowboys.sql


问:
Trying to run each_index on an array but getting `each': can't iterate from NilClass (TypeError)
I am currently attempting the codewars 6th kyu kata "Equal Sides Of An Array" where it asks:

'Input:
An integer array of length 0 < arr < 1000. The numbers in the array can be any integer positive or negative.

Output:
The lowest index N where the side to the left of N is equal to the side to the right of N. If you do not find an index that fits these rules, then you will return -1.

Note:
If you are given an array with multiple answers, return the lowest correct index.'

I know my code doesn't work completely but trying to run the code to see where it is going wrong to try and get a further understanding of how to use error codes to guide my thought process.

My code is as follows

```<code>def find_even_index(arr)
  even_index = -1
  arr.with_each_index do |n, index|
    even_index = index if (arr[0]..arr[index - 1]).sum == (arr[index + 1]..arr[-1]).sum
  end
  even_index
end
</code>```

When I input this into the kata to test, I get the following error:

'./lib/solution.rb:4:in `each': can't iterate from NilClass (TypeError)'

This error leads me to believe that there is an issue with the use of each_with_index on arr but the parameter is an array. What is going wrong here?

答:
There is not with_each_index in Ruby, only each_with_index

Your problem is in arr[index + 1]..arr[-1] on last index

arr[index + 1] in that case is nil so you tries nil..arr[-1]

That's why you have can't iterate from NilClass (TypeError) error

You don't need to use ranges in your solution, just use subarrays, array also have sum method

So you can use each_index method here like this:

```<code>def find_even_index(ary)
  ary.each_index do |idx|
    return idx if ary[...idx].sum == ary[idx + 1..].sum
  end

  -1
end

find_even_index([1, 2, 3, 4, 3, 2, 1])
# => 3

find_even_index([1, 2, 2, 4, 3, 2, 1])
# => -1
</code>```

This solution with beginless (available in Ruby >= 2.7) and endless (available in Ruby >= 2.6) ranges

In earlier versions you can use ary[0...idx] and ary[idx + 1..-1]

Body:
I am currently attempting the codewars 6th kyu kata "Equal Sides Of An Array" where it asks:

'Input:
An integer array of length 0 < arr < 1000. The numbers in the array can be any integer positive or negative.

Output:
The lowest index N where the side to the left of N is equal to the side to the right of N. If you do not find an index that fits these rules, then you will return -1.

Note:
If you are given an array with multiple answers, return the lowest correct index.'

I know my code doesn't work completely but trying to run the code to see where it is going wrong to try and get a further understanding of how to use error codes to guide my thought process.

My code is as follows

def find_even_index(arr)
  even_index = -1
  arr.with_each_index do |n, index|
    even_index = index if (arr[0]..arr[index - 1]).sum == (arr[index + 1]..arr[-1]).sum
  end
  even_index
end

When I input this into the kata to test, I get the following error:

'./lib/solution.rb:4:in `each': can't iterate from NilClass (TypeError)'

This error leads me to believe that there is an issue with the use of each_with_index on arr but the parameter is an array. What is going wrong here?

Body:
There is not with_each_index in Ruby, only each_with_index

Your problem is in arr[index + 1]..arr[-1] on last index

arr[index + 1] in that case is nil so you tries nil..arr[-1]

That's why you have can't iterate from NilClass (TypeError) error

You don't need to use ranges in your solution, just use subarrays, array also have sum method

So you can use each_index method here like this:

def find_even_index(ary)
  ary.each_index do |idx|
    return idx if ary[...idx].sum == ary[idx + 1..].sum
  end

  -1
end

find_even_index([1, 2, 3, 4, 3, 2, 1])
# => 3

find_even_index([1, 2, 2, 4, 3, 2, 1])
# => -1

This solution with beginless (available in Ruby >= 2.7) and endless (available in Ruby >= 2.6) ranges

In earlier versions you can use ary[0...idx] and ary[idx + 1..-1]


问:
Submitting a form in ColdFusion that has special characters
I have a form that contains textboxes and textareas with user entered data. I am using a simple ColdFusion actionpage with a cfquery tag to submit the data to my database.

```<code><cfquery name="add_ticket" datasource="#datasource#">
INSERT INTO service_ticket(end_user, customer_id, ticket_id, company_name, service_description, service_date, status, customer_signature, technician_signature, materials, ticket_type, equipment, discount, percent_discount, material_subtotal, material_tax, material_shipping, material_total, billable_service_total, tax_rate, grand_total, equipment_id, equipment_name)
VALUES("", '#get_customer.customer_id#', "#ticketnum#", "#url.customer_name#", "#url.description# - #get_equipment.equipment_name#", #CreateODBCDateTime(Now())#, "In-progress", "0", "0", "0", "#url.TT#", "0",  '0.00', '0', '0.00', '6.625', '0.00', '0.00', '0.00', '#subscriber.tax_rate#', '0.00', "#get_equipment.id#", "#get_equipment.equipment_name#")
</cfquery>
</code>```

I sporadically run into errors submitting this query because the values for certain columns contain special characters.

For instance, the value for company_name might be: Smith & Johnson, LLC.

The ColdFusion code breaks once it hits the ampersand. I've tried enclosing the value in single quotes and double quotes as well as

```<code><cfqueryparam value="#url.company_name#" cfsqltype="cf_sql_longvarchar" />
</code>```

but nothing seems to help.

Is there a better way to handle this situation?

I'm currently running a Lucee server.

答:
After reading your comment I now understand what the issue is.  The solution to your problem is to use the ColdFusion function encodeForURL() when calling your action page using javascript.

Change your code from

window.open(href='actionpages/add_ticket_maintenance.cfm?TT=commercial&equipment_id=#id#&customer_name=#customer_name#&description=Equipment Maintenance&end_user=Scheduled maintenance', "_self");
```
<p>to</p>
<pre class="lang-js prettyprint-override"><code>window.open(href='actionpages/add_ticket_maintenance.cfm?TT=commercial&equipment_id=#id#&customer_name=#encodeForURL(customer_name)#&description=Equipment Maintenance&end_user=Scheduled maintenance', "_self");
</code>```

Body:
I have a form that contains textboxes and textareas with user entered data. I am using a simple ColdFusion actionpage with a cfquery tag to submit the data to my database.

<cfquery name="add_ticket" datasource="#datasource#">
INSERT INTO service_ticket(end_user, customer_id, ticket_id, company_name, service_description, service_date, status, customer_signature, technician_signature, materials, ticket_type, equipment, discount, percent_discount, material_subtotal, material_tax, material_shipping, material_total, billable_service_total, tax_rate, grand_total, equipment_id, equipment_name)
VALUES("", '#get_customer.customer_id#', "#ticketnum#", "#url.customer_name#", "#url.description# - #get_equipment.equipment_name#", #CreateODBCDateTime(Now())#, "In-progress", "0", "0", "0", "#url.TT#", "0",  '0.00', '0', '0.00', '6.625', '0.00', '0.00', '0.00', '#subscriber.tax_rate#', '0.00', "#get_equipment.id#", "#get_equipment.equipment_name#")
</cfquery>

I sporadically run into errors submitting this query because the values for certain columns contain special characters.

For instance, the value for company_name might be: Smith & Johnson, LLC.

The ColdFusion code breaks once it hits the ampersand. I've tried enclosing the value in single quotes and double quotes as well as

<cfqueryparam value="#url.company_name#" cfsqltype="cf_sql_longvarchar" />

but nothing seems to help.

Is there a better way to handle this situation?

I'm currently running a Lucee server.

Body:
After reading your comment I now understand what the issue is.  The solution to your problem is to use the ColdFusion function encodeForURL() when calling your action page using javascript.

Change your code from

window.open(href='actionpages/add_ticket_maintenance.cfm?TT=commercial&equipment_id=#id#&customer_name=#customer_name#&description=Equipment Maintenance&end_user=Scheduled maintenance', "_self");

to

window.open(href='actionpages/add_ticket_maintenance.cfm?TT=commercial&equipment_id=#id#&customer_name=#encodeForURL(customer_name)#&description=Equipment Maintenance&end_user=Scheduled maintenance', "_self");


问:
What is the best approach for upserting large number of rows into a single table?
Im working on a product that involves large number of upsert operations into a single table.

We are dealing with a time-based data and using timescaledb hypertables with 7 days chunk interval size. we have concurrent tasks that upserts data into a single table, and in extreme cases its possible that we will have 40 concurrent tasks, each one upserting around 250k rows, all to the same table.

Initially we decided to go with the approach of deleting all the old rows and then inserting the updated ones with a COPY FROM statement, but when we got to test the system on large scale these COPYs took long time to finish, eventually resulting in the db's CPU usage to reach 100%, and become unresponsive.
We also noticed that the index size of the table increased radically and filled up the disk usage to 100%, and SELECT statements took extremely long time to execute (over 10 minutes). We concluded that the reason for that was large amount of delete statements that caused index fragmentation, and decided to go with another approach.

following the answers on this post, we decided to copy all the data to a temporary table, and then upsert all the data to the actual table using an "extended insert" statement -

```<code>INSERT INTO table SELECT * FROM temp_table ON CONFLICT DO UPDATE...;
</code>```

our tests show that it helped with the index fragmentation issues, but still large upsert operations of ~250K take over 4 minutes to execute, and during this upsert process SELECT statements take too long to finish which is unacceptable for us.

I'm wondering whats the best approach to create this upsert operation with as low impact to the performance of SELECTs as possible. The only thing that comes in mind right now is to split the insert into smaller chunks -

```<code>INSERT INTO table SELECT * FROM temp_table LIMIT 50000 OFFSET 0 ON CONFLICT DO UPDATE ...;
INSERT INTO table SELECT * FROM temp_table LIMIT 50000 OFFSET 50000 ON CONFLICT DO UPDATE ...;
INSERT INTO table SELECT * FROM temp_table LIMIT 50000 OFFSET 100000 ON CONFLICT DO UPDATE ...;
...
</code>```

but if we batch the inserts, is there any advantage of first copying all the data into a temporary table? will it perform better then a simple multi-row insert statement?
and how do i decide whats the best chunk size to use when splitting up the upsert? is
using a temporary table and upserting the rows directly from it allows for a bigger chunk sizes?

Is there any better approach to achieve this? any suggestion would be appreciated

答:
There are a handful of things that you can do to speed up data loading:

Have no index or foreign key on the table while you load data (check constraints are fine). I am not suggesting that you drop all your constraints, but you could for example use partitioning, load the data into a new table, then create indexes and constraints and attach the table as a new partition.

Load the data with COPY. If you cannot use COPY, use a prepared statement for the INSERT to save on parsing time.

Load many rows in a single transaction.

Set max_wal_size high so that you get no more checkpoints than necessary.

Get fast local disks.

Body:
Im working on a product that involves large number of upsert operations into a single table.

We are dealing with a time-based data and using timescaledb hypertables with 7 days chunk interval size. we have concurrent tasks that upserts data into a single table, and in extreme cases its possible that we will have 40 concurrent tasks, each one upserting around 250k rows, all to the same table.

Initially we decided to go with the approach of deleting all the old rows and then inserting the updated ones with a COPY FROM statement, but when we got to test the system on large scale these COPYs took long time to finish, eventually resulting in the db's CPU usage to reach 100%, and become unresponsive.
We also noticed that the index size of the table increased radically and filled up the disk usage to 100%, and SELECT statements took extremely long time to execute (over 10 minutes). We concluded that the reason for that was large amount of delete statements that caused index fragmentation, and decided to go with another approach.

following the answers on this post, we decided to copy all the data to a temporary table, and then upsert all the data to the actual table using an "extended insert" statement -

INSERT INTO table SELECT * FROM temp_table ON CONFLICT DO UPDATE...;

our tests show that it helped with the index fragmentation issues, but still large upsert operations of ~250K take over 4 minutes to execute, and during this upsert process SELECT statements take too long to finish which is unacceptable for us.

I'm wondering whats the best approach to create this upsert operation with as low impact to the performance of SELECTs as possible. The only thing that comes in mind right now is to split the insert into smaller chunks -

INSERT INTO table SELECT * FROM temp_table LIMIT 50000 OFFSET 0 ON CONFLICT DO UPDATE ...;
INSERT INTO table SELECT * FROM temp_table LIMIT 50000 OFFSET 50000 ON CONFLICT DO UPDATE ...;
INSERT INTO table SELECT * FROM temp_table LIMIT 50000 OFFSET 100000 ON CONFLICT DO UPDATE ...;
...

but if we batch the inserts, is there any advantage of first copying all the data into a temporary table? will it perform better then a simple multi-row insert statement?
and how do i decide whats the best chunk size to use when splitting up the upsert? is
using a temporary table and upserting the rows directly from it allows for a bigger chunk sizes?

Is there any better approach to achieve this? any suggestion would be appreciated


问:
How to download an image using python
I have a question how to download an image with selenium and save it to disk. the download itself I know how to do from a direct link src.
I have a page that has an 'download image' button but I would like to use python to download it. The code responsible for downloading the image looks like this, it is not a direct reference with a url link to it.

function downloadPhoto() {
    data = {  };
    data.directory_id = '56899';
    data.fileName = 'k_000078.JPG';

    $.ajax({
        url: '/photo/request-link',
        data: data,
        type: 'post',
        dataType: 'json',
        async: false,
        success: function (response) {
            if (response.state == 'TRUE') {
                window.open('/photo/download');
            }
            else {
                $('div#alert').html(response.message);
                $('div#alert').dialog({ })
            }
        }
    })

}```

Thank you in advance for your help

答:
you have a few options. But irst you need to find the photo in the web page. maybe by xpath.

```<code>from selenium import webdriver
driver = webdriver.Firefox()
driver.get(url)
with open('filename.png', 'wb') as file:
    file.write(driver.find_element_by_xpath(your_xpath).screenshot_as_png)
</code>```

more option is by using urlib

```<code>import urllib
from selenium import webdriver

driver = webdriver.Firefox()
driver.get(url)

# get the image source
img = driver.find_element_by_xpath(xpath)
src = img.get_attribute('src')

# download the image
urllib.urlretrieve(src, "file.png")

driver.close()
</code>```

Title: How to download an image using python

Body:
I have a question how to download an image with selenium and save it to disk. the download itself I know how to do from a direct link src.
I have a page that has an 'download image' button but I would like to use python to download it. The code responsible for downloading the image looks like this, it is not a direct reference with a url link to it.

function downloadPhoto() {
    data = {  };
    data.directory_id = '56899';
    data.fileName = 'k_000078.JPG';

    $.ajax({
        url: '/photo/request-link',
        data: data,
        type: 'post',
        dataType: 'json',
        async: false,
        success: function (response) {
            if (response.state == 'TRUE') {
                window.open('/photo/download');
            }
            else {
                $('div#alert').html(response.message);
                $('div#alert').dialog({ })
            }
        }
    })

}

Thank you in advance for your help

Body:
you have a few options. But irst you need to find the photo in the web page. maybe by xpath.

from selenium import webdriver
driver = webdriver.Firefox()
driver.get(url)
with open('filename.png', 'wb') as file:
    file.write(driver.find_element_by_xpath(your_xpath).screenshot_as_png)

more option is by using urlib

import urllib
from selenium import webdriver

driver = webdriver.Firefox()
driver.get(url)

# get the image source
img = driver.find_element_by_xpath(xpath)
src = img.get_attribute('src')

# download the image
urllib.urlretrieve(src, "file.png")

driver.close()


问:
The replace_ending function replaces the old string in a sentence with the new string, but only if the sentence ends with the old string
The replace_ending function replaces the old string in a sentence with the new string, but only if the sentence ends with the old string. If there is more than one occurrence of the old string in the sentence, only the one at the end is replaced, not all of them. For example, replace_ending("abcabc", "abc", "xyz") should return abcxyz, not xyzxyz or xyzabc. The string comparison is case-sensitive, so replace_ending("abcabc", "ABC", "xyz") should return abcabc (no changes made).</p>

```<code>def replace_ending(sentence, old, new):
# Check if the old string is at the end of the sentence
if ___:
    # Using i as the slicing index, combine the part
    # of the sentence up to the matched string at the
    # end with the new string
    i = ___
    new_sentence = ___
    return new_sentence

# Return the original sentence if there is no match
return sentence

print(replace_ending("It's raining cats and cats", "cats", "dogs"))
# Should display "It's raining cats and dogs"
print(replace_ending("She sells seashells by the seashore", "seashells",
"donuts"))
# Should display "She sells seashells by the seashore"
print(replace_ending("The weather is nice in May", "may", "april"))
# Should display "The weather is nice in May"
print(replace_ending("The weather is nice in May", "May", "April"))
# Should display "The weather is nice in April"
</code>```

答:
my solution without .endswith() nor rindex():

```<code>def replace_ending(sentence, old, new):
# Check if the old string is at the end of the sentence
if old == sentence[-len(old):]:
    # Using i as the slicing index, combine the part
    # of the sentence up to the matched string at the
    # end with the new string
    i = sentence[:-len(old)]
    new_sentence = i + new
    return new_sentence

# Return the original sentence if there is no match
return sentence
</code>```

Regards!

Body:
The replace_ending function replaces the old string in a sentence with the new string, but only if the sentence ends with the old string. If there is more than one occurrence of the old string in the sentence, only the one at the end is replaced, not all of them. For example, replace_ending("abcabc", "abc", "xyz") should return abcxyz, not xyzxyz or xyzabc. The string comparison is case-sensitive, so replace_ending("abcabc", "ABC", "xyz") should return abcabc (no changes made).

def replace_ending(sentence, old, new):
# Check if the old string is at the end of the sentence
if ___:
    # Using i as the slicing index, combine the part
    # of the sentence up to the matched string at the
    # end with the new string
    i = ___
    new_sentence = ___
    return new_sentence

# Return the original sentence if there is no match
return sentence

print(replace_ending("It's raining cats and cats", "cats", "dogs"))
# Should display "It's raining cats and dogs"
print(replace_ending("She sells seashells by the seashore", "seashells",
"donuts"))
# Should display "She sells seashells by the seashore"
print(replace_ending("The weather is nice in May", "may", "april"))
# Should display "The weather is nice in May"
print(replace_ending("The weather is nice in May", "May", "April"))
# Should display "The weather is nice in April"

Body:
my solution without .endswith() nor rindex():

def replace_ending(sentence, old, new):
# Check if the old string is at the end of the sentence
if old == sentence[-len(old):]:
    # Using i as the slicing index, combine the part
    # of the sentence up to the matched string at the
    # end with the new string
    i = sentence[:-len(old)]
    new_sentence = i + new
    return new_sentence

# Return the original sentence if there is no match
return sentence

Regards!


问:
I don't understand slicing with negative bounds in Python. How is this supposed to work?
I am a newbie to Python and have come across the following example in my book that is not explained very well. Here is my print out from the interpreter:

```<code>>>> s = 'spam'
>>> s[:-1]
'spa'
</code>```

Why does slicing with no beginning bound and a '-1' return every element except the last one? Is calling s[0:-1] logically the same as calling s[:-1]? They both return the same result. But I'm not sure what python is doing exactly. Any help would be greatly appreciated.

答:
RULE  [START, END, STEP] or [START, END]

If you want a slice in regular order, STEP should be positive.

If you want a slice in reverse order, STEP should be negative.

eg:

>>> s = 'abcdefg'
>>> s[1:6:1]
'bcdef'
>>> s[6:1:1]
''
# If in regular order, s[6:1]='' therefore same for s[6:1:1]
>>> s[6:1:-1]
'gfedc'
# Reverse order, START=6 and END=1, a slice is possible
```

OwnerDisplayName: jtbradle

ContentLicense: CC BY-SA 2.5

Body:
I am a newbie to Python and have come across the following example in my book that is not explained very well. Here is my print out from the interpreter:

>>> s = 'spam'
>>> s[:-1]
'spa'

Why does slicing with no beginning bound and a '-1' return every element except the last one? Is calling s[0:-1] logically the same as calling s[:-1]? They both return the same result. But I'm not sure what python is doing exactly. Any help would be greatly appreciated.


问:
Could not find 'minitest' (>= 5.1) among 39 total gem(s)
Situation:

I am trying to setup Cocoapods.

I'm on OSX 12.2. I have installed Ruby with Homebrew. When I run gem list minitest (5.15.0) is listed.

Running pod setup in terminal fails because it could not find minitest (>=5.1) among 39 gems.

I noticed that the directory searched looks to be the OSX system ruby installation at Library/Ruby/Site/2.6.0; rather than ruby 3.1.0 (at /usr/local/opt/ruby/bin/ruby) that I installed with Homebrew.

I assume that what I need to do is point terminal to ruby 3.1.0; but, I double checked my .zhsrc file, and it looks to be in order (I learnt about this from reading SO questions and Ruby and Cocoapods setup guides - so I may be very wrong about this).

This is the contents of .zhsrc:

```<code>export PATH="/usr/local/sbin:$PATH"

# The next line updates PATH for the Google Cloud SDK.
if [ -f '/Users/sean/Desktop/google-cloud-sdk/path.zsh.inc' ]; then . '/Users/sean/Desktop/google-cloud-sdk/path.zsh.inc'; fi

# The next line enables shell command completion for gcloud.
if [ -f '/Users/sean/Desktop/google-cloud-sdk/completion.zsh.inc' ]; then . '/Users/sean/Desktop/google-cloud-sdk/completion.zsh.inc'; fi
export PATH="/usr/local/opt/ruby/bin:$PATH"

. /usr/local/opt/asdf/libexec/asdf.sh
</code>```

Can you please help me figure out what I need to do to get pod setup to succeed?

Things I have tried:

I tried uninstalling and reinstalling cocoapods sudo gem install cocoapods

I tried uninstalling and reinstalling cocoapods with homebrew brew install cocoapods.

Install bundler from this SO suggestion - I tried this and got the error Could not locate Gemfile

I also ran sudo gem install minitest -v 5.15.0 - and am still getting the same error. From this SO question.

Extra Information Below:

If it helps, this is my path:

```<code>/usr/local/opt/ruby/bin:/Users/sean/Desktop/google-cloud-sdk/bin:/usr/local/sbin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Library/Apple/usr/bin:/Applications/Wireshark.app/Contents/MacOS
</code>```

Here are images of the error:

I have looked at these Stackoverflow questions (and many many more) and tried the suggested solutions to no avail:

Could not find 'minitest' (~> 5.1) among 42 total gem(s) (Gem::MissingSpecError)

Could not find 'cocoapods' (>= 0) among N total gem(s) (Gem::LoadError)

How do I install CocoaPods?

Rails: Could not find minitest-4.7.5 in any of the sources

答:
Solved the situation by following this.

Specifically - I added the following text to the end of the .zshrc file:

```<code>if [ -d "/usr/local/opt/ruby/bin" ]; then
  export PATH=/usr/local/opt/ruby/bin:$PATH
  export PATH=`gem environment gemdir`/bin:$PATH
fi
</code>```

And then critically - quitting terminal and re-opening it.

Body:
Situation:

I am trying to setup Cocoapods.

I'm on OSX 12.2. I have installed Ruby with Homebrew. When I run gem list minitest (5.15.0) is listed.

Running pod setup in terminal fails because it could not find minitest (>=5.1) among 39 gems.

I noticed that the directory searched looks to be the OSX system ruby installation at Library/Ruby/Site/2.6.0; rather than ruby 3.1.0 (at /usr/local/opt/ruby/bin/ruby) that I installed with Homebrew.

I assume that what I need to do is point terminal to ruby 3.1.0; but, I double checked my .zhsrc file, and it looks to be in order (I learnt about this from reading SO questions and Ruby and Cocoapods setup guides - so I may be very wrong about this).

This is the contents of .zhsrc:

export PATH="/usr/local/sbin:$PATH"

# The next line updates PATH for the Google Cloud SDK.
if [ -f '/Users/sean/Desktop/google-cloud-sdk/path.zsh.inc' ]; then . '/Users/sean/Desktop/google-cloud-sdk/path.zsh.inc'; fi

# The next line enables shell command completion for gcloud.
if [ -f '/Users/sean/Desktop/google-cloud-sdk/completion.zsh.inc' ]; then . '/Users/sean/Desktop/google-cloud-sdk/completion.zsh.inc'; fi
export PATH="/usr/local/opt/ruby/bin:$PATH"

. /usr/local/opt/asdf/libexec/asdf.sh

Can you please help me figure out what I need to do to get pod setup to succeed?

Things I have tried:

I tried uninstalling and reinstalling cocoapods sudo gem install cocoapods

I tried uninstalling and reinstalling cocoapods with homebrew brew install cocoapods.

Install bundler from this SO suggestion - I tried this and got the error Could not locate Gemfile

I also ran sudo gem install minitest -v 5.15.0 - and am still getting the same error. From this SO question.

Extra Information Below:

If it helps, this is my path:

/usr/local/opt/ruby/bin:/Users/sean/Desktop/google-cloud-sdk/bin:/usr/local/sbin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Library/Apple/usr/bin:/Applications/Wireshark.app/Contents/MacOS

Here are images of the error:

I have looked at these Stackoverflow questions (and many many more) and tried the suggested solutions to no avail:

Could not find 'minitest' (~> 5.1) among 42 total gem(s) (Gem::MissingSpecError)

Could not find 'cocoapods' (>= 0) among N total gem(s) (Gem::LoadError)

How do I install CocoaPods?

Rails: Could not find minitest-4.7.5 in any of the sources

Body:
Solved the situation by following this.

Specifically - I added the following text to the end of the .zshrc file:

if [ -d "/usr/local/opt/ruby/bin" ]; then
  export PATH=/usr/local/opt/ruby/bin:$PATH
  export PATH=`gem environment gemdir`/bin:$PATH
fi

And then critically - quitting terminal and re-opening it.


问:
Merge IP Ranges with PHP
I am stuck at a point and cant think beyond it :

I have a list of Ip ranges, I need to merge them making them as a range. For example

192.168.1.1

192.168.1.2

192.168.1.3

192.168.1.5

192.168.1.6

I need to club them into IP ranges. For this case it will be 192.168.1.1-192.168.1.3 and 192.168.1.5-192.168.1.6

I was thinking of converting these into integer by using ip2long function and sorting it. But can't think beyond that.

Any help would be appreciated.

Thanks In advance :)

答:
```<code>function printCombinedIPs($ip_arr) {
    //$ip_arr = array('192.168.1.5','192.168.1.6');
    $k = NULL;
    $prev = -1;
    foreach ( $ip_arr as $ip ) {
        $octet = explode(".",$ip);
        $fourth = $octet[3];
        $net = $octet[0].".".$octet[1].".".$octet[2];

        if ( $fourth < $prev ) {
            $prev = -1;
        }

        $end = $fourth;
        if ( $fourth - 1 != $prev ) {
            $start = $fourth;
            $rtn_arr[] = $k;
        }

        if ( $start == $end )
            $k = $net.".$end";
        else
            $k = $net.".$start-$end";

        $prev = $octet[3];
    }
    $rtn_arr[] = $k;
    array_shift($rtn_arr);
    return implode(", ", $rtn_arr);
}
</code>```

Title: Merge IP Ranges with PHP


问:
Selecting first non null value in a model
Let's say I have a model class that looks like this:

```<code>   public class ModelTest {
        public string val1 {get;set;}
        public string val2 {get;set;}
        public string val3 {get;set;}
   }
</code>```

Somewhere in my code this ModelTest gets its data. The caveat is that, only 1 of them will hold a value

```<code>   var model = new ModelTest() {val1=null, val2="value", val3=null} //Sudo code
</code>```

What I am trying to do somehow, is compare a value to whichever 1 of the 3 items can potentially have a values, so something like:

```<code>     var testCompare = "someValue"

     if (testCompare == model. ....//how can I get the NOT NULL value from ModelTest here for comparison
</code>```

答:
You can override the method 'Equals' of ModelTest class however you like. Example:

```<code>public class ModelTest {

    public string val1 {get;set;}
    public string val2 {get;set;}
    public string val3 {get;set;}

    public override bool Equals(object obj)
    {
        if(!typeof(string).IsInstanceOfType(obj))
            return base.Equals(obj);

        string value = obj as string;

        if (val1.Equals(value))
            return true;

        if (val2.Equals(value))
            return true;

        if (val3.Equals(value))
            return true;

        return false;
    }

}
</code>```

For to use the method:

```<code>if(model.Equals("yourValue"))
...
</code>```

Body:
Let's say I have a model class that looks like this:

   public class ModelTest {
        public string val1 {get;set;}
        public string val2 {get;set;}
        public string val3 {get;set;}
   }

Somewhere in my code this ModelTest gets its data. The caveat is that, only 1 of them will hold a value

   var model = new ModelTest() {val1=null, val2="value", val3=null} //Sudo code

What I am trying to do somehow, is compare a value to whichever 1 of the 3 items can potentially have a values, so something like:

     var testCompare = "someValue"

     if (testCompare == model. ....//how can I get the NOT NULL value from ModelTest here for comparison

Body:
You can override the method 'Equals' of ModelTest class however you like. Example:

public class ModelTest {

    public string val1 {get;set;}
    public string val2 {get;set;}
    public string val3 {get;set;}

    public override bool Equals(object obj)
    {
        if(!typeof(string).IsInstanceOfType(obj))
            return base.Equals(obj);

        string value = obj as string;

        if (val1.Equals(value))
            return true;

        if (val2.Equals(value))
            return true;

        if (val3.Equals(value))
            return true;

        return false;
    }

}

For to use the method:

if(model.Equals("yourValue"))
...


问:
How to check if left click is pressed after unpressing it from Robot class?
I'm making something like an auto clicker.
I would like to make it so that when the left mouse button is pressed, the auto clicker should turn on. When the button is released, the auto clicker should turn off.

Is there a way to check if the left mouse click (in real life) is pressed after calling the robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK) method?

答:
You should  implement  MouseListener interface in your class   then override these two methods :  mousePressed  and  mouseReleased .

```<code>public void mousePressed(MouseEvent e) {
//do the auto click code here
}

public void mouseReleased(MouseEvent e) {
  //turn off the auto click here
}

</code>```

read this article

Body:
You should  implement  MouseListener interface in your class   then override these two methods :  mousePressed  and  mouseReleased .

public void mousePressed(MouseEvent e) {
//do the auto click code here
}

public void mouseReleased(MouseEvent e) {
  //turn off the auto click here
}

read this article


问:
How to install Tensorflow==1.X.X for Python2.7 on Ubuntu?
I try to install tensorflow==1.1.0 for Python2.7 with pip package manager but am getting the following error when I run the command pip install tensorflow:

```<code>DEPRECATION: Python 2.7 reached the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 is no longer maintained. pip 21.0 will drop support for Python 2.7 in January 2021. More details about Python 2 support in pip can be found at pip.pypa.io/en/latest/development/release-process/… pip 21.0 will remove support for this functionality.
ERROR: Could not find a version that satisfies the requirement tensorflow==1.1.0 (from versions: none)
ERROR: No matching distribution found for tensorflow==1.1.0
</code>```

How else can I install tensorflow for Python2.7?

Thank you!

答:
You could use a ready to use Docker image.
https://hub.docker.com/r/tensorflow/tensorflow/tags?page=1&name=1.1.0

The tags with the postfix ”py3“ indicate using Python 3.x while the ones without this postfix are using Python 2.7.

Here some additional information about the Docker images. https://hub.docker.com/r/tensorflow/tensorflow/

Dockerfiles for TF 1.1.0 https://github.com/tensorflow/tensorflow/tree/v1.1.0/tensorflow/tools/docker

Body:
I try to install tensorflow==1.1.0 for Python2.7 with pip package manager but am getting the following error when I run the command pip install tensorflow:

DEPRECATION: Python 2.7 reached the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 is no longer maintained. pip 21.0 will drop support for Python 2.7 in January 2021. More details about Python 2 support in pip can be found at pip.pypa.io/en/latest/development/release-process/… pip 21.0 will remove support for this functionality.
ERROR: Could not find a version that satisfies the requirement tensorflow==1.1.0 (from versions: none)
ERROR: No matching distribution found for tensorflow==1.1.0

How else can I install tensorflow for Python2.7?

Thank you!


问:
Using plantuml within a markdown document
At the moment I am trying to make a presentation using markdown.

In order to include an UML diagram I want to use PlantUML.

The code is written in the document below. I am of the understanding, that this should work. However it does not.

Of course there is a solution to create the UML diagrams outside separately and include the in markdown. This however would make the document less self contained.

Markdown code

Here is (part of) the code:

```<code>---
Previous slide

---

# diagram

```plantuml
@startuml
  class Example {
    - String name
    - int number

    +void getName()
    +void getNumber()
    +String toString()
  }
@enduml
```

---
Next slide

---
</code>```

This blog post suggests that this should work.

Is there anything I am missing?

答:
As mentioned in the (at the time of writing) top voted answer and the blog post linked in your question, you first need to install the PlantUML plugin.

After doing so, previewing .puml files worked for me, however, previewing .md files containing PlantUML code in code blocks as described in the linked blog post didn't work. If I understand you correctly, this is exactly what you experienced.

The symptoms match the ones described in issue #449 and issue #426 of the plugin repository. The rough gist:

Rendering .puml files uses a local PlantUML renderer installed on your machine, which works out of the box.

Rendering PlantUML diagrams in .md files is done using a remote server (the local renderer does not work for some reason), whose URL needs to be manually entered into your VSCode configuration.

Suggested fix: You need to provide a URL for the "PlantUML server" in configuration, see this comment on issue #449 for details.

Body:
At the moment I am trying to make a presentation using markdown.

In order to include an UML diagram I want to use PlantUML.

The code is written in the document below. I am of the understanding, that this should work. However it does not.

Of course there is a solution to create the UML diagrams outside separately and include the in markdown. This however would make the document less self contained.

Markdown code

Here is (part of) the code:

---
Previous slide

---

# diagram

```plantuml
@startuml
  class Example {
    - String name
    - int number

    +void getName()
    +void getNumber()
    +String toString()
  }
@enduml
```

---
Next slide

---

This blog post suggests that this should work.

Is there anything I am missing?


问:
how can i make this custom path on flutter.Line,quadratic etc custom clipper,clip path

how can i make this custom clipper ?
i cant make it with border radius.Can anyone send code?

答:
You can use this Path

class CardClipperPath extends CustomClipper<Path> {
  final double curveRadius;

  CardClipperPath({this.curveRadius = 16.0});

  @override
  Path getClip(Size size) => Path()
    ..quadraticBezierTo(0, curveRadius * .75, curveRadius, curveRadius)
    ..lineTo(size.width - curveRadius, curveRadius)
    ..quadraticBezierTo(size.width, curveRadius, size.width, curveRadius * 2)
    ..lineTo(size.width, size.height)
    ..lineTo(0, size.height);

  @override
  bool shouldReclip(covariant CardClipperPath oldClipper) => oldClipper != this;
}
```

Wrap with Stack and provide corner image.

Body:
You can use this Path

class CardClipperPath extends CustomClipper<Path> {
  final double curveRadius;

  CardClipperPath({this.curveRadius = 16.0});

  @override
  Path getClip(Size size) => Path()
    ..quadraticBezierTo(0, curveRadius * .75, curveRadius, curveRadius)
    ..lineTo(size.width - curveRadius, curveRadius)
    ..quadraticBezierTo(size.width, curveRadius, size.width, curveRadius * 2)
    ..lineTo(size.width, size.height)
    ..lineTo(0, size.height);

  @override
  bool shouldReclip(covariant CardClipperPath oldClipper) => oldClipper != this;
}

Wrap with Stack and provide corner image.


问:
Worksheet Change on Data Range / Excel Table
I'm new to VBA and perusing YouTube and StackOverflow to figure somethings out.

What I have here is a table for Hours and Overtime % by week.  Overtime % is determined by the formula OT% = MAX(0,(Hours1.05-35)/Hours)

I want users of my model to be able to change Hours OR OT, and the the other value to recalculate.  I can do with for the first row with the following

Sheet1 Code

```<code>Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Address = "$J$2" Or Target.Address = "$K$2" Then
        Call cellUpdate(Target.Address)
    End If
End Sub
</code>```

Module:

```<code>Sub cellUpdate(Target As String)
Application.EnableEvents = False
    With ActiveWorkbook.Worksheets("Sheet1")
        If Target = "$J$2" Then
            .Range("$K$2").Value = WorksheetFunction.Max(0, .Range("$J$2").Value * .Range("$G$2").Value + .Range("$G$3").Value) / .Range("$J$2").Value
        ElseIf Target = "$K$2" Then
            .Range("$J$2").Value = -.Range("$G$3").Value / (.Range("$G$2").Value - .Range("$K$2").Value)
        End If
    End With
Application.EnableEvents = True
End Sub
</code>```

This works great.  If I change J2, K2 updates.  If I change K2, J2 updates.

My questions:

How can I make this work for all rows in the table?

Do I have to define the cells by Row # and Column Letter, or can I define by table name and row header?

What if the end user pastes a value in both J and K by mistake?

What if the end user pastes over multiple rows in J or K, updating multiple weeks simultaneously?

Can I change the references to M and B to something named, perhaps in a hidden sheet?

Thank you in advance for the assistance.

*this exact formula is made up, but for groups of employees (Hrs-40)/Hrs is not accurate since not everyone works 40 hours.

答:
Okay, this is probably not the best solution but it is what I have managed to learn.

Worksheet Code:

```<code>Dim UpdateOT As Boolean
Dim oldarr As Variant
Dim newarr As Variant

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim therow As Long
    Dim thecol As Long

    therow = Target.Row
    thecol = Target.Column

    newarr = Target

    If UpdateOT = True And Sheets("Sheet1").ListObjects("Table1").ListColumns("Hours").Range.Column = Target.Column Then
        Call OTUpdate(newarr, therow, thecol)
    ElseIf UpdateOT = True And Sheets("Sheet1").ListObjects("Table1").ListColumns("OT%").Range.Column = Target.Column Then
        Call HoursUpdate(newarr, therow, thecol)
    End If
End Sub

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    Dim colcount As Long

    UpdateOT = False
    oldarr = Target
    colcount = Target.Columns.Count

    If Target.Columns.Count = 1 And (Sheets("Sheet1").ListObjects("Table1").ListColumns("Hours").Range.Column = Target.Column Or Sheets("Sheet1").ListObjects("Table1").ListColumns("OT%").Range.Column = Target.Column) And Target.Row > Sheets("Sheet1").ListObjects("Table1").HeaderRowRange.Row Then
        UpdateOT = True
    End If
End Sub
</code>```

Module1:

```<code>Sub OTUpdate(ByVal arr As Variant, ByVal therow As Long, ByVal thecol As Long)
    Dim updatecol As Long
    Dim i As Integer

    updatecol = Sheets("Sheet1").ListObjects("Table1").ListColumns("OT%").Range.Column

    Application.EnableEvents = False
    With ActiveWorkbook.Worksheets("Sheet1")
        If IsArray(arr) Then
            For i = 0 To (UBound(arr) - LBound(arr))
                .Cells(therow + i, updatecol).Value = WorksheetFunction.Max(0, .Cells(therow + i, thecol).Value * .Range("slope").Value + .Range("intercept").Value) / .Cells(therow + i, thecol).Value
            Next i
        Else
            .Cells(therow, updatecol).Value = WorksheetFunction.Max(0, .Cells(therow, thecol).Value * .Range("slope").Value + .Range("intercept").Value) / .Cells(therow, thecol).Value
        End If
    End With

    Application.EnableEvents = True
End Sub
</code>```

Module2:

```<code>Sub HoursUpdate(ByVal arr As Variant, ByVal therow As Long, ByVal thecol As Long)
    Dim updatecol As Long
    Dim i As Integer

    updatecol = Sheets("Sheet1").ListObjects("Table1").ListColumns("Hours").Range.Column

    Application.EnableEvents = False
    With ActiveWorkbook.Worksheets("Sheet1")
        If IsArray(arr) Then
            For i = 0 To (UBound(arr) - LBound(arr))
                .Cells(therow + i, updatecol).Value = -.Range("intercept").Value / (.Range("slope").Value - .Cells(therow + i, thecol).Value)
            Next i
        Else
            .Cells(therow, updatecol).Value = -.Range("intercept").Value / (.Range("slope").Value - .Cells(therow, thecol).Value)
        End If
    End With

    Application.EnableEvents = True

End Sub
</code>```

How can I make this work for all rows in the table?

Done!

Do I have to define the cells by Row # and Column Letter, or can I
define by table name and row header?

Defined by table name and headers

What if the end user pastes a value in both J and K by mistake?

This code will do nothing.  Values will be pasted without alteration.  The previous values are stored in an array, so the potential would be to add to this code to restore the previous values and generate an error message

What if the end user pastes over multiple rows in J or K, updating
multiple weeks simultaneously?

Works fine!

Can I change the references to M and B to something named, perhaps in
a hidden sheet?

Changed the cell names, now they can move around the sheet.  Some minor modifications would need to be made to move to another sheet.

Body:
I'm new to VBA and perusing YouTube and StackOverflow to figure somethings out.

What I have here is a table for Hours and Overtime % by week.  Overtime % is determined by the formula OT% = MAX(0,(Hours1.05-35)/Hours)

I want users of my model to be able to change Hours OR OT, and the the other value to recalculate.  I can do with for the first row with the following

Sheet1 Code

Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Address = "$J$2" Or Target.Address = "$K$2" Then
        Call cellUpdate(Target.Address)
    End If
End Sub

Module:

Sub cellUpdate(Target As String)
Application.EnableEvents = False
    With ActiveWorkbook.Worksheets("Sheet1")
        If Target = "$J$2" Then
            .Range("$K$2").Value = WorksheetFunction.Max(0, .Range("$J$2").Value * .Range("$G$2").Value + .Range("$G$3").Value) / .Range("$J$2").Value
        ElseIf Target = "$K$2" Then
            .Range("$J$2").Value = -.Range("$G$3").Value / (.Range("$G$2").Value - .Range("$K$2").Value)
        End If
    End With
Application.EnableEvents = True
End Sub

This works great.  If I change J2, K2 updates.  If I change K2, J2 updates.

My questions:

How can I make this work for all rows in the table?

Do I have to define the cells by Row # and Column Letter, or can I define by table name and row header?

What if the end user pastes a value in both J and K by mistake?

What if the end user pastes over multiple rows in J or K, updating multiple weeks simultaneously?

Can I change the references to M and B to something named, perhaps in a hidden sheet?

Thank you in advance for the assistance.

*this exact formula is made up, but for groups of employees (Hrs-40)/Hrs is not accurate since not everyone works 40 hours.

Body:
Okay, this is probably not the best solution but it is what I have managed to learn.

Worksheet Code:

Dim UpdateOT As Boolean
Dim oldarr As Variant
Dim newarr As Variant

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim therow As Long
    Dim thecol As Long

    therow = Target.Row
    thecol = Target.Column

    newarr = Target

    If UpdateOT = True And Sheets("Sheet1").ListObjects("Table1").ListColumns("Hours").Range.Column = Target.Column Then
        Call OTUpdate(newarr, therow, thecol)
    ElseIf UpdateOT = True And Sheets("Sheet1").ListObjects("Table1").ListColumns("OT%").Range.Column = Target.Column Then
        Call HoursUpdate(newarr, therow, thecol)
    End If
End Sub

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    Dim colcount As Long

    UpdateOT = False
    oldarr = Target
    colcount = Target.Columns.Count

    If Target.Columns.Count = 1 And (Sheets("Sheet1").ListObjects("Table1").ListColumns("Hours").Range.Column = Target.Column Or Sheets("Sheet1").ListObjects("Table1").ListColumns("OT%").Range.Column = Target.Column) And Target.Row > Sheets("Sheet1").ListObjects("Table1").HeaderRowRange.Row Then
        UpdateOT = True
    End If
End Sub

Module1:

Sub OTUpdate(ByVal arr As Variant, ByVal therow As Long, ByVal thecol As Long)
    Dim updatecol As Long
    Dim i As Integer

    updatecol = Sheets("Sheet1").ListObjects("Table1").ListColumns("OT%").Range.Column

    Application.EnableEvents = False
    With ActiveWorkbook.Worksheets("Sheet1")
        If IsArray(arr) Then
            For i = 0 To (UBound(arr) - LBound(arr))
                .Cells(therow + i, updatecol).Value = WorksheetFunction.Max(0, .Cells(therow + i, thecol).Value * .Range("slope").Value + .Range("intercept").Value) / .Cells(therow + i, thecol).Value
            Next i
        Else
            .Cells(therow, updatecol).Value = WorksheetFunction.Max(0, .Cells(therow, thecol).Value * .Range("slope").Value + .Range("intercept").Value) / .Cells(therow, thecol).Value
        End If
    End With

    Application.EnableEvents = True
End Sub

Module2:

Sub HoursUpdate(ByVal arr As Variant, ByVal therow As Long, ByVal thecol As Long)
    Dim updatecol As Long
    Dim i As Integer

    updatecol = Sheets("Sheet1").ListObjects("Table1").ListColumns("Hours").Range.Column

    Application.EnableEvents = False
    With ActiveWorkbook.Worksheets("Sheet1")
        If IsArray(arr) Then
            For i = 0 To (UBound(arr) - LBound(arr))
                .Cells(therow + i, updatecol).Value = -.Range("intercept").Value / (.Range("slope").Value - .Cells(therow + i, thecol).Value)
            Next i
        Else
            .Cells(therow, updatecol).Value = -.Range("intercept").Value / (.Range("slope").Value - .Cells(therow, thecol).Value)
        End If
    End With

    Application.EnableEvents = True

End Sub

How can I make this work for all rows in the table?

Done!

Do I have to define the cells by Row # and Column Letter, or can I
define by table name and row header?

Defined by table name and headers

What if the end user pastes a value in both J and K by mistake?

This code will do nothing.  Values will be pasted without alteration.  The previous values are stored in an array, so the potential would be to add to this code to restore the previous values and generate an error message

What if the end user pastes over multiple rows in J or K, updating
multiple weeks simultaneously?

Works fine!

Can I change the references to M and B to something named, perhaps in
a hidden sheet?

Changed the cell names, now they can move around the sheet.  Some minor modifications would need to be made to move to another sheet.


问:
To implement HMAC-MD5 crypto algorithm in an Win32 application
I have a Win32 application that has to implement algorithm NTLM v2 Authentication in accordance to http://msdn.microsoft.com/en-us/library/cc236700(v=PROT.10).aspx. Partially, I need an implementation of crypto algorithm HMAC_MD5(). I see Win32 Crypto API contains function CryptCreateHash; but cannot understand: how to use it for the HMAC-MD5? Can someone explain me or give an example?</p>

答:
Generic example at http://msdn.microsoft.com/en-us/library/aa382379%28v=vs.85%29.aspx. You might want to replace the CALG_SHA1 with a CALG_MD5 to get the right algorithm.

Good luck with NTLM: hairy little beast that.


问:
Microsoft Team Webhook Integration in C#
I'm trying to develop a custom application that will integrate with Microsoft Teams. I need to fetch metadata (such as name, meeting id, time, etc.) from Microsoft Teams.

Any idea on how I can use webhooks?

Thank you in advance for your help.

答:
You can't get that kind of data from a webhook, your better bet is the Microsoft Graph API. The Graph API covers a large part of the Microsoft 365 products, not just Teams, so you need to find the operations you specifically want, but this is a good starting point: https://learn.microsoft.com/en-us/graph/api/resources/teams-api-overview?view=graph-rest-1.0

In order to work with Graph though, you need to understand a bit about how it works, especially with regards permissions and authorisation. This should help: https://learn.microsoft.com/en-us/graph/auth/?context=graph%2Fapi%2F1.0&view=graph-rest-1.0


问:
NiFi - How can i change ReplacementValue on ReplaceText?
I'm using ExecuteSQL,SplitAvro,ConvertAvroToJSON,EvaluateJsonPath,ReplaceText,ExecuteSQL.

I am trying to replace the content in the flowfile using replaceText processor.

Now, i can replace like this. -> INSERT INTO values (${id},'${name}') . ReplaceText process send excute sql like this :

INSERT into x values(1,'xx')

INSERT into x values(2,'yy')

INSERT into x values(3,'zz')

I'm sending INSERT query for each line.

But i want to send executesql process like this

INSERT INTO x values (1,'xx'),(2,'yy'),(3,'zz')

答:
Although it won't generate exactly the SQL you're looking for, take a look at ConvertRecord and/or JoltTransformRecord -> PutDatabaseRecord. The former is used to get each of your Avro records into the form you want (id, name), and PutDatabaseRecord will use a PreparedStatement in batches to send the records to the database. It might not be quite as efficient as a single INSERT, but should be much more efficient than a Split -> Convert -> ExecuteSQL with separate INSERTs per FlowFile.

To truly get the SQL you want, you'll likely need a scripted processor such as InvokeScriptedProcessor with a RecordReader, I have a blog post on the subject.