问:
Logstash RabbitMQ input plugin - How to define multiple routing_key
I'm using RabbitMQ plugin of Logstash to pull from RabbitMQ and push to Elasticsearch using this pipeline:

```<code>input {
    rabbitmq {
        queue => "Elasticsearch_Queue"
        host => "rabbitmq"
        exchange => "my_event_bus"
        key => "SomeIntegrationEvent"
    }
}
output {
    elasticsearch {
        hosts => [ "elasticsearch:9200" ]
    }
    stdout { codec => rubydebug }
}
</code>```

It works fine and creates a queue named Elasticsearch_Queue and binds to my_event_bus exchange using routing_key SomeIntegrationEvent.

I need to subscribe to multiple events but there is no clear solution on the plugin docs.

答:
Since the key must be a string, you can't explicitly bind the queue to the exchange using multiple keys.

I suggest to make my_event_bus a fanout exchange. This will route every message delivered into this exchange to the bound queue.

Then define a second direct exchange that you manually bind to the first exchange multiple times using the routing keys (= events) you are interested in.

Body:
I'm using RabbitMQ plugin of Logstash to pull from RabbitMQ and push to Elasticsearch using this pipeline:

input {
    rabbitmq {
        queue => "Elasticsearch_Queue"
        host => "rabbitmq"
        exchange => "my_event_bus"
        key => "SomeIntegrationEvent"
    }
}
output {
    elasticsearch {
        hosts => [ "elasticsearch:9200" ]
    }
    stdout { codec => rubydebug }
}

It works fine and creates a queue named Elasticsearch_Queue and binds to my_event_bus exchange using routing_key SomeIntegrationEvent.

I need to subscribe to multiple events but there is no clear solution on the plugin docs.


来源: stackexchange

问:
Getting started with GLSL
I've been doing graphic programming using the fixed pipeline of OpenGL after learning in school and I'm thinking of starting to learn GLSL. However I'm using Intel GMA X3100 card on Windows and it seems that GLSL is only supported up to version 1.10. I would like to ask if it is wise for me to start learning GLSL 1.1 first? (I have a book about GLSL 3.3 but I can't run the tutorials to see the effects, ending up of getting the concept first).</p>

答:
The GMA X3100 should support OpenGL 2.1, which would mean it supports GLSL 1.20. Also, you could check which parts of GLSL 3.30 your book uses. The GLSL specifications are online over at http://www.opengl.org/documentation/specs/ -- then you can try to leave out the stuff that are 3.30 specific. The newer versions of GLSL just leave out some stuff (e.g. ftransform in 1.30 and higher) as well as introducing some new extensions (geometry shaders etc). So maybe you can still start with some simple examples.

In the future, one might also use Mesa (http://mesa3d.org) using software emulation, but as their status reports, work on GLSL 1.30 and higher has not been started yet.

Other than that, you need to get a new GPU / laptop. Preferably with an NVIDIA or AMD GPU, supporting OpenGL 3 and 4.

ContentLicense: CC BY-SA 3.0

Title: Getting started with GLSL


问:
Loop through each sheets to look for name containing value, do something, loop again looking for new value
I am trying to loop through sheets in a workbook, select those with names alike, save them to a PDF, then loop again but change the name it looks for in the sheets.  The sheets will have in common a number that is 4 digits like 0001 or 0243 and the four digits are important so sheets 0030 and 0003 do not get combined.

I have gotten the code to work on just one name to find (below) but cannot figure out how to make it loop through more names.  Tried making the name an integer and add 1 to it after each loop, tried very briefly to make it loop through array values but that did not work how I tried.

```<code>For Each sh In ActiveWorkbook.Worksheets

    If sh.Name Like "*0001*" Then

        Worksheets(sh.Name).Select (False)
        ActiveSheet.ExportAsFixedFormat _
            ''' pdf format and save location'''

    End If

Next sh
</code>```

If it could loop through each digit from 0001 to 0300 that would be ideal so I do not need to edit code each time I run it to add the new sheet names.  However if an array will work best I can make a long array for the numbers I know will be present in the file and add new ones each month as needed.

答:
You could use a function to grab numbers from the tab name.  Looks like you only want tabs that include 100 thru 300.  How 'bout trying this:

```<code>For Each sh In ActiveWorkbook.Worksheets
    vNumName = NumOnly(sh.Name)
    If vNumName >= 100 And vNumName <= 300 Then
        Worksheets(sh.Name).Select (False)
        ActiveSheet.ExportAsFixedFormat _
            ''' pdf format and save location'''
    End If
Next sh
</code>```

The function:

```<code>Function NumOnly(vName As String) As Integer
    vOut = ""
    For i = 1 To Len(vName)
        If Mid(vName, i, 1) >= "0" And Mid(vName, i, 1) <= "9" Then vOut = vOut & Mid(vName, i, 1)
    Next
    If Len(vOut) >= 4 Then
        NumOnly = vOut
    Else
        NumOnly = 0
    End If
End Function
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to loop through sheets in a workbook, select those with names alike, save them to a PDF, then loop again but change the name it looks for in the sheets.  The sheets will have in common a number that is 4 digits like 0001 or 0243 and the four digits are important so sheets 0030 and 0003 do not get combined.

I have gotten the code to work on just one name to find (below) but cannot figure out how to make it loop through more names.  Tried making the name an integer and add 1 to it after each loop, tried very briefly to make it loop through array values but that did not work how I tried.

For Each sh In ActiveWorkbook.Worksheets

    If sh.Name Like "*0001*" Then

        Worksheets(sh.Name).Select (False)
        ActiveSheet.ExportAsFixedFormat _
            ''' pdf format and save location'''

    End If

Next sh

If it could loop through each digit from 0001 to 0300 that would be ideal so I do not need to edit code each time I run it to add the new sheet names.  However if an array will work best I can make a long array for the numbers I know will be present in the file and add new ones each month as needed.

Body:
You could use a function to grab numbers from the tab name.  Looks like you only want tabs that include 100 thru 300.  How 'bout trying this:

For Each sh In ActiveWorkbook.Worksheets
    vNumName = NumOnly(sh.Name)
    If vNumName >= 100 And vNumName <= 300 Then
        Worksheets(sh.Name).Select (False)
        ActiveSheet.ExportAsFixedFormat _
            ''' pdf format and save location'''
    End If
Next sh

The function:

Function NumOnly(vName As String) As Integer
    vOut = ""
    For i = 1 To Len(vName)
        If Mid(vName, i, 1) >= "0" And Mid(vName, i, 1) <= "9" Then vOut = vOut & Mid(vName, i, 1)
    Next
    If Len(vOut) >= 4 Then
        NumOnly = vOut
    Else
        NumOnly = 0
    End If
End Function


问:
How to nest a conditional 3 quote strings inside another 3 quote strings in python?
I am trying to a paragraph of lines using 3 quote strings where some group of lines in the paragraph are to be included on a if condition. I am using {} brackets for those conditional lines and since each of them have to be on the next line, I have to use 3 quote strings for them. So its a nested 3 quote string with a condition

For example, I have

write_line_3nd4 = True
paragraph = f'''
this is line one
x = 12 #line two
{f'''
line 3,4 #this is line 3
x=34 #this is line 4''' if write_line_3nd4 else ''}
'''
```

<p>It gives me an error as such:</p>

```File "<ipython-input-36-4bcb98c8ebe0>", line 6
line 3,4 #this is line 3
     ^
SyntaxError: invalid syntax
```

How do use conditional multi-line strings inside multi-line strings?

答:
In the future, simplify your question down to the most basic form. I am not sure if I understand you correctly but I am assuming you only want to print your line 3 and line 4 if "write_line_3nd4 = True"

It is much simpler to put your conditional outside of the string and then append the result inside. I have edited your code to do this:

```<code>write_line_3nd4 = True

if write_line_3nd4 == True:
    line3 = '3,4'
    line4 = 'x=34'
else:
    line3 = ''
    line4 = ''

paragraph = f'''
this is line one
x = 12
''' + line3 + '''
''' + line4
</code>```

EDIT: If you insist on putting your conditionals inside your multi-line string, you could do it using inline expressions. This is what it would look like:

```<code>write_line_3nd4 = True
paragraph = f'''
this is line one
x = 12
''' + ('3,4' if write_line_3nd4 == True else '') + '''
''' + ('x=34' if write_line_3nd4 == True else '')
</code>```

Body:
I am trying to a paragraph of lines using 3 quote strings where some group of lines in the paragraph are to be included on a if condition. I am using {} brackets for those conditional lines and since each of them have to be on the next line, I have to use 3 quote strings for them. So its a nested 3 quote string with a condition

For example, I have

write_line_3nd4 = True
paragraph = f'''
this is line one
x = 12 #line two
{f'''
line 3,4 #this is line 3
x=34 #this is line 4''' if write_line_3nd4 else ''}
'''

It gives me an error as such:

File "<ipython-input-36-4bcb98c8ebe0>", line 6
line 3,4 #this is line 3
     ^
SyntaxError: invalid syntax

How do use conditional multi-line strings inside multi-line strings?

Body:
In the future, simplify your question down to the most basic form. I am not sure if I understand you correctly but I am assuming you only want to print your line 3 and line 4 if "write_line_3nd4 = True"

It is much simpler to put your conditional outside of the string and then append the result inside. I have edited your code to do this:

write_line_3nd4 = True

if write_line_3nd4 == True:
    line3 = '3,4'
    line4 = 'x=34'
else:
    line3 = ''
    line4 = ''

paragraph = f'''
this is line one
x = 12
''' + line3 + '''
''' + line4

EDIT: If you insist on putting your conditionals inside your multi-line string, you could do it using inline expressions. This is what it would look like:

write_line_3nd4 = True
paragraph = f'''
this is line one
x = 12
''' + ('3,4' if write_line_3nd4 == True else '') + '''
''' + ('x=34' if write_line_3nd4 == True else '')


问:
Plus sign in the select clause of an SQL
I am working on an old SQL written for Oracle. There is a part of the select clause that I do not understand, even after googling and checking the questions related to the + sign with the key words Oracle and SQL.

I have checked the answer for a similar question for the where clause here and I found an Oracle docs for the join as well, but it does not make sense for the select clause.

Given an SQL below what is the purpose of the plus sign.

```<code>select '01,'||
lpad(
   (select nvl(count(*), 0) from table1)
   +
   (select nvl(count(*), 0) from table2)
   +
   (select nvl(count(*), 0) from table3)
,9,'0')
from DUAL
</code>```

The sample output

```<code>01,000011111
</code>```

From a sample sql output, it seems that it is for concatenating a result, but I want to be sure.

答: Rovshen, I agree with Gordon.  The code is concatenating the '01,' to the formatted sum of the counts from three tables.  The LPAD is zero filling the summed number value to 9 digits. "||" is the concatenation symbol in Oracle though there is also a concat function.  It is rarely used.</p>

Body:
I am working on an old SQL written for Oracle. There is a part of the select clause that I do not understand, even after googling and checking the questions related to the + sign with the key words Oracle and SQL.

I have checked the answer for a similar question for the where clause here and I found an Oracle docs for the join as well, but it does not make sense for the select clause.

Given an SQL below what is the purpose of the plus sign.

select '01,'||
lpad(
   (select nvl(count(*), 0) from table1)
   +
   (select nvl(count(*), 0) from table2)
   +
   (select nvl(count(*), 0) from table3)
,9,'0')
from DUAL

The sample output

01,000011111

From a sample sql output, it seems that it is for concatenating a result, but I want to be sure.


问:
XCode 4.01 iOS Universal App not showing iPad View
I am creating a Universal App with XCode support (no unit tests) using XCode 4.01.

In the iPhone folder I create a new UIViewController called iPhoneViewController with XIB.

In xxxAppDelegate_iPhone.h I create a iPhoneViewController instance (called viewController), outlet and property.  In the .m I synthesize the property.

In the xxxAppDelegate_iPhone.m I add the following code:

```<code>- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    // Override point for customization after application launch.
    [self.window addSubview:viewController.view];
    [self.window makeKeyAndVisible];

    return YES;
}
</code>```

In IB I open MainWindow_iPhone and add a new View Controller.  I set the view controller class to be iPhoneViewController and type in the XIB name.  I hook up the outlet to the app delegate.

Running the app in Simulator for iPhone - everything works exactly as it is supposed to.

Now I add the same type of thing for iPad:

In the iPad folder I create a new UIViewController called iPadViewController with XIB.

In xxxAppDelegate_iPad.h I create a iPadViewController instance (called viewController), outlet and property.  In the .m I synthesize the property.

In the xxxAppDelegate_iPad.m I add the following code:

```<code>- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    // Override point for customization after application launch.
    [self.window addSubview:viewController.view];
    [self.window makeKeyAndVisible];

    return YES;
}
</code>```

In IB I open MainWindow_iPad and add a new View Controller.  I set the view controller class to be iPadViewController and type in the XIB name.  I hook up the outlet to the app delegate.

Running the app in Simulator for iPad - the default MainWindow_iPad content is displayed but NOT the new view I added.

I have done this several times - always with the same result.

Debugging:

Setting a breakpoint here in the iPad code:

```<code>[self.window addSubview:viewController.view];
</code>```

viewController is NIL and is never getting loaded.

If I programmatically load from the XIB I can get it to display but it does not fill the entire view.

What am I doing wrong?

答: You also need to connect the window property in IB.</p>

Body:
I am creating a Universal App with XCode support (no unit tests) using XCode 4.01.

In the iPhone folder I create a new UIViewController called iPhoneViewController with XIB.

In xxxAppDelegate_iPhone.h I create a iPhoneViewController instance (called viewController), outlet and property.  In the .m I synthesize the property.

In the xxxAppDelegate_iPhone.m I add the following code:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    // Override point for customization after application launch.
    [self.window addSubview:viewController.view];
    [self.window makeKeyAndVisible];

    return YES;
}

In IB I open MainWindow_iPhone and add a new View Controller.  I set the view controller class to be iPhoneViewController and type in the XIB name.  I hook up the outlet to the app delegate.

Running the app in Simulator for iPhone - everything works exactly as it is supposed to.

Now I add the same type of thing for iPad:

In the iPad folder I create a new UIViewController called iPadViewController with XIB.

In xxxAppDelegate_iPad.h I create a iPadViewController instance (called viewController), outlet and property.  In the .m I synthesize the property.

In the xxxAppDelegate_iPad.m I add the following code:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    // Override point for customization after application launch.
    [self.window addSubview:viewController.view];
    [self.window makeKeyAndVisible];

    return YES;
}

In IB I open MainWindow_iPad and add a new View Controller.  I set the view controller class to be iPadViewController and type in the XIB name.  I hook up the outlet to the app delegate.

Running the app in Simulator for iPad - the default MainWindow_iPad content is displayed but NOT the new view I added.

I have done this several times - always with the same result.

Debugging:

Setting a breakpoint here in the iPad code:

[self.window addSubview:viewController.view];

viewController is NIL and is never getting loaded.

If I programmatically load from the XIB I can get it to display but it does not fill the entire view.

What am I doing wrong?


问:
I Need to remove distinct rows from my table
As you can see by the picture all i need to do is to remove all the row who are multiple but leave only one

https://imgur.com/4RUajPQ

答:
A pretty straightforward but inefficient way would be to cross join the table with itself and remove duplicate entries as given below:

DELETE t1 FROM my_table t1, my_table t2 WHERE t1.id > t2.id AND t1.user_id = t2.user_id AND t1.name = t2.name AND t1.time = t2.time AND t1.temperature = t2.temperature AND t1.activity = t2.activity AND t1.create_time = t2.create_time

Perhaps you could remove the extra equality checks in the where clause of the query if you are sure about the columns whose values can directly be used to identify if two rows are possible duplicates of each other.


问:
How does docker container access Internet
I have docker installed (Docker for Mac).
I start a new container with

```<code>docker run -it ubuntu
</code>```

I can see that my newly created container has internet access by simply invoking

```<code>ping google.com
</code>```

I see:

```<code>root@b06e1a46cc40:/# ping google.com
PING google.com (216.58.209.14) 56(84) bytes of data.
64 bytes from sof01s12-in-f14.1e100.net (216.58.209.14): icmp_seq=1 ttl=37 time=63.0 ms
64 bytes from sof01s12-in-f14.1e100.net (216.58.209.14): icmp_seq=2 ttl=37 time=63.7 ms
64 bytes from sof01s12-in-f14.1e100.net (216.58.209.14): icmp_seq=3 ttl=37 time=64.8 ms
</code>```

Next, I checked the networks that my container is connected to:

```<code>root@b06e1a46cc40:/# ip addr show
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
2: tunl0@NONE: <NOARP> mtu 1480 qdisc noop state DOWN group default qlen 1
    link/ipip 0.0.0.0 brd 0.0.0.0
3: ip6tnl0@NONE: <NOARP> mtu 1452 qdisc noop state DOWN group default qlen 1
    link/tunnel6 :: brd ::
6: eth0@if7: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default
    link/ether 02:42:ac:11:00:02 brd ff:ff:ff:ff:ff:ff link-netnsid 0
    inet 172.17.0.2/16 brd 172.17.255.255 scope global eth0
       valid_lft forever preferred_lft forever
root@b06e1a46cc40:/#
</code>```

As I understand, eth0 is used to access internet - it is a network 172.17.0.0/16.

When I look at network list of my host, I'm not connected to this network.

How does my container access internet then?

As I understand it, my container should access internet through my host, because, after all, my host is connected to internet, so this is the only way to access.

答:
Docker for Mac employs the macOS Hypervisor framework
to run a custom Linux distribution (CLD) in a virtual machine (VM).

Now, the CLD inside the VM has no network connectivity with the host OS (i.e. macOS),
but Docker for Mac fills in the gap (literally) through VPNkit.

VPNkit uses a shared memory queue to send network packets
between the host and the guest, and then injects them into the other side's network stack.

Here are some relevant articles that describe how these things work in details:

https://docs.docker.com/docker-for-mac/networking/
https://github.com/moby/vpnkit/blob/master/docs/ethernet.md
https://github.com/moby/vpnkit/blob/master/docs/ports.md

So to answer your question directly - the networks/interfaces you can see inside your container
have no counterparts on the host (macOS). Instead, when you run ping google.com,
the resulting network packets are intercepted by VPNkit inside the VM,
transferred to the host and injected to the host's network stack.

The same happens for inbound packets, but in the opposite direction.

Body:
I have docker installed (Docker for Mac).
I start a new container with

docker run -it ubuntu

I can see that my newly created container has internet access by simply invoking

ping google.com

I see:

root@b06e1a46cc40:/# ping google.com
PING google.com (216.58.209.14) 56(84) bytes of data.
64 bytes from sof01s12-in-f14.1e100.net (216.58.209.14): icmp_seq=1 ttl=37 time=63.0 ms
64 bytes from sof01s12-in-f14.1e100.net (216.58.209.14): icmp_seq=2 ttl=37 time=63.7 ms
64 bytes from sof01s12-in-f14.1e100.net (216.58.209.14): icmp_seq=3 ttl=37 time=64.8 ms

Next, I checked the networks that my container is connected to:

root@b06e1a46cc40:/# ip addr show
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
2: tunl0@NONE: <NOARP> mtu 1480 qdisc noop state DOWN group default qlen 1
    link/ipip 0.0.0.0 brd 0.0.0.0
3: ip6tnl0@NONE: <NOARP> mtu 1452 qdisc noop state DOWN group default qlen 1
    link/tunnel6 :: brd ::
6: eth0@if7: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default
    link/ether 02:42:ac:11:00:02 brd ff:ff:ff:ff:ff:ff link-netnsid 0
    inet 172.17.0.2/16 brd 172.17.255.255 scope global eth0
       valid_lft forever preferred_lft forever
root@b06e1a46cc40:/#

As I understand, eth0 is used to access internet - it is a network 172.17.0.0/16.

When I look at network list of my host, I'm not connected to this network.

How does my container access internet then?

As I understand it, my container should access internet through my host, because, after all, my host is connected to internet, so this is the only way to access.


问:
How to copy dynamic matrix to device memory in CUDA?
In my code I have dynamic matrix.

```<code>int ** file_data = (int **)malloc(TRANSACTIONS * sizeof(int *));
file_data[0] = (int *)malloc((a_size+1) * sizeof(int));
file_data[1] = (int *)malloc((a_size+1) * sizeof(int));
file_data[2] = (int *)malloc((a_size+1) * sizeof(int));
................................................................
</code>```

I want to copy it to device global memory only once.

I have used:

```<code>__device__ int raw_data[][];
...................................
...................................
...................................
cudaMemcpyToSymbol(raw_data[i], file_data[i], (a_size+1)*sizeof(int));
</code>```

But this do not works.

How can I do it?

答:
You need to Flatten the data

If you're only working with rectangular matrices in the first place, I'd recommend always storing your Matrixes like this anyways, but either way, you'll need to get it into this form before trying to push this data to your device memory.

```<code>template<typename T>
class Matrix {
    std::vector<T> _data;
    size_t rows, columns;
public:
    Matrix(size_t rows, size_t columns) :rows(rows), columns(columns) {
        _data.resize(rows * columns);
    }

    T & operator()(size_t row, size_t column) & {
        return _data.at(row * columns + column); //Row-Major Ordering
    }

    T const& operator()(size_t row, size_t column) const& {
        return _data.at(row * columns + column);
    }

    T operator() size_t row, size_t column) const {
        return _data.at(row * columns + column);
    }

    T * data() & {
        return _data.data();
    }

    T const* data() const& {
        return _data.data();
    }

    std::pair<size_t, size_t> size() const {
        return {rows, columns};
    }

    size_t flat_size() const {
        return rows * columns;
    }

    size_t byte_size() const {
        return flat_size() * sizeof(T);
    }
};
</code>```

```<code>int ** file_data = (int **)malloc(TRANSACTIONS * sizeof(int *));
file_data[0] = (int *)malloc((a_size+1) * sizeof(int));
file_data[1] = (int *)malloc((a_size+1) * sizeof(int));
file_data[2] = (int *)malloc((a_size+1) * sizeof(int));
//................................................................

Matrix<int> flat_data(TRANSACTIONS, a_size + 1);
for(size_t row = 0; row < TRANSACTIONS; row++) {
    for(size_t column = 0; column < a_size + 1; column++) {
        flat_data(row, column) = file_data[row][column];
    }
}
//ALTERNATIVE: use this instead of your manual mallocs in the first place!

cudaMemcpyToSymbol(flat_data.data(), /*buffer name*/, flat_data.byte_size());
</code>```

This has the major advantage that you're not having to copy each row individually into their own buffers, you can put all of them together in memory, saving memory and reducing the number of API calls you need to make. And a class designed specifically to handle your functionality won't break when you inevitably make a mistake trying to manually handle all the pointer management in your original code.

Body:
In my code I have dynamic matrix.

int ** file_data = (int **)malloc(TRANSACTIONS * sizeof(int *));
file_data[0] = (int *)malloc((a_size+1) * sizeof(int));
file_data[1] = (int *)malloc((a_size+1) * sizeof(int));
file_data[2] = (int *)malloc((a_size+1) * sizeof(int));
................................................................

I want to copy it to device global memory only once.

I have used:

__device__ int raw_data[][];
...................................
...................................
...................................
cudaMemcpyToSymbol(raw_data[i], file_data[i], (a_size+1)*sizeof(int));

But this do not works.

How can I do it?

Body:
You need to Flatten the data

If you're only working with rectangular matrices in the first place, I'd recommend always storing your Matrixes like this anyways, but either way, you'll need to get it into this form before trying to push this data to your device memory.

template<typename T>
class Matrix {
    std::vector<T> _data;
    size_t rows, columns;
public:
    Matrix(size_t rows, size_t columns) :rows(rows), columns(columns) {
        _data.resize(rows * columns);
    }

    T & operator()(size_t row, size_t column) & {
        return _data.at(row * columns + column); //Row-Major Ordering
    }

    T const& operator()(size_t row, size_t column) const& {
        return _data.at(row * columns + column);
    }

    T operator() size_t row, size_t column) const {
        return _data.at(row * columns + column);
    }

    T * data() & {
        return _data.data();
    }

    T const* data() const& {
        return _data.data();
    }

    std::pair<size_t, size_t> size() const {
        return {rows, columns};
    }

    size_t flat_size() const {
        return rows * columns;
    }

    size_t byte_size() const {
        return flat_size() * sizeof(T);
    }
};

int ** file_data = (int **)malloc(TRANSACTIONS * sizeof(int *));
file_data[0] = (int *)malloc((a_size+1) * sizeof(int));
file_data[1] = (int *)malloc((a_size+1) * sizeof(int));
file_data[2] = (int *)malloc((a_size+1) * sizeof(int));
//................................................................

Matrix<int> flat_data(TRANSACTIONS, a_size + 1);
for(size_t row = 0; row < TRANSACTIONS; row++) {
    for(size_t column = 0; column < a_size + 1; column++) {
        flat_data(row, column) = file_data[row][column];
    }
}
//ALTERNATIVE: use this instead of your manual mallocs in the first place!

cudaMemcpyToSymbol(flat_data.data(), /*buffer name*/, flat_data.byte_size());

This has the major advantage that you're not having to copy each row individually into their own buffers, you can put all of them together in memory, saving memory and reducing the number of API calls you need to make. And a class designed specifically to handle your functionality won't break when you inevitably make a mistake trying to manually handle all the pointer management in your original code.


问:
K product array
I am working on an algorithms problem. You have an array numbers, size of array t , number number_of_elements and number multiplication_value. You have to find any set of number_of_elements indexes of the elements of the array , which product will be equal to multiplication_value. It is guaranteed, that such set of indexes exists

That problem looks like 2 sum, but I can't extrapolate it to my case.
I have tried naive algorithm for O(n), but it fails, when you have bad first number in an array. I think there is a way to use recursion in here. I guess it is well-known problem, but I couldn't find the solution

Example in:

```<code>t = 7
number_of_elements = 2
multiplication_value = 27
numbers = [9,1,1,27,3,27,3]
</code>```

Example out:

```<code>1 3
</code>```

My code ideas:

    def return_index_values(numbers,multiplication_value,number_of_elements):
    cur_number = int(multiplication_value)
    list_of_indexes = []
    values = []
    for i in range(len(numbers)):
        if ((cur_number == 1) and (len(values) == number_of_elements)):
            print(values)
            #finishing if everything worked
            break
        else:
            if (cur_number % int(numbers[i]) == 0):
                if(len(values) < number_of_elements):
            #pushing values if possible
                    values.append(int(numbers[i]))
                    list_of_indexes.append(i)
                    cur_number = int(cur_number / int(numbers[i]))
                    print(cur_number)
                else:
                    pass
            if(len(values) == number_of_elements):
                if mult_check(values,int(multiplication_value)):
               #mult_check checks if the array's element multiplication gives a value
                    break
                else:
               #started dealing with bad cases, but it doesn't work properly
                    values.sort()
                    val_popped = values.pop()
                    cur_number = cur_number * val_popped
```

<p>Bad case for my code</p>

``` numbers = [9,3,1,27,3,27,3]
```

答:
Here is one implementation. Not necessarily the best solution but it gives you some sense of how it can be done.

It first sorts the numbers by the element keeping the indices information. Then it performs recursion calls.

```<code>number_of_elements = 2
multiplication_value = 27
numbers = [9,1,1,27,3,27,3]

def preprocess(numbers, multiplication_value, number_of_elements):
    l = []
    for i, num in enumerate(numbers):
        l.append((num, i))
    return sorted(l, key = lambda tup: tup[0])

def subroutine(numbers, multiplication_value, number_of_elements, idx_start, result):
    if idx_start >= len(numbers):
        return False
    if number_of_elements == 0:
        return True if multiplication_value == 1 else False
    for i in range(idx_start, len(numbers)):
        num = numbers[i][0]
        if num <= multiplication_value:
            if multiplication_value % num == 0:
                idx = numbers[i][1]
                result.append(idx)
                found = subroutine(numbers, multiplication_value / num, number_of_elements - 1, i + 1, result)
                if not found:
                    del result[-1]
                else:
                    return True
        else:
            return False
    return False

result = []
processed_numbers = preprocess(numbers, multiplication_value, number_of_elements)
subroutine(processed_numbers, multiplication_value, number_of_elements, 0, result)
print(result)
</code>```

Title: K product array

Body:
I am working on an algorithms problem. You have an array numbers, size of array t , number number_of_elements and number multiplication_value. You have to find any set of number_of_elements indexes of the elements of the array , which product will be equal to multiplication_value. It is guaranteed, that such set of indexes exists

That problem looks like 2 sum, but I can't extrapolate it to my case.
I have tried naive algorithm for O(n), but it fails, when you have bad first number in an array. I think there is a way to use recursion in here. I guess it is well-known problem, but I couldn't find the solution

Example in:

t = 7
number_of_elements = 2
multiplication_value = 27
numbers = [9,1,1,27,3,27,3]

Example out:

1 3

My code ideas:

    def return_index_values(numbers,multiplication_value,number_of_elements):
    cur_number = int(multiplication_value)
    list_of_indexes = []
    values = []
    for i in range(len(numbers)):
        if ((cur_number == 1) and (len(values) == number_of_elements)):
            print(values)
            #finishing if everything worked
            break
        else:
            if (cur_number % int(numbers[i]) == 0):
                if(len(values) < number_of_elements):
            #pushing values if possible
                    values.append(int(numbers[i]))
                    list_of_indexes.append(i)
                    cur_number = int(cur_number / int(numbers[i]))
                    print(cur_number)
                else:
                    pass
            if(len(values) == number_of_elements):
                if mult_check(values,int(multiplication_value)):
               #mult_check checks if the array's element multiplication gives a value
                    break
                else:
               #started dealing with bad cases, but it doesn't work properly
                    values.sort()
                    val_popped = values.pop()
                    cur_number = cur_number * val_popped

Bad case for my code

 numbers = [9,3,1,27,3,27,3]

Body:
Here is one implementation. Not necessarily the best solution but it gives you some sense of how it can be done.

It first sorts the numbers by the element keeping the indices information. Then it performs recursion calls.

number_of_elements = 2
multiplication_value = 27
numbers = [9,1,1,27,3,27,3]

def preprocess(numbers, multiplication_value, number_of_elements):
    l = []
    for i, num in enumerate(numbers):
        l.append((num, i))
    return sorted(l, key = lambda tup: tup[0])

def subroutine(numbers, multiplication_value, number_of_elements, idx_start, result):
    if idx_start >= len(numbers):
        return False
    if number_of_elements == 0:
        return True if multiplication_value == 1 else False
    for i in range(idx_start, len(numbers)):
        num = numbers[i][0]
        if num <= multiplication_value:
            if multiplication_value % num == 0:
                idx = numbers[i][1]
                result.append(idx)
                found = subroutine(numbers, multiplication_value / num, number_of_elements - 1, i + 1, result)
                if not found:
                    del result[-1]
                else:
                    return True
        else:
            return False
    return False

result = []
processed_numbers = preprocess(numbers, multiplication_value, number_of_elements)
subroutine(processed_numbers, multiplication_value, number_of_elements, 0, result)
print(result)


问:
Plyr mapvalues to rename levels giving unexpected result
I am trying to use mapvalues to rename a long list of levels of a factor. As it seemed not to be working correctly, I produced a simple example showing the issue.

```<code>x <- c("a", "b", "c","c","d","a")
y <- c("a", "c", "c","d","d","b")
z<-data.frame(cbind(x,y))

levels(z$y)<-mapvalues(z$y, c("a", "c","b"), c("A", "C","m"))
levels(z$x)<-mapvalues(z$x, c("a", "c","b"), c("A", "C","m"))
</code>```

Answer:

```<code>>z
x y
1 A A
2 m C
3 C C
4 C d
5 C d
6 A C
</code>```

As can be seen, $x[5] should be "d" and $y[6] should be "m". I also tried applying "as.character" to "from" "to" vectors but it didn't work either. I'm working in RStudio, Mac version, R version 3.5.2 (2018-12-20) -- "Eggshell Igloo". Thanks for help.

答:
If we look at the output of

```<code>plyr::mapvalues(z$y, c("a", "c","b"), c("A", "C","m"))
#[1] A C C d d m
#Levels: A m C d
</code>```

It is a vector with the same length as 'x', while the levels length is different

If we assign this output to the levels(z$y)`, there is length difference.  We can either do the assignment to the whole column

```<code>z$y <- plyr::mapvalues(z$y, c("a", "c","b"), c("A", "C","m"))
</code>```

Or change the levels with the corresponding levels

```<code>levels(z$y) <- levels(plyr::mapvalues(z$y, c("a", "c","b"), c("A", "C","m")))
</code>```

Body:
I am trying to use mapvalues to rename a long list of levels of a factor. As it seemed not to be working correctly, I produced a simple example showing the issue.

x <- c("a", "b", "c","c","d","a")
y <- c("a", "c", "c","d","d","b")
z<-data.frame(cbind(x,y))

levels(z$y)<-mapvalues(z$y, c("a", "c","b"), c("A", "C","m"))
levels(z$x)<-mapvalues(z$x, c("a", "c","b"), c("A", "C","m"))

Answer:

>z
x y
1 A A
2 m C
3 C C
4 C d
5 C d
6 A C

As can be seen, $x[5] should be "d" and $y[6] should be "m". I also tried applying "as.character" to "from" "to" vectors but it didn't work either. I'm working in RStudio, Mac version, R version 3.5.2 (2018-12-20) -- "Eggshell Igloo". Thanks for help.

Body:
If we look at the output of

plyr::mapvalues(z$y, c("a", "c","b"), c("A", "C","m"))
#[1] A C C d d m
#Levels: A m C d

It is a vector with the same length as 'x', while the levels length is different

If we assign this output to the levels(z$y)`, there is length difference.  We can either do the assignment to the whole column

z$y <- plyr::mapvalues(z$y, c("a", "c","b"), c("A", "C","m"))

Or change the levels with the corresponding levels

levels(z$y) <- levels(plyr::mapvalues(z$y, c("a", "c","b"), c("A", "C","m")))


问:
How can I get these values and text strings added in during my for/next loop?
I have a series of numbers that get updated to a master sheet based on their own separate tabs. I enter a set of numbers in rngB and they populate based on the dimensions of the for/next loop based on the multipliers in the array multplr.

Everything works as it should, but I'm trying to also have a range (x,40) populate with this: wsA.Cells(x, 40).Formula = "=""TSR: ""&AX6&"" - ""&AY6&"" - ""&AZ6&"" USD Annual"

Loop:

```<code>        For x = 6 To FinalRow
            wsA.Cells(x, 40).Formula = "=""TSR: ""&AX6&"" - ""&AY6&"" - ""&AZ6&"" USD Annual"
        Next x
</code>```

it populates the formula, but doesn't autofill like it should, it just repeats the save thing in Cells(6,40)

I know there's the autofill/destination method, but my prior for/next formula loop works as it should, so I'm confused what's going on here.

Rest of script:

```<code>Sub UpdateTSRS()

Dim wbk As Workbook
Dim wsA As Worksheet, wsB As Worksheet
Dim rngA As Range, rngB As Range, rngC As Range
Dim rIterator As Range, c As Range, spread As Range
Dim fndRow As Long, i As Long, j As Long, x As Long
Dim multplr As Variant
Dim FinalRow
multplr = Array(1, 1.1, 1.15, 1.2, 1.3)

Set wbk = ThisWorkbook
Set wsA = wbk.Sheets("Annual")
Set wsB = wbk.Sheets("New Annual")
Set rngA = wsA.Range(wsA.Range("E6"), wsA.Range("E6").End(xlDown))
Set rngB = wsB.Range(wsB.Range("A2"), wsB.Range("A2").End(xlDown))
Set rngC = wsA.Range(wsA.Range("AW6"), wsA.Range("AW6").End(xlDown))

FinalRow = wsA.Cells(Rows.Count, 49).End(xlUp).Row

For Each rIterator In rngB
        On Error Resume Next
        fndRow = Application.Match(rIterator.Value, rngA, 0) + _
            rngA.Range("E1").Row - 1
        If Err.Number <> 0 Then
        Else
        For i = 0 To 4
            For j = 3 To 9
                If j <> 6 Then
                Set c = wsA.Cells(fndRow + i, j + 43)
                c.Interior.Color = VBA.RGB(255, 255, 0)
                wsA.Cells(fndRow + i, j + 43).Value = rIterator.Offset(, j - 1).Value * multplr(i)
            End If
            Next j
        Next i
        End If
        Err.Clear
    Next rIterator

        For x = 6 To FinalRow
            wsA.Cells(x, 49).FormulaR1C1 = "=RC[-1]-RC[-3]"
        Next x

        For x = 6 To FinalRow
            wsA.Cells(x, 40).Formula = "=""TSR: ""&AX6&"" - ""&AY6&"" - ""&AZ6&"" USD Annual"
        Next x
End Sub
</code>```

答:
You have told the formula to use AX6, AY6 and AZ6 so it will put this on every row.  You should change this to

```<code>wsA.Cells(x, 40).Formula = "=""TSR: ""&AX" & x & "&"" - ""&AY" & x & "&"" - ""&AZ" & x & "&"" USD Annual"""
</code>```

or slightly easier to read

```<code>wsA.Cells(x, 40).FormulaR1C1 ="TSR: "&RC[49]&" - "&RC[50]&" - "&RC[51]&" USD Annual"
</code>```

Body:
I have a series of numbers that get updated to a master sheet based on their own separate tabs. I enter a set of numbers in rngB and they populate based on the dimensions of the for/next loop based on the multipliers in the array multplr.

Everything works as it should, but I'm trying to also have a range (x,40) populate with this: wsA.Cells(x, 40).Formula = "=""TSR: ""&AX6&"" - ""&AY6&"" - ""&AZ6&"" USD Annual"

Loop:

        For x = 6 To FinalRow
            wsA.Cells(x, 40).Formula = "=""TSR: ""&AX6&"" - ""&AY6&"" - ""&AZ6&"" USD Annual"
        Next x

it populates the formula, but doesn't autofill like it should, it just repeats the save thing in Cells(6,40)

I know there's the autofill/destination method, but my prior for/next formula loop works as it should, so I'm confused what's going on here.

Rest of script:

Sub UpdateTSRS()

Dim wbk As Workbook
Dim wsA As Worksheet, wsB As Worksheet
Dim rngA As Range, rngB As Range, rngC As Range
Dim rIterator As Range, c As Range, spread As Range
Dim fndRow As Long, i As Long, j As Long, x As Long
Dim multplr As Variant
Dim FinalRow
multplr = Array(1, 1.1, 1.15, 1.2, 1.3)

Set wbk = ThisWorkbook
Set wsA = wbk.Sheets("Annual")
Set wsB = wbk.Sheets("New Annual")
Set rngA = wsA.Range(wsA.Range("E6"), wsA.Range("E6").End(xlDown))
Set rngB = wsB.Range(wsB.Range("A2"), wsB.Range("A2").End(xlDown))
Set rngC = wsA.Range(wsA.Range("AW6"), wsA.Range("AW6").End(xlDown))

FinalRow = wsA.Cells(Rows.Count, 49).End(xlUp).Row

For Each rIterator In rngB
        On Error Resume Next
        fndRow = Application.Match(rIterator.Value, rngA, 0) + _
            rngA.Range("E1").Row - 1
        If Err.Number <> 0 Then
        Else
        For i = 0 To 4
            For j = 3 To 9
                If j <> 6 Then
                Set c = wsA.Cells(fndRow + i, j + 43)
                c.Interior.Color = VBA.RGB(255, 255, 0)
                wsA.Cells(fndRow + i, j + 43).Value = rIterator.Offset(, j - 1).Value * multplr(i)
            End If
            Next j
        Next i
        End If
        Err.Clear
    Next rIterator

        For x = 6 To FinalRow
            wsA.Cells(x, 49).FormulaR1C1 = "=RC[-1]-RC[-3]"
        Next x

        For x = 6 To FinalRow
            wsA.Cells(x, 40).Formula = "=""TSR: ""&AX6&"" - ""&AY6&"" - ""&AZ6&"" USD Annual"
        Next x
End Sub

Body:
You have told the formula to use AX6, AY6 and AZ6 so it will put this on every row.  You should change this to

wsA.Cells(x, 40).Formula = "=""TSR: ""&AX" & x & "&"" - ""&AY" & x & "&"" - ""&AZ" & x & "&"" USD Annual"""

or slightly easier to read

wsA.Cells(x, 40).FormulaR1C1 ="TSR: "&RC[49]&" - "&RC[50]&" - "&RC[51]&" USD Annual"


问:
Why is Lighthouse failing my cached files?
I'm using Google Lighthouse to calculate a performance score. One of the criteria is caching static assets such as images and scripts.

I don't have control over all of these, but the ones I do have control over the cache has been set to 30 days. However, Lighthouse is still reporting these as an issue. Lighthouse does report these as having a 30d cache, but still reports as an issue.

What do I need to do to rectify this?

Please see screenshot below:

答:
I also had a 30 day cache policy and what fixed this for me was adding the public and no-cache values to the Cache-Control header.

I only figured this out as I was testing Firebase hosting vs my old host which was IIS. The IIS hosted site was passing even though it had a shorter max-age value. I checked the network developer tools in chrome and saw it had public and no cache values in my IIS web.config under the Cache-Control header but my firebase.json didn't have those values. Once added I'm passing again!

Now why this passes is a mystery to me, but see if you can add and test again.


问:
Git ignore compiled CSS but keep the latest version for production-ready state
I used to commit my compiled minified CSS files to the repo, then I realized each time, the entire file is sent since it's minified on a single line. So it means for each small modification, I save an entire CSS file in my history and it will quickly add up for no reason.

Can we ignore the CSS files compiled automatically by my Text Editor from a LESS file?

If I put these CSS files in .gitignore, they won't be in the repo but I also use the repository to immediately get a working website.

I always compile the LESS files from my local computer and I want to keep it that way (so don't suggest me to use Grunt or something to automatically compile when a user loads the page, please :P).

The ideal solution would be to only keep the latest file in the repo for CSS files only. For history I'd check the LESS files. The CSS files would be there only to make the site works right after a git clone/pull.

答:
Let me see if I can sum up your requirements here:

The end user should receive minified CSS when they access your server

Your server uses your git repo as its code source (hopefully a Master or Production branch)

You don't want a lot of minified CSS history in your repo

You want developer-readable CSS history in your repo

These are pretty common requirements. Most people are using deployment scripts to perform actions like these consistently on each production push - one script that they can fire on the server to download the source from the repo, minify all CSS/JS/HTML, update your package manager with any new requirements, reload any local services that need reloading, refresh/warm up caches, etc. This can be a simple web service that you write and then call via a hook from GitHub/BitBucket/whoever on a push to your production branch, or you can use a deployment framework specifically built to help you deploy reliably.

If you're coding in a mature framework, there's likely already some deployment tooling out there that you could take advantage of with minimal effort. If not, you'd have to search for something language-specific if you didn't want to write it yourself (depending on how much work you need to do on the server aside from copying the repo and minifying, writing a webhook yourself might be the quickest and easiest solution).


问:
Find a class somewhere inside dozens of JAR files?
How would you find a particular class name inside lots of jar files?

(Looking for the actual class name, not the classes that reference it.)

答:
Filename: searchForFiles.py

```<code>import os, zipfile, glob, sys

def main():
    searchFile = sys.argv[1] #class file to search for, sent from batch file below (optional, see second block of code below)
    listOfFilesInJar = []
    for file in glob.glob("*.jar"):
        archive = zipfile.ZipFile(file, 'r')
        for x in archive.namelist():
            if str(searchFile) in str(x):
                listOfFilesInJar.append(file)

    for something in listOfFilesInJar:
        print("location of "+str(searchFile)+": ",something)

if __name__ == "__main__":
    sys.exit(main())
</code>```

You can easily run this by making a .bat file with the following text (replace "AddWorkflows.class" with the file you are searching for):

(File: CallSearchForFiles.bat)

```<code>@echo off
python -B -c "import searchForFiles;x=searchForFiles.main();" AddWorkflows.class
pause
</code>```

You can double-click CallSearchForFiles.bat to run it, or call it from the command line "CallSearchForFiles.bat SearchFile.class"

Click to See Example Output

Body:
Filename: searchForFiles.py

import os, zipfile, glob, sys

def main():
    searchFile = sys.argv[1] #class file to search for, sent from batch file below (optional, see second block of code below)
    listOfFilesInJar = []
    for file in glob.glob("*.jar"):
        archive = zipfile.ZipFile(file, 'r')
        for x in archive.namelist():
            if str(searchFile) in str(x):
                listOfFilesInJar.append(file)

    for something in listOfFilesInJar:
        print("location of "+str(searchFile)+": ",something)

if __name__ == "__main__":
    sys.exit(main())

You can easily run this by making a .bat file with the following text (replace "AddWorkflows.class" with the file you are searching for):

(File: CallSearchForFiles.bat)

@echo off
python -B -c "import searchForFiles;x=searchForFiles.main();" AddWorkflows.class
pause

You can double-click CallSearchForFiles.bat to run it, or call it from the command line "CallSearchForFiles.bat SearchFile.class"

Click to See Example Output


问:
Converting object to an encodable object failed
I am getting the following error:

```<code>Converting object to an encodable object failed: Instance of 'Patient'
#0      _JsonStringifier.writeObject (dart:convert/json.dart:674)
#1      _JsonStringifier.writeList (dart:convert/json.dart:724)
#2      _JsonStringifier.writeJsonValue (dart:convert/json.dart:706)
#3      _JsonStringifier.writeObject (dart:convert/json.dart:664)
#4      _JsonStringStringifier.printOn (dart:convert/json.dart:873)
#5      _JsonStringStringifier.stringify (dart:convert/json.dart:855)
#6      JsonEncoder.convert (dart:convert/json.dart:256)
#7      JsonCodec.encode (dart:convert/json.dart:155)
#8      Persistence.saveLatestPatients (/Users/dean/Library/Developer/CoreSimulator/Devices/570CC18D-95BF-4062-8523-9C78E106D0CF/data/Containers/Data/Application/70CAEFAA-4AE3-4CBF-A85F-39161E472C83/tmp/flutter_prototypev6jYbr/flutter_prototype/lib/utils/persistence.dart:32:23)
<asynchronous suspension>
#9      _HomeScreenState.fetchData.<anonymous closure> (/Users/dean/Librar<…>
</code>```

My 'Patient' class:

```<code>import 'package:simple_moment/simple_moment.dart';

class Patient {
  String guid;
  String _name;
  String _surname;
  DateTime _updated;

  Patient(String guid) {
    this.guid = guid;
  }

  String get name => _name;
  set name(v) => _name = v;

  String get surname => _surname;
  set surname(v) => _surname = v;

  DateTime get updated => _updated;
  set updated(v) => _updated = v;

  // Helper functions

  String getFullName() => '$_name $_surname';

  String getRelativeLastUpdated() {
    var moment = new Moment.now();
    return moment.from(_updated);
  }

}
</code>```

答:
In my case, I was attempting to use an integer key in a map object.
Once I converted it to String, the error was resolved. Good luck.</p>

Body:
I am getting the following error:

Converting object to an encodable object failed: Instance of 'Patient'
#0      _JsonStringifier.writeObject (dart:convert/json.dart:674)
#1      _JsonStringifier.writeList (dart:convert/json.dart:724)
#2      _JsonStringifier.writeJsonValue (dart:convert/json.dart:706)
#3      _JsonStringifier.writeObject (dart:convert/json.dart:664)
#4      _JsonStringStringifier.printOn (dart:convert/json.dart:873)
#5      _JsonStringStringifier.stringify (dart:convert/json.dart:855)
#6      JsonEncoder.convert (dart:convert/json.dart:256)
#7      JsonCodec.encode (dart:convert/json.dart:155)
#8      Persistence.saveLatestPatients (/Users/dean/Library/Developer/CoreSimulator/Devices/570CC18D-95BF-4062-8523-9C78E106D0CF/data/Containers/Data/Application/70CAEFAA-4AE3-4CBF-A85F-39161E472C83/tmp/flutter_prototypev6jYbr/flutter_prototype/lib/utils/persistence.dart:32:23)
<asynchronous suspension>
#9      _HomeScreenState.fetchData.<anonymous closure> (/Users/dean/Librar<…>

My 'Patient' class:

import 'package:simple_moment/simple_moment.dart';

class Patient {
  String guid;
  String _name;
  String _surname;
  DateTime _updated;

  Patient(String guid) {
    this.guid = guid;
  }

  String get name => _name;
  set name(v) => _name = v;

  String get surname => _surname;
  set surname(v) => _surname = v;

  DateTime get updated => _updated;
  set updated(v) => _updated = v;

  // Helper functions

  String getFullName() => '$_name $_surname';

  String getRelativeLastUpdated() {
    var moment = new Moment.now();
    return moment.from(_updated);
  }

}


问:
How to query Salesforce from NetSuite SuiteScript 2.0?
How would you go about querying Salesforce from a NetSuite suitescript?</p>

答:
Here is an example of querying Users from Salesforce in SuiteScript 2.0.

```<code>/**
 *@NApiVersion 2.x
 *@NScriptType UserEventScript
 */

define(['N/https', 'N/record'],

function (https, record)
{
    //handle the bs if its being created
    function afterSubmit(context)
    {
        var body;
        var response;
        var recordData = {};
        var queryURL;

        body = loginSalesforceNLAP(); //login to SF

        //error check the login
        if(body.access_token == undefined || body.access_token == "")
        {
            log.debug("afterSubmit","Could not access SF");
            return;
        }

        //check this email exists in SF
        response = _HTTPS.get({
            url: getURL(body) + "/query/?q=SELECT Id FROM User WHERE Username = user",
            body: recordData,
            headers: {"Authorization": "OAuth " + body.access_token,"Content-Type": "application/json"}
        });

        if(response.code != 200)
        {
            log.debug('afterSubmit', 'Could not query SF ' + response.code + ' ');
            return;
        }

        //Check results (only 1 should be returned)
        var b = JSON.parse(response.body);
        if (b.totalSize == 1)
        {
            SFID = b.records[0].Id;
            log.debug('afterSubmit', 'Found user in SF with ID ' + SFID);
        }
        else
        {
            log.debug('afterSubmit', 'No SF user with username user was found in SF');
            return;
        }
    }

    return {afterSubmit: afterSubmit};

});

//get URL of max version of SF
function getURL(body)
{
    var max;
    var arr;
    var header = {"Authorization": "OAuth " + body.access_token  };
    var recordData = {};
    var url = body.instance_url + "/services/data/";

    response = _HTTPS.get({
                url: url,
                body: recordData,
                headers: header
            });

    if(response.code == 200 || response.code == 204)
    {
        arr = JSON.parse(response.body);
        for(var i = 0; i < arr.length; i++)
        {
            if(!max || parseInt(arr[i]["version"]) > parseInt(max["version"]))
                max = arr[i];
        }
        return body.instance_url + max.url;
    }
    else
        return "";
}

//Connect to Salesforce instance and obtain the Access Token used for subsequent Salesforce calls this session
function loginSalesforceNLAP() {

    //production
    var clientID = "432432432432432432432432ncK7FyfTUgxH2YNHvR6QPoVXpDE";
    var clientSecret = "732323213210608985";
    var securityToken = "N0bx9d323231aO321igJ6";
    var username = "login@login.com";
    var password = "password";
    var loginURL = "https://login.salesforce.com/services/oauth2/token";

    var header = [];
    header['Content-Type'] = 'application/json;charset=UTF-8';
    var recordData = {};
    var url = loginURL + "?grant_type=password&client_id=" + clientID + "&client_secret=" + clientSecret + "&username=" + username + "&password=" + password + securityToken;

    try
    {
        response = _HTTPS.post({
                url: url,
                body: recordData,
                headers: header
            });
        response = JSON.parse(JSON.stringify(response));
        if (response.code == 200 || response.code == 204)
            return JSON.parse(response.body);
    }
    catch (er02)
    {
        log.error('ERROR:loginSalesforceNLAP', er02);
    }
    return "";
}
</code>```

To find your security token, clientId, and client Secret follow the steps in these links:
https://success.salesforce.com/answers?id=90630000000glADAAY
https://developer.salesforce.com/forums/?id=906F0000000AfcgIAC

Body:
Here is an example of querying Users from Salesforce in SuiteScript 2.0.

/**
 *@NApiVersion 2.x
 *@NScriptType UserEventScript
 */

define(['N/https', 'N/record'],

function (https, record)
{
    //handle the bs if its being created
    function afterSubmit(context)
    {
        var body;
        var response;
        var recordData = {};
        var queryURL;

        body = loginSalesforceNLAP(); //login to SF

        //error check the login
        if(body.access_token == undefined || body.access_token == "")
        {
            log.debug("afterSubmit","Could not access SF");
            return;
        }

        //check this email exists in SF
        response = _HTTPS.get({
            url: getURL(body) + "/query/?q=SELECT Id FROM User WHERE Username = user",
            body: recordData,
            headers: {"Authorization": "OAuth " + body.access_token,"Content-Type": "application/json"}
        });

        if(response.code != 200)
        {
            log.debug('afterSubmit', 'Could not query SF ' + response.code + ' ');
            return;
        }

        //Check results (only 1 should be returned)
        var b = JSON.parse(response.body);
        if (b.totalSize == 1)
        {
            SFID = b.records[0].Id;
            log.debug('afterSubmit', 'Found user in SF with ID ' + SFID);
        }
        else
        {
            log.debug('afterSubmit', 'No SF user with username user was found in SF');
            return;
        }
    }

    return {afterSubmit: afterSubmit};

});

//get URL of max version of SF
function getURL(body)
{
    var max;
    var arr;
    var header = {"Authorization": "OAuth " + body.access_token  };
    var recordData = {};
    var url = body.instance_url + "/services/data/";

    response = _HTTPS.get({
                url: url,
                body: recordData,
                headers: header
            });

    if(response.code == 200 || response.code == 204)
    {
        arr = JSON.parse(response.body);
        for(var i = 0; i < arr.length; i++)
        {
            if(!max || parseInt(arr[i]["version"]) > parseInt(max["version"]))
                max = arr[i];
        }
        return body.instance_url + max.url;
    }
    else
        return "";
}

//Connect to Salesforce instance and obtain the Access Token used for subsequent Salesforce calls this session
function loginSalesforceNLAP() {

    //production
    var clientID = "432432432432432432432432ncK7FyfTUgxH2YNHvR6QPoVXpDE";
    var clientSecret = "732323213210608985";
    var securityToken = "N0bx9d323231aO321igJ6";
    var username = "login@login.com";
    var password = "password";
    var loginURL = "https://login.salesforce.com/services/oauth2/token";

    var header = [];
    header['Content-Type'] = 'application/json;charset=UTF-8';
    var recordData = {};
    var url = loginURL + "?grant_type=password&client_id=" + clientID + "&client_secret=" + clientSecret + "&username=" + username + "&password=" + password + securityToken;

    try
    {
        response = _HTTPS.post({
                url: url,
                body: recordData,
                headers: header
            });
        response = JSON.parse(JSON.stringify(response));
        if (response.code == 200 || response.code == 204)
            return JSON.parse(response.body);
    }
    catch (er02)
    {
        log.error('ERROR:loginSalesforceNLAP', er02);
    }
    return "";
}

To find your security token, clientId, and client Secret follow the steps in these links:
https://success.salesforce.com/answers?id=90630000000glADAAY
https://developer.salesforce.com/forums/?id=906F0000000AfcgIAC


问:
Calling non static method without class instance inside a non static method
```<code>class GFG {
public static void main (String[] args) {
    GFG g=new GFG();
    g.pri();

}

void pri(){
  mod();
}
void mod()
{
    System.out.println("HHI");
}

}
</code>```

In this following code when i am calling a  mod() method inside a non static method without creating class instance for mod() method it does work and given Output "Hi";
According to the definition of non static method cannot be called without Class instance;

How it does work?

答:
It has an instance, the one you created in main, which you used when doing g.pri(). Within an instance method like pri, the instance it was called on is available as this, and this. is optional. In an instance method, these two statements do exactly the same thing:

```<code>mod();
this.mod();
</code>```

If you don't include the this., the Java compiler adds it for you.

(As a matter of opinion, I suggest you include it, at the very least for fields, since otherwise in the code x = y + 1 you have no idea whether x and y are locals in the method or fields on the instance.)

Body:
class GFG {
public static void main (String[] args) {
    GFG g=new GFG();
    g.pri();

}

void pri(){
  mod();
}
void mod()
{
    System.out.println("HHI");
}

}

In this following code when i am calling a  mod() method inside a non static method without creating class instance for mod() method it does work and given Output "Hi";
According to the definition of non static method cannot be called without Class instance;

How it does work?

Body:
It has an instance, the one you created in main, which you used when doing g.pri(). Within an instance method like pri, the instance it was called on is available as this, and this. is optional. In an instance method, these two statements do exactly the same thing:

mod();
this.mod();

If you don't include the this., the Java compiler adds it for you.

(As a matter of opinion, I suggest you include it, at the very least for fields, since otherwise in the code x = y + 1 you have no idea whether x and y are locals in the method or fields on the instance.)


问:
Resolving errors trying to assign values to range variables in Excel VBA code
I am writing a procedure to generate a number of named ranges from values in a worksheet, with the cell to be named in column C and the name to be assigned in the adjacent cell in column D. All variations I've tried to reference these two cells as ranges returned errors. While this procedure will be used only once to generate these names, I'd like to determine the correct syntax so I'll be able to reference ranges for other purposes in the future.

I have a temporary ActiveX CommandButton that calls the following code (just referencing two rows for now for testing purposes):

```<code>Private Sub CommandButton1_Click()
    Call SetRangeNames(38, 39)
End Sub
</code>```

I placed the SetRangeNames procedure in a module based on recommendations in posts I've seen elsewhere. The two lines of code returning errors are indicated by a comment within the procedure code, and all of the variations I've tried (with the errors they return) follow that. I placed a MsgBox call in the proc to see how it was rendering the cell references generated. It displays:

```<code>rangeNameValueCellAddress = "C38"; namedRangeCellAddress = "D38"
</code>```

or

```<code>rangeNameValueCellAddress = "C39"; namedRangeCellAddress = "D39"
</code>```

Here's one varation of the proc:

```<code>Public Sub SetRangeNames(startRow As Integer, endRow As Integer)
    Dim theRange As Range
    Dim currentRow As Integer
    Dim currentName As String
    Dim rangeNameValueCellAddress As String
    Dim namedRangeCellAddress As String

    For currentRow = startRow To endRow
        rangeNameValueCellAddress = """D" & Trim(Str(currentRow) & """")
        namedRangeCellAddress = """C" & Trim(Str(currentRow) & """")
        MsgBox ("rangeNameValueCellAddress = " & rangeNameValueCellAddress & _
            "; namedRangeCellAddress = " & namedRangeCellAddress)
        'MsgBox displays: rangeNameValueCellAddress = "C38"; namedRangeCellAddress = "D38"
        ' or: rangeNameValueCellAddress = "C39"; namedRangeCellAddress = "D39"
        '*** The following two statements return errors:
        Set theRange = ThisWorkbook.Worksheets(ActiveSheet).Range(namedRangeCellAddress)
        currentName = ThisWorkbook.Worksheets(ActiveSheet).Range(rangeNameValueCellAddress).Value2
        ActiveWorkbook.Names.Add Name:=currentName, RefersTo:=theRange
    Next currentRow
End Sub
</code>```

Here are the variations I tried ("SYSProjectData" is both the name and CodeName and Name of the worksheet I am working with):

```<code>Set theRange = SYSProjectData.Range(namedRangeCellAddress)
currentName = SYSProjectData.Range(rangeNameValueCellAddress).Value2
</code>```

Returns: "Application-defined or object-defined error"

```<code>Set theRange = ThisWorkbook.SYSProjectData.Range(namedRangeCellAddress)
currentName = ThisWorkbook.SYSProjectData.Range(rangeNameValueCellAddress).Value2
</code>```

Returns: "Object doesn't support this property or method"

```<code>Set theRange = ThisWorkbook.ActiveSheet.Range(namedRangeCellAddress)
currentName = ThisWorkbook.ActiveSheet.Range(rangeNameValueCellAddress).Value2
</code>```

Returns: "Application-defined or object-defined error"

```<code>Set theRange = ActiveSheet.Range(namedRangeCellAddress)
currentName = ActiveSheet.Range(rangeNameValueCellAddress).Value2
</code>```

Returns: "Application-defined or object-defined error"

```<code>Set theRange = ThisWorkbook.Worksheets(SYSProjectData).Range(namedRangeCellAddress)
currentName = ThisWorkbook.Worksheets(SYSProjectData).Range(rangeNameValueCellAddress).Value2
</code>```

Returns: "Type mismatch"

```<code>Set theRange = ThisWorkbook.Worksheets("SYSProjectData").Range(namedRangeCellAddress)
currentName = ThisWorkbook.Worksheets("SYSProjectData").Range(rangeNameValueCellAddress).Value2
</code>```

Returns: "Application-defined or object-defined error"

```<code>Set theRange = ThisWorkbook.Sheets(SYSProjectData).Range(namedRangeCellAddress)
currentName = ThisWorkbook.Sheets(SYSProjectData).Range(rangeNameValueCellAddress).Value2
</code>```

Returns: "Type mismatch"

```<code>Set theRange = ThisWorkbook.Sheets("SYSProjectData").Range(namedRangeCellAddress)
currentName = ThisWorkbook.Sheets("SYSProjectData").Range(rangeNameValueCellAddress).Value2
</code>```

Returns: "Application-defined or object-defined error"

```<code>Set theRange = ThisWorkbook.Sheets(ActiveSheet).Range(namedRangeCellAddress)
currentName = ThisWorkbook.Sheets(ActiveSheet).Range(rangeNameValueCellAddress).Value2
</code>```

Returns: "Type mismatch"

```<code>Set theRange = ThisWorkbook.Worksheets(ActiveSheet).Range(namedRangeCellAddress)
currentName = ThisWorkbook.Worksheets(ActiveSheet).Range(rangeNameValueCellAddress).Value2
</code>```

Returns: "Type mismatch"

Can anyone tell me what I'm doing wrong?

Thanks!

答:
Sorry for the delay in posting this. This is what I ended up with...

```<code>Public Sub SetRangeNames(strNamedRangeColumn As String, strNameSourceColumn As String, startRow As Long, endRow As Long)
    Dim currentRow As Long
    Dim rngNameSourceCell As Range
    Dim rngNamedRangeCell As Range
    Dim strNameSourceCellAddress As String
    Dim strNamedRangeCellAddress As String
    Dim strNameSourceCellValue As String
    Dim strNamedRangeCellValue As String
    Dim strRangeValueError As String

    strRangeValueError = ""
    strNamedRangeColumn = Trim(UCase(strNamedRangeColumn))
    strNameSourceColumn = Trim(UCase(strNameSourceColumn))

    If Len(strNamedRangeColumn) > 1 Then
        MsgBox ("ERROR: The value given for the named range column, """ & strNamedRangeColumn & _
            ","" was longer than one character.")
        Exit Sub
    ElseIf Len(strNameSourceColumn) > 1 Then
        MsgBox ("ERROR: The value given for the name source column, """ & strNameSourceColumn & _
            ","" was longer than one character.")
        Exit Sub
    ElseIf strNamedRangeColumn = "" Then
        MsgBox ("ERROR: The value given for the named range column was longer than one character.")
        Exit Sub
    ElseIf strNameSourceColumn = "" Then
        MsgBox ("ERROR: The value given for the name source column was longer than one character.")
        Exit Sub
    ElseIf Asc(strNamedRangeColumn) < 65 Or Asc(strNamedRangeColumn) > 90 Then
        MsgBox ("ERROR: The value given for the named range column, """ & strNamedRangeColumn & _
            ","" was not a letter.")
        Exit Sub
    ElseIf Asc(strNameSourceColumn) < 65 Or Asc(strNameSourceColumn) > 90 Then
        MsgBox ("ERROR: The value given for the name source column, """ & strNameSourceColumn & _
            ","" was not a letter.")
        Exit Sub
    End If

    For currentRow = startRow To endRow
        strNameSourceCellAddress = strNameSourceColumn & Trim(str(currentRow))
        strNamedRangeCellAddress = strNamedRangeColumn & Trim(str(currentRow))
        Set rngNameSourceCell = Range(strNameSourceCellAddress)
        Set rngNamedRangeCell = Range(strNamedRangeCellAddress)

        strNameSourceCellValue = Trim(rngNameSourceCell.Value)

        If IsEmpty(rngNameSourceCell) Or Len(strNameSourceCellValue) > 0 Then
                strRangeValueError = "Source cell " & strNameSourceCellAddress & " was empty."
        End If

        If Not (Application.WorksheetFunction.IsText(rngNameSourceCell.Value)) Then
                If Len(strRangeValueError) > 0 Then
                        strRangeValueError = vbCrLf & strRangeValueError
                End If
                strRangeValueError = strRangeValueError & "Source cell " & strNameSourceCellAddress & _
                    " contained the not-text value """ & strNameSourceCellValue & """."
        End If

        If Len(strRangeValueError) > 0 Then
                MsgBox (strRangeValueError)
                Exit Sub
        End If

        ThisWorkbook.sheets("mySheetName").Parent.Names.Add Name:=.Cells(currentRow, strNameSourceColumn), _
            RefersTo:=.Cells(currentRow, strNamedRangeColumn)

    Next currentRow
End Sub
</code>```

Called as follows...

```<code>Private Sub btnGenerateRangeNames_Click()
    Call SetRangeNames("C", "E", 8, 11)
    ' etc.
End Sub
</code>```

Thanks for your help!

Body:
I am writing a procedure to generate a number of named ranges from values in a worksheet, with the cell to be named in column C and the name to be assigned in the adjacent cell in column D. All variations I've tried to reference these two cells as ranges returned errors. While this procedure will be used only once to generate these names, I'd like to determine the correct syntax so I'll be able to reference ranges for other purposes in the future.

I have a temporary ActiveX CommandButton that calls the following code (just referencing two rows for now for testing purposes):

Private Sub CommandButton1_Click()
    Call SetRangeNames(38, 39)
End Sub

I placed the SetRangeNames procedure in a module based on recommendations in posts I've seen elsewhere. The two lines of code returning errors are indicated by a comment within the procedure code, and all of the variations I've tried (with the errors they return) follow that. I placed a MsgBox call in the proc to see how it was rendering the cell references generated. It displays:

rangeNameValueCellAddress = "C38"; namedRangeCellAddress = "D38"

or

rangeNameValueCellAddress = "C39"; namedRangeCellAddress = "D39"

Here's one varation of the proc:

Public Sub SetRangeNames(startRow As Integer, endRow As Integer)
    Dim theRange As Range
    Dim currentRow As Integer
    Dim currentName As String
    Dim rangeNameValueCellAddress As String
    Dim namedRangeCellAddress As String

    For currentRow = startRow To endRow
        rangeNameValueCellAddress = """D" & Trim(Str(currentRow) & """")
        namedRangeCellAddress = """C" & Trim(Str(currentRow) & """")
        MsgBox ("rangeNameValueCellAddress = " & rangeNameValueCellAddress & _
            "; namedRangeCellAddress = " & namedRangeCellAddress)
        'MsgBox displays: rangeNameValueCellAddress = "C38"; namedRangeCellAddress = "D38"
        ' or: rangeNameValueCellAddress = "C39"; namedRangeCellAddress = "D39"
        '*** The following two statements return errors:
        Set theRange = ThisWorkbook.Worksheets(ActiveSheet).Range(namedRangeCellAddress)
        currentName = ThisWorkbook.Worksheets(ActiveSheet).Range(rangeNameValueCellAddress).Value2
        ActiveWorkbook.Names.Add Name:=currentName, RefersTo:=theRange
    Next currentRow
End Sub

Here are the variations I tried ("SYSProjectData" is both the name and CodeName and Name of the worksheet I am working with):

Set theRange = SYSProjectData.Range(namedRangeCellAddress)
currentName = SYSProjectData.Range(rangeNameValueCellAddress).Value2

Returns: "Application-defined or object-defined error"

Set theRange = ThisWorkbook.SYSProjectData.Range(namedRangeCellAddress)
currentName = ThisWorkbook.SYSProjectData.Range(rangeNameValueCellAddress).Value2

Returns: "Object doesn't support this property or method"

Set theRange = ThisWorkbook.ActiveSheet.Range(namedRangeCellAddress)
currentName = ThisWorkbook.ActiveSheet.Range(rangeNameValueCellAddress).Value2

Returns: "Application-defined or object-defined error"

Set theRange = ActiveSheet.Range(namedRangeCellAddress)
currentName = ActiveSheet.Range(rangeNameValueCellAddress).Value2

Returns: "Application-defined or object-defined error"

Set theRange = ThisWorkbook.Worksheets(SYSProjectData).Range(namedRangeCellAddress)
currentName = ThisWorkbook.Worksheets(SYSProjectData).Range(rangeNameValueCellAddress).Value2

Returns: "Type mismatch"

Set theRange = ThisWorkbook.Worksheets("SYSProjectData").Range(namedRangeCellAddress)
currentName = ThisWorkbook.Worksheets("SYSProjectData").Range(rangeNameValueCellAddress).Value2

Returns: "Application-defined or object-defined error"

Set theRange = ThisWorkbook.Sheets(SYSProjectData).Range(namedRangeCellAddress)
currentName = ThisWorkbook.Sheets(SYSProjectData).Range(rangeNameValueCellAddress).Value2

Returns: "Type mismatch"

Set theRange = ThisWorkbook.Sheets("SYSProjectData").Range(namedRangeCellAddress)
currentName = ThisWorkbook.Sheets("SYSProjectData").Range(rangeNameValueCellAddress).Value2

Returns: "Application-defined or object-defined error"

Set theRange = ThisWorkbook.Sheets(ActiveSheet).Range(namedRangeCellAddress)
currentName = ThisWorkbook.Sheets(ActiveSheet).Range(rangeNameValueCellAddress).Value2

Returns: "Type mismatch"

Set theRange = ThisWorkbook.Worksheets(ActiveSheet).Range(namedRangeCellAddress)
currentName = ThisWorkbook.Worksheets(ActiveSheet).Range(rangeNameValueCellAddress).Value2

Returns: "Type mismatch"

Can anyone tell me what I'm doing wrong?

Thanks!

Body:
Sorry for the delay in posting this. This is what I ended up with...

Public Sub SetRangeNames(strNamedRangeColumn As String, strNameSourceColumn As String, startRow As Long, endRow As Long)
    Dim currentRow As Long
    Dim rngNameSourceCell As Range
    Dim rngNamedRangeCell As Range
    Dim strNameSourceCellAddress As String
    Dim strNamedRangeCellAddress As String
    Dim strNameSourceCellValue As String
    Dim strNamedRangeCellValue As String
    Dim strRangeValueError As String

    strRangeValueError = ""
    strNamedRangeColumn = Trim(UCase(strNamedRangeColumn))
    strNameSourceColumn = Trim(UCase(strNameSourceColumn))

    If Len(strNamedRangeColumn) > 1 Then
        MsgBox ("ERROR: The value given for the named range column, """ & strNamedRangeColumn & _
            ","" was longer than one character.")
        Exit Sub
    ElseIf Len(strNameSourceColumn) > 1 Then
        MsgBox ("ERROR: The value given for the name source column, """ & strNameSourceColumn & _
            ","" was longer than one character.")
        Exit Sub
    ElseIf strNamedRangeColumn = "" Then
        MsgBox ("ERROR: The value given for the named range column was longer than one character.")
        Exit Sub
    ElseIf strNameSourceColumn = "" Then
        MsgBox ("ERROR: The value given for the name source column was longer than one character.")
        Exit Sub
    ElseIf Asc(strNamedRangeColumn) < 65 Or Asc(strNamedRangeColumn) > 90 Then
        MsgBox ("ERROR: The value given for the named range column, """ & strNamedRangeColumn & _
            ","" was not a letter.")
        Exit Sub
    ElseIf Asc(strNameSourceColumn) < 65 Or Asc(strNameSourceColumn) > 90 Then
        MsgBox ("ERROR: The value given for the name source column, """ & strNameSourceColumn & _
            ","" was not a letter.")
        Exit Sub
    End If

    For currentRow = startRow To endRow
        strNameSourceCellAddress = strNameSourceColumn & Trim(str(currentRow))
        strNamedRangeCellAddress = strNamedRangeColumn & Trim(str(currentRow))
        Set rngNameSourceCell = Range(strNameSourceCellAddress)
        Set rngNamedRangeCell = Range(strNamedRangeCellAddress)

        strNameSourceCellValue = Trim(rngNameSourceCell.Value)

        If IsEmpty(rngNameSourceCell) Or Len(strNameSourceCellValue) > 0 Then
                strRangeValueError = "Source cell " & strNameSourceCellAddress & " was empty."
        End If

        If Not (Application.WorksheetFunction.IsText(rngNameSourceCell.Value)) Then
                If Len(strRangeValueError) > 0 Then
                        strRangeValueError = vbCrLf & strRangeValueError
                End If
                strRangeValueError = strRangeValueError & "Source cell " & strNameSourceCellAddress & _
                    " contained the not-text value """ & strNameSourceCellValue & """."
        End If

        If Len(strRangeValueError) > 0 Then
                MsgBox (strRangeValueError)
                Exit Sub
        End If

        ThisWorkbook.sheets("mySheetName").Parent.Names.Add Name:=.Cells(currentRow, strNameSourceColumn), _
            RefersTo:=.Cells(currentRow, strNamedRangeColumn)

    Next currentRow
End Sub

Called as follows...

Private Sub btnGenerateRangeNames_Click()
    Call SetRangeNames("C", "E", 8, 11)
    ' etc.
End Sub

Thanks for your help!


问:
JPA and non-primitive ElementCollection
I've got two tables in my database that look like this, with a foreign key from job_label.job_id to equivalent column in job_record.  Additionally, the triple of job_id, label_key, and label in job_record has a unique constraint.

```<code>mysql> select * from job_record;
+--------+---------+
| job_id | state   |
+--------+---------+
|      1 | success |
|      2 | running |
|      3 | errored |
|      4 | success |
+--------+---------+

mysql> select * from job_label
+--------+-----------+--------+
| job_id | label_key | label  |
+--------+-----------+--------+
|      1 | name      | job 1  |
|      1 | type      | normal |
+--------+-----------+--------+
</code>```

On the Java class side I have this class:

```<code>@Entity
@Table(name = "job_record")
public class JobRecord {

    @Id
    @Column(name = "job_id")
    private String jobId;

    @Enumerated(EnumType.STRING)
    @Column(name = "state")
    private JobState state;
}
</code>```

I've tried to define a class for job_label that looks something like this:

```<code>public class JobLabelRecord {
    @Enumerated(EnumType.STRING)
    @Column(name = "label_key")
    private JobLabelKey key;

    @Column(name = "label")
    private String label;
}
</code>```

And then I want a field in JobRecord that provides me all labels for that Job as a List<JobLabelRecord>.  However, nothing I've tried works.

I've tried declaring JobLabelRecord as Embeddable with the equivalent field in JobRecord as Embedded.  I've tried using ManyToOne and OneToMany mappings, but that fails because there's no Id columns in JobLabelRecord (and nothing I do with those works correctly).

Am I supposed to be using an ElementCollection here instead?  I've tried that as well, but without success.

Any ideas here?  Thanks!

答:
You can find a simple example for this by searching for "jpa elementcollection separate table", such as JPA Tutorial - JPA ElementCollection CollectionTable Override Example. Applying this example to your problem gives the following:

```<code>@Entity
@Table(name = "job_record")
public class JobRecord {

    @Id
    @Column(name = "job_id")
    private Integer jobId;

    @Enumerated(EnumType.STRING)
    @Column(name = "state")
    private JobState state;

    @ElementCollection
    @CollectionTable(name="job_label",
           joinColumns=@JoinColumn(name="job_id"))
    private List<JobLabelRecord> labels;
...

@Embeddable
public class JobLabelRecord {
    @Enumerated(EnumType.STRING)
    @Column(name = "label_key")
    private JobLabelKey key;

    @Column(name = "label")
    private String label;
...
</code>```

Note also the JobRecord id should probably be an Integer.

Title: JPA and non-primitive ElementCollection

Body:
I've got two tables in my database that look like this, with a foreign key from job_label.job_id to equivalent column in job_record.  Additionally, the triple of job_id, label_key, and label in job_record has a unique constraint.

mysql> select * from job_record;
+--------+---------+
| job_id | state   |
+--------+---------+
|      1 | success |
|      2 | running |
|      3 | errored |
|      4 | success |
+--------+---------+

mysql> select * from job_label
+--------+-----------+--------+
| job_id | label_key | label  |
+--------+-----------+--------+
|      1 | name      | job 1  |
|      1 | type      | normal |
+--------+-----------+--------+

On the Java class side I have this class:

@Entity
@Table(name = "job_record")
public class JobRecord {

    @Id
    @Column(name = "job_id")
    private String jobId;

    @Enumerated(EnumType.STRING)
    @Column(name = "state")
    private JobState state;
}

I've tried to define a class for job_label that looks something like this:

public class JobLabelRecord {
    @Enumerated(EnumType.STRING)
    @Column(name = "label_key")
    private JobLabelKey key;

    @Column(name = "label")
    private String label;
}

And then I want a field in JobRecord that provides me all labels for that Job as a List<JobLabelRecord>.  However, nothing I've tried works.

I've tried declaring JobLabelRecord as Embeddable with the equivalent field in JobRecord as Embedded.  I've tried using ManyToOne and OneToMany mappings, but that fails because there's no Id columns in JobLabelRecord (and nothing I do with those works correctly).

Am I supposed to be using an ElementCollection here instead?  I've tried that as well, but without success.

Any ideas here?  Thanks!

Body:
You can find a simple example for this by searching for "jpa elementcollection separate table", such as JPA Tutorial - JPA ElementCollection CollectionTable Override Example. Applying this example to your problem gives the following:

@Entity
@Table(name = "job_record")
public class JobRecord {

    @Id
    @Column(name = "job_id")
    private Integer jobId;

    @Enumerated(EnumType.STRING)
    @Column(name = "state")
    private JobState state;

    @ElementCollection
    @CollectionTable(name="job_label",
           joinColumns=@JoinColumn(name="job_id"))
    private List<JobLabelRecord> labels;
...

@Embeddable
public class JobLabelRecord {
    @Enumerated(EnumType.STRING)
    @Column(name = "label_key")
    private JobLabelKey key;

    @Column(name = "label")
    private String label;
...

Note also the JobRecord id should probably be an Integer.


问:
Why Flow cannot call ReactDOM.render with document.getElementById(...)
I was getting this error below in Flow type checking.

```<code>Cannot call ReactDOM.render with document.getElementById(...) bound to container because null [1] is
incompatible with Element [2].

     src/index.js
      26│       </Switch>
      27│     </ScrollToTop>
      28│   </BrowserRouter>
      29│ </Provider>, document.getElementById("root"));
      30│

     /private/tmp/flow/flowlib_174a8121/dom.js
 [1] 646│   getElementById(elementId: string): HTMLElement | null;

     /private/tmp/flow/flowlib_174a8121/react-dom.js
 [2]  18│     container: Element,
</code>```

The code is below.

```<code>// @flow
"use strict";
import React from "react";
import ReactDOM from "react-dom";
import {createStore, applyMiddleware} from "redux";
import {Provider} from "react-redux";
import {BrowserRouter, Switch, Route} from "react-router-dom";
import Home from "./components/home";
import Detail from "./components/detail";
import LevelOfGame from "./components/level-of-game";
import NotFound from "./components/not-found";
import ScrollToTop from "./components/scroll-to-top";

import reducers from "./reducers";

const createStoreWithMiddleware = applyMiddleware()(createStore);

ReactDOM.render(<Provider store={createStoreWithMiddleware(reducers)}>
  <BrowserRouter>
    <ScrollToTop>
      <Switch>
        <Route exact path="/" component={Home}/>
        <Route path="/detail/:detailId" component={Detail}/>
        <Route path="/level-of-game" component={LevelOfGame}/>
        <Route path="*" component={NotFound} status={404}/>
      </Switch>
    </ScrollToTop>
  </BrowserRouter>
</Provider>, document.getElementById("root"));
</code>```

I believe I had to specify the type somehow in getElementById.

So I fixed the error by storing document.getElementById("root"); in a constant variable with a type specification:

```<code>const root: any = document.getElementById("root");
</code>```

The error is fixed and I hope this is useful for other folks, but I'd love to understand what was causing this error. Can anyone be so kind to tell me what this was?

答:
While Cogell's answer is correct, I would argue to keep the code simpler and add an exception.

```<code>ReactDOM.render(
 <Provider store={createStoreWithMiddleware(reducers)}>
  <BrowserRouter>
    <ScrollToTop>
      <Switch>
        <Route exact path="/" component={Home}/>
        <Route path="/detail/:detailId" component={Detail}/>
        <Route path="/level-of-game" component={LevelOfGame}/>
        <Route path="*" component={NotFound} status={404}/>
      </Switch>
    </ScrollToTop>
  </BrowserRouter>
 </Provider>, // $FlowIgnore
 document.getElementById("root")
);
</code>```

Notice the "$FlowIgnore" comment

and then in your .flowconfig file add this to the "options" field:

suppress_comment= \\(.\\|\n\\)*\\$FlowIgnore

Body:
I was getting this error below in Flow type checking.

Cannot call ReactDOM.render with document.getElementById(...) bound to container because null [1] is
incompatible with Element [2].

     src/index.js
      26│       </Switch>
      27│     </ScrollToTop>
      28│   </BrowserRouter>
      29│ </Provider>, document.getElementById("root"));
      30│

     /private/tmp/flow/flowlib_174a8121/dom.js
 [1] 646│   getElementById(elementId: string): HTMLElement | null;

     /private/tmp/flow/flowlib_174a8121/react-dom.js
 [2]  18│     container: Element,

The code is below.

// @flow
"use strict";
import React from "react";
import ReactDOM from "react-dom";
import {createStore, applyMiddleware} from "redux";
import {Provider} from "react-redux";
import {BrowserRouter, Switch, Route} from "react-router-dom";
import Home from "./components/home";
import Detail from "./components/detail";
import LevelOfGame from "./components/level-of-game";
import NotFound from "./components/not-found";
import ScrollToTop from "./components/scroll-to-top";

import reducers from "./reducers";

const createStoreWithMiddleware = applyMiddleware()(createStore);

ReactDOM.render(<Provider store={createStoreWithMiddleware(reducers)}>
  <BrowserRouter>
    <ScrollToTop>
      <Switch>
        <Route exact path="/" component={Home}/>
        <Route path="/detail/:detailId" component={Detail}/>
        <Route path="/level-of-game" component={LevelOfGame}/>
        <Route path="*" component={NotFound} status={404}/>
      </Switch>
    </ScrollToTop>
  </BrowserRouter>
</Provider>, document.getElementById("root"));

I believe I had to specify the type somehow in getElementById.

So I fixed the error by storing document.getElementById("root"); in a constant variable with a type specification:

const root: any = document.getElementById("root");

The error is fixed and I hope this is useful for other folks, but I'd love to understand what was causing this error. Can anyone be so kind to tell me what this was?

Body:
While Cogell's answer is correct, I would argue to keep the code simpler and add an exception.

ReactDOM.render(
 <Provider store={createStoreWithMiddleware(reducers)}>
  <BrowserRouter>
    <ScrollToTop>
      <Switch>
        <Route exact path="/" component={Home}/>
        <Route path="/detail/:detailId" component={Detail}/>
        <Route path="/level-of-game" component={LevelOfGame}/>
        <Route path="*" component={NotFound} status={404}/>
      </Switch>
    </ScrollToTop>
  </BrowserRouter>
 </Provider>, // $FlowIgnore
 document.getElementById("root")
);

Notice the "$FlowIgnore" comment

and then in your .flowconfig file add this to the "options" field:

suppress_comment= \\(.\\|\n\\)*\\$FlowIgnore


问:
how can recognize whether the user sent the maild is id correct or not?
I am sending mail from .net application, my mail code is working fine but I dont want to allow the incorrect mail id's. So how can I recognize whether the user who sent the mail has the correct id or not.

And i want to know the response of the mail which has been sent by the smtpclient.

```<code>    Configuration config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath);
    MailSettingsSectionGroup settings = (MailSettingsSectionGroup)config.GetSectionGroup("system.net/mailSettings");
     smtpHost = settings.Smtp.Network.Host;
     smtpport = settings.Smtp.Network.Port.ToString();
     smtpuser = settings.Smtp.Network.UserName;
     smtppwd = settings.Smtp.Network.Password;

    string MessageBody = string.Empty;
    try
    {

        message = new MailMessage();
        message.From = new MailAddress(smtpuser);

        message.To.Add(toMailAddress);

        message.BodyEncoding = System.Text.Encoding.UTF8;

        message.Subject = mailSubject;
        message.Body = mailMessage.ToString();

        message.IsBodyHtml = true;

        client = new SmtpClient();
        client.Host = smtpHost;
        //if (isSSLEnabled)
        //{
        //    client.EnableSsl = true;
        //}

        client.Port =  Convert.ToInt32(smtpport);
        client.EnableSsl = false;
        client.Credentials = new System.Net.NetworkCredential(smtpuser, smtppwd);

        client.Send(message);

    }
    catch (Exception ex)
    {
        string x = ex.Message;
    }
</code>```

答:
I would use a regular expression to validate the email.

http://www.codeproject.com/KB/recipes/EmailRegexValidator.aspx

As for the capturing the smtp response, this link should help you out greatly.  Just check out the response section, its obvious you know the introduction items.

http://www.csharphelp.com/2007/01/howto-smtp-in-c/

Body:
I am sending mail from .net application, my mail code is working fine but I dont want to allow the incorrect mail id's. So how can I recognize whether the user who sent the mail has the correct id or not.

And i want to know the response of the mail which has been sent by the smtpclient.

    Configuration config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath);
    MailSettingsSectionGroup settings = (MailSettingsSectionGroup)config.GetSectionGroup("system.net/mailSettings");
     smtpHost = settings.Smtp.Network.Host;
     smtpport = settings.Smtp.Network.Port.ToString();
     smtpuser = settings.Smtp.Network.UserName;
     smtppwd = settings.Smtp.Network.Password;

    string MessageBody = string.Empty;
    try
    {

        message = new MailMessage();
        message.From = new MailAddress(smtpuser);

        message.To.Add(toMailAddress);

        message.BodyEncoding = System.Text.Encoding.UTF8;

        message.Subject = mailSubject;
        message.Body = mailMessage.ToString();

        message.IsBodyHtml = true;

        client = new SmtpClient();
        client.Host = smtpHost;
        //if (isSSLEnabled)
        //{
        //    client.EnableSsl = true;
        //}

        client.Port =  Convert.ToInt32(smtpport);
        client.EnableSsl = false;
        client.Credentials = new System.Net.NetworkCredential(smtpuser, smtppwd);

        client.Send(message);

    }
    catch (Exception ex)
    {
        string x = ex.Message;
    }


问:
How to keep the last, non-missing set of complete observations across multiple columns?
I have a longitudinal data set and would like to extract the latest, non-missing complete set of observations for each variable in the data set where id is a unique identifier, yr is year, and x1 and x2 are variables with missing values. The actual data set has 100s of variables over the course of 60 years.

```<code>data <- data.frame(id=rep(1:3,3)
yr=rep(1:3,times=1, each=3)
x1=c(1,3,7,NA,NA,NA,9,4,10)
x2=c(NA,NA,NA,3,9,6,NA,NA,NA))
</code>```

Below are my expected results. For x1, the latest complete set of observations is year 3. For x2, the latest complete set of observations is year 2.

答:
Here's a tidyverse solution. First, I create the data frame.

# Create data frame
df <- data.frame(id=rep(1:3,3),
                   yr=rep(1:3,times=1, each=3),
                   x1=c(1,3,7,NA,NA,NA,9,4,10),
                   x2=c(NA,NA,NA,3,9,6,NA,NA,NA))
```

<p>Next, I load the required libraries.</p>

<pre class="lang-r prettyprint-override"><code># Load library
library(dplyr)
library(tidyr)
</code>```

I then go from wide to long format, group by yr and key (i.e., variable name), remove those that have NA values (i.e., keep those that are all not NA), group by key, keep those data that are in the maximum year, switch back to wide format, and arrange to make the printed result look pretty.

df %>%
  gather("key", "val", x1, x2) %>%
  group_by(yr, key) %>%
  filter(all(!is.na(val))) %>%
  group_by(key) %>%
  filter(yr == max(yr)) %>%
  spread(key, val) %>%
  arrange(yr)
#> # A tibble: 6 x 4
#>      id    yr    x1    x2
#>   <int> <int> <dbl> <dbl>
#> 1     1     2    NA     3
#> 2     2     2    NA     9
#> 3     3     2    NA     6
#> 4     1     3     9    NA
#> 5     2     3     4    NA
#> 6     3     3    10    NA
```

Created on 2019-05-29 by the reprex package (v0.3.0)

Body:
I have a longitudinal data set and would like to extract the latest, non-missing complete set of observations for each variable in the data set where id is a unique identifier, yr is year, and x1 and x2 are variables with missing values. The actual data set has 100s of variables over the course of 60 years.

data <- data.frame(id=rep(1:3,3)
yr=rep(1:3,times=1, each=3)
x1=c(1,3,7,NA,NA,NA,9,4,10)
x2=c(NA,NA,NA,3,9,6,NA,NA,NA))

Below are my expected results. For x1, the latest complete set of observations is year 3. For x2, the latest complete set of observations is year 2.

Body:
Here's a tidyverse solution. First, I create the data frame.

# Create data frame
df <- data.frame(id=rep(1:3,3),
                   yr=rep(1:3,times=1, each=3),
                   x1=c(1,3,7,NA,NA,NA,9,4,10),
                   x2=c(NA,NA,NA,3,9,6,NA,NA,NA))

Next, I load the required libraries.

# Load library
library(dplyr)
library(tidyr)

I then go from wide to long format, group by yr and key (i.e., variable name), remove those that have NA values (i.e., keep those that are all not NA), group by key, keep those data that are in the maximum year, switch back to wide format, and arrange to make the printed result look pretty.

df %>%
  gather("key", "val", x1, x2) %>%
  group_by(yr, key) %>%
  filter(all(!is.na(val))) %>%
  group_by(key) %>%
  filter(yr == max(yr)) %>%
  spread(key, val) %>%
  arrange(yr)
#> # A tibble: 6 x 4
#>      id    yr    x1    x2
#>   <int> <int> <dbl> <dbl>
#> 1     1     2    NA     3
#> 2     2     2    NA     9
#> 3     3     2    NA     6
#> 4     1     3     9    NA
#> 5     2     3     4    NA
#> 6     3     3    10    NA

Created on 2019-05-29 by the reprex package (v0.3.0)


问:
Powershell "UNC paths are not supported" but I'm using Push-Location
I am running a command line program in powershell working on our \servername\files folder as the running folder. I get a "UNC paths are not supported" error even though I am using Push-Location (which is the only solution I find while googling). The simplest code that gives me this error is as follows:</p>

```<code>Push-Location \\servername\files
cmd.exe \c ping 10.1.10.10
Pop-Location
</code>```

答:
Push-Location will save where you are, but since you have not changed your location to a non-UNC location to execute the cmd.exe program, it complains.

Just put a Set-Location before the cmd.exe call to make sure that you are not on a UNC path.  Something like:

Set-Location $env:APPDATA

would work.

Body:
I am running a command line program in powershell working on our \servername\files folder as the running folder. I get a "UNC paths are not supported" error even though I am using Push-Location (which is the only solution I find while googling). The simplest code that gives me this error is as follows:

Push-Location \\servername\files
cmd.exe \c ping 10.1.10.10
Pop-Location


问:
Convert data frame row to column names
Is there a quick way (part of the tidyverse API perhaps) to turn a row into column names for a data.frame or tibble, somewhat similar to tibble::column_to_rownames?

I realize there are many ways to do this, e.g. somewhat clumsily:

```<code>> df <- head(iris)
>
> df %>%
+     set_colnames(magrittr::extract(., 1,)) %>%
+     magrittr::extract(-1,)
  5.1 3.5 1.4 0.2      1
2 4.9 3.0 1.4 0.2 setosa
3 4.7 3.2 1.3 0.2 setosa
4 4.6 3.1 1.5 0.2 setosa
5 5.0 3.6 1.4 0.2 setosa
6 5.4 3.9 1.7 0.4 setosa
</code>```

Title: Convert data frame row to column names

Body:
Is there a quick way (part of the tidyverse API perhaps) to turn a row into column names for a data.frame or tibble, somewhat similar to tibble::column_to_rownames?

I realize there are many ways to do this, e.g. somewhat clumsily:

> df <- head(iris)
>
> df %>%
+     set_colnames(magrittr::extract(., 1,)) %>%
+     magrittr::extract(-1,)
  5.1 3.5 1.4 0.2      1
2 4.9 3.0 1.4 0.2 setosa
3 4.7 3.2 1.3 0.2 setosa
4 4.6 3.1 1.5 0.2 setosa
5 5.0 3.6 1.4 0.2 setosa
6 5.4 3.9 1.7 0.4 setosa

Body:
janitor::row_to_names() implements this:

library(tidyverse)

iris %>%
  head() %>%
  janitor::row_to_names(1)
#>   5.1 3.5 1.4 0.2      1
#> 2 4.9 3.0 1.4 0.2 setosa
#> 3 4.7 3.2 1.3 0.2 setosa
#> 4 4.6 3.1 1.5 0.2 setosa
#> 5 5.0 3.6 1.4 0.2 setosa
#> 6 5.4 3.9 1.7 0.4 setosa

Created on 2019-05-29 by the reprex package (v0.2.1)