问:
Double slash (//) as XML comment
I was a bit surprised that using double slash as comments seems to be valid XML.

The following parses correctly with Python and xml.etree.ElementTree and under xmllint --format:

```<code><root>
    <child1>text1</child1>
    <child2></child2> //this is a valid comment
    <child3></child3>
</root>
</code>```

I first thought that this could be seen as text node for root element, but trying it on python3 proved me wrong:

```<code>>>> import xml.etree.ElementTree as ET
>>> r=ET.parse("test.xml").getroot()
>>> r.text
'\n    '
>>> child2=r[1]
>>> child2.text
>>> ET.tostring(child2)
b'<child2 /> //this is a valid comment\n    '
</code>```

Can someone point me to the spec where this is allowed ?

答:
```<code><!--This is a valid comment-->
</code>```

<p>You need to put the comment this way. Same way comments are formed in HTML. </p>

Title: Double slash (//) as XML comment

Body:
I was a bit surprised that using double slash as comments seems to be valid XML.

The following parses correctly with Python and xml.etree.ElementTree and under xmllint --format:

<root>
    <child1>text1</child1>
    <child2></child2> //this is a valid comment
    <child3></child3>
</root>

I first thought that this could be seen as text node for root element, but trying it on python3 proved me wrong:

>>> import xml.etree.ElementTree as ET
>>> r=ET.parse("test.xml").getroot()
>>> r.text
'\n    '
>>> child2=r[1]
>>> child2.text
>>> ET.tostring(child2)
b'<child2 /> //this is a valid comment\n    '

Can someone point me to the spec where this is allowed ?

Body:
<!--This is a valid comment-->

You need to put the comment this way. Same way comments are formed in HTML.


来源: stackexchange

问:
Java:how to group similar strings (items) to respective array (group)?
I have the following string "0#Aitem, 0#Aitem2, 0#Aitem3, 1#Bitem, 1#Bitem2, 2#Citem, Nitem, Nitem2".

the 0# shows group number. so Aitem, Aitem2, Aitem3 will belong to group 0. Bitem, Bitem2 in group 1. Citem in group 2. If there is no group number, they will all be place in separate group. So Nitem, Nitem2 will be placed in group 3.

I would like to create an array for each group, and place the "items" in respective group(array). So I would end up with something like

```<code>[array("Aitem,Aitem2,Aitem3"), array("Bitem, Bitem2"), array("Citem"), array("Nitem, Nitem2")]
</code>```

I am guessing I need an arrayList to hold all the groups (arrays) which respectively has appropriate elements (items).

This is what I started with but I don't know if this is the best approach. The string is dynamic, so there can be any number of groups and has to follow the criteria above.

```<code>String[] x = Pattern.compile(",").split("0#item, 0#item2, 0#item3, 1#item, 1#item2, 2#item, item");
   for (int ii=0; ii<x.length; ii++) {
       System.out.println(i + " \"" + x[ii] + "\"");
   }
</code>```

答:
My answer shows how you can use a single regex to extract both the group and the item. You can then store these in a map.

```<code>    String s =  "0#Aitem, 0#Aitem2, 0#Aitem3, 1#Bitem, 1#Bitem2, 2#Citem, Nitem, Nitem2";
    Pattern p = Pattern.compile("(\\d*)[#]{0,1}(\\w+?)(,|$)");
    Matcher m = p.matcher(s);
    Map<String, List<String>> map = new TreeMap<String, List<String>>();
    while(m.find()){
        String group = m.group(1);
        String item = m.group(2);
        List<String> items = map.get(group);
        if(items == null){
            items = new ArrayList<String>();
            map.put(group, items);
        }
        items.add(item);
    }
    //let's print it out
    for(String key : map.keySet()){
        System.out.println(key + " : " + map.get(key));
    }
</code>```

prints:

```<code> : [Nitem, Nitem2]
0 : [Aitem, Aitem2, Aitem3]
1 : [Bitem, Bitem2]
2 : [Citem]
</code>```

At the moment, items with no group are keyed against an empty string. I'll leave it at as an exercise for you to handle this scenario. It should simply be a case of finding the max key and incrementing it.

I'm sure the regex can be improved too as it was written in haste.

ContentLicense: CC BY-SA 2.5

Body:
I have the following string "0#Aitem, 0#Aitem2, 0#Aitem3, 1#Bitem, 1#Bitem2, 2#Citem, Nitem, Nitem2".

the 0# shows group number. so Aitem, Aitem2, Aitem3 will belong to group 0. Bitem, Bitem2 in group 1. Citem in group 2. If there is no group number, they will all be place in separate group. So Nitem, Nitem2 will be placed in group 3.

I would like to create an array for each group, and place the "items" in respective group(array). So I would end up with something like

[array("Aitem,Aitem2,Aitem3"), array("Bitem, Bitem2"), array("Citem"), array("Nitem, Nitem2")]

I am guessing I need an arrayList to hold all the groups (arrays) which respectively has appropriate elements (items).

This is what I started with but I don't know if this is the best approach. The string is dynamic, so there can be any number of groups and has to follow the criteria above.

String[] x = Pattern.compile(",").split("0#item, 0#item2, 0#item3, 1#item, 1#item2, 2#item, item");
   for (int ii=0; ii<x.length; ii++) {
       System.out.println(i + " \"" + x[ii] + "\"");
   }

Body:
My answer shows how you can use a single regex to extract both the group and the item. You can then store these in a map.

    String s =  "0#Aitem, 0#Aitem2, 0#Aitem3, 1#Bitem, 1#Bitem2, 2#Citem, Nitem, Nitem2";
    Pattern p = Pattern.compile("(\\d*)[#]{0,1}(\\w+?)(,|$)");
    Matcher m = p.matcher(s);
    Map<String, List<String>> map = new TreeMap<String, List<String>>();
    while(m.find()){
        String group = m.group(1);
        String item = m.group(2);
        List<String> items = map.get(group);
        if(items == null){
            items = new ArrayList<String>();
            map.put(group, items);
        }
        items.add(item);
    }
    //let's print it out
    for(String key : map.keySet()){
        System.out.println(key + " : " + map.get(key));
    }

prints:

 : [Nitem, Nitem2]
0 : [Aitem, Aitem2, Aitem3]
1 : [Bitem, Bitem2]
2 : [Citem]

At the moment, items with no group are keyed against an empty string. I'll leave it at as an exercise for you to handle this scenario. It should simply be a case of finding the max key and incrementing it.

I'm sure the regex can be improved too as it was written in haste.


问:
node.js: cannot find module 'request'
I installed request module, and getting the error:

```<code>module.js:340
    throw err;
          ^
Error: Cannot find module 'request'
</code>```

i've read all the posts about this error, and understand that this is because module requests is not globally found, but i've already tried the 2 suggestions

npm install request -g

should this install it in /usr/loca/bin ? because i don't see it there.

and

sudo npm link

/usr/local/lib/node_modules/request -> /Users/soulsonic/dev/sandbox/node_test/request

i restarted terminal after each command, but keep getting the cannot find module  error.

update

there must have been some sort of conflict in my initial directory, because "npm install request" was not adding "request" under node_modules (there 10 others in there) ..
after switching to a new directory it just worked.

if i run it with -g switch, i do see it bing installed to /usr/local/lib/node_modules/request.

it seems that i just need to update my profile so that above path is automatically added.

答: I had same problem, for me npm install request --save solved the problem.  Hope it helps.

ContentLicense: CC BY-SA 3.0

Title: node.js: cannot find module 'request'

Body:
I installed request module, and getting the error:

module.js:340
    throw err;
          ^
Error: Cannot find module 'request'

i've read all the posts about this error, and understand that this is because module requests is not globally found, but i've already tried the 2 suggestions

npm install request -g

should this install it in /usr/loca/bin ? because i don't see it there.

and

sudo npm link

/usr/local/lib/node_modules/request -> /Users/soulsonic/dev/sandbox/node_test/request

i restarted terminal after each command, but keep getting the cannot find module  error.

update

there must have been some sort of conflict in my initial directory, because "npm install request" was not adding "request" under node_modules (there 10 others in there) ..
after switching to a new directory it just worked.

if i run it with -g switch, i do see it bing installed to /usr/local/lib/node_modules/request.

it seems that i just need to update my profile so that above path is automatically added.


问:
Issue when printing char buffer
I want to store the filename path in a char variable and pass it later via function call. To do so, I declared the following char buffer:

```<code>char *filename_path =  malloc(100* sizeof(char));
</code>```

Now, to test that, I assigned it using a path followed by printing the value of the buffer to make sure it fits well.

```<code>filename_path= "../Datasets/Cluster(%d)%s";
printf("%s\n", filename_path);
...
free(filename_path);
</code>```

However, I get this error :

```<code>../Datasets/Cluster(%d)%s
k.out(1154,0x7fff9843c3c0) malloc: *** error for object 0x103fbbacb: pointer being freed was not allocated
*** set a breakpoint in malloc_error_break to debug
Abort trap: 6
</code>```

Can someone hint me where the issue could be? Thank you

答:
The issue is memory location of malloc() versus a string literal such as filename_path= "../Datasets/Cluster(%d)%s";

malloc() allocates memory on the heap and returns a pointer to that memory. String literals are located somewhere else entirely -- usually in static/data(see this post for more info where in memory are string literals ? stack / heap?)

Since you assigned filename_path to point to somewhere other than where you malloced, you are unable to free it.

Title: Issue when printing char buffer

Body:
I want to store the filename path in a char variable and pass it later via function call. To do so, I declared the following char buffer:

char *filename_path =  malloc(100* sizeof(char));

Now, to test that, I assigned it using a path followed by printing the value of the buffer to make sure it fits well.

filename_path= "../Datasets/Cluster(%d)%s";
printf("%s\n", filename_path);
...
free(filename_path);

However, I get this error :

../Datasets/Cluster(%d)%s
k.out(1154,0x7fff9843c3c0) malloc: *** error for object 0x103fbbacb: pointer being freed was not allocated
*** set a breakpoint in malloc_error_break to debug
Abort trap: 6

Can someone hint me where the issue could be? Thank you


问:
Pandas If function or groupby
New to Pandas. I had this code originally written to read .csv and now I am writing to read .xlsx files. Anyway, I used if function before to read if Valid Part == 'YES' then ..... follow rest of code.

Now that I am using Pandas I have been testing groupby to achieve my count but haven't quite figured it out.

I am looking in this example if Valid Part == 'Yes' and Appl Req == 'Yes' give me the count.

Any advise is greatly appreciated.

```<code>import pandas as pd

df = pd.read_excel('IMPORT.xlsx')

app_req = df.groupby(['Valid Part', 'Appl Req']).count()

print(app_req)
</code>```

Sample of Data

答:
I think you need filter by boolean indexing or query first and then aggregate by size:

```<code>df = df[(df['Valid Part'] == 'Yes') & (df['Appl Req'] == 'Yes')]
app_req = df.groupby(['Valid Part', 'Appl Req']).size()
</code>```

What is the difference between size and count in pandas?

EDIT:

Sample:

```<code>np.random.seed(100)
N = 10
df = pd.DataFrame(np.random.choice(['Yes','No'], size=(N,3)),
                  columns=['Valid Part', 'Appl Req', 'A'])
print (df)
   Valid Part Appl Req    A
0         Yes      Yes   No
1          No       No   No
2         Yes      Yes  Yes
3         Yes      Yes   No
4         Yes      Yes  Yes
5         Yes       No  Yes
6         Yes       No  Yes
7          No      Yes  Yes
8         Yes       No   No
9          No      Yes  Yes
</code>```

It seems you need only sum of True values:

```<code>print ((df['Valid Part'] == 'Yes') & (df['Appl Req'] == 'Yes'))
0     True
1    False
2     True
3     True
4     True
5    False
6    False
7    False
8    False
9    False
dtype: bool

app_req = ((df['Valid Part'] == 'Yes') & (df['Appl Req'] == 'Yes')).sum()
print (app_req)
4
</code>```

```<code>df = df[(df['Valid Part'] == 'Yes') & (df['Appl Req'] == 'Yes')]
app_req = df.groupby(['Valid Part', 'Appl Req']).size().reset_index(name='COUNT')
print (app_req)
  Valid Part Appl Req  COUNT
0        Yes      Yes      4
</code>```

Title: Pandas If function or groupby

Body:
New to Pandas. I had this code originally written to read .csv and now I am writing to read .xlsx files. Anyway, I used if function before to read if Valid Part == 'YES' then ..... follow rest of code.

Now that I am using Pandas I have been testing groupby to achieve my count but haven't quite figured it out.

I am looking in this example if Valid Part == 'Yes' and Appl Req == 'Yes' give me the count.

Any advise is greatly appreciated.

import pandas as pd

df = pd.read_excel('IMPORT.xlsx')

app_req = df.groupby(['Valid Part', 'Appl Req']).count()

print(app_req)

Sample of Data

Body:
I think you need filter by boolean indexing or query first and then aggregate by size:

df = df[(df['Valid Part'] == 'Yes') & (df['Appl Req'] == 'Yes')]
app_req = df.groupby(['Valid Part', 'Appl Req']).size()

What is the difference between size and count in pandas?

EDIT:

Sample:

np.random.seed(100)
N = 10
df = pd.DataFrame(np.random.choice(['Yes','No'], size=(N,3)),
                  columns=['Valid Part', 'Appl Req', 'A'])
print (df)
   Valid Part Appl Req    A
0         Yes      Yes   No
1          No       No   No
2         Yes      Yes  Yes
3         Yes      Yes   No
4         Yes      Yes  Yes
5         Yes       No  Yes
6         Yes       No  Yes
7          No      Yes  Yes
8         Yes       No   No
9          No      Yes  Yes

It seems you need only sum of True values:

print ((df['Valid Part'] == 'Yes') & (df['Appl Req'] == 'Yes'))
0     True
1    False
2     True
3     True
4     True
5    False
6    False
7    False
8    False
9    False
dtype: bool

app_req = ((df['Valid Part'] == 'Yes') & (df['Appl Req'] == 'Yes')).sum()
print (app_req)
4

df = df[(df['Valid Part'] == 'Yes') & (df['Appl Req'] == 'Yes')]
app_req = df.groupby(['Valid Part', 'Appl Req']).size().reset_index(name='COUNT')
print (app_req)
  Valid Part Appl Req  COUNT
0        Yes      Yes      4


问:
How to Print Text In Web Assembly
Is there any way to print text onto the window directly in web assembly instead of having to pass string data into javascript, or print to the console?</p>

答: No.  WebAssembly can't directly manipulate the DOM yet.  For now you must use Javascript glue.  It is a planned future feature however.</p>

Title: How to Print Text In Web Assembly


问:
Designing password text with show password button
I am trying to design EditText for password with show password imageView. However I cannot design it correctly beacuse I cannot see ImageView, since EditText's layout_width="fill_parent". When I change it to wrap_content, I can see my ImageView but then it looks very bad in UI. Is it possible to design it without giving fixed size?

Here is my code;

```<code>        <android.support.design.widget.TextInputLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="8dp"
            android:orientation="horizontal"
            android:layout_marginBottom="8dp">

            <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:orientation="horizontal">

            <EditText
                android:id="@+id/registerPassword"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:hint="@string/register_password"
                android:inputType="textPassword" />
            <ImageView
                android:id="@+id/fragment_login_password_visibility"
                android:layout_height="wrap_content"
                android:layout_width="wrap_content"
                android:src="@android:drawable/ic_partial_secure"
                android:layout_gravity="center"
                android:clickable="true"/>

            </LinearLayout>
        </android.support.design.widget.TextInputLayout>
</code>```

EDIT:

android:layout_weight=1 solved issue. Now I can see ImageView left of EditText. However now, I TextInputLayout hint is not working.

答:
I recommend using a TextInputLayout with passwordToggleDrawable .

```<code>  <android.support.design.widget.TextInputLayout
            android:id="@+id/textInputPasswordLayout"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            app:passwordToggleContentDescription="Show"
            app:passwordToggleDrawable="@drawable/ic_password_visibility_selector"
            app:passwordToggleEnabled="true">

            <android.support.design.widget.TextInputEditText
                android:id="@+id/textInputEditTextPassword"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:ems="10"
                android:fontFamily="sans-serif-light"
                android:gravity="bottom"
                android:hint="@string/enter_your_password"/>

        </android.support.design.widget.TextInputLayout>
</code>```

app:passwordToggleDrawable="@drawable/ic_password_visibility_selector" assign your drawable

Body:
I am trying to design EditText for password with show password imageView. However I cannot design it correctly beacuse I cannot see ImageView, since EditText's layout_width="fill_parent". When I change it to wrap_content, I can see my ImageView but then it looks very bad in UI. Is it possible to design it without giving fixed size?

Here is my code;

        <android.support.design.widget.TextInputLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="8dp"
            android:orientation="horizontal"
            android:layout_marginBottom="8dp">

            <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:orientation="horizontal">

            <EditText
                android:id="@+id/registerPassword"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:hint="@string/register_password"
                android:inputType="textPassword" />
            <ImageView
                android:id="@+id/fragment_login_password_visibility"
                android:layout_height="wrap_content"
                android:layout_width="wrap_content"
                android:src="@android:drawable/ic_partial_secure"
                android:layout_gravity="center"
                android:clickable="true"/>

            </LinearLayout>
        </android.support.design.widget.TextInputLayout>

EDIT:

android:layout_weight=1 solved issue. Now I can see ImageView left of EditText. However now, I TextInputLayout hint is not working.

Body:
I recommend using a TextInputLayout with passwordToggleDrawable .

  <android.support.design.widget.TextInputLayout
            android:id="@+id/textInputPasswordLayout"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            app:passwordToggleContentDescription="Show"
            app:passwordToggleDrawable="@drawable/ic_password_visibility_selector"
            app:passwordToggleEnabled="true">

            <android.support.design.widget.TextInputEditText
                android:id="@+id/textInputEditTextPassword"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:ems="10"
                android:fontFamily="sans-serif-light"
                android:gravity="bottom"
                android:hint="@string/enter_your_password"/>

        </android.support.design.widget.TextInputLayout>

app:passwordToggleDrawable="@drawable/ic_password_visibility_selector" assign your drawable


问:
Preserving order with PostgreSQL and Rails
I'm running some elasticsearch queries and then taking those results and converting them into Active Record. Of course, order is not preserved.

I've had this working before but now I'm using Ruby 2.3.1 an Rails 5.1.1.

I've tried all of the following solutions so I'm beginning to think this is some bug with this environment.

```<code>def self.find_ordered(ids)
  order_clause = "CASE id "
  ids.each_with_index do |id, index|
    order_clause << sanitize_sql_array(["WHEN ? THEN ? ", id, index])
  end
  order_clause << sanitize_sql_array(["ELSE ? END", ids.length])
  where(id: ids).order(order_clause)
end
</code>```

Also:

```<code>def self.order_by_ids(ids)
  order_by = ["case"]
  ids.each_with_index.map do |id, index|
    order_by << "WHEN id='#{id}' THEN #{index}"
  end
  order_by << "end"
  order(order_by.join(" "))
end
</code>```

And https://github.com/panorama-ed/order_as_specified gem:

```<code>Product.order_as_specified(id: [ids])
</code>```

And https://github.com/khiav223577/find_with_order:

```<code>Product.find_with_order([ids])
</code>```

All of these should work, but all default back to numerical order after being run. I'm running them in the console so no code could be being run after.

Edit: Example of request in console.

```<code>Product.where(id: [100,5,10]).order_by_ids([100,5,10]).pluck(:id)
  (127.0ms)  SELECT "products"."id" FROM "products" WHERE
  "products"."id" IN (100, 5, 10) ORDER BY "products"."id" ASC, case
 WHEN id='100' THEN 0 WHEN id='5' THEN 1 WHEN id='10' THEN 2 end
 => [5, 10, 100]
</code>```

答: The simplest solution to preserve order would be to order based on a field that doesn't change. In Rails, created_at would be such a field unless you're not using timestamps.

Body:
I'm running some elasticsearch queries and then taking those results and converting them into Active Record. Of course, order is not preserved.

I've had this working before but now I'm using Ruby 2.3.1 an Rails 5.1.1.

I've tried all of the following solutions so I'm beginning to think this is some bug with this environment.

def self.find_ordered(ids)
  order_clause = "CASE id "
  ids.each_with_index do |id, index|
    order_clause << sanitize_sql_array(["WHEN ? THEN ? ", id, index])
  end
  order_clause << sanitize_sql_array(["ELSE ? END", ids.length])
  where(id: ids).order(order_clause)
end

Also:

def self.order_by_ids(ids)
  order_by = ["case"]
  ids.each_with_index.map do |id, index|
    order_by << "WHEN id='#{id}' THEN #{index}"
  end
  order_by << "end"
  order(order_by.join(" "))
end

And https://github.com/panorama-ed/order_as_specified gem:

Product.order_as_specified(id: [ids])

And https://github.com/khiav223577/find_with_order:

Product.find_with_order([ids])

All of these should work, but all default back to numerical order after being run. I'm running them in the console so no code could be being run after.

Edit: Example of request in console.

Product.where(id: [100,5,10]).order_by_ids([100,5,10]).pluck(:id)
  (127.0ms)  SELECT "products"."id" FROM "products" WHERE
  "products"."id" IN (100, 5, 10) ORDER BY "products"."id" ASC, case
 WHEN id='100' THEN 0 WHEN id='5' THEN 1 WHEN id='10' THEN 2 end
 => [5, 10, 100]


问:
How do I make a working symlink to a command in my node_modules .bin folder on Windows?
I'd like to run lab from my root directory without having to mess with %bindir% or .\node_modules\.bin\lab.cmd. I want to be able to run tests with $ lab and that's it.

Here's my attempt. Keep in mind that I've already set up some aliases for things like grep in Powershell.

```<code>$ ll .\node_modules\.bin | grep lab
-a----         7/5/2017   2:57 PM            293 lab
-a----         7/5/2017   2:57 PM            170 lab.cmd

$ cmd /c mklink lab .\node_modules\.bin\lab\lab.cmd
symbolic link created for lab <<===>> .\node_modules\.bin\lab\lab.cmd

$ ll lab

Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-a---l         7/7/2017   9:04 AM              0 lab

$ lab
lab : The term 'lab' is not recognized as the name of a cmdlet, function, script file...

$ ./lab
Program 'lab' failed to run: No application is associated with the specified file...
</code>```

Naming the alias lab.cmd didn't do anything. Is this possible on Windows?

答:
I really think it's a matter of Windows not really being built like that. I do think there is probably a way you could sort out the symlink but in all reality this is what the various powershell profiles are there for. When something shouldn't be system wide but you want easy and quick access to it.

If you want it to be available just to yourself you can put it in $profile, if you want it to be available to any user you happen to run powershell as you can put it in C:\windows\System32\WindowsPowerShell\v1.0\Microsoft.PowerShell_profile.ps1

The functionality for symlinks exists in Windows, but it isn't as fleshed out as in *nix, for better or for worse, depending on locations, filenames and a whole host of other quirky things you are likely to run into all manner of problems.

Body:
I'd like to run lab from my root directory without having to mess with %bindir% or .\node_modules\.bin\lab.cmd. I want to be able to run tests with $ lab and that's it.

Here's my attempt. Keep in mind that I've already set up some aliases for things like grep in Powershell.

$ ll .\node_modules\.bin | grep lab
-a----         7/5/2017   2:57 PM            293 lab
-a----         7/5/2017   2:57 PM            170 lab.cmd

$ cmd /c mklink lab .\node_modules\.bin\lab\lab.cmd
symbolic link created for lab <<===>> .\node_modules\.bin\lab\lab.cmd

$ ll lab

Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-a---l         7/7/2017   9:04 AM              0 lab

$ lab
lab : The term 'lab' is not recognized as the name of a cmdlet, function, script file...

$ ./lab
Program 'lab' failed to run: No application is associated with the specified file...

Naming the alias lab.cmd didn't do anything. Is this possible on Windows?


问:
Grid item not aligning as expected
I am trying to get the content of item to be in the middle column, but it does not seem to be moving.

.home-grid-container {
  display: grid;
  grid-template-columns: auto;
  grid-template-rows: 0.10fr 0.98fr auto;
  height: 100vh;
}

.home-header {
  grid-column: 1 / span 3;
  grid-row: 1 / span 1;
  background: #3f51b5;
}

.home-main {
  grid-column: 1 / span 3;
  grid-row: 2 / span 3;
  background: #81d4fa;
}

.item {
  grid-column: 2 / span 1;
  grid-row: 2 / span 3;
}

.home-footer {
  grid-column: 1 / span 3;
  grid-row: 5 / span 1;
  background: #3f51b5;
  div {
    text-align: center;
    margin: 2vh;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="home-grid-container">
  <div class="home-header">
    <h1>
      <img src="/src/imgs/sitelogo.png" />
    </h1>
  </div>
  <div class="home-main">
    <div class="item">
      Simple, Fast, Powerful
      <input type="button" value="100% Free" />
    </div>
  </div>
  <div class="home-footer">
    <div>All Rights Reserved</div>
  </div>
</div></code>```

https://css-tricks.com/snippets/css/complete-guide-grid/

答:
The elements you want to center are descendants, but not children, of the grid container.

Because grid layout only extends between parent and child elements, the .item element is out of scope and will not accept grid properties.

But these elements are inline-level children of a block container, which means that text-align: center will work.

.home-grid-container {
  display: grid;
  grid-template-columns: auto;
  grid-template-rows: 0.10fr 0.98fr auto;
  height: 100vh;
}

.home-header {
  grid-column: 1 / span 3;
  grid-row: 1 / span 1;
  background: #3f51b5;
}

.home-main {
  grid-column: 1 / span 3;
  grid-row: 2 / span 3;
  background: #81d4fa;
}

.item {
  grid-column: 2 / span 1;
  grid-row: 2 / span 3;
  text-align: center;    /* NEW */
}

.home-footer {
  grid-column: 1 / span 3;
  grid-row: 5 / span 1;
  background: #3f51b5;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="home-grid-container">
  <div class="home-header">
    <h1>
      <img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt="">
    </h1>
  </div>
  <div class="home-main">
    <div class="item">
      Simple, Fast, Powerful
      <input type="button" value="100% Free" />
    </div>
  </div>
  <div class="home-footer">
    <div>All Rights Reserved</div>
  </div>
</div></code>```

jsFiddle demo

Title: Grid item not aligning as expected

Body:
I am trying to get the content of item to be in the middle column, but it does not seem to be moving.

.home-grid-container {
  display: grid;
  grid-template-columns: auto;
  grid-template-rows: 0.10fr 0.98fr auto;
  height: 100vh;
}

.home-header {
  grid-column: 1 / span 3;
  grid-row: 1 / span 1;
  background: #3f51b5;
}

.home-main {
  grid-column: 1 / span 3;
  grid-row: 2 / span 3;
  background: #81d4fa;
}

.item {
  grid-column: 2 / span 1;
  grid-row: 2 / span 3;
}

.home-footer {
  grid-column: 1 / span 3;
  grid-row: 5 / span 1;
  background: #3f51b5;
  div {
    text-align: center;
    margin: 2vh;
  }
}

      Simple, Fast, Powerful
      <input type="button" value="100% Free" />

All Rights Reserved

https://css-tricks.com/snippets/css/complete-guide-grid/

Body:
The elements you want to center are descendants, but not children, of the grid container.

Because grid layout only extends between parent and child elements, the .item element is out of scope and will not accept grid properties.

But these elements are inline-level children of a block container, which means that text-align: center will work.

.home-grid-container {
  display: grid;
  grid-template-columns: auto;
  grid-template-rows: 0.10fr 0.98fr auto;
  height: 100vh;
}

.home-header {
  grid-column: 1 / span 3;
  grid-row: 1 / span 1;
  background: #3f51b5;
}

.home-main {
  grid-column: 1 / span 3;
  grid-row: 2 / span 3;
  background: #81d4fa;
}

.item {
  grid-column: 2 / span 1;
  grid-row: 2 / span 3;
  text-align: center;    /* NEW */
}

.home-footer {
  grid-column: 1 / span 3;
  grid-row: 5 / span 1;
  background: #3f51b5;
}

<div class="home-grid-container">
  <div class="home-header">
    <h1>
      <img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt="">
    </h1>
  </div>
  <div class="home-main">
    <div class="item">
      Simple, Fast, Powerful
      <input type="button" value="100% Free" />
    </div>
  </div>
  <div class="home-footer">
    <div>All Rights Reserved</div>
  </div>
</div>

jsFiddle demo


问:
New Ruby on Rails Setup : "Expected string default value for '--rc'; got false (boolean)"
I'm setting up a Ruby on Rails web development environment on a new machine (macOS Sierra v. 10.12.1).  I'm following the setup instructions here: Setup Ruby On Rails on macOS 10.12 Sierra.  When I check the newly installed rails version, I get the following:

```<code>$ rails --version
Expected string default value for '--rc'; got false (boolean)
Rails 4.2.6
</code>```

I haven't seen that second line before, and googling hasn't yielded any helpful results.  Background information: clean install of macOS 10.12.1; installed xcode via the App Store; installed Homebrew via the instructions on its homepage; installing Ruby, Rails, etc. via the first link I mentioned.

Anyone have any idea what might be going on?

答:
I had the same issue with Rails 4.2.7, set up with RubyMine 7.1.3.

Adding gem 'thor', '0.19.1' to my Gemfile and then running bundle update thor fixed the issue.

Body:
I'm setting up a Ruby on Rails web development environment on a new machine (macOS Sierra v. 10.12.1).  I'm following the setup instructions here: Setup Ruby On Rails on macOS 10.12 Sierra.  When I check the newly installed rails version, I get the following:

$ rails --version
Expected string default value for '--rc'; got false (boolean)
Rails 4.2.6

I haven't seen that second line before, and googling hasn't yielded any helpful results.  Background information: clean install of macOS 10.12.1; installed xcode via the App Store; installed Homebrew via the instructions on its homepage; installing Ruby, Rails, etc. via the first link I mentioned.

Anyone have any idea what might be going on?


问:
Java inheritance - Two classes that use the same methods
I have two classes, ObjectA and ObjectB that both extend the same class MasterObject. I also have an interface which contains a method that I want both ObjectA and ObjectB to implement. This method is not found within MasterObject. I then have a class which has a field of type MasterObject and want to access the methods within ObjectA and ObjectB. Is this possible without casting? Here is some code that I have.

In addition, I am unable to alter the MasterObject class.

```<code>public interface MyInterface{
    void doSomething();
}

class ObjectA extends MasterObject implements MyInterface {

    @Override
    public void doSomething(){
        //...
    }
}

class ObjectB extends MasterObject implements MyInterface {
    @Override
    public void doSomething(){
        //...
    }
}

class Main {
    MasterObject mObj;

    public void method1() {
        mObj = new ObjectA();
        mObj.doSomething();
    }

    public void method2() {
        mObj = new ObjectB();
        mObj.doSomething(); //runs code from ObjectB class
    }
}
</code>```

Right now this is obviously throwing some compiler issues. (Cannot resolve method doSomething()).

Casting like so: ((ObjectA) mObj).doSomething(); seems to work, but is there another way to do this without casting? Anything cleaner?

答:
The cleanest way would be declaring the object with the interface as type:

```<code>MyInterface mObj;
</code>```

You can instantiate the object with the concrete classes in the same manner:

```<code>mObj = new ObjectA();
...
mObj = new ObjectB();
</code>```

The only constraint is that - without casting - you will be able to call only doSomething method, since it is the only method defined in the interface. If you intend to use this method only, it is the way to go.

Body:
I have two classes, ObjectA and ObjectB that both extend the same class MasterObject. I also have an interface which contains a method that I want both ObjectA and ObjectB to implement. This method is not found within MasterObject. I then have a class which has a field of type MasterObject and want to access the methods within ObjectA and ObjectB. Is this possible without casting? Here is some code that I have.

In addition, I am unable to alter the MasterObject class.

public interface MyInterface{
    void doSomething();
}

class ObjectA extends MasterObject implements MyInterface {

    @Override
    public void doSomething(){
        //...
    }
}

class ObjectB extends MasterObject implements MyInterface {
    @Override
    public void doSomething(){
        //...
    }
}

class Main {
    MasterObject mObj;

    public void method1() {
        mObj = new ObjectA();
        mObj.doSomething();
    }

    public void method2() {
        mObj = new ObjectB();
        mObj.doSomething(); //runs code from ObjectB class
    }
}

Right now this is obviously throwing some compiler issues. (Cannot resolve method doSomething()).

Casting like so: ((ObjectA) mObj).doSomething(); seems to work, but is there another way to do this without casting? Anything cleaner?

Body:
The cleanest way would be declaring the object with the interface as type:

MyInterface mObj;

You can instantiate the object with the concrete classes in the same manner:

mObj = new ObjectA();
...
mObj = new ObjectB();

The only constraint is that - without casting - you will be able to call only doSomething method, since it is the only method defined in the interface. If you intend to use this method only, it is the way to go.


问:
Generic error when saving Bitmap in Xamarin
```<code>open System.Drawing
let bitmap = new Bitmap(16,16)
let path =  __SOURCE_DIRECTORY__
bitmap.Save(path+"bitmap.png")
</code>```

I wrote the code above to save a instantiated Bitmap into the project folder. I got a Generic Error when I ran the code. The whole bunch of error messages is as below.

System.Exception: Generic Error [GDI+ status: GenericError]
     at System.Drawing.GDIPlus.CheckStatus (System.Drawing.Status status) [0x00079] in :0
     at System.Drawing.Image.Save (System.String filename, System.Drawing.Imaging.ImageCodecInfo encoder, System.Drawing.Imaging.EncoderParameters encoderParams) [0x0003d] in :0
     at System.Drawing.Image.Save (System.String filename, System.Drawing.Imaging.ImageFormat format) [0x00044] in :0
     at System.Drawing.Image.Save (System.String filename) [0x00008] in :0
     at (wrapper remoting-invoke-with-check) System.Drawing.Image:Save (string)
     at .$FSI_0037.main@ () [0x00006] in <4081182357644f828a64898ac573806b>:0
     at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (System.Reflection.MonoMethod,object,object[],System.Exception&)
     at System.Reflection.MonoMethod.Invoke (System.Object obj, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00032] in :0

I debugged the code and figured out the following things.

the line of code to create a Bitmap worked fine

the path in this situation was "/"

the code was fine before the Save() function was called

I just started to learn F# and cannot figure out the problem. Could anyone help with this?

答:
The problem came from the value of the "SOURCE_DIRECTORY" of the code.
In most cases, the value of SOURCE_DIRECTORY does not contain a '/' at the end of it. So the last line of code can be changed to the code below.

```<code>bitmap.Save(path+"/bitmap.png")
</code>```

I my case, the value of SOURCE_DIRECTORY is a single "/". Although I still haven't figured out why, the problem described can be solved by specifying an existing directory with the filename in the bitmap save function.

Body:
open System.Drawing
let bitmap = new Bitmap(16,16)
let path =  __SOURCE_DIRECTORY__
bitmap.Save(path+"bitmap.png")

I wrote the code above to save a instantiated Bitmap into the project folder. I got a Generic Error when I ran the code. The whole bunch of error messages is as below.

System.Exception: Generic Error [GDI+ status: GenericError]
     at System.Drawing.GDIPlus.CheckStatus (System.Drawing.Status status) [0x00079] in :0
     at System.Drawing.Image.Save (System.String filename, System.Drawing.Imaging.ImageCodecInfo encoder, System.Drawing.Imaging.EncoderParameters encoderParams) [0x0003d] in :0
     at System.Drawing.Image.Save (System.String filename, System.Drawing.Imaging.ImageFormat format) [0x00044] in :0
     at System.Drawing.Image.Save (System.String filename) [0x00008] in :0
     at (wrapper remoting-invoke-with-check) System.Drawing.Image:Save (string)
     at .$FSI_0037.main@ () [0x00006] in <4081182357644f828a64898ac573806b>:0
     at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (System.Reflection.MonoMethod,object,object[],System.Exception&)
     at System.Reflection.MonoMethod.Invoke (System.Object obj, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00032] in :0

I debugged the code and figured out the following things.

the line of code to create a Bitmap worked fine

the path in this situation was "/"

the code was fine before the Save() function was called

I just started to learn F# and cannot figure out the problem. Could anyone help with this?

Body:
The problem came from the value of the "SOURCE_DIRECTORY" of the code.
In most cases, the value of SOURCE_DIRECTORY does not contain a '/' at the end of it. So the last line of code can be changed to the code below.

bitmap.Save(path+"/bitmap.png")

I my case, the value of SOURCE_DIRECTORY is a single "/". Although I still haven't figured out why, the problem described can be solved by specifying an existing directory with the filename in the bitmap save function.


问:
Counting Rows Based on Exist Condition
I have researched many Stackoverflow questions that demonstrate how to add conditions to the COUNT statement using a CASE statement but I can't find an example of how to do what I need to.  Let's assume I have the following tables:

```<code>CREATE TABLE [Project](
    [ProjectId] [int] NOT NULL,
    [ProjectName] [nvarchar](100) NOT NULL
)
GO

CREATE TABLE [ProjectTask](
    [ProjectTaskId] [int] NOT NULL,
    [ProjectId] [int] NOT NULL,
    [TaskName] [nvarchar](100) NOT NULL
)
GO

CREATE TABLE [ProjectTaskOwner](
    [ProjectTaskId] [int] NOT NULL,
    [UserId] [int] NOT NULL
 )
GO

CREATE TABLE [ProjectTaskEntity](
    [ProjectTaskId] [int] NOT NULL,
    [EntityId] [int] NOT NULL,
    [AssignedUserId] [int]
 )
GO

INSERT Project (ProjectId, ProjectName) VALUES (1, 'Test Project')
INSERT ProjectTask (ProjectTaskId, ProjectId, TaskName) VALUES(1, 1, 'Task1')
INSERT ProjectTask (ProjectTaskId, ProjectId, TaskName) VALUES(2, 1, 'Task2')
INSERT ProjectTaskOwner (ProjectTaskId, UserId) VALUES (1, 1)
INSERT ProjectTaskOwner (ProjectTaskId, UserId) VALUES (1, 2)
INSERT ProjectTaskOwner (ProjectTaskId, UserId) VALUES (1, 3)
INSERT ProjectTaskEntity (ProjectTaskId, EntityId, AssignedUserId) VALUES (1, 1, 1)
INSERT ProjectTaskEntity (ProjectTaskId, EntityId, AssignedUserId) VALUES (1, 2, 2)
INSERT ProjectTaskEntity (ProjectTaskId, EntityId, AssignedUserId) VALUES (1, 3, 3)
INSERT ProjectTaskEntity (ProjectTaskId, EntityId, AssignedUserId) VALUES (1, 4, 256)
</code>```

What I want to do is get for each Project Task the count of entities that are assigned to me and assigned to other task owners.  So for the test data above, given a user id of 1 and a project id of 1 I expect:

```<code>| TaskId | AssignedToMe | AssignedToOthers |
|   1    |      1       |       2          |
|   2    |      0       |       0          |
</code>```

So here is what I have so far:

```<code>DECLARE @userId INT = 1
SELECT
    pt.ProjectId,
    pt.ProjectTaskId,
    COUNT(CASE WHEN pte.AssignedUserId = @userId THEN 1 ELSE NULL END) AS AssignedTo
FROM ProjectTask pt
INNER JOIN Project p
    ON p.ProjectId = pt.ProjectId
LEFT JOIN ProjectTaskEntity pte
    ON pte.ProjectTaskId = pt.ProjectTaskId
WHERE p.ProjectId = 1
GROUP BY pt.ProjectId,  pt.ProjectTaskId
</code>```

Assigned to me was easy.  The problem is I'm not sure how to do others because others isn't just anyone not me.  It is anyone not in the ProjectTaskOwner table for this task.  Anyone have any idea how to achieve this?

答:
I don't see why you need to project table for this.  I would write this as:

```<code>SELECT pt.ProjectId, pt.ProjectTaskId,
       SUM(CASE WHEN pte.AssignedUserId = @userId THEN 1 ELSE 0 END) AS AssignedToMe,
       SUM(CASE WHEN pto.UserId IS NULL THEN 1 ELSE 0 END) AS AssignedToOthers
FROM ProjectTask pt LEFT JOIN
     ProjectTaskEntity pte
     ON pte.ProjectTaskId = pt.ProjectTaskId LEFT JOIN
     ProjectTaskOwner pto
     ON pto.ProjectTaskId = pt.ProjectTaskId AND
        pto.UserId = pte.AssignedUserId
WHERE pt.ProjectId = 1
GROUP BY pt.ProjectId, pt.ProjectTaskId;
</code>```

I replaced the COUNT() with SUM().  As a matter of preference, I prefer SUM() in this situation.

Title: Counting Rows Based on Exist Condition

Body:
I have researched many Stackoverflow questions that demonstrate how to add conditions to the COUNT statement using a CASE statement but I can't find an example of how to do what I need to.  Let's assume I have the following tables:

CREATE TABLE [Project](
    [ProjectId] [int] NOT NULL,
    [ProjectName] [nvarchar](100) NOT NULL
)
GO

CREATE TABLE [ProjectTask](
    [ProjectTaskId] [int] NOT NULL,
    [ProjectId] [int] NOT NULL,
    [TaskName] [nvarchar](100) NOT NULL
)
GO

CREATE TABLE [ProjectTaskOwner](
    [ProjectTaskId] [int] NOT NULL,
    [UserId] [int] NOT NULL
 )
GO

CREATE TABLE [ProjectTaskEntity](
    [ProjectTaskId] [int] NOT NULL,
    [EntityId] [int] NOT NULL,
    [AssignedUserId] [int]
 )
GO

INSERT Project (ProjectId, ProjectName) VALUES (1, 'Test Project')
INSERT ProjectTask (ProjectTaskId, ProjectId, TaskName) VALUES(1, 1, 'Task1')
INSERT ProjectTask (ProjectTaskId, ProjectId, TaskName) VALUES(2, 1, 'Task2')
INSERT ProjectTaskOwner (ProjectTaskId, UserId) VALUES (1, 1)
INSERT ProjectTaskOwner (ProjectTaskId, UserId) VALUES (1, 2)
INSERT ProjectTaskOwner (ProjectTaskId, UserId) VALUES (1, 3)
INSERT ProjectTaskEntity (ProjectTaskId, EntityId, AssignedUserId) VALUES (1, 1, 1)
INSERT ProjectTaskEntity (ProjectTaskId, EntityId, AssignedUserId) VALUES (1, 2, 2)
INSERT ProjectTaskEntity (ProjectTaskId, EntityId, AssignedUserId) VALUES (1, 3, 3)
INSERT ProjectTaskEntity (ProjectTaskId, EntityId, AssignedUserId) VALUES (1, 4, 256)

What I want to do is get for each Project Task the count of entities that are assigned to me and assigned to other task owners.  So for the test data above, given a user id of 1 and a project id of 1 I expect:

| TaskId | AssignedToMe | AssignedToOthers |
|   1    |      1       |       2          |
|   2    |      0       |       0          |

So here is what I have so far:

DECLARE @userId INT = 1
SELECT
    pt.ProjectId,
    pt.ProjectTaskId,
    COUNT(CASE WHEN pte.AssignedUserId = @userId THEN 1 ELSE NULL END) AS AssignedTo
FROM ProjectTask pt
INNER JOIN Project p
    ON p.ProjectId = pt.ProjectId
LEFT JOIN ProjectTaskEntity pte
    ON pte.ProjectTaskId = pt.ProjectTaskId
WHERE p.ProjectId = 1
GROUP BY pt.ProjectId,  pt.ProjectTaskId

Assigned to me was easy.  The problem is I'm not sure how to do others because others isn't just anyone not me.  It is anyone not in the ProjectTaskOwner table for this task.  Anyone have any idea how to achieve this?

Body:
I don't see why you need to project table for this.  I would write this as:

SELECT pt.ProjectId, pt.ProjectTaskId,
       SUM(CASE WHEN pte.AssignedUserId = @userId THEN 1 ELSE 0 END) AS AssignedToMe,
       SUM(CASE WHEN pto.UserId IS NULL THEN 1 ELSE 0 END) AS AssignedToOthers
FROM ProjectTask pt LEFT JOIN
     ProjectTaskEntity pte
     ON pte.ProjectTaskId = pt.ProjectTaskId LEFT JOIN
     ProjectTaskOwner pto
     ON pto.ProjectTaskId = pt.ProjectTaskId AND
        pto.UserId = pte.AssignedUserId
WHERE pt.ProjectId = 1
GROUP BY pt.ProjectId, pt.ProjectTaskId;

I replaced the COUNT() with SUM().  As a matter of preference, I prefer SUM() in this situation.


问:
Excel 2010 VBA - Continually Looking In Folder for File to Process?
I have a need to build a macro in Excel 2010 that basically runs continually (started by button or stopped by button) that looks into a file folder.  If a file is created there and named a certain way then the macro opens it and processes the data inside.  The file is then closed and deleted.  The macro then continues on to watch the file folder for more files to process

Is this a reasonable / doable macro that I could create in Excel with VBA?  Can VBA continually run without issues?

Best Regards
Andy

答:
see this thread for some ideas:

https://superuser.com/questions/226828/how-to-monitor-a-folder-and-trigger-a-command-line-action-when-a-file-is-created

the first answer probably will do it, just trigger the excel macro you want from that. You can get as fancy as you want with the execution. The application.ontime function only works if excel is open, I believe.

What you want is to find a way to monitor the folder constantly.


问:
Flask cookie not set with ajax request
I'm trying to set a cookie from a Flask server on an ajax request from a react app. I made an easy test case and even then, the cookie is sent in the response, but isn't set in the browser

Flask:

```<code>@app.route('/is_alive', methods = ['POST'])
def alive():
    resp = app.make_response("There should be a cookie")
    resp.set_cookie("testing", 'testing')
    return resp
</code>```

Javascript:

```<code>static isAlivePost() {
    return new Promise(resolve => {
        let options = {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json',
            },
            credentials: 'same-origin',
            body: JSON.stringify({
                firstParam: 'true'
            })
        }

        fetch(endpoints.MOCK_API + 'is_alive', options)
            .then(response => {
                resolve(response.text());
            }).then(function(data) {
                resolve(data);
            })
            .catch(e => {
                reject(e);
            });
    });
}
</code>```

答: The credentials: 'same-origin' needed to be credentials: 'include'.

Title: Flask cookie not set with ajax request

Body:
I'm trying to set a cookie from a Flask server on an ajax request from a react app. I made an easy test case and even then, the cookie is sent in the response, but isn't set in the browser

Flask:

@app.route('/is_alive', methods = ['POST'])
def alive():
    resp = app.make_response("There should be a cookie")
    resp.set_cookie("testing", 'testing')
    return resp

Javascript:

static isAlivePost() {
    return new Promise(resolve => {
        let options = {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json',
            },
            credentials: 'same-origin',
            body: JSON.stringify({
                firstParam: 'true'
            })
        }

        fetch(endpoints.MOCK_API + 'is_alive', options)
            .then(response => {
                resolve(response.text());
            }).then(function(data) {
                resolve(data);
            })
            .catch(e => {
                reject(e);
            });
    });
}


问:
Could not load the Tomcat server configuration
I have installed apache tomcat7 using sudo apt get in ubuntu. I have added apache tomcat 7 to eclipse using Windows > Preferences > Server > Runtime Environment.But when I'm starting the server from server view by right clicking the shown Tomcat v7.0 Server at localhost [Stopped,Republish]
It says:

Could not load the Tomcat server configuration at /Servers/Tomcat v7.0
  Server at localhost-config. The configuration may be corrupt or
  incomplete.

The path to tomcat7 that I've provided is /usr/share/tomcat7

答:
You tried to start Tomcat and got the following error:

```<code>Could not load the Tomcat server configuration at /Servers/Tomcat v7.0 Server at localhost-config. The configuration may be corrupt or incomplete
</code>```

How to solve:

Close Eclipse

Copy all files from TOMCAT_7_HOME/conf to WORKSPACE_FOLDER/Servers/Tomcat v7.0 Server at localhost-config

Start Eclipse

Expand the Servers project, click on the Tomcat 7 project and hit F5

Start Tomcat from Eclipse

Body:
You tried to start Tomcat and got the following error:

Could not load the Tomcat server configuration at /Servers/Tomcat v7.0 Server at localhost-config. The configuration may be corrupt or incomplete

How to solve:

Close Eclipse

Copy all files from TOMCAT_7_HOME/conf to WORKSPACE_FOLDER/Servers/Tomcat v7.0 Server at localhost-config

Start Eclipse

Expand the Servers project, click on the Tomcat 7 project and hit F5

Start Tomcat from Eclipse


问:
new category appears near home page tite, why?
I installed PrestaShop 1.7.1.2 and I added many categories, one of them appears on the top menu of the front page, only a specific one of them. I don't know why, I didn't add any products to it.

you can see it by browsing to prestashop.tux-in.com and near the CLASSIC title which is a link to the homepage, DIFFERENT HOLDERS is also shown there which is an empty category. what am I missing? why is this category alone is shown there?

how can I remove it ?

答: It seems it coming from top horizontal menu module, please check it in admin under module section  and remove it.</p>


问:
UTM Source not passing through (google analytics)
I've got an email campaign that Im trying to track with Google Analytics, but for some reason the source, campaign etc are not being tracked.

The URL I'm using is:

https://makemeacocktail.com/list/14911/wimbledon-cocktails/?utm_source=mailinglist&utm_campaign=weeklynewsletter&utm_term=wimbledon

I've obviously got some htaccess rules kicking in that change the php _GET variables, but that shouldn't really matter here (I dont think).

My GA tracking code is:

```<code>const dimensions = {
  TRACKING_VERSION: 'dimension1',
  CLIENT_ID: 'dimension2',
};

const TRACKING_VERSION = '1';

ga('create', 'UA-22275118-1', 'auto');
ga('set', 'transport', 'beacon');
ga('set', dimensions.TRACKING_VERSION, TRACKING_VERSION);
ga('send', 'pageview');

ga((tracker) => {
  var clientId = tracker.get('clientId');
  tracker.set(dimensions.CLIENT_ID, clientId);
});
</code>```

and passing the GA script through using:

```<code><script async src="https://www.google-analytics.com/analytics.js"></script>
</code>```

(This can all be seen in the source). Am I doing something fundamentally wrong?

Thanks in advance

答:
Here are a few thoughts to troubleshoot this:

Install the Google Analytics Debugger in Chrome and verify your pageview is triggering when the campaign URL is there. You'll be able to see individual dimensions and metrics too (so you can check you custom dimensions too).

It seems like you're implying that the pageviews are working, but I wanted to include this just for due diligence.

Looks like you're relying on ES6 and the beacon to send data. That should be fine, but if your users are on older browsers that may prevent the data from coming through.

UTM campaigns require a utm_campaign, utm_source, and utm_medium to be valid. This does not prevent them from sending, but I'd recommend updating your campaign URLs if possible (you're missing utm_medium).

Are you using a filtered view? If so, your own traffic won't appear in the reports.

Are you using the Real Time reports? If not, you'll need to wait a few hours before the data becomes available in the Google Analytics standard reports.

Hopefully one of those steps gets you pointed in the right direction. Best of luck!

Edit: Viewing the source of that link you provided, I don't see your Google Analytics snippet in there. Maybe you're working on it now, but try viewing the page in an incognito window and check the source (maybe your script is tied to an admin or dev user?).

Body:
I've got an email campaign that Im trying to track with Google Analytics, but for some reason the source, campaign etc are not being tracked.

The URL I'm using is:

https://makemeacocktail.com/list/14911/wimbledon-cocktails/?utm_source=mailinglist&utm_campaign=weeklynewsletter&utm_term=wimbledon

I've obviously got some htaccess rules kicking in that change the php _GET variables, but that shouldn't really matter here (I dont think).

My GA tracking code is:

const dimensions = {
  TRACKING_VERSION: 'dimension1',
  CLIENT_ID: 'dimension2',
};

const TRACKING_VERSION = '1';

ga('create', 'UA-22275118-1', 'auto');
ga('set', 'transport', 'beacon');
ga('set', dimensions.TRACKING_VERSION, TRACKING_VERSION);
ga('send', 'pageview');

ga((tracker) => {
  var clientId = tracker.get('clientId');
  tracker.set(dimensions.CLIENT_ID, clientId);
});

and passing the GA script through using:

(This can all be seen in the source). Am I doing something fundamentally wrong?

Thanks in advance


问:
URI correct but incorrect at run-time?
My file, located at 'C:/Users/Username/Desktop/sample.pdf' is there. I can open it manually and it loads fine. Now if I put an invalid link, such as, file:///sample.pdf, which clearly can't be found, the Hololens app will open the Edge browser attempting to open the pdf. So, it's clear the code is functioning.

So why then is this uri incorrect when loading in the Hololens at run-time?

```<code>    string uriToLaunch = "file:///C:/Users/Username/Desktop/sample.pdf";

    // Create a Uri object from a URI string
    var uri = new Uri(uriToLaunch);

    Task task = new Task(

        async () =>
        {
            // Launch the URI
            var success = await Windows.System.Launcher.LaunchUriAsync(uri);

            if (success)
            {
                // URI launched
            }
            else
            {
                // URI launch failed
            }
        });

    task.Start();
    task.Wait();
</code>```

Here is the exception thrown.

Exception thrown: 'System.ArgumentException' in Assembly-CSharp.dll

WinRT information:
The provided URI scheme can't be launched.
Unhandled 'Platform.InvalidArgumentException' exception caught! - 'The parameter is incorrect.'

The parameter is incorrect.
The provided URI scheme can't be launched.', Sender: 'null'. Missing try/catch blocks.

The tricky thing with these exceptions in the Hololens is sometimes they don't seem to be related to whats not working. I've tried googling the error and nothing helpful appears.

EDIT: string uriToLaunch = @"file:///Data/myFiles/sample.pdf";
returns WinRT information: The provided URI scheme can't be launched.
The parameter is incorrect.

string uriToLaunch = @"/Data/myFiles/sample.pdf";
returns UriFormatException: Invalid URI: The format of the URI could not be determined.

NOTE I thought I could open the Edge browser from the app but I'm having trouble replicating this functionality. The only thing that responds, positively, shall we say, is

@"ms-appx:///Data/myFiles/sample.pdf";

This opens up a separate dialog box that will take my to the MS store to try and buy an app that will open ms-appx files.

EDIT 2:

```<code>    FileOpenPicker openPicker = new FileOpenPicker();
    openPicker.ViewMode = PickerViewMode.Thumbnail;
    openPicker.ViewMode = PickerViewMode.Thumbnail;
    openPicker.FileTypeFilter.Add(".jpg");
    openPicker.FileTypeFilter.Add(".jpeg");
    openPicker.FileTypeFilter.Add(".png");

    Task task = new Task(
    async () =>
    {
        StorageFile file = await openPicker.PickSingleFileAsync();
        if (file != null)
        {
            // Application now has read/write access to the picked file
            Debug.Log("Picked photo: " + file.Name);
        }
        else
        {
            Debug.Log("Cancelled");
        }
    });

    task.Start();
    task.Wait();
</code>```

I've tried implementing this simple FileOpenPicker, just to test and see if I could get one working, to no success.

It throws this:

Exception thrown: 'System.Exception' in mscorlib.ni.dll

Unhandled 'Platform.COMException' exception caught! - 'Invalid window handle.

EDIT 3: This is all I can find on the error.

COMException
If the ErrorCode property of the exception has the value 0x80070578 (ERROR_INVALID_WINDOW_HANDLE), this indicates that the method was not called on the UI thread.

EDIT 4: Now it's crashing and returning:

Exception thrown: 'System.Exception' in mscorlib.ni.dll

The program '[4084] hololensapplication.exe' has exited with code -1073741189 (0xc000027b).

答: As @AVK points out, UWP apps are sandboxed. This means files outside of the Hololens local environment aren't reachable. There are local known folders on the HoloLens, but the only way to get around this is to use third party apps such as OneDrive, Azure, etc.</p>

Title: URI correct but incorrect at run-time?

Body:
My file, located at 'C:/Users/Username/Desktop/sample.pdf' is there. I can open it manually and it loads fine. Now if I put an invalid link, such as, file:///sample.pdf, which clearly can't be found, the Hololens app will open the Edge browser attempting to open the pdf. So, it's clear the code is functioning.

So why then is this uri incorrect when loading in the Hololens at run-time?

    string uriToLaunch = "file:///C:/Users/Username/Desktop/sample.pdf";

    // Create a Uri object from a URI string
    var uri = new Uri(uriToLaunch);

    Task task = new Task(

        async () =>
        {
            // Launch the URI
            var success = await Windows.System.Launcher.LaunchUriAsync(uri);

            if (success)
            {
                // URI launched
            }
            else
            {
                // URI launch failed
            }
        });

    task.Start();
    task.Wait();

Here is the exception thrown.

Exception thrown: 'System.ArgumentException' in Assembly-CSharp.dll

WinRT information:
The provided URI scheme can't be launched.
Unhandled 'Platform.InvalidArgumentException' exception caught! - 'The parameter is incorrect.'

The parameter is incorrect.
The provided URI scheme can't be launched.', Sender: 'null'. Missing try/catch blocks.

The tricky thing with these exceptions in the Hololens is sometimes they don't seem to be related to whats not working. I've tried googling the error and nothing helpful appears.

EDIT: string uriToLaunch = @"file:///Data/myFiles/sample.pdf";
returns WinRT information: The provided URI scheme can't be launched.
The parameter is incorrect.

string uriToLaunch = @"/Data/myFiles/sample.pdf";
returns UriFormatException: Invalid URI: The format of the URI could not be determined.

NOTE I thought I could open the Edge browser from the app but I'm having trouble replicating this functionality. The only thing that responds, positively, shall we say, is

@"ms-appx:///Data/myFiles/sample.pdf";

This opens up a separate dialog box that will take my to the MS store to try and buy an app that will open ms-appx files.

EDIT 2:

    FileOpenPicker openPicker = new FileOpenPicker();
    openPicker.ViewMode = PickerViewMode.Thumbnail;
    openPicker.ViewMode = PickerViewMode.Thumbnail;
    openPicker.FileTypeFilter.Add(".jpg");
    openPicker.FileTypeFilter.Add(".jpeg");
    openPicker.FileTypeFilter.Add(".png");

    Task task = new Task(
    async () =>
    {
        StorageFile file = await openPicker.PickSingleFileAsync();
        if (file != null)
        {
            // Application now has read/write access to the picked file
            Debug.Log("Picked photo: " + file.Name);
        }
        else
        {
            Debug.Log("Cancelled");
        }
    });

    task.Start();
    task.Wait();

I've tried implementing this simple FileOpenPicker, just to test and see if I could get one working, to no success.

It throws this:

Exception thrown: 'System.Exception' in mscorlib.ni.dll

Unhandled 'Platform.COMException' exception caught! - 'Invalid window handle.

EDIT 3: This is all I can find on the error.

COMException
If the ErrorCode property of the exception has the value 0x80070578 (ERROR_INVALID_WINDOW_HANDLE), this indicates that the method was not called on the UI thread.

EDIT 4: Now it's crashing and returning:

Exception thrown: 'System.Exception' in mscorlib.ni.dll

The program '[4084] hololensapplication.exe' has exited with code -1073741189 (0xc000027b).

ContentLicense: CC BY-SA 4.0


答:
Is your program continuously pulling changing data from the Excel sheet? If not, I would advise creating the program in another language and running in a continuous loop containing your code and the sleep() function. If so, then I would recommend using the worksheet change event, and you cannot edit the worksheet while a macro is running(even if you use the sleep/wait command in VBA)

This link might also prove helpful: How to get VBA Macro to run continuously in the background?

Title: Excel 2010 VBA - Continually Looking In Folder for File to Process?

Body:
I have a need to build a macro in Excel 2010 that basically runs continually (started by button or stopped by button) that looks into a file folder.  If a file is created there and named a certain way then the macro opens it and processes the data inside.  The file is then closed and deleted.  The macro then continues on to watch the file folder for more files to process

Is this a reasonable / doable macro that I could create in Excel with VBA?  Can VBA continually run without issues?

Best Regards
Andy


问:
LINQ Left Join And Right Join
I need a help,

I have two dataTable called A and B , i need all rows from A and matching row of B

Ex:

```<code>A:                                           B:

User | age| Data                            ID  | age|Growth
1    |2   |43.5                             1   |2   |46.5
2    |3   |44.5                             1   |5   |49.5
3    |4   |45.6                             1   |6   |48.5
</code>```

I need  Out Put:

```<code>User | age| Data |Growth
------------------------
1    |2   |43.5  |46.5
2    |3   |44.5  |
3    |4   |45.6  |
</code>```

答:
The example data and output you've provided does not demonstrate a left join.  If it was a left join your output would look like this (notice how we have 3 results for user 1, i.e. once for each Growth record that user 1 has):

```<code>User | age| Data |Growth
------------------------
1    |2   |43.5  |46.5
1    |2   |43.5  |49.5
1    |2   |43.5  |48.5
2    |3   |44.5  |
3    |4   |45.6  |
</code>```

Assuming that you still require a left join; here's how you do a left join in Linq:

```<code>var results = from data in userData
              join growth in userGrowth
              on data.User equals growth.User into joined
              from j in joined.DefaultIfEmpty()
              select new
              {
                  UserData = data,
                  UserGrowth = j
              };
</code>```

If you want to do a right join, just swap the tables that you're selecting from over, like so:

```<code>var results = from growth in userGrowth
              join data in userData
              on growth.User equals data.User into joined
              from j in joined.DefaultIfEmpty()
              select new
              {
                  UserData = j,
                  UserGrowth = growth
              };
</code>```

The important part of the code is the into statement, followed by the DefaultIfEmpty.  This tells Linq that we want to have the default value (i.e. null) if there isn't a matching result in the other table.

Title: LINQ Left Join And Right Join

Body:
I need a help,

I have two dataTable called A and B , i need all rows from A and matching row of B

Ex:

A:                                           B:

User | age| Data                            ID  | age|Growth
1    |2   |43.5                             1   |2   |46.5
2    |3   |44.5                             1   |5   |49.5
3    |4   |45.6                             1   |6   |48.5

I need  Out Put:

User | age| Data |Growth
------------------------
1    |2   |43.5  |46.5
2    |3   |44.5  |
3    |4   |45.6  |

Body:
The example data and output you've provided does not demonstrate a left join.  If it was a left join your output would look like this (notice how we have 3 results for user 1, i.e. once for each Growth record that user 1 has):

User | age| Data |Growth
------------------------
1    |2   |43.5  |46.5
1    |2   |43.5  |49.5
1    |2   |43.5  |48.5
2    |3   |44.5  |
3    |4   |45.6  |

Assuming that you still require a left join; here's how you do a left join in Linq:

var results = from data in userData
              join growth in userGrowth
              on data.User equals growth.User into joined
              from j in joined.DefaultIfEmpty()
              select new
              {
                  UserData = data,
                  UserGrowth = j
              };

If you want to do a right join, just swap the tables that you're selecting from over, like so:

var results = from growth in userGrowth
              join data in userData
              on growth.User equals data.User into joined
              from j in joined.DefaultIfEmpty()
              select new
              {
                  UserData = j,
                  UserGrowth = growth
              };

The important part of the code is the into statement, followed by the DefaultIfEmpty.  This tells Linq that we want to have the default value (i.e. null) if there isn't a matching result in the other table.


问:
Need to select all the Null value records and email them back to the sender but batch upload the rest of the correctly filled resords
If i have a table that on occasion has columns account, dim1,dim2,description,aparid with Null values, but the other records with correctly filled data.

How do I go about extracting these fields with Null values but upload the rest of the data into a batch input system.

答:
SQL query below returns two results:
First - with rows where are no Null values;
Second - rows having at least one Null value;

```<code>-- Table variable to store KeyIds
DECLARE @KeyTbl table(KeyID bigint)

-- Collecting KeyId's of rows where is no Null values
INSERT INTO @KeyTbl
SELECT batch_id FROM Test
    WHERE account IS NOT NULL
        AND dim_1 is not NULL
        AND dim_2 is not NULL
        AND description IS NOT NULL
        AND apar_id IS NOT NULL;

-- All rows where are no Null values
SELECT Test.* FROM @KeyTbl Keys
INNER JOIN  Test
    ON Test.batch_id = Keys.KeyID;

-- Rows having Null values
SELECT Test.* FROM @KeyTbl Keys
RIGHT JOIN  Test
    ON Test.batch_id = Keys.KeyID
WHERE Keys.KeyID IS NULL;
</code>```

SqlFiddle

Body:
SQL query below returns two results:
First - with rows where are no Null values;
Second - rows having at least one Null value;

-- Table variable to store KeyIds
DECLARE @KeyTbl table(KeyID bigint)

-- Collecting KeyId's of rows where is no Null values
INSERT INTO @KeyTbl
SELECT batch_id FROM Test
    WHERE account IS NOT NULL
        AND dim_1 is not NULL
        AND dim_2 is not NULL
        AND description IS NOT NULL
        AND apar_id IS NOT NULL;

-- All rows where are no Null values
SELECT Test.* FROM @KeyTbl Keys
INNER JOIN  Test
    ON Test.batch_id = Keys.KeyID;

-- Rows having Null values
SELECT Test.* FROM @KeyTbl Keys
RIGHT JOIN  Test
    ON Test.batch_id = Keys.KeyID
WHERE Keys.KeyID IS NULL;

SqlFiddle


问:
angular 4 http.post not sending or working
I am quite new to the latest version of Angular. http.post does not seem to work in anywhere in my application. I have tried things like:

```<code>this.http
    .post(this.bikesUrl, data, { headers: this.headers })
    .toPromise()
    .then(res => res.json().data)
    .catch(this.handleError);
</code>```

...or...

```<code>this.http.post(this.config.apiEndpoint+'/authenticate', JSON.stringify({ username: username, password: password }))
        .map((response: Response) => {
            // login successful if there's a jwt token in the response
            let token = response.json() && response.json().token;
            if (token) {
                // set token property
                this.token = token;

                // store username and jwt token in local storage to keep user logged in between page refreshes
                localStorage.setItem('currentUser', JSON.stringify({ username: username, token: token }));

                // return true to indicate successful login
                return true;
            } else {
                // return false to indicate failed login
                return false;
            }
        }).subscribe(result => {
      if (result === true) {
        // login successful
        this.router.navigate(['/']);
      } else {
        // login failed
        this.error = 'Username or password is incorrect';
        this.loading = false;
      }
    })
</code>```

...or...

```<code> var json = {var1: 'test'};
var params = 'json='+json;
let headers = new Headers();
headers.append('Content-Type', 'application/json');
http.post("http://example.com/infoarray.php", params, headers ).subscribe (re => {
  console.log(re)
})
</code>```

When I run this in the browser it is almost like the script is not there. I see no requests in the inspector. I am using Angular CLI

答:
is your http properly instantiated? try below method please, it works for sure:

```<code>import {Injectable} from '@angular/core';
import {Http, Response} from '@angular/http';
import {Observable} from 'rxjs/Observable';

@Injectable()
export class MyService {
    constructor(private http: Http) {}

    // Post
    MyPost() {
        this.http.post(.....);
      }
  }
</code>```

If still not working, your data might be error, like this.config, username, password ... all valid?

Body:
I am quite new to the latest version of Angular. http.post does not seem to work in anywhere in my application. I have tried things like:

this.http
    .post(this.bikesUrl, data, { headers: this.headers })
    .toPromise()
    .then(res => res.json().data)
    .catch(this.handleError);

...or...

this.http.post(this.config.apiEndpoint+'/authenticate', JSON.stringify({ username: username, password: password }))
        .map((response: Response) => {
            // login successful if there's a jwt token in the response
            let token = response.json() && response.json().token;
            if (token) {
                // set token property
                this.token = token;

                // store username and jwt token in local storage to keep user logged in between page refreshes
                localStorage.setItem('currentUser', JSON.stringify({ username: username, token: token }));

                // return true to indicate successful login
                return true;
            } else {
                // return false to indicate failed login
                return false;
            }
        }).subscribe(result => {
      if (result === true) {
        // login successful
        this.router.navigate(['/']);
      } else {
        // login failed
        this.error = 'Username or password is incorrect';
        this.loading = false;
      }
    })

...or...

 var json = {var1: 'test'};
var params = 'json='+json;
let headers = new Headers();
headers.append('Content-Type', 'application/json');
http.post("http://example.com/infoarray.php", params, headers ).subscribe (re => {
  console.log(re)
})

When I run this in the browser it is almost like the script is not there. I see no requests in the inspector. I am using Angular CLI

Body:
is your http properly instantiated? try below method please, it works for sure:

import {Injectable} from '@angular/core';
import {Http, Response} from '@angular/http';
import {Observable} from 'rxjs/Observable';

@Injectable()
export class MyService {
    constructor(private http: Http) {}

    // Post
    MyPost() {
        this.http.post(.....);
      }
  }

If still not working, your data might be error, like this.config, username, password ... all valid?


问:
How can I search lucene for "John J" and get people like "John Jameson" not just people with John?
For reasons out of my control, I must do this with a global search. I've taken converting a search term "John J" into (John AND J), which works for anyone who's last name doesn't start with the same letter as their first.

How can I make the search for "John J" become "find all people who have John and then another, different J in the field"?

Thanks for your time.

答:
Since you mentioned it is a type ahead input; prefixQuery might help -

```<code>new PrefixQuery(new Term("lastName","J"));
</code>```

This will return all documents with lastName starting with "J".

To get results where firstName starts with "John" and lastName starts with "J", you can have -

```<code>BooleanQuery.Builder booleanQueryBuilder;
booleanQueryBuilder.add(new PrefixQuery(new Term("firstName","John")));
booleanQueryBuilder.add(new PrefixQuery(new Term("lastName","J")));`
</code>```

Body:
Since you mentioned it is a type ahead input; prefixQuery might help -

new PrefixQuery(new Term("lastName","J"));

This will return all documents with lastName starting with "J".

To get results where firstName starts with "John" and lastName starts with "J", you can have -

BooleanQuery.Builder booleanQueryBuilder;
booleanQueryBuilder.add(new PrefixQuery(new Term("firstName","John")));
booleanQueryBuilder.add(new PrefixQuery(new Term("lastName","J")));`


问:
How to copy the sheet name to a column on the same sheet?
I am using this code:

```<code>Function wrksht() as Variant
wrksht = Application.Caller.Parent.Name
End function
</code>```

I am continuously being thrown

run time error '424' object not found

I have a workbook with several sheets, each having a date on it.

I want to populate the first column on every sheet with its sheet name.

答:
Try this

Sub my_macro
On error resume next
Dim ws As Worksheet
For Each ws In ActiveWorkbook.Sheets
    ws.Range("A1") = ws.Name
Next
End sub
```

Body:
I am using this code:

Function wrksht() as Variant
wrksht = Application.Caller.Parent.Name
End function

I am continuously being thrown

run time error '424' object not found

I have a workbook with several sheets, each having a date on it.

I want to populate the first column on every sheet with its sheet name.


问:
How to update a column till the value changed in SQL server
I've table like the following

```<code>TData   Ucode   Fla
Data1   123 w
Data2   123 NULL
Data3   123 NULL
Data4   123 n
Data5   123 NULL
</code>```

The excepted result

```<code>TData   Ucode   Fla
Data1   123 w
Data2   123 W
Data3   123 W
Data4   123 n
Data5   123 n
</code>```

I need to update "Fla" where "Ucode" till the "Fla" changes

答:
you need to use an update statement

UPDATE table_name
SET w='w'.
WHERE w is NULL;

it may be worth looking at CASE statements as well (https://www.techonthenet.com/sql_server/functions/case.php)

Body:
I've table like the following

TData   Ucode   Fla
Data1   123 w
Data2   123 NULL
Data3   123 NULL
Data4   123 n
Data5   123 NULL

The excepted result

TData   Ucode   Fla
Data1   123 w
Data2   123 W
Data3   123 W
Data4   123 n
Data5   123 n

I need to update "Fla" where "Ucode" till the "Fla" changes


答:
The problem is the class MasterObject doesn't implement the interface MyInterface, although his children do.

The solution is to implement the interface:

```<code>MyInterface mObj;
mObj = new ObjectA();
</code>```

Title: Java inheritance - Two classes that use the same methods

Body:
I have two classes, ObjectA and ObjectB that both extend the same class MasterObject. I also have an interface which contains a method that I want both ObjectA and ObjectB to implement. This method is not found within MasterObject. I then have a class which has a field of type MasterObject and want to access the methods within ObjectA and ObjectB. Is this possible without casting? Here is some code that I have.

In addition, I am unable to alter the MasterObject class.

public interface MyInterface{
    void doSomething();
}

class ObjectA extends MasterObject implements MyInterface {

    @Override
    public void doSomething(){
        //...
    }
}

class ObjectB extends MasterObject implements MyInterface {
    @Override
    public void doSomething(){
        //...
    }
}

class Main {
    MasterObject mObj;

    public void method1() {
        mObj = new ObjectA();
        mObj.doSomething();
    }

    public void method2() {
        mObj = new ObjectB();
        mObj.doSomething(); //runs code from ObjectB class
    }
}

Right now this is obviously throwing some compiler issues. (Cannot resolve method doSomething()).

Casting like so: ((ObjectA) mObj).doSomething(); seems to work, but is there another way to do this without casting? Anything cleaner?

Body:
The problem is the class MasterObject doesn't implement the interface MyInterface, although his children do.

The solution is to implement the interface:

MyInterface mObj;
mObj = new ObjectA();


问:
Having trouble compiling 32-bit binary on 64-bit linux armv8 machine
I am trying to use a c++ ARM 32-bit library on a Jetson Tx2, which is an ARM 64-bit linux machine. When I try to compile some of the sample code provided with the library I get the following compilation error:

```<code>/usr/bin/ld: skipping incompatible /home/nvidia/libroyale/bin/libroyale.so
when searching for -lroyale
/usr/bin/ld: cannot find -lroyale
collect2: error: ld returned 1 exit status
CMakeFiles/sampleCameraInfo.dir/build.make:94: recipe for target
'sampleCameraInfo' failed
make[2]: *** [sampleCameraInfo] Error 1
CMakeFiles/Makefile2:67: recipe for target
'CMakeFiles/sampleCameraInfo.dir/all' failed
make[1]: *** [CMakeFiles/sampleCameraInfo.dir/all] Error 2
Makefile:83: recipe for target 'all' failed
make: *** [all] Error 2
</code>```

I assume that this error is because the 32-bit library is somehow incompatible with a 64-bit machine.

I have been browsing other StackOverflow forums on similar issues, and in accordance with those forum recommendations added the -m32 flag to CXXFLAGS and LDFLAGS when I compile. However, I then get the following error:

```<code>g++: error: unrecognized command line option ‘-m32’
CMakeFiles/sampleCameraInfo.dir/build.make:62: recipe for target
'CMakeFiles/sampleCameraInfo.dir/sampleCameraInfo.cpp.o' failed
make[2]: *** [CMakeFiles/sampleCameraInfo.dir/sampleCameraInfo.cpp.o]   Error 1
CMakeFiles/Makefile2:67: recipe for target
'CMakeFiles/sampleCameraInfo.dir/all' failed
make[1]: *** [CMakeFiles/sampleCameraInfo.dir/all] Error 2
Makefile:83: recipe for target 'all' failed
make: *** [all] Error 2
</code>```

Some other StackOverflow threads said that in order to use the -m32 flag, one has to run the command:

```<code>sudo apt-get install g++-multilib
</code>```

I don't think that the installation is working correctly, as I'm getting the following errors:

```<code>Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
g++-multilib:armhf : Depends: cpp:armhf (>= 4:5.3.1-1ubuntu1) but it is
not going to be installed
                  Depends: gcc-multilib:armhf (>= 4:5.3.1-1ubuntu1) but it is not going to be installed
                  Depends: g++:armhf (>= 4:5.3.1-1ubuntu1) but it is not going to be installed
                  Depends: g++-5-multilib:armhf (>= 5.3.1-3~) but it is not going to be installed
E: Unable to correct problems, you have held broken packages.
</code>```

Any suggestions would be very much appreciated. Thanks!

UPDATE: I realized that the -m32 flag is only supported on x86 linux machines. Does anyone know if there is some equivalent for ARM machines?

答:
I had a look at the GCC documentation, especially on the following pages:

https://gcc.gnu.org/onlinedocs/gcc-7.1.0/gcc/x86-Options.html

https://gcc.gnu.org/onlinedocs/gcc-7.1.0/gcc/AArch64-Options.html

Looks like for the GNU compilers x86 is one type of CPU; you can create 16-, 32- or 64-bit code for this CPU type.

However it also looks like for the GNU compilers 32-bit ARM CPUs and 64-bit ARM CPUs are two completely different CPU types.

Therefore compiling for 32-bit ARM with a 64-bit ARM compiler is the same as compiling for x86 with an ARM compiler: It won't work.

Of course the 32-bit library will not be accepted; an ARM compiler would not accept a x86 library, either.

Body:
I am trying to use a c++ ARM 32-bit library on a Jetson Tx2, which is an ARM 64-bit linux machine. When I try to compile some of the sample code provided with the library I get the following compilation error:

/usr/bin/ld: skipping incompatible /home/nvidia/libroyale/bin/libroyale.so
when searching for -lroyale
/usr/bin/ld: cannot find -lroyale
collect2: error: ld returned 1 exit status
CMakeFiles/sampleCameraInfo.dir/build.make:94: recipe for target
'sampleCameraInfo' failed
make[2]: *** [sampleCameraInfo] Error 1
CMakeFiles/Makefile2:67: recipe for target
'CMakeFiles/sampleCameraInfo.dir/all' failed
make[1]: *** [CMakeFiles/sampleCameraInfo.dir/all] Error 2
Makefile:83: recipe for target 'all' failed
make: *** [all] Error 2

I assume that this error is because the 32-bit library is somehow incompatible with a 64-bit machine.

I have been browsing other StackOverflow forums on similar issues, and in accordance with those forum recommendations added the -m32 flag to CXXFLAGS and LDFLAGS when I compile. However, I then get the following error:

g++: error: unrecognized command line option ‘-m32’
CMakeFiles/sampleCameraInfo.dir/build.make:62: recipe for target
'CMakeFiles/sampleCameraInfo.dir/sampleCameraInfo.cpp.o' failed
make[2]: *** [CMakeFiles/sampleCameraInfo.dir/sampleCameraInfo.cpp.o]   Error 1
CMakeFiles/Makefile2:67: recipe for target
'CMakeFiles/sampleCameraInfo.dir/all' failed
make[1]: *** [CMakeFiles/sampleCameraInfo.dir/all] Error 2
Makefile:83: recipe for target 'all' failed
make: *** [all] Error 2

Some other StackOverflow threads said that in order to use the -m32 flag, one has to run the command:

sudo apt-get install g++-multilib

I don't think that the installation is working correctly, as I'm getting the following errors:

Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
g++-multilib:armhf : Depends: cpp:armhf (>= 4:5.3.1-1ubuntu1) but it is
not going to be installed
                  Depends: gcc-multilib:armhf (>= 4:5.3.1-1ubuntu1) but it is not going to be installed
                  Depends: g++:armhf (>= 4:5.3.1-1ubuntu1) but it is not going to be installed
                  Depends: g++-5-multilib:armhf (>= 5.3.1-3~) but it is not going to be installed
E: Unable to correct problems, you have held broken packages.

Any suggestions would be very much appreciated. Thanks!

UPDATE: I realized that the -m32 flag is only supported on x86 linux machines. Does anyone know if there is some equivalent for ARM machines?


问:
Problem starting program (vcom) with multiple arguments in TCL
I'm trying to start a program (vcom) from a TCL script with extra options:

```<code>set compilationArgs "-quiet -93"
vcom $compilationArgs -work work polar2rect/sc_corproc.vhd
</code>```

But when I run this, I get following error message:

```<code># Model Technology ModelSim ALTERA vcom 6.5e Compiler 2010.02 Feb 27 2010
# ** Error: (vcom-1902) Option "-quiet -93" is either unknown, requires an argument, or was given with a bad argument.
# Use the -help option for complete vcom usage.
# /opt/altera/10.0/modelsim_ase/linuxaloem/vcom failed.
</code>```

TCL seems to pass the two extra options (-quiet) and (-93) as one option to vcom. If I use only one of these two options it works. And if I run (vcom -93 -quiet -work work polar2rect/sc_corproc.vhd) it also works.

How can I fix this?

Thanks,
Hendrik.

答:
The “problem” is that Tcl's being careful about managing spaces. This is very useful if you've got arguments with spaces in (such as many full filenames on Windows machines) but can sometimes be frustrating if you wanted the list to be broken up automatically. The fix is to indicate to Tcl that this is something that you want split into multiple words.

The best answer requires at least Tcl 8.5 (find out what version you've got with info tclversion, info patchlevel, or package require Tcl).

```<code>vcom {*}$compilationArgs -work work polar2rect/sc_corproc.vhd
</code>```

If you're built against an older version of Tcl, you'll need this instead:

```<code>eval vcom $compilationArgs -work work polar2rect/sc_corproc.vhd
</code>```

(Or this, to be officiously correct, but hardly anyone bothers for obvious reasons)

```<code>eval [list vcom] $compilationArgs [list -work work polar2rect/sc_corproc.vhd]
</code>```

The version at the top with the expansion syntax ({*}) is best if supported. You can determine if it is easily enough; if it isn't, it's a syntax error.

Body:
I'm trying to start a program (vcom) from a TCL script with extra options:

set compilationArgs "-quiet -93"
vcom $compilationArgs -work work polar2rect/sc_corproc.vhd

But when I run this, I get following error message:

# Model Technology ModelSim ALTERA vcom 6.5e Compiler 2010.02 Feb 27 2010
# ** Error: (vcom-1902) Option "-quiet -93" is either unknown, requires an argument, or was given with a bad argument.
# Use the -help option for complete vcom usage.
# /opt/altera/10.0/modelsim_ase/linuxaloem/vcom failed.

TCL seems to pass the two extra options (-quiet) and (-93) as one option to vcom. If I use only one of these two options it works. And if I run (vcom -93 -quiet -work work polar2rect/sc_corproc.vhd) it also works.

How can I fix this?

Thanks,
Hendrik.

Body:
The “problem” is that Tcl's being careful about managing spaces. This is very useful if you've got arguments with spaces in (such as many full filenames on Windows machines) but can sometimes be frustrating if you wanted the list to be broken up automatically. The fix is to indicate to Tcl that this is something that you want split into multiple words.

The best answer requires at least Tcl 8.5 (find out what version you've got with info tclversion, info patchlevel, or package require Tcl).

vcom {*}$compilationArgs -work work polar2rect/sc_corproc.vhd

If you're built against an older version of Tcl, you'll need this instead:

eval vcom $compilationArgs -work work polar2rect/sc_corproc.vhd

(Or this, to be officiously correct, but hardly anyone bothers for obvious reasons)

eval [list vcom] $compilationArgs [list -work work polar2rect/sc_corproc.vhd]

The version at the top with the expansion syntax ({*}) is best if supported. You can determine if it is easily enough; if it isn't, it's a syntax error.


问:
How to multiply a vector by an array/matrix element-wise in numpy?
I have a multidimensional array a whose shape is (32,3,5,5) and an array v with a shape of (32,). How could I multiply (i,3,5,5) with (i,) for each i using numpy other than a for-loop?

答:
With a and v as the two arrays, few approaches could be suggested -

```<code>a*v[:,None,None,None]
a*v.reshape(-1, *[1]*3)
(a.T * v).T
np.einsum('i...,i->i...', a, v)
</code>```

Body:
With a and v as the two arrays, few approaches could be suggested -

a*v[:,None,None,None]
a*v.reshape(-1, *[1]*3)
(a.T * v).T
np.einsum('i...,i->i...', a, v)


问:
How to EXEC a stored procedure from SSIS to get its output to text file
I wrote a stored procedure that reads records into a temp table and then creates a pivoted output from the data in the temp table.

Running the stored procedure from SSMS works just fine. What I am facing problems is now that I am trying to create the SSIS package that will execute the sproc, and write its output to a tab delimited text file.

I am using Visual Studio 2015. My first problem is that when I try to configure the OLE DB Source within the Data Flow Task, when adding the SQL Command inside the SQL Command Text box: EXEC ShopperSkuHistory and click OK, I get this error:

I have been looking for information about this error, but I have not found anything that helps me understand why this is happening, and how I can fix it.

I hope through this post I can learn how to fix this error.

Thank you much in advance.

Here is my sproc:

UPDATED CODE

```<code>ALTER PROCEDURE [dbo].[ShopperSkuHistory]

AS
BEGIN

        IF OBJECT_ID('tempdb..[#ShopperSku_History_Load]') IS NOT NULL
                BEGIN
                        DROP TABLE [#ShopperSku_History_Load];
                END;

        -- Create main table
        CREATE TABLE [#ShopperSku_History_Load]
        (
            [ID]                                    INT IDENTITY(1, 1) NOT NULL
        ,   [shopper_id]    CHAR(32) NOT NULL
        ,   [sku]                               VARCHAR(100) NOT NULL
        , time_added  DATETIME
        )

        SET NOCOUNT ON;

        -- Populate the table
        INSERT INTO [#ShopperSku_History_Load] ([shopper_id], [sku], [time_added])
        SELECT DISTINCT [cr].[shopper_id], LEFT([cri].[sku], 9) [sku], GETDATE() [time_added]
        FROM [dbo].[receipt_item] [cri]
        INNER JOIN [dbo].[receipt] [cr]
                ON [cri].[order_id] = [cr].[order_id]
        WHERE[cri].[list_price] > 0
                AND [cri].[IsInitialPurchase] = 1
                AND LEFT([cri].[sku], 3) = 'MN0'
                AND ([cr].[date_entered] > DATEADD(YEAR, -2, GETDATE()))
                AND EXISTS (SELECT 1 FROM [product] [cp] WHERE [cp].[pf_id] = [cri].[sku] AND [cp].[for_sale] = 1)
                AND NOT EXISTS (SELECT 1 FROM [dbo].[shopper] [cs] WHERE [cs].[IsTesting] = 1 AND [cs].[shopper_bounce] = [cr].[shopper_id])
        ORDER BY [shopper_id];

        CREATE TABLE [#HistoryOutput]
        (
        [shopper_id] VARCHAR(32)
        , skus TEXT
        )

        INSERT INTO [#HistoryOutput]
        ( [shopper_id], [skus] )

        SELECT
            [shopper_id]
        , STUFF(( SELECT ', ' + ISNULL([a].[sku], '')
                                                            FROM [#ShopperSku_History_Load] [a]
                                                            WHERE [a].[shopper_id] = [b].[shopper_id]
                                                                FOR
                                                                        XML PATH('')
                                                        ), 1, 1, '') [skus]
    FROM [#ShopperSku_History_Load] [b]
        GROUP BY [shopper_id];

    SELECT
        [shopper_id]
      , [skus]
    FROM
        [#HistoryOutput];

END;
</code>```

UPDATED ERROR

```<code>Exception from HRESULT: 0xC0202009
Error at Data Flow Task [OLE DB Source [1]]: SSIS Error Code DTS_E_OLEDBERROR.  An OLE DB error has occurred. Error code: 0x80040E14.
An OLE DB record is available.  Source: "Microsoft SQL Server Native Client 11.0"  Hresult: 0x80040E14  Description: "Statement(s) could not be prepared.".
An OLE DB record is available.  Source: "Microsoft SQL Server Native Client 11.0"  Hresult: 0x80040E14  Description: "Incorrect syntax near 'shopper_id'.".
</code>```

答:
This error

The metadata could not be determined because statement 'EXEC
  XXXXXX'  in procedure 'XXXXXX' contains dynamic SQL.
  Consider using the WITH RESULT SETS clause to explicitly describe the
  result set.

happens because the SP contains either a

Temp table

Dynamic SQL

Because of these dynamic elements, SSIS/SSDT has trouble getting the column metadata correctly. More info here.  We need to help SSIS get that column metadata. Depending on your SQL Server version, there are two solutions.

For SSIS/SQL 2008, you can try setting FMTONLY OFF

For SSIS/SQL 2012, you can wrap the stored procedure with a RESULT SET from SSIS.  Try this ...

Other options include updating the Stored Procedure itself and adding a WITH RESULTS SETS clause.  Or updating the stored procedure to return a table variable.

Body:
I wrote a stored procedure that reads records into a temp table and then creates a pivoted output from the data in the temp table.

Running the stored procedure from SSMS works just fine. What I am facing problems is now that I am trying to create the SSIS package that will execute the sproc, and write its output to a tab delimited text file.

I am using Visual Studio 2015. My first problem is that when I try to configure the OLE DB Source within the Data Flow Task, when adding the SQL Command inside the SQL Command Text box: EXEC ShopperSkuHistory and click OK, I get this error:

I have been looking for information about this error, but I have not found anything that helps me understand why this is happening, and how I can fix it.

I hope through this post I can learn how to fix this error.

Thank you much in advance.

Here is my sproc:

UPDATED CODE

ALTER PROCEDURE [dbo].[ShopperSkuHistory]

AS
BEGIN

        IF OBJECT_ID('tempdb..[#ShopperSku_History_Load]') IS NOT NULL
                BEGIN
                        DROP TABLE [#ShopperSku_History_Load];
                END;

        -- Create main table
        CREATE TABLE [#ShopperSku_History_Load]
        (
            [ID]                                    INT IDENTITY(1, 1) NOT NULL
        ,   [shopper_id]    CHAR(32) NOT NULL
        ,   [sku]                               VARCHAR(100) NOT NULL
        , time_added  DATETIME
        )

        SET NOCOUNT ON;

        -- Populate the table
        INSERT INTO [#ShopperSku_History_Load] ([shopper_id], [sku], [time_added])
        SELECT DISTINCT [cr].[shopper_id], LEFT([cri].[sku], 9) [sku], GETDATE() [time_added]
        FROM [dbo].[receipt_item] [cri]
        INNER JOIN [dbo].[receipt] [cr]
                ON [cri].[order_id] = [cr].[order_id]
        WHERE[cri].[list_price] > 0
                AND [cri].[IsInitialPurchase] = 1
                AND LEFT([cri].[sku], 3) = 'MN0'
                AND ([cr].[date_entered] > DATEADD(YEAR, -2, GETDATE()))
                AND EXISTS (SELECT 1 FROM [product] [cp] WHERE [cp].[pf_id] = [cri].[sku] AND [cp].[for_sale] = 1)
                AND NOT EXISTS (SELECT 1 FROM [dbo].[shopper] [cs] WHERE [cs].[IsTesting] = 1 AND [cs].[shopper_bounce] = [cr].[shopper_id])
        ORDER BY [shopper_id];

        CREATE TABLE [#HistoryOutput]
        (
        [shopper_id] VARCHAR(32)
        , skus TEXT
        )

        INSERT INTO [#HistoryOutput]
        ( [shopper_id], [skus] )

        SELECT
            [shopper_id]
        , STUFF(( SELECT ', ' + ISNULL([a].[sku], '')
                                                            FROM [#ShopperSku_History_Load] [a]
                                                            WHERE [a].[shopper_id] = [b].[shopper_id]
                                                                FOR
                                                                        XML PATH('')
                                                        ), 1, 1, '') [skus]
    FROM [#ShopperSku_History_Load] [b]
        GROUP BY [shopper_id];

    SELECT
        [shopper_id]
      , [skus]
    FROM
        [#HistoryOutput];

END;

UPDATED ERROR

Exception from HRESULT: 0xC0202009
Error at Data Flow Task [OLE DB Source [1]]: SSIS Error Code DTS_E_OLEDBERROR.  An OLE DB error has occurred. Error code: 0x80040E14.
An OLE DB record is available.  Source: "Microsoft SQL Server Native Client 11.0"  Hresult: 0x80040E14  Description: "Statement(s) could not be prepared.".
An OLE DB record is available.  Source: "Microsoft SQL Server Native Client 11.0"  Hresult: 0x80040E14  Description: "Incorrect syntax near 'shopper_id'.".