问:
select all checkbox datatable trigger
I've been currently struggling with this problem for days. The problem is how can I makes the 'click' on the select all checkbox on thead of datatables to trigger something (in this case, a "disabled" class for my buttons)?

I've makes the trigger work when user 'click' the checkbox one by one, but I can't make it works when user click the select all checkbox. Please help me, thankyou in advance.

This is my Datatables script:

```<code>$(document).ready(function () {
            table = $('#em').DataTable({
                "scrollY": "45vh",
                "scrollX": true,
                "scrollCollapse": true,
                "paging": false,

                "responsive": true,

                "aaSorting": [1, 'desc'],
                "iDisplayLength": 5,
                "ajax": {
                    "url": "/Eromo_Web/inv?act=getAll",
                    "type": "POST",
                    "dataSrc": ""
                },
                "columnDefs": [
                    {
                        'targets': 0,
                        'checkboxes': {
                            'selectRow': true
                        }
                    }
                ],
                "columns": [
                    {"data": null},
                    {"data": "CODE"},
                    {"data": "TYPE"},
                    {"data": "NAME"},
                    {"data": "KIND"},
                    {"data": "MERK"},
                    {"data": "MODEL_TYPE"},
                    {"data": "LOC"},
                    {"data": "BUY_DATE"},
                    {"data": "USERNAME"},
                    {"data": "DESCR"},
                    {"data": "RFRGRNT"},
                    {"data": "MANF"},
                    {"data": "COUNTRY"}
                ]
            });
</code>```

My current click trigger:

```<code>//getting ID on checkbox click
            $('#em').on('change', null, function () {
                if (table.column(0).checkboxes.selected().length > 0) {
                    $('#generateqrcode').attr('disabled', false);
                } else {
                    $('#generateqrcode').attr('disabled', true);
                }
                if (table.column(0).checkboxes.selected().length === 1) {
                    ID = "";
                    $.each(table.column(0).checkboxes.selected(), function (key, value) {
                        ID = value["CODE"];
                    });
                    $('#update').attr('disabled', false);
                    $('#delete').attr('disabled', false);
                } else {
                    $('#update').attr('disabled', true);
                    $('#delete').attr('disabled', true);
                }
            });
</code>```

答:
Thankyou for the answer. Sorry for the late reply, I found my problem, it is because I use the property "scrollY": "45vh", and "scrollX": true. If I deactivated it, the "selectAll" checkbox can be triggered easily. I don't know why tho.

This is my final code:

```<code>table = $('#em').DataTable({
                "ajax": {
                    "url": "/Eromo_Web/inv?act=getAll",
                    "type": "POST",
                    "dataSrc": ""
                },
                "columnDefs": [
                    {
                        'targets': 0,
                        'checkboxes': {
                            'selectRow': false
                        }
                    }
                ],
                "columns": [
                    {"data": null},
                    {"data": "CODE"},
                    {"data": "TYPE"},
                    {"data": "NAME"},
                    {"data": "KIND"},
                    {"data": "MERK"},
                    {"data": "MODEL_TYPE"},
                    {"data": "LOC"},
                    {"data": "BUY_DATE"},
                    {"data": "USERNAME"},
                    {"data": "DESCR"},
                    {"data": "RFRGRNT"},
                    {"data": "MANF"},
                    {"data": "COUNTRY"}
                ],
                "paging": false,
                "responsive": true,
                "aaSorting": [1, 'desc'],
                "iDisplayLength": 5
            });
</code>```

And this:

```<code>//                getting ID on checkbox click
                $('#em').on('change', null, function () {
                    if (table.column(0).checkboxes.selected().length > 0) {
                        $('#generateqrcode').attr('disabled', false);
                    } else {
                        $('#generateqrcode').attr('disabled', true);
                    }
                    if (table.column(0).checkboxes.selected().length === 1) {
                        ID = "";
                        $.each(table.column(0).checkboxes.selected(), function (key, value) {
                            ID = value["CODE"];
                        });
                        $('#update').attr('disabled', false);
                        $('#delete').attr('disabled', false);
                    } else {
                        $('#update').attr('disabled', true);
                        $('#delete').attr('disabled', true);
                    }
                });
</code>```

Title: select all checkbox datatable trigger

Body:
I've been currently struggling with this problem for days. The problem is how can I makes the 'click' on the select all checkbox on thead of datatables to trigger something (in this case, a "disabled" class for my buttons)?

I've makes the trigger work when user 'click' the checkbox one by one, but I can't make it works when user click the select all checkbox. Please help me, thankyou in advance.

This is my Datatables script:

$(document).ready(function () {
            table = $('#em').DataTable({
                "scrollY": "45vh",
                "scrollX": true,
                "scrollCollapse": true,
                "paging": false,

                "responsive": true,

                "aaSorting": [1, 'desc'],
                "iDisplayLength": 5,
                "ajax": {
                    "url": "/Eromo_Web/inv?act=getAll",
                    "type": "POST",
                    "dataSrc": ""
                },
                "columnDefs": [
                    {
                        'targets': 0,
                        'checkboxes': {
                            'selectRow': true
                        }
                    }
                ],
                "columns": [
                    {"data": null},
                    {"data": "CODE"},
                    {"data": "TYPE"},
                    {"data": "NAME"},
                    {"data": "KIND"},
                    {"data": "MERK"},
                    {"data": "MODEL_TYPE"},
                    {"data": "LOC"},
                    {"data": "BUY_DATE"},
                    {"data": "USERNAME"},
                    {"data": "DESCR"},
                    {"data": "RFRGRNT"},
                    {"data": "MANF"},
                    {"data": "COUNTRY"}
                ]
            });

My current click trigger:

//getting ID on checkbox click
            $('#em').on('change', null, function () {
                if (table.column(0).checkboxes.selected().length > 0) {
                    $('#generateqrcode').attr('disabled', false);
                } else {
                    $('#generateqrcode').attr('disabled', true);
                }
                if (table.column(0).checkboxes.selected().length === 1) {
                    ID = "";
                    $.each(table.column(0).checkboxes.selected(), function (key, value) {
                        ID = value["CODE"];
                    });
                    $('#update').attr('disabled', false);
                    $('#delete').attr('disabled', false);
                } else {
                    $('#update').attr('disabled', true);
                    $('#delete').attr('disabled', true);
                }
            });

Body:
Thankyou for the answer. Sorry for the late reply, I found my problem, it is because I use the property "scrollY": "45vh", and "scrollX": true. If I deactivated it, the "selectAll" checkbox can be triggered easily. I don't know why tho.

This is my final code:

table = $('#em').DataTable({
                "ajax": {
                    "url": "/Eromo_Web/inv?act=getAll",
                    "type": "POST",
                    "dataSrc": ""
                },
                "columnDefs": [
                    {
                        'targets': 0,
                        'checkboxes': {
                            'selectRow': false
                        }
                    }
                ],
                "columns": [
                    {"data": null},
                    {"data": "CODE"},
                    {"data": "TYPE"},
                    {"data": "NAME"},
                    {"data": "KIND"},
                    {"data": "MERK"},
                    {"data": "MODEL_TYPE"},
                    {"data": "LOC"},
                    {"data": "BUY_DATE"},
                    {"data": "USERNAME"},
                    {"data": "DESCR"},
                    {"data": "RFRGRNT"},
                    {"data": "MANF"},
                    {"data": "COUNTRY"}
                ],
                "paging": false,
                "responsive": true,
                "aaSorting": [1, 'desc'],
                "iDisplayLength": 5
            });

And this:

//                getting ID on checkbox click
                $('#em').on('change', null, function () {
                    if (table.column(0).checkboxes.selected().length > 0) {
                        $('#generateqrcode').attr('disabled', false);
                    } else {
                        $('#generateqrcode').attr('disabled', true);
                    }
                    if (table.column(0).checkboxes.selected().length === 1) {
                        ID = "";
                        $.each(table.column(0).checkboxes.selected(), function (key, value) {
                            ID = value["CODE"];
                        });
                        $('#update').attr('disabled', false);
                        $('#delete').attr('disabled', false);
                    } else {
                        $('#update').attr('disabled', true);
                        $('#delete').attr('disabled', true);
                    }
                });


来源: stackexchange

问:
Rails 3 with Liquid Custom Tags not found
I am trying to create a set of custom tags for some liquid templates using Rails 3.  I added a 'liquid_tags.rb' in my lib/ directory with content like this:

```<code>class UserControls < Liquid::Tag
  def initialize(tag_name)
     super
  end

  def render(context)
    tag = "<b>TAG</b>"
  end
end

Liquid::Template.register_tag('user_controls', UserControls)
</code>```

When I try to get the tag in my view via '{% user_controls %}' it tells me the tag isn't found.

Any ideas?

Thanks in advance.

答:
I think it's not loading problem -- I have it also. The tag is being loaded, you can print the current registered tags: </p>

```<code>Liquid::Template.tags.inspect
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I am trying to create a set of custom tags for some liquid templates using Rails 3.  I added a 'liquid_tags.rb' in my lib/ directory with content like this:

class UserControls < Liquid::Tag
  def initialize(tag_name)
     super
  end

  def render(context)
    tag = "TAG"
  end
end

Liquid::Template.register_tag('user_controls', UserControls)

When I try to get the tag in my view via '{% user_controls %}' it tells me the tag isn't found.

Any ideas?

Thanks in advance.

Body:
I think it's not loading problem -- I have it also. The tag is being loaded, you can print the current registered tags:

Liquid::Template.tags.inspect

ContentLicense: CC BY-SA 3.0


问:
JSON Serialization: Class name to be picked from annotation
Can anybody help me in JSON Serialization. I need to change the qualified class name using Annotation. I don't have to use Map or another class. Name should be picked from Annotation.

-> Annotation I used is

@JsonTypeInfo(use = Id.CLASS, include = As.PROPERTY, property ="type")
private Object menu;

-> JSON I'm able to get is

"menu" : [ "java.util.ArrayList", [ {
      "name" : "Menu_Test",
      "data" : "Menu_123"
    } ] ],

-> But I want it to be something like this.

"menu" : [ "list", [ {
      "name" : "Menu_Test",
      "data" : "Menu_123"
    } ] ],

答:
You should use JsonTypeInfo.Id.NAME and then you will need to specify the name of each class with additional annotations, for example:

```<code>@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type")
@JsonSubTypes({
    @JsonSubTypes.Type(value = ArrayList.class, name = "list")
})
</code>```

Body:
You should use JsonTypeInfo.Id.NAME and then you will need to specify the name of each class with additional annotations, for example:

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type")
@JsonSubTypes({
    @JsonSubTypes.Type(value = ArrayList.class, name = "list")
})


问:
Adding fields to js objects, in functional way
I have an array of objects with a set of fields in node.js. Lets say

```<code>let arr = [ {a:1,b:2}, {a:3,b:6}]
</code>```

I would like to extend all objects and assign to a new variable. My naïve approach is like the following way

```<code>let arr2 = arr.map(x => x.c = x.a + x.b )
</code>```

However, the arrow function returns the x.a+x.b value, instead of the x object, so this won't work as I hope. It also alters the arr in place which is very nonfunctional and confusing.

I'm relatively new to js so maybe I'm thinking wrong from the beginning. What is the idiomatic js expression for this kind of object extension?

答:
Although the same general idea as other answers, this might be slightly more readable:</p>

```<code>arr.map(({a, b}) => ({a, b, c: a + b}))
</code>```

Body:
I have an array of objects with a set of fields in node.js. Lets say

let arr = [ {a:1,b:2}, {a:3,b:6}]

I would like to extend all objects and assign to a new variable. My naïve approach is like the following way

let arr2 = arr.map(x => x.c = x.a + x.b )

However, the arrow function returns the x.a+x.b value, instead of the x object, so this won't work as I hope. It also alters the arr in place which is very nonfunctional and confusing.

I'm relatively new to js so maybe I'm thinking wrong from the beginning. What is the idiomatic js expression for this kind of object extension?

Body:
Although the same general idea as other answers, this might be slightly more readable:

arr.map(({a, b}) => ({a, b, c: a + b}))


问:
char* = new char And char* = new char[N]
I construct a class named CMyString, here is it:

```<code>class CMyString {
public:
    CMyString();
    CMyString(char* pData);
    CMyString(const CMyString& str);
    ~CMyString(void);

    char* getData();
    void setData(char* pData);

    CMyString& operator=(const CMyString& str);

private:
    char* m_pData;
};

    CMyString::CMyString() {
    m_pData = new char;
}

CMyString::CMyString(char* pData) {
//    m_pData = new char;
    m_pData = pData;
}

CMyString::CMyString(const CMyString& str) {
    // 为指针分配内存
//    m_pData = new char;
    // 拷贝值
    m_pData = str.m_pData;
}

CMyString::~CMyString(void) {
//    delete m_pData;
}

CMyString& CMyString::operator=(const CMyString& str) {
    if (this == &str)
        return *this;

    delete m_pData;
    m_pData = nullptr;
    m_pData = new char[strlen(str.m_pData) + 1];
    strcpy(m_pData, str.m_pData);

    return *this;
}

char* CMyString::getData() {
    return m_pData;
}

void CMyString::setData(char *pData) {
    m_pData = pData;
}
</code>```

And here is my main.cpp:

```<code>#include <iostream>
#include "CMyString.h"

using std::cout;
using std::endl;

int main() {
    char* pData = "What are you worrying about?";
    std::cout << pData << std::endl;

    cout << strlen(pData) << endl;
    char* test = new char[30];
    cout << sizeof(test) << endl;
    char* test2 = new char;
    test2 = "23";
    cout << test2 << endl;

    strcpy(test, pData);

    cout << endl << test << endl << endl;

    CMyString str(pData);
    std::cout << str.getData() << std::endl;

    CMyString str2, str3;
    str3 = str2 = str;

    std::cout << str3.getData() << endl;

    char* pData2 = "Data has been changed.";
    str3.setData(pData2);

    cout << str.getData() << endl;
    cout << str2.getData() << endl;
    cout << str3.getData() << endl;

    return 0;
}
</code>```

then I'm confused by the

```<code>char* pData = new char;
char* pData2 = new char[30];
</code>```

Am I right in the class implementation?
How can I tell the two different pointers?
Do I write the constructor and de-constructor function and the operator= correctly? if not, how to write them?

答:
Well, you have a ton of bugs. Just not in operator=. There you only have a pointless m_pData = nullptr;.

new char allocates a single char and new char[30] allocates an array of 30 chars. The pointer is the same and you have to know which of the two it is. Every new must be balanced by a delete and every new[] balanced by a delete[]. So best to never mix the two. Use new char[1].

Some notes for the rest of your code:

1) m_pData = str.m_pData; copies the address of the array so now 2 classes use the same array and the old array is never freed.

2) The commented out delete in the destructor is needed to prevent memory leacks but should be delete[]. But 1 makes that impossible.

3) test2 = "23"; uses incompatible pointer types. C strings are const and your compiler should have warned you about this.

4)  test2 = "23"; copies the addsress of the array overwriting the old value. The old array is a memory leak.

5) CMyString str(pData); causes the address of pData to be copied into your class. The delete[] in 2 would later try to free it but it was never allocated by new[]. The constructors and setData should realy copy the string like you do in operator=.

6) Have a look at std::move, std::uniq_ptr, std::shared_ptr.

Body:
I construct a class named CMyString, here is it:

class CMyString {
public:
    CMyString();
    CMyString(char* pData);
    CMyString(const CMyString& str);
    ~CMyString(void);

    char* getData();
    void setData(char* pData);

    CMyString& operator=(const CMyString& str);

private:
    char* m_pData;
};

    CMyString::CMyString() {
    m_pData = new char;
}

CMyString::CMyString(char* pData) {
//    m_pData = new char;
    m_pData = pData;
}

CMyString::CMyString(const CMyString& str) {
    // 为指针分配内存
//    m_pData = new char;
    // 拷贝值
    m_pData = str.m_pData;
}

CMyString::~CMyString(void) {
//    delete m_pData;
}

CMyString& CMyString::operator=(const CMyString& str) {
    if (this == &str)
        return *this;

    delete m_pData;
    m_pData = nullptr;
    m_pData = new char[strlen(str.m_pData) + 1];
    strcpy(m_pData, str.m_pData);

    return *this;
}

char* CMyString::getData() {
    return m_pData;
}

void CMyString::setData(char *pData) {
    m_pData = pData;
}

And here is my main.cpp:

#include <iostream>
#include "CMyString.h"

using std::cout;
using std::endl;

int main() {
    char* pData = "What are you worrying about?";
    std::cout << pData << std::endl;

    cout << strlen(pData) << endl;
    char* test = new char[30];
    cout << sizeof(test) << endl;
    char* test2 = new char;
    test2 = "23";
    cout << test2 << endl;

    strcpy(test, pData);

    cout << endl << test << endl << endl;

    CMyString str(pData);
    std::cout << str.getData() << std::endl;

    CMyString str2, str3;
    str3 = str2 = str;

    std::cout << str3.getData() << endl;

    char* pData2 = "Data has been changed.";
    str3.setData(pData2);

    cout << str.getData() << endl;
    cout << str2.getData() << endl;
    cout << str3.getData() << endl;

    return 0;
}

then I'm confused by the

char* pData = new char;
char* pData2 = new char[30];

Am I right in the class implementation?
How can I tell the two different pointers?
Do I write the constructor and de-constructor function and the operator= correctly? if not, how to write them?


问:
How to Query between a date range in MySQL

I'm querying

```<code>SELECT * FROM tempLog WHERE date BETWEEN '23-03-2017' AND '02-04-2017'
</code>```

and the result is null. How to fix this. But

```<code>SELECT * FROM tempLog WHERE date BETWEEN '23-03-2017' AND '30-03-2017'
</code>```

giving me the correct result.
Note:- tempLog is the table name.

答: According to the documentation, you're supposed to use this format when writing a date: 'YYYY-MM-DD' (although it says it may accept 'YYYYMMDD' or even YYYYMMDD in some contexts).

Body:
I'm querying

SELECT * FROM tempLog WHERE date BETWEEN '23-03-2017' AND '02-04-2017'

and the result is null. How to fix this. But

SELECT * FROM tempLog WHERE date BETWEEN '23-03-2017' AND '30-03-2017'

giving me the correct result.
Note:- tempLog is the table name.


问:
P(R) represents a pattern drawn by Julia in R rows. The following pattern represents P(5)
I recently started learning  mysql and got stuck in this question:

P(R) represents a pattern drawn by Julia in R rows. The following pattern represents P(5):
Write a query to print the pattern P(20).

the question

I have written the answer like this:

```<code>DELIMITER $$
BEGIN
DECLARE CH VARCHAR(255);
DECLARE CT INT DEFAULT 20;
SET CH = ' *';
WHILE CT>0 DO
    SELECT REPEAT(CH,CT);
    SET CT=CT-1;
    END WHILE
  END $$
DELIMITER ;
</code>```

Somehow it's not working..what's missing?

答:
You have multiple errors in your code. Try this:</p>

```<code>DROP PROCEDURE IF EXISTS `DoPattern`;
DELIMITER $$
CREATE PROCEDURE DoPattern()
BEGIN
    DECLARE CT INT(10) DEFAULT 20;
    DECLARE CH VARCHAR(256) DEFAULT " *";
    CREATE TEMPORARY TABLE `pattern` (`rowno` INT(2) UNSIGNED, `pattern_string` VARCHAR(50)) ENGINE=MEMORY;

    WHILE CT > 0 DO
        INSERT INTO `pattern` (`rowno`,`pattern_string`) VALUES (CT,REPEAT(CH,CT));
        SET CT = CT - 1;
    END WHILE;

    SELECT `pattern_string` FROM `pattern` ORDER BY `rowno` DESC;
    DROP TABLE `pattern`;
END$$
DELIMITER ;

CALL DoPattern();
</code>```

Body:
I recently started learning  mysql and got stuck in this question:

P(R) represents a pattern drawn by Julia in R rows. The following pattern represents P(5):
Write a query to print the pattern P(20).

the question

I have written the answer like this:

DELIMITER $$
BEGIN
DECLARE CH VARCHAR(255);
DECLARE CT INT DEFAULT 20;
SET CH = ' *';
WHILE CT>0 DO
    SELECT REPEAT(CH,CT);
    SET CT=CT-1;
    END WHILE
  END $$
DELIMITER ;

Somehow it's not working..what's missing?

Body:
You have multiple errors in your code. Try this:

DROP PROCEDURE IF EXISTS `DoPattern`;
DELIMITER $$
CREATE PROCEDURE DoPattern()
BEGIN
    DECLARE CT INT(10) DEFAULT 20;
    DECLARE CH VARCHAR(256) DEFAULT " *";
    CREATE TEMPORARY TABLE `pattern` (`rowno` INT(2) UNSIGNED, `pattern_string` VARCHAR(50)) ENGINE=MEMORY;

    WHILE CT > 0 DO
        INSERT INTO `pattern` (`rowno`,`pattern_string`) VALUES (CT,REPEAT(CH,CT));
        SET CT = CT - 1;
    END WHILE;

    SELECT `pattern_string` FROM `pattern` ORDER BY `rowno` DESC;
    DROP TABLE `pattern`;
END$$
DELIMITER ;

CALL DoPattern();


问:
Transfer WordPress from live server to localhost
I'm trying to transfer all my files from the remote server to my localhost. I've downloaded everything from ftp and exported the database(.gzip). I've logged in to my local phpmyadmin and changed the url in the 'wp_options' table.

My problem is that when I try to run it in the browser, it redirects to my live site.

Note: I've also deleted my .htaccess file thinking that it may have caused the redirection.

答: After export your DB to gzip, unpack the file. Replace all urls of your remote example.com with localsite.com. Pack edited to gzip again. Import it with phpmyadmin.</p>


问:
selenium C# Unable to locate element
I am having a trouble with Selenium. I am trying to open Google and search Selenium. Then to open the first page that appear, so I am doing this:

driver.FindElement(By.XPath("//*@id=\"rso\"]/div/div/div[1]/div/h3/a")).Click();

But it doesn't open the first url by XPath. It says: Unable to locate element
Can you help me? Thank you in advance!

答:
Try to wait until link is generated and clickable:</p>

```<code>WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
wait.Until(ExpectedConditions.ElementToBeClickable(By.XPath("//div[@class=\"rc\"]/h3/a"))).Click();
</code>```

Title: selenium C# Unable to locate element

Body:
Try to wait until link is generated and clickable:

WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
wait.Until(ExpectedConditions.ElementToBeClickable(By.XPath("//div[@class=\"rc\"]/h3/a"))).Click();


问:
Is it possible to create an application WITHOUT a framework?
I was just thinking. C# has Winforms/WPF, Java has Swing and other frameworks, C++ has QT and so on; is it possible to create an application without using a Framework?

Putting aside the practicality of it, I'm just curious. How would one create an application that Just Works(tm) without needing external frameworks?

答: Yes. How: in the way that the frameworks you mentioned are implemented.</p>

OwnerDisplayName: delete


问:
Program to find numbers with odd no of divisors
Given 2 integers L and R, you are expected to find the number of integers between L and R that have odd number of divisors.

Input Format :

First line contains a single integer T
, the number of test cases. Each of the next T lines contains two space separated integers Li and Ri, depicting the parameters of the ith test case.

Constraints

1≤ T ≤ 10000

1≤ L ≤ R ≤ 10^18

```<code>#include <stdio.h>

int main(void)
{
    int t;
    long int cnt,countj;
    scanf("%d",&t);
    long long int l[t], r[t];
    int i=0;
    for(i=0;i<t;i++){
        scanf("%d%d",&l[i],&r[i]);
        }

    int div[t];
    for(i=0;i<t;i++){
        //count[i]=0;
        cnt=0;
        for(int j=l[i]+1;j<r[i];j++){
            countj=0;
            for(int k=1;k<=j/2;k++){
                if(j%k==0)
                   countj++;
            }
            if ((countj%2)==0)
            cnt++;
        }
        printf("%ld\n",cnt);
    }
    return 0;
}
</code>```

This program takes too long to execute, especially for bigger numbers, how can it be optimized ?
And it doesent pass all the test cases, what may be error in the code?

答:
If the problem is indeed as you described, there a many ways you can improve performance, just one of them being below, but you have to understand the theory behind what you're trying to accomplish first.

Integers with odd numbers of divisors are always perfect squares. Given some number N, if X is a divisor there must be some corresponding Y such that XY=N holds true. They always come in pairs. The exception is a perfect square. In that case they number has some divisor W such that WW=N, and W is only counted as one divisor. Therefore N has an odd number of divisors.

So how does this help? Well, your stated task is to find all integers from L through R having an odd count of divisors. But we just showed that only perfect squares have such a property. Therefore, what that question is really asking is:

Find the number of perfect squares between two integers L and R.

One such algorithm is simply this:

Starting with L take the floating point square root of the test number

Square the root after converting to an appropriate integer type

If the square of the root results in the original number, you have a perfect square. Stop looping.

Otherwise, increment you test number and try again. Stop if you pass R or find a perfect square, whichever comes first.

If you found no perfect square, the answer is zero and you're done. If you found a perfect square, you will no longer need to loop incrementally across L and R. You have a starting point (a perfect root), and now you will loop by incrementally increasing that root until its square exceeds R. This will significantly reduce the number of iterations.

In the below code:

T  : the number of tests

L  : the first number in a test series

R  : the last number in a test series

N  : the number of odd-divisor values between L and R inclusive

sr : The running square-root of our discovery loops.

Code

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int main()
{
    unsigned int T = 0;
    if (scanf("%u", &T) != 1)
        return EXIT_FAILURE;

    while (T--)
    {
        unsigned int L, R, N=0, sr, i;
        if (scanf("%u %u", &L, &R) != 2)
            return EXIT_FAILURE;

        for (i=L; i<=R; ++i)
        {
            sr = sqrt(i);
            if (sr * sr == i)
                break;
        }

        if (i <= R)
            for (;sr*sr <= R; ++sr,++N);

        printf("%u\n", N);
    }

    return 0;
}
```

<p><strong>Input</strong></p>

<pre class="lang-none prettyprint-override"><code>5
1 2
10 100
100 1000
500 2500
1 262144
</code>```

Output

1
7
22
28
512
```

<p><strong>Performance</strong></p>

<p>This code performs well], considering how little of it there is. The resulting disassembly using clang 3.9.1 with <code>-x c -O2</code> is respectable.</p>

```.LC0:
        .string "%u"
.LC1:
        .string "%u %u"
.LC3:
        .string "%u\n"
main:
        push    rbp
        push    rbx
        xor     eax, eax
        mov     edi, OFFSET FLAT:.LC0
        mov     ebp, 1
        sub     rsp, 40
        lea     rsi, [rsp+20]
        mov     DWORD PTR [rsp+20], 0
        call    __isoc99_scanf
        cmp     eax, 1
        je      .L24
.L1:
        add     rsp, 40
        mov     eax, ebp
        pop     rbx
        pop     rbp
        ret
.L24:
        mov     ebp, eax
        mov     eax, DWORD PTR [rsp+20]
        lea     edx, [rax-1]
        test    eax, eax
        mov     DWORD PTR [rsp+20], edx
        je      .L25
.L3:
        lea     rdx, [rsp+28]
        lea     rsi, [rsp+24]
        xor     eax, eax
        mov     edi, OFFSET FLAT:.LC1
        call    __isoc99_scanf
        cmp     eax, 2
        jne     .L1
        mov     ebx, DWORD PTR [rsp+24]
        cmp     ebx, DWORD PTR [rsp+28]
        jbe     .L10
        jmp     .L11
.L26:
        add     ebx, 1
        cmp     DWORD PTR [rsp+28], ebx
        jb      .L11
.L10:
        pxor    xmm0, xmm0
        mov     eax, ebx
        pxor    xmm2, xmm2
        cvtsi2sdq       xmm0, rax
        ucomisd xmm2, xmm0
        sqrtsd  xmm1, xmm0
        jbe     .L8
        movsd   QWORD PTR [rsp+8], xmm1
        call    sqrt
        movsd   xmm1, QWORD PTR [rsp+8]
.L8:
        cvttsd2si       rax, xmm1
        mov     edx, eax
        mov     ecx, eax
        imul    edx, eax
        cmp     edx, ebx
        jne     .L26
        mov     edi, DWORD PTR [rsp+28]
        cmp     ebx, edi
        ja      .L11
.L12:
        add     eax, 1
        mov     edx, eax
        mov     esi, eax
        imul    edx, eax
        sub     esi, ecx
        cmp     edi, edx
        jnb     .L12
        mov     edi, OFFSET FLAT:.LC3
        xor     eax, eax
        call    printf
.L27:
        mov     eax, DWORD PTR [rsp+20]
        lea     edx, [rax-1]
        test    eax, eax
        mov     DWORD PTR [rsp+20], edx
        jne     .L3
.L25:
        xor     ebp, ebp
        jmp     .L1
.L11:
        xor     esi, esi
        mov     edi, OFFSET FLAT:.LC3
        xor     eax, eax
        call    printf
        jmp     .L27
```

That's it. It could be made even faster, but so long as it meets your performance needs, it probably isn't worth more effort (so I hope it does) Normally questions about odd-divisors also request the one number with the lowest (or highest) number of divisors, which make it much more complicated. The question you stated does not ask that, and thus the problem reduces down very well.

Body:
Given 2 integers L and R, you are expected to find the number of integers between L and R that have odd number of divisors.

Input Format :

First line contains a single integer T
, the number of test cases. Each of the next T lines contains two space separated integers Li and Ri, depicting the parameters of the ith test case.

Constraints

1≤ T ≤ 10000

1≤ L ≤ R ≤ 10^18

#include <stdio.h>

int main(void)
{
    int t;
    long int cnt,countj;
    scanf("%d",&t);
    long long int l[t], r[t];
    int i=0;
    for(i=0;i<t;i++){
        scanf("%d%d",&l[i],&r[i]);
        }

    int div[t];
    for(i=0;i<t;i++){
        //count[i]=0;
        cnt=0;
        for(int j=l[i]+1;j<r[i];j++){
            countj=0;
            for(int k=1;k<=j/2;k++){
                if(j%k==0)
                   countj++;
            }
            if ((countj%2)==0)
            cnt++;
        }
        printf("%ld\n",cnt);
    }
    return 0;
}

This program takes too long to execute, especially for bigger numbers, how can it be optimized ?
And it doesent pass all the test cases, what may be error in the code?

Body:
If the problem is indeed as you described, there a many ways you can improve performance, just one of them being below, but you have to understand the theory behind what you're trying to accomplish first.

Integers with odd numbers of divisors are always perfect squares. Given some number N, if X is a divisor there must be some corresponding Y such that XY=N holds true. They always come in pairs. The exception is a perfect square. In that case they number has some divisor W such that WW=N, and W is only counted as one divisor. Therefore N has an odd number of divisors.

So how does this help? Well, your stated task is to find all integers from L through R having an odd count of divisors. But we just showed that only perfect squares have such a property. Therefore, what that question is really asking is:

Find the number of perfect squares between two integers L and R.

One such algorithm is simply this:

Starting with L take the floating point square root of the test number

Square the root after converting to an appropriate integer type

If the square of the root results in the original number, you have a perfect square. Stop looping.

Otherwise, increment you test number and try again. Stop if you pass R or find a perfect square, whichever comes first.

If you found no perfect square, the answer is zero and you're done. If you found a perfect square, you will no longer need to loop incrementally across L and R. You have a starting point (a perfect root), and now you will loop by incrementally increasing that root until its square exceeds R. This will significantly reduce the number of iterations.

In the below code:

T  : the number of tests

L  : the first number in a test series

R  : the last number in a test series

N  : the number of odd-divisor values between L and R inclusive

sr : The running square-root of our discovery loops.

Code

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int main()
{
    unsigned int T = 0;
    if (scanf("%u", &T) != 1)
        return EXIT_FAILURE;

    while (T--)
    {
        unsigned int L, R, N=0, sr, i;
        if (scanf("%u %u", &L, &R) != 2)
            return EXIT_FAILURE;

        for (i=L; i<=R; ++i)
        {
            sr = sqrt(i);
            if (sr * sr == i)
                break;
        }

        if (i <= R)
            for (;sr*sr <= R; ++sr,++N);

        printf("%u\n", N);
    }

    return 0;
}

Input

5
1 2
10 100
100 1000
500 2500
1 262144

Output

1
7
22
28
512

Performance

This code performs well], considering how little of it there is. The resulting disassembly using clang 3.9.1 with -x c -O2 is respectable.

.LC0:
        .string "%u"
.LC1:
        .string "%u %u"
.LC3:
        .string "%u\n"
main:
        push    rbp
        push    rbx
        xor     eax, eax
        mov     edi, OFFSET FLAT:.LC0
        mov     ebp, 1
        sub     rsp, 40
        lea     rsi, [rsp+20]
        mov     DWORD PTR [rsp+20], 0
        call    __isoc99_scanf
        cmp     eax, 1
        je      .L24
.L1:
        add     rsp, 40
        mov     eax, ebp
        pop     rbx
        pop     rbp
        ret
.L24:
        mov     ebp, eax
        mov     eax, DWORD PTR [rsp+20]
        lea     edx, [rax-1]
        test    eax, eax
        mov     DWORD PTR [rsp+20], edx
        je      .L25
.L3:
        lea     rdx, [rsp+28]
        lea     rsi, [rsp+24]
        xor     eax, eax
        mov     edi, OFFSET FLAT:.LC1
        call    __isoc99_scanf
        cmp     eax, 2
        jne     .L1
        mov     ebx, DWORD PTR [rsp+24]
        cmp     ebx, DWORD PTR [rsp+28]
        jbe     .L10
        jmp     .L11
.L26:
        add     ebx, 1
        cmp     DWORD PTR [rsp+28], ebx
        jb      .L11
.L10:
        pxor    xmm0, xmm0
        mov     eax, ebx
        pxor    xmm2, xmm2
        cvtsi2sdq       xmm0, rax
        ucomisd xmm2, xmm0
        sqrtsd  xmm1, xmm0
        jbe     .L8
        movsd   QWORD PTR [rsp+8], xmm1
        call    sqrt
        movsd   xmm1, QWORD PTR [rsp+8]
.L8:
        cvttsd2si       rax, xmm1
        mov     edx, eax
        mov     ecx, eax
        imul    edx, eax
        cmp     edx, ebx
        jne     .L26
        mov     edi, DWORD PTR [rsp+28]
        cmp     ebx, edi
        ja      .L11
.L12:
        add     eax, 1
        mov     edx, eax
        mov     esi, eax
        imul    edx, eax
        sub     esi, ecx
        cmp     edi, edx
        jnb     .L12
        mov     edi, OFFSET FLAT:.LC3
        xor     eax, eax
        call    printf
.L27:
        mov     eax, DWORD PTR [rsp+20]
        lea     edx, [rax-1]
        test    eax, eax
        mov     DWORD PTR [rsp+20], edx
        jne     .L3
.L25:
        xor     ebp, ebp
        jmp     .L1
.L11:
        xor     esi, esi
        mov     edi, OFFSET FLAT:.LC3
        xor     eax, eax
        call    printf
        jmp     .L27

That's it. It could be made even faster, but so long as it meets your performance needs, it probably isn't worth more effort (so I hope it does) Normally questions about odd-divisors also request the one number with the lowest (or highest) number of divisors, which make it much more complicated. The question you stated does not ask that, and thus the problem reduces down very well.


问:
Merging http observables using forkjoin
I'm trying to avoid nested observables by using forkjoin. The current (nested) version looks like this:

```<code>  this.http.get('https://testdb1.firebaseio.com/.json').map(res => res.json()).subscribe(data_changes => {
    this.http.get('https://testdb2.firebaseio.com/.json').map(res => res.json()).subscribe(data_all => {
      /* Do this once resolved */
      this.platform.ready().then(() => {
        this.storage.set('data_changes', data_changes);
        this.storage.set('data_all', data_all);
        document.getElementById("chart").innerHTML = "";
        this.createChart();
      });
    });
  },

    err => {
      this.platform.ready().then(() => {
        console.log("server error 2");
        document.getElementById("chart").innerHTML = "";
        this.createChart();
      });
    });
  }
</code>```

I can rewrite the first part as:

```<code>Observable.forkJoin(
  this.http.get('https://testdb1.firebaseio.com/.json').map((res: Response) => res.json()),
  this.http.get('https://testdb2.firebaseio.com/.json').map((res: Response) => res.json())
)
</code>```

But i'm not sure how I would then add the .subscribe method to access both data_changes and data_all.

Looking at another example, I know it should look something like .subscribe(res => this.combined = {friends:res[0].friends, customer:res[1]});, but i'm not sure how to adapt this to my example.

答:
Try to use combineLatest instead of forkJoin :

With combineLatest :

```<code>const combined = Observable.combineLatest(
  this.http.get('https://testdb1.firebaseio.com/.json').map((res: Response) => res.json()),
  this.http.get('https://testdb2.firebaseio.com/.json').map((res: Response) => res.json())
)

combined.subscribe(latestValues => {
    const [ data_changes , data_all ] = latestValues;
    console.log( "data_changes" , data_changes);
    console.log( "data_all" , data_all);
});
</code>```

You can also handle it by forkJoin , but forkJoin will return data when all calls are finished and return result , but in combineLatest When any observable emits a value, emit the latest value from each.

With forkJoin :

```<code>const combined = Observable.forkJoin(
  this.http.get('https://testdb1.firebaseio.com/.json').map((res: Response) => res.json()),
  this.http.get('https://testdb2.firebaseio.com/.json').map((res: Response) => res.json())
)

combined.subscribe(latestValues => {
    const [ data_changes , data_all ] = latestValues;
    console.log( "data_changes" , data_changes);
    console.log( "data_all" , data_all);
});
</code>```

Call both and check the console log , you will get idea.

Title: Merging http observables using forkjoin

Body:
I'm trying to avoid nested observables by using forkjoin. The current (nested) version looks like this:

  this.http.get('https://testdb1.firebaseio.com/.json').map(res => res.json()).subscribe(data_changes => {
    this.http.get('https://testdb2.firebaseio.com/.json').map(res => res.json()).subscribe(data_all => {
      /* Do this once resolved */
      this.platform.ready().then(() => {
        this.storage.set('data_changes', data_changes);
        this.storage.set('data_all', data_all);
        document.getElementById("chart").innerHTML = "";
        this.createChart();
      });
    });
  },

    err => {
      this.platform.ready().then(() => {
        console.log("server error 2");
        document.getElementById("chart").innerHTML = "";
        this.createChart();
      });
    });
  }

I can rewrite the first part as:

Observable.forkJoin(
  this.http.get('https://testdb1.firebaseio.com/.json').map((res: Response) => res.json()),
  this.http.get('https://testdb2.firebaseio.com/.json').map((res: Response) => res.json())
)

But i'm not sure how I would then add the .subscribe method to access both data_changes and data_all.

Looking at another example, I know it should look something like .subscribe(res => this.combined = {friends:res[0].friends, customer:res[1]});, but i'm not sure how to adapt this to my example.

Body:
Try to use combineLatest instead of forkJoin :

With combineLatest :

const combined = Observable.combineLatest(
  this.http.get('https://testdb1.firebaseio.com/.json').map((res: Response) => res.json()),
  this.http.get('https://testdb2.firebaseio.com/.json').map((res: Response) => res.json())
)

combined.subscribe(latestValues => {
    const [ data_changes , data_all ] = latestValues;
    console.log( "data_changes" , data_changes);
    console.log( "data_all" , data_all);
});

You can also handle it by forkJoin , but forkJoin will return data when all calls are finished and return result , but in combineLatest When any observable emits a value, emit the latest value from each.

With forkJoin :

const combined = Observable.forkJoin(
  this.http.get('https://testdb1.firebaseio.com/.json').map((res: Response) => res.json()),
  this.http.get('https://testdb2.firebaseio.com/.json').map((res: Response) => res.json())
)

combined.subscribe(latestValues => {
    const [ data_changes , data_all ] = latestValues;
    console.log( "data_changes" , data_changes);
    console.log( "data_all" , data_all);
});

Call both and check the console log , you will get idea.


问:
OAuth2 Login (Not Authorization)
I have implemented an OAuth2 register workflow (in Java) according to rfc6749

I'm using GitLab as OAuth2 Provider.

After the user granted access to my application for his account, I get an OAuth Token (along with refresh token and other stuff), I am able to make API requests on behalf of the user, so this is working fine.

This way I can get the users e-mail adress which I use to create an internal user.

My questions are:

Is it practice to issue a token that is generated by my application for the user (along with the OAuthToken) or should I just use the token that has been issued by the OAauth Provider? (My App also has local auth with bearer tokens). This token will be used for further API - CLIENT communication (stored in Angular2 local storage as bearer)

How to do login only? When a OAuth User accesses my web service, how do I know that this user is a OAuth User and which OAuth Token belongs to him? How can the user login without providing e-mail or password? (The user has no password) I guess I have to redirect him to the OAuth Provider again, but I don't want my user to grant access everytime he logs in.

答:
Answer 1:

Though you can use the token provided by OAuth provider, you SHOULD NOT use it considering the risk that may arise exposing it to the public.

Instead you should securely save the token provided by OAuth provider into the database and use another token for authentication of further api calls. (you could use JWT)

Answer 2:

There are two types of systems

Which always uses OAuth provider for identifying user. (Ex. Tinder)

Which provides both OAuth Login and Traditional login/signup. (Ex. Quora, Instagram)

If you want your application to follow 2nd approach, you should ask the user to create password for the first time when the user logs in using OAuth provider.

This will allow the user to log into your application by both methods, traditional as well as OAuth

Title: OAuth2 Login (Not Authorization)


问:
ASP.NET MVC Check state for just some properties
I'm new to MVC and I'm facing this problem.

I'm designing a view that allows user to modify their profile and password in 2 different forms.

This is my main action:

```<code>public ActionResult ModifyAccount()
{
    User user = this._userManager.FindById(User.Identity.GetUserId());
    ViewBag.User = user;
    return View(new AccountViewModel
    {
        User = user
    });
}
</code>```

In my ModifyAccount view, i have 2 form:

```<code>@using (Html.BeginForm("ModifyPassword", "Account", FormMethod.Post))
{
    // Change password
}

@using (Html.BeginForm("ModifyProfile", "Account", FormMethod.Post))
{
    // Change profile
}
</code>```

And this is my Model

```<code>public class AccountViewModel
    {
        public User User { get; set; } // For change profile

        // For change password
        [Display(Name = "Mật khẩu cũ")]
        public string OldPassword { get; set; }
        [Display(Name = "Mật khẩu mới")]
        public string NewPassword { get; set; }
        [Display(Name = "Xác nhận mật khẩu mới")]
        [Compare("NewPassword", ErrorMessage = "Mật khẩu xác nhận không trùng khớp")]
        public string NewPasswordConfirm { get; set; }
    }
</code>```

I know that when we use ModelState.IsValid, the whole model will be validated. What I want is if the user submits the ModifyPassword form, only 3 properties OldPassword, NewPassword, NewPasswordConfirm will be validated. Please help, thank you!

答:
Create a ViewModel with the 3 properties OldPassword, NewPassword, NewPasswordConfirm and receive that as the parameter in the Post version of ModifyPassword:

```<code>Class ModifyPasswordView
{
    public string OldPassword {get;set;}
    public string NewPassword {get;set;}
    public bool NewPasswordConfirm {get;set;}
}

[HttpPost]
public ActionResult ModifyPassword( ModifyPasswordView passwordView)
{
     if ( ModelState.IsValid )
     {
        ...
     }
}
</code>```

The modelstate check above only looks at the 3 fields in the ModifyPasswordView model, regardless of the fields present in the form

Body:
I'm new to MVC and I'm facing this problem.

I'm designing a view that allows user to modify their profile and password in 2 different forms.

This is my main action:

public ActionResult ModifyAccount()
{
    User user = this._userManager.FindById(User.Identity.GetUserId());
    ViewBag.User = user;
    return View(new AccountViewModel
    {
        User = user
    });
}

In my ModifyAccount view, i have 2 form:

@using (Html.BeginForm("ModifyPassword", "Account", FormMethod.Post))
{
    // Change password
}

@using (Html.BeginForm("ModifyProfile", "Account", FormMethod.Post))
{
    // Change profile
}

And this is my Model

public class AccountViewModel
    {
        public User User { get; set; } // For change profile

        // For change password
        [Display(Name = "Mật khẩu cũ")]
        public string OldPassword { get; set; }
        [Display(Name = "Mật khẩu mới")]
        public string NewPassword { get; set; }
        [Display(Name = "Xác nhận mật khẩu mới")]
        [Compare("NewPassword", ErrorMessage = "Mật khẩu xác nhận không trùng khớp")]
        public string NewPasswordConfirm { get; set; }
    }

I know that when we use ModelState.IsValid, the whole model will be validated. What I want is if the user submits the ModifyPassword form, only 3 properties OldPassword, NewPassword, NewPasswordConfirm will be validated. Please help, thank you!

Body:
Create a ViewModel with the 3 properties OldPassword, NewPassword, NewPasswordConfirm and receive that as the parameter in the Post version of ModifyPassword:

Class ModifyPasswordView
{
    public string OldPassword {get;set;}
    public string NewPassword {get;set;}
    public bool NewPasswordConfirm {get;set;}
}

[HttpPost]
public ActionResult ModifyPassword( ModifyPasswordView passwordView)
{
     if ( ModelState.IsValid )
     {
        ...
     }
}

The modelstate check above only looks at the 3 fields in the ModifyPasswordView model, regardless of the fields present in the form


问:
maintain different versions of the code simultaneously using git
I got a code that I'm required to optimize. I would like to maintain a set of versions of the code (each version can be described as a composition of some features, optimizations) simultaneously. Eventually, I'll decide which version is the best one. I do not want to merge these versions into fewer versions. However, I would like to be able to make a (minor) modification to a (big) source file which may divert across the versions and I want this modification to write through more than one (possibly all) versions. How can I achieve that with git?

For example let us consider 3 versions: v1, v2, v3 and source code file source.cpp which has lots of code that is different across all versions but class A method aMethod() is identical. I would like to update the method and write the update to versions v1 and v2 only.

How can I do that?

If I modify source.cpp, for example, in v1, than merge it to v2 there will be a merge conflict (because source.cpp is different in v1, v2). Is there any way to avoid the conflict? If not, what is the best way to deal with the merge conflict int this case?
By the way, I don't want to increase code granularity so that the aMethod() will be placed in a dedicated file, because there is already lots of source code written and there will be too much overhead for doing this for any such modification that I describe.

Thanks in advance,

Daniel

答: If the optimizations you're making are mostly independent of each other, you could branch for each individual optimization from your starting point, and when you want to test some combination, make another branch from the starting point and do an octopus merge of the desired optimizations.</p>


问:
Combine 2 lists in python such that elements at the corresponding index are together
I have two lists like:

```<code>listone = [1, 2, 3]
listtwo = [4, 5, 6]
</code>```

I would like to combine them to get:

```<code>l = [1, 4, 2, 5, 3, 6]
</code>```

How can I do this without using loops?

答:
You can use numpy (as here)</p>

```<code>import numpy as np

listone = [1, 2, 3]
listtwo = [4, 5, 6]

l=np.empty((len(listone)+len(listtwo)))
l[0::2]=listone
l[1::2]=listtwo

print l
>>> l = [ 1.  4.  2.  5.  3.  6.]
</code>```

Body:
I have two lists like:

listone = [1, 2, 3]
listtwo = [4, 5, 6]

I would like to combine them to get:

l = [1, 4, 2, 5, 3, 6]

How can I do this without using loops?

Body:
You can use numpy (as here)

import numpy as np

listone = [1, 2, 3]
listtwo = [4, 5, 6]

l=np.empty((len(listone)+len(listtwo)))
l[0::2]=listone
l[1::2]=listtwo

print l
>>> l = [ 1.  4.  2.  5.  3.  6.]


问:
Porting a Visual C++ project to C#
I got my hands on some well documented C++ code that's about 1KLOC. It would take me a significant amount of time to port this line by line and debug the results, so I'm wondering if there are tools or ways to do it faster, and I have questions in case I have to do it fully manually.

Specific questions:

Does C# also support overriding operators like * and +?

What to do with the C++ memory management code like alloc() and free()?

How to identify functions used from <stdio.h>, <conio.h> and <math.h>?

How to find replacements to such system functions?

Does C# have any special/open source libraries that provide such functions?

No graphics libraries have been used, its purely command line based.

答:
You will need to do it manually, and 1KLOC isn't much.

However, you will need to learn C#.

To answer your questions:

Yes

Depending on what you're doing, probably List<T>

I don't know what you're asking

Look in the .Net Framework class library on MSDN

Yes

Title: Porting a Visual C++ project to C#


问:
Getting original $index of ng-repeat with toArray and groupBy
I have 2 ng-repeats with a toArray and grouptBy in order to show the array grouped in Sections, with each repeating type as the Section header:

```<code><div ng-repeat="feed in feeds | groupBy:'type' | toArray:true">
  <section layout="row" layout-sm="column" layout-align="center" layout-wrap>
    <div>{{feed.$key}}</div>
    <md-button class="md-raised" ng-class="{'md-primary': !item.hide}"
          ng-click="toggleFeed($index)" ng-repeat="item in feed">
      {{item.name}}
    </md-button>
  </section>
</code>```

I am trying to get the original $index so I can access $scope.feeds faster (using $scope.feeds[$index]).

Right now $index gives me the index within the second loop and $parent.$index gives me the index of the parents (first) loop, but I am trying to get the original index when clicking on the child.

Any ideas?

答:
As already explained in the comments its much better to parse the selected object instead of the $index. In that way you don't need to struggle with your index/object/array changes (e.g. filter or sort).

The good way:

```<code><div ng-repeat="feed in feeds | groupBy:'type' | toArray:true">
    <section layout="row" layout-sm="column" layout-align="center" layout-wrap>
        <div>{{feed.$key}}</div>
        <md-button class="md-raised" ng-class="{'md-primary': !item.hide}"
                   ng-click="toggleFeed(item)" ng-repeat="item in feed">
            {{item.name}}
        </md-button>
    </section>
</div>
</code>```

The worst way:

Keeping the original index is only possible with an unnecessary iteration. You need to prepare your data before parsing it into your view scope. I would no recommend to do this because it's not that performant. Keep it simple and parse your object into your toggleFeed() function.

```<code>$scope.data = [{
    someAttribute: 'value'
},{
    someAttribute: 'value'
},{
    someAttribute: 'value'
},{
    someAttribute: 'value'
},{
    someAttribute: 'value'
},{
    someAttribute: 'value'
},{
    someAttribute: 'value'
}];

$scope.data.forEach(function(item, index) {
    $scope.data[index].originalIndex = index;
});

$scope.feeds = $scope.data;
</code>```

In that way you are able to parse to original index to your function:

```<code><div ng-repeat="feed in feeds | groupBy:'type' | toArray:true">
    <section layout="row" layout-sm="column" layout-align="center" layout-wrap>
        <div>{{feed.$key}}</div>
        <md-button class="md-raised" ng-class="{'md-primary': !item.hide}"
                   ng-click="toggleFeed(feed.originalIndex)" ng-repeat="item in feed">
            {{item.name}}
        </md-button>
    </section>
</div>
</code>```

The first approach is simple and much more performant.

Body:
I have 2 ng-repeats with a toArray and grouptBy in order to show the array grouped in Sections, with each repeating type as the Section header:

{{feed.$key}}

    <md-button class="md-raised" ng-class="{'md-primary': !item.hide}"
          ng-click="toggleFeed($index)" ng-repeat="item in feed">
      {{item.name}}
    </md-button>

I am trying to get the original $index so I can access $scope.feeds faster (using $scope.feeds[$index]).

Right now $index gives me the index within the second loop and $parent.$index gives me the index of the parents (first) loop, but I am trying to get the original index when clicking on the child.

Any ideas?

Body:
As already explained in the comments its much better to parse the selected object instead of the $index. In that way you don't need to struggle with your index/object/array changes (e.g. filter or sort).

The good way:

<div ng-repeat="feed in feeds | groupBy:'type' | toArray:true">
    <section layout="row" layout-sm="column" layout-align="center" layout-wrap>
        <div>{{feed.$key}}</div>
        <md-button class="md-raised" ng-class="{'md-primary': !item.hide}"
                   ng-click="toggleFeed(item)" ng-repeat="item in feed">
            {{item.name}}
        </md-button>
    </section>
</div>

The worst way:

Keeping the original index is only possible with an unnecessary iteration. You need to prepare your data before parsing it into your view scope. I would no recommend to do this because it's not that performant. Keep it simple and parse your object into your toggleFeed() function.

$scope.data = [{
    someAttribute: 'value'
},{
    someAttribute: 'value'
},{
    someAttribute: 'value'
},{
    someAttribute: 'value'
},{
    someAttribute: 'value'
},{
    someAttribute: 'value'
},{
    someAttribute: 'value'
}];

$scope.data.forEach(function(item, index) {
    $scope.data[index].originalIndex = index;
});

$scope.feeds = $scope.data;

In that way you are able to parse to original index to your function:

<div ng-repeat="feed in feeds | groupBy:'type' | toArray:true">
    <section layout="row" layout-sm="column" layout-align="center" layout-wrap>
        <div>{{feed.$key}}</div>
        <md-button class="md-raised" ng-class="{'md-primary': !item.hide}"
                   ng-click="toggleFeed(feed.originalIndex)" ng-repeat="item in feed">
            {{item.name}}
        </md-button>
    </section>
</div>

The first approach is simple and much more performant.


问:
Populate drop-down list in HTML using JSON data
I'm a student and very new to code. I've created a drop-down list using HTML and CSS, and I'm trying to populate it using data from JSON. This is my HTML code:

```<code>    <div class="dropdown">
  <button class="dropbtn">Choose your area</button>
  <div class="dropdown-content">
    <a href="#">Place 1</a>
    <a href="#">Place 2</a>
    <a href="#">Place 3</a>

  </div>
</div>
</code>```

I'm trying to replace 'Place 1', 'Place 2' etc with about 150 real place names. These are in JSON:

```<code>    "areaNames": [
 {
   "A": 1,
   "B": "Barking & Dagenham"
 },
 {
   "A": 2,
   "B": "Barnet"
 },
</code>```

and so on. How do I pull in the place names from JSON to be in the place of  'Place 1', 'Place 2' etc? I've tried following the advice in response to similar tutorials but that seems to give me a list of several separate drop-down boxes rather than a simple list of places.

Thanks for your help.

答:
I don't see a dropdown in the code.

You could use jQuery, which is a Javascript library, to accomplish your goal.

HTML:

```<code><select id="sel">

</select>
</code>```

JavaScript:

```<code>$(function() {
    var data = [
        {
        "id": "1",
        "name": "test1"},
    {
        "id": "2",
        "name": "test2"}
    ];
    $.each(data, function(i, option) {
        $('#sel').append($('<option/>').attr("value", option.id).text(option.name));
    });
})
</code>```

Body:
I'm a student and very new to code. I've created a drop-down list using HTML and CSS, and I'm trying to populate it using data from JSON. This is my HTML code:

  <button class="dropbtn">Choose your area</button>

    Place 1
    Place 2
    Place 3

I'm trying to replace 'Place 1', 'Place 2' etc with about 150 real place names. These are in JSON:

    "areaNames": [
 {
   "A": 1,
   "B": "Barking & Dagenham"
 },
 {
   "A": 2,
   "B": "Barnet"
 },

and so on. How do I pull in the place names from JSON to be in the place of  'Place 1', 'Place 2' etc? I've tried following the advice in response to similar tutorials but that seems to give me a list of several separate drop-down boxes rather than a simple list of places.

Thanks for your help.

Body:
I don't see a dropdown in the code.

You could use jQuery, which is a Javascript library, to accomplish your goal.

HTML:

<select id="sel">

</select>

JavaScript:

$(function() {
    var data = [
        {
        "id": "1",
        "name": "test1"},
    {
        "id": "2",
        "name": "test2"}
    ];
    $.each(data, function(i, option) {
        $('#sel').append($('<option/>').attr("value", option.id).text(option.name));
    });
})


问:
Getting value of internal div when outside div is clicked
I have the following: A bunch of button div's which each have unique info

```<code><div class="button">
  <div id="first">
      Johny
  </div>
  <div id="second">
      Dog
  </div>
  <div id="third">
      Pasta
  </div>
</div>
<div class="button">
  <div id="first">
      Bob
  </div>
  <div id="second">
      Cat
  </div>
  <div id="third">
      Noodles
  </div>
</div>
   .
   .
   .
</code>```

I'm trying to make it so that when one of these buttons is clicked, i can check the values of the inner divs.

For instance

```<code>$('.button').on('click', function () {
     // Check to see if the text of the 'first' div is
     // johnny or bob or something else
});
</code>```

答: Try $(this).children(":first").text() to get fist div's text

Body:
I have the following: A bunch of button div's which each have unique info

      Johny

      Dog

      Pasta

      Bob

      Cat

      Noodles

   .
   .
   .

I'm trying to make it so that when one of these buttons is clicked, i can check the values of the inner divs.

For instance

$('.button').on('click', function () {
     // Check to see if the text of the 'first' div is
     // johnny or bob or something else
});


问:
I have a query related to Computer Architecture
20% of the total instructions in an application are multiplies. A new processor cuts the CPI for
multiplies from 10 to 5 but increases the cycle time by 20%. All other instructions take 1 cycle
each to process.
What is the speedup of the new processor compared to the old one?</p>

答:
In order to calculate normal CPI:

```<code>CPI = (SIGMA(Intruction_Count*Instruction_Precentage)/Total_Instructions)*Cycle_Length
</code>```

Calculating the old cpi we get:

```<code>CPI_OLD= ( 10*0.2 + 1*0.8 ) * 1 = 2.8
</code>```

Adjusting for the new changes we get:

```<code>CPI_NEW = (5*0.2 + 1*0.8) * 1.2 = 2.16

Speedup = CPI_NEW/CPI_OLD = 1.3
</code>```

Body:
In order to calculate normal CPI:

CPI = (SIGMA(Intruction_Count*Instruction_Precentage)/Total_Instructions)*Cycle_Length

Calculating the old cpi we get:

CPI_OLD= ( 10*0.2 + 1*0.8 ) * 1 = 2.8

Adjusting for the new changes we get:

CPI_NEW = (5*0.2 + 1*0.8) * 1.2 = 2.16

Speedup = CPI_NEW/CPI_OLD = 1.3


问:
Alerting when heartbeat not received
I've got an Application Insights log being written to by a Windows Service.  Is it possible to set an alert for inactivity; for instance "If not been written to in the last 15 minutes, activate an alert"?</p>

答:
I'm afraid there isn't such an option out of the box.

What I would recommend doing is firing your custom metric for Keep Alive with a value of 1 every so-and-so minutes, and define a custom alert (see here) on it in case the value drops below some threshold.

Title: Alerting when heartbeat not received


答:
```<code><script>
    $('.button').on('click', function () {
       if ($(this).find("#first").html().trim() == "Johny") {
           console.log("The first div is Johny");
       } else if ($(this).find("#first").html().trim() == "Bob") {
           console.log("The first div is Bob");
       }
    });
</script>
</code>```

Title: Getting value of internal div when outside div is clicked


答: From a Windows point of view, you would register your window with Windows, then listen to window messages and react as required. Everything would be up to you - from drawing the window to building controls.</p>

Title: Is it possible to create an application WITHOUT a framework?

Body:
I was just thinking. C# has Winforms/WPF, Java has Swing and other frameworks, C++ has QT and so on; is it possible to create an application without using a Framework?

Putting aside the practicality of it, I'm just curious. How would one create an application that Just Works(tm) without needing external frameworks?


问:
I want to make datePicker on IOS by swift
all
I am a new developer on IOS. nowdays I study Swift by books.
there are some trouble. I use swift3 but the book consists of swift2.
so I don't know what is wrong code.
could you help me?
thanks you for reading and helping me.

this is datacode.

```<code>import UIKit

class ViewController: UIViewController {

    let timeSelector: Selector = #selector(ViewController.updateTime)
    let interval = 1.0
    var count = 0
    @IBOutlet weak var IbICurrentTime: UILabel!
    @IBOutlet weak var IbIPickTime: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        Timer.scheduledTimer(withTimeInterval: interval, repeats: true, block: timeSelector)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func changeDatePicker(_ sender: UIDatePicker) {
        let datePickerView = sender
        let formatter = DateFormatter()
        formatter.dateFormat = "YYYY-MM-dd HH:mm:ss EEE"
        IbIPickTime.text = "선택시간: " + formatter.string(from: datePickerView.date)
    }
    func updateTime() {
        IbICurrentTime.text = String(count)
        count = count+1
    }

}
</code>```

there are problem

```<code>Timer.scheduledTimer(withTimeInterval: interval, repeats: true, block: timeSelector)
    }
</code>```

i don't know what i have to input at "block"?

答:
"Block" is the Objective-C term of Swift's closure. The "Blocks" variant works like this:

```<code>Timer.scheduledTimer(timeInterval: interval, repeats: true, block: { timer in
    self.IbICurrentTime.text = String(self.count)
    self.count += 1
})
</code>```

You don't need to define a separate updateTime() function with the block syntax.

In Swift the above can be written more naturally as

```<code>Timer.scheduledTimer(timeInterval: interval, repeats: true) { _ in
    self.IbICurrentTime.text = String(self.count)
    self.count += 1
}
</code>```

If you want to use selectors, use scheduledTimer(timeInterval:target:selector:userInfo:repeats:) instead:

```<code>Timer.scheduledTimer(timeInterval: interval,
                     target: self,
                     selector: #selector(updateTime),
                     userInfo: nil,
                     repeats: true)
</code>```

Body:
all
I am a new developer on IOS. nowdays I study Swift by books.
there are some trouble. I use swift3 but the book consists of swift2.
so I don't know what is wrong code.
could you help me?
thanks you for reading and helping me.

this is datacode.

import UIKit

class ViewController: UIViewController {

    let timeSelector: Selector = #selector(ViewController.updateTime)
    let interval = 1.0
    var count = 0
    @IBOutlet weak var IbICurrentTime: UILabel!
    @IBOutlet weak var IbIPickTime: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        Timer.scheduledTimer(withTimeInterval: interval, repeats: true, block: timeSelector)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func changeDatePicker(_ sender: UIDatePicker) {
        let datePickerView = sender
        let formatter = DateFormatter()
        formatter.dateFormat = "YYYY-MM-dd HH:mm:ss EEE"
        IbIPickTime.text = "선택시간: " + formatter.string(from: datePickerView.date)
    }
    func updateTime() {
        IbICurrentTime.text = String(count)
        count = count+1
    }

}

there are problem

Timer.scheduledTimer(withTimeInterval: interval, repeats: true, block: timeSelector)
    }

i don't know what i have to input at "block"?

Body:
"Block" is the Objective-C term of Swift's closure. The "Blocks" variant works like this:

Timer.scheduledTimer(timeInterval: interval, repeats: true, block: { timer in
    self.IbICurrentTime.text = String(self.count)
    self.count += 1
})

You don't need to define a separate updateTime() function with the block syntax.

In Swift the above can be written more naturally as

Timer.scheduledTimer(timeInterval: interval, repeats: true) { _ in
    self.IbICurrentTime.text = String(self.count)
    self.count += 1
}

If you want to use selectors, use scheduledTimer(timeInterval:target:selector:userInfo:repeats:) instead:

Timer.scheduledTimer(timeInterval: interval,
                     target: self,
                     selector: #selector(updateTime),
                     userInfo: nil,
                     repeats: true)


问:
Get Hazelcast EntryExpiredListener only of one node (not all replicas)
I have requirement where i have a continuous flow of signals and i want to be informed if there has'nt been a signal for a certain amount of time.

right now i am adding every signal to a Hazelcast map and if it has not been updated for a certain amount of time the Hazelcast EntryExpiredListener fires.

So far, so good, but the EntryExpiredListener is called for every replica, so i am notified N times.

Is there a way to be only informed in the master node or only one replica?

I am aware that i am abusing HZ a bit and i am open for other ideas too.

答: I guess you use IMap::addEntryListener to register your expiry listener. Instead try to use IMap::addLocalEntryListener which will only be fired on the node currently owning the entry, which means you'll get one notification only.


问:
Java unable to read signed negative bytes written to standard out
I have 2 classes, the first is fed a binary string of 1s and 0s to standard in, and splits the string into sub strings of length 8 to convert to bytes, to write to standard out like so:

```<code>byte b = (byte)Integer.parseInt(byteString, 2);
System.out.write(b);
System.out.flush();
</code>```

The second is piped the output of the first, and ultimately will turn the bytes back into the long binary string, but currently I have it just doing this:

```<code>int next;
    while((next = System.in.read())!=-1){
    System.out.print(next); System.out.print(" ");
    System.out.flush();
}
</code>```

If I replace System.out.write(b); with System.out.print(b); System.out.print(" "); in the first class with some small sample input, the output is -80 -84 83 11 98 -116 53 -119 49 27 10 -80 -72 104 -123 0

If I pipe this output to the second class it outputs 63 63 83 11 98 63 53 63 49 27 13 10 63 63 104 63 0 13 10

Two things seem to be happening that I can't figure out why, System.in.read() is returning 63, which is ASCII for ? when reading bytes that would be signed negative, and a carriage return + new line has been added to the end. I am stumped for solutions, insight is greatly appreciated.

Note: I was running this in Windows 10 powershell, but on normal command line and in a linux terminal the behaviour was as expected, so problem is only in powershell!

答:
I do not use powershell, but a small test shows that pipes do change the output, like adding a newline and carriage return at the end, or converting the byte 0xA2 to 0x3f ('?').

Searching the net I found Understanding the Windows PowerShell Pipeline. I did not read more than the first paragraph, but that contains a hint:

Piping works virtually everywhere in Windows PowerShell. Although you see text on the screen, Windows PowerShell does not pipe text between commands. Instead, it pipes objects.

Maybe this helps: What exactly does the pipe | mean in PowerShell?

Body:
I have 2 classes, the first is fed a binary string of 1s and 0s to standard in, and splits the string into sub strings of length 8 to convert to bytes, to write to standard out like so:

byte b = (byte)Integer.parseInt(byteString, 2);
System.out.write(b);
System.out.flush();

The second is piped the output of the first, and ultimately will turn the bytes back into the long binary string, but currently I have it just doing this:

int next;
    while((next = System.in.read())!=-1){
    System.out.print(next); System.out.print(" ");
    System.out.flush();
}

If I replace System.out.write(b); with System.out.print(b); System.out.print(" "); in the first class with some small sample input, the output is -80 -84 83 11 98 -116 53 -119 49 27 10 -80 -72 104 -123 0

If I pipe this output to the second class it outputs 63 63 83 11 98 63 53 63 49 27 13 10 63 63 104 63 0 13 10

Two things seem to be happening that I can't figure out why, System.in.read() is returning 63, which is ASCII for ? when reading bytes that would be signed negative, and a carriage return + new line has been added to the end. I am stumped for solutions, insight is greatly appreciated.

Note: I was running this in Windows 10 powershell, but on normal command line and in a linux terminal the behaviour was as expected, so problem is only in powershell!


问:
Removing Entity Framework Reference from MVC project
Apologies if this has already been answered, but after 2 hours of research I am yet to find a definitive answer to this issue. Hopefully asking will yield results.

I'm "somewhat better than beginner" with MVC and EF, but I do understand overall application architecture. You see, for even greater Separation of Concerns and future planned changes, I'd like to decouple my MVC project from Entity Framework. Here's what I have so far:

Models project (full of well-annotated POCOs, as containers, no business logic)

DataAccess project (references my Models project, and Entity Framework)

MVC Web project (which references my Models project only)

I've already created my Repository pattern (in the DataAccess project), and tested it using a separate UnitTest project. It all works.

Problem is, the consumer (the UnitTest project, in this case) still needs a nuget reference to Entity Framework (same with the MVC Web project). When I remove the EF reference from my Test project (and instead hard-code my connection string when passing it into my DataAccess project), I get this error:

No Entity Framework provider found for the ADO.NET provider with
  invariant name 'System.Data.SqlClient'. Make sure the provider is
  registered in the 'entityFramework' section of the application config
  file.

How can I design this so I can completely remove the Entity Framework reference from the Repository consumer (UnitTest or MVC Web projects)? I want to do everything via my Repository, without the MVC project knowing anything about my ORM technology.

答:
You could try accessing your services via a Web API, which acts as a buffer to the Data Access Layer(s) and deals in View Models passed back and forth as anonymous JSON objects. Your front end (website) can then be totally isolated from the details behind the API and just act as a client to it.
Angular JS / Angular (2) lend themselves well to this approach as I'm sure many other client side technologies do.</p>


问:
Automapper: change map behavior based on presence of custom attribute
Is it possible to have AutoMapper look for an attribute on the source property?  I want AutoMapper to change how it maps the properties when those properties have a specific attribute set.</p>

答: There's nothing out of the box that allows you to do this. You will need to use reflection to read attributes for a given property and based on it's value adapt the mapping.</p>


问:
Check if a a formated table with style has no data
I have a formatted table with style named "Goals". And I have a counter to check how many rows has the table. Every time a row is added or deleted the counter updates.

```<code>Private Sub Worksheet_Change(ByVal Target As Range)

If Range("Goals").Rows(1) = Empty Then
    Worksheets("Counters").Cells(2, 1) = 0
Else
    Worksheets("Counters").Cells(2, 1) = Range("Goals").Rows.Count
End If

End Sub
</code>```

If the table is populated and all rows are deleted, which result in a table with no data, the condition Range("Goals").Rows(1) = Empty is evaluated as False and the counter doesn't update properly. However, if the table has one row of data, and the cell is erased manually (without deleted the row of the table) the counter does update correctly, and I dont know why.

I've tried evaluating the condition as Worksheets(GoalsList).Cells(2,1) = Empty, but it doesn't work either.

Please help, I don't know what to do!

答:
If you have an Excel Table with name "Table1" you can find the last row with data based on it's column 1 data like below...

```<code>Worksheets("Counters").Cells(2, 1) = ws.ListObjects("Table1").Range.Columns(1).Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
</code>```

If you have created a Named Range called "Golas" which refers to the whole Excel Table, you may try...

```<code>Worksheets("Counters").Cells(2, 1) = Range("Goals").Columns(1).Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
</code>```

To check if the table exists, try something like below...

```<code>Dim tbl As ListObject
On Error Resume Next
Set tbl = ws.ListObjects("Goals")
On Error GoTo 0
If Not tbl Is Nothing Then
    Worksheets("Counters").Cells(2, 1) = WorksheetFunction.CountA(ws.ListObjects("Goals").DataBodyRange.Columns(1).Cells)
End If
</code>```

Body:
I have a formatted table with style named "Goals". And I have a counter to check how many rows has the table. Every time a row is added or deleted the counter updates.

Private Sub Worksheet_Change(ByVal Target As Range)

If Range("Goals").Rows(1) = Empty Then
    Worksheets("Counters").Cells(2, 1) = 0
Else
    Worksheets("Counters").Cells(2, 1) = Range("Goals").Rows.Count
End If

End Sub

If the table is populated and all rows are deleted, which result in a table with no data, the condition Range("Goals").Rows(1) = Empty is evaluated as False and the counter doesn't update properly. However, if the table has one row of data, and the cell is erased manually (without deleted the row of the table) the counter does update correctly, and I dont know why.

I've tried evaluating the condition as Worksheets(GoalsList).Cells(2,1) = Empty, but it doesn't work either.

Please help, I don't know what to do!

Body:
If you have an Excel Table with name "Table1" you can find the last row with data based on it's column 1 data like below...

Worksheets("Counters").Cells(2, 1) = ws.ListObjects("Table1").Range.Columns(1).Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row

If you have created a Named Range called "Golas" which refers to the whole Excel Table, you may try...

Worksheets("Counters").Cells(2, 1) = Range("Goals").Columns(1).Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row

To check if the table exists, try something like below...

Dim tbl As ListObject
On Error Resume Next
Set tbl = ws.ListObjects("Goals")
On Error GoTo 0
If Not tbl Is Nothing Then
    Worksheets("Counters").Cells(2, 1) = WorksheetFunction.CountA(ws.ListObjects("Goals").DataBodyRange.Columns(1).Cells)
End If


问:
Transport polling error with Socket.Io
I'm getting a transport error when using socket.io v1.3.2. It's just meant to be a test for socket.io so I can familiarize myself with it.

I have a file app.js (taken directly from socket.io docs):

```<code>var app = require('http').createServer(handler);
var io = require('socket.io')(app);
var fs = require('fs');

app.listen(3000);

function handler (req, res) {
  fs.readFile(__dirname + '/index.html',
  function (err, data) {
    if (err) {
      res.writeHead(500);
      return res.end('Error loading index.html');
    }

    res.writeHead(200);
    res.end(data);
  });
}

io.on('connection', function (socket) {
  socket.emit('news', { hello: 'world' });
});
</code>```

And a file index.html:

```<code><!DOCTYPE html>
<html>
<head>
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title></title>
    <link rel="stylesheet" href="">
</head>
<body>
    <h1>Socket Test</h1>
    <script src="/socket.io/socket.io.js"></script>
    <script>
        var socket = io.connect('http://localhost');
        socket.on('news', function (data) {
            console.log(data);
        });
    </script>

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

In the console, I get the following error:

```<code>GET http://localhost/socket.io/?EIO=3&transport=polling&t=1422782880286-40
(index):1 XMLHttpRequest cannot load http://localhost/socket.io/?EIO=3&transport=polling&t=1422782880286-40. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 404.
socket.io.js:3715 engine.io-client:socket socket error {"type":"TransportError","description":0} +37ms
socket.io.js:1402 socket.io-client:manager connect_error +38ms
socket.io.js:1402 socket.io-client:manager reconnect attempt error +1ms
socket.io.js:1402 socket.io-client:manager will wait 5000ms before reconnect attempt +0ms
socket.io.js:3715 engine.io-client:socket socket close with reason: "transport error" +2ms
socket.io.js:3715 engine.io-client:polling transport not open - deferring close +1ms
socket.io.js:1402 socket.io-client:manager attempting reconnect +5s
socket.io.js:1402 socket.io-client:manager readyState closed +0ms
socket.io.js:1402 socket.io-client:manager opening http://localhost +0ms
socket.io.js:3715 engine.io-client:socket creating transport "polling" +5s
socket.io.js:3715 engine.io-client:polling polling +0ms
socket.io.js:3715 engine.io-client:polling-xhr xhr poll +0ms
socket.io.js:3715 engine.io-client:polling-xhr xhr open GET: http://localhost/socket.io/?EIO=3&transport=polling&t=1422782885332-41 +1ms
socket.io.js:3715 engine.io-client:polling-xhr xhr data null +0ms
socket.io.js:3715 engine.io-client:socket setting transport polling +1ms
socket.io.js:1402 socket.io-client:manager connect attempt will timeout after 20000 +3ms
</code>```

Does anyone know how to fix this error. I found this discussion, but have been unable to solve the problem.

答: by default, the localhost port is 80. you connected the client's socket to localhost without declaring the port. so it gave you the port 80 by default and your node server is listening to port 3000. in order for your client to connect to your server, you must declare the port which server listens. example: var socket = io.connect('http://localhost:3000');</p>

Title: Transport polling error with Socket.Io

Body:
I'm getting a transport error when using socket.io v1.3.2. It's just meant to be a test for socket.io so I can familiarize myself with it.

I have a file app.js (taken directly from socket.io docs):

var app = require('http').createServer(handler);
var io = require('socket.io')(app);
var fs = require('fs');

app.listen(3000);

function handler (req, res) {
  fs.readFile(__dirname + '/index.html',
  function (err, data) {
    if (err) {
      res.writeHead(500);
      return res.end('Error loading index.html');
    }

    res.writeHead(200);
    res.end(data);
  });
}

io.on('connection', function (socket) {
  socket.emit('news', { hello: 'world' });
});

And a file index.html:

<!DOCTYPE html>

    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title></title>
    <link rel="stylesheet" href="">

Socket Test

In the console, I get the following error:

GET http://localhost/socket.io/?EIO=3&transport=polling&t=1422782880286-40
(index):1 XMLHttpRequest cannot load http://localhost/socket.io/?EIO=3&transport=polling&t=1422782880286-40. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 404.
socket.io.js:3715 engine.io-client:socket socket error {"type":"TransportError","description":0} +37ms
socket.io.js:1402 socket.io-client:manager connect_error +38ms
socket.io.js:1402 socket.io-client:manager reconnect attempt error +1ms
socket.io.js:1402 socket.io-client:manager will wait 5000ms before reconnect attempt +0ms
socket.io.js:3715 engine.io-client:socket socket close with reason: "transport error" +2ms
socket.io.js:3715 engine.io-client:polling transport not open - deferring close +1ms
socket.io.js:1402 socket.io-client:manager attempting reconnect +5s
socket.io.js:1402 socket.io-client:manager readyState closed +0ms
socket.io.js:1402 socket.io-client:manager opening http://localhost +0ms
socket.io.js:3715 engine.io-client:socket creating transport "polling" +5s
socket.io.js:3715 engine.io-client:polling polling +0ms
socket.io.js:3715 engine.io-client:polling-xhr xhr poll +0ms
socket.io.js:3715 engine.io-client:polling-xhr xhr open GET: http://localhost/socket.io/?EIO=3&transport=polling&t=1422782885332-41 +1ms
socket.io.js:3715 engine.io-client:polling-xhr xhr data null +0ms
socket.io.js:3715 engine.io-client:socket setting transport polling +1ms
socket.io.js:1402 socket.io-client:manager connect attempt will timeout after 20000 +3ms

Does anyone know how to fix this error. I found this discussion, but have been unable to solve the problem.


问:
Is it possible to find the sign of an input number, with neural network?
For example I have a set of numbers  {3 4 5 -6 -43 2 -7 8 5 -3 456 78 5}, and I want a NN program that categorises the positive and negative number of this set.

Is it possible for NN?

答:
That doesn't really look like a problem for a NN, but more like an if-else statement. </p>

<p>But answering you question, yes, it is possible. </p>

Body:
That doesn't really look like a problem for a NN, but more like an if-else statement.

But answering you question, yes, it is possible.


问:
How to copy data from one csv to another with respect to header names in python?
I have two CSV files one with certain columns and rows, the second one has just one row with headers in it, The headers in the second file has more headers than first but includes all the headers from the first file.
I want to fill the columns in the second file when it matches the header from the first file.
The first file is a raw data file which has 20 columns with 100,000 rows that need to be copied to the working file that has 30 columns(20 columns are same as raw). The working file also has no data in it except column headers.
I am able to copy the data with the code below but it but it changes the sequence of columns.I want the sequence of columns in working file intact.
I am pretty new to the language, I would really appreciate any help.

The code i am using right now is:

```<code>import os
import glob
import pandas as pd
def concatenate(indir = "", outfile = "",outdf=""):
    os.chdir(indir)
    fileList=glob.glob("*.csv")
    dfList=[]
    for fileName in fileList:
        print(fileName)
        df=pd.read_csv(fileName,low_memory=False)
        dfList.append(df)
    concatdf=pd.concat(dfList, axis=0)
    concatdf.to_csv(outfile, index=False)
concatenate(indir = "xyz.csv", outfile = "abc.csv")
</code>```

答:
pandas is a great tool, but is overkill here. csv module is enough and DictReader and DictWriter do what you need automatically:

Assumptions:

inputs:

The output file template contains initially the headers in its first line

you want to process a list of input files that contains subsets of the headers of the output file

output:

the output file is populated with data from the input files with respect of field names

Possible code:

```<code>def populate(outfile, infilelist)
    # First of all read output file field names:
    with open(outfile) as fd:
        rd = csv.DictReader(fd)
        names = rd.fieldnames

    # Reopen output file in append mode to populate if from the files of infilelist
    with open(outfile, "a") as fdout:
        wr = csvDictWriter(fdout, fieldnames = names)
        # loop over the input files:
        for filename in infilelist:
            with open(filename) as fd:
                rd = csv.DictReader(fd)
                # simply copy the rows, one at a time
                for row in rd:
                    wr.writerow(row)
</code>```

This algorithm allows to add data even if the output file contains more that the header line, and can process huge data because (apart from the file buffers) only one line is kept in memory.

Body:
I have two CSV files one with certain columns and rows, the second one has just one row with headers in it, The headers in the second file has more headers than first but includes all the headers from the first file.
I want to fill the columns in the second file when it matches the header from the first file.
The first file is a raw data file which has 20 columns with 100,000 rows that need to be copied to the working file that has 30 columns(20 columns are same as raw). The working file also has no data in it except column headers.
I am able to copy the data with the code below but it but it changes the sequence of columns.I want the sequence of columns in working file intact.
I am pretty new to the language, I would really appreciate any help.

The code i am using right now is:

import os
import glob
import pandas as pd
def concatenate(indir = "", outfile = "",outdf=""):
    os.chdir(indir)
    fileList=glob.glob("*.csv")
    dfList=[]
    for fileName in fileList:
        print(fileName)
        df=pd.read_csv(fileName,low_memory=False)
        dfList.append(df)
    concatdf=pd.concat(dfList, axis=0)
    concatdf.to_csv(outfile, index=False)
concatenate(indir = "xyz.csv", outfile = "abc.csv")

Body:
pandas is a great tool, but is overkill here. csv module is enough and DictReader and DictWriter do what you need automatically:

Assumptions:

inputs:

The output file template contains initially the headers in its first line

you want to process a list of input files that contains subsets of the headers of the output file

output:

the output file is populated with data from the input files with respect of field names

Possible code:

def populate(outfile, infilelist)
    # First of all read output file field names:
    with open(outfile) as fd:
        rd = csv.DictReader(fd)
        names = rd.fieldnames

    # Reopen output file in append mode to populate if from the files of infilelist
    with open(outfile, "a") as fdout:
        wr = csvDictWriter(fdout, fieldnames = names)
        # loop over the input files:
        for filename in infilelist:
            with open(filename) as fd:
                rd = csv.DictReader(fd)
                # simply copy the rows, one at a time
                for row in rd:
                    wr.writerow(row)

This algorithm allows to add data even if the output file contains more that the header line, and can process huge data because (apart from the file buffers) only one line is kept in memory.


问:
SceneKit objects collide at their bounding box instead of along the mesh
I'm using "DAE" model as SCNGeometry.

Trying to use it as physics body shape:

```<code>    let url = Bundle.main.url(forResource: "art.scnassets/half", withExtension: "dae")
    let sceneSource = SCNSceneSource(url: url!, options: nil)
    let tubeGeometry = (sceneSource?.entryWithIdentifier("Cube-mesh", withClass: SCNGeometry.self ))! as SCNGeometry

    tubeNode = SCNNode(geometry: tubeGeometry)
    tubeNode.position = SCNVector3(0, 1, 0)
    tubeNode.eulerAngles = SCNVector3Make(1.5, 2, 0)

    let tubeShape = SCNPhysicsShape(geometry: tubeGeometry, options: nil)
    let tubeBody = SCNPhysicsBody(type: .static, shape: tubeShape)
    tubeNode.physicsBody = tubeBody
    scene.rootNode.addChildNode(tubeNode)
</code>```

Do not perceive geometrical object properties (edges, faces, etc.).
Perceives the cube as it seems.
So as a result, the ball collides with an invisible plane that is not my object, but must fall inward as on screenshot below:

Any ideas / advices why is it?
Please help me to fix that problem...

Thanks in advance!

答: You need to configure your physics body shape to "SCNPhysicsShapeTypeConcavePolyhedron" (defaults to convex). You can use the SCNView's debugOptions to visualize the physics shapes</p>

Body:
I'm using "DAE" model as SCNGeometry.

Trying to use it as physics body shape:

    let url = Bundle.main.url(forResource: "art.scnassets/half", withExtension: "dae")
    let sceneSource = SCNSceneSource(url: url!, options: nil)
    let tubeGeometry = (sceneSource?.entryWithIdentifier("Cube-mesh", withClass: SCNGeometry.self ))! as SCNGeometry

    tubeNode = SCNNode(geometry: tubeGeometry)
    tubeNode.position = SCNVector3(0, 1, 0)
    tubeNode.eulerAngles = SCNVector3Make(1.5, 2, 0)

    let tubeShape = SCNPhysicsShape(geometry: tubeGeometry, options: nil)
    let tubeBody = SCNPhysicsBody(type: .static, shape: tubeShape)
    tubeNode.physicsBody = tubeBody
    scene.rootNode.addChildNode(tubeNode)

Do not perceive geometrical object properties (edges, faces, etc.).
Perceives the cube as it seems.
So as a result, the ball collides with an invisible plane that is not my object, but must fall inward as on screenshot below:

Any ideas / advices why is it?
Please help me to fix that problem...

Thanks in advance!


问:
Can I take a snapshot of a website from the command line?
I am writing documentation for a website  database interface. Is it possible to write a script that, when executed, takes the most recent snapshot of the website and saves it as an image file?

note: I am using the tags ruby, bash, and python since those are the languages used in our group (along with R and FORTRAN; for sport, I'll set a 100 point bounty If anyone can post a FORTRAN solution).

update: as @birryree notes, a previous question provides the answer. Considering the FORTRAN offer is just for sport, perhaps this is a duplicate?

答:
CutyCapt (command-line) does a fine job.</p>

```<code>CutyCapt --url=http://www.example.org --out=example.png
</code>```

Body:
CutyCapt (command-line) does a fine job.

CutyCapt --url=http://www.example.org --out=example.png


问:
I have to Transform every line of code that I have written for charts into a class (object oriented) using coffeescript
Lets say I have 5 Fusion Charts
Most of the charts have same attributes.
I have to pass all this attributes into coffeescript contructor
But how to achieve it?

any sample code would be helpful

答:
Below is a example class declaration that take a parameter and when we call draw method it print input params on console.

```<code>class Chart
  constructor: (params) ->
    # initialize your variable
    # example @foo = params
    @attr = params

  draw: ->
    # access @attr instance variable
    console.log "your input params is #{@attr}"

 new Chart('this is test params').draw()
</code>```

I highly recommended you first read coffeescript official guide before start. There are great books available that may help you The Little Book on CoffeeScript and coffeescript-cookbook. And of-course use http://js2.coffee/ site for experiment js to coffee and vise versa. Hope it will help you

Body:
Below is a example class declaration that take a parameter and when we call draw method it print input params on console.

class Chart
  constructor: (params) ->
    # initialize your variable
    # example @foo = params
    @attr = params

  draw: ->
    # access @attr instance variable
    console.log "your input params is #{@attr}"

 new Chart('this is test params').draw()

I highly recommended you first read coffeescript official guide before start. There are great books available that may help you The Little Book on CoffeeScript and coffeescript-cookbook. And of-course use http://js2.coffee/ site for experiment js to coffee and vise versa. Hope it will help you


问:
String Format Get Attribute Function
I try to create an attribute function in a model which returns a string result but I would like to change the format of the string.

Actually I have a number licence (varchar column), which is displayed like 17923457 and I would like to change the format to 17-92-3457.

My function attribute actually is like:

```<code>public function getNumberAttribute() {

return $this->num_licence ;

}
</code>```

Someone knows how I can display that specific format? Thanks a lot in advance

答:
another one linear approach using vpsprintf

```<code>public function getNumberAttribute() {

    return vsprintf('%d%d-%d%d-%d%d%d%d', str_split($this->num_licence));

}
</code>```

for example :

```<code>$s = vsprintf('%d%d-%d%d-%d%d%d%d', str_split('17923457'));

print_r($s); // Outputs 17-92-3457
</code>```

Title: String Format Get Attribute Function

Body:
I try to create an attribute function in a model which returns a string result but I would like to change the format of the string.

Actually I have a number licence (varchar column), which is displayed like 17923457 and I would like to change the format to 17-92-3457.

My function attribute actually is like:

public function getNumberAttribute() {

return $this->num_licence ;

}

Someone knows how I can display that specific format? Thanks a lot in advance

Body:
another one linear approach using vpsprintf

public function getNumberAttribute() {

    return vsprintf('%d%d-%d%d-%d%d%d%d', str_split($this->num_licence));

}

for example :

$s = vsprintf('%d%d-%d%d-%d%d%d%d', str_split('17923457'));

print_r($s); // Outputs 17-92-3457


问:
Is it possible to create an application WITHOUT a framework?
I was just thinking. C# has Winforms/WPF, Java has Swing and other frameworks, C++ has QT and so on; is it possible to create an application without using a Framework?

Putting aside the practicality of it, I'm just curious. How would one create an application that Just Works(tm) without needing external frameworks?

答:
Firstly, what is a framework?

Really a framework is just a bunch of code that is provided to you. You could, at least in theory, write the same code yourself. In that case you wouldn't be using a framework.

Your application can only do what the operating system allows it to do. Your program cannot directly manipulate the graphics card for example. So you have to use the APIs of your operating system in order to do anything.

So you are going to be calling into other code. (unless you write your own operating system). You will also being using another framework or api to get stuff done.


答: This seems like a overly simplified question for a NN. You could probably simply use a linear classifier. Why are you trying to overkill the problem with a NN?</p>

Title: Is it possible to find the sign of an input number, with neural network?

Body:
For example I have a set of numbers  {3 4 5 -6 -43 2 -7 8 5 -3 456 78 5}, and I want a NN program that categorises the positive and negative number of this set.

Is it possible for NN?