问:
Zebra .zpl file backwards to designer
I am still learning zpl.  I have created some simple labels using the Zebra designer and converted them to zpl files and added to printers.  Now, I have been tasked to update existing labels for some of our customers and I do not have the file available in the designer.  I have been successfully been able to do things like update a barcode type and add a field by directly updating the script.  But, the changes the users want would be much easier if I could use designer (I know that is like cheating!).  But, the timeline I have is short.  I have found some older questions out there that say this is not possible, so I thought I would check to see if it may now be possible to use the script on the zebra printer, and convert it to text that the designer will recognize.

I would like to mention that the printers I work with are physically located in other countries, with most inside restricted manufacturing production areas.  When testing, I have to coordinate with users who have access to these printers.  This means that printing one label, and then receiving a picture of this label can take several hours.  I am still waiting for results of one test we did yesterday!  Thanks to this site, I have found a site on line that will kind of mimic the label, but the actual printed copy is the best test.

Thanks for your attention.

答:
You cannot import the ZPL back into a designer, but there are two tools that are very helpful when you don't have a printer to test with:

Labelary Online ZPL Viewer

Chrome ZPL Plugin

I've used both and have been pleased with the results, but your experience may vary depending on the complexity of the label.

Title: Zebra .zpl file backwards to designer


来源: stackexchange

问:
Port forwarding to virtual machine qemu
I recently installed a Virtual Machine under Ubuntu 11.10, Right now, I assume, it is using NAT and its internal address is 192.168.122.88.

I have setup a web server in my virtual machine and I want to be able to access it when I go to 192.168.122.88 . However, right now it times out. When I log in to the virtual machine and try to access localhost it works.

So, for some reason, my iptables is blocking traffic from the host to the virtual machine (But not the other way around).

How can I allow traffic to flow from my host to my vm so I can see the webserver from the host?

I used Ubuntu Virtual Machine Manager w/KVM and libvirt.

I tried doing someting like this

```<code>iptables -t nat -A PREROUTING -d 192.168.0.10 -p tcp --dport 80 -j DNAT --to-destination 192.168.122.88:80
</code>```

with no avail. Apparently it says there is no route to host??

答:
Maybe you need to allow forwarded connections to the virtual machines. Try this:

```<code>iptables -I FORWARD -m state -d 192.168.122.0/24 --state NEW,RELATED,ESTABLISHED -j ACCEPT
</code>```

Hope this helps.

ContentLicense: CC BY-SA 3.0

Title: Port forwarding to virtual machine qemu

Body:
I recently installed a Virtual Machine under Ubuntu 11.10, Right now, I assume, it is using NAT and its internal address is 192.168.122.88.

I have setup a web server in my virtual machine and I want to be able to access it when I go to 192.168.122.88 . However, right now it times out. When I log in to the virtual machine and try to access localhost it works.

So, for some reason, my iptables is blocking traffic from the host to the virtual machine (But not the other way around).

How can I allow traffic to flow from my host to my vm so I can see the webserver from the host?

I used Ubuntu Virtual Machine Manager w/KVM and libvirt.

I tried doing someting like this

iptables -t nat -A PREROUTING -d 192.168.0.10 -p tcp --dport 80 -j DNAT --to-destination 192.168.122.88:80

with no avail. Apparently it says there is no route to host??

Body:
Maybe you need to allow forwarded connections to the virtual machines. Try this:

iptables -I FORWARD -m state -d 192.168.122.0/24 --state NEW,RELATED,ESTABLISHED -j ACCEPT

Hope this helps.


问:
Unti Test: Mock a method result
```<code>    public void Pay()
    {
        // some insert db code
        // ...

        // Call Bank api
        BankApi api = new BankApi();
        int result = api.pay();
        if(result == 1)
        {
            //...
        }
        else
        {
            //...
        }
    }
</code>```

I dont want to call api in unit test. How to mock the pay method without modify inner code (such as the line new BankApi() code)?

答:
Its possible to mock your BankApi class without changing any of your legacy code, you just need a unit testing framework that allows you to mock concrete classes.
for example a test for your method with Typemock :</p>

```<code>[TestMethod]
public void ExampleTest()
{
    //fakes the next BankApi instace
    var handler = Isolate.Fake.NextInstance<BankApi>();

    //change the pay method behavior
    Isolate.WhenCalled(() => handler.pay()).WillReturn(1);

    new ClassUnderTest().Pay();
}
</code>```

Title: Unti Test: Mock a method result

Body:
    public void Pay()
    {
        // some insert db code
        // ...

        // Call Bank api
        BankApi api = new BankApi();
        int result = api.pay();
        if(result == 1)
        {
            //...
        }
        else
        {
            //...
        }
    }

I dont want to call api in unit test. How to mock the pay method without modify inner code (such as the line new BankApi() code)?

Body:
Its possible to mock your BankApi class without changing any of your legacy code, you just need a unit testing framework that allows you to mock concrete classes.
for example a test for your method with Typemock :

[TestMethod]
public void ExampleTest()
{
    //fakes the next BankApi instace
    var handler = Isolate.Fake.NextInstance<BankApi>();

    //change the pay method behavior
    Isolate.WhenCalled(() => handler.pay()).WillReturn(1);

    new ClassUnderTest().Pay();
}


问:
Regular expression with only numbers after it
I'm fairly new to using regular expressions in general. And I'm having trouble coming up with one that will suit my purpose.

I've tried this

```<code>line1 = 'REQ-1234'
match = re.match(r'^REQ-\d', line1, re.I)
</code>```

This will work as long as the string is not something like
'REQ-1234 and then there is more stuff'

Is there a way to specify that there must not be anything after 'REQ-' except numbers? The other requirement is that 'REQ-1234' must be the only thing in the string. I think the caret symbol takes care of that though.

答:
You need to add a + quantifier after \d to match 1 or more digits, and then add $ anchor to require the end of string position after these digits:

```<code>match = re.match(r'REQ-\d+$', line1, re.I)
                         ^^
</code>```

Note that ^ is redundant since you are using re.match that anchors the match at the string start.

To match a req- that may be followed with digits, replace + (1 or more repetitions) with * quantifier (0 or more repetitions).

Note that with Python 3, you may use re.fullmatch without explicit anchors, r'REQ-\d+' or r'REQ-\d*' will do.

Body:
I'm fairly new to using regular expressions in general. And I'm having trouble coming up with one that will suit my purpose.

I've tried this

line1 = 'REQ-1234'
match = re.match(r'^REQ-\d', line1, re.I)

This will work as long as the string is not something like
'REQ-1234 and then there is more stuff'

Is there a way to specify that there must not be anything after 'REQ-' except numbers? The other requirement is that 'REQ-1234' must be the only thing in the string. I think the caret symbol takes care of that though.

Body:
You need to add a + quantifier after \d to match 1 or more digits, and then add $ anchor to require the end of string position after these digits:

match = re.match(r'REQ-\d+$', line1, re.I)
                         ^^

Note that ^ is redundant since you are using re.match that anchors the match at the string start.

To match a req- that may be followed with digits, replace + (1 or more repetitions) with * quantifier (0 or more repetitions).

Note that with Python 3, you may use re.fullmatch without explicit anchors, r'REQ-\d+' or r'REQ-\d*' will do.


问:
php Get the original key value in in_array multidimensional
I have a multidimensional array with some duplicate sub-arrays:

```<code> $data = array(
    2 => array  (
            'User'      => 'cat',
            'File_name' => 'cat.docx',
            'Document'  => 'Document1',
            'Date'      => '2017-03-02',
            'Pages'     => 1
        ),
    3 => array  (
            'User'      => 'dog',
            'File_name' => 'dog.docx',
            'Document'  => 'Document2',
            'Date'      => '2017-03-02',
            'Pages'     => 3
        ),
    4 => array  (
            'User'      => 'shark',
            'File_name' => 'shark.docx',
            'Document'  => 'Document3',
            'Date'      => '2017-03-01',
            'Pages'     => 5
        ),
    5 => array  (
            'User'      => 'dog',
            'File_name' => 'dog.docx',
            'Document'  => 'Document2',
            'Date'      => '2017-03-02',
            'Pages'     => 3
    ),
    6 => array  (
            'User'      => 'dog',
            'File_name' => 'dog.docx',
            'Document'  => 'Document2',
            'Date'      => '2017-03-02',
            'Pages'     => 3
    ),
    //...
);
</code>```

I could recognize which items are duplicated with:

```<code>$final = $dupli = array();
foreach ($data as $key => $array ) {
    if(!in_array($array, $final)){
        $final[$key] = $array;
    }
    else
    {
        $dupli[$key] = $array;
    }
}
print_r($dupli);
</code>```

But I would like to know what index was the first subarray (the key of this) found, as a message, for example:

```<code> $final = $dupli = array();
    foreach ($data as $key => $array ) {
        if(!in_array($array, $final)){
            $final[$key] = $array;
        }
        else
        {
            $dupli[$key] = $array;
            echo "Line " . $key . " duplicated row, the original row is: " . $originalkey;
        }
    }
</code>```

Output:

```<code>Line 5 duplicated row, the original row is: 3
Line 6 duplicated row, the original row is: 3
</code>```

答:
As Magnus Eriksson said you can use array_search, if you use it instead of in_array in your existing cycle you can do the operation only once per cycle: </p>

```<code> $final = $dupli = array();
 foreach ($data as $key => $array ) {
    if(($originalkey = array_search($array, $final)) === false){
        $final[$key] = $array;
    }
    else
    {
        $dupli[$key] = $array;
        echo "Line " . $key . " duplicated row, the original row is: " . $originalkey;
    }
}
</code>```

Body:
I have a multidimensional array with some duplicate sub-arrays:

 $data = array(
    2 => array  (
            'User'      => 'cat',
            'File_name' => 'cat.docx',
            'Document'  => 'Document1',
            'Date'      => '2017-03-02',
            'Pages'     => 1
        ),
    3 => array  (
            'User'      => 'dog',
            'File_name' => 'dog.docx',
            'Document'  => 'Document2',
            'Date'      => '2017-03-02',
            'Pages'     => 3
        ),
    4 => array  (
            'User'      => 'shark',
            'File_name' => 'shark.docx',
            'Document'  => 'Document3',
            'Date'      => '2017-03-01',
            'Pages'     => 5
        ),
    5 => array  (
            'User'      => 'dog',
            'File_name' => 'dog.docx',
            'Document'  => 'Document2',
            'Date'      => '2017-03-02',
            'Pages'     => 3
    ),
    6 => array  (
            'User'      => 'dog',
            'File_name' => 'dog.docx',
            'Document'  => 'Document2',
            'Date'      => '2017-03-02',
            'Pages'     => 3
    ),
    //...
);

I could recognize which items are duplicated with:

$final = $dupli = array();
foreach ($data as $key => $array ) {
    if(!in_array($array, $final)){
        $final[$key] = $array;
    }
    else
    {
        $dupli[$key] = $array;
    }
}
print_r($dupli);

But I would like to know what index was the first subarray (the key of this) found, as a message, for example:

 $final = $dupli = array();
    foreach ($data as $key => $array ) {
        if(!in_array($array, $final)){
            $final[$key] = $array;
        }
        else
        {
            $dupli[$key] = $array;
            echo "Line " . $key . " duplicated row, the original row is: " . $originalkey;
        }
    }

Output:

Line 5 duplicated row, the original row is: 3
Line 6 duplicated row, the original row is: 3

Body:
As Magnus Eriksson said you can use array_search, if you use it instead of in_array in your existing cycle you can do the operation only once per cycle:

 $final = $dupli = array();
 foreach ($data as $key => $array ) {
    if(($originalkey = array_search($array, $final)) === false){
        $final[$key] = $array;
    }
    else
    {
        $dupli[$key] = $array;
        echo "Line " . $key . " duplicated row, the original row is: " . $originalkey;
    }
}


问:
How to exit a gw basic program at any time?
I am creating a game and i want that if the user hit F10 or any other function key then they the program should end.</p>

答:
For future searchers, this answer provides additional context to inform the design of mechanisms for exiting BASIC programs.

For some simplistically designed BASIC programs, the only method to exit is Control-C or Control-Break. But some emulators (such as DOSBox) do not process Control-C in a manner that will present it to the underlying program.

On some systems, you can press Ctrl-ScrollLock as a workaround:

I have a little trick for those interested: use Ctrl-ScrollLock, it
  behaves like Ctrl-Break with many BASIC interpreters running within
  DOSBox. It works with GW-BASIC, BASICA (often bundled with compatible
  DOSes like Compaq's), QBasic, QuickBasic, and possibly other
  development "workbench" interfaces.

The reason this works is a little complicated, so only read on if
  you're interested in knowing. DOSBox does not have true Ctrl-Break
  handling like real DOS, which is a combination of hardware and
  software interrupts and internal flags. However, the DOS Ctrl-Break
  handler is only a default handler that all starts with INT 9, the
  keyboard hardware interrupt. Many of the program development apps hook
  INT 9 and intercept keys before DOS sees them, so they can do their
  own processing. After all, the DOS default behavior for Ctrl-Break is
  to terminate the app, and that is often not what is wanted. The INT 9
  handler code looks for the Control key being depressed by checking the
  shift status byte in BIOS data, and then reads scancodes from the
  keyboard data port 60h. The scancode for ScrollLock is 46h, and the
  scancode for Ctrl-Break is a 2-byte "escaped" sequence of E0h 46h,
  where E0h is the escape code. It seems the handler routines are often
  not very rigorous in their processing of the escape code, and just
  drop it, so Ctrl-ScrollLock ends up working the same as Ctrl-Break.


问:
How do I integrate a simple unsigned Google Checkout cart with Google Analytics?
How can I get a simple unsigned cart in Google Checkout to integrate with Google Analytics for ecommerce tracking?

The top Google Results for this all point to documentation for implementations that involve signed carts or server-to server API requests.

(asking to self-answer)

答:
The documentation for how to do this is extremely difficult to find, hence my motiviation for posting and self-answering.

Enabling Analytics Support for Unsigned Google Checkout Carts for Google Analytics ECommerce Tracking:

This method applies for any cart that does not use 'signed' carts or server-to-server API calls. Basically, the 'simplest' method of setting up Google Checkout. If signed carts and server-to-server API calls don't mean anything to anyone, it's probably this way.

First, you must make sure that the standard Google Analytics snippet is not included on pages with the Cart.

Second, you must append an attribute value to the cart.js  tag already on the site, as aid="UA-XXXXXX-X", where UA-XXXXX-X is the account code for the site.

Here's the example:

```<code><script id="googlecart-script" type="text/javascript"
src="http://checkout.google.com/seller/gsc/v2/cart.js?mid=MERCHANT_ID"
aid="UA-XXXXXX-X"
currency="USD">
</script>
</code>```

That's all you need to do. It's shockingly easy to do, but almost impossible to find this documentation, hence my posting here. Hopefully, the power of StackOverflow's SEO will make this easier for people to find.

ContentLicense: CC BY-SA 2.5

Body:
The documentation for how to do this is extremely difficult to find, hence my motiviation for posting and self-answering.

Enabling Analytics Support for Unsigned Google Checkout Carts for Google Analytics ECommerce Tracking:

This method applies for any cart that does not use 'signed' carts or server-to-server API calls. Basically, the 'simplest' method of setting up Google Checkout. If signed carts and server-to-server API calls don't mean anything to anyone, it's probably this way.

First, you must make sure that the standard Google Analytics snippet is not included on pages with the Cart.

Second, you must append an attribute value to the cart.js  tag already on the site, as aid="UA-XXXXXX-X", where UA-XXXXX-X is the account code for the site.

Here's the example:

<script id="googlecart-script" type="text/javascript"
src="http://checkout.google.com/seller/gsc/v2/cart.js?mid=MERCHANT_ID"
aid="UA-XXXXXX-X"
currency="USD">
</script>

That's all you need to do. It's shockingly easy to do, but almost impossible to find this documentation, hence my posting here. Hopefully, the power of StackOverflow's SEO will make this easier for people to find.


问:
Xamarin Forms, Android and HttpClient issue
I've created in Xamarin Forms for iOS a HttpClient function to send a picture from the device to my server. The core function is

```<code>var content = new MultipartFormDataContent();

var fileContent = new ByteArrayContent(fileBytes);
fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");
fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
    FileName = fName
};
fileContent.Headers.ContentDisposition.Parameters
                   .Add(new NameValueHeaderValue("userId", UserId.ToString()));
content.Add(fileContent);

using (var client = new HttpClient()) {
    client.DefaultRequestHeaders.Add("authenticationToken", SyncData.Token);

    HttpResponseMessage response = await client.PostAsync(url, content);
    if (response.IsSuccessStatusCode)
    {
        // more code
    }
}
</code>```

I'm using System.Net.Http. I tried to use the same function for a project in Android but surprisingly it doesn't work. The problem is in the header: if I inspect fileContent I can see every keys but for webapi on the server FileName is not received.

After some logs, I changed this function adding more client.DefaultRequestHeaders like

```<code>client.DefaultRequestHeaders.Add("FileName", fName);
</code>```

Now the webapi receives FileName param.

Now my question is: what did I wrong?

答:
Personally, I use the Add method on MultipartFormDataContent that accepts a filename.

```<code>var content = new MultipartFormDataContent();
var fileContent = new ByteArrayContent(fileBytes);

...

// Use the overload Add method which accepts a file name
content.Add(fileContent, "FileName", fName);

...
</code>```

I'm not sure if this will solve your problem or not, but it works for me.

Body:
I've created in Xamarin Forms for iOS a HttpClient function to send a picture from the device to my server. The core function is

var content = new MultipartFormDataContent();

var fileContent = new ByteArrayContent(fileBytes);
fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");
fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
    FileName = fName
};
fileContent.Headers.ContentDisposition.Parameters
                   .Add(new NameValueHeaderValue("userId", UserId.ToString()));
content.Add(fileContent);

using (var client = new HttpClient()) {
    client.DefaultRequestHeaders.Add("authenticationToken", SyncData.Token);

    HttpResponseMessage response = await client.PostAsync(url, content);
    if (response.IsSuccessStatusCode)
    {
        // more code
    }
}

I'm using System.Net.Http. I tried to use the same function for a project in Android but surprisingly it doesn't work. The problem is in the header: if I inspect fileContent I can see every keys but for webapi on the server FileName is not received.

After some logs, I changed this function adding more client.DefaultRequestHeaders like

client.DefaultRequestHeaders.Add("FileName", fName);

Now the webapi receives FileName param.

Now my question is: what did I wrong?

Body:
Personally, I use the Add method on MultipartFormDataContent that accepts a filename.

var content = new MultipartFormDataContent();
var fileContent = new ByteArrayContent(fileBytes);

...

// Use the overload Add method which accepts a file name
content.Add(fileContent, "FileName", fName);

...

I'm not sure if this will solve your problem or not, but it works for me.


问:
ExpandableListView shows nothing
No errors, no warnings, it compiles successfully, but my ExpandableListView is not showing anything.
Here is my ExpandableListViewAdapter class:

```<code>public class ExpandableListAdapter extends BaseExpandableListAdapter {

private Context _context;
private List<String> _listDataHeader; // header titles
// child data in format of header title, child title
private HashMap<String, List<String>> _listDataChild;

public ExpandableListAdapter(Context context, List<String> listDataHeader,
                             HashMap<String, List<String>> listChildData) {
    this._context = context;
    this._listDataHeader = listDataHeader;
    this._listDataChild = listChildData;
}

@Override
public Object getChild(int groupPosition, int childPosititon) {
    return this._listDataChild.get(this._listDataHeader.get(groupPosition))
            .get(childPosititon);
}

@Override
public long getChildId(int groupPosition, int childPosition) {
    return childPosition;
}

@Override
public View getChildView(int groupPosition, final int childPosition,
                         boolean isLastChild, View convertView, ViewGroup parent) {

    final String childText = (String) getChild(groupPosition, childPosition);

    if (convertView == null) {
        LayoutInflater infalInflater = (LayoutInflater) this._context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = infalInflater.inflate(R.layout.list_item, null);
    }

    TextView txtListChild = (TextView) convertView
            .findViewById(R.id.lblListItem);

    txtListChild.setText(childText);
    return convertView;
}

@Override
public int getChildrenCount(int groupPosition) {
    return this._listDataChild.get(this._listDataHeader.get(groupPosition))
            .size();
}

@Override
public Object getGroup(int groupPosition) {
    return this._listDataHeader.get(groupPosition);
}

@Override
public int getGroupCount() {
    return this._listDataHeader.size();
}

@Override
public long getGroupId(int groupPosition) {
    return groupPosition;
}

@Override
public View getGroupView(int groupPosition, boolean isExpanded,
                         View convertView, ViewGroup parent) {
    String headerTitle = (String) getGroup(groupPosition);
    if (convertView == null) {
        LayoutInflater infalInflater = (LayoutInflater) this._context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = infalInflater.inflate(R.layout.list_group, null);
    }

    TextView lblListHeader = (TextView) convertView.findViewById(R.id.lblListHeader);
    lblListHeader.setTypeface(null, Typeface.BOLD);
    lblListHeader.setText(headerTitle);

    return convertView;
}

@Override
public boolean hasStableIds() {
    return false;
}

@Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
    return true;
}

}
</code>```

Here is my ListViewtest class:

```<code>public class ListViewTest extends AppCompatActivity {

ExpandableListAdapter listAdapter;
ExpandableListView expListView;
List<String> listDataHeader;
HashMap<String, List<String>> listDataChild;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // get the listview
   // expListView = (ExpandableListView) findViewById(R.id.lvExp);
    View explist = getLayoutInflater().inflate(R.layout.activity_expandable_list,null,false );
    expListView = (ExpandableListView) explist.findViewById(R.id.lvExp);
    // preparing list data
    prepareListData();

    listAdapter = new ExpandableListAdapter(this, listDataHeader, listDataChild);

    // setting list adapter
    expListView.setAdapter(listAdapter);
    setContentView(R.layout.activity_expandable_list);

}

/*
 * Preparing the list data
 */
private void prepareListData() {
    listDataHeader = new ArrayList<String>();
    listDataChild = new HashMap<String, List<String>>();

    // Adding child data
    listDataHeader.add("Top 250");
    listDataHeader.add("Now Showing");
    listDataHeader.add("Coming Soon..");

    // Adding child data
    List<String> top250 = new ArrayList<String>();
    top250.add("The Shawshank Redemption");
    top250.add("The Godfather");
    top250.add("The Godfather: Part II");
    top250.add("Pulp Fiction");
    top250.add("The Good, the Bad and the Ugly");
    top250.add("The Dark Knight");
    top250.add("12 Angry Men");

    List<String> nowShowing = new ArrayList<String>();
    nowShowing.add("The Conjuring");
    nowShowing.add("Despicable Me 2");
    nowShowing.add("Turbo");
    nowShowing.add("Grown Ups 2");
    nowShowing.add("Red 2");
    nowShowing.add("The Wolverine");

    List<String> comingSoon = new ArrayList<String>();
    comingSoon.add("2 Guns");
    comingSoon.add("The Smurfs 2");
    comingSoon.add("The Spectacular Now");
    comingSoon.add("The Canyons");
    comingSoon.add("Europa Report");

    listDataChild.put(listDataHeader.get(0), top250); // Header, Child data
    listDataChild.put(listDataHeader.get(1), nowShowing);
    listDataChild.put(listDataHeader.get(2), comingSoon);
}
</code>```

I don't know what I am doing wrong. Can anyonone tell me where the problem my be ? Thank you in advance.

答:
You override all layout changes by calling this:

```<code>setContentView(R.layout.activity_expandable_list);
</code>```

This might fix the problem:

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_expandable_list);

    // get the listview
    expListView = (ExpandableListView) findViewById(R.id.lvExp);
    // preparing list data
    prepareListData();

    listAdapter = new ExpandableListAdapter(this, listDataHeader, listDataChild);

    // setting list adapter
    expListView.setAdapter(listAdapter);
}
</code>```

Title: ExpandableListView shows nothing

Body:
No errors, no warnings, it compiles successfully, but my ExpandableListView is not showing anything.
Here is my ExpandableListViewAdapter class:

public class ExpandableListAdapter extends BaseExpandableListAdapter {

private Context _context;
private List<String> _listDataHeader; // header titles
// child data in format of header title, child title
private HashMap<String, List<String>> _listDataChild;

public ExpandableListAdapter(Context context, List<String> listDataHeader,
                             HashMap<String, List<String>> listChildData) {
    this._context = context;
    this._listDataHeader = listDataHeader;
    this._listDataChild = listChildData;
}

@Override
public Object getChild(int groupPosition, int childPosititon) {
    return this._listDataChild.get(this._listDataHeader.get(groupPosition))
            .get(childPosititon);
}

@Override
public long getChildId(int groupPosition, int childPosition) {
    return childPosition;
}

@Override
public View getChildView(int groupPosition, final int childPosition,
                         boolean isLastChild, View convertView, ViewGroup parent) {

    final String childText = (String) getChild(groupPosition, childPosition);

    if (convertView == null) {
        LayoutInflater infalInflater = (LayoutInflater) this._context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = infalInflater.inflate(R.layout.list_item, null);
    }

    TextView txtListChild = (TextView) convertView
            .findViewById(R.id.lblListItem);

    txtListChild.setText(childText);
    return convertView;
}

@Override
public int getChildrenCount(int groupPosition) {
    return this._listDataChild.get(this._listDataHeader.get(groupPosition))
            .size();
}

@Override
public Object getGroup(int groupPosition) {
    return this._listDataHeader.get(groupPosition);
}

@Override
public int getGroupCount() {
    return this._listDataHeader.size();
}

@Override
public long getGroupId(int groupPosition) {
    return groupPosition;
}

@Override
public View getGroupView(int groupPosition, boolean isExpanded,
                         View convertView, ViewGroup parent) {
    String headerTitle = (String) getGroup(groupPosition);
    if (convertView == null) {
        LayoutInflater infalInflater = (LayoutInflater) this._context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = infalInflater.inflate(R.layout.list_group, null);
    }

    TextView lblListHeader = (TextView) convertView.findViewById(R.id.lblListHeader);
    lblListHeader.setTypeface(null, Typeface.BOLD);
    lblListHeader.setText(headerTitle);

    return convertView;
}

@Override
public boolean hasStableIds() {
    return false;
}

@Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
    return true;
}

}

Here is my ListViewtest class:

public class ListViewTest extends AppCompatActivity {

ExpandableListAdapter listAdapter;
ExpandableListView expListView;
List<String> listDataHeader;
HashMap<String, List<String>> listDataChild;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // get the listview
   // expListView = (ExpandableListView) findViewById(R.id.lvExp);
    View explist = getLayoutInflater().inflate(R.layout.activity_expandable_list,null,false );
    expListView = (ExpandableListView) explist.findViewById(R.id.lvExp);
    // preparing list data
    prepareListData();

    listAdapter = new ExpandableListAdapter(this, listDataHeader, listDataChild);

    // setting list adapter
    expListView.setAdapter(listAdapter);
    setContentView(R.layout.activity_expandable_list);

}

/*
 * Preparing the list data
 */
private void prepareListData() {
    listDataHeader = new ArrayList<String>();
    listDataChild = new HashMap<String, List<String>>();

    // Adding child data
    listDataHeader.add("Top 250");
    listDataHeader.add("Now Showing");
    listDataHeader.add("Coming Soon..");

    // Adding child data
    List<String> top250 = new ArrayList<String>();
    top250.add("The Shawshank Redemption");
    top250.add("The Godfather");
    top250.add("The Godfather: Part II");
    top250.add("Pulp Fiction");
    top250.add("The Good, the Bad and the Ugly");
    top250.add("The Dark Knight");
    top250.add("12 Angry Men");

    List<String> nowShowing = new ArrayList<String>();
    nowShowing.add("The Conjuring");
    nowShowing.add("Despicable Me 2");
    nowShowing.add("Turbo");
    nowShowing.add("Grown Ups 2");
    nowShowing.add("Red 2");
    nowShowing.add("The Wolverine");

    List<String> comingSoon = new ArrayList<String>();
    comingSoon.add("2 Guns");
    comingSoon.add("The Smurfs 2");
    comingSoon.add("The Spectacular Now");
    comingSoon.add("The Canyons");
    comingSoon.add("Europa Report");

    listDataChild.put(listDataHeader.get(0), top250); // Header, Child data
    listDataChild.put(listDataHeader.get(1), nowShowing);
    listDataChild.put(listDataHeader.get(2), comingSoon);
}

I don't know what I am doing wrong. Can anyonone tell me where the problem my be ? Thank you in advance.

Body:
You override all layout changes by calling this:

setContentView(R.layout.activity_expandable_list);

This might fix the problem:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_expandable_list);

    // get the listview
    expListView = (ExpandableListView) findViewById(R.id.lvExp);
    // preparing list data
    prepareListData();

    listAdapter = new ExpandableListAdapter(this, listDataHeader, listDataChild);

    // setting list adapter
    expListView.setAdapter(listAdapter);
}


问:
tomcat http server :: add # to requested URLs
I am deploying a AngularJS web application on tomcat apache 7.0.76

I am deploying the app under the ROOT directory of the webapps

now whenever the URL is requested by the user i.e. www.mydomain.com , angular changes the directory to www.mydomain.com/#/ and any virtual sub-directory requested it will still be under the root (followed by the #). for an instance, if I clicked a link in the home page to enter faq page , it will take the user to something like www.mydomain.com/#/faq

now .. if user wants to access the faq page directly , he needs to enter the link as www.mydomain.com/#/faq and angular will know which template to load

so far no problem , now the issue when the user to access the page directly by entering www.mydomain.com/faq (without the #) , then the server returns that the page does not exist , because there is no physical page / directory called faq under the root

hence , what I am looking for , is there a possible way to check if the requested URL does not contain the # under the root to automatically add the # after the root. so if the user enters www.mydomain.com/faq it should re map it to www.mydomain.com/#/faq

Thank you

答: Tomcat Rewrite Valve should allow you to redirect requests similar to apache mod_rewrite.</p>


问:
Is there a Google Insights API?
I've been looking for an API to automatically retrieve Google Insights information for part of another algorithm, but have been unable to find anything. The first result on Google delivers a site with a python plugin which is now out of date.

Does such an API exist, or has anyone written a plugin, perhaps for python?

答:
I couldn't find any documentation provided by Google, but Brad Jasper seems to have come up with some method for querying Insights for information. Note: I'm not sure if it still works... Good luck!

Use Python to Access Google Insights API

Title: Is there a Google Insights API?


问:
Imported library 'owaspapi' contains no keywords. (if it's installed using pip)
I have made a library for Robot Framework (myapi.py). If I place it in the same directory with my robot test I can import the library like this:

```<code>Library    myapi.py
</code>```

It works just fine.

However, I made the library pip installable so that others may take it into use in other projects easily. The library installs just fine with pip. I also changed the robot test to import the library like this:

```<code>Library    myapi
</code>```

When I run the robot test I get warning:

[ WARN ] Imported library 'myapi' contains no keywords.

Here's the (pip installable) library file structure:

```<code>setup.py
myapi
  \__init__.py
  \myapi.py
  \version.py
</code>```

The setup.py content is:

```<code>from setuptools import setup, find_packages

exec(open('myapi/version.py').read())

    setup(
        name='myapi',
        version=__version__,
        packages=['myapi'],
        install_requires=['requests']
    )
</code>```

The init.py content is:

```<code>from .version import __version__
</code>```

The version.py content is:

```<code>__version__ = '1.1.0'
</code>```

The myapi.py content is (included only the first function I have):

```<code>import requests
import time
from time import strftime
import urllib2

__all__ = ['create_new_MY_session']

def create_new_MY_session():
    session_name = strftime('my_session_%S_%H_%M_%d_%m_%Y')
    r = requests.get("http://localhost:8080/JSON/core/action/newSession/?zapapiformat=JSON&name=" + session_name + "/'")
    print ("Creating new session: " + session_name + ". Status code...")
    print (r.status_code)
    assert (r.status_code) == 200
</code>```

And finally the beginning of the robot test (login.robot):

```<code>*** Settings ***

Suite Setup       Open Firefox With Proxy
Suite Teardown    Close Browser

Library           mypapi
Library           OperatingSystem
Library           Selenium2Library

Resource    ws_keywords/product/webui.robot

*** Test Cases ***

MY Start New MY Session
    Create New MY Session
</code>```

I wonder if the library works just fine when located right next to the robot test, what am I missing if I make it pip installable...? Why does it complain that there are no keywords?

答:
In your myapi.py file you missing the class reference. When the file is placed inside your Robot Framework project this wasn't an issue, but when creating a pip installable module, this is required. A basic Python Library code example is this:

myapi.py

```<code>class myapi(object):

    ROBOT_LIBRARY_VERSION = 1.0

    def __init__(self):
        pass

    def keyword(self):
        pass
</code>```

Body:
I have made a library for Robot Framework (myapi.py). If I place it in the same directory with my robot test I can import the library like this:

Library    myapi.py

It works just fine.

However, I made the library pip installable so that others may take it into use in other projects easily. The library installs just fine with pip. I also changed the robot test to import the library like this:

Library    myapi

When I run the robot test I get warning:

[ WARN ] Imported library 'myapi' contains no keywords.

Here's the (pip installable) library file structure:

setup.py
myapi
  \__init__.py
  \myapi.py
  \version.py

The setup.py content is:

from setuptools import setup, find_packages

exec(open('myapi/version.py').read())

    setup(
        name='myapi',
        version=__version__,
        packages=['myapi'],
        install_requires=['requests']
    )

The init.py content is:

from .version import __version__

The version.py content is:

__version__ = '1.1.0'

The myapi.py content is (included only the first function I have):

import requests
import time
from time import strftime
import urllib2

__all__ = ['create_new_MY_session']

def create_new_MY_session():
    session_name = strftime('my_session_%S_%H_%M_%d_%m_%Y')
    r = requests.get("http://localhost:8080/JSON/core/action/newSession/?zapapiformat=JSON&name=" + session_name + "/'")
    print ("Creating new session: " + session_name + ". Status code...")
    print (r.status_code)
    assert (r.status_code) == 200

And finally the beginning of the robot test (login.robot):

*** Settings ***

Suite Setup       Open Firefox With Proxy
Suite Teardown    Close Browser

Library           mypapi
Library           OperatingSystem
Library           Selenium2Library

Resource    ws_keywords/product/webui.robot

*** Test Cases ***

MY Start New MY Session
    Create New MY Session

I wonder if the library works just fine when located right next to the robot test, what am I missing if I make it pip installable...? Why does it complain that there are no keywords?

Body:
In your myapi.py file you missing the class reference. When the file is placed inside your Robot Framework project this wasn't an issue, but when creating a pip installable module, this is required. A basic Python Library code example is this:

myapi.py

class myapi(object):

    ROBOT_LIBRARY_VERSION = 1.0

    def __init__(self):
        pass

    def keyword(self):
        pass


问:
How to turn Highchart scrollable?
I have many columns to set in my chart, but the chart has width and label rotation fixed, so I need expand columns width to keep labels looks better.

Example:

var labels = ['Column 1', 'Column 2', 'Column 3', 'Column 4', 'Column 5', 'Column 6', 'Column 7'];
Highcharts.chart('myChart', {
  chart: {
    type: 'column'
  },
  title: {
    text: ''
  },
  xAxis: {
    categories: labels,
    labels: {
      rotation: 0
    }
  },
  plotOptions: {
    column: {
      stacking: 'normal'
    }
  },
  series: [{
    data: [1,2,3,4,5,6,7]
  }, {
    data: [2,3,4,5,6,7,8]
  }, {
    data: [3,4,5,6,7,8,9]
  }]

});
console.log('jia')```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#myChart {
  width: 300px;
  height: 300px;
}</code>```

<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>

```

I tried to use HighStocks, but I couldn't change xAxis categories to custom text, I think it's just for time.

How can I set fixed width to chart column and add scroll to the chart made with HighCharts?

答:
You can set a high width on your chart container and add a parent container with a smaller width and set the overflow-x property to scroll

var labels = ['Column 1', 'Column 2', 'Column 3', 'Column 4', 'Column 5', 'Column 6', 'Column 7'];
Highcharts.chart('myChart', {
  chart: {
    type: 'column'
  },
  title: {
    text: ''
  },
  xAxis: {
    categories: labels,
    labels: {
      rotation: 0
    }
  },
  plotOptions: {
    column: {
      stacking: 'normal'
    }
  },
  series: [{
    data: [1,2,3,4,5,6,7]
  }, {
    data: [2,3,4,5,6,7,8]
  }, {
    data: [3,4,5,6,7,8,9]
  }]

});
console.log('jia')```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#myChart {
  width: 800px;
  height: 300px;
}
.chart-container{
  width:300px;
  overflow-x:scroll;
}</code>```

<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>

```

Title: How to turn Highchart scrollable?

Body:
I have many columns to set in my chart, but the chart has width and label rotation fixed, so I need expand columns width to keep labels looks better.

Example:

var labels = ['Column 1', 'Column 2', 'Column 3', 'Column 4', 'Column 5', 'Column 6', 'Column 7'];
Highcharts.chart('myChart', {
  chart: {
    type: 'column'
  },
  title: {
    text: ''
  },
  xAxis: {
    categories: labels,
    labels: {
      rotation: 0
    }
  },
  plotOptions: {
    column: {
      stacking: 'normal'
    }
  },
  series: [{
    data: [1,2,3,4,5,6,7]
  }, {
    data: [2,3,4,5,6,7,8]
  }, {
    data: [3,4,5,6,7,8,9]
  }]

});
console.log('jia')

#myChart {
  width: 300px;
  height: 300px;
}

<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>

I tried to use HighStocks, but I couldn't change xAxis categories to custom text, I think it's just for time.

How can I set fixed width to chart column and add scroll to the chart made with HighCharts?

Body:
You can set a high width on your chart container and add a parent container with a smaller width and set the overflow-x property to scroll

var labels = ['Column 1', 'Column 2', 'Column 3', 'Column 4', 'Column 5', 'Column 6', 'Column 7'];
Highcharts.chart('myChart', {
  chart: {
    type: 'column'
  },
  title: {
    text: ''
  },
  xAxis: {
    categories: labels,
    labels: {
      rotation: 0
    }
  },
  plotOptions: {
    column: {
      stacking: 'normal'
    }
  },
  series: [{
    data: [1,2,3,4,5,6,7]
  }, {
    data: [2,3,4,5,6,7,8]
  }, {
    data: [3,4,5,6,7,8,9]
  }]

});
console.log('jia')

#myChart {
  width: 800px;
  height: 300px;
}
.chart-container{
  width:300px;
  overflow-x:scroll;
}

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
<script src="https://code.highcharts.com/highcharts.src.js"></script>
  <div class="chart-container">
    <div id="myChart"></div>
  </div>
</body>
</html>


问:
Javascript get HTML of selected text nodes
I got the following HTML:

```<code><div id="editable_phrase">
   <span data-id="42">My</span>
   <span data-id="43">very</span>
   <span data-id="1">first</span>
   <span data-id="21">phrase</span>
</div>
</code>```

and I need to get the data-id attributes when I select (highlight) with a mouse these words. I use the following code:

```<code>var data = window.getSelection().getRangeAt(0).cloneContents();//this gets the data for all selected words
console.log(data);
</code>```

It works fine except that when I select last word phrase, it selects only text without html contents. Any ideas how to fix that? I can use jQuery.

If I select 2 or 3 words, I need to get their data-ids respectively to each word, as it is with getRangeAt(0).cloneContents(). The problem is only with the last word, which does not return HTML code.

Thank you.

答:
EDIT:

There has been a similar thread before, here is a working solution:

https://jsfiddle.net/hallleron/wg1pbwbf/2/

Basically you loop through the siblings in the selection to get each value and then parse the array as string to display it in my result paragraph for better visuals.

ORIGINAL:

If you want a jQuery-free version, here is a fiddle: https://jsfiddle.net/hallleron/wg1pbwbf/

The whole Javascript Part is the following:

```<code>document.getElementById('editable_phrase').addEventListener("click", getDataId);

function getDataId(){
     console.log(window.getSelection().anchorNode.parentElement.attributes[0].nodeValue);
}
</code>```

So every time the event listener detects a click, it gets the selected text/span and extracts its data-id attribute from the object.

Body:
I got the following HTML:

   My
   very
   first
   phrase

and I need to get the data-id attributes when I select (highlight) with a mouse these words. I use the following code:

var data = window.getSelection().getRangeAt(0).cloneContents();//this gets the data for all selected words
console.log(data);

It works fine except that when I select last word phrase, it selects only text without html contents. Any ideas how to fix that? I can use jQuery.

If I select 2 or 3 words, I need to get their data-ids respectively to each word, as it is with getRangeAt(0).cloneContents(). The problem is only with the last word, which does not return HTML code.

Thank you.

Body:
EDIT:

There has been a similar thread before, here is a working solution:

https://jsfiddle.net/hallleron/wg1pbwbf/2/

Basically you loop through the siblings in the selection to get each value and then parse the array as string to display it in my result paragraph for better visuals.

ORIGINAL:

If you want a jQuery-free version, here is a fiddle: https://jsfiddle.net/hallleron/wg1pbwbf/

The whole Javascript Part is the following:

document.getElementById('editable_phrase').addEventListener("click", getDataId);

function getDataId(){
     console.log(window.getSelection().anchorNode.parentElement.attributes[0].nodeValue);
}

So every time the event listener detects a click, it gets the selected text/span and extracts its data-id attribute from the object.


问:
How to get random value from specific ranges of dictionary content
If this way I can get random value from given range:

```<code> int r = ran.Next(1, 4);
 string v;
 if (dict.TryGetValue(r, out v))
 {
    ///...
 }
</code>```

how to properly get random value of <int, string> dictionary content from specific range, for example only from 4 to 6 and 1 and 2 and avoid look for 3:

```<code>Dictionary<int, string> dict = new Dictionary<int, string>()
{
    { 1, "word1" },
    { 2, "word2" },
    { 3, "word3" },
    { 4, "word4" },
    { 5, "word5" },
    { 6, "word6" }
};
</code>```

答:
Here's a solution using an extension method:

```<code>public static class RandomExtensions
{
    public static int NextWithinRange(this Random random, params Range[] ranges)
    {
        if (ranges.Length > 0)
        {
            Range range = ranges[random.Next(0, ranges.Length)];
            return random.Next(range.MinValue, range.MaxValue + 1);
        }

        return random.Next();
    }

    public class Range
    {
        public int MinValue { get; set; }
        public int MaxValue { get; set; }

        public Range(int minValue, int maxValue)
        {
            MinValue = minValue;
            MaxValue = maxValue;
        }
    }
}
</code>```

Usage:

```<code>int r = ran.NextWithinRange(new Range(1, 2), new Range(4, 6));
string v;
if (dict.TryGetValue(r, out v))
{
    ///...
}
</code>```

Here's a solution using LINQ:

```<code>var rand = new Random();

// create a new dictionary, filtering out any unwanted keys within range(s)
Dictionary<int, string> filteredDict =
    dict.Where(pair => (pair.Key >= 1 && pair.Key <= 2)
                    || (pair.Key >= 4 && pair.Key <= 6))
        .ToDictionary(pair => pair.Key, pair => pair.Value);

// get a random entry from the filtered dictionary
KeyValuePair<int, string> entry = filteredDict.ElementAt(rand.Next(0, filteredDict.Count));

// get random entry's value
string value = entry.Value;
</code>```

EDIT: thanks @Kyle for pointing out the potential ArgumentOutOfRange exception in my initial post.

Body:
If this way I can get random value from given range:

 int r = ran.Next(1, 4);
 string v;
 if (dict.TryGetValue(r, out v))
 {
    ///...
 }

how to properly get random value of <int, string> dictionary content from specific range, for example only from 4 to 6 and 1 and 2 and avoid look for 3:

Dictionary<int, string> dict = new Dictionary<int, string>()
{
    { 1, "word1" },
    { 2, "word2" },
    { 3, "word3" },
    { 4, "word4" },
    { 5, "word5" },
    { 6, "word6" }
};

Body:
Here's a solution using an extension method:

public static class RandomExtensions
{
    public static int NextWithinRange(this Random random, params Range[] ranges)
    {
        if (ranges.Length > 0)
        {
            Range range = ranges[random.Next(0, ranges.Length)];
            return random.Next(range.MinValue, range.MaxValue + 1);
        }

        return random.Next();
    }

    public class Range
    {
        public int MinValue { get; set; }
        public int MaxValue { get; set; }

        public Range(int minValue, int maxValue)
        {
            MinValue = minValue;
            MaxValue = maxValue;
        }
    }
}

Usage:

int r = ran.NextWithinRange(new Range(1, 2), new Range(4, 6));
string v;
if (dict.TryGetValue(r, out v))
{
    ///...
}

Here's a solution using LINQ:

var rand = new Random();

// create a new dictionary, filtering out any unwanted keys within range(s)
Dictionary<int, string> filteredDict =
    dict.Where(pair => (pair.Key >= 1 && pair.Key <= 2)
                    || (pair.Key >= 4 && pair.Key <= 6))
        .ToDictionary(pair => pair.Key, pair => pair.Value);

// get a random entry from the filtered dictionary
KeyValuePair<int, string> entry = filteredDict.ElementAt(rand.Next(0, filteredDict.Count));

// get random entry's value
string value = entry.Value;

EDIT: thanks @Kyle for pointing out the potential ArgumentOutOfRange exception in my initial post.


问:
CurrentProject vs CurrentDb
I'm new to VBA and very new to SQL so I don't quite understand why I am having this problem. I'm trying to import excel files into an access database. For a few reasons I have to store my excel data into an array and then upload that array into a temporary table and then append the pertinent parts of the table. To my current understanding, the best way to get my data from my array into a new temporary table would be to create that table and then populate it row by row using SQL. My problem is that when I try to create the table, I get an error. I've simplified my code, I believe this contains what you need to know.

```<code>Dim strSQL As String
strSQL = "CREATE TABLE TestTable (`Value` VARCHAR(20))"
CurrentDb.Execute strSQL
</code>```

This works fine

```<code>Dim strSQL As String
strSQL = "CREATE TABLE TestTable (`Value` DECIMAL(4,2))"
CurrentDb.Execute strSQL
</code>```

This results in run-time error 3292 "Syntax error in field definition"

```<code>Dim strSQL As String
strSQL = "CREATE TABLE TestTable (`Value` DECIMAL(4,2))"
CurrentProject.Connection.Execute strSQL
</code>```

This works fine

Is there a reason why I should ever use one over the other? Simply changing to CurrentProject seems to fix any problems I have but I just want to understand what is happening here. I have done my own research but any answer I find goes over my head (again, I am relatively new to VBA). I apologize in advance, there may be no answer that I am currently able to comprehend

答:
IIRC, CurrentDb.Execute supports a different ANSI SQL standard, I think ANSI 89, although I could be wrong. CurrentProject.Connection.Execute supports ANSI 92, which allows that statement to execute correctly. It's a different spec of the SQL language. If you've ever used or will use SQL server this becomes obvious pretty quickly.

You should notice that your SQL statement won't work either trying to run it as a plain SQL query either. To run this successfully as a query, one option is to enable ANSI 92 as it isn't enabled by default in Access. See below for the relevant option to toggle.

That being said, changing the SQL standard may be less than ideal if you are familiar with Access' SQL syntax, however it might be very helpful if you already have experience with SQL Server. Also worth noting, changing the ANSI option in Access won't change how CurrentDB.Execute runs executes SQL statements in VBA, you'll still need the current approach, or running a stored query.

Title: CurrentProject vs CurrentDb

Body:
I'm new to VBA and very new to SQL so I don't quite understand why I am having this problem. I'm trying to import excel files into an access database. For a few reasons I have to store my excel data into an array and then upload that array into a temporary table and then append the pertinent parts of the table. To my current understanding, the best way to get my data from my array into a new temporary table would be to create that table and then populate it row by row using SQL. My problem is that when I try to create the table, I get an error. I've simplified my code, I believe this contains what you need to know.

Dim strSQL As String
strSQL = "CREATE TABLE TestTable (`Value` VARCHAR(20))"
CurrentDb.Execute strSQL

This works fine

Dim strSQL As String
strSQL = "CREATE TABLE TestTable (`Value` DECIMAL(4,2))"
CurrentDb.Execute strSQL

This results in run-time error 3292 "Syntax error in field definition"

Dim strSQL As String
strSQL = "CREATE TABLE TestTable (`Value` DECIMAL(4,2))"
CurrentProject.Connection.Execute strSQL

This works fine

Is there a reason why I should ever use one over the other? Simply changing to CurrentProject seems to fix any problems I have but I just want to understand what is happening here. I have done my own research but any answer I find goes over my head (again, I am relatively new to VBA). I apologize in advance, there may be no answer that I am currently able to comprehend


问:
How to get path of the file on Server using Java Code?
I have uploaded a file on server 'www.server.com'. Now I wish to know the path of the file on the same server through java code. Is there any specific method or process present? I am new to this.</p>

```<code>public class Test {
    public static void main(String[] args) {
        test test = new test();
        String server ="www.server.com";
        int port = 21;
        String username = "abc";
        String password = "abc`enter code here`";

        FTPClient ftpclient = new FTPClient();

        try {
            ftpclient.connect(server, port);
            ftpclient.login(username, password);
            ftpclient.enterLocalPassiveMode();
            ftpclient.setFileType(FTP.BINARY_FILE_TYPE);

            File firstLocalFile = new File("D:\\ADF\\Tax Files\\TERData.zip");

            String firstRemoteFile = "TERData.zip";

            InputStream inputstream = new FileInputStream(firstLocalFile);
            System.out.println("Start Uploading the First File");

            System.out.println(" File Path ":+firstLocalFile.getAbsolutePath());

            boolean done = ftpclient.storeFile(firstRemoteFile, inputstream);

            if(done){
                System.out.println(" File successfully uploaded ");
            }
        } catch (IOException e) {
            // TODO: Add catch code
            System.out.println("Error: " + e.getMessage());
            e.printStackTrace();
        }

    }
}
</code>```

答:
```<code>    FTPClient ftpClient = new FTPClient();
            try {

                ftpClient.connect(server, port);
                ftpClient.login(user, pass);
                ftpClient.enterLocalPassiveMode();
                ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

                 FTPFile[] files1 = ftpClient.listFiles("/test");//"/test/test.txt";
String remoteFile1 =files1[0].getName();
                File downloadFile1 = new File("D:/Downloads/test.mp4");
                OutputStream outputStream1 = new BufferedOutputStream(new FileOutputStream(downloadFile1));
                boolean success = ftpClient.retrieveFile(remoteFile1, outputStream1);
                outputStream1.close();

                if (success) {
                    System.out.println("File #1 has been downloaded successfully.");
                }
</code>```

Body:
I have uploaded a file on server 'www.server.com'. Now I wish to know the path of the file on the same server through java code. Is there any specific method or process present? I am new to this.

public class Test {
    public static void main(String[] args) {
        test test = new test();
        String server ="www.server.com";
        int port = 21;
        String username = "abc";
        String password = "abc`enter code here`";

        FTPClient ftpclient = new FTPClient();

        try {
            ftpclient.connect(server, port);
            ftpclient.login(username, password);
            ftpclient.enterLocalPassiveMode();
            ftpclient.setFileType(FTP.BINARY_FILE_TYPE);

            File firstLocalFile = new File("D:\\ADF\\Tax Files\\TERData.zip");

            String firstRemoteFile = "TERData.zip";

            InputStream inputstream = new FileInputStream(firstLocalFile);
            System.out.println("Start Uploading the First File");

            System.out.println(" File Path ":+firstLocalFile.getAbsolutePath());

            boolean done = ftpclient.storeFile(firstRemoteFile, inputstream);

            if(done){
                System.out.println(" File successfully uploaded ");
            }
        } catch (IOException e) {
            // TODO: Add catch code
            System.out.println("Error: " + e.getMessage());
            e.printStackTrace();
        }

    }
}


问:
Knockout JS visible based on select value
I am trying to show or hide a paragraph based on the value of a select. I have reviewed the various posts that seem the same as my question however, I am new to knockout.js and none of them seem to give a basic simple example of what I am trying to do.

Here is the fiddle:
http://jsfiddle.net/scooke/ub8ozbvf/

答:
you can use the ko if comment.

in your case:

```<code><!-- ko if: multipleSelectedOptionValues() == "Alpha" -->
        <p>show or hide</p>
<!-- /ko -->
</code>```

Body:
you can use the ko if comment.

in your case:

<!-- ko if: multipleSelectedOptionValues() == "Alpha" -->
        <p>show or hide</p>
<!-- /ko -->


问:
Maven-ear-plugin custom finalname
I can't find a solution to my problem.
in short: in the ear/pom.xml with this configuration all work perfectly

```<code><project ...>
  <build>
     <finalName>${project.artifactId}</finalName>
     ....
  </build>
</project>
</code>```

But when i try to add a timestamp to finalname:

```<code>...
<finalName>${project.artifactId}-${maven.build.timestamp}</finalName>
...
</code>```

I get this error:

[ERROR] Failed to execute goal
  org.apache.maven.plugins:maven-ear-plugin:2.8:generate-application-xml
  (default-generate-application-xml) on project soc-ear: Unable to copy
  application.xml to final destination: The file, directory, or volume
  name syntax is incorrect

Some idea? Thanks in advance

答:
I found the solution.
To edit the final name, just move the property to the plugin

```<code>    <build>
        <plugins>
            <plugin>
                <artifactId>maven-ear-plugin</artifactId>
                <configuration>
                    <finalName>${project.artifactId}-${maven.build.timestamp}</finalName>
                    ...
                </configuration>
            </plugin>
        </plugins>
    </build>
</code>```

I do not know the difference between putting it in the generic build rather than in the plugin, but it does work.

Title: Maven-ear-plugin custom finalname

Body:
I can't find a solution to my problem.
in short: in the ear/pom.xml with this configuration all work perfectly

<project ...>
  <build>
     <finalName>${project.artifactId}</finalName>
     ....
  </build>
</project>

But when i try to add a timestamp to finalname:

...
<finalName>${project.artifactId}-${maven.build.timestamp}</finalName>
...

I get this error:

[ERROR] Failed to execute goal
  org.apache.maven.plugins:maven-ear-plugin:2.8:generate-application-xml
  (default-generate-application-xml) on project soc-ear: Unable to copy
  application.xml to final destination: The file, directory, or volume
  name syntax is incorrect

Some idea? Thanks in advance

Body:
I found the solution.
To edit the final name, just move the property to the plugin

    <build>
        <plugins>
            <plugin>
                <artifactId>maven-ear-plugin</artifactId>
                <configuration>
                    <finalName>${project.artifactId}-${maven.build.timestamp}</finalName>
                    ...
                </configuration>
            </plugin>
        </plugins>
    </build>

I do not know the difference between putting it in the generic build rather than in the plugin, but it does work.


问:
Bind window handle (HWND) to class name/ component type in unmanaged code

I would like to find out the top level component name of a window from knowing its window handle.

This is done like so in managed C++ code:

```<code>//handle is the window handle as int
System::Windows::Forms::Control^ c = Control::FromHandle((System::IntPtr)System::Convert::ToInt32(handle));
System::Type^ t= c->GetType();
Console::WriteLine(t->FullName);//This is the top level name of the component.
</code>```

However, I cannot use managed code for the solution that I have to develop.

I have tried to use GetClassName() as an equivalent, but this just gives me WindowsForms10.STATIC. [...] mumbo jumbo :)

Does anyone have any idea how this can be done in unmanaged code?

I know that C++ does not natively offer any support for WinForms, but I am hoping to get a pointer in the right way. I've seen it done in some solutions, but have been unable to get my code working :(

Thank you in advance.

答:
This is probably what the WinForms code is doing:

When a window is created, use SetWindowLongPtr (handle, GWL_USERDATA, value) to store a reference to the object owning the window.

The Control::FromHandle calls GetWindowLongPtr (handle, GWL_USERDATA) to retrieve the managed object reference which you can then do managed stuff with (GetType(), etc)

To do this in native Win32 and C++, create an interface class like:

```<code>class IControl
{
public:
  virtual const string &GetTypeName () = 0;
};
</code>```

and then derive controls from it:

```<code>class TextBoxControl : public IControl
{
  virtual const string &GetTypeName () { return "TextBox"; }
}
</code>```

and then in the control constructor:

```<code>TextBoxControl::TextBoxControl ()
{
   handle = CreateWindowEx (parameters to create a text box);
   SetWindowLongPtr (handle, GWL_USERDATA, this);
}
</code>```

and finally, given a window handle:

```<code>string GetWindowTypeName (HWND handle)
{
  IControl *control = GetWindowLongPtr (handle, GWL_USERDATA);
  return control->GetTypeName ();
}
</code>```

Body:
I would like to find out the top level component name of a window from knowing its window handle.

This is done like so in managed C++ code:

//handle is the window handle as int
System::Windows::Forms::Control^ c = Control::FromHandle((System::IntPtr)System::Convert::ToInt32(handle));
System::Type^ t= c->GetType();
Console::WriteLine(t->FullName);//This is the top level name of the component.

However, I cannot use managed code for the solution that I have to develop.

I have tried to use GetClassName() as an equivalent, but this just gives me WindowsForms10.STATIC. [...] mumbo jumbo :)

Does anyone have any idea how this can be done in unmanaged code?

I know that C++ does not natively offer any support for WinForms, but I am hoping to get a pointer in the right way. I've seen it done in some solutions, but have been unable to get my code working :(

Thank you in advance.

Body:
This is probably what the WinForms code is doing:

When a window is created, use SetWindowLongPtr (handle, GWL_USERDATA, value) to store a reference to the object owning the window.

The Control::FromHandle calls GetWindowLongPtr (handle, GWL_USERDATA) to retrieve the managed object reference which you can then do managed stuff with (GetType(), etc)

To do this in native Win32 and C++, create an interface class like:

class IControl
{
public:
  virtual const string &GetTypeName () = 0;
};

and then derive controls from it:

class TextBoxControl : public IControl
{
  virtual const string &GetTypeName () { return "TextBox"; }
}

and then in the control constructor:

TextBoxControl::TextBoxControl ()
{
   handle = CreateWindowEx (parameters to create a text box);
   SetWindowLongPtr (handle, GWL_USERDATA, this);
}

and finally, given a window handle:

string GetWindowTypeName (HWND handle)
{
  IControl *control = GetWindowLongPtr (handle, GWL_USERDATA);
  return control->GetTypeName ();
}


问:
How can I disable a table in a SQL Server database from SSMS
I inherited a SQL Server database used with a C# client application. I know enough to be dangerous but I'm not a programmer. I know the previous programmer liked to play around in the live database and as a result I have a number of what I think are orphaned tables.

The application itself isn't super high-usage and can withstand the exceptions of tables not being there for a small time frame. I'd like to start turning off or disabling these tables to see they're being used anymore through trial and error.

Is there a way to turn them off without completely removing the data so that I can re-enable them quickly if needed? Or is there a more transparent way to discover whether those tables are needed?

答:
There is no easy way.  The tables can be accessed through both stored procedures and direct SQL calls from your client application.  A comprehensive approach would mean that you'd have to have some way of making each table unavailable (renaming has been suggested in comments) and then perform a full regression test on your client application; you might have to do this with each table in the database.  The client application might access the tables conditionally, subject to external things like the logged-in user (and related privileges), the date, configuration, and so forth.

The SQL Server Profiler is a good tool to use, but it's not going to solve your problem all by itself because you still have to analyze what it captures.


问:
Qt: how to pass input values from on_pushButton_clicked() function to paintGL()
I am working on a mortgage calculator with QT.
When the user clicks the push button, the "on_pushButton_clicked()" function will get the inputs.

The Question is I am confused about how to pass the inputs from "on_pushButton_clicked()" to "paintGL()" function for drawing purpose.

My last resort is using global variables to solve this issue, but I really want to avoid something like that...so it will be more than welcome if someone can enlighten with better approaches.

My code are as followed:

mainwindow.h

```<code>#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include "ui_mainwindow.h"

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT
public:

    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();
    template <class T>
    T inputcheck(QLineEdit *input, T output);
    //friend class GLwidget;
    double loan;
    int maturity;
    double rate1;
    double rate2;
    double rate3;
    int period2;
    int period3;

private slots:
    void on_pushButton_Calculate_clicked();

    void on_pushButton_Quit_clicked();

private:
    Ui::MainWindow *ui;
};

#endif // MAINWINDOW_H
</code>```

mainwindow.cpp

```<code>#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QCoreApplication>
#include <QDesktopWidget>
#include "glwidget.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}

MainWindow::~MainWindow()
{
    delete ui;
}

template <class T>
T MainWindow::inputcheck(QLineEdit *input, T output)
{
    bool ok;
    output = input->text().toDouble(&ok);
    if(TRUE && output > 0)
    {
        return output;
    }
    else
    {
        input->setText("ERR");
        return 0;
    }
}

void MainWindow::on_pushButton_Calculate_clicked()
{

    // getting inputs()
    loan = inputcheck(ui->lineEdit_loan, loan);
    maturity = inputcheck(ui->lineEdit_maturity, maturity);
    rate1 = inputcheck(ui->lineEdit_rate1, rate1);
    rate2 = inputcheck(ui->lineEdit_rate2, rate2);
    rate3 = inputcheck(ui->lineEdit_rate3, rate3);
    period2 = inputcheck(ui->lineEdit_period2, period2);
    period3 = inputcheck(ui->lineEdit_period3, period3);
    printf("loan:%f, maturity:%d,rate1:%f,rate2:%f,rate3:%f, period2:%d, period3:%d\n", loan, maturity, rate1, rate2, rate3, period2, period3);

}

void MainWindow::on_pushButton_Quit_clicked()
{
    QCoreApplication::quit();

}
</code>```

glwidget.h

```<code>#ifndef GLWIDGET_H
#define GLWIDGET_H

#include <QObject>
#include <QGLWidget>

class calculation;
class GLwidget : public QGLWidget
{
    Q_OBJECT
public:
    explicit GLwidget(QWidget *parent = 0);
    void initializeGL();
    void paintGL();
    void resizeGL(int width, int height);

private:

};

#endif // GLWIDGET_H
</code>```

glwidget.cpp

```<code>#include "glwidget.h"
#include <gl/GL.h>

GLwidget::GLwidget(QWidget *parent):QGLWidget(parent)
{
}

void GLwidget::initializeGL()
{
}

void GLwidget::paintGL()
{
**// I need the inputs to be here!!**
}

void GLwidget::resizeGL(int width, int height)
{
}
</code>```

Thanks for your help:)

答:
The idiomatic approach is to make the widget become a display for the values, with the values being the properties for the widget. This is how all Qt controls work, e.g. a QLabel can display some text, and has a text property that you set using setText. Once setText is called with a new text, the label knows to update itself. Thus:

```<code>class DataView : public QOpenGLWidget
{
  Q_OBJECT
  Q_PROPERTY(double principal READ principal WRITE setPrincipal)
  Q_PROPERTY(int amortizationPeriod READ amortizationPeriod WRITE setAmortizationPeriod)
  ...
  double m_principal = {};
  int m_amortizationPeriod = {};
public:
  explicit GLwidget(QWidget *parent = {}) : QOpenGLWidget(parent) {}
  void initializeGL() override;
  void paintGL() override;
  void resizeGL(int w, int h) override;
  double principal() const { return m_principal; }
  void setPrincipal(double principal) {
    if (m_principal == principal) return;
    m_principal = principal;
    update();
  }
  int amortizationPeriod() const { return m_amortizationPeriod; }
  void setAmortizationPeriod(int period) {
    if (m_amortizationPeriod == period) return;
    m_amortizationPeriod = period;
    update();
  }
  ...
};
</code>```

update() schedules a repaint from the event loop. The update requests are coalesced, thus setting multiple properties in a row only paints the widget once.

Thus, assuming that you hold the dataView as an element of the Ui form:

```<code>void MainWindow::on_pushButton_Calculate_clicked()
{
    auto principal = inputcheck(ui->lineEdit_loan, loan);
    auto amortizationPeriod = inputcheck(ui->lineEdit_maturity, maturity);
    ...
    ui->dataView->setPrincipal(principal);
    ui->dataView->setAmortizationPeriod(amortizationPeriod);
    ...
}
</code>```

Perhaps you're wishing to show the dataView dynamically as a new top-level window:

```<code>void MainWindow::on_pushButton_Calculate_clicked()
{
    auto principal = inputcheck(ui->lineEdit_loan, loan);
    auto amortizationPeriod = inputcheck(ui->lineEdit_maturity, maturity);
    ...
    auto dataView = new DataView(this);
    dataView->setWindowFlags(dataWidget->windowFlags() | Qt::Window);
    dataView->setPrincipal(principal);
    dataView->setAmortizationPeriod(amortizationPeriod);
    ...
    dataView->show();
}
</code>```

If you wish to make it easier to pass data around, you can bundle all of the properties in a data type representing a loan:

```<code>struct Loan {
  double principal = {};
  int amortizationPeriod = {};
  ...
  bool operator==(const Loan & o) const {
    return
      qFuzzyCompare(principal, o.principal)
      && amortizationPeriod == o.amortizationPeriod
      && ...;
    // use qFuzzyCompare when comparing floating point values
  }
};
Q_DECLARE_METATYPE(Loan)

class DataView : public QOpenGLWidget
{
  Q_OBJECT
  Q_PROPERTY(Loan loan READ loan WRITE setLoan)
  Loan m_loan;
public:
  explicit GLwidget(QWidget *parent = {}) : QOpenGLWidget(parent) {}
  void initializeGL() override;
  void paintGL() override;
  void resizeGL(int w, int h) override;
  const Loan & loan() const { return m_loan; }
  Loan getLoan() const { return m_loan; }
  void setLoan(const Loan & loan) {
     if (m_loan == loan) return;
     m_loan = loan;
     update();
  }
};
</code>```

When convenient, one can use getLoan to get a modifiable copy of the loan. The usual loan getter has low cost since it returns a const reference to the internal data, not a copy.

Then:

```<code>void MainWindow::on_pushButton_Calculate_clicked()
{
    Loan loan;
    loan.principal = inputcheck(ui->lineEdit_loan, loan);
    loan.amortizationPeriod = inputcheck(ui->lineEdit_maturity, maturity);
    ...
    ui->dataView->setLoan(loan);
    ...
}
</code>```

If you're wishing to show the dataView dynamically as a new top-level window:

```<code>void MainWindow::on_pushButton_Calculate_clicked()
{
    Loan loan;
    loan.principal = inputcheck(ui->lineEdit_loan, loan);
    loan.amortizationPeriod = inputcheck(ui->lineEdit_maturity, maturity);
    ...
    auto dataView = new DataView(this);
    dataView->setWindowFlags(dataView->windowFlags() | Qt::Window);
    dataView->setLoan(loan);
    dataView->show();
}
</code>```

You can also decouple the data view from the MainWindow completely and pass the data out via a signal:

```<code>class MainWindow : public QMainWindow {
  ...
public:
  Q_SLOT newLoan(const Loan &);
  ...
};

void MainWindow::on_pushButton_Calculate_clicked()
{
    Loan loan;
    loan.principal = inputcheck(ui->lineEdit_loan, loan);
    loan.amortizationPeriod = inputcheck(ui->lineEdit_maturity, maturity);
    ...
    emit newLoan(loan);
}

int main(int argc, char ** argv) {
  QApplication app(argc, argv);
  MainWindow mainWindow;
  DataView dataView;
  QObject::connect(&mainWindow, &MainWindow::newLoan, [&](const Loan & loan){
    dataView.setLoan(loan);
    dataView.show();
  });
  mainWindow.show();
  return app.exec();
}
</code>```

If the data view is always visible, you'd have:

```<code>int main(int argc, char ** argv) {
  QApplication app(argc, argv);
  MainWindow mainWindow;
  DataView dataView;
  QObject::connect(&mainWindow, &MainWindow::newLoan, &dataView, &DataView::setLoan);
  mainWindow.show();
  dataView.show();
  return app.exec();
}
</code>```

Body:
I am working on a mortgage calculator with QT.
When the user clicks the push button, the "on_pushButton_clicked()" function will get the inputs.

The Question is I am confused about how to pass the inputs from "on_pushButton_clicked()" to "paintGL()" function for drawing purpose.

My last resort is using global variables to solve this issue, but I really want to avoid something like that...so it will be more than welcome if someone can enlighten with better approaches.

My code are as followed:

mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include "ui_mainwindow.h"

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT
public:

    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();
    template <class T>
    T inputcheck(QLineEdit *input, T output);
    //friend class GLwidget;
    double loan;
    int maturity;
    double rate1;
    double rate2;
    double rate3;
    int period2;
    int period3;

private slots:
    void on_pushButton_Calculate_clicked();

    void on_pushButton_Quit_clicked();

private:
    Ui::MainWindow *ui;
};

#endif // MAINWINDOW_H

mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QCoreApplication>
#include <QDesktopWidget>
#include "glwidget.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}

MainWindow::~MainWindow()
{
    delete ui;
}

template <class T>
T MainWindow::inputcheck(QLineEdit *input, T output)
{
    bool ok;
    output = input->text().toDouble(&ok);
    if(TRUE && output > 0)
    {
        return output;
    }
    else
    {
        input->setText("ERR");
        return 0;
    }
}

void MainWindow::on_pushButton_Calculate_clicked()
{

    // getting inputs()
    loan = inputcheck(ui->lineEdit_loan, loan);
    maturity = inputcheck(ui->lineEdit_maturity, maturity);
    rate1 = inputcheck(ui->lineEdit_rate1, rate1);
    rate2 = inputcheck(ui->lineEdit_rate2, rate2);
    rate3 = inputcheck(ui->lineEdit_rate3, rate3);
    period2 = inputcheck(ui->lineEdit_period2, period2);
    period3 = inputcheck(ui->lineEdit_period3, period3);
    printf("loan:%f, maturity:%d,rate1:%f,rate2:%f,rate3:%f, period2:%d, period3:%d\n", loan, maturity, rate1, rate2, rate3, period2, period3);

}

void MainWindow::on_pushButton_Quit_clicked()
{
    QCoreApplication::quit();

}

glwidget.h

#ifndef GLWIDGET_H
#define GLWIDGET_H

#include <QObject>
#include <QGLWidget>

class calculation;
class GLwidget : public QGLWidget
{
    Q_OBJECT
public:
    explicit GLwidget(QWidget *parent = 0);
    void initializeGL();
    void paintGL();
    void resizeGL(int width, int height);

private:

};

#endif // GLWIDGET_H

glwidget.cpp

#include "glwidget.h"
#include <gl/GL.h>

GLwidget::GLwidget(QWidget *parent):QGLWidget(parent)
{
}

void GLwidget::initializeGL()
{
}

void GLwidget::paintGL()
{
**// I need the inputs to be here!!**
}

void GLwidget::resizeGL(int width, int height)
{
}

Thanks for your help:)

Body:
The idiomatic approach is to make the widget become a display for the values, with the values being the properties for the widget. This is how all Qt controls work, e.g. a QLabel can display some text, and has a text property that you set using setText. Once setText is called with a new text, the label knows to update itself. Thus:

class DataView : public QOpenGLWidget
{
  Q_OBJECT
  Q_PROPERTY(double principal READ principal WRITE setPrincipal)
  Q_PROPERTY(int amortizationPeriod READ amortizationPeriod WRITE setAmortizationPeriod)
  ...
  double m_principal = {};
  int m_amortizationPeriod = {};
public:
  explicit GLwidget(QWidget *parent = {}) : QOpenGLWidget(parent) {}
  void initializeGL() override;
  void paintGL() override;
  void resizeGL(int w, int h) override;
  double principal() const { return m_principal; }
  void setPrincipal(double principal) {
    if (m_principal == principal) return;
    m_principal = principal;
    update();
  }
  int amortizationPeriod() const { return m_amortizationPeriod; }
  void setAmortizationPeriod(int period) {
    if (m_amortizationPeriod == period) return;
    m_amortizationPeriod = period;
    update();
  }
  ...
};

update() schedules a repaint from the event loop. The update requests are coalesced, thus setting multiple properties in a row only paints the widget once.

Thus, assuming that you hold the dataView as an element of the Ui form:

void MainWindow::on_pushButton_Calculate_clicked()
{
    auto principal = inputcheck(ui->lineEdit_loan, loan);
    auto amortizationPeriod = inputcheck(ui->lineEdit_maturity, maturity);
    ...
    ui->dataView->setPrincipal(principal);
    ui->dataView->setAmortizationPeriod(amortizationPeriod);
    ...
}

Perhaps you're wishing to show the dataView dynamically as a new top-level window:

void MainWindow::on_pushButton_Calculate_clicked()
{
    auto principal = inputcheck(ui->lineEdit_loan, loan);
    auto amortizationPeriod = inputcheck(ui->lineEdit_maturity, maturity);
    ...
    auto dataView = new DataView(this);
    dataView->setWindowFlags(dataWidget->windowFlags() | Qt::Window);
    dataView->setPrincipal(principal);
    dataView->setAmortizationPeriod(amortizationPeriod);
    ...
    dataView->show();
}

If you wish to make it easier to pass data around, you can bundle all of the properties in a data type representing a loan:

struct Loan {
  double principal = {};
  int amortizationPeriod = {};
  ...
  bool operator==(const Loan & o) const {
    return
      qFuzzyCompare(principal, o.principal)
      && amortizationPeriod == o.amortizationPeriod
      && ...;
    // use qFuzzyCompare when comparing floating point values
  }
};
Q_DECLARE_METATYPE(Loan)

class DataView : public QOpenGLWidget
{
  Q_OBJECT
  Q_PROPERTY(Loan loan READ loan WRITE setLoan)
  Loan m_loan;
public:
  explicit GLwidget(QWidget *parent = {}) : QOpenGLWidget(parent) {}
  void initializeGL() override;
  void paintGL() override;
  void resizeGL(int w, int h) override;
  const Loan & loan() const { return m_loan; }
  Loan getLoan() const { return m_loan; }
  void setLoan(const Loan & loan) {
     if (m_loan == loan) return;
     m_loan = loan;
     update();
  }
};

When convenient, one can use getLoan to get a modifiable copy of the loan. The usual loan getter has low cost since it returns a const reference to the internal data, not a copy.

Then:

void MainWindow::on_pushButton_Calculate_clicked()
{
    Loan loan;
    loan.principal = inputcheck(ui->lineEdit_loan, loan);
    loan.amortizationPeriod = inputcheck(ui->lineEdit_maturity, maturity);
    ...
    ui->dataView->setLoan(loan);
    ...
}

If you're wishing to show the dataView dynamically as a new top-level window:

void MainWindow::on_pushButton_Calculate_clicked()
{
    Loan loan;
    loan.principal = inputcheck(ui->lineEdit_loan, loan);
    loan.amortizationPeriod = inputcheck(ui->lineEdit_maturity, maturity);
    ...
    auto dataView = new DataView(this);
    dataView->setWindowFlags(dataView->windowFlags() | Qt::Window);
    dataView->setLoan(loan);
    dataView->show();
}

You can also decouple the data view from the MainWindow completely and pass the data out via a signal:

class MainWindow : public QMainWindow {
  ...
public:
  Q_SLOT newLoan(const Loan &);
  ...
};

void MainWindow::on_pushButton_Calculate_clicked()
{
    Loan loan;
    loan.principal = inputcheck(ui->lineEdit_loan, loan);
    loan.amortizationPeriod = inputcheck(ui->lineEdit_maturity, maturity);
    ...
    emit newLoan(loan);
}

int main(int argc, char ** argv) {
  QApplication app(argc, argv);
  MainWindow mainWindow;
  DataView dataView;
  QObject::connect(&mainWindow, &MainWindow::newLoan, [&](const Loan & loan){
    dataView.setLoan(loan);
    dataView.show();
  });
  mainWindow.show();
  return app.exec();
}

If the data view is always visible, you'd have:

int main(int argc, char ** argv) {
  QApplication app(argc, argv);
  MainWindow mainWindow;
  DataView dataView;
  QObject::connect(&mainWindow, &MainWindow::newLoan, &dataView, &DataView::setLoan);
  mainWindow.show();
  dataView.show();
  return app.exec();
}


问:
route all traffic over gre tunnel
I have an openvswitch sw1 with subnet 10.207.39.0/24 that has lxc containers attached and I have the same on another physical server and I have successfully connected these using a GRE tunnel.  However, the lxc containers have additional ports on additional openvswitches, e.g. sw4 with subnet 192.220.39.0/24 and I want to push that traffic over the single gre tunnel on sw1 because there is only one physical interface and it's not possible to have multiple gre tunnels on each openvswitch with the same physical interface IP addr endpoints.  Is it possible to push the traffic on the other openvswitches over the gre tunnel on sw1?  Or is there a better way to connect multiple subnets in lxc containers on two physical hosts? Thanks.</p>

答:
I solved this "myself" - with help from two links provided below -  (after sleeping on it and relentless google searches over several frustrating days).

I realize the solution is pretty simple and would be clear to a networking professional. I am an Oracle DBA and only know as much networking as I need to work with orabuntu-lxc software, LXC containers, and Oracle software, so please keep that in mind if the below is "obvious" - it wasn't obvious to me in my network ignorance.

I got the clue on how to solve the actual steps from this blog post:

http://www.cnblogs.com/popsuper1982/p/3800548.html

I confirmed that any subnet should be routable over a GRE tunnel from this blog post (which gave me hope to keep working towards a solution):

https://supportforums.adtran.com/thread/1408

In particular the author stated in the adtran comment that "GRE tunnels have no limitation on the types of traffic which can traverse it. It can route multiple subnets without multiple tunnels."

That post told me that the solution was likely a routing solution and that only one GRE tunnel would be needed for this use case.

Note that this feature of "no limitation" on the types of traffic is great for Oracle RAC because we need to be able to send multicast over the GRE tunnel for RAC.

This use case:

I am building an Oracle RAC infrastructure to run in LXC Linux containers.  I have a public network 10.207.39.0/24 on openvswitch sw1 and a private RAC interconnect network 192.220.39.0/24 on openvswitch sw4. I want to be able to build the RAC in LXC linux containers that span multiple physical hosts and so I created a GRE tunnel to connect the 10.207.39.1 tunnel endpoint on colossus to 10.207.39.5 tunnel endpoint on guardian.

Here is the setup details:

Host "guardian":

LAN wireless physical network interface:  wlp4s0  (IP 192.168.1.11)

sw1  10.207.39.5

sw4 192.220.39.5

Host "colossus":

LAN wireless physical network interface:  wlp4s0  (IP 192.168.1.15)

sw1  10.207.39.1

sw4 192.220.39.1

Step 1:

Create GRE tunnel between sw1 openvswitches on both physical hosts with physical wireless LAN network interface end points:

Host "guardian":  Create gre tunnel phys hosts (guardian --> colossus).

sudo ovs-vsctl add-port sw1 gre0 -- set interface gre0 type=gre options:remote_ip=192.168.1.15

Host "colossus":  Create gre tunnel phys hosts (colossus --> guardian).

sudo ovs-vsctl add-port sw1 gre0 -- set interface gre0 type=gre options:remote_ip=192.168.1.11

Step 2:

Route the 192.220.39.0/24 network over the established GRE tunnel as shown below:

Host "guardian": route 192.220.39.0/24 openvswitch sw4 over GRE tunnel:

sudo route add -net 192.220.39.0/24 gw 10.207.39.5 dev sw1

Host "colossus": route 192.220.39.0/24 openvswitch sw4 over GRE tunnel:

sudo route add -net 192.220.39.0/24 gw 10.207.39.1 dev sw1

Note:  To add additional subnets repeat step 2 for each subnet.

Note on MTU:

Also, you have to allow for GRE encapsulation in MTU if you want to ssh over these tunnels.

Therefore in the above example for the main GRE tunnel connecting the hosts, we need MTU to be set to 1420 to allow 80 for the GRE header.

MTU on the LXC container virtual interfaces on the sw1 switches need to be set to MTU=1420 in the LXC container config files.

MTU on the LXC container virtual interfaces on the sw4 switches need to be set to MTU=1420 in the LXC container config files.

Note that the MTU on the openvswitches sw1 and sw4 should automatically set to the MTU on the LXC intefaces as long as ALL LXC virtual interfaces are set to the new lower MTU values, so explicitly setting MTU on the openvswitches sw1 and sw4 themselves should not be necessary.

If run into issues still with SSH over the tunnels, but ping works cross-hosts cross-containers, then re-check all MTU settings on the virtual interfaces and openvswitches and recheck.

Title: route all traffic over gre tunnel


问:
Bootstrap checkbox size wrong with smaller body font
I have set my default font size to be based on 10px via 62.5%, and then set the body to be 1.4rem. This seems to cause issues with the custom checkbox controls and they no longer align correctly.

I'm using Bootstrap 4's SASS files combined with my own. Is there something in the variables file that I'm missing to fix this? Or maybe some overrides I need to do? I've tried messing with various padding, margins, font sizes, etc. but the way they have this working isn't obvious.

Here is what I have set for the default font sizes for the site:

```<code>html {
  font-size: 62.5%;
}
body {
  font-size: 1.4rem;
}
</code>```

And here is the HTML

```<code><div class="container-fluid">
  <div class="row align-items-end">
    <div class="col">
      <div class="form-group">
        <label for="worker">Worker</label>
        <select class="form-control" id="worker">
          <option>Jane Doe</option>
          <option>John Smith</option>
        </select>
      </div>
    </div>
    <div class="col">
      <div class="form-group">
        <label class="custom-control custom-checkbox">
          <input type="checkbox" class="custom-control-input">
          <span class="custom-control-indicator"></span>
          <span class="custom-control-description">Check this custom checkbox</span>
        </label>
      </div>
    </div>
  </div>
</div>
</code>```

JSFiddle

To sum up, basically I need the ability to change the body font size and yet still have the checkbox to still work correctly and be the same height as the input fields when they are next to each other.

答:
You can make the parent element flex and use align-items to center vertically. You would also need to use non-absolute position on the checkbox element. That will keep them centered vertically regardless the font size of the page.

html {
  font-size: 62.5%;
}

body {
  font-size: 1.4rem;
}

.custom-control {
  display: flex;
  align-items: baseline;
}
.custom-control-indicator {
  position: static;
  margin: 0 .5rem 0 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container-fluid">
  <div class="row align-items-end">
    <div class="col">
      <div class="form-group">
        <label for="worker">Worker</label>
        <select class="form-control" id="worker">
          <option>Jane Doe</option>
          <option>John Smith</option>
        </select>
      </div>
    </div>
    <div class="col">
      <div class="form-group">
        <label class="custom-control custom-checkbox">
          <input type="checkbox" class="custom-control-input">
          <span class="custom-control-indicator"></span>
          <span class="custom-control-description">Check this custom checkbox</span>
        </label>
      </div>
    </div>
  </div>
</div></code>```

You could also use top: 50%; transform: translateY(-50%); to center the checkbox vertically, then set the line-height of the text to 1 so it doesn't affect vertical alignment.

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet"/>

        Worker
        <select class="form-control" id="worker">
          <option>Jane Doe</option>
          <option>John Smith</option>
        </select>

          <input type="checkbox" class="custom-control-input">

          Check this custom checkbox

```

Body:
I have set my default font size to be based on 10px via 62.5%, and then set the body to be 1.4rem. This seems to cause issues with the custom checkbox controls and they no longer align correctly.

I'm using Bootstrap 4's SASS files combined with my own. Is there something in the variables file that I'm missing to fix this? Or maybe some overrides I need to do? I've tried messing with various padding, margins, font sizes, etc. but the way they have this working isn't obvious.

Here is what I have set for the default font sizes for the site:

html {
  font-size: 62.5%;
}
body {
  font-size: 1.4rem;
}

And here is the HTML

        Worker
        <select class="form-control" id="worker">
          <option>Jane Doe</option>
          <option>John Smith</option>
        </select>

          <input type="checkbox" class="custom-control-input">

          Check this custom checkbox

JSFiddle

To sum up, basically I need the ability to change the body font size and yet still have the checkbox to still work correctly and be the same height as the input fields when they are next to each other.

Body:
You can make the parent element flex and use align-items to center vertically. You would also need to use non-absolute position on the checkbox element. That will keep them centered vertically regardless the font size of the page.

html {
  font-size: 62.5%;
}

body {
  font-size: 1.4rem;
}

.custom-control {
  display: flex;
  align-items: baseline;
}
.custom-control-indicator {
  position: static;
  margin: 0 .5rem 0 0;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container-fluid">
  <div class="row align-items-end">
    <div class="col">
      <div class="form-group">
        <label for="worker">Worker</label>
        <select class="form-control" id="worker">
          <option>Jane Doe</option>
          <option>John Smith</option>
        </select>
      </div>
    </div>
    <div class="col">
      <div class="form-group">
        <label class="custom-control custom-checkbox">
          <input type="checkbox" class="custom-control-input">
          <span class="custom-control-indicator"></span>
          <span class="custom-control-description">Check this custom checkbox</span>
        </label>
      </div>
    </div>
  </div>
</div>

You could also use top: 50%; transform: translateY(-50%); to center the checkbox vertically, then set the line-height of the text to 1 so it doesn't affect vertical alignment.

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet"/>
<style>
html {
  font-size: 62.5%;
}

body {
  font-size: 1.4rem;
}

.custom-control-indicator {
  top: 50%;
  transform: translateY(-50%);
}
.custom-control-description {
  line-height: 1;
}
</style>
<div class="container-fluid">
  <div class="row align-items-end">
    <div class="col">
      <div class="form-group">
        <label for="worker">Worker</label>
        <select class="form-control" id="worker">
          <option>Jane Doe</option>
          <option>John Smith</option>
        </select>
      </div>
    </div>
    <div class="col">
      <div class="form-group">
        <label class="custom-control custom-checkbox">
          <input type="checkbox" class="custom-control-input">
          <span class="custom-control-indicator"></span>
          <span class="custom-control-description">Check this custom checkbox</span>
        </label>
      </div>
    </div>
  </div>
</div>


问:
How to turn a string of letters into integer?
Specifically, I'm taking a word that a user inputs, which is equivalent to a number (that the user wouldn't know).

my code:

```<code>animal = raw_input( > )  #and a user inputs cat
dog = 30
cat = 10
frog = 5
print 10 + int(animal) #with the hope that will output 20
</code>```

Not sure how to do it..

答:
I would use a dictionary here

First, initialize your dictionary with the relevant values.

Second, ask for the user input.

Last, get the value from the map with the user input as the key.

```<code>animals_map = {"dog" : 30, "cat" : 10, "frog" : 5}

animal = raw_input('>') #and a user inputs cat
animal_number = animals_map[animal]

print 10 + int(animal_number) #with the hope that will output 20
</code>```

EDIT:

As Ev. Kounis mentioned at the comment you can use the get function so that you can get a default value when the user input is not in the dictionary.

```<code>animals_map.get(animal, 0) # default for zero whether the user input is not a key at the dictionary.
</code>```

Body:
Specifically, I'm taking a word that a user inputs, which is equivalent to a number (that the user wouldn't know).

my code:

animal = raw_input( > )  #and a user inputs cat
dog = 30
cat = 10
frog = 5
print 10 + int(animal) #with the hope that will output 20

Not sure how to do it..

Body:
I would use a dictionary here

First, initialize your dictionary with the relevant values.

Second, ask for the user input.

Last, get the value from the map with the user input as the key.

animals_map = {"dog" : 30, "cat" : 10, "frog" : 5}

animal = raw_input('>') #and a user inputs cat
animal_number = animals_map[animal]

print 10 + int(animal_number) #with the hope that will output 20

EDIT:

As Ev. Kounis mentioned at the comment you can use the get function so that you can get a default value when the user input is not in the dictionary.

animals_map.get(animal, 0) # default for zero whether the user input is not a key at the dictionary.