问:
NameError uninitialized constant Worker - (production only) But others workers process with no error
I'm getting an NameError uninitialized constant error on production.  The call to the worker is in a name spaced controller (controllers/api/mobile).

However, I have a separate worker that has no issues on production and doesn't raise this error.

I have two workers:

app/workers/ExtractionWorker

app/workers/CopyWasabiObject

I have two controllers:

app/controllers/photos_controller.rb
app/controllers/api/mobile/photos_controller.rb

The non name spaced controller makes a call to ExtractionWorker with no problems and performs the work and doesn't raise this error.

When an API request is sent to the api/mobile/photos_controller.rb, I get the following error:

NameError: uninitialized constant CopyWasabiObject

From the command line on production, I can instantiate the class with no issue

```<code>Loading production environment (Rails 6.0.2.1)
irb(main):001:0> CopyWasabiObject.new
=> #<CopyWasabiObject:0x0000557aa6e262f8>
</code>```

app/controllers/photos_controller.rb

```<code>if @photo.save
  ExtractionWorker.perform_async(wasabi_path(folder.uuid, photo_params[:name]), @photo.id)
  ...
end
</code>```

works as expected

app/controllers/api/mobile/photos_controller.rb

```<code>def update
  ...
  CopyWasabiObject.perform_async(@photo.uuid, raw_folder_uuid) if @photo.update!(merged_params)
end
</code>```

works on dev but fails on production

Why does one worker work, while the other fails to load?  I haven't touched auto loading in config/application.rb.  Every file is under app/* and I am not using anything at the root like lib.

What I have tried recently and doesn't work.

I tried name spacing the works to match the paths.  IE:  workers/api/mobile
I tried moving all works into app/models/
I have changed the calls in the controllers to call class methods which then call the worker

No matter what I seem to try, I just get the NameError: uninitialized constant CopyWasabiObject

Any help would be appreciated!

答: I think something is wrong with my systemd configuration.  I don't think sidekiq is being restarted on deploys.  I restarted sidekiq and everything was fine.  </p>

Body:
I'm getting an NameError uninitialized constant error on production.  The call to the worker is in a name spaced controller (controllers/api/mobile).

However, I have a separate worker that has no issues on production and doesn't raise this error.

I have two workers:

app/workers/ExtractionWorker

app/workers/CopyWasabiObject

I have two controllers:

app/controllers/photos_controller.rb
app/controllers/api/mobile/photos_controller.rb

The non name spaced controller makes a call to ExtractionWorker with no problems and performs the work and doesn't raise this error.

When an API request is sent to the api/mobile/photos_controller.rb, I get the following error:

NameError: uninitialized constant CopyWasabiObject

From the command line on production, I can instantiate the class with no issue

Loading production environment (Rails 6.0.2.1)
irb(main):001:0> CopyWasabiObject.new
=> #<CopyWasabiObject:0x0000557aa6e262f8>

app/controllers/photos_controller.rb

if @photo.save
  ExtractionWorker.perform_async(wasabi_path(folder.uuid, photo_params[:name]), @photo.id)
  ...
end

works as expected

app/controllers/api/mobile/photos_controller.rb

def update
  ...
  CopyWasabiObject.perform_async(@photo.uuid, raw_folder_uuid) if @photo.update!(merged_params)
end

works on dev but fails on production

Why does one worker work, while the other fails to load?  I haven't touched auto loading in config/application.rb.  Every file is under app/* and I am not using anything at the root like lib.

What I have tried recently and doesn't work.

I tried name spacing the works to match the paths.  IE:  workers/api/mobile
I tried moving all works into app/models/
I have changed the calls in the controllers to call class methods which then call the worker

No matter what I seem to try, I just get the NameError: uninitialized constant CopyWasabiObject

Any help would be appreciated!


来源: stackexchange

问:
Which documentations / pdfs are worth printing for reference as programmer
I have just printed and binded Advanced Bash Scripting guide . it had 800 pages.
and It was really worth of that.

Are there more like that which are worth to be printed and binded to keep aside ofr reference

答:
If you are very new to a programming language, I don't have a tutorial for you. But what is always handy, when you are programming in a certain language, is a cheat sheet. This site has many cheat sheets for each programming language:
http://www.cheat-sheets.org/

You should check it out.

ContentLicense: CC BY-SA 3.0


问:
Docker container will automatically stop after "docker run -d"
According to tutorial I read so far, use "docker run -d" will start a container from image, and the container will run in background. This is how it looks like, we can see we already have container id.

```<code>root@docker:/home/root# docker run -d centos
605e3928cdddb844526bab691af51d0c9262e0a1fc3d41de3f59be1a58e1bd1d
</code>```

But if I ran "docker ps", nothing was returned.

So I tried "docker ps -a", I can see container already exited:

```<code>root@docker:/home/root# docker ps -a
CONTAINER ID        IMAGE                 COMMAND             CREATED             STATUS                         PORTS               NAMES
605e3928cddd        centos:latest         "/bin/bash"         31 minutes ago      Exited (0) 31 minutes ago                          kickass_swartz
</code>```

Anything I did wrong? How can I troubleshoot this issue?

答: if you want to operate on the container, you need to run it in foreground to keep it alive.</p>

Body:
According to tutorial I read so far, use "docker run -d" will start a container from image, and the container will run in background. This is how it looks like, we can see we already have container id.

root@docker:/home/root# docker run -d centos
605e3928cdddb844526bab691af51d0c9262e0a1fc3d41de3f59be1a58e1bd1d

But if I ran "docker ps", nothing was returned.

So I tried "docker ps -a", I can see container already exited:

root@docker:/home/root# docker ps -a
CONTAINER ID        IMAGE                 COMMAND             CREATED             STATUS                         PORTS               NAMES
605e3928cddd        centos:latest         "/bin/bash"         31 minutes ago      Exited (0) 31 minutes ago                          kickass_swartz

Anything I did wrong? How can I troubleshoot this issue?

ContentLicense: CC BY-SA 4.0


问:
How to configure multiple HttpClient instances with different configurations in Blazor WebAssembly
I'm trying to configure multiple API urls in the Program.cs class in Blazor WASM. I'm not seeing an AddHttpClient extension like in server-side. Was wondering if anyone had an alternate solution for this?

Here's what I have so far:

```<code>var firstURI = new Uri("https://localhost:44340/");
var secondURI = new Uri("https://localhost:5001/");

void RegisterTypedClient<TClient, TImplementation>(Uri apiBaseUrl)
   where TClient : class where TImplementation : class, TClient
{
   builder.Services.AddHttpClient<TClient, TImplementation>(client =>
   {
       client.BaseAddress = apiBaseUrl;
   });
}

// HTTP services
RegisterTypedClient<IFirstService, FirstService>(firstURI);
RegisterTypedClient<ISecondService, SecondService>(secondURI);
</code>```

答:
This can be done with Blazor Client Side. First, in your client-side package, get the following nuget package: Microsoft.Extensions.Http

Then, create two classes for this example (normally you would use an interface, but a class  on its own should work here. I am going to demonstrate two different base addresses being used so you know there is a difference.

```<code>   public class GoogleService
    {
        private readonly HttpClient httpClient;

        public GoogleService(HttpClient httpClient)
        {
            this.httpClient = httpClient;
        }

        public string GetBaseUrl()
        {
            return httpClient.BaseAddress.ToString();
        }
    }
</code>```

And the Yahoo Service:

```<code>  public class YahooService
    {
        private readonly HttpClient httpClient;

        public YahooService(HttpClient httpClient)
        {
            this.httpClient = httpClient;
        }

        public string GetBaseUrl()
        {
            return httpClient.BaseAddress.ToString();
        }
    }
</code>```

Next, in your Client Program's Program.cs, you can do something like the following:

```<code>public static async Task Main(string[] args)
        {
            var builder = WebAssemblyHostBuilder.CreateDefault(args);
            builder.RootComponents.Add<App>("app");

            builder.Services.AddHttpClient<GoogleService>(client =>
            {
                client.BaseAddress = new Uri("https://google.com/");
            });

            builder.Services.AddHttpClient<YahooService>(client =>
            {
                client.BaseAddress = new Uri("https://yahoo.com/");
            });

            await builder.Build().RunAsync();
        }
</code>```

Next, you can inject them into your front end like so, and see that they are indeed two different injected clients:

```<code>@page "/"
@inject BlazorHttpClientTest.Client.Clients.GoogleService googleService;
@inject BlazorHttpClientTest.Client.Clients.YahooService yahooService;

<h1>Hello, world!</h1>

<label>Google Address:</label><label>@googleAddress</label>
<label>Yahoo Address:</label><label>@yahooAddress</label>

@code{
    string googleAddress;
    string yahooAddress;

    protected override void OnInitialized()
    {
        base.OnInitialized();

        googleAddress = googleService.GetBaseUrl();
        yahooAddress = yahooService.GetBaseUrl();

    }
}
</code>```

And just like that, you should have it working:

Let me know if you need me to explain anything else more in depth, otherwise, mark as answered if it works for you.

Body:
I'm trying to configure multiple API urls in the Program.cs class in Blazor WASM. I'm not seeing an AddHttpClient extension like in server-side. Was wondering if anyone had an alternate solution for this?

Here's what I have so far:

var firstURI = new Uri("https://localhost:44340/");
var secondURI = new Uri("https://localhost:5001/");

void RegisterTypedClient<TClient, TImplementation>(Uri apiBaseUrl)
   where TClient : class where TImplementation : class, TClient
{
   builder.Services.AddHttpClient<TClient, TImplementation>(client =>
   {
       client.BaseAddress = apiBaseUrl;
   });
}

// HTTP services
RegisterTypedClient<IFirstService, FirstService>(firstURI);
RegisterTypedClient<ISecondService, SecondService>(secondURI);

Body:
This can be done with Blazor Client Side. First, in your client-side package, get the following nuget package: Microsoft.Extensions.Http

Then, create two classes for this example (normally you would use an interface, but a class  on its own should work here. I am going to demonstrate two different base addresses being used so you know there is a difference.

   public class GoogleService
    {
        private readonly HttpClient httpClient;

        public GoogleService(HttpClient httpClient)
        {
            this.httpClient = httpClient;
        }

        public string GetBaseUrl()
        {
            return httpClient.BaseAddress.ToString();
        }
    }

And the Yahoo Service:

  public class YahooService
    {
        private readonly HttpClient httpClient;

        public YahooService(HttpClient httpClient)
        {
            this.httpClient = httpClient;
        }

        public string GetBaseUrl()
        {
            return httpClient.BaseAddress.ToString();
        }
    }

Next, in your Client Program's Program.cs, you can do something like the following:

public static async Task Main(string[] args)
        {
            var builder = WebAssemblyHostBuilder.CreateDefault(args);
            builder.RootComponents.Add<App>("app");

            builder.Services.AddHttpClient<GoogleService>(client =>
            {
                client.BaseAddress = new Uri("https://google.com/");
            });

            builder.Services.AddHttpClient<YahooService>(client =>
            {
                client.BaseAddress = new Uri("https://yahoo.com/");
            });

            await builder.Build().RunAsync();
        }

Next, you can inject them into your front end like so, and see that they are indeed two different injected clients:

@page "/"
@inject BlazorHttpClientTest.Client.Clients.GoogleService googleService;
@inject BlazorHttpClientTest.Client.Clients.YahooService yahooService;

<h1>Hello, world!</h1>

<label>Google Address:</label><label>@googleAddress</label>
<label>Yahoo Address:</label><label>@yahooAddress</label>

@code{
    string googleAddress;
    string yahooAddress;

    protected override void OnInitialized()
    {
        base.OnInitialized();

        googleAddress = googleService.GetBaseUrl();
        yahooAddress = yahooService.GetBaseUrl();

    }
}

And just like that, you should have it working:

Let me know if you need me to explain anything else more in depth, otherwise, mark as answered if it works for you.


问:
Binding a list of uris to collection view of images
I have a list of object data for images that I am retrieving from the backend.

The response has a format similar to this: images = {[0]:{AbsoluteUri: "https://foo.bar/image.jpg"}, [1]:{AbsoluteUri: "https://foo.bar/image-banana.jpg"}

Where images has a collection of images with image property data.

I set this two properties:

```<code>        public ObservableCollection<Uri> ImagesList
        {
            get => imagesList;
            set
            {
                if (imagesList == value)
                    return;

                imagesList = value;
                OnPropertyChanged(nameof(ImagesList));
            }
        }
</code>```

I have this snippet:

```<code>var images = await FetchMediaService.CallImagesEndpoint();
ImagesList = images;
</code>```

which sets the data coming from the backend to the ImagesList property.

But I'm confused on how the XAML binding works here:

```<code><Grid x:Name="layout">
        <CollectionView x:Name="cv" BackgroundColor="LightGray" ItemsSource="{Binding ImagesList}">
            <CollectionView.ItemsLayout>
                <LinearItemsLayout
                    SnapPointsAlignment="Start"
                    SnapPointsType="MandatorySingle"
                    Orientation="Horizontal"
                    ItemSpacing="{Binding Source={x:Reference mainPage}, Path=HingeWidth}" />
            </CollectionView.ItemsLayout>
            <CollectionView.ItemTemplate>
                <DataTemplate>
                    <Frame BackgroundColor="LightGray" Padding="0" Margin="0"
                           WidthRequest="{Binding Source={x:Reference mainPage}, Path=ContentWidth}"
                           HeightRequest="{Binding Source={x:Reference mainPage}, Path=ContentHeight}">
                        <Frame Margin="20" BackgroundColor="White">
                          <Image
                                   Source="{Binding AbsoluteUri}" //What should this bind to?
                                   Aspect="AspectFill" />
                        </Frame>
                    </Frame>
                </DataTemplate>
            </CollectionView.ItemTemplate>
        </CollectionView>
    </Grid>
</code>```

I added ImagesList to ItemsSource of CollectionView but I'm not positive to how set the individual uri I get back from the server on each image in the collection. How do I properly set the ImageUri?

答:
Firstly, we need to generate the C#.net class for JSON response string,

```<code> public class imageurl
{
    public string AbsoluteUri { get; set; }
}
</code>```

Secondly, installing "Newtonsoft.Json" by Nuget package to parse JSON string,

Finally, write below code to parse above JSON response.

```<code>   public async void GetJSON()
    {
        var response = await client.GetAsync("REPLACE YOUR JSON URL");
        string stringJson = await response.Content.ReadAsStringAsync();

        urls= JsonConvert.DeserializeObject<List<imageurl>>(stringJson);
    }
</code>```

The entire code here.

```<code>public partial class Page21 : ContentPage, INotifyPropertyChanged
{
    private List<imageurl> _urls;

    public List<imageurl> urls
    {
        get { return _urls; }
        set
        {
            _urls = value;
            RaisePropertyChanged("urls");

        }
    }

    public Page21()
    {
        InitializeComponent();

        urls = new List<imageurl>();

        GetJSON();

        this.BindingContext = this;
    }

    public async void GetJSON()
    {
        var response = await client.GetAsync("REPLACE YOUR JSON URL");
        string stringJson = await response.Content.ReadAsStringAsync();

        urls= JsonConvert.DeserializeObject<List<imageurl>>(stringJson);
    }

    public event PropertyChangedEventHandler PropertyChanged;
    public void RaisePropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}
public class imageurl
{
    public string AbsoluteUri { get; set; }
}
</code>```

There is one article about this, you can take a look:

http://bsubramanyamraju.blogspot.com/2017/04/xamarinforms-consuming-rest-webserivce_17.html

Body:
I have a list of object data for images that I am retrieving from the backend.

The response has a format similar to this: images = {[0]:{AbsoluteUri: "https://foo.bar/image.jpg"}, [1]:{AbsoluteUri: "https://foo.bar/image-banana.jpg"}

Where images has a collection of images with image property data.

I set this two properties:

        public ObservableCollection<Uri> ImagesList
        {
            get => imagesList;
            set
            {
                if (imagesList == value)
                    return;

                imagesList = value;
                OnPropertyChanged(nameof(ImagesList));
            }
        }

I have this snippet:

var images = await FetchMediaService.CallImagesEndpoint();
ImagesList = images;

which sets the data coming from the backend to the ImagesList property.

But I'm confused on how the XAML binding works here:

<Grid x:Name="layout">
        <CollectionView x:Name="cv" BackgroundColor="LightGray" ItemsSource="{Binding ImagesList}">
            <CollectionView.ItemsLayout>
                <LinearItemsLayout
                    SnapPointsAlignment="Start"
                    SnapPointsType="MandatorySingle"
                    Orientation="Horizontal"
                    ItemSpacing="{Binding Source={x:Reference mainPage}, Path=HingeWidth}" />
            </CollectionView.ItemsLayout>
            <CollectionView.ItemTemplate>
                <DataTemplate>
                    <Frame BackgroundColor="LightGray" Padding="0" Margin="0"
                           WidthRequest="{Binding Source={x:Reference mainPage}, Path=ContentWidth}"
                           HeightRequest="{Binding Source={x:Reference mainPage}, Path=ContentHeight}">
                        <Frame Margin="20" BackgroundColor="White">
                          <Image
                                   Source="{Binding AbsoluteUri}" //What should this bind to?
                                   Aspect="AspectFill" />
                        </Frame>
                    </Frame>
                </DataTemplate>
            </CollectionView.ItemTemplate>
        </CollectionView>
    </Grid>

I added ImagesList to ItemsSource of CollectionView but I'm not positive to how set the individual uri I get back from the server on each image in the collection. How do I properly set the ImageUri?

Body:
Firstly, we need to generate the C#.net class for JSON response string,

 public class imageurl
{
    public string AbsoluteUri { get; set; }
}

Secondly, installing "Newtonsoft.Json" by Nuget package to parse JSON string,

Finally, write below code to parse above JSON response.

   public async void GetJSON()
    {
        var response = await client.GetAsync("REPLACE YOUR JSON URL");
        string stringJson = await response.Content.ReadAsStringAsync();

        urls= JsonConvert.DeserializeObject<List<imageurl>>(stringJson);
    }

The entire code here.

public partial class Page21 : ContentPage, INotifyPropertyChanged
{
    private List<imageurl> _urls;

    public List<imageurl> urls
    {
        get { return _urls; }
        set
        {
            _urls = value;
            RaisePropertyChanged("urls");

        }
    }

    public Page21()
    {
        InitializeComponent();

        urls = new List<imageurl>();

        GetJSON();

        this.BindingContext = this;
    }

    public async void GetJSON()
    {
        var response = await client.GetAsync("REPLACE YOUR JSON URL");
        string stringJson = await response.Content.ReadAsStringAsync();

        urls= JsonConvert.DeserializeObject<List<imageurl>>(stringJson);
    }

    public event PropertyChangedEventHandler PropertyChanged;
    public void RaisePropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}
public class imageurl
{
    public string AbsoluteUri { get; set; }
}

There is one article about this, you can take a look:

http://bsubramanyamraju.blogspot.com/2017/04/xamarinforms-consuming-rest-webserivce_17.html


问:
Using AND OR within a IF statement of a two dimensional array in order sum the value of a row
I would like to sum the value of the first row of a 4x5 two dimensional array and put into the int variable rowTotal1.  Each object within the array has both a value and a name. If the sum of values exceeds 21 for the row AND if any of the cells within the row have any of these four names ("AA", "AB", "AC", "AD"), I'd like like to subtract 10 from the total row sum.  Below is what I have so far but it is not able to subtract 10 under the right circumstances

```<code>    for(int i=0; i<5; i++) {
        rowTotal1 += square[0][i].value;
            if(rowTotal1 > 22 && square[0][i].name == "AA" ||
                                 square[0][i].name == "AB" ||
                                 square[0][i].name == "AC" ||
                                 square[0][i].name == "AD") {
                rowTotal1 += square[0][i].value - 10;
            }
    }
</code>```

答:
Do you mean:</p>

```<code>let rowTotal1 = 0;
let hasSpecialNames = false;

for(int i=0; i<5; i++) {
  rowTotal1 += square[0][i].value;

  if (square[0][i].name == "AA" ||
                       square[0][i].name == "AB" ||
                       square[0][i].name == "AC" ||
                       square[0][i].name == "AD") {
    hasSpecialNames = true;
  }
}

if(rowTotal1 > 21 || hasSpecialNames) {
  rowTotal1 = rowTotal1 - 10;
}
</code>```

Body:
I would like to sum the value of the first row of a 4x5 two dimensional array and put into the int variable rowTotal1.  Each object within the array has both a value and a name. If the sum of values exceeds 21 for the row AND if any of the cells within the row have any of these four names ("AA", "AB", "AC", "AD"), I'd like like to subtract 10 from the total row sum.  Below is what I have so far but it is not able to subtract 10 under the right circumstances

    for(int i=0; i<5; i++) {
        rowTotal1 += square[0][i].value;
            if(rowTotal1 > 22 && square[0][i].name == "AA" ||
                                 square[0][i].name == "AB" ||
                                 square[0][i].name == "AC" ||
                                 square[0][i].name == "AD") {
                rowTotal1 += square[0][i].value - 10;
            }
    }

Body:
Do you mean:

let rowTotal1 = 0;
let hasSpecialNames = false;

for(int i=0; i<5; i++) {
  rowTotal1 += square[0][i].value;

  if (square[0][i].name == "AA" ||
                       square[0][i].name == "AB" ||
                       square[0][i].name == "AC" ||
                       square[0][i].name == "AD") {
    hasSpecialNames = true;
  }
}

if(rowTotal1 > 21 || hasSpecialNames) {
  rowTotal1 = rowTotal1 - 10;
}


问:
Tensorflow2.0 MultiWorkerMirroredStrategy example hangs
I followed the example from official tensorflow website.

https://www.tensorflow.org/tutorials/distribute/multi_worker_with_keras

Here is my spec

WSL

Ubuntu 16.04.6 LTS

Tensorflow2.0

No-GPU available

I have a file called 'tfexample.py' which looks like this

from __future__ import absolute_import, division, print_function, unicode_literals
import tensorflow_datasets as tfds
import tensorflow as tf
import json, os

tfds.disable_progress_bar()

os.environ["TF_CONFIG"] = json.dumps(
    {
        "cluster": {"worker": ["localhost:12345", "localhost:23456"]},
        "task": {"type": "worker", "index": 0},
    }
)
strategy = tf.distribute.experimental.MultiWorkerMirroredStrategy()
BUFFER_SIZE = 10000
BATCH_SIZE = 64

def make_datasets_unbatched():
    # Scaling MNIST data from (0, 255] to (0., 1.]
    def scale(image, label):
        image = tf.cast(image, tf.float32)
        image /= 255
        return image, label

    datasets, info = tfds.load(name="mnist", with_info=True, as_supervised=True)

    return datasets["train"].map(scale).cache().shuffle(BUFFER_SIZE)

train_datasets = make_datasets_unbatched().batch(BATCH_SIZE)

def build_and_compile_cnn_model():
    model = tf.keras.Sequential(
        [
            tf.keras.layers.Conv2D(32, 3, activation="relu", input_shape=(28, 28, 1)),
            tf.keras.layers.MaxPooling2D(),
            tf.keras.layers.Flatten(),
            tf.keras.layers.Dense(64, activation="relu"),
            tf.keras.layers.Dense(10, activation="softmax"),
        ]
    )
    model.compile(
        loss=tf.keras.losses.sparse_categorical_crossentropy,
        optimizer=tf.keras.optimizers.SGD(learning_rate=0.001),
        metrics=["accuracy"],
    )
    return model

# single_worker_model = build_and_compile_cnn_model()
# single_worker_model.fit(x=train_datasets, epochs=3, steps_per_epoch=5)

NUM_WORKERS = 2
# Here the batch size scales up by number of workers since
# `tf.data.Dataset.batch` expects the global batch size. Previously we used 64,
# and now this becomes 128.
GLOBAL_BATCH_SIZE = 64 * NUM_WORKERS
with strategy.scope():
    # Creation of dataset, and model building/compiling need to be within
    # `strategy.scope()`.
    train_datasets = make_datasets_unbatched().batch(GLOBAL_BATCH_SIZE)
    multi_worker_model = build_and_compile_cnn_model()

# Keras' `model.fit()` trains the model with specified number of epochs and
# number of steps per epoch. Note that the numbers here are for demonstration
# purposes only and may not sufficiently produce a model with good quality.
multi_worker_model.fit(x=train_datasets, epochs=3, steps_per_epoch=5)
```

<p>When I run this file with </p>

```python tfexample.py
```

<p>The terminal just hangs like below</p>

```2020-02-04 17:50:23.483411: W tensorflow/stream_executor/platform/default/dso_loader.cc:55] Could not load dynamic library 'libnvinfer.so.6'; dlerror: libnvinfer.so.6: cannot open shared object file: No such file or directory
2020-02-04 17:50:23.485194: W tensorflow/stream_executor/platform/default/dso_loader.cc:55] Could not load dynamic library 'libnvinfer_plugin.so.6'; dlerror: libnvinfer_plugin.so.6: cannot open shared object file: No such file or directory
2020-02-04 17:50:23.485747: W tensorflow/compiler/tf2tensorrt/utils/py_utils.cc:30] Cannot dlopen some TensorRT libraries. If you would like to use Nvidia GPU with TensorRT, please make sure the missing libraries mentioned above are installed properly.
/home/danny/.local/lib/python2.7/site-packages/requests/__init__.py:83: RequestsDependencyWarning: Old version of cryptography ([1, 2, 3]) may cause slowdown.
  warnings.warn(warning, RequestsDependencyWarning)
2020-02-04 17:50:29.013263: W tensorflow/stream_executor/platform/default/dso_loader.cc:55] Could not load dynamic library 'libcuda.so.1'; dlerror: libcuda.so.1: cannot open shared object file: No such file or directory
2020-02-04 17:50:29.014152: E tensorflow/stream_executor/cuda/cuda_driver.cc:351] failed call to cuInit: UNKNOWN ERROR (303)
2020-02-04 17:50:29.014781: I tensorflow/stream_executor/cuda/cuda_diagnostics.cc:156] kernel driver does not appear to be running on this host (WINDOWS-6DFFM0Q): /proc/driver/nvidia/version does not exist
2020-02-04 17:50:29.015780: I tensorflow/core/platform/cpu_feature_guard.cc:142] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2 FMA
2020-02-04 17:50:29.025575: I tensorflow/core/platform/profile_utils/cpu_utils.cc:94] CPU Frequency: 2701000000 Hz
2020-02-04 17:50:29.027050: I tensorflow/compiler/xla/service/service.cc:168] XLA service 0x66b11a0 initialized for platform Host (this does not guarantee that XLA will be used). Devices:
2020-02-04 17:50:29.027669: I tensorflow/compiler/xla/service/service.cc:176]   StreamExecutor device (0): Host, Default Version
E0204 17:50:29.038614800   24084 socket_utils_common_posix.cc:198] check for SO_REUSEPORT: {"created":"@1580856629.038575000","description":"Protocol not available","errno":92,"file":"external/grpc/src/core/lib/iomgr/socket_utils_common_posix.cc","file_line":175,"os_error":"Protocol not available","syscall":"getsockopt(SO_REUSEPORT)"}
E0204 17:50:29.039313500   24084 socket_utils_common_posix.cc:299] setsockopt(TCP_USER_TIMEOUT) Protocol not available
2020-02-04 17:50:29.051180: I tensorflow/core/distributed_runtime/rpc/grpc_channel.cc:300] Initialize GrpcChannelCache for job worker -> {0 -> localhost:12345, 1 -> localhost:23456}
2020-02-04 17:50:29.053392: I tensorflow/core/distributed_runtime/rpc/grpc_server_lib.cc:390] Started server with target: grpc://localhost:12345
```

Any help will be appreciated!

答: Are you  running the tfexample.py on two sessions  with the  correct TFconfig. I haven't tried two instances on the same machine </p>

Body:
I followed the example from official tensorflow website.

https://www.tensorflow.org/tutorials/distribute/multi_worker_with_keras

Here is my spec

WSL

Ubuntu 16.04.6 LTS

Tensorflow2.0

No-GPU available

I have a file called 'tfexample.py' which looks like this

from __future__ import absolute_import, division, print_function, unicode_literals
import tensorflow_datasets as tfds
import tensorflow as tf
import json, os

tfds.disable_progress_bar()

os.environ["TF_CONFIG"] = json.dumps(
    {
        "cluster": {"worker": ["localhost:12345", "localhost:23456"]},
        "task": {"type": "worker", "index": 0},
    }
)
strategy = tf.distribute.experimental.MultiWorkerMirroredStrategy()
BUFFER_SIZE = 10000
BATCH_SIZE = 64

def make_datasets_unbatched():
    # Scaling MNIST data from (0, 255] to (0., 1.]
    def scale(image, label):
        image = tf.cast(image, tf.float32)
        image /= 255
        return image, label

    datasets, info = tfds.load(name="mnist", with_info=True, as_supervised=True)

    return datasets["train"].map(scale).cache().shuffle(BUFFER_SIZE)

train_datasets = make_datasets_unbatched().batch(BATCH_SIZE)

def build_and_compile_cnn_model():
    model = tf.keras.Sequential(
        [
            tf.keras.layers.Conv2D(32, 3, activation="relu", input_shape=(28, 28, 1)),
            tf.keras.layers.MaxPooling2D(),
            tf.keras.layers.Flatten(),
            tf.keras.layers.Dense(64, activation="relu"),
            tf.keras.layers.Dense(10, activation="softmax"),
        ]
    )
    model.compile(
        loss=tf.keras.losses.sparse_categorical_crossentropy,
        optimizer=tf.keras.optimizers.SGD(learning_rate=0.001),
        metrics=["accuracy"],
    )
    return model

# single_worker_model = build_and_compile_cnn_model()
# single_worker_model.fit(x=train_datasets, epochs=3, steps_per_epoch=5)

NUM_WORKERS = 2
# Here the batch size scales up by number of workers since
# `tf.data.Dataset.batch` expects the global batch size. Previously we used 64,
# and now this becomes 128.
GLOBAL_BATCH_SIZE = 64 * NUM_WORKERS
with strategy.scope():
    # Creation of dataset, and model building/compiling need to be within
    # `strategy.scope()`.
    train_datasets = make_datasets_unbatched().batch(GLOBAL_BATCH_SIZE)
    multi_worker_model = build_and_compile_cnn_model()

# Keras' `model.fit()` trains the model with specified number of epochs and
# number of steps per epoch. Note that the numbers here are for demonstration
# purposes only and may not sufficiently produce a model with good quality.
multi_worker_model.fit(x=train_datasets, epochs=3, steps_per_epoch=5)

When I run this file with

python tfexample.py

The terminal just hangs like below

2020-02-04 17:50:23.483411: W tensorflow/stream_executor/platform/default/dso_loader.cc:55] Could not load dynamic library 'libnvinfer.so.6'; dlerror: libnvinfer.so.6: cannot open shared object file: No such file or directory
2020-02-04 17:50:23.485194: W tensorflow/stream_executor/platform/default/dso_loader.cc:55] Could not load dynamic library 'libnvinfer_plugin.so.6'; dlerror: libnvinfer_plugin.so.6: cannot open shared object file: No such file or directory
2020-02-04 17:50:23.485747: W tensorflow/compiler/tf2tensorrt/utils/py_utils.cc:30] Cannot dlopen some TensorRT libraries. If you would like to use Nvidia GPU with TensorRT, please make sure the missing libraries mentioned above are installed properly.
/home/danny/.local/lib/python2.7/site-packages/requests/__init__.py:83: RequestsDependencyWarning: Old version of cryptography ([1, 2, 3]) may cause slowdown.
  warnings.warn(warning, RequestsDependencyWarning)
2020-02-04 17:50:29.013263: W tensorflow/stream_executor/platform/default/dso_loader.cc:55] Could not load dynamic library 'libcuda.so.1'; dlerror: libcuda.so.1: cannot open shared object file: No such file or directory
2020-02-04 17:50:29.014152: E tensorflow/stream_executor/cuda/cuda_driver.cc:351] failed call to cuInit: UNKNOWN ERROR (303)
2020-02-04 17:50:29.014781: I tensorflow/stream_executor/cuda/cuda_diagnostics.cc:156] kernel driver does not appear to be running on this host (WINDOWS-6DFFM0Q): /proc/driver/nvidia/version does not exist
2020-02-04 17:50:29.015780: I tensorflow/core/platform/cpu_feature_guard.cc:142] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2 FMA
2020-02-04 17:50:29.025575: I tensorflow/core/platform/profile_utils/cpu_utils.cc:94] CPU Frequency: 2701000000 Hz
2020-02-04 17:50:29.027050: I tensorflow/compiler/xla/service/service.cc:168] XLA service 0x66b11a0 initialized for platform Host (this does not guarantee that XLA will be used). Devices:
2020-02-04 17:50:29.027669: I tensorflow/compiler/xla/service/service.cc:176]   StreamExecutor device (0): Host, Default Version
E0204 17:50:29.038614800   24084 socket_utils_common_posix.cc:198] check for SO_REUSEPORT: {"created":"@1580856629.038575000","description":"Protocol not available","errno":92,"file":"external/grpc/src/core/lib/iomgr/socket_utils_common_posix.cc","file_line":175,"os_error":"Protocol not available","syscall":"getsockopt(SO_REUSEPORT)"}
E0204 17:50:29.039313500   24084 socket_utils_common_posix.cc:299] setsockopt(TCP_USER_TIMEOUT) Protocol not available
2020-02-04 17:50:29.051180: I tensorflow/core/distributed_runtime/rpc/grpc_channel.cc:300] Initialize GrpcChannelCache for job worker -> {0 -> localhost:12345, 1 -> localhost:23456}
2020-02-04 17:50:29.053392: I tensorflow/core/distributed_runtime/rpc/grpc_server_lib.cc:390] Started server with target: grpc://localhost:12345

Any help will be appreciated!


问:
How do I grant a user permissions to specific Azure services (as you can with AWS's IAM)?
I've tried reading different guides and documentation about Azure users and roles, but nothing looks similar to IAM on AWS.

Where I can limit users to use only certain services in the Azure console/portal?

Could someone provide me with a link to the relevant documentation or describe to be a way to do this (if it is possible to do)?

Thanks for everyone time by the way.

答:
Azure provides this functionality through Role Based Access Control (RBAC). Using RBAC, you can provide granular permissions to  users, groups or applications (also known as Service Principal) in your Azure AD. Azure provides a number of in-built roles that cover a variety of scenarios. It also provides you an ability to create custom roles if an in-built role does not suit your requirements.

You can learn more about RBAC here: https://learn.microsoft.com/en-us/azure/role-based-access-control/overview.

Azure Portal provides a comprehensive user experience for managing RBAC. You can learn more about it here: https://learn.microsoft.com/en-us/azure/role-based-access-control/quickstart-assign-role-user-portal.


问:
RGB to hex and hex to RGB
How to convert colors in RGB format to hex format and vice versa?

For example, convert '#0080C0' to (0, 128, 192).

答:
Fairly straightforward one liner. Splits the rgb by commas, ignores non numerics, converts to hex, pads a 0, and finishes off with a hashbang.

var yellow = 'rgb(255, 255, 0)';
var rgb2hex = str => "#"+str.split(',').map(s => (s.replace(/\D/g,'')|0).toString(16)).map(s => s.length < 2 ? "0"+s : s).join('');

console.log(rgb2hex(yellow));```

Title: RGB to hex and hex to RGB


答:
First,

values exceeds 21

but you write

```<code>if(rowTotal1 > 22...
</code>```

shouldn't it be rowTotal1 > 21?

About you question,

rowTotal1 += square[0][i].value - 10;

What is the value for square[0][i].value?

If you want to "subtract 10 from the row",

just rowTotal1 -= 10; should do it.

Title: Using AND OR within a IF statement of a two dimensional array in order sum the value of a row

Body:
First,

values exceeds 21

but you write

if(rowTotal1 > 22...

shouldn't it be rowTotal1 > 21?

About you question,

rowTotal1 += square[0][i].value - 10;

What is the value for square[0][i].value?

If you want to "subtract 10 from the row",

just rowTotal1 -= 10; should do it.


问:
Mysql support this kind of "with" sql?
In postgres, I use this kind of sql often.

```<code>with list (id, name) as (
    values
    (1004007, 'aaa'),
    (1002147, 'bbb'),
    (1004493, 'ccc'),
    (1007978, 'ddd'),
    (1005218, 'eee'),
    (1005507, 'fff')
)
select * from list;
</code>```

Dose Mysql support that kind of sql ?

答:
You can use select:

```<code>with list (id, name) as (
      select 1004007, 'aaa' union all
      select 1002147, 'bbb' union all
      select 1004493, 'ccc' union all
      select 1007978, 'ddd' union all
      select 1005218, 'eee' union all
      select 1005507, 'fff'
     )
select l.*
from list l;
</code>```

Here is a db<>fiddle.  Note:  This also works in Postgres.

Pre 8.0 versions of MySQL do not support with.  You can create a derived table:

```<code>select list.*
from (select 1004007, 'aaa' union all
      select 1002147, 'bbb' union all
      select 1004493, 'ccc' union all
      select 1007978, 'ddd' union all
      select 1005218, 'eee' union all
      select 1005507, 'fff'
     ) list;
</code>```

This can then be used just a like a table reference.

Title: Mysql support this kind of "with" sql?

Body:
In postgres, I use this kind of sql often.

with list (id, name) as (
    values
    (1004007, 'aaa'),
    (1002147, 'bbb'),
    (1004493, 'ccc'),
    (1007978, 'ddd'),
    (1005218, 'eee'),
    (1005507, 'fff')
)
select * from list;

Dose Mysql support that kind of sql ?

Body:
You can use select:

with list (id, name) as (
      select 1004007, 'aaa' union all
      select 1002147, 'bbb' union all
      select 1004493, 'ccc' union all
      select 1007978, 'ddd' union all
      select 1005218, 'eee' union all
      select 1005507, 'fff'
     )
select l.*
from list l;

Here is a db<>fiddle.  Note:  This also works in Postgres.

Pre 8.0 versions of MySQL do not support with.  You can create a derived table:

select list.*
from (select 1004007, 'aaa' union all
      select 1002147, 'bbb' union all
      select 1004493, 'ccc' union all
      select 1007978, 'ddd' union all
      select 1005218, 'eee' union all
      select 1005507, 'fff'
     ) list;

This can then be used just a like a table reference.


问:
store sql data in variables in nested if's
i have to use nested if/then/else statements to check the queries obtained from oracle db.
i am new to unix. from searching on google, i understand the procedure for storing sql data into variables. but when i have to use nested if statements, how can i do that?

i cannot connect to the database again and again for storing data into variables. can someone please help?

what i am writing here is teh code. excuse the wrong syntax. i am coming from coding for php

```<code>    LOGFILE = #enter path here

fetchdate = `sqlplus -s prmappo/prmappo@PRMDB << EOFSQL
select min(call_start_datetime) from error_repository;
exit;
EOFSQL`
if (( "${fetchdate:4:2}" == "02" ));
    then
    $query_1 = select * from error_repository_BKP partition(part_maxval);
    if (($query_1 == NULL));
    then
        $query_2 = "alter table error_repository_BKP
                        exchange partition part_maxval
                        with table error_repository
                        without validation;" >> $LOGFILE
    commit;
    fi

  $query_3 = "select * from error_repository;"
</code>```

Also, please tell me how do I read the SQL row data stored in the variables?

答:
If you want to use sqlplus for scripting, easiest is to spool the data in some separated format to a file and interpret the output from that file. You can assign the variables from the fields of the spool file.

Unless you are manipulating OS objects, it might be smarter to code completely in pl/sql. In that case you have full control and have no problems with assignments at all. If you are only manipulating Oracle objects, try pl/sql. This is a powerful programming language. Doing so also prevents lots of extra database connections. If you use 11g, you can also manipulate OS objects by using the remote job agent.

Use sqldeveloper to code and debug your code.download from here: Oracle SQL Developer

Body:
i have to use nested if/then/else statements to check the queries obtained from oracle db.
i am new to unix. from searching on google, i understand the procedure for storing sql data into variables. but when i have to use nested if statements, how can i do that?

i cannot connect to the database again and again for storing data into variables. can someone please help?

what i am writing here is teh code. excuse the wrong syntax. i am coming from coding for php

    LOGFILE = #enter path here

fetchdate = `sqlplus -s prmappo/prmappo@PRMDB << EOFSQL
select min(call_start_datetime) from error_repository;
exit;
EOFSQL`
if (( "${fetchdate:4:2}" == "02" ));
    then
    $query_1 = select * from error_repository_BKP partition(part_maxval);
    if (($query_1 == NULL));
    then
        $query_2 = "alter table error_repository_BKP
                        exchange partition part_maxval
                        with table error_repository
                        without validation;" >> $LOGFILE
    commit;
    fi

  $query_3 = "select * from error_repository;"

Also, please tell me how do I read the SQL row data stored in the variables?


问:
Postgres 9.6.17 and JDBC 42.2.1 how to switch connection mode to 'extended'
I have a Postgres 9.6.17 DBMS and a simple Java standalone program (no Spring) that connects to the DBMS and issues a query. Based on Postgres documentation a query can be executed in 'simple mode' or 'extended mode' (where parsing and query rewriting is done in once) but the binding happens repeatedly.

I have a simple table customer(cust_id integer, first_name varchar(100), last_name varchar(100)). The code I am executing is as follows:

```<code>Properties props = new Properties();
....//typical properties such as user, password, database etc
props.setProperty("preferQueryMode", "extendedForPrepared");
Connection con = DriverManager.getConnection(url, props);
PreparedStatement st = con.prepareStatement("select * from ecommerce.customer where cust_id = ?");
st.setInt(1, 22);
ResultSet rs = st.executeQuery();
</code>```

I was hoping that this would produce an 'extended query mode' protocol use between JDBC client and DBMS backend. But it keeps produced a 'simple query mode' interaction. I verified this by enabling JDBC logging for postgres driver. I also looked at the implementations of Query interface within JDBC driver and all I could find is 3 implementations as follows:

BatchedQuery

CompositeQuery

SimpleQuery

Despite the name CompositeQuery all it does is splits up a query involving multiple statements into a list of SimpleQuery objects.

So my question is what can I do to get the protocol used by my connection to an extended mode?

答:
By default, the Postgres JDBC driver will only start using server-side statements after a prepared statement is used 5 times.  From the JDBC driver property documentation:

prepareThreshold = int

Determine the number of PreparedStatement executions required before switching over to use server side prepared statements. The default is five, meaning start using server side prepared statements on the fifth execution of the same PreparedStatement object. More information on server side prepared statements is available in the section called “Server Prepared Statements”.

But that property can be changed.

This is the program I tested with:

```<code>Properties props = new Properties();
props.setProperty("user", "test");
props.setProperty("password", "test");
props.setProperty("loggerLevel", "TRACE");
props.setProperty("prepareThreshold", "1");
try (Connection con = DriverManager.getConnection("jdbc:postgresql:test", props);
     PreparedStatement stat = con.prepareStatement("select * from app_user where username = ?"))
{
    for (String username : List.of("user1", "user2", "user3"))
    {
        stat.setString(1, username);
        try (ResultSet rs = stat.executeQuery())
        {
            if (rs.next())
                System.out.println("User " + username + " has ID: " + rs.getString(1));
        }
    }
}
</code>```

When prepareThreshold is set to 1, the logs show:

```<code>Feb 18, 2020 1:56:59 PM org.postgresql.core.v3.QueryExecutorImpl execute
FINEST:   simple execute, handler=org.postgresql.jdbc.PgStatement$StatementResultHandler@33065d67, maxRows=0, fetchSize=0, flags=16
Feb 18, 2020 1:56:59 PM org.postgresql.core.v3.QueryExecutorImpl sendParse
FINEST:  FE=> Parse(stmt=S_1,query="select * from app_user where username = $1",oids={1043})
Feb 18, 2020 1:56:59 PM org.postgresql.core.v3.QueryExecutorImpl sendBind
FINEST:  FE=> Bind(stmt=S_1,portal=null,$1=<'user1'>)
Feb 18, 2020 1:56:59 PM org.postgresql.core.v3.QueryExecutorImpl sendDescribePortal
FINEST:  FE=> Describe(portal=null)
Feb 18, 2020 1:56:59 PM org.postgresql.core.v3.QueryExecutorImpl sendExecute
FINEST:  FE=> Execute(portal=null,limit=0)
...
Feb 18, 2020 1:56:59 PM org.postgresql.core.v3.QueryExecutorImpl execute
FINEST:   simple execute, handler=org.postgresql.jdbc.PgStatement$StatementResultHandler@35dab4eb, maxRows=0, fetchSize=0, flags=16
Feb 18, 2020 1:56:59 PM org.postgresql.core.v3.QueryExecutorImpl sendBind
FINEST:  FE=> Bind(stmt=S_1,portal=null,$1=<'user2'>)
Feb 18, 2020 1:56:59 PM org.postgresql.core.v3.QueryExecutorImpl sendExecute
FINEST:  FE=> Execute(portal=null,limit=0)
...
Feb 18, 2020 1:56:59 PM org.postgresql.core.v3.QueryExecutorImpl execute
FINEST:   simple execute, handler=org.postgresql.jdbc.PgStatement$StatementResultHandler@2d901eb0, maxRows=0, fetchSize=0, flags=16
Feb 18, 2020 1:56:59 PM org.postgresql.core.v3.QueryExecutorImpl sendBind
FINEST:  FE=> Bind(stmt=S_1,portal=null,$1=<'user3'>)
Feb 18, 2020 1:56:59 PM org.postgresql.core.v3.QueryExecutorImpl sendExecute
FINEST:  FE=> Execute(portal=null,limit=0)
</code>```

which show the query parse happens once, then there are repeated binds.

Compare this to when prepareThreshold is not set:

```<code>Feb 18, 2020 2:01:25 PM org.postgresql.core.v3.QueryExecutorImpl execute
FINEST:   simple execute, handler=org.postgresql.jdbc.PgStatement$StatementResultHandler@33065d67, maxRows=0, fetchSize=0, flags=17
Feb 18, 2020 2:01:25 PM org.postgresql.core.v3.QueryExecutorImpl sendParse
FINEST:  FE=> Parse(stmt=null,query="select * from app_user where username = $1",oids={1043})
Feb 18, 2020 2:01:25 PM org.postgresql.core.v3.QueryExecutorImpl sendBind
FINEST:  FE=> Bind(stmt=null,portal=null,$1=<'user1'>)
Feb 18, 2020 2:01:25 PM org.postgresql.core.v3.QueryExecutorImpl sendDescribePortal
FINEST:  FE=> Describe(portal=null)
Feb 18, 2020 2:01:25 PM org.postgresql.core.v3.QueryExecutorImpl sendExecute
FINEST:  FE=> Execute(portal=null,limit=0)
...
Feb 18, 2020 2:01:25 PM org.postgresql.core.v3.QueryExecutorImpl execute
FINEST:   simple execute, handler=org.postgresql.jdbc.PgStatement$StatementResultHandler@8519cb4, maxRows=0, fetchSize=0, flags=17
Feb 18, 2020 2:01:25 PM org.postgresql.core.v3.QueryExecutorImpl sendParse
FINEST:  FE=> Parse(stmt=null,query="select * from app_user where username = $1",oids={1043})
Feb 18, 2020 2:01:25 PM org.postgresql.core.v3.QueryExecutorImpl sendBind
FINEST:  FE=> Bind(stmt=null,portal=null,$1=<'user2'>)
Feb 18, 2020 2:01:25 PM org.postgresql.core.v3.QueryExecutorImpl sendDescribePortal
FINEST:  FE=> Describe(portal=null)
Feb 18, 2020 2:01:25 PM org.postgresql.core.v3.QueryExecutorImpl sendExecute
FINEST:  FE=> Execute(portal=null,limit=0)
...
Feb 18, 2020 2:01:25 PM org.postgresql.core.v3.QueryExecutorImpl execute
FINEST:   simple execute, handler=org.postgresql.jdbc.PgStatement$StatementResultHandler@35dab4eb, maxRows=0, fetchSize=0, flags=17
Feb 18, 2020 2:01:25 PM org.postgresql.core.v3.QueryExecutorImpl sendParse
FINEST:  FE=> Parse(stmt=null,query="select * from app_user where username = $1",oids={1043})
Feb 18, 2020 2:01:25 PM org.postgresql.core.v3.QueryExecutorImpl sendBind
FINEST:  FE=> Bind(stmt=null,portal=null,$1=<'user3'>)
Feb 18, 2020 2:01:25 PM org.postgresql.core.v3.QueryExecutorImpl sendDescribePortal
FINEST:  FE=> Describe(portal=null)
Feb 18, 2020 2:01:25 PM org.postgresql.core.v3.QueryExecutorImpl sendExecute
FINEST:  FE=> Execute(portal=null,limit=0)
</code>```

where there are 3 separate statement parses and binds.  After 5 queries they should start getting reused, however.

Regarding the query mode being 'simple' vs 'extended', it looks like the logs always print out 'simple execute' regardless, however the difference is that true simple mode the parameters will not be bound in prepared statement and instead the entire query will be sent as text.  In this example, if the preferQueryMode property is set to simple, the logs show:

```<code>Feb 18, 2020 2:06:19 PM org.postgresql.core.v3.QueryExecutorImpl execute
FINEST:   simple execute, handler=org.postgresql.jdbc.PgStatement$StatementResultHandler@33065d67, maxRows=0, fetchSize=0, flags=1,041
Feb 18, 2020 2:06:19 PM org.postgresql.core.v3.QueryExecutorImpl sendSimpleQuery
FINEST:  FE=> SimpleQuery(query="select * from app_user where username = 'user1'")
...
Feb 18, 2020 2:06:20 PM org.postgresql.core.v3.QueryExecutorImpl execute
FINEST:   simple execute, handler=org.postgresql.jdbc.PgStatement$StatementResultHandler@28261e8e, maxRows=0, fetchSize=0, flags=1,041
Feb 18, 2020 2:06:20 PM org.postgresql.core.v3.QueryExecutorImpl sendSimpleQuery
FINEST:  FE=> SimpleQuery(query="select * from app_user where username = 'user2'")
...
Feb 18, 2020 2:06:20 PM org.postgresql.core.v3.QueryExecutorImpl execute
FINEST:   simple execute, handler=org.postgresql.jdbc.PgStatement$StatementResultHandler@d737b89, maxRows=0, fetchSize=0, flags=1,041
Feb 18, 2020 2:06:20 PM org.postgresql.core.v3.QueryExecutorImpl sendSimpleQuery
FINEST:  FE=> SimpleQuery(query="select * from app_user where username = 'user3'")
</code>```

notice the difference between this and the default - there are no parameters and the 'user1', 'user2' and 'user3' values are being sent inline with each query.

I think what you are really looking for then is to re-use server-side statements immediately and rebind parameters.  In this case, setting prepareThreshold to 1 will do the job.

Body:
I have a Postgres 9.6.17 DBMS and a simple Java standalone program (no Spring) that connects to the DBMS and issues a query. Based on Postgres documentation a query can be executed in 'simple mode' or 'extended mode' (where parsing and query rewriting is done in once) but the binding happens repeatedly.

I have a simple table customer(cust_id integer, first_name varchar(100), last_name varchar(100)). The code I am executing is as follows:

Properties props = new Properties();
....//typical properties such as user, password, database etc
props.setProperty("preferQueryMode", "extendedForPrepared");
Connection con = DriverManager.getConnection(url, props);
PreparedStatement st = con.prepareStatement("select * from ecommerce.customer where cust_id = ?");
st.setInt(1, 22);
ResultSet rs = st.executeQuery();

I was hoping that this would produce an 'extended query mode' protocol use between JDBC client and DBMS backend. But it keeps produced a 'simple query mode' interaction. I verified this by enabling JDBC logging for postgres driver. I also looked at the implementations of Query interface within JDBC driver and all I could find is 3 implementations as follows:

BatchedQuery

CompositeQuery

SimpleQuery

Despite the name CompositeQuery all it does is splits up a query involving multiple statements into a list of SimpleQuery objects.

So my question is what can I do to get the protocol used by my connection to an extended mode?

Body:
By default, the Postgres JDBC driver will only start using server-side statements after a prepared statement is used 5 times.  From the JDBC driver property documentation:

prepareThreshold = int

Determine the number of PreparedStatement executions required before switching over to use server side prepared statements. The default is five, meaning start using server side prepared statements on the fifth execution of the same PreparedStatement object. More information on server side prepared statements is available in the section called “Server Prepared Statements”.

But that property can be changed.

This is the program I tested with:

Properties props = new Properties();
props.setProperty("user", "test");
props.setProperty("password", "test");
props.setProperty("loggerLevel", "TRACE");
props.setProperty("prepareThreshold", "1");
try (Connection con = DriverManager.getConnection("jdbc:postgresql:test", props);
     PreparedStatement stat = con.prepareStatement("select * from app_user where username = ?"))
{
    for (String username : List.of("user1", "user2", "user3"))
    {
        stat.setString(1, username);
        try (ResultSet rs = stat.executeQuery())
        {
            if (rs.next())
                System.out.println("User " + username + " has ID: " + rs.getString(1));
        }
    }
}

When prepareThreshold is set to 1, the logs show:

Feb 18, 2020 1:56:59 PM org.postgresql.core.v3.QueryExecutorImpl execute
FINEST:   simple execute, handler=org.postgresql.jdbc.PgStatement$StatementResultHandler@33065d67, maxRows=0, fetchSize=0, flags=16
Feb 18, 2020 1:56:59 PM org.postgresql.core.v3.QueryExecutorImpl sendParse
FINEST:  FE=> Parse(stmt=S_1,query="select * from app_user where username = $1",oids={1043})
Feb 18, 2020 1:56:59 PM org.postgresql.core.v3.QueryExecutorImpl sendBind
FINEST:  FE=> Bind(stmt=S_1,portal=null,$1=<'user1'>)
Feb 18, 2020 1:56:59 PM org.postgresql.core.v3.QueryExecutorImpl sendDescribePortal
FINEST:  FE=> Describe(portal=null)
Feb 18, 2020 1:56:59 PM org.postgresql.core.v3.QueryExecutorImpl sendExecute
FINEST:  FE=> Execute(portal=null,limit=0)
...
Feb 18, 2020 1:56:59 PM org.postgresql.core.v3.QueryExecutorImpl execute
FINEST:   simple execute, handler=org.postgresql.jdbc.PgStatement$StatementResultHandler@35dab4eb, maxRows=0, fetchSize=0, flags=16
Feb 18, 2020 1:56:59 PM org.postgresql.core.v3.QueryExecutorImpl sendBind
FINEST:  FE=> Bind(stmt=S_1,portal=null,$1=<'user2'>)
Feb 18, 2020 1:56:59 PM org.postgresql.core.v3.QueryExecutorImpl sendExecute
FINEST:  FE=> Execute(portal=null,limit=0)
...
Feb 18, 2020 1:56:59 PM org.postgresql.core.v3.QueryExecutorImpl execute
FINEST:   simple execute, handler=org.postgresql.jdbc.PgStatement$StatementResultHandler@2d901eb0, maxRows=0, fetchSize=0, flags=16
Feb 18, 2020 1:56:59 PM org.postgresql.core.v3.QueryExecutorImpl sendBind
FINEST:  FE=> Bind(stmt=S_1,portal=null,$1=<'user3'>)
Feb 18, 2020 1:56:59 PM org.postgresql.core.v3.QueryExecutorImpl sendExecute
FINEST:  FE=> Execute(portal=null,limit=0)

which show the query parse happens once, then there are repeated binds.

Compare this to when prepareThreshold is not set:

Feb 18, 2020 2:01:25 PM org.postgresql.core.v3.QueryExecutorImpl execute
FINEST:   simple execute, handler=org.postgresql.jdbc.PgStatement$StatementResultHandler@33065d67, maxRows=0, fetchSize=0, flags=17
Feb 18, 2020 2:01:25 PM org.postgresql.core.v3.QueryExecutorImpl sendParse
FINEST:  FE=> Parse(stmt=null,query="select * from app_user where username = $1",oids={1043})
Feb 18, 2020 2:01:25 PM org.postgresql.core.v3.QueryExecutorImpl sendBind
FINEST:  FE=> Bind(stmt=null,portal=null,$1=<'user1'>)
Feb 18, 2020 2:01:25 PM org.postgresql.core.v3.QueryExecutorImpl sendDescribePortal
FINEST:  FE=> Describe(portal=null)
Feb 18, 2020 2:01:25 PM org.postgresql.core.v3.QueryExecutorImpl sendExecute
FINEST:  FE=> Execute(portal=null,limit=0)
...
Feb 18, 2020 2:01:25 PM org.postgresql.core.v3.QueryExecutorImpl execute
FINEST:   simple execute, handler=org.postgresql.jdbc.PgStatement$StatementResultHandler@8519cb4, maxRows=0, fetchSize=0, flags=17
Feb 18, 2020 2:01:25 PM org.postgresql.core.v3.QueryExecutorImpl sendParse
FINEST:  FE=> Parse(stmt=null,query="select * from app_user where username = $1",oids={1043})
Feb 18, 2020 2:01:25 PM org.postgresql.core.v3.QueryExecutorImpl sendBind
FINEST:  FE=> Bind(stmt=null,portal=null,$1=<'user2'>)
Feb 18, 2020 2:01:25 PM org.postgresql.core.v3.QueryExecutorImpl sendDescribePortal
FINEST:  FE=> Describe(portal=null)
Feb 18, 2020 2:01:25 PM org.postgresql.core.v3.QueryExecutorImpl sendExecute
FINEST:  FE=> Execute(portal=null,limit=0)
...
Feb 18, 2020 2:01:25 PM org.postgresql.core.v3.QueryExecutorImpl execute
FINEST:   simple execute, handler=org.postgresql.jdbc.PgStatement$StatementResultHandler@35dab4eb, maxRows=0, fetchSize=0, flags=17
Feb 18, 2020 2:01:25 PM org.postgresql.core.v3.QueryExecutorImpl sendParse
FINEST:  FE=> Parse(stmt=null,query="select * from app_user where username = $1",oids={1043})
Feb 18, 2020 2:01:25 PM org.postgresql.core.v3.QueryExecutorImpl sendBind
FINEST:  FE=> Bind(stmt=null,portal=null,$1=<'user3'>)
Feb 18, 2020 2:01:25 PM org.postgresql.core.v3.QueryExecutorImpl sendDescribePortal
FINEST:  FE=> Describe(portal=null)
Feb 18, 2020 2:01:25 PM org.postgresql.core.v3.QueryExecutorImpl sendExecute
FINEST:  FE=> Execute(portal=null,limit=0)

where there are 3 separate statement parses and binds.  After 5 queries they should start getting reused, however.

Regarding the query mode being 'simple' vs 'extended', it looks like the logs always print out 'simple execute' regardless, however the difference is that true simple mode the parameters will not be bound in prepared statement and instead the entire query will be sent as text.  In this example, if the preferQueryMode property is set to simple, the logs show:

Feb 18, 2020 2:06:19 PM org.postgresql.core.v3.QueryExecutorImpl execute
FINEST:   simple execute, handler=org.postgresql.jdbc.PgStatement$StatementResultHandler@33065d67, maxRows=0, fetchSize=0, flags=1,041
Feb 18, 2020 2:06:19 PM org.postgresql.core.v3.QueryExecutorImpl sendSimpleQuery
FINEST:  FE=> SimpleQuery(query="select * from app_user where username = 'user1'")
...
Feb 18, 2020 2:06:20 PM org.postgresql.core.v3.QueryExecutorImpl execute
FINEST:   simple execute, handler=org.postgresql.jdbc.PgStatement$StatementResultHandler@28261e8e, maxRows=0, fetchSize=0, flags=1,041
Feb 18, 2020 2:06:20 PM org.postgresql.core.v3.QueryExecutorImpl sendSimpleQuery
FINEST:  FE=> SimpleQuery(query="select * from app_user where username = 'user2'")
...
Feb 18, 2020 2:06:20 PM org.postgresql.core.v3.QueryExecutorImpl execute
FINEST:   simple execute, handler=org.postgresql.jdbc.PgStatement$StatementResultHandler@d737b89, maxRows=0, fetchSize=0, flags=1,041
Feb 18, 2020 2:06:20 PM org.postgresql.core.v3.QueryExecutorImpl sendSimpleQuery
FINEST:  FE=> SimpleQuery(query="select * from app_user where username = 'user3'")

notice the difference between this and the default - there are no parameters and the 'user1', 'user2' and 'user3' values are being sent inline with each query.

I think what you are really looking for then is to re-use server-side statements immediately and rebind parameters.  In this case, setting prepareThreshold to 1 will do the job.


问:
get address of an EC2 agent from a Jenkins pipeline for git push/scp?
I'm setting up a simple Jenkins pipeline, with a stage running on an AWS EC2 agent.

```<code>pipeline {
  agent none
  stages {
    stage('Prepare') {
      agent { label 'master' }
      steps {
        sh "touch somefile"
        stash includes: "somefile", name:"ARTIFACT"
      }
    }
    stage('AWS') {
      agent { label 'aws' }
      steps {
        unstash 'ARTIFACT'
        sh "cat somefile"
      }
    }
  }
}
</code>```

Stash/unstash works for simple files, but ideally I'd like direct ssh connection so that I can push a git repo onto the slave, and maybe scp a directory. My simple issue is I don't know the public DNS/IP of the slave started by the EC2 plugin so can't connect.

I guess I could figure that out via extra scripts and installing AWS CLI on my Jenkins boxes. Also I've seen suggestions to use S3 and CodeDeploy to push anything onto the instances..however this seems more convoluted than I want at least initially.

I've also seen hints to use instance metadata and http requests to get the IP/DNS (  https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/configuring-instance-metadata-service.html#configuring-instance-metadata-options ) - again looks way more complicated than I'd expect (maybe because I'm a newbie on aws;), so I think/hope I'm not on the right track there.

Was also thinking of adding an extra stage on the aws agent, just to login and do something like "ip addr show" , and pass that back to the pipeline so that a subsequent step could use that for "git push" or scp, etc..

I would have assumed the Jenkins EC2 plugin already knows the IP/DNS to the slave otherwise it couldn't connect itself.

So it would be great to hear about a more straightforward and robust solution.

答:
Get ec2 public ip from metadata via curl.</p>

```<code>stage('AWS') {
  agent { label 'aws' }
  steps {
    unstash 'ARTIFACT'

    cmd = '''curl --fail --noproxy '*' http://169.254.169.254/latest/meta-data/public-ipv4'''
    public_ip = sh(script:cmd, returnStdout:true).trim()

  }
}
</code>```

Body:
I'm setting up a simple Jenkins pipeline, with a stage running on an AWS EC2 agent.

pipeline {
  agent none
  stages {
    stage('Prepare') {
      agent { label 'master' }
      steps {
        sh "touch somefile"
        stash includes: "somefile", name:"ARTIFACT"
      }
    }
    stage('AWS') {
      agent { label 'aws' }
      steps {
        unstash 'ARTIFACT'
        sh "cat somefile"
      }
    }
  }
}

Stash/unstash works for simple files, but ideally I'd like direct ssh connection so that I can push a git repo onto the slave, and maybe scp a directory. My simple issue is I don't know the public DNS/IP of the slave started by the EC2 plugin so can't connect.

I guess I could figure that out via extra scripts and installing AWS CLI on my Jenkins boxes. Also I've seen suggestions to use S3 and CodeDeploy to push anything onto the instances..however this seems more convoluted than I want at least initially.

I've also seen hints to use instance metadata and http requests to get the IP/DNS (  https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/configuring-instance-metadata-service.html#configuring-instance-metadata-options ) - again looks way more complicated than I'd expect (maybe because I'm a newbie on aws;), so I think/hope I'm not on the right track there.

Was also thinking of adding an extra stage on the aws agent, just to login and do something like "ip addr show" , and pass that back to the pipeline so that a subsequent step could use that for "git push" or scp, etc..

I would have assumed the Jenkins EC2 plugin already knows the IP/DNS to the slave otherwise it couldn't connect itself.

So it would be great to hear about a more straightforward and robust solution.

Body:
Get ec2 public ip from metadata via curl.

stage('AWS') {
  agent { label 'aws' }
  steps {
    unstash 'ARTIFACT'

    cmd = '''curl --fail --noproxy '*' http://169.254.169.254/latest/meta-data/public-ipv4'''
    public_ip = sh(script:cmd, returnStdout:true).trim()

  }
}


问:
How to convert object to string pandas python
Most answer given to the questions that seemed like the answers would help weren't helpful to anyone asking any questions. Nor the people answering the questions knew figure things out after they found out what they had contributed didn't work. I  have tried pretty much every str() and .to_string variation I could find.

Anyways, I've been trying to get data in a file paired up and omit data I can't pair up. I believe I've paired things together, but there's no way for me to verify this other than seeing the column and true or false.

```<code>import pandas as pd

# read file
with open('TastyTrades.csv', 'r') as trade_history:
    trade_reader = pd.read_csv('TastyTrades.csv')
    # sort out for options only
    options_frame = trade_reader.loc[(trade_reader['Instrument Type'] == 'Equity Option')]
    # resort data
    date_frame = options_frame.sort_values(by=['Symbol', 'Date', 'Action'], ascending=True)
    # pair BTO to STC
    BTO = date_frame['Action'].isin(['BUY_TO_OPEN', 'SELL_TO_CLOSE'])
    STO = date_frame['Action'].isin(['SELL_TO_OPEN', 'BUY_TO_CLOSE'])
    # bringing both frames as one
    pairs = [BTO, STO]
    # return readable data
    result = pd.concat(pairs).astype(str)

    # write to new file
    result.to_csv('new_taste.csv')

</code>```

This code bring me:

```<code>,Action
101,True
75,True
102,False
76,False
95,False
97,True
98,True
38,True
174,True
166,True
</code>```

I am trying to get the data back to the readable format:

```<code>Date,Type,Action,Symbol,Instrument Type,Description,Value,Quantity,Average Price,Commissions,Fees,Multiplier,Underlying Symbol,Expiration Date,Strike Price,Call or Put
2020-02-14T15:49:12-0500,Trade,SELL_TO_OPEN,TGT   200327C00127000,Equity Option,Sold 1 TGT 03/27/20 Call 127.00 @ 1.33,133,1,133,-1,-0.15,100,TGT,3/27/2020,127,CALL
2020-02-14T15:49:11-0500,Trade,SELL_TO_OPEN,TGT   200327P00107000,Equity Option,Sold 1 TGT 03/27/20 Put 107.00 @ 1.80,180,1,180,-1,-0.15,100,TGT,3/27/2020,107,PUT
2020-02-14T15:49:11-0500,Trade,BUY_TO_OPEN,TGT   200327C00128000,Equity Option,Bought 1 TGT 03/27/20 Call 128.00 @ 1.17,-117,1,-117,-1,-0.14,100,TGT,3/27/2020,128,CALL

</code>```

答:
Here BTO and STO will only have the result of isin condition (true or false).
So, Rewrite two of your lines as below:

```<code>BTO = date_frame[date_frame['Action'].isin(['BUY_TO_OPEN', 'SELL_TO_CLOSE'])]
STO = date_frame[date_frame['Action'].isin(['SELL_TO_OPEN', 'BUY_TO_CLOSE'])]
</code>```

This will give all the columns into BTO and STO and then you can merge these two DF's.
Hope this helps.
Check below working code:
I tried it, and got expected result. All the rows using above code. I tried without converting to 'str', that too gave me same result. Try printing the result and see what it shows.

```<code>BTO = quotes[quotes['Action'].isin(['BTO', 'STC'])]
STO = quotes[quotes['Action'].isin(['STO', 'BTC'])]
frames = [BTO,STO]
result = pd.concat(frames).astype(str)
result.to_csv('new_taste.csv')
</code>```

Body:
Most answer given to the questions that seemed like the answers would help weren't helpful to anyone asking any questions. Nor the people answering the questions knew figure things out after they found out what they had contributed didn't work. I  have tried pretty much every str() and .to_string variation I could find.

Anyways, I've been trying to get data in a file paired up and omit data I can't pair up. I believe I've paired things together, but there's no way for me to verify this other than seeing the column and true or false.

import pandas as pd

# read file
with open('TastyTrades.csv', 'r') as trade_history:
    trade_reader = pd.read_csv('TastyTrades.csv')
    # sort out for options only
    options_frame = trade_reader.loc[(trade_reader['Instrument Type'] == 'Equity Option')]
    # resort data
    date_frame = options_frame.sort_values(by=['Symbol', 'Date', 'Action'], ascending=True)
    # pair BTO to STC
    BTO = date_frame['Action'].isin(['BUY_TO_OPEN', 'SELL_TO_CLOSE'])
    STO = date_frame['Action'].isin(['SELL_TO_OPEN', 'BUY_TO_CLOSE'])
    # bringing both frames as one
    pairs = [BTO, STO]
    # return readable data
    result = pd.concat(pairs).astype(str)

    # write to new file
    result.to_csv('new_taste.csv')

This code bring me:

,Action
101,True
75,True
102,False
76,False
95,False
97,True
98,True
38,True
174,True
166,True

I am trying to get the data back to the readable format:

Date,Type,Action,Symbol,Instrument Type,Description,Value,Quantity,Average Price,Commissions,Fees,Multiplier,Underlying Symbol,Expiration Date,Strike Price,Call or Put
2020-02-14T15:49:12-0500,Trade,SELL_TO_OPEN,TGT   200327C00127000,Equity Option,Sold 1 TGT 03/27/20 Call 127.00 @ 1.33,133,1,133,-1,-0.15,100,TGT,3/27/2020,127,CALL
2020-02-14T15:49:11-0500,Trade,SELL_TO_OPEN,TGT   200327P00107000,Equity Option,Sold 1 TGT 03/27/20 Put 107.00 @ 1.80,180,1,180,-1,-0.15,100,TGT,3/27/2020,107,PUT
2020-02-14T15:49:11-0500,Trade,BUY_TO_OPEN,TGT   200327C00128000,Equity Option,Bought 1 TGT 03/27/20 Call 128.00 @ 1.17,-117,1,-117,-1,-0.14,100,TGT,3/27/2020,128,CALL

Body:
Here BTO and STO will only have the result of isin condition (true or false).
So, Rewrite two of your lines as below:

BTO = date_frame[date_frame['Action'].isin(['BUY_TO_OPEN', 'SELL_TO_CLOSE'])]
STO = date_frame[date_frame['Action'].isin(['SELL_TO_OPEN', 'BUY_TO_CLOSE'])]

This will give all the columns into BTO and STO and then you can merge these two DF's.
Hope this helps.
Check below working code:
I tried it, and got expected result. All the rows using above code. I tried without converting to 'str', that too gave me same result. Try printing the result and see what it shows.

BTO = quotes[quotes['Action'].isin(['BTO', 'STC'])]
STO = quotes[quotes['Action'].isin(['STO', 'BTC'])]
frames = [BTO,STO]
result = pd.concat(frames).astype(str)
result.to_csv('new_taste.csv')


问:
Karate framework variable usage
I have this steps:

```<code>...
Then status 200
And match response.requests[0].request.url == "/endpoint"
And json body = response.requests[0].request.body
And match body == { "something": "something"}
</code>```

To simplify, I tried to put response.requests[0].request in a variable called request:

```<code>...
Then status 200
And def request = response.requests[0].request
And match request.url == "/endpoint"
And json body = request.body
And match body == { "something": "something"}
</code>```

I'm having the following error:

```<code>'request' is not a variable, use the form '* request <expression>' instead
</code>```

I read the documentation and the use of request seems to be fine:

```<code>Given def color = 'red '
And def num = 5
Then assert color + num == 'red 5'
</code>```

What am I doing wrong?

Thanks in advance.

答:
Just make this change:

```<code>* def req = response.requests[0].request
# other steps
* request req
</code>```

We simply disallow def request (using request as a variable name) because a lot of newbie users get confused. The error message has worked 99.9% of the time for users to understand what the problem is, but I guess you fall in the 0.1% :)

Title: Karate framework variable usage

Body:
I have this steps:

...
Then status 200
And match response.requests[0].request.url == "/endpoint"
And json body = response.requests[0].request.body
And match body == { "something": "something"}

To simplify, I tried to put response.requests[0].request in a variable called request:

...
Then status 200
And def request = response.requests[0].request
And match request.url == "/endpoint"
And json body = request.body
And match body == { "something": "something"}

I'm having the following error:

'request' is not a variable, use the form '* request <expression>' instead

I read the documentation and the use of request seems to be fine:

Given def color = 'red '
And def num = 5
Then assert color + num == 'red 5'

What am I doing wrong?

Thanks in advance.

Body:
Just make this change:

* def req = response.requests[0].request
# other steps
* request req

We simply disallow def request (using request as a variable name) because a lot of newbie users get confused. The error message has worked 99.9% of the time for users to understand what the problem is, but I guess you fall in the 0.1% :)


问:
How can I make a JS if statement to see if a value isn't certain strings?
Why does this JS not work? The goal is to enter something into the text box that isn't help, windows-xp, explicit, default, or nothing, press enter, and have that alert "Command doesn't exist".

function checkInput() {
  var commandInput = document.getElementById("command-input")

  if (commandInput.value !== "help", "windows-xp", "explicit", "default", "") {
    alert("Command doesn't exist.");
  }

  event.preventDefault();

  document.getElementById("command-form").reset();
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form id="command-form">
  <input type="text" placeholder="Enter Command" id="command-input">
  <input type="submit" onclick="checkInput();" style="display: none;">
</form></code>```

答:
Make an array (or Set) of the strings you want to permit, then check if the array .includes the value:

function checkInput(event) {
  event.preventDefault();
  const commands = ["help", "windows-xp", "explicit", "default", ""];
  const { value } = document.getElementById("command-input");
  if (!commands.includes(value)) {
    console.log('Command doesnt exist ');
    return;
  }
  console.log('Carrying out command', value);
  commandForm.reset();
}
const commandForm = document.getElementById("command-form");
commandForm.addEventListener('submit', checkInput);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form id="command-form">
    <input type="text" placeholder="Enter Command" id="command-input">
    <input type="submit">
</form></code>```

Also note that you should avoid inline handlers whenever possible, they have too many gotchas, require global pollution, and are bad practice - attach event listeners properly using Javascript instead, like in the above snippet.

Body:
Why does this JS not work? The goal is to enter something into the text box that isn't help, windows-xp, explicit, default, or nothing, press enter, and have that alert "Command doesn't exist".

function checkInput() {
  var commandInput = document.getElementById("command-input")

  if (commandInput.value !== "help", "windows-xp", "explicit", "default", "") {
    alert("Command doesn't exist.");
  }

  event.preventDefault();

  document.getElementById("command-form").reset();
}

<form id="command-form">
  <input type="text" placeholder="Enter Command" id="command-input">
  <input type="submit" onclick="checkInput();" style="display: none;">
</form>

Body:
Make an array (or Set) of the strings you want to permit, then check if the array .includes the value:

function checkInput(event) {
  event.preventDefault();
  const commands = ["help", "windows-xp", "explicit", "default", ""];
  const { value } = document.getElementById("command-input");
  if (!commands.includes(value)) {
    console.log('Command doesnt exist ');
    return;
  }
  console.log('Carrying out command', value);
  commandForm.reset();
}
const commandForm = document.getElementById("command-form");
commandForm.addEventListener('submit', checkInput);

<form id="command-form">
    <input type="text" placeholder="Enter Command" id="command-input">
    <input type="submit">
</form>

Also note that you should avoid inline handlers whenever possible, they have too many gotchas, require global pollution, and are bad practice - attach event listeners properly using Javascript instead, like in the above snippet.


问:
Forecasting with a gap of negative 1
I am using H2O.ai to understand both current week and lagged week features that affect the target value of the current week.

Using the Walmart example.

For a particular week of sales, I am interested in the features that most likely affect how well or poorly sales performed.
To set this problem up, I want H2O.ai to 'predict' what the current week of sales are using the current week feature values as well as the lagged values (including the lag of the target) -- i.e., this is not a forecast problem, but a problem to understand the drivers.

In forecasting terms, this would be setting the prediction horizon to 1 and the gap of negative 1.

However, H2O.ai seems to not allow you to set it in this unconventional way.

How would I set up this experiment in H2O.ai?

答:
The problem described corresponds to a multi-variate time series problem that uses only lags 0 and 1. Of course, it can't and won't use use lag 0 on target, but it can will use lag 0 on other time series and features.

To setup the problem in Driverless AI properly with walmart dataset set:

target column: Weekly_Sales

time column: Date

time group columns (TGC): Store, Dept

Forecast horizon: 1 week

Gap: 0 week

Expert Settings -> Time Series:

Time Series Lag Override: 1

(optional but recommended) Probability to create non-target lag features: 0.5 or higher

(optional but worth trying) Always Group by All Time Groups Columns for Creating Lag Features: Disabled

With lag override set to 1 no lags greater than 1 can be used to predict target, plus current (lag 0) features (everything but target). So, effectively, it still a forecast problem but it complies with all restrictions you placed in your question.

Title: Forecasting with a gap of negative 1


问:
Is it possible to make a button on an AlertDialog that doesn't automatically close the dialog?
I have a simple list view with some check boxes in an alert dialog.  I need to option to add a select all/none but you can't bring up the menu in an alert dialog, and I want to do this function from a button.  From what I've seen any kind of button (positive, neutral, and negative) all close the dialog regardless.

So, is this possible?  If no, what alternatives do I have?  My last mitigation is to simply create a new view and recreate everything.  Is a new view the best solution?

答:
Have you tried to extend the AlertDialog class and have it implment OnCLickListener

```<code>public class MyDialog extends AlertDialog implements OnClickListener {
    private Button myButton;

    public void onCreate( Bundle savedInstanceState ) {
        super.onCreate( savedInstanceState );
        // use LayoutInflater to get at custom button
        LayoutInflater layoutInflater = (LayoutInflater)getContext().getSystemService( Context.LAYOUT_INFLATER_SERVICE );
        View contentView = layoutInflater.inflate( R.layout.mydialog_layout, null );

        // pull button from layout, set listener
        myButton = (Button)contentView.findViewById( R.id.myButtonId );
        myButton.setOnClickListener( this );

        setContentView( contentView );
    }

    public void onClick( View v ) {
        if ( v.getId() == R.id.myButtonId ) {
            // DO your button actions.
        }
    }
}
</code>```

Following this template, you can put any buttons you need and create your own functionality within the dialog itself.  You could also create your own Button at runtime, but you'll have to do the extra work of configuring the button's text, size, icon, etc.

You can then create the dialog in your activity under the onCreateDialog() call.

```<code>protected Dialog onCreateDialog( int id ) {
    MyDialog dialog = new MyDialog( this, 0 );
    dialog.setOnCancelListener( this );
    dialog.setOnDismissListener( this );
    return dialog;
}
</code>```

Hope this helps.

ContentLicense: CC BY-SA 2.5

Body:
Have you tried to extend the AlertDialog class and have it implment OnCLickListener

public class MyDialog extends AlertDialog implements OnClickListener {
    private Button myButton;

    public void onCreate( Bundle savedInstanceState ) {
        super.onCreate( savedInstanceState );
        // use LayoutInflater to get at custom button
        LayoutInflater layoutInflater = (LayoutInflater)getContext().getSystemService( Context.LAYOUT_INFLATER_SERVICE );
        View contentView = layoutInflater.inflate( R.layout.mydialog_layout, null );

        // pull button from layout, set listener
        myButton = (Button)contentView.findViewById( R.id.myButtonId );
        myButton.setOnClickListener( this );

        setContentView( contentView );
    }

    public void onClick( View v ) {
        if ( v.getId() == R.id.myButtonId ) {
            // DO your button actions.
        }
    }
}

Following this template, you can put any buttons you need and create your own functionality within the dialog itself.  You could also create your own Button at runtime, but you'll have to do the extra work of configuring the button's text, size, icon, etc.

You can then create the dialog in your activity under the onCreateDialog() call.

protected Dialog onCreateDialog( int id ) {
    MyDialog dialog = new MyDialog( this, 0 );
    dialog.setOnCancelListener( this );
    dialog.setOnDismissListener( this );
    return dialog;
}

Hope this helps.


答:
Use Array.includes:

```<code>const validCommands = ["help", "windows-xp", "explicit", "default", ""];

if (!validCommands.includes(commandInput.value)) {
  alert("Command doesn't exist.");
}
</code>```

Title: How can I make a JS if statement to see if a value isn't certain strings?

Body:
Use Array.includes:

const validCommands = ["help", "windows-xp", "explicit", "default", ""];

if (!validCommands.includes(commandInput.value)) {
  alert("Command doesn't exist.");
}


问:
how to get values to update in c++
```<code>
using namespace std;

int main()
{
   int slotWild = 0;
   int slotOne = 1 + slotWild;
   int slotTwo = 1 + slotOne;

   cout << slotWild << slotOne << slotTwo;
   slotWild -= 1;
   cout << slotWild << slotOne << slotTwo;
   slotWild -= 1;
   cout << slotWild << slotOne << slotTwo;
   return 0;
}
</code>```

the output that I get it is:

0 1 2

-1 1 2

-2 1 2

so my question is, why don't the other values update if the value of slotWild is included in slotOne and slotTwo's definition? For example, you would expect the output for the 2nd and 3rd line to be:

-1 0 1

-2 -1 0

答:
Those aren't "definitions", they're assignments. When you say x = y + 1 you're saying "assign to x the value of y, as of right now plus 1".

If you want it to be dynamic you must define a function, as in:

```<code>int slotOne() {
  return 1 + slotWild;
}
</code>```

Where that requires slotWild to be a class property or a global variable.

That means you'll need to call it as well, as in:

```<code>cout << slotWild << slotOne() << slotTwo();
</code>```

A function is evaluated each time it is called whereas a variable is initialized only once and after that point the value won't change unless the variable has been modified.

As Walnut points out, that C++ statement is actually two parts:

```<code>int slotOne = 1 + slotWild;
^^^^^^^^^^^   ^^^^^^^^^^^^^
    |              \- Variable Initialization
    \--- Variable Definition
</code>```

The initialization part happens the instant this variable is defined, as in when that line of code executes.

(As with many things in C++ that's not always the case, but as a general rule that's how it works.)

Title: how to get values to update in c++

Body:
using namespace std;

int main()
{
   int slotWild = 0;
   int slotOne = 1 + slotWild;
   int slotTwo = 1 + slotOne;

   cout << slotWild << slotOne << slotTwo;
   slotWild -= 1;
   cout << slotWild << slotOne << slotTwo;
   slotWild -= 1;
   cout << slotWild << slotOne << slotTwo;
   return 0;
}

the output that I get it is:

0 1 2

-1 1 2

-2 1 2

so my question is, why don't the other values update if the value of slotWild is included in slotOne and slotTwo's definition? For example, you would expect the output for the 2nd and 3rd line to be:

-1 0 1

-2 -1 0

Body:
Those aren't "definitions", they're assignments. When you say x = y + 1 you're saying "assign to x the value of y, as of right now plus 1".

If you want it to be dynamic you must define a function, as in:

int slotOne() {
  return 1 + slotWild;
}

Where that requires slotWild to be a class property or a global variable.

That means you'll need to call it as well, as in:

cout << slotWild << slotOne() << slotTwo();

A function is evaluated each time it is called whereas a variable is initialized only once and after that point the value won't change unless the variable has been modified.

As Walnut points out, that C++ statement is actually two parts:

int slotOne = 1 + slotWild;
^^^^^^^^^^^   ^^^^^^^^^^^^^
    |              \- Variable Initialization
    \--- Variable Definition

The initialization part happens the instant this variable is defined, as in when that line of code executes.

(As with many things in C++ that's not always the case, but as a general rule that's how it works.)


问:
Different hash algorithm for ASP.NET Membership provider?
Does anyone know if it is possible to configure the ASP.NET membership API to use SHA-256 or SHA-512? I don't really want to have to go down the line of writing my own and our employer has an encryption policy that does not allow MD5 or SHA-1. All i can find from Microsoft is the the HashAlgorythmType enum

...but this only contains MD5 and SHA1

Thanks,

Keeno

答: This answer can help. ASP.NET Membership Provider can now use PBKDF2 (much better than SHA1, SHA256-SHA512): https://stackoverflow.com/a/60273188/2508781</p>

OwnerDisplayName: keene


问:
IBM Watson Visual Recognition android sdk failing to load
Hi I hope you are doing well,

I'm using the IBM Watson service Visual Recognition with Android, I set the IBM Cloud part correctly, but when I want to work with the service in Android (Android SDK), it doesn't recognize or resolve the dependency.

Photo :

Android studio didn't recognize IBM Visual Recognition Classes, click to see image

Dependency on gradle:

implementation 'com.ibm.watson:ibm-watson:8.+'

I want to know if the IBM android SDK isn't working or I missed something somewhere.
Thanks.

答:
From the gradle entry above, I think you are referring to Watson developer cloud Java SDK as Watson developer cloud Android SDK’s latest version is 0.5.2 -Android SDK.

If you are using Watson Visual recognition, you can install only Visual recognition piece through gradle by following the steps mentioned here.

Also, add the gradle entry to app/build.gradle as shown here


问:
My navbar isn't scrolling when I use position: sticky
I have looked over some of the other questions regarding non-sticking nav bars, but I still haven't fixed it. It might have something to do with the way I placed my tags, but I'm not quite sure. I might just be placing the sticky code in the wrong CSS selector.

Here is my code:

#navbar {
  max-width: 100%;
  background-color: black;
  top: 0;
}

nav span:hover {
  border-bottom: 1px solid rgb(200, 140, 16);
}
nav a:hover {
  color: rgb(200, 140, 16);
}

ul {
  display: flex;
  height: 30px;
  padding: 0px;
}
nav {
  font-family: "Odibee Sans", cursive;
  font-size: 25px;
  margin: 0 auto;
  border-bottom: 1px solid rgb(200, 140, 16);
  z-index: 1;
  text-decoration: none;
  display: flex;
  justify-content: center;
  position: sticky;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
    <header>
      <div id="banner-container">
        <img id="topper" src="./newstop.png" />
      </div>
      <nav id="navbar">
        <div id="side-icon">
          <img src="../copo.png"/>
        </div>
        <div class="link-container">
          <ul id="list-container">
            <li>
              <div class="links">
                <span>Our Story</span>
              </div>
            </li>
            <li>
              <div class="links">
                <a><span>Our Vehicles</span></a>
              </div>
            </li>
            <li>
              <div class="links">
                <span>News</span>
              </div>
            </li>
            <li>
              <div class="links">
                <a><span>Sign In</span></a>
              </div>
            </li>
          </ul>
        </div>
      </nav>
    </header></code>```

答:
#navbar {
  max-width: 100%;
  background-color: black;
  top: 0;
}

nav span:hover {
  border-bottom: 1px solid rgb(200, 140, 16);
}
nav a:hover {
  color: rgb(200, 140, 16);
}

ul {
  display: flex;
  height: 30px;
  padding: 0px;
}
nav {
  font-family: "Odibee Sans", cursive;
  font-size: 25px;
  margin: 0 auto;
  border-bottom: 1px solid rgb(200, 140, 16);
  z-index: 1;
  text-decoration: none;
  display: flex;
  justify-content: center;
  position: sticky;
  top: 0;
}
#topper{
  height: 200px;
  width: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
    <header>
      <div id="banner-container">
        <img id="topper" src="https://images-eu.ssl-images-amazon.com/images/I/41lMD31ltzL.jpg" />
      </div>
      <nav id="navbar">
        <div id="side-icon">
          <img src="../copo.png"/>
        </div>
        <div class="link-container">
          <ul id="list-container">
            <li>
              <div class="links">
                <span>Our Story</span>
              </div>
            </li>
            <li>
              <div class="links">
                <a><span>Our Vehicles</span></a>
              </div>
            </li>
            <li>
              <div class="links">
                <span>News</span>
              </div>
            </li>
            <li>
              <div class="links">
                <a><span>Sign In</span></a>
              </div>
            </li>
          </ul>
        </div>
      </nav>
      <div>
       <p>
        <img src="https://images-eu.ssl-images-amazon.com/images/I/41lMD31ltzL.jpg" />
       </p>
      </div>
    </header></code>```

Body:
I have looked over some of the other questions regarding non-sticking nav bars, but I still haven't fixed it. It might have something to do with the way I placed my tags, but I'm not quite sure. I might just be placing the sticky code in the wrong CSS selector.

Here is my code:

#navbar {
  max-width: 100%;
  background-color: black;
  top: 0;
}

nav span:hover {
  border-bottom: 1px solid rgb(200, 140, 16);
}
nav a:hover {
  color: rgb(200, 140, 16);
}

ul {
  display: flex;
  height: 30px;
  padding: 0px;
}
nav {
  font-family: "Odibee Sans", cursive;
  font-size: 25px;
  margin: 0 auto;
  border-bottom: 1px solid rgb(200, 140, 16);
  z-index: 1;
  text-decoration: none;
  display: flex;
  justify-content: center;
  position: sticky;
}

                Our Story

                Our Vehicles

                News

                Sign In

Body:
#navbar {
  max-width: 100%;
  background-color: black;
  top: 0;
}

nav span:hover {
  border-bottom: 1px solid rgb(200, 140, 16);
}
nav a:hover {
  color: rgb(200, 140, 16);
}

ul {
  display: flex;
  height: 30px;
  padding: 0px;
}
nav {
  font-family: "Odibee Sans", cursive;
  font-size: 25px;
  margin: 0 auto;
  border-bottom: 1px solid rgb(200, 140, 16);
  z-index: 1;
  text-decoration: none;
  display: flex;
  justify-content: center;
  position: sticky;
  top: 0;
}
#topper{
  height: 200px;
  width: 100%;
}

<body>
    <header>
      <div id="banner-container">
        <img id="topper" src="https://images-eu.ssl-images-amazon.com/images/I/41lMD31ltzL.jpg" />
      </div>
      <nav id="navbar">
        <div id="side-icon">
          <a href="#top"><img src="../copo.png"/></a>
        </div>
        <div class="link-container">
          <ul id="list-container">
            <li>
              <div class="links">
                <a href="../home/index.html"><span>Our Story</span></a>
              </div>
            </li>
            <li>
              <div class="links">
                <a><span>Our Vehicles</span></a>
              </div>
            </li>
            <li>
              <div class="links">
                <a href="#recent" class="active"><span>News</span></a>
              </div>
            </li>
            <li>
              <div class="links">
                <a><span>Sign In</span></a>
              </div>
            </li>
          </ul>
        </div>
      </nav>
      <div>
       <p>
        <img src="https://images-eu.ssl-images-amazon.com/images/I/41lMD31ltzL.jpg" />
       </p>
      </div>
    </header>


问:
bash ascii to hex
was wondering if anyone could help me with converting ascii to hex in bash.
Example code:

```<code>#!/bin/bash
STR = "hello"
#Convert to hex
HEXVAL = $STR #(in hex here?)
</code>```

I want hexval to have the value:
68656C6C6F (hello in hex)

Title: bash ascii to hex

Body:
was wondering if anyone could help me with converting ascii to hex in bash.
Example code:

#!/bin/bash
STR = "hello"
#Convert to hex
HEXVAL = $STR #(in hex here?)

I want hexval to have the value:
68656C6C6F (hello in hex)

Body:
xxd -p -u <<< "$STR" | sed 's/\(..\)/0x&, /g; s/, $//;'

0x68, 0x65, 0x6C, 0x6C, 0x6F, 0x0A


问:
Specify "privileged" container mode in dockerfile?
I am a little new to Docker technology, however, I would like to deploy a couple of BGP BIRD containers throughout my infrastructure. I would like to automate container creation with Dockerfile builds, however, I can not run BIRD in docker without giving the container "privileged" mode. There doesn't appear to be a Dockerfile version for getting "privileged" mode. Are there workarounds or perhaps I am missing the point?</p>

答: it's a parameter you pass when you run the container --privileged


问:
How do I combine multiple form inputs into a single object with SimpleFormController in Spring?
I have an object called Person that has the following properties:

```<code>int id;
Name name;
String address;
Date birthday;
String email;
String note;
</code>```

The Name class has these properties:

```<code>String firstName;
String middleName;
String lastName;
</code>```

In my form, I have these input fields:

```<code><tr>
    <td>First Name:</td>
    <td><form:input path="firstName" /></td>
</tr>
<tr>
    <td>Middle Name:</td>
    <td><form:input path="middleName" /></td>
</tr>
<tr>
    <td>Last Name:</td>
    <td><form:input path="lastName" /></td>
</tr>
</code>```

How will I be able to retrieve the value of the name input fields and turn it into a Name object before passing it to the Person object that will be created by the SimpleFormController? I'm pretty sure I need to use the initBinder() method, but I don't know how to start.

I'm using Spring 3.0, and yes, I know that SimpleFormController is deprecated already, but I still intend to use it.

答:
You need to write:

```<code><form:input path="name.firstName" />
...
</code>```

in you jsp. And need to override the formBackingObject Method, so that it retuns an empty Person object with an reference to an emtpy name object

```<code>protected Object formBackingObject(HttpServletRequest request) {
   Person person = new Person();
   person.Name = new Name();
   return person;
}
</code>```

Thats all, you do not need to write your own binding.

Body:
I have an object called Person that has the following properties:

int id;
Name name;
String address;
Date birthday;
String email;
String note;

The Name class has these properties:

String firstName;
String middleName;
String lastName;

In my form, I have these input fields:

    First Name:
    <form:input path="firstName" />

    Middle Name:
    <form:input path="middleName" />

    Last Name:
    <form:input path="lastName" />

How will I be able to retrieve the value of the name input fields and turn it into a Name object before passing it to the Person object that will be created by the SimpleFormController? I'm pretty sure I need to use the initBinder() method, but I don't know how to start.

I'm using Spring 3.0, and yes, I know that SimpleFormController is deprecated already, but I still intend to use it.

Body:
You need to write:

<form:input path="name.firstName" />
...

in you jsp. And need to override the formBackingObject Method, so that it retuns an empty Person object with an reference to an emtpy name object

protected Object formBackingObject(HttpServletRequest request) {
   Person person = new Person();
   person.Name = new Name();
   return person;
}

Thats all, you do not need to write your own binding.