问:
How to send a message to specific user using aspnetcore signalR?
I have a requirement to send notification to specific user. I am using dotnet core 3.1. ASPNETCORE signalR for the notification.
I am able to send the messages to all clients but unablt to do so for specific user.

EDIT 1

My Hub looks like :

```<code>public class NotificationHub : Hub
{
    public override async Task OnConnectedAsync()
    {
        await Groups.AddToGroupAsync(Context.ConnectionId, Context.User.Identity.Name);
        await base.OnConnectedAsync();
    }

    public override async Task OnDisconnectedAsync(Exception ex)
    {
        await Groups.RemoveFromGroupAsync(Context.ConnectionId, Context.User.Identity.Name);
        await base.OnDisconnectedAsync(ex);
    }
}
</code>```

And i am calling the SendAsync method from Controller as :

```<code> private IHubContext<NotificationHub> _hub;

    public NotificationController(IHubContext<NotificationHub> hub)
    {
        _hub = hub;
    }

[HttpGet]
    public IActionResult Get()
    {
        //_hub.Clients.All.SendAsync("SendMessage",
        _hub.Clients.All.SendAsync("SendMessage",
            new
            {
                val1 = getRandomString(),
                val2 = getRandomString(),
                val3 = getRandomString(),
                val4 = getRandomString()
            });

        return Ok(new { Message = "Request Completed" });
    }
</code>```

答:
You can send notifications to a specified if you know the users connectionId or add the connected user to an group.

In the hub, assuming you know the connectionId:

await this.Clients.Client("connectionId").SendAsync("MethodName", "The message");
```

<p>You also can add a specified user in to a group and then send the message to the group:</p>

<pre class="lang-cs prettyprint-override"><code>await this.Groups.AddToGroupAsync("connectionId", "groupName");

await this.Clients.Group("groupName").SendAsync("MethodName", "The message");
</code>```

You can read more about it in this Microsoft Documentation.

Update:

To answer your updated question, you must provide the authorization attribute to your hub in order to have identity name and other parameters

[Authorize]
public class NotificationHub : Hub
{
    public override async Task OnConnectedAsync()
    {
        await Groups.AddToGroupAsync(Context.ConnectionId, Context.User.Identity.Name);
        await base.OnConnectedAsync();
    }

    public override async Task OnDisconnectedAsync(Exception ex)
    {
        await Groups.RemoveFromGroupAsync(Context.ConnectionId, Context.User.Identity.Name);
        await base.OnDisconnectedAsync(ex);
    }
}
```

<p>And then on your Angular client, you must provide a token to connect to your hub like:</p>

<pre class="lang-js prettyprint-override"><code>private configureSignalR(token: string) {
    this.hubMessageConnection = new signalR.HubConnectionBuilder()
    .configureLogging(signalR.LogLevel.Error).withUrl(this.signalRUrl + "/notifications",
    {
        accessTokenFactory: () => token
    })
    .withAutomaticReconnect()
    .build();
}
</code>```

You can read more about Authentication and authorization in the microsoft documentation.

Body:
I have a requirement to send notification to specific user. I am using dotnet core 3.1. ASPNETCORE signalR for the notification.
I am able to send the messages to all clients but unablt to do so for specific user.

EDIT 1

My Hub looks like :

public class NotificationHub : Hub
{
    public override async Task OnConnectedAsync()
    {
        await Groups.AddToGroupAsync(Context.ConnectionId, Context.User.Identity.Name);
        await base.OnConnectedAsync();
    }

    public override async Task OnDisconnectedAsync(Exception ex)
    {
        await Groups.RemoveFromGroupAsync(Context.ConnectionId, Context.User.Identity.Name);
        await base.OnDisconnectedAsync(ex);
    }
}

And i am calling the SendAsync method from Controller as :

 private IHubContext<NotificationHub> _hub;

    public NotificationController(IHubContext<NotificationHub> hub)
    {
        _hub = hub;
    }

[HttpGet]
    public IActionResult Get()
    {
        //_hub.Clients.All.SendAsync("SendMessage",
        _hub.Clients.All.SendAsync("SendMessage",
            new
            {
                val1 = getRandomString(),
                val2 = getRandomString(),
                val3 = getRandomString(),
                val4 = getRandomString()
            });

        return Ok(new { Message = "Request Completed" });
    }

Body:
You can send notifications to a specified if you know the users connectionId or add the connected user to an group.

In the hub, assuming you know the connectionId:

await this.Clients.Client("connectionId").SendAsync("MethodName", "The message");

You also can add a specified user in to a group and then send the message to the group:

await this.Groups.AddToGroupAsync("connectionId", "groupName");

await this.Clients.Group("groupName").SendAsync("MethodName", "The message");

You can read more about it in this Microsoft Documentation.

Update:

To answer your updated question, you must provide the authorization attribute to your hub in order to have identity name and other parameters

[Authorize]
public class NotificationHub : Hub
{
    public override async Task OnConnectedAsync()
    {
        await Groups.AddToGroupAsync(Context.ConnectionId, Context.User.Identity.Name);
        await base.OnConnectedAsync();
    }

    public override async Task OnDisconnectedAsync(Exception ex)
    {
        await Groups.RemoveFromGroupAsync(Context.ConnectionId, Context.User.Identity.Name);
        await base.OnDisconnectedAsync(ex);
    }
}

And then on your Angular client, you must provide a token to connect to your hub like:

private configureSignalR(token: string) {
    this.hubMessageConnection = new signalR.HubConnectionBuilder()
    .configureLogging(signalR.LogLevel.Error).withUrl(this.signalRUrl + "/notifications",
    {
        accessTokenFactory: () => token
    })
    .withAutomaticReconnect()
    .build();
}

You can read more about Authentication and authorization in the microsoft documentation.


来源: stackexchange

问:
Resolution problem in C# .NET Winform application
I have developed my winform application without caring about the resolution. Now am stuck up on PCs with a lower resolution. What to do now? Is there any way of conversion? I mean can the application get the resolution of the PC on which it is running, and set itself accordingly? Is there not any code or variable of Resolution in Windows which can be used ?</p>

答: Hard to advice something... When you created your forms you should take care about smaller screens: http://www.techrepublic.com/article/manage-winform-controls-using-the-anchor-and-dock-properties/6165908</p>

ContentLicense: CC BY-SA 3.0


问:
Jmeter 5.2.1 and Kafka
everyone, I'm testing Jmeter (5.2.1) versus a Kafka server, eventually, I will be hitting Heroku but for now, I'm testing locally.

I followed the steps from this youtube video but is not working and I cannot see why.

I installed and ran Kafka using the steps from the link below on the sources and it works fine testing from the terminal but JMETER just shows some logs but nothing else... Can anyone share some light?... Thanks!!

I'm supposed to see the messages produced by JMeter on the consumer terminal but nothing :(

Install Kafka Locally:
[https://medium.com/@Ankitthakur/apache-kafka-installation-on-mac-using-homebrew-a367cdefd273].

Video Tutorial on Windows: [https://www.youtube.com/watch?v=6288UEUmgWA].

Test Plan (JMX) and JSON files: [https://drive.google.com/drive/folders/1_qG4890t_Qsqx9_X04PrScu573jzUNfI?usp=sharing].

答:
I think you need to use fully qualified class names for these kafka_message_serializer and kafka_key_serializer, for example one of these:

for example org.apache.kafka.common.serialization.StringDeserializer

You might also want to try Pepper-Box - Kafka Load Generator as it looks like to be more up-to-date and flexible.

Check out Apache Kafka - How to Load Test with JMeter article for more details.

ContentLicense: CC BY-SA 4.0

Title: Jmeter 5.2.1 and Kafka


问:
How to get a calculated column based on 2 different column in Power Query
Appreciate for any helps and suggestions.
I have a table structure as following:-

```<code>  Date,   Product Code   ,Result ,Schedule
  Day1,   A              ,0      ,0
  Day2,   A              ,20     ,100
  Day3,   A              ,200    ,100
</code>```

How can i add a new column [Different] which reset by product code

```<code>  Date   ,Product Code   ,Result ,Schedule ,Different
  Day1   ,A              ,0      ,0        ,0
  Day2   ,A              ,20     ,100      ,-80
  Day3   ,A              ,200    ,100      ,20
</code>```

Where different = previous's different + result - schedule

thank you.

答:
Try to achieve that with a Column From Examples, and type what you want to see in the new column. It usually works fine for me.

Documentation in case you have never used it before:
https://learn.microsoft.com/en-us/power-bi/desktop-add-column-from-example

Body:
Appreciate for any helps and suggestions.
I have a table structure as following:-

  Date,   Product Code   ,Result ,Schedule
  Day1,   A              ,0      ,0
  Day2,   A              ,20     ,100
  Day3,   A              ,200    ,100

How can i add a new column [Different] which reset by product code

  Date   ,Product Code   ,Result ,Schedule ,Different
  Day1   ,A              ,0      ,0        ,0
  Day2   ,A              ,20     ,100      ,-80
  Day3   ,A              ,200    ,100      ,20

Where different = previous's different + result - schedule

thank you.


问:
Why is typename necessary in return type? C++
Given a template class Queue with a nested Node struct.

Why is typename needed in the return type here?

```<code>template<typename T>
typename Queue<T>::Node* Queue<T>::test() {}
</code>```

The nested struct Node in the template class Queue would be in the scope of Queue<T>:: without typename.

According to Where and why do I have to put the "template" and "typename" keywords?:

We decide how the compiler should parse this. If t::x is a dependent
  name, then we need to prefix it by typename to tell the compiler to
  parse it in a certain way.

But I don't see why it justifies using typename?

答:
While parsing the return type (as defined in the question) we are not in the scope of Queue<T> yet. Your reasoning would be correct if you were to write

```<code>template<typename T>
auto Queue<T>::test() -> Node* {

}
</code>```

The nested name qualifier of the fully qualified function name puts us into the scope of the current template specialization. Here unqualified name lookup finds Node* in the current specialization, where it is known to refer to a type.

But while parsing the return type in your question the compiler hasn't yet encountered the "current specialization" where Node* can be unambiguously assumed to name a type. All it sees is us writing a dependent name from some specialization. As such, typename is required. It's no different to us having to write

```<code>template<typename T>
typename OtherUnrelatedClass<T>::Node* Queue<T>::test() {

}
</code>```

Body:
Given a template class Queue with a nested Node struct.

Why is typename needed in the return type here?

template<typename T>
typename Queue<T>::Node* Queue<T>::test() {}

The nested struct Node in the template class Queue would be in the scope of Queue<T>:: without typename.

According to Where and why do I have to put the "template" and "typename" keywords?:

We decide how the compiler should parse this. If t::x is a dependent
  name, then we need to prefix it by typename to tell the compiler to
  parse it in a certain way.

But I don't see why it justifies using typename?

Body:
While parsing the return type (as defined in the question) we are not in the scope of Queue<T> yet. Your reasoning would be correct if you were to write

template<typename T>
auto Queue<T>::test() -> Node* {

}

The nested name qualifier of the fully qualified function name puts us into the scope of the current template specialization. Here unqualified name lookup finds Node* in the current specialization, where it is known to refer to a type.

But while parsing the return type in your question the compiler hasn't yet encountered the "current specialization" where Node* can be unambiguously assumed to name a type. All it sees is us writing a dependent name from some specialization. As such, typename is required. It's no different to us having to write

template<typename T>
typename OtherUnrelatedClass<T>::Node* Queue<T>::test() {

}


问:
Change the title of Solution Explorer in Visual Studio?
My job forces me to work in Visual Studio and .NET. I'm attempting to streamline the experience, somewhat successfully. (TFS still thwarts me.)

Right now, I want to work with multiple Solution Explorers, as we have a Visual Studio solution containing a multitude of csproj files. Creating a new Solution Explorer view for each commonly-used project would be great, except for this - all of the tabs and titles say "Solution Explorer".

Is there any way to change the title of the Solution Explorer window and tab? Is there any way to set the title to the title of the root solution or project file? (If there's an extension that will do this, I will happily install it.)

Thank you.

Edit: It looks like my question wasn't understood very well. The project conforms to regular standards - it's one Solution with multiple Projects, with a highly-nested directory structure. Basically, instead of having to scroll a lot, and constantly open and close nodes in the tree view, I'd like to have multiple Solution Windows to help facilitate this. Visual Studio provides an option called New Solution Explorer View in the context menu, which will open a new Solution Explorer window with a target object at its root. I want to do this for the commonly-used projects in my solution, but I want each Explorer instance to be named so that I can keep them in a single pane and click between them. Make sense?

Hope I've appeased the VS enthusiasts.

Double Edit: This is the feature I'm looking for. Is this possible through an extension?

答:
There exists a visual studio-extension named Multiple Solution Explorer Tools, which extends the default behavior of the New Solution Explorer View-command:

Multiple Solution Explorer Tools Visual Studio Extension

New Solution Explorer instances gets persisted across solution unload and load.

The toolbar provides an icon () to rename the current solution explorer view.

The extension currently supports Visual Studio 2017 and 2019.


问:
Convert Pdf response from API Call to Blob and generate Blob Url
I am trying to convert the response to blob and then generate url to access that. The response from the get request is Pdf.

Here's what I am doing.

```<code>this.$http.get<string>(
        invoicePath
      ).then((response:any)=> {
        console.log("CREATING A BLOB")
        console.log("RESPONSE BLOB: ", response.data);
        const blob:any = new Blob([response], { type: 'application/pdf; charset=utf-8' });
        console.log("RESPONSE BLOB: ", blob);
        const url= window.URL.createObjectURL(blob);
        // window.open(url);
        return url
        //window.location.href = response.url;
      })
</code>```

The url returned gives me the below error message.

答:
We have to convert the response to ArrayBuffer first.</p>

```<code>this.$http.get<string>(
        invoicePath, {responseType:'arraybuffer'}
      ).then((response:any)=> {
        console.log("CREATING A BLOB")
        console.log("RESPONSE BLOB: ", response.data);
        const blob:any = new Blob([response.data], { type: 'application/pdf; charset=utf-8' });
        console.log("RESPONSE BLOB: ", blob);
        const url= window.URL.createObjectURL(blob);
        // window.open(url);
        return url
        //window.location.href = response.url;
      })
</code>```

Body:
I am trying to convert the response to blob and then generate url to access that. The response from the get request is Pdf.

Here's what I am doing.

this.$http.get<string>(
        invoicePath
      ).then((response:any)=> {
        console.log("CREATING A BLOB")
        console.log("RESPONSE BLOB: ", response.data);
        const blob:any = new Blob([response], { type: 'application/pdf; charset=utf-8' });
        console.log("RESPONSE BLOB: ", blob);
        const url= window.URL.createObjectURL(blob);
        // window.open(url);
        return url
        //window.location.href = response.url;
      })

The url returned gives me the below error message.

Body:
We have to convert the response to ArrayBuffer first.

this.$http.get<string>(
        invoicePath, {responseType:'arraybuffer'}
      ).then((response:any)=> {
        console.log("CREATING A BLOB")
        console.log("RESPONSE BLOB: ", response.data);
        const blob:any = new Blob([response.data], { type: 'application/pdf; charset=utf-8' });
        console.log("RESPONSE BLOB: ", blob);
        const url= window.URL.createObjectURL(blob);
        // window.open(url);
        return url
        //window.location.href = response.url;
      })


问:
How to solve 'import pycocotools._mask is not a valid win32 application' in tensorflow 1.13.1 and python 3.7?
I'm using object detection raccoon by datitran(https://github.com/datitran/raccoon_dataset) to train my own dataset and met an issue.

Environment Info.:

OS:Windows 10 64bit

CUDA and CUDNN: CUDA 10/CUDNN 7.5.0

Tensorflow version:1.13.1(GPU)

Python version:3.7.0 64 bit (Anaconda, Inc. on win32)

Model:ssd_mobilenet_v1_coco

Issue:

I want to start trainning by

```<code>python model_main.py
--pipeline_config_path=Z:/Train/ssd_mobilenet_v1_coco_ship.config
--model_dir=Z:/Train/train
--alsologtostderr
</code>```

and met an error

```<code>    Traceback (most recent call last):
  File "model_main.py", line 26, in <module>
    from object_detection import model_lib
  File "D:\Anaconda\envs\tensorflow\Lib\models\research\object_detection\model_lib.py", line 27, in <module>
    from object_detection import eval_util
  File "D:\Anaconda\envs\tensorflow\Lib\models\research\object_detection\eval_util.py", line 27, in <module>
    from object_detection.metrics import coco_evaluation
  File "D:\Anaconda\envs\tensorflow\Lib\models\research\object_detection\metrics\coco_evaluation.py", line 20, in <module>
    from object_detection.metrics import coco_tools
  File "D:\Anaconda\envs\tensorflow\Lib\models\research\object_detection\metrics\coco_tools.py", line 47, in <module>
    from pycocotools import coco
  File "D:\Anaconda\envs\tensorflow\lib\site-packages\pycocotools\coco.py", line 56, in <module>
    from . import mask as maskUtils
  File "D:\Anaconda\envs\tensorflow\lib\site-packages\pycocotools\mask.py", line 3, in <module>
    import pycocotools._mask as _mask
ImportError: DLL load failed: %1 is not a valid Win32 application.
</code>```

Besides, I also tried old version command train.py in ~\research\object_detection\legacyby

```<code>python train.py
--logtostderr
--pipeline_config_path=Z:/Train/ssd_mobilenet_v1_coco_ship.config
--train_dir=Z:/Train/train
</code>```

but it also failed to work:

```<code>WARNING: The TensorFlow contrib module will not be included in TensorFlow 2.0.
For more information, please see:
  * https://github.com/tensorflow/community/blob/master/rfcs/20180907-contrib-sunset.md
  * https://github.com/tensorflow/addons
If you depend on functionality not listed there, please file an issue.

WARNING:tensorflow:From D:\Anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\platform\app.py:125: main (from __main__) is deprecated and will be removed in a future version.
Instructions for updating:
Use object_detection/model_main.py.
WARNING:tensorflow:From D:\Anaconda\envs\tensorflow\Lib\models\research\object_detection\legacy\trainer.py:266: create_global_step (from tensorflow.contrib.framework.python.ops.variables) is deprecated and will be removed in a future version.
Instructions for updating:
Please switch to tf.train.create_global_step
WARNING:tensorflow:From D:\Anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\framework\op_def_library.py:263: colocate_with (from tensorflow.python.framework.ops) is deprecated and will be removed in a future version.
Instructions for updating:
Colocations handled automatically by placer.
WARNING:tensorflow:num_readers has been reduced to 1 to match input file shards.
WARNING:tensorflow:From D:\Anaconda\envs\tensorflow\Lib\models\research\object_detection\builders\dataset_builder.py:80: parallel_interleave (from tensorflow.contrib.data.python.ops.interleave_ops) is deprecated and will be removed in a future version.
Instructions for updating:
Use `tf.data.experimental.parallel_interleave(...)`.
Traceback (most recent call last):
  File "train.py", line 186, in <module>
    tf.app.run()
  File "D:\Anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\platform\app.py", line 125, in run
    _sys.exit(main(argv))
  File "D:\Anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\util\deprecation.py", line 324, in new_func
    return func(*args, **kwargs)
  File "train.py", line 182, in main
    graph_hook_fn=graph_rewriter_fn)
  File "D:\Anaconda\envs\tensorflow\Lib\models\research\object_detection\legacy\trainer.py", line 280, in train
    train_config.prefetch_queue_capacity, data_augmentation_options)
  File "D:\Anaconda\envs\tensorflow\Lib\models\research\object_detection\legacy\trainer.py", line 59, in create_input_queue
    tensor_dict = create_tensor_dict_fn()
  File "train.py", line 123, in get_next
    dataset_builder.build(config)).get_next()
  File "D:\Anaconda\envs\tensorflow\Lib\models\research\object_detection\builders\dataset_builder.py", line 134, in build
    config.input_path[:], input_reader_config)
  File "D:\Anaconda\envs\tensorflow\Lib\models\research\object_detection\builders\dataset_builder.py", line 80, in read_dataset
    sloppy=config.shuffle))
  File "D:\Anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\data\ops\dataset_ops.py", line 1605, in apply
    return DatasetV1Adapter(super(DatasetV1, self).apply(transformation_func))
  File "D:\Anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\data\ops\dataset_ops.py", line 1127, in apply
    dataset = transformation_func(self)
  File "D:\Anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\data\experimental\ops\interleave_ops.py", line 88, in _apply_fn
    buffer_output_elements, prefetch_input_elements)
  File "D:\Anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\data\ops\readers.py", line 133, in __init__
    cycle_length, block_length)
  File "D:\Anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\data\ops\dataset_ops.py", line 2827, in __init__
    super(InterleaveDataset, self).__init__(input_dataset, map_func)
  File "D:\Anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\data\ops\dataset_ops.py", line 2798, in __init__
    map_func, self._transformation_name(), dataset=input_dataset)
  File "D:\Anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\data\ops\dataset_ops.py", line 2124, in __init__
    self._function.add_to_graph(ops.get_default_graph())
  File "D:\Anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\framework\function.py", line 490, in add_to_graph
    self._create_definition_if_needed()
  File "D:\Anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\framework\function.py", line 341, in _create_definition_if_needed
    self._create_definition_if_needed_impl()
  File "D:\Anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\framework\function.py", line 355, in _create_definition_if_needed_impl
    whitelisted_stateful_ops=self._whitelisted_stateful_ops)
  File "D:\Anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\framework\function.py", line 883, in func_graph_from_py_func
    outputs = func(*func_graph.inputs)
  File "D:\Anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\data\ops\dataset_ops.py", line 2099, in tf_data_structured_function_wrapper
    ret = func(*nested_args)
  File "D:\Anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\data\ops\readers.py", line 247, in __init__
    filenames, compression_type, buffer_size, num_parallel_reads)
  File "D:\Anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\data\ops\readers.py", line 212, in __init__
    self._impl = filenames.flat_map(read_one_file)
  File "D:\Anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\data\ops\dataset_ops.py", line 1005, in flat_map
    return FlatMapDataset(self, map_func)
  File "D:\Anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\data\ops\dataset_ops.py", line 2798, in __init__
    map_func, self._transformation_name(), dataset=input_dataset)
  File "D:\Anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\data\ops\dataset_ops.py", line 2124, in __init__
    self._function.add_to_graph(ops.get_default_graph())
  File "D:\Anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\framework\function.py", line 490, in add_to_graph
    self._create_definition_if_needed()
  File "D:\Anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\framework\function.py", line 341, in _create_definition_if_needed
    self._create_definition_if_needed_impl()
  File "D:\Anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\framework\function.py", line 355, in _create_definition_if_needed_impl
    whitelisted_stateful_ops=self._whitelisted_stateful_ops)
  File "D:\Anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\framework\function.py", line 883, in func_graph_from_py_func
    outputs = func(*func_graph.inputs)
  File "D:\Anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\data\ops\dataset_ops.py", line 2099, in tf_data_structured_function_wrapper
    ret = func(*nested_args)
  File "D:\Anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\data\ops\readers.py", line 209, in read_one_file
    return _TFRecordDataset(filename, compression_type, buffer_size)
  File "D:\Anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\data\ops\readers.py", line 111, in __init__
    argument_dtype=dtypes.string)
  File "D:\Anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\data\util\convert.py", line 35, in optional_param_to_tensor
    argument_default, dtype=argument_dtype, name=argument_name)
  File "D:\Anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\framework\constant_op.py", line 245, in constant
    allow_broadcast=True)
  File "D:\Anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\framework\constant_op.py", line 283, in _constant_impl
    allow_broadcast=allow_broadcast))
  File "D:\Anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\framework\tensor_util.py", line 501, in make_tensor_proto
    (dtype, nparray.dtype, values))
TypeError: Incompatible types: <dtype: 'string'> vs. object. Value is
</code>```

What should I do to make any of them work?

答:
Hey for anyone using windows for me this actually worked.

1) Install Visual C++ 2015 Build Tools from https://go.microsoft.com/fwlink/?LinkId=691126 with the default selection.

2) Go to C:\Program Files (x86)\Microsoft Visual C++ Build Tools and run vcbuildtools_msbuild.bat

3)Then in Anaconda copy and run this (you have to have installed git ... if not just use pip install git)

pip install

git+https://github.com/philferriere/cocoapi.git#egg=pycocotools^&subdirectory=PythonAPI

Hope it works for you too :)

Body:
I'm using object detection raccoon by datitran(https://github.com/datitran/raccoon_dataset) to train my own dataset and met an issue.

Environment Info.:

OS:Windows 10 64bit

CUDA and CUDNN: CUDA 10/CUDNN 7.5.0

Tensorflow version:1.13.1(GPU)

Python version:3.7.0 64 bit (Anaconda, Inc. on win32)

Model:ssd_mobilenet_v1_coco

Issue:

I want to start trainning by

python model_main.py
--pipeline_config_path=Z:/Train/ssd_mobilenet_v1_coco_ship.config
--model_dir=Z:/Train/train
--alsologtostderr

and met an error

    Traceback (most recent call last):
  File "model_main.py", line 26, in <module>
    from object_detection import model_lib
  File "D:\Anaconda\envs\tensorflow\Lib\models\research\object_detection\model_lib.py", line 27, in <module>
    from object_detection import eval_util
  File "D:\Anaconda\envs\tensorflow\Lib\models\research\object_detection\eval_util.py", line 27, in <module>
    from object_detection.metrics import coco_evaluation
  File "D:\Anaconda\envs\tensorflow\Lib\models\research\object_detection\metrics\coco_evaluation.py", line 20, in <module>
    from object_detection.metrics import coco_tools
  File "D:\Anaconda\envs\tensorflow\Lib\models\research\object_detection\metrics\coco_tools.py", line 47, in <module>
    from pycocotools import coco
  File "D:\Anaconda\envs\tensorflow\lib\site-packages\pycocotools\coco.py", line 56, in <module>
    from . import mask as maskUtils
  File "D:\Anaconda\envs\tensorflow\lib\site-packages\pycocotools\mask.py", line 3, in <module>
    import pycocotools._mask as _mask
ImportError: DLL load failed: %1 is not a valid Win32 application.

Besides, I also tried old version command train.py in ~\research\object_detection\legacyby

python train.py
--logtostderr
--pipeline_config_path=Z:/Train/ssd_mobilenet_v1_coco_ship.config
--train_dir=Z:/Train/train

but it also failed to work:

WARNING: The TensorFlow contrib module will not be included in TensorFlow 2.0.
For more information, please see:
  * https://github.com/tensorflow/community/blob/master/rfcs/20180907-contrib-sunset.md
  * https://github.com/tensorflow/addons
If you depend on functionality not listed there, please file an issue.

WARNING:tensorflow:From D:\Anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\platform\app.py:125: main (from __main__) is deprecated and will be removed in a future version.
Instructions for updating:
Use object_detection/model_main.py.
WARNING:tensorflow:From D:\Anaconda\envs\tensorflow\Lib\models\research\object_detection\legacy\trainer.py:266: create_global_step (from tensorflow.contrib.framework.python.ops.variables) is deprecated and will be removed in a future version.
Instructions for updating:
Please switch to tf.train.create_global_step
WARNING:tensorflow:From D:\Anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\framework\op_def_library.py:263: colocate_with (from tensorflow.python.framework.ops) is deprecated and will be removed in a future version.
Instructions for updating:
Colocations handled automatically by placer.
WARNING:tensorflow:num_readers has been reduced to 1 to match input file shards.
WARNING:tensorflow:From D:\Anaconda\envs\tensorflow\Lib\models\research\object_detection\builders\dataset_builder.py:80: parallel_interleave (from tensorflow.contrib.data.python.ops.interleave_ops) is deprecated and will be removed in a future version.
Instructions for updating:
Use `tf.data.experimental.parallel_interleave(...)`.
Traceback (most recent call last):
  File "train.py", line 186, in <module>
    tf.app.run()
  File "D:\Anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\platform\app.py", line 125, in run
    _sys.exit(main(argv))
  File "D:\Anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\util\deprecation.py", line 324, in new_func
    return func(*args, **kwargs)
  File "train.py", line 182, in main
    graph_hook_fn=graph_rewriter_fn)
  File "D:\Anaconda\envs\tensorflow\Lib\models\research\object_detection\legacy\trainer.py", line 280, in train
    train_config.prefetch_queue_capacity, data_augmentation_options)
  File "D:\Anaconda\envs\tensorflow\Lib\models\research\object_detection\legacy\trainer.py", line 59, in create_input_queue
    tensor_dict = create_tensor_dict_fn()
  File "train.py", line 123, in get_next
    dataset_builder.build(config)).get_next()
  File "D:\Anaconda\envs\tensorflow\Lib\models\research\object_detection\builders\dataset_builder.py", line 134, in build
    config.input_path[:], input_reader_config)
  File "D:\Anaconda\envs\tensorflow\Lib\models\research\object_detection\builders\dataset_builder.py", line 80, in read_dataset
    sloppy=config.shuffle))
  File "D:\Anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\data\ops\dataset_ops.py", line 1605, in apply
    return DatasetV1Adapter(super(DatasetV1, self).apply(transformation_func))
  File "D:\Anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\data\ops\dataset_ops.py", line 1127, in apply
    dataset = transformation_func(self)
  File "D:\Anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\data\experimental\ops\interleave_ops.py", line 88, in _apply_fn
    buffer_output_elements, prefetch_input_elements)
  File "D:\Anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\data\ops\readers.py", line 133, in __init__
    cycle_length, block_length)
  File "D:\Anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\data\ops\dataset_ops.py", line 2827, in __init__
    super(InterleaveDataset, self).__init__(input_dataset, map_func)
  File "D:\Anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\data\ops\dataset_ops.py", line 2798, in __init__
    map_func, self._transformation_name(), dataset=input_dataset)
  File "D:\Anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\data\ops\dataset_ops.py", line 2124, in __init__
    self._function.add_to_graph(ops.get_default_graph())
  File "D:\Anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\framework\function.py", line 490, in add_to_graph
    self._create_definition_if_needed()
  File "D:\Anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\framework\function.py", line 341, in _create_definition_if_needed
    self._create_definition_if_needed_impl()
  File "D:\Anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\framework\function.py", line 355, in _create_definition_if_needed_impl
    whitelisted_stateful_ops=self._whitelisted_stateful_ops)
  File "D:\Anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\framework\function.py", line 883, in func_graph_from_py_func
    outputs = func(*func_graph.inputs)
  File "D:\Anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\data\ops\dataset_ops.py", line 2099, in tf_data_structured_function_wrapper
    ret = func(*nested_args)
  File "D:\Anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\data\ops\readers.py", line 247, in __init__
    filenames, compression_type, buffer_size, num_parallel_reads)
  File "D:\Anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\data\ops\readers.py", line 212, in __init__
    self._impl = filenames.flat_map(read_one_file)
  File "D:\Anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\data\ops\dataset_ops.py", line 1005, in flat_map
    return FlatMapDataset(self, map_func)
  File "D:\Anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\data\ops\dataset_ops.py", line 2798, in __init__
    map_func, self._transformation_name(), dataset=input_dataset)
  File "D:\Anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\data\ops\dataset_ops.py", line 2124, in __init__
    self._function.add_to_graph(ops.get_default_graph())
  File "D:\Anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\framework\function.py", line 490, in add_to_graph
    self._create_definition_if_needed()
  File "D:\Anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\framework\function.py", line 341, in _create_definition_if_needed
    self._create_definition_if_needed_impl()
  File "D:\Anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\framework\function.py", line 355, in _create_definition_if_needed_impl
    whitelisted_stateful_ops=self._whitelisted_stateful_ops)
  File "D:\Anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\framework\function.py", line 883, in func_graph_from_py_func
    outputs = func(*func_graph.inputs)
  File "D:\Anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\data\ops\dataset_ops.py", line 2099, in tf_data_structured_function_wrapper
    ret = func(*nested_args)
  File "D:\Anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\data\ops\readers.py", line 209, in read_one_file
    return _TFRecordDataset(filename, compression_type, buffer_size)
  File "D:\Anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\data\ops\readers.py", line 111, in __init__
    argument_dtype=dtypes.string)
  File "D:\Anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\data\util\convert.py", line 35, in optional_param_to_tensor
    argument_default, dtype=argument_dtype, name=argument_name)
  File "D:\Anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\framework\constant_op.py", line 245, in constant
    allow_broadcast=True)
  File "D:\Anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\framework\constant_op.py", line 283, in _constant_impl
    allow_broadcast=allow_broadcast))
  File "D:\Anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\framework\tensor_util.py", line 501, in make_tensor_proto
    (dtype, nparray.dtype, values))
TypeError: Incompatible types: <dtype: 'string'> vs. object. Value is

What should I do to make any of them work?


问:
Using Pandas query() to filter dataframe on a timestamp column
I'm trying to filter a Pandas dataframe using a string and function query() on a timestamp column:

```<code>df.query('Timestamp < "2020-02-01"')
</code>```

However, I get the following error:

```<code>Traceback (most recent call last):
File "C:\ENERCON\Python 3.7.2\lib\site-packages\IPython\core\interactiveshell.py", line 3326, in run_code
     exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-3-7bb40e9c631a>", line 1, in <module>
     df.query('Timestamp < "2020-02-01"')
File "C:\ENERCON\Python 3.7.2\lib\site-packages\pandas\core\frame.py", line 3199, in query
     res = self.eval(expr, **kwargs)
File "C:\ENERCON\Python 3.7.2\lib\site-packages\pandas\core\frame.py", line 3315, in eval
     return _eval(expr, inplace=inplace, **kwargs)
File "C:\ENERCON\Python 3.7.2\lib\site-packages\pandas\core\computation\eval.py", line 327, in eval
     ret = eng_inst.evaluate()
File "C:\ENERCON\Python 3.7.2\lib\site-packages\pandas\core\computation\engines.py", line 142, in evaluate
     return self.expr()
File "C:\ENERCON\Python 3.7.2\lib\site-packages\pandas\core\computation\expr.py", line 837, in __call__
     return self.terms(self.env)
File "C:\ENERCON\Python 3.7.2\lib\site-packages\pandas\core\computation\ops.py", line 380, in __call__
     return self.func(left, right)
TypeError: '<' not supported between instances of 'type' and 'str'
</code>```

Also tried to convert the string to datetime, but the error is similar.

```<code>df.query('Timestamp < @pd.to_datetime("2020-02-01")')
Traceback (most recent call last):
  File "C:\ENERCON\Python 3.7.2\lib\site-packages\IPython\core\interactiveshell.py", line 3326, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-5-23540526aad9>", line 1, in <module>
    df.query('Timestamp < @pd.to_datetime("2020-02-01")')
  File "C:\ENERCON\Python 3.7.2\lib\site-packages\pandas\core\frame.py", line 3199, in query
    res = self.eval(expr, **kwargs)
  File "C:\ENERCON\Python 3.7.2\lib\site-packages\pandas\core\frame.py", line 3315, in eval
    return _eval(expr, inplace=inplace, **kwargs)
  File "C:\ENERCON\Python 3.7.2\lib\site-packages\pandas\core\computation\eval.py", line 322, in eval
    parsed_expr = Expr(expr, engine=engine, parser=parser, env=env, truediv=truediv)
  File "C:\ENERCON\Python 3.7.2\lib\site-packages\pandas\core\computation\expr.py", line 830, in __init__
    self.terms = self.parse()
  File "C:\ENERCON\Python 3.7.2\lib\site-packages\pandas\core\computation\expr.py", line 847, in parse
    return self._visitor.visit(self.expr)
  File "C:\ENERCON\Python 3.7.2\lib\site-packages\pandas\core\computation\expr.py", line 441, in visit
    return visitor(node, **kwargs)
  File "C:\ENERCON\Python 3.7.2\lib\site-packages\pandas\core\computation\expr.py", line 447, in visit_Module
    return self.visit(expr, **kwargs)
  File "C:\ENERCON\Python 3.7.2\lib\site-packages\pandas\core\computation\expr.py", line 441, in visit
    return visitor(node, **kwargs)
  File "C:\ENERCON\Python 3.7.2\lib\site-packages\pandas\core\computation\expr.py", line 450, in visit_Expr
    return self.visit(node.value, **kwargs)
  File "C:\ENERCON\Python 3.7.2\lib\site-packages\pandas\core\computation\expr.py", line 441, in visit
    return visitor(node, **kwargs)
  File "C:\ENERCON\Python 3.7.2\lib\site-packages\pandas\core\computation\expr.py", line 747, in visit_Compare
    return self.visit(binop)
  File "C:\ENERCON\Python 3.7.2\lib\site-packages\pandas\core\computation\expr.py", line 441, in visit
    return visitor(node, **kwargs)
  File "C:\ENERCON\Python 3.7.2\lib\site-packages\pandas\core\computation\expr.py", line 565, in visit_BinOp
    return self._maybe_evaluate_binop(op, op_class, left, right)
  File "C:\ENERCON\Python 3.7.2\lib\site-packages\pandas\core\computation\expr.py", line 547, in _maybe_evaluate_binop
    return self._maybe_eval(res, self.binary_ops)
  File "C:\ENERCON\Python 3.7.2\lib\site-packages\pandas\core\computation\expr.py", line 519, in _maybe_eval
    self.env, self.engine, self.parser, self.term_type, eval_in_python
  File "C:\ENERCON\Python 3.7.2\lib\site-packages\pandas\core\computation\ops.py", line 399, in evaluate
    res = self(env)
  File "C:\ENERCON\Python 3.7.2\lib\site-packages\pandas\core\computation\ops.py", line 380, in __call__
    return self.func(left, right)
TypeError: '<' not supported between instances of 'type' and 'Timestamp'
</code>```

If I run the equivalent function using .loc I have the desired results (but I can't use a user input string).

```<code>df.loc[df['Timestamp'] < "2020-02-01"]
Out[4]:
     Timestamp  Error  ...  ToD  Day_Night
0    2020-01-17 00:00:00      0  ...    0      Night
1    2020-01-17 00:10:00      0  ...    0      Night
2    2020-01-17 00:20:00      0  ...    0      Night
3    2020-01-17 00:30:00      0  ...    0      Night
4    2020-01-17 00:40:00      0  ...    0      Night
2154 2020-01-31 23:10:00      0  ...   23      Night
2155 2020-01-31 23:20:00      0  ...   23      Night
2156 2020-01-31 23:30:00      0  ...   23      Night
2157 2020-01-31 23:40:00      0  ...   23      Night
2158 2020-01-31 23:50:00      0  ...   23      Night
[2159 rows x 37 columns]
</code>```

Does anyone knows how to use query() with datetime columns?

答:
The Timestamp column name shadows the built-in type timestamp. As a first step, you can rename the column to something else, using rename():

```<code>df.rename(columns={"Timestamp": "MyTimestamp"})
</code>```

Then the following should do the trick for the datetime:

```<code>df.query('MyTimestamp < 20200201')
</code>```

Alternatively, if you want to query the dataframe using a timestamp:

```<code>df.query('MyTimestamp < @ts("20200201T071320")'
</code>```

Body:
I'm trying to filter a Pandas dataframe using a string and function query() on a timestamp column:

df.query('Timestamp < "2020-02-01"')

However, I get the following error:

Traceback (most recent call last):
File "C:\ENERCON\Python 3.7.2\lib\site-packages\IPython\core\interactiveshell.py", line 3326, in run_code
     exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-3-7bb40e9c631a>", line 1, in <module>
     df.query('Timestamp < "2020-02-01"')
File "C:\ENERCON\Python 3.7.2\lib\site-packages\pandas\core\frame.py", line 3199, in query
     res = self.eval(expr, **kwargs)
File "C:\ENERCON\Python 3.7.2\lib\site-packages\pandas\core\frame.py", line 3315, in eval
     return _eval(expr, inplace=inplace, **kwargs)
File "C:\ENERCON\Python 3.7.2\lib\site-packages\pandas\core\computation\eval.py", line 327, in eval
     ret = eng_inst.evaluate()
File "C:\ENERCON\Python 3.7.2\lib\site-packages\pandas\core\computation\engines.py", line 142, in evaluate
     return self.expr()
File "C:\ENERCON\Python 3.7.2\lib\site-packages\pandas\core\computation\expr.py", line 837, in __call__
     return self.terms(self.env)
File "C:\ENERCON\Python 3.7.2\lib\site-packages\pandas\core\computation\ops.py", line 380, in __call__
     return self.func(left, right)
TypeError: '<' not supported between instances of 'type' and 'str'

Also tried to convert the string to datetime, but the error is similar.

df.query('Timestamp < @pd.to_datetime("2020-02-01")')
Traceback (most recent call last):
  File "C:\ENERCON\Python 3.7.2\lib\site-packages\IPython\core\interactiveshell.py", line 3326, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-5-23540526aad9>", line 1, in <module>
    df.query('Timestamp < @pd.to_datetime("2020-02-01")')
  File "C:\ENERCON\Python 3.7.2\lib\site-packages\pandas\core\frame.py", line 3199, in query
    res = self.eval(expr, **kwargs)
  File "C:\ENERCON\Python 3.7.2\lib\site-packages\pandas\core\frame.py", line 3315, in eval
    return _eval(expr, inplace=inplace, **kwargs)
  File "C:\ENERCON\Python 3.7.2\lib\site-packages\pandas\core\computation\eval.py", line 322, in eval
    parsed_expr = Expr(expr, engine=engine, parser=parser, env=env, truediv=truediv)
  File "C:\ENERCON\Python 3.7.2\lib\site-packages\pandas\core\computation\expr.py", line 830, in __init__
    self.terms = self.parse()
  File "C:\ENERCON\Python 3.7.2\lib\site-packages\pandas\core\computation\expr.py", line 847, in parse
    return self._visitor.visit(self.expr)
  File "C:\ENERCON\Python 3.7.2\lib\site-packages\pandas\core\computation\expr.py", line 441, in visit
    return visitor(node, **kwargs)
  File "C:\ENERCON\Python 3.7.2\lib\site-packages\pandas\core\computation\expr.py", line 447, in visit_Module
    return self.visit(expr, **kwargs)
  File "C:\ENERCON\Python 3.7.2\lib\site-packages\pandas\core\computation\expr.py", line 441, in visit
    return visitor(node, **kwargs)
  File "C:\ENERCON\Python 3.7.2\lib\site-packages\pandas\core\computation\expr.py", line 450, in visit_Expr
    return self.visit(node.value, **kwargs)
  File "C:\ENERCON\Python 3.7.2\lib\site-packages\pandas\core\computation\expr.py", line 441, in visit
    return visitor(node, **kwargs)
  File "C:\ENERCON\Python 3.7.2\lib\site-packages\pandas\core\computation\expr.py", line 747, in visit_Compare
    return self.visit(binop)
  File "C:\ENERCON\Python 3.7.2\lib\site-packages\pandas\core\computation\expr.py", line 441, in visit
    return visitor(node, **kwargs)
  File "C:\ENERCON\Python 3.7.2\lib\site-packages\pandas\core\computation\expr.py", line 565, in visit_BinOp
    return self._maybe_evaluate_binop(op, op_class, left, right)
  File "C:\ENERCON\Python 3.7.2\lib\site-packages\pandas\core\computation\expr.py", line 547, in _maybe_evaluate_binop
    return self._maybe_eval(res, self.binary_ops)
  File "C:\ENERCON\Python 3.7.2\lib\site-packages\pandas\core\computation\expr.py", line 519, in _maybe_eval
    self.env, self.engine, self.parser, self.term_type, eval_in_python
  File "C:\ENERCON\Python 3.7.2\lib\site-packages\pandas\core\computation\ops.py", line 399, in evaluate
    res = self(env)
  File "C:\ENERCON\Python 3.7.2\lib\site-packages\pandas\core\computation\ops.py", line 380, in __call__
    return self.func(left, right)
TypeError: '<' not supported between instances of 'type' and 'Timestamp'

If I run the equivalent function using .loc I have the desired results (but I can't use a user input string).

df.loc[df['Timestamp'] < "2020-02-01"]
Out[4]:
     Timestamp  Error  ...  ToD  Day_Night
0    2020-01-17 00:00:00      0  ...    0      Night
1    2020-01-17 00:10:00      0  ...    0      Night
2    2020-01-17 00:20:00      0  ...    0      Night
3    2020-01-17 00:30:00      0  ...    0      Night
4    2020-01-17 00:40:00      0  ...    0      Night
2154 2020-01-31 23:10:00      0  ...   23      Night
2155 2020-01-31 23:20:00      0  ...   23      Night
2156 2020-01-31 23:30:00      0  ...   23      Night
2157 2020-01-31 23:40:00      0  ...   23      Night
2158 2020-01-31 23:50:00      0  ...   23      Night
[2159 rows x 37 columns]

Does anyone knows how to use query() with datetime columns?

Body:
The Timestamp column name shadows the built-in type timestamp. As a first step, you can rename the column to something else, using rename():

df.rename(columns={"Timestamp": "MyTimestamp"})

Then the following should do the trick for the datetime:

df.query('MyTimestamp < 20200201')

Alternatively, if you want to query the dataframe using a timestamp:

df.query('MyTimestamp < @ts("20200201T071320")'


问:
Best way for Flutter Photo Management
I am creating an app where the user will select some photos for the avatars used in the app. Once selected, on the next launch I want to populate the avatars automatically.

Solution I am Thinking: I will keep a duplicate of the original photo in the app directory and next time I will use the photo to make the avatars.

Issue: Not efficient as the same copy of the image exists.

Question: Since many apps are doing this thing, I want to know the best way to do that, more specifically in Flutter?

答: I think you must copy the original photo, Most people use cloud service(google photos etc.) for their photos and not keep photos on phones any more..</p>

Title: Best way for Flutter Photo Management


问:
Adding subplots to a subplot
I'm trying to create a figure that consists of a 2x2 grid, where in each quadrant there are 2 vertically stacked subplots (i.e. a 2x1 grid). I can't seem to figure out how to achieve this, though.

The closest I've gotten is using gridspec and some ugly code (see below), but because gridspec.update(hspace=X) changes the spacing for all of the subplots I'm still not where I'd like to be.

Ideally what I want is to, using the picture below as an example, decrease the spacing between the subplots within each quadrant, while increasing the vertical spacing between the top and bottom quadrants (i.e. between 1-3 and 2-4).

Is there a way to do this (with or without using gridspec)? What I originally envisioned is generating each of the sub-subplot grids (i.e. each 2x1 grid) and inserting them into the larger 2x2 grid of subplots, but I haven't figured out how to add a subplot to a subplot, if there is even a way.

```<code>import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
plt.figure(figsize=(10, 8))
gs = gridspec.GridSpec(4,2)
gs.update(hspace=0.4)
for i in range(2):
    for j in range(4):
        ax = plt.subplot(gs[j,i])
        ax.spines['top'].set_visible(False)
        ax.spines['right'].set_visible(False)
        plt.tick_params(which='both', top='off', right='off')
        if j % 2 == 0:
            ax.set_title(str(i+j+1))
            ax.plot([1,2,3], [1,2,3])
            ax.spines['bottom'].set_visible(False)
            ax.get_xaxis().set_visible(False)
        else:
            ax.plot([1,2,3], [3,2,1])
</code>```

答:
As I had to rely on Suever's answer but had to modify it to my needs, I thought I might contribute in case someone finds it helpful:

```<code>import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

channelArrangement = [16, 17, 18 , 19 , 22, 25, 28 , 29 , 31]

fig = plt.figure(figsize=(10, 8))
outer = gridspec.GridSpec(1, 2, wspace=0.2, hspace=0.2)

for i in range(2):
    inner = gridspec.GridSpecFromSubplotSpec(3, 3, subplot_spec=outer[i],
                                             wspace=0.1, hspace=0.1)
    row     = 0
    col     = 0
    maxCol  = 3

    for chan in channelArrangement:
        ax = plt.Subplot(fig, inner[row,col])
        t= ax.text(0.5,0.5, 'outer=%d\nrow=%d\ncol=%d' % (i,row,col))
        ax.set_xticks([])
        ax.set_yticks([])
        t.set_ha('center')
        fig.add_subplot(ax)
        col += 1
        if col == maxCol:
            col = 0
            row += 1
plt.show()
</code>```

Title: Adding subplots to a subplot

Body:
I'm trying to create a figure that consists of a 2x2 grid, where in each quadrant there are 2 vertically stacked subplots (i.e. a 2x1 grid). I can't seem to figure out how to achieve this, though.

The closest I've gotten is using gridspec and some ugly code (see below), but because gridspec.update(hspace=X) changes the spacing for all of the subplots I'm still not where I'd like to be.

Ideally what I want is to, using the picture below as an example, decrease the spacing between the subplots within each quadrant, while increasing the vertical spacing between the top and bottom quadrants (i.e. between 1-3 and 2-4).

Is there a way to do this (with or without using gridspec)? What I originally envisioned is generating each of the sub-subplot grids (i.e. each 2x1 grid) and inserting them into the larger 2x2 grid of subplots, but I haven't figured out how to add a subplot to a subplot, if there is even a way.

import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
plt.figure(figsize=(10, 8))
gs = gridspec.GridSpec(4,2)
gs.update(hspace=0.4)
for i in range(2):
    for j in range(4):
        ax = plt.subplot(gs[j,i])
        ax.spines['top'].set_visible(False)
        ax.spines['right'].set_visible(False)
        plt.tick_params(which='both', top='off', right='off')
        if j % 2 == 0:
            ax.set_title(str(i+j+1))
            ax.plot([1,2,3], [1,2,3])
            ax.spines['bottom'].set_visible(False)
            ax.get_xaxis().set_visible(False)
        else:
            ax.plot([1,2,3], [3,2,1])

Body:
As I had to rely on Suever's answer but had to modify it to my needs, I thought I might contribute in case someone finds it helpful:

import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

channelArrangement = [16, 17, 18 , 19 , 22, 25, 28 , 29 , 31]

fig = plt.figure(figsize=(10, 8))
outer = gridspec.GridSpec(1, 2, wspace=0.2, hspace=0.2)

for i in range(2):
    inner = gridspec.GridSpecFromSubplotSpec(3, 3, subplot_spec=outer[i],
                                             wspace=0.1, hspace=0.1)
    row     = 0
    col     = 0
    maxCol  = 3

    for chan in channelArrangement:
        ax = plt.Subplot(fig, inner[row,col])
        t= ax.text(0.5,0.5, 'outer=%d\nrow=%d\ncol=%d' % (i,row,col))
        ax.set_xticks([])
        ax.set_yticks([])
        t.set_ha('center')
        fig.add_subplot(ax)
        col += 1
        if col == maxCol:
            col = 0
            row += 1
plt.show()


问:
How can I convert this SQL query to sequelize?
```<code>SELECT
  "flatNo",
  "buildingId",
  count(*)
FROM "FlatDetails"
WHERE "buildingId"= 'E7EA2771'
GROUP BY
  "flatNo",
  "buildingId"
HAVING count(*) > 1;
</code>```

<p>I have tried this tool https://pontaku-tools.com/english/ but it is not giving me the correct answer. </p>

答:
You can try this code. The keywords are fn & literal

```<code>FlatDetails.findAll({
    attributes: ['flatNo', 'buildingId', [sequelize.fn('count', sequelize.col('*')), 'count']],
    where: {
        buildingId: 'E7EA2771'
    },
    group: ['flatNo', 'buildingId'],
    having: sequelize.literal('count(*) > 1'),
    raw: true,
    logging: true
})
.then(flats => {
    console.log(flats);
})
.catch(err => {
    console.log(err);
})
</code>```

Body:
SELECT
  "flatNo",
  "buildingId",
  count(*)
FROM "FlatDetails"
WHERE "buildingId"= 'E7EA2771'
GROUP BY
  "flatNo",
  "buildingId"
HAVING count(*) > 1;

I have tried this tool https://pontaku-tools.com/english/ but it is not giving me the correct answer.

Body:
You can try this code. The keywords are fn & literal

FlatDetails.findAll({
    attributes: ['flatNo', 'buildingId', [sequelize.fn('count', sequelize.col('*')), 'count']],
    where: {
        buildingId: 'E7EA2771'
    },
    group: ['flatNo', 'buildingId'],
    having: sequelize.literal('count(*) > 1'),
    raw: true,
    logging: true
})
.then(flats => {
    console.log(flats);
})
.catch(err => {
    console.log(err);
})


问:
Accessing the server response when an error occurs in my saga request
I'm using the library redux-saga-requests for network communication and high level state management. Following the guidance from the documentation, I've set up a global error handler to display a notification in case the server request times out or the user has connection troubles.

However, when I get a server error (500 for example), I can't access the response in my action. The server response is just not there.

Is there a way to access this object while still staying within the confines and rules of redux-saga?

Here's the initial store setup - note that onErrorSaga doesn't give me the network response, so I might as well go with the default behaviour - sending a suffixed _ERROR action that can be caught by my reducer:

function* onErrorSaga(error, action) {
    console.log('error?', error)
    console.log('action?', action)

    // None of these contain the server response,
    // just the error message and stack thrown by the client.

    yield { error }
}

function* rootSaga(axiosInstance) {
    yield createRequestInstance({
        driver: {
            default: createAxiosDriver(axiosInstance),
        },
        onError: onErrorSaga,
    })
    yield watchRequests()
}

const configureStore = initialState => {
    const sagaMiddleware = createSagaMiddleware()
    const middlewares = [thunkMiddleware, requestsPromiseMiddleware({ auto: true }), sagaMiddleware, trackingMiddleware]
    const store = createStore(rootReducer, initialState, composeWithDevTools(applyMiddleware(...middlewares)))

    sagaMiddleware.run(rootSaga, axiosInstance)

    return store
}

export const configureStoreAsync = () => {
    return new Promise((resolve, reject) => {
        const store = configureStore()
        store
            .dispatch(fetchAppInitialization())
            .then(result => resolve(store))
            .catch(e => reject(store))
    })
}

```

<p>Here's how I'm currently handling errors in my state (which is then displayed by a notification component):</p>

<pre class="lang-js prettyprint-override"><code>
import { CLOSE_NOTIFICATION } from '../actions/actions.notification'

export default (state = [], action) => {
    if (action.type.endsWith('_ERROR')) {
        return {
            type: 'warning',
            title: action.error.message,
            message: `${action.error.stack.substring(0, 200)}...`,
            open: true,
            timestamp: new Date(),
        }
    }
    switch (action.type) {
        case CLOSE_NOTIFICATION:
            return {
                ...state,
                open: false,
            }
        default:
            return state
    }
}

</code>```

答:
Turns out it was way easier than I thought. The action object does in fact contain the server response.

The path to the response is:

action.error.response.data

Body:
I'm using the library redux-saga-requests for network communication and high level state management. Following the guidance from the documentation, I've set up a global error handler to display a notification in case the server request times out or the user has connection troubles.

However, when I get a server error (500 for example), I can't access the response in my action. The server response is just not there.

Is there a way to access this object while still staying within the confines and rules of redux-saga?

Here's the initial store setup - note that onErrorSaga doesn't give me the network response, so I might as well go with the default behaviour - sending a suffixed _ERROR action that can be caught by my reducer:

function* onErrorSaga(error, action) {
    console.log('error?', error)
    console.log('action?', action)

    // None of these contain the server response,
    // just the error message and stack thrown by the client.

    yield { error }
}

function* rootSaga(axiosInstance) {
    yield createRequestInstance({
        driver: {
            default: createAxiosDriver(axiosInstance),
        },
        onError: onErrorSaga,
    })
    yield watchRequests()
}

const configureStore = initialState => {
    const sagaMiddleware = createSagaMiddleware()
    const middlewares = [thunkMiddleware, requestsPromiseMiddleware({ auto: true }), sagaMiddleware, trackingMiddleware]
    const store = createStore(rootReducer, initialState, composeWithDevTools(applyMiddleware(...middlewares)))

    sagaMiddleware.run(rootSaga, axiosInstance)

    return store
}

export const configureStoreAsync = () => {
    return new Promise((resolve, reject) => {
        const store = configureStore()
        store
            .dispatch(fetchAppInitialization())
            .then(result => resolve(store))
            .catch(e => reject(store))
    })
}

Here's how I'm currently handling errors in my state (which is then displayed by a notification component):

import { CLOSE_NOTIFICATION } from '../actions/actions.notification'

export default (state = [], action) => {
    if (action.type.endsWith('_ERROR')) {
        return {
            type: 'warning',
            title: action.error.message,
            message: `${action.error.stack.substring(0, 200)}...`,
            open: true,
            timestamp: new Date(),
        }
    }
    switch (action.type) {
        case CLOSE_NOTIFICATION:
            return {
                ...state,
                open: false,
            }
        default:
            return state
    }
}


问:
nullpointerexception on Button ClickListener android
hi all m having a strange problem.

i have a button and when i set onClick Listener of it.

it gives me null Pointer Exception and application forcefully closes.

my code is

```<code>more = (Button) findViewById(R.id.moreButton);
System.out.println("BEFORE more listener CALL");
more.setOnClickListener(this);
</code>```

Its so strange for me please can any one help?

stackTrace is Below:

```<code>05-17 13:28:54.141: ERROR/AndroidRuntime(1509): FATAL EXCEPTION: main
05-17 13:28:54.141: ERROR/AndroidRuntime(1509): java.lang.RuntimeException: Unable to start activity ComponentInfo{org.sigmatec.finditnear/org.sigmatec.finditnear.customListView}: java.lang.NullPointerException
05-17 13:28:54.141: ERROR/AndroidRuntime(1509):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
05-17 13:28:54.141: ERROR/AndroidRuntime(1509):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
05-17 13:28:54.141: ERROR/AndroidRuntime(1509):     at android.app.ActivityThread.access$2300(ActivityThread.java:125)
05-17 13:28:54.141: ERROR/AndroidRuntime(1509):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
05-17 13:28:54.141: ERROR/AndroidRuntime(1509):     at android.os.Handler.dispatchMessage(Handler.java:99)
05-17 13:28:54.141: ERROR/AndroidRuntime(1509):     at  android.os.Looper.loop(Looper.java:123)
05-17 13:28:54.141: ERROR/AndroidRuntime(1509):     at android.app.ActivityThread.main(ActivityThread.java:4627)
05-17 13:28:54.141: ERROR/AndroidRuntime(1509):     at java.lang.reflect.Method.invokeNative(Native Method)
05-17 13:28:54.141: ERROR/AndroidRuntime(1509):     at java.lang.reflect.Method.invoke(Method.java:521)
05-17 13:28:54.141: ERROR/AndroidRuntime(1509):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
05-17 13:28:54.141: ERROR/AndroidRuntime(1509):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
05-17 13:28:54.141: ERROR/AndroidRuntime(1509):     at dalvik.system.NativeStart.main(Native Method)
05-17 13:28:54.141: ERROR/AndroidRuntime(1509): Caused by: java.lang.NullPointerException
05-17 13:28:54.141: ERROR/AndroidRuntime(1509):     at org.sigmatec.finditnear.customListView.onCreate(customListView.java:114)
05-17 13:28:54.141: ERROR/AndroidRuntime(1509):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
05-17 13:28:54.141: ERROR/AndroidRuntime(1509):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
05-17 13:28:54.141: ERROR/AndroidRuntime(1509):     ... 11 more
</code>```

UPDATED:

one more thing the Button that i am using has been taken from the answer from the link

How to add a footer in ListView?

i have used button instead of TextView Take a look at answer#2 at the end.

m using the Button from some other layout not from the one which has been set on setContentView. because i am using List and i want a button at the end of the list so i made a seperate .xml and used the following code to join it with the List Footer.

COde:

```<code>super.onCreate(savedInstanceState);
setContentView(R.layout.listview);

 ListView l1 = (ListView) findViewById(R.id.ListView01);
    View footerView =
        ((LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.layout_footer, null, false);

    l1.addFooterView(footerView);
    l1.setAdapter(adapter);
</code>```

答:
A couple of questions:

Did you call setContentView with the layout conatining the button before that code?

If yes, can you paste the layout source?

Body:
hi all m having a strange problem.

i have a button and when i set onClick Listener of it.

it gives me null Pointer Exception and application forcefully closes.

my code is

more = (Button) findViewById(R.id.moreButton);
System.out.println("BEFORE more listener CALL");
more.setOnClickListener(this);

Its so strange for me please can any one help?

stackTrace is Below:

05-17 13:28:54.141: ERROR/AndroidRuntime(1509): FATAL EXCEPTION: main
05-17 13:28:54.141: ERROR/AndroidRuntime(1509): java.lang.RuntimeException: Unable to start activity ComponentInfo{org.sigmatec.finditnear/org.sigmatec.finditnear.customListView}: java.lang.NullPointerException
05-17 13:28:54.141: ERROR/AndroidRuntime(1509):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
05-17 13:28:54.141: ERROR/AndroidRuntime(1509):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
05-17 13:28:54.141: ERROR/AndroidRuntime(1509):     at android.app.ActivityThread.access$2300(ActivityThread.java:125)
05-17 13:28:54.141: ERROR/AndroidRuntime(1509):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
05-17 13:28:54.141: ERROR/AndroidRuntime(1509):     at android.os.Handler.dispatchMessage(Handler.java:99)
05-17 13:28:54.141: ERROR/AndroidRuntime(1509):     at  android.os.Looper.loop(Looper.java:123)
05-17 13:28:54.141: ERROR/AndroidRuntime(1509):     at android.app.ActivityThread.main(ActivityThread.java:4627)
05-17 13:28:54.141: ERROR/AndroidRuntime(1509):     at java.lang.reflect.Method.invokeNative(Native Method)
05-17 13:28:54.141: ERROR/AndroidRuntime(1509):     at java.lang.reflect.Method.invoke(Method.java:521)
05-17 13:28:54.141: ERROR/AndroidRuntime(1509):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
05-17 13:28:54.141: ERROR/AndroidRuntime(1509):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
05-17 13:28:54.141: ERROR/AndroidRuntime(1509):     at dalvik.system.NativeStart.main(Native Method)
05-17 13:28:54.141: ERROR/AndroidRuntime(1509): Caused by: java.lang.NullPointerException
05-17 13:28:54.141: ERROR/AndroidRuntime(1509):     at org.sigmatec.finditnear.customListView.onCreate(customListView.java:114)
05-17 13:28:54.141: ERROR/AndroidRuntime(1509):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
05-17 13:28:54.141: ERROR/AndroidRuntime(1509):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
05-17 13:28:54.141: ERROR/AndroidRuntime(1509):     ... 11 more

UPDATED:

one more thing the Button that i am using has been taken from the answer from the link

How to add a footer in ListView?

i have used button instead of TextView Take a look at answer#2 at the end.

m using the Button from some other layout not from the one which has been set on setContentView. because i am using List and i want a button at the end of the list so i made a seperate .xml and used the following code to join it with the List Footer.

COde:

super.onCreate(savedInstanceState);
setContentView(R.layout.listview);

 ListView l1 = (ListView) findViewById(R.id.ListView01);
    View footerView =
        ((LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.layout_footer, null, false);

    l1.addFooterView(footerView);
    l1.setAdapter(adapter);


问:
Tunnelling / Proxy SSH
I need to connect to a particular API but that API only accept request from my mate server. Then include thoses informations back in our website.

So basically I need to connect to the server make the request receiving the answer transfering it to my host so that I can play around with them and integrating them to my website through a php file.

I've already exchange ssh keys and I can connect to my server easily, I know I probably need to use ssh -L (not -R or -D) for the tunneling, though I don't know what to do with my php files to make that request etc etc or what are the other steps once I've entered that command.

If anyone can help that would be lovely :) !

答:
You can create an SSH tunnel using the -L command line switch:

$ ssh -L [port on local]:[apiserver hostname]:[port on apiserver]
[user]@[your friend's server hostname]

E.g.

```<code>$ ssh -L 8080:apiserver.com:80 bob@friend.server.com
</code>```

After the above command successfully connects to friend.server.com, any requests sent to your localhost:8080 will be tunneled through friend.server.com host and arrive at apiserver.com:80. From apiserver's perspective, the request's origin is friend's server.

(This will actually open an SSH session in the terminal window where executed, i.e. you get the prompt of the remote server, which is not required and you can ignore that prompt. It is possible ro run this in the background w/o console login with other switches)

Title: Tunnelling / Proxy SSH

Body:
You can create an SSH tunnel using the -L command line switch:

$ ssh -L [port on local]:[apiserver hostname]:[port on apiserver]
[user]@[your friend's server hostname]

E.g.

$ ssh -L 8080:apiserver.com:80 bob@friend.server.com

After the above command successfully connects to friend.server.com, any requests sent to your localhost:8080 will be tunneled through friend.server.com host and arrive at apiserver.com:80. From apiserver's perspective, the request's origin is friend's server.

(This will actually open an SSH session in the terminal window where executed, i.e. you get the prompt of the remote server, which is not required and you can ignore that prompt. It is possible ro run this in the background w/o console login with other switches)


问:
Can't find entry point
I wanted to create an new c++ project and start coding. I am working in an existing solution with 30+ projects in it. So instead of main() GwMain(..) is used. This works for all other files but not when I create a new c++ project. I get a linker error:

```<code>LNK2019 unresolved external symbol _main referenced in function "int__cdel invoke_main(void)" (?invoke_main@@YAHXZ)

File: MSVCRTD.lib(exe_main.obj)
</code>```

I already compared the property configs with the other projects and
it is nearly the same. The solution is migrated from visual studio
2012 to 2019 I guess this is one of the reasons why it is not working
how it should.

I checked already this: Linker->System->SubSystem -> Windows.

And when I change it from console to windows it shows this:

LNK2019 unresolved external symbol _WinMain referenced in function
"int__cdel invoke_main(void)" (?invoke_main@@YAHXZ)

And I do not use cmake

When I use int main(){return 0;} I get no errors, but I have to use
GwMain()

When I change Under Advanced the EntryPoint I actually get more
errors. I tried to insert GwMain.

The code is just like this:

```<code>#include <gwcore.hpp>
#include <gw.hpp>

int GwMain(int, char**)
{

    return 0;
}
</code>```

Grit is used here a very old framework.

答:
After checking all the compilation and linking options with other projects that work fine.

From your solution, select a project that works (and that uses GwMain). Right button-> property and check its dependencies in "common properties":

Do this manipulation on the other projects that work correctly (and that use GwMain) and try to see if there is a common dependency which allows them to use GwMain, then, try to add this dependency to your project that does not work

Title: Can't find entry point

Body:
I wanted to create an new c++ project and start coding. I am working in an existing solution with 30+ projects in it. So instead of main() GwMain(..) is used. This works for all other files but not when I create a new c++ project. I get a linker error:

LNK2019 unresolved external symbol _main referenced in function "int__cdel invoke_main(void)" (?invoke_main@@YAHXZ)

File: MSVCRTD.lib(exe_main.obj)

I already compared the property configs with the other projects and
it is nearly the same. The solution is migrated from visual studio
2012 to 2019 I guess this is one of the reasons why it is not working
how it should.

I checked already this: Linker->System->SubSystem -> Windows.

And when I change it from console to windows it shows this:

LNK2019 unresolved external symbol _WinMain referenced in function
"int__cdel invoke_main(void)" (?invoke_main@@YAHXZ)

And I do not use cmake

When I use int main(){return 0;} I get no errors, but I have to use
GwMain()

When I change Under Advanced the EntryPoint I actually get more
errors. I tried to insert GwMain.

The code is just like this:

#include <gwcore.hpp>
#include <gw.hpp>

int GwMain(int, char**)
{

    return 0;
}

Grit is used here a very old framework.


问:
CarrierWave: Create the same, unique filename for all versioned files
Before I go into detail I'll get right to the point: has anyone figured out a way to get Carrierwave to save files with their names as a timestamp or any arbitrary string that is unique to each file?

By default Carrierwave saves each file and its alternate versions in its own directory (named after the model ID number). I'm not a fan of this because instead of one directory with 1,000, for the sake of using a large round number, files (in my case pictures) in it we get one directory with 1,000 subdirectories each with one or two files. Yuck.

Now, when you override your Uploader's store_dir method to be something like the following:

```<code>def store_dir
  "uploads/#{model.class.to_s.underscore}/#{mounted_as}"
end
</code>```

you end up with the exact behavior that I want. All the files (pictures) go into one big happy folder. No more subfolders that stick around when the object gets deleted.

There's only one problem. File collisions. If you upload delicious_cake.jpg twice the second one will overwrite the first even if they are two different pictures of delicious cake! That's clearly why the store_dir method has the extra /#{model.id} tacked on the end of the value it returns.

So, what to do? After reading around a bit I discovered that in the generated uploader file there is an apparent solution commented out.

```<code># Override the filename of the uploaded files:
# Avoid using model.id or version_name here, see uploader/store.rb for details.
# def filename
#   "something.jpg" if original_filename
# end
</code>```

After a little bit of searching I found someone who had done the following

```<code>def filename
  @name ||= "#{secure_token}.#{file.extension}" if original_filename
end
</code>```

This got me thinking, why not just do this

```<code>def filename
  @name ||= "#{(Time.now.to_i.to_s + Time.now.usec.to_s).ljust(16, '0')}#{File.extname(original_filename)}"
end
</code>```

That's when things got horribly broken. The problem with this is that filename apparently gets called for each version of the file so we end up with file names like 1312335603175322.jpg and thumb_1312335603195323.jpg. Notice the slight difference? Each file name is based on the time when filename was called for that particular version. That won't do at all.

I next tired using model.created_at for the basis of the timestamp. Only one problem, that returns nil for the first version since it hasn't been put in the database yet.

After some further thinking I decided to try the following in my pictures controller.

```<code>def create
  if params[:picture] and params[:picture][:image]
    params[:picture][:image].original_filename = "#{(Time.now.to_i.to_s + Time.now.usec.to_s).ljust(16, '0')}#{File.extname(params[:picture][:image].original_filename)}"
  end
  ...
</code>```

This overrides the original_filename property before Carrierwave even gets to it making it be a timestamp. It does exactly what I want. The original version of the file ends up with a name like 1312332906940106.jpg and the thumbnail version (or any other version) ends up with a name like thumb_1312332906940106.jpg.

But, this seems like an awful hack. This should be part of the model, or better yet part of the uploader mounted onto the model.

So, my question is, is there a better way to achieve this? Did I miss something crucial with Carrierwave that makes this easy? Is there a not so obvious but cleaner way of going about this? Working code is good, but working code that doesn't smell bad is better.

答:
The solution is the same as described in the official documentation

But it always returns original_filename as nil. So just change it to instance variable as @original_filename.present?

Body:
Before I go into detail I'll get right to the point: has anyone figured out a way to get Carrierwave to save files with their names as a timestamp or any arbitrary string that is unique to each file?

By default Carrierwave saves each file and its alternate versions in its own directory (named after the model ID number). I'm not a fan of this because instead of one directory with 1,000, for the sake of using a large round number, files (in my case pictures) in it we get one directory with 1,000 subdirectories each with one or two files. Yuck.

Now, when you override your Uploader's store_dir method to be something like the following:

def store_dir
  "uploads/#{model.class.to_s.underscore}/#{mounted_as}"
end

you end up with the exact behavior that I want. All the files (pictures) go into one big happy folder. No more subfolders that stick around when the object gets deleted.

There's only one problem. File collisions. If you upload delicious_cake.jpg twice the second one will overwrite the first even if they are two different pictures of delicious cake! That's clearly why the store_dir method has the extra /#{model.id} tacked on the end of the value it returns.

So, what to do? After reading around a bit I discovered that in the generated uploader file there is an apparent solution commented out.

# Override the filename of the uploaded files:
# Avoid using model.id or version_name here, see uploader/store.rb for details.
# def filename
#   "something.jpg" if original_filename
# end

After a little bit of searching I found someone who had done the following

def filename
  @name ||= "#{secure_token}.#{file.extension}" if original_filename
end

This got me thinking, why not just do this

def filename
  @name ||= "#{(Time.now.to_i.to_s + Time.now.usec.to_s).ljust(16, '0')}#{File.extname(original_filename)}"
end

That's when things got horribly broken. The problem with this is that filename apparently gets called for each version of the file so we end up with file names like 1312335603175322.jpg and thumb_1312335603195323.jpg. Notice the slight difference? Each file name is based on the time when filename was called for that particular version. That won't do at all.

I next tired using model.created_at for the basis of the timestamp. Only one problem, that returns nil for the first version since it hasn't been put in the database yet.

After some further thinking I decided to try the following in my pictures controller.

def create
  if params[:picture] and params[:picture][:image]
    params[:picture][:image].original_filename = "#{(Time.now.to_i.to_s + Time.now.usec.to_s).ljust(16, '0')}#{File.extname(params[:picture][:image].original_filename)}"
  end
  ...

This overrides the original_filename property before Carrierwave even gets to it making it be a timestamp. It does exactly what I want. The original version of the file ends up with a name like 1312332906940106.jpg and the thumbnail version (or any other version) ends up with a name like thumb_1312332906940106.jpg.

But, this seems like an awful hack. This should be part of the model, or better yet part of the uploader mounted onto the model.

So, my question is, is there a better way to achieve this? Did I miss something crucial with Carrierwave that makes this easy? Is there a not so obvious but cleaner way of going about this? Working code is good, but working code that doesn't smell bad is better.


问:
NestJS - can't resolve ConfigService
I am using NestJS jwt passport to auth user. I follow the doc, here is my app module:

import { Module } from '@nestjs/common';
import { UserModule } from './user/user.module';
import { TypeOrmModule } from '@nestjs/typeorm';
import { AuthModule } from './auth/auth.module';
import { ConfigModule } from '@nestjs/config';
import configuration from '../config/configuration';

@Module({
  imports: [
      ConfigModule.forRoot({
          load: [configuration],
      }),
      TypeOrmModule.forRoot(),
      UserModule,
      AuthModule,
  ],
})
export class AppModule {}
```

<p>And here is my auth module:</p>

<pre class="lang-js prettyprint-override"><code>import { Module } from '@nestjs/common';
import { AuthService } from './auth.service';
import { PassportModule } from '@nestjs/passport';
import { UserModule } from '../user/user.module';
import { LocalStrategy } from './local.strategy';
import { JwtStrategy } from './jwt.strategy';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { JwtModule } from '@nestjs/jwt';
import { AuthController } from './auth.controller';

@Module({
    imports: [
        UserModule,
        PassportModule,
        JwtModule.registerAsync({
            imports: [ConfigModule],
            useFactory: async (configService: ConfigService) => ({
                secret:  configService.get('jwt.secret'),
                signOptions: {
                    expiresIn: configService.get('jwt.expiresIn'),
                },
            }),
            inject: [ConfigService],
        }),
    ],
    providers: [AuthService, LocalStrategy, JwtStrategy],
    exports: [AuthService],
    controllers: [AuthController],
})
export class AuthModule {}
</code>```

Every time I run npm run start, I got this error message:

```<code>Nest can't resolve dependencies of the JWT_MODULE_OPTIONS (?). Please make sure that the argument ConfigService at index [0] is available in the JwtModule context.
</code>```

I have searched this problem, but still can't fix this. Someone can help me? Thanks.

答: One option, as mentioned by others, is to make the ConfigModule global with the isGlobal: true setting. Otherwise, in @nestjs/config@0.2.3 it should be fixed and should now work as the docs show.

Title: NestJS - can't resolve ConfigService

Body:
I am using NestJS jwt passport to auth user. I follow the doc, here is my app module:

import { Module } from '@nestjs/common';
import { UserModule } from './user/user.module';
import { TypeOrmModule } from '@nestjs/typeorm';
import { AuthModule } from './auth/auth.module';
import { ConfigModule } from '@nestjs/config';
import configuration from '../config/configuration';

@Module({
  imports: [
      ConfigModule.forRoot({
          load: [configuration],
      }),
      TypeOrmModule.forRoot(),
      UserModule,
      AuthModule,
  ],
})
export class AppModule {}

And here is my auth module:

import { Module } from '@nestjs/common';
import { AuthService } from './auth.service';
import { PassportModule } from '@nestjs/passport';
import { UserModule } from '../user/user.module';
import { LocalStrategy } from './local.strategy';
import { JwtStrategy } from './jwt.strategy';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { JwtModule } from '@nestjs/jwt';
import { AuthController } from './auth.controller';

@Module({
    imports: [
        UserModule,
        PassportModule,
        JwtModule.registerAsync({
            imports: [ConfigModule],
            useFactory: async (configService: ConfigService) => ({
                secret:  configService.get('jwt.secret'),
                signOptions: {
                    expiresIn: configService.get('jwt.expiresIn'),
                },
            }),
            inject: [ConfigService],
        }),
    ],
    providers: [AuthService, LocalStrategy, JwtStrategy],
    exports: [AuthService],
    controllers: [AuthController],
})
export class AuthModule {}

Every time I run npm run start, I got this error message:

Nest can't resolve dependencies of the JWT_MODULE_OPTIONS (?). Please make sure that the argument ConfigService at index [0] is available in the JwtModule context.

I have searched this problem, but still can't fix this. Someone can help me? Thanks.


问:
how to set initialRouteName dynamically in the react-native
how to give dynamic initial route name in the react-navigation? if the unit exists we have to redirect to another route or else we have to take user another route.

Note: I'm creating a bottom tab navigator in which I have to set an initial route to that particular bottom tab navigator.

(Not the authentication flow)

```<code>import React, {Component} from 'react';
import {createAppContainer} from 'react-navigation';
import {createMaterialBottomTabNavigator} from 'react-navigation-material-bottom-tabs';
... imports
function getInitialScreen() {
  AsyncStorage.getItem('unit')
    .then(unit => {
      return unit ? 'Home' : 'secondTab';
    })
    .catch(err => {

    });
}

const TabNavigator = createMaterialBottomTabNavigator(
  {
    Home: {
       screen: HomeScreen,
       navigationOptions: {
        .....navigation options
       },
     },
    secondTab: {
      screen: secondTab,
    },
  },
  {
    initialRouteName: getInitialScreen(),
  },
);
export default createAppContainer(TabNavigator);
</code>```

答:
As you can see here:

If you need to set the initialRouteName as a prop it is because there
  is some data that you need to fetch asynchronously before you render
  the app navigation. another way to handle this is to use a
  switchnavigator and have a screen that you show when you are fetching
  the async data, then navigate to the appropriate initial route with
  params when necessary. see docs for a full example of this.

Take a look at here.

You'll find more description!

Also quick fix for this situation is check your condition inside SplashScreen componentDidMount() function

Example of SplashScreen :

```<code>componentDidMount(){
  AsyncStorage.getItem('unit')
    .then(unit => {
      if(unit){
       this.props.navigation.navigate('Home')
      }else{
       this.props.navigation.navigate('secondTab')
      }
    })
    .catch(err => {

    });
}
</code>```

Body:
how to give dynamic initial route name in the react-navigation? if the unit exists we have to redirect to another route or else we have to take user another route.

Note: I'm creating a bottom tab navigator in which I have to set an initial route to that particular bottom tab navigator.

(Not the authentication flow)

import React, {Component} from 'react';
import {createAppContainer} from 'react-navigation';
import {createMaterialBottomTabNavigator} from 'react-navigation-material-bottom-tabs';
... imports
function getInitialScreen() {
  AsyncStorage.getItem('unit')
    .then(unit => {
      return unit ? 'Home' : 'secondTab';
    })
    .catch(err => {

    });
}

const TabNavigator = createMaterialBottomTabNavigator(
  {
    Home: {
       screen: HomeScreen,
       navigationOptions: {
        .....navigation options
       },
     },
    secondTab: {
      screen: secondTab,
    },
  },
  {
    initialRouteName: getInitialScreen(),
  },
);
export default createAppContainer(TabNavigator);

Body:
As you can see here:

If you need to set the initialRouteName as a prop it is because there
  is some data that you need to fetch asynchronously before you render
  the app navigation. another way to handle this is to use a
  switchnavigator and have a screen that you show when you are fetching
  the async data, then navigate to the appropriate initial route with
  params when necessary. see docs for a full example of this.

Take a look at here.

You'll find more description!

Also quick fix for this situation is check your condition inside SplashScreen componentDidMount() function

Example of SplashScreen :

componentDidMount(){
  AsyncStorage.getItem('unit')
    .then(unit => {
      if(unit){
       this.props.navigation.navigate('Home')
      }else{
       this.props.navigation.navigate('secondTab')
      }
    })
    .catch(err => {

    });
}


问:
Constructing a date with year and month
I want to construct a date from just a year and month. I'm currently running a query like this:

```<code>SELECT
    yyyy_mm_dd AS
    t.year,
    t.month,
    t.id,
    t.name,
    ...,
    ...
    ...
FROM(
    SELECT
        p.last_yyyy_mm_dd,
        p.id,
        p.name,
    FROM(
        SELECT
            t.*,
            MAX(yyyy_mm_dd) OVER (PARTITION BY last_day(yyyy_mm_dd)) as last_yyyy_mm_dd
        FROM
            table1 t
        WHERE
            yyyy_mm_dd IS NOT NULL
            AND name = 'XXX'
    ) p
    WHERE
        yyyy_mm_dd = last_yyyy_mm_dd
) p
RIGHT JOIN(
    SELECT
        YEAR(yyyy_mm_dd) as year,
        MONTH(yyyy_mm_dd) as month,
        id,
        name,
        ...,
        ...,
        ...,
    FROM
        table2
    WHERE
        yyyy_mm_dd IS NOT NULL
        AND name = 'XXX'
    GROUP BY
        1,2,3,4
    ) t
ON
    p.id = t.id
    AND YEAR(p.last_yyyy_mm_dd) = t.year
    AND MONTH(p.last_yyyy_mm_dd) = t.month
</code>```

On the top level select, I'd like to also have a date (YYYY-MM-DD) field constructed from the year and month. The day part should be the last day of the given month. I.e. for January it'll be 31.

I've looked here https://cwiki.apache.org/confluence/display/Hive/LanguageManual+UDF#LanguageManualUDF-DateFunctions and can see last_day which might be useful, however there doesn't seem to be a make date function like in MySQL - https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html. How can I construct a date like this in Hive?

Title: Constructing a date with year and month

Body:
I want to construct a date from just a year and month. I'm currently running a query like this:

SELECT
    yyyy_mm_dd AS
    t.year,
    t.month,
    t.id,
    t.name,
    ...,
    ...
    ...
FROM(
    SELECT
        p.last_yyyy_mm_dd,
        p.id,
        p.name,
    FROM(
        SELECT
            t.*,
            MAX(yyyy_mm_dd) OVER (PARTITION BY last_day(yyyy_mm_dd)) as last_yyyy_mm_dd
        FROM
            table1 t
        WHERE
            yyyy_mm_dd IS NOT NULL
            AND name = 'XXX'
    ) p
    WHERE
        yyyy_mm_dd = last_yyyy_mm_dd
) p
RIGHT JOIN(
    SELECT
        YEAR(yyyy_mm_dd) as year,
        MONTH(yyyy_mm_dd) as month,
        id,
        name,
        ...,
        ...,
        ...,
    FROM
        table2
    WHERE
        yyyy_mm_dd IS NOT NULL
        AND name = 'XXX'
    GROUP BY
        1,2,3,4
    ) t
ON
    p.id = t.id
    AND YEAR(p.last_yyyy_mm_dd) = t.year
    AND MONTH(p.last_yyyy_mm_dd) = t.month

On the top level select, I'd like to also have a date (YYYY-MM-DD) field constructed from the year and month. The day part should be the last day of the given month. I.e. for January it'll be 31.

I've looked here https://cwiki.apache.org/confluence/display/Hive/LanguageManual+UDF#LanguageManualUDF-DateFunctions and can see last_day which might be useful, however there doesn't seem to be a make date function like in MySQL - https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html. How can I construct a date like this in Hive?

Body:
try the next code. It works for me:

select to_date(date_sub(add_months(concat(from_unixtime(unix_timestamp('2020-01','yyyy-MM'), 'yyyy-MM'),'-01'),1),1))

Output:

+-------------+--+
|     _c0     |
+-------------+--+
| 2020-01-31  |
+-------------+--+