问:
Parcelable objct with another types MPAndroidChart
```<code>public class DataForBinding implements Parcelable {

// private static final long serialVersionUID = 1L;
public ArrayList<BarEntry> barEntries;
public ArrayList<CandleEntry> candleEntries;
public ArrayList<Entry> lineEntries;

public DataForBinding() {

}

protected DataForBinding(Parcel in) {
    barEntries=new ArrayList<BarEntry>();
    candleEntries=new ArrayList<CandleEntry>();
    lineEntries=new ArrayList<Entry>();
    this.candleEntries = in.readArrayList(Entry.class.getClassLoader());
    this.barEntries = in.readArrayList(Entry.class.getClassLoader());
    this.lineEntries = in.readArrayList(Entry.class.getClassLoader());
}

public static final Creator<DataForBinding> CREATOR = new Creator<DataForBinding>() {
    @Override
    public DataForBinding createFromParcel(Parcel in) {
        return new DataForBinding(in);
    }

    @Override
    public DataForBinding[] newArray(int size) {
        return new DataForBinding[size];
    }
};

@Override
public int describeContents() {
    return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
    dest.writeList(barEntries);
    dest.writeList(candleEntries);
    dest.writeList(lineEntries);
}                  //set&get
</code>```

BarEntry extends Entry

CandleEntry extends Entry

 BarEntry extends Entry

Entry extends BaseEntry implements Parcelable

I use this for send/receive data for chart.
(First activity)

```<code>Intent intent = new Intent(getActivity(), MainTabActivity.class);
                data = new DataForBinding();
                data.candleEntries=generateCandleData();
                data.barEntries=generateBarData();
                data.lineEntries=generateLineData();
                intent.putExtra("object",data);
                startActivity(intent);
</code>```

//---------------------------------------------- (Second)

```<code>  public class MainTabActivity extends AppCompatActivity {
        Toolbar toolbar;
        TabLayout tabLayout;
        ViewPager viewPager;
        ViewPagerAdapter adapter;
        @Override
        protected void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main_tab);
            DataForBinding data=getIntent().getParcelableExtra("object");
            getIntent().putExtra("data_all",data);
               }
</code>```

All data i sent from activity to activity, and from second activity to fragment in tab.
But on fragment he work only with Entry class (lineEntries), and say
Entry cannot be cast to com.github.mikephil.charting.data.CandleEntry

```<code> @Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    mChart = (CombinedChart) getView().findViewById(R.id.chart_in_tab);
    DataForBinding data = new DataForBinding();

    ArrayList<BarEntry> barEntries = new ArrayList<>();
    ArrayList<CandleEntry> candleEntries;
    ArrayList<Entry> lineEntries = new ArrayList<>();

    data = getActivity().getIntent().getParcelableExtra("data_all");

    barEntries = data.getBarEntries();
    candleEntries = data.getCandleEntries();
    lineEntries = data.getLineEntries();

    mChart = CombinedChartHelper.setSettings(mChart);

    LineDataSet set2 = new LineDataSet(lineEntries, "line");
    DataHelper.setLineDataSet(set2);
    LineData dataLine = new LineData(set2);

    CandleDataSet set1 = new CandleDataSet(candleEntries, "candle");
    DataHelper.setCandleDataSet(set1);
    CandleData dataCandle = new CandleData(set1);

    CombinedData data = new CombinedData();

    data.setData(dataLine);
</code>```

答:
The subclasses of Entry do not implement Parcelable as has been pointed out in the answers to this question. Hence, they will not deserialise into the correct invariants (BarEntry, CandleEntry) etc. but instead into the covariant Entry.

You will have to find some way to work around it, either by passing the raw data and making Entry of it inside the recipient, or extracting a common repository for the data and having the recipients deal with that instead.

Body:
public class DataForBinding implements Parcelable {

// private static final long serialVersionUID = 1L;
public ArrayList<BarEntry> barEntries;
public ArrayList<CandleEntry> candleEntries;
public ArrayList<Entry> lineEntries;

public DataForBinding() {

}

protected DataForBinding(Parcel in) {
    barEntries=new ArrayList<BarEntry>();
    candleEntries=new ArrayList<CandleEntry>();
    lineEntries=new ArrayList<Entry>();
    this.candleEntries = in.readArrayList(Entry.class.getClassLoader());
    this.barEntries = in.readArrayList(Entry.class.getClassLoader());
    this.lineEntries = in.readArrayList(Entry.class.getClassLoader());
}

public static final Creator<DataForBinding> CREATOR = new Creator<DataForBinding>() {
    @Override
    public DataForBinding createFromParcel(Parcel in) {
        return new DataForBinding(in);
    }

    @Override
    public DataForBinding[] newArray(int size) {
        return new DataForBinding[size];
    }
};

@Override
public int describeContents() {
    return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
    dest.writeList(barEntries);
    dest.writeList(candleEntries);
    dest.writeList(lineEntries);
}                  //set&get

BarEntry extends Entry

CandleEntry extends Entry

 BarEntry extends Entry

Entry extends BaseEntry implements Parcelable

I use this for send/receive data for chart.
(First activity)

Intent intent = new Intent(getActivity(), MainTabActivity.class);
                data = new DataForBinding();
                data.candleEntries=generateCandleData();
                data.barEntries=generateBarData();
                data.lineEntries=generateLineData();
                intent.putExtra("object",data);
                startActivity(intent);

//---------------------------------------------- (Second)

  public class MainTabActivity extends AppCompatActivity {
        Toolbar toolbar;
        TabLayout tabLayout;
        ViewPager viewPager;
        ViewPagerAdapter adapter;
        @Override
        protected void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main_tab);
            DataForBinding data=getIntent().getParcelableExtra("object");
            getIntent().putExtra("data_all",data);
               }

All data i sent from activity to activity, and from second activity to fragment in tab.
But on fragment he work only with Entry class (lineEntries), and say
Entry cannot be cast to com.github.mikephil.charting.data.CandleEntry

 @Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    mChart = (CombinedChart) getView().findViewById(R.id.chart_in_tab);
    DataForBinding data = new DataForBinding();

    ArrayList<BarEntry> barEntries = new ArrayList<>();
    ArrayList<CandleEntry> candleEntries;
    ArrayList<Entry> lineEntries = new ArrayList<>();

    data = getActivity().getIntent().getParcelableExtra("data_all");

    barEntries = data.getBarEntries();
    candleEntries = data.getCandleEntries();
    lineEntries = data.getLineEntries();

    mChart = CombinedChartHelper.setSettings(mChart);

    LineDataSet set2 = new LineDataSet(lineEntries, "line");
    DataHelper.setLineDataSet(set2);
    LineData dataLine = new LineData(set2);

    CandleDataSet set1 = new CandleDataSet(candleEntries, "candle");
    DataHelper.setCandleDataSet(set1);
    CandleData dataCandle = new CandleData(set1);

    CombinedData data = new CombinedData();

    data.setData(dataLine);


来源: stackexchange

问:
C++: Quicksort words instead of numbers
I am trying to write a code that uses quicksort to sort words by alphabetical order, but when I run my code it gets stuck on inputting the user's words. What's the reason behind this? It works fine when I leave the array as an integer array. Thanks in advance!</p>

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

void quicksort(char a[], int size, int left, int right)
{
    int i = left;
    int j = right;
    int pivot = a[(left+right)/2];
    char temp;
    while (i <= j)
    {
        while (a[i] < pivot) i++;
        while (a[j] > pivot) j--;
        if (i <= j)
        {
            temp = a[i];
            a[i] = a[j];
            a[j] = temp;
            i++;
            j--;
        }
    }

    if (i < right)
        quicksort(a, size, i, right);
    if (j > left)
        quicksort(a, size, left, j);
}

int main()
{
    char a[10], n;
    system("clear");
    cout << "Enter the number of elements to be sorted: " << endl;
    cin >> n;
    cout << "Enter the elements to be sorted (press ENTER after each word): " << endl;
    for (int i = 0; i < n; i++)
        cin >> a[i];
        quicksort(a, n, 0, n-1);
        cout << endl;
    cout << "The sorted elements are: " << endl;
    for (int i = 0; i < n; i++)
        cout << a[i] << " ";
        cout << endl;

    return 0;

}
</code>```

答:
Thank you all for helping! This is the final solution:</p>

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

void quicksort(std::string a[], int size, int left, int right)
{
int i = left;
int j = right;
std::string pivot = a[(left+right)/2];
std::string temp;
while (i <= j)
{
    while (a[i] < pivot) i++;
    while (a[j] > pivot) j--;
    if (i <= j)
    {
        temp = a[i];
        a[i] = a[j];
        a[j] = temp;
        i++;
        j--;
    }
}

if (i < right)
    quicksort(a, size, i, right);
if (j > left)
    quicksort(a, size, left, j);
}

int main()
{
std::string a[100];
int n;
system("clear");
cout << "Enter the number of elements to be sorted: " << endl;
cin >> n;
cout << "Enter the elements to be sorted (press ENTER after each word): " << endl;
for (int i = 0; i < n; i++)
{
    cin >> a[i];
}
quicksort(a, n, 0, n-1);
cout << endl;
cout << "The sorted elements are: " << endl;
for (int i = 0; i < n; i++)
    cout << a[i] << " ";
cout << endl;

return 0;

}
</code>```

ContentLicense: CC BY-SA 3.0

Title: C++: Quicksort words instead of numbers

Body:
I am trying to write a code that uses quicksort to sort words by alphabetical order, but when I run my code it gets stuck on inputting the user's words. What's the reason behind this? It works fine when I leave the array as an integer array. Thanks in advance!

#include <iostream>
#include <cstdlib>
#include <cstring>
using namespace std;

void quicksort(char a[], int size, int left, int right)
{
    int i = left;
    int j = right;
    int pivot = a[(left+right)/2];
    char temp;
    while (i <= j)
    {
        while (a[i] < pivot) i++;
        while (a[j] > pivot) j--;
        if (i <= j)
        {
            temp = a[i];
            a[i] = a[j];
            a[j] = temp;
            i++;
            j--;
        }
    }

    if (i < right)
        quicksort(a, size, i, right);
    if (j > left)
        quicksort(a, size, left, j);
}

int main()
{
    char a[10], n;
    system("clear");
    cout << "Enter the number of elements to be sorted: " << endl;
    cin >> n;
    cout << "Enter the elements to be sorted (press ENTER after each word): " << endl;
    for (int i = 0; i < n; i++)
        cin >> a[i];
        quicksort(a, n, 0, n-1);
        cout << endl;
    cout << "The sorted elements are: " << endl;
    for (int i = 0; i < n; i++)
        cout << a[i] << " ";
        cout << endl;

    return 0;

}

Body:
Thank you all for helping! This is the final solution:

#include <iostream>
#include <cstdlib>
#include <cstring>
using namespace std;

void quicksort(std::string a[], int size, int left, int right)
{
int i = left;
int j = right;
std::string pivot = a[(left+right)/2];
std::string temp;
while (i <= j)
{
    while (a[i] < pivot) i++;
    while (a[j] > pivot) j--;
    if (i <= j)
    {
        temp = a[i];
        a[i] = a[j];
        a[j] = temp;
        i++;
        j--;
    }
}

if (i < right)
    quicksort(a, size, i, right);
if (j > left)
    quicksort(a, size, left, j);
}

int main()
{
std::string a[100];
int n;
system("clear");
cout << "Enter the number of elements to be sorted: " << endl;
cin >> n;
cout << "Enter the elements to be sorted (press ENTER after each word): " << endl;
for (int i = 0; i < n; i++)
{
    cin >> a[i];
}
quicksort(a, n, 0, n-1);
cout << endl;
cout << "The sorted elements are: " << endl;
for (int i = 0; i < n; i++)
    cout << a[i] << " ";
cout << endl;

return 0;

}


问:
Getting all the nodes from Python AST that correspond to a particular variable with a given name
Consider the code below:

```<code>1 | x = 20
2 |
3 | def f():
4 |     x = 0
5 |     for x in range(10):
6 |         x += 10
7 |     return x
8 | f()
9 |
10| for x in range(10):
11|     pass
12| x += 1
13| print(x)
</code>```

The value of x after execution of the code above is 10. Now, how can I get all the nodes with class Name whose ids are x and refer to the x that's being used in lines 1, 10, 12 and 13?

In other words, the x inside of f is different from the rest of the xs. Is it possible to get their AST nodes, having only the script and script's AST while not executing it?

答:
When walking the AST tree, track the context; start with a global context, then as you encounter FunctionDef or ClassDef or Lambda nodes, record that context as a stack (pop the stack again when exiting the relevant node).

You can then simply only look at Name nodes in the global context. You can track global identifiers too (I'd use a set per stack level).

Using a NodeVisitor subclass:

```<code>import ast

class GlobalUseCollector(ast.NodeVisitor):
    def __init__(self, name):
        self.name = name
        # track context name and set of names marked as `global`
        self.context = [('global', ())]

    def visit_FunctionDef(self, node):
        self.context.append(('function', set()))
        self.generic_visit(node)
        self.context.pop()

    # treat coroutines the same way
    visit_AsyncFunctionDef = visit_FunctionDef

    def visit_ClassDef(self, node):
        self.context.append(('class', ()))
        self.generic_visit(node)
        self.context.pop()

    def visit_Lambda(self, node):
        # lambdas are just functions, albeit with no statements, so no assignments
        self.context.append(('function', ()))
        self.generic_visit(node)
        self.context.pop()

    def visit_Global(self, node):
        assert self.context[-1][0] == 'function'
        self.context[-1][1].update(node.names)

    def visit_Name(self, node):
        ctx, g = self.context[-1]
        if node.id == self.name and (ctx == 'global' or node.id in g):
            print('{} used at line {}'.format(node.id, node.lineno))
</code>```

Demo (given the AST tree for your sample code in t):

```<code>>>> GlobalUseCollector('x').visit(t)
x used at line 1
x used at line 10
x used at line 12
x used at line 13
</code>```

And using global x in a function:

```<code>>>> u = ast.parse('''\
... x = 20
...
... def g():
...     global x
...     x = 0
...     for x in range(10):
...         x += 10
...     return x
...
... g()
... for x in range(10):
...     pass
... x += 1
... print(x)
... ''')
>>> GlobalUseCollector('x').visit(u)
x used at line 1
x used at line 5
x used at line 6
x used at line 7
x used at line 8
x used at line 11
x used at line 13
x used at line 14
</code>```

Body:
Consider the code below:

1 | x = 20
2 |
3 | def f():
4 |     x = 0
5 |     for x in range(10):
6 |         x += 10
7 |     return x
8 | f()
9 |
10| for x in range(10):
11|     pass
12| x += 1
13| print(x)

The value of x after execution of the code above is 10. Now, how can I get all the nodes with class Name whose ids are x and refer to the x that's being used in lines 1, 10, 12 and 13?

In other words, the x inside of f is different from the rest of the xs. Is it possible to get their AST nodes, having only the script and script's AST while not executing it?

Body:
When walking the AST tree, track the context; start with a global context, then as you encounter FunctionDef or ClassDef or Lambda nodes, record that context as a stack (pop the stack again when exiting the relevant node).

You can then simply only look at Name nodes in the global context. You can track global identifiers too (I'd use a set per stack level).

Using a NodeVisitor subclass:

import ast

class GlobalUseCollector(ast.NodeVisitor):
    def __init__(self, name):
        self.name = name
        # track context name and set of names marked as `global`
        self.context = [('global', ())]

    def visit_FunctionDef(self, node):
        self.context.append(('function', set()))
        self.generic_visit(node)
        self.context.pop()

    # treat coroutines the same way
    visit_AsyncFunctionDef = visit_FunctionDef

    def visit_ClassDef(self, node):
        self.context.append(('class', ()))
        self.generic_visit(node)
        self.context.pop()

    def visit_Lambda(self, node):
        # lambdas are just functions, albeit with no statements, so no assignments
        self.context.append(('function', ()))
        self.generic_visit(node)
        self.context.pop()

    def visit_Global(self, node):
        assert self.context[-1][0] == 'function'
        self.context[-1][1].update(node.names)

    def visit_Name(self, node):
        ctx, g = self.context[-1]
        if node.id == self.name and (ctx == 'global' or node.id in g):
            print('{} used at line {}'.format(node.id, node.lineno))

Demo (given the AST tree for your sample code in t):

>>> GlobalUseCollector('x').visit(t)
x used at line 1
x used at line 10
x used at line 12
x used at line 13

And using global x in a function:

>>> u = ast.parse('''\
... x = 20
...
... def g():
...     global x
...     x = 0
...     for x in range(10):
...         x += 10
...     return x
...
... g()
... for x in range(10):
...     pass
... x += 1
... print(x)
... ''')
>>> GlobalUseCollector('x').visit(u)
x used at line 1
x used at line 5
x used at line 6
x used at line 7
x used at line 8
x used at line 11
x used at line 13
x used at line 14

ContentLicense: CC BY-SA 4.0


问:
HtmlUnit disable status code error exception
In HtmlUnit, how to disable throw exception when the requested page returns fail status code (like 4xx)? I need to get the status code, so if it throws an exception, I can't get the status code.

```<code>Page page = null;
try {
    page = webClient.getPage(requestSettings);
    System.out.println(page.getWebResponse().getStatusCode()); // it doesn't go to this line because exception is already thrown
} catch (Exception e) {
    System.out.println(page.getWebResponse().getStatusCode()); // it will fail because of NullPointerException
    System.out.println(e);
}
</code>```

The following method seems to work only on older versions of HtmlUnit. I'm using v2.25 and the method doesn't exist.

```<code>webClient.setThrowExceptionOnFailingStatusCode(false);
</code>```

答:
The new API now has WebClientOptions,

you should use:

```<code>webClient.getOptions().setThrowExceptionOnFailingStatusCode(false);
</code>```

Body:
In HtmlUnit, how to disable throw exception when the requested page returns fail status code (like 4xx)? I need to get the status code, so if it throws an exception, I can't get the status code.

Page page = null;
try {
    page = webClient.getPage(requestSettings);
    System.out.println(page.getWebResponse().getStatusCode()); // it doesn't go to this line because exception is already thrown
} catch (Exception e) {
    System.out.println(page.getWebResponse().getStatusCode()); // it will fail because of NullPointerException
    System.out.println(e);
}

The following method seems to work only on older versions of HtmlUnit. I'm using v2.25 and the method doesn't exist.

webClient.setThrowExceptionOnFailingStatusCode(false);

Body:
The new API now has WebClientOptions,

you should use:

webClient.getOptions().setThrowExceptionOnFailingStatusCode(false);


问:
POST vs DELETE in AJAX requests
jQuery AJAX supports DELETE method, right?

Please enumerate arguments pro and contra for using POST vs DELETE jQuery AJAX requests to the backend to delete an object.

Is it true that with DELETE requests we may have trouble with proxy servers?

答:
According to Wikipedia (https://en.wikipedia.org/wiki/Representational_state_transfer) the argument is twofold: on the one side 'Unlike SOAP-based Web services, there is no "official" standard for RESTful Web APIs.' while on the other side PUT and DELETE are 'Standard HTTP Methods'

The strongest argument for DELETE is that it is the most widely used accepted standard for REST, and that is an advantage when you have to "justify" jour choices (an accepted standard is right, unless there are specific reasons to say the opposite)

The strongest argument against DELETE (and for using POST) is that it is far easier to test via simple forms and if you use odd frameworks (I am just supposing, i do not know about such things)

Besides, standard HTTP methods should not be blocked by proxies (using HTTP is exactly the point for web services for not being blocked) so I would in the end go for standard and use DELETE as shown in the wikipedia article.

Title: POST vs DELETE in AJAX requests


问:
Horizontal Div Scroll
I'm quite new to Jquery, I'm trying to implement horizontal scrolling on a div using the scrollLeft property, I'm not getting any error messages and nothing seems to be working, could someone explain why? Thanks in advance
this is my code:

```
<pre class="snippet-code-css lang-css prettyprint-override"><code><style>
        #container{
            max-width: 938px;
            height: 500px;
            border: 2px solid black;
            margin-left: auto;
            margin-right: auto;
            overflow: scroll;
            /*display: table;*/
        }
        .picsdiv{
            display: table-cell;
            min-width: 286px;
            padding-right: 80px;
            height: 508px;
            border: 2px solid pink;

        }

        .prev, .next {
          cursor: pointer;
          position: absolute;
          top: 250px;
          width: auto;
          margin-top: -22px;
          padding: 16px;
          color: white;
          font-weight: bold;
          font-size: 18px;
          transition: 0.6s ease;
          border-radius: 0 3px 3px 0;
            border: 2px solid pink;
        }

        .next {
          right: 170px;
          border-radius: 3px 0 0 3px;
        }
        .prev{
            left: 170px;
        }

        .prev:hover, .next:hover {
          background-color: rgba(0,0,0,0.8);
        }
    </style></code>```

       ❮
      ❯

```

答:
You have done 2 mistakes in your code:

scrollLeft: pos - 200; should be like scrollLeft: (pos - 200), because you are passing an object as parameter

Write two

And another for your custom java-script

```<code><script type="text/javascript">
    $(document).ready (function(){
        var pos  = $("#container").scrollLeft();
        $(".prev").click(function(){
            $("#container").animate({
                scrollLeft: (pos - 200)
            });
        });
    });
</code>```

Because you can not write code inside  element if you are using ths element as external reference.

Here is your complete running code

```<code><html>
<head>
<style>
    #container{
    max-width: 938px;
    height: 500px;
    border: 2px solid black;
    margin-left: auto;
    margin-right: auto;
    overflow: scroll;
    /*display: table;*/
    }
    .picsdiv{
    display: table-cell;
    min-width: 286px;
    padding-right: 80px;
    height: 508px;
    border: 2px solid pink;
    }
    .prev, .next {
    cursor: pointer;
    position: absolute;
    top: 250px;
    width: auto;
    margin-top: -22px;
    padding: 16px;
    color: white;
    font-weight: bold;
    font-size: 18px;
    transition: 0.6s ease;
    border-radius: 0 3px 3px 0;
    border: 2px solid pink;
    }
    .next {
    right: 170px;
    border-radius: 3px 0 0 3px;
    }
    .prev{
    left: 170px;
    }
    .prev:hover, .next:hover {
    background-color: rgba(0,0,0,0.8);
    }
</style>
</head>
<body>
    <div id="container">
        <div class="picsdiv">
        </div>
        <div class="picsdiv">
        </div>
        <div class="picsdiv">
        </div>
        <div class="picsdiv">
        </div>
        <a class="prev"><</a>
        <a class="next">></a>
    </div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
    $(document).ready (function(){
            var pos  = $("#container").scrollLeft();
            $(".prev").click(function(){
                $("#container").animate({
                    scrollLeft: (pos - 200)
                });
            });
        });
</script>
</html>
</code>```

Title: Horizontal Div Scroll

Body:
I'm quite new to Jquery, I'm trying to implement horizontal scrolling on a div using the scrollLeft property, I'm not getting any error messages and nothing seems to be working, could someone explain why? Thanks in advance
this is my code:

       ❮
      ❯

Body:
You have done 2 mistakes in your code:

scrollLeft: pos - 200; should be like scrollLeft: (pos - 200), because you are passing an object as parameter

Write two <script> tags, one for jQuery, like below

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js" type="text/javacsript"></script>

And another for your custom java-script

<script type="text/javascript">
    $(document).ready (function(){
        var pos  = $("#container").scrollLeft();
        $(".prev").click(function(){
            $("#container").animate({
                scrollLeft: (pos - 200)
            });
        });
    });

Because you can not write code inside  element if you are using ths element as external reference.

Here is your complete running code

<html>
<head>
<style>
    #container{
    max-width: 938px;
    height: 500px;
    border: 2px solid black;
    margin-left: auto;
    margin-right: auto;
    overflow: scroll;
    /*display: table;*/
    }
    .picsdiv{
    display: table-cell;
    min-width: 286px;
    padding-right: 80px;
    height: 508px;
    border: 2px solid pink;
    }
    .prev, .next {
    cursor: pointer;
    position: absolute;
    top: 250px;
    width: auto;
    margin-top: -22px;
    padding: 16px;
    color: white;
    font-weight: bold;
    font-size: 18px;
    transition: 0.6s ease;
    border-radius: 0 3px 3px 0;
    border: 2px solid pink;
    }
    .next {
    right: 170px;
    border-radius: 3px 0 0 3px;
    }
    .prev{
    left: 170px;
    }
    .prev:hover, .next:hover {
    background-color: rgba(0,0,0,0.8);
    }
</style>
</head>
<body>
    <div id="container">
        <div class="picsdiv">
        </div>
        <div class="picsdiv">
        </div>
        <div class="picsdiv">
        </div>
        <div class="picsdiv">
        </div>
        <a class="prev">&lt;</a>
        <a class="next">&gt;</a>
    </div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
    $(document).ready (function(){
            var pos  = $("#container").scrollLeft();
            $(".prev").click(function(){
                $("#container").animate({
                    scrollLeft: (pos - 200)
                });
            });
        });
</script>
</html>


问:
Problem in Google Map API...!
Hi there i'm currently working with google map api

for plotting multiple address with marker

i have written the following code as i understand the api function while study from google api documentation

```<code>for(var i=0; i<address.length; i++){
geocoder.getLocations(address[i],function(response){
            if(response){
                place = response.Placemark[0];
                  point = new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]);
                map.setCenter(point, 12);
                map.addOverlay(createmarker(point));
            }
});
}
</code>```

createmarker is my function which works properly but the problem is this
this place random markers with the address comes from address array
sometimes 10, 12, 14, 14, and so on ....

I just want to plot all the address exists in my address array and on the google maps too..

so it must be fixed number of markers onto the map...!

So is there anyone who can help me for this issue..!

Thanks is advanced

答:
The createMarker function should look like this. Please see my example here, where you can add multiple markers on the map. Complete javascript can be found here.

```<code>function createMarker(latlng) {
   var contentString = html;
    var marker = new google.maps.Marker({
        position: latlng,
        map: map,
        zIndex: Math.round(latlng.lat()*-100000)<<5
    });

    google.maps.event.addListener(marker, 'click', function() {
        infowindow.setContent(contentString);
        infowindow.open(map,marker);
    });
    marker.MyZoom = zoom;
    return marker;
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: Problem in Google Map API...!

Body:
Hi there i'm currently working with google map api

for plotting multiple address with marker

i have written the following code as i understand the api function while study from google api documentation

for(var i=0; i<address.length; i++){
geocoder.getLocations(address[i],function(response){
            if(response){
                place = response.Placemark[0];
                  point = new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]);
                map.setCenter(point, 12);
                map.addOverlay(createmarker(point));
            }
});
}

createmarker is my function which works properly but the problem is this
this place random markers with the address comes from address array
sometimes 10, 12, 14, 14, and so on ....

I just want to plot all the address exists in my address array and on the google maps too..

so it must be fixed number of markers onto the map...!

So is there anyone who can help me for this issue..!

Thanks is advanced

Body:
The createMarker function should look like this. Please see my example here, where you can add multiple markers on the map. Complete javascript can be found here.

function createMarker(latlng) {
   var contentString = html;
    var marker = new google.maps.Marker({
        position: latlng,
        map: map,
        zIndex: Math.round(latlng.lat()*-100000)<<5
    });

    google.maps.event.addListener(marker, 'click', function() {
        infowindow.setContent(contentString);
        infowindow.open(map,marker);
    });
    marker.MyZoom = zoom;
    return marker;
}


问:
How to find char if there is not another one before
I've got a string

```<code>{'lalala'} text before \{'lalala'\} {'lalala'} text after
</code>```

I want to get open bracket { but only if there is no escape char \ before.

Kind of /(?:[^\\])\{/ but it doesn't work at first statement.

答:
The typical approach is to match the non-\ preceding character (or beginning of string), and then put it back in your replacement logic.

const input = String.raw`{'lalala'} text before \{'lalala'\} {'lalala'} text after`;

function replace(str) {
  return input.replace(/(^|[^\\])\{'(\w+)'\}/g,
    (_, chr, word) => chr + word.toUpperCase());
}

console.log(replace(input));```

Body:
I've got a string

{'lalala'} text before \{'lalala'\} {'lalala'} text after

I want to get open bracket { but only if there is no escape char \ before.

Kind of /(?:[^\\])\{/ but it doesn't work at first statement.


问:
Maximum of Longest Increasing Sequences
I have a code that will find all the cycles of a list, e.g for [1,2,3] the cycles are [1,2,3], [2,3,1], [3,1,2]. I also have a code for finding the longest increasing subsequence.

What I want to do is input a list, find the longest increasing subsequence of every cycle of that list, and then return the maximum length out of all of these. how do I go from these two functions to finding the LIS of every cycle and then return the maximum?

Here is my code so far:

```<code>def cycles(X):

  n = len(X)

  values = []

  for i in range(0,n):
    values.append(X[i:n] + X[0:i])

  return values

def longest_increasing_subsequence(d):

    l = []

    for i in range(len(d)):

        l.append(max([l[j] for j in range(i) if l[j][-1] < d[i]] or  [[]], key=len)  + [d[i]])

    return len(max(l, key=len))
</code>```

I'd appreciate any help. thanks.

答:
This will do the job:

```<code>l=[1,2,3,4]
s=cycles(l)
lis=[longest_increasing_subsequence(d) for d in s]
print(lis)
print(max(lis))
</code>```

The result is

```<code>[4,3,2,3]
</code>```

and

```<code>4
</code>```

Title: Maximum of Longest Increasing Sequences

Body:
I have a code that will find all the cycles of a list, e.g for [1,2,3] the cycles are [1,2,3], [2,3,1], [3,1,2]. I also have a code for finding the longest increasing subsequence.

What I want to do is input a list, find the longest increasing subsequence of every cycle of that list, and then return the maximum length out of all of these. how do I go from these two functions to finding the LIS of every cycle and then return the maximum?

Here is my code so far:

def cycles(X):

  n = len(X)

  values = []

  for i in range(0,n):
    values.append(X[i:n] + X[0:i])

  return values

def longest_increasing_subsequence(d):

    l = []

    for i in range(len(d)):

        l.append(max([l[j] for j in range(i) if l[j][-1] < d[i]] or  [[]], key=len)  + [d[i]])

    return len(max(l, key=len))

I'd appreciate any help. thanks.

Body:
This will do the job:

l=[1,2,3,4]
s=cycles(l)
lis=[longest_increasing_subsequence(d) for d in s]
print(lis)
print(max(lis))

The result is

[4,3,2,3]

and

4


问:
Kotlin anonymous function use case?
Based on my understanding, anonymous function in Kotlin allow you to specify return type. In addition to that, return statement inside anonymous will exit only the function block, while in lambda it will exit the enclosing function.

Still, I can't imagine what would be the real world use case of anonymous function in Kotlin that lambda syntax cannot provide?

Kotlin Higher Order Function and Lambda

答:
Anonymous functions (a.k.a function expressions) are very handy when you have to pass a huge lambda with complex logic and want early returns to work. For example if you write a dispatcher in spark-java:</p>

```<code>get("/", fun(request, response) {
    // Your web page here
    // You can use `return` to interrupt the handler
})
</code>```

Title: Kotlin anonymous function use case?

Body:
Anonymous functions (a.k.a function expressions) are very handy when you have to pass a huge lambda with complex logic and want early returns to work. For example if you write a dispatcher in spark-java:

get("/", fun(request, response) {
    // Your web page here
    // You can use `return` to interrupt the handler
})


问:
lombok @ExtensionMethod: cannot resolve method
I've added this class:

```<code>public class StringExtensions {
  public static String makeMusical( String in ) {
    return "1";
  }
}

@ExtensionMethod({StringExtensions.class})
public class App {
   public static void main(String[] args) {
   String a = "A".makeMusical();  //compiles but ide shows:"cannot resolve method makeMusical"
  }
}
</code>```

but when trying to use it on a string I get:

"cannot resolve method makeMusical"

(The solution is built and running on IntelliJ but I do not have intellisense / ide doesn't recognized the method)

I've set:

Enable annotation processing.

答:
Still experimental feature - Probably the reason for that is here.

The created method makeMusical is static, so I guess when you're trying to intellisense after "A". the IDE tries to auto-complete only using non-static methods.

Hopefully, when the issue in the link will be resolved the IDE plugin will behave accordingly.

BTW - Eclipse intellisense behavior is similar, but it doesn't show any errors though.

Body:
I've added this class:

public class StringExtensions {
  public static String makeMusical( String in ) {
    return "1";
  }
}

@ExtensionMethod({StringExtensions.class})
public class App {
   public static void main(String[] args) {
   String a = "A".makeMusical();  //compiles but ide shows:"cannot resolve method makeMusical"
  }
}

but when trying to use it on a string I get:

"cannot resolve method makeMusical"

(The solution is built and running on IntelliJ but I do not have intellisense / ide doesn't recognized the method)

I've set:

Enable annotation processing.


问:
Rails 4, Unknown action, The action 'destroy' could not be found for PostsController
What is usually a simple error with a simple solution, I seem to be stuck:

posts#controller:

```<code>class PostsController < ApplicationController

def index
 @posts = Post.all
end

def show
 @post = Post.find params[:id]
end

def new
 @post = Post.new
end

def create
 @post = Post.create post_params

 if @post.save
  redirect_to posts_path, :notice => "Your post was saved!"
 else
  render 'new'
 end

end

private
 def post_params
  params.require(:post).permit(:title, :content)
 end

def edit
 @post = Post.find params[:id]
end

def update
 @post = Post.find params[:id]

 if @post.update_attributes params[:post]
  redirect_to posts_path
 else
  render 'edit'
 end
end

def destroy
 @post = Post.find params[:id]
 @post.destroy

 redirect_to posts_path, :notice => "Your post has been deleted"
end

end
</code>```

routes.rb:

```<code>Blog::Application.routes.draw do

 resources :posts

end
</code>```

rake routes:

```<code>Prefix Verb   URI Pattern               Controller#Action
posts GET    /posts(.:format)          posts#index
      POST   /posts(.:format)          posts#create
new_post GET    /posts/new(.:format)      posts#new
edit_post GET    /posts/:id/edit(.:format) posts#edit
post GET    /posts/:id(.:format)      posts#show
      PATCH  /posts/:id(.:format)      posts#update
      PUT    /posts/:id(.:format)      posts#update
      DELETE /posts/:id(.:format)      posts#destroy
</code>```

posts view, index.html.slim:

```<code>h1 Blog
- @posts.each do |post|
 h2 = link_to post.title, post
 p = post.content
 p = link_to 'Edit', edit_post_path(post)
 p = link_to 'Delete', post, :confirm => "Are you sure?", method: :delete
 br

p = link_to 'Add a new post', new_post_path
</code>```

Yet I continue to get an error inside the browser showing:

Unknown action, The action 'destroy' could not be found for PostsController

I seem to be getting a few of these basic problems since I updated to Rails 4, probably a minor oversight, anyone got any ideas?

答:
In posts_controller.rb, try using this code

def destroy
  Post.find(params[:id]).destroy
  redirect_to posts_path
end```
</div>
</div>
</p>

<p>And in index.html.erb use   </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><%= link_to "Delete", post, :data => {:confirm => "Are you sure?"}, :method => :delete %></code>```

Figured it out using rails 4.2.5.1. I think this is rails 4.x specific but it might work on other versions.

Body:
What is usually a simple error with a simple solution, I seem to be stuck:

posts#controller:

class PostsController < ApplicationController

def index
 @posts = Post.all
end

def show
 @post = Post.find params[:id]
end

def new
 @post = Post.new
end

def create
 @post = Post.create post_params

 if @post.save
  redirect_to posts_path, :notice => "Your post was saved!"
 else
  render 'new'
 end

end

private
 def post_params
  params.require(:post).permit(:title, :content)
 end

def edit
 @post = Post.find params[:id]
end

def update
 @post = Post.find params[:id]

 if @post.update_attributes params[:post]
  redirect_to posts_path
 else
  render 'edit'
 end
end

def destroy
 @post = Post.find params[:id]
 @post.destroy

 redirect_to posts_path, :notice => "Your post has been deleted"
end

end

routes.rb:

Blog::Application.routes.draw do

 resources :posts

end

rake routes:

Prefix Verb   URI Pattern               Controller#Action
posts GET    /posts(.:format)          posts#index
      POST   /posts(.:format)          posts#create
new_post GET    /posts/new(.:format)      posts#new
edit_post GET    /posts/:id/edit(.:format) posts#edit
post GET    /posts/:id(.:format)      posts#show
      PATCH  /posts/:id(.:format)      posts#update
      PUT    /posts/:id(.:format)      posts#update
      DELETE /posts/:id(.:format)      posts#destroy

posts view, index.html.slim:

h1 Blog
- @posts.each do |post|
 h2 = link_to post.title, post
 p = post.content
 p = link_to 'Edit', edit_post_path(post)
 p = link_to 'Delete', post, :confirm => "Are you sure?", method: :delete
 br

p = link_to 'Add a new post', new_post_path

Yet I continue to get an error inside the browser showing:

Unknown action, The action 'destroy' could not be found for PostsController

I seem to be getting a few of these basic problems since I updated to Rails 4, probably a minor oversight, anyone got any ideas?

Body:
In posts_controller.rb, try using this code

def destroy
  Post.find(params[:id]).destroy
  redirect_to posts_path
end

And in index.html.erb use

<%= link_to "Delete", post, :data => {:confirm => "Are you sure?"}, :method => :delete %>

Figured it out using rails 4.2.5.1. I think this is rails 4.x specific but it might work on other versions.


问:
Java hibernate how to use select ... where id in ()
I have Account class--account table mapping already.

Now I need use

from account where account_id in (select account_id from anothertable where...)

I got an error saying

org.hibernate.hql.ast.QuerySyntaxException: account is not mapped [from account where account_id in (select account_id from anothertable where...)]

Any suggestions?

答: I should use CLASS NAME, not TABLE NAME. Thank you for your time anyway.


问:
Android. Supporting 10 - 18 inch screen sizes
I'm sorry, if there is already a question like mine and for my English.

I have received a task where i need support tablets with screens from 10 to 18 inch.

All tutorials, "stackoverflow", "developer.android" and so on, are explain me how to support 10'inch tablets or smaller, xlarge, sw720dp, but what's about bigger sizes.

I have developed layout for resolution 1600, but then i chose device with another dpi, and for "mdpi, hdpi, xhdpi, tv, dpi, 280dpi" it's also different. And for every resolution "1080, 768, 800, 600, 1536, 1440, 2048."

I don't think i need to create a lot of layout folders (or values with dimens) for every resolution and dpi, like "layout-land-sw1600dp-mdpi" or (value-w1600dp-mdpi).

Through "weight" it's bad practice how i understood. So i set fixed values.
I have many TextViews with different sp, icons(svg) sizes, margins, paddings. I can't use only match_parent and wrap_content. But if i'm not, there are a lot of values.

And my question, how do it right, and can you help me, please.

PS. How i already said I used internet sources but can't found what i need. Maybe i not very good at that.

答:
I have got answer from my mentor.
I do not know, is it right answer, but it helped me.

I had to use only 3 folders:

values-sw720dp

values-sw1080dp

values-sw1280dp

It worked perfectly, unlike the decisions that i found early.


问:
Using toCharArray to check if String has any non-digits
So I'm new to java and trying to write some code for a project. I'm trying to use toCharArray to check if String has any non-digits. This is my code I've written so far:

```<code>public void setMobile(String mobile)
{
   boolean ok = true;
   char[] mob = mobile.toCharArray();
   for(int index = 0; Character.isDigit(mob) == true; index++)
   {

   }

   if(ok == true)
   {
       this.mobile = mobile;
   }
}
</code>```

I'm trying to check if mobile has any letter, and if so, do not assign mobile to this.mobile.

答:
I assume you want to learn the solution in basic java.
My suggestion would be check each character if it is a number or not something like this:

```<code>public void setMobile(String mobile)
{
    boolean flag=true;
    for(int index=0;i<mobile.length();index++)
    {
        if(mobile.charAt(index) < '0' || mobile.charAt(index) > '9')
            flag=false;
    }
    if(flag==true)
        this.mobile=mobile;
}
</code>```

Much simpler and intuitive and no need for extra data structures.

Body:
So I'm new to java and trying to write some code for a project. I'm trying to use toCharArray to check if String has any non-digits. This is my code I've written so far:

public void setMobile(String mobile)
{
   boolean ok = true;
   char[] mob = mobile.toCharArray();
   for(int index = 0; Character.isDigit(mob) == true; index++)
   {

   }

   if(ok == true)
   {
       this.mobile = mobile;
   }
}

I'm trying to check if mobile has any letter, and if so, do not assign mobile to this.mobile.

Body:
I assume you want to learn the solution in basic java.
My suggestion would be check each character if it is a number or not something like this:

public void setMobile(String mobile)
{
    boolean flag=true;
    for(int index=0;i<mobile.length();index++)
    {
        if(mobile.charAt(index) < '0' || mobile.charAt(index) > '9')
            flag=false;
    }
    if(flag==true)
        this.mobile=mobile;
}

Much simpler and intuitive and no need for extra data structures.


答:
That's where ^ comes in: it anchors a piece of regex to the start of the string (or the line, in m multiline mode). Because a 'valid' opening bracket is either at the start of a string or after a non-\ character, we can use the following regex:

```<code>/(?:^|[^\\])\{/g
</code>```

I added the g global flag because we want to match all 'valid' opening brackets. Example use:

console.log("{'lalala'} text before \\{'lalala'\\} {'lalala'} text after".match(/(?:^|[^\\])\{/g))```

If you want to use the regex in a replace, you might want to capture the character before the bracket, as that gets replaced as well.

Title: How to find char if there is not another one before

Body:
That's where ^ comes in: it anchors a piece of regex to the start of the string (or the line, in m multiline mode). Because a 'valid' opening bracket is either at the start of a string or after a non-\ character, we can use the following regex:

/(?:^|[^\\])\{/g

I added the g global flag because we want to match all 'valid' opening brackets. Example use:

console.log("{'lalala'} text before \\{'lalala'\\} {'lalala'} text after".match(/(?:^|[^\\])\{/g))

If you want to use the regex in a replace, you might want to capture the character before the bracket, as that gets replaced as well.


问:
i686-linux-gcc:error trying to exec 'cc1':execvp:No such file or directory
When I run make otapackge on android4.4 ，it runs with the errori686-linux-gcc:error trying to exec 'cc1':execvp:No such file or directorywhen build fs_config,I am very confused about that

答: I fixed it by export PATH=../prebuilts/gcc/linux-x86/host/.../i686-linux/4.4.3/:$PATH</p>


问:
iterative render with node and express
New to node and async and still struggling with concepts.

Trying to use express/handlebars render with a callback to iteratively build an html body with content from an array.  End goal is to send a response with a number of emails each one individually rendered using a view.hbs.

Got this far but realised it was never going to work. res.render can't pass my html variable back in the callback and res.send would run before the renders have completed???

```<code>function buildRes (req, res, email) {
    var html = '';
    Object.keys(email).forEach(function (i) {
        res.render('emailPanel', {subject: email[i].subject, body: email[i].body},
            function(err, renOut) {
                if err throw err;
                html=html+renOut;
            }
        )
    })
    res.send(html);
}
</code>```

Any suggestions on how I should be approaching this problem?

Started out trying to use handlebars #each helper to do the iteration but all of the examples show a simple list whereas in my case there a multiple array parameters to be passed to the render.

答: I'm still not sure what you're trying to accomplish with this, but one is for sure, I think it's better for you to do all looping inside your view by passing the entire array (filtered) with res.render to your view. Also note that you can respond only once per request. </p>

Title: iterative render with node and express

Body:
New to node and async and still struggling with concepts.

Trying to use express/handlebars render with a callback to iteratively build an html body with content from an array.  End goal is to send a response with a number of emails each one individually rendered using a view.hbs.

Got this far but realised it was never going to work. res.render can't pass my html variable back in the callback and res.send would run before the renders have completed???

function buildRes (req, res, email) {
    var html = '';
    Object.keys(email).forEach(function (i) {
        res.render('emailPanel', {subject: email[i].subject, body: email[i].body},
            function(err, renOut) {
                if err throw err;
                html=html+renOut;
            }
        )
    })
    res.send(html);
}

Any suggestions on how I should be approaching this problem?

Started out trying to use handlebars #each helper to do the iteration but all of the examples show a simple list whereas in my case there a multiple array parameters to be passed to the render.


问:
SQL giving me headache - multiple joins
First I'll explain my scenario. Here's the 2 general tables in use:

Accounts:

LegacyID = The identifer of the
account

InvoiceAccount = An account can have
multiple subaccounts in the same
table. This    field is the LegacyID
of its parent account

Customer = There can be two different
types of accounts, and they can share
ID's - so this column differentiates
between the 2. For the purposes of my
SQL I always want it to be true rather
than false

AllocatedUser = The username of the
person who needs to see this
deliveries. This is only populated on
the parent account, so I need to link
back to get this for the subaccounts

Deliveries:

LegacyID = The deliveries identifier

Customer = The LegacyID of the account
related to the delivery (can be a
subaccount)

OnHold = A flag which for the purposes
of my query needs to be 'true'

Now that's explained, basically I need an SQL which returns any deliveries that are 'OnHold', but only for deliveries for accounts that are allocated the logged in user. The query for selecting the AllocatedUser if the delivery links to a parent account was simple, but I'm having issues with returning rows if the delivery is linked to a subaccount - it's simply not returning any. Here is the SQL below:

```<code>SELECT     Deliveries_1.LegacyID, Deliveries_1.TripDate, Deliveries_1.OnHoldReason, Account_2.AllocatedUser
FROM         Deliveries AS Deliveries_1 INNER JOIN
                      Account AS Account_1 ON Deliveries_1.Customer = Account_1.InvoiceAccount INNER JOIN
                      Account AS Account_2 ON Account_1.InvoiceAccount = Account_2.LegacyID
WHERE     (Deliveries_1.OnHold = @OnHold) AND (Account_2.Customer = 'True') AND (Account_2.AllocatedUser = @AllocatedUser)
</code>```

My mind is frazzled from trying to work out why it don't work at the moment - I'd really appreciate any advice.

Thanks!

答:
```<code> ON Deliveries_1.Customer = Account_1.InvoiceAccount
 ON Account_1.InvoiceAccount = Account_2.LegacyID
</code>```

If both of these criteria are true, then Delivery.Customer would equal Account2.LegacyId (delivery would have to be on the parent account).  I don't think that's what you intended.

Perhaps you meant

```<code> ON Deliveries_1.Customer = Account_1.LegacyID
 ON Account_1.InvoiceAccount = Account_2.LegacyID
</code>```

Title: SQL giving me headache - multiple joins

Body:
First I'll explain my scenario. Here's the 2 general tables in use:

Accounts:

LegacyID = The identifer of the
account

InvoiceAccount = An account can have
multiple subaccounts in the same
table. This    field is the LegacyID
of its parent account

Customer = There can be two different
types of accounts, and they can share
ID's - so this column differentiates
between the 2. For the purposes of my
SQL I always want it to be true rather
than false

AllocatedUser = The username of the
person who needs to see this
deliveries. This is only populated on
the parent account, so I need to link
back to get this for the subaccounts

Deliveries:

LegacyID = The deliveries identifier

Customer = The LegacyID of the account
related to the delivery (can be a
subaccount)

OnHold = A flag which for the purposes
of my query needs to be 'true'

Now that's explained, basically I need an SQL which returns any deliveries that are 'OnHold', but only for deliveries for accounts that are allocated the logged in user. The query for selecting the AllocatedUser if the delivery links to a parent account was simple, but I'm having issues with returning rows if the delivery is linked to a subaccount - it's simply not returning any. Here is the SQL below:

SELECT     Deliveries_1.LegacyID, Deliveries_1.TripDate, Deliveries_1.OnHoldReason, Account_2.AllocatedUser
FROM         Deliveries AS Deliveries_1 INNER JOIN
                      Account AS Account_1 ON Deliveries_1.Customer = Account_1.InvoiceAccount INNER JOIN
                      Account AS Account_2 ON Account_1.InvoiceAccount = Account_2.LegacyID
WHERE     (Deliveries_1.OnHold = @OnHold) AND (Account_2.Customer = 'True') AND (Account_2.AllocatedUser = @AllocatedUser)

My mind is frazzled from trying to work out why it don't work at the moment - I'd really appreciate any advice.

Thanks!

Body:
 ON Deliveries_1.Customer = Account_1.InvoiceAccount
 ON Account_1.InvoiceAccount = Account_2.LegacyID

If both of these criteria are true, then Delivery.Customer would equal Account2.LegacyId (delivery would have to be on the parent account).  I don't think that's what you intended.

Perhaps you meant

 ON Deliveries_1.Customer = Account_1.LegacyID
 ON Account_1.InvoiceAccount = Account_2.LegacyID


问:
JavaFX Node partial border
Having a Node for example VBox I am trying to add a border and there are 2 ways I can think of - using css or using new Border () etc..

How can I remove part of the border ? i.e remove the bottom part of the border

答:
You can specify different styles for the borders on different sides

Using Border

```<code>@Override
public void start(Stage primaryStage) {
    Region root = new Region();
    root.setBorder(new Border(new BorderStroke(Color.RED, Color.RED, Color.RED, Color.RED,
            BorderStrokeStyle.SOLID, BorderStrokeStyle.SOLID, BorderStrokeStyle.NONE, BorderStrokeStyle.SOLID,
            CornerRadii.EMPTY, new BorderWidths(5), Insets.EMPTY)));

    Scene scene = new Scene(root, 300, 300);

    primaryStage.setScene(scene);
    primaryStage.show();
}
</code>```

Using inline css

```<code>root.setStyle("-fx-border-style: solid solid none solid; -fx-border-width: 5; -fx-border-color: red;");
</code>```

Using a css stylesheet

.root { /* modify the selector according to your needs */
    -fx-border-style: solid solid none solid;
    -fx-border-width: 5;
    -fx-border-color: red;
}
```

Title: JavaFX Node partial border

Body:
You can specify different styles for the borders on different sides

Using Border

@Override
public void start(Stage primaryStage) {
    Region root = new Region();
    root.setBorder(new Border(new BorderStroke(Color.RED, Color.RED, Color.RED, Color.RED,
            BorderStrokeStyle.SOLID, BorderStrokeStyle.SOLID, BorderStrokeStyle.NONE, BorderStrokeStyle.SOLID,
            CornerRadii.EMPTY, new BorderWidths(5), Insets.EMPTY)));

    Scene scene = new Scene(root, 300, 300);

    primaryStage.setScene(scene);
    primaryStage.show();
}

Using inline css

root.setStyle("-fx-border-style: solid solid none solid; -fx-border-width: 5; -fx-border-color: red;");

Using a css stylesheet

.root { /* modify the selector according to your needs */
    -fx-border-style: solid solid none solid;
    -fx-border-width: 5;
    -fx-border-color: red;
}


问:
AngularJS wait for $http request
I have an AnuglarJS app using ui-router and i have a http request that tells information about the user such as login state, access, language, user group, what controllers he can access and so on. It also defines behavior for some controllers and my ui-router states rely on it.

```<code>$http.get("/user").then(function(response) {
    UserService.userData = response.data.userData,
});
</code>```

Now I would like to delay all of the ui-router state change AND delay Services to be loaded if possible. And only allow anything to happen in the angular app after the request returned. So I can either redirect the user to the login page or load the proper templates, or do whatever i want inside the application based on the information received.

I would like this to apply to multiple routes with possibly adding exceptions.

So the goal i would like to achieve is to delay the angular.js app being loaded, wait for the http request to finish then continue the application.

答:
You could achieve this with $stateChangeStartdefault event provided by ui-router. It get called before any route change. You could put this stuff in the run() part of your main application module define object.

```<code>/**
 * Before state change / page switch
 */
$rootScope.$on("$stateChangeStart", function (event, toState, toParams, fromState, fromParams, options) {

   //prevent default route change if user is not available in factory/service.
   if ((!UserService.userData || !UserService.userData.loggedIn)
          && toState.name !== 'login') {

        event.preventDefault();

        $http.get("/user").then(function(response) {
            if (response.data.loggedIn) {
                UserService.userData = response.data.userData;
                if (toState.name !== fromState.name) {
                   $state.go(toState.name, toParams, options);
                }
            } else {
                $state.go('login');
            }
        });
   }
});
</code>```

Hint: It would be much better to not fire a HTTP-Request on any route-change just for checking the login session state. You could store the session state into localStorage which brings you performance push. Check this session state on any request which recives data from a secured route in your backend. If the session is not active any more, redirect the user in the moment he tries to access this data.

Title: AngularJS wait for $http request

Body:
I have an AnuglarJS app using ui-router and i have a http request that tells information about the user such as login state, access, language, user group, what controllers he can access and so on. It also defines behavior for some controllers and my ui-router states rely on it.

$http.get("/user").then(function(response) {
    UserService.userData = response.data.userData,
});

Now I would like to delay all of the ui-router state change AND delay Services to be loaded if possible. And only allow anything to happen in the angular app after the request returned. So I can either redirect the user to the login page or load the proper templates, or do whatever i want inside the application based on the information received.

I would like this to apply to multiple routes with possibly adding exceptions.

So the goal i would like to achieve is to delay the angular.js app being loaded, wait for the http request to finish then continue the application.

Body:
You could achieve this with $stateChangeStartdefault event provided by ui-router. It get called before any route change. You could put this stuff in the run() part of your main application module define object.

/**
 * Before state change / page switch
 */
$rootScope.$on("$stateChangeStart", function (event, toState, toParams, fromState, fromParams, options) {

   //prevent default route change if user is not available in factory/service.
   if ((!UserService.userData || !UserService.userData.loggedIn)
          && toState.name !== 'login') {

        event.preventDefault();

        $http.get("/user").then(function(response) {
            if (response.data.loggedIn) {
                UserService.userData = response.data.userData;
                if (toState.name !== fromState.name) {
                   $state.go(toState.name, toParams, options);
                }
            } else {
                $state.go('login');
            }
        });
   }
});

Hint: It would be much better to not fire a HTTP-Request on any route-change just for checking the login session state. You could store the session state into localStorage which brings you performance push. Check this session state on any request which recives data from a secured route in your backend. If the session is not active any more, redirect the user in the moment he tries to access this data.


问:
Weka discretising attribute where one value is most common by far
I have a dataset in which there's a numerical attribute for the 'number of days since last contact' but the value -1 is being used to indicate that there hasn't been a last contact. It is by far the largest value for this attribute.

My idea is to discretise this attribute but how can I ensure there is a 'no contact'/-1 bin?

Also, is this the correct approach to this problem?

答:
The proper approach supposedly is to

Split the data into -1 and everything else

Apply binning to the values in the 'everything else' set only

Concatenate the data sets again (it may be good to shuffle, too)


问:
Pandas Dataframe: Split a column into multiple columns
I have a pandas dataframe with columns names as: (columns type as Object)

```<code>1. x_id
2. y_id
3. Sentence1
4. Sentences2
5. Label
</code>```

I want to separate sentences1 and sentence2 into multiple columns in same dataframe.

Here is an example: dataframe names as df

```<code>x_id     y_id     Sentence1          Sentence2          Label
0        2        This is a ball     I hate you         0
1        5        I am a boy         Ahmed Ali          1
2        1        Apple is red       Rose is red        1
3        9        I love you so much Me too             1
</code>```

After splitting the columns[Sentence1,Sentence2] by ' ' Space, dataframe looks like:

```<code>x_id     y_id     1     2     3    4     5      6      7     8      Label
0        2        This  is    a    ball  NONE   I      hate  you    0
1        5        I     am    a    boy   NONE   Ahmed  Ali   NONE   1
2        1        Apple is    red  NONE  NONE   Rose   is    red    1
3        9        I     love  you  so    much   Me     too   NONE   1
</code>```

How to split the columns like this in python? How to do this using pandas dataframe?

答:
It looks like a machine learning problem. Converting from 1 col to max words columns this way may not be efficient.

Another (probably more efficient) solution is converting each words to integer and then padding to the longest sentences. Tensorflow as tools for that.

Body:
I have a pandas dataframe with columns names as: (columns type as Object)

1. x_id
2. y_id
3. Sentence1
4. Sentences2
5. Label

I want to separate sentences1 and sentence2 into multiple columns in same dataframe.

Here is an example: dataframe names as df

x_id     y_id     Sentence1          Sentence2          Label
0        2        This is a ball     I hate you         0
1        5        I am a boy         Ahmed Ali          1
2        1        Apple is red       Rose is red        1
3        9        I love you so much Me too             1

After splitting the columns[Sentence1,Sentence2] by ' ' Space, dataframe looks like:

x_id     y_id     1     2     3    4     5      6      7     8      Label
0        2        This  is    a    ball  NONE   I      hate  you    0
1        5        I     am    a    boy   NONE   Ahmed  Ali   NONE   1
2        1        Apple is    red  NONE  NONE   Rose   is    red    1
3        9        I     love  you  so    much   Me     too   NONE   1

How to split the columns like this in python? How to do this using pandas dataframe?


问:
Sorting an array by providing an array of pointers as arguments
I wrote this code, but it is only giving me an address of something:

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

void swap(int* a,int* b)
{
    int temp=*a;
    *a=*b;
    *b=temp;
}

void sort(int* p[],int n)
{
    for(int i=0; i<n;i++)
    {
        if(*p[i]>*p[i+1])
        swap(p[i],p[i+1]);
    }
}

int main()
{
    int arr[]={8,6,5,4,3,7,1};
    int* p[7];

    for(int i=0;i<7;i++)
    {
        p[i]=&arr[i];
    }

    sort(p,7);

    /*i tried to change arr[1] to p[1] or *p[1] but same output*/
    cout<<arr[1]<<arr[2];
    return 0;
}
</code>```

I think I'm lacking in concept somewhere. The complete question is this:

Write the following function that indirectly sorts the floats pointed to by the first n pointers in the array p by rearranging the pointers: void sort(float* p[],int n)

Please help.

答:
Here is a better way of doing what you want, there are many ways it can be done better but it looks like your new to c++ so I tried to make it as simple as possible.

```<code>#include "stdafx.h"
#include<iostream>
using namespace std;

//not needed, std::swap does the same job!
void swap(int *a, int *b)
{
    std::swap(a, b);
}

//using a pointer to the array is better!
void sort(int arr[], int n)
{
    //two loops are needed to sort the entire array!
    for (int x(0); x < n - 1; x++)
    {
        //optimize the loop by removing already sorted items from loop
        int sorted = n - x;
        for (int y(0); y < sorted - 1; ++y)
            if (arr[y] > arr[y + 1])
                std::swap(arr[y], arr[y + 1]);
    }
}

int main()
{
    //vector or std::array better option!
    int arr[] { 8,6,5,4,3,7,1 };

    //provide the array to sort(), no need to make stuff harder
    sort(arr, 7);

    //Show you that the sort worked!
    for (int ccc = 0; ccc < 7; ccc++)
        std::cout << arr[ccc] << ' ';

    std::cout << '\n';

    cout << "Index 5: " << arr[5] << "\nIndex 6: " << arr[6] << "\n";

    return 0;
}
</code>```

Here is a very good tutorial on sorting arrays: http://www.learncpp.com/cpp-tutorial/64-sorting-an-array-using-selection-sort/

Body:
I wrote this code, but it is only giving me an address of something:

#include<iostream>
using namespace std;

void swap(int* a,int* b)
{
    int temp=*a;
    *a=*b;
    *b=temp;
}

void sort(int* p[],int n)
{
    for(int i=0; i<n;i++)
    {
        if(*p[i]>*p[i+1])
        swap(p[i],p[i+1]);
    }
}

int main()
{
    int arr[]={8,6,5,4,3,7,1};
    int* p[7];

    for(int i=0;i<7;i++)
    {
        p[i]=&arr[i];
    }

    sort(p,7);

    /*i tried to change arr[1] to p[1] or *p[1] but same output*/
    cout<<arr[1]<<arr[2];
    return 0;
}

I think I'm lacking in concept somewhere. The complete question is this:

Write the following function that indirectly sorts the floats pointed to by the first n pointers in the array p by rearranging the pointers: void sort(float* p[],int n)

Please help.

Body:
Here is a better way of doing what you want, there are many ways it can be done better but it looks like your new to c++ so I tried to make it as simple as possible.

#include "stdafx.h"
#include<iostream>
using namespace std;

//not needed, std::swap does the same job!
void swap(int *a, int *b)
{
    std::swap(a, b);
}

//using a pointer to the array is better!
void sort(int arr[], int n)
{
    //two loops are needed to sort the entire array!
    for (int x(0); x < n - 1; x++)
    {
        //optimize the loop by removing already sorted items from loop
        int sorted = n - x;
        for (int y(0); y < sorted - 1; ++y)
            if (arr[y] > arr[y + 1])
                std::swap(arr[y], arr[y + 1]);
    }
}

int main()
{
    //vector or std::array better option!
    int arr[] { 8,6,5,4,3,7,1 };

    //provide the array to sort(), no need to make stuff harder
    sort(arr, 7);

    //Show you that the sort worked!
    for (int ccc = 0; ccc < 7; ccc++)
        std::cout << arr[ccc] << ' ';

    std::cout << '\n';

    cout << "Index 5: " << arr[5] << "\nIndex 6: " << arr[6] << "\n";

    return 0;
}

Here is a very good tutorial on sorting arrays: http://www.learncpp.com/cpp-tutorial/64-sorting-an-array-using-selection-sort/


问:
Laravel 5.1 rename project
What is the best solution if I want to rename my laravel 5.1 project, I just tried to rename one but it did not work properly got some errors.

Are there some kind of steps one has to do to rename a laravel project?

答:
From laravel version 5.3^ there is a function to call the app name

```<code>config('app.name');
</code>```

You can change the default name 'Laravel' inside this file

```<code>config/app.php

'name' => 'Laravel',
</code>```

And also inside .env file

APP_NAME=Laravel

Title: Laravel 5.1 rename project

Body:
From laravel version 5.3^ there is a function to call the app name

config('app.name');

You can change the default name 'Laravel' inside this file

config/app.php

'name' => 'Laravel',

And also inside .env file

APP_NAME=Laravel


问:
Get files from web directory
I wanted to just get random Images from http://random.cat/, so I wanted to index them using Directory.GetFiles or something like that, but this doesn't work. So what would be the best way to get the functionality of Directory.GetFiles but for http://random.cat/i (this is where the Images are stored, I think)?

Thanks in advance!

答:
You do not have access to the images database but they provide an api to retrieve one image at a time.

Create a basic model:

```<code>public class RandomImage
{
    public string file { get; set; }
}
</code>```

Then you can use WebClient to do that:

```<code>public string RandomImage()
{
    string result = null;

    var apiurl = "http://random.cat";

    HttpClient client = new HttpClient();
    client.BaseAddress = new Uri(apiurl);
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

    HttpResponseMessage ResponseMessage = client.GetAsync(apiurl + "/meow").Result; // The .Result part will make this method not async
    if (ResponseMessage.IsSuccessStatusCode)
    {
        var ResponseData = ResponseMessage.Content.ReadAsStringAsync().Result;
        var MyRandomImage = JsonConvert.DeserializeObject<RandomImage>(ResponseData);

        result = MyRandomImage.file; // This is the url for the file
    }

    // Return
    return result;
}
</code>```

Call the function from your methods:

```<code>var MyImage = RandomImage();
</code>```

Title: Get files from web directory

Body:
You do not have access to the images database but they provide an api to retrieve one image at a time.

Create a basic model:

public class RandomImage
{
    public string file { get; set; }
}

Then you can use WebClient to do that:

public string RandomImage()
{
    string result = null;

    var apiurl = "http://random.cat";

    HttpClient client = new HttpClient();
    client.BaseAddress = new Uri(apiurl);
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

    HttpResponseMessage ResponseMessage = client.GetAsync(apiurl + "/meow").Result; // The .Result part will make this method not async
    if (ResponseMessage.IsSuccessStatusCode)
    {
        var ResponseData = ResponseMessage.Content.ReadAsStringAsync().Result;
        var MyRandomImage = JsonConvert.DeserializeObject<RandomImage>(ResponseData);

        result = MyRandomImage.file; // This is the url for the file
    }

    // Return
    return result;
}

Call the function from your methods:

var MyImage = RandomImage();


问:
Start timer immediately in Elm
What I expected to the following code is to increment count asynchronously when I toggle timer on and off. But it always works synchronously (increments by 2).

How can I make it asynchronous?

EDIT: Maybe due to the shortage of my english capability, it seems the question is often misunderstood. I want the implementation which does exactly same behavior as my answer. And the point is, That two timers should increment the count separately by toggling.

```<code>import Html exposing (program, div, button, text)
import Html.Events exposing (onClick)
import Time exposing (every, second)

main = program
  { init = ({cnt = 0, on = True}, Cmd.none)
  , view = view
  , update = update
  , subscriptions = subscriptions
  }

subscriptions model = Sub.batch
  [ every second (always Increment)
  , if model.on then every second (always Increment) else Sub.none
  ]

view model = div []
  [ button [ onClick Toggle ] [ text "-" ]
  , div [] [ text (toString model) ]
  , button [ onClick Increment ] [ text "+" ]
  ]

type Msg = Increment | Toggle

update msg model =
  case msg of
    Increment ->
      ({model | cnt = model.cnt + 1}, Cmd.none)
    Toggle ->
      ({model | on = not model.on}, Cmd.none)
</code>```

答:
Here's a version that counts up by 1 per second while on, and always allows manually incrementing by 1.

```<code>import Html exposing (program, div, button, text)
import Html.Events exposing (onClick)
import Time exposing (every, second)

main = program
  { init = ({cnt = 0, on = True}, Cmd.none)
  , view = view
  , update = update
  , subscriptions = subscriptions
  }

subscriptions model = Sub.batch
  [ every second (always Tick)
  ]

view model = div []
  [ button [ onClick Toggle ] [ text "Toggle" ]
  , div [] [ text (toString model) ]
  , button [ onClick Increment ] [ text "+" ]
  ]

type Msg = Tick | Toggle | Increment

update msg model =
  case msg of
    Increment ->
      ({model | cnt = model.cnt + 1}, Cmd.none)

    Tick ->
      case model.on of
        True ->
          ({model | cnt = model.cnt + 1}, Cmd.none)
        False ->
          (model, Cmd.none)

    Toggle ->
      ({model | on = not model.on}, Cmd.none)
</code>```

Title: Start timer immediately in Elm

Body:
What I expected to the following code is to increment count asynchronously when I toggle timer on and off. But it always works synchronously (increments by 2).

How can I make it asynchronous?

EDIT: Maybe due to the shortage of my english capability, it seems the question is often misunderstood. I want the implementation which does exactly same behavior as my answer. And the point is, That two timers should increment the count separately by toggling.

import Html exposing (program, div, button, text)
import Html.Events exposing (onClick)
import Time exposing (every, second)

main = program
  { init = ({cnt = 0, on = True}, Cmd.none)
  , view = view
  , update = update
  , subscriptions = subscriptions
  }

subscriptions model = Sub.batch
  [ every second (always Increment)
  , if model.on then every second (always Increment) else Sub.none
  ]

view model = div []
  [ button [ onClick Toggle ] [ text "-" ]
  , div [] [ text (toString model) ]
  , button [ onClick Increment ] [ text "+" ]
  ]

type Msg = Increment | Toggle

update msg model =
  case msg of
    Increment ->
      ({model | cnt = model.cnt + 1}, Cmd.none)
    Toggle ->
      ({model | on = not model.on}, Cmd.none)

Body:
Here's a version that counts up by 1 per second while on, and always allows manually incrementing by 1.

import Html exposing (program, div, button, text)
import Html.Events exposing (onClick)
import Time exposing (every, second)

main = program
  { init = ({cnt = 0, on = True}, Cmd.none)
  , view = view
  , update = update
  , subscriptions = subscriptions
  }

subscriptions model = Sub.batch
  [ every second (always Tick)
  ]

view model = div []
  [ button [ onClick Toggle ] [ text "Toggle" ]
  , div [] [ text (toString model) ]
  , button [ onClick Increment ] [ text "+" ]
  ]

type Msg = Tick | Toggle | Increment

update msg model =
  case msg of
    Increment ->
      ({model | cnt = model.cnt + 1}, Cmd.none)

    Tick ->
      case model.on of
        True ->
          ({model | cnt = model.cnt + 1}, Cmd.none)
        False ->
          (model, Cmd.none)

    Toggle ->
      ({model | on = not model.on}, Cmd.none)


问:
Azure portal returns error 400 when trying to manage my database
When I try to open the azure web-portal to manage my database with:
https://manage.windowsazure.com/@MyId#Workspaces/MobileServicesExtension/apps/MyApp/tables/MyTable/columns
I only get error "400, try again later or contact support". This was working fine for a long time and since a while its this error. I didn't change anything and the mobile app using this db is also still working, but I just would like to access my managment portal.
I'm on a free azure acount, so no access to proper support, but maybe here somebody can help?</p>

答:
Problem solved with MS-support:

"you should be able to find the Tables and record related to your mobile app under mobile section, if you browsed to your mobile app on portal.azure.com > Easy Tables, Easy APIs, Data connection, all of these blades are related to your mobile app,
to find your tables choose Easy tables."


问:
Pass data between routes in Angular2
I'm trying to share data between the login page and the sign-up page. If the user tries to login and authentication fails I wish to redirect to the sign-up page with the login attempt data pre-filled. I'm trying to pass the data using a shared service, declared as provider in app.module.ts

```<code>import {Component, Input, OnInit} from '@angular/core';
import {Router} from "@angular/router";
import {AuthenticationService} from "../../services/authentication.service";
import {SharedService} from "../../services/shared.service";

@Component({
    selector: 'my-page-login',
    templateUrl: 'login.component.html',
    styleUrls: ['login.component.scss']
})

export class PageLoginComponent implements OnInit {

    constructor(
                 private router: Router,
                 private authenticationService: AuthenticationService,
                 private sharedService: SharedService
    ) {}

    onSubmit(data) {

        this.sharedService.setData(data);
        this.authenticationService.login(data)
            .subscribe(
                data => {
                },
                error => {

                    this.router.navigate(['/sign-up']);

                });
    }
}
</code>```

I'm using a shared service for passing the data to the sign-up page.

```<code>import { Injectable } from '@angular/core';
import { Subject }    from 'rxjs/Subject';
import {Observable} from "rxjs/Observable";

@Injectable()
export class SharedService {
    // Observable string sources
    private subject = new Subject<string>();

    setData(data) {
        this.subject.next(data);
    }
    getData(): Observable<any> {
        return this.subject.asObservable();
    }

}
</code>```

Data are not available in sign-up component

```<code>import { Component } from '@angular/core';
import {Router} from "@angular/router";
import {SharedService} from "../../services/shared.service";
import { Subscription } from 'rxjs/Subscription';

@Component({
    selector: 'my-page-sign-up',
    styles: [],
    templateUrl: './sign-up.component.html'
})

export class PageSignUpComponent {
    private subscription: Subscription;
    constructor(
        private router: Router,
        private sharedService: SharedService
    ) {

    }

    ngOnInit() {

        this.subscription = this.sharedService.getData().subscribe(
            data => {

                console.log(data, "Data"); //not getting here
            });
    }
</code>```

答:
Data are not available in sign-up component

It's because Subject does not cache anything. When you emit something to it, only subscribers that are currently subscribed will get the message. Otherwise the message is lost forever.

If you want the value to be cached, use a BehaviorSubject instead.

See also:

Angular 2 special Observables (Subject / Behaviour subject / ReplaySubject)

Title: Pass data between routes in Angular2

Body:
I'm trying to share data between the login page and the sign-up page. If the user tries to login and authentication fails I wish to redirect to the sign-up page with the login attempt data pre-filled. I'm trying to pass the data using a shared service, declared as provider in app.module.ts

import {Component, Input, OnInit} from '@angular/core';
import {Router} from "@angular/router";
import {AuthenticationService} from "../../services/authentication.service";
import {SharedService} from "../../services/shared.service";

@Component({
    selector: 'my-page-login',
    templateUrl: 'login.component.html',
    styleUrls: ['login.component.scss']
})

export class PageLoginComponent implements OnInit {

    constructor(
                 private router: Router,
                 private authenticationService: AuthenticationService,
                 private sharedService: SharedService
    ) {}

    onSubmit(data) {

        this.sharedService.setData(data);
        this.authenticationService.login(data)
            .subscribe(
                data => {
                },
                error => {

                    this.router.navigate(['/sign-up']);

                });
    }
}

I'm using a shared service for passing the data to the sign-up page.

import { Injectable } from '@angular/core';
import { Subject }    from 'rxjs/Subject';
import {Observable} from "rxjs/Observable";

@Injectable()
export class SharedService {
    // Observable string sources
    private subject = new Subject<string>();

    setData(data) {
        this.subject.next(data);
    }
    getData(): Observable<any> {
        return this.subject.asObservable();
    }

}

Data are not available in sign-up component

import { Component } from '@angular/core';
import {Router} from "@angular/router";
import {SharedService} from "../../services/shared.service";
import { Subscription } from 'rxjs/Subscription';

@Component({
    selector: 'my-page-sign-up',
    styles: [],
    templateUrl: './sign-up.component.html'
})

export class PageSignUpComponent {
    private subscription: Subscription;
    constructor(
        private router: Router,
        private sharedService: SharedService
    ) {

    }

    ngOnInit() {

        this.subscription = this.sharedService.getData().subscribe(
            data => {

                console.log(data, "Data"); //not getting here
            });
    }


问:
unable to Deserialize a wcf Class object
I have a WCF service with WSHttpBinding. Both Client and server are on .net Platform. On windows form application I am calling a function to get the task and save that task in a file, later on, load that task as:

```<code>DataContract()>
Public Class Task

    <DataMember()>
    Public Property UID As String

    <DataMember()>
    Public Property Name As String

    <DataMember()>
    Public Property progress As String

    <DataMember()>
    Public Property Type As Long
    <DataMember()>
    Public Property Version As String  Version

    <DataMember()>
        Public Property Status As Long
    <DataMember()>
        Public Property Narr As String
    <DataMember()>
        Public Property Dt As Date
End Class
</code>```

I am calling a function that serializes the object and saves to file so that later on, that can easily be loaded to object as:

```<code>Function GetSaveTask()
   Dim Task_ As serv.Task = ServObj.GetTask() '' Calling Service to get Task
   Dim ObStrng As String = Jserialize(Task_)
   File.WriteAllText("D:\Task.ini", ObStrng)
End Function
Function LoadTask()
   Dim Task_ As serv.Task
   Dim ObStrng As String = File.ReadAllText("D:\Task.ini")
   Task_ = Deserialize(Of serv.Task)(ObStrng)

End Function
Public Shared Function Jserialize(Of T)(ByVal obb As Object) As Object
    Dim serializer As New Web.Script.Serialization.JavaScriptSerializer()
    Return serializer.Serialize(obb)
End Function
 Public Function Deserialize(Of T)(ByVal obb As String) As Object
    Dim JavaScriptSerializer As New Web.Script.Serialization.JavaScriptSerializer()
    Return JavaScriptSerializer.Deserialize(Of T)(obb)
End Function
</code>```

Serialized Data in Task.ini :

```<code>[{"ExtensionData":{},"Dt":"\/Date(1490985000000)\/","Name":"Task-2017",
"Narr":null,"Status":20,"Type":0,"UID":"ABBB-KKKK","Version":"1.0.1.2","progress":20}]
</code>```

I can only use System.Web.Script.Serialization.JavaScriptSerializer.
The Task_ can easily serialize and saved to File. But LoadTask() is unable to Deserialize and throwing an error :

No parameterless constructor defined for the type of 'System.Runtime.Serialization.ExtensionDataObject'

I have tried to create a proxy class same as Class Task, and save it to file. But the service keeps on updating the DataMember. We just update the service reference and everything works fine. So the proxy class will be an overhead and have to keep on updating as service class changes (which is not possible throughout the project).

Why is it unable to deserialize? Is there any way to load all, except ExtensionData?

答:
ExtensionData is causing that error. The ExtensionData is actually a feature that must be built into the type to enable round-tripping. It is always emitted by the DataContractSerializer. As you said, service keeps on updating, one thing you can do is, every time updating the service reference, comment the ExtensionData and its implementation.

```<code> <System.NonSerializedAttribute()>  _
 Private extensionDataField As System.Runtime.Serialization.ExtensionDataObject
</code>```

and remove Implements :

```<code>Implements System.Runtime.Serialization.IExtensibleDataObject
</code>```

Body:
I have a WCF service with WSHttpBinding. Both Client and server are on .net Platform. On windows form application I am calling a function to get the task and save that task in a file, later on, load that task as:

DataContract()>
Public Class Task

    <DataMember()>
    Public Property UID As String

    <DataMember()>
    Public Property Name As String

    <DataMember()>
    Public Property progress As String

    <DataMember()>
    Public Property Type As Long
    <DataMember()>
    Public Property Version As String  Version

    <DataMember()>
        Public Property Status As Long
    <DataMember()>
        Public Property Narr As String
    <DataMember()>
        Public Property Dt As Date
End Class

I am calling a function that serializes the object and saves to file so that later on, that can easily be loaded to object as:

Function GetSaveTask()
   Dim Task_ As serv.Task = ServObj.GetTask() '' Calling Service to get Task
   Dim ObStrng As String = Jserialize(Task_)
   File.WriteAllText("D:\Task.ini", ObStrng)
End Function
Function LoadTask()
   Dim Task_ As serv.Task
   Dim ObStrng As String = File.ReadAllText("D:\Task.ini")
   Task_ = Deserialize(Of serv.Task)(ObStrng)

End Function
Public Shared Function Jserialize(Of T)(ByVal obb As Object) As Object
    Dim serializer As New Web.Script.Serialization.JavaScriptSerializer()
    Return serializer.Serialize(obb)
End Function
 Public Function Deserialize(Of T)(ByVal obb As String) As Object
    Dim JavaScriptSerializer As New Web.Script.Serialization.JavaScriptSerializer()
    Return JavaScriptSerializer.Deserialize(Of T)(obb)
End Function

Serialized Data in Task.ini :

[{"ExtensionData":{},"Dt":"\/Date(1490985000000)\/","Name":"Task-2017",
"Narr":null,"Status":20,"Type":0,"UID":"ABBB-KKKK","Version":"1.0.1.2","progress":20}]

I can only use System.Web.Script.Serialization.JavaScriptSerializer.
The Task_ can easily serialize and saved to File. But LoadTask() is unable to Deserialize and throwing an error :

No parameterless constructor defined for the type of 'System.Runtime.Serialization.ExtensionDataObject'

I have tried to create a proxy class same as Class Task, and save it to file. But the service keeps on updating the DataMember. We just update the service reference and everything works fine. So the proxy class will be an overhead and have to keep on updating as service class changes (which is not possible throughout the project).

Why is it unable to deserialize? Is there any way to load all, except ExtensionData?

Body:
ExtensionData is causing that error. The ExtensionData is actually a feature that must be built into the type to enable round-tripping. It is always emitted by the DataContractSerializer. As you said, service keeps on updating, one thing you can do is, every time updating the service reference, comment the ExtensionData and its implementation.

 <System.NonSerializedAttribute()>  _
 Private extensionDataField As System.Runtime.Serialization.ExtensionDataObject

and remove Implements :

Implements System.Runtime.Serialization.IExtensibleDataObject


答:
while some of the answers given before me are correct, I feel they only give you the answer to the problem without explaining what was your error.

Notice that one of the problems your code has is that you never set the okvariable to false, therefore you will always enter inside the if statement.

Another error is that you are assuming the only characters in a String are digit or letters, therefore checking for Character.isDigit() will tell you if that is or isn't a digit, but if the character is a backslash for example, Character.isDigit('\') will return false, even though it is not a letter.

the proper way to check if something is a letter or not is to check if it is between 'a' and 'z', or between 'A' and 'Z'.

once you have understood what is wrong, I would advise trying to change your current code to work before continuing with the answers given, just so you can understand how to do it in the simplest way and than continue with the answers given.

Title: Using toCharArray to check if String has any non-digits

Body:
So I'm new to java and trying to write some code for a project. I'm trying to use toCharArray to check if String has any non-digits. This is my code I've written so far:

public void setMobile(String mobile)
{
   boolean ok = true;
   char[] mob = mobile.toCharArray();
   for(int index = 0; Character.isDigit(mob) == true; index++)
   {

   }

   if(ok == true)
   {
       this.mobile = mobile;
   }
}

I'm trying to check if mobile has any letter, and if so, do not assign mobile to this.mobile.


问:
Sending email from specific server gives socket forbidden error
I get this error
An attempt was made to access a socket in a way forbidden by its access permissions xxx.xxx.xxx.xxx:587 when sending email from a godaddy server.

I have seen many questions like this but what's unique here is that, this code works on my local computer. It also works on my other Go daddy hosting Server.

This original server has TLS 1.0, because i needed TLS 1.2, I purchased a deluxe hosting plan and moved my code to this new server, then i start getting this error.  I've searched everywhere and used every combination of  port 587, 465, 25 along with ssl = false or true.

Any ideas please?

```<code>        using (SmtpClient smtpClient = new SmtpClient("smtp.gmail.com", 587))
        {

            MailMessage mail = new MailMessage();
           smtpClient.UseDefaultCredentials = false;

           smtpClient.Credentials = new NetworkCredential("********@gmail.com", "********");
            smtpClient.EnableSsl = true;
            string fromEmail = "********@gmail.com";
            mail.From = new MailAddress(fromEmail, "System");
            mail.To.Add(new MailAddress(toEmail));
            mail.Body = body.ToString();
            mail.Subject = subject;
            smtpClient.Send(mail);
        }
</code>```

答: Try to use port 2525 for 587, 465, 25. Some cloud providers disable all outbound traffic from 587, 465, 25 ports.</p>

Body:
I get this error
An attempt was made to access a socket in a way forbidden by its access permissions xxx.xxx.xxx.xxx:587 when sending email from a godaddy server.

I have seen many questions like this but what's unique here is that, this code works on my local computer. It also works on my other Go daddy hosting Server.

This original server has TLS 1.0, because i needed TLS 1.2, I purchased a deluxe hosting plan and moved my code to this new server, then i start getting this error.  I've searched everywhere and used every combination of  port 587, 465, 25 along with ssl = false or true.

Any ideas please?

        using (SmtpClient smtpClient = new SmtpClient("smtp.gmail.com", 587))
        {

            MailMessage mail = new MailMessage();
           smtpClient.UseDefaultCredentials = false;

           smtpClient.Credentials = new NetworkCredential("********@gmail.com", "********");
            smtpClient.EnableSsl = true;
            string fromEmail = "********@gmail.com";
            mail.From = new MailAddress(fromEmail, "System");
            mail.To.Add(new MailAddress(toEmail));
            mail.Body = body.ToString();
            mail.Subject = subject;
            smtpClient.Send(mail);
        }


问:
BigQuery Error – UNIQUE_HEAP requires an int32 argument
Using legacy SQL, I am trying to use COUNT(DISTINCT field, n) in Google BigQuery. But I am get following error:

UNIQUE_HEAP requires an int32 argument which is greater than 0 (error code: invalidQuery)

Here is my query that I have used:

```<code>SELECT
    hits.page.pagePath AS Page,
    COUNT(DISTINCT CONCAT(fullVisitorId, INTEGER(visitId)), 1e6) AS UniquePageviews,
    COUNT(DISTINCT fullVisitorId, 1e6) as Users
FROM
    [xxxxxxxx.ga_sessions_20170101]
GROUP BY
    Page
ORDER BY
    UniquePageviews DESC
LIMIT
    20
</code>```

BigQuery is not even showing line number of error therefore I am not sure which line is causing this error.

What could be possible cause of above error?

答:
Don't use 1e6 in your COUNT(DISTINCT). Instead, use an actual INTEGER value for the 2nd parameter 'N' (default is 1000), or use EXACT_COUNT_DISTINCT() instead.

COUNT(DISTINCT) documentation

EXACT_COUNT_DISTINCT() documentation

If you require greater accuracy from COUNT(DISTINCT), you can specify
  a second parameter, n, which gives the threshold below which exact
  results are guaranteed. By default, n is 1000, but if you give a
  larger n, you will get exact results for COUNT(DISTINCT) up to that
  value of n. However, giving larger values of n will reduce scalability
  of this operator and may substantially increase query execution time
  or cause the query to fail.

To compute the exact number of distinct values, use
  EXACT_COUNT_DISTINCT. Or, for a more scalable approach, consider using
  GROUP EACH BY on the relevant field(s) and then applying COUNT(*). The
  GROUP EACH BY approach is more scalable but might incur a slight
  up-front performance penalty.

Body:
Using legacy SQL, I am trying to use COUNT(DISTINCT field, n) in Google BigQuery. But I am get following error:

UNIQUE_HEAP requires an int32 argument which is greater than 0 (error code: invalidQuery)

Here is my query that I have used:

SELECT
    hits.page.pagePath AS Page,
    COUNT(DISTINCT CONCAT(fullVisitorId, INTEGER(visitId)), 1e6) AS UniquePageviews,
    COUNT(DISTINCT fullVisitorId, 1e6) as Users
FROM
    [xxxxxxxx.ga_sessions_20170101]
GROUP BY
    Page
ORDER BY
    UniquePageviews DESC
LIMIT
    20

BigQuery is not even showing line number of error therefore I am not sure which line is causing this error.

What could be possible cause of above error?


问:
Vuejs, Plugin, global method/property not found
What am I doing wrong here?  I install a plugin, and set a global property, but then in my method's I can't access that property.

main.js for my root Vue component

```<code>import Vue from 'vue'
...
Vue.use({
  install (Vue) {
    let googleAuth = null
    console.log('called!')
    Vue.auth = {
      setAuth (auth) {
        googleAuth = auth
      },
      isAuthenticated () {
        return googleAuth !== null && googleAuth.isSignedIn.get()
      },
      currentUser () {
        return googleAuth.currentUser.get()
      },
      currentUserProfile () {
        return this.currentUser().getBasicProfile()
      },
      getIdToken () {
        return this.currentUser().getAuthResponse().id_token
      }
    }
  }
})
</code>```

App.vue from root Vue component

```<code><template></template>
<script>
  export default {
    name: 'Trudit',
    data () {
      return {
        title: 'Trudit'
      }
    },
    methods: {
      onSignInSuccess (googleUser) {
        console.log(this)
        this.auth.setAuth(googleUser)   //<-  this.auth === undefined
      }
    }
  }
</script>
</code>```

Error

Uncaught TypeError: Cannot read property 'setAuth' of undefined
      at VueComponent.onSignInSuccess (eval at 57 (0.83049e6….hot-update.js:13), :17:16)
      at boundFn (eval at  (app.js:630), :126:14)
      at H_. (cb=gapi.loaded_0:285)
      at cb=gapi.loaded_0:175
      at h.r2 (cb=gapi.loaded_0:78)
      at xs (cb=gapi.loaded_0:81)
      at Wq (cb=gapi.loaded_0:81)
      at _.C.uea (cb=gapi.loaded_0:80)
      at Ap (cb=gapi.loaded_0:74)

答:
As @Srinivas Damam pointed out I needed to set it using prototype.

Vue.prototype.auth fixed it

Body:
What am I doing wrong here?  I install a plugin, and set a global property, but then in my method's I can't access that property.

main.js for my root Vue component

import Vue from 'vue'
...
Vue.use({
  install (Vue) {
    let googleAuth = null
    console.log('called!')
    Vue.auth = {
      setAuth (auth) {
        googleAuth = auth
      },
      isAuthenticated () {
        return googleAuth !== null && googleAuth.isSignedIn.get()
      },
      currentUser () {
        return googleAuth.currentUser.get()
      },
      currentUserProfile () {
        return this.currentUser().getBasicProfile()
      },
      getIdToken () {
        return this.currentUser().getAuthResponse().id_token
      }
    }
  }
})

App.vue from root Vue component

<template></template>

Error

Uncaught TypeError: Cannot read property 'setAuth' of undefined
      at VueComponent.onSignInSuccess (eval at 57 (0.83049e6….hot-update.js:13), :17:16)
      at boundFn (eval at  (app.js:630), :126:14)
      at H_. (cb=gapi.loaded_0:285)
      at cb=gapi.loaded_0:175
      at h.r2 (cb=gapi.loaded_0:78)
      at xs (cb=gapi.loaded_0:81)
      at Wq (cb=gapi.loaded_0:81)
      at _.C.uea (cb=gapi.loaded_0:80)
      at Ap (cb=gapi.loaded_0:74)