问:
How to write a List of string arrays to txt file
Is it possible to write a List of string arrays to txt file?

This is my code and I'm not sure how to make the final step. I made a list through which I foreach based on the number the user inputs, and it returns all the values correctly, but I can't seem to be able to save all the data to a txt file.

```<code> static void Main(string[] args)
    {
        Console.WriteLine("Unesi broj:");

        int userNumber = Convert.ToInt32(Console.ReadLine());

        var numberLIst = Enumerable.Range(1,userNumber).ToList();

        string path = @"C:\Users\mcrnic\Desktop\scriptFolder\input.txt";

        List<string[]> listaStringova = new List<string[]>();

        int n = 0;

        foreach (var data in numberLIst)
        {

            n++;

            #region Varijable
            var textBoxNumberRangeFirst = "tbxNumberRangeFirstInput" + data;
            var textBoxNumberRangeSecond = "tbxNumberRangeSecondInput" + data;
            var textBoxNumberRangeThird = "tbxNumberRangeThirdInput" + data;
            var textBoxHomeNumbersFirst = "tbxRangeOfHomeNumbersFirstInput" + data;
            var textBoxHomeNumbersSecond = "tbxRangeOfHomeNumbersSecondInput" + data;
            var textBoxVPNFirst = "tbxRangeOfShortVPNNumbersFirstInput" + data;
            var textBoxVPNSecond = "tbxRangeOfShortVPNNumbersSecondInput" + data;
            var checkBoxNumberTransfer = "cbxNumberTransfer" + data;
            var checkBoxSecretNumber = "cbxSecretNumber" + data;
            var checkBoxSearchByNumber = "cbxSearchByNumber" + data;
            var checkBoxZ1 = "cbxZ1_" + data;
            var checkBoxZ2 = "cbxZ2_" + data;
            var checkBoxZ3 = "cbxZ3_" + data;
            var checkBoxZ4 = "cbxZ4_" + data;
            var checkBoxZ5 = "cbxZ5_" + data;
            var checkBoxZ6 = "cbxZ6_" + data;
            var checkBoxZ7 = "cbxZ7_" + data;
            #endregion

            string[] htmlLinije = {"<%-- Row" + n + " --%>",
                                "<div class=&row rowFullWidth form-inline pb10& hidden>",
                                "<div class=&col-sm-4&>",
                                "<asp:TextBox runat=&server& ID=&" + textBoxNumberRangeFirst + "& class=&form-control textbox-width-25 ml10& ReadOnly=&true& />",
                                "<span class=&pr5 pl5&>/</span><asp:TextBox runat=&server& ID=&" + textBoxNumberRangeSecond +"& class=&form-control textbox-width-25& ReadOnly=&true&/>",
                                "<span class=&pr5 pl5&>-</span><asp:TextBox runat=&server& ID=&" + textBoxHomeNumbersSecond + "& class=&form-control textbox-width-25& ReadOnly=&true&/>",
                                "</div>",
                                "<div class=&col-sm-2&>",
                                "<asp:CheckBox runat=&server& ID=&" + checkBoxNumberTransfer + "& AutoPostBack=&false& CssClass=&checkbox pl20 pr15 pt5& Enabled=&false&/>",
                                "<asp:CheckBox runat=&server& ID=&" + checkBoxSecretNumber + "& AutoPostBack=&false& CssClass=&checkbox pl20 pr15 pt5& Enabled=&false&/>",
                                "<asp:CheckBox runat=&server& ID=&" + checkBoxSearchByNumber + "& AutoPostBack=&false& CssClass=&checkbox pl20 pr15 pt5& Enabled=&false& />",
                                "</div>",
                                "<div class=&col-sm-2&>",
                                "<asp:TextBox runat=&server& ID=&" + textBoxHomeNumbersFirst + "& class=&form-control textbox-width-40& ReadOnly=&true& /><span class=&pr10 pl10&>-</span>",
                                "<asp:TextBox runat=&server& ID=&" + textBoxHomeNumbersSecond + "& class=&form-control textbox-width-40& ReadOnly=&true& />",
                                "</div>",
                                "<div class=&col-sm-2&>",
                                "<asp:TextBox runat=&server& ID=&" + textBoxVPNFirst + "& class=&form-control textbox-width-40& ReadOnly=&true& /><span class=&pr10 pl10&>-</span>",
                                "<asp:TextBox runat=&server& ID=&" + textBoxVPNSecond + "& class=&form-control textbox-width-40& ReadOnly=&true& />",
                                "</div>",
                                "<div class=&col-sm-2&>",
                                "<div class=&pt5&>",
                                "<asp:CheckBox runat=&server& ID=&" + checkBoxZ1 + "& AutoPostBack=&false& CssClass=&checkbox pr5& Enabled=&false& />",
                                "<asp:CheckBox runat=&server& ID=&" + checkBoxZ2 + "& AutoPostBack=&false& CssClass=&checkbox pr5& Enabled=&false& />",
                                "<asp:CheckBox runat=&server& ID=&" + checkBoxZ3 + "& AutoPostBack=&false& CssClass=&checkbox pr5& Enabled=&false& />",
                                "<asp:CheckBox runat=&server& ID=&" + checkBoxZ4 + "& AutoPostBack=&false& CssClass=&checkbox pr5& Enabled=&false& />",
                                "<asp:CheckBox runat=&server& ID=&" + checkBoxZ5 + "& AutoPostBack=&false& CssClass=&checkbox pr5& Enabled=&false& />",
                                "<asp:CheckBox runat=&server& ID=&" + checkBoxZ6 + "& AutoPostBack=&false& CssClass=&checkbox pr5& Enabled=&false& />",
                                "<asp:CheckBox runat=&server& ID=&" + checkBoxZ7 + "& AutoPostBack=&false& CssClass=&checkbox pr5& Enabled=&false& />",
                                "</div>",
                                "</div>",
                                "</div>",
                                ""
            };

            listaStringova.Add(htmlLinije);
        }

        System.IO.File.WriteAllLines(path, listaStringova);

    }
</code>```

I get this error when I try to WriteAllLines:

Error CS1503  Argument 2: cannot convert from System.Collections.Generic.List to string[]

答:
WriteAllLines expects an array of strings as the second parameter. You are sending an array of string arrays, so you need to flatten this list first.

This can be done using SelectMany like so:

```<code>var stringlist = listaStringova.SelectMany(line => line);
System.IO.File.WriteAllLines(path, stringlist);
</code>```

Body:
Is it possible to write a List of string arrays to txt file?

This is my code and I'm not sure how to make the final step. I made a list through which I foreach based on the number the user inputs, and it returns all the values correctly, but I can't seem to be able to save all the data to a txt file.

 static void Main(string[] args)
    {
        Console.WriteLine("Unesi broj:");

        int userNumber = Convert.ToInt32(Console.ReadLine());

        var numberLIst = Enumerable.Range(1,userNumber).ToList();

        string path = @"C:\Users\mcrnic\Desktop\scriptFolder\input.txt";

        List<string[]> listaStringova = new List<string[]>();

        int n = 0;

        foreach (var data in numberLIst)
        {

            n++;

            #region Varijable
            var textBoxNumberRangeFirst = "tbxNumberRangeFirstInput" + data;
            var textBoxNumberRangeSecond = "tbxNumberRangeSecondInput" + data;
            var textBoxNumberRangeThird = "tbxNumberRangeThirdInput" + data;
            var textBoxHomeNumbersFirst = "tbxRangeOfHomeNumbersFirstInput" + data;
            var textBoxHomeNumbersSecond = "tbxRangeOfHomeNumbersSecondInput" + data;
            var textBoxVPNFirst = "tbxRangeOfShortVPNNumbersFirstInput" + data;
            var textBoxVPNSecond = "tbxRangeOfShortVPNNumbersSecondInput" + data;
            var checkBoxNumberTransfer = "cbxNumberTransfer" + data;
            var checkBoxSecretNumber = "cbxSecretNumber" + data;
            var checkBoxSearchByNumber = "cbxSearchByNumber" + data;
            var checkBoxZ1 = "cbxZ1_" + data;
            var checkBoxZ2 = "cbxZ2_" + data;
            var checkBoxZ3 = "cbxZ3_" + data;
            var checkBoxZ4 = "cbxZ4_" + data;
            var checkBoxZ5 = "cbxZ5_" + data;
            var checkBoxZ6 = "cbxZ6_" + data;
            var checkBoxZ7 = "cbxZ7_" + data;
            #endregion

            string[] htmlLinije = {"<%-- Row" + n + " --%>",
                                "
",
                                "
",
                                "<asp:TextBox runat=&server& ID=&" + textBoxNumberRangeFirst + "& class=&form-control textbox-width-25 ml10& ReadOnly=&true& />",
                                "/<asp:TextBox runat=&server& ID=&" + textBoxNumberRangeSecond +"& class=&form-control textbox-width-25& ReadOnly=&true&/>",
                                "-<asp:TextBox runat=&server& ID=&" + textBoxHomeNumbersSecond + "& class=&form-control textbox-width-25& ReadOnly=&true&/>",
                                "
",
                                "
",
                                "<asp:CheckBox runat=&server& ID=&" + checkBoxNumberTransfer + "& AutoPostBack=&false& CssClass=&checkbox pl20 pr15 pt5& Enabled=&false&/>",
                                "<asp:CheckBox runat=&server& ID=&" + checkBoxSecretNumber + "& AutoPostBack=&false& CssClass=&checkbox pl20 pr15 pt5& Enabled=&false&/>",
                                "<asp:CheckBox runat=&server& ID=&" + checkBoxSearchByNumber + "& AutoPostBack=&false& CssClass=&checkbox pl20 pr15 pt5& Enabled=&false& />",
                                "
",
                                "
",
                                "<asp:TextBox runat=&server& ID=&" + textBoxHomeNumbersFirst + "& class=&form-control textbox-width-40& ReadOnly=&true& />-",
                                "<asp:TextBox runat=&server& ID=&" + textBoxHomeNumbersSecond + "& class=&form-control textbox-width-40& ReadOnly=&true& />",
                                "
",
                                "
",
                                "<asp:TextBox runat=&server& ID=&" + textBoxVPNFirst + "& class=&form-control textbox-width-40& ReadOnly=&true& />-",
                                "<asp:TextBox runat=&server& ID=&" + textBoxVPNSecond + "& class=&form-control textbox-width-40& ReadOnly=&true& />",
                                "
",
                                "
",
                                "
",
                                "<asp:CheckBox runat=&server& ID=&" + checkBoxZ1 + "& AutoPostBack=&false& CssClass=&checkbox pr5& Enabled=&false& />",
                                "<asp:CheckBox runat=&server& ID=&" + checkBoxZ2 + "& AutoPostBack=&false& CssClass=&checkbox pr5& Enabled=&false& />",
                                "<asp:CheckBox runat=&server& ID=&" + checkBoxZ3 + "& AutoPostBack=&false& CssClass=&checkbox pr5& Enabled=&false& />",
                                "<asp:CheckBox runat=&server& ID=&" + checkBoxZ4 + "& AutoPostBack=&false& CssClass=&checkbox pr5& Enabled=&false& />",
                                "<asp:CheckBox runat=&server& ID=&" + checkBoxZ5 + "& AutoPostBack=&false& CssClass=&checkbox pr5& Enabled=&false& />",
                                "<asp:CheckBox runat=&server& ID=&" + checkBoxZ6 + "& AutoPostBack=&false& CssClass=&checkbox pr5& Enabled=&false& />",
                                "<asp:CheckBox runat=&server& ID=&" + checkBoxZ7 + "& AutoPostBack=&false& CssClass=&checkbox pr5& Enabled=&false& />",
                                "
",
                                "
",
                                "
",
                                ""
            };

            listaStringova.Add(htmlLinije);
        }

        System.IO.File.WriteAllLines(path, listaStringova);

    }

I get this error when I try to WriteAllLines:

Error CS1503  Argument 2: cannot convert from System.Collections.Generic.List to string[]

Body:
WriteAllLines expects an array of strings as the second parameter. You are sending an array of string arrays, so you need to flatten this list first.

This can be done using SelectMany like so:

var stringlist = listaStringova.SelectMany(line => line);
System.IO.File.WriteAllLines(path, stringlist);


来源: stackexchange

问:
"RobolectricTestRunner.class" not recognized in Android Studio
I'm trying to use Robolectric to run unit tests but the Android Studio is not recognizing the class on:

```<code>@RunWith(RobolectricTestRunner.class)
</code>```

Details:

```<code>classpath 'com.android.tools.build:gradle:3.0.0'
</code>```

And I'm importing dependency:

```<code>testImplementation "org.robolectric:robolectric:3.5.1"
</code>```

And:

```<code>android {
    testOptions {
        unitTests {
            includeAndroidResources = true
        }
    }
}
</code>```

It simply does not appear option to import the class.
Should I add any more dependencies I'm forgetting?

Error:

```<code> error: package org.robolectric does not exist
 error: package org.robolectric does not exist
 error: package org.robolectric.shadows does not exist
 error: cannot find symbol class RobolectricTestRunner
 error: cannot find symbol variable Robolectric
 error: cannot find symbol variable ShadowApplication
</code>```

答:
RobolectricGradleTestRunner is deprecated since version 3 of Robolectric. Just use @RunWith(RobolectricTestRunner.class)
Take a look at official documentation.

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to use Robolectric to run unit tests but the Android Studio is not recognizing the class on:

@RunWith(RobolectricTestRunner.class)

Details:

classpath 'com.android.tools.build:gradle:3.0.0'

And I'm importing dependency:

testImplementation "org.robolectric:robolectric:3.5.1"

And:

android {
    testOptions {
        unitTests {
            includeAndroidResources = true
        }
    }
}

It simply does not appear option to import the class.
Should I add any more dependencies I'm forgetting?

Error:

 error: package org.robolectric does not exist
 error: package org.robolectric does not exist
 error: package org.robolectric.shadows does not exist
 error: cannot find symbol class RobolectricTestRunner
 error: cannot find symbol variable Robolectric
 error: cannot find symbol variable ShadowApplication


问:
Stereo Display (non head-mounted) option in Unity 2017.2 is not available?
I would like to know the where to enable option for 'Stereo Display (non head-mounted)' in Unity 2017.2. I was using this for nvdia 3D vision stereo and it was present until 2017.1. I have checked with unity's documentation regarding that it does not mention anything about it. This option was available in player settings of unity 2017.1 and 5.6 by enabling Virtual Reality-> And in virtual reality SDK's. Since the VR settings are now moved to XR section in player settings as you can see the below images

.

I cannot seem to find it anymore. Also the Unity's release blog does not mention anything about removing it so not sure where exactly it is. So if anyone has information regarding enabling stereo display in 2017.2 it would be helpful. If also want to know by scripting is it possible to change the player settings to include "Stereo Display" option it as I had scripts for changing player settings for using rendering API like directx11 and openGL while making builds so Iam pretty sure this will also have it but I'm unsure where to look for this and how to add it.

Edit: I use the 'Stereo Display(non head-mounted)' to acieve Active Stereo in my game as the @programmer has mentioned Mock HMD vive has replaced the option of 'Split Stereo Display(non head-mounted)' which I do not want to use as it is SBS and not active stereo. Only the 'Stereo Display(non head-mounted)' option is where I get my Nvdia active glasses working.

答:
When in doubt about a missing feature, check the final release note.

XR: Added support for certain aspects of the Vive HMD to be simulated
  in-Editor without the need of a physical HMD. To enable this, use the
  "Mock HMD - Vive" virtual reality SDK in the Player Settings. The mock
  HMD uses the same asymmetric projection matrix, hidden occlusion mesh,
  field of view, aspect ratio, and eye texture size as the Vive. You can
  use mock HMD with both multi and single pass rendering paths. It
  renders as a split-screen stereo display in the Editor.

In the Beta 2017.2 release note:

XR: Certain aspects of the Vive HMD can be simulated in Editor,
  without the need of a physical HMD, using the "Mock HMD - Vive"
  virtual reality SDK in the player settings. The mock HMD will use the
  same asymmetric projection matrix, hidden occlusion mesh, field of
  view, aspect ratio, and eye texture size as the Vive. Mock HMD can be
  used with both multi and single pass rendering paths. Mock HMD will
  render as a split screen stereo display in Editor.

So it looks like Mock HMD  replaced it.


问:
Get innerhtml from external page with Javascript
I'm trying to get innerHTML of a DIV that is located on external page. It is possible to do this using this kind javascript code?</p>

```<code>    <script type="text/javascript">
        $(document).ready(function(){
            var html = document.getElementById("glr1").src='/my_page.html'.innerHTML ;
            alert(html);
        });
    </script>
</code>```

答:
not quite.
Only if the desireed page is on the same domain and same protocol you could try to embed it in an iframe or you could use ajax.
jQuery already has implemented a way to retrieve only a part of an external page ,via ajax:

$.get(url+"#"+id); , where id is the div's id. so you would have something like :

```
var aux = window.location.href.split('/'),
id = 'glr1',
page = 'my_page.html';
$.get(
  aux.splice(0,aux.length-1).join('/') + '/' + page + '#' + id,
  function(){alert(arguments[0]);}
);
```

Body:
not quite.
Only if the desireed page is on the same domain and same protocol you could try to embed it in an iframe or you could use ajax.
jQuery already has implemented a way to retrieve only a part of an external page ,via ajax:

$.get(url+"#"+id); , where id is the div's id. so you would have something like :

var aux = window.location.href.split('/'),
id = 'glr1',
page = 'my_page.html';
$.get(
  aux.splice(0,aux.length-1).join('/') + '/' + page + '#' + id,
  function(){alert(arguments[0]);}
);

ContentLicense: CC BY-SA 2.5


问:
Scala - reducing a map based on changed key
Lets say have the following Map data

```<code>val testMap: Map[String, Int] = Map("AAA_abc" -> 1,
                                    "AAA_anghesh" -> 2,
                                    "BBB_wfejw" -> 3,
                                    "BBB_qgqwe" -> 4,
                                    "C_fkee" -> 5)
</code>```

Now I want to reduce the map by key.split("_").head and add all the values for the keys that became equal. So for this example the Map should result into:

```<code>Map(AAA -> 3, BBB -> 7, C -> 5)
</code>```

What would be the correct way to do so in Scala?
I tried constructions with groupBy and reduceLeft but could not find a solution.

答:
Here's a way to do it:</p>

```<code>testMap.groupBy(_._1.split("_").head).mapValues(_.values.sum)
</code>```

Body:
Lets say have the following Map data

val testMap: Map[String, Int] = Map("AAA_abc" -> 1,
                                    "AAA_anghesh" -> 2,
                                    "BBB_wfejw" -> 3,
                                    "BBB_qgqwe" -> 4,
                                    "C_fkee" -> 5)

Now I want to reduce the map by key.split("_").head and add all the values for the keys that became equal. So for this example the Map should result into:

Map(AAA -> 3, BBB -> 7, C -> 5)

What would be the correct way to do so in Scala?
I tried constructions with groupBy and reduceLeft but could not find a solution.

Body:
Here's a way to do it:

testMap.groupBy(_._1.split("_").head).mapValues(_.values.sum)


问:
pdftk extract random pages from script variable
I have some pdf files about 2000 pages. They are randomly generated.
I need to extract some pages that contain some specific patterns, that changes its page number for every pdf.
With some steps using pdfToText and AWK, I can get the page numbers and I store some info into a csv file like that:

```<code>PatternA ; 1 3 5 7
PatternB ; 1 8 10 22
</code>```

I have been trying to do a loop to get and process each line from this csv into the cat option from pdftk command, but it aways return error:

```<code>$IFS=$(printf '\n\t')
for line in `cat job.csv`
do
pattern=`echo $line ¦ cut -d ';' -f 1`
pages=`echo $line ¦ cut -d ';' - f 2`
pdftk input.pdf cat $pages output $pattern
done
</code>```

When echoing pattern and pages variables, everything are ok. But the pdftk command returns error if I try to get pages from $pages variable:

```<code>Error: Unexpected text in page range end, here:
   1 3 5 7
   Exiting.
   Acceptable keywords, for example: "even" or "odd".
   To rotate pages, use: "north" "south" "east"
       "west" "left" "right" or "down"
Errors encountered.  No output created.
Done.  Input errors, so no output created.
</code>```

What I am doing wrong?

Thanks!

答:
[SOLVED]

I guess.. I don't know if it is the best choice, but works:

Instead directly execute the pdftk command:

```<code>pdftk input.pdf cat $pages output $pattern
</code>```

I stored entire command into a new variable and them, ran the eval command:

```<code>cmd="pdftk input.pdf cat $pages output $pattern"
eval $cmd
</code>```

So, it worked like a charm...

If there are more elegant solution, I'll appreciate!

Body:
I have some pdf files about 2000 pages. They are randomly generated.
I need to extract some pages that contain some specific patterns, that changes its page number for every pdf.
With some steps using pdfToText and AWK, I can get the page numbers and I store some info into a csv file like that:

PatternA ; 1 3 5 7
PatternB ; 1 8 10 22

I have been trying to do a loop to get and process each line from this csv into the cat option from pdftk command, but it aways return error:

$IFS=$(printf '\n\t')
for line in `cat job.csv`
do
pattern=`echo $line ¦ cut -d ';' -f 1`
pages=`echo $line ¦ cut -d ';' - f 2`
pdftk input.pdf cat $pages output $pattern
done

When echoing pattern and pages variables, everything are ok. But the pdftk command returns error if I try to get pages from $pages variable:

Error: Unexpected text in page range end, here:
   1 3 5 7
   Exiting.
   Acceptable keywords, for example: "even" or "odd".
   To rotate pages, use: "north" "south" "east"
       "west" "left" "right" or "down"
Errors encountered.  No output created.
Done.  Input errors, so no output created.

What I am doing wrong?

Thanks!

Body:
[SOLVED]

I guess.. I don't know if it is the best choice, but works:

Instead directly execute the pdftk command:

pdftk input.pdf cat $pages output $pattern

I stored entire command into a new variable and them, ran the eval command:

cmd="pdftk input.pdf cat $pages output $pattern"
eval $cmd

So, it worked like a charm...

If there are more elegant solution, I'll appreciate!


问:
Select current element from getElementsbyClassName
This code will hide the first div, even if it were activated from the second button. What keyword should I use to get it to hide the parent div (first button hides the first div, second button hides the second div)?

var x = document.getElementsbyClassName(myClass);

function myFunction() {
  x[0].display = "none";
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="myClass">
  <button onclick="myFunction()">Click</button>
</div>
<div class="myClass">
  <button onclick="myFunction()">Click</button>
</div></code>```

答:
This should do the job:

HTML:

```<code><div class="myClass">
  <button>Click</button>
</div>
<div class="myClass">
  <button>Click</button>
</div>
</code>```

JS:

```<code>var btns = document.getElementsByTagName("button");

for (var i = 0; i < btns.length; i++) {
  btns[i].onclick = function() {
    this.parentElement.style.display = "none";
  }
}
</code>```

Body:
This code will hide the first div, even if it were activated from the second button. What keyword should I use to get it to hide the parent div (first button hides the first div, second button hides the second div)?

var x = document.getElementsbyClassName(myClass);

function myFunction() {
  x[0].display = "none";
}

  <button onclick="myFunction()">Click</button>

  <button onclick="myFunction()">Click</button>

Body:
This should do the job:

HTML:

<div class="myClass">
  <button>Click</button>
</div>
<div class="myClass">
  <button>Click</button>
</div>

JS:

var btns = document.getElementsByTagName("button");

for (var i = 0; i < btns.length; i++) {
  btns[i].onclick = function() {
    this.parentElement.style.display = "none";
  }
}


答:
You are trying to write a list of string arrays to the file. You have to write a list of strings (one string for each line):

List<string> listStringova = new List<string>();

Title: How to write a List of string arrays to txt file


问:
ASP.NET validation: gathering information from client-side validation
I'd like to implement ajax message box that will gather information from validators on a page when client-side validation fires.
Like: I have left some text fields blank then press submit button and appropriate RequiredFieldValidators show messages. I would like my message box shows those messages too. I am looking for appropriate way to hook on validators JS event or something.

Thanks!

答: What about Using jQuery with the ASP.NET CustomValidator Control?</p>


问:
Running statistical operations across variables in a dataframe using R
I currently have a time series that I need to regress against several variables of different lengths. I need to perform a couple of statistical operations on them and I am trying to find the most efficient way to do so.

Example- I have three independent time series variables B, C, D and a dependent variable A.

Data# A tibble: 15 × 5
           DateA B C D
         <dttm>    <dbl>  <dbl>  <dbl>  <dbl>
  1  2017-10-01  0.03000  0.050 -0.070 -0.014
  2  2017-09-01  0.02500  0.010 -0.050  0.040
  3  2017-08-01 -0.02000 -0.070  0.010  0.024
  4  2017-07-01  0.01500 -0.004  0.030 -0.010
  5  2017-06-01  0.00800 -0.007  0.050  0.064
  6  2017-05-01  0.04000  0.040  0.054  0.010
  7  2017-04-01  0.06000  0.050  0.068  0.080
  8  2017-03-01  0.00114  0.004  0.012  0.040
  9  2017-02-01  0.00058 -0.090  0.032  0.050
  10 2017-01-01 -0.00054  0.040  0.040  0.090
  11 2016-12-01  0.06000  0.060     NA  0.010
  12 2016-11-01  0.00400  0.010     NA     NA
  13 2016-10-01 -0.03000  0.020     NA     NA
  14 2016-09-01 -0.04000     NA     NA     NA
  15 2016-08-01  0.08000     NA     NA     NA

I'd like to create 12 more lagged variables by lagging the variables B, C, D by one period each (i.e Blag1, Clag1, Dlag1, Blag2, clag2....)

Once I have created the 12 lagged variables, I'd like to run a regression b/w A and the 15 variables (B,C,D and the 12 lagged variables)

I am currently lagging the variables in excel and then running a regression in R. The lag doesn't work as intended in R due to the NAs.

What's the most efficient way to run these (lag & regression) operations in R?

Lags in Excel:

答:
Here we go.

library(dplyr)

set.seed(1001)
df = data_frame(Date = as.Date(seq(17440,17014,length.out=15),origin="1970-01-01"),
                A = runif(15,-.1,.1),
                B = runif(15,-.1,.1),
                C = runif(15,-.1,.1),
                D = runif(15,-.1,.1)
)

df$B[14:15] = NA
df$C[11:15] = NA
df$D[12:15] = NA

genLag = function(df,col,lag){
  `[[`(df,paste0(col,"lag",lag)) = lead(`[[`(df,col),lag)
  assign("df",df,envir = globalenv())
}
for(col in LETTERS[2:4]){
  for(lag in 1:4){
    genLag(df,col,lag)
  }
}

model = lm(A~.,data=df[,names(df) != "Date"])
```

I had to generate some dummy data to match what you had, at least close.  Note I added the NA's the end of the columns like you have.

First, you don't want to lag your data, you want to lead your data.  Lagging takes x[t-1] and puts it in x[t].  However, because you data is in descending data order you need to put x[t+1] into x[t].  Data formatting is important.

Second, I don't see how doing the lag/lead work in Excel prevents the NA's from happening in R - those empty cells are still going to load in as NAs.

I wrote a function called genLag which takes as arguments your data.frame, the column you want to lag and how far you want to lag it.  This will create a new column in the data.frame which is named something like Blag1.  Then it assigns it back to the global environment, one giant side effect.

A couple of nested for loops to iterate over the column names and the lag distances and we have in 9 lines of code the creation of 12 new columns.

Finally, fitting the model is really easy.  In a formula statement you can use . to mean 'all other columns in the data'.  So, lm(A~.,data=df) will regress A against all 16 other columns.  Which is bad, you only want 15 columns - we need to drop the 'Date' column to make sure we don't have a 1:1 model situation.

The final model that is produced is utter garbage.  You only have 6 complete observations so you only have 5 degrees of freedom meaning 10 of your inputs are singularities.  I hope you have more real data in your dataset.

Body:
Here we go.

library(dplyr)

set.seed(1001)
df = data_frame(Date = as.Date(seq(17440,17014,length.out=15),origin="1970-01-01"),
                A = runif(15,-.1,.1),
                B = runif(15,-.1,.1),
                C = runif(15,-.1,.1),
                D = runif(15,-.1,.1)
)

df$B[14:15] = NA
df$C[11:15] = NA
df$D[12:15] = NA

genLag = function(df,col,lag){
  `[[`(df,paste0(col,"lag",lag)) = lead(`[[`(df,col),lag)
  assign("df",df,envir = globalenv())
}
for(col in LETTERS[2:4]){
  for(lag in 1:4){
    genLag(df,col,lag)
  }
}

model = lm(A~.,data=df[,names(df) != "Date"])

I had to generate some dummy data to match what you had, at least close.  Note I added the NA's the end of the columns like you have.

First, you don't want to lag your data, you want to lead your data.  Lagging takes x[t-1] and puts it in x[t].  However, because you data is in descending data order you need to put x[t+1] into x[t].  Data formatting is important.

Second, I don't see how doing the lag/lead work in Excel prevents the NA's from happening in R - those empty cells are still going to load in as NAs.

I wrote a function called genLag which takes as arguments your data.frame, the column you want to lag and how far you want to lag it.  This will create a new column in the data.frame which is named something like Blag1.  Then it assigns it back to the global environment, one giant side effect.

A couple of nested for loops to iterate over the column names and the lag distances and we have in 9 lines of code the creation of 12 new columns.

Finally, fitting the model is really easy.  In a formula statement you can use . to mean 'all other columns in the data'.  So, lm(A~.,data=df) will regress A against all 16 other columns.  Which is bad, you only want 15 columns - we need to drop the 'Date' column to make sure we don't have a 1:1 model situation.

The final model that is produced is utter garbage.  You only have 6 complete observations so you only have 5 degrees of freedom meaning 10 of your inputs are singularities.  I hope you have more real data in your dataset.


问:
Is this a thread-safe implementation of Singleton?
I read the Wikipeida's Singleton introduction, and wrote this Singleton class. Could there be any thread safety issue?

```<code> public class Engine {

    private static volatile Engine instance = null;
    private final Pipeline pipeline;

    private Engine() {
        pipeline = createEngine(SystemProperties.LANGUAGE);

    }

    public static Engine getInstance() {
        if (instance == null) {
            synchronized (Engine.class) {
                if (instance == null) {
                    instance = new Engine();
                }
            }
        }
        return instance;
    }

    private Pipeline createEngine(Constants.Language langauge) {
        Pipeline pipeline;
        if (langauge == Constants.Language.Chinese) {
            Properties props = IOUtils.readProperties("properties/chinese.properties");
            pipeline = new Pipeline(props);
        } else if (langauge == Constants.Language.English) {
            Properties props = IOUtils.readProperties("properties/english.properties");
            pipeline = new Pipeline(props);
        } else {
            throw new IllegalStateException("Unknow langauge not supported!");
        }
        return pipeline;
    }
}
</code>```

Client code to use it:

```<code>    private List<String> segment(String str) {

            Engine ENGINE = Engine.getInstance();
            List<String> tokens = new ArrayList<>();
             ...
            try {
                ENGINE.annotate(tokens);
            }catch(Exception e){
                log.warn("can't annotate this sentence:" + str);
            }
            ...

            return tokens;
        }
</code>```

答:
It is thread-safe in Java 5.0+ as described in the Wikipedia article.

It is important to know, that the volatile keyword actually makes it thread-safe. Java allows other threads to use partially constructed classes, and threads work with local copies of other thread's variables, which - in combination - can result in a situation where Thread B keeps working with a not yet fully initialized class from Thread A. The volatile keyword guarantees that this cannot happen, at a slightly increased performance cost.

Aside from that this way of lazy initialization is excessively complicated when compared to the simple (and completely thread-safe) implementation below, that relies on the guarantees of class loading:

```<code>public enum Singleton {
  INSTANCE;

  private Singleton() {
    // initialization of Singleton
  }
}
</code>```

Body:
I read the Wikipeida's Singleton introduction, and wrote this Singleton class. Could there be any thread safety issue?

 public class Engine {

    private static volatile Engine instance = null;
    private final Pipeline pipeline;

    private Engine() {
        pipeline = createEngine(SystemProperties.LANGUAGE);

    }

    public static Engine getInstance() {
        if (instance == null) {
            synchronized (Engine.class) {
                if (instance == null) {
                    instance = new Engine();
                }
            }
        }
        return instance;
    }

    private Pipeline createEngine(Constants.Language langauge) {
        Pipeline pipeline;
        if (langauge == Constants.Language.Chinese) {
            Properties props = IOUtils.readProperties("properties/chinese.properties");
            pipeline = new Pipeline(props);
        } else if (langauge == Constants.Language.English) {
            Properties props = IOUtils.readProperties("properties/english.properties");
            pipeline = new Pipeline(props);
        } else {
            throw new IllegalStateException("Unknow langauge not supported!");
        }
        return pipeline;
    }
}

Client code to use it:

    private List<String> segment(String str) {

            Engine ENGINE = Engine.getInstance();
            List<String> tokens = new ArrayList<>();
             ...
            try {
                ENGINE.annotate(tokens);
            }catch(Exception e){
                log.warn("can't annotate this sentence:" + str);
            }
            ...

            return tokens;
        }

Body:
It is thread-safe in Java 5.0+ as described in the Wikipedia article.

It is important to know, that the volatile keyword actually makes it thread-safe. Java allows other threads to use partially constructed classes, and threads work with local copies of other thread's variables, which - in combination - can result in a situation where Thread B keeps working with a not yet fully initialized class from Thread A. The volatile keyword guarantees that this cannot happen, at a slightly increased performance cost.

Aside from that this way of lazy initialization is excessively complicated when compared to the simple (and completely thread-safe) implementation below, that relies on the guarantees of class loading:

public enum Singleton {
  INSTANCE;

  private Singleton() {
    // initialization of Singleton
  }
}


问:
LINQ to entity, sort the subset of returned values
```<code>        var myView = await _context.foo
            .Include(p => p.subFoos)
            .SingleOrDefaultAsync(m => m.FooID == id);
</code>```

This code returns a row from the database and the linked sub rows held in the collection subFoos, what I'd like to do is order the collection rather than have them displayed in table order. I've got a field OrderBy but I can't figure out how to use it.

```<code>        var myView = await _context.foo
            .Include(p => p.subFoos)
                .OrderBy(x => x.OrderBy)
            .SingleOrDefaultAsync(m => m.FooID == id);
</code>```

This orders by the top level row, rather than the collection. How do I apply OrderBy to the collection.
Thanks

答:
Couldn't get any of the above to work so just retrieved the data using

```<code>var myView  = await _context.foo
.Include(p => p.subFoos)
.SingleOrDefaultAsync(m => m.FooID == id);
</code>```

then ordered the myView.subFoos by converting them to a List

```<code>myView.subFoos = myView.subFoos.ToList().OrderBy(x => x.OrderBy).ToList();
</code>```

Only one database call, works nicely.

Body:
        var myView = await _context.foo
            .Include(p => p.subFoos)
            .SingleOrDefaultAsync(m => m.FooID == id);

This code returns a row from the database and the linked sub rows held in the collection subFoos, what I'd like to do is order the collection rather than have them displayed in table order. I've got a field OrderBy but I can't figure out how to use it.

        var myView = await _context.foo
            .Include(p => p.subFoos)
                .OrderBy(x => x.OrderBy)
            .SingleOrDefaultAsync(m => m.FooID == id);

This orders by the top level row, rather than the collection. How do I apply OrderBy to the collection.
Thanks

Body:
Couldn't get any of the above to work so just retrieved the data using

var myView  = await _context.foo
.Include(p => p.subFoos)
.SingleOrDefaultAsync(m => m.FooID == id);

then ordered the myView.subFoos by converting them to a List

myView.subFoos = myView.subFoos.ToList().OrderBy(x => x.OrderBy).ToList();

Only one database call, works nicely.


问:
beeline not able to connect to hiveserver2
I have a CDH 5.3 instance.
I start the hive-server2 by first starting the hive-metastore and then the hive-server from command line.
After this I use beeline to connect to my hive-server2 but apparently it is not able to so.

```<code>Could not open connection to jdbc:hive2://localhost:10000: java.net.ConnectException: Connection refused (state=08S01,code=0)
</code>```

Another issue, I tried to see if the hive-server2 was listening on port 10000.
I did " sudo netstat -tulpn | grep :10000" but none of the applications came up.
I also added the following property in the hive-site.xml but to no avail. Why it doesn't show up on the netstat?

```<code><property>
   <name>hive.server2.thrift.port</name>
   <value>10000</value>
   <description>TCP port number to listen on, default 10000</description>
 </property>
</code>```

The connect command on beeline:

```<code>!connect jdbc:hive2://localhost:10000 org.apache.hive.jdbc.HiveDriver
</code>```

when asked for username and password, I just enter test "user" and "password"
for the respective values and then it throws the error.
Any help will be appreciated

答: you have to give hiveserver2 username and password check it in hive-site.xml by default username(anonymous) and password(anonymous) otherwise just give enter without giving password and username.</p>

Body:
I have a CDH 5.3 instance.
I start the hive-server2 by first starting the hive-metastore and then the hive-server from command line.
After this I use beeline to connect to my hive-server2 but apparently it is not able to so.

Could not open connection to jdbc:hive2://localhost:10000: java.net.ConnectException: Connection refused (state=08S01,code=0)

Another issue, I tried to see if the hive-server2 was listening on port 10000.
I did " sudo netstat -tulpn | grep :10000" but none of the applications came up.
I also added the following property in the hive-site.xml but to no avail. Why it doesn't show up on the netstat?

<property>
   <name>hive.server2.thrift.port</name>
   <value>10000</value>
   <description>TCP port number to listen on, default 10000</description>
 </property>

The connect command on beeline:

!connect jdbc:hive2://localhost:10000 org.apache.hive.jdbc.HiveDriver

when asked for username and password, I just enter test "user" and "password"
for the respective values and then it throws the error.
Any help will be appreciated


问:
align-items center does not work
I am trying to vertically center the h1 with the a's in the span but somehow the navigation buttons are a couple pixels higher than the h1. I have tried solving this but i couldn't find a way. So i'm hoping you maybe know what the problem could be.

h1 {
  font-family: sans-serif;
  font-size: 2em;
  font-weight: normal;
}

h1 a {
  text-decoration: none;
  color: black;
  font-size: 1em;
}

.nav {
  display: flex;
  justify-content: center;
}

.nav nav {
  width: 90%;
  height: 100px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="nav">
  <nav>
    <div>
      <h1>workout</h1>
    </div>
    <span>
      index
      pricing
      schedule
    </span>
  </nav>
</div></code>```

答:
Just remove .nav div styling for this. check updated snippet below..

h1{
  font-family: sans-serif;
  font-size:2em;
  font-weight:normal;

}
h1 a{
  text-decoration: none;
  color:black;
  font-size: 1em;
}
/*.nav{
  display: flex;
  justify-content: center;

}*/
.nav nav{
  width: 90%;
  height: 100px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="nav">
  <nav>
 <div>
   <h1>workout</h1>
 </div>
 <span>
   index
   pricing
   schedule
 </span>
  </nav>
</div></code>```

Title: align-items center does not work

Body:
I am trying to vertically center the h1 with the a's in the span but somehow the navigation buttons are a couple pixels higher than the h1. I have tried solving this but i couldn't find a way. So i'm hoping you maybe know what the problem could be.

h1 {
  font-family: sans-serif;
  font-size: 2em;
  font-weight: normal;
}

h1 a {
  text-decoration: none;
  color: black;
  font-size: 1em;
}

.nav {
  display: flex;
  justify-content: center;
}

.nav nav {
  width: 90%;
  height: 100px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

workout

      index
      pricing
      schedule

Body:
Just remove .nav div styling for this. check updated snippet below..

h1{
  font-family: sans-serif;
  font-size:2em;
  font-weight:normal;

}
h1 a{
  text-decoration: none;
  color:black;
  font-size: 1em;
}
/*.nav{
  display: flex;
  justify-content: center;

}*/
.nav nav{
  width: 90%;
  height: 100px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

<div class="nav">
  <nav>
 <div>
   <h1><a href="index.html">workout</a></h1>
 </div>
 <span>
   <a id='home' href="index.html">index</a>
   <a id='work' href="pricing.html">pricing</a>
   <a id='contact' href="schedule.html">schedule</a>
 </span>
  </nav>
</div>


问:
iOS app submission and beta review process
I'm currently developing an iOS application for a client. The submission review process to the store can often be a lengthy process and is relatively new to me.

My client wants to do a beta test using TestFlight as well as submitting the app to the app store afterwards, through XCode and Itunes Connect.

Scouring Apple's documentation I can't seem to get a good idea of following:

If I want to update an existing application on the store do I have to go through the review process again in full?

If I have my app approved for beta testing release through TestFlight, is this taken into consideration when submitting the app for review to the store?

If I want to test a new build through TestFlight, do I need to go through the beta review process again in full?

If an app is approved on the app store, does it automatically pass the beta review?

(This sounds counterintuitive considering you don't want to do a beta test after releasing to the store but in a scenario where you may want to do a closed release of an update for testing while a live version is up on the store)

答:
Update July 2019

TestFlight review times:

First upload build: takes 36h average.

Updates: take from 6h to 20h average for Build.

Weekends are off.

More information here:

IOS APP SUBMISSION AND BETA REVIEW PROCESS TIMES

ContentLicense: CC BY-SA 4.0


问:
LINQ syntax for CONTAINS method with an inclusive "filter"
This may seem a little "much", but this is picking at me!

Envision a form with a CheckBoxList that acts as an inclusive filter for a user.

This user fills out a form, checks off which items in the filter they want, and off they go.

I'm looking for a concise way to write the following LINQ statement:

If NO items are checked, show all results
else
Show results filtered by user selection

Is it possible (and if so, how) to write this without using a conditional statement that basically is the same query, but without the Contains method?

I tried putting a ternary operator in my Where clause, but the compiler didn't like it at all.

System.Collections.Generic.List catIds = new System.Collections.Generic.List();

```<code>              foreach (ListItem lstItemCategory in lstCategories.Items)
              {
                  if (lstItemCategory.Selected)
                  {
                      catIds.Add(Convert.ToInt64(lstItemCategory.Value));
                  }
              }

              var qry = from rategroup in rategroups
                        from rate in rategroup.Rates
                        orderby rate.RateClass.Id descending
                        select new
                        {
                            Category = rate.Product.ProductCategories[0].Category.Description,
                            rate.Product.Description,
                            Carrier = rate.CarrierName,
                            Id = rate.Product.ProductCategories[0].Id
                        };

              this.gvSchedule.DataSource = qry.Where(x => catIds.Contains(x.Id)).OrderBy(x => x.Category).ThenBy(x => x.Carrier).ToArray();
              this.gvSchedule.DataBind();
</code>```

答:
Why not just do:

```<code>var filteredQry = catIds.Any() ? qry.Where(x => catIds.Contains(x.Id)) : qry;
this.gvSchedule.DataSource = filteredQry.OrderBy(x => x.Category)
                                        .ThenBy(x => x.Carrier)
                                        .ToArray();
</code>```

Or:

```<code>if(catIds.Any())
    qry = qry.Where(x => catIds.Contains(x.Id));

this.gvSchedule.DataSource = qry.OrderBy(x => x.Category)
                                .ThenBy(x => x.Carrier)
                                .ToArray();
</code>```

You could also try using an Expression<Func<Foo, bool>> filter and assigning it to an 'always true' predicate or the genuine filter depending on the condition, but this will be slightly difficult since an anonymous type is involved.

Body:
This may seem a little "much", but this is picking at me!

Envision a form with a CheckBoxList that acts as an inclusive filter for a user.

This user fills out a form, checks off which items in the filter they want, and off they go.

I'm looking for a concise way to write the following LINQ statement:

If NO items are checked, show all results
else
Show results filtered by user selection

Is it possible (and if so, how) to write this without using a conditional statement that basically is the same query, but without the Contains method?

I tried putting a ternary operator in my Where clause, but the compiler didn't like it at all.

System.Collections.Generic.List catIds = new System.Collections.Generic.List();

              foreach (ListItem lstItemCategory in lstCategories.Items)
              {
                  if (lstItemCategory.Selected)
                  {
                      catIds.Add(Convert.ToInt64(lstItemCategory.Value));
                  }
              }

              var qry = from rategroup in rategroups
                        from rate in rategroup.Rates
                        orderby rate.RateClass.Id descending
                        select new
                        {
                            Category = rate.Product.ProductCategories[0].Category.Description,
                            rate.Product.Description,
                            Carrier = rate.CarrierName,
                            Id = rate.Product.ProductCategories[0].Id
                        };

              this.gvSchedule.DataSource = qry.Where(x => catIds.Contains(x.Id)).OrderBy(x => x.Category).ThenBy(x => x.Carrier).ToArray();
              this.gvSchedule.DataBind();

Body:
Why not just do:

var filteredQry = catIds.Any() ? qry.Where(x => catIds.Contains(x.Id)) : qry;
this.gvSchedule.DataSource = filteredQry.OrderBy(x => x.Category)
                                        .ThenBy(x => x.Carrier)
                                        .ToArray();

Or:

if(catIds.Any())
    qry = qry.Where(x => catIds.Contains(x.Id));

this.gvSchedule.DataSource = qry.OrderBy(x => x.Category)
                                .ThenBy(x => x.Carrier)
                                .ToArray();

You could also try using an Expression<Func<Foo, bool>> filter and assigning it to an 'always true' predicate or the genuine filter depending on the condition, but this will be slightly difficult since an anonymous type is involved.


问:
UIButton Function add Tap Style
I Have written a function in Swift 4 which creates a button that receives the UIButton, a Color and a String for the title. I would like to add to this function a highlight or tap style but I am not sure how.

The function:

```<code> func homeBtn(button: UIButton, color: UIColor, title: String){
    button.setTitle(title, for: .normal)
    button.setTitleColor(color, for: .normal)
    button.titleLabel?.font =  UIFont(name: "Raleway-Medium", size: 24)
    button.titleLabel?.lineBreakMode = .byWordWrapping
    button.titleLabel?.textAlignment = .center
    button.titleEdgeInsets = UIEdgeInsetsMake(20,20,20,20)
    button.layer.borderColor = color.cgColor
    button.layer.borderWidth = 2
    button.layer.cornerRadius = button.frame.width/2
    button.layer.backgroundColor = whiteColor.cgColor
 }
</code>```

The button is a circle and has a String centered in the middle with the UIColor being used as an outline. Can someone show me how to add a tap style to this function that uses the same UIColor to fill in the button and turn the text white please?

答:
For the title color you can easily do this without adding events.

```<code>button.setTitleColor(.white, for: .highlighted)
button.setTitleColor(.black, for: .normal)
</code>```

For the background color you need to define the following events:

```<code>    button.addTarget(self, action: #selector(touchDown(button:)), for: .touchDown)
    button.addTarget(self, action: #selector(touchUpInside(button:)), for: .touchUpInside)
</code>```

Define functions - You can refer additional touch types as well - see UIControlEvents

```<code>@objc func touchDown(button: UIButton) {
    guard let borderColor = button.layer.borderColor else {
        return
    }
    button.backgroundColor = UIColor(cgColor: borderColor)
}

@objc func touchUpInside(button: UIButton) {
    // Set backgroundColor for normal state...
}
</code>```

Title: UIButton Function add Tap Style

Body:
I Have written a function in Swift 4 which creates a button that receives the UIButton, a Color and a String for the title. I would like to add to this function a highlight or tap style but I am not sure how.

The function:

 func homeBtn(button: UIButton, color: UIColor, title: String){
    button.setTitle(title, for: .normal)
    button.setTitleColor(color, for: .normal)
    button.titleLabel?.font =  UIFont(name: "Raleway-Medium", size: 24)
    button.titleLabel?.lineBreakMode = .byWordWrapping
    button.titleLabel?.textAlignment = .center
    button.titleEdgeInsets = UIEdgeInsetsMake(20,20,20,20)
    button.layer.borderColor = color.cgColor
    button.layer.borderWidth = 2
    button.layer.cornerRadius = button.frame.width/2
    button.layer.backgroundColor = whiteColor.cgColor
 }

The button is a circle and has a String centered in the middle with the UIColor being used as an outline. Can someone show me how to add a tap style to this function that uses the same UIColor to fill in the button and turn the text white please?

Body:
For the title color you can easily do this without adding events.

button.setTitleColor(.white, for: .highlighted)
button.setTitleColor(.black, for: .normal)

For the background color you need to define the following events:

    button.addTarget(self, action: #selector(touchDown(button:)), for: .touchDown)
    button.addTarget(self, action: #selector(touchUpInside(button:)), for: .touchUpInside)

Define functions - You can refer additional touch types as well - see UIControlEvents

@objc func touchDown(button: UIButton) {
    guard let borderColor = button.layer.borderColor else {
        return
    }
    button.backgroundColor = UIColor(cgColor: borderColor)
}

@objc func touchUpInside(button: UIButton) {
    // Set backgroundColor for normal state...
}


问:
PostgreSQL how to update only the Year part of the date
I have a table in PostgreSQL.
This table has a months column and a mydate column.
The months has a value of Jan the mydate has a value of 2017-01-01

I want to update that value to 2018-01-01 but I don't want to have to do it by hard coding in the 2018 date. I would like to use a date_part function but I am not sure if I am approaching this correctly.

Here is what I have so far it is not complete I am stuck on what I need to finish this query:

```<code>UPDATE tblshopstatus
Set mydate = mydate + date_part('year') -----I am stuck on this line----
WHERE months = 'Jan'
</code>```

More examples:

In the months column I have all 12 months listed.

In the mydate column I have dates listed as 2017-01-01, 2017-02-01 etc... through the 12 months.

Is there a way to just increase the year to 2018 for all months.

答:
```<code>set mydate = mydate + interval '1 year'
</code>```

Body:
I have a table in PostgreSQL.
This table has a months column and a mydate column.
The months has a value of Jan the mydate has a value of 2017-01-01

I want to update that value to 2018-01-01 but I don't want to have to do it by hard coding in the 2018 date. I would like to use a date_part function but I am not sure if I am approaching this correctly.

Here is what I have so far it is not complete I am stuck on what I need to finish this query:

UPDATE tblshopstatus
Set mydate = mydate + date_part('year') -----I am stuck on this line----
WHERE months = 'Jan'

More examples:

In the months column I have all 12 months listed.

In the mydate column I have dates listed as 2017-01-01, 2017-02-01 etc... through the 12 months.

Is there a way to just increase the year to 2018 for all months.

Body: set mydate = mydate + interval '1 year'


问:
How to write a List of string arrays to txt file
Is it possible to write a List of string arrays to txt file?

This is my code and I'm not sure how to make the final step. I made a list through which I foreach based on the number the user inputs, and it returns all the values correctly, but I can't seem to be able to save all the data to a txt file.

```<code> static void Main(string[] args)
    {
        Console.WriteLine("Unesi broj:");

        int userNumber = Convert.ToInt32(Console.ReadLine());

        var numberLIst = Enumerable.Range(1,userNumber).ToList();

        string path = @"C:\Users\mcrnic\Desktop\scriptFolder\input.txt";

        List<string[]> listaStringova = new List<string[]>();

        int n = 0;

        foreach (var data in numberLIst)
        {

            n++;

            #region Varijable
            var textBoxNumberRangeFirst = "tbxNumberRangeFirstInput" + data;
            var textBoxNumberRangeSecond = "tbxNumberRangeSecondInput" + data;
            var textBoxNumberRangeThird = "tbxNumberRangeThirdInput" + data;
            var textBoxHomeNumbersFirst = "tbxRangeOfHomeNumbersFirstInput" + data;
            var textBoxHomeNumbersSecond = "tbxRangeOfHomeNumbersSecondInput" + data;
            var textBoxVPNFirst = "tbxRangeOfShortVPNNumbersFirstInput" + data;
            var textBoxVPNSecond = "tbxRangeOfShortVPNNumbersSecondInput" + data;
            var checkBoxNumberTransfer = "cbxNumberTransfer" + data;
            var checkBoxSecretNumber = "cbxSecretNumber" + data;
            var checkBoxSearchByNumber = "cbxSearchByNumber" + data;
            var checkBoxZ1 = "cbxZ1_" + data;
            var checkBoxZ2 = "cbxZ2_" + data;
            var checkBoxZ3 = "cbxZ3_" + data;
            var checkBoxZ4 = "cbxZ4_" + data;
            var checkBoxZ5 = "cbxZ5_" + data;
            var checkBoxZ6 = "cbxZ6_" + data;
            var checkBoxZ7 = "cbxZ7_" + data;
            #endregion

            string[] htmlLinije = {"<%-- Row" + n + " --%>",
                                "<div class=&row rowFullWidth form-inline pb10& hidden>",
                                "<div class=&col-sm-4&>",
                                "<asp:TextBox runat=&server& ID=&" + textBoxNumberRangeFirst + "& class=&form-control textbox-width-25 ml10& ReadOnly=&true& />",
                                "<span class=&pr5 pl5&>/</span><asp:TextBox runat=&server& ID=&" + textBoxNumberRangeSecond +"& class=&form-control textbox-width-25& ReadOnly=&true&/>",
                                "<span class=&pr5 pl5&>-</span><asp:TextBox runat=&server& ID=&" + textBoxHomeNumbersSecond + "& class=&form-control textbox-width-25& ReadOnly=&true&/>",
                                "</div>",
                                "<div class=&col-sm-2&>",
                                "<asp:CheckBox runat=&server& ID=&" + checkBoxNumberTransfer + "& AutoPostBack=&false& CssClass=&checkbox pl20 pr15 pt5& Enabled=&false&/>",
                                "<asp:CheckBox runat=&server& ID=&" + checkBoxSecretNumber + "& AutoPostBack=&false& CssClass=&checkbox pl20 pr15 pt5& Enabled=&false&/>",
                                "<asp:CheckBox runat=&server& ID=&" + checkBoxSearchByNumber + "& AutoPostBack=&false& CssClass=&checkbox pl20 pr15 pt5& Enabled=&false& />",
                                "</div>",
                                "<div class=&col-sm-2&>",
                                "<asp:TextBox runat=&server& ID=&" + textBoxHomeNumbersFirst + "& class=&form-control textbox-width-40& ReadOnly=&true& /><span class=&pr10 pl10&>-</span>",
                                "<asp:TextBox runat=&server& ID=&" + textBoxHomeNumbersSecond + "& class=&form-control textbox-width-40& ReadOnly=&true& />",
                                "</div>",
                                "<div class=&col-sm-2&>",
                                "<asp:TextBox runat=&server& ID=&" + textBoxVPNFirst + "& class=&form-control textbox-width-40& ReadOnly=&true& /><span class=&pr10 pl10&>-</span>",
                                "<asp:TextBox runat=&server& ID=&" + textBoxVPNSecond + "& class=&form-control textbox-width-40& ReadOnly=&true& />",
                                "</div>",
                                "<div class=&col-sm-2&>",
                                "<div class=&pt5&>",
                                "<asp:CheckBox runat=&server& ID=&" + checkBoxZ1 + "& AutoPostBack=&false& CssClass=&checkbox pr5& Enabled=&false& />",
                                "<asp:CheckBox runat=&server& ID=&" + checkBoxZ2 + "& AutoPostBack=&false& CssClass=&checkbox pr5& Enabled=&false& />",
                                "<asp:CheckBox runat=&server& ID=&" + checkBoxZ3 + "& AutoPostBack=&false& CssClass=&checkbox pr5& Enabled=&false& />",
                                "<asp:CheckBox runat=&server& ID=&" + checkBoxZ4 + "& AutoPostBack=&false& CssClass=&checkbox pr5& Enabled=&false& />",
                                "<asp:CheckBox runat=&server& ID=&" + checkBoxZ5 + "& AutoPostBack=&false& CssClass=&checkbox pr5& Enabled=&false& />",
                                "<asp:CheckBox runat=&server& ID=&" + checkBoxZ6 + "& AutoPostBack=&false& CssClass=&checkbox pr5& Enabled=&false& />",
                                "<asp:CheckBox runat=&server& ID=&" + checkBoxZ7 + "& AutoPostBack=&false& CssClass=&checkbox pr5& Enabled=&false& />",
                                "</div>",
                                "</div>",
                                "</div>",
                                ""
            };

            listaStringova.Add(htmlLinije);
        }

        System.IO.File.WriteAllLines(path, listaStringova);

    }
</code>```

I get this error when I try to WriteAllLines:

Error CS1503  Argument 2: cannot convert from System.Collections.Generic.List to string[]

答: You're trying to WriteAllLines for the List, not the string[]. Per MSDN, the only overload for WriteAllLines takes IEnumerable<String>, NOT IEnumerable<String[]>. Further, you should make proper use of the StringBuilder class, and then do a WriteAllText. This would help you tremendously.

Body:
Is it possible to write a List of string arrays to txt file?

This is my code and I'm not sure how to make the final step. I made a list through which I foreach based on the number the user inputs, and it returns all the values correctly, but I can't seem to be able to save all the data to a txt file.

 static void Main(string[] args)
    {
        Console.WriteLine("Unesi broj:");

        int userNumber = Convert.ToInt32(Console.ReadLine());

        var numberLIst = Enumerable.Range(1,userNumber).ToList();

        string path = @"C:\Users\mcrnic\Desktop\scriptFolder\input.txt";

        List<string[]> listaStringova = new List<string[]>();

        int n = 0;

        foreach (var data in numberLIst)
        {

            n++;

            #region Varijable
            var textBoxNumberRangeFirst = "tbxNumberRangeFirstInput" + data;
            var textBoxNumberRangeSecond = "tbxNumberRangeSecondInput" + data;
            var textBoxNumberRangeThird = "tbxNumberRangeThirdInput" + data;
            var textBoxHomeNumbersFirst = "tbxRangeOfHomeNumbersFirstInput" + data;
            var textBoxHomeNumbersSecond = "tbxRangeOfHomeNumbersSecondInput" + data;
            var textBoxVPNFirst = "tbxRangeOfShortVPNNumbersFirstInput" + data;
            var textBoxVPNSecond = "tbxRangeOfShortVPNNumbersSecondInput" + data;
            var checkBoxNumberTransfer = "cbxNumberTransfer" + data;
            var checkBoxSecretNumber = "cbxSecretNumber" + data;
            var checkBoxSearchByNumber = "cbxSearchByNumber" + data;
            var checkBoxZ1 = "cbxZ1_" + data;
            var checkBoxZ2 = "cbxZ2_" + data;
            var checkBoxZ3 = "cbxZ3_" + data;
            var checkBoxZ4 = "cbxZ4_" + data;
            var checkBoxZ5 = "cbxZ5_" + data;
            var checkBoxZ6 = "cbxZ6_" + data;
            var checkBoxZ7 = "cbxZ7_" + data;
            #endregion

            string[] htmlLinije = {"<%-- Row" + n + " --%>",
                                "
",
                                "
",
                                "<asp:TextBox runat=&server& ID=&" + textBoxNumberRangeFirst + "& class=&form-control textbox-width-25 ml10& ReadOnly=&true& />",
                                "/<asp:TextBox runat=&server& ID=&" + textBoxNumberRangeSecond +"& class=&form-control textbox-width-25& ReadOnly=&true&/>",
                                "-<asp:TextBox runat=&server& ID=&" + textBoxHomeNumbersSecond + "& class=&form-control textbox-width-25& ReadOnly=&true&/>",
                                "
",
                                "
",
                                "<asp:CheckBox runat=&server& ID=&" + checkBoxNumberTransfer + "& AutoPostBack=&false& CssClass=&checkbox pl20 pr15 pt5& Enabled=&false&/>",
                                "<asp:CheckBox runat=&server& ID=&" + checkBoxSecretNumber + "& AutoPostBack=&false& CssClass=&checkbox pl20 pr15 pt5& Enabled=&false&/>",
                                "<asp:CheckBox runat=&server& ID=&" + checkBoxSearchByNumber + "& AutoPostBack=&false& CssClass=&checkbox pl20 pr15 pt5& Enabled=&false& />",
                                "
",
                                "
",
                                "<asp:TextBox runat=&server& ID=&" + textBoxHomeNumbersFirst + "& class=&form-control textbox-width-40& ReadOnly=&true& />-",
                                "<asp:TextBox runat=&server& ID=&" + textBoxHomeNumbersSecond + "& class=&form-control textbox-width-40& ReadOnly=&true& />",
                                "
",
                                "
",
                                "<asp:TextBox runat=&server& ID=&" + textBoxVPNFirst + "& class=&form-control textbox-width-40& ReadOnly=&true& />-",
                                "<asp:TextBox runat=&server& ID=&" + textBoxVPNSecond + "& class=&form-control textbox-width-40& ReadOnly=&true& />",
                                "
",
                                "
",
                                "
",
                                "<asp:CheckBox runat=&server& ID=&" + checkBoxZ1 + "& AutoPostBack=&false& CssClass=&checkbox pr5& Enabled=&false& />",
                                "<asp:CheckBox runat=&server& ID=&" + checkBoxZ2 + "& AutoPostBack=&false& CssClass=&checkbox pr5& Enabled=&false& />",
                                "<asp:CheckBox runat=&server& ID=&" + checkBoxZ3 + "& AutoPostBack=&false& CssClass=&checkbox pr5& Enabled=&false& />",
                                "<asp:CheckBox runat=&server& ID=&" + checkBoxZ4 + "& AutoPostBack=&false& CssClass=&checkbox pr5& Enabled=&false& />",
                                "<asp:CheckBox runat=&server& ID=&" + checkBoxZ5 + "& AutoPostBack=&false& CssClass=&checkbox pr5& Enabled=&false& />",
                                "<asp:CheckBox runat=&server& ID=&" + checkBoxZ6 + "& AutoPostBack=&false& CssClass=&checkbox pr5& Enabled=&false& />",
                                "<asp:CheckBox runat=&server& ID=&" + checkBoxZ7 + "& AutoPostBack=&false& CssClass=&checkbox pr5& Enabled=&false& />",
                                "
",
                                "
",
                                "
",
                                ""
            };

            listaStringova.Add(htmlLinije);
        }

        System.IO.File.WriteAllLines(path, listaStringova);

    }

I get this error when I try to WriteAllLines:

Error CS1503  Argument 2: cannot convert from System.Collections.Generic.List to string[]


问:
Firebase: How to get User.uid?
I'm using Firebaseauth to manage users and data for my iOS app. The users can log in, and their userinfo is stored correct in the database.
But when I try to get the users to write to the database in a different viewController, using this string:

```<code>self.ref.child("users").child(user.uid).setValue(["username": username])
</code>```

The thrown error is

Type user has no member .uid

That makes sense I guess, since I haven't created the variable. But I can't figure out how to declare it?

答:
FIRAuth has actually been renamed to Auth. So, as per the latest changes, it will be

```<code>let userID = Auth.auth().currentUser!.uid
</code>```

Edit.

As pointed out in comments, A force unwrap may crash the app.

```<code>guard let userID = Auth.auth().currentUser?.uid else { return }
</code>```

Title: Firebase: How to get User.uid?

Body:
I'm using Firebaseauth to manage users and data for my iOS app. The users can log in, and their userinfo is stored correct in the database.
But when I try to get the users to write to the database in a different viewController, using this string:

self.ref.child("users").child(user.uid).setValue(["username": username])

The thrown error is

Type user has no member .uid

That makes sense I guess, since I haven't created the variable. But I can't figure out how to declare it?

Body:
FIRAuth has actually been renamed to Auth. So, as per the latest changes, it will be

let userID = Auth.auth().currentUser!.uid

Edit.

As pointed out in comments, A force unwrap may crash the app.

guard let userID = Auth.auth().currentUser?.uid else { return }


问:
Background-image: not showing in CSS
I'm having a problem with getting a background-image to show within a flexbox. Whenever I enter it manually in the HTML it shows the image, however... When I try to load it as background-image: url("imagepath") it won't load.

This is the CSS:

```<code>* {
  box-sizing: border-box;
}

/*Style van overall body*/

body {
  margin: 0;
  background-color: #f3f3f3;
  color: white;
}

/*Style voor h2 tekst*/

h2 {}

/* Style the header */

.header {
  background-color: #999999;
  padding: 50px;
  text-align: center;
}

/* Container for flexboxes */

.row {
  display: -webkit-flex;
  display: flex;
}

.contentrow {
  display: -webkit-flex;
  display: flex;
}

/* 3 middelse columns (Grootte wordt bepaald in html doc (Standaard: Flex-Grow: 4;)) */

.column {
  -webkit-flex: 1;
  -ms-flex: 1;
  flex: 1;
  padding: 0px;
  text-align: center;
}
.newsboxtop{
  -webkit-flex: 1;
  -ms-flex: 1;
  flex: 1;
  border: 3px;
  background: url("images/Lightgraydient75x30.png");
  text-align: center;
  height: 30px;
}

.middlemenu {
  -webkit-flex: 1;
  -ms-flex: 1;
  flex: 1;
  padding: 0px;
  height: 50px;
  text-align: center;
  margin: 0px;
}

/* Container for newsboxes */

.newsrow {
  display: -webkit-flex;
  display: flex;
}

.newsbox {
  -webkit-flex: 1;
  -ms-flex: 1;
  flex: 1;
  margin-top: 30px;
  margin-left: 30px;
  margin-right: 30px;
  margin-bottom: 30px;
  min-width: 200px;
  height: 225px;
  text-align: center;
  background-color: #999999;

}

/* Style van de footer. */

.footer {
  background-color: #999999;
  padding: 10px;
  text-align: center;
}

/* Zorgt ervoor dat bij het krimpen de flexboxes stapelen i.p.v. naast elkaar blijven staan.*/

@media (max-width: 1280px) {
  .row {
    -webkit-flex-direction: column;
    flex-direction: column;
  }
}

  @media (max-width: 1500px){
  .newsrow {
    -webkit-flex-direction: column;
    flex-direction: column;
  }
}
</code>```

And this is the HTML:

```<code><!DOCTYPE html>
<html lang="en">
<head>
<title>CSS Template</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>

<div class="header">
  <h2>234234</h2>
</div>

<div class="row">
  <div class="column" style="background-color:#444; padding: 10px;">1337 WHEH</div>
  <div class="column" style="background-color:#555; flex-grow: 4;">
    <div class="middlemenu" style="background-color:#777">
      <!--Hier komt menu content-->
    </div>
    <div class="newsrow">
      <div class="newsbox">
        <div class="newsboxtop">
            <!--////////////////////////////////////////////////////-->
            <!-- images/Lightgraydient75x30.png This is for testing -->
            <!--////////////////////////////////////////////////////-->
            asd
        </div>
      </div>
      <div class="newsbox">
        <div class="newsboxtop">
            dfg
        </div>
      </div>
      <div class="newsbox">
        <div class="newsboxtop">
            ghj
        </div>
      </div>
    </div>
  </div>
  <div class="column" style="background-color:#666; padding: 10px;">1337 WHEEEH</div>
</div>
<div class="footer">
  <p>Footer</p>
</div>

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

Please let me know if I'm overlooking something, or if I'm using CSS the wrong way, thank you so much.

答:
Have you tried </p>

```<code>background: url("../images/Lightgraydient75x30.png");
</code>```

Title: Background-image: not showing in CSS

Body:
I'm having a problem with getting a background-image to show within a flexbox. Whenever I enter it manually in the HTML it shows the image, however... When I try to load it as background-image: url("imagepath") it won't load.

This is the CSS:

* {
  box-sizing: border-box;
}

/*Style van overall body*/

body {
  margin: 0;
  background-color: #f3f3f3;
  color: white;
}

/*Style voor h2 tekst*/

h2 {}

/* Style the header */

.header {
  background-color: #999999;
  padding: 50px;
  text-align: center;
}

/* Container for flexboxes */

.row {
  display: -webkit-flex;
  display: flex;
}

.contentrow {
  display: -webkit-flex;
  display: flex;
}

/* 3 middelse columns (Grootte wordt bepaald in html doc (Standaard: Flex-Grow: 4;)) */

.column {
  -webkit-flex: 1;
  -ms-flex: 1;
  flex: 1;
  padding: 0px;
  text-align: center;
}
.newsboxtop{
  -webkit-flex: 1;
  -ms-flex: 1;
  flex: 1;
  border: 3px;
  background: url("images/Lightgraydient75x30.png");
  text-align: center;
  height: 30px;
}

.middlemenu {
  -webkit-flex: 1;
  -ms-flex: 1;
  flex: 1;
  padding: 0px;
  height: 50px;
  text-align: center;
  margin: 0px;
}

/* Container for newsboxes */

.newsrow {
  display: -webkit-flex;
  display: flex;
}

.newsbox {
  -webkit-flex: 1;
  -ms-flex: 1;
  flex: 1;
  margin-top: 30px;
  margin-left: 30px;
  margin-right: 30px;
  margin-bottom: 30px;
  min-width: 200px;
  height: 225px;
  text-align: center;
  background-color: #999999;

}

/* Style van de footer. */

.footer {
  background-color: #999999;
  padding: 10px;
  text-align: center;
}

/* Zorgt ervoor dat bij het krimpen de flexboxes stapelen i.p.v. naast elkaar blijven staan.*/

@media (max-width: 1280px) {
  .row {
    -webkit-flex-direction: column;
    flex-direction: column;
  }
}

  @media (max-width: 1500px){
  .newsrow {
    -webkit-flex-direction: column;
    flex-direction: column;
  }
}

And this is the HTML:

<!DOCTYPE html>

<title>CSS Template</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" href="css/style.css">

234234

1337 WHEH

            asd

            dfg

            ghj

1337 WHEEEH

Footer

Please let me know if I'm overlooking something, or if I'm using CSS the wrong way, thank you so much.

Body:
Have you tried

background: url("../images/Lightgraydient75x30.png");


问:
Why the Retrofit response gives null value for fields, while the response can get the object?
I'm just making a simple application in Android Studio 2.3 to get a JSON response from the Web app. I chose Retrofit 2.0 for consuming the response.

It seems I could get the   objects inside onResponse

```<code>Object item =  response.body().get(1);
Log.e("success", String.valueOf(item));
</code>```

inside logcat it gives a success,

```<code>success:com.makemyapp.firstapplication.Item@67205ae
</code>```

But when tried to fetch the fields inside the object,

```<code>Object item =  response.body().get(1).getItemDescription();
Log.e("success", String.valueOf(item));
</code>```

It returns a null

```<code>success: null
</code>```

This is the Interface- GrocsApi,

```<code>package com.makemyapp.firstapplication;
import java.util.List;
import retrofit2.Call;
import retrofit2.http.GET;

public interface GrocsApi {

    @GET("api/getitemlist")
    Call<List<Item>> getItem();

}
</code>```

Class for returning service- GrocsService

```<code>package com.makemyapp.firstapplication;

import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class GrocsService {

    public  static GrocsApi service;
    public static String BASE_URL = "http://10.0.2.2:8000/";

    public static GrocsApi getGrocsService(){
        if (service==null){

            Retrofit retrofit= new Retrofit.Builder()
                              .baseUrl(BASE_URL)
                              .addConverterFactory(GsonConverterFactory.create())
                              .build();
            service = retrofit.create(GrocsApi.class);

            return service;
        }

return  service;
    }

}
</code>```

MainActivity.java ,where Request Call is initiated,

```<code>package com.makemyapp.firstapplication;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MainActivity extends AppCompatActivity {

    Button button;
    //TextView textView; for later use

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        onClickGetData();
    }

    public void onClickGetData(){

      //  textView=(TextView)findViewById(R.id.textView); for later use
        button=(Button)findViewById(R.id.button);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
  Call<List<Item>> call =   GrocsService.getGrocsService().getItem();

           call.enqueue(new Callback<List<Item>>  () {
                  @Override
                  public void onResponse(Call<List<Item>>  call, Response<List<Item>>   response) {

 if(response.isSuccessful()) {
     Object item =  response.body().get(1).getItemDescription();

     Log.e("success", String.valueOf(item));

 } else{
     Log.e("response is not good", "");
 }
                  }

                  @Override
                  public void onFailure(Call<List<Item>>   call, Throwable t) {

                      Log.e("failed", t.getMessage());

                  }
              });

            }

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

This is my POJO class- Item

```<code>package com.makemyapp.firstapplication;

public class Item {

    private Integer itemId;
    private Object itemName;
    private Object itemDescription;
    private Object itemPhotoUrl;
    private Object itemWikipediaLink;
    private Object itemTag;

    public Integer getItemId() {
        return itemId;
    }

    public void setItemId(Integer itemId) {
        this.itemId = itemId;
    }

    public Object getItemName() {
        return itemName;
    }

    public void setItemName(Object itemName) {
        this.itemName = itemName;
    }

    public Object getItemDescription() {
        return itemDescription;
    }

    public void setItemDescription(Object itemDescription) {
        this.itemDescription = itemDescription;
    }

    public Object getItemPhotoUrl() {
        return itemPhotoUrl;
    }

    public void setItemPhotoUrl(Object itemPhotoUrl) {
        this.itemPhotoUrl = itemPhotoUrl;
    }

    public Object getItemWikipediaLink() {
        return itemWikipediaLink;
    }

    public void setItemWikipediaLink(Object itemWikipediaLink) {
        this.itemWikipediaLink = itemWikipediaLink;
    }

    public Object getItemTag() {
        return itemTag;
    }

    public void setItemTag(Object itemTag) {
        this.itemTag = itemTag;
    }

}
</code>```

And the JSON response is ,

```<code>[{"ItemId":1,"ItemName":"Orange","ItemDescription":"Sweet and Juicy","ItemPhotoUrl":"https:\/\/en.wikipedia.org\/wiki\/Orange_(fruit)","ItemWikipediaLink":"'https:\/\/en.wikipedia.org\/wiki\/Orange_(fruit)#\/media\/File:Orange-Whole-%26-Split.jpg","ItemTag":"RS.70 per kg"},{"ItemId":3,"ItemName":"Apple","ItemDescription":"Reddish","ItemPhotoUrl":"https:\/\/en.wikipedia.org\/wiki\/Apple","ItemWikipediaLink":"https:\/\/en.wikipedia.org\/wiki\/Apple#\/media\/File:Red_Apple.jpg","ItemTag":"RS.10 per kg"},{"ItemId":4,"ItemName":"Mango","ItemDescription":"Fresh","ItemPhotoUrl":"https:\/\/en.wikipedia.org\/wiki\/Mango#\/media\/File:Mangoes_pic.jpg","ItemWikipediaLink":"https:\/\/en.wikipedia.org\/wiki\/Mango","ItemTag":"RS.100 per kg"},{"ItemId":5,"ItemName":"Pineapple","ItemDescription":"Large and Juicy","ItemPhotoUrl":"https:\/\/en.wikipedia.org\/wiki\/Pineapple#\/media\/File:Pineapple_and_cross_section.jpg","ItemWikipediaLink":"https:\/\/en.wikipedia.org\/wiki\/Pineapple","ItemTag":"RS.50 per kg"},{"ItemId":6,"ItemName":"Grapes","ItemDescription":"Dark and Juicy","ItemPhotoUrl":"https:\/\/en.wikipedia.org\/wiki\/Grape#\/media\/File:Abhar-iran.JPG","ItemWikipediaLink":"https:\/\/en.wikipedia.org\/wiki\/Grape","ItemTag":"110 per kg"},{"ItemId":7,"ItemName":"Guava","ItemDescription":"Green","ItemPhotoUrl":null,"ItemWikipediaLink":null,"ItemTag":"50 per kg"},{"ItemId":8,"ItemName":null,"ItemDescription":null,"ItemPhotoUrl":null,"ItemWikipediaLink":null,"ItemTag":null}]
</code>```

Could any one spot a light on my problem?

答: Your variable is : "itemDescription" but your json response is 'ItemDescription" , you should consider that the parser is case-sensitive.</p>

Body:
I'm just making a simple application in Android Studio 2.3 to get a JSON response from the Web app. I chose Retrofit 2.0 for consuming the response.

It seems I could get the   objects inside onResponse

Object item =  response.body().get(1);
Log.e("success", String.valueOf(item));

inside logcat it gives a success,

success:com.makemyapp.firstapplication.Item@67205ae

But when tried to fetch the fields inside the object,

Object item =  response.body().get(1).getItemDescription();
Log.e("success", String.valueOf(item));

It returns a null

success: null

This is the Interface- GrocsApi,

package com.makemyapp.firstapplication;
import java.util.List;
import retrofit2.Call;
import retrofit2.http.GET;

public interface GrocsApi {

    @GET("api/getitemlist")
    Call<List<Item>> getItem();

}

Class for returning service- GrocsService

package com.makemyapp.firstapplication;

import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class GrocsService {

    public  static GrocsApi service;
    public static String BASE_URL = "http://10.0.2.2:8000/";

    public static GrocsApi getGrocsService(){
        if (service==null){

            Retrofit retrofit= new Retrofit.Builder()
                              .baseUrl(BASE_URL)
                              .addConverterFactory(GsonConverterFactory.create())
                              .build();
            service = retrofit.create(GrocsApi.class);

            return service;
        }

return  service;
    }

}

MainActivity.java ,where Request Call is initiated,

package com.makemyapp.firstapplication;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MainActivity extends AppCompatActivity {

    Button button;
    //TextView textView; for later use

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        onClickGetData();
    }

    public void onClickGetData(){

      //  textView=(TextView)findViewById(R.id.textView); for later use
        button=(Button)findViewById(R.id.button);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
  Call<List<Item>> call =   GrocsService.getGrocsService().getItem();

           call.enqueue(new Callback<List<Item>>  () {
                  @Override
                  public void onResponse(Call<List<Item>>  call, Response<List<Item>>   response) {

 if(response.isSuccessful()) {
     Object item =  response.body().get(1).getItemDescription();

     Log.e("success", String.valueOf(item));

 } else{
     Log.e("response is not good", "");
 }
                  }

                  @Override
                  public void onFailure(Call<List<Item>>   call, Throwable t) {

                      Log.e("failed", t.getMessage());

                  }
              });

            }

        }
    );
}
}

This is my POJO class- Item

package com.makemyapp.firstapplication;

public class Item {

    private Integer itemId;
    private Object itemName;
    private Object itemDescription;
    private Object itemPhotoUrl;
    private Object itemWikipediaLink;
    private Object itemTag;

    public Integer getItemId() {
        return itemId;
    }

    public void setItemId(Integer itemId) {
        this.itemId = itemId;
    }

    public Object getItemName() {
        return itemName;
    }

    public void setItemName(Object itemName) {
        this.itemName = itemName;
    }

    public Object getItemDescription() {
        return itemDescription;
    }

    public void setItemDescription(Object itemDescription) {
        this.itemDescription = itemDescription;
    }

    public Object getItemPhotoUrl() {
        return itemPhotoUrl;
    }

    public void setItemPhotoUrl(Object itemPhotoUrl) {
        this.itemPhotoUrl = itemPhotoUrl;
    }

    public Object getItemWikipediaLink() {
        return itemWikipediaLink;
    }

    public void setItemWikipediaLink(Object itemWikipediaLink) {
        this.itemWikipediaLink = itemWikipediaLink;
    }

    public Object getItemTag() {
        return itemTag;
    }

    public void setItemTag(Object itemTag) {
        this.itemTag = itemTag;
    }

}

And the JSON response is ,

[{"ItemId":1,"ItemName":"Orange","ItemDescription":"Sweet and Juicy","ItemPhotoUrl":"https:\/\/en.wikipedia.org\/wiki\/Orange_(fruit)","ItemWikipediaLink":"'https:\/\/en.wikipedia.org\/wiki\/Orange_(fruit)#\/media\/File:Orange-Whole-%26-Split.jpg","ItemTag":"RS.70 per kg"},{"ItemId":3,"ItemName":"Apple","ItemDescription":"Reddish","ItemPhotoUrl":"https:\/\/en.wikipedia.org\/wiki\/Apple","ItemWikipediaLink":"https:\/\/en.wikipedia.org\/wiki\/Apple#\/media\/File:Red_Apple.jpg","ItemTag":"RS.10 per kg"},{"ItemId":4,"ItemName":"Mango","ItemDescription":"Fresh","ItemPhotoUrl":"https:\/\/en.wikipedia.org\/wiki\/Mango#\/media\/File:Mangoes_pic.jpg","ItemWikipediaLink":"https:\/\/en.wikipedia.org\/wiki\/Mango","ItemTag":"RS.100 per kg"},{"ItemId":5,"ItemName":"Pineapple","ItemDescription":"Large and Juicy","ItemPhotoUrl":"https:\/\/en.wikipedia.org\/wiki\/Pineapple#\/media\/File:Pineapple_and_cross_section.jpg","ItemWikipediaLink":"https:\/\/en.wikipedia.org\/wiki\/Pineapple","ItemTag":"RS.50 per kg"},{"ItemId":6,"ItemName":"Grapes","ItemDescription":"Dark and Juicy","ItemPhotoUrl":"https:\/\/en.wikipedia.org\/wiki\/Grape#\/media\/File:Abhar-iran.JPG","ItemWikipediaLink":"https:\/\/en.wikipedia.org\/wiki\/Grape","ItemTag":"110 per kg"},{"ItemId":7,"ItemName":"Guava","ItemDescription":"Green","ItemPhotoUrl":null,"ItemWikipediaLink":null,"ItemTag":"50 per kg"},{"ItemId":8,"ItemName":null,"ItemDescription":null,"ItemPhotoUrl":null,"ItemWikipediaLink":null,"ItemTag":null}]

Could any one spot a light on my problem?


问:
Set word document properties programmatically from c#
I'm trying to set the the Paper source of an existing .docx file from my C# code. I don't know if
1. Word is installed on the computer,
2. Word format is OpenXML or not (that depend's on the computer's installation as far as I understood).

I've found two approaches :
- using Interop as described here, with following properties,
- using OpenXML as described here.

I am unsure about which way to go and if this will result in a "stable" solution, in the sense that it is not sensitive the configuration of the machine on which the code is executed (is Word installed or not, which version, which configuration, ...).

Which way should I go and what limitations will I have?

答: I ended using OpenXML sdk which works great. It will work but do mot forget to deploy the dll (un case the OpenXML framework is mot installed on the client computer).</p>


问:
How do I invert an integer around a selected number point
I want to essentially be able to have a function swap where I can enter 2 arguments. The first would be the central point, the point of inversion so to speak, while the second would be the number I want to find the opposite of, with respect to the point.

So if I put in swap(5,2) it would return 8.

The idea being that 5-2=3 then 5+3=8.

答:
Functional form (in its own .m file or another function file)

```<code>function out = swap(x, y)
    out = x + (x-y);
end

% Then in another file / command window
swap(5,2) % >> 8
</code>```

Anonymous function (can be defined anywhere within the scope it is used)

```<code>swap = @(x,y) x + (x-y);
% Then in same function / script
swap(5,2) % >> 8
</code>```

Body:
Functional form (in its own .m file or another function file)

function out = swap(x, y)
    out = x + (x-y);
end

% Then in another file / command window
swap(5,2) % >> 8

Anonymous function (can be defined anywhere within the scope it is used)

swap = @(x,y) x + (x-y);
% Then in same function / script
swap(5,2) % >> 8


问:
Change the color and shape of a bubble chart in excel based on value in different column
I have a spreadsheet with lots of data in it,  some of the data  is displayed in a bubble chart, the size of the points is also displayed correctly.

Now, I need to change the colour (and shape, but that for later) depending on the status of the data, which is displayed in row Z with values from 1 ( red) to 3 (green).

My VBA skills are really rusty by now and i can't figure out why the following code only changes the colour of the first point?

```<code>Option Explicit
Sub ColortheFingpoints()
    Dim cht As Chart
    Dim srs As Series
    Dim pt As Point
    Dim p As Long
    Dim valRange As Range, cl As Range
    Dim myColor As Long

Set cht = ActiveSheet.ChartObjects(1).Chart
Set srs = cht.SeriesCollection(1)
Set valRange = Range("Z8:Z10")

    For p = 1 To srs.Points.Count
    Set pt = srs.Points(p)
    Set cl = valRange(p)

    With pt.Format.Fill
        .Visible = msoTrue
        Select Case LCase(cl)
            Case "1"
                myColor = RGB(255, 0, 0)
            Case "2"
                myColor = RGB(255, 140, 0)
            Case "3"
                myColor = RGB(0, 128, 0)
        End Select

        .ForeColor.RGB = myColor

    End With
Next

End Sub
</code>```

edit 1:

The problem seems to be that it only runs once and therefore only looks at Cell Z8 and not Z9 or the following

答:
Chris, try to change

```<code>Set cl = valRange(p)
</code>```

to

```<code>Set cl = valRange.Range("A" & p)
</code>```

I don't know, why your code is working, but this one shall be more human readable. Tell me if it works.

Body:
I have a spreadsheet with lots of data in it,  some of the data  is displayed in a bubble chart, the size of the points is also displayed correctly.

Now, I need to change the colour (and shape, but that for later) depending on the status of the data, which is displayed in row Z with values from 1 ( red) to 3 (green).

My VBA skills are really rusty by now and i can't figure out why the following code only changes the colour of the first point?

Option Explicit
Sub ColortheFingpoints()
    Dim cht As Chart
    Dim srs As Series
    Dim pt As Point
    Dim p As Long
    Dim valRange As Range, cl As Range
    Dim myColor As Long

Set cht = ActiveSheet.ChartObjects(1).Chart
Set srs = cht.SeriesCollection(1)
Set valRange = Range("Z8:Z10")

    For p = 1 To srs.Points.Count
    Set pt = srs.Points(p)
    Set cl = valRange(p)

    With pt.Format.Fill
        .Visible = msoTrue
        Select Case LCase(cl)
            Case "1"
                myColor = RGB(255, 0, 0)
            Case "2"
                myColor = RGB(255, 140, 0)
            Case "3"
                myColor = RGB(0, 128, 0)
        End Select

        .ForeColor.RGB = myColor

    End With
Next

End Sub

edit 1:

The problem seems to be that it only runs once and therefore only looks at Cell Z8 and not Z9 or the following

Body:
Chris, try to change

Set cl = valRange(p)

to

Set cl = valRange.Range("A" & p)

I don't know, why your code is working, but this one shall be more human readable. Tell me if it works.


答:
Just write it down on paper:</p>

```<code>function out = swap(in1,in2)
% pivot = in1 - in2;
% out = in1 + pivot = in1 + (in1 - in2) = 2*in1 - in2
out = 2*in1 - in2;
</code>```

Title: How do I invert an integer around a selected number point

Body:
I want to essentially be able to have a function swap where I can enter 2 arguments. The first would be the central point, the point of inversion so to speak, while the second would be the number I want to find the opposite of, with respect to the point.

So if I put in swap(5,2) it would return 8.

The idea being that 5-2=3 then 5+3=8.

Body:
Just write it down on paper:

function out = swap(in1,in2)
% pivot = in1 - in2;
% out = in1 + pivot = in1 + (in1 - in2) = 2*in1 - in2
out = 2*in1 - in2;


问:
Why i cant get value of input
I cant get value of inputs to create rectangle on page after click. I thought it because of event loop and tried to wrap it in setTimeout() but it doesn't work out. So what should I do and how it actually work?
Code:

(() => {
    const inputElements = document.getElementsByTagName("INPUT");
    const inputs = {
        height: setTimeout(() => {return inputElements[0].value},0),
        width: inputElements[1].value || 50
    }

    const elements = [];
    const bodyClick = document.body.addEventListener('click', () => {
        event.target.tagName !== "INPUT" ? addRectangle(): formClick();
    })
    const addRectangle = () => {
        let newRectangle = document.createElement('div');
        newRectangle.style.background = getRandomColor();
        newRectangle.style.width = inputs.width + 'px';
        console.log(inputs.width)
        newRectangle.style.height = inputs.height +'px';
        document.body.appendChild(newRectangle);
        elements.push(newRectangle);
    }
    const formClick = () => {

    }
    const getRandomColor = () => {
        let letters = '0123456789ABCDEF';
        let color = '#';
        for (let i = 0; i < 6; i++) {
            color += letters[Math.floor(Math.random() * 16)];
        }
        return color;
    }
})()```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
    height: 1000px;
    width:100%;
}</code>```

<!DOCTYPE html>

    <meta charset="UTF-8">
    <link href="style.css" rel="stylesheet">
    <title>Lab 6</title>

    <form id = "form">
        <input type="text" placeholder="height">
        <input type="text" placeholder="width">
    </form>

```

答:
(() => {
    const inputElements = document.getElementsByTagName("INPUT");
    const elements = [];
    const bodyClick = document.body.addEventListener('click', () => {
        event.target.tagName !== "INPUT" ? addRectangle(): formClick();
    })
    const addRectangle = () => {
        const inputs = {
          height: inputElements[0].value || 50,
          width: inputElements[1].value || 50
        }
        let newRectangle = document.createElement('div');
        newRectangle.style.background = getRandomColor();
        newRectangle.style.width = inputs.width + 'px';
        newRectangle.style.height = inputs.height +'px';
        document.body.appendChild(newRectangle);
        elements.push(newRectangle);
    }
    const formClick = () => {

    }
    const getRandomColor = () => {
        let letters = '0123456789ABCDEF';
        let color = '#';
        for (let i = 0; i < 6; i++) {
            color += letters[Math.floor(Math.random() * 16)];
        }
        return color;
    }
})()```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
    height: 1000px;
    width:100%;
}</code>```

<form id = "form">
    <input type="text" placeholder="height">
    <input type="text" placeholder="width">
</form>```

setTimeout wont return value to you.

On body click get the values for input then set it to created div.

Title: Why i cant get value of input

Body:
I cant get value of inputs to create rectangle on page after click. I thought it because of event loop and tried to wrap it in setTimeout() but it doesn't work out. So what should I do and how it actually work?
Code:

(() => {
    const inputElements = document.getElementsByTagName("INPUT");
    const inputs = {
        height: setTimeout(() => {return inputElements[0].value},0),
        width: inputElements[1].value || 50
    }

    const elements = [];
    const bodyClick = document.body.addEventListener('click', () => {
        event.target.tagName !== "INPUT" ? addRectangle(): formClick();
    })
    const addRectangle = () => {
        let newRectangle = document.createElement('div');
        newRectangle.style.background = getRandomColor();
        newRectangle.style.width = inputs.width + 'px';
        console.log(inputs.width)
        newRectangle.style.height = inputs.height +'px';
        document.body.appendChild(newRectangle);
        elements.push(newRectangle);
    }
    const formClick = () => {

    }
    const getRandomColor = () => {
        let letters = '0123456789ABCDEF';
        let color = '#';
        for (let i = 0; i < 6; i++) {
            color += letters[Math.floor(Math.random() * 16)];
        }
        return color;
    }
})()

body {
    height: 1000px;
    width:100%;
}

<!DOCTYPE html>

    <meta charset="UTF-8">
    <link href="style.css" rel="stylesheet">
    <title>Lab 6</title>

    <form id = "form">
        <input type="text" placeholder="height">
        <input type="text" placeholder="width">
    </form>

Body:
(() => {
    const inputElements = document.getElementsByTagName("INPUT");
    const elements = [];
    const bodyClick = document.body.addEventListener('click', () => {
        event.target.tagName !== "INPUT" ? addRectangle(): formClick();
    })
    const addRectangle = () => {
        const inputs = {
          height: inputElements[0].value || 50,
          width: inputElements[1].value || 50
        }
        let newRectangle = document.createElement('div');
        newRectangle.style.background = getRandomColor();
        newRectangle.style.width = inputs.width + 'px';
        newRectangle.style.height = inputs.height +'px';
        document.body.appendChild(newRectangle);
        elements.push(newRectangle);
    }
    const formClick = () => {

    }
    const getRandomColor = () => {
        let letters = '0123456789ABCDEF';
        let color = '#';
        for (let i = 0; i < 6; i++) {
            color += letters[Math.floor(Math.random() * 16)];
        }
        return color;
    }
})()

body {
    height: 1000px;
    width:100%;
}

<form id = "form">
    <input type="text" placeholder="height">
    <input type="text" placeholder="width">
</form>

setTimeout wont return value to you.

On body click get the values for input then set it to created div.