问:
Automation support for Visual Basic 6 ListView
I need to get value/text of control via automation interface (coding with C++/C#). I tried with UI Automation API and this is some result captured by the Inspect:

UI Automation recognize these control as pane and I can't get list view text item or get/set slider value as normal.

Tried with other tool like MSAA, Automation Spy give the same result.

After researching, I found that control with class name like ListView20WndClass, Slider20WndClass, ... belong to Visual Basic 6 control.

So, Is there any API can support these type of control as well?

Remark 1:
There is a tool named Ranorex can support these control (sadly, it is €3490 commercial license), and I don't know which underlying API was used:

Remark 2
There are some other control type used in the application under test that UI Automation still can get value:

ThunderRT6FormDC: recognize as window

ThunderRT6CommandButton: recognize as button

ThunderRT6CheckBox: recognize as checkbox

etc...

sadly, they embed ListView20WndClass and Slider20WndClass but both recognize as pane

Update 1
I create a simple program to get text but still not working (compile as Unicode Character Set):

```<code>#include <iostream>
using namespace std;

#include <UIAutomation.h>
#include <atlstr.h>
#include <Commctrl.h>

CString getListViewItemText(HWND hwnd, int nItem, int nSubItem) {
    LVITEM item;
    memset(&item, 0, sizeof(LVITEM));
    item.iSubItem = nSubItem;
    CString string;
    int Length = 64; //initial reasonable string length
    int ReturnCode;

    do {
        Length *= 2; //resize the string buffer
        item.cchTextMax = Length;
        item.pszText = string.GetBufferSetLength(Length);

        ReturnCode = (int)::SendMessage(hwnd, LVM_GETITEMTEXT,
            (WPARAM)nItem, (LPARAM)&item);
        printf("len = %d \n", ReturnCode);

    } while (ReturnCode == Length - 1); //if could not get all chars, try again

    string.ReleaseBuffer();
    return string;
}

void UI_Spy() {

    // Init COM
    CoInitialize(NULL);

    // Init UIAutomation instance
    IUIAutomation *pAuto;
    CoCreateInstance(CLSID_CUIAutomation, NULL,
        CLSCTX_INPROC_SERVER, IID_IUIAutomation, reinterpret_cast<void**>(&pAuto));

    if (pAuto) {

        IUIAutomationElement *pElm;
        POINT p;

        for (int i = 0; i < 10; i++) {
            for (int j = 5; j > 0; j--) {
                Sleep(1000);
                printf("%d ", j);
            }
            GetCursorPos(&p);
            if (pAuto->ElementFromPoint(p, &pElm) == S_OK) {
                wprintf(L"\nPOSITION x = %d, y = %d\n", p.x, p.y);

                BSTR str;
                pElm->get_CurrentName(&str);
                wprintf(L"-Name = %s\n", str);
                SysFreeString(str);

                pElm->get_CurrentLocalizedControlType(&str);
                wprintf(L"-Type = %s\n", str);
                SysFreeString(str);

                CONTROLTYPEID typeId;
                pElm->get_CurrentControlType(&typeId);

                switch (typeId) {

                    // Process checkbox
                case UIA_CheckBoxControlTypeId:
                    IUIAutomationTogglePattern  *toggle;
                    pElm->GetCurrentPattern(UIA_TogglePatternId, (IUnknown**)&toggle);
                    ToggleState state;
                    toggle->get_CurrentToggleState(&state);
                    printf("-Checkbox = %s\n", state == ToggleState::ToggleState_On ? "TRUE"
                        : (state == ToggleState::ToggleState_Off ? "FALSE" : "INTER"));
                    break;

                    // Process VB6 listview
                case UIA_PaneControlTypeId:
                    pElm->get_CurrentClassName(&str);
                    if (str != nullptr && wcscmp(str, L"ListView20WndClass") == 0) {
                        HWND hwnd;
                        pElm->get_CurrentNativeWindowHandle((UIA_HWND*)&hwnd);
                        printf("-VB6 Listview: %p\n", hwnd);

                        CString txt = getListViewItemText(hwnd, 0, 0);
                        //txt = "Test";
                        printf("-[0,0] = %S\n", (const wchar_t*)txt);
                    }
                    SysFreeString(str);
                    break;

                    // Process normal listview
                case UIA_ListControlTypeId:
                    HWND hwnd;
                    pElm->get_CurrentNativeWindowHandle((UIA_HWND*)&hwnd);
                    printf("-Normal Listview: %p\n", hwnd);

                    CString txt = getListViewItemText(hwnd, 0, 0);
                    //txt = "Test";
                    printf("-[0,0] = %S\n", (const wchar_t*)txt);
                    break;
                }

                wprintf(L"\n");
                pElm->Release();
            }
            printf("\n");
        }

        // Release UIAutomation instance
        pAuto->Release();
    }

    // Release COM
    CoUninitialize();
}

int main()
{
    UI_Spy();

    cin.get();
    return 0;
}
</code>```

When it count 5..4..3..2..1 just mouse over some element on the screen to check.

But when I mouse over the list view:

VB6 list view (ListView20WndClass): it return an empty string (expected is 101 as my example)

MFC/Winform list view (SysListView32): the application under mouse stopped working (the console application still running)

答:
ListView.ListItem object has not hwnd.

You should search ListView by class name, next use SendMessage() to send the message LVM_GETITEM and using the LVITEM structure to get info about items:

LVM_GETITEM message (Windows)

https://msdn.microsoft.com/en-us/library/windows/desktop/bb774953(v=vs.85).aspx

LVITEM structure (Windows)

https://msdn.microsoft.com/en-us/library/windows/desktop/bb774760(v=vs.85).aspx

this reference page may help you:

List-View Control Reference (Windows) https://msdn.microsoft.com/en-us/library/windows/desktop/ff485973(v=vs.85).aspx

EDIT
However, your problem is not related to VB6 language programming.
So, I think that this is the wrong forum, you should ask on forum related to Your language to use for.

Body:
I need to get value/text of control via automation interface (coding with C++/C#). I tried with UI Automation API and this is some result captured by the Inspect:

UI Automation recognize these control as pane and I can't get list view text item or get/set slider value as normal.

Tried with other tool like MSAA, Automation Spy give the same result.

After researching, I found that control with class name like ListView20WndClass, Slider20WndClass, ... belong to Visual Basic 6 control.

So, Is there any API can support these type of control as well?

Remark 1:
There is a tool named Ranorex can support these control (sadly, it is €3490 commercial license), and I don't know which underlying API was used:

Remark 2
There are some other control type used in the application under test that UI Automation still can get value:

ThunderRT6FormDC: recognize as window

ThunderRT6CommandButton: recognize as button

ThunderRT6CheckBox: recognize as checkbox

etc...

sadly, they embed ListView20WndClass and Slider20WndClass but both recognize as pane

Update 1
I create a simple program to get text but still not working (compile as Unicode Character Set):

#include <iostream>
using namespace std;

#include <UIAutomation.h>
#include <atlstr.h>
#include <Commctrl.h>

CString getListViewItemText(HWND hwnd, int nItem, int nSubItem) {
    LVITEM item;
    memset(&item, 0, sizeof(LVITEM));
    item.iSubItem = nSubItem;
    CString string;
    int Length = 64; //initial reasonable string length
    int ReturnCode;

    do {
        Length *= 2; //resize the string buffer
        item.cchTextMax = Length;
        item.pszText = string.GetBufferSetLength(Length);

        ReturnCode = (int)::SendMessage(hwnd, LVM_GETITEMTEXT,
            (WPARAM)nItem, (LPARAM)&item);
        printf("len = %d \n", ReturnCode);

    } while (ReturnCode == Length - 1); //if could not get all chars, try again

    string.ReleaseBuffer();
    return string;
}

void UI_Spy() {

    // Init COM
    CoInitialize(NULL);

    // Init UIAutomation instance
    IUIAutomation *pAuto;
    CoCreateInstance(CLSID_CUIAutomation, NULL,
        CLSCTX_INPROC_SERVER, IID_IUIAutomation, reinterpret_cast<void**>(&pAuto));

    if (pAuto) {

        IUIAutomationElement *pElm;
        POINT p;

        for (int i = 0; i < 10; i++) {
            for (int j = 5; j > 0; j--) {
                Sleep(1000);
                printf("%d ", j);
            }
            GetCursorPos(&p);
            if (pAuto->ElementFromPoint(p, &pElm) == S_OK) {
                wprintf(L"\nPOSITION x = %d, y = %d\n", p.x, p.y);

                BSTR str;
                pElm->get_CurrentName(&str);
                wprintf(L"-Name = %s\n", str);
                SysFreeString(str);

                pElm->get_CurrentLocalizedControlType(&str);
                wprintf(L"-Type = %s\n", str);
                SysFreeString(str);

                CONTROLTYPEID typeId;
                pElm->get_CurrentControlType(&typeId);

                switch (typeId) {

                    // Process checkbox
                case UIA_CheckBoxControlTypeId:
                    IUIAutomationTogglePattern  *toggle;
                    pElm->GetCurrentPattern(UIA_TogglePatternId, (IUnknown**)&toggle);
                    ToggleState state;
                    toggle->get_CurrentToggleState(&state);
                    printf("-Checkbox = %s\n", state == ToggleState::ToggleState_On ? "TRUE"
                        : (state == ToggleState::ToggleState_Off ? "FALSE" : "INTER"));
                    break;

                    // Process VB6 listview
                case UIA_PaneControlTypeId:
                    pElm->get_CurrentClassName(&str);
                    if (str != nullptr && wcscmp(str, L"ListView20WndClass") == 0) {
                        HWND hwnd;
                        pElm->get_CurrentNativeWindowHandle((UIA_HWND*)&hwnd);
                        printf("-VB6 Listview: %p\n", hwnd);

                        CString txt = getListViewItemText(hwnd, 0, 0);
                        //txt = "Test";
                        printf("-[0,0] = %S\n", (const wchar_t*)txt);
                    }
                    SysFreeString(str);
                    break;

                    // Process normal listview
                case UIA_ListControlTypeId:
                    HWND hwnd;
                    pElm->get_CurrentNativeWindowHandle((UIA_HWND*)&hwnd);
                    printf("-Normal Listview: %p\n", hwnd);

                    CString txt = getListViewItemText(hwnd, 0, 0);
                    //txt = "Test";
                    printf("-[0,0] = %S\n", (const wchar_t*)txt);
                    break;
                }

                wprintf(L"\n");
                pElm->Release();
            }
            printf("\n");
        }

        // Release UIAutomation instance
        pAuto->Release();
    }

    // Release COM
    CoUninitialize();
}

int main()
{
    UI_Spy();

    cin.get();
    return 0;
}

When it count 5..4..3..2..1 just mouse over some element on the screen to check.

But when I mouse over the list view:

VB6 list view (ListView20WndClass): it return an empty string (expected is 101 as my example)

MFC/Winform list view (SysListView32): the application under mouse stopped working (the console application still running)


来源: stackexchange

问:
Merge lines in bash
I would like to write a script that restores a file, but preserving the changes that may be done after the backout file is created.

With more details: at some moment I create a backup of a file (file_orig). Do some changes to the original file as well(file_my_changes). After that, the original file can be changed again (file_additional_changes), but after the restore I want to have the backup file, plus the additional changes (file_orig + file_addtional_changes). In general backing out my changes only.

I am talking about grub.cfg file, so the expected possible changes will be adding or removing parts of a line.

Is it possible this to be done with a bash script?

I have 2 ideas:

Add some comments above the lines I am going to change, and then before the resotore if the line differ from the one from the backed out file, to read the comment, which will tell me what exactly to remove from the line;

If there is a way to display only the part of the line that differs from the file_orig and file_additional_changes, then to replace this line with the line from file_orig + the part that differs. But I am not sure if this is possible to be done at all.

Example"

line1: This is line1

line2: This is another line1

Is it possible to display only "another"?

Of course any other ideas are welcome!

Thank you!

答:
Unclear, but perhaps if you're using a bash script you could run a diff on the 2 edited file and the last one and save that output someplace that you want to keep it? That would mean you have a copy of the changes.

Or just use git like everybody else.

ContentLicense: CC BY-SA 3.0

Title: Merge lines in bash


问:
How to set multiline RSA private key environment variable for AWS Elastic Beans
I am deploying a Ruby on Rails application to AWS using Elastic Beanstalk and have to set a private key as an environment variable

E.g

-----BEGIN RSA PRIVATE KEY-----
SpvpksXQIBA65ICOgQxV2TvMIICAiMeV9prhdJSKjjsk2
tYdz8lhn/ibROQW71utuHLAyHGMBxz3kIaaIq1kjdkkk
tYdz8lhn/ibROQW71utuHLAyHGMBxz3kIaaIq1kjdkkk
tYdz8lhn/ibROQW71utuHLAyHGMBxz3kIaaIq1kjdkkk
tYdz8lhn/ibROQW71utuHLAyHGMBxz3kIaaIq1kjdkkk
-----END RSA PRIVATE KEY-----

However this doesn't seem to work when deploying the app as it always fails with a

OpenSSL::PKey::RSAError: Neither PUB key nor PRIV key: nested asn1
  error

I think it's because the RSA Key is malformed.

However unlike in Heroku, AWS EB does not accept multiline input (see below) so I have to use \n to create new lines.

I tried with few different styles but none of them seem to interpolate the \n properly and I always keep getting the same error.

I've tried with \n and the end of each line, then \\n and also tried tried double quotes \" to wrap the key but I still keep getting the same error.

How do I properly set a multiline environment variable in AWS Elastic Beanstalk ?

答:
You could set it in EB using \n and then convert the '\n' to newlines before you pass it to config.key - something like this (note the single and double quotes in the call to gsub):

```<code>single_line_key = ENV.fetch('CLOUDFRONT_KEY')
multi_line_key = single_line_key.gsub('\n', "\n")
config.key = multi_line_key
</code>```

Body:
You could set it in EB using \n and then convert the '\n' to newlines before you pass it to config.key - something like this (note the single and double quotes in the call to gsub):

single_line_key = ENV.fetch('CLOUDFRONT_KEY')
multi_line_key = single_line_key.gsub('\n', "\n")
config.key = multi_line_key


问:
text_field_with_auto_complete inside form_for
Simple question really - how do I use text_field_with_auto_complete inside a form_for block?

I've tried doing f.text_field_with_auto_complete but that gives an error, and just using text_field_with_auto_complete by itself doesn't seem to do anything.

Am I missing something here?

答:
A couple of months back I wrote a plugin that allows you to call the "text_field_with_auto_complete" method directly on fields_for or form_for. The idea was to support text fields that appear more than once in a form by generating unique ids to allow the javascript to work, but it might help solve your problem also, or at least give you some new ideas.

See: http://github.com/pat11639/repeated_auto_complete

...and this article for details for how it works: http://patshaughnessy.net/2008/10/31/modifying-the-autocomplete-plugin-to-allow-repeated-fields

OwnerDisplayName: robintw

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: pat


问:
How to set wildcard in $_SERVER['REMOTE_ADDR'] possible?
is it possible to set $_SERVER['REMOTE_ADDR'] to a wildcard, so that anyone on the network can see this?

```<code><?php

if($_SERVER['REMOTE_ADDR'] == "112.200.150.212"){

                ?>
                <a href="http://www.tinycounter.com" target="_blank" title="free hit counter"><img border="0" alt="free hit counter" src="http://mycounter.tinycounter.com/index.php?user=fortressgate"></a>

                <?php
                }?>
</code>```

but i want the network can see the counter... so it would look like this?

```<code>if($_SERVER['REMOTE_ADDR'] == "112.200.150.%")
</code>```

is this possible?

答:
Two solutions:

```<code>$chk = "112.200.150.";
if( substr($_SERVER['REMOTE_ADDR'],0,strlen($chk)) == $chk)
</code>```

OR:

```<code>if( preg_match("(^112\.200\.150\.)",$_SERVER['REMOTE_ADDR']))
</code>```

Body:
is it possible to set $_SERVER['REMOTE_ADDR'] to a wildcard, so that anyone on the network can see this?

<?php

if($_SERVER['REMOTE_ADDR'] == "112.200.150.212"){

                ?>

                <?php
                }?>

but i want the network can see the counter... so it would look like this?

if($_SERVER['REMOTE_ADDR'] == "112.200.150.%")

is this possible?

Body:
Two solutions:

$chk = "112.200.150.";
if( substr($_SERVER['REMOTE_ADDR'],0,strlen($chk)) == $chk)

OR:

if( preg_match("(^112\.200\.150\.)",$_SERVER['REMOTE_ADDR']))


问:
DocumentDB Emulator Remote Connection
Do we have any way to connect document dB emulator from remote system ?

Can we create procedure , triggers , user defined functions etcs in document db emulator ?

答:
The Emulator is meant for local dev scenarios, since it runs exposing a local port, you probably could (never tried, this is purely theoretical) work around the firewall and expose it, then connect from another system using your external IP and the exposed port.

There is also the local SSL certificate that you must solve (that probably is the biggest issue), though you could try with the TCP connection setting, might want to check this thread about which ports need to be opened.

Also, the Emulator does not have the entire feature set that the live service does:

The DocumentDB Emulator supports only a single fixed account and a well-known master key. Key regeneration is not possible in the DocumentDB Emulator.

The DocumentDB Emulator is not a scalable service and will not support a large number of collections.

The DocumentDB Emulator does not simulate different DocumentDB consistency levels.

The DocumentDB Emulator does not simulate multi-region replication.

The DocumentDB Emulator does not support the service quota overrides that are available in the Azure DocumentDB service (e.g. document size limits, increased partitioned collection storage).

As your copy of the DocumentDB Emulator might not be up to date with the most recent changes with the Azure DocumentDB service, please DocumentDB capacity planner to accurately estimate production throughput (RUs) needs of your application.

So, you are probably better off installing the emulator on the other system via the installer or Chocolatey and avoid all the problems.

Title: DocumentDB Emulator Remote Connection


问:
NHibernate count average on select
first of all, I am new to NHibernate. Here is my problem:

I have data stored in Database, and each sample in DB has attribute Date and numeric value. Now I would like to know, is there any way, that I can SELECT some data and count an average (of numeric values) in each 3 second interval ?

I am using QueryOver.

Thank you for any help.

答:
This is a simple group by. But I do not use queryover. Try converting following linq-to-nhibernate query:

```<code>var test = session.Query<Entity>()
    .GroupBy(e =>
        new
        {
            e.YourDate.Date,
            e.YourDate.Hour,
            e.YourDate.Minute,
            threeSec = e.YourDate.Second / 3
        })
    .Select(g =>
        new {
            g.Key.Date,
            g.Key.Hour,
            g.Key.Minute,
            g.Key.threeSec,
            avg = g.Average(e => e.YourNumeric)
        })
    .ToList();
</code>```

On a big dataset, it may perform poorly. The server will be unlikely to use an index on such a group by.

Title: NHibernate count average on select

Body:
This is a simple group by. But I do not use queryover. Try converting following linq-to-nhibernate query:

var test = session.Query<Entity>()
    .GroupBy(e =>
        new
        {
            e.YourDate.Date,
            e.YourDate.Hour,
            e.YourDate.Minute,
            threeSec = e.YourDate.Second / 3
        })
    .Select(g =>
        new {
            g.Key.Date,
            g.Key.Hour,
            g.Key.Minute,
            g.Key.threeSec,
            avg = g.Average(e => e.YourNumeric)
        })
    .ToList();

On a big dataset, it may perform poorly. The server will be unlikely to use an index on such a group by.


问:
How to add the total + 1 in the text span each time a notification using vue.js 2?
My vue component is like this :

```<code><template>
    ...
        <span v-if="total > 0" class="badge" id="total">{{ total }}</span>
    ...
</template>
<script>
    import { mapGetters } from 'vuex'
    export default {
        mounted() {
            this.initialMount()
        },
        computed: {
            ...mapGetters(['total'])
        },
        methods: {
            initialMount() {
                Echo.private('App.User.' + window.Laravel.authUser.id).notification((notification) => {
                     const a = $('#total').text()
                     const b= parseInt(a) + 1
                     $('#total').text(b)
                })
            },
        }
    }
</script>
</code>```

My modules is like this :

```<code>import { set } from 'vue'
import notification from '../../api/notification'
import * as types from '../mutation-types'

const state = {
    total: 0,
}

const getters = {
    total: state => state.total
}

const actions = {
    getNotificationList ({ commit,state })
    {
        notification.getList(
            data => {
                const notifications = data
                commit(types.GET_NOTIFICATION,{ notifications });
            },
            errors => {
                console.log(errors)
            }
        )
    }
}

const mutations = {
    [types.GET_NOTIFICATION] (state, { notifications }) {
        state.total = notifications.length
    }
}

export default {
    state,
    getters,
    actions,
    mutations
}
</code>```

===================================================================

I want every notification, the notification number incremented by 1

My above code works, but it still using jquery

I want change it using vue.js

How can I do it?

答:
You have to commit action into the sucess callback of Echo, but first you have to define mutation:

```<code>const mutations = {
    [types.GET_NOTIFICATION] (state, { notifications }) {
        state.total = notifications.length
    },
    inc (state) {
      state.total++
    }
}
</code>```

And then, you can commit action

```<code>methods: {
    initialMount() {
        Echo.private('App.User.' + window.Laravel.authUser.id).notification((notification) => {
          // Make sure you have imported store
          store.commit('inc')
        })
    },
}
</code>```

Body:
My vue component is like this :

<template>
    ...
         0" class="badge" id="total">{{ total }}
    ...
</template>

My modules is like this :

import { set } from 'vue'
import notification from '../../api/notification'
import * as types from '../mutation-types'

const state = {
    total: 0,
}

const getters = {
    total: state => state.total
}

const actions = {
    getNotificationList ({ commit,state })
    {
        notification.getList(
            data => {
                const notifications = data
                commit(types.GET_NOTIFICATION,{ notifications });
            },
            errors => {
                console.log(errors)
            }
        )
    }
}

const mutations = {
    [types.GET_NOTIFICATION] (state, { notifications }) {
        state.total = notifications.length
    }
}

export default {
    state,
    getters,
    actions,
    mutations
}

===================================================================

I want every notification, the notification number incremented by 1

My above code works, but it still using jquery

I want change it using vue.js

How can I do it?

Body:
You have to commit action into the sucess callback of Echo, but first you have to define mutation:

const mutations = {
    [types.GET_NOTIFICATION] (state, { notifications }) {
        state.total = notifications.length
    },
    inc (state) {
      state.total++
    }
}

And then, you can commit action

methods: {
    initialMount() {
        Echo.private('App.User.' + window.Laravel.authUser.id).notification((notification) => {
          // Make sure you have imported store
          store.commit('inc')
        })
    },
}


问:
jquery - find center part of image you are looking at on the screen
I am trying to add a graphic indicator on top of an image that I am looking at. I would basically put the DIV containing object with higher z-index on top of image I am looking at. The main image can be ANY SIZE.

So any ideas on how when I click "Add indicator", the indicator graphic would always be popped into view on top of the main image container (and not outside it) and viewable by me?

Another case is if image is very high (like 3000px height, it would require scrolling). So I might be viewing the bottom part of the image.

Any suggestions welcomed!

答:
I hope this little solution will help you out. You can see it action here:
http://jsfiddle.net/neopreneur/ZQqbQ/

In the second example, scroll the image and click the button to see the indicator re-center.

-css-

```<code>.fancy-img{
    display:inline-block;
    position: relative;
    max-height:400px;
    max-width: 300px;
    overflow: auto;
}

.indicator{
    width: 50px;
    height: 50px;
    border: 2px solid green;
    position: absolute;
}
</code>```

-html-

```<code><div class="fancy-img">
    <img id="img1" src="http://upload.wikimedia.org/wikipedia/en/7/72/Example-serious.jpg" alt="" />
</div>

<div class="fancy-img">
    <img id="img2" src="http://upload.wikimedia.org/wikipedia/commons/thumb/8/84/Example.svg/600px-Example.svg.png" alt="" />
</div>
</code>```

-js-

```<code>$(document).ready(function(){
    // add indicator functionality for each img
    $('.fancy-img').each(function(){
        // button to toggle indicator
        $(this).after('<button class="indicator-btn" data-imageid="' + $(this).find('img').attr('id') + '" type="button">Adjust Indicator</button>');
    });

    // handle button click
    $('button.indicator-btn').click(function(){
        var imgId = $(this).data('imageid');

        // insert indicator
        $('#' + imgId).before('<div class="indicator" />');

        // center indicator (also adjust for offset)
        var containerWidth = $('#' + imgId).parents('.fancy-img:first').width();
        var containerHeight = $('#' + imgId).parents('.fancy-img:first').height();
        var indicatorWidth = $('.indicator:first').width();
        var indicatorHeight = $('.indicator:first').height();
        var newIndicator = $('#' + imgId).parents('.fancy-img:first').find('.indicator');

        $(newIndicator).css({
            left: containerWidth/2 - indicatorWidth /2 + $('#' + imgId).parents('.fancy-img:first').scrollLeft(),
            top: containerHeight/2 - indicatorHeight/2 + $('#' + imgId).parents('.fancy-img:first').scrollTop()
        });
    });
});
</code>```

Let me know if this has helped. Cheers!

Body:
I hope this little solution will help you out. You can see it action here:
http://jsfiddle.net/neopreneur/ZQqbQ/

In the second example, scroll the image and click the button to see the indicator re-center.

-css-

.fancy-img{
    display:inline-block;
    position: relative;
    max-height:400px;
    max-width: 300px;
    overflow: auto;
}

.indicator{
    width: 50px;
    height: 50px;
    border: 2px solid green;
    position: absolute;
}

-html-

<div class="fancy-img">
    <img id="img1" src="http://upload.wikimedia.org/wikipedia/en/7/72/Example-serious.jpg" alt="" />
</div>

<div class="fancy-img">
    <img id="img2" src="http://upload.wikimedia.org/wikipedia/commons/thumb/8/84/Example.svg/600px-Example.svg.png" alt="" />
</div>

-js-

$(document).ready(function(){
    // add indicator functionality for each img
    $('.fancy-img').each(function(){
        // button to toggle indicator
        $(this).after('<button class="indicator-btn" data-imageid="' + $(this).find('img').attr('id') + '" type="button">Adjust Indicator</button>');
    });

    // handle button click
    $('button.indicator-btn').click(function(){
        var imgId = $(this).data('imageid');

        // insert indicator
        $('#' + imgId).before('<div class="indicator" />');

        // center indicator (also adjust for offset)
        var containerWidth = $('#' + imgId).parents('.fancy-img:first').width();
        var containerHeight = $('#' + imgId).parents('.fancy-img:first').height();
        var indicatorWidth = $('.indicator:first').width();
        var indicatorHeight = $('.indicator:first').height();
        var newIndicator = $('#' + imgId).parents('.fancy-img:first').find('.indicator');

        $(newIndicator).css({
            left: containerWidth/2 - indicatorWidth /2 + $('#' + imgId).parents('.fancy-img:first').scrollLeft(),
            top: containerHeight/2 - indicatorHeight/2 + $('#' + imgId).parents('.fancy-img:first').scrollTop()
        });
    });
});

Let me know if this has helped. Cheers!


问:
sql connection error 000webhost
I am using 000 webhost to store a sql database.
Every time I want to connect to it I recieve this error message

```<code>Warning: mysqli::__construct(): (HY000/2002): Connection refused in /storage/h10/804/1186804/public_html/Handy_Help_PHP_files/conexiune.php on line 7
Connection failed: Connection refused
</code>```

This is the php I use to connect

```<code><?php
$servername = "localhost:3306";
$username = "id1186804_admin";
$password = "12345";

// Create connection
$conn = new mysqli($servername, $username, $password);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
</code>```

Can somebody help me to find the error?

答:
Remove port from host parameter and put in this order:

mysqli_connect(host,username,password,dbname,port,socket);

Title: sql connection error 000webhost

Body:
I am using 000 webhost to store a sql database.
Every time I want to connect to it I recieve this error message

Warning: mysqli::__construct(): (HY000/2002): Connection refused in /storage/h10/804/1186804/public_html/Handy_Help_PHP_files/conexiune.php on line 7
Connection failed: Connection refused

This is the php I use to connect

<?php
$servername = "localhost:3306";
$username = "id1186804_admin";
$password = "12345";

// Create connection
$conn = new mysqli($servername, $username, $password);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>

Can somebody help me to find the error?


问:
Reporting Template (RDLC) not exists in Visual Studio 2017
Reporting template Component (RDLC) not exists to as New Item in Visual Studio 2017 Enterprise.

How to resolve this?

I have tried by installing SQL Server Data Tools.

Previously it works for me in Visual Studio 2015.

答: The RDLC editor for VS2017 is only available as a VSIX installer from the marketplace: Download</p>

ContentLicense: CC BY-SA 4.0


问:
MySQL update table add different amount to each row

MySQL Table:

```
Key Total
 A   20
 B   15
 C   25
 D   30
```

I have this data:

```
Key Total
 A   5
 C   10
 D   10
```

I want to update the table:

by adding each row's total. Note the data is incomplete, so some rows (B) are not going to be updated. So the result should be:

```
Key Total
 A   25
 B   15
 C   35
 D   40
```

My current plan is running update table set total = total + ? where key = ?. But is there a more efficient way?

答:
If the second set of data were stored in a table then it would have been much easier.

Let's say your first table is named as first_table and your second data set is stored a table named second_table.

Query:

```<code>UPDATE first_table AS FT
INNER JOIN second_table AS ST
  ON FT.key = ST.key
SET FT.total = FT.total + ST.total;
</code>```

SEE DEMO

Body:
MySQL Table:

Key Total
 A   20
 B   15
 C   25
 D   30

I have this data:

Key Total
 A   5
 C   10
 D   10

I want to update the table:

by adding each row's total. Note the data is incomplete, so some rows (B) are not going to be updated. So the result should be:

Key Total
 A   25
 B   15
 C   35
 D   40

My current plan is running update table set total = total + ? where key = ?. But is there a more efficient way?

Body:
If the second set of data were stored in a table then it would have been much easier.

Let's say your first table is named as first_table and your second data set is stored a table named second_table.

Query:

UPDATE first_table AS FT
INNER JOIN second_table AS ST
  ON FT.key = ST.key
SET FT.total = FT.total + ST.total;

SEE DEMO


问:
What are Clojure's AOT limitations?
It looks like exposing clojure library api to Java code requires the use of AOT compilation (at least when the exposed api is OO). If I'm wrong about that, I am happy to be revised. In the past, there have been multiple issues with AOT, thusly relying on it may have seemed a bit reckless or unstable.

What is the current state in that?
Is it a safe practice?

Would you use that as a means to expose an OO api to java applications?

答:
You can use AOT to produce bytecode that will pass muster as a Java library. But it's not terribly pleasant, for you or for the Java programmers, who will rightfully ask: Where is the JavaDoc? Why are you using Object instead of generics? And other similarly awkward questions.

Instead, my preferred approach is to not make the Clojure code Java-friendly at all. Expose it as ordinary Clojure vars, and that's it. Then, write some Java code yourself, in the same library, that consumes the Clojure-based API and repackages it in terms of whatever Java constructs you want.

For one example, see my thrift-gen library. Using it from Clojure, you get a function that takes a map as input and produces a sequence; using it from Java, you get a builder pattern for configuration instead of the map, and you get a List<? extends T> as output. No JavaDoc, because I felt the usage documentation in the readme was sufficient, but if I were serious about using this there is a real .java source file to easily add JavaDoc to.

Title: What are Clojure's AOT limitations?


问:
CreateTexture2D() fails when using DXGI_FORMAT_YUY2 as Format
When D3D10_TEXTURE2D_DESC contains the following:

```<code>textureDesc.Width               = 1920 * 2;
textureDesc.Height              = 1080 * 2;
textureDesc.MipLevels           = 1;
textureDesc.ArraySize           = 1;
textureDesc.Format              = DXGI_FORMAT_YUY2;
textureDesc.SampleDesc.Count    = 1;
textureDesc.SampleDesc.Quality  = 0;
textureDesc.Usage               = D3D10_USAGE_DYNAMIC;
textureDesc.BindFlags           = D3D10_BIND_SHADER_RESOURCE;
textureDesc.CPUAccessFlags      = D3D10_CPU_ACCESS_WRITE;
textureDesc.MiscFlags           = 0;
</code>```

the ID3D10Device::CreateTexture2D() fails.

But, if I change Format to DXGI_FORMAT_R8G8B8A8_UNORM, the ID3D10Device::CreateTexture2D() succeeds. Can somebody explain why?

答: I know, that DirectX can output comments about error to stderr or stdout if you set D3D10_CREATE_DEVICE_DEBUG flag. Looks like it will help you to find the reason of failed.</p>

Body:
When D3D10_TEXTURE2D_DESC contains the following:

textureDesc.Width               = 1920 * 2;
textureDesc.Height              = 1080 * 2;
textureDesc.MipLevels           = 1;
textureDesc.ArraySize           = 1;
textureDesc.Format              = DXGI_FORMAT_YUY2;
textureDesc.SampleDesc.Count    = 1;
textureDesc.SampleDesc.Quality  = 0;
textureDesc.Usage               = D3D10_USAGE_DYNAMIC;
textureDesc.BindFlags           = D3D10_BIND_SHADER_RESOURCE;
textureDesc.CPUAccessFlags      = D3D10_CPU_ACCESS_WRITE;
textureDesc.MiscFlags           = 0;

the ID3D10Device::CreateTexture2D() fails.

But, if I change Format to DXGI_FORMAT_R8G8B8A8_UNORM, the ID3D10Device::CreateTexture2D() succeeds. Can somebody explain why?


问:
How can i divide two expressions in Microsoft SQL Server
How can i divide two expressions in Microsoft SQL Server which give Numbers as a Result? I tried with a /, but this didn't work

```<code>SELECT COUNT(*) FROM A
SELECT COUNT(*) FROM B WHERE c = 1
</code>```

I tried with  / but this didnt work

```<code>SELECT COUNT(*)
FROM A/SELECT COUNT(*) FROM B WHERE c = 1
</code>```

答:
Use subqueries:</p>

```<code>SELECT (a.countA / b.countB) As divisionResult
FROM
    (SELECT COUNT(*) AS countA FROM A) a,
    (SELECT COUNT(*) AS countB FROM B WHERE c = 1) b
;
</code>```

Body:
How can i divide two expressions in Microsoft SQL Server which give Numbers as a Result? I tried with a /, but this didn't work

SELECT COUNT(*) FROM A
SELECT COUNT(*) FROM B WHERE c = 1

I tried with  / but this didnt work

SELECT COUNT(*)
FROM A/SELECT COUNT(*) FROM B WHERE c = 1

Body:
Use subqueries:

SELECT (a.countA / b.countB) As divisionResult
FROM
    (SELECT COUNT(*) AS countA FROM A) a,
    (SELECT COUNT(*) AS countB FROM B WHERE c = 1) b
;


问:
How do I return a List to JSON along with hard coded roots
I'm not entirely sure how to define this question but basically I'm developing an ASP.Net application where I am generating a JsonResult called IndexJson.

My code is as follows:

```<code>public JsonResult IndexJson()
{
    var contacts = (from x in db.ContactSet
                   select new
                   {
                       x.AccountId,
                       x.FirstName,
                       x.LastName,
                       x.FullName,
                       x.JobTitle,
                       x.ParentCustomerId,
                       x.EMailAddress1,
                       x.Telephone1,
                       x.MobilePhone,
                       x.Fax,
                       x.GenderCode,
                       x.BirthDate
                   }).ToList();

    return Json(contacts, JsonRequestBehavior.AllowGet);
}
</code>```

This works well at returning the following JSON:

```<code>[{/*contact info*/}, {/*contact info*/}, {/*contact info*/}, ...]
</code>```

But now I want to return the following JSON (hard-coded for now, I will change the values later):

```<code>{
  "current": 1,
  "rowCount": 10,
  "rows": [{/*contact info*/}, {/*contact info*/}, {/*contact info*/}, ...],
  "total": 1123
}
</code>```

How can I adapt my code to do that?

答:
Simply wrap all into new anonymous object</p>

```<code>return Json(new { current = 1, rowCount = 10, rows = contacts, total = 1123 },
            JsonRequestBehavior.AllowGet
           );
</code>```

Body:
I'm not entirely sure how to define this question but basically I'm developing an ASP.Net application where I am generating a JsonResult called IndexJson.

My code is as follows:

public JsonResult IndexJson()
{
    var contacts = (from x in db.ContactSet
                   select new
                   {
                       x.AccountId,
                       x.FirstName,
                       x.LastName,
                       x.FullName,
                       x.JobTitle,
                       x.ParentCustomerId,
                       x.EMailAddress1,
                       x.Telephone1,
                       x.MobilePhone,
                       x.Fax,
                       x.GenderCode,
                       x.BirthDate
                   }).ToList();

    return Json(contacts, JsonRequestBehavior.AllowGet);
}

This works well at returning the following JSON:

[{/*contact info*/}, {/*contact info*/}, {/*contact info*/}, ...]

But now I want to return the following JSON (hard-coded for now, I will change the values later):

{
  "current": 1,
  "rowCount": 10,
  "rows": [{/*contact info*/}, {/*contact info*/}, {/*contact info*/}, ...],
  "total": 1123
}

How can I adapt my code to do that?

Body:
Simply wrap all into new anonymous object

return Json(new { current = 1, rowCount = 10, rows = contacts, total = 1123 },
            JsonRequestBehavior.AllowGet
           );


问:
how to compare version variables in DetectCondition in burn (wix)
Here's my Fragment

```<code><Fragment>
    <Variable Name="Hasp_BundleVersion" Value="7.54.8889.1" />
    <Variable Name="Hasp_IsInstalled" />
    <Variable Name="Hasp_InstalledVersion" />

    <util:RegistrySearch Id="Hasp_IsInstalled"
                         Variable="Hasp_IsInstalled"
                         Root="HKLM"
                         Key="SOFTWARE\Aladdin Knowledge Systems\HASP\Driver\Installer"
                         Value="Version"
                         Result="exists" />

    <util:RegistrySearch Condition="Hasp_IsInstalled"
                         After="Hasp_IsInstalled"
                         Variable="Hasp_InstalledVersion"
                         Root="HKLM"
                         Key="SOFTWARE\Aladdin Knowledge Systems\HASP\Driver\Installer"
                         Value="Version"
                         Result="value" />

    <PackageGroup Id="Hasp">
        <ExePackage Id="Hasp"
                    DisplayName="Hasp"
                    SourceFile="setups\HASPUserSetup.exe"
                    Compressed="yes"
                    DetectCondition="Hasp_IsInstalled AND Hasp_InstalledVersion >= Hasp_BundleVersion"
                    InstallCommand="/s /v/qn"
                    PerMachine="yes"
                    Permanent="yes" />
    </PackageGroup>
</Fragment>
</code>```

This doesn't work, because it seems like it is comparing the two values as strings. Here's the log:

```<code>[0A74:0A4C][2017-03-29T16:29:02]i000: Initializing string variable 'Hasp_BundleVersion' to value '7.54.8889.1'
[0A74:0A4C][2017-03-29T16:29:02]i000: Setting numeric variable 'Hasp_IsInstalled' to value 1
[0A74:0A4C][2017-03-29T16:29:02]i000: Setting string variable 'Hasp_InstalledVersion' to value '7.54.66980.1'
[0A74:0A4C][2017-03-29T16:29:02]i052: Condition 'Hasp_IsInstalled AND Hasp_InstalledVersion >= Hasp_BundleVersion' evaluates to false.
</code>```

If I change to type Version, it doesn't work either:

```<code><Fragment>
    <Variable Name="Hasp_BundleVersion" Type="version" Value="7.54.8889.1" />
    <Variable Name="Hasp_IsInstalled" />
    <Variable Name="Hasp_InstalledVersion" Type="version" Value="0.0.0.0" />

    <util:RegistrySearch Id="Hasp_IsInstalled"
                         Variable="Hasp_IsInstalled"
                         Root="HKLM"
                         Key="SOFTWARE\Aladdin Knowledge Systems\HASP\Driver\Installer"
                         Value="Version"
                         Result="exists" />

    <util:RegistrySearch Condition="Hasp_IsInstalled"
                         After="Hasp_IsInstalled"
                         Variable="Hasp_InstalledVersion"
                         Root="HKLM"
                         Key="SOFTWARE\Aladdin Knowledge Systems\HASP\Driver\Installer"
                         Value="Version"
                         Result="value" />

    <PackageGroup Id="Hasp">
        <ExePackage Id="Hasp"
                    DisplayName="Hasp"
                    SourceFile="setups\HASPUserSetup.exe"
                    Compressed="yes"
                    DetectCondition="Hasp_IsInstalled AND Hasp_InstalledVersion >= Hasp_BundleVersion"
                    InstallCommand="/s /v/qn"
                    PerMachine="yes"
                    Permanent="yes" />
    </PackageGroup>
</Fragment>
</code>```

Log:

```<code>[1B40:0CEC][2017-03-29T16:42:23]i000: Initializing version variable 'Hasp_BundleVersion' to value '7.54.8889.1'
[1B40:0CEC][2017-03-29T16:42:23]i000: Initializing version variable 'Hasp_InstalledVersion' to value '0.0.0.0'
[1B40:0CEC][2017-03-29T16:42:23]i000: Setting numeric variable 'Hasp_IsInstalled' to value 1
[1B40:0CEC][2017-03-29T16:42:23]i000: Setting string variable 'Hasp_InstalledVersion' to value '7.54.66980.1'
[1B40:0CEC][2017-03-29T16:42:23]i052: Condition 'Hasp_IsInstalled AND Hasp_InstalledVersion >= Hasp_BundleVersion' evaluates to false.
</code>```

I'm using Variables, because I need to access the values later in my custom bootstrapper.

What am I doing wrong?

答:
Below the Horizontal line is my original response which I think is wrong.
You define a version variable as roli09 did ie:

```<code><Variable Name="Hasp_BundleVersion" Type="version" Value="7.54.8889.1" />
</code>```

and you don't need the 'v'. You do need the v if you are doing a condition like this:

```<code>Condition="InstalledVersion >= v7.0.2.1"
</code>```

So that the compiler processes the second operand as a version.

What I think happened here is in the first code snippet, we have both versions being treated as string variables. And as strings they are compared character by character and '6' < '8' so we get false.

In the second code snippet I believe we end up with two Hasp_InstalledVersion variables. The one defined in the bundle which is a "version" variable and the one defined by the RegistySearch which is a string variable. I'm am guessing that in the condition it compares both version variables so this

```<code>Hasp_InstalledVersion >= Hasp_BundleVersion
</code>```

becomes

```<code>0.0.0.0 >= 7.54.8889.1
</code>```

which is false.

To fix this issue, do define

```<code><Variable Name="Hasp_BundleVersion" Type="version" Value="7.54.8889.1" />
</code>```

but do not define

```<code><Variable Name="Hasp_InstalledVersion" Type="version" Value="0.0.0.0" />
</code>```

Now it should compare the string variable from the registry search to the version variable defined in in the proj file. In condition.cpp of burn, if you have a "string variable OPERATION version variable", it tries to convert the string variable to a version variable and do version comparison.

Wix burn condition evaluation is a bit confusing.

I dug into it a while ago to figure out this exact issue. I believe the issue is that you're defining the version value incorrectly.

Also, I'm not sure you can use

```<code><Variable Name="Hasp_InstalledVersion" Type="version" Value="0.0.0.0" />
</code>```

since all variables set by RegistrySearches are string variables. I'm not sure if you end up having two Hasp_InstalledVersion variables defined now since one is a "version" variable and the other is a "string" version. Without wanting to delve into the wix source I would just stick to leaving it as a non-typed variable like in your first code snippet.

Now, onto fixing your condition, in the conditional evaluation there is promotion of string variables to other types of variables depending on the format of said variables. ie: string op string will do string comparison, string op version will do version comparison.

The way you format a variable to indicate it is a version is to just put a 'v' in front of it. So, I believe your issue will be solved if you update your Hasp_BundleVersion to be

```<code><Variable Name="Hasp_BundleVersion" Value="v7.54.8889.1" />
</code>```

Or better yet, you define the version somewhere in a include file or a property file (for msbuild, then included in DefineConstants) and you can update your code to

```<code><Variable Name="Hasp_BundleVersion" Value="v$(var.HaspBundleVersion)" />
</code>```

But going this far is just a matter of preference I think.

Body:
Here's my Fragment

<Fragment>
    <Variable Name="Hasp_BundleVersion" Value="7.54.8889.1" />
    <Variable Name="Hasp_IsInstalled" />
    <Variable Name="Hasp_InstalledVersion" />

    <util:RegistrySearch Id="Hasp_IsInstalled"
                         Variable="Hasp_IsInstalled"
                         Root="HKLM"
                         Key="SOFTWARE\Aladdin Knowledge Systems\HASP\Driver\Installer"
                         Value="Version"
                         Result="exists" />

    <util:RegistrySearch Condition="Hasp_IsInstalled"
                         After="Hasp_IsInstalled"
                         Variable="Hasp_InstalledVersion"
                         Root="HKLM"
                         Key="SOFTWARE\Aladdin Knowledge Systems\HASP\Driver\Installer"
                         Value="Version"
                         Result="value" />

    <PackageGroup Id="Hasp">
        <ExePackage Id="Hasp"
                    DisplayName="Hasp"
                    SourceFile="setups\HASPUserSetup.exe"
                    Compressed="yes"
                    DetectCondition="Hasp_IsInstalled AND Hasp_InstalledVersion >= Hasp_BundleVersion"
                    InstallCommand="/s /v/qn"
                    PerMachine="yes"
                    Permanent="yes" />
    </PackageGroup>
</Fragment>

This doesn't work, because it seems like it is comparing the two values as strings. Here's the log:

[0A74:0A4C][2017-03-29T16:29:02]i000: Initializing string variable 'Hasp_BundleVersion' to value '7.54.8889.1'
[0A74:0A4C][2017-03-29T16:29:02]i000: Setting numeric variable 'Hasp_IsInstalled' to value 1
[0A74:0A4C][2017-03-29T16:29:02]i000: Setting string variable 'Hasp_InstalledVersion' to value '7.54.66980.1'
[0A74:0A4C][2017-03-29T16:29:02]i052: Condition 'Hasp_IsInstalled AND Hasp_InstalledVersion >= Hasp_BundleVersion' evaluates to false.

If I change to type Version, it doesn't work either:

<Fragment>
    <Variable Name="Hasp_BundleVersion" Type="version" Value="7.54.8889.1" />
    <Variable Name="Hasp_IsInstalled" />
    <Variable Name="Hasp_InstalledVersion" Type="version" Value="0.0.0.0" />

    <util:RegistrySearch Id="Hasp_IsInstalled"
                         Variable="Hasp_IsInstalled"
                         Root="HKLM"
                         Key="SOFTWARE\Aladdin Knowledge Systems\HASP\Driver\Installer"
                         Value="Version"
                         Result="exists" />

    <util:RegistrySearch Condition="Hasp_IsInstalled"
                         After="Hasp_IsInstalled"
                         Variable="Hasp_InstalledVersion"
                         Root="HKLM"
                         Key="SOFTWARE\Aladdin Knowledge Systems\HASP\Driver\Installer"
                         Value="Version"
                         Result="value" />

    <PackageGroup Id="Hasp">
        <ExePackage Id="Hasp"
                    DisplayName="Hasp"
                    SourceFile="setups\HASPUserSetup.exe"
                    Compressed="yes"
                    DetectCondition="Hasp_IsInstalled AND Hasp_InstalledVersion >= Hasp_BundleVersion"
                    InstallCommand="/s /v/qn"
                    PerMachine="yes"
                    Permanent="yes" />
    </PackageGroup>
</Fragment>

Log:

[1B40:0CEC][2017-03-29T16:42:23]i000: Initializing version variable 'Hasp_BundleVersion' to value '7.54.8889.1'
[1B40:0CEC][2017-03-29T16:42:23]i000: Initializing version variable 'Hasp_InstalledVersion' to value '0.0.0.0'
[1B40:0CEC][2017-03-29T16:42:23]i000: Setting numeric variable 'Hasp_IsInstalled' to value 1
[1B40:0CEC][2017-03-29T16:42:23]i000: Setting string variable 'Hasp_InstalledVersion' to value '7.54.66980.1'
[1B40:0CEC][2017-03-29T16:42:23]i052: Condition 'Hasp_IsInstalled AND Hasp_InstalledVersion >= Hasp_BundleVersion' evaluates to false.

I'm using Variables, because I need to access the values later in my custom bootstrapper.

What am I doing wrong?

Body:
Below the Horizontal line is my original response which I think is wrong.
You define a version variable as roli09 did ie:

<Variable Name="Hasp_BundleVersion" Type="version" Value="7.54.8889.1" />

and you don't need the 'v'. You do need the v if you are doing a condition like this:

Condition="InstalledVersion &gt;= v7.0.2.1"

So that the compiler processes the second operand as a version.

What I think happened here is in the first code snippet, we have both versions being treated as string variables. And as strings they are compared character by character and '6' < '8' so we get false.

In the second code snippet I believe we end up with two Hasp_InstalledVersion variables. The one defined in the bundle which is a "version" variable and the one defined by the RegistySearch which is a string variable. I'm am guessing that in the condition it compares both version variables so this

Hasp_InstalledVersion &gt;= Hasp_BundleVersion

becomes

0.0.0.0 >= 7.54.8889.1

which is false.

To fix this issue, do define

<Variable Name="Hasp_BundleVersion" Type="version" Value="7.54.8889.1" />

but do not define

<Variable Name="Hasp_InstalledVersion" Type="version" Value="0.0.0.0" />

Now it should compare the string variable from the registry search to the version variable defined in in the proj file. In condition.cpp of burn, if you have a "string variable OPERATION version variable", it tries to convert the string variable to a version variable and do version comparison.

Wix burn condition evaluation is a bit confusing.

I dug into it a while ago to figure out this exact issue. I believe the issue is that you're defining the version value incorrectly.

Also, I'm not sure you can use

<Variable Name="Hasp_InstalledVersion" Type="version" Value="0.0.0.0" />

since all variables set by RegistrySearches are string variables. I'm not sure if you end up having two Hasp_InstalledVersion variables defined now since one is a "version" variable and the other is a "string" version. Without wanting to delve into the wix source I would just stick to leaving it as a non-typed variable like in your first code snippet.

Now, onto fixing your condition, in the conditional evaluation there is promotion of string variables to other types of variables depending on the format of said variables. ie: string op string will do string comparison, string op version will do version comparison.

The way you format a variable to indicate it is a version is to just put a 'v' in front of it. So, I believe your issue will be solved if you update your Hasp_BundleVersion to be

<Variable Name="Hasp_BundleVersion" Value="v7.54.8889.1" />

Or better yet, you define the version somewhere in a include file or a property file (for msbuild, then included in DefineConstants) and you can update your code to

<Variable Name="Hasp_BundleVersion" Value="v$(var.HaspBundleVersion)" />

But going this far is just a matter of preference I think.


问:
ko.computed property to determine visibility not working
In my KncokoutJS ViewModel, I have the follow computed property:

```<code>self.SelectedUserHasRoles = ko.computed(function () {
  if (self.isLoaded()) {
    return self.selectedUser().roles().length > 0;
  }
  return false;
});
</code>```

And in my HTML, I have the following:

```<code><!-- ko if: isLoaded() -->
  <!-- ko if: !SelectedUserHasRoles -->
  <div>
    <p>User has no Roles.</p>
  </div>
  <!-- /ko -->
  <!-- ko if: SelectedUserHasRoles -->
  <div class="roles-wrapper" data-bind="foreach: $root.selectedUser().roles()">
    <div class="role-token" data-bind="text: Name"></div>
  </div>
  <!-- /ko -->
<!-- /ko -->
</code>```

In my code, I was to say this:

If data from AJAX call has finished loading (isLoaded is true), then for the currently selected user, check and see if he/she has any roles. If yes, then loop through them and show them, if not, show a bit of text saying 'User has no Roles.'

All seems to work, except for the showing User has no Roles text snippet. I've no idea why that isn't showing! I'm putting breakpoints into my computed property and can see that when I select a user with no roles, the expression (in console window) is false, and I'm negating that, so I should see that text snippet!

What am I doing wrong? I've created a screencast to make things easier to understand.

答:
When you want to negate an observable or computed value in a binding, you have to call it explicitly:

```<code><!-- ko if: !SelectedUserHasRoles() -->
</code>```

In the case of the if binding, there's also the ifnot counterpart:

```<code><!-- ko ifnot: SelectedUserHasRoles -->
</code>```

I think it's useful to understand why this is needed, since I see it happening a lot.

You could see the data-bind attribute as a comma separated string of key value pairs. Knockout wraps each of the values in a function, which it calls the valueAccessor.

Essentially, you'll go from:

```<code> data-bind="if: SelectedUserHasRoles"
</code>```

to

```<code>{
   "if": function() { return SelectedUserHasRoles }
}
</code>```

SelectedUserHasRoles is an observable instance, which evaluates as truthy. When you negate this value using an !, it will always be false.

var myObs = ko.observable("anything");

var valueAccessor =    function() { return  myObs; };
var valueAccessorNeg = function() { return !myObs; };

console.log(valueAccessor());    // Returns the observable
console.log(valueAccessorNeg()); // Always prints false```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script></code>```

The valueAccessor function is passed to the init method of a binding. Usually, it is retrieved by calling it, and then unwrapped. Because the unwrap utility doesn't care about whether you pass it an observable or a plain value, you'll not see any errors when you make this mistake.

var myObs = ko.observable(false);

var va1 = function() { return myObs; };
var va2 = function() { return !myObs; };
var va3 = function() { return !myObs(); };

console.log(ko.unwrap(va1()));    // false
console.log(ko.unwrap(va2()));    // always false
console.log(ko.unwrap(va3()));    // true```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script></code>```

I hope this small peek under the hood might help you (and others that have made this mistake) to be able to determine when the () are needed in the future.

Body:
In my KncokoutJS ViewModel, I have the follow computed property:

self.SelectedUserHasRoles = ko.computed(function () {
  if (self.isLoaded()) {
    return self.selectedUser().roles().length > 0;
  }
  return false;
});

And in my HTML, I have the following:

User has no Roles.

In my code, I was to say this:

If data from AJAX call has finished loading (isLoaded is true), then for the currently selected user, check and see if he/she has any roles. If yes, then loop through them and show them, if not, show a bit of text saying 'User has no Roles.'

All seems to work, except for the showing User has no Roles text snippet. I've no idea why that isn't showing! I'm putting breakpoints into my computed property and can see that when I select a user with no roles, the expression (in console window) is false, and I'm negating that, so I should see that text snippet!

What am I doing wrong? I've created a screencast to make things easier to understand.

Body:
When you want to negate an observable or computed value in a binding, you have to call it explicitly:

<!-- ko if: !SelectedUserHasRoles() -->

In the case of the if binding, there's also the ifnot counterpart:

<!-- ko ifnot: SelectedUserHasRoles -->

I think it's useful to understand why this is needed, since I see it happening a lot.

You could see the data-bind attribute as a comma separated string of key value pairs. Knockout wraps each of the values in a function, which it calls the valueAccessor.

Essentially, you'll go from:

 data-bind="if: SelectedUserHasRoles"

to

{
   "if": function() { return SelectedUserHasRoles }
}

SelectedUserHasRoles is an observable instance, which evaluates as truthy. When you negate this value using an !, it will always be false.

var myObs = ko.observable("anything");

var valueAccessor =    function() { return  myObs; };
var valueAccessorNeg = function() { return !myObs; };

console.log(valueAccessor());    // Returns the observable
console.log(valueAccessorNeg()); // Always prints false

<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>

The valueAccessor function is passed to the init method of a binding. Usually, it is retrieved by calling it, and then unwrapped. Because the unwrap utility doesn't care about whether you pass it an observable or a plain value, you'll not see any errors when you make this mistake.

var myObs = ko.observable(false);

var va1 = function() { return myObs; };
var va2 = function() { return !myObs; };
var va3 = function() { return !myObs(); };

console.log(ko.unwrap(va1()));    // false
console.log(ko.unwrap(va2()));    // always false
console.log(ko.unwrap(va3()));    // true

<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>

I hope this small peek under the hood might help you (and others that have made this mistake) to be able to determine when the () are needed in the future.


问:
strcat segmentation fault
The second call to strcat here is generating a segmentation fault, why?

```<code>#include <unistd.h>
#include<stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>

int main (int argc, char * argv[])
{
         char command[250];

         //if(scanf("%199s", command) == 1)

            gets(command);
            puts(command);

         int pipeIntId;

         char whitespaceseparator[2]=" ";

         char pidstring [30];

         int pid= getpid();

         sprintf(pidstring,"%d", pid);

         char * whitespace_and_pid;

         whitespace_and_pid = strcat(whitespaceseparator,pidstring);

         char * command_and_pid;

         command_and_pid=strcat(command,whitespace_and_pid); // here's the problem, I guess

          if((mkfifo("pipe"/*pipeName*/,0666))==-1)
          {
              perror("error creating pipe 1");
          exit(1);
          }

         if((pipeIntId=open("pipe",/*pipeName*/O_WRONLY))==-1)
         {
          perror("error creating pipe 2");
          exit(1);
         }

         int written;

         written=write(pipeIntId,command_and_pid,250); // send the command + the pid

         close(pipeIntId);

    return 0;
}
</code>```

答:
"String concatenation" is an idiom you should drop when learning C. Not only does it lead to a lot of bugs with overflowing buffers; it's also super inefficient. In your code, you could just have included the space in the snprintf format string (you should be using it in place of sprintf).

Whenever possible, try to assemble a string entirely in one step using snprintf. This consolidates all of the buffer length checking into one place and makes it really hard to get wrong. You can also call snprintf with a 0 size argument to get the length that the combined string would be, in order to find out what size to allocate, if the size of the output is not known in advance (you should allocate one more byte than this length so that the null terminator does not truncate your output).

Title: strcat segmentation fault

Body:
The second call to strcat here is generating a segmentation fault, why?

#include <unistd.h>
#include<stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>

int main (int argc, char * argv[])
{
         char command[250];

         //if(scanf("%199s", command) == 1)

            gets(command);
            puts(command);

         int pipeIntId;

         char whitespaceseparator[2]=" ";

         char pidstring [30];

         int pid= getpid();

         sprintf(pidstring,"%d", pid);

         char * whitespace_and_pid;

         whitespace_and_pid = strcat(whitespaceseparator,pidstring);

         char * command_and_pid;

         command_and_pid=strcat(command,whitespace_and_pid); // here's the problem, I guess

          if((mkfifo("pipe"/*pipeName*/,0666))==-1)
          {
              perror("error creating pipe 1");
          exit(1);
          }

         if((pipeIntId=open("pipe",/*pipeName*/O_WRONLY))==-1)
         {
          perror("error creating pipe 2");
          exit(1);
         }

         int written;

         written=write(pipeIntId,command_and_pid,250); // send the command + the pid

         close(pipeIntId);

    return 0;
}


问:
select part of a string after certain number of special character
I have a data.table with a column

```<code>V1
a_b_c_las_poi
a_b_c_kiosk_pran
a_b_c_qwer_ok
</code>```

I would like to add a new column to this data.table which does not include the last part of string after the "_".

UPDATE

So i would like the output to be

a_b_c_las
a_b_c_kiosk
a_b_c_qwer

答:
If k is the number of fields to keep:

```<code>k <- 2
DT[, V1 := do.call(paste, c(read.table(text=V1, fill=TRUE, sep="_")[1:k], sep = "_"))]
</code>```

fill=TRUE can be omitted if all rows have the same number of fields.

Note: DT in a reproducible form is:

```<code>library(data.table)

DF <- data.frame(V1 = c("a_b_c_las_poi", "a_b_c_kiosk_pran", "a_b_c_qwer_ok"),
   stringsAsFactors = FALSE)
DT <- as.data.table(DF)
</code>```

Body:
I have a data.table with a column

V1
a_b_c_las_poi
a_b_c_kiosk_pran
a_b_c_qwer_ok

I would like to add a new column to this data.table which does not include the last part of string after the "_".

UPDATE

So i would like the output to be

a_b_c_las
a_b_c_kiosk
a_b_c_qwer

Body:
If k is the number of fields to keep:

k <- 2
DT[, V1 := do.call(paste, c(read.table(text=V1, fill=TRUE, sep="_")[1:k], sep = "_"))]

fill=TRUE can be omitted if all rows have the same number of fields.

Note: DT in a reproducible form is:

library(data.table)

DF <- data.frame(V1 = c("a_b_c_las_poi", "a_b_c_kiosk_pran", "a_b_c_qwer_ok"),
   stringsAsFactors = FALSE)
DT <- as.data.table(DF)


问:
Error using sql server sequence with Hibernate 5.0.3
This is the error. The 'SQ_USERS' is the sequence created in a sql server database.

com.microsoft.sqlserver.jdbc.SQLServerException: Invalid object name 'dbo.SQ_USERS'.

This is the entity that is used to get the sequence...

```<code>@Entity
@Table(name="USERS")
public class User {

    @Id
    @Column(name="id")
    @SequenceGenerator(name = "USER", schema="dbo", sequenceName = "SQ_USERS", allocationSize = 20)
    @GeneratedValue(generator = "USER", strategy = GenerationType.SEQUENCE)
    private int id;
}
</code>```

The sql that is generated is "select next_val as id_val from dbo.SQ_USERS with (updlock, rowlock)", but if i try this in sql server management studio, i get the error "Invalid object name 'dbo.SQ_USERS'."

Can anyone help?

Thanks.

答: I found the issue to the problem. I was using the wrong hibernate dialect. When I changed the dialect to "SQLServer2008Dialect" it worked correctly. </p>

Body:
This is the error. The 'SQ_USERS' is the sequence created in a sql server database.

com.microsoft.sqlserver.jdbc.SQLServerException: Invalid object name 'dbo.SQ_USERS'.

This is the entity that is used to get the sequence...

@Entity
@Table(name="USERS")
public class User {

    @Id
    @Column(name="id")
    @SequenceGenerator(name = "USER", schema="dbo", sequenceName = "SQ_USERS", allocationSize = 20)
    @GeneratedValue(generator = "USER", strategy = GenerationType.SEQUENCE)
    private int id;
}

The sql that is generated is "select next_val as id_val from dbo.SQ_USERS with (updlock, rowlock)", but if i try this in sql server management studio, i get the error "Invalid object name 'dbo.SQ_USERS'."

Can anyone help?

Thanks.


问:
Trigger User Action from Facebook Messenger Bot
I have a working Facebook messenger bot.

From the Messenger app, I would like my bot to trigger the "camera" action (to snap a new picture or video) for the user.

To clarify with a hypothetical context, I would create persistent menu action which mimics the behavior of clicking the "camera" button under the message text area.

I looked into the "Page Call To Action" operation of the Graph Api but could not find parameters that would produce the desired behavior.

答:
Here is the solution to your problem.

In Facebook Messenger, you can open a webview and load a webpage. But remeber that good old HTML 5 provides us with a simple way of asking the user to use their camera when they are on mobile.

These steps below work today

You can use a url button to open a webview as such

"buttons":[
      {
        "type":"web_url",
        "url":"https://url_to_your_webpage",
        "title":"View Item",
        "webview_height_ratio": "compact"
      }
    ]

In your webpage, include this HTML5 element that allows user to take image via camera on mobile

<input type="file" accept="image/*" capture="camera" />

Submit the image to your servers, close the webview, and do any processing required. For example you can now send the image back to the user from your bot.


问:
Automatically run Git hook when creating a Git tag
Is there a Git hook which can be executed when a new Git tag is added? Because I want to automatically write new Git tag names into a textfile. Do you have a clue on how to do this?</p>

答:
While it's not currently possible using hooks, you can always create a simple script.

mytag.sh :

```<code>#!/bin/sh
[ -z "$1" ] || ( git tag $1 && git tag > /path/to/your-tags-file )
</code>```

then :

```<code>chmod +x mytag.sh
git config alias.mytag !/path/to/mytag.sh
</code>```

Body:
While it's not currently possible using hooks, you can always create a simple script.

mytag.sh :

#!/bin/sh
[ -z "$1" ] || ( git tag $1 && git tag > /path/to/your-tags-file )

then :

chmod +x mytag.sh
git config alias.mytag !/path/to/mytag.sh


问:
My UPDATE statement with WHERE EXISTS does not limit to the SELECT statement results
I have data in a temporary table and I am checking for duplicates in two other tables.  I want to set a flag on the temp table (SET DupFlag = TRUE) for all duplicates found.  My SELECT statement works perfectly, returning only the 48 duplicates that I entered to test with.  But when I add UPDATE and WHERE EXISTS, every record in idTempImport2 is set to TRUE instead of just the 48 records returned from the SELECT statement. Is my syntax wrong? It looks like this:</p>

```<code>UPDATE idTempImport2 as tmp2 SET DupFlag = TRUE
WHERE EXISTS
(SELECT * FROM idTempImport2 tmp2
LEFT JOIN (SELECT im.idDate, im.UserID, im.ActionID, im.IsHC, idn.Epic1, idn.Epic2
      FROM idMain AS im
      INNER JOIN idNotes AS idn ON im.aID = idn.MainID
     WHERE idDate BETWEEN "2017-01-02" AND "2017-01-31")  AS qry
ON qry.idDate = tmp2.idDate AND qry.UserID = tmp2.UserID AND qry.ActionID = tmp2.ActionID AND qry.Epic1 = clng(tmp2.Epic1) AND qry.Epic2 = clng(tmp2.Epic2)
WHERE qry.Epic1 <> NULL);
</code>```

答:
I think the ultimate issue is that you want a correlated subquery.  As written, the subquery has no connection to the outer query, so it is likely that at least one row meets the condition.  So, everything gets updated.

I think you intend:

```<code>UPDATE idTempImport2 as tmp2
    SET DupFlag = TRUE
WHERE EXISTS (SELECT im.idDate, im.UserID, im.ActionID, im.IsHC, idn.Epic1, idn.Epic2
              FROM idMain AS im INNER JOIN
                   idNotes AS idn
                   ON im.aID = idn.MainID
              WHERE idDate BETWEEN "2017-01-02" AND "2017-01-31" AND
                    im.idDate = tmp2.idDate AND im.UserID = tmp2.UserID AND
                    im.ActionID = tmp2.ActionID AND
                    ?.Epic1 = clng(tmp2.Epic1) AND ?.Epic2 = clng(tmp2.Epic2)
             );
</code>```

Body:
I have data in a temporary table and I am checking for duplicates in two other tables.  I want to set a flag on the temp table (SET DupFlag = TRUE) for all duplicates found.  My SELECT statement works perfectly, returning only the 48 duplicates that I entered to test with.  But when I add UPDATE and WHERE EXISTS, every record in idTempImport2 is set to TRUE instead of just the 48 records returned from the SELECT statement. Is my syntax wrong? It looks like this:

UPDATE idTempImport2 as tmp2 SET DupFlag = TRUE
WHERE EXISTS
(SELECT * FROM idTempImport2 tmp2
LEFT JOIN (SELECT im.idDate, im.UserID, im.ActionID, im.IsHC, idn.Epic1, idn.Epic2
      FROM idMain AS im
      INNER JOIN idNotes AS idn ON im.aID = idn.MainID
     WHERE idDate BETWEEN "2017-01-02" AND "2017-01-31")  AS qry
ON qry.idDate = tmp2.idDate AND qry.UserID = tmp2.UserID AND qry.ActionID = tmp2.ActionID AND qry.Epic1 = clng(tmp2.Epic1) AND qry.Epic2 = clng(tmp2.Epic2)
WHERE qry.Epic1 <> NULL);

Body:
I think the ultimate issue is that you want a correlated subquery.  As written, the subquery has no connection to the outer query, so it is likely that at least one row meets the condition.  So, everything gets updated.

I think you intend:

UPDATE idTempImport2 as tmp2
    SET DupFlag = TRUE
WHERE EXISTS (SELECT im.idDate, im.UserID, im.ActionID, im.IsHC, idn.Epic1, idn.Epic2
              FROM idMain AS im INNER JOIN
                   idNotes AS idn
                   ON im.aID = idn.MainID
              WHERE idDate BETWEEN "2017-01-02" AND "2017-01-31" AND
                    im.idDate = tmp2.idDate AND im.UserID = tmp2.UserID AND
                    im.ActionID = tmp2.ActionID AND
                    ?.Epic1 = clng(tmp2.Epic1) AND ?.Epic2 = clng(tmp2.Epic2)
             );


问:
How to understand array sorting in Swift
Can someone please visualize the process of sorting?

```<code>let numbers = [0,2,1]
let sortedNumbers = numbers.sorted { $0 > $1 }
</code>```

If I were to sort these 3 numbers in descending order in real life, it would result in this: scrSh1, but Swift makes it complicated: scrSh2.

How can there be 4 returns and why is the last one 'false'?
How are the arguments $0 and $1 changing their positions?

答:
It's shortly but comprehensively described in the documentation:

```<code>let names = ["Chris", "Alex", "Ewa", "Barry", "Daniella"]
</code>```

...

```<code>reversedNames = names.sorted(by: { s1, s2 in s1 > s2 } )
</code>```

Shorthand Argument Names

Swift automatically provides shorthand argument names to inline
  closures, which can be used to refer to the values of the closure’s
  arguments by the names $0, $1, $2, and so on.

If you use these shorthand argument names within your closure
  expression, you can omit the closure’s argument list from its
  definition, and the number and type of the shorthand argument names
  will be inferred from the expected function type. The in keyword can
  also be omitted, because the closure expression is made up entirely of
  its body:

```<code>reversedNames = names.sorted(by: { $0 > $1 } )
</code>```

Here, $0 and $1 refer to the closure’s first and second String arguments.

Body:
Can someone please visualize the process of sorting?

let numbers = [0,2,1]
let sortedNumbers = numbers.sorted { $0 > $1 }

If I were to sort these 3 numbers in descending order in real life, it would result in this: scrSh1, but Swift makes it complicated: scrSh2.

How can there be 4 returns and why is the last one 'false'?
How are the arguments $0 and $1 changing their positions?

Body:
It's shortly but comprehensively described in the documentation:

let names = ["Chris", "Alex", "Ewa", "Barry", "Daniella"]

...

reversedNames = names.sorted(by: { s1, s2 in s1 > s2 } )

Shorthand Argument Names

Swift automatically provides shorthand argument names to inline
  closures, which can be used to refer to the values of the closure’s
  arguments by the names $0, $1, $2, and so on.

If you use these shorthand argument names within your closure
  expression, you can omit the closure’s argument list from its
  definition, and the number and type of the shorthand argument names
  will be inferred from the expected function type. The in keyword can
  also be omitted, because the closure expression is made up entirely of
  its body:

reversedNames = names.sorted(by: { $0 > $1 } )

Here, $0 and $1 refer to the closure’s first and second String arguments.


问:
Haskell, List as input for a function, How?
I've been given the following question in my coursework;

Define a function

```<code>flatten :: [(Char,Int)] -> String
</code>```

that flattens a list of pairs of characters and digits to a string. For example:

```<code>flatten [('a',5),('b',4),('c',2)]
"a5b4c2"
flatten [('d',9),('d',3)]
"d9d3"
</code>```

My problem is that whenever I attempt to define this function i get a type error relating the the [(Char, Int)] input. For example;

```<code>Couldn't match type '(Char, Int)' with '[Char]'
Expected type: [[Char]]
Actual type: [(Char, Int)]
</code>```

I've tried more ways of writing this definition in more ways than I can count, so I don't have any particular code to show, or any particular error ( I kept getting different ones...so many). All i have so far is;

```<code>flatten :: [(Char, Int)] -> String
flatten [] = []
</code>```

i figure my next line should go something like;

```<code>flatten ???? = concat (????)
</code>```

but I have no idea what to put in place of these question marks and Google search/class notes give no examples to follow.
any ideas?

答:
Let’s think about what goes into flatten and what comes out of it.
flatten, takes a list of pairs of type: (Char, Int) and produces a [Char]; it produces a list from an existing list. Does this ring a bell?

```<code>flatten xs = [ c | (char, int) <- xs, c <-[char] ++ show int]
</code>```

We can sequentially deconstruct each pair in the given list; for each pair, we turn each component into a string so we can concatenate them. Now we have a string for each pair, we just need to take each character out to produce the final string.

Body:
I've been given the following question in my coursework;

Define a function

flatten :: [(Char,Int)] -> String

that flattens a list of pairs of characters and digits to a string. For example:

flatten [('a',5),('b',4),('c',2)]
"a5b4c2"
flatten [('d',9),('d',3)]
"d9d3"

My problem is that whenever I attempt to define this function i get a type error relating the the [(Char, Int)] input. For example;

Couldn't match type '(Char, Int)' with '[Char]'
Expected type: [[Char]]
Actual type: [(Char, Int)]

I've tried more ways of writing this definition in more ways than I can count, so I don't have any particular code to show, or any particular error ( I kept getting different ones...so many). All i have so far is;

flatten :: [(Char, Int)] -> String
flatten [] = []

i figure my next line should go something like;

flatten ???? = concat (????)

but I have no idea what to put in place of these question marks and Google search/class notes give no examples to follow.
any ideas?

Body:
Let’s think about what goes into flatten and what comes out of it.
flatten, takes a list of pairs of type: (Char, Int) and produces a [Char]; it produces a list from an existing list. Does this ring a bell?

flatten xs = [ c | (char, int) <- xs, c <-[char] ++ show int]

We can sequentially deconstruct each pair in the given list; for each pair, we turn each component into a string so we can concatenate them. Now we have a string for each pair, we just need to take each character out to produce the final string.


问:
How to set wildcard in $_SERVER['REMOTE_ADDR'] possible?
is it possible to set $_SERVER['REMOTE_ADDR'] to a wildcard, so that anyone on the network can see this?

```<code><?php

if($_SERVER['REMOTE_ADDR'] == "112.200.150.212"){

                ?>
                <a href="http://www.tinycounter.com" target="_blank" title="free hit counter"><img border="0" alt="free hit counter" src="http://mycounter.tinycounter.com/index.php?user=fortressgate"></a>

                <?php
                }?>
</code>```

but i want the network can see the counter... so it would look like this?

```<code>if($_SERVER['REMOTE_ADDR'] == "112.200.150.%")
</code>```

is this possible?

Body:
is it possible to set $_SERVER['REMOTE_ADDR'] to a wildcard, so that anyone on the network can see this?

<?php

if($_SERVER['REMOTE_ADDR'] == "112.200.150.212"){

                ?>

                <?php
                }?>

but i want the network can see the counter... so it would look like this?

if($_SERVER['REMOTE_ADDR'] == "112.200.150.%")

is this possible?

Body: if(strpos($_SERVER['REMOTE_ADDR'], "112.200.150.") === 0)


问:
Polymorphism: member acces and getter give different results
Here is the code:

```<code>#include <iostream>
#include <vector>
#include <array>

class Parent
{
public:
    virtual void whatAmI(){std::cout << "A Parent" << std::endl;}
    virtual long getValue(){std::cout << "value from Parent " << std::endl; return value;}
    long value;
};

class Child : public Parent
{
public:
    virtual void whatAmI(){std::cout << "A child" << std::endl;}
    virtual long getValue(){std::cout << "value from Child " << std::endl; return value;}
    long value;
};

class SomeClass
{
public:
    Parent * parent;
};

int main()
{

Child c = Child();
SomeClass sc;

sc.parent = &c;
sc.parent->value = 10;
sc.parent->whatAmI();

std::cout << sc.parent->value << std::endl;
std::cout << sc.parent->getValue() << std::endl;
}
</code>```

It returns:

```<code>A child
10
value from Child
0
</code>```

I have read about object slicing, and made sure I would assign the value of 10 after the child has been sliced up. I still don't understand why the direct field access and the function call would give different results.

Thank you.

答:
There is no slicing here - you're accessing via a pointer.

The behaviour is due to the fact that member-variable access is not polymorphic.  So parent->value always refers to Parent::value, never Child::value.  Whereas value (in Child::getValue) refers to Child::value.

Body:
Here is the code:

#include <iostream>
#include <vector>
#include <array>

class Parent
{
public:
    virtual void whatAmI(){std::cout << "A Parent" << std::endl;}
    virtual long getValue(){std::cout << "value from Parent " << std::endl; return value;}
    long value;
};

class Child : public Parent
{
public:
    virtual void whatAmI(){std::cout << "A child" << std::endl;}
    virtual long getValue(){std::cout << "value from Child " << std::endl; return value;}
    long value;
};

class SomeClass
{
public:
    Parent * parent;
};

int main()
{

Child c = Child();
SomeClass sc;

sc.parent = &c;
sc.parent->value = 10;
sc.parent->whatAmI();

std::cout << sc.parent->value << std::endl;
std::cout << sc.parent->getValue() << std::endl;
}

It returns:

A child
10
value from Child
0

I have read about object slicing, and made sure I would assign the value of 10 after the child has been sliced up. I still don't understand why the direct field access and the function call would give different results.

Thank you.


问:
Is it possible to force download using download attribute?
I know how to use download attribute to force download, but I want to do something different.

```<code><a href="filename.mp4" download=""><img src="download.png"></a>
</code>```

This is the download attribute which works properly, but I want to download using the meta tag like so:

```<code><meta http-equiv="refresh" content="5; url=uploads/<?php echo $_POST["filename"]; ?>"> Please wait while your file start downloading.
</code>```

It is working great with extensions like zipfile, rar, etc.. But when I try to use mp4, it opens up the file in a browser instead of force download.

答:
I change some thing. Sir i think it may help you:
The first page code:

```<code><?php $file = $_POST["filename"]; ?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <meta http-equiv="refresh" content="5; url=hello.php?file=<?php echo $file; ?>">

    <title>Document</title>
</head>
<body>

</body>
</html>
</code>```

Then i create a hello.php file and it contain:

```<code><?php
$file = 'uploads/' . $_GET['file'];

if( !file_exists($file) ) die("File not found");

header('Content-Disposition: attachment; filename="' . basename($file) . '"');
header("Content-Length: " . filesize($file));
header('Content-type: vedio/mp4');

readfile($file);
?>
</code>```

the process download the file automatic.

Body:
I know how to use download attribute to force download, but I want to do something different.

This is the download attribute which works properly, but I want to download using the meta tag like so:

<meta http-equiv="refresh" content="5; url=uploads/<?php echo $_POST["filename"]; ?>"> Please wait while your file start downloading.

It is working great with extensions like zipfile, rar, etc.. But when I try to use mp4, it opens up the file in a browser instead of force download.

Body:
I change some thing. Sir i think it may help you:
The first page code:

<?php $file = $_POST["filename"]; ?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <meta http-equiv="refresh" content="5; url=hello.php?file=<?php echo $file; ?>">

    <title>Document</title>
</head>
<body>

</body>
</html>

Then i create a hello.php file and it contain:

<?php
$file = 'uploads/' . $_GET['file'];

if( !file_exists($file) ) die("File not found");

header('Content-Disposition: attachment; filename="' . basename($file) . '"');
header("Content-Length: " . filesize($file));
header('Content-type: vedio/mp4');

readfile($file);
?>

the process download the file automatic.


问:
Data attribute in XML View elements
I'm trying to add data attributes to elements in a XML View as below:

```<code><core:FragmentDefinition
    xmlns="sap.m"
    <VBox data-help-id="Some.String.Here">
        ...
    </VBox>
</core:FragmentDefinition>
</code>```

but couldn't find how to do it, unless I assign them via Controller.

Tried using CustomData namespace, but it only adds data, without adding the HTML attribute to the DOM element.

Any idea?

Thanks!

答:
actually you can do something very close and associate data to your xmlView. This is available for xml views and more. Check this url for more details: Custom Data - Attaching Data Objects to Controls

What you would need to do is add a custom namespace to your xmlView:

```<code>xmlns:dataHelp="http://schemas.sap.com/sapui5/extension/sap.ui.core.CustomData/1"
</code>```

...

```<code><core:FragmentDefinition
    xmlns="sap.m"
    <VBox dataHelp:id="Some.String.Here" id="myBox"
        ...
    </VBox>
</core:FragmentDefinition>
</code>```

you are then able to set and consume this attribute in your binding and javascript/controller/event handler:

```<code>sap.ui.getCore().byId("myBox").data("id") // = Some.String.Here
</code>```

Title: Data attribute in XML View elements

Body:
I'm trying to add data attributes to elements in a XML View as below:

<core:FragmentDefinition
    xmlns="sap.m"
    <VBox data-help-id="Some.String.Here">
        ...
    </VBox>
</core:FragmentDefinition>

but couldn't find how to do it, unless I assign them via Controller.

Tried using CustomData namespace, but it only adds data, without adding the HTML attribute to the DOM element.

Any idea?

Thanks!

Body:
actually you can do something very close and associate data to your xmlView. This is available for xml views and more. Check this url for more details: Custom Data - Attaching Data Objects to Controls

What you would need to do is add a custom namespace to your xmlView:

xmlns:dataHelp="http://schemas.sap.com/sapui5/extension/sap.ui.core.CustomData/1"

...

<core:FragmentDefinition
    xmlns="sap.m"
    <VBox dataHelp:id="Some.String.Here" id="myBox"
        ...
    </VBox>
</core:FragmentDefinition>

you are then able to set and consume this attribute in your binding and javascript/controller/event handler:

sap.ui.getCore().byId("myBox").data("id") // = Some.String.Here


问:
How to use the same PHP script to fetch data for mobile app and website?
So, I have a website that hits up a very simple PHP script to display data from a database in an HTML table.

My question is simple; is it possible to write the PHP script in such a way that I can use the same script to get the same data and return it in JSON for the android app that will need it (without a single if(onMobileApp) type god statment which is basically equivalent to writing two scripts anyways)?

Or do I have to have two scripts, like

```<code>get_songs_web.php
get_songs_android.php
</code>```

It should be noted that speed of development is crucial here; I'm learning this skill for a 24h competition, so I'm writing procedural PHP, not OO.

As an example of the type of scripts I have, so that you can use it as an example in your responses, here is one of the ones used in the webpage:

```<code><?php
    // Connect to database
    $db_connection = mysqli_connect('localhost', 'root', '', 'songs_list_data')
    or die('Error connecting to MySQL server!');

    // Get data from HTML form
    $name = $_POST["song"];
    $artist = $_POST["artist"];

    // Add song to database
    $add_song_query = $db_connection->prepare("INSERT INTO songs"
            . "(artist, name)"
            . "VALUES (?, ?)");
    $add_song_query->bind_param("ss", $artist, $name);
    $add_song_query->execute();
    $add_song_query->close();
?>

<html>
    <table id="results">
        <?php
            $results_query = $db_connection->prepare("SELECT *"
                    . "FROM songs");
            mysqli_stmt_execute($results_query);
            $result = mysqli_stmt_get_result($results_query);
            $row_num = 1;
            while($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
            {
                echo '<tr class="songs_table_row">';
                    echo '<td class="row_num">' . $row_num . '</td>';
                    echo '<td class="artst">' . $row['artist'] . '</td>';
                    echo '<td class="name">' . $row['name'] . '</td>';
                echo '</tr>';
                $row_num++;
            }
            mysqli_stmt_close($results_query);
        ?>
    </table>
</html>

<?php
    // Close database connection
    mysqli_close($db_connection);
?>
</code>```

答:
Yes, use

```<code><?php
echo json_encode($your_data);
</code>```

To export to JSON. Not sure if json_encode is enabled by default in your php version. It's worth a try.

If you need the code to export both JSON and HTML use something like:

```<code><?php

if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) &&
    strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) {

    // ... export JSON here

} else {

    // ... export HTML here

}
</code>```

Body:
So, I have a website that hits up a very simple PHP script to display data from a database in an HTML table.

My question is simple; is it possible to write the PHP script in such a way that I can use the same script to get the same data and return it in JSON for the android app that will need it (without a single if(onMobileApp) type god statment which is basically equivalent to writing two scripts anyways)?

Or do I have to have two scripts, like

get_songs_web.php
get_songs_android.php

It should be noted that speed of development is crucial here; I'm learning this skill for a 24h competition, so I'm writing procedural PHP, not OO.

As an example of the type of scripts I have, so that you can use it as an example in your responses, here is one of the ones used in the webpage:

<?php
    // Connect to database
    $db_connection = mysqli_connect('localhost', 'root', '', 'songs_list_data')
    or die('Error connecting to MySQL server!');

    // Get data from HTML form
    $name = $_POST["song"];
    $artist = $_POST["artist"];

    // Add song to database
    $add_song_query = $db_connection->prepare("INSERT INTO songs"
            . "(artist, name)"
            . "VALUES (?, ?)");
    $add_song_query->bind_param("ss", $artist, $name);
    $add_song_query->execute();
    $add_song_query->close();
?>

        <?php
            $results_query = $db_connection->prepare("SELECT *"
                    . "FROM songs");
            mysqli_stmt_execute($results_query);
            $result = mysqli_stmt_get_result($results_query);
            $row_num = 1;
            while($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
            {
                echo '
';
                    echo '' . $row_num . '	';
                    echo '' . $row['artist'] . '	';
                    echo '' . $row['name'] . '	';
                echo '
';
                $row_num++;
            }
            mysqli_stmt_close($results_query);
        ?>

<?php
    // Close database connection
    mysqli_close($db_connection);
?>

Body:
Yes, use

<?php
echo json_encode($your_data);

To export to JSON. Not sure if json_encode is enabled by default in your php version. It's worth a try.

If you need the code to export both JSON and HTML use something like:

<?php

if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) &&
    strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) {

    // ... export JSON here

} else {

    // ... export HTML here

}


问:
Python: how pass string as a function's argument
I have a dataframe with US state abbreviations:

```<code>state
tx
ca
fl
wa
ny
az
</code>```

I'm trying to get full names with the us.states module

```<code>df['state_ru'] = df.state.apply(lambda x: us.states.x.upper().name)
</code>```

And it returns

```<code>AttributeError: module 'us.states' has no attribute 'x'
</code>```

I'm unclear how to pass the x into the us.states module to produce what I'm looking for.

Expected results:

```<code>state  state_ru
tx     Texas
ca     California
fl     Florida
wa     Washington
ny     New York
az     Arizona
</code>```

答:
Yes you can do it using getattr like this

```<code>getattr(obj, 'foo')
</code>```

This is equivalent to doing : obj.foo and is very useful when the attribute name is variable.

Body:
I have a dataframe with US state abbreviations:

state
tx
ca
fl
wa
ny
az

I'm trying to get full names with the us.states module

df['state_ru'] = df.state.apply(lambda x: us.states.x.upper().name)

And it returns

AttributeError: module 'us.states' has no attribute 'x'

I'm unclear how to pass the x into the us.states module to produce what I'm looking for.

Expected results:

state  state_ru
tx     Texas
ca     California
fl     Florida
wa     Washington
ny     New York
az     Arizona

Body:
Yes you can do it using getattr like this

getattr(obj, 'foo')

This is equivalent to doing : obj.foo and is very useful when the attribute name is variable.


问:
How to emulate a do-while loop?
I need to emulate a do-while loop in a Python program. Unfortunately, the following straightforward code does not work:

```<code>list_of_ints = [ 1, 2, 3 ]
iterator = list_of_ints.__iter__()
element = None

while True:
  if element:
    print element

  try:
    element = iterator.next()
  except StopIteration:
    break

print "done"
</code>```

Instead of "1,2,3,done", it prints the following output:

```<code>[stdout:]1
[stdout:]2
[stdout:]3
None['Traceback (most recent call last):
', '  File "test_python.py", line 8, in <module>
    s = i.next()
', 'StopIteration
']
</code>```

What can I do in order to catch the 'stop iteration' exception and break a while
loop properly?

An example of why such a thing may be needed is shown below as pseudocode.

State machine:

```<code>s = ""
while True :
  if state is STATE_CODE :
    if "//" in s :
      tokens.add( TOKEN_COMMENT, s.split( "//" )[1] )
      state = STATE_COMMENT
    else :
      tokens.add( TOKEN_CODE, s )
  if state is STATE_COMMENT :
    if "//" in s :
      tokens.append( TOKEN_COMMENT, s.split( "//" )[1] )
    else
      state = STATE_CODE
      # Re-evaluate same line
      continue
  try :
    s = i.next()
  except StopIteration :
    break
</code>```

答:
```<code>while condition is True:
  stuff()
else:
  stuff()
</code>```

Title: How to emulate a do-while loop?

Body:
I need to emulate a do-while loop in a Python program. Unfortunately, the following straightforward code does not work:

list_of_ints = [ 1, 2, 3 ]
iterator = list_of_ints.__iter__()
element = None

while True:
  if element:
    print element

  try:
    element = iterator.next()
  except StopIteration:
    break

print "done"

Instead of "1,2,3,done", it prints the following output:

[stdout:]1
[stdout:]2
[stdout:]3
None['Traceback (most recent call last):
', '  File "test_python.py", line 8, in <module>
    s = i.next()
', 'StopIteration
']

What can I do in order to catch the 'stop iteration' exception and break a while
loop properly?

An example of why such a thing may be needed is shown below as pseudocode.

State machine:

s = ""
while True :
  if state is STATE_CODE :
    if "//" in s :
      tokens.add( TOKEN_COMMENT, s.split( "//" )[1] )
      state = STATE_COMMENT
    else :
      tokens.add( TOKEN_CODE, s )
  if state is STATE_COMMENT :
    if "//" in s :
      tokens.append( TOKEN_COMMENT, s.split( "//" )[1] )
    else
      state = STATE_CODE
      # Re-evaluate same line
      continue
  try :
    s = i.next()
  except StopIteration :
    break


问:
Classic ASP XMLDom read Root Node Name
I receive this xml text

```<code><InsertProductsRequest>
    <ProductsContainer>
        <Product>
            <ProductCode>AB25E</ProductCode>
            <Description>Good Item bla bla...</Description>
            <Price>25.5</Price>
            <Currency>EUR</Currency>
            ......
            <ShippingService>DHL</ShippingService>
            <ShippingService>TNT</ShippingService>
        </Product>
    </ProductsContainer>
</InsertProductsRequest>
</code>```

using Classic ASP and Microsoft.XMLDOM

how can I get the root node name, thus "InsertProductsRequest"

Thanks
Joe

答:
You need to use tagName property of the documentElement.

'the string containing xml document
xml = "<InsertProductsRequest></InsertProductsRequest>"

Set doc = Server.CreateObject("MSXML2.DomDocument")
doc.loadXML xml

Response.Write doc.documentElement.tagName
```

Title: Classic ASP XMLDom read Root Node Name

Body:
I receive this xml text

<InsertProductsRequest>
    <ProductsContainer>
        <Product>
            <ProductCode>AB25E</ProductCode>
            <Description>Good Item bla bla...</Description>
            <Price>25.5</Price>
            <Currency>EUR</Currency>
            ......
            <ShippingService>DHL</ShippingService>
            <ShippingService>TNT</ShippingService>
        </Product>
    </ProductsContainer>
</InsertProductsRequest>

using Classic ASP and Microsoft.XMLDOM

how can I get the root node name, thus "InsertProductsRequest"

Thanks
Joe