问:
Slicing a Pandas DataFrame into a new DataFrame
I would like to slice a DataFrame with a Boolean index obtaining a copy, and then do stuff on that copy independently of the original DataFrame.

Judging from this answer, selecting with .loc using a Boolean array will hand me back a copy, but then, if I try to change the copy, SettingWithCopyWarning gets in the way. Would this then be the correct way:

```<code>import numpy as np
import pandas as pd
d1 = pd.DataFrame(np.random.randn(10, 5), columns=['a', 'b', 'c', 'd', 'e'])
# create a new dataframe from the sliced copy
d2 = pd.DataFrame(d1.loc[d1.a > 1, :])
# do stuff with d2, keep d1 unchanged
</code>```

答:
You need copy with boolean indexing, new DataFrame constructor is not necessary:

```<code>d2 = d1[d1.a > 1].copy()
</code>```

Explanation of warning:

If you modify values in d2 later you will find that the modifications do not propagate back to the original data (d1), and that Pandas does warning.

Body:
I would like to slice a DataFrame with a Boolean index obtaining a copy, and then do stuff on that copy independently of the original DataFrame.

Judging from this answer, selecting with .loc using a Boolean array will hand me back a copy, but then, if I try to change the copy, SettingWithCopyWarning gets in the way. Would this then be the correct way:

import numpy as np
import pandas as pd
d1 = pd.DataFrame(np.random.randn(10, 5), columns=['a', 'b', 'c', 'd', 'e'])
# create a new dataframe from the sliced copy
d2 = pd.DataFrame(d1.loc[d1.a > 1, :])
# do stuff with d2, keep d1 unchanged

Body:
You need copy with boolean indexing, new DataFrame constructor is not necessary:

d2 = d1[d1.a > 1].copy()

Explanation of warning:

If you modify values in d2 later you will find that the modifications do not propagate back to the original data (d1), and that Pandas does warning.


来源: stackexchange

问:
How to compare to strings?
I have two array lists, one list is of strings and second of Toggle button.Now I want to compare the strings in two arrays.Please help me. </p>

```<code>for(int i=0; i<arrayList1.size();i++){
            for (int j=0; j<arrayList.size();j++){

                Log.d("error in response:  ", "  " + arrayList.get(j).getText());

                Log.d("Tag" , arrayList1.get(i));
                if(arrayList1.get(i)==arrayList.get(j).getText()){

                    Log.d("Tag" , arrayList1.get(i));
                    Log.d("Tag" , String.valueOf(arrayList.get(j).getText()));

                    onCheckedChanged(arrayList.get(j), true);
                }
            }
        }
</code>```

答: You have to use String#equals, because == used on objects checks if they're the same instance. </p>

ContentLicense: CC BY-SA 3.0

Title: How to compare to strings?

Body:
I have two array lists, one list is of strings and second of Toggle button.Now I want to compare the strings in two arrays.Please help me.

for(int i=0; i<arrayList1.size();i++){
            for (int j=0; j<arrayList.size();j++){

                Log.d("error in response:  ", "  " + arrayList.get(j).getText());

                Log.d("Tag" , arrayList1.get(i));
                if(arrayList1.get(i)==arrayList.get(j).getText()){

                    Log.d("Tag" , arrayList1.get(i));
                    Log.d("Tag" , String.valueOf(arrayList.get(j).getText()));

                    onCheckedChanged(arrayList.get(j), true);
                }
            }
        }


问:
How do I display a property from a simple object using ngrx redux and angular2
I'm using angular2 2.0.0-beta.2 with ngrx store https://github.com/ngrx/store and implemented a simple app using a modified version of the "counter" example on the ngrx/store github page.

In my app, I have a "user" object with two buttons for login and logout. I also have the corresponding reducer functions login and logout where I either return the state with an object that includes a name property or with an empty object...

```<code>export const user: Reducer<any> = (state: any = {}, action: Action) => {

    switch (action.type) {
        case LOGIN:
            return {name: 'jdoe'};

        case LOGOUT:
            return {};

        default:
            return state;
    }
};
</code>```

This doesn't update:

```<code><h2>User Name = {{ user.name | async }}</h2>
</code>```

...It remains blank when I click the login button, but when piped through the 'json' pipe, I see that indeed the object has changed...

This does update

```<code>{{ user | async | json }}
</code>```

...which outputs { "name": "jdoe" } but obviously that does me no good. Using simply {{ user.name | async }} doesn't work and remains blank.

the template:

```<code><div>
    <h2>User Name = {{ user.name | async }}</h2>
    <button (click)="login()">login</button><button (click)="logout()">logout</button>
</div>
<hr>
<div>
      {{ user | async | json }}
</div>
</code>```

Here's the plunker:
http://plnkr.co/edit/cPubI9upph344qrOqtj8?p=preview

答:
You could also do </p>

```<code>    <div *ngIf="user | async as userdata">
     {{userdata.name}}
     {{userdata.birthday}}
     ...
    </div>
</code>```

Body:
I'm using angular2 2.0.0-beta.2 with ngrx store https://github.com/ngrx/store and implemented a simple app using a modified version of the "counter" example on the ngrx/store github page.

In my app, I have a "user" object with two buttons for login and logout. I also have the corresponding reducer functions login and logout where I either return the state with an object that includes a name property or with an empty object...

export const user: Reducer<any> = (state: any = {}, action: Action) => {

    switch (action.type) {
        case LOGIN:
            return {name: 'jdoe'};

        case LOGOUT:
            return {};

        default:
            return state;
    }
};

This doesn't update:

User Name = {{ user.name | async }}

...It remains blank when I click the login button, but when piped through the 'json' pipe, I see that indeed the object has changed...

This does update

{{ user | async | json }}

...which outputs { "name": "jdoe" } but obviously that does me no good. Using simply {{ user.name | async }} doesn't work and remains blank.

the template:

User Name = {{ user.name | async }}

    <button (click)="login()">login</button><button (click)="logout()">logout</button>

      {{ user | async | json }}

Here's the plunker:
http://plnkr.co/edit/cPubI9upph344qrOqtj8?p=preview

Body:
You could also do

    <div *ngIf="user | async as userdata">
     {{userdata.name}}
     {{userdata.birthday}}
     ...
    </div>


问:
Can I use vue.js to change a css class?
I have an MVC project and im using vue for my application form.

```<code><div class="validation-error" ref="message">@Html.ValidationMessageFor(m => m.Title)</div>
<div class="label-container">@Html.LabelFor(m => m.Title)</div>
<div class="form-control">@Html.TextBoxFor(m => m.Title, new { v_model = "val", @ref = "field" })</div>
</code>```

which is a text box with a validation message bounded to it. Im wondering if I can change the colour of the text box only if the validation message is active.

I saw the html renders an attribute called aria-invalid="true" so im wondering if I could use v-if or something.

Thanks

答:
Yes, see the Class and Style Bindings section of the Vue.js documentation.

Here's an example of a class that is enabled or disabled based on the truthiness of a Vue.js variable:

```<code><div :class="{ 'css-class-name': isActive }"></div>
</code>```

Title: Can I use vue.js to change a css class?

Body:
I have an MVC project and im using vue for my application form.

@Html.ValidationMessageFor(m => m.Title)

@Html.LabelFor(m => m.Title)

@Html.TextBoxFor(m => m.Title, new { v_model = "val", @ref = "field" })

which is a text box with a validation message bounded to it. Im wondering if I can change the colour of the text box only if the validation message is active.

I saw the html renders an attribute called aria-invalid="true" so im wondering if I could use v-if or something.

Thanks

Body:
Yes, see the Class and Style Bindings section of the Vue.js documentation.

Here's an example of a class that is enabled or disabled based on the truthiness of a Vue.js variable:

<div :class="{ 'css-class-name': isActive }"></div>

ContentLicense: CC BY-SA 4.0


问:
Is it possible to simplify this code which iterates a std map?
So I have this definition:

```<code>using HistoryDataItemList = list<CHistoryDataItem>;
HistoryDataItemList m_listHistoryItems;
</code>```

And this method:

```<code>bool CHistoryData::HasHistoryForAssignment(ASSIGN_TYPE_E eAssignType)
{
    bool bHasHistoryForAssignment = false;
    auto iter = m_listHistoryItems.begin();

    for (; iter != m_listHistoryItems.end(); iter++)
    {
        if (iter->GetAssignmentType() == eAssignType)
        {
            bHasHistoryForAssignment = true;
            break;
        }
    }

    return bHasHistoryForAssignment;
}
</code>```

I know that with languages like C# you can simplify the code a bit but can that also be done with MFC when using the newer C++11? Or is what I have written pretty much as simple as it can be?

Thank you.

答:
The most obvious improvement is using a C++11 "range-for" loop:

```<code>bool CHistoryData::HasHistoryForAssignment(ASSIGN_TYPE_E eAssignType)
{
    bool bHasHistoryForAssignment = false;

    for (auto& item : m_listHistoryItems)
    {
        if(item.GetAssignmentType() == eAssignType)
        {
            bHasHistoryForAssignment = true;
            break;
        }
    }

    return bHasHistoryForAssignment;
}
</code>```

But thinking about your code, what you really want is to check if any of the items matches a particular predicate. There's an <algorithm> for that!

```<code>bool CHistoryData::HasHistoryForAssignment(ASSIGN_TYPE_E eAssignType)
{
    return std::any_of(std::begin(m_listHistoryItems),
                       std::end(m_listHistoryItems),
                       [](const CHistoryDataItem& item)
                       {
                           return item.GetAssignmentType() == eAssignType;
                       });
}
</code>```

Alternatively, using a for with no extra state is also easy to read and understand:

```<code>bool CHistoryData::HasHistoryForAssignment(ASSIGN_TYPE_E eAssignType)
{
    for (auto& item : m_listHistoryItems)
    {
        if(item.GetAssignmentType() == eAssignType)
            return true;
    }

    return false;
}
</code>```

Body:
So I have this definition:

using HistoryDataItemList = list<CHistoryDataItem>;
HistoryDataItemList m_listHistoryItems;

And this method:

bool CHistoryData::HasHistoryForAssignment(ASSIGN_TYPE_E eAssignType)
{
    bool bHasHistoryForAssignment = false;
    auto iter = m_listHistoryItems.begin();

    for (; iter != m_listHistoryItems.end(); iter++)
    {
        if (iter->GetAssignmentType() == eAssignType)
        {
            bHasHistoryForAssignment = true;
            break;
        }
    }

    return bHasHistoryForAssignment;
}

I know that with languages like C# you can simplify the code a bit but can that also be done with MFC when using the newer C++11? Or is what I have written pretty much as simple as it can be?

Thank you.

Body:
The most obvious improvement is using a C++11 "range-for" loop:

bool CHistoryData::HasHistoryForAssignment(ASSIGN_TYPE_E eAssignType)
{
    bool bHasHistoryForAssignment = false;

    for (auto& item : m_listHistoryItems)
    {
        if(item.GetAssignmentType() == eAssignType)
        {
            bHasHistoryForAssignment = true;
            break;
        }
    }

    return bHasHistoryForAssignment;
}

But thinking about your code, what you really want is to check if any of the items matches a particular predicate. There's an <algorithm> for that!

bool CHistoryData::HasHistoryForAssignment(ASSIGN_TYPE_E eAssignType)
{
    return std::any_of(std::begin(m_listHistoryItems),
                       std::end(m_listHistoryItems),
                       [](const CHistoryDataItem& item)
                       {
                           return item.GetAssignmentType() == eAssignType;
                       });
}

Alternatively, using a for with no extra state is also easy to read and understand:

bool CHistoryData::HasHistoryForAssignment(ASSIGN_TYPE_E eAssignType)
{
    for (auto& item : m_listHistoryItems)
    {
        if(item.GetAssignmentType() == eAssignType)
            return true;
    }

    return false;
}


问:
Reduce an array of objects in PHP
I have an array of objects. Something like this:

```<code>$my_array = [
    (object) ['name' => 'name 0'],
    (object) ['name' => 'name 1'],
    (object) ['name' => 'name 2'],
];
</code>```

And I'd like to reduce it to a concatenation of all name properties like:

name 0 / name 1 / name 2

One way would be:

```<code>$result = [];
foreach ($my_array as $item) {
    $result[] = $item->name;
}
echo implode(' / ', $result);
</code>```

But I'd prefer something more compact, like using array_map:

```<code>implode(' / ', array_map(function($item) {
    return $item->name;
}, $my_array ));
</code>```

Given that in fact I want to reduce and array to a string I thought it would be cleaner with array_reduce but the only solution I can come out with is:

```<code>array_reduce($my_array, function($carry, $obj) {
    return empty($carry) ? $obj->name : $carry .= " / $obj->name";
});
</code>```

Yet it doesn't feel cleaner... So the question is simple:

Can anybody think of an understandable better/cleaner solution?

答:
You might be looking for array_column(), which takes the values of the given column:

```<code>$result = array_column($largeArray, 'name');// take all values with the key 'name'

// If you want it with a slash:
echo implode(" / ", $result);
</code>```

Doesn't need much more explanation. Which is the kind of code you should go for. Weird functionality that feels fancy, but nobody can understand is worse. You might understand what it does now, but if you leave it alone for 6 months and come back, you've forgotten it just as much.

Often: maintainability > complexity (and sometimes even >performance)

Title: Reduce an array of objects in PHP

Body:
I have an array of objects. Something like this:

$my_array = [
    (object) ['name' => 'name 0'],
    (object) ['name' => 'name 1'],
    (object) ['name' => 'name 2'],
];

And I'd like to reduce it to a concatenation of all name properties like:

name 0 / name 1 / name 2

One way would be:

$result = [];
foreach ($my_array as $item) {
    $result[] = $item->name;
}
echo implode(' / ', $result);

But I'd prefer something more compact, like using array_map:

implode(' / ', array_map(function($item) {
    return $item->name;
}, $my_array ));

Given that in fact I want to reduce and array to a string I thought it would be cleaner with array_reduce but the only solution I can come out with is:

array_reduce($my_array, function($carry, $obj) {
    return empty($carry) ? $obj->name : $carry .= " / $obj->name";
});

Yet it doesn't feel cleaner... So the question is simple:

Can anybody think of an understandable better/cleaner solution?

Body:
You might be looking for array_column(), which takes the values of the given column:

$result = array_column($largeArray, 'name');// take all values with the key 'name'

// If you want it with a slash:
echo implode(" / ", $result);

Doesn't need much more explanation. Which is the kind of code you should go for. Weird functionality that feels fancy, but nobody can understand is worse. You might understand what it does now, but if you leave it alone for 6 months and come back, you've forgotten it just as much.

Often: maintainability > complexity (and sometimes even >performance)


问:
Can Math.Round in C# be used for whole integer values?
I have integer 363 for example.

Any method to make it 360 or 365?

答:
Here's what I usually do, which is a combination of the two ideas:

```<code>static int RoundDown(int x, int n) {
    return x / n * n;
}

static int Round(int x, int n) {
    return (x + n / 2) / n * n;
}

static int RoundUp(int x, int n) {
    return (x + n - 1) / n * n;
}
</code>```

(That assumes positive numbers; Extending it to negatives is straight-forward.)

[edit]

According to LLVM, the Round function can also be written like this:

```<code>int Round(int x, int n) {
    int z = (x + n / 2);
    return z - (z % n);
}
</code>```

Which you may find more elegant.

ContentLicense: CC BY-SA 2.5

Body:
Here's what I usually do, which is a combination of the two ideas:

static int RoundDown(int x, int n) {
    return x / n * n;
}

static int Round(int x, int n) {
    return (x + n / 2) / n * n;
}

static int RoundUp(int x, int n) {
    return (x + n - 1) / n * n;
}

(That assumes positive numbers; Extending it to negatives is straight-forward.)

[edit]

According to LLVM, the Round function can also be written like this:

int Round(int x, int n) {
    int z = (x + n / 2);
    return z - (z % n);
}

Which you may find more elegant.


问:
Merge two table based on row name
I need to merge two table into one based on Row name, each table has 172 rows and 172 columns example of my data look

```<code>#table 1
A B C
1 2 3
2 3 4
5 6 7

#table 2
A B C
1 3 8
2 4 6
5 4 2
</code>```

I want my output like this

```<code>A B C
1 2 3
1 3 8
2 3 4
2 4 6
5 6 7
5 4 2
</code>```

答: You may use rbind(table1, table2)

Title: Merge two table based on row name

Body:
I need to merge two table into one based on Row name, each table has 172 rows and 172 columns example of my data look

#table 1
A B C
1 2 3
2 3 4
5 6 7

#table 2
A B C
1 3 8
2 4 6
5 4 2

I want my output like this

A B C
1 2 3
1 3 8
2 3 4
2 4 6
5 6 7
5 4 2

Body: You may use rbind(table1, table2)


问:
How are the row heights in an SSRS tablix calculated?
I am wondering how the row heights in an SSRS tablix are calculated.

For instance, I have data for which the displayed and grouped by columns are close enough to be identical. However, some rows will for some unknown reason have a massive height with a lot of blank space. If you inspect the HTML output you can see that these rows have a rowspan and height applied to them.

This is not a wrapping issue as I can do an IIf on that row's item id and simply display "a" instead of the actual values and still get abnormal height.  I have also disabled CanGrow on all textboxes/rows etc. and have set manual heights yet the issue persists.

What causes this behaviour and how are the row heights usually calculated?

答:
GOT HUGE problems with show/hide rows and CanShrink/CanGrow din't work, so I found out that there was a "Row visibillity" expression, that show/hides the whole row depend of a Textbox value.

(Right click the tablixrow and choose "Row visibility")

Cheers


问:
How to make UWP app to suspend and resume state
I am able to suspend and resume the UWP application using visual studio Life cycle events. But when I tried with User's machine I am unable to get the suspend and resume state of the application.

I tried using resource monitor to suspend and resume the process , but it is not hitting "Onsuspend" event, while on resuming it is not hitting "OnResume" event.

Is there any other way to hit the OnResume event in the application?

答:
We can make the Application to go suspend and resume state in tablet mode.

Change the OS to tablet mode(we can change it in action center).
In the tablet mode only fore ground application will be in running state. All other UWP  applications in the background will be in "Suspended state".
When we make those application to fore ground it will come from "Suspend state" to "Resume state".


问:
Many layouts in Scroll View in android
I want to have 3 layouts in my ScrollView but when I add them it actually doesn't scroll. I tried to put all layouts in different files, then include them, tried to put them in ListView and it doesn't work too. In this option, when I put in ScrollView the LinearLayout and there include the rest of the layouts the application show nothing. That's probably becouse I don't know how to refer to that nested layouts... This is my XML:

activity_main.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="wrap_content"
>
    <ScrollView android:layout_width="match_parent" android:layout_height="match_parent">
        <LinearLayout android:layout_width="match_parent"
                      android:layout_height="wrap_content"
                      android:orientation="vertical"
        >
            <include layout="@layout/first"/>
            <include layout="@layout/second"/>
            <include layout="@layout/third"/>
        </LinearLayout>
    </ScrollView>
</LinearLayout>
</code>```

@EDIT views included (all are the same so I put just one):

```<code><RelativeLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/first"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
>
</RelativeLayout>
</code>```

And in the main activity I put the objects into layouts like this:

```<code>setContentView(R.layout.activity_main);
RelativeLayout first = (RelativeLayout) findViewById(R.id.first);
RelativeLayout second = (RelativeLayout) findViewById(R.id.second);
RelativeLayout third = (RelativeLayout) findViewById(R.id.third);

...some code creating views...

first.addView(myView1);
second.addView(myView2);
third.addView(myView3);
</code>```

答:
Need to put fix size in included layout, for example:

```<code><RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/first"
    android:layout_width="match_parent"
    android:layout_height="300dp"
</code>```

/>

I don`t understand why do you need to add view manually when you already added it to the layout.

You should also eliminate top Linear Layout since there is no use of it.

Title: Many layouts in Scroll View in android

Body:
I want to have 3 layouts in my ScrollView but when I add them it actually doesn't scroll. I tried to put all layouts in different files, then include them, tried to put them in ListView and it doesn't work too. In this option, when I put in ScrollView the LinearLayout and there include the rest of the layouts the application show nothing. That's probably becouse I don't know how to refer to that nested layouts... This is my XML:

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="wrap_content"
>
    <ScrollView android:layout_width="match_parent" android:layout_height="match_parent">
        <LinearLayout android:layout_width="match_parent"
                      android:layout_height="wrap_content"
                      android:orientation="vertical"
        >
            <include layout="@layout/first"/>
            <include layout="@layout/second"/>
            <include layout="@layout/third"/>
        </LinearLayout>
    </ScrollView>
</LinearLayout>

@EDIT views included (all are the same so I put just one):

<RelativeLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/first"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
>
</RelativeLayout>

And in the main activity I put the objects into layouts like this:

setContentView(R.layout.activity_main);
RelativeLayout first = (RelativeLayout) findViewById(R.id.first);
RelativeLayout second = (RelativeLayout) findViewById(R.id.second);
RelativeLayout third = (RelativeLayout) findViewById(R.id.third);

...some code creating views...

first.addView(myView1);
second.addView(myView2);
third.addView(myView3);

Body:
Need to put fix size in included layout, for example:

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/first"
    android:layout_width="match_parent"
    android:layout_height="300dp"

/>

I don`t understand why do you need to add view manually when you already added it to the layout.

You should also eliminate top Linear Layout since there is no use of it.


问:
how to retrieve hashMap data as a list and display in list
I am saving date to firebase with HashMap, I watched many tutorials, but facing problem in getting that data into list and display as List. Any help please thanks.</p>

答:
To solve your problem i recomand you iterate your Map. You can achieve this using this code:

```<code>Map<String, String> map = (Map<String, String>) dataSnapshot.child("yourChild").getValue();
List<String> list = new ArrayList<>();
for (Map.Entry<String, String> entry : map.entrySet()) {
    list.add(entry.getKey() + "/" + entry.getValue());
}

for(String s : list) {
    Log.d("TAG", s);
}
</code>```

Hope it helps.

Body:
To solve your problem i recomand you iterate your Map. You can achieve this using this code:

Map<String, String> map = (Map<String, String>) dataSnapshot.child("yourChild").getValue();
List<String> list = new ArrayList<>();
for (Map.Entry<String, String> entry : map.entrySet()) {
    list.add(entry.getKey() + "/" + entry.getValue());
}

for(String s : list) {
    Log.d("TAG", s);
}

Hope it helps.


问:
What tools are built using themselves?
I am curious about what tools are used to build the next version of themselves.

For example, Delphi has long claimed that "Delphi is written in Delphi".

I assume Visual Studio is written using Visual Studio.

What are some other examples of tools that written in themselves?

答:
I'm developing an Eclipse plugin called nWire which assists and accelerates code exploration. I've been using it as part of my development since the moment it was stable enough and I just can't live without it now (well, it has the tendency of becoming a habit very quickly :-).

For me it's "eat your own dog food", but it really helps. This also raises my confidence in the product.

OwnerDisplayName: kogus

Title: What tools are built using themselves?

LastEditorDisplayName: kogus

OwnerDisplayName: zvikico


问:
Generate single JSON array from several input objects using jq
I do have several similar JSON objects (e.g. in files):

```<code>file_1.json: {"myArray":[{a},{b}]}
...
file_n.json: {"myArray":[{n},{m}]}
</code>```

I would like to transform all these files into one output with the following format, using jq and Linux or Windows command line tools:

```<code>result_file.json: [{a},{b},...,{n},{m}]
</code>```

So, I just want one array having all the objects that can be found in the "myArray" arrays from the different inputs.

Currently I use this command, which separates the objects, but doesn't create an array that includes them:

```<code>type file_1.json file_n.json | jq ".result[]" > result_file.json
</code>```

(replace type with cat on Linux)

How can I get the format right?

答:
You can "slurp" your inputs:

-s        read (slurp) all inputs into an array; apply filter to it;

(man jq)

Like that:

1.json

```<code>{"myArray":[1,2,3]}
</code>```

2.json

```<code>{"myArray":[3,4,5]}
</code>```

%jq -s '[.[].myArray[]]' 1.json 2.json

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

Body:
I do have several similar JSON objects (e.g. in files):

file_1.json: {"myArray":[{a},{b}]}
...
file_n.json: {"myArray":[{n},{m}]}

I would like to transform all these files into one output with the following format, using jq and Linux or Windows command line tools:

result_file.json: [{a},{b},...,{n},{m}]

So, I just want one array having all the objects that can be found in the "myArray" arrays from the different inputs.

Currently I use this command, which separates the objects, but doesn't create an array that includes them:

type file_1.json file_n.json | jq ".result[]" > result_file.json

(replace type with cat on Linux)

How can I get the format right?

Body:
You can "slurp" your inputs:

-s        read (slurp) all inputs into an array; apply filter to it;

(man jq)

Like that:

1.json

{"myArray":[1,2,3]}

2.json

{"myArray":[3,4,5]}

%jq -s '[.[].myArray[]]' 1.json 2.json

[
  1,
  2,
  3,
  3,
  4,
  5
]


问:
Removing duplicate string values in 2d array not working
I know this question has been asked many times before, however I am a complete beginner to C arrays and would like to avoid using pointers (if possible) and keep it as simple as possible.
I have used the input from the user for a char array and would like to remove any duplicate string values in my program

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

int main(){
    int N, i, j, k;
        int flag=1;
    scanf("%d", &N);
    if(1<=N<=10^6){
    char a[N][5];
        for(i=0; i<N; i++){
            scanf("%s", &a[i]);
        }
        for(i=0; i<N; i++){
            for(j=i+1;j<N;){
                if(strcmp(a[i],a[j])==0){
                    for(k=j+1; k<N; k++){
                        memcpy(a[k], a[k+1], 5);
                    }
                    N--;
                }else{
                    j++;
                }
            }
        }
        for(i=0; i<N; i++){
            printf("%s\n", a[i]);
        }
    }
    return 0;
}
</code>```

An input of 3 and {"abc", "abc", "as"} returns the value only {"abc"}.
I would like to get the array as {"abc", "as"}. I cannot understand where in the code or logic, I have gone wrong.

Update

I changed the code as mentioned below however for larger examples it is concatenating the strings

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

int main(){
    int N, i, j, k;

    scanf("%d", &N);
    if(1 <= N && N <= 1000000){
    char a[N][5];
        for(i=0; i<N; i++){
            scanf("%5s", a[i]);
        }
        for(i=0; i<N; i++){
            for(j=i+1;j<N;){
                if(strcmp(a[i],a[j])==0){
                    for(k=j+1; k<N; k++){
                        strcpy(a[k-1], a[k]);
                    }
                    N--;
                }else{
                    j++;
                }
            }
        }
        printf("%d\n", N);
        for(i=0; i<N; i++){
            printf("%s\n", a[i]);
        }
    }
    return 0;
}
</code>```

答:
My first reaction would be to write it in c++ using standard algorithms.</p>

```<code>#include<iostream>
#include<string>
#include<algorithm>
#include<cmath>
#include<vector>
#include<unordered_set>
#include<algorithm>

template<class T, class A>
auto deduplictate_keep_order(std::vector<T, A> &vec) -> std::vector<T, A> &
{
    std::unordered_set<T> seen;
    seen.reserve(vec.size());

    auto check_seen = [&seen](T const &val) {
        return !seen.insert(val).second;
    };

    vec.erase(std::remove_if(vec.begin(), vec.end(), check_seen), vec.end());
    return vec;
};

template<class T, class A>
auto deduplictate_any_order(std::vector<T, A> &vec) -> std::vector<T, A> &
{
    std::sort(vec.begin(), vec.end());
    vec.erase(std::unique(vec.begin(), vec.end()), vec.end());
    return vec;
};

int main() {
    int N, i, j, k;
    int flag = 1;
    std::cin >> N;

    int limit = std::pow(10, 6);
    if (1 <= N && N <= limit) {  //  1 <= N <= will not do what you want. 10^6 is 10 XOR 6. You don't want that.
        std::vector<std::string> a;
        for (i = 0; i < N; i++) {
            a.emplace_back();
            std::cin >> a.back();
        }

        // remove duplicates
        deduplictate_keep_order(a);

        // or this
//        deduplictate_any_order(a);

        for (std::string const &s : a)
            std::cout << s << '\n';
    }
    return 0;
}
</code>```

Body:
I know this question has been asked many times before, however I am a complete beginner to C arrays and would like to avoid using pointers (if possible) and keep it as simple as possible.
I have used the input from the user for a char array and would like to remove any duplicate string values in my program

#include<string.h>
#include<stdio.h>

int main(){
    int N, i, j, k;
        int flag=1;
    scanf("%d", &N);
    if(1<=N<=10^6){
    char a[N][5];
        for(i=0; i<N; i++){
            scanf("%s", &a[i]);
        }
        for(i=0; i<N; i++){
            for(j=i+1;j<N;){
                if(strcmp(a[i],a[j])==0){
                    for(k=j+1; k<N; k++){
                        memcpy(a[k], a[k+1], 5);
                    }
                    N--;
                }else{
                    j++;
                }
            }
        }
        for(i=0; i<N; i++){
            printf("%s\n", a[i]);
        }
    }
    return 0;
}

An input of 3 and {"abc", "abc", "as"} returns the value only {"abc"}.
I would like to get the array as {"abc", "as"}. I cannot understand where in the code or logic, I have gone wrong.

Update

I changed the code as mentioned below however for larger examples it is concatenating the strings

#include<string.h>
#include<stdio.h>

int main(){
    int N, i, j, k;

    scanf("%d", &N);
    if(1 <= N && N <= 1000000){
    char a[N][5];
        for(i=0; i<N; i++){
            scanf("%5s", a[i]);
        }
        for(i=0; i<N; i++){
            for(j=i+1;j<N;){
                if(strcmp(a[i],a[j])==0){
                    for(k=j+1; k<N; k++){
                        strcpy(a[k-1], a[k]);
                    }
                    N--;
                }else{
                    j++;
                }
            }
        }
        printf("%d\n", N);
        for(i=0; i<N; i++){
            printf("%s\n", a[i]);
        }
    }
    return 0;
}

Body:
My first reaction would be to write it in c++ using standard algorithms.

#include<iostream>
#include<string>
#include<algorithm>
#include<cmath>
#include<vector>
#include<unordered_set>
#include<algorithm>

template<class T, class A>
auto deduplictate_keep_order(std::vector<T, A> &vec) -> std::vector<T, A> &
{
    std::unordered_set<T> seen;
    seen.reserve(vec.size());

    auto check_seen = [&seen](T const &val) {
        return !seen.insert(val).second;
    };

    vec.erase(std::remove_if(vec.begin(), vec.end(), check_seen), vec.end());
    return vec;
};

template<class T, class A>
auto deduplictate_any_order(std::vector<T, A> &vec) -> std::vector<T, A> &
{
    std::sort(vec.begin(), vec.end());
    vec.erase(std::unique(vec.begin(), vec.end()), vec.end());
    return vec;
};

int main() {
    int N, i, j, k;
    int flag = 1;
    std::cin >> N;

    int limit = std::pow(10, 6);
    if (1 <= N && N <= limit) {  //  1 <= N <= will not do what you want. 10^6 is 10 XOR 6. You don't want that.
        std::vector<std::string> a;
        for (i = 0; i < N; i++) {
            a.emplace_back();
            std::cin >> a.back();
        }

        // remove duplicates
        deduplictate_keep_order(a);

        // or this
//        deduplictate_any_order(a);

        for (std::string const &s : a)
            std::cout << s << '\n';
    }
    return 0;
}


问:
How to extend multiple classes in Laravel?
I want to make class User extend both Authenticatable and Model at the same time:

```<code>class User extends Authenticatable

class User extends Model
</code>```

What is the proper way to do it?

答:
The User class by default extends Illuminate\Foundation\Auth\User as Authenticable. This class already extends the Model class.

Check the API for more information

Body:
I want to make class User extend both Authenticatable and Model at the same time:

class User extends Authenticatable

class User extends Model

What is the proper way to do it?


问:
PhP regex for a string, what would be the best way to do it?
I have an array with rule field that has a string like this:

```<code>FREQ=MONTHLY;BYDAY=3FR
FREQ=MONTHLY;BYDAY=3SA
FREQ=WEEKLY;UNTIL=20170728T080000Z;BYDAY=MO,TU,WE,TH,FR
FREQ=MONTHLY;UNTIL=20170527T100000Z;BYDAY=4SA
FREQ=WEEKLY;BYDAY=SA
FREQ=WEEKLY;INTERVAL=2;BYDAY=TH
FREQ=WEEKLY;BYDAY=TH
FREQ=WEEKLY;UNTIL=20170610T085959Z;BYDAY=SA
FREQ=MONTHLY;BYDAY=2TH
</code>```

Each line is a different array, I am giving a few clues to get an idea of what I need.

What I need is to write a regex that would take off all unnecessary values.

So, I don't need FREQ= ; BYDAY= etc. I basically need the values after = but each one I want to store in a different variable.

Taking third one as an example it would be:

```<code>$frequency = WEEKLY
$until = 20170728T080000Z
$day = MO, TU, WE, TH, FR
</code>```

It doesn't have to be necessarily one regex, there can be one regex for each value. So I have one for FREQ:

```<code>preg_match("/[^FREQ=][A-Z]+/", $input_line, $output_array);
</code>```

But I can't do it for the rest unfortunately, how can I solve this?

答:
The only way to go would be PHP array destructuring:

```<code>$str = "FREQ=WEEKLY;UNTIL=20170728T080000Z;BYDAY=MO,TU,WE,TH,FR";

preg_match_all('~(\w+)=([^;]+)~', $str, $matches);
[$freq, $until, $byday] = $matches[2]; // As of PHP 7.1 (otherwise use list() function)
echo $freq, " ", $until, " ", $byday;
// WEEKLY 20170728T080000Z MO,TU,WE,TH,FR
</code>```

Live demo

Be more general

Using extract function:

```<code>preg_match_all('~(\w+)=([^;]+)~', $str, $m);
$m[1] = array_map('strtolower', $m[1]);
$vars = array_combine($m[1], $m[2]);
extract($vars);
echo $freq, " ", $until, " ", $byday;
</code>```

Live demo

Body:
I have an array with rule field that has a string like this:

FREQ=MONTHLY;BYDAY=3FR
FREQ=MONTHLY;BYDAY=3SA
FREQ=WEEKLY;UNTIL=20170728T080000Z;BYDAY=MO,TU,WE,TH,FR
FREQ=MONTHLY;UNTIL=20170527T100000Z;BYDAY=4SA
FREQ=WEEKLY;BYDAY=SA
FREQ=WEEKLY;INTERVAL=2;BYDAY=TH
FREQ=WEEKLY;BYDAY=TH
FREQ=WEEKLY;UNTIL=20170610T085959Z;BYDAY=SA
FREQ=MONTHLY;BYDAY=2TH

Each line is a different array, I am giving a few clues to get an idea of what I need.

What I need is to write a regex that would take off all unnecessary values.

So, I don't need FREQ= ; BYDAY= etc. I basically need the values after = but each one I want to store in a different variable.

Taking third one as an example it would be:

$frequency = WEEKLY
$until = 20170728T080000Z
$day = MO, TU, WE, TH, FR

It doesn't have to be necessarily one regex, there can be one regex for each value. So I have one for FREQ:

preg_match("/[^FREQ=][A-Z]+/", $input_line, $output_array);

But I can't do it for the rest unfortunately, how can I solve this?

Body:
The only way to go would be PHP array destructuring:

$str = "FREQ=WEEKLY;UNTIL=20170728T080000Z;BYDAY=MO,TU,WE,TH,FR";

preg_match_all('~(\w+)=([^;]+)~', $str, $matches);
[$freq, $until, $byday] = $matches[2]; // As of PHP 7.1 (otherwise use list() function)
echo $freq, " ", $until, " ", $byday;
// WEEKLY 20170728T080000Z MO,TU,WE,TH,FR

Live demo

Be more general

Using extract function:

preg_match_all('~(\w+)=([^;]+)~', $str, $m);
$m[1] = array_map('strtolower', $m[1]);
$vars = array_combine($m[1], $m[2]);
extract($vars);
echo $freq, " ", $until, " ", $byday;

Live demo


问:
How to assign value to directive using javascript code?
Hi I am developing angularjs application. I am doing validation for textbox. I am doing range validation. textbox should accept numbers within the specified range. I have developed directive for this purpose. I am assigning value as range-number="10,4096". Instead of assigning value in this tag i want to assign in angularjs code.

Below is my html.

```<code>  <div class="inputblock" ng-class="{ 'has-error' : ((form5.$submitted && form5.DownPayment.$invalid )|| (form5.DownPayment.$invalid && form5.DownPayment.$dirty))}">
                        <div>
                            <span class="ang-error" style="color:#fff" ng-show="form5.DownPayment.$dirty && form5.DownPayment.$invalid  && form5.DownPayment.$error.rangeNumber">
                                <span ng-show="form5.DownPayment.$invalid && form5.DownPayment.$dirty">Invalid</span>
                            </span>
                        </div>
                        <input class="" type="text" name="DownPayment" placeholder="{{ 'DownPayment' | translate }}" ng-model="DownPayment" required ng-readonly="makereadonlyDownPayment" range-number="range">
                    </div>
</code>```

Below is my js code.

```<code>app.directive('rangeNumber', function () {
    return {
        require: 'ngModel',
        link: function (scope, elem, attrs, ctrl) {
            if (!ctrl) return;
            var range = attrs.rangeNumber.split(',').map(Number);
            ctrl.$validators.rangeNumber = function (value) {
                return value >= range[0] && value <= range[1];
            };
        }
    };
});
</code>```

May i know how can i do this? Any help would be appreciated. Thank you.

答:
You can pass an array with these informations to your directive, your html can be like:

<input class="" type="text" name="DownPayment" placeholder="{{ 'DownPayment' | translate }}" ng-model="DownPayment" required ng-readonly="makereadonlyDownPayment" range-number="range">

and you retrieve the variable range with an isolate scope into your directive:

```<code>return {
    require: 'ngModel',
    scope: {
        range: '='
    },
    link: function (scope, elem, attrs, ctrl) {
        if (!ctrl) return;
        var range = scope.range;
        ctrl.$validators.rangeNumber = function (value) {
            return value >= range[0] && value <= range[1];
        };
    }
}
</code>```

Body:
Hi I am developing angularjs application. I am doing validation for textbox. I am doing range validation. textbox should accept numbers within the specified range. I have developed directive for this purpose. I am assigning value as range-number="10,4096". Instead of assigning value in this tag i want to assign in angularjs code.

Below is my html.

                                Invalid

                        <input class="" type="text" name="DownPayment" placeholder="{{ 'DownPayment' | translate }}" ng-model="DownPayment" required ng-readonly="makereadonlyDownPayment" range-number="range">

Below is my js code.

app.directive('rangeNumber', function () {
    return {
        require: 'ngModel',
        link: function (scope, elem, attrs, ctrl) {
            if (!ctrl) return;
            var range = attrs.rangeNumber.split(',').map(Number);
            ctrl.$validators.rangeNumber = function (value) {
                return value >= range[0] && value <= range[1];
            };
        }
    };
});

May i know how can i do this? Any help would be appreciated. Thank you.

Body:
You can pass an array with these informations to your directive, your html can be like:

<input class="" type="text" name="DownPayment" placeholder="{{ 'DownPayment' | translate }}" ng-model="DownPayment" required ng-readonly="makereadonlyDownPayment" range-number="range">

and you retrieve the variable range with an isolate scope into your directive:

return {
    require: 'ngModel',
    scope: {
        range: '='
    },
    link: function (scope, elem, attrs, ctrl) {
        if (!ctrl) return;
        var range = scope.range;
        ctrl.$validators.rangeNumber = function (value) {
            return value >= range[0] && value <= range[1];
        };
    }
}


问:
Update object of an array in UIViewController from UITableViewCell
I have a UITableViewCell that I use in several UITableView's that are in differents UIViewController's. From my cell, there is an object that I update but I would like to update it also in the array of my controllers. How ?

For example :

UITableViewCell :

```<code>class NotificationTableViewCell: UITableViewCell {

    @IBOutlet weak var buttonRead: UIButton!

    var notification = Notification()

    override func awakeFromNib() {
        super.awakeFromNib()
    }

    @IBAction func clickButtonRead(_ sender: Any) {
        self.notification.isRead = true
    }
}
</code>```

UIViewController :

```<code>class NotificationsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UITabBarControllerDelegate {

    @IBOutlet weak var tableView: UITableView!

    /* List notifications */
    var listNotifications = [Notification]()

    override func viewDidLoad() {
        super.viewDidLoad()

        //View cell
        let nib = UINib(nibName: "viewNotificationTableViewCell", bundle: nil)
        self.tableView.register(nib, forCellReuseIdentifier: "cellNotification")

    }

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

    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.listNotifications.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        var cell = tableView.dequeueReusableCell(withIdentifier: "cellNotification", for: indexPath) as! NotificationTableViewCell

        cell.notification = self.listNotifications[indexPath.row]

        return cell
    }
}
</code>```

EDIT :
I can pass the controller and the indexPath to the cell for update the object notification in listNotifications like this : self.controller.listNotifications[indexPath.row] = self.notification
But if i use this cell with more controllers, I must cast the controller from cell to know what controller is it.
I am looking for a way to update the object without having to cast the controller.

答:
The ideal way to do it is you create a NotificationTableViewCellDelegate and set the delegate to view controller. In your method clickButtonRead call the delegate method and update the object in the view controller.

```<code>    protocol NotificationTableViewCellDelegate {
        func enableReadForNotification(notification: Notification)
    }

    class NotificationTableViewCell: UITableViewCell {

            @IBOutlet weak var buttonRead: UIButton!
            var notification = Notification()
            weak var delegate: NotificationTableViewCellDelegate?

            override func awakeFromNib() {
                super.awakeFromNib()
            }

            @IBAction func clickButtonRead(_ sender: Any) {
                self.notification.isRead = true
               if let delegate = self.delegate {
                  delegate.enableReadForNotification(self.notification)
               }
            }
        }
</code>```

Hope this helps!

Body:
I have a UITableViewCell that I use in several UITableView's that are in differents UIViewController's. From my cell, there is an object that I update but I would like to update it also in the array of my controllers. How ?

For example :

UITableViewCell :

class NotificationTableViewCell: UITableViewCell {

    @IBOutlet weak var buttonRead: UIButton!

    var notification = Notification()

    override func awakeFromNib() {
        super.awakeFromNib()
    }

    @IBAction func clickButtonRead(_ sender: Any) {
        self.notification.isRead = true
    }
}

UIViewController :

class NotificationsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UITabBarControllerDelegate {

    @IBOutlet weak var tableView: UITableView!

    /* List notifications */
    var listNotifications = [Notification]()

    override func viewDidLoad() {
        super.viewDidLoad()

        //View cell
        let nib = UINib(nibName: "viewNotificationTableViewCell", bundle: nil)
        self.tableView.register(nib, forCellReuseIdentifier: "cellNotification")

    }

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

    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.listNotifications.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        var cell = tableView.dequeueReusableCell(withIdentifier: "cellNotification", for: indexPath) as! NotificationTableViewCell

        cell.notification = self.listNotifications[indexPath.row]

        return cell
    }
}

EDIT :
I can pass the controller and the indexPath to the cell for update the object notification in listNotifications like this : self.controller.listNotifications[indexPath.row] = self.notification
But if i use this cell with more controllers, I must cast the controller from cell to know what controller is it.
I am looking for a way to update the object without having to cast the controller.

Body:
The ideal way to do it is you create a NotificationTableViewCellDelegate and set the delegate to view controller. In your method clickButtonRead call the delegate method and update the object in the view controller.

    protocol NotificationTableViewCellDelegate {
        func enableReadForNotification(notification: Notification)
    }

    class NotificationTableViewCell: UITableViewCell {

            @IBOutlet weak var buttonRead: UIButton!
            var notification = Notification()
            weak var delegate: NotificationTableViewCellDelegate?

            override func awakeFromNib() {
                super.awakeFromNib()
            }

            @IBAction func clickButtonRead(_ sender: Any) {
                self.notification.isRead = true
               if let delegate = self.delegate {
                  delegate.enableReadForNotification(self.notification)
               }
            }
        }

Hope this helps!


问:
Redirect user to another page once increment value reach 100
I have created a UI where when service return true value, I have created a loading bar which will reach 100%, after reaching 100% user should be redirect to another page.

lets assume, If the service return false value, the status bar stay at 10% loaded.

Link to jsfiddle

I have created function were I have written the progress bar logic and I am returning true value when service return true and redirecting to other URL.

everything is working great. But I want the progress bar to reach 100% and after that only user should be redirected. Below is the code (And above is jsfiddle link):

```<code>var serviceStatus = true; // Suppose value from service
var elem = document.getElementById("blueBar");
var perNum = document.getElementById("progressPercentage");

var width = 10; // intial progress bar width
var id = setInterval(progressBar, 10);
function progressBar() {
    if (width >= 100 || serviceStatus === false) {
        clearInterval(id);
        return false;
    } else {
        width ++;
        elem.style.width = width + '%';
        perNum.innerHTML = width * 1  + '%';
        //return true;
    }
}

function redirectUser(progressBar) {
    console.log(progressBar);
    // if (frame === true) {
    //  window.location = "http://www.google.com";
    // };
}

redirectUser(progressBar());
</code>```

Thanks, any questions? please ask.

答:
Check that when the width reaches 100 % then only redirect to other page. So add condition in your progressBar function like this. Have added timeout just to show that the width reaches 100% and then it is redirected. Even if you don't use timeout that will redirect.

```<code>function progressBar() {
        if (width >= 100 || serviceStatus === false) {
            clearInterval(id);
            return false;
        } else {
            width ++;
            elem.style.width = width + '%';
            perNum.innerHTML = width * 1  + '%';
            return true;
        }
    }

function redirectUser(progressBar) {
    if(progressBar){
      setTimeout(function(){
         window.location.href = "https://www.google.com";
      },1000)
  }
</code>```

This may not work on fiddle or Stackoverflow Snippets because 'X-Frame-Options' is set to 'SAMEORIGIN' in frames used to display results.

Body:
I have created a UI where when service return true value, I have created a loading bar which will reach 100%, after reaching 100% user should be redirect to another page.

lets assume, If the service return false value, the status bar stay at 10% loaded.

Link to jsfiddle

I have created function were I have written the progress bar logic and I am returning true value when service return true and redirecting to other URL.

everything is working great. But I want the progress bar to reach 100% and after that only user should be redirected. Below is the code (And above is jsfiddle link):

var serviceStatus = true; // Suppose value from service
var elem = document.getElementById("blueBar");
var perNum = document.getElementById("progressPercentage");

var width = 10; // intial progress bar width
var id = setInterval(progressBar, 10);
function progressBar() {
    if (width >= 100 || serviceStatus === false) {
        clearInterval(id);
        return false;
    } else {
        width ++;
        elem.style.width = width + '%';
        perNum.innerHTML = width * 1  + '%';
        //return true;
    }
}

function redirectUser(progressBar) {
    console.log(progressBar);
    // if (frame === true) {
    //  window.location = "http://www.google.com";
    // };
}

redirectUser(progressBar());

Thanks, any questions? please ask.

Body:
Check that when the width reaches 100 % then only redirect to other page. So add condition in your progressBar function like this. Have added timeout just to show that the width reaches 100% and then it is redirected. Even if you don't use timeout that will redirect.

function progressBar() {
        if (width >= 100 || serviceStatus === false) {
            clearInterval(id);
            return false;
        } else {
            width ++;
            elem.style.width = width + '%';
            perNum.innerHTML = width * 1  + '%';
            return true;
        }
    }

function redirectUser(progressBar) {
    if(progressBar){
      setTimeout(function(){
         window.location.href = "https://www.google.com";
      },1000)
  }

This may not work on fiddle or Stackoverflow Snippets because 'X-Frame-Options' is set to 'SAMEORIGIN' in frames used to display results.


问:
Update values from multiple selected rows
I have 2 tables. Both have the same amount of rows.

Sample data:

```<code>Table1{
    Id, IdTable2Row
}

Table2 {
    Id, RedChicken -- LOL
}
</code>```

Each row of Table1 (column IdTable2Row) should get the id of 1 row of table 2 (irrelevant which one).
Table1.IdTable2Row is null in every row before the operation.

How can I do something like this?

```<code>UPDATE Table1 SET IdTable2Row = (SELECT Id FROM [Table2])
</code>```

答:
If I understand correctly you need to match rows 1 to 1. Here is a solution I come up with:</p>

```<code>declare @Table1 table(
    Id INT,
    IdTable2Row INT NULL
)

declare @Table2 table(
    Id INT, RedChicken varchar(10) -- LOL
)

INSERT INTO @Table1
    VALUES
    (
        1,NULL
    ),(
        2,NULL
    ),(
        3,NULL
    );

INSERT INTO @Table2
    VALUES
    (
        10,'s'
    ),(
        20,'a'
    ),(
        30,'b'
    );

SELECT *
FROM @Table1 ;
SELECT *
FROM @Table2;

WITH cte1 AS
(
SELECT
ROW_NUMBER() over(ORDER by Id)  AS rown
,Id
,IdTable2Row
FROM @Table1
),
cte2 AS
(
SELECT ROW_NUMBER() over(ORDER by Id) AS rown
 ,Id
 ,RedChicken
FROM @Table2
)
UPDATE t
SET IdTable2Row = c2.Id
FROM @Table1 t
JOIN cte1 c1 ON c1.Id = t.Id
JOIN cte2 c2 ON c1.rown = c2.rown

SELECT *
FROM @Table1
</code>```

Body:
I have 2 tables. Both have the same amount of rows.

Sample data:

Table1{
    Id, IdTable2Row
}

Table2 {
    Id, RedChicken -- LOL
}

Each row of Table1 (column IdTable2Row) should get the id of 1 row of table 2 (irrelevant which one).
Table1.IdTable2Row is null in every row before the operation.

How can I do something like this?

UPDATE Table1 SET IdTable2Row = (SELECT Id FROM [Table2])

Body:
If I understand correctly you need to match rows 1 to 1. Here is a solution I come up with:

declare @Table1 table(
    Id INT,
    IdTable2Row INT NULL
)

declare @Table2 table(
    Id INT, RedChicken varchar(10) -- LOL
)

INSERT INTO @Table1
    VALUES
    (
        1,NULL
    ),(
        2,NULL
    ),(
        3,NULL
    );

INSERT INTO @Table2
    VALUES
    (
        10,'s'
    ),(
        20,'a'
    ),(
        30,'b'
    );

SELECT *
FROM @Table1 ;
SELECT *
FROM @Table2;

WITH cte1 AS
(
SELECT
ROW_NUMBER() over(ORDER by Id)  AS rown
,Id
,IdTable2Row
FROM @Table1
),
cte2 AS
(
SELECT ROW_NUMBER() over(ORDER by Id) AS rown
 ,Id
 ,RedChicken
FROM @Table2
)
UPDATE t
SET IdTable2Row = c2.Id
FROM @Table1 t
JOIN cte1 c1 ON c1.Id = t.Id
JOIN cte2 c2 ON c1.rown = c2.rown

SELECT *
FROM @Table1


问:
JavaFX Location is not set error message
I have problem when trying to close current scene and open up another scene when menuItem is selected. My main stage is coded as below:

```<code>public void start(Stage primaryStage) throws Exception {
    primaryStage.setTitle("Shop Management");
    FXMLLoader myLoader = new FXMLLoader(getClass().getResource("cartHomePage.fxml"));

    Pane myPane = (Pane) myLoader.load();

    CartHomePageUI controller = (CartHomePageUI) myLoader.getController();

    controller.setPrevStage(primaryStage);
    Scene myScene = new Scene(myPane);
    primaryStage.setScene(myScene);
    primaryStage.show();
}
</code>```

When the program is executed, it will go to the cartHomePage.fxml. From there, I can select to go to create product or create category when the menu item is selected. Here is my action event:

```<code>Stage prevStage;

public void setPrevStage(Stage stage){
     this.prevStage = stage;
}

 public void gotoCreateCategory(ActionEvent event) throws IOException {
  Stage stage = new Stage();
    stage.setTitle("Shop Management");
    FXMLLoader myLoader = new FXMLLoader(getClass().getResource("createCategory.fxml"));
    Pane myPane = (Pane) myLoader.load();
    Scene scene = new Scene(myPane);
    stage.setScene(scene);
    prevStage.close();
    setPrevStage(stage);
    stage.show();
}

//Method to change scene when menu item create product is on click
@FXML
public void gotoCreateProduct(ActionEvent event) throws IOException {
   Stage stage = new Stage();
    stage.setTitle("Shop Management");
    FXMLLoader myLoader = new FXMLLoader(getClass().getResource("creatProduct.fxml"));
    Pane myPane = (Pane) myLoader.load();
    Scene scene = new Scene(myPane);
    stage.setScene(scene);
    prevStage.close();
    setPrevStage(stage);
    stage.show();
}
</code>```

However, I can only switch the stage once. For example, my default page is cartHomePage.fxml. When I run the program, first I go to create product stage. After that, I cannot go to anywhere any more. The error message is:

```<code>java.lang.IllegalStateException: Location is not set.
and Null Pointer Exception
</code>```

I did set the stage after I close it and pass it around. I wonder which part went wrong.

Thanks in advance.

答:
I think problem is either incorrect layout name or invalid layout file path.

for IntelliJ, you can create resource directory and place layout files there.

```<code>FXMLLoader loader = new FXMLLoader();
loader.setLocation(getClass().getResource("/sample.fxml"));
rootLayout = loader.load();
</code>```

Body:
I have problem when trying to close current scene and open up another scene when menuItem is selected. My main stage is coded as below:

public void start(Stage primaryStage) throws Exception {
    primaryStage.setTitle("Shop Management");
    FXMLLoader myLoader = new FXMLLoader(getClass().getResource("cartHomePage.fxml"));

    Pane myPane = (Pane) myLoader.load();

    CartHomePageUI controller = (CartHomePageUI) myLoader.getController();

    controller.setPrevStage(primaryStage);
    Scene myScene = new Scene(myPane);
    primaryStage.setScene(myScene);
    primaryStage.show();
}

When the program is executed, it will go to the cartHomePage.fxml. From there, I can select to go to create product or create category when the menu item is selected. Here is my action event:

Stage prevStage;

public void setPrevStage(Stage stage){
     this.prevStage = stage;
}

 public void gotoCreateCategory(ActionEvent event) throws IOException {
  Stage stage = new Stage();
    stage.setTitle("Shop Management");
    FXMLLoader myLoader = new FXMLLoader(getClass().getResource("createCategory.fxml"));
    Pane myPane = (Pane) myLoader.load();
    Scene scene = new Scene(myPane);
    stage.setScene(scene);
    prevStage.close();
    setPrevStage(stage);
    stage.show();
}

//Method to change scene when menu item create product is on click
@FXML
public void gotoCreateProduct(ActionEvent event) throws IOException {
   Stage stage = new Stage();
    stage.setTitle("Shop Management");
    FXMLLoader myLoader = new FXMLLoader(getClass().getResource("creatProduct.fxml"));
    Pane myPane = (Pane) myLoader.load();
    Scene scene = new Scene(myPane);
    stage.setScene(scene);
    prevStage.close();
    setPrevStage(stage);
    stage.show();
}

However, I can only switch the stage once. For example, my default page is cartHomePage.fxml. When I run the program, first I go to create product stage. After that, I cannot go to anywhere any more. The error message is:

java.lang.IllegalStateException: Location is not set.
and Null Pointer Exception

I did set the stage after I close it and pass it around. I wonder which part went wrong.

Thanks in advance.

Body:
I think problem is either incorrect layout name or invalid layout file path.

for IntelliJ, you can create resource directory and place layout files there.

FXMLLoader loader = new FXMLLoader();
loader.setLocation(getClass().getResource("/sample.fxml"));
rootLayout = loader.load();


答:
You can achieve this by using protocol
make a protocol in your tableview Cell Class

```<code>    protocol NotificationDelegate{
       func didReadNotification(notification:Notification , index:Int)
    }
    class NotificationTableViewCell: UITableViewCell {

        @IBOutlet weak var buttonRead: UIButton!
        // and make this optional don't initialize it
        var notification:Notification?
        var delegate:NotificationDelegate?
        var indexOfNotification:Int?
        override func awakeFromNib() {
            super.awakeFromNib()
        }

        @IBAction func clickButtonRead(_ sender: Any) {
            self.notification?.isRead = true
            self.delegate?.didReadNotification(notification:self.notification! , index:indexOfNotification!)
        }

}
</code>```

and add NotificationDelegate in you ViewController

```<code>    class NotificationsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UITabBarControllerDelegate , NotificationDelegate {

        @IBOutlet weak var tableView: UITableView!

        /* List notifications */
        var listNotifications = [Notification]()

        override func viewDidLoad() {
            super.viewDidLoad()

            //View cell
            let nib = UINib(nibName: "viewNotificationTableViewCell", bundle: nil)
            self.tableView.register(nib, forCellReuseIdentifier: "cellNotification")

        }

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

        func numberOfSections(in tableView: UITableView) -> Int {
            return 1
        }

        func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return self.listNotifications.count
        }

        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

            var cell = tableView.dequeueReusableCell(withIdentifier: "cellNotification", for: indexPath) as! NotificationTableViewCell

            cell.notification = self.listNotifications[indexPath.row]
            cell.delegate = self
            cell.indexOfNotification = indexPath.row
            return cell
        }

      // This Delegte method will be called whenever user read the notification
      func didReadNotification(notification:Notification , index:Int){
          // do what ever you want here is your index and notification..
          let notification = listNotifications[index] // this is your notification in listNotifications
      }

}
</code>```

Title: Update object of an array in UIViewController from UITableViewCell

Body:
You can achieve this by using protocol
make a protocol in your tableview Cell Class

    protocol NotificationDelegate{
       func didReadNotification(notification:Notification , index:Int)
    }
    class NotificationTableViewCell: UITableViewCell {

        @IBOutlet weak var buttonRead: UIButton!
        // and make this optional don't initialize it
        var notification:Notification?
        var delegate:NotificationDelegate?
        var indexOfNotification:Int?
        override func awakeFromNib() {
            super.awakeFromNib()
        }

        @IBAction func clickButtonRead(_ sender: Any) {
            self.notification?.isRead = true
            self.delegate?.didReadNotification(notification:self.notification! , index:indexOfNotification!)
        }

}

and add NotificationDelegate in you ViewController

    class NotificationsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UITabBarControllerDelegate , NotificationDelegate {

        @IBOutlet weak var tableView: UITableView!

        /* List notifications */
        var listNotifications = [Notification]()

        override func viewDidLoad() {
            super.viewDidLoad()

            //View cell
            let nib = UINib(nibName: "viewNotificationTableViewCell", bundle: nil)
            self.tableView.register(nib, forCellReuseIdentifier: "cellNotification")

        }

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

        func numberOfSections(in tableView: UITableView) -> Int {
            return 1
        }

        func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return self.listNotifications.count
        }

        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

            var cell = tableView.dequeueReusableCell(withIdentifier: "cellNotification", for: indexPath) as! NotificationTableViewCell

            cell.notification = self.listNotifications[indexPath.row]
            cell.delegate = self
            cell.indexOfNotification = indexPath.row
            return cell
        }

      // This Delegte method will be called whenever user read the notification
      func didReadNotification(notification:Notification , index:Int){
          // do what ever you want here is your index and notification..
          let notification = listNotifications[index] // this is your notification in listNotifications
      }

}


问:
List all SQL columns with max length AND greatest length
I am trying to get a list of all columns from a table with their data types, data lengths and the length of the longest value in that column.

I have this SQL for getting the columns and their data types and lengths:

```<code>SELECT
    Object_Name(c.object_id),
    c.name 'Column Name',
    t.Name 'Data type',
    c.max_length 'Max Length'
FROM
    sys.columns c
INNER JOIN
    sys.types t ON c.system_type_id = t.system_type_id
WHERE
    c.object_id = OBJECT_ID('MyTable')
</code>```

And I have this SQL for getting the maximum length of a value:

```<code>SELECT Max(Len(MyColumn))
FROM MyTable
</code>```

But I can't figure out how to combine them. I am using SQL Server 2008.

答:
Note that all queries mentioned above will report some "strange" sizes - particularly for n... types (nvarchar / nchar). This slightly modified query fixes this issue:</p>

```<code>DECLARE @tableName AS NVARCHAR(200) = 'Items'

SELECT
    Object_Name(c.object_id) AS 'Table',
    c.name AS 'Column Name',
    t.name AS 'Data type',
    CASE WHEN t.name LIKE 'n%' THEN c.max_length / 2 ELSE c.max_length END AS 'Max Length'
FROM
    sys.columns c
INNER JOIN
    sys.types t ON c.user_type_id = t.user_type_id
WHERE
    c.object_id = OBJECT_ID(@tableName)
</code>```

Body:
I am trying to get a list of all columns from a table with their data types, data lengths and the length of the longest value in that column.

I have this SQL for getting the columns and their data types and lengths:

SELECT
    Object_Name(c.object_id),
    c.name 'Column Name',
    t.Name 'Data type',
    c.max_length 'Max Length'
FROM
    sys.columns c
INNER JOIN
    sys.types t ON c.system_type_id = t.system_type_id
WHERE
    c.object_id = OBJECT_ID('MyTable')

And I have this SQL for getting the maximum length of a value:

SELECT Max(Len(MyColumn))
FROM MyTable

But I can't figure out how to combine them. I am using SQL Server 2008.

Body:
Note that all queries mentioned above will report some "strange" sizes - particularly for n... types (nvarchar / nchar). This slightly modified query fixes this issue:

DECLARE @tableName AS NVARCHAR(200) = 'Items'

SELECT
    Object_Name(c.object_id) AS 'Table',
    c.name AS 'Column Name',
    t.name AS 'Data type',
    CASE WHEN t.name LIKE 'n%' THEN c.max_length / 2 ELSE c.max_length END AS 'Max Length'
FROM
    sys.columns c
INNER JOIN
    sys.types t ON c.user_type_id = t.user_type_id
WHERE
    c.object_id = OBJECT_ID(@tableName)


问:
Regex to Validate GSTIN Number
How to Validate GSTIN Number using regex.
eg.11ABCDE1234L1Z1

My current regex is:

```<code>^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$
</code>```

答:
System.Text.RegularExpressions.Regex rPan =
                        new System.Text.RegularExpressions.Regex("^[0-9]{2}[A-Z]{5}[0-9]{4}[A-Z]{1}[0-9]{1}[Z]{1}[0-9]{1}$");</p>

Title: Regex to Validate GSTIN Number

Body:
How to Validate GSTIN Number using regex.
eg.11ABCDE1234L1Z1

My current regex is:

^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$


答:
Your methods seems correct, but you are calling them incorrectly.

```<code>redirectUser(progressBar());
</code>```

This will call redirectUser first and then progressBar() that's why you are seeing undefined. If you have to pass function or callback to another function you are not suppose to call it.

You can pass it like another variables.

```<code>redirectUser(progressBar);
</code>```

Hope this will help you.

```<code>var blueProgressBar = {
    initialize: function() {
        var serviceStatus = true; // Suppose value from service
        var elem = document.getElementById("blueBar");
        var perNum = document.getElementById("progressPercentage");

        var width = 10; // intial progress bar width
        var id = setInterval(progressBar, 10);

        function progressBar() {
            if (width >= 100 || serviceStatus === false) {
                clearInterval(id);
                redirectUser()
            } else {
                width ++;
                elem.style.width = width + '%';
                perNum.innerHTML = width * 1  + '%';
            }
        }

        function redirectUser() {
          console.log("redirect");
          window.location = "http://www.google.com";
        }

        progressBar();
    }

}

$(function() {
    blueProgressBar.initialize();
});
</code>```

Title: Redirect user to another page once increment value reach 100

Body:
Your methods seems correct, but you are calling them incorrectly.

redirectUser(progressBar());

This will call redirectUser first and then progressBar() that's why you are seeing undefined. If you have to pass function or callback to another function you are not suppose to call it.

You can pass it like another variables.

redirectUser(progressBar);

Hope this will help you.

var blueProgressBar = {
    initialize: function() {
        var serviceStatus = true; // Suppose value from service
        var elem = document.getElementById("blueBar");
        var perNum = document.getElementById("progressPercentage");

        var width = 10; // intial progress bar width
        var id = setInterval(progressBar, 10);

        function progressBar() {
            if (width >= 100 || serviceStatus === false) {
                clearInterval(id);
                redirectUser()
            } else {
                width ++;
                elem.style.width = width + '%';
                perNum.innerHTML = width * 1  + '%';
            }
        }

        function redirectUser() {
          console.log("redirect");
          window.location = "http://www.google.com";
        }

        progressBar();
    }

}

$(function() {
    blueProgressBar.initialize();
});


问:
Application crashes when sending to different device
I have developed a few applications and run them on my phone and they work well. But when I send them to different phone they won't open even when I try to reinstall them on my phone from the APK file they stop working. Can anyone help me?</p>

答:
I think you share your app which install from android studio directly. That app cannot able to run in other devices.

So, Build apk file in android studio and then share that apk file to your friends. It will run smoothly/


问:
Youtube API iframes don't show up on browser refresh
The following script works fine, however in a very random order, when I refresh the browser, the iframe youtube generated video don't show up (sometimes they do, it's very random). The iframe doesn't get generated and the markup has only the empty divs which would eventually be replaced by the iframe.

I am loading the  youtube API using a script tag:

```<code><script src="https://www.youtube.com/iframe_api"></script>
</code>```

When the videos don't show up I don't get any error in the console either.

```<code>$(document).ready(function(){

    window.onYouTubePlayerAPIReady = function() {
        var players = [], vids=[], player0, player1, player2;

        for (var i = 0; i < document.querySelectorAll(".video-thumb__single").length; i++) {
            players.push(document.querySelectorAll(".video-thumb__single")[i].dataset.videoId);
        }

        player0 = new YT.Player('player0', {
          height: '200',
          width: '400',
          videoId: players[0],
          events: {
            'onStateChange': onPlayerStateChange
          }
        });
        vids.push(player0);

        player1 = new YT.Player('player1', {
          height: '200',
          width: '400',
          videoId: players[1],
          events: {
            'onStateChange': onPlayerStateChange
          }
        });
        vids.push(player1);

        player2 = new YT.Player('player2', {
          height: '200',
          width: '400',
          videoId: players[2],
          events: {
            'onStateChange': onPlayerStateChange
          }
        });
        vids.push(player2);

        function onPlayerStateChange(event) {
            if (event.data == YT.PlayerState.PLAYING) {
              stopVideo(event.target.a.id);
            }
        }

        function stopVideo(player_id) {
            console.log(vids);
            for (var i = 0; i < vids.length; i++) {
              if (player_id != vids[i].a.id)
                vids[i].stopVideo();
            }
        }

    }

});
</code>```

答:
I ended up doing the following:

```<code>    window.onYouTubeIframeAPIReady = function() {
        player0 = new YT.Player('player0', {
            height: '390',
            width: '640',
            videoId: ids[0],
            events: {
                'onStateChange': onPlayerStateChange
            }
        });

        player1 = new YT.Player('player1', {
            height: '390',
            width: '640',
            videoId: ids[1],
            events: {
                'onStateChange': onPlayerStateChange
            }
        });

        player2 = new YT.Player('player2', {
            height: '390',
            width: '640',
            videoId: ids[2],
            events: {
                'onStateChange': onPlayerStateChange
            }
        });
    }
</code>```

had to attache "onYouTubeIframeAPIReady" to the window object. The API says that the function has to be in the global scope to be fired. This has fixed my problem but I still don't understand how it's different from before.

Body:
The following script works fine, however in a very random order, when I refresh the browser, the iframe youtube generated video don't show up (sometimes they do, it's very random). The iframe doesn't get generated and the markup has only the empty divs which would eventually be replaced by the iframe.

I am loading the  youtube API using a script tag:

When the videos don't show up I don't get any error in the console either.

$(document).ready(function(){

    window.onYouTubePlayerAPIReady = function() {
        var players = [], vids=[], player0, player1, player2;

        for (var i = 0; i < document.querySelectorAll(".video-thumb__single").length; i++) {
            players.push(document.querySelectorAll(".video-thumb__single")[i].dataset.videoId);
        }

        player0 = new YT.Player('player0', {
          height: '200',
          width: '400',
          videoId: players[0],
          events: {
            'onStateChange': onPlayerStateChange
          }
        });
        vids.push(player0);

        player1 = new YT.Player('player1', {
          height: '200',
          width: '400',
          videoId: players[1],
          events: {
            'onStateChange': onPlayerStateChange
          }
        });
        vids.push(player1);

        player2 = new YT.Player('player2', {
          height: '200',
          width: '400',
          videoId: players[2],
          events: {
            'onStateChange': onPlayerStateChange
          }
        });
        vids.push(player2);

        function onPlayerStateChange(event) {
            if (event.data == YT.PlayerState.PLAYING) {
              stopVideo(event.target.a.id);
            }
        }

        function stopVideo(player_id) {
            console.log(vids);
            for (var i = 0; i < vids.length; i++) {
              if (player_id != vids[i].a.id)
                vids[i].stopVideo();
            }
        }

    }

});

Body:
I ended up doing the following:

    window.onYouTubeIframeAPIReady = function() {
        player0 = new YT.Player('player0', {
            height: '390',
            width: '640',
            videoId: ids[0],
            events: {
                'onStateChange': onPlayerStateChange
            }
        });

        player1 = new YT.Player('player1', {
            height: '390',
            width: '640',
            videoId: ids[1],
            events: {
                'onStateChange': onPlayerStateChange
            }
        });

        player2 = new YT.Player('player2', {
            height: '390',
            width: '640',
            videoId: ids[2],
            events: {
                'onStateChange': onPlayerStateChange
            }
        });
    }

had to attache "onYouTubeIframeAPIReady" to the window object. The API says that the function has to be in the global scope to be fired. This has fixed my problem but I still don't understand how it's different from before.


问:
Marshalling two similar json fields to the same java field
I have a sample dummy JSON response that looks like :

```<code>    {
        "id": 1,
        "teacher_name": "Foo",
        "teacher_address": "123 Main St.",
        "teacher_phone_num": 1234567891,
        "student_name": "Bar",
        "student_address": "546 Main St.",
        "student_phone_num": 9184248576
    }
</code>```

The above is a silly example, but it helps illustrate the issue I am having trying to de-serialize the above into a Java class called "Employee" using Jackson:

```<code>public class Employee {
    String name;
    String address;
    String phoneNumber;
}
</code>```

The issue is that the JSON has two different prepends so I cannot annotate each field in Employee and have the object mapper map teacher_name and student_name to the name field in an Employee object. Is there a way in Jackson to specify two differently named nodes to map to the same Java field?

答:
So in my example, I should end up with two Employee objects (I am guaranteed to have one pair per response)

It is not possible with Jackson. It is designed to map one-to-one: one json object to one java object. But you want to end up with two java objects from one json.

I would recommend you to go with strait forward way by implementing some processing level that will consume Response and map it to two Employee objects.

Body:
I have a sample dummy JSON response that looks like :

    {
        "id": 1,
        "teacher_name": "Foo",
        "teacher_address": "123 Main St.",
        "teacher_phone_num": 1234567891,
        "student_name": "Bar",
        "student_address": "546 Main St.",
        "student_phone_num": 9184248576
    }

The above is a silly example, but it helps illustrate the issue I am having trying to de-serialize the above into a Java class called "Employee" using Jackson:

public class Employee {
    String name;
    String address;
    String phoneNumber;
}

The issue is that the JSON has two different prepends so I cannot annotate each field in Employee and have the object mapper map teacher_name and student_name to the name field in an Employee object. Is there a way in Jackson to specify two differently named nodes to map to the same Java field?


问:
'find -exec' a shell function in Linux
Is there a way to get find to execute a function I define in the shell?

For example:

```<code>dosomething () {
  echo "Doing something with $1"
}
find . -exec dosomething {} \;
</code>```

The result of that is:

```<code>find: dosomething: No such file or directory
</code>```

Is there a way to get find's -exec to see dosomething?

答:
I find the easiest way is as follows, repeating two commands in a single do:

```<code>func_one () {
  echo "The first thing with $1"
}

func_two () {
  echo "The second thing with $1"
}

find . -type f | while read file; do func_one $file; func_two $file; done
</code>```

Title: 'find -exec' a shell function in Linux

Body:
Is there a way to get find to execute a function I define in the shell?

For example:

dosomething () {
  echo "Doing something with $1"
}
find . -exec dosomething {} \;

The result of that is:

find: dosomething: No such file or directory

Is there a way to get find's -exec to see dosomething?

Body:
I find the easiest way is as follows, repeating two commands in a single do:

func_one () {
  echo "The first thing with $1"
}

func_two () {
  echo "The second thing with $1"
}

find . -type f | while read file; do func_one $file; func_two $file; done


问:
Why does my code not work (diary code)?
This is a code of a diary. I want the user to write something in the diary and this is gonna be the first page and gonna be put in a list. After writing enter the next page should be started and he writes something in the next page etc.
I get errors over and over and I don't know why. After writing "enter" I get errors. I am new to java and all in all programming/coding (if it's the same). Sorry if it's a really dumb question i'm asking :/
Thank you for every advice. I am thankful for everything because I want to learn as much as I can for my university which would be in 1 year.</p>

```<code>import java.util.ArrayList;
import java.util.Scanner;

public class NotizbuchKlasse{
    public static void Pages(){
        System.out.println("Tag 1 : Write something in your diary.");
        System.out.println("Write enter if you are done writing.");
        ArrayList<String> List = new ArrayList<String>();
        String ListInList;
        Scanner write;
        do{
            write = new Scanner(System.in);
            ListInList = write.next();}
        while (! ListInList.equals("enter"));
        System.out.println("This is now your page. Your page is gonna be
        created after writing something new.");
        String y = ListInList;
        List.add(y);
        write.close();
        Pages();
    }
public static void main(String[]Args){
    Pages();
}
}

day 1 : Write something in your diary.
Write enter if you are done writing.
hello diary
enter
This is now your page. Your page is gonna be created after writing something
new.
Exception in thread "main" day 1 : Write something in your diary.
Write enter if you are done writing.
java.util.NoSuchElementException
    at java.util.Scanner.throwFor(Unknown Source)
    at java.util.Scanner.next(Unknown Source)
    at NotizbuchKlasse.Pages(NotizbuchKlasse.java:14)
    at NotizbuchKlasse.Pages(NotizbuchKlasse.java:20)
    at NotizbuchKlasse.main(NotizbuchKlasse.java:38)
</code>```

答:
You are using a.nextInt() which is used for taking integer as input. Just use a.next().charAt(0) instead of that. This is working</p>

```<code>import java.util.Scanner;

public class Taschenrechner {
    public static void calculator() {
        Scanner a = new Scanner(System.in);
        System.out.println("Give me the 2 numbers first: ");
        int x = a.nextInt();
        int y = a.nextInt();
        System.out.println("Now give me the operation (+,-,*,/): ");
        if (a.next().charAt(0) == '+') {
            float result = x + y;
            System.out.println("result: " + result);
        } else if (a.next().charAt(0) == '-') {
            float result = x - y;
            System.out.println("result: " + result);
        } else if (a.next().charAt(0) == '*') {
            float result = x * y;
            System.out.println("result: " + result);
        } else {
            float result = x / y;
            System.out.println("result: " + result);
        }
        a.close();
    }

    public static void main(String[] args) {
        calculator();
    }
}
</code>```

Title: Why does my code not work (diary code)?

Body:
This is a code of a diary. I want the user to write something in the diary and this is gonna be the first page and gonna be put in a list. After writing enter the next page should be started and he writes something in the next page etc.
I get errors over and over and I don't know why. After writing "enter" I get errors. I am new to java and all in all programming/coding (if it's the same). Sorry if it's a really dumb question i'm asking :/
Thank you for every advice. I am thankful for everything because I want to learn as much as I can for my university which would be in 1 year.

import java.util.ArrayList;
import java.util.Scanner;

public class NotizbuchKlasse{
    public static void Pages(){
        System.out.println("Tag 1 : Write something in your diary.");
        System.out.println("Write enter if you are done writing.");
        ArrayList<String> List = new ArrayList<String>();
        String ListInList;
        Scanner write;
        do{
            write = new Scanner(System.in);
            ListInList = write.next();}
        while (! ListInList.equals("enter"));
        System.out.println("This is now your page. Your page is gonna be
        created after writing something new.");
        String y = ListInList;
        List.add(y);
        write.close();
        Pages();
    }
public static void main(String[]Args){
    Pages();
}
}

day 1 : Write something in your diary.
Write enter if you are done writing.
hello diary
enter
This is now your page. Your page is gonna be created after writing something
new.
Exception in thread "main" day 1 : Write something in your diary.
Write enter if you are done writing.
java.util.NoSuchElementException
    at java.util.Scanner.throwFor(Unknown Source)
    at java.util.Scanner.next(Unknown Source)
    at NotizbuchKlasse.Pages(NotizbuchKlasse.java:14)
    at NotizbuchKlasse.Pages(NotizbuchKlasse.java:20)
    at NotizbuchKlasse.main(NotizbuchKlasse.java:38)

Body:
You are using a.nextInt() which is used for taking integer as input. Just use a.next().charAt(0) instead of that. This is working

import java.util.Scanner;

public class Taschenrechner {
    public static void calculator() {
        Scanner a = new Scanner(System.in);
        System.out.println("Give me the 2 numbers first: ");
        int x = a.nextInt();
        int y = a.nextInt();
        System.out.println("Now give me the operation (+,-,*,/): ");
        if (a.next().charAt(0) == '+') {
            float result = x + y;
            System.out.println("result: " + result);
        } else if (a.next().charAt(0) == '-') {
            float result = x - y;
            System.out.println("result: " + result);
        } else if (a.next().charAt(0) == '*') {
            float result = x * y;
            System.out.println("result: " + result);
        } else {
            float result = x / y;
            System.out.println("result: " + result);
        }
        a.close();
    }

    public static void main(String[] args) {
        calculator();
    }
}


问:
How to compare to strings?
I have two array lists, one list is of strings and second of Toggle button.Now I want to compare the strings in two arrays.Please help me. </p>

```<code>for(int i=0; i<arrayList1.size();i++){
            for (int j=0; j<arrayList.size();j++){

                Log.d("error in response:  ", "  " + arrayList.get(j).getText());

                Log.d("Tag" , arrayList1.get(i));
                if(arrayList1.get(i)==arrayList.get(j).getText()){

                    Log.d("Tag" , arrayList1.get(i));
                    Log.d("Tag" , String.valueOf(arrayList.get(j).getText()));

                    onCheckedChanged(arrayList.get(j), true);
                }
            }
        }
</code>```

答:
You can do by foreach loop too or just compare string by equals method call:</p>

```<code>for(String textString1:arrayList1 )
        {
            for(String textString:arrayList )
            {
                if(textString1.equalsIgnoreCase(textString))
                {
                    //do your stuff
                }
            }
        }
</code>```

Title: How to compare to strings?

Body:
I have two array lists, one list is of strings and second of Toggle button.Now I want to compare the strings in two arrays.Please help me.

for(int i=0; i<arrayList1.size();i++){
            for (int j=0; j<arrayList.size();j++){

                Log.d("error in response:  ", "  " + arrayList.get(j).getText());

                Log.d("Tag" , arrayList1.get(i));
                if(arrayList1.get(i)==arrayList.get(j).getText()){

                    Log.d("Tag" , arrayList1.get(i));
                    Log.d("Tag" , String.valueOf(arrayList.get(j).getText()));

                    onCheckedChanged(arrayList.get(j), true);
                }
            }
        }

Body:
You can do by foreach loop too or just compare string by equals method call:

for(String textString1:arrayList1 )
        {
            for(String textString:arrayList )
            {
                if(textString1.equalsIgnoreCase(textString))
                {
                    //do your stuff
                }
            }
        }


问:
Converting more than one image to binary with just one method
For my Little application, i have written a method to convert an image to binary and then save it in database. What i want to do now , is to find of way of making that same method be reuseable by other fileUpload. Which means, if i have two fileUploads eg.

                Image 1

```<code>        <div class="col-md-3">
            <div class="form-group">
                <label for="image2">Image 2</label>
                <asp:FileUpload ID="Upload2" runat="server" ForeColor="Blue" />
            </div>
        </div>
</code>```

i should be able to modify the method below to process the the images without having to rewrite the method again

```<code> private byte[]ConvertImage()
        {

            byte[] bytes = null;
           // byte[] bytes2 = null;
            try
            {

                HttpPostedFile postedFile = Upload1.PostedFile;

                string filename = Path.GetFileName(postedFile.FileName);
                string fileExtension = Path.GetExtension(filename);
                int filesize = postedFile.ContentLength;

                Stream stream = postedFile.InputStream;
                BinaryReader binaryreader = new BinaryReader(stream);

                bytes = binaryreader.ReadBytes((int)stream.Length);
                return bytes;
            }
            catch (Exception ex)
            {
                return null;
            }

        }
</code>```

The above code is what i'm using to just one fileUpload but i want to use it two without having to rewrite the whole code

答:
Extract the common code into a function:</p>

```<code>private void ConvertImages() {
  try {
    //Process first file.
    HttpPostedFile postedFile = Upload1.PostedFile;
    byte[] ReadImage(postedFile);
    //Now do whatever you want with first file. Maybe save it?

    //Process second file.
    postedFile = Upload2.PostedFile;
    byte[] ReadImage(postedFile);
    //Now do whatever you want with second file. Maybe save it?

  } catch (Exception ex) {
    //Handle exceptions.
  }
}

private byte[] ReadImage(HttpPostedFile postedFile) {
    string filename = Path.GetFileName(postedFile.FileName);
    string fileExtension = Path.GetExtension(filename);
    int filesize = postedFile.ContentLength;

    Stream stream = postedFile.InputStream;
    BinaryReader binaryreader = new BinaryReader(stream);

    return binaryreader.ReadBytes((int) stream.Length);
}
</code>```

Body:
For my Little application, i have written a method to convert an image to binary and then save it in database. What i want to do now , is to find of way of making that same method be reuseable by other fileUpload. Which means, if i have two fileUploads eg.

                Image 1

                Image 2
                <asp:FileUpload ID="Upload2" runat="server" ForeColor="Blue" />

i should be able to modify the method below to process the the images without having to rewrite the method again

 private byte[]ConvertImage()
        {

            byte[] bytes = null;
           // byte[] bytes2 = null;
            try
            {

                HttpPostedFile postedFile = Upload1.PostedFile;

                string filename = Path.GetFileName(postedFile.FileName);
                string fileExtension = Path.GetExtension(filename);
                int filesize = postedFile.ContentLength;

                Stream stream = postedFile.InputStream;
                BinaryReader binaryreader = new BinaryReader(stream);

                bytes = binaryreader.ReadBytes((int)stream.Length);
                return bytes;
            }
            catch (Exception ex)
            {
                return null;
            }

        }

The above code is what i'm using to just one fileUpload but i want to use it two without having to rewrite the whole code

Body:
Extract the common code into a function:

private void ConvertImages() {
  try {
    //Process first file.
    HttpPostedFile postedFile = Upload1.PostedFile;
    byte[] ReadImage(postedFile);
    //Now do whatever you want with first file. Maybe save it?

    //Process second file.
    postedFile = Upload2.PostedFile;
    byte[] ReadImage(postedFile);
    //Now do whatever you want with second file. Maybe save it?

  } catch (Exception ex) {
    //Handle exceptions.
  }
}

private byte[] ReadImage(HttpPostedFile postedFile) {
    string filename = Path.GetFileName(postedFile.FileName);
    string fileExtension = Path.GetExtension(filename);
    int filesize = postedFile.ContentLength;

    Stream stream = postedFile.InputStream;
    BinaryReader binaryreader = new BinaryReader(stream);

    return binaryreader.ReadBytes((int) stream.Length);
}


问:
Cannot GET / Node.js when publish with azure
i just have a problem when i publish to azure . it said: Cannot GET / when i open the website .

i using static site with node.js , angular.js, and loopback(API)

here my client side (site.js):

```<code>var express = require('express'),
    app = express();

app.use(express.static(__dirname + '/Public'));

var server = app.listen(1338, function() {
  console.log('Listening on port %d', server.address().port);
});
</code>```

There is index.html inside Public Folder .

this is my Package.json :

```<code>{
  "name": "angular-site",
  "version": "1.0.0",
  "description": "static server to server Node.js",
  "main": "site.js",
  "author": "Jordan Leonardi",
  "dependencies": {
    "express": "^4.8.5"
  }
}
</code>```

when i tried to localhost, its look Fine, but when i tried to Azurewebsites its give me back an error " Cannot GET / " . .

答:
You doesn't seem to have setup a route for /.
Your current implementation will return only the files in the /Public directory, when asked for. But the root route is not assigned.

You can use:

```<code>app.get('/', (req, res) => res.send('Hello World'));
</code>```

Body:
i just have a problem when i publish to azure . it said: Cannot GET / when i open the website .

i using static site with node.js , angular.js, and loopback(API)

here my client side (site.js):

var express = require('express'),
    app = express();

app.use(express.static(__dirname + '/Public'));

var server = app.listen(1338, function() {
  console.log('Listening on port %d', server.address().port);
});

There is index.html inside Public Folder .

this is my Package.json :

{
  "name": "angular-site",
  "version": "1.0.0",
  "description": "static server to server Node.js",
  "main": "site.js",
  "author": "Jordan Leonardi",
  "dependencies": {
    "express": "^4.8.5"
  }
}

when i tried to localhost, its look Fine, but when i tried to Azurewebsites its give me back an error " Cannot GET / " . .

Body:
You doesn't seem to have setup a route for /.
Your current implementation will return only the files in the /Public directory, when asked for. But the root route is not assigned.

You can use:

app.get('/', (req, res) => res.send('Hello World'));