问:
Sending SMS, MMS messages from mobile device and getting that message to a Java application server
I've been tasked with a project where the customer would like to send SMS, MMS messages from a mobile device.  They would like to have a dedicated phone number to send these messages to.  We would like these messages get routed through a gateway so it can be processed in a Java Application Server and have the server generate a response that will make its way back to the users mobile device.  The server side of this will be done in Java.

I'm new to this and trying to understand the best approach.  Please let me know what services and APIs are available that will allow me to do this.  It seems like there are plenty of services available to get the message from the server to the phone, but I'm not clear on the mechanism for getting the message from the device routed to the Java application server.

Any suggestions are greatly appreciated.

Thanks in advance.

Seth

答:
There are a bunch of companies that can provide a phone number to receive incoming sms messages as well as send them (not sure about MMS; that is a different story).  One of them is Clickatell.  They have a variety of API's you can use from Java.

http://www.clickatell.com/products/gateway.php


来源: stackexchange

问:
Angular 2 fill variable with return JSON info from HTTP Request
I'm pretty new on Angular2, and I'm trying to obtain the key/value pair from a JSON file returned by a Http request. I want to store them on the objectResource property so I can retrieve them on the template.

This is my component.ts:

```<code>export class ResourceDetailComponent implements OnInit {

    objectResource: any = Array();
    id:any;
    sub:any;

    constructor(private contentService: ContentService, private route: ActivatedRoute) {

        this.sub = this.route.params.subscribe(params => {
            this.id = +params['id'];
        });

        this.getResource(this.id);
     }

    ngOnInit(){}

    private getResource(id:number) {
        return this.contentService.getSpecificResource(id).then(res => this.objectResource.push(res));
    }

}
</code>```

and this is mi service.ts:

```<code>public getSpecificResource(id:number) {
        return this.http.get(`http://resources.dev/v1/resources/show/${id}`)
        .toPromise()
        .then(res => res.json());
    }
</code>```

when I do console.log on res I obtain this log, which mean the service is doing the request as expected:

```<code>Object {
    id: 1,
    name: "quisquam",
    image: "http://lorempixel.com/480/480/?88330",
    description: "Consequuntur quo provident alias aut rerum.",
    author: "Marc Mann Sr."
}
</code>```

I've tried to retrieve these values on the template using {{objectResource.name}} but isn't working, and I don't know how can I access this values from the template.

答:
First of all make this change

```<code>export class ResourceDetailComponent implements OnInit {

    objectResource: Array<any> = [];
    ..........
}
</code>```

If there will be an array of multiple data.

```<code><div *ngFor='let data of objectResource'>
    <div> id : {{data.id}} </div>
    <div> name : {{data.name}} </div>
    <div> description : {{data.description}} </div>
    .....
</div>
</code>```

This will show data if there is any data inside "objectResource"

ContentLicense: CC BY-SA 3.0

Body:
I'm pretty new on Angular2, and I'm trying to obtain the key/value pair from a JSON file returned by a Http request. I want to store them on the objectResource property so I can retrieve them on the template.

This is my component.ts:

export class ResourceDetailComponent implements OnInit {

    objectResource: any = Array();
    id:any;
    sub:any;

    constructor(private contentService: ContentService, private route: ActivatedRoute) {

        this.sub = this.route.params.subscribe(params => {
            this.id = +params['id'];
        });

        this.getResource(this.id);
     }

    ngOnInit(){}

    private getResource(id:number) {
        return this.contentService.getSpecificResource(id).then(res => this.objectResource.push(res));
    }

}

and this is mi service.ts:

public getSpecificResource(id:number) {
        return this.http.get(`http://resources.dev/v1/resources/show/${id}`)
        .toPromise()
        .then(res => res.json());
    }

when I do console.log on res I obtain this log, which mean the service is doing the request as expected:

Object {
    id: 1,
    name: "quisquam",
    image: "http://lorempixel.com/480/480/?88330",
    description: "Consequuntur quo provident alias aut rerum.",
    author: "Marc Mann Sr."
}

I've tried to retrieve these values on the template using {{objectResource.name}} but isn't working, and I don't know how can I access this values from the template.

Body:
First of all make this change

export class ResourceDetailComponent implements OnInit {

    objectResource: Array<any> = [];
    ..........
}

If there will be an array of multiple data.

<div *ngFor='let data of objectResource'>
    <div> id : {{data.id}} </div>
    <div> name : {{data.name}} </div>
    <div> description : {{data.description}} </div>
    .....
</div>

This will show data if there is any data inside "objectResource"


问:
how can i refresh a page on particular time in php?
```<code><?php

$page = $_SERVER['PHP_SELF'];
$sec = "10";

date("Y-m-d");

date_default_timezone_set('Asia/Kolkata');
$time= date('H:i');

if($time == '11:51')
{
    echo mt_rand(0,9);
    echo '<br>';
}
?>
<?php
$page = $_SERVER['PHP_SELF'];
$sec = "10";
?>
<html>
    <head>
    <meta http-equiv="refresh" content="<?php echo $sec?>;URL='<?php echo $page?>'">
    </head>
    <body>
    <?php
        echo "Watch the page reload itself in 10 second!";
    ?>
    </body>
</html>
</code>```

<p>// in this code insted of second i wont to pass time like 12.00 then the code execute in above code after 10 second page refresh and generate number on every 10 sec and i also wont to generate 1 random number on particular time   </p>

答:
PHP is server side, any code there will not get called without a request from the browser, the solution is AJAX. In your case try something like this (you need jQuery for this particular example):

```<code>window.setInterval(function(){
  $.ajax({
    url:"my-file.php",
    success:function(data){
      //now data is the current time on the server, react accordingly with location.reload(true);
  });

}, 10000); // check every 10 seconds (change to any milliseconds you want)
</code>```

In your my-file.php just echo the server time

Body:
<?php

$page = $_SERVER['PHP_SELF'];
$sec = "10";

date("Y-m-d");

date_default_timezone_set('Asia/Kolkata');
$time= date('H:i');

if($time == '11:51')
{
    echo mt_rand(0,9);
    echo '
';
}
?>
<?php
$page = $_SERVER['PHP_SELF'];
$sec = "10";
?>

    <meta http-equiv="refresh" content="<?php echo $sec?>;URL='<?php echo $page?>'">

    <?php
        echo "Watch the page reload itself in 10 second!";
    ?>

// in this code insted of second i wont to pass time like 12.00 then the code execute in above code after 10 second page refresh and generate number on every 10 sec and i also wont to generate 1 random number on particular time

Body:
PHP is server side, any code there will not get called without a request from the browser, the solution is AJAX. In your case try something like this (you need jQuery for this particular example):

window.setInterval(function(){
  $.ajax({
    url:"my-file.php",
    success:function(data){
      //now data is the current time on the server, react accordingly with location.reload(true);
  });

}, 10000); // check every 10 seconds (change to any milliseconds you want)

In your my-file.php just echo the server time


问:
How to set vertical align to middle in my case?
I am trying to modify htmls element to achieve two things:

Vertical align two glyphicons and texts to middle.
(vertical align middle doesn't work)

Modify css to have a small gap between text "thanks" and glyphicons to become something like <icon><thanks><icon> instead of  <icon>   <thanks>   <icon>

I have created a jsfiddle:
https://jsfiddle.net/vwdhd1wy/

It seems odd that it created two gap without any additional css. Can someone help me about it?

答:
This work for you

```<code>   <div>
       <span class="left glyphicon glyphicon-forward"></span>
       <span class="middle">Thansk</span>
       <span class="right glyphicon glyphicon-backward"></span>
    </div>
</code>```

And style like this

```<code>  .left {
      background-color: red;
      height: 30px;
    }

    .middle {
      height: 30px;
      display:inline-block;
      background-color: grey;
      vertical-align:middle;
    }

    .right {
      background-color: red;
        height: 30px;
    }
    span {
       align-items: center;
       display: inline-flex !important;
       flex-wrap: wrap;
    }
</code>```

Body:
This work for you

   <div>
       <span class="left glyphicon glyphicon-forward"></span>
       <span class="middle">Thansk</span>
       <span class="right glyphicon glyphicon-backward"></span>
    </div>

And style like this

  .left {
      background-color: red;
      height: 30px;
    }

    .middle {
      height: 30px;
      display:inline-block;
      background-color: grey;
      vertical-align:middle;
    }

    .right {
      background-color: red;
        height: 30px;
    }
    span {
       align-items: center;
       display: inline-flex !important;
       flex-wrap: wrap;
    }


问:
ListView DataTemplate Grid bind Image height to other View's height
I have a ListView with such a Grid DataTemplate definiotion:

```<code><Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition />
        <ColumnDefinition />
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition/>
    </Grid.RowDefinitions>
    <TextBlock x:Name="Tb" Text="{x:Bind Address}" TextWrapping="Wrap"/>
    <Image Source="{x:Bind SignalResource}" Height="{Binding ElementName=Tb, Path=ActualHeight}"/>
</Grid>
</code>```

I want Image take the TextBlock's height, but my Binding does not work (as I understood - because when binding is resolved, ActualHeight of View is still 0)

The question is how to bind Image height to TextBlock height?

答:
ActualHeight (Width) doesn't work as a regular property - MSDN information:

Note  Although it has an ActualHeightProperty backing field, ActualHeight does not raise property change notifications and it should be thought of as a regular CLR property and not a dependency property.

In your case you can use SizeChanged event on your TextBlock and then adjust the height of the Image. I'm not sure but maybe it will be possible to do it also via RelativePanel with proper aligning. Here is a try with RelativePanel (as I've tried there is a chance it will work):

<RelativePanel>
    <TextBlock Name="MyTB" Text="Something" FontSize="24"/>
    <Rectangle Fill="Green" Width="40" RelativePanel.RightOf="MyTB" RelativePanel.AlignTopWith="MyTB" RelativePanel.AlignBottomWith="MyTB"/>
</RelativePanel>
```

Body:
I have a ListView with such a Grid DataTemplate definiotion:

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition />
        <ColumnDefinition />
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition/>
    </Grid.RowDefinitions>
    <TextBlock x:Name="Tb" Text="{x:Bind Address}" TextWrapping="Wrap"/>
    <Image Source="{x:Bind SignalResource}" Height="{Binding ElementName=Tb, Path=ActualHeight}"/>
</Grid>

I want Image take the TextBlock's height, but my Binding does not work (as I understood - because when binding is resolved, ActualHeight of View is still 0)

The question is how to bind Image height to TextBlock height?


问:
Java Compare Two List's object values?
I have two list **ListA<MyData> listA = new ArrayList<MyData>()** and ListB<MyData> listB = new ArrayList<MyData>() both contain object of type MyData and MyData contain these variables.

```<code>MyData {
    String name;
    boolean check;
}
</code>```

ListA and ListB both contains MyData objects ,now I have to compare both the list's object values here name as well check variable like if ListA contains these object values

```<code>ListA = ["Ram",true],["Hariom",true],["Shiv",true];
</code>```

and ListB also contain

```<code>ListB = ["Ram",true],["Hariom",true],["Shiv",true];
</code>```

then i have to compare lists and return false because both list are same
But if ListA contains

```<code>ListA = ["Ram",true],["Hariom",true],["Shiv",false];
</code>```

and ListB Contain

```<code> ListB = ["Ram",true],["Hariom",true],["Shiv",true];
</code>```

then I have to compare lists and return true because both list are not same

or vice-versa so any slight change in the any list values I have to return true.
One thing I have to mentioned here objects can be in any order.

答:
Using java 8 removeIf to compare similar items</p>

```<code>public int getSimilarItems(){
    List<String> one = Arrays.asList("milan", "dingo", "elpha", "hafil", "meat", "iga", "neeta.peeta");
    List<String> two = new ArrayList<>(Arrays.asList("hafil", "iga", "binga", "mike", "dingo")); //Cannot remove directly from array backed collection
    int initial = two.size();

    two.removeIf(one::contains);
    return initial - two.size();
}
</code>```

Title: Java Compare Two List's object values?

Body:
I have two list **ListA<MyData> listA = new ArrayList<MyData>()** and ListB<MyData> listB = new ArrayList<MyData>() both contain object of type MyData and MyData contain these variables.

MyData {
    String name;
    boolean check;
}

ListA and ListB both contains MyData objects ,now I have to compare both the list's object values here name as well check variable like if ListA contains these object values

ListA = ["Ram",true],["Hariom",true],["Shiv",true];

and ListB also contain

ListB = ["Ram",true],["Hariom",true],["Shiv",true];

then i have to compare lists and return false because both list are same
But if ListA contains

ListA = ["Ram",true],["Hariom",true],["Shiv",false];

and ListB Contain

 ListB = ["Ram",true],["Hariom",true],["Shiv",true];

then I have to compare lists and return true because both list are not same

or vice-versa so any slight change in the any list values I have to return true.
One thing I have to mentioned here objects can be in any order.

Body:
Using java 8 removeIf to compare similar items

public int getSimilarItems(){
    List<String> one = Arrays.asList("milan", "dingo", "elpha", "hafil", "meat", "iga", "neeta.peeta");
    List<String> two = new ArrayList<>(Arrays.asList("hafil", "iga", "binga", "mike", "dingo")); //Cannot remove directly from array backed collection
    int initial = two.size();

    two.removeIf(one::contains);
    return initial - two.size();
}


问:
How to get previous LI in multi-level UL/LI elements
I have following html code:

```<code><ul>
  <li>Parameter1</li>
  <li>Group1
    <ul>
      <li>Parameter2</li>
      <li>Parameter3</li>
    </ul>
  </li>
  <li>Parameter4</li>
  <li>Group2
    <ul>
      <li>Parameter5</li>
    </ul>
  </li>
</ul>
</code>```

And when I trigger onClick method on any of the LI elements, I need to get closest previous LI element.

If I click Parameter4 I need Parameter3 element.
If I click Parameter5 I need Group2 element.

I know the basics of prev(), closest(), find(), but I am not able to make it work.

element.prev('li') ignores nested LIs in UL

I think I am able to write the logic in words: I need previous LI element element.prev('li') and if this element has UL inside, I want last LI in that. If it has no UL, return the prev('li') that we started with.

Thank you.

答:
$(document).ready(function() {
  $('ul li').click(function(event) {
    event.stopPropagation();
    var self = $(this);
    if (self.prev().is('li') && !self.prev('li').children().is('ul')) {
      console.log(self.prev('li').text());
    }
    else if (self.prev().is('li') && self.prev('li').children().is('ul')) {
      console.log(self.prev('li').children('ul').children('li').last().text());
    }
    else if (self.parent('ul').parent().is('li') && !self.prev().is('li')) {
      console.log(self.parent('ul').parent('li').prev('li').text());
    } else {
      console.log('no previous element');
    }
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li>Parameter1</li>
  <li>Group1
    <ul>
      <li>Parameter2</li>
      <li>Parameter3</li>
    </ul>
  </li>

  <li>Parameter4</li>
  <li>Group2
    <ul>
      <li>Parameter5</li>
    </ul>
  </li>

</ul></code>```

Body:
I have following html code:

Parameter1

Group1

Parameter2

Parameter3

Parameter4

Group2

Parameter5

And when I trigger onClick method on any of the LI elements, I need to get closest previous LI element.

If I click Parameter4 I need Parameter3 element.
If I click Parameter5 I need Group2 element.

I know the basics of prev(), closest(), find(), but I am not able to make it work.

element.prev('li') ignores nested LIs in UL

I think I am able to write the logic in words: I need previous LI element element.prev('li') and if this element has UL inside, I want last LI in that. If it has no UL, return the prev('li') that we started with.

Thank you.

Body:
$(document).ready(function() {
  $('ul li').click(function(event) {
    event.stopPropagation();
    var self = $(this);
    if (self.prev().is('li') && !self.prev('li').children().is('ul')) {
      console.log(self.prev('li').text());
    }
    else if (self.prev().is('li') && self.prev('li').children().is('ul')) {
      console.log(self.prev('li').children('ul').children('li').last().text());
    }
    else if (self.parent('ul').parent().is('li') && !self.prev().is('li')) {
      console.log(self.parent('ul').parent('li').prev('li').text());
    } else {
      console.log('no previous element');
    }
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li>Parameter1</li>
  <li>Group1
    <ul>
      <li>Parameter2</li>
      <li>Parameter3</li>
    </ul>
  </li>

  <li>Parameter4</li>
  <li>Group2
    <ul>
      <li>Parameter5</li>
    </ul>
  </li>

</ul>


问:
Changing displayed text and font size of block ui
I am using blockUI in my first project. The script below shows how I am using it:

```<code>$(document).ready(function(){
    $('#elem').click(function(e){

            $.blockUI({ css: {
                border: 'none',
                padding: '15px',
                backgroundColor: '#000',
                '-webkit-border-radius': '10px',
                '-moz-border-radius': '10px',
                opacity: .5,
                color: '#fff'
            } });

            setTimeout($.unblockUI, 2000);

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

When the click event occurs, the block is shown, with the text 'Please wait ...'. I don't know where this text is coming from, I would like to modify the text as follows:

change the size of the font used to display the text

add an image of a spinning wheel to the 'Please Wait ..' text

Can someone help with this?

答:
Try it this way:</p>

```<code>    $.blockUI(
    {
        css: {
            border: 'none',
            padding: '15px',
            backgroundColor: '#000',
            '-webkit-border-radius': '10px',
            '-moz-border-radius': '10px',
            opacity: .5,
            color: '#fff',
            fontSize:'16px'
        },
        message: 'Your custom message'
    });
</code>```

Body:
I am using blockUI in my first project. The script below shows how I am using it:

$(document).ready(function(){
    $('#elem').click(function(e){

            $.blockUI({ css: {
                border: 'none',
                padding: '15px',
                backgroundColor: '#000',
                '-webkit-border-radius': '10px',
                '-moz-border-radius': '10px',
                opacity: .5,
                color: '#fff'
            } });

            setTimeout($.unblockUI, 2000);

    });
});

When the click event occurs, the block is shown, with the text 'Please wait ...'. I don't know where this text is coming from, I would like to modify the text as follows:

change the size of the font used to display the text

add an image of a spinning wheel to the 'Please Wait ..' text

Can someone help with this?

Body:
Try it this way:

    $.blockUI(
    {
        css: {
            border: 'none',
            padding: '15px',
            backgroundColor: '#000',
            '-webkit-border-radius': '10px',
            '-moz-border-radius': '10px',
            opacity: .5,
            color: '#fff',
            fontSize:'16px'
        },
        message: 'Your custom message'
    });


问:
SQL: Select Vegetarians
i'm stuck with a small problem here and i can't seem to find the right answer.

I have a DB with multiple Tables, in which i have ANIMALS and their FOOD. I have to select which ANIMALS only eat VEGETARIAN meals. The table is set up with a BOOLEAN. 0 = MEAT 1 = VEGETARIAN.

There are ANIMALS in the Table who eat MEAT and VEGETARIAN. I don't need them, i strictly need Animals who only eat VEGETARIAN.

Thanks in advance.

答:
You didn't say what is You table schema, so i will create simple one with fields AnimalId int , Meat bit .

In table the records are stored as simple as that

```<code>+----------+------+
| AnimalId | meat |
+----------+------+
|        1 |    0 |
|        1 |    1 |
|        2 |    0 |
|        3 |    1 |
|        4 |    0 |
+----------+------+
</code>```

So Animal 1 is eating both meat and vegetables, animal nr 2 only vegetables, animal nr 3 only meat. Our expected result is to get only Animal ID 2 and 4.

You need to group data by AnimalId, take MAX from meat bit column after casting it to int and filter data having 0 as result of MAX.

```<code>SELECT        AnimalId
FROM            dbo.Animals
GROUP BY AnimalId
HAVING        (MAX(CAST(Meat AS INT)) = 0)
</code>```

Title: SQL: Select Vegetarians

Body:
You didn't say what is You table schema, so i will create simple one with fields AnimalId int , Meat bit .

In table the records are stored as simple as that

+----------+------+
| AnimalId | meat |
+----------+------+
|        1 |    0 |
|        1 |    1 |
|        2 |    0 |
|        3 |    1 |
|        4 |    0 |
+----------+------+

So Animal 1 is eating both meat and vegetables, animal nr 2 only vegetables, animal nr 3 only meat. Our expected result is to get only Animal ID 2 and 4.

You need to group data by AnimalId, take MAX from meat bit column after casting it to int and filter data having 0 as result of MAX.

SELECT        AnimalId
FROM            dbo.Animals
GROUP BY AnimalId
HAVING        (MAX(CAST(Meat AS INT)) = 0)


问:
disable horizontal scroll in jscrollpane
I have a JScrollPane with FlowLayout that I want to have a fixed width. It should be scrolling vertically only, and the contents should be rearranged automatically when I resize the window. I think there should be a method like setEnableHorizontalScroll(false) but can't find it.

Is there any easy way to do this?

答:
I came across this issue as well... my solution was to modify the JScrollPane source code and pass an additional parameter to disable horizontal scrolling. The edits are really simple:

On line 53:

```<code>$.fn.jScrollPane = function (settings, horizontalScrollingEnabled) {
</code>```

Then, on line 177:

```<code>if (horizontalScrollingEnabled) {
isScrollableH = percentInViewH > 1;
} else {
isScrollableH = false;
}
</code>```

That's all you need to change. Minify the modified source code and include it on your page. When initializing the jScrollPane, you can now set whether you want it to scroll horizontally like so:

```<code>$('.scroll-pane').jScrollPane("", false);
</code>```

Hope that helps.

Body:
I came across this issue as well... my solution was to modify the JScrollPane source code and pass an additional parameter to disable horizontal scrolling. The edits are really simple:

On line 53:

$.fn.jScrollPane = function (settings, horizontalScrollingEnabled) {

Then, on line 177:

if (horizontalScrollingEnabled) {
isScrollableH = percentInViewH > 1;
} else {
isScrollableH = false;
}

That's all you need to change. Minify the modified source code and include it on your page. When initializing the jScrollPane, you can now set whether you want it to scroll horizontally like so:

$('.scroll-pane').jScrollPane("", false);

Hope that helps.

ContentLicense: CC BY-SA 2.5


问:
Find elements on webpage with Selenium
I have XPath

```<code>/html/body/div[@id='page']/div[@id='page-inner']/div[@id='main-box']/div[@class='in1']/div[@id='content-and-context']/div[@id='content']/div[@class='under-bar']/table[@class='flights']/tbody/tr[@id='flight-932539']/td[2]:
</code>```

But flight-number are changes. Can I find Elements with part XPath ?
I use foreach() and write data for every flight.

this is html code:

答:
First thing first: don't use absolute path. Even the smallest change in the html invalidate the path, especially in dynamic applications. Your xpath could easily be //tr[@id='flight-932539']/td[2]

As for your question, you can use contains() for partial id

```<code>//tr[contains(@id, 'flight-')]/td[2]
</code>```

Title: Find elements on webpage with Selenium

Body:
I have XPath

/html/body/div[@id='page']/div[@id='page-inner']/div[@id='main-box']/div[@class='in1']/div[@id='content-and-context']/div[@id='content']/div[@class='under-bar']/table[@class='flights']/tbody/tr[@id='flight-932539']/td[2]:

But flight-number are changes. Can I find Elements with part XPath ?
I use foreach() and write data for every flight.

this is html code:

Body:
First thing first: don't use absolute path. Even the smallest change in the html invalidate the path, especially in dynamic applications. Your xpath could easily be //tr[@id='flight-932539']/td[2]

As for your question, you can use contains() for partial id

//tr[contains(@id, 'flight-')]/td[2]


问:
Time Elapsed Calculation from form in JavaScript
I'm working on a time elapsed calculator were the user enters in a month, day, and year. From their input and the current date, I want to calculate how many days are in between and then display how many years, months, and days have elapsed. I started by making a form with three input values of "month" , "day" , and "year". I then started on the script:

```<code>function timeElapsed() {
       var timeMonth = document.getElementById("month");
       var timeDay = document.getElementById("day");
       var timeYear = document.getElementById("year");
       var currentDate = new Date();
       var elapsed =
       document.getElementById("timeElapsed").innerHTML = elapsed;
   }
       //Event Listener
       var submitButton= document.getElementById("sButton");
    if (submitButton.addEventListener) {
        submitButton.addEventListener("click", timeElapsed, false);
    } else if (submitButton.attachEvent) {
        submitButton.attachEvent("onclick", timeElapsed);
    }
</code>```

Obviously as you can tell I kind of stopped because I'm stumped on where to go from here. This is a lab in school for me and I just want to understand how to do it. My teacher mentioned "Note that your program must include code to convert day values in excess of 31 into months, and months in excess of 12 into years." and I am actually totally confused but understands what he means. It's just actually understanding how to actually do this. It's a web class and it is very hard to understand from just a textbook. I've looked a bit online but I haven't found anything that was useful for my situation. If you can help me out, thank you so much.

答:
Here is an example you can use to calculate Date difference

function get(ID){
  return document.getElementById(ID);
}

function calculateDiff(){
  var FromYear  = get('FromYear').value;
  var FromMonth = get('FromMonth').value;
  var FromDay  = get('FromDay').value;

  var ToYear  = get('ToYear').value;
  var ToMonth  = get('ToMonth').value;
  var ToDay  = get('ToDay').value;

  var date1  = new Date(FromYear,FromMonth,FromDay);   /*Create Date Object From date*/
  var date2  = new Date(ToYear,ToMonth,ToDay);         /*Create Date Object To date*/
  var diff  = new Date(date2.getTime() - date1.getTime());

  get('ResultYear').value  = diff.getUTCFullYear()-1970;  /*Calculate year difference*/
  get('ResultMonth').value = diff.getUTCMonth();          /*Count month difference*/
  get('ResultDay').value   = diff.getUTCDate()-1;         /*Count day difference*/
}

calculateDiff();

var calculate = get('calculate');

calculate.onclick = function(){
  calculateDiff();
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>table input{
  width: 60px;
}
button{
  width: 80%;
  margin: 10px auto;
}</code>```

      YYYY
      MM
      DD

      FROM
      <input  id="FromYear"  placeholder="YYYY" value="2017">
      <input  id="FromMonth" placeholder="MM" value="3">
      <input  id="FromDay"   placeholder="DD" value="18">

      TO
      <input  id="ToYear"  placeholder="YYYY" value="2017">
      <input  id="ToMonth" placeholder="MM" value="3">
      <input  id="ToDay"   placeholder="DD" value="29">

        <button id="calculate">Calculate</button>

       RESULT
       <input  id="ResultYear"  placeholder="YYYY" value="">
       <input  id="ResultMonth" placeholder="MM" value="">
       <input  id="ResultDay"   placeholder="DD" value="">

```

Body:
I'm working on a time elapsed calculator were the user enters in a month, day, and year. From their input and the current date, I want to calculate how many days are in between and then display how many years, months, and days have elapsed. I started by making a form with three input values of "month" , "day" , and "year". I then started on the script:

function timeElapsed() {
       var timeMonth = document.getElementById("month");
       var timeDay = document.getElementById("day");
       var timeYear = document.getElementById("year");
       var currentDate = new Date();
       var elapsed =
       document.getElementById("timeElapsed").innerHTML = elapsed;
   }
       //Event Listener
       var submitButton= document.getElementById("sButton");
    if (submitButton.addEventListener) {
        submitButton.addEventListener("click", timeElapsed, false);
    } else if (submitButton.attachEvent) {
        submitButton.attachEvent("onclick", timeElapsed);
    }

Obviously as you can tell I kind of stopped because I'm stumped on where to go from here. This is a lab in school for me and I just want to understand how to do it. My teacher mentioned "Note that your program must include code to convert day values in excess of 31 into months, and months in excess of 12 into years." and I am actually totally confused but understands what he means. It's just actually understanding how to actually do this. It's a web class and it is very hard to understand from just a textbook. I've looked a bit online but I haven't found anything that was useful for my situation. If you can help me out, thank you so much.

Body:
Here is an example you can use to calculate Date difference

function get(ID){
  return document.getElementById(ID);
}

function calculateDiff(){
  var FromYear  = get('FromYear').value;
  var FromMonth = get('FromMonth').value;
  var FromDay  = get('FromDay').value;

  var ToYear  = get('ToYear').value;
  var ToMonth  = get('ToMonth').value;
  var ToDay  = get('ToDay').value;

  var date1  = new Date(FromYear,FromMonth,FromDay);   /*Create Date Object From date*/
  var date2  = new Date(ToYear,ToMonth,ToDay);         /*Create Date Object To date*/
  var diff  = new Date(date2.getTime() - date1.getTime());

  get('ResultYear').value  = diff.getUTCFullYear()-1970;  /*Calculate year difference*/
  get('ResultMonth').value = diff.getUTCMonth();          /*Count month difference*/
  get('ResultDay').value   = diff.getUTCDate()-1;         /*Count day difference*/
}

calculateDiff();

var calculate = get('calculate');

calculate.onclick = function(){
  calculateDiff();
}

table input{
  width: 60px;
}
button{
  width: 80%;
  margin: 10px auto;
}

<table border="1">
  <tbody>
    <tr class="header">
      <th>&nbsp;</th>
      <th>YYYY</th>
      <th>MM</th>
      <th>DD</th>
    </tr>
    <tr>
      <th>FROM</th>
      <td><input  id="FromYear"  placeholder="YYYY" value="2017"></td>
      <td><input  id="FromMonth" placeholder="MM" value="3"></td>
      <td><input  id="FromDay"   placeholder="DD" value="18"></td>
    </tr>
    <tr>
      <th>TO</th>
      <td><input  id="ToYear"  placeholder="YYYY" value="2017"></td>
      <td><input  id="ToMonth" placeholder="MM" value="3"></td>
      <td><input  id="ToDay"   placeholder="DD" value="29"></td>
 </tr>
    <tr>
      <th colspan="4">
        <button id="calculate">Calculate</button>
      </th>
    </tr>
    <tr>
       <th>RESULT</th>
       <td><input  id="ResultYear"  placeholder="YYYY" value=""></td>
       <td><input  id="ResultMonth" placeholder="MM" value=""></td>
       <td><input  id="ResultDay"   placeholder="DD" value=""></td>
     </tr>
  </tbody>
</table>


问:
method doesn't override from its superclass- swift
```<code>override func tableView(_ tableView: UITableView,cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

let cell = tableView.dequeueReusableCell( withIdentifier: "ChecklistItem", for: indexPath as IndexPath)
    return cell }
</code>```

There's an error saying: method doesn't override from its superclass. I've deleted the "override"  but still not working.
These are the source code from a book and it is said this is right syntax. So I want to know why I had this error?

答:
```<code>    override func tableView(_ tableView: UITableView,cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell( withIdentifier: "ChecklistItem", for: indexPath as IndexPath)
        return cell
}
</code>```

In this code you have written remove extra IndexPath in parameter list.

It should be

cellForRowAt indexPath: NSIndexPath) -> UITableViewCell

Not

cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell

Error is because compiler does'nt able to see such a method in base
  class.

Body:
override func tableView(_ tableView: UITableView,cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

let cell = tableView.dequeueReusableCell( withIdentifier: "ChecklistItem", for: indexPath as IndexPath)
    return cell }

There's an error saying: method doesn't override from its superclass. I've deleted the "override"  but still not working.
These are the source code from a book and it is said this is right syntax. So I want to know why I had this error?

Body:
    override func tableView(_ tableView: UITableView,cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell( withIdentifier: "ChecklistItem", for: indexPath as IndexPath)
        return cell
}

In this code you have written remove extra IndexPath in parameter list.

It should be

cellForRowAt indexPath: NSIndexPath) -> UITableViewCell

Not

cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell

Error is because compiler does'nt able to see such a method in base
  class.


问:
Update or Delete tables with streaming buffer in BigQuery?
I'm getting this following error when trying to delete records from a table created through GCP Console and updated with GCP BigQuery Node.js table insert function.

UPDATE or DELETE DML statements are not supported over table stackdriver-360-150317:my_dataset.users with streaming buffer

The table was created without streaming features. And from what I'm reading in documentation Tables that have been written to recently via BigQuery Streaming (tabledata.insertall) cannot be modified using UPDATE or DELETE statements.

Does it mean that once a record has been inserted with this function into a table, there's no way to delete records? At all? If that's the case, does it mean that table needs to be deleted and recreated from scratch? If that's not the case. Can you please suggest a workaround to avoid this issue?

Thanks!

Including new error message for SEO: "UPDATE or DELETE statement over table ... would affect rows in the streaming buffer, which is not supported" -- Fh

答:
To check if the table has a streaming buffer, check the tables.get response for a section named streamingBuffer or, when streaming to a partitioned table, data in the streaming buffer has a NULL value for the _PARTITIONTIME pseudo column, so even with a simple WHERE query can be checked.

Streamed data is available for real-time analysis within a few seconds of the first streaming insertion into a table but it can take up to 90 minutes to become available for copy/export and other operations. You probably have to wait up to 90 minutes so all buffer is persisted on the cluster. You can use queries to see if the streaming buffer is empty or not like you mentioned.

If you use load job to create the table, you won't have streaming buffer, but probably you streamed some values to it.

Note the answer below to work with tables that have ongoing streaming buffers. Just use a WHERE to filter out the latest minutes of data and your queries will work. -- Fh

ContentLicense: CC BY-SA 4.0


问:
Nesting resource
I'm trying to nest my messages controller into my channels controller. But when I go to my messages view i get the error "couldn't find channel with no id"

```<code> class MessagesController < ApplicationController

  def index
    @channel = Channel.find(params[:channel_id])
    @messages = @channel.messages
  end

  def new
    @channel = Channel.find(params[:channel_id])
    @message = @channel.messages.build
  end

  def create
    @channel = Channel.find(params[:channel_id])
    @message = @channel.messages.build(params[:message])
    if @message.save
      flash[:notice] = "Successfully created message."
      redirect_to channel_url(@message.channel_id)
    else
      render :action => 'new'
    end
  end

  def edit
    @message = Message.find(params[:id])
  end

  def update
    @message = Message.find(params[:id])
    if @message.update_attributes(params[:message])
      flash[:notice] = "Successfully updated message."
      redirect_to channel_url(@message.channel_id)
    else
      render :action => 'edit'
    end
  end

  def destroy
    @message = Message.find(params[:id])
    @message.destroy
    flash[:notice] = "Successfully destroyed message."
    redirect_to channel_url(@message.channel_id)
  end
end
</code>```

Channels controller

```<code>class ChannelsController < ApplicationController

  def index
    @channels = Channel.find(:all)
  end

  def show
    @channel = Channel.find(params[:id])
    @message = Message.new(:channel => @channel)
  end

  def new
    @channel = Channel.new
  end

  def create
    @channel = Channel.new(params[:channel])
    if @channel.save
      flash[:notice] = "Successfully created channel."
      redirect_to @channel
    else
      render :action => 'new'
    end
  end

  def edit
    @channel = Channel.find(params[:id])
  end

  def update
    @channel = Channel.find(params[:id])
    if @channel.update_attributes(params[:channel])
      flash[:notice] = "Successfully updated channel."
      redirect_to @channel
    else
      render :action => 'edit'
    end
  end

  def destroy
    @channel = Channel.find(params[:id])
    @channel.destroy
    flash[:notice] = "Successfully destroyed channel."
    redirect_to channels_url
  end
end
</code>```

routes.rb

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

  resources :users
  resources :channels, :shallow => true do |channels|
    channels.resources :messages
  end

  root :channels

  resources :users, :user_sessions

  match 'login' => 'user_sessions#new', :as => :login
  match 'logout' => 'user_sessions#destroy', :as => :logout
  match ':controller(/:action(/:id(.:format)))'
</code>```

end

答:
What's going on here is that this line:

```<code>@channel = Channel.find(params[:channel_id])
</code>```

Is falling over because there's no defined channel_id in the params hash.  I see you're using shallow routes, which means your uri probably looks like this:

```<code>/messages
</code>```

And you need it to look like:

```<code>/channels/1/messages
</code>```

Try changing your url to be:

```<code>channel_messages_url(@channel)
</code>```

instead of

```<code>messages_url
</code>```

This is a guess btw, it could be because of the way you've defined your routes.rb, which looks a little odd because you're defining the messages routes twice, once with the has_many and again as a proper resource.  You probably want something like:

```<code># assuming you need shallow routes
resources :channels, :shallow => true do |channels|
  channels.resources :messages
end
</code>```

Title: Nesting resource

Body:
I'm trying to nest my messages controller into my channels controller. But when I go to my messages view i get the error "couldn't find channel with no id"

 class MessagesController < ApplicationController

  def index
    @channel = Channel.find(params[:channel_id])
    @messages = @channel.messages
  end

  def new
    @channel = Channel.find(params[:channel_id])
    @message = @channel.messages.build
  end

  def create
    @channel = Channel.find(params[:channel_id])
    @message = @channel.messages.build(params[:message])
    if @message.save
      flash[:notice] = "Successfully created message."
      redirect_to channel_url(@message.channel_id)
    else
      render :action => 'new'
    end
  end

  def edit
    @message = Message.find(params[:id])
  end

  def update
    @message = Message.find(params[:id])
    if @message.update_attributes(params[:message])
      flash[:notice] = "Successfully updated message."
      redirect_to channel_url(@message.channel_id)
    else
      render :action => 'edit'
    end
  end

  def destroy
    @message = Message.find(params[:id])
    @message.destroy
    flash[:notice] = "Successfully destroyed message."
    redirect_to channel_url(@message.channel_id)
  end
end

Channels controller

class ChannelsController < ApplicationController

  def index
    @channels = Channel.find(:all)
  end

  def show
    @channel = Channel.find(params[:id])
    @message = Message.new(:channel => @channel)
  end

  def new
    @channel = Channel.new
  end

  def create
    @channel = Channel.new(params[:channel])
    if @channel.save
      flash[:notice] = "Successfully created channel."
      redirect_to @channel
    else
      render :action => 'new'
    end
  end

  def edit
    @channel = Channel.find(params[:id])
  end

  def update
    @channel = Channel.find(params[:id])
    if @channel.update_attributes(params[:channel])
      flash[:notice] = "Successfully updated channel."
      redirect_to @channel
    else
      render :action => 'edit'
    end
  end

  def destroy
    @channel = Channel.find(params[:id])
    @channel.destroy
    flash[:notice] = "Successfully destroyed channel."
    redirect_to channels_url
  end
end

routes.rb

   SeniorProject::Application.routes.draw do

  resources :users
  resources :channels, :shallow => true do |channels|
    channels.resources :messages
  end

  root :channels

  resources :users, :user_sessions

  match 'login' => 'user_sessions#new', :as => :login
  match 'logout' => 'user_sessions#destroy', :as => :logout
  match ':controller(/:action(/:id(.:format)))'

end

Body:
What's going on here is that this line:

@channel = Channel.find(params[:channel_id])

Is falling over because there's no defined channel_id in the params hash.  I see you're using shallow routes, which means your uri probably looks like this:

/messages

And you need it to look like:

/channels/1/messages

Try changing your url to be:

channel_messages_url(@channel)

instead of

messages_url

This is a guess btw, it could be because of the way you've defined your routes.rb, which looks a little odd because you're defining the messages routes twice, once with the has_many and again as a proper resource.  You probably want something like:

# assuming you need shallow routes
resources :channels, :shallow => true do |channels|
  channels.resources :messages
end


问:
Schedule garbage collections for multiple jvms on single server
We have linux servers running about 200 microservices in java each, using c-groups for isolation for cpu and memory isolation. One  thing we have discovered is that java tends to require a full core of CPU to perform (major) garbage collection efficiently.

However obviously with 200 apps running and only 24 CPUs if they all decided to GC at the same time they would be limited by the c-groups. Since typical application CPU usage is relatively small (say about 15% of 1 cpu peak), it would be nice to find a way to ensure they don't all GC at the same time.

I'm looking into how we can schedule GCs so that each microserevice does not GC at the same time so that we can still run over 200 apps per host, but was wondering if anybody had some suggestions or experience on this topic before trying to re invent the wheel.

I found that there are command line methods that we can use, as well as using MBeans to actually trigger the GC, but read that it is not advised to do so as this will mess up the non-deterministic procedure java uses for GC.

Something that I'm thinking about is using performance metrics to monitor cpu, memory, and traffic to try and predict a GC, then if multiple are about to GC, perhaps we could trigger them one at a time, however this might be impractical or also bad idea.

We are running java 7, and 8.

答:
You can't schedule a GC, since it depends on the allocation rate - i.e. it depends on the load and application logic. Some garbage collectors try to control major GC duration, total time consumed by GC, but not the rate. There is no guarantee as well that an externally triggered GC (e.g. via MBean) will actually run, and if it will run it might be ran later then it was triggered.

As other guys pointed, it is a very rare possibility (you can calculate it by gathering an average period in seconds of a major GC from all of your apps and bulding a histogram) to face it under the "normal" load. Under the "heavy" load you'll likely face CPU shortage much earlier than a probable simultaneous GC from an increased allocation rate will happen - because you would need to have a "lot" (depending on the size of your objects) of "long"-living objects to pollute the old generation to trigger a major GC.


问:
lists with parenthesis using only javascript or jquery?
I need a list (
 and
) with parenthesis like this.

```<code>(1) List1
(2) List2
(3) List3
(4) List4
</code>```

The important thing is that I need this using only javascript or jQuery without using external, internal css.

This is my code

```<code>$("ol").css("counter-reset", "list");
$("ol li").css("list-style", "none");
$("ol li:before").css({"content": "counter(list, lower-alpha) ') '", "counter-increment": "list"});
</code>```

答:
This can be done using the pseudo CSS tag :before, but it only works on newer browsers.

ol {list-style-type: none}
li {counter-increment: step-counter}
li::before {
  content: "(" counter(step-counter) ")";
  padding-right: 10px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ol>
  <li>List1</li>
  <li>List2</li>
  <li>List3</li>
  <li>List4</li>
</ol></code>```

update

You mentioned that you would like to toggle it. You could do it like this

$('button').click(function() {
  $('ol').toggleClass('numbered') // this toggles it
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.numbered {
  list-style-type: none;
  padding-left: 25px;
}

.numbered li {
  counter-increment: step-counter;
}

.numbered li::before {
  content: "(" counter(step-counter) ")";
  padding-right: 4px;
}</code>```

List1

List2

List3

List4

<button>Change</button>```

Body:
I need a list (
 and
) with parenthesis like this.

(1) List1
(2) List2
(3) List3
(4) List4

The important thing is that I need this using only javascript or jQuery without using external, internal css.

This is my code

$("ol").css("counter-reset", "list");
$("ol li").css("list-style", "none");
$("ol li:before").css({"content": "counter(list, lower-alpha) ') '", "counter-increment": "list"});

Body:
This can be done using the pseudo CSS tag :before, but it only works on newer browsers.

ol {list-style-type: none}
li {counter-increment: step-counter}
li::before {
  content: "(" counter(step-counter) ")";
  padding-right: 10px;
}

<ol>
  <li>List1</li>
  <li>List2</li>
  <li>List3</li>
  <li>List4</li>
</ol>

update

You mentioned that you would like to toggle it. You could do it like this

$('button').click(function() {
  $('ol').toggleClass('numbered') // this toggles it
})

.numbered {
  list-style-type: none;
  padding-left: 25px;
}

.numbered li {
  counter-increment: step-counter;
}

.numbered li::before {
  content: "(" counter(step-counter) ")";
  padding-right: 4px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ol>
  <li>List1</li>
  <li>List2</li>
  <li>List3</li>
  <li>List4</li>
</ol>

<button>Change</button>


问:
What's the purpose of ugettext_noop in Django?
As mentioned in this section of Translation | Django documentation, the function ugettext_noop is a utility function for internationalization:

ugettext_noop(message) ¶

Marks strings for translation but doesn’t translate them now. This can
  be used to store strings in global variables that should stay in the
  base language (because they might be used externally) and will be
  translated later.

Also, this answer provides an example of its usage:

```<code>import logging
from django.http import HttpResponse
from django.utils.translation import ugettext as _, ugettext_noop as _noop

def view(request):
    msg = _noop("An error has occurred")
    logging.error(msg)
    return HttpResponse(_(msg))
</code>```

Despite these docs, I still don't understand why should I mark a string as extractable for translation. To me it seems that ugettext_noop is nothing but a reminder, and even so, what's the purpose of reminding programmers that some strings (msg in this case) are to be translated later?

答:
Once I have a task to make event log with storing its messages in database. It had to support i18n. So firstly I marked all event log messages with ugettext_noop function. In this case they were not translated before adding to database. But at the same time they were added to *.po files.

In this example ugettext or ugettext_lazy functions should be used only after extracting messages from database.

Body:
As mentioned in this section of Translation | Django documentation, the function ugettext_noop is a utility function for internationalization:

ugettext_noop(message) ¶

Marks strings for translation but doesn’t translate them now. This can
  be used to store strings in global variables that should stay in the
  base language (because they might be used externally) and will be
  translated later.

Also, this answer provides an example of its usage:

import logging
from django.http import HttpResponse
from django.utils.translation import ugettext as _, ugettext_noop as _noop

def view(request):
    msg = _noop("An error has occurred")
    logging.error(msg)
    return HttpResponse(_(msg))

Despite these docs, I still don't understand why should I mark a string as extractable for translation. To me it seems that ugettext_noop is nothing but a reminder, and even so, what's the purpose of reminding programmers that some strings (msg in this case) are to be translated later?


问:
Programmatically save a home address to a new contact using CNContactStore? Swift 3
I would like to programmatically create a contact in my app and save it into actual contacts using apples Contacts framework. I can create one with a first name, last name, and even work with dates.

I start with

```<code>let contact = CNMutableContact()
</code>```

and end with

```<code>let store = CNContactStore()
let saveRequest = CNSaveRequest()
saveRequest.add(contact, toContainerWithIdentifier: nil)
try? store.execute(saveRequest)
</code>```

but I can't figure out how to do it with a home address. Any help would be appreciated, thanks. Would love to do it via location coordinates or even a string of a city, state, street, etc.

Thank you.

答:
Here's how you would create a home address:

```<code>let store = CNContactStore()
let contact = CNMutableContact()
contact.familyName = "Tester"
contact.givenName = "Bad"
// Address
let address = CNMutablePostalAddress()
address.street = "Your Street"
address.city = "Your City"
address.state = "Your State"
address.postalCode = "Your ZIP/Postal Code"
address.country = "Your Country"
let home = CNLabeledValue<CNPostalAddress>(label:CNLabelHome, value:address)
contact.postalAddresses = [home]
// Save
let saveRequest = CNSaveRequest()
saveRequest.add(contact, toContainerWithIdentifier: nil)
try? store.execute(saveRequest)
</code>```

If you wanted to create a work address, then you'd create another CNMutablePostalAddress instance to hold the work address information, then create another CNLabeledValue<CNPostalAddress> with a label of CNLabelWork and add the new CNLabeledValue<CNPostalAddress> instance to the final postalAddresses array as well.

Body:
I would like to programmatically create a contact in my app and save it into actual contacts using apples Contacts framework. I can create one with a first name, last name, and even work with dates.

I start with

let contact = CNMutableContact()

and end with

let store = CNContactStore()
let saveRequest = CNSaveRequest()
saveRequest.add(contact, toContainerWithIdentifier: nil)
try? store.execute(saveRequest)

but I can't figure out how to do it with a home address. Any help would be appreciated, thanks. Would love to do it via location coordinates or even a string of a city, state, street, etc.

Thank you.

Body:
Here's how you would create a home address:

let store = CNContactStore()
let contact = CNMutableContact()
contact.familyName = "Tester"
contact.givenName = "Bad"
// Address
let address = CNMutablePostalAddress()
address.street = "Your Street"
address.city = "Your City"
address.state = "Your State"
address.postalCode = "Your ZIP/Postal Code"
address.country = "Your Country"
let home = CNLabeledValue<CNPostalAddress>(label:CNLabelHome, value:address)
contact.postalAddresses = [home]
// Save
let saveRequest = CNSaveRequest()
saveRequest.add(contact, toContainerWithIdentifier: nil)
try? store.execute(saveRequest)

If you wanted to create a work address, then you'd create another CNMutablePostalAddress instance to hold the work address information, then create another CNLabeledValue<CNPostalAddress> with a label of CNLabelWork and add the new CNLabeledValue<CNPostalAddress> instance to the final postalAddresses array as well.


问:
Get top most UIViewController
I can't seem to get the top most UIViewController without access to a UINavigationController. Here is what I have so far:

```<code>UIApplication.sharedApplication().keyWindow?.rootViewController?.presentViewController(vc, animated: true, completion: nil)
</code>```

However, it does not seem to do anything. The keyWindow and rootViewController seem to be non-nil values too, so the optional chaining shouldn't be an issue.

NOTE: It is a bad idea to do something like this. It breaks the MVC pattern.

答:
To find the visible viewController in Swift 3

```<code>if let viewControllers = window?.rootViewController?.childViewControllers {

     let prefs = UserDefaults.standard

     if viewControllers[viewControllers.count - 1] is ABCController{
        print("[ABCController] is visible")

     }
}
</code>```

This code find the last added or the last active controller visible.

This I have used in AppDelegate to find active view Controller

Title: Get top most UIViewController

Body:
I can't seem to get the top most UIViewController without access to a UINavigationController. Here is what I have so far:

UIApplication.sharedApplication().keyWindow?.rootViewController?.presentViewController(vc, animated: true, completion: nil)

However, it does not seem to do anything. The keyWindow and rootViewController seem to be non-nil values too, so the optional chaining shouldn't be an issue.

NOTE: It is a bad idea to do something like this. It breaks the MVC pattern.

Body:
To find the visible viewController in Swift 3

if let viewControllers = window?.rootViewController?.childViewControllers {

     let prefs = UserDefaults.standard

     if viewControllers[viewControllers.count - 1] is ABCController{
        print("[ABCController] is visible")

     }
}

This code find the last added or the last active controller visible.

This I have used in AppDelegate to find active view Controller


问:
React fetch data in server before render
I'm new to reactjs, I want to fetch data in server, so that it will send page with data to client.

It is OK when the function getDefaultProps return dummy data like this {data: {books: [{..}, {..}]}}.

However not work with code below. The code execute in this sequence with error message "Cannot read property 'books' of undefined"

getDefaultProps

return

fetch

{data: {books: [{..}, {..}]}}

However, I expect the code should run in this sequence

getDefaultProps

fetch

{data: {books: [{..}, {..}]}}

return

Any Idea?

```<code>statics: {
    fetchData: function(callback) {
      var me = this;

      superagent.get('http://localhost:3100/api/books')
        .accept('json')
        .end(function(err, res){
          if (err) throw err;

          var data = {data: {books: res.body} }

          console.log('fetch');
          callback(data);
        });
    }

getDefaultProps: function() {
    console.log('getDefaultProps');
    var me = this;
    me.data = '';

    this.fetchData(function(data){
        console.log('callback');
        console.log(data);
        me.data = data;
      });

    console.log('return');
    return me.data;
  },

  render: function() {
    console.log('render book-list');
    return (
      <div>
        <ul>
        {
          this.props.data.books.map(function(book) {
            return <li key={book.name}>{book.name}</li>
          })
        }
        </ul>
      </div>
    );
  }
</code>```

答:
As a supplement of the answer of Michael Parker, you can make getData accept a callback function to active the setState update the data:</p>

```<code>componentWillMount : function () {
    var data = this.getData(()=>this.setState({data : data}));
},
</code>```

Body:
I'm new to reactjs, I want to fetch data in server, so that it will send page with data to client.

It is OK when the function getDefaultProps return dummy data like this {data: {books: [{..}, {..}]}}.

However not work with code below. The code execute in this sequence with error message "Cannot read property 'books' of undefined"

getDefaultProps

return

fetch

{data: {books: [{..}, {..}]}}

However, I expect the code should run in this sequence

getDefaultProps

fetch

{data: {books: [{..}, {..}]}}

return

Any Idea?

statics: {
    fetchData: function(callback) {
      var me = this;

      superagent.get('http://localhost:3100/api/books')
        .accept('json')
        .end(function(err, res){
          if (err) throw err;

          var data = {data: {books: res.body} }

          console.log('fetch');
          callback(data);
        });
    }

getDefaultProps: function() {
    console.log('getDefaultProps');
    var me = this;
    me.data = '';

    this.fetchData(function(data){
        console.log('callback');
        console.log(data);
        me.data = data;
      });

    console.log('return');
    return me.data;
  },

  render: function() {
    console.log('render book-list');
    return (

        {
          this.props.data.books.map(function(book) {
            return
{book.name}

          })
        }

    );
  }

Body:
As a supplement of the answer of Michael Parker, you can make getData accept a callback function to active the setState update the data:

componentWillMount : function () {
    var data = this.getData(()=>this.setState({data : data}));
},


问:
Does this Maven range dependency error makes sense?
I'm working with a "pom" dependency that defines this dependency

```<code><groupId>com.oracle.toplink</groupId>
<artifactId>eclipselink</artifactId>
<version>[12.2.1,12.2.2)</version>
</code>```

And in the repository, the maven-metadata of eclipselink contains the following

```<code><metadata>
  <groupId>com.oracle.toplink</groupId>
  <artifactId>eclipselink</artifactId>
  <version>12.1.3-0-0</version>
  <versioning>
    <latest>12.2.1-0-0</latest>
    <release>12.2.1-0-0</release>
    <versions>
      <version>12.1.2-0-0</version>
      <version>12.1.3-0-0</version>
      <version>12.2.1-0-0</version>
    </versions>
    <lastUpdated>20161123223550</lastUpdated>
  </versioning>
</metadata>
</code>```

But Maven throws this error

Couldn't find a version in [12.1.2-0-0, 12.1.3-0-0, 12.2.1-0-0] to match range [12.2.1,12.2.2)

If I'm not wrong, Maven should've matched with the 12.2.1-0-0 version.

Why does this happen?

Also, there are two more versions in the repository 12.2.1-1-0 and 12.2.1-2-0 but these do not appear in the maven-metadata of eclipselink (any idea why?)

答:
If really do a comparsion of the version in Maven via:

$ java -jar apache-maven-3.3.9\lib\apache-artifact-3.3.9.jar 12.2.1-1-0 12.2.1
Display parameters as parsed by Maven (in canonical form) and comparison result:
1. 12.2.1-1-0 == 12.2.1-1
   12.2.1-1-0 > 12.2.1
2. 12.2.1 == 12.2.1

You see that 12.2.1 is something different than12.2.1-1-0`

Furthermore if you use 12.2.1-0-0 and compare it to 12.2.1 via:

$ java -jar apache-maven-3.3.9\lib\apache-artifact-3.3.9.jar 12.2.1-0-0 12.2.1
Display parameters as parsed by Maven (in canonical form) and comparison result:
1. 12.2.1-0-0 == 12.2.1
   12.2.1-0-0 == 12.2.1
2. 12.2.1 == 12.2.1

You see that there is no difference between those versions.

https://cwiki.apache.org/confluence/display/MAVENOLD/Versioning

https://maven.apache.org/ref/3.3.9/maven-artifact/apidocs/src-html/org/apache/maven/artifact/versioning/ComparableVersion.html

http://maven.apache.org/ref/3.3.9/maven-artifact/index.html

Body:
I'm working with a "pom" dependency that defines this dependency

<groupId>com.oracle.toplink</groupId>
<artifactId>eclipselink</artifactId>
<version>[12.2.1,12.2.2)</version>

And in the repository, the maven-metadata of eclipselink contains the following

<metadata>
  <groupId>com.oracle.toplink</groupId>
  <artifactId>eclipselink</artifactId>
  <version>12.1.3-0-0</version>
  <versioning>
    <latest>12.2.1-0-0</latest>
    <release>12.2.1-0-0</release>
    <versions>
      <version>12.1.2-0-0</version>
      <version>12.1.3-0-0</version>
      <version>12.2.1-0-0</version>
    </versions>
    <lastUpdated>20161123223550</lastUpdated>
  </versioning>
</metadata>

But Maven throws this error

Couldn't find a version in [12.1.2-0-0, 12.1.3-0-0, 12.2.1-0-0] to match range [12.2.1,12.2.2)

If I'm not wrong, Maven should've matched with the 12.2.1-0-0 version.

Why does this happen?

Also, there are two more versions in the repository 12.2.1-1-0 and 12.2.1-2-0 but these do not appear in the maven-metadata of eclipselink (any idea why?)


问:
How to ignore certain files in Git
I have a repository with a file, Hello.java. When I compile it, an additional Hello.class file is generated.

I created an entry for Hello.class in a .gitignore file. However, the file still appears to be tracked.

How can I make Git ignore Hello.class?

答:
You should write something like

```<code>*.class
</code>```

into your .gitignore file.

Title: How to ignore certain files in Git

Body:
You should write something like

*.class

into your .gitignore file.


问:
Spring Roo 2.0.RC1: use Mysql DB with springlets authentification
When is use Spring Roo with mysql and use

```<code>security setup --provider SPRINGLETS_JPA
</code>```

When i now start the application i get error Stacktrace

```<code>2017-03-28 10:00:57.695  WARN 7544 --- [  restartedMain] ationConfigEmbeddedWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory
2017-03-28 10:00:57.695  INFO 7544 --- [  restartedMain] o.apache.catalina.core.StandardService   : Stopping service Tomcat
2017-03-28 10:00:57.711  WARN 7544 --- [  restartedMain] o.s.boot.SpringApplication               : Error handling failed (Error creating bean with name 'delegatingApplicationListener' defined in class path resource [org/springframework/security/config/annotation/web/configuration/WebSecurityConfiguration.class]: BeanPostProcessor before instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'metaDataSourceAdvisor': Cannot resolve reference to bean 'methodSecurityMetadataSource' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration': Initialization of bean failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'org.springframework.context.annotation.ConfigurationClassPostProcessor.importRegistry' is defined)
2017-03-28 10:00:57.711 ERROR 7544 --- [  restartedMain] o.s.boot.SpringApplication               : Application startup failed

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1583) ~[spring-beans-4.3.3.RELEASE.jar:4.3.3.RELEASE]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:545) ~[spring-beans-4.3.3.RELEASE.jar:4.3.3.RELEASE]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482) ~[spring-beans-4.3.3.RELEASE.jar:4.3.3.RELEASE]
        at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.3.RELEASE.jar:4.3.3.RELEASE]
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.3.RELEASE.jar:4.3.3.RELEASE]
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.3.RELEASE.jar:4.3.3.RELEASE]
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.3.3.RELEASE.jar:4.3.3.RELEASE]
        at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1076) ~[spring-context-4.3.3.RELEASE.jar:4.3.3.RELEASE]
        at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:851) ~[spring-context-4.3.3.RELEASE.jar:4.3.3.RELEASE]
        at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:541) ~[spring-context-4.3.3.RELEASE.jar:4.3.3.RELEASE]
        at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122) ~[spring-boot-1.4.1.RELEASE.jar:1.4.1.RELEASE]
        at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:761) [spring-boot-1.4.1.RELEASE.jar:1.4.1.RELEASE]
        at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:371) [spring-boot-1.4.1.RELEASE.jar:1.4.1.RELEASE]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:315) [spring-boot-1.4.1.RELEASE.jar:1.4.1.RELEASE]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1186) [spring-boot-1.4.1.RELEASE.jar:1.4.1.RELEASE]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1175) [spring-boot-1.4.1.RELEASE.jar:1.4.1.RELEASE]
        at de.quintra.webapps.rechnungspruefung.RechnungspruefungApplication.main(RechnungspruefungApplication.java:21) [classes/:na]
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_121]
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_121]
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_121]
        at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_121]
        at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) [spring-boot-devtools-1.4.1.RELEASE.jar:1.4.1.RELEASE]
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory
Caused by: org.hibernate.MappingException: org.hibernate.dialect.MySQL5Dialect does not support pooled sequences
</code>```

What is the problem.
What i must added to solve this Problem?

答:
When you include the SPRINGLETS_JPA security type, new Spring Boot auto-configuration is being included inside your project. Also, a new entity called UserLogin it's being registered in your context.

After seen your error log org.hibernate.dialect.MySQL5Dialect does not support pooled sequences, I checked the UserLogin entity and I've seen that the @Id field includes the following annotation that configures how the id value is being generated.

```<code>@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "userLoginGen")
</code>```

As you could see, it's using the GenerationType SEQUENCE, but this type it's not supported for MySQL databases.

Check out this post https://dzone.com/articles/hibernate-identity-sequence

I've just create the following issue in the Springlets project to solve this problem.

https://github.com/DISID/springlets/issues/53

Hope it helps,

Body:
When is use Spring Roo with mysql and use

security setup --provider SPRINGLETS_JPA

When i now start the application i get error Stacktrace

2017-03-28 10:00:57.695  WARN 7544 --- [  restartedMain] ationConfigEmbeddedWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory
2017-03-28 10:00:57.695  INFO 7544 --- [  restartedMain] o.apache.catalina.core.StandardService   : Stopping service Tomcat
2017-03-28 10:00:57.711  WARN 7544 --- [  restartedMain] o.s.boot.SpringApplication               : Error handling failed (Error creating bean with name 'delegatingApplicationListener' defined in class path resource [org/springframework/security/config/annotation/web/configuration/WebSecurityConfiguration.class]: BeanPostProcessor before instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'metaDataSourceAdvisor': Cannot resolve reference to bean 'methodSecurityMetadataSource' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration': Initialization of bean failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'org.springframework.context.annotation.ConfigurationClassPostProcessor.importRegistry' is defined)
2017-03-28 10:00:57.711 ERROR 7544 --- [  restartedMain] o.s.boot.SpringApplication               : Application startup failed

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1583) ~[spring-beans-4.3.3.RELEASE.jar:4.3.3.RELEASE]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:545) ~[spring-beans-4.3.3.RELEASE.jar:4.3.3.RELEASE]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482) ~[spring-beans-4.3.3.RELEASE.jar:4.3.3.RELEASE]
        at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.3.RELEASE.jar:4.3.3.RELEASE]
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.3.RELEASE.jar:4.3.3.RELEASE]
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.3.RELEASE.jar:4.3.3.RELEASE]
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.3.3.RELEASE.jar:4.3.3.RELEASE]
        at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1076) ~[spring-context-4.3.3.RELEASE.jar:4.3.3.RELEASE]
        at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:851) ~[spring-context-4.3.3.RELEASE.jar:4.3.3.RELEASE]
        at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:541) ~[spring-context-4.3.3.RELEASE.jar:4.3.3.RELEASE]
        at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122) ~[spring-boot-1.4.1.RELEASE.jar:1.4.1.RELEASE]
        at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:761) [spring-boot-1.4.1.RELEASE.jar:1.4.1.RELEASE]
        at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:371) [spring-boot-1.4.1.RELEASE.jar:1.4.1.RELEASE]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:315) [spring-boot-1.4.1.RELEASE.jar:1.4.1.RELEASE]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1186) [spring-boot-1.4.1.RELEASE.jar:1.4.1.RELEASE]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1175) [spring-boot-1.4.1.RELEASE.jar:1.4.1.RELEASE]
        at de.quintra.webapps.rechnungspruefung.RechnungspruefungApplication.main(RechnungspruefungApplication.java:21) [classes/:na]
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_121]
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_121]
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_121]
        at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_121]
        at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) [spring-boot-devtools-1.4.1.RELEASE.jar:1.4.1.RELEASE]
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory
Caused by: org.hibernate.MappingException: org.hibernate.dialect.MySQL5Dialect does not support pooled sequences

What is the problem.
What i must added to solve this Problem?

Body:
When you include the SPRINGLETS_JPA security type, new Spring Boot auto-configuration is being included inside your project. Also, a new entity called UserLogin it's being registered in your context.

After seen your error log org.hibernate.dialect.MySQL5Dialect does not support pooled sequences, I checked the UserLogin entity and I've seen that the @Id field includes the following annotation that configures how the id value is being generated.

@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "userLoginGen")

As you could see, it's using the GenerationType SEQUENCE, but this type it's not supported for MySQL databases.

Check out this post https://dzone.com/articles/hibernate-identity-sequence

I've just create the following issue in the Springlets project to solve this problem.

https://github.com/DISID/springlets/issues/53

Hope it helps,


问:
Getting specific character values from argv[] and making a new const char
I am certain this has been answered before, but I cannot wrap my head around the answers. I am doing an entry C course and there is a provided header, cs50.h, that has the string type in it. So while I have been using it, I am not quite sure how it works.

My goal is to get the characters at argv[1][0] and argv[1][1] into a const char *variable. While I know the answer definitely involves pointers and addresses, I have not been able to find the successful combination. I am asking here in hope that someone can show me the right way with my own code so I can learn how to go about it.

UPDATE I am trying to get the first two char characters from the second (i.e. first string that isn't the file name) thus, argv[1][0] and argv[1][1] So the given input will be something like this helloworld and I just want 'h' and 'e'. I do not know how to combine 'h' and 'e' from the argv array into a const char *variable, which is the requested format I need to pass it to another function.

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

int main(int argc, string argv[])
{

    string saltget[2] = { &argv[1][0] , &argv[1][1] };
    printf("%s\n", saltget);

}
</code>```

答:
argv[1][0] is of type char, so if you wish to construct a string with this character as first letter, it would be:

```<code>char str [] = {argv[1][0], argv[1][1], '\0'};
</code>```

Please note that hiding pointers behind a typedef is very bad practice, so you should avoid the cs50 library, as it teaches this bad practice. They define "string" as typedef char *string;. And while the pointer hiding is bad, the name string is even worse, as the name collides with C++ std::string and there will therefore be much confusion for the reader when they see the code.

Body:
I am certain this has been answered before, but I cannot wrap my head around the answers. I am doing an entry C course and there is a provided header, cs50.h, that has the string type in it. So while I have been using it, I am not quite sure how it works.

My goal is to get the characters at argv[1][0] and argv[1][1] into a const char *variable. While I know the answer definitely involves pointers and addresses, I have not been able to find the successful combination. I am asking here in hope that someone can show me the right way with my own code so I can learn how to go about it.

UPDATE I am trying to get the first two char characters from the second (i.e. first string that isn't the file name) thus, argv[1][0] and argv[1][1] So the given input will be something like this helloworld and I just want 'h' and 'e'. I do not know how to combine 'h' and 'e' from the argv array into a const char *variable, which is the requested format I need to pass it to another function.

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

int main(int argc, string argv[])
{

    string saltget[2] = { &argv[1][0] , &argv[1][1] };
    printf("%s\n", saltget);

}

Body:
argv[1][0] is of type char, so if you wish to construct a string with this character as first letter, it would be:

char str [] = {argv[1][0], argv[1][1], '\0'};

Please note that hiding pointers behind a typedef is very bad practice, so you should avoid the cs50 library, as it teaches this bad practice. They define "string" as typedef char *string;. And while the pointer hiding is bad, the name string is even worse, as the name collides with C++ std::string and there will therefore be much confusion for the reader when they see the code.


问:
How to take weighted sums of each row of a matrix in R
I have a weighted portfolio of stocks and a history of their daily returns.  I'm trying to compute the return of the portfolio on each of the historic days assuming the weights don't move, and replacing missing data with zeroes (I'm trying to compute historic VaR, or Value at Risk).

Here is a simplified version:

```<code># portfolio
pfolio = data.frame(ticker = c("stock_a", "stock_b", "stock_noob"), weight = c(0.25, 0.6, 0.15))

# Daily stock returns (with some NA values for one stock):
m = matrix(c(0.0016, 0.0037, -0.0042, -0.0096, -0.0006, -0.0043, -0.0292, -0.0158, 0.0128, 0.0113, 0.0016, 0.0042, NA, NA, 0.0168, -0.0293, 0.0037, -0.0083),
    nrow = 6,
    ncol = 3,
    dimnames = list(c("2017-03-01", "2017-03-02", "2017-03-03", "2017-03-06", "2017-03-07", "2017-03-08"), c("stock_a", "stock_b", "stock_noob"))
)
</code>```

I'm trying to use a clever apply or mapply method, but the best I can come up with is cleaning the data first, then applying a for-loop (yuck):

```<code>m_clean = apply(m, c(1, 2), function(x) if (is.na(x)) 0 else x)
answer = numeric(0)
for (i in 1:nrow(m_clean)) {
    answer = c(answer, sum(m_clean[i, pfolio$ticker] * pfolio$weight))
}
</code>```

So the main question is:  what is a clean, one-line way of doing this?

答:
You can do:

```<code>m_clean <- ifelse(is.na(m), 0, m) # or
m_clean <- m; m_clean[is.na(m_clean)] <- 0
</code>```

and then

```<code>answer <- apply(m_clean, 1, weighted.mean, w=pfolio$weight) # or
answer <- colSums(t(m_clean) * pfolio$weight) # or
answer <- tcrossprod(pfolio$weight, m_clean)
</code>```

The last is giving a matrix:

```<code>#> tcrossprod(pfolio$weight, m_clean)
#     2017-03-01 2017-03-02 2017-03-03 2017-03-06 2017-03-07 2017-03-08
#[1,]   -0.01712  -0.008555    0.00915   -1.5e-05   0.001365      2e-04
</code>```

the other solutions are giving a named vector.

benchmarks:

```<code>library("microbenchmark")
microbenchmark(
  a= apply(m_clean, 1, weighted.mean, w=pfolio$weight),
  c= colSums(t(m_clean) * pfolio$weight),
  p= tcrossprod(pfolio$weight, m_clean),
  m= m_clean %*% pfolio$weight
)
# Unit: microseconds
# expr    min      lq     mean  median      uq    max neval cld
#    a 49.115 51.0590 54.46379 52.3685 53.9815 99.023   100   c
#    c 12.688 13.8385 15.02912 14.8460 15.7560 32.366   100  b
#    p  5.978  6.8955  7.75998  7.4170  7.8770 30.771   100 a
#    m  5.438  6.4330  6.95056  6.8615  7.2710 17.109   100 a
</code>```

Body:
I have a weighted portfolio of stocks and a history of their daily returns.  I'm trying to compute the return of the portfolio on each of the historic days assuming the weights don't move, and replacing missing data with zeroes (I'm trying to compute historic VaR, or Value at Risk).

Here is a simplified version:

# portfolio
pfolio = data.frame(ticker = c("stock_a", "stock_b", "stock_noob"), weight = c(0.25, 0.6, 0.15))

# Daily stock returns (with some NA values for one stock):
m = matrix(c(0.0016, 0.0037, -0.0042, -0.0096, -0.0006, -0.0043, -0.0292, -0.0158, 0.0128, 0.0113, 0.0016, 0.0042, NA, NA, 0.0168, -0.0293, 0.0037, -0.0083),
    nrow = 6,
    ncol = 3,
    dimnames = list(c("2017-03-01", "2017-03-02", "2017-03-03", "2017-03-06", "2017-03-07", "2017-03-08"), c("stock_a", "stock_b", "stock_noob"))
)

I'm trying to use a clever apply or mapply method, but the best I can come up with is cleaning the data first, then applying a for-loop (yuck):

m_clean = apply(m, c(1, 2), function(x) if (is.na(x)) 0 else x)
answer = numeric(0)
for (i in 1:nrow(m_clean)) {
    answer = c(answer, sum(m_clean[i, pfolio$ticker] * pfolio$weight))
}

So the main question is:  what is a clean, one-line way of doing this?

Body:
You can do:

m_clean <- ifelse(is.na(m), 0, m) # or
m_clean <- m; m_clean[is.na(m_clean)] <- 0

and then

answer <- apply(m_clean, 1, weighted.mean, w=pfolio$weight) # or
answer <- colSums(t(m_clean) * pfolio$weight) # or
answer <- tcrossprod(pfolio$weight, m_clean)

The last is giving a matrix:

#> tcrossprod(pfolio$weight, m_clean)
#     2017-03-01 2017-03-02 2017-03-03 2017-03-06 2017-03-07 2017-03-08
#[1,]   -0.01712  -0.008555    0.00915   -1.5e-05   0.001365      2e-04

the other solutions are giving a named vector.

benchmarks:

library("microbenchmark")
microbenchmark(
  a= apply(m_clean, 1, weighted.mean, w=pfolio$weight),
  c= colSums(t(m_clean) * pfolio$weight),
  p= tcrossprod(pfolio$weight, m_clean),
  m= m_clean %*% pfolio$weight
)
# Unit: microseconds
# expr    min      lq     mean  median      uq    max neval cld
#    a 49.115 51.0590 54.46379 52.3685 53.9815 99.023   100   c
#    c 12.688 13.8385 15.02912 14.8460 15.7560 32.366   100  b
#    p  5.978  6.8955  7.75998  7.4170  7.8770 30.771   100 a
#    m  5.438  6.4330  6.95056  6.8615  7.2710 17.109   100 a


问:
Avoiding complex if statements
I have the following function

```<code>const getVal = (type, a, b, val) => {
    if(type) {
        if(a && b) {
            return val;
        }else if(a) {
            return toPercent(val);
        }else{
            return undefined;
        }
    }
    return toPx(val);
}
</code>```

is there a better way to express this? How would such a code be written in functional programming style

答:
The else is unneeded. You can simply return at the end of checking the two prior conditions. You can also express the decisions about a and b and   more succinctly:

```<code>const getVal = (type, a, b, val) => {
  if(type) {
    if(a) {
      if(b) {
        return val;
      }
      return toPercent(val);
    }
    return undefined;
  }
  return toPx(val);
}
</code>```

Title: Avoiding complex if statements

Body:
I have the following function

const getVal = (type, a, b, val) => {
    if(type) {
        if(a && b) {
            return val;
        }else if(a) {
            return toPercent(val);
        }else{
            return undefined;
        }
    }
    return toPx(val);
}

is there a better way to express this? How would such a code be written in functional programming style

Body:
The else is unneeded. You can simply return at the end of checking the two prior conditions. You can also express the decisions about a and b and   more succinctly:

const getVal = (type, a, b, val) => {
  if(type) {
    if(a) {
      if(b) {
        return val;
      }
      return toPercent(val);
    }
    return undefined;
  }
  return toPx(val);
}


问:
ImportXML for live exchange rates from Xe.com
I'm trying to import specific currency exchange rates,i.e. JPY-USD, JPY-EUR,JPY-INR etc from XE.com into Google spreadsheets using Import XML.
How can I figure out the x path that I need from XE.com's page source? Help would be greatly appreciated!

URL: http://www.xe.com/currency/jpy-japanese-yen?r=

答:
Use IMPORTHTML instead :

```<code>=IMPORTHTML ("http://www.xe.com/currency/xau-gold-ounce","table",1)
</code>```

xe.com returns a table with the data which you could then use a HLOOKUP to only return the data for USD. Eg. :

```<code>=hlookup("USD",{IMPORThtML("http://www.xe.com/currency/xau-gold-ounce","table",1)},2,false)
</code>```

Body:
Use IMPORTHTML instead :

=IMPORTHTML ("http://www.xe.com/currency/xau-gold-ounce","table",1)

xe.com returns a table with the data which you could then use a HLOOKUP to only return the data for USD. Eg. :

=hlookup("USD",{IMPORThtML("http://www.xe.com/currency/xau-gold-ounce","table",1)},2,false)


问:
Multiple value checks using 'in' operator (Python)
```<code>if 'string1' in line: ...
</code>```

... works as expected but what if I need to check multiple strings like so:

```<code>if 'string1' or 'string2' or 'string3' in line: ...
</code>```

... doesn't seem to work.

答:
Using map and lambda

```<code>a = ["a", "b", "c"]
b = ["a", "d", "e"]
c = ["1", "2", "3"]

# any element in `a` is a element of `b` ?
any(map(lambda x:x in b, a))
>>> True

# any element in `a` is a element of `c` ?
any(map(lambda x:x in c, a)) # any element in `a` is a element of `c` ?
>>> False
</code>```

and high-order function

```<code>has_any = lambda b: lambda a: any(map(lambda x:x in b, a))

# using ...
f1 = has_any( [1,2,3,] )
f1( [3,4,5,] )
>>> True
f1( [6,7,8,] )
>>> False
</code>```

Body:
if 'string1' in line: ...

... works as expected but what if I need to check multiple strings like so:

if 'string1' or 'string2' or 'string3' in line: ...

... doesn't seem to work.

Body:
Using map and lambda

a = ["a", "b", "c"]
b = ["a", "d", "e"]
c = ["1", "2", "3"]

# any element in `a` is a element of `b` ?
any(map(lambda x:x in b, a))
>>> True

# any element in `a` is a element of `c` ?
any(map(lambda x:x in c, a)) # any element in `a` is a element of `c` ?
>>> False

and high-order function

has_any = lambda b: lambda a: any(map(lambda x:x in b, a))

# using ...
f1 = has_any( [1,2,3,] )
f1( [3,4,5,] )
>>> True
f1( [6,7,8,] )
>>> False


问:
How to show table in columns from to to bottom?
I have array:

```<code>$array = [
    'category1' => [
        'product33',
        'product41'
    ],
    'category2' => [
        'product1',
        'product45'
    ],
    'category3' => [
        'product65',
        'product23',
        'product423'
    ],
];
</code>```

How can I show this data from array in table from top to bottom?

This should looks this:

```<code>category1  | category 2 | category3
product33  | product1   | product65
product41  | product45  | product23
           |            | product423
</code>```

I tried:

```<code><table>
  <tr>
     <?php foreach ($array as $category): ?>
         <td><?php echo $category ?></td>
     <?php endforeach ?>
  </tr>
//????
</table>
</code>```

答:
You can try something like this:</p>

```<code><?php
 foreach ($array as $category)
 {
   echo "<td>" . key($array) . "</td>";

   foreach ($category as $item)
   {
     echo "<td>" . $item . "</td>";
   }
   next($array);
 }
?>
</code>```

Body:
I have array:

$array = [
    'category1' => [
        'product33',
        'product41'
    ],
    'category2' => [
        'product1',
        'product45'
    ],
    'category3' => [
        'product65',
        'product23',
        'product423'
    ],
];

How can I show this data from array in table from top to bottom?

This should looks this:

category1  | category 2 | category3
product33  | product1   | product65
product41  | product45  | product23
           |            | product423

I tried:

     <?php foreach ($array as $category): ?>
         <?php echo $category ?>
     <?php endforeach ?>

//????

Body:
You can try something like this:

<?php
 foreach ($array as $category)
 {
   echo "<td>" . key($array) . "</td>";

   foreach ($category as $item)
   {
     echo "<td>" . $item . "</td>";
   }
   next($array);
 }
?>


问:
how can i refresh a page on particular time in php?
```<code><?php

$page = $_SERVER['PHP_SELF'];
$sec = "10";

date("Y-m-d");

date_default_timezone_set('Asia/Kolkata');
$time= date('H:i');

if($time == '11:51')
{
    echo mt_rand(0,9);
    echo '<br>';
}
?>
<?php
$page = $_SERVER['PHP_SELF'];
$sec = "10";
?>
<html>
    <head>
    <meta http-equiv="refresh" content="<?php echo $sec?>;URL='<?php echo $page?>'">
    </head>
    <body>
    <?php
        echo "Watch the page reload itself in 10 second!";
    ?>
    </body>
</html>
</code>```

<p>// in this code insted of second i wont to pass time like 12.00 then the code execute in above code after 10 second page refresh and generate number on every 10 sec and i also wont to generate 1 random number on particular time   </p>

答:
You can do this in both JavaScript and PHP , JavaScript solution is already above. Here is a PHP solution:</p>

```<code><?php

$page = $_SERVER['PHP_SELF'];
$sec = "10";

date("Y-m-d");

date_default_timezone_set('Asia/Kolkata');
$time= date('H:i');

if($time == '11:51')
{
    echo mt_rand(0,9);
    echo '<br>';
}
?>
<?php
$page = $_SERVER['PHP_SELF'];
$sec = "10";
header("Refresh: $sec; url=$page");
?>
<html>
    <head>
    </head>
    <body>
    <?php
        echo "Watch the page reload itself in 10 second!";
    ?>
    </body>
</html>
</code>```

Body:
<?php

$page = $_SERVER['PHP_SELF'];
$sec = "10";

date("Y-m-d");

date_default_timezone_set('Asia/Kolkata');
$time= date('H:i');

if($time == '11:51')
{
    echo mt_rand(0,9);
    echo '
';
}
?>
<?php
$page = $_SERVER['PHP_SELF'];
$sec = "10";
?>

    <meta http-equiv="refresh" content="<?php echo $sec?>;URL='<?php echo $page?>'">

    <?php
        echo "Watch the page reload itself in 10 second!";
    ?>

// in this code insted of second i wont to pass time like 12.00 then the code execute in above code after 10 second page refresh and generate number on every 10 sec and i also wont to generate 1 random number on particular time

Body:
You can do this in both JavaScript and PHP , JavaScript solution is already above. Here is a PHP solution:

<?php

$page = $_SERVER['PHP_SELF'];
$sec = "10";

date("Y-m-d");

date_default_timezone_set('Asia/Kolkata');
$time= date('H:i');

if($time == '11:51')
{
    echo mt_rand(0,9);
    echo '<br>';
}
?>
<?php
$page = $_SERVER['PHP_SELF'];
$sec = "10";
header("Refresh: $sec; url=$page");
?>
<html>
    <head>
    </head>
    <body>
    <?php
        echo "Watch the page reload itself in 10 second!";
    ?>
    </body>
</html>


问:
Find sum of largest subset of array
I'm solving one CS problem, namely we have given array with size N, such that N<=100000, and the array will have both negative and positive integers, now we have to find the sum of the largest subset of the array, or more formally we have to find the indexes i and j such that the sum of the elements between those elements will me maximum possible.

Here is one example:
N=5, array={12, -4, -10, 4, 9}, answer = 13, because 4+9 is the best we can get.

I know that this can be solved by bruteforce in quadratic time, but I wonder if this can be solved in linear, on logarithmic time.

Thanks in advance.

答:
According to this presentation, the algorithm by Kadane apparently yields a linear runtime bound; an implementation in C++ taken from there looks as follows.</p>

```<code>int maxSubArraySum(int a[], int size)
{
    int max_so_far = INT_MIN, max_ending_here = 0;

    for (int i = 0; i < size; i++)
    {
        max_ending_here = max_ending_here + a[i];
        if (max_so_far < max_ending_here)
            max_so_far = max_ending_here;

        if (max_ending_here < 0)
            max_ending_here = 0;
    }
    return max_so_far;
}
</code>```

Title: Find sum of largest subset of array

Body:
According to this presentation, the algorithm by Kadane apparently yields a linear runtime bound; an implementation in C++ taken from there looks as follows.

int maxSubArraySum(int a[], int size)
{
    int max_so_far = INT_MIN, max_ending_here = 0;

    for (int i = 0; i < size; i++)
    {
        max_ending_here = max_ending_here + a[i];
        if (max_so_far < max_ending_here)
            max_so_far = max_ending_here;

        if (max_ending_here < 0)
            max_ending_here = 0;
    }
    return max_so_far;
}


问:
Update dbus on Raspberry Pi
I need to update DBus on my Raspberry Pi, in order to upgrade to the latest Bluez version (and I hope for performance benefits).  I can't use a package install, as the latest packaged version is old, so I "configure/make/make install".

The problem with this is that it appears to install alongside the old version, but in a different directory.  So, if I run dbus-daemon --version, I see the old version number following the install.

The original version (and launch path) is /usr/bin, whereas my install is going to /usr/arm-linux-gnueabi/bin.  I did try editing the path for launch in /lib/systemd/system/dbus.service, but after this, Linux failed to start.

So now I have two versions of dbus on my Pi, with the old one booting.

Any help would be greatly appreciated.

答:
Before answering your question, share the failure log from "journalctl -xe" or "systemctl status dbus". Following might solve your problem,

Make sure to stop the dbus before update it. "systemctl stop dbus"

systemctl daemon-reload (Needs to run after changing service file of any daemon)

Start dbus again, systemctl start dbus.

check the binary path available in "echo $PATH", if not, export it. In your case, export PATH=/usr/arm-linux-gnueabi/bin:$PATH should help

Note: Many applications will stop working when you stop dbus.

Title: Update dbus on Raspberry Pi