问:
Scala syntax for anonymous object
I'm trying to find the Scala syntax corresponding to this java code. Assume A is a class a has got a method sayHi.

new A().sayHi() would be perfectly compilable as per valid java syntax. On the other hand, when I tried new A.sayHi() it does not compile in Scala. What syntax do we have in Scala for this?

答:
In Scala, one could use one of the following:

```<code>new A().sayHi()
(new A).sayHi()
</code>```

Without parentheses and when preceded by new, A.sayHi would be interpreted as a type and new A.sayHi() would then be an instantiation of the class type A.sayHi. If A.sayHi is not a class type that would result in a compile error.

Take a look:

```<code>scala> class A { def sayHi() = "hi" }; object A { type sayHi = String }
defined class A
defined object A

scala> new A().sayHi()
res0: String = hi

scala> new A.sayHi()  // same as `new String()`
res1: String = ""

scala> (new A).sayHi()
res2: String = hi
</code>```

Title: Scala syntax for anonymous object

Body:
In Scala, one could use one of the following:

new A().sayHi()
(new A).sayHi()

Without parentheses and when preceded by new, A.sayHi would be interpreted as a type and new A.sayHi() would then be an instantiation of the class type A.sayHi. If A.sayHi is not a class type that would result in a compile error.

Take a look:

scala> class A { def sayHi() = "hi" }; object A { type sayHi = String }
defined class A
defined object A

scala> new A().sayHi()
res0: String = hi

scala> new A.sayHi()  // same as `new String()`
res1: String = ""

scala> (new A).sayHi()
res2: String = hi


来源: stackexchange

问:
Delete or Select Only row with same id but have values for certain fields
I would like to select/delete data with different rows but with same id.

For Example.

```<code>ID  ColumnA
A    Honda
A    NULL
B    Yamaha
B    NULL
C    NULL
C    Merc
D    NULL
E    NULL
</code>```

Output:

```<code>ID  ColumnA
A    Honda
B    Yamaha
C    Merc
D    NULL
E    NULL
</code>```

First thing, I already google for the solutions, but no answers. Any help is greatly appreciated

答:
You could use Row_number and TOP 1 WITH TIES

```<code>DECLARE @SampleData AS TABLE
(
    ID varchar(10),
    ColumnA varchar(20)
)

INSERT INTO @SampleData
VALUES
('A', 'Honda'),
('A', NULL),
('B', 'Yamaha'),
('B', NULL),
('C', NULL),
('C', 'Merc'),
('D', NULL),
('E', NULL)

SELECT  TOP (1) WITH TIES
       sd.ID,
       sd.ColumnA
FROM @SampleData sd
ORDER BY Row_number() OVER(PARTITION BY sd.ID ORDER BY sd.ColumnA DESC)
</code>```

Return

```<code>ID  ColumnA
------------
A   Honda
B   Yamaha
C   Merc
D   NULL
E   NULL
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I would like to select/delete data with different rows but with same id.

For Example.

ID  ColumnA
A    Honda
A    NULL
B    Yamaha
B    NULL
C    NULL
C    Merc
D    NULL
E    NULL

Output:

ID  ColumnA
A    Honda
B    Yamaha
C    Merc
D    NULL
E    NULL

First thing, I already google for the solutions, but no answers. Any help is greatly appreciated

Body:
You could use Row_number and TOP 1 WITH TIES

DECLARE @SampleData AS TABLE
(
    ID varchar(10),
    ColumnA varchar(20)
)

INSERT INTO @SampleData
VALUES
('A', 'Honda'),
('A', NULL),
('B', 'Yamaha'),
('B', NULL),
('C', NULL),
('C', 'Merc'),
('D', NULL),
('E', NULL)

SELECT  TOP (1) WITH TIES
       sd.ID,
       sd.ColumnA
FROM @SampleData sd
ORDER BY Row_number() OVER(PARTITION BY sd.ID ORDER BY sd.ColumnA DESC)

Return

ID  ColumnA
------------
A   Honda
B   Yamaha
C   Merc
D   NULL
E   NULL


问:
Display an error message next to the input field if input field is blank
I am new to JavaScript and am a bit stuck...

I have a form and am trying to generate error messages next to input fields that are blank or do not contain the correct information.

Unfortunately is doesn't do anything...
Thanks for your help!!

My HTML:

```<code><form name="user_details" method="post" onsubmit="return checkform()">
    <table id="form_table">
        <tr>
            <td class="form_cell"><label for="first_name">First Name:</label></td>
            <td class="form_cell"><input type="text" id="first_name">*</td>
            <td id="error_first_name">The first name field needs to contain at least one character.</td>
        </tr>
        <tr>
            <td class="form_cell"><label for="surname">Surname:</label></td>
            <td class="form_cell"><input type="text" id="surname">*</td>
            <td id="error_surname">The surname field needs to contain at least one character.</td>
        </tr>
        <tr>
            <td class="form_cell"><label for="address">Address:</label></td>
            <td class="form_cell"><input type="text" id="address">*</td>
            <td id="error_address">The address field needs to contain at least one character.</td>
        </tr>
        <tr>
            <td class="form_cell"><label for="city">City:</label></td>
            <td class="form_cell"><input type="text" id="city">*</td>
            <td id="error_city">The city field needs to contain at least one character.</td>
        </tr>
        <tr>
            <td class="form_cell"><label for="post_code">Post Code:</label></td>
            <td class="form_cell"><input type="text" id="post_code">*</td>
            <td id="error_post_code">The post code field needs to contain a number.</td>
        </tr>
        <tr>
            <td class="form_cell"><label for="email">Email:</label></td>
            <td class="form_cell"><input type="email" id="email">*</td>
            <td id="error_email">The email field needs to contain an email address.</td>
        </tr>
        <tr>
            <td class="form_cell"><label for="phone_number">Phone Number:</label></td>
            <td class="form_cell"><input type="text" id="phone_number"></td>
        </tr>
    </table>
        <input type="submit"><input type=reset>
    </form>
</code>```

My JavaScript:

```<code>function checkform() {
var ok = true,
    first_name,
    surname,
    address,
    city,
    post_code,
    email;

if (document.getElementById("first_name").value == "") {
    document.getElementById("first_name").style.borderColor = "red";
    $("#error_first_name").show();
    ok = false;
}

else if (document.getElementById("surname").value == "") {
    document.getElementById("surname").style.borderColor = "red";
    $("#error_surname").show();
    ok = false;
}

else if (document.getElementById("address").value == "") {
    document.getElementById("address").style.borderColor = "red";
    $("#error_address").show();
    ok = false;
}

else if (document.getElementById("city").value == "") {
    document.getElementById("city").style.borderColor = "red";
    $("#error_city").show();
    ok = false;
}

else if (document.getElementById("post_code").value == "") {
    document.getElementById("post_code").style.borderColor = "red";
    $("#error_post_code").show();
    ok = false;
}

else if (document.getElementById("email").value == "") {
    document.getElementById("email").style.borderColor = "red";
    $("#error_email").show();
    ok = false;
}

else if (!/^[A-Za-z]+$/.test(document.getElementById("first_name").value)) {
    document.getElementById("first_name").style.borderColor = "red";
    ok = false;
}

else if (!/^[A-Za-z]+$/.test(document.getElementById("surname").value)) {
    document.getElementById("surname").style.borderColor = "red";
    ok = false;
}

else if (!/^[A-Za-z]+$/.test(document.getElementById("address").value)) {
    document.getElementById("address").style.borderColor = "red";
    ok = false;
}

else if (!/^[A-Za-z][0-9]+$/.test(document.getElementById("city").value)) {
    document.getElementById("city").style.borderColor = "red";
    ok = false;
}

else if (!/^[0-9]+$/.test(document.getElementById("post_code").value)) {
    document.getElementById("post_code").style.borderColor = "red";
    ok = false;
}

else if (!/\S+@\S+/.test(document.getElementById("email").value)) {
    document.getElementById("first_name").style.borderColor = "red";
    ok = false;
}

else {
    return ok;
}
</code>```

}

My CSS:

```<code>#error_first_name {
display: none;
}

#error_surname {
display: none;
}

#error_address {
display: none;
}

#error_city {
display: none;
}

#error_post_code {
display: none;
}

#error_email {
display: none;
}
</code>```

答:
I want to highlight some points based on your code

The errors is because you didn't include a jquery version in your code.

If you are using jquery then short your code using it.

Don't repeat same property to each id in CSS use a class instead.

Check empty and regex in single condition using ||

function checkform() {
  var ok = true,
    first_name = $.trim($("#first_name").val()),
    surname = $.trim($("#surname").val()),
    address = $.trim($("#first_name").val()),
    city = $.trim($("#city").val()),
    post_code = $.trim($("#post_code").val()),
    email = $.trim($("#email").val());
  $('input.bdred').removeClass('bdred');
  $('.errors').hide();
  if (!first_name || !/^[A-Za-z]+$/.test(first_name)) {
    $("#first_name").addClass('bdred');
    $("#error_first_name").show();
    ok = false;
  } else if (!surname || !/^[A-Za-z]+$/.test(surname)) {
    $("#surname").addClass('bdred');
    $("#error_surname").show();
    ok = false;
  } else if (!address || !/^[A-Za-z]+$/.test(address)) {
    $("#address").addClass('bdred');
    $("#error_address").show();
    ok = false;
  } else if (!city || !/^[A-Za-z][0-9]+$/.test(city)) {
    $("#city").addClass('bdred');
    $("#error_city").show();
    ok = false;
  } else if (!post_code || !/^[0-9]+$/.test(post_code)) {
    $("#post_code").addClass('bdred');
    $("#error_post_code").show();
    ok = false;
  } else if (!email || !/\S+@\S+/.test(email)) {
    $("#email").addClass('bdred');
    $("#error_email").show();
    ok = false;
  }
  return ok;
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.errors {
  display: none;
}

.bdred {
  border-color: red
}</code>```

<form name="user_details" method="post" onsubmit="return  checkform();">

      First Name:
      <input type="text" id="first_name">*
      The first name field needs to contain at least one character.

      Surname:
      <input type="text" id="surname">*
      The surname field needs to contain at least one character.

      Address:
      <input type="text" id="address">*
      The address field needs to contain at least one character.

      City:
      <input type="text" id="city">*
      The city field needs to contain at least one character.

      Post Code:
      <input type="text" id="post_code">*
      The post code field needs to contain a number.

      Email:
      <input type="email" id="email">*
      The email field needs to contain an email address.

      Phone Number:
      <input type="text" id="phone_number">

  <input type="submit"><input type=reset>
</form>```

Body:
I am new to JavaScript and am a bit stuck...

I have a form and am trying to generate error messages next to input fields that are blank or do not contain the correct information.

Unfortunately is doesn't do anything...
Thanks for your help!!

My HTML:

<form name="user_details" method="post" onsubmit="return checkform()">

            First Name:
            <input type="text" id="first_name">*
            The first name field needs to contain at least one character.

            Surname:
            <input type="text" id="surname">*
            The surname field needs to contain at least one character.

            Address:
            <input type="text" id="address">*
            The address field needs to contain at least one character.

            City:
            <input type="text" id="city">*
            The city field needs to contain at least one character.

            Post Code:
            <input type="text" id="post_code">*
            The post code field needs to contain a number.

            Email:
            <input type="email" id="email">*
            The email field needs to contain an email address.

            Phone Number:
            <input type="text" id="phone_number">

        <input type="submit"><input type=reset>
    </form>

My JavaScript:

function checkform() {
var ok = true,
    first_name,
    surname,
    address,
    city,
    post_code,
    email;

if (document.getElementById("first_name").value == "") {
    document.getElementById("first_name").style.borderColor = "red";
    $("#error_first_name").show();
    ok = false;
}

else if (document.getElementById("surname").value == "") {
    document.getElementById("surname").style.borderColor = "red";
    $("#error_surname").show();
    ok = false;
}

else if (document.getElementById("address").value == "") {
    document.getElementById("address").style.borderColor = "red";
    $("#error_address").show();
    ok = false;
}

else if (document.getElementById("city").value == "") {
    document.getElementById("city").style.borderColor = "red";
    $("#error_city").show();
    ok = false;
}

else if (document.getElementById("post_code").value == "") {
    document.getElementById("post_code").style.borderColor = "red";
    $("#error_post_code").show();
    ok = false;
}

else if (document.getElementById("email").value == "") {
    document.getElementById("email").style.borderColor = "red";
    $("#error_email").show();
    ok = false;
}

else if (!/^[A-Za-z]+$/.test(document.getElementById("first_name").value)) {
    document.getElementById("first_name").style.borderColor = "red";
    ok = false;
}

else if (!/^[A-Za-z]+$/.test(document.getElementById("surname").value)) {
    document.getElementById("surname").style.borderColor = "red";
    ok = false;
}

else if (!/^[A-Za-z]+$/.test(document.getElementById("address").value)) {
    document.getElementById("address").style.borderColor = "red";
    ok = false;
}

else if (!/^[A-Za-z][0-9]+$/.test(document.getElementById("city").value)) {
    document.getElementById("city").style.borderColor = "red";
    ok = false;
}

else if (!/^[0-9]+$/.test(document.getElementById("post_code").value)) {
    document.getElementById("post_code").style.borderColor = "red";
    ok = false;
}

else if (!/\S+@\S+/.test(document.getElementById("email").value)) {
    document.getElementById("first_name").style.borderColor = "red";
    ok = false;
}

else {
    return ok;
}

}

My CSS:

#error_first_name {
display: none;
}

#error_surname {
display: none;
}

#error_address {
display: none;
}

#error_city {
display: none;
}

#error_post_code {
display: none;
}

#error_email {
display: none;
}

Body:
I want to highlight some points based on your code

The errors is because you didn't include a jquery version in your code.

If you are using jquery then short your code using it.

Don't repeat same property to each id in CSS use a class instead.

Check empty and regex in single condition using ||

function checkform() {
  var ok = true,
    first_name = $.trim($("#first_name").val()),
    surname = $.trim($("#surname").val()),
    address = $.trim($("#first_name").val()),
    city = $.trim($("#city").val()),
    post_code = $.trim($("#post_code").val()),
    email = $.trim($("#email").val());
  $('input.bdred').removeClass('bdred');
  $('.errors').hide();
  if (!first_name || !/^[A-Za-z]+$/.test(first_name)) {
    $("#first_name").addClass('bdred');
    $("#error_first_name").show();
    ok = false;
  } else if (!surname || !/^[A-Za-z]+$/.test(surname)) {
    $("#surname").addClass('bdred');
    $("#error_surname").show();
    ok = false;
  } else if (!address || !/^[A-Za-z]+$/.test(address)) {
    $("#address").addClass('bdred');
    $("#error_address").show();
    ok = false;
  } else if (!city || !/^[A-Za-z][0-9]+$/.test(city)) {
    $("#city").addClass('bdred');
    $("#error_city").show();
    ok = false;
  } else if (!post_code || !/^[0-9]+$/.test(post_code)) {
    $("#post_code").addClass('bdred');
    $("#error_post_code").show();
    ok = false;
  } else if (!email || !/\S+@\S+/.test(email)) {
    $("#email").addClass('bdred');
    $("#error_email").show();
    ok = false;
  }
  return ok;
}

.errors {
  display: none;
}

.bdred {
  border-color: red
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="user_details" method="post" onsubmit="return  checkform();">
  <table id="form_table">
    <tr>
      <td class="form_cell"><label for="first_name">First Name:</label></td>
      <td class="form_cell"><input type="text" id="first_name">*</td>
      <td id="error_first_name" class="errors">The first name field needs to contain at least one character.</td>
    </tr>
    <tr>
      <td class="form_cell"><label for="surname">Surname:</label></td>
      <td class="form_cell"><input type="text" id="surname">*</td>
      <td id="error_surname" class="errors">The surname field needs to contain at least one character.</td>
    </tr>
    <tr>
      <td class="form_cell"><label for="address">Address:</label></td>
      <td class="form_cell"><input type="text" id="address">*</td>
      <td id="error_address" class="errors">The address field needs to contain at least one character.</td>
    </tr>
    <tr>
      <td class="form_cell"><label for="city">City:</label></td>
      <td class="form_cell"><input type="text" id="city">*</td>
      <td id="error_city" class="errors">The city field needs to contain at least one character.</td>
    </tr>
    <tr>
      <td class="form_cell"><label for="post_code">Post Code:</label></td>
      <td class="form_cell"><input type="text" id="post_code">*</td>
      <td id="error_post_code" class="errors">The post code field needs to contain a number.</td>
    </tr>
    <tr>
      <td class="form_cell"><label for="email">Email:</label></td>
      <td class="form_cell"><input type="email" id="email">*</td>
      <td id="error_email" class="errors">The email field needs to contain an email address.</td>
    </tr>
    <tr>
      <td class="form_cell"><label for="phone_number">Phone Number:</label></td>
      <td class="form_cell"><input type="text" id="phone_number"></td>
    </tr>
  </table>
  <input type="submit"><input type=reset>
</form>


问:
Doing operations with only Nth element of a list
I want to multiply only every second number on a list(0-100) but I just can't get it to work.</p>

答:
You can`t multiply with 0 , because the result will be always 0.</p>

```<code>result=1
for i in range (1 , 10 ):
   if i%2==0:
     result*=i
print(result)
</code>```

Body:
You can`t multiply with 0 , because the result will be always 0.

result=1
for i in range (1 , 10 ):
   if i%2==0:
     result*=i
print(result)


问:
Join columns that do not satisfy the condition
I have the following df:

```<code>df1:
            A    B     C
test1     1.06  4.0  6.00
test2     1.02  4.1  6.20
test3     1.07  0.9  6.10
test4     4.00  1.1  6.05
</code>```

then I divide each row by the previous obtaining this:

```<code>df2:
             A         B         C
test1       NaN       NaN       NaN
test2  0.962264  1.025000  1.033333
test3  1.049020  0.219512  0.983871
test4  3.738318  1.222222  0.991803
</code>```

I am looking that for each value higher than 1.35 (in df2) or less than 0.65 multiply the previous rows of df1 by that value higher than 1.35 or less than 0.65.

The desired output would look something like this:

```<code>             A         B         C
test1      3.96       0.87     6.00
test2      3.81       0.90     6.20
test3      4.00       0.90     6.10
test4      4.00       1.10     6.05
</code>```

The code I've made is this:

```<code>df_filtrado=pd.DataFrame()
for i in range(len(df2)):
    for j in range(len(list(df2.columns))):
        if df2.iloc[i,j]>1.35:
            values_higher=pd.concat([df1.iloc[0:i+1,[j]]*df2.iloc[i,j],df1.iloc[i+1:,[j]]])
            if df_filtrado.empty:
                df_filtrado= values_higher
            else:
                df_filtrado=pd.concat([df_filtrado,values_higher],axis=1, join_axes=[df_filtrado.index])
        elif df2.iloc[i,j]<0.65:
            values_lower=pd.concat([df1.iloc[0:i+1,[j]]*df2.iloc[i,j],df1.iloc[i+1:,[j]]])
            if df_filtrado.empty:
                df_filtrado= values_lower
            else:
                df_filtrado=pd.concat([df_filtrado,values_lower],axis=1, join_axes=[df_filtrado.index])

print df_filtrado
</code>```

The current output up to here does okay and returns the following:

```<code>          B         A
test1  0.878049  3.962617
test2  0.900000  3.813084
test3  0.900000  4.000000
test4  1.100000  4.000000
</code>```

What I am not capable of doing is to add the column that does not has any values higher than 1.35 or lower than 0.65 , like column C of df2 .

This is what I have tried (adding it to the previous code):

```<code>    normal=pd.DataFrame(df.iloc[:,i])
    if df2.iloc[:,i].all()>0.65 and df2.iloc[:,i].all()<1.35:

        if df_filtrado.empty:
            df_filtrado= normal
        else:
            df_filtrado=pd.concat([df_filtrado,normal],axis=1, join_axes=[df_filtrado.index])

print df_filtrado
</code>```

However the output returned is :

```<code>         A         B    B         A     C
test1  1.06  0.878049  4.0  3.962617  6.00
test2  1.02  0.900000  4.1  3.813084  6.20
test3  1.07  0.900000  0.9  4.000000  6.10
test4  4.00  1.100000  1.1  4.000000  6.05
</code>```

How can I return the desired output??

答:
I think simpliest is use combine_first if no NaN values:

```<code>df = df_filtrado.combine_first(df1)
</code>```

If possible some NaNs:

```<code>mask = ((df2 < 0.65) | (df2 > 1.35)).any()
df = df1.loc[:, ~mask]
print (df)
          C
test1  6.00
test2  6.20
test3  6.10
test4  6.05

df = pd.concat([df_filtrado, df], axis=1)
print (df)
              B          A     C
test1  0.878049   3.962617  6.00
test2  0.900000   3.813084  6.20
test3  0.197561   4.000000  6.10
test4  1.100000  14.953271  6.05
</code>```

Body:
I have the following df:

df1:
            A    B     C
test1     1.06  4.0  6.00
test2     1.02  4.1  6.20
test3     1.07  0.9  6.10
test4     4.00  1.1  6.05

then I divide each row by the previous obtaining this:

df2:
             A         B         C
test1       NaN       NaN       NaN
test2  0.962264  1.025000  1.033333
test3  1.049020  0.219512  0.983871
test4  3.738318  1.222222  0.991803

I am looking that for each value higher than 1.35 (in df2) or less than 0.65 multiply the previous rows of df1 by that value higher than 1.35 or less than 0.65.

The desired output would look something like this:

             A         B         C
test1      3.96       0.87     6.00
test2      3.81       0.90     6.20
test3      4.00       0.90     6.10
test4      4.00       1.10     6.05

The code I've made is this:

df_filtrado=pd.DataFrame()
for i in range(len(df2)):
    for j in range(len(list(df2.columns))):
        if df2.iloc[i,j]>1.35:
            values_higher=pd.concat([df1.iloc[0:i+1,[j]]*df2.iloc[i,j],df1.iloc[i+1:,[j]]])
            if df_filtrado.empty:
                df_filtrado= values_higher
            else:
                df_filtrado=pd.concat([df_filtrado,values_higher],axis=1, join_axes=[df_filtrado.index])
        elif df2.iloc[i,j]<0.65:
            values_lower=pd.concat([df1.iloc[0:i+1,[j]]*df2.iloc[i,j],df1.iloc[i+1:,[j]]])
            if df_filtrado.empty:
                df_filtrado= values_lower
            else:
                df_filtrado=pd.concat([df_filtrado,values_lower],axis=1, join_axes=[df_filtrado.index])

print df_filtrado

The current output up to here does okay and returns the following:

          B         A
test1  0.878049  3.962617
test2  0.900000  3.813084
test3  0.900000  4.000000
test4  1.100000  4.000000

What I am not capable of doing is to add the column that does not has any values higher than 1.35 or lower than 0.65 , like column C of df2 .

This is what I have tried (adding it to the previous code):

    normal=pd.DataFrame(df.iloc[:,i])
    if df2.iloc[:,i].all()>0.65 and df2.iloc[:,i].all()<1.35:

        if df_filtrado.empty:
            df_filtrado= normal
        else:
            df_filtrado=pd.concat([df_filtrado,normal],axis=1, join_axes=[df_filtrado.index])

print df_filtrado

However the output returned is :

         A         B    B         A     C
test1  1.06  0.878049  4.0  3.962617  6.00
test2  1.02  0.900000  4.1  3.813084  6.20
test3  1.07  0.900000  0.9  4.000000  6.10
test4  4.00  1.100000  1.1  4.000000  6.05

How can I return the desired output??

Body:
I think simpliest is use combine_first if no NaN values:

df = df_filtrado.combine_first(df1)

If possible some NaNs:

mask = ((df2 < 0.65) | (df2 > 1.35)).any()
df = df1.loc[:, ~mask]
print (df)
          C
test1  6.00
test2  6.20
test3  6.10
test4  6.05

df = pd.concat([df_filtrado, df], axis=1)
print (df)
              B          A     C
test1  0.878049   3.962617  6.00
test2  0.900000   3.813084  6.20
test3  0.197561   4.000000  6.10
test4  1.100000  14.953271  6.05


问:
how to push sub array object into an a array in javascript
hi all i am using javascript i am trying to push object values into one array here i attached my code

```<code>var data = [{
            BuildingID: "56", FloorId: "65", volume: [{

                one: 12,
                two: 15,
                three: 12
            }]
        }]

var MainInfo=[];
            for (i = 0; i < data.length; i++) {

                var obj = {}
                obj.BuildingID = data[i].BuildingID;
                obj.FloorId = data[i].FloorId;
                obj.volume = data[i].volume[0];
                MainInfo.push(obj);

            }
</code>```

it's working but not fully applicable here i mentioned the excepted output what should i need

Current output

Expected output

Note:in data volume is dynamic help how to do this

答:
loop volume and get keys

var data = [{
            BuildingID: "56", FloorId: "65", volume: [{

                one: 12,
                two: 15,
                three: 12
            }]
        }];

var MainInfo=[];
  for (var i = 0; i < data.length; i++) {

      var obj = {};
      obj.BuildingID = data[i].BuildingID;
      obj.FloorId = data[i].FloorId;

      for(var j in data[i].volume[0]){

        obj[j]= data[i].volume[0][j];
      }
      MainInfo.push(obj);

  }

            console.log(MainInfo);```

Body:
hi all i am using javascript i am trying to push object values into one array here i attached my code

var data = [{
            BuildingID: "56", FloorId: "65", volume: [{

                one: 12,
                two: 15,
                three: 12
            }]
        }]

var MainInfo=[];
            for (i = 0; i < data.length; i++) {

                var obj = {}
                obj.BuildingID = data[i].BuildingID;
                obj.FloorId = data[i].FloorId;
                obj.volume = data[i].volume[0];
                MainInfo.push(obj);

            }

it's working but not fully applicable here i mentioned the excepted output what should i need

Current output

Expected output

Note:in data volume is dynamic help how to do this


问:
How to save the objects uid when I push the data in firebase database list, using javascript
I want to save the uid when I push new data in Firebase database. This is possible not for auth users but for data objects.

For example, I want this object schema:

```<code>"-Kdsfdsg555555fdsgfsdgfs" : {  <------- I want this id
  Id : "Kdsfdsg555555fdsgfsdgfs",   <--- How to put that inside
  name : "A",
  time_updated : "6/6/2017"
}
</code>```

Is any way how to get this id and pushed inside the object?

My code is as follows:

```<code>categories: FirebaseListObservable<any[]>;

this.categories = this.db.list('/categories') as FirebaseListObservable<Category[]>;

addCategory(category: any) {
    return this.categories.push(category).then( snap => {
      this.openSnackBar('New category has been added', 'ok');

    }).catch(error => {
      this.openSnackBar(error.message, 'ok');
    });
  }
</code>```

答:
There are two ways to use Firebase's push() method:

By passing in an argument, it will generate a new location and store the argument there.

By passing in no arguments, it will just generate a new location.

You can use the second way of using push() to just get the new location or its key:

```<code>addCategory(category: any) {
  var newRef = this.categories.push();
  category.Id = newRef.key;
  newRef.set(category).then( snap => {
    this.openSnackBar('New category has been added', 'ok');
  }).catch(error => {
    this.openSnackBar(error.message, 'ok');
  });
}
</code>```

But note that it's typically an anti-pattern to store the key of an item inside that item itself too.

Body:
I want to save the uid when I push new data in Firebase database. This is possible not for auth users but for data objects.

For example, I want this object schema:

"-Kdsfdsg555555fdsgfsdgfs" : {  <------- I want this id
  Id : "Kdsfdsg555555fdsgfsdgfs",   <--- How to put that inside
  name : "A",
  time_updated : "6/6/2017"
}

Is any way how to get this id and pushed inside the object?

My code is as follows:

categories: FirebaseListObservable<any[]>;

this.categories = this.db.list('/categories') as FirebaseListObservable<Category[]>;

addCategory(category: any) {
    return this.categories.push(category).then( snap => {
      this.openSnackBar('New category has been added', 'ok');

    }).catch(error => {
      this.openSnackBar(error.message, 'ok');
    });
  }

Body:
There are two ways to use Firebase's push() method:

By passing in an argument, it will generate a new location and store the argument there.

By passing in no arguments, it will just generate a new location.

You can use the second way of using push() to just get the new location or its key:

addCategory(category: any) {
  var newRef = this.categories.push();
  category.Id = newRef.key;
  newRef.set(category).then( snap => {
    this.openSnackBar('New category has been added', 'ok');
  }).catch(error => {
    this.openSnackBar(error.message, 'ok');
  });
}

But note that it's typically an anti-pattern to store the key of an item inside that item itself too.


问:
Ui-grid: Opening a modal in filterHeaderTemplate
I would like to have a filter that would be a very basic kind of a modal window opened on a click event.
However, I am unable to display that window on top of a grid, when it is located in filterHeaderTemplate.

I created a very simple Plunker to reproduce that issue - the div is created correctly but it's hidden below the ui-grid and it happens for any z-index.

http://plnkr.co/edit/15oUIui2kWfPgE5CQXwk?p=preview

The templates is as simple as that:

```<code><button ng-click="showModal = !showModal">Open \'Modal\'</button>
<div class="myModalClass" ng-if="showModal">My \'Modal\' Content</div>
</code>```

and styles for the modal:

```<code>width: 200px;
height: 200px;
background-color: white;
border: 3px solid black;
position: absolute;
z-index: 999999999;
</code>```

Any ideas would be really appreciated!

答:
Solved :)
The problem was connected with top-panel and header-viewport overflow that is set to hidden by default.

The possible solution is to set it to visible:

```<code>.ui-grid-top-panel,
.ui-grid-header-viewport {
   overflow: visible !important;
}
</code>```

Body:
I would like to have a filter that would be a very basic kind of a modal window opened on a click event.
However, I am unable to display that window on top of a grid, when it is located in filterHeaderTemplate.

I created a very simple Plunker to reproduce that issue - the div is created correctly but it's hidden below the ui-grid and it happens for any z-index.

http://plnkr.co/edit/15oUIui2kWfPgE5CQXwk?p=preview

The templates is as simple as that:

<button ng-click="showModal = !showModal">Open \'Modal\'</button>

My \'Modal\' Content

and styles for the modal:

width: 200px;
height: 200px;
background-color: white;
border: 3px solid black;
position: absolute;
z-index: 999999999;

Any ideas would be really appreciated!

Body:
Solved :)
The problem was connected with top-panel and header-viewport overflow that is set to hidden by default.

The possible solution is to set it to visible:

.ui-grid-top-panel,
.ui-grid-header-viewport {
   overflow: visible !important;
}


问:
Weird behavior on UILabel with \n on StoryBoard
I want to add a line feed on an UILabel. On storyboard using \ndoes not work at all.
Here is an example.

Adding Labels

On StoryBoard I've created 2 UILabel and set their content in dedicated field:

Label 1\nhello with \n created by ALT+RETURN

Label 2\nhello with explicit \n

Then I added a third label and configure it on controller, not on Story Board:

label3.numberOfLines = 0
label3.text = "Label3\nhello"

Context

This is a brand new project, on Xcode 8. Language is Swift 3.1 and AutoLayout is off. So there must not have any interferences from any external libraries, nor AutoLayout.

Result

Here is the rendering.

Conclusion

UILabel behavior is not the same if used on StoryBoard or code source and this is really disturbing. Of course while you faced and solved this problem everything seems to be cristal clear, as the answer is known.

This problem is easily solved by using a UITextView instead of UILabel. So as for now and until I rather prefer using UITextView for displaying simple text on multilines despite the fact UILabel must work for this purpose.

答:
In UILabels you simply can't use

\n

You have to use

Alt + Enter

to move to the next line.


问:
Intent with multiple startactivity paramaters
I want a value to be passed from the first to the last activity when a button is clicked.

At the same time I want this button to bring me to the second activity. Somehow this doesn't work.

```<code>private void imagebutton1 () {
          ImageButton btn = (ImageButton) findViewById(R.id.imageButton4);
            btn.setOnClickListener(new View.OnClickListener() {
              @Override
              public void onClick(View v) {
                  //startActivity (new Intent(Akt1.this,Akt2.class));

                  String data1 = "data1";

                  Intent intent = new Intent (Akt1.this,Akt2.class);
                  Intent passdata_intent = new Intent(Akt1.this, Akt6.class);
                  passdata_intent.putExtra("data1",data1);

                 startActivity(passdata_intent);

              }
          });
</code>```

答:
Try the following :

```<code>            @Override
            public void onClick(View v) {
                //startActivity (new Intent(Akt1.this,Akt2.class));

                String data1 = "data1";

                getSharedPreferences("YOURKEY", MODE_PRIVATE).edit().putString("someKey", data1).apply();

                startActivity(new Intent (Akt1.this, Akt2.class));
            }
</code>```

Then in AKT6 :

```<code>String data1 = getSharedPreferences("YOURKEY", MODE_PRIVATE).prefs.getString("someKey");
</code>```

Body:
I want a value to be passed from the first to the last activity when a button is clicked.

At the same time I want this button to bring me to the second activity. Somehow this doesn't work.

private void imagebutton1 () {
          ImageButton btn = (ImageButton) findViewById(R.id.imageButton4);
            btn.setOnClickListener(new View.OnClickListener() {
              @Override
              public void onClick(View v) {
                  //startActivity (new Intent(Akt1.this,Akt2.class));

                  String data1 = "data1";

                  Intent intent = new Intent (Akt1.this,Akt2.class);
                  Intent passdata_intent = new Intent(Akt1.this, Akt6.class);
                  passdata_intent.putExtra("data1",data1);

                 startActivity(passdata_intent);

              }
          });

Body:
Try the following :

            @Override
            public void onClick(View v) {
                //startActivity (new Intent(Akt1.this,Akt2.class));

                String data1 = "data1";

                getSharedPreferences("YOURKEY", MODE_PRIVATE).edit().putString("someKey", data1).apply();

                startActivity(new Intent (Akt1.this, Akt2.class));
            }

Then in AKT6 :

String data1 = getSharedPreferences("YOURKEY", MODE_PRIVATE).prefs.getString("someKey");


问:
Should I adapt loss weights for misclassified samples during epochs?
I am using FCN (Fully Convolutional Networks) and trying to do image segmentation. When training, there are some areas which are mislabeled, however further training doesn't help much to make them go away. I believe this is because network learns about some features which might not be completely correct ones, but because there are enough correctly classified examples, it is stuck in local minimum and can't get out.

One solution I can think of is to train for an epoch, then validate the network on training images, and then adjust weights for mismatched parts to penalize mismatch more there in next epoch.

Intuitively, this makes sense to me - but I haven't found any writing on this. Is this a known technique? If yes, how is it called? If no, what am I missing (what are the downsides)?

答:
First, if I understand well you want your network to overfit your training set ? Because that's generally something you don't want to see happening, because this would mean that while training your network have found some "rules" that enables it to have great results on your training set, but it also means that it hasn't been able to generalize so when you'll give it new samples it will probably perform poorly. Moreover, you never talk about any testing set .. have you divided your dataset in training/testing set ?

Secondly, to give you something to look into, the idea of penalizing more where you don't perform well made me think of something that is called "AdaBoost" (It might be unrelated). This short video might help you understand what it is :
https://www.youtube.com/watch?v=sjtSo-YWCjc

Hope it helps


问:
Genetic algorithms: How to do crossover in "subset" problems?
I have a problem which I am trying to solve with genetic algorithms. The problem is selecting some subset (say 4) of 100 integers (these integers are just ids that represent something else). Order does not matter, the solution to the problem is a SET of integers not an ordered list. I have a good fitness function but am having trouble with the crossover function.

I want to be able to mate the following two chromosomes:

[1 2 3 4] and
[3 4 5 6] into something useful. Clearly I cannot use the typical crossover function because I could end up with duplicates in my children which would represent invalid solutions. What is the best crossover method in this case.

答:
Just ignore any element that occurs in both of the sets (i.e. in their intersection.), that is leave such elements unchanged in both sets.

The rest of the elements form two disjoint sets, to which you can apply pretty much any random transformation (e.g. swapping some pairs randomly) without getting duplicates.

This can be thought of as ordering and aligning both sets so that matching elements face each other and applying one of the standard crossover algorithms.

ContentLicense: CC BY-SA 2.5


问:
why it didn't go through the thread?
I was checking if the sign Up button is clicked it do something in another thread but it didn't go to the end of thread ?

```<code>    if(!(email.isEmpty() ||username.isEmpty() || password.isEmpty())){
     Main.users.add(new User(username, password, email));
                        new Thread(new SocketSender(Main.socket, Main.users)).start();
   Thread.sleep(1000);
   System.out.println("here");
   new Thread(new ServerReciver(Main.socket)).start();
   Thread.sleep(2000);
   System.out.println("here");
   Main.pstage.setScene(new Scene(FXMLLoader.load(getClass().getResource("/sample/logIn.fxml")),700,700))}
</code>```

Socket Sender

```<code>public class SocketSender  implements  Runnable{
    Socket socket;
    Object object;

    public SocketSender(Socket socket, Object object) {
        this.socket = socket;
        this.object = object;
    }

@Override
public void run() {
    try {
        ObjectOutputStream write = new ObjectOutputStream(socket.getOutputStream());
        write.writeObject(object);
        write.flush();
    } catch (IOException e) {
        e.printStackTrace();
    }
}}
</code>```

Server Reciver

```<code>public class ServerReciver implements  Runnable {
    Socket socket;

    public ServerReciver(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        System.out.println("log1");
        try {
            System.out.println("log2");
            ObjectInputStream read = new ObjectInputStream(socket.getInputStream());
            System.out.println("log3");
            Object o = read.readObject();
            System.out.println("ma");
            if(o instanceof User){
                System.out.println(log4);
                Server.getUsers().add((User) o);
            }
            else if(o instanceof Artist){
                Server.getArtists().add((Artist) o);
            }
            else if(o instanceof PlayList){
                Server.getPlayLists().add((PlayList) o);
            }
            else if(o instanceof Song){
                Server.getSongs().add((Song) o);
            }
            else if(o instanceof Album){
                Server.getAlbums().add((Album) o);
            }
            System.out.println(log6);
            Server.write();
            System.out.println(log7);
            Thread.sleep(100);
            System.out.println(Server.getUsers().get(0));
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
</code>```

in the Server receiver it prints the 2 first log but it didn't print all the logs!?

答:
Your problem is simply: you can't use the same socket object to send and read data at the same time.

What you are trying is like: using your own mobile phone to call your own number and then talk to you (in a way that works).

In other words: instead of reusing some Main.socket you simply have to create two distinct sockets in the first place.

But of course, there is zero point in doing things in this order. Don't build a JavaFX application and then try to add in client/server connectivity to a remote system.

Start by learning how to do that client/server thing, for example by reading the corresponding Oracle tutorial. And then, when you have written small command line tools that nicely communicate via sockets; even to a remote system; then take that knowledge forward and build it into your JavaFX application. Instead of trying to learn juggling while learning to use the unicycle.

Title: why it didn't go through the thread?

Body:
I was checking if the sign Up button is clicked it do something in another thread but it didn't go to the end of thread ?

    if(!(email.isEmpty() ||username.isEmpty() || password.isEmpty())){
     Main.users.add(new User(username, password, email));
                        new Thread(new SocketSender(Main.socket, Main.users)).start();
   Thread.sleep(1000);
   System.out.println("here");
   new Thread(new ServerReciver(Main.socket)).start();
   Thread.sleep(2000);
   System.out.println("here");
   Main.pstage.setScene(new Scene(FXMLLoader.load(getClass().getResource("/sample/logIn.fxml")),700,700))}

Socket Sender

public class SocketSender  implements  Runnable{
    Socket socket;
    Object object;

    public SocketSender(Socket socket, Object object) {
        this.socket = socket;
        this.object = object;
    }

@Override
public void run() {
    try {
        ObjectOutputStream write = new ObjectOutputStream(socket.getOutputStream());
        write.writeObject(object);
        write.flush();
    } catch (IOException e) {
        e.printStackTrace();
    }
}}

Server Reciver

public class ServerReciver implements  Runnable {
    Socket socket;

    public ServerReciver(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        System.out.println("log1");
        try {
            System.out.println("log2");
            ObjectInputStream read = new ObjectInputStream(socket.getInputStream());
            System.out.println("log3");
            Object o = read.readObject();
            System.out.println("ma");
            if(o instanceof User){
                System.out.println(log4);
                Server.getUsers().add((User) o);
            }
            else if(o instanceof Artist){
                Server.getArtists().add((Artist) o);
            }
            else if(o instanceof PlayList){
                Server.getPlayLists().add((PlayList) o);
            }
            else if(o instanceof Song){
                Server.getSongs().add((Song) o);
            }
            else if(o instanceof Album){
                Server.getAlbums().add((Album) o);
            }
            System.out.println(log6);
            Server.write();
            System.out.println(log7);
            Thread.sleep(100);
            System.out.println(Server.getUsers().get(0));
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

in the Server receiver it prints the 2 first log but it didn't print all the logs!?


问:
Python 3 - Get n greatest values in dict
I have a dict, with strings as keys and lists as values and want to find the n keys with the longest lists (length).

How could I approach this problem?

答:
If you have a dictionary as you described

```<code>>>> my_dict = {"first": [1, 2, 3], "second": [2, 3], "third": [1], "fourth": [1, 2, 3, 4]}
</code>```

You can fetch the n longest values in the dictionary with something like:

```<code>>>> sorted(my_dict.items(), key=lambda x: len(x[1]), reverse=True)[:2]

[('fourth', [1, 2, 3, 4]), ('first', [1, 2, 3])]
</code>```

If you wanted the key names

```<code>>>> from operator import itemgetter
>>> tuple(map(itemgetter(0), sorted(my_dict.items(), key=lambda x: len(x[1]), reverse=True)[:2]))
('fourth', 'first')
</code>```

If you care about persistence, use an OrderedDict

```<code>>>> from collections import OrderedDict

>>> OrderedDict(sorted(my_dict.items(), key=lambda x: len(x[1])))
OrderedDict([('third', [1]),
             ('second', [2, 3]),
             ('first', [1, 2, 3]),
             ('fourth', [1, 2, 3, 4])])
</code>```

To sort the key by order:

```<code>>>> tuple(OrderedDict(sorted(my_dict.items(), key=lambda x: len(x[1]))).keys())[::-1]
('fourth', 'first', 'second', 'third')
</code>```

Body:
If you have a dictionary as you described

>>> my_dict = {"first": [1, 2, 3], "second": [2, 3], "third": [1], "fourth": [1, 2, 3, 4]}

You can fetch the n longest values in the dictionary with something like:

>>> sorted(my_dict.items(), key=lambda x: len(x[1]), reverse=True)[:2]

[('fourth', [1, 2, 3, 4]), ('first', [1, 2, 3])]

If you wanted the key names

>>> from operator import itemgetter
>>> tuple(map(itemgetter(0), sorted(my_dict.items(), key=lambda x: len(x[1]), reverse=True)[:2]))
('fourth', 'first')

If you care about persistence, use an OrderedDict

>>> from collections import OrderedDict

>>> OrderedDict(sorted(my_dict.items(), key=lambda x: len(x[1])))
OrderedDict([('third', [1]),
             ('second', [2, 3]),
             ('first', [1, 2, 3]),
             ('fourth', [1, 2, 3, 4])])

To sort the key by order:

>>> tuple(OrderedDict(sorted(my_dict.items(), key=lambda x: len(x[1]))).keys())[::-1]
('fourth', 'first', 'second', 'third')


答:
```<code>;With cte(ID,  ColumnA)
AS
(
SELECT 'A','Honda'  Union all
SELECT 'A',NULL     Union all
SELECT 'B','Yamaha' Union all
SELECT 'B',NULL     Union all
SELECT 'C',NULL     Union all
SELECT 'C','Merc'    Union all
SELECT 'D' ,   NULL   Union all
SELECT 'E',    NULL
)
SELECT ID, ColumnA From
(
SELECT *,ROW_NUMBER()Over(Partition by ID order by ColumnA DESc)AS Seq from cte
)Dt
WHERE dt.Seq =1
</code>```

Output:

```<code>ID  ColumnA
A    Honda
B    Yamaha
C    Merc
D    NULL
E    NULL
</code>```

Title: Delete or Select Only row with same id but have values for certain fields

Body:
;With cte(ID,  ColumnA)
AS
(
SELECT 'A','Honda'  Union all
SELECT 'A',NULL     Union all
SELECT 'B','Yamaha' Union all
SELECT 'B',NULL     Union all
SELECT 'C',NULL     Union all
SELECT 'C','Merc'    Union all
SELECT 'D' ,   NULL   Union all
SELECT 'E',    NULL
)
SELECT ID, ColumnA From
(
SELECT *,ROW_NUMBER()Over(Partition by ID order by ColumnA DESc)AS Seq from cte
)Dt
WHERE dt.Seq =1

Output:

ID  ColumnA
A    Honda
B    Yamaha
C    Merc
D    NULL
E    NULL


问:
Does  have significance to search engines?
The corporate guidlines at my company stipulate that our product names are written in a strange and "wonderful" way [oh how we all love Marketing departments!].

A product name such as "iPhone" is written with the "i" as bold and italic. E.g.

iPhone

I don't want search engines to segment the context of the bold/italic text - for example the above should just be read by a search engine as "iPhone", and not !! I !! Phone.

Just want to check if anyone knows for sure that

```<code><span class="branding">i</span>Phone
</code>```

Would not apply any additional significance to the "i"?

Many thanks

答:
Type i phone into an unnamed popular search engine and you'll get results for iphone, i-phone, etc. Search engines are pretty clever nowadays. I would say no, it won't have any effect.

Plus, span and other inline tags aren't supposed to represent word boundaries, and search engines shouldn't be treating them as such. If I learned that they do, I'd be very surprised.

Title: Does <span> have significance to search engines?

Body:
The corporate guidlines at my company stipulate that our product names are written in a strange and "wonderful" way [oh how we all love Marketing departments!].

A product name such as "iPhone" is written with the "i" as bold and italic. E.g.

iPhone

I don't want search engines to segment the context of the bold/italic text - for example the above should just be read by a search engine as "iPhone", and not !! I !! Phone.

Just want to check if anyone knows for sure that

iPhone

Would not apply any additional significance to the "i"?

Many thanks


问:
c++ - NRVO and move
I have read a few posts about move functions (http://www.cprogramming.com/c++11/rvalue-references-and-move-semantics-in-c++11.html for example), and I wanted to observe move operators in action. So I tried the following code:

```<code>#include <vector>
#include <cassert>
#include <functional>
#include <algorithm>
#include <iostream>
using namespace std;

vector<double> operator+(const vector<double>& a, const vector<double>& b){
  assert(a.size()==b.size());
  vector<double> result(a.size(),0);
    transform (a.begin(), a.end(), b.begin(), result.begin(), std::plus<double>());
  cout<<&result<<endl;
  return result;
}

int main(int argc, char const *argv[]) {
  vector<double> a,b;
  for (int i=0;i<10;i++){
    a.push_back(i);
    b.push_back(1);
  }
  std::vector<double> c=a+b;
  cout<<&c<<endl;
  return 0;
}
</code>```

I was expecting to obtain the same address for the local variable result and c since move operators are implemented for vector. And I obtained exactly that, but with and without the flag -std=c++11. That is when I learned about NRVO (c++11 Return value optimization or move?), so I disabled it with the flag -fno-elide-constructors and now the address is different, even with the flag -std=c++11. Is there an issue with my code or did I understand something wrong about move operators ?

From what I understood, returning by value should be enough for the move operator to kick in (C++11 rvalues and move semantics confusion (return statement)).

PS: I tried with GCC 6.3.0_1 and Apple LLVM version 8.1.0 .

EDIT

As pointed out, I should have checked result.data() instead of &result (see below). But in that case, I always found the same address, even without std=c++11 and with -fno-elide-constructors. See accepted answer and its comment section.

答: The move constructor constructs a new object by stealing the resources of the old one. It does not merge temporaries at all: if the construction isn't elided, you still have two objects.</p>

Title: c++ - NRVO and move

Body:
I have read a few posts about move functions (http://www.cprogramming.com/c++11/rvalue-references-and-move-semantics-in-c++11.html for example), and I wanted to observe move operators in action. So I tried the following code:

#include <vector>
#include <cassert>
#include <functional>
#include <algorithm>
#include <iostream>
using namespace std;

vector<double> operator+(const vector<double>& a, const vector<double>& b){
  assert(a.size()==b.size());
  vector<double> result(a.size(),0);
    transform (a.begin(), a.end(), b.begin(), result.begin(), std::plus<double>());
  cout<<&result<<endl;
  return result;
}

int main(int argc, char const *argv[]) {
  vector<double> a,b;
  for (int i=0;i<10;i++){
    a.push_back(i);
    b.push_back(1);
  }
  std::vector<double> c=a+b;
  cout<<&c<<endl;
  return 0;
}

I was expecting to obtain the same address for the local variable result and c since move operators are implemented for vector. And I obtained exactly that, but with and without the flag -std=c++11. That is when I learned about NRVO (c++11 Return value optimization or move?), so I disabled it with the flag -fno-elide-constructors and now the address is different, even with the flag -std=c++11. Is there an issue with my code or did I understand something wrong about move operators ?

From what I understood, returning by value should be enough for the move operator to kick in (C++11 rvalues and move semantics confusion (return statement)).

PS: I tried with GCC 6.3.0_1 and Apple LLVM version 8.1.0 .

EDIT

As pointed out, I should have checked result.data() instead of &result (see below). But in that case, I always found the same address, even without std=c++11 and with -fno-elide-constructors. See accepted answer and its comment section.


问:
Can't resolve all parameters for WinwheelService: (?, ?)
I have an Winwheel service like this

```<code>@Injectable()
export class WinwheelService {

  constructor(options, drawWheel) {}

}
</code>```

then i am initializing this service in my app component like this

```<code>export class AppComponent implements AfterViewInit {

  ngAfterViewInit() {
    this.initWheel();
  }

  initWheel() {

    this.wheel = new Winwheel({
      'numSegments': 8,   // Specify number of segments.
      'outerRadius': 212,  // Set radius to so wheel fits the background.
      'innerRadius': 150,  // Set inner radius to make wheel hollow.
      'pointerAngle': 90,
      'pointerGuide':        // Turn pointer guide on.
      {
        'display': true,
        'strokeStyle': 'red',
        'lineWidth': 3
      },
      'segments':       // Define segments including colour and text.
      [
        { 'fillStyle': '#eae56f', 'text': 'Prize 1' },
        { 'fillStyle': '#89f26e', 'text': 'Prize 2' },
        { 'fillStyle': '#7de6ef', 'text': 'Prize 3' },
        { 'fillStyle': '#e7706f', 'text': 'Prize 4' },
        { 'fillStyle': '#eae56f', 'text': 'Prize 5' },
        { 'fillStyle': '#89f26e', 'text': 'Prize 6' },
        { 'fillStyle': '#7de6ef', 'text': 'Prize 7' },
        { 'fillStyle': '#e7706f', 'text': 'Prize 8' }
      ],
      'animation':           // Define spin to stop animation.
      {
        'type': 'spinToStop',
        'duration': 5,
        'spins': 8,
        'callbackFinished': this.alertPrize()
      }
    }, true);
  }
}
</code>```

But initializing my service like this gives me following error

```<code>Can't resolve all parameters for WinwheelService: (?, ?)
</code>```

What is the other way to initialize a class with parameters.

答:
Since i am initializing an object of my service class, rather than injecting it in the component, so there is no need to register it inside the providers it the app module.

There is also other way of doing this, click here to know more about this

Body:
I have an Winwheel service like this

@Injectable()
export class WinwheelService {

  constructor(options, drawWheel) {}

}

then i am initializing this service in my app component like this

export class AppComponent implements AfterViewInit {

  ngAfterViewInit() {
    this.initWheel();
  }

  initWheel() {

    this.wheel = new Winwheel({
      'numSegments': 8,   // Specify number of segments.
      'outerRadius': 212,  // Set radius to so wheel fits the background.
      'innerRadius': 150,  // Set inner radius to make wheel hollow.
      'pointerAngle': 90,
      'pointerGuide':        // Turn pointer guide on.
      {
        'display': true,
        'strokeStyle': 'red',
        'lineWidth': 3
      },
      'segments':       // Define segments including colour and text.
      [
        { 'fillStyle': '#eae56f', 'text': 'Prize 1' },
        { 'fillStyle': '#89f26e', 'text': 'Prize 2' },
        { 'fillStyle': '#7de6ef', 'text': 'Prize 3' },
        { 'fillStyle': '#e7706f', 'text': 'Prize 4' },
        { 'fillStyle': '#eae56f', 'text': 'Prize 5' },
        { 'fillStyle': '#89f26e', 'text': 'Prize 6' },
        { 'fillStyle': '#7de6ef', 'text': 'Prize 7' },
        { 'fillStyle': '#e7706f', 'text': 'Prize 8' }
      ],
      'animation':           // Define spin to stop animation.
      {
        'type': 'spinToStop',
        'duration': 5,
        'spins': 8,
        'callbackFinished': this.alertPrize()
      }
    }, true);
  }
}

But initializing my service like this gives me following error

Can't resolve all parameters for WinwheelService: (?, ?)

What is the other way to initialize a class with parameters.


问:
Why does StackTrace.GetFrames not return the reference directly?
Here is the source code of StackTrace.

```<code>public virtual StackFrame GetFrame(int index)
{
    if ((frames != null) && (index < m_iNumOfFrames) && (index >= 0))
        return frames[index+m_iMethodsToSkip];

    return null;
}

public virtual StackFrame [] GetFrames()
{
    if (frames == null || m_iNumOfFrames <= 0)
        return null;

    // We have to return a subset of the array. Unfortunately this
    // means we have to allocate a new array and copy over.
    StackFrame [] array = new StackFrame[m_iNumOfFrames];
    Array.Copy(frames, m_iMethodsToSkip, array, 0, m_iNumOfFrames);
    return array;
}
</code>```

Why doesn't GetFrames just return frames? If it does not want caller to modify the frames, why does GetFrame return the reference instead of copy?

By the way,  StackFrame has no method or property to modify itself.

答:
Why doesn't GetFrames just return frames?

Well, the frames variable is the internal storage. So you, as a receiver of the return value could change the internal storage variable by just setting the indexes of the array. To prevent that, it copies the immutable objects to a new array (with a better size than the stack size which the array has).

Also, as the comment states: We have to return a subset of the array. So not the entire array is returned. An example can be found here: all methods from DiagnosticTrace are filtered out.

Why does GetFrame return the reference instead of copy?

Because a frame is immutable, you can't change it. There is no need to copy it since it is read-only.

Body:
Here is the source code of StackTrace.

public virtual StackFrame GetFrame(int index)
{
    if ((frames != null) && (index < m_iNumOfFrames) && (index >= 0))
        return frames[index+m_iMethodsToSkip];

    return null;
}

public virtual StackFrame [] GetFrames()
{
    if (frames == null || m_iNumOfFrames <= 0)
        return null;

    // We have to return a subset of the array. Unfortunately this
    // means we have to allocate a new array and copy over.
    StackFrame [] array = new StackFrame[m_iNumOfFrames];
    Array.Copy(frames, m_iMethodsToSkip, array, 0, m_iNumOfFrames);
    return array;
}

Why doesn't GetFrames just return frames? If it does not want caller to modify the frames, why does GetFrame return the reference instead of copy?

By the way,  StackFrame has no method or property to modify itself.


问:
PHPUnit - Assert two XMLs are not equal
I have just started introduction some PHPUnit tests to my application and want to compare two XML files that get generated. The positive test is not an issue, since there is a dedicated method to do so:

```<code>$this->assertEqualXMLStructure(
  $expectedResultXml->firstChild,
  $generatedResultXml->firstChild
);
</code>```

Now, I have been looking to write a negative test where I purposely create an invalid XML so they no longer match. I have been googling for some time now, but I can't seem to find a good solution (something like a method called assertNotEqualXMLStructure();). I am really new to PHP so this might be a noob question; sorry if that is the case here.

How can I test that two XML files are not equal based on their structure?

答:
There is no method like assertNotEqualXMLStructure() because it is not needed. Since your two XML documents have a different structure, their text representation cannot be the same.

You can use DOMNode::C14N() to produce the canonical representation of the two nodes as text and assert the text representations are not equal (using $this->assertNotEquals()):

```<code>$this->assertNotEquals(
    $expectedResultXml->firstChild->C14N(),
    $generatedResultXml->firstChild->C14N()
);
</code>```

Title: PHPUnit - Assert two XMLs are not equal

Body:
I have just started introduction some PHPUnit tests to my application and want to compare two XML files that get generated. The positive test is not an issue, since there is a dedicated method to do so:

$this->assertEqualXMLStructure(
  $expectedResultXml->firstChild,
  $generatedResultXml->firstChild
);

Now, I have been looking to write a negative test where I purposely create an invalid XML so they no longer match. I have been googling for some time now, but I can't seem to find a good solution (something like a method called assertNotEqualXMLStructure();). I am really new to PHP so this might be a noob question; sorry if that is the case here.

How can I test that two XML files are not equal based on their structure?

Body:
There is no method like assertNotEqualXMLStructure() because it is not needed. Since your two XML documents have a different structure, their text representation cannot be the same.

You can use DOMNode::C14N() to produce the canonical representation of the two nodes as text and assert the text representations are not equal (using $this->assertNotEquals()):

$this->assertNotEquals(
    $expectedResultXml->firstChild->C14N(),
    $generatedResultXml->firstChild->C14N()
);


Title: Doing operations with only Nth element of a list

Body: I want to multiply only every second number on a list(0-100) but I just can't get it to work.

Body:
[x*10 for x in range(100) if x%2==0] # take vale to be multiply instead of 10, use x if you want to multiply with number it self

below code will only multiply even elements and keep other as it is.

def iterate_lis(get_list):
    ls = []
    for x in get_list:
        if x%2==0:
            ls.append(x*2)
        else:
            ls.append(x)
    print(ls)
    return ls

iterate_count = 5  # list will be iterate 5 times

for i in range(iterate_count):
    if i ==0:
        get_lis = iterate_lis(range(100))
    else:
        get_lis = iterate_lis(get_lis)

result for iterate_count=5 will be as follow:

>>>
[0, 1, 4, 3, 8, 5, 12, 7, 16, 9, 20, 11, 24, 13, 28, 15, 32, 17, 36, 19, 40, 21, 44, 23, 48, 25, 52, 27, 56, 29, 60, 31, 64, 33, 68, 35, 72, 37, 76, 39, 80, 41, 84, 43, 88, 45, 92, 47, 96, 49, 100, 51, 104, 53, 108, 55, 112, 57, 116, 59, 120, 61, 124, 63, 128, 65, 132, 67, 136, 69, 140, 71, 144, 73, 148, 75, 152, 77, 156, 79, 160, 81, 164, 83, 168, 85, 172, 87, 176, 89, 180, 91, 184, 93, 188, 95, 192, 97, 196, 99]
[0, 1, 8, 3, 16, 5, 24, 7, 32, 9, 40, 11, 48, 13, 56, 15, 64, 17, 72, 19, 80, 21, 88, 23, 96, 25, 104, 27, 112, 29, 120, 31, 128, 33, 136, 35, 144, 37, 152, 39, 160, 41, 168, 43, 176, 45, 184, 47, 192, 49, 200, 51, 208, 53, 216, 55, 224, 57, 232, 59, 240, 61, 248, 63, 256, 65, 264, 67, 272, 69, 280, 71, 288, 73, 296, 75, 304, 77, 312, 79, 320, 81, 328, 83, 336, 85, 344, 87, 352, 89, 360, 91, 368, 93, 376, 95, 384, 97, 392, 99]
[0, 1, 16, 3, 32, 5, 48, 7, 64, 9, 80, 11, 96, 13, 112, 15, 128, 17, 144, 19, 160, 21, 176, 23, 192, 25, 208, 27, 224, 29, 240, 31, 256, 33, 272, 35, 288, 37, 304, 39, 320, 41, 336, 43, 352, 45, 368, 47, 384, 49, 400, 51, 416, 53, 432, 55, 448, 57, 464, 59, 480, 61, 496, 63, 512, 65, 528, 67, 544, 69, 560, 71, 576, 73, 592, 75, 608, 77, 624, 79, 640, 81, 656, 83, 672, 85, 688, 87, 704, 89, 720, 91, 736, 93, 752, 95, 768, 97, 784, 99]
[0, 1, 32, 3, 64, 5, 96, 7, 128, 9, 160, 11, 192, 13, 224, 15, 256, 17, 288, 19, 320, 21, 352, 23, 384, 25, 416, 27, 448, 29, 480, 31, 512, 33, 544, 35, 576, 37, 608, 39, 640, 41, 672, 43, 704, 45, 736, 47, 768, 49, 800, 51, 832, 53, 864, 55, 896, 57, 928, 59, 960, 61, 992, 63, 1024, 65, 1056, 67, 1088, 69, 1120, 71, 1152, 73, 1184, 75, 1216, 77, 1248, 79, 1280, 81, 1312, 83, 1344, 85, 1376, 87, 1408, 89, 1440, 91, 1472, 93, 1504, 95, 1536, 97, 1568, 99]
[0, 1, 64, 3, 128, 5, 192, 7, 256, 9, 320, 11, 384, 13, 448, 15, 512, 17, 576, 19, 640, 21, 704, 23, 768, 25, 832, 27, 896, 29, 960, 31, 1024, 33, 1088, 35, 1152, 37, 1216, 39, 1280, 41, 1344, 43, 1408, 45, 1472, 47, 1536, 49, 1600, 51, 1664, 53, 1728, 55, 1792, 57, 1856, 59, 1920, 61, 1984, 63, 2048, 65, 2112, 67, 2176, 69, 2240, 71, 2304, 73, 2368, 75, 2432, 77, 2496, 79, 2560, 81, 2624, 83, 2688, 85, 2752, 87, 2816, 89, 2880, 91, 2944, 93, 3008, 95, 3072, 97, 3136, 99]


问:
How do you add a cell array to a plot title in MATLAB
I have created a loop in MATLAB to automate some FFT work. The loop selects a new .mat files each time through. I have extracted a cell array which references the test data being processed (for example Test 1), and I would like to use that information in the title of the figures I produce.

I have tried

```<code>title(fileInfo);
</code>```

Here, fileInfo contains Test 1.

What do I need to do to be able to get this information into the figure on each iteration of the loop?

答:
I am not sure, how you are calling your matfiles, but this is the good method to achieve the task:

```<code>matfiles = dir('*.mat') ;

for i = 1:length(matfiles)
    %% do waht you want
    figure
    title(matfiles(i).name)
end
</code>```

Straight away to your question. You can get title like below:

```<code>fileInfo = 'Test 1';
figure
%% plot
title(fileInfo)
</code>```

Or straight away:

```<code>  figure
  % plot
  title('Test 1')
</code>```

Body:
I have created a loop in MATLAB to automate some FFT work. The loop selects a new .mat files each time through. I have extracted a cell array which references the test data being processed (for example Test 1), and I would like to use that information in the title of the figures I produce.

I have tried

title(fileInfo);

Here, fileInfo contains Test 1.

What do I need to do to be able to get this information into the figure on each iteration of the loop?

Body:
I am not sure, how you are calling your matfiles, but this is the good method to achieve the task:

matfiles = dir('*.mat') ;

for i = 1:length(matfiles)
    %% do waht you want
    figure
    title(matfiles(i).name)
end

Straight away to your question. You can get title like below:

fileInfo = 'Test 1';
figure
%% plot
title(fileInfo)

Or straight away:

  figure
  % plot
  title('Test 1')


问:
SQL update all records except the last one with a value
I need to make a query where only the last line of each user that has a car gets a license plate number.

```<code>ID    UserId    LicensePlate    HasCar
1     1         ABC123          1
2     1         ABC123          1
3     2         NULL            0
4     3         UVW789          1
5     3         UVW789          1
</code>```

Should become:

```<code>ID    UserId    LicensePlate    HasCar
1     1         NULL            1
2     1         ABC123          1
3     2         NULL            0
4     3         NULL            1
5     3         UVW789          1
</code>```

So I basically need to find all users with a licenseplate and change all but the last one and make the LicensePlate NULL

答:
You can try this</p>

```<code>UPDATE l
SET l.LicensePlate = null
FROM Car l
INNER JOIN (SELECT UserId, Max(Id) AS max_id
            FROM Car
            GROUP BY UserId) m ON m.UserId = l.UserId
                                  AND m.max_id <> l.id
</code>```

Body:
I need to make a query where only the last line of each user that has a car gets a license plate number.

ID    UserId    LicensePlate    HasCar
1     1         ABC123          1
2     1         ABC123          1
3     2         NULL            0
4     3         UVW789          1
5     3         UVW789          1

Should become:

ID    UserId    LicensePlate    HasCar
1     1         NULL            1
2     1         ABC123          1
3     2         NULL            0
4     3         NULL            1
5     3         UVW789          1

So I basically need to find all users with a licenseplate and change all but the last one and make the LicensePlate NULL

Body:
You can try this

UPDATE l
SET l.LicensePlate = null
FROM Car l
INNER JOIN (SELECT UserId, Max(Id) AS max_id
            FROM Car
            GROUP BY UserId) m ON m.UserId = l.UserId
                                  AND m.max_id <> l.id


问:
Doing operations with only Nth element of a list
I want to multiply only every second number on a list(0-100) but I just can't get it to work.</p>

答:
```<code>import numpy as np
l = range(100)
np.product(l[0::2])
</code>```

This will give you every second element of your list and multiply all.

Body:
import numpy as np
l = range(100)
np.product(l[0::2])

This will give you every second element of your list and multiply all.


问:
How to pass the Result of my CustomDotNet Activity to my stored procedure
I've created a ADF for my project,which consist of a Custom Activity and stored procedureactivity.

The thing I'm blocked here is.

My custom activity does the obtain the most recent modified file - let's assume xx.txt is the file - from  in my Azure Blob Container.

My stored procedure has the single parameter FileName. I want to pass the file name to my stored procedure which can be obtained from the above custom activity.
(We can say simply as my stored procedure activity input depends on the Custom Activity output)

How can I do this in my ADF?

答:
You will need to do this with two separate activities (maybe in two separate pipelines, if you want greater control) and using some middle ground storage that both processes can access.

For example:

Input dataset, Blob.

Custom activity.

Output dataset, SQL DB.

Input dataset, SQLDB (same as 3).

Stored Proc activity.

Output dataset, SQLDB.

It is the staging area datasets used for point 3 and 4 that is most important here.

This is how ADF will want to handle it. Although I understand why you would want to pass the output for the custom activity straight to the stored procedure, without using an additional dataset.

Hope this helps.


问:
try block with empty finally block
When we have a try block without any code is finally block, the compiler compiles it fine. However, there is no purpose of try here - because we are neither catching a exception nor cleaning up code in finally block.

```<code>public int updateTable(InputVo sfVo){
    //SqlSession session = ConnFactory.getSqlSession();
    //InputMapper spMapper = session.getMapper(InputMapper .class);
    int updRecs=0;
    try {

        mapper.updateData(sfVo);

        updRecs=sfVo.getRecsUpdated();
        return updRecs;

    } finally {
        //session.close();
    }
}
</code>```

If thats the case, why does JAVA has not considered a compile time check on this ?

Wouldn't be better if compiler throws error at compile time itself - like "Cannot have a empty finally block"

答:
To add some context, finally is just keyword/label to identify a block statement linked to the try. It's like a goto that is called in the try.

Every block statement can be empty.

```<code>if(true){}
--
while(true){}
--
public void method(){}
</code>```

even this is valid

```<code>public void method(){
    {}
}
</code>```

So, we could say that the compiler don't care about the content of those, only the syntax in it.

Title: try block with empty finally block

Body:
When we have a try block without any code is finally block, the compiler compiles it fine. However, there is no purpose of try here - because we are neither catching a exception nor cleaning up code in finally block.

public int updateTable(InputVo sfVo){
    //SqlSession session = ConnFactory.getSqlSession();
    //InputMapper spMapper = session.getMapper(InputMapper .class);
    int updRecs=0;
    try {

        mapper.updateData(sfVo);

        updRecs=sfVo.getRecsUpdated();
        return updRecs;

    } finally {
        //session.close();
    }
}

If thats the case, why does JAVA has not considered a compile time check on this ?

Wouldn't be better if compiler throws error at compile time itself - like "Cannot have a empty finally block"

Body:
To add some context, finally is just keyword/label to identify a block statement linked to the try. It's like a goto that is called in the try.

Every block statement can be empty.

if(true){}
--
while(true){}
--
public void method(){}

even this is valid

public void method(){
    {}
}

So, we could say that the compiler don't care about the content of those, only the syntax in it.


问:
Having issues displaying images Xamarin Forms using only C#
I ask this question with reference to this website https://developer.xamarin.com/guides/xamarin-forms/user-interface/images/#Local_Images

I tried the xaml code on the website and it works, however after I created a new xamarin PCL project and tested the c# code. It failed to display images.

What I did:
Removed everything from the AboutPage.xaml till it looks like this:

```<code><?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="EmbbedImages.Views.AboutPage"
             xmlns:vm="clr-namespace:EmbbedImages.ViewModels;"
             Title="{Binding Title}">
  <ContentPage.BindingContext>
    <vm:AboutViewModel />
  </ContentPage.BindingContext>

</ContentPage>
</code>```

And then for the AboutPage.xaml.cs, I modified it such that it looks like the following:

```<code>using Xamarin.Forms;

namespace EmbbedImages.Views
{
    public partial class AboutPage : ContentPage
    {
        public AboutPage()
        {
            InitializeComponent();

            var beachImage = new Image { Aspect = Aspect.AspectFit };
            beachImage.Source = ImageSource.FromFile("butterfly.jfif");

        }
    }
}
</code>```

I have ensured that the butterfly.jfif image is added into my android drawable folder, however no images are being displayed. As I am new to xamarin and Android and c# any help would be greatly appreciated.

答:
The image probably won't display, because it's not part of the Page.
If you've added it to the Page and it still won't show it would have to be a problem in loading / opening the file / decoding it.

Either you add it in XAML or edit your code to the following:

```<code>using Xamarin.Forms;

namespace EmbbedImages.Views
{
    public partial class AboutPage : ContentPage
    {
        public AboutPage()
        {
            InitializeComponent();

            var beachImage = new Image { Aspect = Aspect.AspectFit };
            beachImage.Source = ImageSource.FromFile("butterfly.jfif");
            this.Content = beachImage;
        }
    }
}
</code>```

Adding it in XAML would look like that:

```<code><ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="EmbbedImages.Views.AboutPage"
             xmlns:vm="clr-namespace:EmbbedImages.ViewModels;"
             Title="{Binding Title}">
  <ContentPage.BindingContext>
    <vm:AboutViewModel />
  </ContentPage.BindingContext>

  <ContentPage.Content>
    <Image x:Name="beachImage" Aspect="AspectFit">
  </ContentPage.Content>

</ContentPage>
</code>```

And the code behind:

```<code>using Xamarin.Forms;

namespace EmbbedImages.Views
{
    public partial class AboutPage : ContentPage
    {
        public AboutPage()
        {
            InitializeComponent();

            beachImage.Source = ImageSource.FromFile("butterfly.jfif");
        }
    }
}
</code>```

Body:
I ask this question with reference to this website https://developer.xamarin.com/guides/xamarin-forms/user-interface/images/#Local_Images

I tried the xaml code on the website and it works, however after I created a new xamarin PCL project and tested the c# code. It failed to display images.

What I did:
Removed everything from the AboutPage.xaml till it looks like this:

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="EmbbedImages.Views.AboutPage"
             xmlns:vm="clr-namespace:EmbbedImages.ViewModels;"
             Title="{Binding Title}">
  <ContentPage.BindingContext>
    <vm:AboutViewModel />
  </ContentPage.BindingContext>

</ContentPage>

And then for the AboutPage.xaml.cs, I modified it such that it looks like the following:

using Xamarin.Forms;

namespace EmbbedImages.Views
{
    public partial class AboutPage : ContentPage
    {
        public AboutPage()
        {
            InitializeComponent();

            var beachImage = new Image { Aspect = Aspect.AspectFit };
            beachImage.Source = ImageSource.FromFile("butterfly.jfif");

        }
    }
}

I have ensured that the butterfly.jfif image is added into my android drawable folder, however no images are being displayed. As I am new to xamarin and Android and c# any help would be greatly appreciated.

Body:
The image probably won't display, because it's not part of the Page.
If you've added it to the Page and it still won't show it would have to be a problem in loading / opening the file / decoding it.

Either you add it in XAML or edit your code to the following:

using Xamarin.Forms;

namespace EmbbedImages.Views
{
    public partial class AboutPage : ContentPage
    {
        public AboutPage()
        {
            InitializeComponent();

            var beachImage = new Image { Aspect = Aspect.AspectFit };
            beachImage.Source = ImageSource.FromFile("butterfly.jfif");
            this.Content = beachImage;
        }
    }
}

Adding it in XAML would look like that:

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="EmbbedImages.Views.AboutPage"
             xmlns:vm="clr-namespace:EmbbedImages.ViewModels;"
             Title="{Binding Title}">
  <ContentPage.BindingContext>
    <vm:AboutViewModel />
  </ContentPage.BindingContext>

  <ContentPage.Content>
    <Image x:Name="beachImage" Aspect="AspectFit">
  </ContentPage.Content>

</ContentPage>

And the code behind:

using Xamarin.Forms;

namespace EmbbedImages.Views
{
    public partial class AboutPage : ContentPage
    {
        public AboutPage()
        {
            InitializeComponent();

            beachImage.Source = ImageSource.FromFile("butterfly.jfif");
        }
    }
}


问:
How secure my Executable jar file
I developed a desktop application in Java. I converted my code in the form of Executable jar (.jar) format. Here my problem is, this jar files easily extracted by winrar/winzip. My Java class files are visible to others and also i do De-compilation process using JAD my source code are visible to everyone. is any way to protect my source code from De-compileation process.</p>

答:
Put a password or licence check at start of application. With proper authentication, only user must be able to run the application further.

For password check, you should generate private-public key concepts. For licence, some installed software or attached hardware can be use to provide access.

Title: How secure my Executable jar file


问:
Maximum number of allowable file uploads has been exceeded
We're uploading about 500 images at a time

```<code>max_file_uploads = 600
memory_limit = 200M ( most images are 12-15KB )
post_max_size = 200M
</code>```

Why are we still getting that warning?

EDIT: All these variables are set in the php.ini file and confirmed by checking using phpinfo();

答:
```<code>add max_file_uploads=500 to php.ini
</code>```

Body:
We're uploading about 500 images at a time

max_file_uploads = 600
memory_limit = 200M ( most images are 12-15KB )
post_max_size = 200M

Why are we still getting that warning?

EDIT: All these variables are set in the php.ini file and confirmed by checking using phpinfo();

Body: add max_file_uploads=500 to php.ini


问:
Removing duplicates in lists
How can I check if a list has any duplicates and return a new list without duplicates?</p>

答:
You could also do this:

```<code>>>> t = [1, 2, 3, 3, 2, 4, 5, 6]
>>> s = [x for i, x in enumerate(t) if i == t.index(x)]
>>> s
[1, 2, 3, 4, 5, 6]
</code>```

The reason that above works is that index method returns only the first index of an element. Duplicate elements have higher indices. Refer to here:

list.index(x[, start[, end]])

  Return zero-based index in the list of
  the first item whose value is x.    Raises a ValueError if there is no
  such item.

ContentLicense: CC BY-SA 4.0

Title: Removing duplicates in lists

Body:
You could also do this:

>>> t = [1, 2, 3, 3, 2, 4, 5, 6]
>>> s = [x for i, x in enumerate(t) if i == t.index(x)]
>>> s
[1, 2, 3, 4, 5, 6]

The reason that above works is that index method returns only the first index of an element. Duplicate elements have higher indices. Refer to here:

list.index(x[, start[, end]])

  Return zero-based index in the list of
  the first item whose value is x.    Raises a ValueError if there is no
  such item.


问:
How to embed a youtube channel in my site
I have a url like: https://www.youtube.com/channel/xxxxxxxxxxxxxxxxxxxxx
Without user, is it possible to embed a channel to show the latest videos in my webpage using IFRAME?? if possible how???

I saw with user like:

```<code><iframe width="600" height="340" src="http://www.youtube.com/embed?max-   results=1&controls=0&showinfo=0&rel=0&listType=user_uploads&list=YOUR_CHANNEL_NAME_HERE" frameborder="0" allowfullscreen></iframe>
</code>```

It works but without user how can i embed??

答:
YouTube provides an RSS feed for each channel: https://www.youtube.com/feeds/videos.xml?channel_id={{{channel_id_here}}}, so you could make a script that check this RSS feed periodically and updates your database.

The easiest way to get this RSS feed URL is probably to give the channel's URL to a feed aggregator: for instance, Vsauce's feed is https://www.youtube.com/feeds/videos.xml?channel_id=UC6nSFpj9HTCZ5t-N3Rm3-HA.

Body:
I have a url like: https://www.youtube.com/channel/xxxxxxxxxxxxxxxxxxxxx
Without user, is it possible to embed a channel to show the latest videos in my webpage using IFRAME?? if possible how???

I saw with user like:

It works but without user how can i embed??


问:
Is there any restriction for number of characters in TFS REST API?
I am trying to retrieve workitems from TFS using REST API. https://servername/tfs/collectionname/_apis/wit/workitems?ids='xxxx,yyyy,zzzz,....n' (where n count is 420). Each id is a 4 digit number. I could not retrieve more than 409 workitems. If the query exceed more than 409 ids, I receive "404 - File or directory not found" error. Please help me to find solution for this.</p>

答:
I can reproduce this issue,it has restriction for the length of the strings when using the REST API.

In this case, we can not get all the work items in one time, we can get the work items separately, just call the API twice.


问:
How to upload multiple files(each file contains max 1 file) on clicking on submit button?
Hi i am developing file upload module using Angularjs and api. I am following https://jsfiddle.net/JeJenny/vtqavfhf/. I have one list which contains document names such as passport,visa etc and so on. I am binding this list to array and looping inside ng-repeat. So based on the number of documents it generates file upload controls as below.

```<code><div class="upload-button" ng-repeat="file in files">
                <div class="upload-button-icon">
                    <img src="images/folder-small.png">
                    <div class="upload-text">{{file}}</div>
                    <input type="file" id="file1" name="file1" file-model="{{file}}"  />
                </div>
</div>
</code>```

Note: we can upload obly one document on one upload.
So clearly if i have 4 documents in files array then 4 file upload controls will generate.

Finally i have one button which should save all the above files on click.

```<code>   <input type="submit" value="{{ 'NEXT' | translate }}" class="blue-button" ng-click="uploadFile(files)">
</code>```

I have this function to save file(Taken from fiddler)

```<code>$scope.uploadFile = function(filename){
       //Here i want to save all the files. For example if there are three documents in array files then 3 documents at a time i want to send it to server.
    };
</code>```

As you can see, fiddler will be having separate functions to save each file individually. I am trying to send all the files at a time.

May i get some help here? I am not sure what should be written inside  $scope.uploadFile function? How can i collect here all files data? Thank you.

答:
Here is a working example, hope it helps

var myApp = angular.module('myApp', []);

myApp.directive('fileModel', ['fileUpload', function(fileUpload) {
  return {
    restrict: 'A',
    link: function(scope, element, attrs) {
      element.bind("change", function(evt) {
        fileUpload.pendingFiles[attrs.fileModel] = evt.target.files[0];
      });
    }
  };
}]);

myApp.factory('fileUpload', ['$http', function($http) {

  var service = {
    uploadUrl: "https://httpbin.org/post",
    pendingFiles: [],
    doUpload: doUpload
  };

  return service;

  function doUpload() {
    var files = new FormData();
    angular.forEach(this.pendingFiles, function(value, key) {
      files.append('file', value);
    });

    return $http.post(this.uploadUrl, files, {
      transformRequest: angular.identity,
      headers: {
        'Content-Type': undefined
      }
    })
  }
}]);

myApp.controller('myCtrl', ['$scope', 'fileUpload', function($scope, fileUpload) {
  $scope.fileInputs = [1, 2, 3];
  $scope.upload = function(filename) {
    fileUpload.doUpload().success(function(success) {
      $scope.result = success
    });
  };
}]);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<body ng-app="myApp">
  <div ng-controller="myCtrl">
    <div ng-repeat="fileInput in fileInputs">
      <input type="file" file-data="{{fileInput}}" file-model="{{fileInput}}" />
    </div>
    <br />
    <button ng-click="upload()">upload all</button>
  <br />
    ```{{result | json}}```
  </div>
</body></code>```

Body:
Hi i am developing file upload module using Angularjs and api. I am following https://jsfiddle.net/JeJenny/vtqavfhf/. I have one list which contains document names such as passport,visa etc and so on. I am binding this list to array and looping inside ng-repeat. So based on the number of documents it generates file upload controls as below.

{{file}}

                    <input type="file" id="file1" name="file1" file-model="{{file}}"  />

Note: we can upload obly one document on one upload.
So clearly if i have 4 documents in files array then 4 file upload controls will generate.

Finally i have one button which should save all the above files on click.

   <input type="submit" value="{{ 'NEXT' | translate }}" class="blue-button" ng-click="uploadFile(files)">

I have this function to save file(Taken from fiddler)

$scope.uploadFile = function(filename){
       //Here i want to save all the files. For example if there are three documents in array files then 3 documents at a time i want to send it to server.
    };

As you can see, fiddler will be having separate functions to save each file individually. I am trying to send all the files at a time.

May i get some help here? I am not sure what should be written inside  $scope.uploadFile function? How can i collect here all files data? Thank you.

Body:
Here is a working example, hope it helps

var myApp = angular.module('myApp', []);

myApp.directive('fileModel', ['fileUpload', function(fileUpload) {
  return {
    restrict: 'A',
    link: function(scope, element, attrs) {
      element.bind("change", function(evt) {
        fileUpload.pendingFiles[attrs.fileModel] = evt.target.files[0];
      });
    }
  };
}]);

myApp.factory('fileUpload', ['$http', function($http) {

  var service = {
    uploadUrl: "https://httpbin.org/post",
    pendingFiles: [],
    doUpload: doUpload
  };

  return service;

  function doUpload() {
    var files = new FormData();
    angular.forEach(this.pendingFiles, function(value, key) {
      files.append('file', value);
    });

    return $http.post(this.uploadUrl, files, {
      transformRequest: angular.identity,
      headers: {
        'Content-Type': undefined
      }
    })
  }
}]);

myApp.controller('myCtrl', ['$scope', 'fileUpload', function($scope, fileUpload) {
  $scope.fileInputs = [1, 2, 3];
  $scope.upload = function(filename) {
    fileUpload.doUpload().success(function(success) {
      $scope.result = success
    });
  };
}]);

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<body ng-app="myApp">
  <div ng-controller="myCtrl">
    <div ng-repeat="fileInput in fileInputs">
      <input type="file" file-data="{{fileInput}}" file-model="{{fileInput}}" />
    </div>
    <br />
    <button ng-click="upload()">upload all</button>
  <br />
    <pre>{{result | json}}</pre>
  </div>
</body>


问:
Delegate for UITextField not working...Return button not responding
I've just started with xcode and objective-c and did some very basic apps, but what i'm having problem with is very basic this. the keyboard return button not hiding the keyboard.

I've searched the internet for the solution and all they say is to connect delegate to the file's owner and add the function and it should work, i did that and nothing is working.

I have an ok button and it is working and also clicking on any free space on the screen is working, just the return button....

I am using the simulator, not testing on iphone yet. (xcode 3.2.5 64 bit with the 4.2 simulator).

This is the line of code that should connect the delegate to every textFiled.
1. i've tried already to return both YES and NO, didn't work.
2. i've tried both a specific object name for the textField and this general way, didn't work.

```<code>- (BOOL)textFieldShouldReturn:(UITextField *)textField {
[textField resignFirstResponder];
return NO;
}
</code>```

In the: basic view controller connection -> connections -> outlets, i have the: delegate -- File's Owner. and in the file's owner in referencing outlets there is: delegate - Round style text.....

EDIT - i forgot to mention before, i've check and the method isn't being called!!!

```<code>- (BOOL)textFieldShouldReturn:(UITextField *)textField{
NSLog(@"Working!!!");
[textField resignFirstResponder];
return YES;
</code>```

}

what should i do to make it happen? that is why people say to connect the delegate, but in my case it is connected and not triggering the function...i know it is kind of dumb question but for a nobie like me the solution is not obvious...

OK, another Edit - with all my code: just can't understand what to do....
This is: basicViewController.h:

```<code>#import <UIKit/UIKit.h>

@interface basicViewController : <#superclass#> <UITextFieldDelegate>

@interface basicViewController : UIViewController <UITextFieldDelegate> {
//every object that we want to interact with (like text field or lable) is call an   outlet!!!!
//here we define the outlets for our program
IBOutlet UITextField *txtName;
IBOutlet UILabel *lblMessage;
 }

//here are the getters and setter for our outlets
@property (nonatomic, retain) IBOutlet UITextField *txtName;
@property (nonatomic, retain) IBOutlet UILabel *lblMessage;

//method decleration for the OK button action
- (IBAction) doSomething;

//method for hiding the keyboard when clicking on empty area in the app
   //we will put an invisible button on all area and clicking on it will make keyboard disapear
   - (IBAction) makeKeyboardGoAway;

   @end
</code>```

This is basicViewController.m:

```<code> #import "basicViewController.h"

 @implementation basicViewController

 //synthesizeing the objects that we made' this will create the getter and setters automaticly
 @synthesize txtName;
 @synthesize lblMessage;

 - (IBAction) doSomething{
// makeing keyboard disapear when pressing ok button (doing that form the text field)
//when pressing the OK button, the keyboard will disapear and when clicking in the text field it will show again
[txtName resignFirstResponder];

NSString *msg = [[NSString alloc] initWithFormat:@"Hello, %@",txtName.text];

//the objective-c way for setting the test in the text field
[lblMessage setText:msg];
//the regular object oriented way
//lblMessage.text = msg;
[msg  release];
 }

 - (IBAction) makeKeyboardGoAway{
[txtName resignFirstResponder];
 }

 //when clicking the return button in the keybaord
 - (BOOL)textFieldShouldReturn:(UITextField *)textField{
NSLog(@"Working!!!");
[textField resignFirstResponder];
return YES;
 }

 - (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

// Release any cached data, images, etc that aren't in use.
 }

 - (void)viewDidUnload {
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
 }

 - (void)dealloc {
     [super dealloc];
 }

 @end
</code>```

Maybe now i am more clear, sorry i didn't do it before.
Any one has an idea what am i doing wrong? it should be pretty strait forward.....

EDIT - Adding an image of all the elements, i hope that will help to help me :-)

10x a lot for every one that is trying to help....i really like this framework, it is so great after c++ and java, python and many other...and i am working with a book, but it is for ios 3.1, maybe that is the problem.....

答:
Can you try this..</p>

```<code>@interface ClassName : SuperClass < UITextFieldDelegate >
</code>```

Body:
I've just started with xcode and objective-c and did some very basic apps, but what i'm having problem with is very basic this. the keyboard return button not hiding the keyboard.

I've searched the internet for the solution and all they say is to connect delegate to the file's owner and add the function and it should work, i did that and nothing is working.

I have an ok button and it is working and also clicking on any free space on the screen is working, just the return button....

I am using the simulator, not testing on iphone yet. (xcode 3.2.5 64 bit with the 4.2 simulator).

This is the line of code that should connect the delegate to every textFiled.
1. i've tried already to return both YES and NO, didn't work.
2. i've tried both a specific object name for the textField and this general way, didn't work.

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
[textField resignFirstResponder];
return NO;
}

In the: basic view controller connection -> connections -> outlets, i have the: delegate -- File's Owner. and in the file's owner in referencing outlets there is: delegate - Round style text.....

EDIT - i forgot to mention before, i've check and the method isn't being called!!!

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
NSLog(@"Working!!!");
[textField resignFirstResponder];
return YES;

}

what should i do to make it happen? that is why people say to connect the delegate, but in my case it is connected and not triggering the function...i know it is kind of dumb question but for a nobie like me the solution is not obvious...

OK, another Edit - with all my code: just can't understand what to do....
This is: basicViewController.h:

#import <UIKit/UIKit.h>

@interface basicViewController : <#superclass#> <UITextFieldDelegate>

@interface basicViewController : UIViewController <UITextFieldDelegate> {
//every object that we want to interact with (like text field or lable) is call an   outlet!!!!
//here we define the outlets for our program
IBOutlet UITextField *txtName;
IBOutlet UILabel *lblMessage;
 }

//here are the getters and setter for our outlets
@property (nonatomic, retain) IBOutlet UITextField *txtName;
@property (nonatomic, retain) IBOutlet UILabel *lblMessage;

//method decleration for the OK button action
- (IBAction) doSomething;

//method for hiding the keyboard when clicking on empty area in the app
   //we will put an invisible button on all area and clicking on it will make keyboard disapear
   - (IBAction) makeKeyboardGoAway;

   @end

This is basicViewController.m:

 #import "basicViewController.h"

 @implementation basicViewController

 //synthesizeing the objects that we made' this will create the getter and setters automaticly
 @synthesize txtName;
 @synthesize lblMessage;

 - (IBAction) doSomething{
// makeing keyboard disapear when pressing ok button (doing that form the text field)
//when pressing the OK button, the keyboard will disapear and when clicking in the text field it will show again
[txtName resignFirstResponder];

NSString *msg = [[NSString alloc] initWithFormat:@"Hello, %@",txtName.text];

//the objective-c way for setting the test in the text field
[lblMessage setText:msg];
//the regular object oriented way
//lblMessage.text = msg;
[msg  release];
 }

 - (IBAction) makeKeyboardGoAway{
[txtName resignFirstResponder];
 }

 //when clicking the return button in the keybaord
 - (BOOL)textFieldShouldReturn:(UITextField *)textField{
NSLog(@"Working!!!");
[textField resignFirstResponder];
return YES;
 }

 - (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

// Release any cached data, images, etc that aren't in use.
 }

 - (void)viewDidUnload {
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
 }

 - (void)dealloc {
     [super dealloc];
 }

 @end

Maybe now i am more clear, sorry i didn't do it before.
Any one has an idea what am i doing wrong? it should be pretty strait forward.....

EDIT - Adding an image of all the elements, i hope that will help to help me :-)

10x a lot for every one that is trying to help....i really like this framework, it is so great after c++ and java, python and many other...and i am working with a book, but it is for ios 3.1, maybe that is the problem.....

Body:
Can you try this..

@interface ClassName : SuperClass < UITextFieldDelegate >